A cast skill plans a prompt as a workflow and runs it with subagents
/cast <prompt> has a fresh agent plan the prompt as tasks in steps, and a second agent check the plan. The user reviews and edits it in a local page. Approved, each step's tasks run in parallel subagents, and the scheduler checks every result itself. The idea and the prompts come from the cast app. .gitignore keeps __pycache__ out of the repo. Co-Authored-By: Claude Opus 5.5
@@ -0,0 +1 @@
1+__pycache__/
@@ -10,6 +10,7 @@ How I work, written down for coding agents. Agent skills that follow the [Agent
1010 | [design](skills/design/SKILL.md) | Any UI: developer tools, TUIs, web apps, games, and how to propose a direction |
1111 | [prose](skills/prose/SKILL.md) | Anything a person reads: the voice, the sentence rules, the tells to cut, and the formats for READMEs, commits, tickets, and replies |
1212 | [linux-computer-use](skills/linux-computer-use/SKILL.md) | Driving a real desktop window on KDE Wayland or XFCE X11: keys, clicks, screenshots, kitty, sound |
13+| [cast](skills/cast/SKILL.md) | `/cast <prompt>`: plan the prompt as a workflow, review it in a local page, run it with subagents |
1314
1415 ## Install
1516
@@ -0,0 +1,103 @@
1+---
2+name: cast
3+description: Turn a prompt into a workflow of tasks, let the user review and edit it in a local web page, then run it with subagents, step by step, with parallel tasks in a step. Use when the user types `/cast <prompt>`, or asks to plan work as a workflow, review the plan, and run it with agents.
4+---
5+
6+# Cast a prompt into a workflow
7+
8+`/cast <prompt>` plans the prompt as tasks in steps, checks the plan with a second agent, shows it in a review page, and runs the approved version with one subagent per task. The idea and the prompts come from the cast app in `~/s/repos/cast`.
9+
10+You are the planner's client and the run's scheduler. Subagents plan, check, and do the tasks. You never do a task's work yourself, and you check every result yourself.
11+
12+## The workflow
13+
14+A workflow is a list of tasks. Each task has an `id`, a `step`, a `title`, the `decisions` it made, its `acceptance` criteria, and the `evidence` files it will write. Steps run in order. Tasks that share a step run at the same time.
15+
16+The state lives outside the project, so cast never adds files to it:
17+
18+```
19+${XDG_STATE_HOME:-~/.local/state}/cast/<project folder name>/<slug>/
20+ prompt.md the user's prompt
21+ v1.json, v2.json one file per version: {"tasks": [...], "notes": [...]}
22+ decision.json the user's last click, until you read it
23+ run-v2/run.json the run of v2
24+ run-v2/T1/ the evidence T1 wrote
25+```
26+
27+The slug is the first line of the prompt in kebab case, at most 40 characters. Call this folder `$dir`.
28+
29+## 1. Plan
30+
31+1. Write the prompt to `$dir/prompt.md`. If the prompt names files, read them, so the planner gets the same context the user meant.
32+2. Send the plan prompt from [references/prompts.md](references/prompts.md) to a fresh subagent. Tell it to change no files.
33+3. Send its JSON and the prompt to a second fresh subagent with the check prompt. A planner does not catch its own mistakes.
34+4. Write the checked workflow to `$dir/v<N>.json`, with the checker's notes. If the check fails or returns bad JSON, keep the draft and put the reason in `notes`.
35+5. Normalize the steps before you write: sort by step, and number them 1, 2, 3 with no gaps.
36+
37+## 2. Review
38+
39+1. Start the server in the background, once per session, and read the URL it prints:
40+
41+ ```sh
42+ python3 -B <this skill>/scripts/serve.py "$dir"
43+ ```
44+
45+2. Give the user the URL. Open it with `xdg-open` only if they ask. The page shows the prompt, the steps as columns, and the selected task in a side panel. The user edits tasks in place, moves a task to an earlier or later step, runs it alone, adds or deletes tasks, and writes feedback. Every edit saves to the current version.
46+3. Wait for a click in the background. The command exits when the user decides, and its output is the decision:
47+
48+ ```sh
49+ until [ -f "$dir/decision.json" ]; do sleep 1; done; cat "$dir/decision.json"
50+ ```
51+
52+4. Read `$dir/v<N>.json` again, because the user may have changed it. Then delete `decision.json` and act on the `action`:
53+
54+| Action | What you do |
55+| --- | --- |
56+| `refine` | Plan again with the refine prompt, the current version, and the `feedback`. Check it and write `v<N+1>.json`. Wait again. |
57+| `discard` | Delete `v<N>.json`. If an older version is left, wait again. Otherwise stop the server and ask the user to edit the prompt. |
58+| `approve` | Run the version in the given `mode`. |
59+
60+## 3. Run
61+
62+Three scripts keep the run state, so you never edit `run.json` by hand. `PROJECT` is the project folder.
63+
64+```sh
65+python3 -B <this skill>/scripts/run.py "$dir" start MODE # create run.json, or resume it
66+python3 -B <this skill>/scripts/run.py "$dir" next # the task ids to start now
67+python3 -B <this skill>/scripts/task_prompt.py "$dir" ID PROJECT # the prompt for one task
68+python3 -B <this skill>/scripts/run.py "$dir" mark ID running
69+echo "SUMMARY" | python3 -B <this skill>/scripts/run.py "$dir" mark ID done
70+```
71+
72+The page polls `run.json` every second and shows the progress. `start` on an existing run resumes it, and marks a task that was still `running` as failed, because it was cut off.
73+
74+Repeat until every task is done:
75+
76+1. Run `next`. It prints the queued tasks of the current step, or one of them in `task` mode. It prints nothing while a task is running, failed, or cancelled.
77+2. Mark each one `running`. Write each task prompt to `$dir/run-v<N>/<ID>.prompt`, and send all of them in one message, so they run in parallel. Tell each subagent to read its file and follow it, so you don't copy the prompt into the message.
78+3. When a subagent returns, read its summary and its evidence. Run the acceptance checks yourself. A subagent's claim is not proof. Mark the task `done` or `failed`, with your own one-line summary on stdin.
79+4. Look for `decision.json`. Act on it, and delete it.
80+5. When the batch is done, run `next` again in `all` mode. In `step` or `task` mode, or after a failure, start nothing new and wait for a decision as in step 2 of the review.
81+
82+While tasks run, keep the decision wait from the review going in the background, so a Pause or Cancel click reaches you at once.
83+
84+| Action | What you do |
85+| --- | --- |
86+| `pause` | Let the running tasks finish, start nothing new, and wait. |
87+| `continue` | Run `run.py "$dir" continue MODE`. It queues the failed and cancelled tasks again. Then go on. |
88+| `cancel` | Stop the running subagents, mark them `cancelled`, and wait. |
89+
90+A failed task stops the run. Tell the user which criterion failed and why, in one or two sentences, and wait.
91+
92+## 4. Finish
93+
94+1. When every task is done, run the project's own checks, and walk the change in the real product with the **verification** skill. The run is not verified until you have done this.
95+2. Stop the server by the PID you started. Never `pkill`.
96+3. Report each task in one line, with its status and its evidence, then what you checked and what you didn't.
97+
98+## Keep it honest
99+
100+- Planner and checker subagents read the project but change nothing.
101+- Never edit a version that has a run. Refine it into a new version instead. The server refuses those edits.
102+- Never commit unless a task says to, and only from a task that runs alone in its step.
103+- Give the user the URL, the version, and the step that is running whenever they ask where things are.
@@ -0,0 +1,89 @@
1+# Cast prompts
2+
3+Fill the `{placeholders}` and send each prompt to a fresh subagent. These come from cast's `src/agent/prompts.rs`. `scripts/task_prompt.py` builds the task prompts.
4+
5+## Rules
6+
7+The plan and check prompts get this block where they say `{rules}`:
8+
9+```
10+How the workflow runs:
11+- Steps run in ascending order. Tasks with the same step run at the same time, each with its own agent, in the same project folder.
12+- Each agent sees only the original prompt and its own task, so every task must carry the decisions and context it needs.
13+- Each task lists the decisions it made, its acceptance criteria, and the evidence to attach.
14+- Evidence is the bare file names the task will write as proof, such as test output, logs, or screenshots. Give no folder.
15+
16+Rules for tasks that run at the same time:
17+- Read the code to find the files each task will create or change. Tasks in one step never change the same files, including lockfiles, manifests, generated code, snapshots, docs, and changelogs.
18+- If two tasks need the same files, put them in different steps, or give each its own git worktree and branch and add a later task that merges them.
19+- They never commit, stash, reset, rebase, check out, or clean, and never revert changes they did not make.
20+- They never run commands that rewrite files they do not own, such as project-wide formatters or code generators.
21+
22+Rules for git:
23+- If the project is not a git repository, no task uses git.
24+- Only a task that runs alone in its step commits. Parallel work is followed by a consolidation task that reviews the combined diff, merges any worktree branches, runs the full checks, and commits.
25+- Follow the project's own CLAUDE.md, AGENTS.md, or CONTRIBUTING.md on commits and checks.
26+- A task that adds a worktree removes it once its branch is merged.
27+```
28+
29+## Schema
30+
31+```json
32+{"tasks":[{"id":"T1","step":1,"title":"short imperative title","decisions":["a decision and why"],"acceptance":["a checkable criterion"],"evidence":["test-output.txt"]}]}
33+```
34+
35+## Plan
36+
37+```
38+You plan software work. The project is {project}. Read it as needed, but change no files.
39+Turn the user's prompt below into a workflow of tasks.
40+
41+{rules}
42+
43+Answer with only JSON in this shape, no prose and no code fence:
44+{schema}
45+
46+<prompt>
47+{prompt}
48+</prompt>
49+```
50+
51+To refine, append:
52+
53+```
54+This is the current workflow:
55+{workflow}
56+
57+Revise it with this feedback:
58+{feedback}
59+```
60+
61+## Check
62+
63+Send the plan to a different, fresh subagent. A planner does not catch its own mistakes.
64+
65+```
66+You review a workflow that another agent planned from the user's prompt. The project is {project}. Read it as needed, but change no files.
67+Make sure the workflow is correct and ready to run, and fix it where it is not.
68+
69+{rules}
70+
71+Check each of these against the prompt and the code:
72+- It does everything the prompt asks and nothing it does not.
73+- Tasks in the same step change separate files. Open the files to confirm it.
74+- Each task depends only on tasks in earlier steps.
75+- Commits come only from tasks that run alone, and parallel work is consolidated before anything builds on it.
76+- Every acceptance criterion can be checked by running something or reading the evidence.
77+- Every task has the decisions and context its agent needs without seeing the other tasks.
78+
79+Answer with only JSON, no prose and no code fence: the corrected workflow in the schema below, plus "notes", a list with one short sentence for each change you made and why. Leave "notes" empty if the workflow was already right.
80+{schema}
81+
82+<prompt>
83+{prompt}
84+</prompt>
85+
86+<workflow>
87+{workflow}
88+</workflow>
89+```
@@ -0,0 +1,202 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+<meta charset="utf-8">
5+<title>cast</title>
6+<style>
7+:root{--bg:#0a0b0d;--surface:#0e1013;--raised:#16191e;--line:#22262d;--fg:#cfd3da;--strong:#f2f3f5;--muted:#7b8290;--faint:#5d6470;--accent:#ff8a3d;--accent-fg:#0a0b0d;--soft:#1d1710;--ok:#3ddc97;--danger:#ff5d5d}
8+*{box-sizing:border-box;margin:0}
9+body{background:var(--bg);color:var(--fg);font:14px/20px ui-monospace,"JetBrains Mono",monospace;height:100vh;display:grid;grid-template-rows:auto 1fr auto}
10+header,footer{background:var(--surface);padding:12px 20px;display:flex;gap:16px;align-items:center}
11+header h1{font-size:16px;font-weight:500;color:var(--strong)}
12+.muted{color:var(--muted)}.faint{color:var(--faint)}
13+main{display:grid;grid-template-columns:1fr 440px;min-height:0}
14+#flow{overflow:auto;padding:20px}
15+#steps{display:flex;gap:24px;align-items:flex-start}
16+.step{display:flex;flex-direction:column;gap:8px;width:220px}
17+.step h2{font-size:14px;font-weight:400;color:var(--muted)}
18+.task{all:unset;cursor:pointer;background:var(--raised);padding:10px 12px;border-radius:4px;display:flex;flex-direction:column;gap:2px;outline:1px solid transparent}
19+.task:focus-visible,.task.on{outline-color:var(--accent)}
20+.task .id{color:var(--faint)}
21+.st-running .id,.st-running .glyph{color:var(--accent)}
22+.st-done .glyph{color:var(--ok)}
23+.st-failed .glyph{color:var(--danger)}
24+details{margin-bottom:20px}
25+summary{cursor:pointer;color:var(--muted)}
26+pre{white-space:pre-wrap;max-width:90ch;margin-top:8px;color:var(--fg)}
27+.notes{margin-bottom:20px;color:var(--muted);max-width:90ch;padding-left:18px}
28+.read{color:var(--fg)}
29+ul.read{padding-left:18px}
30+aside{background:var(--surface);overflow:auto;padding:20px;display:flex;flex-direction:column;gap:12px}
31+label{display:flex;flex-direction:column;gap:4px;color:var(--muted)}
32+input,textarea,select{font:inherit;color:var(--fg);background:var(--raised);border:0;border-radius:4px;padding:8px}
33+textarea{resize:vertical;min-height:72px}
34+input:focus-visible,textarea:focus-visible,select:focus-visible,button:focus-visible{outline:1px solid var(--accent)}
35+.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
36+button{font:inherit;color:var(--fg);background:var(--raised);border:0;border-radius:4px;padding:6px 12px;cursor:pointer}
37+button.primary{background:var(--accent);color:var(--accent-fg)}
38+button.danger{color:var(--danger)}
39+button:disabled{opacity:.4;cursor:default}
40+footer textarea{flex:1;min-height:40px}
41+#status{color:var(--muted)}
42+#status.live{color:var(--accent)}
43+#status.failed{color:var(--danger)}
44+a{color:var(--fg)}
45+img{max-width:100%;border-radius:4px}
46+</style>
47+</head>
48+<body>
49+<header><h1 id="name"></h1><span class="muted" id="version"></span><span id="status"></span></header>
50+<main>
51+ <section id="flow">
52+ <details><summary>Prompt</summary><pre id="prompt"></pre></details>
53+ <ul class="notes" id="notes"></ul>
54+ <div id="steps"></div>
55+ </section>
56+ <aside id="panel"></aside>
57+</main>
58+<footer id="actions"></footer>
59+<script>
60+const $ = id => document.getElementById(id)
61+const h = (tag, props = {}, ...kids) => { const el = Object.assign(document.createElement(tag), props); el.append(...kids); return el }
62+const glyphs = {queued: "○", running: "◐", done: "✓", failed: "✕", cancelled: "■"}
63+let s = null, wf = null, sel = 0, saving = null
64+
65+const tasks = () => wf.tasks
66+const run = () => s.run
67+const status = t => run()?.tasks?.[t.id]?.status || "queued"
68+const editable = () => !run() && !s.decision
69+const lines = v => v.split("\n").map(x => x.trim()).filter(Boolean)
70+
71+function normalize() {
72+ tasks().sort((a, b) => a.step - b.step)
73+ let prev = null, n = 0
74+ for (const t of tasks()) { if (t.step !== prev) { prev = t.step; n++ } t.step = n }
75+}
76+
77+function save() {
78+ normalize()
79+ clearTimeout(saving)
80+ saving = setTimeout(() => fetch("/workflow", {method: "PUT", body: JSON.stringify(wf)}), 300)
81+}
82+
83+function move(d) {
84+ const t = tasks()[sel]
85+ if (d === 0) {
86+ if (tasks().filter(x => x.step === t.step).length < 2) return
87+ for (const x of tasks()) if (x.step > t.step) x.step++
88+ t.step++
89+ } else t.step = Math.max(0, t.step + d)
90+ save()
91+ sel = tasks().indexOf(t)
92+ draw()
93+}
94+
95+function add() {
96+ const n = Math.max(0, ...tasks().map(t => parseInt(t.id.slice(1)) || 0)) + 1
97+ tasks().push({id: `T${n}`, step: (tasks().at(-1)?.step || 0) + 1, title: "New task", decisions: [], acceptance: [], evidence: []})
98+ sel = tasks().length - 1
99+ save()
100+ draw()
101+}
102+
103+function remove() {
104+ if (tasks().length < 2) return
105+ tasks().splice(sel, 1)
106+ sel = Math.max(0, sel - 1)
107+ save()
108+ draw()
109+}
110+
111+async function decide(action) {
112+ const feedback = $("feedback")?.value.trim() || ""
113+ if (action === "refine" && !feedback) return $("feedback").focus()
114+ const mode = $("mode")?.value || "all"
115+ await fetch("/decide", {method: "POST", body: JSON.stringify({action, mode, feedback})})
116+ refresh()
117+}
118+
119+function drawSteps() {
120+ const steps = [...new Set(tasks().map(t => t.step))]
121+ $("steps").replaceChildren(...steps.map(n => h("div", {className: "step"},
122+ h("h2", {textContent: `Step ${n}${tasks().filter(t => t.step === n).length > 1 ? ", parallel" : ""}`}),
123+ ...tasks().map((t, i) => [t, i]).filter(([t]) => t.step === n).map(([t, i]) =>
124+ h("button", {className: `task st-${status(t)}${i === sel ? " on" : ""}`, onclick: () => { sel = i; draw() }},
125+ h("span", {className: "id"}, h("span", {className: "glyph", textContent: glyphs[status(t)] + " "}), t.id),
126+ h("span", {textContent: t.title}))))),
127+ ...(editable() ? [h("button", {textContent: "+ Task", onclick: add})] : []))
128+}
129+
130+function field(t, key, label) {
131+ const list = Array.isArray(t[key])
132+ if (!editable()) return h("label", {}, label, list ? h("ul", {className: "read"}, ...t[key].map(x => h("li", {textContent: x}))) : h("span", {className: "read", textContent: t[key]}))
133+ const el = h(list ? "textarea" : "input", {value: list ? t[key].join("\n") : t[key]})
134+ el.oninput = () => { t[key] = list ? lines(el.value) : el.value; save(); if (!list) drawSteps() }
135+ return h("label", {}, list ? `${label}, one per line` : label, el)
136+}
137+
138+function drawPanel() {
139+ const t = tasks()[sel]
140+ if (!t) return $("panel").replaceChildren()
141+ const r = run()?.tasks?.[t.id]
142+ const kids = [h("div", {className: "muted", textContent: `${t.id}, step ${t.step}, ${status(t)}`}),
143+ field(t, "title", "Title"), field(t, "decisions", "Decisions"), field(t, "acceptance", "Acceptance criteria"), field(t, "evidence", "Evidence files")]
144+ if (editable()) kids.push(h("div", {className: "row"},
145+ h("button", {textContent: "Earlier", onclick: () => move(-1)}),
146+ h("button", {textContent: "Later", onclick: () => move(1)}),
147+ h("button", {textContent: "Run alone", onclick: () => move(0)}),
148+ h("button", {className: "danger", textContent: "Delete", onclick: remove, disabled: tasks().length < 2})))
149+ if (r?.summary) kids.push(h("label", {}, "Summary", h("pre", {textContent: r.summary})))
150+ for (const f of r?.evidence || []) {
151+ const url = `/files/run-v${s.version}/${t.id}/${f}`
152+ kids.push(/\.png$/.test(f) ? h("a", {href: url, target: "_blank"}, h("img", {src: url, alt: f})) : h("a", {href: url, target: "_blank", textContent: f}))
153+ }
154+ $("panel").replaceChildren(...kids)
155+}
156+
157+function drawActions() {
158+ const all = tasks().map(status)
159+ const phase = all.every(x => x === "done") ? "done" : all.includes("running") ? "running" : all.includes("failed") ? "failed" : "paused"
160+ $("status").textContent = s.decision ? `Sent "${s.decision.action}", waiting for the agent` : run() ? phase : ""
161+ $("status").className = s.decision || phase === "running" ? "live" : phase === "failed" ? "failed" : ""
162+ if (s.decision || (run() && phase === "done")) return $("actions").replaceChildren()
163+ const mode = h("select", {id: "mode"}, ...[["all", "Run all"], ["step", "One step"], ["task", "One task"]].map(([value, textContent]) => h("option", {value, textContent, selected: value === run()?.mode})))
164+ $("actions").replaceChildren(...(run()
165+ ? [mode, h("button", {className: "primary", textContent: "Continue", onclick: () => decide("continue"), disabled: phase === "running"}),
166+ h("button", {textContent: "Pause", onclick: () => decide("pause"), disabled: phase !== "running"}),
167+ h("button", {className: "danger", textContent: "Cancel", onclick: () => decide("cancel")})]
168+ : [h("textarea", {id: "feedback", placeholder: "Feedback for the planner"}),
169+ h("button", {textContent: "Refine", onclick: () => decide("refine")}),
170+ h("button", {className: "danger", textContent: "Discard", onclick: () => decide("discard")}),
171+ mode, h("button", {className: "primary", textContent: "Approve", onclick: () => decide("approve")})]))
172+}
173+
174+function draw() {
175+ $("name").textContent = s.name
176+ $("version").textContent = `v${s.version}`
177+ $("prompt").textContent = s.prompt
178+ $("notes").replaceChildren(...(wf.notes || []).map(n => h("li", {textContent: n})))
179+ drawSteps()
180+ drawPanel()
181+}
182+
183+async function refresh() {
184+ const next = await (await fetch("/state")).json()
185+ const changed = !s || next.version !== s.version || JSON.stringify(next.run) !== JSON.stringify(s.run) || JSON.stringify(next.decision) !== JSON.stringify(s.decision)
186+ if (!changed) return
187+ s = next
188+ wf = s.workflow || {tasks: []}
189+ sel = Math.min(sel, tasks().length - 1)
190+ draw()
191+ drawActions()
192+}
193+
194+addEventListener("keydown", e => {
195+ if (e.key === "Escape") document.activeElement?.blur()
196+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey) && editable()) decide("approve")
197+})
198+refresh()
199+setInterval(refresh, 1000)
200+</script>
201+</body>
202+</html>
@@ -0,0 +1,55 @@
1+import pathlib
2+import sys
3+
4+from state import now, read, run_dir, workflow, write
5+
6+usage = """usage:
7+ run.py DIR start MODE create run.json, or resume it and fail the tasks that were cut off
8+ run.py DIR next print the task ids to start now, one per line
9+ run.py DIR mark ID STATUS set a status, read the summary from stdin when it ends the task
10+ run.py DIR continue MODE queue failed and cancelled tasks again and set the mode
11+MODE is all, step, or task. STATUS is running, done, failed, or cancelled."""
12+
13+root = pathlib.Path(sys.argv[1]).resolve() if len(sys.argv) > 2 else sys.exit(usage)
14+cmd, args = sys.argv[2], sys.argv[3:]
15+path = run_dir(root) / "run.json"
16+wf = workflow(root)
17+run = read(path)
18+steps = {t["id"]: t["step"] for t in wf["tasks"]}
19+
20+
21+def blank():
22+ return {"status": "queued", "started": None, "ended": None, "summary": "", "evidence": []}
23+
24+
25+if cmd == "start":
26+ run = run or {"tasks": {i: blank() for i in steps}}
27+ run["mode"] = args[0]
28+ for t in run["tasks"].values():
29+ if t["status"] == "running":
30+ t.update(status="failed", ended=now(), summary="interrupted: the run stopped while this task ran")
31+elif cmd == "next":
32+ tasks = run["tasks"]
33+ if any(t["status"] in ("running", "failed", "cancelled") for t in tasks.values()):
34+ sys.exit(0)
35+ left = [i for i in steps if tasks[i]["status"] != "done"]
36+ current = min((steps[i] for i in left), default=None)
37+ ready = [i for i in left if steps[i] == current]
38+ print("\n".join(ready[:1] if run["mode"] == "task" else ready))
39+ sys.exit(0)
40+elif cmd == "mark":
41+ task, status = run["tasks"][args[0]], args[1]
42+ task["status"] = status
43+ if status == "running":
44+ task.update(started=now(), ended=None, summary="", evidence=[])
45+ else:
46+ folder = run_dir(root) / args[0]
47+ task.update(ended=now(), summary=sys.stdin.read().strip(), evidence=sorted(f.name for f in folder.iterdir()) if folder.is_dir() else [])
48+elif cmd == "continue":
49+ run["mode"] = args[0]
50+ for t in run["tasks"].values():
51+ if t["status"] in ("failed", "cancelled"):
52+ t.update(blank())
53+else:
54+ sys.exit(usage)
55+write(path, run)
@@ -0,0 +1,68 @@
1+import http.server
2+import json
3+import pathlib
4+import sys
5+
6+from state import latest, read, versions
7+
8+root = pathlib.Path(sys.argv[1]).resolve()
9+page = pathlib.Path(__file__).with_name("review.html")
10+
11+
12+def state():
13+ v = latest(root)
14+ prompt = root / "prompt.md"
15+ return {
16+ "name": root.name,
17+ "prompt": prompt.read_text() if prompt.is_file() else "",
18+ "version": v,
19+ "versions": versions(root),
20+ "workflow": read(root / f"v{v}.json"),
21+ "run": read(root / f"run-v{v}" / "run.json"),
22+ "decision": read(root / "decision.json"),
23+ }
24+
25+
26+class Handler(http.server.BaseHTTPRequestHandler):
27+ def send(self, code, body, kind="application/json"):
28+ data = body if isinstance(body, bytes) else json.dumps(body).encode()
29+ self.send_response(code)
30+ self.send_header("Content-Type", kind)
31+ self.send_header("Cache-Control", "no-store")
32+ self.end_headers()
33+ self.wfile.write(data)
34+
35+ def body(self):
36+ return json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"null")
37+
38+ def do_GET(self):
39+ if self.path == "/":
40+ return self.send(200, page.read_bytes(), "text/html; charset=utf-8")
41+ if self.path == "/state":
42+ return self.send(200, state())
43+ file = (root / self.path.removeprefix("/files/")).resolve()
44+ if self.path.startswith("/files/") and file.is_relative_to(root) and file.is_file():
45+ kind = "image/png" if file.suffix == ".png" else "text/plain; charset=utf-8"
46+ return self.send(200, file.read_bytes(), kind)
47+ self.send(404, {"error": "not found"})
48+
49+ def do_PUT(self):
50+ s = state()
51+ if self.path != "/workflow" or s["run"]:
52+ return self.send(409, {"error": "this version already ran, refine it into a new version"})
53+ (root / f"v{s['version']}.json").write_text(json.dumps(self.body(), indent=2))
54+ self.send(200, {"ok": True})
55+
56+ def do_POST(self):
57+ if self.path != "/decide":
58+ return self.send(404, {"error": "not found"})
59+ (root / "decision.json").write_text(json.dumps(self.body()))
60+ self.send(200, {"ok": True})
61+
62+ def log_message(self, *args):
63+ pass
64+
65+
66+server = http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[2]) if len(sys.argv) > 2 else 0), Handler)
67+print(f"http://127.0.0.1:{server.server_address[1]}", flush=True)
68+server.serve_forever()
@@ -0,0 +1,34 @@
1+import datetime
2+import json
3+import pathlib
4+import re
5+
6+
7+def versions(root):
8+ return sorted(int(m[1]) for p in root.glob("v*.json") if (m := re.fullmatch(r"v(\d+)\.json", p.name)))
9+
10+
11+def read(path):
12+ return json.loads(path.read_text()) if path.is_file() else None
13+
14+
15+def write(path, data):
16+ path.parent.mkdir(parents=True, exist_ok=True)
17+ path.write_text(json.dumps(data, indent=2))
18+
19+
20+def latest(root):
21+ vs = versions(root)
22+ return vs[-1] if vs else 0
23+
24+
25+def workflow(root):
26+ return read(root / f"v{latest(root)}.json")
27+
28+
29+def run_dir(root):
30+ return root / f"run-v{latest(root)}"
31+
32+
33+def now():
34+ return datetime.datetime.now().isoformat(timespec="seconds")
@@ -0,0 +1,37 @@
1+import pathlib
2+import sys
3+
4+from state import run_dir, workflow
5+
6+if len(sys.argv) != 4:
7+ sys.exit("usage: task_prompt.py DIR ID PROJECT")
8+root, tid, project = pathlib.Path(sys.argv[1]).resolve(), sys.argv[2], sys.argv[3]
9+wf = workflow(root)
10+task = next(t for t in wf["tasks"] if t["id"] == tid)
11+others = [t for t in wf["tasks"] if t["step"] == task["step"] and t["id"] != tid]
12+
13+
14+def bullets(xs):
15+ return "".join(f"- {x}\n" for x in xs)
16+
17+
18+parallel = f"""
19+These tasks run at the same time as yours, each with its own agent, in the same folder:
20+{bullets(f"{t['id']}: {t['title']}" for t in others)}Change only the files your task needs. Do not commit, stash, reset, rebase, check out, or clean. Do not revert changes you did not make, and do not run project-wide formatters or generators. If your task says to use a git worktree, work only inside it.
21+You share the desktop with the other agents. Find your windows by the PID you started, never close or type into a window you did not open, and give agent-browser a --session of your own.
22+""" if others else ""
23+
24+print(f"""You run task {tid} of a workflow in {project}, the user's project.
25+Original prompt:
26+<prompt>
27+{(root / "prompt.md").read_text().strip()}
28+</prompt>
29+
30+Task {tid}: {task["title"]}
31+Decisions already made:
32+{bullets(task["decisions"])}Acceptance criteria:
33+{bullets(task["acceptance"])}Evidence to attach:
34+{bullets(task["evidence"])}{parallel}
35+Do the work. Save every piece of evidence into {run_dir(root) / tid}/ and create it first.
36+Finish with a short summary of what changed and how you met each acceptance criterion.
37+Step {task["step"]} of {len({t["step"] for t in wf["tasks"]})}.""")