mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 04:45:33 -08:00
Sync upstream v2.4.0 (web console, dashboard skill, implement-review, global launcher) with 24 review fixes and a look-around wake-up for Planny
AI Assisted
This commit is contained in:
1 parent
eefa7082ed
commit
0d7c2e140b
523 files changed
+339802
-401
No files matched your search
@@ -12,6 +12,10 @@ Start all FINALIZATION MODE responses with '🧹 [FINALIZATION STEP X: Step Name
|
||||
|
||||
QA engineer and technical lead performing rigorous final validation. Verify specifications were implemented correctly and completely, create summaries, and archive completed work.
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the Required Context check, before Step 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow finalize` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec specs/<feature-name>` if known, else post `specDir` later), then <D>/console.md → Finalize; the audit options, the doc-update approval and every cleanup confirmation go through it. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then the Required Context check.
|
||||
|
||||
## Rules
|
||||
|
||||
- Follow `./AGENTS.md` if it exists
|
||||
@@ -39,9 +43,7 @@ If multiple active spec folders exist or nothing provided, ask user for:
|
||||
|
||||
## Examples
|
||||
|
||||
**Task Audit:** Always show verification table with phase totals, blocked items, and completion %. Never just assert "all complete" without evidence.
|
||||
|
||||
**Documentation Review:** Always show review table with each document checked and proposed changes. Never assert "no updates needed" without evidence.
|
||||
**Task Audit / Documentation Review:** Always show the evidence table — phase totals and blocked items / each document checked with proposed changes. Never assert "all complete" or "no updates needed" without it.
|
||||
|
||||
## Process
|
||||
|
||||
@@ -194,9 +196,9 @@ If updates needed, show Planny and ask for approval:
|
||||
```
|
||||
⋅
|
||||
╭───╮
|
||||
│ ● │
|
||||
│ ~ │ Found some docs that need updating!
|
||||
╰───╯
|
||||
│ ★ │╱
|
||||
╱│ ~ │ Found some docs that need updating!
|
||||
╰┬─┬╯
|
||||
```
|
||||
|
||||
> Reply "approve" to proceed with doc updates, or specify which to skip.
|
||||
@@ -251,8 +253,6 @@ Ask: "Submit this feedback + run metrics to the maintainer via GitHub? (optional
|
||||
3. Remove temporary scratch files not part of the final spec record
|
||||
4. Verify original directory empty and can be removed
|
||||
|
||||
**Keep folder name exactly as-is during archival.**
|
||||
|
||||
---
|
||||
|
||||
### STEP 6.5: Community Feedback Submission
|
||||
@@ -308,9 +308,9 @@ Replace METRICS_JSON values with actuals. `completion_rate_at_audit` = Y/Z as de
|
||||
```
|
||||
⋅
|
||||
╭───╮
|
||||
│ ★ │
|
||||
╲│ ★ │╱
|
||||
│ ◡ │ You did it! Feature complete!
|
||||
╰───╯
|
||||
╰┬─┬╯
|
||||
```
|
||||
|
||||
> IMPLEMENTATION COMPLETED!
|
||||
@@ -323,7 +323,7 @@ Replace METRICS_JSON values with actuals. `completion_rate_at_audit` = Y/Z as de
|
||||
| Completion | Action |
|
||||
|-----------|--------|
|
||||
| **>75%** | Finalize with notice. List incomplete items. Note remaining tasks for follow-up cycle. |
|
||||
| **<75%** | Recommend returning to implementation. List incomplete phases with task counts. Options: 1) Return via `/plan2code-3-implement` 2) Proceed with partial finalization. |
|
||||
| **<75%** | Recommend returning to implementation. List incomplete phases with task counts. Options: 1) Return via `/plan2code-3-implement --web` 2) Proceed with partial finalization. |
|
||||
|
||||
## Abort Handling
|
||||
|
||||
@@ -342,7 +342,7 @@ If user says "abort", "cancel", or similar:
|
||||
|
||||
## Learning Capture
|
||||
|
||||
At session end, if you discovered undocumented commands, dependency quirks, gotchas (>5min cost), framework workarounds, or missing `AGENTS.md` patterns → prompt user to update AGENTS.md. If yes, apply the edit directly.
|
||||
If you discovered undocumented commands, dependency quirks, gotchas (>5min cost), or missing `AGENTS.md` patterns → prompt user to update AGENTS.md; apply the edit if yes.
|
||||
|
||||
## Session End
|
||||
|
||||
@@ -354,3 +354,5 @@ git commit -m "chore: finalize and archive <feature-name>" -m "<JIRA-Ticket-ID>"
|
||||
```
|
||||
|
||||
Returning context: Feature complete. Specs archived to `specs--completed/<feature-name>/`.
|
||||
|
||||
**On the web console:** a `__stop` action in a send ends the session: see console.md → Stop requests. At every session end post `finish` BEFORE `stop`, per console.md → Finalize — the completion summary is printed to a terminal the browser user is not watching.
|
||||
@@ -52,9 +52,9 @@ Display the exact rendered title, full body (including the `METRICS_JSON` block)
|
||||
```
|
||||
⋅
|
||||
╭───╮
|
||||
│ ● │
|
||||
│ ~ │ Ready to submit your feedback to the maintainer!
|
||||
╰───╯
|
||||
│ ★ │╱
|
||||
╱│ ~ │ Ready to submit your feedback to the maintainer!
|
||||
╰┬─┬╯
|
||||
```
|
||||
|
||||
> Reply "approve" to proceed with submission, or "skip" to cancel.
|
||||
|
||||
@@ -0,0 +1,444 @@
|
||||
# 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.
|
||||
|
||||
**The console changes where you ask, not what you build.** Every rule of the
|
||||
workflow stands: the same specs, the same checkbox writes to disk after every
|
||||
task, the same sign-off wording, the same "no git commands". The files under
|
||||
`specs/` and the code are the record. The page is a window onto them.
|
||||
|
||||
---
|
||||
|
||||
## Opening
|
||||
|
||||
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>` |
|
||||
| `/plan2code-3-implement-review` | `implement-review` | `specs/<feature>` |
|
||||
| `/plan2code-quick-task` | `quick-task` | leave it out |
|
||||
|
||||
`--spec` is what the page builds a resume command from if you ever cannot
|
||||
answer a stop yourself. Pass it to `open` when you already know the spec;
|
||||
otherwise post `"specDir": "specs/<feature>"` and a real `title` ("<feature>:
|
||||
Phase 3") in your first update, once the phase is chosen, or with the phase
|
||||
question as its first item if there is one to ask. `--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.
|
||||
|
||||
**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.
|
||||
|
||||
`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.
|
||||
|
||||
---
|
||||
|
||||
## 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:
|
||||
|
||||
```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
|
||||
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.
|
||||
|
||||
### 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:
|
||||
|
||||
```
|
||||
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. |
|
||||
| `10` | Nothing waiting. Carry on. |
|
||||
| `20` | The server is gone: `open --resume <sid>` as usual, then carry on. |
|
||||
|
||||
This is an instant check, not a wait: it never sleeps and never touches card
|
||||
sends. It does not replace `wait` at a gate, and no build calls `wait`
|
||||
mid-build for cards. An approved chat edit is made here, between tasks, never
|
||||
in the middle of one.
|
||||
|
||||
A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are
|
||||
not questions. Put them in the phase doc as they happen, and in the report.
|
||||
|
||||
### When the workflow asks something
|
||||
|
||||
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }`, and
|
||||
go into the wait loop. When the answer lands, set `working` again and carry on.
|
||||
|
||||
| Moment | `kind` | Notes |
|
||||
| --- | --- | --- |
|
||||
| Several phases can be picked | `choice` | One option per phase, `detail` = status and task count, `token` = the phase number. Put the "run another agent on a different phase" tip in `body`. |
|
||||
| A phase is already in progress | `confirm` | "Resume Phase 3?" `yes` / `no`. |
|
||||
| `SPEC CONFLICT` | `choice` or `text` | The conflict in `body`, the readings as options where there are clear ones. Never guess on architecture. |
|
||||
| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first. |
|
||||
| A small phase, continue with the next? | `confirm` | |
|
||||
| A spec gap only they can close | `text` | |
|
||||
| Something learned for AGENTS.md | `confirm` | The proposed lines in `consequences`. |
|
||||
|
||||
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, 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" },
|
||||
"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",
|
||||
"dashboard": true
|
||||
},
|
||||
"agent": { "status": "waiting" }
|
||||
}
|
||||
```
|
||||
|
||||
`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` scores the approved phase on the session meter (console.md → Posting an
|
||||
update → Session meter), in the same post that records the approval:
|
||||
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
||||
Review, id `phase-N`. 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` | They closed the tab. Do not resume: the session is over. |
|
||||
| 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. 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" }`.
|
||||
|
||||
---
|
||||
|
||||
## 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, then
|
||||
exactly as "While you build", with the plan's steps
|
||||
as the task list and `total` = the number of steps.
|
||||
- **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. Keep waiting for the answer, 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:
|
||||
|
||||
- **implement / implement-review:** Implementation Mode's abort, without the
|
||||
"are you sure" (the page asked): the phase stays `[/]`, list completed and
|
||||
remaining tasks, post `finish` with the resume command
|
||||
(`/plan2code-3-implement specs/<feature>/overview.md`), then `stop`. An
|
||||
implement abort is a pause: a headline starting "Paused", no `dashboard`,
|
||||
`stop` at once.
|
||||
- **quick-task:** say in `finish.body` what was worked out, and that nothing was
|
||||
saved unless it was built; `"command": "/plan2code-quick-task"`.
|
||||
|
||||
A mid-build `__dashboard` (the top bar's triangle, console.md → Stop requests →
|
||||
"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.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,233 @@
|
||||
// Plan2Code Web Console - the native folder picker behind Workspace's Browse…
|
||||
//
|
||||
// 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
|
||||
// moment the launcher's picker changes without it. The prompt is a parameter
|
||||
// here rather than the launcher's constant.
|
||||
//
|
||||
// Always spawned asynchronously: spawnSync would freeze the server's polling,
|
||||
// chat and wait for as long as the dialog stayed open.
|
||||
//
|
||||
// Node built-ins only.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const IS_WINDOWS = process.platform === "win32";
|
||||
const IS_MAC = process.platform === "darwin";
|
||||
|
||||
export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace";
|
||||
|
||||
// Copied verbatim from src/launcher/plan2code.js; see the drift test.
|
||||
export const WINDOWS_PICKER_SOURCE = `
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class Plan2CodeFolderPicker {
|
||||
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
|
||||
private class FileOpenDialog {}
|
||||
|
||||
[ComImport, Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IFileOpenDialog {
|
||||
[PreserveSig] int Show(IntPtr owner);
|
||||
void SetFileTypes(uint count, IntPtr specs);
|
||||
void SetFileTypeIndex(uint index);
|
||||
void GetFileTypeIndex(out uint index);
|
||||
void Advise(IntPtr events, out uint cookie);
|
||||
void Unadvise(uint cookie);
|
||||
void SetOptions(uint options);
|
||||
void GetOptions(out uint options);
|
||||
void SetDefaultFolder(IShellItem item);
|
||||
void SetFolder(IShellItem item);
|
||||
void GetFolder(out IShellItem item);
|
||||
void GetCurrentSelection(out IShellItem item);
|
||||
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
|
||||
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
|
||||
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
|
||||
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
|
||||
void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
|
||||
void GetResult(out IShellItem item);
|
||||
}
|
||||
|
||||
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IShellItem {
|
||||
void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
|
||||
void GetParent(out IShellItem parent);
|
||||
void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
|
||||
}
|
||||
|
||||
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
|
||||
private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item);
|
||||
|
||||
private const uint FOS_PICKFOLDERS = 0x20;
|
||||
private const uint FOS_FORCEFILESYSTEM = 0x40;
|
||||
private const uint FOS_PATHMUSTEXIST = 0x800;
|
||||
private const uint SIGDN_FILESYSPATH = 0x80058000;
|
||||
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
|
||||
|
||||
public static string Pick(IntPtr owner, string title, string start) {
|
||||
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
|
||||
try {
|
||||
uint options;
|
||||
dialog.GetOptions(out options);
|
||||
dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
|
||||
dialog.SetTitle(title);
|
||||
if (!string.IsNullOrEmpty(start)) {
|
||||
try {
|
||||
Guid iid = typeof(IShellItem).GUID;
|
||||
IShellItem folder;
|
||||
SHCreateItemFromParsingName(start, IntPtr.Zero, ref iid, out folder);
|
||||
dialog.SetFolder(folder);
|
||||
} catch (Exception) {}
|
||||
}
|
||||
int hr = dialog.Show(owner);
|
||||
if (hr == ERROR_CANCELLED) return null;
|
||||
Marshal.ThrowExceptionForHR(hr);
|
||||
IShellItem result;
|
||||
dialog.GetResult(out result);
|
||||
string path;
|
||||
result.GetDisplayName(SIGDN_FILESYSPATH, out path);
|
||||
return path;
|
||||
} finally {
|
||||
Marshal.ReleaseComObject(dialog);
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
// Resolve a command on PATH the way the shell would, including PATHEXT on Windows.
|
||||
function findOnPath(command) {
|
||||
const dirs = (process.env.PATH || "").split(path.delimiter).filter(Boolean);
|
||||
const extensions = IS_WINDOWS ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
|
||||
for (const dir of dirs) {
|
||||
for (const ext of extensions) {
|
||||
const candidate = path.join(dir.replace(/^"|"$/g, ""), command + ext);
|
||||
try {
|
||||
if (fs.statSync(candidate).isFile()) return candidate;
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The native folder picker for this OS, as a command to run: it prints the
|
||||
* chosen folder, or nothing when the person cancels. Null when this OS has no
|
||||
* picker we can drive.
|
||||
*/
|
||||
export function pickerCommand(start, prompt) {
|
||||
if (IS_WINDOWS) {
|
||||
const script = [
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
"try {",
|
||||
" [Console]::OutputEncoding = [Text.Encoding]::UTF8",
|
||||
" Add-Type -AssemblyName System.Windows.Forms",
|
||||
" [System.Windows.Forms.Application]::EnableVisualStyles()",
|
||||
// A TopMost owner keeps the dialog in front of the console window that launched it.
|
||||
" $owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; ShowInTaskbar = $false }",
|
||||
" try {",
|
||||
" Add-Type -TypeDefinition $env:PLAN2CODE_PICKER_SOURCE",
|
||||
" $picked = [Plan2CodeFolderPicker]::Pick($owner.Handle, $env:PLAN2CODE_PICKER_PROMPT, $env:PLAN2CODE_PICKER_START)",
|
||||
" } catch {",
|
||||
// Add-Type is blocked under Constrained Language Mode and some AppLocker policies; the
|
||||
// old tree dialog still works there.
|
||||
" $dialog = New-Object System.Windows.Forms.FolderBrowserDialog",
|
||||
" $dialog.Description = $env:PLAN2CODE_PICKER_PROMPT",
|
||||
" $dialog.SelectedPath = $env:PLAN2CODE_PICKER_START",
|
||||
" $picked = if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { $dialog.SelectedPath } else { $null }",
|
||||
" }",
|
||||
" if ($picked) { $picked }",
|
||||
"} catch { exit 3 }",
|
||||
].join("\n");
|
||||
return {
|
||||
command: "powershell.exe",
|
||||
args: [
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-STA",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-EncodedCommand",
|
||||
Buffer.from(script, "utf16le").toString("base64"),
|
||||
],
|
||||
env: {
|
||||
PLAN2CODE_PICKER_PROMPT: prompt,
|
||||
PLAN2CODE_PICKER_START: start,
|
||||
PLAN2CODE_PICKER_SOURCE: WINDOWS_PICKER_SOURCE,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (IS_MAC) {
|
||||
return {
|
||||
command: "osascript",
|
||||
args: [
|
||||
"-e",
|
||||
"on run argv",
|
||||
"-e",
|
||||
`POSIX path of (choose folder with prompt "${prompt}" default location (POSIX file (item 1 of argv)))`,
|
||||
"-e",
|
||||
"end run",
|
||||
start,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return null;
|
||||
if (findOnPath("zenity")) {
|
||||
return {
|
||||
command: "zenity",
|
||||
args: ["--file-selection", "--directory", `--title=${prompt}`, `--filename=${start}${path.sep}`],
|
||||
};
|
||||
}
|
||||
if (findOnPath("kdialog")) {
|
||||
return { command: "kdialog", args: ["--title", prompt, "--getexistingdirectory", start] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the picker and settle on what the person did: `{ path }` for a pick,
|
||||
* `{ cancelled: true }` when they closed it, `{ error }` when the picker
|
||||
* itself failed or this OS has none. Pickers exit 0 or 1 with nothing printed
|
||||
* when cancelled.
|
||||
*/
|
||||
export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
|
||||
const picker = pickerCommand(start, prompt);
|
||||
if (!picker) return Promise.resolve({ error: "picker-failed" });
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const settle = (result) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(result);
|
||||
};
|
||||
let child;
|
||||
try {
|
||||
child = spawnImpl(picker.command, picker.args, {
|
||||
env: { ...process.env, ...(picker.env || {}) },
|
||||
// stderr is ignored, not piped: a pipe nobody reads fills up and
|
||||
// blocks a chatty picker (GTK warnings) before it can exit.
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
windowsHide: true,
|
||||
});
|
||||
} catch {
|
||||
return settle({ error: "picker-failed" });
|
||||
}
|
||||
let stdout = "";
|
||||
if (child.stdout) {
|
||||
child.stdout.setEncoding?.("utf8");
|
||||
child.stdout.on("data", (chunk) => (stdout += chunk));
|
||||
}
|
||||
child.on("error", () => settle({ error: "picker-failed" }));
|
||||
child.on("close", (code) => {
|
||||
const folder = stdout.trim();
|
||||
if (code === 0 && folder) return settle({ path: path.resolve(folder) });
|
||||
if (!folder && (code === 0 || code === 1)) return settle({ cancelled: true });
|
||||
settle({ error: "picker-failed" });
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,971 @@
|
||||
// The page's pure logic: what the person answered, and what they asked for, in
|
||||
// the words those things have to reach the agent as.
|
||||
//
|
||||
// Everything here is a pure function of an item and a value. That is the point
|
||||
// of the file: app.js cannot be loaded outside a browser (it touches `document`
|
||||
// at module scope and starts a session on import), so any logic that stays in
|
||||
// it is logic no test can reach. Three defects in this exact code got as far as
|
||||
// the screen before anyone noticed. It lives here so `node --test` can see it.
|
||||
//
|
||||
// No DOM, no `local`, no fetch. If a function in here needs any of those, it
|
||||
// belongs in app.js instead.
|
||||
|
||||
/* ----------------------------------------------------- the sent answer */
|
||||
|
||||
/**
|
||||
* The value an in-flight send carries, or null if it carries no answer.
|
||||
*
|
||||
* A send can be a note on its own: someone asks a question about the question
|
||||
* before answering it. That still goes in `local.sent`, because the note really
|
||||
* is on its way, but it must NOT make the page treat the question as answered
|
||||
* and lock the form. They have not answered it yet, and locking them out is how
|
||||
* an open question becomes unanswerable.
|
||||
*/
|
||||
export function sentAnswer(sent) {
|
||||
return sent && sent.value ? sent.value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the person settled on, for a question that is no longer open.
|
||||
*
|
||||
* `answer` is what the agent recorded when it settled the question. `submitted`
|
||||
* is what the server wrote down the moment Send was pressed. The second exists
|
||||
* because the first depends on the agent remembering to do it, and a card that
|
||||
* says "Settled" above an empty form is the worst thing this page can show.
|
||||
*/
|
||||
export function recordedAnswer(item) {
|
||||
const a = item && item.answer && typeof item.answer === "object" ? item.answer : null;
|
||||
const s = item && item.submitted && typeof item.submitted === "object" ? item.submitted : null;
|
||||
if (!a && !s) return null;
|
||||
return { ...(s || {}), ...(a || {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* A send the person made that the agent never settled, still sitting on an
|
||||
* OPEN question.
|
||||
*
|
||||
* `local.sent` covers this while the same tab is alive; `submitted` is the
|
||||
* server's own record of the send and survives a reload, a resume onto a new
|
||||
* port, and a second tab. An open item that carries one, and has had no agent
|
||||
* reply since, is "sent, waiting on Plan2Code" — not a question still
|
||||
* waiting for them, which is what it reads as when an agent takes the answer
|
||||
* and moves on without marking the item settled.
|
||||
*
|
||||
* Two ways out, both meaning the question is theirs again:
|
||||
*
|
||||
* - an agent message in the item's thread AFTER the send means the question
|
||||
* is being asked again — the person gets a live form back, not a locked
|
||||
* record of what they already said;
|
||||
* - a recorded `answer` means the agent did settle it at some point (the
|
||||
* status is just stale or the question was re-asked), so the leftover
|
||||
* `submitted` is the old send, not one in flight.
|
||||
*/
|
||||
export function submittedAwaiting(item) {
|
||||
const s = item && item.submitted;
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (item.answer && typeof item.answer === "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
return replied ? null : s;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- labels */
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export function verdictLabel(item, id) {
|
||||
const list = (item && item.verdicts) || [
|
||||
{ id: "approve", label: "Looks good, go ahead" },
|
||||
{ id: "changes", label: "I want changes" },
|
||||
];
|
||||
const v = list.find((x) => x.id === id);
|
||||
return v ? verdictText(v) : String(id);
|
||||
}
|
||||
|
||||
// A verdict's button text. `label` is the contract; `text` is what menu
|
||||
// options use, and an agent that borrows it must not get blank buttons.
|
||||
export function verdictText(v) {
|
||||
return v.label || v.text || v.id;
|
||||
}
|
||||
|
||||
export const CHECK_STATE_LABEL = {
|
||||
done: "All done",
|
||||
blocked: "I am stuck",
|
||||
help: "I need help",
|
||||
defer: "Later",
|
||||
};
|
||||
|
||||
/**
|
||||
* The answer as lines to show back, in the page's words rather than the
|
||||
* agent's shorthand: "A · Run the setup first", not "a".
|
||||
*/
|
||||
export function answerLines(item, v) {
|
||||
const out = [];
|
||||
if (!v) return out;
|
||||
if (v.skipped) out.push("Skipped");
|
||||
if (v.k) out.push(optionLabel(item, v.k));
|
||||
if (Array.isArray(v.ks)) for (const k of v.ks) out.push(optionLabel(item, k));
|
||||
if (typeof v.yes === "boolean") out.push(v.yes ? item.yesLabel || "Yes" : item.noLabel || "No");
|
||||
if (typeof v.ok === "boolean") {
|
||||
out.push(v.ok ? item.yesLabel || "Yes, that is right" : item.noLabel || "Not quite");
|
||||
}
|
||||
if (v.verdict) out.push(verdictLabel(item, v.verdict));
|
||||
if (v.state) out.push(CHECK_STATE_LABEL[v.state] || String(v.state));
|
||||
if (Array.isArray(v.done) && v.done.length) {
|
||||
out.push(`Steps done: ${v.done.map((n) => n + 1).join(", ")}`);
|
||||
}
|
||||
if (Array.isArray(v.rows) && v.rows.length) {
|
||||
out.push(`${v.rows.length} steps, in the order you set`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A single-choice answer, which is one thing or the other and never both.
|
||||
*
|
||||
* Picking an option and then writing "none of these, because…" used to send
|
||||
* both, joined, with the pick first: an answer that argued with itself. The
|
||||
* rule lives here rather than in the two click handlers that apply it, so it
|
||||
* is one statement that a test can hold to.
|
||||
*
|
||||
* Returns null when there is nothing to stage, which is what "they have not
|
||||
* answered yet" looks like everywhere else in the page.
|
||||
*/
|
||||
export function choiceAnswer({ k, text } = {}) {
|
||||
if (k) return { type: "answer", kind: "choice", k };
|
||||
const said = String(text || "").trim();
|
||||
return said ? { type: "answer", kind: "choice", text: said } : null;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- the brief ask */
|
||||
|
||||
/**
|
||||
* The words a brief request reaches the agent as.
|
||||
*
|
||||
* This is not an answer, but it is the same kind of thing and it belongs to the
|
||||
* same rule: a string the agent parses, so it has to be exactly right, so it
|
||||
* has to be somewhere a test can see it. `range` is the Pathfinder brief
|
||||
* playbook's own grammar -- `today`, `this week`, `since <YYYY-MM-DD>`, `full`.
|
||||
*/
|
||||
export function briefPhrase(range) {
|
||||
const r = String(range || "today").trim();
|
||||
if (r === "full") return "Write a full brief.";
|
||||
if (r.startsWith("since ")) return `Write a brief covering everything ${r}.`;
|
||||
return `Write a brief for ${r}.`;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------- the autofill text */
|
||||
|
||||
// A placeholder is a suggestion nobody can edit, and it vanishes the moment you
|
||||
// type. On a question whose example is most of a good answer, retyping it is
|
||||
// busywork, so offer it as a value instead. The lead-in ("For example:") is the
|
||||
// agent talking about the example, not part of it, so it is stripped.
|
||||
//
|
||||
// Two rules keep the stripping from mangling a real answer:
|
||||
//
|
||||
// The lead-in must be FOLLOWED by a separator. Without that, "Egypt office"
|
||||
// loses its "Eg" and "Exampled output" loses its "Example".
|
||||
//
|
||||
// A bare hyphen only separates when it has space around it. "For example - a"
|
||||
// is a lead-in; the hyphen in "example-name-here" is part of the name, and a
|
||||
// kebab-case suggestion must survive intact for a field with a `pattern`.
|
||||
//
|
||||
// "Say" is deliberately not in the list: "Say when you need it by" is a
|
||||
// question far more often than it is a preamble.
|
||||
const EXAMPLE_LEAD =
|
||||
/^\s*(?:for\s+(?:example|instance)|examples?|such\s+as|e\.?\s?g\.?|i\.?\s?e\.?)(?:\s+-\s+|\s*[:,.]\s*|\s+)/i;
|
||||
|
||||
/**
|
||||
* The placeholder, as a value someone could accept as their own answer.
|
||||
* Empty string when there is nothing worth offering.
|
||||
*/
|
||||
export function suggestionFrom(item) {
|
||||
const raw = String((item && item.placeholder) || "").trim();
|
||||
if (!raw) return "";
|
||||
const stripped = raw.replace(EXAMPLE_LEAD, "").trim();
|
||||
if (!stripped) return "";
|
||||
// Recapitalise only when a lead-in was actually removed, and never on a
|
||||
// field with a shape to match: "audit-export" must not become "Audit-export".
|
||||
if (stripped !== raw && !item.pattern && /^[a-z]/.test(stripped)) {
|
||||
return stripped[0].toUpperCase() + stripped.slice(1);
|
||||
}
|
||||
return stripped;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the hand-off */
|
||||
|
||||
// The badge each workflow wears. Shared with the server, which writes it into
|
||||
// the page it serves so the first paint already names the session instead of
|
||||
// flashing a placeholder until the script arrives.
|
||||
export const WORKFLOW_LABEL = {
|
||||
dashboard: "Dashboard",
|
||||
init: "Setting up",
|
||||
"init-update": "Refreshing",
|
||||
pathfinder: "Pathfinder",
|
||||
plan: "Planning",
|
||||
"revise-plan": "Revising the plan",
|
||||
document: "Documenting",
|
||||
implement: "Building",
|
||||
"implement-review": "Building + review",
|
||||
review: "Review",
|
||||
"quick-task": "Quick task",
|
||||
finalize: "Wrapping up",
|
||||
handoff: "Handoff",
|
||||
};
|
||||
|
||||
export function workflowLabel(workflow) {
|
||||
return WORKFLOW_LABEL[workflow] || workflow || "Session";
|
||||
}
|
||||
|
||||
// The workflows that ship the console (install.js bundles it into every
|
||||
// skill as `additionalReferences`). Any other next step has no browser page
|
||||
// to open, and asking for one would send the next session looking for
|
||||
// something that is not there.
|
||||
export const CONSOLE_WORKFLOWS = [
|
||||
"/plan2code",
|
||||
"/plan2code-init",
|
||||
"/plan2code-init-update",
|
||||
"/plan2code-0-pathfinder",
|
||||
"/plan2code-quick-task",
|
||||
"/plan2code-1-plan",
|
||||
"/plan2code-1b-revise-plan",
|
||||
"/plan2code-2-document",
|
||||
"/plan2code-3-implement",
|
||||
"/plan2code-3-implement-review",
|
||||
"/plan2code-review",
|
||||
"/plan2code-4-finalize",
|
||||
"/plan2code-handoff",
|
||||
];
|
||||
|
||||
// Rides on the end of the command as part of the skill's argument. Every
|
||||
// console skill takes it as the answer to "web console or terminal?" instead
|
||||
// of asking again. It must stay clear of "brief", "recap" and "minutes":
|
||||
// pathfinder reads any of those in its argument as a request for a brief.
|
||||
export const CONTINUE_IN_CONSOLE = "--web";
|
||||
|
||||
// The long form the skills still accept. A command that carries it is copied
|
||||
// with the flag instead, which is shorter and reads as the parameter it is.
|
||||
const CONSOLE_SENTENCE = /\s*Use the web console for this session\.?/gi;
|
||||
|
||||
/**
|
||||
* What the Copy button on the finished screen puts on the clipboard.
|
||||
*
|
||||
* Someone who worked the whole session in the browser should land back in the
|
||||
* browser, not be asked the interface question as though they were new. The
|
||||
* `--web` flag goes on the same line as the command, because what follows a
|
||||
* slash command is its argument, and a pasted second line is not reliably that.
|
||||
* A command written with the long sentence is copied with the flag instead.
|
||||
*
|
||||
* `fin.console` overrides the inference either way; otherwise it follows from
|
||||
* whether the next step is a workflow that has a console at all.
|
||||
*/
|
||||
export function handoffText(fin) {
|
||||
const raw = String((fin && fin.command) || "").trim();
|
||||
if (!raw) return "";
|
||||
const cmd = raw.replace(CONSOLE_SENTENCE, "").trim();
|
||||
const capable =
|
||||
typeof fin.console === "boolean"
|
||||
? fin.console
|
||||
: cmd !== raw || CONSOLE_WORKFLOWS.some((w) => cmd === w || cmd.startsWith(w + " "));
|
||||
// An agent that already wrote the flag should not get it twice.
|
||||
if (!capable || /(^|\s)--web\b/.test(cmd)) return cmd;
|
||||
return `${cmd} ${CONTINUE_IN_CONSOLE}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A finish is a pause when its headline says so. There is no flag to read:
|
||||
* the stop playbook asks the agent to write "a headline that says it is
|
||||
* paused rather than done", so the page reads the same words the person
|
||||
* does. A session that ends on its own says nothing of the sort.
|
||||
*/
|
||||
export function finishPaused(fin) {
|
||||
return /^\s*paused\b/i.test(String((fin && fin.headline) || ""));
|
||||
}
|
||||
|
||||
// The line a finished session shows when it has nothing left to run. Split so
|
||||
// the page can render the backticked command as code; joined with a space they
|
||||
// read as one sentence.
|
||||
export const ALL_DONE_LEAD = "All done, nothing left to run.";
|
||||
export const ALL_DONE_REST = "To start something else, run `/plan2code` in a new conversation to open the dashboard.";
|
||||
export const DASHBOARD_COMMAND = "/plan2code";
|
||||
|
||||
/**
|
||||
* Which hand-off a finish gets: a pause always offers its resume command, a
|
||||
* finish with a command offers it as the next step, and one without has
|
||||
* nothing left to run.
|
||||
*/
|
||||
export function handoffShape(fin) {
|
||||
if (finishPaused(fin)) return "paused";
|
||||
return String((fin && fin.command) || "").trim() ? "next" : "all-done";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ stopping */
|
||||
|
||||
// What a stop request reads as, the way a typed message would. It goes to the
|
||||
// agent as part of `reply`, so the same caution applies as to the hand-off
|
||||
// sentence: nothing Pathfinder would read as asking for a brief.
|
||||
export const STOP_REPLY = "Stop here and save my place, so I can pick this up later.";
|
||||
|
||||
/**
|
||||
* Why a session-level button (Stop session, Back to the dashboard) cannot be
|
||||
* pressed right now, or null when it can. Both wait for the person's turn:
|
||||
* while Plan2Code has the ball it may be halfway through writing their last
|
||||
* answers into the files, and a request landing then is how a question ends up
|
||||
* half recorded. `waiting` is the caller's "the agent is working or a reply is
|
||||
* owed, and it has not gone adrift" -- an agent that has stopped checking in
|
||||
* never replies, and a button greyed out forever would lock the person in. An
|
||||
* uncollected send still blocks even then, because the server takes one at a
|
||||
* time.
|
||||
*/
|
||||
export function turnGate({ gone = false, pendingResult = false, waiting = false } = {}) {
|
||||
if (gone) return "gone";
|
||||
if (pendingResult) return "pending";
|
||||
if (waiting) return "waiting";
|
||||
return null;
|
||||
}
|
||||
|
||||
// What the top bar's Back to the dashboard button reads as to the agent. It
|
||||
// goes in `reply` like the stop, so the same caution applies: nothing
|
||||
// Pathfinder would read as asking for a brief.
|
||||
export const HOME_REPLY = "Save my place and take me back to the dashboard, right here in this session.";
|
||||
|
||||
const HOME_TITLES = {
|
||||
gone: "Not connected right now.",
|
||||
pending: "Your last answers are still being picked up. You can leave once they have been.",
|
||||
waiting: "Plan2Code is working on your answers. You can leave once it replies.",
|
||||
};
|
||||
|
||||
/**
|
||||
* The top bar's Back to the dashboard button. Hidden on the dashboard itself,
|
||||
* on a finished screen (which carries its own way back) and while a stop is
|
||||
* under way; otherwise pressable on the person's turn, like Stop session.
|
||||
* Once pressed it waits for the page to turn, unless the agent has gone
|
||||
* 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 } = {}) {
|
||||
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.",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The resume command the PAGE can offer when the agent cannot: it stopped
|
||||
* listening, or went away without posting a finish. Built only from what the
|
||||
* session state says, never guessed.
|
||||
*
|
||||
* Pathfinder resumes from its folder, so it needs `specDir` (`specs/<idea>`),
|
||||
* which the workflow posts once the folder exists. Without one the bare
|
||||
* command still works: Pathfinder asks which idea. Planning finds its own
|
||||
* draft and takes no path. The implementation steps, Revision and
|
||||
* Finalization take the spec's overview.md, and without it they ask which
|
||||
* spec (or find the only one). A quick task keeps nothing on disk to resume
|
||||
* from, so its command starts it again.
|
||||
*/
|
||||
export function resumeCommand({ workflow, specDir } = {}) {
|
||||
const raw = String(specDir || "").trim().replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
// Only a real relative specs/ path. Anything else would be run verbatim by
|
||||
// someone with no way to tell it was wrong.
|
||||
const dir = /^specs\/[a-z0-9][a-z0-9._-]*$/i.test(raw) ? raw : "";
|
||||
const withOverview = (cmd) => (dir ? `${cmd} ${dir}/overview.md` : cmd);
|
||||
switch (workflow) {
|
||||
case "dashboard":
|
||||
return "/plan2code";
|
||||
case "init":
|
||||
return "/plan2code-init";
|
||||
case "init-update":
|
||||
return "/plan2code-init-update";
|
||||
case "plan":
|
||||
return "/plan2code-1-plan";
|
||||
case "quick-task":
|
||||
return "/plan2code-quick-task";
|
||||
case "document":
|
||||
return withOverview("/plan2code-2-document");
|
||||
case "implement":
|
||||
return withOverview("/plan2code-3-implement");
|
||||
case "implement-review":
|
||||
return withOverview("/plan2code-3-implement-review");
|
||||
case "review":
|
||||
return "/plan2code-review";
|
||||
case "revise-plan":
|
||||
return withOverview("/plan2code-1b-revise-plan");
|
||||
case "finalize":
|
||||
return withOverview("/plan2code-4-finalize");
|
||||
case "handoff":
|
||||
return "/plan2code-handoff";
|
||||
default:
|
||||
return dir ? `/plan2code-0-pathfinder ${dir}/pathfinder` : "/plan2code-0-pathfinder";
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ after a build is done */
|
||||
|
||||
// What the two buttons on a finished build's hand-off reach the agent as. They
|
||||
// go in `reply` like any typed message, so the same caution applies as to the
|
||||
// other session phrases: plain words, nothing Pathfinder would read as a brief.
|
||||
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.";
|
||||
|
||||
// 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.
|
||||
export const DASHBOARD_NOTE =
|
||||
"This picks up in the same conversation. That's fine after a quick or small skill; after a long one, type `/clear` in your terminal and run `/plan2code` for a clean start.";
|
||||
|
||||
/**
|
||||
* Whether a finish offers the way back to the dashboard. The agent opts in
|
||||
* with `finish.dashboard: true`, so a skill that predates the button never
|
||||
* shows one nobody answers; a pause never offers it.
|
||||
*/
|
||||
export function dashboardOffer(fin) {
|
||||
return Boolean(fin && fin.dashboard === true && !finishPaused(fin));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a finish carries the offer to review what was just built. The agent
|
||||
* posts `finish.review` as `true` or as `{ "label": "..." }` on a finished
|
||||
* quick task (an implementation phase offers the review earlier, as a verdict
|
||||
* on its sign-off card).
|
||||
*/
|
||||
export function reviewOffer(fin) {
|
||||
const r = fin && fin.review;
|
||||
if (!r) return null;
|
||||
const label = typeof r === "object" && typeof r.label === "string" ? r.label.trim() : "";
|
||||
return { label: label || "Review what was just built" };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- the dashboard */
|
||||
|
||||
// The skills the dashboard offers, in the order it offers them. The page owns
|
||||
// this list rather than the session state: the catalog is product UI, fixed
|
||||
// for everyone, and the alternative — the agent posting it — would put a dozen
|
||||
// cards of boilerplate through the patch channel every time the menu opened.
|
||||
// `menu` in the state can still say what the agent knows: a `recommend` skill
|
||||
// to highlight and a `details` line per card ("Phase 2 of 4 is next").
|
||||
//
|
||||
// `workflow` is the name the skill resumes the session under: the dashboard
|
||||
// hands its session over, and this is what turns the page into that skill's
|
||||
// console. A test holds this list against the skills install.js builds, so a
|
||||
// new skill cannot ship without a card here.
|
||||
export const CATALOG_GROUPS = [
|
||||
{ id: "setup", title: "First, the project" },
|
||||
{ id: "pipeline", title: "The steps, in order" },
|
||||
{ id: "extra", title: "Useful any time" },
|
||||
];
|
||||
|
||||
// `spec: true` marks the cards that take a spec folder as their target: when
|
||||
// the picker has a spec selected, its `dir` rides along in the `__launch`
|
||||
// action so the launched skill knows which spec it was picked for.
|
||||
export const SKILL_CATALOG = [
|
||||
{
|
||||
skill: "plan2code-init",
|
||||
command: "/plan2code-init",
|
||||
workflow: "init",
|
||||
group: "setup",
|
||||
chip: "Set up",
|
||||
title: "Set up this project",
|
||||
blurb: "Reads your project and writes AGENTS.md, the guide every later step works from.",
|
||||
about:
|
||||
"Plan2Code reads the whole project: how it is organized, how it runs, and where the sharp edges are. Then it writes AGENTS.md, the guide every later step steers by. It asks a few questions as it goes, so nothing important gets guessed. Run this once per project, or again when the project has moved on.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-init-update",
|
||||
command: "/plan2code-init-update",
|
||||
workflow: "init-update",
|
||||
group: "setup",
|
||||
chip: "Set up",
|
||||
title: "Refresh AGENTS.md",
|
||||
blurb: "Brings AGENTS.md and its notes up to date with what the project has learned lately.",
|
||||
about:
|
||||
"The project moved on since AGENTS.md was written: new commands, new habits, new gotchas. This re-reads the project, asks what changed, and folds it into AGENTS.md and the notes beside it. Cheaper than a fresh setup, and whatever is still right is kept.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-0-pathfinder",
|
||||
command: "/plan2code-0-pathfinder",
|
||||
workflow: "pathfinder",
|
||||
group: "pipeline",
|
||||
chip: "Step 0",
|
||||
spec: true,
|
||||
title: "Pathfinder",
|
||||
blurb: "A foggy idea becomes a clear list of decisions, settled one question at a time.",
|
||||
about:
|
||||
"You have a rough idea and a lot of unknowns. Pathfinder asks one question at a time: who it is for, what it must do, what could go wrong. Each answer is written down in a spec folder. It ends with a list of decisions clear enough to plan from, and nothing gets built yet.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-1-plan",
|
||||
command: "/plan2code-1-plan",
|
||||
workflow: "plan",
|
||||
group: "pipeline",
|
||||
chip: "Step 1",
|
||||
spec: true,
|
||||
title: "Plan",
|
||||
blurb: "Requirements, technical design and your approval: the shape of what gets built.",
|
||||
about:
|
||||
"Turns what you bring into a real plan: a finished Pathfinder map, a folder of design notes, or just the idea in your head. You get requirements, a technical design, a phase-by-phase breakdown, and a final version to approve before anything is built. This is where 'what are we building' becomes 'how it gets built'.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-1b-revise-plan",
|
||||
command: "/plan2code-1b-revise-plan",
|
||||
workflow: "revise-plan",
|
||||
group: "pipeline",
|
||||
chip: "Step 1b",
|
||||
spec: true,
|
||||
title: "Revise the plan",
|
||||
blurb: "Requirements changed mid-build? Adjust the plan without starting over.",
|
||||
about:
|
||||
"Requirements moved mid-build: a feature added, a rule dropped, a deadline pulled in. This adjusts the existing spec for the change, shows you what it affects, and only rewrites what actually has to move. The approved plan stays the plan.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-2-document",
|
||||
command: "/plan2code-2-document",
|
||||
workflow: "document",
|
||||
group: "pipeline",
|
||||
chip: "Step 2",
|
||||
spec: true,
|
||||
title: "Document",
|
||||
blurb: "The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.",
|
||||
about:
|
||||
"Writes the plan as numbered phase files. Each phase is a checklist of tasks small enough to just do, with the details a builder needs right there. This is the file the build step works from, and the thing a later session can pick up cold.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-3-implement",
|
||||
command: "/plan2code-3-implement",
|
||||
workflow: "implement",
|
||||
group: "pipeline",
|
||||
chip: "Step 3",
|
||||
spec: true,
|
||||
title: "Implement",
|
||||
blurb: "Builds the next phase, task by task, with a report and your sign-off at the end.",
|
||||
about:
|
||||
"Builds the next phase of the spec. Tasks get checked off one by one, with progress and the occasional decision landing on this page as it goes. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-3-implement-review",
|
||||
command: "/plan2code-3-implement-review",
|
||||
workflow: "implement-review",
|
||||
group: "pipeline",
|
||||
chip: "Step 3",
|
||||
spec: true,
|
||||
title: "Implement + review",
|
||||
blurb: "One phase built, then a careful review of the changes, then your sign-off. All in one run.",
|
||||
about:
|
||||
"The same build as Implement, with a review folded in before sign-off. The phase is built, then a fresh pass hunts for problems in exactly what changed, you pick what gets fixed, and only then does the sign-off card arrive.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-4-finalize",
|
||||
command: "/plan2code-4-finalize",
|
||||
workflow: "finalize",
|
||||
group: "pipeline",
|
||||
chip: "Step 4",
|
||||
spec: true,
|
||||
title: "Finalize",
|
||||
blurb: "Checks the work, writes the summary, files the specs away and suggests the commit message.",
|
||||
about:
|
||||
"The closer. Checks every task against the spec, makes sure the build actually works, writes the summary into overview.md, updates the project docs, and suggests the commit message. Run it when the feature is done. It leaves the project tidy behind it.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-quick-task",
|
||||
command: "/plan2code-quick-task",
|
||||
workflow: "quick-task",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Quick task",
|
||||
blurb: "Too small for the full process? A quick plan, then it just builds it.",
|
||||
about:
|
||||
"A fix, a tweak, a small feature. Not worth a spec folder. Describe it, confirm the one-line plan, and it builds it right there, with a report at the end. The fast lane for work the full process would over-plan.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-review",
|
||||
command: "/plan2code-review",
|
||||
workflow: "review",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Review",
|
||||
blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.",
|
||||
about:
|
||||
"A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-handoff",
|
||||
command: "/plan2code-handoff",
|
||||
workflow: "handoff",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Handoff",
|
||||
blurb: "Pack this conversation into a document a fresh session can pick up cold.",
|
||||
about:
|
||||
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
|
||||
},
|
||||
];
|
||||
|
||||
// A workflow by the name its dashboard card gives it ("Implement"), for the
|
||||
// screens that speak of it as a thing being started rather than as a badge.
|
||||
export function workflowTitle(workflow) {
|
||||
const entry = SKILL_CATALOG.find((e) => e.workflow === workflow);
|
||||
return entry ? entry.title : workflowLabel(workflow);
|
||||
}
|
||||
|
||||
// Every skill gets its own Planny on the starting and waiting screens, drawn
|
||||
// as a <template data-pose> in index.html. A skill that is a variant of
|
||||
// another borrows its pose. Anything else (the dashboard) keeps the flight.
|
||||
export const START_POSES = [
|
||||
"init",
|
||||
"pathfinder",
|
||||
"plan",
|
||||
"document",
|
||||
"implement",
|
||||
"finalize",
|
||||
"quick-task",
|
||||
"review",
|
||||
"handoff",
|
||||
];
|
||||
|
||||
const POSE_ALIASES = { "init-update": "init", "revise-plan": "plan", "implement-review": "implement" };
|
||||
|
||||
export function startPose(workflow) {
|
||||
const pose = POSE_ALIASES[workflow] || workflow;
|
||||
return START_POSES.includes(pose) ? pose : null;
|
||||
}
|
||||
|
||||
export function catalogEntry(skill) {
|
||||
return SKILL_CATALOG.find((e) => e.skill === skill) || null;
|
||||
}
|
||||
|
||||
/* ------------------------------------------- dashboard card availability */
|
||||
|
||||
// What the picker shows next to a spec's name — the pipeline position the
|
||||
// server's scan worked out, in plain words.
|
||||
export const SPEC_STATE_LABELS = {
|
||||
exploring: "Exploring",
|
||||
mapped: "Ready to plan",
|
||||
planned: "Ready to document",
|
||||
documented: "Ready to build",
|
||||
building: "Building",
|
||||
built: "Ready to finalize",
|
||||
unrecognized: "Files on disk",
|
||||
};
|
||||
|
||||
// The card each spec state exists to light up. Used as the fallback for the
|
||||
// "Suggested" pill when the agent's menu payload names nothing.
|
||||
const NEXT_FOR_STATE = {
|
||||
exploring: "plan2code-0-pathfinder",
|
||||
mapped: "plan2code-1-plan",
|
||||
planned: "plan2code-2-document",
|
||||
documented: "plan2code-3-implement",
|
||||
building: "plan2code-3-implement",
|
||||
built: "plan2code-4-finalize",
|
||||
};
|
||||
|
||||
const ON = { on: true };
|
||||
const off = (reason) => ({ on: false, reason });
|
||||
|
||||
/**
|
||||
* Whether a catalog card is clickable for the current picker selection.
|
||||
*
|
||||
* `scan` is the server's project scan ({ hasAgents, specs }); `sel` is the
|
||||
* picked spec object or null for "start from scratch". A spec whose files
|
||||
* match no pipeline shape ("unrecognized") behaves like no spec at all for
|
||||
* availability — but its folder still goes along on a Pathfinder or Plan
|
||||
* launch, since the files may be reference docs.
|
||||
*
|
||||
* Returns { on, reason?, next? } — `reason` is the one line a greyed card
|
||||
* shows, `next` marks the state's natural step.
|
||||
*/
|
||||
export function cardAvailability(entry, scan, sel) {
|
||||
const hasAgents = Boolean(scan && scan.hasAgents);
|
||||
const state = sel && sel.state && sel.state !== "unrecognized" ? sel.state : null;
|
||||
const next = sel ? Boolean(state) && NEXT_FOR_STATE[state] === entry.skill : entry.skill === "plan2code-0-pathfinder";
|
||||
|
||||
switch (entry.skill) {
|
||||
case "plan2code-init":
|
||||
return hasAgents ? off("AGENTS.md is already written. Refresh it instead.") : ON;
|
||||
case "plan2code-init-update":
|
||||
return hasAgents ? ON : off("Needs an AGENTS.md. Set the project up first.");
|
||||
case "plan2code-quick-task":
|
||||
case "plan2code-review":
|
||||
case "plan2code-handoff":
|
||||
return ON;
|
||||
case "plan2code-0-pathfinder":
|
||||
if (!state || state === "exploring") return { ...ON, next };
|
||||
return off("This spec is already past the questions");
|
||||
case "plan2code-1-plan":
|
||||
if (state === "exploring") return off("Pathfinder is not finished with this spec yet");
|
||||
if (state === "documented" || state === "building" || state === "built")
|
||||
return off("The plan is written. Revise it instead if it moved.");
|
||||
return { ...ON, next };
|
||||
case "plan2code-1b-revise-plan":
|
||||
if (state === "documented" || state === "building") return ON;
|
||||
return off(state === "built" ? "The spec is fully built" : "Needs a spec that is already written up");
|
||||
case "plan2code-2-document":
|
||||
if (state === "planned") return { ...ON, next };
|
||||
if (state === "documented" || state === "building" || state === "built")
|
||||
return off("The phases are already written up");
|
||||
return off("Needs a drafted plan first");
|
||||
case "plan2code-3-implement":
|
||||
case "plan2code-3-implement-review":
|
||||
if (state === "documented" || state === "building") return { ...ON, next };
|
||||
return off(state === "built" ? "All tasks are already done" : "Needs the phase checklists written up first");
|
||||
case "plan2code-4-finalize":
|
||||
if (state === "built") return { ...ON, next };
|
||||
return off("Needs a spec that is fully built");
|
||||
default:
|
||||
return ON;
|
||||
}
|
||||
}
|
||||
|
||||
export function cardPresentation(entry, scan, sel, menu = {}) {
|
||||
const availability = cardAvailability(entry, scan, sel);
|
||||
const specs = scan && Array.isArray(scan.specs) ? scan.specs : [];
|
||||
const initial = specs.length ? Boolean(sel && sel.dir === specs[0].dir) : !sel;
|
||||
const requested = initial && typeof menu.recommend === "string" ? catalogEntry(menu.recommend) : null;
|
||||
const recommendation = requested && cardAvailability(requested, scan, sel).on ? requested.skill : null;
|
||||
const recommended = availability.on && (recommendation ? entry.skill === recommendation : availability.next);
|
||||
const supplied = initial && menu.details && typeof menu.details[entry.skill] === "string" ? menu.details[entry.skill] : "";
|
||||
const detail = availability.on && supplied ? supplied : !initial && availability.next && sel && sel.detail ? sel.detail : "";
|
||||
return { ...availability, recommended, detail };
|
||||
}
|
||||
|
||||
/**
|
||||
* What a card click reaches the agent as, in `reply`. The action itself
|
||||
* carries `skill`, which is what the dashboard parses; this line is the
|
||||
* human-readable record of the ask. Like the other session phrases it keeps
|
||||
* clear of "brief", "recap" and "minutes", which Pathfinder would read as a
|
||||
* brief request.
|
||||
*/
|
||||
export function launchReply(entry, spec) {
|
||||
const target = spec && spec.dir ? ` for ${spec.dir}` : "";
|
||||
return `Start ${entry.title} (${entry.command})${target}, right here in this session.`;
|
||||
}
|
||||
|
||||
export function staleLaunchFeedback(title, adrift) {
|
||||
if (!adrift) return null;
|
||||
return {
|
||||
kicker: "Saved",
|
||||
title: `${title || "Your workflow"} is saved and waiting`,
|
||||
quip: "Plan2Code is not running right now.",
|
||||
hint: "Return to the terminal and send any message. Plan2Code will collect this launch and continue here.",
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ progress */
|
||||
|
||||
// The label must never read "7 of 5", whatever the agent posted: a build that
|
||||
// grew tasks mid-phase can post a `cleared` past its `total`. Guarded here on
|
||||
// the page only; the server takes the numbers as sent.
|
||||
export function progressTotal(cleared, total) {
|
||||
return Math.max(Number(cleared) || 0, Number(total) || 0);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- attachments */
|
||||
|
||||
// Attachments on a note or a quick question: at most five, images and
|
||||
// documents together. Images are re-encoded in the browser to a JPEG whose
|
||||
// long edge fits IMAGE_LONG_EDGE, with a small data: URL copy for the tray.
|
||||
// Documents upload byte for byte, and the server checks their contents itself.
|
||||
export const MAX_ATTACHMENTS = 5;
|
||||
export const MAX_NOTE_IMAGES = MAX_ATTACHMENTS;
|
||||
export const MAX_DOC_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
// The documents an agent can read with its own file tool, keyed by lower-case
|
||||
// extension. A hard-coded list, like the server's TYPES: it is the picker's
|
||||
// `accept`, the server's allow-list and the chip's label, so they can never
|
||||
// disagree.
|
||||
const textDoc = (label) => Object.freeze({ kind: "text", label });
|
||||
export const DOC_TYPES = Object.freeze({
|
||||
md: textDoc("Markdown"),
|
||||
txt: textDoc("Text"),
|
||||
json: textDoc("JSON"),
|
||||
yaml: textDoc("YAML"),
|
||||
yml: textDoc("YAML"),
|
||||
toml: textDoc("TOML"),
|
||||
ini: textDoc("INI"),
|
||||
csv: textDoc("CSV"),
|
||||
tsv: textDoc("TSV"),
|
||||
log: textDoc("Log"),
|
||||
xml: textDoc("XML"),
|
||||
html: textDoc("HTML"),
|
||||
css: textDoc("CSS"),
|
||||
scss: textDoc("SCSS"),
|
||||
js: textDoc("JavaScript"),
|
||||
mjs: textDoc("JavaScript"),
|
||||
cjs: textDoc("JavaScript"),
|
||||
ts: textDoc("TypeScript"),
|
||||
tsx: textDoc("TypeScript"),
|
||||
jsx: textDoc("JavaScript"),
|
||||
py: textDoc("Python"),
|
||||
java: textDoc("Java"),
|
||||
cs: textDoc("C#"),
|
||||
go: textDoc("Go"),
|
||||
rs: textDoc("Rust"),
|
||||
rb: textDoc("Ruby"),
|
||||
php: textDoc("PHP"),
|
||||
sh: textDoc("Shell"),
|
||||
ps1: textDoc("PowerShell"),
|
||||
sql: textDoc("SQL"),
|
||||
pdf: Object.freeze({ kind: "pdf", label: "PDF" }),
|
||||
});
|
||||
|
||||
// A file name's document extension, or null. A name whose only dot leads it
|
||||
// (`.env`, `.gitignore`) has no extension: dotfiles are where secrets live.
|
||||
export function docExt(name) {
|
||||
const s = String(name || "");
|
||||
const dot = s.lastIndexOf(".");
|
||||
if (dot <= 0 || dot === s.length - 1) return null;
|
||||
const ext = s.slice(dot + 1).toLowerCase();
|
||||
return Object.prototype.hasOwnProperty.call(DOC_TYPES, ext) ? ext : null;
|
||||
}
|
||||
|
||||
// The file picker's `accept`: any image, plus every document extension.
|
||||
export function pickerAccept() {
|
||||
return "image/*," + Object.keys(DOC_TYPES).map((ext) => "." + ext).join(",");
|
||||
}
|
||||
|
||||
export function formatBytes(n) {
|
||||
const bytes = Number(n) || 0;
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const mb = bytes >= 1024 * 1024;
|
||||
return new Intl.NumberFormat(undefined, {
|
||||
style: "unit",
|
||||
unit: mb ? "megabyte" : "kilobyte",
|
||||
maximumFractionDigits: mb ? 1 : 0,
|
||||
}).format(mb ? bytes / (1024 * 1024) : bytes / 1024);
|
||||
}
|
||||
|
||||
// An entry saved before documents existed has no `kind`: it is an image.
|
||||
export function attachmentKind(entry) {
|
||||
return entry && entry.kind === "file" ? "file" : "image";
|
||||
}
|
||||
|
||||
// Files the person picked, pasted or dropped, sorted by what they will be.
|
||||
// The extension decides first: browsers report `""` for `.md` and
|
||||
// `video/mp2t` for `.ts`, so `type` only settles what has no document
|
||||
// extension. Each list keeps the order given.
|
||||
export function sortAttachments(files) {
|
||||
const images = [];
|
||||
const docs = [];
|
||||
const refused = [];
|
||||
for (const file of files || []) {
|
||||
if (docExt(file.name)) {
|
||||
if (file.size > MAX_DOC_BYTES) refused.push({ name: file.name, reason: "too-large" });
|
||||
else docs.push(file);
|
||||
} else if (typeof file.type === "string" && file.type.startsWith("image/")) images.push(file);
|
||||
else refused.push({ name: file.name, reason: "type" });
|
||||
}
|
||||
return { images, docs, refused };
|
||||
}
|
||||
|
||||
export const IMAGE_LONG_EDGE = 2000;
|
||||
export const IMAGE_QUALITY = 0.85;
|
||||
export const THUMB_EDGE = 160;
|
||||
|
||||
// Scaled so the longer side is at most `max`, aspect kept, never upscaled.
|
||||
export function fitWithin(w, h, max) {
|
||||
const scale = Math.min(1, max / Math.max(w, h));
|
||||
return { w: Math.round(w * scale), h: Math.round(h * scale) };
|
||||
}
|
||||
|
||||
// A note's action, its attachments split into `images` and `files`. Only
|
||||
// `path` and `name` go: the page's own bookkeeping (`id`, `url`, `status`) is
|
||||
// nothing the agent can use. A key with nothing in it is left out.
|
||||
export function noteAction(id, text, attachments) {
|
||||
const action = { i: id, type: "comment", text };
|
||||
const list = attachments || [];
|
||||
const pick = (kind) => list.filter((a) => attachmentKind(a) === kind).map(({ path, name }) => ({ path, name }));
|
||||
const images = pick("image");
|
||||
const files = pick("file");
|
||||
if (images.length) action.images = images;
|
||||
if (files.length) action.files = files;
|
||||
return action;
|
||||
}
|
||||
|
||||
// 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.
|
||||
export function noteReplyLines(title, text, attachments) {
|
||||
const list = attachments || [];
|
||||
const anyFile = list.some((a) => attachmentKind(a) === "file");
|
||||
const said = text || (list.length ? (anyFile ? "(attachments only)" : "(images only)") : "");
|
||||
return [
|
||||
`Note on ${title}: ${said}`,
|
||||
...list.map((a) => ` ${attachmentKind(a) === "file" ? "File" : "Image"}: ${a.path} (${a.name})`),
|
||||
];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ patience */
|
||||
|
||||
/**
|
||||
* How long the agent may go quiet before the page calls it stuck.
|
||||
*
|
||||
* Every workflow before the build steps was a conversation: the agent was
|
||||
* either thinking about a reply or sitting in `wait`, so two or three minutes
|
||||
* of silence really did mean something had gone wrong. A build is different.
|
||||
* One task can take twenty minutes of honest work with nothing to post, and a
|
||||
* page that said "has not checked in, look at your terminal" every time would
|
||||
* be crying wolf. So the agent says how long quiet is normal right now
|
||||
* (`agent.quietMinutes`), and it counts only while the agent is `working`: a
|
||||
* waiting agent is polling, and a silent poller is still a stuck one. Never
|
||||
* below the page's own threshold, and capped at an hour so a typo cannot hide
|
||||
* a dead session.
|
||||
*/
|
||||
export function quietLimitMs(agent, baseMs) {
|
||||
if (!agent || agent.status !== "working") return baseMs;
|
||||
const m = Number(agent.quietMinutes);
|
||||
if (!Number.isFinite(m) || m <= 0) return baseMs;
|
||||
return Math.max(baseMs, Math.min(m, 60) * 60 * 1000);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- skip moves on */
|
||||
|
||||
// "Skip this one" moves the person on by itself. `staged` and `sent` are maps
|
||||
// keyed by item id: a card staged or already sent no longer needs them.
|
||||
const needsPerson = (id, staged, sent) => !(staged && staged[id]) && !(sent && sent[id]);
|
||||
|
||||
/** True when no open card other than `currentId` still needs the person. */
|
||||
export function lastOpenCard(openIds, staged, sent, currentId) {
|
||||
return openIds.every((id) => id === currentId || !needsPerson(id, staged, sent));
|
||||
}
|
||||
|
||||
/**
|
||||
* The next open card after `currentId` that still needs the person, wrapping
|
||||
* to the start; null when there is none.
|
||||
*/
|
||||
export function nextOpenAfter(openIds, staged, sent, currentId) {
|
||||
const at = openIds.indexOf(currentId);
|
||||
for (let step = 1; step <= openIds.length; step++) {
|
||||
const id = openIds[(at + step) % openIds.length];
|
||||
if (id !== currentId && needsPerson(id, staged, sent)) return id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ approvals */
|
||||
|
||||
// The page cannot see a harness's permission prompt, so it nudges instead: a
|
||||
// quiet tip line where a session starts, and a soft line beside Planny once a
|
||||
// working agent has gone quiet for a while. Mode names verified 2026-09-23.
|
||||
export const APPROVAL_TIP =
|
||||
"Your agent may pause for approvals in the terminal. A hands-off mode (e.g. `auto` mode in Claude Code, `smart` mode in Devin) can help avoid that, but additional attention may still be required.";
|
||||
export const APPROVAL_HINT = "Still working, or waiting on an approval in your terminal?";
|
||||
export const APPROVAL_HINT_MS = 30_000;
|
||||
// When a working agent's silence turns into "has not checked in".
|
||||
export const STALE_MS = 2 * 60 * 1000;
|
||||
|
||||
// The soft line, shown before the stale message takes over. It sits at a fixed
|
||||
// share of the stale limit (30 s of 2 min) rather than stretching on its own:
|
||||
// stretched separately, a build's quietMinutes lifted both to the same moment
|
||||
// and the soft line never showed where approvals stall most.
|
||||
export function approvalHint(agent, quietMs) {
|
||||
if (!agent || agent.status !== "working") return "";
|
||||
const at = quietLimitMs(agent, STALE_MS) * (APPROVAL_HINT_MS / STALE_MS);
|
||||
return quietMs >= at ? APPROVAL_HINT : "";
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,117 @@
|
||||
// Planny's wake-up on a freshly opened dashboard: he sits powered down centre
|
||||
// stage until the first click or key, gets nudged awake (he rocks side to side
|
||||
// for one snore), then about five seconds of him powering on, then a glide
|
||||
// into the rail as the menu comes in.
|
||||
//
|
||||
// The beats before the glide are pure CSS (keyframes on delays under
|
||||
// `.wake.booting`, see app.css). The glide is the one part CSS cannot know on
|
||||
// its own, because it ends wherever the rail's Planny sits right now, so this
|
||||
// measures it once and hands CSS a single transform through --wake-glide.
|
||||
//
|
||||
// No DOM access at module scope, so `node --test` can import it.
|
||||
|
||||
// When the glide starts, and when the run is over at the latest. The CSS
|
||||
// delays are the beats before GLIDE_AT_MS; the glide itself is 0.6 s.
|
||||
export const GLIDE_AT_MS = 4300;
|
||||
export const DONE_AT_MS = 5000;
|
||||
|
||||
// Plays the wake-up and resolves `{ skipped }` once the dashboard is fully
|
||||
// awake. He waits powered down until the first click or key anywhere, which
|
||||
// nudges him (`.stirring`) and calls `stir()` -- the page's cue to play one
|
||||
// full snore, since a browser only lets a page make noise after a real click
|
||||
// or keypress. The boot starts once the promise `stir()` returns settles (at
|
||||
// once without one), and calls `onStart()`, the page's cue for the boot-up
|
||||
// sound. `onGlide({ instant })` is the page's cue to bring the menu in: called
|
||||
// at the glide, or with `instant: true` if the run ends before one (a skip).
|
||||
// From the nudge on, clicks and keys are swallowed, so the run always plays
|
||||
// out to the end with its sound; only `signal` aborting (the page leaving the
|
||||
// dashboard, dormant or mid-run) cuts it short, as a skip. Under reduced
|
||||
// motion nothing is shown and it resolves at once.
|
||||
export function playWake({ stage, bot, target, stir, onStart, onGlide, signal }) {
|
||||
return new Promise((resolve) => {
|
||||
if (matchMedia("(prefers-reduced-motion: reduce)").matches || signal?.aborted) {
|
||||
resolve({ skipped: false });
|
||||
return;
|
||||
}
|
||||
const timers = [];
|
||||
let glided = false;
|
||||
let over = false;
|
||||
|
||||
const onGlideEnd = (e) => {
|
||||
if (e.target === bot && e.propertyName === "transform") end(false);
|
||||
};
|
||||
const skip = () => end(true);
|
||||
// Browser and OS shortcuts (reload, tab switch, devtools) still go through.
|
||||
const swallow = (e) => {
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
|
||||
function glide() {
|
||||
glided = true;
|
||||
// Measured untransformed, as the sketch's glideToSlot() does: the
|
||||
// transform-origin is the drawing's top-left, so the move is the gap
|
||||
// between the two top-left corners and the scale is the width ratio.
|
||||
// The target's own box, not its bounding rect: the rail's Planny is
|
||||
// usually tilted mid-flight, and a tilted box measures wider than he
|
||||
// is. Centred on the rect, which the tilt barely moves.
|
||||
const from = bot.getBoundingClientRect();
|
||||
const rect = target.getBoundingClientRect();
|
||||
const w = target.clientWidth || rect.width;
|
||||
const h = target.clientHeight || rect.height;
|
||||
const left = rect.left + (rect.width - w) / 2;
|
||||
const top = rect.top + (rect.height - h) / 2;
|
||||
const scale = from.width ? w / from.width : 1;
|
||||
bot.style.setProperty("--wake-glide", `translate(${left - from.left}px, ${top - from.top}px) scale(${scale})`);
|
||||
bot.addEventListener("transitionend", onGlideEnd);
|
||||
stage.classList.add("gliding");
|
||||
onGlide({ instant: false });
|
||||
}
|
||||
|
||||
function end(skipped) {
|
||||
if (over) return;
|
||||
over = true;
|
||||
for (const t of timers) clearTimeout(t);
|
||||
document.removeEventListener("pointerdown", start, true);
|
||||
document.removeEventListener("keydown", start, true);
|
||||
document.removeEventListener("pointerdown", swallow, true);
|
||||
document.removeEventListener("keydown", swallow, true);
|
||||
bot.removeEventListener("transitionend", onGlideEnd);
|
||||
signal?.removeEventListener("abort", skip);
|
||||
stage.hidden = true;
|
||||
stage.classList.remove("dormant", "stirring", "booting", "gliding");
|
||||
bot.style.removeProperty("--wake-glide");
|
||||
if (!glided) onGlide({ instant: true });
|
||||
resolve({ skipped });
|
||||
}
|
||||
|
||||
// The waking click is the only input the run takes: from here on every
|
||||
// click and key is swallowed until it ends.
|
||||
function start(e) {
|
||||
e.preventDefault();
|
||||
document.removeEventListener("pointerdown", start, true);
|
||||
document.removeEventListener("keydown", start, true);
|
||||
stage.classList.replace("dormant", "stirring");
|
||||
document.addEventListener("pointerdown", swallow, true);
|
||||
document.addEventListener("keydown", swallow, true);
|
||||
Promise.resolve(stir?.()).then(boot);
|
||||
}
|
||||
|
||||
function boot() {
|
||||
if (over) return;
|
||||
stage.classList.replace("stirring", "booting");
|
||||
onStart?.();
|
||||
timers.push(setTimeout(glide, GLIDE_AT_MS));
|
||||
// The glide's transitionend normally ends the run a touch earlier; this
|
||||
// is the fallback for a transition that never fires (a hidden tab).
|
||||
timers.push(setTimeout(() => end(false), DONE_AT_MS));
|
||||
}
|
||||
|
||||
document.addEventListener("pointerdown", start, true);
|
||||
document.addEventListener("keydown", start, true);
|
||||
signal?.addEventListener("abort", skip);
|
||||
stage.hidden = false;
|
||||
stage.classList.add("dormant");
|
||||
});
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,224 @@
|
||||
// Plan2Code Web Console - the Quick question chat's shared rules.
|
||||
//
|
||||
// Imported by the server (its guards) and by the page (its composer), so the
|
||||
// two can never disagree about a limit. No DOM access at module scope, and no
|
||||
// imports but answers.js: the server and `node --test` import this file too.
|
||||
|
||||
import { MAX_ATTACHMENTS, STALE_MS, quietLimitMs } from "./answers.js";
|
||||
|
||||
// Typed messages per conversation. Approve / Decline and resets never count.
|
||||
export const CHAT_LIMIT = 10;
|
||||
export const CHAT_MAX_CHARS = 4000;
|
||||
// Images and documents together. The old name stays for existing imports.
|
||||
export const CHAT_MAX_ATTACHMENTS = MAX_ATTACHMENTS;
|
||||
export const CHAT_MAX_IMAGES = CHAT_MAX_ATTACHMENTS;
|
||||
|
||||
export const CHAT_LIMIT_TEXT = "That's 10 questions in this conversation — start a new one to keep going.";
|
||||
export const CHAT_OFFLINE_TEXT = "No agent available — wait for one to become available (your terminal might be working on a task or waiting a permission approval)";
|
||||
export const CHAT_LAST_WAIT_TEXT = "That was the last question in this conversation — its answer will land here.";
|
||||
export const CHAT_WAITING_TEXT = "Plan2Code will answer at its next check-in";
|
||||
export const CHAT_WORKING_TEXT = "Plan2Code is working on the answer…";
|
||||
|
||||
const EMPTY_CHAT = { conversation: 0, messages: [], typed: 0, limit: CHAT_LIMIT, offline: false, pickedUp: 0 };
|
||||
const chatOf = (frameChat) => ({ ...EMPTY_CHAT, ...(frameChat || {}) });
|
||||
|
||||
// Person messages in the frame, each marked with whether an agent reply comes
|
||||
// after it. The server puts a reply straight after the entry it answers, so a
|
||||
// reply further down also covers the follow-ups sent before it.
|
||||
function answeredFlags(messages) {
|
||||
const flags = new Map();
|
||||
let replyLater = false;
|
||||
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);
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the Ask pane draws, in order: the conversation from the frame, then
|
||||
* any send of this page's the server has not echoed yet.
|
||||
*/
|
||||
export function chatView(frameChat, ui = {}) {
|
||||
const chat = chatOf(frameChat);
|
||||
const messages = Array.isArray(chat.messages) ? chat.messages : [];
|
||||
const answered = answeredFlags(messages);
|
||||
const decisions = new Map(
|
||||
messages.filter((m) => m.from === "person" && m.kind === "decision").map((m) => [m.re, m.decision])
|
||||
);
|
||||
const activity = typeof ui.agentActivity === "string" ? ui.agentActivity.trim() : "";
|
||||
// The last seq the agent collected: an unanswered message at or below it is
|
||||
// in the agent's hands, not still waiting for a check-in.
|
||||
const pickedUp = Number.isInteger(chat.pickedUp) ? chat.pickedUp : 0;
|
||||
const rows = [];
|
||||
for (const m of messages) {
|
||||
if (m.from === "agent") {
|
||||
rows.push({
|
||||
kind: "agent",
|
||||
id: m.id,
|
||||
md: m.md,
|
||||
proposal: m.proposal || null,
|
||||
changed: m.changed || null,
|
||||
decided: decisions.get(m.id) || null,
|
||||
});
|
||||
} else if (m.kind === "decision") {
|
||||
rows.push({ kind: "decision", decision: m.decision, text: m.text || "", re: m.re });
|
||||
} else if (m.kind === "message") {
|
||||
const row = {
|
||||
kind: "person",
|
||||
seq: m.seq,
|
||||
text: m.text,
|
||||
about: m.about || null,
|
||||
images: m.images || [],
|
||||
files: m.files || [],
|
||||
};
|
||||
if (!answered.get(m.seq)) {
|
||||
row.waiting = true;
|
||||
row.working = m.seq <= pickedUp;
|
||||
row.waitingText = row.working ? CHAT_WORKING_TEXT : CHAT_WAITING_TEXT;
|
||||
if (activity) row.activity = activity;
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
// A pending send is echoed once the server has it: by the seq its POST came
|
||||
// back with, or, while that response is still on its way, by its text
|
||||
// against a server message no other pending send has claimed.
|
||||
const serverPerson = messages.filter((m) => m.from === "person" && m.kind === "message");
|
||||
const serverSeqs = new Set(serverPerson.map((m) => m.seq));
|
||||
const claimed = new Set((ui.pendingSends || []).filter((p) => p.seq).map((p) => p.seq));
|
||||
for (const p of ui.pendingSends || []) {
|
||||
if (p.seq) {
|
||||
if (serverSeqs.has(p.seq)) continue;
|
||||
} else {
|
||||
const echo = serverPerson.find((m) => m.text === p.text && !claimed.has(m.seq));
|
||||
if (echo) {
|
||||
claimed.add(echo.seq);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
rows.push({
|
||||
kind: "person",
|
||||
pending: true,
|
||||
tempId: p.tempId,
|
||||
text: p.text,
|
||||
about: p.about || null,
|
||||
images: p.images || [],
|
||||
files: p.files || [],
|
||||
failed: Boolean(p.failed),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
conversation: chat.conversation,
|
||||
rows,
|
||||
counterText: `${chat.typed} of ${chat.limit}`,
|
||||
typed: chat.typed,
|
||||
limit: chat.limit,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the composer can take a message, and what to say when it cannot.
|
||||
* Offline first, so a finished page never talks about the limit. The limit
|
||||
* lands once the 10th question is answered; until then the 10th is simply
|
||||
* waiting, and nothing more can be typed.
|
||||
*/
|
||||
export function sendState({ frameChat, gone, pendingSendCount = 0 }) {
|
||||
const chat = chatOf(frameChat);
|
||||
if (chat.offline || gone) return { state: "offline", text: CHAT_OFFLINE_TEXT, canType: false };
|
||||
if (chat.typed + pendingSendCount >= chat.limit) {
|
||||
const allAnswered = pendingSendCount === 0 && [...answeredFlags(chat.messages || []).values()].every(Boolean);
|
||||
if (allAnswered) return { state: "limit", text: CHAT_LIMIT_TEXT, canType: false };
|
||||
return { state: "ok", text: CHAT_LAST_WAIT_TEXT, canType: false };
|
||||
}
|
||||
return { state: "ok", text: "", canType: true };
|
||||
}
|
||||
|
||||
const ABOUT_HISTORY = 3;
|
||||
|
||||
/**
|
||||
* What a message is about, attached on purpose. Visiting a question card, doc
|
||||
* section or spec only records it in `history` (the last 3 places, newest
|
||||
* first, one entry per place); `about` is set only when the person picks one
|
||||
* from + Add context, and × or a send clears it.
|
||||
*
|
||||
* The tracker is `{ history, about }`; each entry and `about` are
|
||||
* `{ kind, id, label }` (`about` may be null), in the exact shape POST /chat
|
||||
* takes. An old `{ about, frozen, dropped }` tracker normalises to an empty
|
||||
* history.
|
||||
*/
|
||||
export function nextAbout(prev, event) {
|
||||
const p = prev || {};
|
||||
const state = { history: Array.isArray(p.history) ? [...p.history] : [], about: p.about ?? null };
|
||||
const visit = (entry) => ({
|
||||
...state,
|
||||
history: [entry, ...state.history.filter((h) => h.kind !== entry.kind || h.id !== entry.id)].slice(0, ABOUT_HISTORY),
|
||||
});
|
||||
switch (event && event.type) {
|
||||
case "card":
|
||||
return visit({ kind: "card", id: String(event.id), label: String(event.label || "") });
|
||||
case "section":
|
||||
return visit({ kind: "section", id: `${event.docId}#${event.blockId}`, label: String(event.label || "") });
|
||||
case "spec":
|
||||
return visit({ kind: "spec", id: String(event.dir), label: String(event.label || "") });
|
||||
case "pick":
|
||||
return event.about ? { ...state, about: event.about } : state;
|
||||
case "drop":
|
||||
case "sent":
|
||||
return { ...state, about: null };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
// What + Add context lists: the recent places, then "This spec" unless it is
|
||||
// already one of them.
|
||||
export function contextOptions(state, spec) {
|
||||
const options = [...((state && state.history) || [])];
|
||||
if (spec && spec.dir && !options.some((o) => o.kind === "spec" && o.id === spec.dir)) {
|
||||
options.push({ kind: "spec", id: spec.dir, label: "This spec" });
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
const newestReply = (frameChat) => {
|
||||
const messages = chatOf(frameChat).messages || [];
|
||||
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].from === "agent") return messages[i];
|
||||
return null;
|
||||
};
|
||||
|
||||
// The Ask tab's dot: a reply landed that the person has not seen.
|
||||
export function unreadDot({ lastSeenReplyId, frameChat, viewIsAsk }) {
|
||||
if (viewIsAsk) return false;
|
||||
const reply = newestReply(frameChat);
|
||||
return Boolean(reply) && reply.id !== lastSeenReplyId;
|
||||
}
|
||||
|
||||
export function newestReplyId(frameChat) {
|
||||
const reply = newestReply(frameChat);
|
||||
return reply ? reply.id : null;
|
||||
}
|
||||
|
||||
// One chime per reply: only the moment the dot appears.
|
||||
export function shouldChime(prevDot, nextDot) {
|
||||
return !prevDot && Boolean(nextDot);
|
||||
}
|
||||
|
||||
// The page's own "has drifted away" threshold for an agent that is waiting.
|
||||
const ADRIFT_MS = 3 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Whether nobody is there to answer a chat message. A finished or paused
|
||||
* session has no agent coming back to it; otherwise the agent is offline once
|
||||
* it has been silent longer than the page would tolerate before calling it
|
||||
* stuck (working) or adrift (anything else).
|
||||
*/
|
||||
export function chatOffline({ finish, agent, agentLastSeenMs, now }) {
|
||||
if (finish) return true;
|
||||
const silent = now - agentLastSeenMs;
|
||||
if (agent && agent.status === "working") return silent > quietLimitMs(agent, STALE_MS);
|
||||
return silent > quietLimitMs(agent, ADRIFT_MS);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Plan2Code Web Console - the tab icon's status bar.
|
||||
//
|
||||
// The favicon follows the status line with a bar along its bottom edge: dashed
|
||||
// amber while Plan2Code is busy, solid green when it is the person's move,
|
||||
// solid red when it needs attention, and none (the plain Planny) once the
|
||||
// session is finished. It reads from the same calls
|
||||
// renderStatus() already makes for Planny's mood, so the icon and the line
|
||||
// beside him can never disagree. No DOM access at module scope: `node --test`
|
||||
// imports this file.
|
||||
|
||||
// Planny exactly as public/favicon.svg draws him (a test keeps the two in
|
||||
// step), minus the <svg> wrapper so the bar can be layered on top.
|
||||
export const FAVICON_BODY = `<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
|
||||
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
|
||||
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />`;
|
||||
|
||||
// The bar's color per state. `plain` has none.
|
||||
export const FAVICON_COLORS = Object.freeze({
|
||||
busy: "#f5a524",
|
||||
ready: "#22c55e",
|
||||
attention: "#e5484d",
|
||||
});
|
||||
|
||||
/**
|
||||
* Which icon a status line calls for. `mood` and `spin` are what renderStatus()
|
||||
* handed to say(): `spin` marks something really happening at the other end
|
||||
* right now, so that is busy. A working mood without the spin is the stale
|
||||
* line ("has not checked in for a few minutes"), which, like adrift and gone,
|
||||
* needs attention. `point` is the person's move. A finished session is plain
|
||||
* unless it is visibly busy again (opening the dashboard, starting a review).
|
||||
*/
|
||||
export function faviconState({ mood, spin = false, finished = false } = {}) {
|
||||
if (spin) return "busy";
|
||||
if (finished) return "plain";
|
||||
if (mood === "adrift" || mood === "gone" || mood === "work") return "attention";
|
||||
if (mood === "point") return "ready";
|
||||
return "plain";
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole SVG for a state: Planny, plus a bar across the bottom edge, where
|
||||
* he is cropped anyway. Busy's bar is dashed on a white strip (a progress bar
|
||||
* mid-run) and the others solid, so busy differs by pattern as well as color:
|
||||
* amber and green are close to one color for red-green color-blind eyes.
|
||||
*/
|
||||
export function faviconSvg(state) {
|
||||
const color = FAVICON_COLORS[state];
|
||||
let badge = "";
|
||||
if (state === "busy") {
|
||||
badge = `\n <rect x="0" y="27" width="32" height="5" fill="#ffffff" />\n <path d="M1.5 29.5 L30.5 29.5" stroke="${color}" stroke-width="4" stroke-dasharray="4 2.5" />`;
|
||||
} else if (color) {
|
||||
badge = `\n <rect x="0" y="27" width="32" height="5" rx="1" fill="${color}" />`;
|
||||
}
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">\n ${FAVICON_BODY}${badge}\n</svg>\n`;
|
||||
}
|
||||
|
||||
let shown = "plain";
|
||||
|
||||
/**
|
||||
* Point the page's two icon links at `state`'s icon, only when it changed. The
|
||||
* SVG link takes the variant as a data URL; the PNG link, for browsers that
|
||||
* pick the bitmap, gets the same variant drawn through a canvas. Plain goes
|
||||
* back to the served files.
|
||||
*/
|
||||
export function setFavicon(state) {
|
||||
if (state === shown || typeof document === "undefined") return;
|
||||
shown = state;
|
||||
const svgLink = document.querySelector('link[rel="icon"][type="image/svg+xml"]');
|
||||
const pngLink = document.querySelector('link[rel="icon"][type="image/png"]');
|
||||
if (state === "plain") {
|
||||
if (svgLink) svgLink.href = "/favicon.svg";
|
||||
if (pngLink) pngLink.href = "/favicon.png";
|
||||
return;
|
||||
}
|
||||
const url = "data:image/svg+xml," + encodeURIComponent(faviconSvg(state));
|
||||
if (svgLink) svgLink.href = url;
|
||||
if (!pngLink) return;
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
// A newer state won the race while this one was loading.
|
||||
if (shown !== state) return;
|
||||
try {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = 64;
|
||||
canvas.getContext("2d").drawImage(img, 0, 0, 64, 64);
|
||||
pngLink.href = canvas.toDataURL("image/png");
|
||||
} catch {}
|
||||
};
|
||||
img.src = url;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.5 KiB |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<rect x="4" y="4.6" width="24" height="30" rx="5" fill="#fff4ef" stroke="#3b332c" stroke-width="2.2" />
|
||||
<path d="M16 9.8 L17.41 13.26 L21.14 13.53 L18.28 15.94 L19.17 19.57 L16 17.6 L12.83 19.57 L13.72 15.94 L10.86 13.53 L14.59 13.26 Z" fill="#ae4f2b" />
|
||||
<path d="M11.6 22.2 Q16 26.4 20.4 22.2" fill="none" stroke="#3b332c" stroke-width="1.8" stroke-linecap="round" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 443 B |
@@ -0,0 +1,65 @@
|
||||
// Plan2Code Web Console - the Help dialog's tab list and rules.
|
||||
//
|
||||
// The source of truth for which tabs Help has, in what order, and which one
|
||||
// opens. The content itself is HTML in <template id="help-content">
|
||||
// in index.html. No DOM access at module scope and no imports: the page and
|
||||
// `node --test` both import this file.
|
||||
|
||||
const tab = (id, label, diagram) => Object.freeze({ id, label, diagram });
|
||||
|
||||
export const HELP_TABS = Object.freeze([
|
||||
tab("about", "What this page is", true),
|
||||
tab("around", "Finding your way around", true),
|
||||
tab("workspace", "Your workspace", false),
|
||||
tab("planny", "Reading Planny", true),
|
||||
tab("answering", "Answering questions", false),
|
||||
tab("sending", "Sending and what happens next", true),
|
||||
tab("notes", "Notes and attachments", false),
|
||||
tab("docs", "Documents and printing", false),
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
tab("stuck", "When something looks stuck", true),
|
||||
tab("prefs", "Keyboard and preferences", false),
|
||||
tab("privacy", "Privacy and where things are saved", false),
|
||||
]);
|
||||
|
||||
// Not labels.js's BUILD_WORKFLOWS: that one leaves out quick-task, which is a
|
||||
// build as far as the person watching it is concerned.
|
||||
const HELP_BUILD_WORKFLOWS = new Set(["implement", "implement-review", "quick-task"]);
|
||||
|
||||
// Which tab Help opens on, from where the person is. First match wins.
|
||||
export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow, workspace, meterRed } = {}) {
|
||||
const v = view || "";
|
||||
// Finished comes first: a finished session's server is stopped on purpose,
|
||||
// which also sets `gone`, and that is not something being stuck.
|
||||
if (finished || v === "end") return "finishing";
|
||||
if (gone || adrift) return "stuck";
|
||||
if (workspace) return "workspace";
|
||||
if (v === "ask") return "ask";
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build";
|
||||
return "about";
|
||||
}
|
||||
|
||||
// The tab index a key moves to, or -1 when the key is not a tab key.
|
||||
export function helpKeyTarget(key, index, count) {
|
||||
switch (key) {
|
||||
case "ArrowDown":
|
||||
case "ArrowRight":
|
||||
return (index + 1) % count;
|
||||
case "ArrowUp":
|
||||
case "ArrowLeft":
|
||||
return (index - 1 + count) % count;
|
||||
case "Home":
|
||||
return 0;
|
||||
case "End":
|
||||
return count - 1;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
@@ -0,0 +1,31 @@
|
||||
// Activity-line wording the page corrects on the way in. Kept out of app.js so
|
||||
// `node --test` can import it: no DOM access at module scope.
|
||||
//
|
||||
// A build numbers its tasks "Task 4.2" after the phase, but a person watching
|
||||
// the page counts within the phase, so "Task 4.2 of 6" reads as nonsense
|
||||
// beside a progress bar that says 2 of 6.
|
||||
|
||||
// The only workflows whose activity lines get rewritten.
|
||||
export const BUILD_WORKFLOWS = new Set(["implement", "implement-review"]);
|
||||
|
||||
const PHASE_TASK = /^Task (\d+)\.(\d+) of (\d+)/;
|
||||
|
||||
export function taskLabel(text) {
|
||||
if (typeof text !== "string" || !PHASE_TASK.test(text)) return text;
|
||||
return text.replace(PHASE_TASK, (_, _phase, n, total) => `Task ${n} of ${total}`);
|
||||
}
|
||||
|
||||
// An activity line as the page shows it: rewritten in a build, as sent
|
||||
// everywhere else (a plan's "Task 2.1" is a real section number).
|
||||
export function activityLabel(text, workflow) {
|
||||
return BUILD_WORKFLOWS.has(workflow) ? taskLabel(text) : text;
|
||||
}
|
||||
|
||||
// What a working agent is doing, for a page with nothing asked yet: its
|
||||
// activity line, or the headline note it posted instead. Either one means the
|
||||
// skill has started, so the page leaves its starting screen.
|
||||
export function workingLine(agent, headline, workflow) {
|
||||
if (!agent || agent.status !== "working") return "";
|
||||
if (typeof agent.activity === "string" && agent.activity.trim()) return activityLabel(agent.activity.trim(), workflow);
|
||||
return typeof headline?.note === "string" ? headline.note.trim() : "";
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// Plan2Code Web Console - `@name` suggestions in a text box.
|
||||
//
|
||||
// Finds the `@partial` the caret sits in, filters the workspace's folder
|
||||
// names against it, and splices a pick back into the text. The page owns the
|
||||
// popover; this file owns the rules. No DOM access at module scope and no
|
||||
// imports: the page and `node --test` both import this file.
|
||||
|
||||
const NAME_CHAR = /[a-z0-9-]/;
|
||||
const MAX_MATCHES = 6;
|
||||
|
||||
/**
|
||||
* The mention the caret is in: `{ start, query }`, where `start` is the index
|
||||
* of the `@`, or null. The `@` must open the text or follow whitespace or
|
||||
* `(`, so an email address never offers suggestions.
|
||||
*/
|
||||
export function mentionAt(text, caret) {
|
||||
let i = caret;
|
||||
while (i > 0 && NAME_CHAR.test(text[i - 1])) i--;
|
||||
const at = i - 1;
|
||||
if (at < 0 || text[at] !== "@") return null;
|
||||
if (at > 0 && !/[\s(]/.test(text[at - 1])) return null;
|
||||
return { start: at, query: text.slice(i, caret) };
|
||||
}
|
||||
|
||||
// Names starting with the query first, then names containing it, in the
|
||||
// order given, at most six.
|
||||
export function matchNames(names, query) {
|
||||
const q = String(query || "");
|
||||
const prefix = names.filter((n) => n.startsWith(q));
|
||||
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
|
||||
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
||||
}
|
||||
|
||||
// The text with `@partial` replaced by `@name `, and the caret after the space.
|
||||
export function applyMention(text, caret, mention, name) {
|
||||
const insert = `@${name} `;
|
||||
return {
|
||||
text: text.slice(0, mention.start) + insert + text.slice(caret),
|
||||
caret: mention.start + insert.length,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Plan2Code Web Console - the session meter's weights, count and wording.
|
||||
//
|
||||
// The source of truth for how much each piece of work weighs, how the count
|
||||
// is folded out of ledger.ndjson, and what the pill says at each level. The
|
||||
// count is never stored: it is always pointsFrom() over the ledger. No DOM
|
||||
// access at module scope and no imports: the server, console.mjs, the page
|
||||
// and `node --test` all import this file.
|
||||
|
||||
// The one place the weights live (FR-12). Tune here.
|
||||
export const WEIGHTS = Object.freeze({
|
||||
"pathfinder-chart": 2,
|
||||
"pathfinder-question": 1,
|
||||
plan: 2,
|
||||
"revise-plan": 1,
|
||||
document: 2,
|
||||
"implement-phase": 2,
|
||||
"implement-review-phase": 3,
|
||||
review: 2,
|
||||
"quick-task": 1,
|
||||
init: 2,
|
||||
"init-update": 2,
|
||||
finalize: 1,
|
||||
handoff: 0,
|
||||
});
|
||||
|
||||
// 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.
|
||||
export const LAUNCH_COUNTED = Object.freeze(
|
||||
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize"])
|
||||
);
|
||||
|
||||
// The event names an agent may report in `run`.
|
||||
export const RUN_EVENTS = new Set(Object.keys(WEIGHTS));
|
||||
|
||||
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
|
||||
|
||||
/**
|
||||
* The session's points, folded from ledger entries in order. An id seen
|
||||
* before is skipped, so a repeated `post` never counts twice.
|
||||
*/
|
||||
export function pointsFrom(entries) {
|
||||
const seen = new Set();
|
||||
let points = 0;
|
||||
for (const entry of Array.isArray(entries) ? entries : []) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
if (entry.id !== undefined) {
|
||||
if (seen.has(entry.id)) continue;
|
||||
seen.add(entry.id);
|
||||
}
|
||||
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) points += weightOf(entry.workflow);
|
||||
else if (entry.kind === "run") points += weightOf(entry.event);
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
export const YELLOW_AT = 4;
|
||||
export const RED_AT = 6;
|
||||
export const RING_FULL = 8;
|
||||
|
||||
export function levelFor(points) {
|
||||
if (points < YELLOW_AT) return "green";
|
||||
if (points < RED_AT) return "yellow";
|
||||
return "red";
|
||||
}
|
||||
|
||||
// How much of the ring is filled: full at RING_FULL, never below empty.
|
||||
export function ringFraction(points) {
|
||||
return Math.max(0, Math.min(points, RING_FULL)) / RING_FULL;
|
||||
}
|
||||
|
||||
export const WORDS = Object.freeze({
|
||||
green: "Session: fresh",
|
||||
yellow: "Session: getting long",
|
||||
red: "Session: time for a fresh start",
|
||||
});
|
||||
|
||||
export function tooltipFor(points) {
|
||||
const count = `${points} ${points === 1 ? "point" : "points"}`;
|
||||
switch (levelFor(points)) {
|
||||
case "green":
|
||||
return `This session is fresh (${count}).`;
|
||||
case "yellow":
|
||||
return `This session is getting long (${count}). A fresh one will soon be sharper.`;
|
||||
default:
|
||||
return `This session has done a lot (${count}). The agent may start missing things.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const RED_BANNER =
|
||||
"This console session has done a lot. Starting a new console session will keep the agent sharp.";
|
||||
|
||||
// Everything the pill draws, from the ledger alone.
|
||||
export function meterView(entries) {
|
||||
const points = pointsFrom(entries);
|
||||
const level = levelFor(points);
|
||||
return { points, level, fraction: ringFraction(points), words: WORDS[level], tooltip: tooltipFor(points) };
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
// The highlight colors, as data. Kept out of app.js for one reason: app.js
|
||||
// cannot be imported outside a browser, and thirty-two colors each with four
|
||||
// shades in two themes is far too many to trust to eyeballing. The test suite
|
||||
// imports this and checks every one.
|
||||
//
|
||||
// The palette has three colors that MEAN something -- green settled, amber
|
||||
// waiting, red careful. The reds, golds and greens here are offered anyway,
|
||||
// because people asked for them; the help text in the dialog says what they
|
||||
// share a hue with, and the choice is theirs.
|
||||
//
|
||||
// Each accent is four values, not one, because one color cannot do four jobs:
|
||||
// fill the highlight itself: filled buttons, the marker on the open step
|
||||
// soft a tint faint enough to sit behind body text
|
||||
// ink what is legible ON the fill. Dark mode's accents are light shades,
|
||||
// where a white label falls to about 2:1; they take a near-black.
|
||||
// line the secondary: borders, badge edges, the dashed drop target.
|
||||
//
|
||||
// Every pair clears 4.5:1 for ink on fill and for fill on soft (the fill is
|
||||
// also badge text on the soft tint). Everything after the first five was
|
||||
// found by stepping lightness until both held, not picked by eye.
|
||||
//
|
||||
// Order is the order of the picker: round the wheel, then the greys. Sixteen
|
||||
// a row, so the warm half and the greens sit on the first, the blues, purples,
|
||||
// pinks and greys on the second.
|
||||
|
||||
export const ACCENTS = {
|
||||
// name fill soft ink line
|
||||
crimson: {
|
||||
name: "Crimson",
|
||||
light: ["#cd1d41", "#fbe9ed", "#ffffff", "#dcaab4"],
|
||||
dark: ["#e75874", "#321b1f", "#140b0d", "#743e49"],
|
||||
},
|
||||
scarlet: {
|
||||
name: "Scarlet",
|
||||
light: ["#cf2317", "#fbebe9", "#ffffff", "#ddaaa7"],
|
||||
dark: ["#eb594e", "#321c1b", "#140b0b", "#74403c"],
|
||||
},
|
||||
coral: {
|
||||
name: "Coral",
|
||||
light: ["#c83510", "#fbede9", "#ffffff", "#dcaca0"],
|
||||
dark: ["#ef5b37", "#321f1b", "#140d0b", "#6f4237"],
|
||||
},
|
||||
rust: {
|
||||
name: "Rust",
|
||||
light: ["#ae4f2b", "#fbeee7", "#ffffff", "#dd9b7e"],
|
||||
dark: ["#e8825a", "#34211a", "#1a120e", "#8a4f36"],
|
||||
},
|
||||
tangerine: {
|
||||
name: "Tangerine",
|
||||
light: ["#b15209", "#fbf1e9", "#ffffff", "#d9af8f"],
|
||||
dark: ["#f2700d", "#32251b", "#140f0b", "#664830"],
|
||||
},
|
||||
copper: {
|
||||
name: "Copper",
|
||||
light: ["#a2592f", "#f9f0eb", "#ffffff", "#cdb2a2"],
|
||||
dark: ["#cb7a4b", "#32231b", "#140e0b", "#5f493d"],
|
||||
},
|
||||
clay: {
|
||||
name: "Clay",
|
||||
light: ["#8d644c", "#f5f2f0", "#ffffff", "#bfafa6"],
|
||||
dark: ["#ba957f", "#2b2521", "#17100c", "#62544b"],
|
||||
},
|
||||
marigold: {
|
||||
name: "Marigold",
|
||||
light: ["#9a6406", "#fbf5e9", "#ffffff", "#d3b279"],
|
||||
dark: ["#f59f0a", "#32291b", "#14110b", "#5e4c2c"],
|
||||
},
|
||||
gold: {
|
||||
name: "Gold",
|
||||
light: ["#896b09", "#fbf7e9", "#ffffff", "#ccb66d"],
|
||||
dark: ["#f0bb0f", "#322c1b", "#14120b", "#584d2a"],
|
||||
},
|
||||
mustard: {
|
||||
name: "Mustard",
|
||||
light: ["#806f1b", "#fbf8ea", "#ffffff", "#c3b881"],
|
||||
dark: ["#d2b72d", "#322e1b", "#14120b", "#544e31"],
|
||||
},
|
||||
olive: {
|
||||
name: "Olive",
|
||||
light: ["#72742c", "#f8f8ed", "#ffffff", "#b8ba8c"],
|
||||
dark: ["#b5b946", "#31321b", "#14140b", "#4f5037"],
|
||||
},
|
||||
lime: {
|
||||
name: "Lime",
|
||||
light: ["#577a1a", "#f4fbea", "#ffffff", "#a6c07a"],
|
||||
dark: ["#96d22d", "#29321b", "#11140b", "#465230"],
|
||||
},
|
||||
moss: {
|
||||
name: "Moss",
|
||||
light: ["#577740", "#f2f6ee", "#ffffff", "#acbca1"],
|
||||
dark: ["#79a659", "#24321b", "#0f140b", "#475140"],
|
||||
},
|
||||
emerald: {
|
||||
name: "Emerald",
|
||||
light: ["#207e47", "#ebfaf1", "#ffffff", "#8ac4a2"],
|
||||
dark: ["#33cc73", "#1b3224", "#0b140f", "#345542"],
|
||||
},
|
||||
jade: {
|
||||
name: "Jade",
|
||||
light: ["#297c61", "#ecf9f4", "#ffffff", "#92c1b1"],
|
||||
dark: ["#40bf95", "#1b322a", "#0b1411", "#38544b"],
|
||||
},
|
||||
teal: {
|
||||
name: "Teal",
|
||||
light: ["#0f766e", "#e2f1ef", "#ffffff", "#6fb3aa"],
|
||||
dark: ["#5ecfc0", "#14302c", "#0b1a18", "#3a7d74"],
|
||||
},
|
||||
cyan: {
|
||||
name: "Cyan",
|
||||
light: ["#0f798a", "#ebf7f9", "#ffffff", "#75bec9"],
|
||||
dark: ["#19cae6", "#183034", "#0c1617", "#305f66"],
|
||||
},
|
||||
sky: {
|
||||
name: "Sky",
|
||||
light: ["#0e74a7", "#ebf5fa", "#ffffff", "#85b9d3"],
|
||||
dark: ["#21a9ed", "#182b35", "#0c1417", "#325c71"],
|
||||
},
|
||||
ocean: {
|
||||
name: "Ocean",
|
||||
light: ["#206cc3", "#ecf2f9", "#ffffff", "#9ab4d3"],
|
||||
dark: ["#619fe5", "#1a2533", "#0c1117", "#3d5978"],
|
||||
},
|
||||
navy: {
|
||||
name: "Navy",
|
||||
light: ["#24396b", "#eef0f7", "#ffffff", "#a7b3cd"],
|
||||
dark: ["#819ad5", "#1e232f", "#0c1017", "#4a5775"],
|
||||
},
|
||||
cobalt: {
|
||||
name: "Cobalt",
|
||||
light: ["#405ce7", "#ebeef9", "#ffffff", "#a8b0dc"],
|
||||
dark: ["#7b8fef", "#191d34", "#0c0e17", "#465392"],
|
||||
},
|
||||
indigo: {
|
||||
name: "Indigo",
|
||||
light: ["#4f46e5", "#ecebfb", "#ffffff", "#9b95ef"],
|
||||
dark: ["#a5a0ff", "#1e1d3a", "#121129", "#5f5ba8"],
|
||||
},
|
||||
violet: {
|
||||
name: "Violet",
|
||||
light: ["#7f4dd5", "#f1edf8", "#ffffff", "#bbabd6"],
|
||||
dark: ["#a785e2", "#231c31", "#100c17", "#624c87"],
|
||||
},
|
||||
lilac: {
|
||||
name: "Lilac",
|
||||
light: ["#8b51b8", "#f3eff6", "#ffffff", "#beaccb"],
|
||||
dark: ["#b189cf", "#271f2d", "#130c17", "#634f73"],
|
||||
},
|
||||
orchid: {
|
||||
name: "Orchid",
|
||||
light: ["#a141b9", "#f5eef7", "#ffffff", "#c5a8cc"],
|
||||
dark: ["#c281d3", "#2b1e2f", "#150c17", "#6c4b74"],
|
||||
},
|
||||
magenta: {
|
||||
name: "Magenta",
|
||||
light: ["#b82eaa", "#f8edf7", "#ffffff", "#d1a3cc"],
|
||||
dark: ["#dc72d1", "#311c2f", "#170c16", "#784573"],
|
||||
},
|
||||
plum: {
|
||||
name: "Plum",
|
||||
light: ["#8a3b6b", "#f8eaf2", "#ffffff", "#c88cb0"],
|
||||
dark: ["#e08ab8", "#331a29", "#1d1017", "#8a5570"],
|
||||
},
|
||||
rose: {
|
||||
name: "Rose",
|
||||
light: ["#c42e6a", "#f8edf1", "#ffffff", "#d3a6b8"],
|
||||
dark: ["#df77a0", "#311c24", "#170c11", "#7c465b"],
|
||||
},
|
||||
steel: {
|
||||
name: "Steel",
|
||||
light: ["#50737c", "#f0f3f4", "#ffffff", "#a5b5b8"],
|
||||
dark: ["#7fa4ad", "#22292a", "#0c1517", "#4c595c"],
|
||||
},
|
||||
slate: {
|
||||
name: "Slate",
|
||||
light: ["#5b6e88", "#f0f2f4", "#ffffff", "#acb3bc"],
|
||||
dark: ["#8e9eb4", "#23262a", "#0c1117", "#515861"],
|
||||
},
|
||||
mauve: {
|
||||
name: "Mauve",
|
||||
light: ["#816281", "#f4f1f4", "#ffffff", "#bbafbb"],
|
||||
dark: ["#ae93ae", "#292329", "#170c17", "#5f545f"],
|
||||
},
|
||||
graphite: {
|
||||
name: "Graphite",
|
||||
light: ["#4a4640", "#eeedea", "#ffffff", "#a8a196"],
|
||||
dark: ["#cfc7bb", "#2b2a28", "#161513", "#7a7369"],
|
||||
},
|
||||
};
|
||||
|
||||
export const DEFAULT_ACCENT = "rust";
|
||||
|
||||
// The card-width presets. Here for the same reason the accents are: the page
|
||||
// validates a saved `looks.width` with cardWidth(), and the server uses it to
|
||||
// paint the first-load `data-width` attribute before app.js runs. One list,
|
||||
// two readers, no drift.
|
||||
export const CARD_WIDTHS = {
|
||||
narrow: { label: "Narrow", px: 720 },
|
||||
comfortable: { label: "Comfortable", px: 880 },
|
||||
wide: { label: "Wide", px: 1080 },
|
||||
};
|
||||
|
||||
export const DEFAULT_CARD_WIDTH = "comfortable";
|
||||
|
||||
export function cardWidth(value) {
|
||||
return typeof value === "string" && Object.hasOwn(CARD_WIDTHS, value) ? value : DEFAULT_CARD_WIDTH;
|
||||
}
|
||||
|
||||
// Every moment the page makes a noise, each switchable on its own in User
|
||||
// Preferences (the `data-sound` boxes in index.html). Several share a file;
|
||||
// the event, not the file, is what a person turns off. `rank` settles which
|
||||
// wins when two ask at once (see the sounds section in app.js). Stored flat as
|
||||
// `soundQuestion` and so on, because looks.json only holds flat values.
|
||||
export const SOUND_EVENTS = {
|
||||
startSkill: { file: "start-skill", rank: 5 },
|
||||
bootup: { file: "bootup", rank: 4 },
|
||||
sessionStart: { file: "start-stop", rank: 3 },
|
||||
sessionEnd: { file: "start-stop", rank: 3 },
|
||||
question: { file: "next", rank: 2 },
|
||||
skillReady: { file: "next", rank: 2 },
|
||||
chatReply: { file: "next", rank: 2 },
|
||||
newTab: { file: "insert", rank: 1 },
|
||||
snore: { file: "sleeping", rank: 0 },
|
||||
};
|
||||
|
||||
export const soundKey = (event) => "sound" + event[0].toUpperCase() + event.slice(1);
|
||||
|
||||
// The per-event switches out of a saved looks object: each one as saved when
|
||||
// it is a boolean, on otherwise. A looks.json from before the switches has
|
||||
// none of these keys, so it keeps every sound.
|
||||
export function soundPrefs(saved) {
|
||||
const source = saved && typeof saved === "object" ? saved : {};
|
||||
return Object.fromEntries(
|
||||
Object.keys(SOUND_EVENTS).map((event) => {
|
||||
const value = source[soundKey(event)];
|
||||
return [soundKey(event), typeof value === "boolean" ? value : true];
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
// Markdown to DOM, safely.
|
||||
//
|
||||
// The rule this file exists to enforce: NO HTML STRING IS EVER PRODUCED.
|
||||
// We take marked's token tree and build nodes with createElement/textContent.
|
||||
//
|
||||
// Why that matters more than it looks: this page is same-origin with a server
|
||||
// that reads and writes the user's files and holds the session cookie. Script
|
||||
// running here could post arbitrary answers back to the agent, which would then
|
||||
// act on them with the agent's full tool permissions. And the markdown is only
|
||||
// nominally agent-authored: in practice the agent is summarising a dependency
|
||||
// README, a scraped page, a PR description, a log. Treat it as hostile.
|
||||
//
|
||||
// Building nodes rather than parsing a string makes injection structurally
|
||||
// impossible instead of filtered, so there is nothing for a sanitiser bypass to
|
||||
// bypass. `html` tokens render as visible text, on purpose.
|
||||
|
||||
import { marked } from "./vendor/marked.esm.js";
|
||||
|
||||
// A bare `/` path stays on this origin; `//host` (and `/\host`, which browsers
|
||||
// read the same way) is protocol-relative and would not, so it is refused.
|
||||
const SAFE_PROTOCOL = /^(https?:|mailto:|#|\/(?![/\\]))/i;
|
||||
|
||||
function safeHref(href) {
|
||||
if (!href) return null;
|
||||
const trimmed = String(href).trim();
|
||||
// Blocks javascript: and data: hrefs before they can reach the DOM.
|
||||
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
|
||||
}
|
||||
|
||||
function el(tag, className, text) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (text != null) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
function inlineInto(parent, tokens) {
|
||||
for (const t of tokens || []) {
|
||||
switch (t.type) {
|
||||
case "text":
|
||||
// Nested inline tokens (a link inside emphasis, say) arrive here.
|
||||
if (t.tokens && t.tokens.length) inlineInto(parent, t.tokens);
|
||||
else parent.appendChild(document.createTextNode(t.text ?? t.raw ?? ""));
|
||||
break;
|
||||
case "escape":
|
||||
parent.appendChild(document.createTextNode(t.text));
|
||||
break;
|
||||
case "strong": {
|
||||
const n = el("strong");
|
||||
inlineInto(n, t.tokens);
|
||||
parent.appendChild(n);
|
||||
break;
|
||||
}
|
||||
case "em": {
|
||||
const n = el("em");
|
||||
inlineInto(n, t.tokens);
|
||||
parent.appendChild(n);
|
||||
break;
|
||||
}
|
||||
case "del": {
|
||||
const n = el("s");
|
||||
inlineInto(n, t.tokens);
|
||||
parent.appendChild(n);
|
||||
break;
|
||||
}
|
||||
case "codespan":
|
||||
parent.appendChild(el("code", "md-code", t.text));
|
||||
break;
|
||||
case "br":
|
||||
parent.appendChild(document.createElement("br"));
|
||||
break;
|
||||
case "link": {
|
||||
const href = safeHref(t.href);
|
||||
if (!href) {
|
||||
inlineInto(parent, t.tokens);
|
||||
break;
|
||||
}
|
||||
const a = el("a");
|
||||
a.href = href;
|
||||
a.rel = "noopener noreferrer";
|
||||
if (/^https?:/i.test(href)) a.target = "_blank";
|
||||
if (t.title) a.title = t.title;
|
||||
inlineInto(a, t.tokens);
|
||||
parent.appendChild(a);
|
||||
break;
|
||||
}
|
||||
case "image": {
|
||||
const src = safeHref(t.href);
|
||||
if (!src) {
|
||||
parent.appendChild(document.createTextNode(t.text || ""));
|
||||
break;
|
||||
}
|
||||
const img = el("img", "md-img");
|
||||
img.src = src;
|
||||
img.alt = t.text || "";
|
||||
parent.appendChild(img);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// Includes `html`: rendered as literal text, never parsed.
|
||||
parent.appendChild(document.createTextNode(t.raw ?? t.text ?? ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function blockInto(parent, tokens) {
|
||||
for (const t of tokens || []) {
|
||||
switch (t.type) {
|
||||
case "space":
|
||||
break;
|
||||
case "heading": {
|
||||
const level = Math.min(6, Math.max(2, (t.depth || 1) + 1)); // never an h1: the page owns that
|
||||
const h = el("h" + level, "md-h");
|
||||
inlineInto(h, t.tokens);
|
||||
parent.appendChild(h);
|
||||
break;
|
||||
}
|
||||
case "paragraph": {
|
||||
const p = el("p", "md-p");
|
||||
inlineInto(p, t.tokens);
|
||||
parent.appendChild(p);
|
||||
break;
|
||||
}
|
||||
case "text": {
|
||||
const p = el("p", "md-p");
|
||||
if (t.tokens) inlineInto(p, t.tokens);
|
||||
else p.textContent = t.text || "";
|
||||
parent.appendChild(p);
|
||||
break;
|
||||
}
|
||||
case "blockquote": {
|
||||
const q = el("blockquote", "md-quote");
|
||||
blockInto(q, t.tokens);
|
||||
parent.appendChild(q);
|
||||
break;
|
||||
}
|
||||
case "code": {
|
||||
const wrap = el("div", "md-pre-wrap");
|
||||
const pre = el("pre", "md-pre");
|
||||
// textContent, so a fenced block containing markup is inert.
|
||||
pre.appendChild(el("code", null, t.text));
|
||||
wrap.appendChild(copyButton(t.text, "md-copy"));
|
||||
wrap.appendChild(pre);
|
||||
parent.appendChild(wrap);
|
||||
break;
|
||||
}
|
||||
case "hr":
|
||||
parent.appendChild(el("hr", "md-hr"));
|
||||
break;
|
||||
case "list": {
|
||||
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" : ""));
|
||||
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);
|
||||
}
|
||||
blockInto(li, item.tokens);
|
||||
list.appendChild(li);
|
||||
}
|
||||
parent.appendChild(list);
|
||||
break;
|
||||
}
|
||||
case "table": {
|
||||
const scroll = el("div", "md-table-wrap");
|
||||
const table = el("table", "md-table");
|
||||
const thead = el("thead");
|
||||
const hr = el("tr");
|
||||
(t.header || []).forEach((cell, i) => {
|
||||
const th = el("th");
|
||||
if (t.align && t.align[i]) th.style.textAlign = t.align[i];
|
||||
inlineInto(th, cell.tokens);
|
||||
hr.appendChild(th);
|
||||
});
|
||||
thead.appendChild(hr);
|
||||
table.appendChild(thead);
|
||||
const tbody = el("tbody");
|
||||
for (const row of t.rows || []) {
|
||||
const tr = el("tr");
|
||||
row.forEach((cell, i) => {
|
||||
const td = el("td");
|
||||
if (t.align && t.align[i]) td.style.textAlign = t.align[i];
|
||||
inlineInto(td, cell.tokens);
|
||||
tr.appendChild(td);
|
||||
});
|
||||
tbody.appendChild(tr);
|
||||
}
|
||||
table.appendChild(tbody);
|
||||
scroll.appendChild(table);
|
||||
parent.appendChild(scroll);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
// Unknown or raw html block: show the source, do not interpret it.
|
||||
const p = el("p", "md-p");
|
||||
p.textContent = t.raw ?? t.text ?? "";
|
||||
parent.appendChild(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Render markdown into a fresh element. Returns the element. */
|
||||
export function md(source, className = "md") {
|
||||
const host = el("div", className);
|
||||
if (!source) return host;
|
||||
let tokens;
|
||||
try {
|
||||
tokens = marked.lexer(String(source));
|
||||
} catch {
|
||||
host.appendChild(el("p", "md-p", String(source)));
|
||||
return host;
|
||||
}
|
||||
blockInto(host, tokens);
|
||||
return host;
|
||||
}
|
||||
|
||||
/** Render markdown into an existing element, replacing its contents. */
|
||||
export function mdInto(node, source) {
|
||||
node.replaceChildren();
|
||||
const rendered = md(source);
|
||||
while (rendered.firstChild) node.appendChild(rendered.firstChild);
|
||||
return node;
|
||||
}
|
||||
|
||||
// The page's only clipboard action, in one place. writeText can be refused --
|
||||
// a browser that has not granted the permission, a page that was not focused
|
||||
// when the click landed -- and a button that silently does nothing is worse
|
||||
// than one that says what to press instead.
|
||||
//
|
||||
// It lives here rather than in app.js because app.js imports this file and not
|
||||
// the other way round, and a fenced code block needed it first.
|
||||
//
|
||||
// copyText() is the action itself: `button` reads "Copied" for a moment, then
|
||||
// `label` again. `label` may be a function, read when the moment is up, for a
|
||||
// button whose text can change in the meantime. `onRefused` is what the caller
|
||||
// offers instead when the browser says no -- usually a selection to press
|
||||
// Ctrl+C on.
|
||||
async function copyText(text, button, label, onRefused) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
button.textContent = "Copied";
|
||||
setTimeout(() => (button.textContent = typeof label === "function" ? label() : label), 1400);
|
||||
} catch {
|
||||
onRefused();
|
||||
}
|
||||
}
|
||||
|
||||
function selectContents(node) {
|
||||
try {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(node);
|
||||
const sel = getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function copyButton(text, className, source) {
|
||||
const b = el("button", className || "btn small", "Copy");
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () =>
|
||||
copyText(text, b, "Copy", () => {
|
||||
// "Press Ctrl+C" on its own asks them to copy a selection that does not
|
||||
// exist. Select the text for them, so the instruction is one they can
|
||||
// actually follow.
|
||||
const node = source || b.parentNode.querySelector("pre, code");
|
||||
if (node) selectContents(node);
|
||||
b.textContent = "Press Ctrl+C";
|
||||
})
|
||||
);
|
||||
return b;
|
||||
}
|
||||
|
||||
export { el, copyButton, copyText, selectContents };
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,254 @@
|
||||
// Plan2Code Web Console - roles, starter templates and Ask starter questions.
|
||||
//
|
||||
// The source of truth for the Role list in User Preferences, the starter
|
||||
// templates on the first "What's the idea?" card of Pathfinder, Plan and Quick
|
||||
// Task, the order each role sees them in, and the starter questions an empty
|
||||
// Ask conversation offers. No DOM access at module scope and no imports: the
|
||||
// page and `node --test` both import this file.
|
||||
|
||||
const role = (id, label) => Object.freeze({ id, label });
|
||||
|
||||
export const ROLES = Object.freeze([
|
||||
role("engineer", "Engineer"),
|
||||
role("pm", "Product lead / PM"),
|
||||
role("architect", "Architect / tech lead"),
|
||||
role("designer", "Designer (UX)"),
|
||||
role("qa", "QA / test engineer"),
|
||||
role("em", "Engineering manager"),
|
||||
]);
|
||||
|
||||
export const ROLE_NOT_SET = "none";
|
||||
export const ROLE_NOT_SET_LABEL = "Not set / none of these";
|
||||
|
||||
export const TEMPLATE_WORKFLOWS = Object.freeze(["pathfinder", "plan", "quick-task"]);
|
||||
|
||||
const ROLE_IDS = new Set(ROLES.map((r) => r.id));
|
||||
|
||||
// A known role id, or "none" for anything else (missing, unknown, not a string).
|
||||
export function normalizeRole(value) {
|
||||
return ROLE_IDS.has(value) ? value : ROLE_NOT_SET;
|
||||
}
|
||||
|
||||
// The dashboard nudge shows until looks.json carries a role of any value:
|
||||
// choosing Not set, or pressing Not now, ends it just as a real role does.
|
||||
export function needsRoleNudge(looks) {
|
||||
if (!looks || typeof looks !== "object") return true;
|
||||
return !Object.hasOwn(looks, "role");
|
||||
}
|
||||
|
||||
// The wording is approved (PLAN-DRAFT Appendix A); a change is a page change.
|
||||
const template = (id, label, lines) => Object.freeze({ id, label, text: lines.join("\n") });
|
||||
|
||||
export const TEMPLATES = Object.freeze({
|
||||
"engineering-spec": template("engineering-spec", "Engineering spec", [
|
||||
"Engineering spec for: [the feature or change, in a sentence]",
|
||||
"Who reads it: the engineers who will build and review it.",
|
||||
"What it should pin down: the behaviour, the parts of the code it touches, the interfaces between them, and how we'll know it works.",
|
||||
"What I already know: [constraints, links, earlier attempts]",
|
||||
]),
|
||||
"product-requirements": template("product-requirements", "Product requirements", [
|
||||
"Product requirements for: [the feature, in a sentence]",
|
||||
"Who it's for: [the users], and the product, design and engineering people deciding on it.",
|
||||
"What it should pin down: the problem, who has it, what success looks like, and what waits for later.",
|
||||
"What I already know: [customer asks, data, deadlines]",
|
||||
]),
|
||||
"design-decision": template("design-decision", "Design decision", [
|
||||
"A design decision to work out: [the choice we're facing, in a sentence]",
|
||||
"Who it's for: the engineers and architects who will live with it.",
|
||||
"What it should pin down: the options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"Constraints: [performance, compatibility, deadlines, team skills]",
|
||||
]),
|
||||
"test-strategy": template("test-strategy", "Test strategy", [
|
||||
"Test strategy for: [the feature or area]",
|
||||
"Who reads it: QA and the engineers writing the tests.",
|
||||
'What it should pin down: what\'s risky, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"What exists today: [current tests, known gaps]",
|
||||
]),
|
||||
"scoping-rollout": template("scoping-rollout", "Scoping & rollout", [
|
||||
"Scoping and rollout for: [the feature or project]",
|
||||
"Who reads it: the engineering manager, the product lead and the team.",
|
||||
"What it should pin down: what's in the first release and what waits, the build order, risks to the timeline, and how it reaches users (flags, stages, who goes first).",
|
||||
"Constraints: [dates, people, dependencies]",
|
||||
]),
|
||||
"brainstorm-notes": template("brainstorm-notes", "Brainstorm → curated notes", [
|
||||
"Brainstorm to turn into curated notes: [the topic or rough idea]",
|
||||
"Who reads the notes: [the team or people this goes to]",
|
||||
"What I want out of it: the ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"Starting thoughts: [anything already on your mind]",
|
||||
]),
|
||||
"bug-investigation": template("bug-investigation", "Bug investigation", [
|
||||
"Bug to investigate: [what's going wrong, in a sentence]",
|
||||
"Steps to reproduce: [1. ... 2. ...]",
|
||||
"Expected: [what should happen]. Actual: [what happens instead]",
|
||||
"Where and since when: [environment, version, first seen]",
|
||||
]),
|
||||
"small-change": template("small-change", "Small change", [
|
||||
"Small change: [what to change, in a sentence]",
|
||||
"Where: [the file, screen or command, if you know it]",
|
||||
"Done when: [how you'll tell it worked]",
|
||||
]),
|
||||
"copy-tweak": template("copy-tweak", "Copy / content tweak", [
|
||||
"Change the wording of: [the screen, message, email or doc]",
|
||||
"Current text: [paste it]",
|
||||
"New text: [paste it, or describe the tone you want]",
|
||||
"Who reads it: [the people who see it]",
|
||||
]),
|
||||
"ui-polish": template("ui-polish", "UI polish", [
|
||||
"UI polish on: [the screen or component]",
|
||||
"What looks or feels off: [spacing, alignment, colour, states, small screens]",
|
||||
"What good looks like: [a reference, screenshot or description]",
|
||||
"Leave alone: [anything that must not move]",
|
||||
]),
|
||||
"visual-prototype": template("visual-prototype", "Visual prototype", [
|
||||
"A throwaway visual prototype of: [the screen or component]",
|
||||
"What to show: [the states or flows to click through]",
|
||||
"What I want to learn: [the question it should answer]",
|
||||
"Where it lives: a prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
]),
|
||||
"add-a-test": template("add-a-test", "Add a test", [
|
||||
"Add a test for: [the function, behaviour or bug]",
|
||||
"Cases to cover: [the normal case, the edge cases, the bug it guards against]",
|
||||
"Where tests live: [the test file or folder, if you know it]",
|
||||
]),
|
||||
"record-decision": template("record-decision", "Record a decision", [
|
||||
"Record a decision we've already made: [the decision, in a sentence]",
|
||||
"Why: [the reasons, and what we turned down]",
|
||||
"What it commits us to: [the consequences]",
|
||||
"Save it as an ADR in: docs/adr/ [or wherever this repo keeps them]",
|
||||
]),
|
||||
});
|
||||
|
||||
const orders = (byRole) => Object.freeze(Object.fromEntries(Object.entries(byRole).map(([r, ids]) => [r, Object.freeze(ids)])));
|
||||
|
||||
// One full order per role per skill. No "none" row: Not set reads Engineer's.
|
||||
export const TEMPLATE_ORDERS = Object.freeze({
|
||||
pathfinder: orders({
|
||||
engineer: ["engineering-spec", "design-decision", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "engineering-spec", "design-decision", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "design-decision", "brainstorm-notes"],
|
||||
}),
|
||||
plan: orders({
|
||||
engineer: ["engineering-spec", "bug-investigation", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "test-strategy", "design-decision", "bug-investigation"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "bug-investigation"],
|
||||
qa: ["test-strategy", "bug-investigation", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "bug-investigation", "design-decision"],
|
||||
}),
|
||||
"quick-task": orders({
|
||||
engineer: ["small-change", "bug-investigation", "add-a-test", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "add-a-test", "record-decision"],
|
||||
architect: ["record-decision", "small-change", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "add-a-test", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "small-change", "ui-polish", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "add-a-test", "bug-investigation", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
}),
|
||||
});
|
||||
|
||||
const roleRow = (role) => {
|
||||
const r = normalizeRole(role);
|
||||
return r === ROLE_NOT_SET ? "engineer" : r;
|
||||
};
|
||||
|
||||
/**
|
||||
* The idea card's template row for a skill: Blank first, then the skill's
|
||||
* templates in the role's order. The first template carries `forYou` only for
|
||||
* a chosen role, never for Not set. `[]` for a skill with no templates.
|
||||
*/
|
||||
export function templatesFor(workflow, role) {
|
||||
if (!TEMPLATE_WORKFLOWS.includes(workflow)) return [];
|
||||
const chosen = normalizeRole(role) !== ROLE_NOT_SET;
|
||||
const ordered = TEMPLATE_ORDERS[workflow][roleRow(role)].map((id, i) => {
|
||||
const { label, text } = TEMPLATES[id];
|
||||
return { id, label, text, forYou: chosen && i === 0 };
|
||||
});
|
||||
return [{ id: "blank", label: "Blank", text: "" }, ...ordered];
|
||||
}
|
||||
|
||||
// Swapping templates: an empty box, or one untouched since the last pick,
|
||||
// swaps silently; anything the person typed asks first.
|
||||
export function templateSwap({ selectedText, boxText, nextText } = {}) {
|
||||
const box = typeof boxText === "string" ? boxText : "";
|
||||
const selected = typeof selectedText === "string" ? selectedText : "";
|
||||
return { text: typeof nextText === "string" ? nextText : "", confirm: box.trim() !== "" && box !== selected };
|
||||
}
|
||||
|
||||
// Ask starter questions (PLAN-DRAFT Appendix B, approved). `lead` names the
|
||||
// roles that see a starter first; `needsContext` starters wait for
|
||||
// + Add context.
|
||||
const starter = (id, text, lead, needsContext = false) =>
|
||||
Object.freeze({ id, text, lead: Object.freeze(lead), needsContext });
|
||||
|
||||
export const STARTER_SETS = Object.freeze({
|
||||
pathfinder: Object.freeze([
|
||||
starter("pathfinder-files", "Which files or parts of the code does this decision touch?", ["engineer", "architect"], true),
|
||||
starter("pathfinder-prior-art", "Has anything like this been done elsewhere in the repo?", ["engineer", "architect"]),
|
||||
starter("pathfinder-decided", "What have we already decided, and what's still open?", ["pm", "em", "architect"]),
|
||||
starter("pathfinder-plain", "What does this question mean, in plain words?", ["pm", "designer", "em"], true),
|
||||
]),
|
||||
plan: Object.freeze([
|
||||
starter("plan-files", "Which existing files would this plan change?", ["engineer", "architect"]),
|
||||
starter("plan-test", "How would we test this?", ["qa", "engineer"], true),
|
||||
starter("plan-risks", "What are the biggest risks or unknowns in this plan?", ["architect", "em", "qa"]),
|
||||
starter("plan-plain", "Explain this section as if I'm not an engineer.", ["pm", "designer", "em"], true),
|
||||
]),
|
||||
document: Object.freeze([
|
||||
starter("document-touch", "Where does this phase touch existing code?", ["engineer"], true),
|
||||
starter("document-guesses", "Which parts of this phase are still guesses?", ["architect", "engineer"], true),
|
||||
starter("document-users", "What will users notice once every phase ships?", ["designer", "pm", "qa"]),
|
||||
starter("document-summary", "Summarize the phases written so far in three bullets.", ["pm", "em"]),
|
||||
]),
|
||||
build: Object.freeze([
|
||||
starter("build-last-task", "What changed in the last task, and why?", ["engineer", "em", "qa"]),
|
||||
starter("build-finding", "Where exactly is this finding in the code?", ["engineer", "qa"], true),
|
||||
starter("build-progress", "How far along are we, and what's next?", ["em", "pm"]),
|
||||
starter("build-check", "What should I check by hand after this phase?", ["qa", "designer"]),
|
||||
]),
|
||||
"quick-task": Object.freeze([
|
||||
starter("quick-task-files", "Which files will this touch?", ["engineer"]),
|
||||
starter("quick-task-pattern", "Is there a similar pattern in the code I should follow?", ["engineer", "architect"]),
|
||||
starter("quick-task-size", "Is this bigger than a quick task?", ["em", "architect"]),
|
||||
starter("quick-task-try", "How do I try this out once it's done?", ["qa", "designer", "pm"]),
|
||||
]),
|
||||
dashboard: Object.freeze([
|
||||
starter("dashboard-project", "What does this project do, in a paragraph?", ["pm", "designer", "em"]),
|
||||
starter("dashboard-which-skill", "Which skill should I use for my idea?", ["pm", "designer", "em"]),
|
||||
starter("dashboard-difference", "What's the difference between Pathfinder, Plan and Quick Task?", []),
|
||||
starter("dashboard-spec", "Where does this spec stand?", ["pm", "em"], true),
|
||||
]),
|
||||
general: Object.freeze([
|
||||
starter("general-step", "What is this step going to do, and what will it change?", []),
|
||||
starter("general-summary", "Summarize this session so far.", ["em", "pm"]),
|
||||
starter("general-left", "What's left to do after this?", ["em", "pm"]),
|
||||
]),
|
||||
});
|
||||
|
||||
// Workflows missing here (init, init-update, revise-plan, finalize, handoff,
|
||||
// anything unknown) use the general set.
|
||||
export const STARTER_SET_FOR = Object.freeze({
|
||||
pathfinder: "pathfinder",
|
||||
plan: "plan",
|
||||
document: "document",
|
||||
implement: "build",
|
||||
"implement-review": "build",
|
||||
review: "build",
|
||||
"quick-task": "quick-task",
|
||||
dashboard: "dashboard",
|
||||
});
|
||||
|
||||
/**
|
||||
* The starters an empty Ask conversation offers: the workflow's set, minus
|
||||
* those that need context until some is attached, with the role's leads
|
||||
* first and written order kept inside each group. Not set leads as Engineer.
|
||||
*/
|
||||
export function startersFor(workflow, role, { hasContext } = {}) {
|
||||
const setId = Object.hasOwn(STARTER_SET_FOR, workflow) ? STARTER_SET_FOR[workflow] : "general";
|
||||
const lead = roleRow(role);
|
||||
const shown = STARTER_SETS[setId].filter((s) => hasContext || !s.needsContext);
|
||||
const first = shown.filter((s) => s.lead.includes(lead));
|
||||
const rest = shown.filter((s) => !s.lead.includes(lead));
|
||||
return [...first, ...rest].map(({ id, text }) => ({ id, text }));
|
||||
}
|
||||
+2580
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,92 @@
|
||||
// Plan2Code Web Console - the Workspace's naming and wording rules.
|
||||
//
|
||||
// The source of truth for what a folder may be called, the name a new folder
|
||||
// gets by default, and the suggestion offered when a name is taken. Imported
|
||||
// by the server (its guards), lib.mjs and the page, so they can never disagree.
|
||||
// No DOM access at module scope and no imports: the page and `node --test`
|
||||
// both import this file.
|
||||
|
||||
export const NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
export const NAME_MAX = 40;
|
||||
|
||||
const trimDashes = (s) => s.replace(/^-+|-+$/g, "");
|
||||
|
||||
/**
|
||||
* The name a folder gets before anyone renames it: its last path segment,
|
||||
* lowercased, with every run of other characters turned into one `-`.
|
||||
*/
|
||||
export function defaultName(folderPath) {
|
||||
const segments = String(folderPath || "")
|
||||
.split(/[\\/]/)
|
||||
.filter(Boolean);
|
||||
const last = segments.length ? segments[segments.length - 1] : "";
|
||||
const name = trimDashes(trimDashes(last.toLowerCase().replace(/[^a-z0-9]+/g, "-")).slice(0, NAME_MAX));
|
||||
return name || "folder";
|
||||
}
|
||||
|
||||
// null when the name can be used, "bad-name" when it cannot.
|
||||
export function nameProblem(name) {
|
||||
if (typeof name !== "string" || !name || name.length > NAME_MAX || !NAME_PATTERN.test(name)) return "bad-name";
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `base` when nobody has it, else the first free `base-2`, `base-3`, ...
|
||||
* `base` is shortened first so the suffixed name still fits NAME_MAX.
|
||||
*/
|
||||
export function freeName(base, taken) {
|
||||
if (!taken.has(base)) return base;
|
||||
for (let n = 2; ; n++) {
|
||||
const suffix = `-${n}`;
|
||||
const candidate = trimDashes(base.slice(0, NAME_MAX - suffix.length)) + suffix;
|
||||
if (!taken.has(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
// How many footer label tiers there are: the page tries 0..FOOTER_TIERS-1,
|
||||
// widest first, until the text fits.
|
||||
export const FOOTER_TIERS = 4;
|
||||
|
||||
/**
|
||||
* The footer's workspace label. `folders[0]` is the original folder.
|
||||
* 0 plan2code + 2 folders · main
|
||||
* 1 plan2code + 2 folders
|
||||
* 2 plan2code +2
|
||||
* 3 plan2code
|
||||
*/
|
||||
export function footerLabel({ folders, branch }, tier = 0) {
|
||||
const list = Array.isArray(folders) ? folders : [];
|
||||
const name = list.length ? list[0].name : "";
|
||||
const n = Math.max(0, list.length - 1);
|
||||
if (tier >= 3) return name;
|
||||
let label = name;
|
||||
if (n > 0) label += tier === 2 ? ` +${n}` : ` + ${n} ${n === 1 ? "folder" : "folders"}`;
|
||||
if (tier === 0 && branch) label += ` · ${branch}`;
|
||||
return label;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reply line an agent is handed for one workspace.json change entry
|
||||
* (`{ kind, name, path, description?, from? }`).
|
||||
*/
|
||||
export function changeLine(change) {
|
||||
const { kind, name, path, description, from } = change || {};
|
||||
switch (kind) {
|
||||
case "added":
|
||||
return `Workspace: added @${name} — ${path}` + (description ? ` (${description})` : "");
|
||||
case "renamed":
|
||||
return `Workspace: renamed @${from} to @${name} — ${path}`;
|
||||
case "described":
|
||||
return description
|
||||
? `Workspace: @${name} is now described as "${description}"`
|
||||
: `Workspace: @${name} description cleared`;
|
||||
case "removed":
|
||||
return `Workspace: removed @${name} — ${path}`;
|
||||
case "missing":
|
||||
return `Workspace: @${name} is missing — ${path} no longer exists`;
|
||||
case "found":
|
||||
return `Workspace: @${name} is back — ${path}`;
|
||||
default:
|
||||
return `Workspace: @${name} changed — ${path}`;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user