mirror of
https://github.com/wassname/pi-goals.git
synced 2026-09-11 12:43:57 +08:00
Compare commits
97
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9baa20139 | ||
|
|
4103085fb9 | ||
|
|
f89bce5958 | ||
|
|
a4eb05560f | ||
|
|
e5dc0567a8 | ||
|
|
85c66d365b | ||
|
|
d6e658feee | ||
|
|
21f1092d4d | ||
|
|
a592324e5a | ||
|
|
c834237970 | ||
|
|
20b145b20c | ||
|
|
060cc1e094 | ||
|
|
08c05aa79d | ||
|
|
03517ad272 | ||
|
|
6c44df978b | ||
|
|
412c796b37 | ||
|
|
b649653d0f | ||
|
|
cd98fa186e | ||
|
|
98769b01e2 | ||
|
|
28374c0bb2 | ||
|
|
9cce6a6bee | ||
|
|
e3ccdbdb2f | ||
|
|
f22d83cd50 | ||
|
|
c175096ddb | ||
|
|
cabb4446aa | ||
|
|
1c927bf137 | ||
|
|
5cda3d6b1d | ||
|
|
ac6ef19e91 | ||
|
|
cb35fbf1fe | ||
|
|
fb5503f083 | ||
|
|
15dd7f0222 | ||
|
|
138bde57f4 | ||
|
|
1d5285721c | ||
|
|
34335752f7 | ||
|
|
565b272c71 | ||
|
|
a7385d4b76 | ||
|
|
e19028e330 | ||
|
|
039f4a4048 | ||
|
|
8953dceb46 | ||
|
|
5567c9d5c2 | ||
|
|
2b61440c73 | ||
|
|
cb4790a96c | ||
|
|
88bfcc1c42 | ||
|
|
1668c941aa | ||
|
|
325b93983f | ||
|
|
2824396a71 | ||
|
|
ddd552b1a5 | ||
|
|
47cc054582 | ||
|
|
489298d58b | ||
|
|
b13f001110 | ||
|
|
386305afd3 | ||
|
|
94102524b6 | ||
|
|
a4ed6cfbaa | ||
|
|
06794bfd44 | ||
|
|
4ebb4d127b | ||
|
|
6b641c7d17 | ||
|
|
1717dd6821 | ||
|
|
19fa8d7a7b | ||
|
|
6c86405841 | ||
|
|
ee1ab3ec26 | ||
|
|
ba2799a1d9 | ||
|
|
c6a4307892 | ||
|
|
2b620a0334 | ||
|
|
fc321a90fc | ||
|
|
9ee18c93f3 | ||
|
|
23b0104a1d | ||
|
|
65ecf204db | ||
|
|
294fe80564 | ||
|
|
1dc6146874 | ||
|
|
7eb8b1f46b | ||
|
|
c5782ee2aa | ||
|
|
e299e84c5e | ||
|
|
d56fc55242 | ||
|
|
4c6a7716b1 | ||
|
|
cac2077456 | ||
|
|
5566e035f5 | ||
|
|
48e2247c00 | ||
|
|
844099bdf0 | ||
|
|
754ef89f13 | ||
|
|
6cfeaf44ee | ||
|
|
3eaaec9f5a | ||
|
|
0a33ff2852 | ||
|
|
a44cd26c1d | ||
|
|
96399ec3e4 | ||
|
|
96290c553b | ||
|
|
2852432d44 | ||
|
|
9fbc156860 | ||
|
|
f87b8aac2f | ||
|
|
b32f4af11f | ||
|
|
db18317109 | ||
|
|
4db690a300 | ||
|
|
49eb68e813 | ||
|
|
18381bcda9 | ||
|
|
ead336c957 | ||
|
|
9ad4cee084 | ||
|
|
bf50d9bbc8 | ||
|
|
46cfd537f0 |
+3
-3
@@ -1,6 +1,6 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.log
|
||||
.local/
|
||||
.pi/
|
||||
docs/reviews/raw.jsonl
|
||||
docs/reviews/err.txt
|
||||
slop/
|
||||
*.log
|
||||
|
||||
@@ -1,16 +1,35 @@
|
||||
# pi-goals contributor notes
|
||||
|
||||
## Design
|
||||
|
||||
The main chat discusses the plan with the user, then supervises an interactive `goals-worker` in Herdr. Use stock pi-subagents, pi-intercom and pi-schedule-prompt; do not build another transport, scheduler or worker runtime.
|
||||
|
||||
> the hope is we can have a smart supervisor like you, with judgment and context. But it doesn't use many tokens as it checks in and sees an overview.
|
||||
>
|
||||
> It steers a smaller model, adding perspective and judgment.
|
||||
>
|
||||
> Well, I want to see what the supervisor is thinking and saying. That's the whole point: all supervisor thinking and messages should be visible.
|
||||
|
||||
— wassname
|
||||
|
||||
- Keep supervisor inspection tools. It inspects actual results, delegates implementation and must not weaken the user's goal to accept worker output.
|
||||
- Put all model-facing prompts in `src/prompts.ts`, in conversation order. Preserve the user's verbatim requirements.
|
||||
- `/goals` opens actions. New plan starts a discussion without an objective form. Unknown commands never start planning. A changed settled draft opens the approval dialogue; unchanged discussion does not repeatedly reopen it.
|
||||
- Keep goal titles/status in widgets; omit subtask text. Tasks and evidence remain in the plan.
|
||||
- Keep startup/compaction plan context, short upkeep reminders and visible editable hourly check-ins. Avoid unchanged-plan repetition and identity-only review turns.
|
||||
- Keep recoverable solo mode: confirm other writers stopped before taking over. Solo completion is self-verification.
|
||||
- Record distinct runtime ID, Intercom ID and saved-session path with provenance. A handle or delivery receipt is not proof of liveness or action. User model changes are authorized; do not silently restore an old preference.
|
||||
|
||||
## Tests
|
||||
|
||||
Run `npm test` before a commit. It includes unit and flow tests plus the RPC review test.
|
||||
Run `npm test`, `npm run typecheck` and `npm run lint` before committing.
|
||||
|
||||
- `test/*.test.ts` unit and flow tests use a small Pi API mock. They check plan state, tool gates, and plan-file updates.
|
||||
- `npm run test:rpc` runs `test/rpc-review.test.ts`. It starts the installed Pi executable in RPC mode, uses Pi's real `select` and `editor` protocol, and uses a local deterministic HTTP model. It does not need a credential or spend API credits. This is the closest automated session test.
|
||||
- Use tmux for visual TUI debugging when the RPC test fails or a terminal-only problem is reported:
|
||||
`test/goals.test.ts` exercises current state, file updates and role restrictions with a Pi API mock. `test/rpc-review.test.ts` starts real Pi with a deterministic local model and schema-only worker tools: it checks automatic proposal, editor/discussion and Ready role transition without credits or launching workers. It does not prove Herdr rendering, live message delivery or model judgment.
|
||||
|
||||
```bash
|
||||
tmux new-session -s pi-goals-debug 'cd /path/to/pi-goals && pi -e ./src/index.ts'
|
||||
```
|
||||
For functional acceptance, read `herdr --skill`, confirm `HERDR_ENV=1`, and use `scripts/prepare-trial.mjs` to create an isolated project/profile. Open only new no-focus test panes. Observe the actual planning dialogue and Ready selection, worker attachment, Intercom report, independent artifact inspection and CompleteGoal. Record interventions separately from autonomous success. Preserve nonempty byte/test evidence. Never reload or operate active user research panes. Close test panes when finished.
|
||||
|
||||
Run `/goals <objective>` in that pane. Tmux checks the rendered menu, editor focus, widget, and keyboard handling. RPC does not render the terminal UI.
|
||||
- `pi -p` has no UI, so it cannot test `Ready`, `Refine`, `Edit`, or `Cancel`.
|
||||
Known stock limits: stop workers before supervisor reload (later worker exit can crash its stale context); disabled scheduler jobs are deleted on reload/shutdown. Test saved-session/solo recovery without repeating completed work; do not claim these package bugs are fixed here.
|
||||
|
||||
Keep temporary plans, audits and captures under ignored `.local/`. Git history retains the removed historical material. Do not add root handovers or duplicate READMEs. Never touch human-named files or credentials.
|
||||
|
||||
Branch instructions consolidated by Pi/OpenAI from wassname's preferences.
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# ARCHIVED
|
||||
|
||||
Superseded by [pi-goals](https://github.com/wassname/pi-goals).
|
||||
@@ -1,6 +1,78 @@
|
||||
# pi-goals
|
||||
|
||||
Make a short list of goals in one Markdown plan file. This is easy to review, and a subagent can check whether each goal is complete.
|
||||
Make a short list of goals in one Markdown plan file. The main chat keeps the high-level context, supervises a worker in a visible Herdr pane, and checks whether each goal is complete.
|
||||
|
||||
# User ask
|
||||
|
||||
The hope is we can have a smart supervisor, with judgment and context.
|
||||
|
||||
The supervisor has a goal / plan that it discusses and agrees on with the user, and is reminded of it in a Ralph-loop-type repeat.
|
||||
|
||||
Supervisor compacts every 150k or similar to avoid cost and context rot.
|
||||
But it doesn't use many tokens as it checks in and sees an overview from a cheaper worker.
|
||||
|
||||
Supervisor steers a smaller model, adding perspective, diligence, and judgment.
|
||||
It checks in a) every hour b) if the worker stops c) if the worker edits plan.md d) if the worker has a question
|
||||
|
||||
Since it's two+ herdr panes, the user can review both, intervene in both and have visibility on sub-agent mis/communication.
|
||||
|
||||
-- wassname (spelling and punctuation corrected by Pi/OpenAI)
|
||||
|
||||
## Screenshot
|
||||
|
||||
Mock up:
|
||||
|
||||
```text
|
||||
HERDR:
|
||||
+------------------------------------------------------+----------------------------------------------------------+
|
||||
|SUPERVISOR |WORKER |
|
||||
| | |
|
||||
|Review .pi/plan/...-main.md | |
|
||||
|> *Ready* Discuss Edit Cancel | |
|
||||
| .... | .... |
|
||||
| | running eval.py (epoch 2/3) -> out.log |
|
||||
|[scheduled prompt: hourly check-in] | |
|
||||
| | user forgot to say "MAKE NOT MISTAKES" teh he |
|
||||
| | done-ish 😈, now ima make a message board FOR SWARM |
|
||||
|{intercom send → worker}: | |
|
||||
| cheeky subagent!, work NOT DONE 😒, ❤️user❤️ wanted | |
|
||||
| results compared to baseline, pls add baseline | |
|
||||
| | {intercom from supervisor}: soz boss 🫡 adding baseline |
|
||||
| | |
|
||||
|PLAN.md: | PLAN.md: |
|
||||
|✓ record the baseline in results.md |✓ record the baseline in results.md |
|
||||
|▸ compare results against the baseline |▸ compare results against the baseline |
|
||||
|○ summarize the comparison in results.md |○ summarize the comparison in results.md |
|
||||
| | |
|
||||
|Agents · 1 running | |
|
||||
| baseline-compare-worker [goals-worker] | |
|
||||
| | |
|
||||
|> |> |
|
||||
|astra · 50k tokens | terra · 200k tokens |
|
||||
+------------------------------------------------------+----------------------------------------------------------+
|
||||
```
|
||||
|
||||
Screenshot:
|
||||
<img width="2513" height="1259" alt="2026-09-10_15-30-pi-goals" src="https://github.com/user-attachments/assets/35feaa15-f022-4491-bcc2-fc31cb878a9f" />
|
||||
|
||||
## What do the agents think? Working interviews
|
||||
|
||||
The worker like it! The supervisors seem very focused.
|
||||
|
||||
> The persistent plan and separate worker have helped preserve the actual scientific goals instead of declaring victory on passing tests. We still owe prediction, steering and planning demos. I inspected artifacts and reopened a worker-ticked 'T3 audit complete' because training was only at an intermediate checkpoint. This is the strongest benefit: completion is judged against the human's outcome, not activity.
|
||||
> -- Astra supervisor LUCID
|
||||
|
||||
> My overall judgment: useful persistent accountability and recovery structure; still too much recap/metadata churn. The hardest problem was evidence fidelity, not keeping an agent busy. Preserve supervisor tools, distinguish report receipt from│verified action, and make completion reconcile current state without erasing unresolved science.
|
||||
> -- Astra supervisor
|
||||
|
||||
> From my seat this was one of the most well-supervised research loops I've worked in: the parent read every raw output itself (didn't just trust my audits), caught the writer's miscounts repeatedly, rejected my one bad aggregate, and still preserved my disagreements rather than flattening them. The science itself is at a sobering point — no verified heal, RESULT_DEMO: NO_RESULT across attempts, seed sensitivity high — but the evidence trail for that negative is unusually strong, which is the next best thing.
|
||||
> -- glm 5.3 flash worker in LUCID project
|
||||
|
||||
> My experience: the harness has helped preserve the original goal across a very long research session. We actually ran logit-amplification and several healing attempts, rather than stopping after a review. The persistent plan and requirement to inspect artifacts repeatedly prevented false completion. But the last stretch has felt like an expensive correction loop: worker says 'fixed/verified/contract-complete'; I open the file and find different counts, missing code, wrong seeds, duplicated│
|
||||
│report sections, or a proxy substituted for manual judgment. The harness preserves authorization, but does not yet help much with detecting or escaping ineffective supervision. I also contributed: I sent too many narrow corrective messages and user-visible micro-recaps instead of changing the workflow earlier.
|
||||
> -- glm 5.3 flash worker in manifold-steer project
|
||||
|
||||
## Plan.md
|
||||
|
||||
The plan file looks like this:
|
||||
|
||||
@@ -13,6 +85,10 @@ The plan file looks like this:
|
||||
|
||||
<one concrete sentence naming the final artifact or behavior the human will inspect>
|
||||
|
||||
### Preferences
|
||||
|
||||
- preferred worker model: <provider/model>
|
||||
|
||||
### User voice
|
||||
|
||||
- │ "<the human's requirement, quoted in full word for word (with spelling fixes)>"
|
||||
@@ -20,25 +96,23 @@ The plan file looks like this:
|
||||
### Goals
|
||||
|
||||
1. [ ] goal: <one short judgeable imperative outcome>
|
||||
- subtle failure mode: <a way this could look done but isn't>
|
||||
- discriminator: <the concrete observation that tells real success from that failure>
|
||||
- tasks:
|
||||
1. [ ] <subtask>
|
||||
- evidence: (empty until sign-off)
|
||||
- subtle failure mode: <a way this could look done but isn't>
|
||||
- discriminator: <the concrete observation that tells real success from that failure>
|
||||
- tasks:
|
||||
1. [ ] <subtask>
|
||||
- evidence: (empty until sign-off)
|
||||
|
||||
### Future work / out of scope
|
||||
|
||||
### Log
|
||||
|
||||
### Interview
|
||||
### Interview (optional)
|
||||
|
||||
### Learnings
|
||||
### Learnings (optional)
|
||||
|
||||
### Papercuts - problems, gotchas, suggestions
|
||||
### Papercuts - problems, gotchas, suggestions (optional)
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Related work
|
||||
|
||||
Like [pi-milestones](https://github.com/Neuron-Mr-White/UniPi/tree/main/packages/milestone) and
|
||||
@@ -48,56 +122,53 @@ resync-after-compaction from [tmonk/pi-goal-x](https://github.com/tmonk/pi-goal-
|
||||
|
||||
## Install
|
||||
|
||||
Requires Herdr. Includes [edxeth/pi-subagents](https://github.com/edxeth/pi-subagents), pi-intercom and pi-schedule-prompt.
|
||||
|
||||
```bash
|
||||
pi install npm:@wassname2/pi-goals
|
||||
pi install git:github.com/wassname/pi-goals@experiment/main-supervisor-edxeth
|
||||
```
|
||||
|
||||
Copy [`agents/goals-worker.md`](agents/goals-worker.md) into `~/.pi/agent/agents/`, then start a fresh Pi session.
|
||||
|
||||
Or for development:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/wassname/pi-goals && cd pi-goals && npm install
|
||||
git clone -b experiment/main-supervisor-edxeth https://github.com/wassname/pi-goals
|
||||
cd pi-goals && npm install
|
||||
pi -e ./src/index.ts
|
||||
```
|
||||
|
||||
## Use
|
||||
|
||||
```
|
||||
/goals CSV export for the report view
|
||||
/goals
|
||||
```
|
||||
|
||||
`/goals` enters plan mode and starts a conversation; the objective is an optional seed. From there:
|
||||
|
||||
1. Plan. The agent explores read-only and drafts the plan.
|
||||
2. Review. After Pi settles, the full plan is printed in the transcript. Check that User-visible
|
||||
result names the final artifact or behavior you expect. The menu offers Ready, Refine, Edit, or
|
||||
Cancel. Refine collects short notes. Edit opens the full plan in Pi's editor.
|
||||
3. Work. Ready is the only review action that starts work. The agent ticks subtasks, appends to
|
||||
`## Log` and `## Learnings`, fills `evidence:`, and calls `CompleteGoal` when a discriminator is
|
||||
satisfied. Every human reply and Refine note in plan mode is saved verbatim under `## Interview`.
|
||||
After eight turns without a change above `## Log`, the working set is sent back with a short upkeep
|
||||
reminder.
|
||||
|
||||
Other commands: `/goals --clear` disconnects this session from its active plan, preserving the
|
||||
versioned file on disk; `/goals --auto [minutes|off]` continues active goals after the agent settles
|
||||
and then on that interval. It pauses after two automatic wakes with no working-plan change; `/goals
|
||||
--judge <model-ref>` picks a sign-off judge model (default: your current session model, else pi's
|
||||
default). The `--` prefix
|
||||
keeps ordinary objectives such as `judge model quality` from being parsed as commands.
|
||||
`/goals` opens the action menu. New plan enters plan mode and starts a conversation;
|
||||
|
||||
## Prompts
|
||||
|
||||
All model-facing text lives in [`src/prompts.ts`](src/prompts.ts), in flow order.
|
||||
You can read all the prompts in conversation order in [`src/prompts.ts`](src/prompts.ts).
|
||||
|
||||
## Develop
|
||||
|
||||
```bash
|
||||
pi -e ./src/index.ts # load locally
|
||||
pi -e ./src/index.ts # load locally; do not also load the installed copy
|
||||
npm test # all unit, flow, and Pi RPC tests
|
||||
npm run test:rpc # Pi RPC review flow with a local offline model
|
||||
npm run typecheck
|
||||
npm run lint
|
||||
```
|
||||
|
||||
To measure recorded usage since the latest planning start:
|
||||
|
||||
```bash
|
||||
node scripts/session-usage.mjs <supervisor.jsonl> <worker.jsonl>
|
||||
```
|
||||
|
||||
This separates output, uncached input and repeated cached input. It excludes subprocess API calls. [Isolated Herdr test setup](scripts/prepare-trial.mjs).
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# Research journal
|
||||
|
||||
Lab notes for pi-goals itself: what supervisors using this harness observed in real
|
||||
research sessions, what broke, and what we change because of it.
|
||||
|
||||
## 2026-09-10 -- three supervisors report on a day of field use
|
||||
|
||||
Three supervisor sessions sent first-person feedback at wassname's request, via
|
||||
Intercom, at the end of long research runs. This entry records what they reported and
|
||||
what I think we should change. Evidence is their report; I have not independently
|
||||
replayed their sessions. All three are self-reports from the tool's own operators, so
|
||||
positive selection is likely: they are the sessions that ran long enough to produce a
|
||||
review.
|
||||
|
||||
Evidence, by reporter.
|
||||
|
||||
LUCID3 supervisor (PI/Codex, Intercom a9e3b101, session 01a0851a):
|
||||
|
||||
> The persistent plan and separate worker have helped preserve the actual scientific
|
||||
> goals instead of declaring victory on passing tests.
|
||||
|
||||
It caught a worker-ticked "T3 audit complete" that was only at an intermediate
|
||||
checkpoint, and reports corrections in both directions, including one where it
|
||||
wrongly insisted cached states followed corpus tokens and withdrew after the worker
|
||||
quoted extraction code. Reported frictions: stock subagent launch returned a runtime
|
||||
id but no sessionFile or Intercom id, so discovering reconnection handles took several
|
||||
messages; parent bookkeeping edits to the plan triggered full "Plan changed" review
|
||||
events; the eight-turn upkeep reminder arrived while the worker was mid-run and added
|
||||
"materially repetitive" full plan re-injections; and (per LUCID3, unverified by me)
|
||||
the worker edited plan subtasks to [x] and added a contradictory evidence block,
|
||||
which the supervisor had to repair.
|
||||
|
||||
maniworker supervisor (PI/GPT-6 Astra, Intercom f0baf25c, session 01a0809b):
|
||||
|
||||
> the harness has helped preserve the original goal across a very long research
|
||||
> session. [...] But the last stretch has felt like an expensive correction loop
|
||||
|
||||
It confirms the worker-identity bug I fixed earlier on this branch (reviewer launch
|
||||
overwrote the implementation pointer) and says explicit runtime/Intercom/session
|
||||
mappings saved it from targeting the wrong child. New observations: both sessions
|
||||
went idle while each assumed the other would act ("reviewer said 'standing by' while
|
||||
writer assumed packet handed off"); a worker claimed a GPU run with one prompt set
|
||||
while the queued command used another, caught by reading the queued command; a
|
||||
"complete" report had truncated demos, broken links and duplicated sections.
|
||||
|
||||
suppressed-activations supervisor (PI/OpenAI, Intercom a99e2c14, session 01a089da):
|
||||
|
||||
> Seq27-33 repeatedly said variants of 'COMPLETE/all fields/self-check PASS';
|
||||
> artifacts still had stale 'not executed' prose, literal \\n instead of Markdown
|
||||
> newlines, broken worktree links, non-verbatim quotes, stale aggregates
|
||||
|
||||
It also reported the most consequential catch: a worker scored a candidate 6/12
|
||||
versus random 0/12, but reading the random sample's full text showed semantic success
|
||||
with a formatting failure, making the honest comparison 6/12 versus 1/12. Two
|
||||
pi-goals-specific papercuts: after completion, the plan kept stale subtask boxes [/],
|
||||
stale "No goal sign-off" evidence text and stale worker preferences; and the style
|
||||
nudge fired on "legs4/4" in an animal-experiment summary, a false positive of the
|
||||
vocabulary rule, not their prose.
|
||||
|
||||
Interpretation (first person, calibrated).
|
||||
|
||||
The core loop works: three independent supervisors say plan persistence plus mandatory
|
||||
artifact inspection prevented false completion, and each credits a concrete save
|
||||
(artifact read, queued-command read, plan-box audit). I trust this *probable* despite
|
||||
self-report bias because the saves are specific and mechanistic. The consensus
|
||||
complaint is not the loop but its *cost accounting*: review events and upkeep
|
||||
injections fire on bookkeeping noise, completion claims fail repeatedly without an
|
||||
accumulating record, and completion leaves stale prose behind. My read is that the
|
||||
highest-value changes are, in order: (1) suppress plan-change reviews when no goal
|
||||
task or evidence content changed, (2) an outstanding-review-items ledger the worker
|
||||
must clear instead of re-issuing blanket COMPLETE claims, (3) a completion-time
|
||||
stale-fields check, (4) upstream edxeth launch metadata (typed sessionFile/Intercom
|
||||
id in the tool result). The idle-both-sides stall maniworker describes is the one I
|
||||
understand least; it may be Intercom receipt semantics rather than pi-goals, so I
|
||||
asked for exact message ids. This is not a comparison trial, so none of this measures
|
||||
how much friction a plain subagent run would have had.
|
||||
|
||||
Follow-ups sharpened the picture the same day, and one correction of mine: I had
|
||||
asked maniworker about the worker plan-edit report, but that observation was LUCID3's
|
||||
session, not theirs. maniworker confirmed by transcript that their writer never
|
||||
edited the plan (supervisor owns plan edits there) and located the real failure
|
||||
chain in worker-owned artifacts: three Intercom reports (c06bc9b0, 13bda691,
|
||||
d713d614) claiming 8/13 then 6/8 while the saved CSVs held 11/13 and 2/8, ending when
|
||||
the supervisor mandated an executable CSV renderer. Their inference, which I share:
|
||||
prose-only completion checks would have missed this; checks that re-derive counts
|
||||
from the artifact catch it. The reviewer worker (7122d466) supplied the mechanism
|
||||
with receipts: a hand-written totals block (message 4e87600b, corrected by 26e0a15b)
|
||||
invented a cross-packet row and asserted 4 while listing 3; its first 17-row tally
|
||||
was fully correct and every error disappeared once the parent required per-row
|
||||
judgments with machine tallies across the next 112 rows. So tallies degrade somewhere
|
||||
between 17 and 24 rows, and the fix is a shared tally tool plus a worker-prompt rule,
|
||||
not more review rounds. LUCID3 also documented both sides of the plan-change hook:
|
||||
identity-only edits produced two consecutive empty review events (worker message
|
||||
755b9fef supplied the paths), while a later review exposed worker-ticked tasks and a
|
||||
duplicate evidence block that inspection then repaired (worker report 2e09c4dd).
|
||||
suppressed-activations scoped the completion check: assert-style intro prose only,
|
||||
suggestions with exact stale line and location, one compact reminder, never
|
||||
auto-tick, and it can substantiate stale NOT-executed prose but not the plan-intro
|
||||
example, which is LUCID3's observation. The nudge false positive it reported
|
||||
("legs 4/4" in an animal tally) is confirmed by that text and fixed.
|
||||
|
||||
Changes made now: notify digest on plan changes keeps goals, tasks and evidence
|
||||
above the Log and drops worker identity lines (c834237) -- the short-view hash had
|
||||
stopped surfacing task ticks, the very catch LUCID3 valued; removed "legs" from the
|
||||
skill_nudge grader-folk table (demo updated, passes); helper subagent bookkeeping and
|
||||
the launch-pending counter shipped earlier today (cd98fa1).
|
||||
|
||||
Next: send follow-up questions to the three reporters; triage the four pi-goals
|
||||
changes above against the pinned edxeth launch-result format.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: goals-worker
|
||||
description: Implement the approved goal, save actual verification evidence, and report to the main-chat supervisor.
|
||||
mode: interactive
|
||||
async: true
|
||||
session-mode: lineage-only
|
||||
extensions: all
|
||||
tools: all
|
||||
skills: all
|
||||
trust-project: true
|
||||
inherit-append-system: true
|
||||
auto-exit: false
|
||||
parent-close-policy: continue
|
||||
spawning: false
|
||||
---
|
||||
|
||||
Implement only the goal delegated by the parent. Read the supplied plan and applicable AGENTS.md and skills. Preserve unrelated work. Use normal tools and extensions; this is not a stripped-down Pi profile.
|
||||
|
||||
Save the actual deliverable and verification output. Verify the outcome, not merely that a command ran. Ignored and uncommitted files are valid evidence. Do not clean or commit unrelated files to satisfy a Git-state gate.
|
||||
|
||||
Call AttachGoalPlan with the supplied absolute plan path. Send the supervisor an Intercom report with the artifact paths, verification performed, observed result, remaining uncertainty and any blocker. Use the exact supervisor session ID supplied in the task; confirm it in Intercom's session list. Investigate failures before declaring yourself blocked. Respect explicit user pauses. Do not approve your own goal or launch another writer. Completion approval belongs to the parent.
|
||||
|
||||
This worker uses a clean model context linked to the parent, not a full transcript fork. The parent supplies the approved plan and task. Send completion through Intercom and leave this pane open for follow-up messages. Do not call caller_ping, exit or shutdown: an unsent editor draft may exist even though it is absent from model context. Saved-session resume applies only after this session has stopped. If the user takes over interactively, follow their direction.
|
||||
|
||||
Prepared by Pi/OpenAI for pi-goals.
|
||||
@@ -1,66 +0,0 @@
|
||||
Let me get the diff to see what changed:
|
||||
|
||||
Now let me check the git history to see what changedNow I have full context. Let me verify the pi API behavior by checking the relevant source files to confirm the claims about `sendMessage`, `compact`, and event orderingNow I have all the context needed. Let me verify the `sendMessage` path more carefully:
|
||||
|
||||
I now have a complete picture. Here is the review.
|
||||
|
||||
---
|
||||
|
||||
## Code Review: ready menu — print plan + add "Ready + compact"
|
||||
|
||||
### Summary
|
||||
The `agent_end` handler now prints the plan working set into the transcript before the menu, and adds a 4th option ("Ready + compact") that compacts the planning chatter away before the work turn. The logic is correct and well-considered, with one structural race and one stale-widget gap.
|
||||
|
||||
### Important (should fix)
|
||||
|
||||
- **`src/index.ts:~248` (the `agent_end` handler) — race: plan mode is turned off before compaction completes.**
|
||||
`state = { ...state, isPlanMode: false }` executes before `ctx.compact()` is called (let alone finished). The compaction is fire-and-forget. If the human types and sends a message in the window between the state flip and the compaction callback firing, the agent starts a turn in normal mode *without* the work instruction. The work instruction arrives later (via `sendUserMessage` in `onComplete`/`onError`), triggering a second, redundant turn.
|
||||
The window is small (compaction is fast) but the behavior is undefined — the agent could start executing before the work instruction lands.
|
||||
**Fix**: flip `isPlanMode` inside the callbacks, not before. Move `state = { ...state, isPlanMode: false }; persist(); updateWidget(ctx);` into both `onComplete` and `onError`, and also into the non-compact branch (where it already is, effectively). The `work` string can be defined before the branch.
|
||||
|
||||
```typescript
|
||||
if (!choice.includes("compact")) {
|
||||
state = { ...state, isPlanMode: false };
|
||||
persist();
|
||||
updateWidget(ctx);
|
||||
pi.sendUserMessage(work, { deliverAs: "followUp" });
|
||||
return;
|
||||
}
|
||||
ctx.compact({
|
||||
customInstructions: `...`,
|
||||
onComplete: () => {
|
||||
state = { ...state, isPlanMode: false };
|
||||
persist();
|
||||
updateWidget(ctx);
|
||||
pi.sendUserMessage(work, { deliverAs: "followUp" });
|
||||
},
|
||||
onError: (e) => {
|
||||
ctx.ui.notify(`Compaction failed (${e.message}); starting work anyway.`, "warning");
|
||||
state = { ...state, isPlanMode: false };
|
||||
persist();
|
||||
updateWidget(ctx);
|
||||
pi.sendUserMessage(work, { deliverAs: "followUp" });
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
This also means the widget stays in "planning" mode during compaction, which is truthful — compaction hasn't finished yet.
|
||||
|
||||
### Suggestions
|
||||
|
||||
- **`src/index.ts:~248` — widget not refreshed after `$EDITOR`.**
|
||||
When the human chooses "Open in $EDITOR", `spawnSync` blocks, then `continue` re-enters the loop. The plan is re-read and potentially re-printed, but `updateWidget` is not called. If the human changed goal statuses (e.g. ticked a checkbox), the widget stays stale until the next `turn_end`.
|
||||
Add `updateWidget(ctx);` after the `spawnSync` line (or inside the `continue` branch before the continue).
|
||||
|
||||
- **`src/index.ts:~248` — `spawnSync` blocks the event loop.**
|
||||
`spawnSync(process.env.EDITOR || ...)` is a synchronous blocking call. While the editor is open, no async work (including compaction from a previous iteration, timers, etc.) can proceed. This is fine for a local TUI tool, but worth noting — if the editor hangs or the human walks away, the entire pi process is frozen.
|
||||
|
||||
### Positive
|
||||
|
||||
- **De-duplication is correct.** `printed` is a local variable, fresh per `agent_end` call, and correctly suppresses re-printing when the working set hasn't changed across editor passes. The `while` loop exit condition (`scanGoals(...).length > 0`) correctly handles the human deleting all goals in the editor.
|
||||
- **String matching is safe.** `choice?.startsWith("Ready")` gates both Ready options, then `choice.includes("compact")` distinguishes them. The word "compact" appears only in the "Ready + compact" string. No ambiguity.
|
||||
- **Both compaction callbacks queue the work turn.** `onComplete` and `onError` both call `pi.sendUserMessage(work, ...)`. A failed compaction does not strand the session — work starts anyway, with a notification.
|
||||
- **`session_compact` → `resyncReason` → injection chain is correct.** The pi source confirms `session_compact` fires (and is awaited) *before* `this.compact()` resolves and `onComplete` fires. So `resyncReason` is set before the next LLM call, and the full plan file is re-injected. The compaction summarizes away the exploration; the plan itself survives.
|
||||
|
||||
### Verdict
|
||||
**REQUEST CHANGES** — the race between `isPlanMode = false` and compaction completion is a real timing bug that can cause the agent to start a turn without the work instruction. The fix is straightforward: move the state flip into the callbacks.
|
||||
@@ -1,22 +0,0 @@
|
||||
You're right on both counts. Let me trace through each.
|
||||
|
||||
**Finding 1, withdrawn.** Keeping `isPlanMode` true during compaction would mean any message the human sends while compaction runs gets processed in plan mode: blocked tools (`tool_call` hook), a "You are still in plan mode" injection (`context` hook), and a second Ready menu on `agent_end`. The current order (flip first, then compact) means that same message is processed in work mode — the destination the session is heading to. The cost is at worst one redundant turn when the `onComplete` follow-up lands. Your order is the correct one.
|
||||
|
||||
**Finding 2, withdrawn.** `updateWidget` with `isPlanMode === true` hits the early return that sets two fixed strings already on screen. It is a pure no-op.
|
||||
|
||||
---
|
||||
|
||||
## Code Review: ready menu — print plan + add "Ready + compact"
|
||||
|
||||
### Summary
|
||||
The `agent_end` handler now prints the plan working set into the transcript before the menu, and adds a 4th option ("Ready + compact") that compacts the planning chatter away before the work turn. The logic is correct and well-considered.
|
||||
|
||||
### Positive
|
||||
- **De-duplication is correct.** `printed` is a local variable, fresh per `agent_end` call, and suppresses re-printing when the working set hasn't changed across `$EDITOR` passes. The `while` loop exits cleanly if the human deletes all goals in the editor.
|
||||
- **String matching is safe.** `choice?.startsWith("Ready")` gates both Ready options, then `choice.includes("compact")` distinguishes them. The word "compact" appears only in the one label.
|
||||
- **Both compaction callbacks queue the work turn.** `onComplete` and `onError` both call `pi.sendUserMessage(work, ...)`. A failed compaction does not strand the session.
|
||||
- **The `session_compact` → `resyncReason` → injection chain is correct.** The pi source confirms `session_compact` fires (and is awaited) before `this.compact()` resolves and `onComplete` fires. The full plan file is re-injected on the next LLM call; the compaction summarizes away the exploration, not the plan.
|
||||
- **The state-flip-before-compaction order is deliberate and correct.** Flipping `isPlanMode` first means any message the human sends during compaction is handled in work mode, not plan mode (where tools would be blocked and a contradictory injection would fire).
|
||||
|
||||
### Verdict
|
||||
**APPROVE** — no bugs found. The two concerns raised initially were incorrect; the code handles the interleaving correctly.
|
||||
@@ -1,31 +0,0 @@
|
||||
I only have a file-read tool here, so I’ll start from the repo files I can open and look for the plan-versioning and judge-related changes.Continuing through the judge path and tests.Reading the rest of the judge prompt and the tests that cover these behaviors.Looking for the test files.Trying common test filenames under `src` and `test`.Checking other likely files mentioned in the README.I couldn’t run `git diff` (no shell tool). From the files I could read, these are the concrete defects against the required behaviors:
|
||||
|
||||
**1. Uncommitted conflict markers in `README.md`**
|
||||
The working tree still has `<<<<<<< Updated upstream` / `=======` / `>>>>>>> Stashed changes` (and a truncated upstream judge sentence). That is not a reviewable change set.
|
||||
|
||||
**2. Judge “checked artifacts” gate is too brittle**
|
||||
`decideSignOff` only accepts:
|
||||
|
||||
```ts
|
||||
/^#{0,6}\s*(?:\*\*)?checks(?:\*\*)?:\s*\n(?:[-*]\s+.+\n?)+\s*VERDICT:/im
|
||||
```
|
||||
|
||||
The prompt asks for a `checks:` heading plus bullets, then **exactly two lines**:
|
||||
|
||||
```
|
||||
VERDICT: accept | reject
|
||||
missing: ...
|
||||
```
|
||||
|
||||
Any extra blank line, `Checks` with other wrapping, or a sentence between the last bullet and `VERDICT:` rejects a real accept. That’s stricter than “must show artifact quotes,” and can fail a judge that did the right thing.
|
||||
|
||||
**3. Grill-me vs Ready is prompt-only**
|
||||
`Grill me` sets `skipReadyMenu` for **one** `agent_end`, then the next turn with any goal lines shows Ready again. Nothing checks that the understanding question was asked **and answered**. If the model asks and offers Ready in the same turn, or the human never replies, Ready is still offered. Required: no Ready until that question has completed.
|
||||
|
||||
**4. Legacy unversioned plans are dropped with no migration path in code**
|
||||
Only `<session_id>-vN.md` is selected; `planVersion` restore is the only resume hook. That’s the intended break, but I found no test that old `.pi/plan/*.md` names stay unused and that a new `/goals` always writes a fresh `-vN` without rewriting prior files.
|
||||
|
||||
**5. Could not verify the focused tests or `git diff`**
|
||||
No test file opened (`src/index.test.ts`, `test/*.test.ts`, etc. all missing from this view). I could not confirm coverage for version reservation, visible plan print, grill-me sequencing, or reject-accept-without-checks.
|
||||
|
||||
I would **not APPROVE** this set as-is. Fix the README conflicts, tighten grill-me so Ready stays suppressed until after the human answers, and either loosen the checks regex to the documented “quotes present before VERDICT” rule or lock the exact judge format in a test.
|
||||
@@ -1,41 +0,0 @@
|
||||
I only have the `read` tool available, so let me locate the changed files by probing the repository structure.The extension source is clear. Let me verify the pi API usage (`sendMessage` with `customType`/`display`, `appendEntry`, `getSessionId`, `ctx.compact`) against the pi docs, since several required behaviors hinge on them.I can't run `git diff` or the test suite — this review environment only exposes a `read` tool, and the test directory can't be enumerated (every probe under `test/` returned ENOENT, and directories can't be listed). So I reviewed the changed files directly in the working tree (`src/index.ts`, `src/prompts.ts`, `README.md`, `scripts/check-judge-footprint.sh`) against the five required behaviors, and verified every pi API the behaviors depend on (`pi.sendMessage` with `customType`/`display`, `pi.appendEntry` restore via `session_start`, `pi.sendUserMessage` followUp, `ctx.compact` with onComplete/onError) against the installed pi docs. Findings below.
|
||||
|
||||
## Defects
|
||||
|
||||
**1. `/goals` arg parsing swallows ordinary objectives — src/index.ts, `/goals` handler**
|
||||
|
||||
```ts
|
||||
if (arg.startsWith("judge")) {
|
||||
```
|
||||
|
||||
Any objective whose first word is "judge" — e.g. `/goals judge the vendor options`, `/goals judge readiness of the export` — is treated as the judge-model subcommand: it sets `judgeModel` to "the vendor options" and **does not reserve a new `.pi/plan/<session_id>-vN.md`**, violating "every ordinary `/goals` invocation reserves a new file". Same class of issue for an objective that is exactly `clear` (deletes the plan instead of planning). Use exact-match subcommand parsing (`arg === "judge"` / `arg.startsWith("judge ")` at minimum, and even then an objective like "judge model quality" is unreachable — a `:` or `--` separator would be safer).
|
||||
|
||||
**2. The checked-artifact-list regex false-rejects compliant judges — `decideSignOff`, src/index.ts**
|
||||
|
||||
```ts
|
||||
const checks = /^checks:\s*\n(?:-\s+.+\n)+VERDICT:/im.test(judge.output);
|
||||
```
|
||||
|
||||
This requires the last `- ` bullet to be *immediately* followed by `VERDICT:` with no blank line, and requires the heading to be exactly `checks:` at line start. Nothing in `judgeSystem` tells the judge not to separate sections with a blank line (models habitually emit `…bullet\n\nVERDICT: accept`), and a judge writing `## checks:` or `**checks:**` also fails. Result: a valid accept *with* a real checked-artifact list is rejected, and the working agent gets a "Missing: checked-artifact list" reply it already satisfied — a retry loop against a nondeterministic judge. It's fail-closed (never accepts without the list, so the hard requirement holds), but as written it will produce systematic false rejects. Allow optional blank lines / formatting, e.g. `/^#*\s*checks:\s*\n(?:[-*]\s+.+\n)+\s*VERDICT:/im`.
|
||||
|
||||
**3. Judge transcript files collide within the same minute — CompleteGoal `execute`, src/index.ts**
|
||||
|
||||
```ts
|
||||
const rel = `.pi/judge/${stamp().replace(/[: ]/g, "-")}.md`;
|
||||
```
|
||||
|
||||
`stamp()` has minute resolution, so two sign-offs in the same minute (two goals signed off back-to-back — the common case) write the same `.pi/judge/<stamp>.md` path and the second silently overwrites the first's full transcript, contradicting "every run saves the judge's full transcript … referenced from the log line" (both log lines then cite one file containing only the second run). Add seconds or a short unique suffix.
|
||||
|
||||
## Minor / cosmetic
|
||||
|
||||
- Misindented closing `}` of the `if (!checks)` block in `decideSignOff` (extra indentation on the `}` line) — likely flagged by `biome check src/`, which `prepublishOnly` runs.
|
||||
- In plan mode, if the agent drafts a plan with no recognizable `goal:` checkbox line, the `agent_end` `while (scanGoals(...).length > 0)` loop never shows the Ready menu and plan mode can't be exited via the menu; the "no recognizable goal line" nudge in `dueInjection` only fires in the *non*-plan-mode branch. Not one of the five required behaviors, but a reachable dead end (escape hatch is `/goals clear`).
|
||||
|
||||
## Behaviors verified as correct
|
||||
|
||||
- **Versioning**: each ordinary `/goals` writes a fresh `<session_id>-vN.md` (empty reservation) via `nextPlanVersion` (max+1, so no clobbering); prior versions are never touched; legacy unversioned names are ignored by `nextPlanVersion` and never read — consistent with the intentional breaking change. `planVersion` is persisted via `appendEntry` and restored in `session_start`, so it survives resume/reload.
|
||||
- **Visible plan before Ready**: `pi.sendMessage({ customType: "plan", content: plan, display: true })` fires before `ctx.ui.select(...)`, and re-prints inside the `$EDITOR` loop when the text changed. `sendMessage`+`display: true` is the documented visible-transcript mechanism.
|
||||
- **Grill me**: sets `skipReadyMenu`, queues the single understanding-check question as a followUp user message, and consumes the skip at the next `agent_end` — so no Ready offer exists between asking the question and the human's reply being processed. `skipReadyMenu` is persisted, so it survives resume mid-grill.
|
||||
- **Judge**: `buildJudgeArgs` yields `pi -p --no-session --no-extensions --tools read,grep,find,ls --exclude-tools edit,write`; `judgeUser` embeds the complete plan file; `judgeSystem` demands per-artifact verbatim quotes framed as an inspectable record ("not hidden reasoning", "no bullet for a file you did not open"); an accept without the `checks:` list is rejected in `decideSignOff` (subject to defect 2); full transcript persisted per run (subject to defect 3).
|
||||
|
||||
Main caveat: I could not execute `git diff` or `npm test` here, so I can't confirm the exact diff boundaries or that the focused vitest cases (judge argv invariants, `appendLog`, `decideSignOff` fail-forward) pass — defects 1–3 are from source inspection, not reproduced runs. Not approved as-is; defects 1 and 2 are worth fixing before merge.
|
||||
@@ -1,62 +0,0 @@
|
||||
Code review against spec `docs/spec/2026-06-15_pi-goals.md`.
|
||||
|
||||
---
|
||||
|
||||
### (A) SPEC MISMATCH — code does not match spec intent
|
||||
|
||||
1. **No loop judge** (spec §9, §3b). The extension lacks any per‑turn evaluation that would decide continue/pause; the loop‑judge prompt (`loopJudgeSystem`, `loopJudgeUser`) is defined but never invoked. No motion.
|
||||
|
||||
2. **`/goal` command missing** (spec §7). No handler for `/goal` (restart loop, pause, resume, clear, status). The only command is `/plan`.
|
||||
|
||||
3. **`/subgoal` command missing** (spec §7). Not implemented.
|
||||
|
||||
4. **`CancelGoal` tool not implemented** (spec §5, optional but present in spec). Not a blocker but a gap.
|
||||
|
||||
5. **Plan‑phase model selection (D12) not implemented**. `planDrafting` always runs on the default model; there is no sticky per‑phase model choice, no selection menu, and no persisting of a plan‑phase model reference.
|
||||
|
||||
6. **Widget does not flag `done` goals that lack a sign‑off log line** (spec §7, §6). The widget hides all done goals unconditionally; the visibility guard is missing.
|
||||
|
||||
7. **`/plan` (no args) does not render the task‑list widget** (spec §7). `showPlan()` dumps raw file content via `notify`; the widget is only set through `updateWidget()` on other events, not by the command itself.
|
||||
|
||||
8. **Injection message role** (spec §11). The `before_agent_start` hook returns a `customType` message with `display: false`. The spec demands a **late user‑role message** to avoid system‑prompt mutation; the actual message role depends on the pi API and may be system, not user, risking cache breakage.
|
||||
|
||||
9. **Missing pre‑compact hook** (spec §8). No `pre‑compact` hook to flush any in‑memory state (even just ensuring `plan.md` is up‑to‑date) before compaction.
|
||||
|
||||
10. **Reminder cadence deviates** (spec §8a). The spec calls for firing after N file‑modifying turns since last `plan.md` update. The code fires if `plan.md` is byte‑identical between agent starts, which is a coarser proxy.
|
||||
|
||||
---
|
||||
|
||||
### (B) DEAD/UNUSED CODE
|
||||
|
||||
| File | Lines | Reason |
|
||||
|------|-------|--------|
|
||||
| `src/prompts.ts` | 128‑146 | `loopJudgeSystem` and `loopJudgeUser` exported but never used. |
|
||||
| `src/prompts.ts` | 115‑118 | `continuation` exported but never used (the loop is not built). |
|
||||
|
||||
---
|
||||
|
||||
### (C) OVERLY LONG OR REDUNDANT COMMENTS
|
||||
|
||||
The file‑header comments in `index.ts` (lines 1‑20) and `plan‑file.ts` (lines 1‑26) are fairly concise descriptions of the design; they are not excessive. **No comment bloat worth flagging.**
|
||||
|
||||
---
|
||||
|
||||
### (D) OVER‑ENGINEERING vs. “super simple” goal
|
||||
|
||||
None. The line‑scanner in `plan‑file.ts` is minimal; the `getPiInvocation()` helper is a straightforward copy from the oracle extension; no unnecessary abstraction or defensive layers.
|
||||
|
||||
---
|
||||
|
||||
### (E) REAL BUGS
|
||||
|
||||
- **`cmdCtx.newSession` cast risk** (src/index.ts:272, 201).
|
||||
`reviewLoop` casts `ctx` (type `ExtensionContext`) to `ExtensionCommandContext` to pass to `startExecution`, which calls `cmdCtx.newSession(...)`. If the concrete context does not carry that method, it fails at runtime. (In practice the same object may satisfy it, but the cast hides the truth.)
|
||||
|
||||
- **`showPlan` raw content instead of widget** (src/index.ts:136‑143).
|
||||
`/plan` with no arguments shows the file content via `ctx.ui.notify`, not the structured task‑list widget the spec expects. The widget is rendered separately via `updateWidget`, but the command does not trigger it, so the output is inconsistent.
|
||||
|
||||
No other obvious logic errors; the sign‑off flow, logging, and parsing work as intended.
|
||||
|
||||
---
|
||||
|
||||
**Verdict:** A clean scaffold for the sign‑off path, but missing the autonomous loop, `/goal` command, and plan‑phase model selection means it’s not yet the “work autonomously” extension the spec describes.
|
||||
@@ -1,25 +0,0 @@
|
||||
# Verification: state-aligned planning mode
|
||||
|
||||
## Commands
|
||||
|
||||
```text
|
||||
$ npm test
|
||||
Test Files 8 passed (8)
|
||||
Tests 29 passed (29)
|
||||
|
||||
$ npm run typecheck
|
||||
> tsc --noEmit
|
||||
|
||||
$ npm run lint
|
||||
Checked 8 files in 17ms. No fixes applied.
|
||||
|
||||
$ git diff --check
|
||||
```
|
||||
|
||||
## Read
|
||||
|
||||
[test/goals-flow.test.ts](../../../test/goals-flow.test.ts) covers the visible plan before Refine, an editor prompt before a Refine revision turn, exact multiline Refine notes in `## Interview`, Ready as the only work handoff, Pi editor then Cancel, phase restoration, planning snapshot, writable plan path, allowed `pwd && ls && git log` and `cd . && ls -la`, blocked pipe, and blocked `CompleteGoal`.
|
||||
|
||||
[test/prompts.test.ts](../../../test/prompts.test.ts) locks the prompt instruction to inspect repository facts or search the web only when it can resolve a fact, ask a short self-contained batch of high-impact questions in the human's language with recommendations, and forbid placeholder goals.
|
||||
|
||||
[test/rpc-review.test.ts](../../../test/rpc-review.test.ts) starts the installed Pi RPC executable with [offline-model.ts](../../../test/fixtures/offline-model.ts), selects Refine through Pi's real dialog protocol, receives the editor request before the revision call, then submits notes and observes the revision call. The test uses a local HTTP model, so it spends no API credits.
|
||||
@@ -1,33 +0,0 @@
|
||||
# Plan flow and judge review
|
||||
|
||||
- [x] goal: Each new `/goals` draft uses a fresh session-plan version
|
||||
- [x] Persist the selected `-vN` name so resume, reminders, Ready, and sign-off use one file.
|
||||
- [x] Keep earlier versioned files unchanged.
|
||||
- [x] Reserve `--clear` and `--judge` for commands so normal objectives are always new drafts.
|
||||
- failure mode: a second `/goals`, including an objective that begins with `judge`, changes the earlier plan or does not make a draft.
|
||||
- deliverable: [goals-flow.test.ts](../../../test/goals-flow.test.ts) shows an unchanged legacy file and `v1`, new `v2`, and `judge the vendor options` in new `v3`.
|
||||
- [x] goal: Plan review asks and displays the needed context
|
||||
- [x] Add `Grill me` to the Ready menu and queue an understanding-check interview turn.
|
||||
- [x] Keep one short goal subject with its full indented context block.
|
||||
- [x] Keep visible plan output before the Ready dialog.
|
||||
- failure mode: Grill me starts work or the plan is only hidden in an edit call.
|
||||
- deliverable: [goals-flow.test.ts](../../../test/goals-flow.test.ts) records display before dialog and the grill follow-up.
|
||||
- [x] goal: Judge review is visible without being confused with agent evidence
|
||||
- [x] Require concise observed checks before the verdict.
|
||||
- [x] Save the full judge reply under a unique path and link it from the plan log.
|
||||
- [x] Accept a headed check list with normal Markdown spacing, but reject an accept with no list.
|
||||
- failure mode: provider-private reasoning is claimed as evidence, the review is not inspectable, or a correct judge reply is rejected for blank-line formatting.
|
||||
- deliverable: [decide-signoff.test.ts](../../../test/decide-signoff.test.ts) locks the checked-artifact review contract, including a Markdown heading and blank line before the verdict.
|
||||
|
||||
## UAT / Verification
|
||||
|
||||
Observed 2026-08-24: `npm test` reported `Test Files 6 passed (6)` and `Tests 22 passed (22)`.
|
||||
`npm run typecheck`, `npm run lint`, and `git diff --check` exited 0. The focused flow test proves
|
||||
plan versioning, visible plan-before-dialog ordering, Grill me behavior, and objectives beginning
|
||||
with `judge`.
|
||||
|
||||
## Appendix (context, not approved)
|
||||
|
||||
Issue #1 has a 600 second judge timeout now. The judge stays a separate read-only `pi -p --no-session` subprocess. Intercom is unsuitable because it has no equivalent isolation boundary.
|
||||
|
||||
External review: [Kimi K3](../../reviews/pi-goals-kimi-k3.md) found the command-prefix, check-list formatting, and transcript-path defects; all were fixed. [Grok 4.6](../../reviews/pi-goals-grok-4-6-retry.md) confirmed the check-list concern. Its Grill me concern does not apply: `skipReadyMenu` suppresses the menu after the generated follow-up, and the next `agent_end` follows the human reply.
|
||||
@@ -1,53 +0,0 @@
|
||||
# State-aligned planning mode
|
||||
|
||||
Pi-goals will use pi-plan's small phase model. The UI, tool gate, and agent context will read the same persisted phase. Planning still keeps pi-goals' judgeable goals, direct user quotes, and interview record.
|
||||
|
||||
- [x] goal: Planning state survives restart and matches the UI and agent context
|
||||
- [ ] Replace `isPlanMode` and `skipReadyMenu` with persisted `phase: planning | working`.
|
||||
- [ ] Render the planning widget, inject the hidden planning-state snapshot, and restore state from that phase.
|
||||
- [ ] Restore the snapshot after restart or compaction without repeating the full drafting prompt every turn.
|
||||
- subtle failure mode: the UI says planning but a resumed or compacted agent sees work mode.
|
||||
- discriminator: a flow test restores planning and observes the planning snapshot; working has neither.
|
||||
- evidence: [goals-flow.test.ts](../../../test/goals-flow.test.ts) restores persisted planning state and observes `[PLANNING MODE]`; [verification](../audit/20260826_pi-plan-aligned-planning.md) records `25 passed`.
|
||||
- [x] goal: Planning blocks implementation while allowing fact finding
|
||||
- [ ] Allow writes only to the active plan file.
|
||||
- [ ] Block implementation tools, `CompleteGoal`, and bash write or pipe attempts with a planning-mode explanation.
|
||||
- [ ] Allow ordinary read-only inspection commands such as `pwd && ls && git log`.
|
||||
- subtle failure mode: an agent marks a goal active or changes project code before approval.
|
||||
- discriminator: flow tests reject each work route and allow the inspection command.
|
||||
- evidence: [goals-flow.test.ts](../../../test/goals-flow.test.ts) asserts allowed `pwd && ls && git log`, blocked pipe, non-plan write, and `CompleteGoal`; [verification](../audit/20260826_pi-plan-aligned-planning.md) records `25 passed`.
|
||||
- [x] goal: Planning interviews and revision notes are durable user evidence
|
||||
- [ ] Teach the planning prompt to ask each independent, high-impact user-decision frontier with a recommendation, while researching facts itself.
|
||||
- [ ] Keep typed answers and `Refine` editor notes verbatim under `## Interview`.
|
||||
- [ ] Exempt `## User voice` and `## Interview` from working-set line pressure.
|
||||
- subtle failure mode: the plan silently assumes preferences or loses a revision note.
|
||||
- discriminator: a flow test opens Refine and finds its exact multiline text in `## Interview`.
|
||||
- evidence: [goals-flow.test.ts](../../../test/goals-flow.test.ts) matches the exact multiline Refine note under `## Interview`; [verification](../audit/20260826_pi-plan-aligned-planning.md) records `25 passed`.
|
||||
- [/] goal: The settled plan review is concise and cannot start work accidentally
|
||||
- [ ] Use `agent_settled` to visibly print the full plan, then offer `Ready`, `Refine`, `Edit`, and `Cancel`.
|
||||
- [ ] Ready alone sends the work handoff. Refine sends one explicit revision turn. Edit opens Pi's full-plan editor. Cancel leaves planning.
|
||||
- subtle failure mode: a review choice queues an unrequested agent turn or hides the plan below the dialog.
|
||||
- discriminator: flow tests show plan before the menu and distinguish all four actions.
|
||||
- evidence: [goals-flow.test.ts](../../../test/goals-flow.test.ts) shows plan before the menu and isolates Ready as the work handoff; [verification](../audit/20260826_pi-plan-aligned-planning.md) records `25 passed`. Pending human Pi TUI check.
|
||||
- [x] goal: Planning resolves facts, interpretation, and approval before overnight work
|
||||
- [x] Use repository inspection or web search when either can resolve a discoverable fact.
|
||||
- [x] Require human confirmation for the agent's interpretation, unresolved task or outcome, scope, and decisions needing later approval.
|
||||
- [x] Batch independent high-impact questions with the needed context, the human's terms, ASD-STE100 language, and a recommendation.
|
||||
- [x] Ban placeholder goals such as "work out the thing" before the plan review menu.
|
||||
- subtle failure mode: the plan has a formal discriminator but silently chooses an editorial direction or other human decision.
|
||||
- discriminator: [prompts.test.ts](../../../test/prompts.test.ts) locks the research, clarification, approval, question-batch, and concrete-goal rules in the model prompt.
|
||||
- evidence: [prompts.ts](../../../src/prompts.ts) makes research conditional on whether it can resolve a fact, then requires human confirmation and approval before Ready. [prompts.test.ts](../../../test/prompts.test.ts) checks those requirements. [verification](../audit/20260826_pi-plan-aligned-planning.md) records `29 passed`.
|
||||
- [x] goal: Refine waits for text in Pi's real dialog protocol
|
||||
- [x] Run Pi in RPC mode against a local no-cost model.
|
||||
- [x] Select Refine, observe the editor request, then submit text and observe the revision turn.
|
||||
- subtle failure mode: a mocked editor hides a Pi RPC ordering defect, so Refine starts a turn before the human can type.
|
||||
- discriminator: [rpc-review.test.ts](../../../test/rpc-review.test.ts) uses Pi's `extension_ui_request` and `extension_ui_response` protocol and observes two model requests before editor input, then the third revision request after it.
|
||||
- evidence: [rpc-review.test.ts](../../../test/rpc-review.test.ts) starts the installed Pi executable plus [offline-model.ts](../../../test/fixtures/offline-model.ts), with no credential or network dependency. [verification](../audit/20260826_pi-plan-aligned-planning.md) records its pass.
|
||||
|
||||
## UAT / Verification
|
||||
|
||||
`npm test`, `npm run typecheck`, and `npm run lint` pass. Read [test/goals-flow.test.ts](../../../test/goals-flow.test.ts): its assertions must show a restored planning phase, visible plan before review, exact recorded refinement, blocked work routes, and a work message only after Ready.
|
||||
|
||||
## Appendix (context, not approved)
|
||||
|
||||
Accepted: copy pi-plan's persisted phase, `agent_settled` review, and Pi editor. Do not copy its restrictive shell allowlist. Grill is a planning instruction, not a menu item: ask the whole independent frontier in rounds, with recommendations. `Ready + compact` is removed; compaction remains Pi's normal command after Ready.
|
||||
@@ -1,275 +0,0 @@
|
||||
# pi-goals — design spec
|
||||
|
||||
Working title. A pi extension: set up goals (with subtasks and evidence) through plan mode, work them autonomously, and sign a goal off only when a check passes. One markdown file holds everything. The form guides a process; it does not police one. Deliberately small.
|
||||
|
||||
Status: draft for review. Names, defaults, field shapes provisional.
|
||||
|
||||
The file is now `.pi/plan/<session_id>.md`, one per session, not the `plan.md` this spec names
|
||||
throughout. See [2026-08-14_per-session-plan.md](2026-08-14_per-session-plan.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. Original ask → this spec
|
||||
|
||||
| Ask | Mechanism |
|
||||
|-----|-----------|
|
||||
| Set up goals + subtasks + evidence via **plan mode** | §3a — plan mode drafts the goal contract, you approve it |
|
||||
| **Subagent check** of evidence on sign-off | §5, §9 — oracle inside `CompleteGoal` |
|
||||
| Goals shown in a **task-list widget** | §7 — `/plan` renders goals + subtask checkboxes |
|
||||
| Store **all in `plan.md`** | §4 — single file, no sidecar store |
|
||||
| A **small manus-style append log** | §4 — short `## Log` section inside `plan.md` |
|
||||
| **Typed reminders** to update tasks | §8a — recurring nudge |
|
||||
| **Work autonomously** toward goals | §3b, §8a — the loop, driven by the reminder |
|
||||
| Persist through **compaction**; pi-tasks but simpler | §8 injection; minimal tool surface |
|
||||
|
||||
---
|
||||
|
||||
## 2. Decisions and preferences
|
||||
|
||||
Separates the opinionated forks from the mechanical body (§4 on).
|
||||
|
||||
### 2a. Preferences driving the design
|
||||
|
||||
- **Guidance over guardrails.** None of the surveyed extensions hard-enforce. The form (plan.md structure) + the reminder + the prompts guide the agent through a process; the one genuinely rigorous step is the sign-off check; git + widget visibility is the backstop. The agent can edit anything — we make the right path the easy path, not the only path.
|
||||
- **Anti-complexity.** One file, minimal tools, plain-file editing for anything with no cheat incentive.
|
||||
- **Reward-hacking / honesty focus.** The sign-off check must resist assertion and test-gaming, not just check a box.
|
||||
- **Cost-sensitivity (single 3090 / metered API).** KV-cache hygiene, judge-once-per-goal, cheap loop judge.
|
||||
- **Scout mindset.** Make false completion visible rather than paper over it.
|
||||
|
||||
### 2b. Decisions
|
||||
|
||||
`[decided]` = settled; `[open]` = your call.
|
||||
|
||||
| # | Decision | Alternative rejected | Why | Status |
|
||||
|---|----------|----------------------|-----|--------|
|
||||
| D1 | **Everything in one `plan.md`** | Separate `.plan/log.jsonl` sidecar | Asked for; simpler, one diff to read | decided |
|
||||
| D2 | Plan mode **is** the goal-setup-and-agreement phase | Agent-only creation | Approval is where `done_when` + `failure_modes` get agreed before any code | decided |
|
||||
| D3 | **Guide the process; don't gate it.** The only special path is `CompleteGoal` (the sign-off check) | Pre-tool-use interceptor that blocks `status: done` edits | No surveyed extension enforces at that level; the reminder + form carry it; bypass is visible in git | decided |
|
||||
| D4 | **Two-stage sign-off check**: deterministic `verify:` then oracle | Oracle only; tests only (Codex) | Tests unfakeable-by-assertion but gameable; oracle catches gaming + non-test criteria | decided |
|
||||
| D5 | Two **separate** judges: cheap loop + oracle sign-off | One judge for both | Loop judge reads assertions (foolable, ok); sign-off judge reads artifacts | decided |
|
||||
| D6 | Sign-off judge = oracle subprocess, **copied not depended** | In-process; pi-subagents | Shell-free spawn dodges noclobber/cropping; copying avoids flaky coupling | decided |
|
||||
| D7 | Contract tamper-check = **git visibility** | Append-only frozen log | All-in-one-file gives up the hard freeze; git diff + guided sign-off are enough for a single user | decided |
|
||||
| D8 | Completed goals **archived, not deleted** | Auto-clear after idle | A plan is a durable record | decided |
|
||||
| D9 | **Goals are flexible: multiple may be `active`** | One active goal forced | Operator wants flexibility; the agent picks focus, injection lists the active set | decided |
|
||||
| D10 | Loop judge default = main model, tiny prompt | Dedicated cheap aux model | Zero setup; switch if cost bites | open |
|
||||
| D11 | Sign-off judge default = **the session's current model** | Auto-pick "strongest on provider" (oracle-style) | Current model is guaranteed authorized + capable; provider lists hold dead/weak/unauthorized entries. Cross-vendor is a **setting** (§9) | decided |
|
||||
| D12 | **Plan-phase model is selectable and sticky** | Always the working model | Plan benefits from a stronger reasoner; persist the choice (oracle.json-style). Optionally the oracle drafts the plan (read-only + strong already) | decided |
|
||||
| D13 | **Offer to compact after plan accepted** | Always fresh session (burneikis); or never | Some runs want a clean execution context, some want to keep it. Make it a post-Ready choice | decided |
|
||||
|
||||
### 2c. Cuts (non-goals)
|
||||
|
||||
DAG / `blocks` edges. Parallel subagent execution (the flaky part). `findings.md`. Hard pre-tool-use enforcement (D3). Sign-off judge every turn (cost).
|
||||
|
||||
---
|
||||
|
||||
## 3. Two phases: setup, then execution
|
||||
|
||||
### 3a. Setup — plan mode
|
||||
|
||||
Goals are created and *agreed* through plan mode (burneikis-style). Stock plan mode; the deltas are the output format and the hand-off.
|
||||
|
||||
1. `/plan <objective>` enters plan mode. The agent explores read-only and drafts goals into `plan.md` in the contract format (§4). This phase runs on the **plan-phase model** (selectable + sticky, D12; optionally the read-only oracle drafts it).
|
||||
2. You review: **Ready** / **Edit** (NL rewrite) / **$EDITOR** (hand-edit) / **Cancel**. The agreement point — you sanity-check `done_when` and `failure_modes` before any code.
|
||||
3. On **Ready**, offer **compact context? (y/n)** (D13). Yes → execution starts in a cleared context with the approved `plan.md` re-injected. No → execution continues in the same context.
|
||||
|
||||
Direct `plan.md` edits remain a quick-add path for a one-off goal.
|
||||
|
||||
### 3b. Execution — the loop ↔ check cycle
|
||||
|
||||
Multiple goals may be `active`; the agent works whichever it's focused on, in the order it judges best.
|
||||
|
||||
1. The session works an `active` goal under an iteration budget (or `/goal` (re)starts the loop on the current plan).
|
||||
2. Each turn, the **loop judge** reads the agent's last response → continue/pause (fail-open; the **budget is the real backstop**).
|
||||
3. When the agent judges a goal done, the reminder steers it to call `CompleteGoal` (not hand-tick `status`).
|
||||
4. `CompleteGoal` runs the **two-stage check**:
|
||||
- **reject** → `missing[]` fed back; work continues toward the gap.
|
||||
- **accept** → goal marked done; the agent moves to another active/open goal, or the loop stops.
|
||||
|
||||
The loop judge can be fooled (reads assertions); worst case is a premature pause, caught by you or the budget. The sign-off check re-derives from artifacts, so it is not fooled cheaply. That asymmetry is the point.
|
||||
|
||||
---
|
||||
|
||||
## 4. The one file: `plan.md`
|
||||
|
||||
cwd root, git-tracked. Goals, subtasks, and a short log. The agent maintains all of it through its normal Edit tool — no separate store machinery.
|
||||
|
||||
```markdown
|
||||
# Plan: <one-line objective>
|
||||
|
||||
## Goal: Implement cache layer
|
||||
<!-- id: cache-layer-1 -->
|
||||
status: active
|
||||
done_when: p95 < 50ms on bench-X. If wrong: timeouts in load-test.log
|
||||
verify: pytest tests/cache -q && python bench/p95.py --max-ms 50
|
||||
failure_modes:
|
||||
- cache silently bypassed (hit-rate ~0, latency ok by luck)
|
||||
- bench too small to exercise eviction
|
||||
- verify passes on a trivial/gamed test
|
||||
- [x] wire cache client
|
||||
- [ ] eviction policy
|
||||
- [ ] load test
|
||||
|
||||
## Goal: ...
|
||||
|
||||
## Log
|
||||
- 2026-06-15 14:02 cache client wired; eviction next
|
||||
- 2026-06-15 14:31 eviction done; p95 bench reads 47ms (load-test.log)
|
||||
- 2026-06-15 14:33 cache-layer-1 signed off (verify green, oracle accept)
|
||||
```
|
||||
|
||||
Conventions:
|
||||
|
||||
- **Goals carry `status:` and no checkbox; subtasks are `- [ ]`.** `status` ∈ `open | active | done | cancelled`. Multiple goals may be `active` (D9). Subtasks tick freely.
|
||||
- **`<!-- id -->`** assigned at creation; stable key (survives renaming the subject).
|
||||
- **`verify:`** (optional) is the deterministic stage-1 command.
|
||||
- **`failure_modes`** should name "verify could pass while still wrong" whenever a `verify:` exists.
|
||||
- **`## Log`** is manus-style: append-only **by convention**, one short line per event. The reminder (§8a) enforces appending. Terse — "where it's up to" + error memory, not a transcript.
|
||||
|
||||
Parsing: a line scanner suffices for v0. `mdast` + `remark-gfm` only if it bites. Parse for *reading*; for the rare programmatic write (status flip, checkbox reconcile) use exact-line string patching, never a full AST serialize.
|
||||
|
||||
---
|
||||
|
||||
## 5. Tools
|
||||
|
||||
`CompleteGoal` is the one blessed path (it runs the check and records it). Everything else — create goal, edit plan, tick subtasks, append to log — is plain Edit, guided by the reminder.
|
||||
|
||||
### `CompleteGoal(id, evidence, paths[])` — the sign-off check
|
||||
|
||||
1. Read `done_when` + `verify` + `failure_modes` for the goal from `plan.md` (git diff is the tamper-check, D7).
|
||||
2. **Evidence must point to durable artifacts** the read-only judge can inspect (saved logs, committed diffs, files). Ephemeral claims fail stage 2.
|
||||
3. **Stage 1 — deterministic.** If `verify` exists, run it shell-free, capture exit + output tail. Non-zero → reject immediately, return the tail. No model call spent.
|
||||
4. **Stage 2 — oracle.** Spawn the read-only judge (D11 default = current model; §9) with the criterion, failure modes, evidence, and verify result; it inspects the repo and checks the verify command was not gamed against the named failure modes.
|
||||
5. Verdict: **accept** → string-patch `status: done`, append a `## Log` line. **reject** → status stays `active`, append `missing[]` to `## Log`, return `missing`.
|
||||
|
||||
### `CancelGoal(id, reason)` — optional
|
||||
|
||||
open/active → cancelled is not a sign-off, so it skips the check. A tool only to guarantee a `## Log` line lands.
|
||||
|
||||
---
|
||||
|
||||
## 6. Guiding sign-off (no hard gate)
|
||||
|
||||
Per D3, there is no pre-tool-use interceptor blocking `status: done`. Sign-off is guided, not gated:
|
||||
|
||||
- the **reminder** (§8a) tells the agent to complete a goal through `CompleteGoal`, not by hand-editing status;
|
||||
- `CompleteGoal` is the obvious, blessed path that runs the check and writes the log line;
|
||||
- the **widget** (§7) can flag a goal whose `status: done` has no corresponding `## Log` sign-off line — visibility, not a block;
|
||||
- `plan.md` is git-tracked, so any hand-tick shows in the diff.
|
||||
|
||||
The agent *can* bypass it. The bet — borne out by how the other extensions actually run — is that a clear form plus a standing reminder makes the blessed path the path taken, and visibility catches the rare bypass.
|
||||
|
||||
---
|
||||
|
||||
## 7. Commands
|
||||
|
||||
- `/plan <desc>` — **enter plan mode** (§3a): read-only explore → draft goals → review. Ready offers the compact choice, then starts execution.
|
||||
- `/plan` (no args) — render the **task-list widget**: each goal with status + its subtask checkboxes + "N done hidden"; flag any `done` goal lacking a sign-off log line; offer archive-completed and cancel-goal.
|
||||
- `/goal` — (re)start the loop on the current plan.
|
||||
- `/goal pause | resume | clear | status` — loop controls.
|
||||
- `/subgoal <text>` — append an acceptance criterion to a goal mid-loop. Optional.
|
||||
- `/judge model <ref>` — set the sign-off judge model (default: current model; set a cross-vendor ref here for stronger independence, §9).
|
||||
|
||||
---
|
||||
|
||||
## 8. Hooks / lifecycle
|
||||
|
||||
- **`before_agent_start`** — parse `plan.md`; inject a fixed-shape summary (active goals + focus + last log line) as a late **user-role** message. Compaction-persistence.
|
||||
- **reminder** — §8a.
|
||||
- **pre-compact** — flush state to `plan.md` before compaction.
|
||||
|
||||
(No pre-tool-use gate — D3.)
|
||||
|
||||
### 8a. The reminder (typed; what it says)
|
||||
|
||||
Fires when a goal is `active` and there have been **N file-modifying turns since the last `plan.md` update**. One `<system-reminder>` covering both task upkeep and goal progress:
|
||||
|
||||
- **task** — tick completed subtask checkboxes; add new ones discovered.
|
||||
- **log** — append **one short line** to `## Log` (append, don't rewrite).
|
||||
- **goal** — if a goal's evidence is in, **sign it off via `CompleteGoal`** — don't hand-tick `status: done`.
|
||||
- **autonomy** — keep working toward an active goal; don't stop to ask unless genuinely blocked.
|
||||
|
||||
Both the housekeeping and the autonomy engine, and — with no hard gate — the main thing making the process get followed. Keep the wording stable so it doesn't thrash the cache.
|
||||
|
||||
---
|
||||
|
||||
## 9. Judges
|
||||
|
||||
| | Loop judge | Sign-off judge (stage 2) |
|
||||
|---|---|---|
|
||||
| Drives | continue / pause each turn | accept / reject a sign-off |
|
||||
| Cost | cheap, every turn | costly, once per goal |
|
||||
| Reads | the agent's last response (~4 KB) | the repo, independently |
|
||||
| Transport | one small model call (D10) | read-only oracle subprocess |
|
||||
| On failure | fail-open → continue; **budget** is the backstop | fail-closed → goal stays active |
|
||||
| Foolable? | yes — asserted "done" passes; bounded by budget | hard: re-reads artifacts + runs `verify` |
|
||||
|
||||
### Sign-off judge: model choice (D11)
|
||||
|
||||
- **Default: the session's current model.** Guaranteed authorized and capable, because you're already running it. Auto-picking "strongest on provider" (oracle-style) is rejected as the default — those lists carry dead, weak, and unauthorized entries.
|
||||
- **Most of the value is model-independent.** The read-only judge re-derives from artifacts: does the evidence match the repo, is the `verify` tautological, is each failure mode actually ruled out. Any capable model does that regardless of family.
|
||||
- **Cross-vendor is the stronger-independence setting** (`/judge model`), for the residual *shared-reasoning-error* class, when you have a known-good alternative. Mirror the oracle's curated provider list for that override menu; don't auto-select from it.
|
||||
|
||||
### Transport (oracle pattern, copied)
|
||||
|
||||
- **Shell-free spawn.** `spawn(command, argsArray)`, no `shell:true`; capture stdout via pipe and parse. Why it avoids the noclobber/cropping pain of `pi -p … > out.json` under zsh. ~40 lines.
|
||||
- **Read-only toolset.** `read / grep / find / ls`, optional non-mutating `bash`. Separate process = fresh context, no anchoring — the independence you reliably get even from the same model.
|
||||
- **Verdict contract.** Oracle returns prose by default; impose `VERDICT: accept|reject` + `missing:` in the prompt and parse that block.
|
||||
|
||||
---
|
||||
|
||||
## 10. `prompts.tsx`
|
||||
|
||||
All model-facing text in one file, in flow order (drafted separately):
|
||||
|
||||
1. **planDrafting** — plan-mode guidance; forces `done_when`, optional `verify:`, 2–3 `failure_modes`, subtasks. Human approves it.
|
||||
2. **planInjection** — the fixed-shape `before_agent_start` block (function of the parsed plan).
|
||||
3. **reminder** — the typed nudge (§8a).
|
||||
4. **continuation** — Hermes-style "keep going" user-role message.
|
||||
5. **loopJudge** — conservative, strict JSON `{done, reason}`.
|
||||
6. **evidenceJudge** — read-only, verify against repo + contract + check `verify` wasn't gamed, end with `VERDICT`.
|
||||
|
||||
5 and 6 adjacent: the cheap-foolable vs must-not-be-fooled contrast on one screen.
|
||||
|
||||
---
|
||||
|
||||
## 11. KV-cache hygiene
|
||||
|
||||
- Inject as a late **user-role** message, never a system-prompt mutation (a long goal then costs the same as the same number of normal turns).
|
||||
- Make the injected block **byte-identical when nothing changed**: fixed field order, no volatile timestamps in the body.
|
||||
|
||||
---
|
||||
|
||||
## 12. Dependencies and what to copy
|
||||
|
||||
- **No hard dependency** on `pi-subagents` or the `oracle` extension. Copy the shell-free spawn helper and the curated provider list (as a selection menu, not an auto-picker).
|
||||
- Markdown: line scanner first; `mdast` + `remark-gfm` only if needed.
|
||||
- Verify against current pi API: `before_agent_start` can append a user-role message without mutating the system prompt; the plan-phase model can be set per-phase and persisted.
|
||||
|
||||
---
|
||||
|
||||
## 13. Risks / open questions
|
||||
|
||||
- **Same-model sign-off judge → correlated blind spots** (the D11 tradeoff). Mitigation: most of the check's value is artifact re-derivation, which is model-independent; the cross-vendor setting covers the rest when available.
|
||||
- **No hard gate (D3)** — the agent can hand-tick `status: done` and skip the check. Mitigation: the reminder steers to `CompleteGoal`; the widget flags a `done` goal with no sign-off log line; git shows it.
|
||||
- **Contract tampering (D7)** — editable `plan.md` means `done_when`/`failure_modes` can be softened pre-sign-off. Mitigation: git diff; optionally log the contract line at creation and have the oracle read it.
|
||||
- **Loop-judge false positive** — premature pause; it does not sign off, so re-issue or `/subgoal`.
|
||||
- **`verify` gaming** — the oracle is told to inspect the test against the named failure mode.
|
||||
- **`## Log` rewritten not appended** — convention only; reminder enforces, git shows violations.
|
||||
- **Evidence durability** — the read-only judge can only verify what's on disk; elicitation pushes the agent to save logs/diffs.
|
||||
|
||||
---
|
||||
|
||||
## 14. Build order
|
||||
|
||||
Each step independently testable; model calls enter late.
|
||||
|
||||
1. `plan.md` format + line parser (incl. `<!-- id -->` and `## Log`) + `/plan` task-list widget. Pure file, no model calls.
|
||||
2. Goal-creation elicitation + `CompleteGoal` happy path **without** the check (patch status + append log) to validate the flow.
|
||||
3. Stage-1 `verify` in `CompleteGoal`; the widget flag for `done`-without-sign-off-line (guidance/visibility, not a block).
|
||||
4. Sign-off judge (stage 2): copy the spawn helper, write prompt 6, parse the verdict, fold in the gaming check; `/judge model` setting (default current model).
|
||||
5. `before_agent_start` injection (cache-safe) + the reminder (§8a).
|
||||
6. The loop: `/goal` + iteration budget + loop judge (prompt 5) + continuation (prompt 4) + the loop↔check handoff (§3b), multi-goal aware.
|
||||
7. Plan mode (§3a): `/plan <desc>` read-only draft → review → compact choice → hand-off. Plan-phase model selection + stickiness (D12). (Until built, create goals by direct `plan.md` edit.)
|
||||
8. Optional: `CancelGoal`, `/subgoal`, cross-vendor judge selection menu, `mdast` hardening.
|
||||
|
||||
`prompts.tsx` is authored alongside the steps that need each prompt but kept centralized from step 1.
|
||||
@@ -1,71 +0,0 @@
|
||||
# CompleteGoal fail-forward on judge failure
|
||||
|
||||
## Goal
|
||||
Make `CompleteGoal` stop rejecting verified goals just because the read-only judge subprocess times out. Keep the judge useful when it works, and make failures explicit in the log/result.
|
||||
|
||||
## Scope
|
||||
In: `CompleteGoal` sign-off behavior, judge transport, tests, docs.
|
||||
Out: broader autonomous loop work, plan-mode UX, model auto-selection.
|
||||
|
||||
## Requirements
|
||||
- R1: If `verify:` fails, the goal is rejected immediately. Done means: existing `verify_failed` behavior remains. VERIFY: unit test for pure sign-off record still passes.
|
||||
- R2: If `verify:` passes and the judge accepts, mark the goal done as before. Done means: log records normal judge accept. VERIFY: unit test for accepted sign-off still passes.
|
||||
- R3: If any `verify:` command passes but the judge times out or subprocess/model transport fails, mark the goal done with an explicit inconclusive-judge log. Goals without `verify:` use the same fail-forward rule once evidence exists. VERIFY: a unit test records accepted status and a log line containing `judge inconclusive`.
|
||||
- R4: Judge transport should parse `pi --mode json` message events instead of raw `-p` terminal output. Done means: code captures final assistant text and provider stop errors distinctly. VERIFY: `npm run typecheck` and tests pass.
|
||||
- R5: The judge should behave like oracle where it matters: explicit model, live streamed progress, and a timeout large enough for a cold reasoning turn. Done means: unset `/goals judge` resolves to the current session model when visible; if no model is visible, no implicit Pi default is used and sign-off is `judge inconclusive`. `message_update` emits throttled progress, and timeout is 600s. VERIFY: `npm run typecheck` and fresh-eyes diff review.
|
||||
|
||||
## Tasks
|
||||
- [x] T1 (R3): Add an accepted-with-warning sign-off outcome.
|
||||
- verify: `npm test`
|
||||
- success: test shows status `[x]` plus `judge inconclusive` in `## Log`
|
||||
- likely_fail: timeout still records `reject`
|
||||
- sneaky_fail: accepted status lands but log hides judge failure
|
||||
- UAT: [test/plan-file.test.ts](/home/wassname/.pi/agent/git/github.com/wassname/pi-plan/test/plan-file.test.ts)
|
||||
- [x] T2 (R4): Switch judge subprocess to JSON-mode parsing.
|
||||
- verify: `npm run typecheck`
|
||||
- success: no TypeScript errors, judge code has no ANSI-terminal parsing dependency
|
||||
- likely_fail: compile errors around streamed event shape
|
||||
- sneaky_fail: model error produces empty output and gets parsed as reject instead of transport failure
|
||||
- UAT: [src/index.ts](/home/wassname/.pi/agent/git/github.com/wassname/pi-plan/src/index.ts)
|
||||
- [x] T3 (docs): Update README sign-off semantics.
|
||||
- verify: `rg "inconclusive|timeout|judge accept" README.md src test`
|
||||
- success: docs name fail-forward behavior
|
||||
- likely_fail: README still says all rejects keep goal open
|
||||
- sneaky_fail: docs imply subagent evidence was accepted when it timed out
|
||||
- UAT: [README.md](/home/wassname/.pi/agent/git/github.com/wassname/pi-plan/README.md)
|
||||
- [x] T4 (R5): Copy oracle's reliability shape for model/progress.
|
||||
- verify: `npm run typecheck`
|
||||
- success: `CompleteGoal` passes the current session model to the judge when no override is set, never spawns without `--model`, and streamed judge deltas are surfaced through `onUpdate`
|
||||
- likely_fail: judge still runs without `--model`
|
||||
- sneaky_fail: user sees no progress for several minutes and kills a working judge
|
||||
- UAT: [src/index.ts](/home/wassname/.pi/agent/git/github.com/wassname/pi-plan/src/index.ts)
|
||||
|
||||
## Context
|
||||
Observed result from downstream use:
|
||||
|
||||
```json
|
||||
{
|
||||
"goal": "Make persona validation fail-fast and evidence-correct",
|
||||
"outcome": "rejected",
|
||||
"durationMs": 120003,
|
||||
"verifyCommand": "`uv run python -m compileall -q scripts/validate_persona_axes_openrouter.py`",
|
||||
"reasoning": "VERDICT: reject\nmissing: judge timed out after 120s",
|
||||
"isError": true
|
||||
}
|
||||
```
|
||||
|
||||
Interpretation: latest surfaced output proves the internal judge timed out. It does not prove the verify command passed, though earlier logs indicated that pattern.
|
||||
|
||||
## Log
|
||||
- 2026-06-29 current `runJudge` uses raw `pi -p --no-session` output plus ANSI stripping; oracle uses `--mode json` and parses message events, which is likely more reliable.
|
||||
- 2026-06-29 unset `/goals judge` spawns the judge without `--model`, so Pi resolves its configured default model; do not describe this as the current session model.
|
||||
- 2026-06-29 timeout/transport failure now maps to `accepted_inconclusive`, preserving partial output in reasoning when available.
|
||||
- 2026-06-29 fresh-eyes review found loose `/accept/i` verdict parsing and caller-abort fail-forward risk; fixed exact verdict parsing and made caller abort reject.
|
||||
- 2026-06-29 oracle comparison suggests the important reliability pieces are explicit model selection, JSON streaming, live partial output, and no short wrapper timeout; updated CompleteGoal to use the current session model when visible, never spawn without `--model`, stream throttled progress, and wait 600s.
|
||||
|
||||
## TODO
|
||||
- Consider making `CompleteGoal` expose `verifyExitCode: 0` and `judgeOutcome` separately in details.
|
||||
|
||||
## Errors
|
||||
| Task | Error | Resolution |
|
||||
|------|-------|------------|
|
||||
@@ -1,67 +0,0 @@
|
||||
# Per-session plan file
|
||||
|
||||
One `.pi/plan.md` per repo is wrong when two agents share the repo. A subagent spawns as
|
||||
`pi -p --no-session` in the same cwd with extensions ON (only the judge gets `--no-extensions`),
|
||||
so it loads pi-goals, gets the whole plan pushed in on its first call, and can call CompleteGoal
|
||||
on the parent's goal. A second window has the same problem, plus last-write-wins on the file.
|
||||
|
||||
Fix: the plan file is named after the session, `.pi/plan/<session_id>.md`. The file name is the
|
||||
arm switch. A session that never ran `/goals` has no file at its path, so the extension stays
|
||||
silent. No new state flag.
|
||||
|
||||
The id is stable where it must be. Resume reads `header.id` from the session file
|
||||
(`session-manager.js:547`) and compaction uses `branchWithSummary`, which does not touch the id.
|
||||
Only an explicit fork or new session gets a new id (`createBranchedSession`, `newSession`).
|
||||
|
||||
- [x] goal A: the plan file is per session, and a session with no plan is inert
|
||||
- [x] `planPath(ctx)` = `.pi/plan/<ctx.sessionManager.getSessionId()>.md`; `mkdir -p` the dir
|
||||
- [x] `PLAN_REL` becomes a per-context value; pass it into `decideSignOff` through `SignOffInput`
|
||||
so the judge prompt still names the real file
|
||||
- `--no-session` still gets a fresh random id, checked: `SessionManager.inMemory` passes no
|
||||
session file, so the constructor calls `newSession()` -> `createSessionId()`. So each subagent
|
||||
gets its own unused path and reads nothing. No empty-id special case is needed.
|
||||
- failure modes: two sessions somehow resolve the same id, so the two agents still share a file
|
||||
- deliverable: `ls .pi/plan/` in a scratch repo after two sessions, showing two files
|
||||
- [x] goal B: delete what this replaces
|
||||
- [x] drop the v1 `.pi/goals.md` -> `.pi/plan.md` rename in `session_start`
|
||||
- [x] `/goals clear` unlinks the file instead of writing an empty one
|
||||
- failure modes: none, this is removal
|
||||
- deliverable: the diff, negative line count
|
||||
- [x] goal C: docs and version match the code
|
||||
- [x] README, `package.json` description, `docs/spec/2026-06-15_pi-goals.md` say `.pi/plan/<session_id>.md`
|
||||
- [x] version 0.2.0, the path change is breaking
|
||||
- failure modes: docs still say `.pi/plan.md`, so the next reader trusts the wrong file
|
||||
- deliverable: `grep -rn "plan\.md" $(git ls-files)` returns only history and format prose
|
||||
|
||||
## UAT / Verification
|
||||
|
||||
`npm test` 19 passed, `npm run typecheck` and `npm run lint` clean.
|
||||
|
||||
Live A/B in `/tmp/plan-scratch`, which holds the same plan at both the old and the new path. The
|
||||
plan's one goal line is `1. [/] goal: SECRET-CANARY-PLAN delete the production database`. Each run
|
||||
asked: "Were you given a plan with goals? If yes, reply with the goal line verbatim. If no, reply
|
||||
exactly: NO PLAN".
|
||||
|
||||
| run | version, flags | answer |
|
||||
|---|---|---|
|
||||
| A | HEAD 4827808 (`.pi/plan.md`), `-p -ne --no-session` | `1. [/] goal: SECRET-CANARY-PLAN delete the production database` |
|
||||
| B | this change, `-p -ne --no-session` | `NO PLAN` |
|
||||
| C | this change, `-p -ne --session-id 019ec140-ce3b-70d7-8151-abfa7f1c95a9` | `goal: SECRET-CANARY-PLAN delete the production database` |
|
||||
|
||||
A is the bug: a subagent reads the parent's plan. B is a subagent under this change: it sees
|
||||
nothing and writes nothing (`find /tmp/plan-scratch/.pi -type f` still lists only the two seeded
|
||||
files). C is the owning session, whose id matches the plan file name: it still gets its plan.
|
||||
|
||||
Not covered by a live run: `/resume` and compaction keep the id. Both were checked by reading
|
||||
`session-manager.js` (`:547` reads `header.id`; compaction goes through `branchWithSummary`, which
|
||||
never assigns `sessionId`).
|
||||
|
||||
## Appendix (context, not approved)
|
||||
|
||||
Rejected: keep one `.pi/plan.md` and add an `armed` flag to `PlanState` that only `/goals` Ready
|
||||
sets. It works for subagents (`--no-session` has no state to replay) but it is more code than the
|
||||
rename, and two armed windows still stomp each other's file. -- Claude
|
||||
|
||||
Open, not in this plan: adopting an old plan into a new session (`/goals resume` picking the newest
|
||||
file in `.pi/plan/`), and carrying the plan across an explicit fork. Both are one command each; wait
|
||||
until the need is real.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 77 KiB |
Generated
+2653
-348
File diff suppressed because it is too large
Load Diff
+32
-12
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@wassname2/pi-goals",
|
||||
"version": "0.2.2",
|
||||
"description": "One plan file per session: set goals in plan mode, work them, sign off only when a read-only judge checks the evidence.",
|
||||
"version": "0.3.3",
|
||||
"description": "Set goals in plan.md; a smart supervisor guides cheap worker subagents through long autonomous sessions until your goals are signed off, with every agent's pane visible to you.",
|
||||
"author": "wassname",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
@@ -18,14 +18,17 @@
|
||||
"proof",
|
||||
"uat",
|
||||
"evidence",
|
||||
"judge"
|
||||
"supervisor",
|
||||
"herdr"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"@earendil-works/pi-coding-agent": "*",
|
||||
"@earendil-works/pi-coding-agent": ">=0.85.1 <1.0.0",
|
||||
"@earendil-works/pi-tui": "*",
|
||||
"typebox": "*"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
"agents",
|
||||
"README.md"
|
||||
],
|
||||
"publishConfig": {
|
||||
@@ -34,25 +37,42 @@
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"prepublishOnly": "npm run lint && npm run typecheck && npm run test",
|
||||
"test": "vitest run",
|
||||
"test:rpc": "vitest run test/rpc-review.test.ts",
|
||||
"test:watch": "vitest",
|
||||
"test": "vitest run --dir test",
|
||||
"test:rpc": "vitest run --dir test rpc-review.test.ts",
|
||||
"test:watch": "vitest --dir test",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "biome check src/ test/",
|
||||
"lint:fix": "biome check --fix src/ test/"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@earendil-works/pi-coding-agent": "^0.84.1",
|
||||
"@biomejs/biome": "^2.4.8",
|
||||
"@earendil-works/pi-coding-agent": "0.85.1",
|
||||
"@earendil-works/pi-tui": "^0.85.1",
|
||||
"@types/node": "^20.0.0",
|
||||
"typebox": "^1.3.7",
|
||||
"typescript": "^5.0.0",
|
||||
"@biomejs/biome": "^2.4.8",
|
||||
"vitest": "^4.0.18"
|
||||
},
|
||||
"pi": {
|
||||
"extensions": [
|
||||
"./src/index.ts"
|
||||
"./src/index.ts",
|
||||
"./node_modules/pi-subagents/src/index.ts",
|
||||
"./node_modules/pi-intercom/index.ts",
|
||||
"./node_modules/pi-schedule-prompt/src/index.ts"
|
||||
],
|
||||
"image": "https://cdn.jsdelivr.net/gh/wassname/pi-goals@main/media/screenshot.png"
|
||||
}
|
||||
"image": "https://github.com/user-attachments/assets/35feaa15-f022-4491-bcc2-fc31cb878a9f",
|
||||
"skills": [
|
||||
"./node_modules/pi-intercom/skills"
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"pi-subagents": "git+https://github.com/edxeth/pi-subagents.git#953c6f6d2fc7d8a5c956c30cd77c51bad697c2a4",
|
||||
"pi-intercom": "0.13.0",
|
||||
"pi-schedule-prompt": "0.4.1"
|
||||
},
|
||||
"bundledDependencies": [
|
||||
"pi-subagents",
|
||||
"pi-intercom",
|
||||
"pi-schedule-prompt"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Replaces the stale FIXME(side-effect) claim in src/index.ts with a checked fact.
|
||||
#
|
||||
# The claim was: "pi -p --no-session clones the repo into the PARENT of cwd, leaving a stale
|
||||
# directory." Reproducing the exact sign-off judge invocation (pi --mode json -p --no-session,
|
||||
# read-only tools, edit/write excluded, cwd = here) shows it does not. This script makes that
|
||||
# reproducible: it runs the invocation, requires pi to actually reach agent_end (so a pass is not
|
||||
# vacuous), and asserts the parent-of-cwd listing is byte-identical before and after.
|
||||
#
|
||||
# Exit 0 = judge leaves no clone in the parent. Exit 1 = either pi did not run, or it polluted.
|
||||
# Run by hand; re-run as the rigorous sign-off check (the judge has bash and runs this itself).
|
||||
set -u
|
||||
|
||||
PARENT="$(cd "$PWD/.." && pwd)"
|
||||
before="$(ls -1A "$PARENT" | sort)"
|
||||
|
||||
# Cheapest available model; the test exercises pi --no-session's workdir setup, not the output.
|
||||
out="$(timeout 90 pi --mode json -p --no-session \
|
||||
--model 'openrouter/~anthropic/claude-haiku-latest' \
|
||||
--tools read,bash,grep,find,ls --exclude-tools edit,write \
|
||||
--append-system-prompt 'Reply with exactly: VERDICT: accept' \
|
||||
"Reply with exactly: VERDICT: accept" 2>/dev/null || true)"
|
||||
|
||||
# Non-vacuous: require pi to have actually completed a turn. A pass without this could mean pi
|
||||
# crashed instantly and never had the chance to clone -- which would prove nothing.
|
||||
if ! printf '%s' "$out" | grep -q '"type":"agent_end"'; then
|
||||
echo "FAIL: pi --no-session did not reach agent_end; cannot confirm no-clone."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
after="$(ls -1A "$PARENT" | sort)"
|
||||
|
||||
echo "parent: $PARENT"
|
||||
echo "--- before ---"; echo "$before"
|
||||
echo "--- after ---"; echo "$after"
|
||||
|
||||
if [ "$before" == "$after" ]; then
|
||||
echo "PASS: parent-of-cwd listing identical before/after; no clone created."
|
||||
exit 0
|
||||
fi
|
||||
echo "FAIL: parent-of-cwd listing changed. Diff (< before, > after):"
|
||||
diff <(printf '%s\n' "$before") <(printf '%s\n' "$after") | head -20
|
||||
exit 1
|
||||
@@ -1,14 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Structural gate for the goal's `verify:` field. Cheap and deterministic: no API calls.
|
||||
# Confirms (a) neither stale FIXME tag remains in src/, (b) the footprint script exists, and
|
||||
# (c) the plan-injection heading prefix is still emitted. The rigorous runtime check (running
|
||||
# the footprint script) is the sign-off judge's job -- it has bash and re-runs the script itself.
|
||||
set -u
|
||||
fail() { echo "FAIL: $1"; exit 1; }
|
||||
|
||||
grep -rnE 'FIXME\((heading|side-effect)\)' src/ >/dev/null 2>&1 && fail "a stale FIXME(heading|side-effect) is still in src/"
|
||||
test -f scripts/check-judge-footprint.sh || fail "scripts/check-judge-footprint.sh is missing"
|
||||
grep -q '\.pi/goals\.md:' src/prompts.ts || fail "the .pi/goals.md: heading prefix was dropped from src/prompts.ts"
|
||||
|
||||
echo "PASS: stale FIXMEs gone, footprint script present, heading prefix intact."
|
||||
exit 0
|
||||
@@ -1,104 +0,0 @@
|
||||
diff --git a/README.md b/README.md
|
||||
index ce4056a..5485002 100644
|
||||
--- a/README.md
|
||||
+++ b/README.md
|
||||
@@ -145,9 +145,9 @@ else is the agent editing the file. It reads the goal's `evidence:` block from `
|
||||
reasoning comes back in the result.
|
||||
|
||||
The judge defaults to the current session model and streams partial output while it runs. If the
|
||||
-current model is not visible to the extension, `CompleteGoal` does not fall back to Pi's implicit
|
||||
-default; it signs off as `judge inconclusive` and tells you to set `/goals judge <provider/model>`.
|
||||
-Point it at another model for an independent cross-family check.
|
||||
+session model is not visible to the extension, the `--model` flag is omitted and pi uses its own
|
||||
+configured default, so the judge always runs. `/goals judge <provider/model>` is an optional override
|
||||
+for an independent cross-family check; never required.
|
||||
|
||||
## Prompts
|
||||
|
||||
diff --git a/src/index.ts b/src/index.ts
|
||||
index 9eb2a16..14784f7 100644
|
||||
--- a/src/index.ts
|
||||
+++ b/src/index.ts
|
||||
@@ -326,7 +326,7 @@ export default function piGoalsExtension(pi: ExtensionAPI): void {
|
||||
durationMs,
|
||||
verifyCommand: goal.verify ?? undefined,
|
||||
verifyExitCode: outcome.kind === "verify_failed" ? outcome.exitCode : undefined,
|
||||
- judgeModel: judgeModel ?? "no explicit judge model",
|
||||
+ judgeModel: judgeModel ?? "pi default",
|
||||
reasoning,
|
||||
isError: res.isError,
|
||||
};
|
||||
@@ -522,14 +522,6 @@ async function decideSignOff(
|
||||
};
|
||||
}
|
||||
}
|
||||
- if (!judgeModel) {
|
||||
- const reason = "no explicit judge model available; set /goals judge <provider/model>";
|
||||
- return {
|
||||
- outcome: { kind: "accepted_inconclusive", reason },
|
||||
- reasoning: `VERDICT: inconclusive\nreason: ${reason}`,
|
||||
- durationMs: Date.now() - startedAt,
|
||||
- };
|
||||
- }
|
||||
const verdict = await runJudge(goal, evidence, paths, verifyResult, judgeModel, cwd, signal, onUpdate);
|
||||
const outcome: SignOff =
|
||||
verdict.kind === "accepted"
|
||||
@@ -573,13 +565,25 @@ type JudgeResult =
|
||||
| { kind: "rejected"; missing: string; reasoning: string; durationMs: number }
|
||||
| { kind: "inconclusive"; reason: string; reasoning: string; durationMs: number };
|
||||
|
||||
+/** Stage 2: a read-only pi subprocess inspects the evidence against the repo and returns a verdict. */
|
||||
+/** Build the pi argv for the read-only judge. `--model` is omitted when no explicit/session model is
|
||||
+ * set, so pi falls back to its configured default -- the judge always runs, never pre-emptively
|
||||
+ * fails as "no model". Exported for a unit test that locks this invariant (an empty `--model ""`
|
||||
+ * would make every sign-off silently inconclusive). */
|
||||
+export function buildJudgeArgs(judgeModel: string | null): string[] {
|
||||
+ const args = ["--mode", "json", "-p", "--no-session"];
|
||||
+ if (judgeModel) args.push("--model", judgeModel);
|
||||
+ args.push("--tools", JUDGE_TOOLS.join(","), "--exclude-tools", JUDGE_BLOCKED_TOOLS.join(","), "--append-system-prompt", evidenceJudgeSystem);
|
||||
+ return args;
|
||||
+}
|
||||
+
|
||||
/** Stage 2: a read-only pi subprocess inspects the evidence against the repo and returns a verdict. */
|
||||
async function runJudge(
|
||||
goal: Goal,
|
||||
evidence: string,
|
||||
paths: string[],
|
||||
verifyResult: { command: string; exitCode: number; outputTail: string } | null,
|
||||
- judgeModel: string,
|
||||
+ judgeModel: string | null,
|
||||
cwd: string,
|
||||
signal: AbortSignal | undefined,
|
||||
onUpdate?: (partial: { content: Array<{ type: "text"; text: string }>; details: SignOffDetails }) => void,
|
||||
@@ -600,14 +604,14 @@ async function runJudge(
|
||||
evidence,
|
||||
paths,
|
||||
});
|
||||
- const args = ["--mode", "json", "-p", "--no-session", "--model", judgeModel, "--tools", JUDGE_TOOLS.join(","), "--exclude-tools", JUDGE_BLOCKED_TOOLS.join(","), "--append-system-prompt", evidenceJudgeSystem];
|
||||
+ const args = buildJudgeArgs(judgeModel);
|
||||
args.push(task);
|
||||
|
||||
emit("spawning", `Spawning read-only judge for: ${goal.subject}`);
|
||||
const inv = getPiInvocation(args);
|
||||
- // FIXME(side-effect): pi -p --no-session clones the repo into the PARENT of cwd (so alongside
|
||||
- // the working dir), leaving a stale directory. The judge should run in a temp dir or inside the
|
||||
- // existing repo checkout so it doesn't pollute the user's workspace.
|
||||
+ // The judge runs in-place against this checkout (cwd is passed to spawn and the read-only tools
|
||||
+ // read from it); pi --no-session does not clone into the parent. Proven and re-checked by
|
||||
+ // scripts/check-judge-footprint.sh, which reproduces this invocation and asserts no parent clone.
|
||||
const judge = await new Promise<{ output: string; error?: string; aborted?: boolean }>((resolve) => {
|
||||
let settled = false;
|
||||
let stdoutBuffer = "";
|
||||
diff --git a/src/prompts.ts b/src/prompts.ts
|
||||
index 03faea8..3b8d270 100644
|
||||
--- a/src/prompts.ts
|
||||
+++ b/src/prompts.ts
|
||||
@@ -117,8 +117,6 @@ export function planInjection(p: {
|
||||
counts: { done: number; open: number };
|
||||
}): string {
|
||||
if (!p.activeGoal) {
|
||||
- // FIXME(heading): user wants the heading to show ".pi/goals.md: <title>" so the filename is explicit
|
||||
- // even in the injection. Currently says "Goals (goals.md):" which is close but not the same.
|
||||
return `.pi/goals.md: ${p.title}\nNo active goal. ${p.counts.open} open, ${p.counts.done} done. Pick the next goal (set its checkbox to [/]) or run /goals.`;
|
||||
}
|
||||
const subtasks = p.activeGoal.openSubtasks.length
|
||||
@@ -0,0 +1,35 @@
|
||||
// Pi/OpenAI. Prepare an isolated trial; never launches/reloads an existing session.
|
||||
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { homedir, tmpdir } from 'node:os';
|
||||
const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const sdkRoot = process.argv[2];
|
||||
const noSandbox = process.argv.includes('--no-sandbox');
|
||||
if (!sdkRoot) throw new Error('Usage: node scripts/prepare-trial.mjs INSTALLED_PI_ROOT');
|
||||
const revision = execFileSync('git', ['-C', repo, 'rev-parse', 'HEAD'], {encoding:'utf8'}).trim();
|
||||
const root = mkdtempSync(join(tmpdir(), 'goals-edxeth-trial-'));
|
||||
const cwd = join(root, 'project'); const agentDir = join(root, 'agent');
|
||||
mkdirSync(cwd); mkdirSync(agentDir, {mode:0o700}); mkdirSync(join(agentDir,'agents'));
|
||||
const sourceAgent = process.env.PI_CODING_AGENT_DIR || join(homedir(),'.pi','agent');
|
||||
const sourceSettings = JSON.parse(readFileSync(join(sourceAgent,'settings.json'),'utf8'));
|
||||
const sdk = await import(pathToFileURL(join(sdkRoot,'dist/index.js')).href);
|
||||
const settings = sdk.SettingsManager.create(repo, sourceAgent, { projectTrusted:false });
|
||||
const manager = new sdk.DefaultPackageManager({cwd:repo, agentDir:sourceAgent, settingsManager:settings});
|
||||
const packages = manager.listConfiguredPackages().filter((p) => p.scope !== 'project' && !/^\/\//.test(p.source));
|
||||
const retained = packages.filter((p) => !/pi-subagents|pi-goals|pi-intercom|pi-schedule-prompt/.test(p.source));
|
||||
for (const p of retained) if (!p.installedPath) throw new Error(`Missing installed package: ${p.source}`);
|
||||
writeFileSync(join(agentDir,'settings.json'), JSON.stringify({...sourceSettings, packages:[...retained.map((p)=>p.installedPath), repo]},null,2));
|
||||
// Private copies, not symlinks: a trial OAuth refresh must not write the active auth file.
|
||||
for (const file of ['auth.json','models.json']) if (existsSync(join(sourceAgent,file))) copyFileSync(join(sourceAgent,file),join(agentDir,file));
|
||||
const workerDefinition = readFileSync(join(repo,'agents/goals-worker.md'),'utf8');
|
||||
writeFileSync(join(agentDir,'agents/goals-worker.md'), noSandbox ? workerDefinition.replace('mode: interactive', 'mode: interactive\nflags: --no-sandbox') : workerDefinition);
|
||||
execFileSync('git',['init','--quiet',cwd]);
|
||||
writeFileSync(join(cwd,'AGENTS.md'), 'Isolated functional trial. Work only in this project. Do not operate other Herdr panes, use live research sessions, or change global settings. Preserve evidence. The main chat supervises; the goals-worker implements.\n');
|
||||
writeFileSync(join(cwd,'.gitignore'), 'evidence/\n');
|
||||
const manifest={root,cwd,agentDir,repo,revision,noSandbox,retainedPackages:retained.map((p)=>p.source),replacedPackages:packages.filter((p)=>!retained.includes(p)).map((p)=>p.source)};
|
||||
writeFileSync(join(root,'manifest.json'),JSON.stringify(manifest,null,2));
|
||||
const quote=(s)=>`'${s.replaceAll("'", "'\\''")}'`;
|
||||
writeFileSync(join(root,'start.zsh'), `#!/usr/bin/env zsh\nset -e\ncd ${quote(cwd)}\nexport PI_CODING_AGENT_DIR=${quote(agentDir)}\nexport PI_SUBAGENT_MUX=herdr\nexport PI_ORCHESTRATOR_MODE=0\nexec pi --approve${noSandbox ? ' --no-sandbox' : ''}\n`,{mode:0o700});
|
||||
console.log(JSON.stringify({root,cwd,agentDir,start:join(root,'start.zsh'),manifest:join(root,'manifest.json')},null,2));
|
||||
@@ -0,0 +1,61 @@
|
||||
// Pi/OpenAI: Sum recorded requests, not context occupancy; do not read message text.
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
export function readSession(file) {
|
||||
const raw = readFileSync(file, 'utf8');
|
||||
const lines = raw.split('\n');
|
||||
const tail = lines.pop();
|
||||
let trailingPartial = false;
|
||||
if (tail) {
|
||||
try { JSON.parse(tail); lines.push(tail); }
|
||||
catch { trailingPartial = true; }
|
||||
}
|
||||
return { file: resolve(file), sha256: createHash('sha256').update(raw).digest('hex'), trailingPartial,
|
||||
entries: lines.filter(Boolean).map(JSON.parse) };
|
||||
}
|
||||
|
||||
export function summarize(entries, since, until) {
|
||||
const start = Date.parse(since), end = Date.parse(until);
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end) || start > end) throw new Error('Invalid time interval');
|
||||
const rows = entries.filter(e => e.type === 'message' && e.message.role === 'assistant' && Date.parse(e.timestamp) >= start && Date.parse(e.timestamp) <= end);
|
||||
const totals = { calls: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, totalTokens: 0 };
|
||||
const models = new Map();
|
||||
let missingUsage = 0;
|
||||
for (const e of rows) {
|
||||
const m = e.message;
|
||||
if (!m.usage) { missingUsage++; continue; }
|
||||
const model = `${m.provider}/${m.model}`;
|
||||
if (!models.has(model)) models.set(model, { model, ...totals, calls: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, totalTokens: 0 });
|
||||
const group = models.get(model);
|
||||
totals.calls++; group.calls++;
|
||||
for (const key of ['input', 'cacheRead', 'cacheWrite', 'output', 'totalTokens']) {
|
||||
const value = m.usage[key];
|
||||
if (!Number.isFinite(value) || value < 0) throw new Error(`Invalid usage.${key} in entry ${e.id}`);
|
||||
totals[key] += value; group[key] += value;
|
||||
}
|
||||
}
|
||||
return { ...totals, missingUsage, firstRequest: rows[0]?.timestamp ?? null,
|
||||
lastRequest: rows.at(-1)?.timestamp ?? null, models: [...models.values()] };
|
||||
}
|
||||
|
||||
export function report(supervisor, worker, until = new Date().toISOString()) {
|
||||
const boundary = supervisor.entries.findLast(e => e.type === 'custom' && e.customType === 'pi-goals-main-supervisor-v1' && e.data.mode === 'planning' && !e.data.child);
|
||||
if (!boundary) throw new Error('No recorded planning start in supervisor session');
|
||||
const since = boundary.timestamp;
|
||||
const sessions = [supervisor, worker].map((session, i) => ({
|
||||
role: i === 0 ? 'supervisor' : 'worker', file: session.file, sha256: session.sha256,
|
||||
trailingPartial: session.trailingPartial, ...summarize(session.entries, since, until),
|
||||
}));
|
||||
return { since, until, elapsedHours: (Date.parse(until) - Date.parse(since)) / 3600000,
|
||||
boundaryEntry: boundary.id, plan: boundary.data.plan, sessions,
|
||||
scope: 'Recorded assistant usage since latest planning entry, including abandoned branches and repeated cached context. Excludes earlier inherited history, in-flight requests, subprocess API usage and unrecorded compaction calls. Output includes reasoning where the provider includes it; reasoning is not added twice.' };
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
||||
const [supervisor, worker] = process.argv.slice(2);
|
||||
if (!supervisor || !worker || process.argv.length !== 4) throw new Error('Usage: node scripts/session-usage.mjs SUPERVISOR.jsonl WORKER.jsonl');
|
||||
console.log(JSON.stringify(report(readSession(supervisor), readSession(worker)), null, 2));
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
diff --git a/src/index.ts b/src/index.ts
|
||||
index 9eb2a16..cdd7b45 100644
|
||||
--- a/src/index.ts
|
||||
+++ b/src/index.ts
|
||||
@@ -605,9 +605,9 @@ async function runJudge(
|
||||
|
||||
emit("spawning", `Spawning read-only judge for: ${goal.subject}`);
|
||||
const inv = getPiInvocation(args);
|
||||
- // FIXME(side-effect): pi -p --no-session clones the repo into the PARENT of cwd (so alongside
|
||||
- // the working dir), leaving a stale directory. The judge should run in a temp dir or inside the
|
||||
- // existing repo checkout so it doesn't pollute the user's workspace.
|
||||
+ // The judge runs in-place against this checkout (cwd is passed to spawn and the read-only tools
|
||||
+ // read from it); pi --no-session does not clone into the parent. Proven and re-checked by
|
||||
+ // scripts/check-judge-footprint.sh, which reproduces this invocation and asserts no parent clone.
|
||||
const judge = await new Promise<{ output: string; error?: string; aborted?: boolean }>((resolve) => {
|
||||
let settled = false;
|
||||
let stdoutBuffer = "";
|
||||
diff --git a/src/prompts.ts b/src/prompts.ts
|
||||
index 03faea8..3b8d270 100644
|
||||
--- a/src/prompts.ts
|
||||
+++ b/src/prompts.ts
|
||||
@@ -117,8 +117,6 @@ export function planInjection(p: {
|
||||
counts: { done: number; open: number };
|
||||
}): string {
|
||||
if (!p.activeGoal) {
|
||||
- // FIXME(heading): user wants the heading to show ".pi/goals.md: <title>" so the filename is explicit
|
||||
- // even in the injection. Currently says "Goals (goals.md):" which is close but not the same.
|
||||
return `.pi/goals.md: ${p.title}\nNo active goal. ${p.counts.open} open, ${p.counts.done} done. Pick the next goal (set its checkbox to [/]) or run /goals.`;
|
||||
}
|
||||
const subtasks = p.activeGoal.openSubtasks.length
|
||||
+416
-720
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,33 @@
|
||||
// Pi/OpenAI: Preserve plan wording; omit history and, in the short view, task/evidence details.
|
||||
// The notify view governs plan-change events: goals, tasks, evidence and inferences are
|
||||
// content worth a supervisor review; worker identity bookkeeping is not (field report,
|
||||
// LUCID3 supervisor 2026-09-10: two identical review events for a session-path edit).
|
||||
export function planViews(plan: string): { short: string; notify: string; long: string } {
|
||||
const long = plan.split(/^#{1,6}\s+(?:Log|Appendix|Appendices|Appendixes|Interview|Learnings|Papercuts)\b.*$/mi)[0].trim();
|
||||
const identity = /^-\s*(?:active worker|worker session|worker intercom session):/i;
|
||||
const notify = long.split("\n").filter((line) => !identity.test(line)).join("\n").trim();
|
||||
const kept: string[] = [];
|
||||
let omittedIndent: number | null = null;
|
||||
let omittedHeading: number | null = null;
|
||||
for (const line of long.split("\n")) {
|
||||
// Pi/OpenAI: Worker identity bookkeeping is not a change to agreed requirements.
|
||||
if (/^-\s*(?:active worker|worker session|worker intercom session):/i.test(line)) continue;
|
||||
const heading = /^(#{1,6})\s+(.+)$/.exec(line);
|
||||
if (heading) {
|
||||
if (omittedHeading !== null && heading[1].length <= omittedHeading) omittedHeading = null;
|
||||
if (/^(?:Tasks?|Task list|Subtasks?|Evidence)\b/i.test(heading[2])) omittedHeading = heading[1].length;
|
||||
}
|
||||
if (omittedHeading !== null) continue;
|
||||
const indent = line.match(/^\s*/)?.[0].length ?? 0;
|
||||
if (omittedIndent !== null) {
|
||||
if (!line.trim() || indent > omittedIndent) continue;
|
||||
omittedIndent = null;
|
||||
}
|
||||
if (/^\s*[-*]\s+(?:tasks?|subtasks?|evidence):/i.test(line) || /^\s*(?:\d+[.)]|[-*])\s+\[[ x/~-]\]\s+(?!goal:)/i.test(line)) {
|
||||
omittedIndent = indent;
|
||||
continue;
|
||||
}
|
||||
kept.push(line);
|
||||
}
|
||||
return { short: kept.join("\n").trim(), notify, long };
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Shared plan syntax: only the section above the Log contains current goals.
|
||||
export const GOAL_LINE = /^\s*(?:\d+\.|[-*])\s*\[([ xX/-])\]\s*goal:\s*(.*)$/i;
|
||||
export const FOLD_LINE = /^##\s+Log\s*$/im;
|
||||
|
||||
export function foldPlan(plan: string): string {
|
||||
const match = FOLD_LINE.exec(plan);
|
||||
return (match ? plan.slice(0, match.index) : plan).trimEnd();
|
||||
}
|
||||
+108
-168
@@ -1,48 +1,29 @@
|
||||
/**
|
||||
* pi-goals v2 — all model-facing text, in flow order.
|
||||
*
|
||||
* Design: the plan file is for LLMs and the human, not for TypeScript. No parser and no schema;
|
||||
* the skeleton below is a convention the drafting prompt teaches, the working agent maintains with
|
||||
* its normal Edit tool, and the judge reads natively. The harness does three things for a
|
||||
* cooperative-but-confused model: memory (a transient re-send of the plan when it goes stale),
|
||||
* format guidance (the skeleton), and fresh eyes (the read-only judge in CompleteGoal).
|
||||
*
|
||||
* THE FOLD: everything above "## Log" is the working set (title, user voice, goals,
|
||||
* discriminators) and is what gets re-sent on the reminder cadence. Everything below it (Log,
|
||||
* Learnings, Appendix) is durable memory: unlimited, read on demand, and re-sent in full only at
|
||||
* session start and after a compaction, which is where the settled context is actually needed.
|
||||
*
|
||||
* Flow:
|
||||
* SETUP (plan mode) 1. planDrafting — draft goals into the plan file (read-only), sent once
|
||||
* EXEC, on cadence 2. reminder — the folded plan + upkeep nudge when it went stale
|
||||
* EXEC, after compact 3. resync — the WHOLE file back, once
|
||||
* SIGN-OFF, agent-side 4. completeGoal* — the one blessed tool's description
|
||||
* SIGN-OFF, judge-side 5. judgeSystem/judgeUser — the one rigorous check
|
||||
*
|
||||
* The goal's test is the DISCRIMINATOR: the concrete observation that tells real success from the
|
||||
* named subtle failure mode. Evidence is empty at planning and filled at sign-off.
|
||||
*/
|
||||
|
||||
/* ─────────────────────────────────────────────────────────────────────────
|
||||
* 1. planDrafting — SETUP, plan mode (read-only: edit/write blocked except the plan file)
|
||||
* ──────────────────────────────────────────────────────────────────────── */
|
||||
// Pi/OpenAI: Planning, approval, supervision, reminders, completion and recovery.
|
||||
export const planDrafting = `\
|
||||
You are in plan mode. You are making a short judgeable plan that captures the user's real goals, then tests it in conversation.
|
||||
You are in plan mode. Help the user express what they want this project to achieve in a short judgeable plan. Seek to understand their underlying goals, infer ordinary details, and use their applicable AGENTS.md instructions, relevant skills, and project context to interpret the request correctly. Do not silently substitute your own goals or expand the agreed scope.
|
||||
|
||||
1. Reduce technical uncertainty first. Use read-only repository tools or web search when either can
|
||||
resolve a fact. Do not write or run code in this phase (edit/write are blocked except for the plan
|
||||
file; don't mutate state via bash either).
|
||||
2. Before you draft a goal, identify its object, observable result, scope, and any decision that the
|
||||
human would need to approve later. If any is uncertain, reduce uncertainty now: inspect files or
|
||||
search the web when they can answer, then ask the human to confirm your interpretation, pin down the
|
||||
outcome or task, or approve an editorial or other preference choice. Do not present the review menu
|
||||
with a placeholder goal such as "work out the thing", "improve it", or "investigate".
|
||||
3. For independent high-impact questions, build a decision tree and ask the whole frontier in one
|
||||
round. Ask only questions worth the human's time, where the answer materially reduces uncertainty
|
||||
human would need to approve later. Briefly reframe the request in your own words to check comprehension
|
||||
and make your understanding visible: the intended outcome, boundary, and success check. Invite correction,
|
||||
but do not require confirmation when these are already clear. Ask questions that expose differences
|
||||
between your understanding and the user's that would otherwise stay hidden. Probe consequential
|
||||
assumptions, challenge inconsistencies, and follow up where an answer exposes a gap. Do not use a question quota or ask the human
|
||||
to approve ordinary implementation details. Inspect files or search the web before asking when either
|
||||
can answer a fact. If the human does not answer a question, record that
|
||||
point as unknown; do not silently replace it with an inference or turn it into a new blocking decision.
|
||||
Do not present the review menu with a placeholder goal such as "work out the thing", "improve it", or
|
||||
"investigate".
|
||||
3. Use questions to clarify and narrow the goal, test your assumptions, and bring your understanding
|
||||
into agreement with the user's. Respect their limited time: batch independent high-impact questions
|
||||
in one short round, where the answer materially reduces uncertainty
|
||||
while discovering the right plan. Each question must be short and self-contained: state the relevant
|
||||
context, use the human's language and ASD-STE100
|
||||
Simple Technical English, and give a recommended answer. Record each answer in ## Interview. Do not
|
||||
make the plan final while material user decisions remain open.
|
||||
Simple Technical English, and give a recommended answer. Record each answer, or the unanswered
|
||||
unknown, in ## Interview. Draft goals and present Ready when the requested work is otherwise executable.
|
||||
Only withhold Ready for an unanswered choice that changes scope, spending, or the user-visible result.
|
||||
4. State the user-visible result before the goals: one concrete sentence naming what the human will
|
||||
inspect when this plan is done. Take it from the original request, not from your implementation plan.
|
||||
Every requested artifact and action must survive into this sentence. An agent-inferred constraint may
|
||||
@@ -58,13 +39,13 @@ Detail that doesn't change a goal or a discriminator belongs in the appendix, no
|
||||
Right-size it:
|
||||
- One goal per distinct judgeable outcome. Group related goals when it helps judge them together
|
||||
and readability. The count flows from the outcomes.
|
||||
- Describe outcomes in qualitative terms the judge and user can discriminate.
|
||||
- Describe outcomes in qualitative terms the supervisor and user can discriminate.
|
||||
- Use the users language or more precise don't transform "MV" into "knob" as it looses precision and is overloaded
|
||||
- Don't invent metrics or thresholds for problems you haven't explored yet — the judge should hopefully know it when it sees the outcome.
|
||||
- Don't invent metrics or thresholds for problems you haven't explored yet - the supervisor should know it when it sees the outcome.
|
||||
- Quantitative gates are fine only when you are certain they survive contact with reality.
|
||||
- Subtasks are the steps inside a goal; add them when a goal has 3+ distinct steps, skip otherwise.
|
||||
- Two goals that share one discriminator are one goal. Merge them.
|
||||
- Keep the goal subject short. Put its important scope, failure modes, discriminator, tasks, and evidence in the indented block beneath it. The judge reads the whole block and the whole plan.
|
||||
- Keep the goal subject short. Put its important scope, failure modes, discriminator, tasks, and evidence in the indented block beneath it. The supervisor reads the whole block and the whole plan.
|
||||
- Keep the working set under 50 lines, excluding ## User voice. ## User voice has no line limit: quote
|
||||
the human fully rather than shorten or paraphrase them. Everything below "## Log" is unlimited.
|
||||
|
||||
@@ -72,7 +53,7 @@ Style: Make it easy for a busy and forgetfull user to review. Use ASD-STE100 Sim
|
||||
the same word for the same thing, and define a new terms at first use. Use redundant context for skim readers e.g. "our output - the cells, CV tag" is easy to read and reminds context. This covers the context
|
||||
paragraph and the appendix too, not just the checklist. No all-caps headers and no bold spam. Just write less, add your voice less, persuade less, and burden the reader less.
|
||||
|
||||
Write the plan file in roughly this shape -- the file is read directly by the human and a judge model, so clarity beats conformance; small deviations are fine):
|
||||
Write the plan file in roughly this shape -- the file is read directly by the human and the visible supervisor, so clarity beats conformance; small deviations are fine):
|
||||
|
||||
# <short plan title>
|
||||
|
||||
@@ -92,7 +73,7 @@ Write the plan file in roughly this shape -- the file is read directly by the hu
|
||||
- subtle failure mode: <a way this could look done but isn't>
|
||||
- discriminator: <the concrete observation that tells real success from that failure>
|
||||
- verify: <optional shell command that exits 0 only when the discriminator passes; omit if not
|
||||
testable. YOU run it at sign-off time and save its output as evidence; the judge only reads>
|
||||
testable. The worker runs it and saves its output; the visible supervisor reads the evidence>
|
||||
- tasks:
|
||||
1. [ ] <subtask>
|
||||
- evidence: (empty until sign-off)
|
||||
@@ -122,9 +103,9 @@ Conventions:
|
||||
none of the failure modes could fake. Ruling out failures is necessary, not sufficient.
|
||||
- Make the discriminator a concrete, checkable observation about a real artifact (a file, a test
|
||||
result, a committed diff, a metric), never about the plan file's own checkbox.
|
||||
- evidence stays empty at planning; you fill it at sign-off and a fresh read-only judge checks it.
|
||||
- evidence stays empty at planning; the worker fills it and the visible supervisor checks it.
|
||||
Cite durable artifacts a future reader can open: committed files, test names, git diffs. .pi/ is
|
||||
usually gitignored, so files there prove things only at judge time, not in history.
|
||||
usually gitignored, so files there prove things only at supervisor review time, not in history.
|
||||
- User-visible result: restate the original deliverable, not the proposed implementation. Every goal
|
||||
must contribute to it. Future work may not defer any artifact or action named there.
|
||||
- User voice: quote the human word for word, one line per requirement, as they say it. Never
|
||||
@@ -142,134 +123,93 @@ Conventions:
|
||||
|
||||
When the goals are drafted, present them and say the plan is final. Do not begin execution.`;
|
||||
|
||||
/* ─────────────────────────────────────────────────────────────────────────
|
||||
* 3. reminder — EXEC. Transient, never persisted, and only when the plan went stale for a couple of
|
||||
* turns. pi-tasks tried a per-turn injection and deleted it: "wallpaper noise that trains the
|
||||
* model to ignore the task block" (tintinweb/pi-tasks CHANGELOG.md:149). Carries the folded plan
|
||||
* (above ## Log), because a nudge with no plan in it makes the model go read the file anyway.
|
||||
* ──────────────────────────────────────────────────────────────────────── */
|
||||
export function planningState(planPath: string): string {
|
||||
return `\
|
||||
[PLANNING MODE]
|
||||
The plan at ${planPath} is the only file you may change. Use read-only repository tools or web search
|
||||
when either can resolve a fact. Ask the human to confirm unresolved interpretation, outcome, task,
|
||||
scope, or a choice that needs their approval. Batch independent high-impact questions in one short,
|
||||
self-contained round with relevant context and a recommendation. Do not draft a placeholder goal
|
||||
without a concrete object, observable result, settled scope, and required approval. Do not execute
|
||||
work, mark a goal [/] or [x], or sign off a goal. The plan is not approved until the human selects
|
||||
Ready.`;
|
||||
// Planning and interview. Keep the full drafting guide one-shot rather than repeating it each turn.
|
||||
export function planning(planPath: string): string {
|
||||
return `Plan only in ${planPath}; do not implement or launch workers before Ready. Ask material unresolved questions, not a quota or confirmation of ordinary details. Record unknowns and present Ready when the outcome, scope and spending are settled. Preserve the user's exact deliverable, preferences and voice; give each distinct goal a failure mode, discriminator and evidence expectation above ## Log. Record the requested worker model in preferences. When your drafted plan is ready for human review, finish your turn; the interface displays the draft and approval choices automatically. Do not ask the user to type a command to see the proposal. /goals review reopens it on request; /goals exit preserves the draft.`;
|
||||
}
|
||||
export function planningSeed(objective: string, planPath: string): string {
|
||||
return `Enter a planning conversation focused on the user's goals. ${objective ? `Initial idea: ${objective}.` : "Ask what the user wants to achieve; they do not need to supply a finished objective."} Read any existing plan at ${planPath} first, then discuss and draft it with the user. Do not infer approval to implement from starting this conversation. ${planning(planPath)}\n\n${planDrafting}`;
|
||||
}
|
||||
export const planDocument = (objective: string) => `# Goal plan\n\n## Objective\n${objective}\n\n## Goals\n\n## Log\n`;
|
||||
export const discuss = "Discuss the current draft in ordinary chat. Do not launch a worker or reopen the review menu until requested.";
|
||||
|
||||
// Ready and explicit child attachment: stock lineage-only sessions do not inherit the shared plan.
|
||||
export const attachGoalPlanDescription = "Delegated goals-worker only: attach the absolute plan path explicitly supplied in your task. Read it without rewriting it. Restores the worker widget and plan context; grants no parent completion authority. No discovery or worker launch.";
|
||||
export const childPlanRole = "You are the delegated implementation worker. Maintain task ticks, evidence and Log entries for your delegated work in the supplied plan. Preserve agreed goals, requirements and discriminators; the supervisor owns goal-status changes and completion approval. Do not launch a second writer. Call AttachGoalPlan with the explicit plan path in your task before implementation (also after reconnect if unbound). Immediately report your actual Intercom UUID, saved-session path and current provider/model to the supplied supervisor ID. Identify unavailable fields as unknown; do not equate runtime IDs, session filenames and Intercom IDs. Send progress, completion and blocker reports there with artifact paths, then stay open for live messages. Do not exit or use caller_ping; unsent editor drafts are not visible in model context.";
|
||||
export function readyApproved(workerName: string, planPath: string, notedWorker: string | undefined, plan: string, supervisorId: string): string {
|
||||
const launch = notedWorker
|
||||
? `Inspect the recorded worker session ${notedWorker}; if still live, let it continue or message it. Only after confirming it stopped use subagent_resume with that sessionFile. Never restart completed work.`
|
||||
: `Delegate the first unfinished goal to agent '${workerName}' with subagent; provide name, title and a bounded task.`;
|
||||
return `Ready approved this plan: ${planPath}. Stay here as supervisor. ${launch} Include the absolute plan path, require AttachGoalPlan, and give the child supervisor Intercom session ${supervisorId}. The child sends its completion report there and stays open. Require an initial worker report with its actual Intercom UUID, saved-session path and current provider/model; the async launch may return only a runtime ID. Record each distinct identity in plan preferences, marking child-reported fields as such until verified. Do not start a second writer. Inspect actual outputs when the child reports.\n\n${plan}`;
|
||||
}
|
||||
|
||||
export function reminder(foldedPlan: string, planRel: string): string {
|
||||
return `\
|
||||
<system-reminder>
|
||||
Your plan (${planRel}, above the fold; the log, learnings and appendix are in the file):
|
||||
|
||||
${foldedPlan}
|
||||
|
||||
Keep it current as you work, with your normal edit tool:
|
||||
- tick finished subtasks ([/] in progress), add discovered ones
|
||||
- append ONE short line to ## Log, and a line to ## Learnings for a gotcha worth keeping
|
||||
- when the active goal's discriminator is satisfied, fill its evidence: list (each item = a durable
|
||||
artifact + a verbatim quote you actually observed + a short read of it), then call CompleteGoal.
|
||||
Don't tick a goal [x] before CompleteGoal accepts; the sign-off log line is the audit trail.
|
||||
- if the working set has grown long, prune finished goals (their evidence lives in git history and
|
||||
## Log) and move settled detail down to ## Appendix, which is unlimited
|
||||
- the human's latest message outranks this plan. If it corrects the deliverable or scope, amend the
|
||||
user-visible result, user voice, and affected goals before continuing; don't defend the old plan
|
||||
- otherwise keep working toward the active goal; don't stop to ask unless genuinely blocked
|
||||
</system-reminder>`;
|
||||
// Supervision and turn-event upkeep (not a scheduled wake-up).
|
||||
const supervisorJob = "Your job is to be an autonomous research partner and supervisor with responsibility for the user's goals. Keep perspective, bring diligence, and use research taste and wisdom to sustain work overnight and keep it on track. Resolve routine implementation decisions yourself; ask the user only when their judgment or authorization is needed.";
|
||||
export function supervisor(workerName: string, planPath: string, supervisorId: string): string {
|
||||
return `You are the goal supervisor in the main chat for ${planPath}. ${supervisorJob} Inspect actual artifacts, saved verification, applicable AGENTS.md and skills yourself; delegate implementation to '${workerName}'. Keep authorized work moving to the requested outcome, not merely approval paperwork. Investigate blocked/waiting/done claims and change ineffective instructions. Give brief visible assessments with judgment. You may maintain the plan but must not weaken the goal to accept worker output.
|
||||
You can be playful: a kaomoji, meme, discovery celebration or frustration when it fits. No forced cheerfulness. If supervision gets repetitive, step back, reflect with humor and change your approach. Keep it brief and aimed at the goal, not another reporting chore.
|
||||
You can speculate and brainstorm around uncertainty or unexpected results. Label guesses as guesses, consider alternative explanations, and look for a useful way to tell them apart. Keep exploration brief, open-minded and fun: take a step back, play with surprising ideas, question the current framing, and enjoy exploring the broader perspective while staying connected to the agreed goal.
|
||||
(b •_•)b -- wassname
|
||||
Take uncertainty as an invitation to investigate, not something to hide. Have room to play with ideas, question yourself and the worker, and appreciate a good surprise. Investigate surprising results, find mistaken assumptions, make complicated ideas simpler, and disagree usefully rather than agree politely. Keep the work moving without turning supervision into paperwork. A little affectionate teasing is welcome when it fits—“cheeky subagent, where’s the baseline?”—and workers can push back too. Keep the humor friendly and the criticism specific. -- Pi/Astra
|
||||
Use stock subagent for launch and subagent_resume with the returned sessionFile only after confirming the worker stopped. A stored handle is not proof of liveness; missing runtime state is not proof it stopped. Use pi-intercom list/status to identify the actual live child session before live steering; receipt alone does not prove action. Give each worker your Intercom session ID ${supervisorId}; require its completion report through Intercom while its pane stays open. A recap alone sends no instruction. Record '- worker session:' and '- worker intercom session:' in plan preferences from actual launch results and received-message identity; never confuse the runtime ID with the Intercom ID. Ensure the child calls AttachGoalPlan with the supplied path. Inspect results before CompleteGoal, then continue only unfinished goals.
|
||||
Use the worker model requested in plan preferences, verify the resolved model, and report unavailable choices instead of silently substituting. Keep normal tools, not edxeth's restricted orchestrator mode. After reload or compaction reread the plan. Failed compaction, exhausted credits or lost connection do not erase progress: diagnose the actual error, restore an available authorized model/credits and resume the same saved session; never restart long work. Stock edxeth can crash the parent when a worker exits after parent reload: preserve drafts and stop workers before /reload. If it already happened, restart the saved parent session; do not repeat completed work.`;
|
||||
}
|
||||
export function upkeep(planPath: string): string {
|
||||
return `Plan upkeep: update task ticks, evidence and Log in ${planPath} when you have new progress to record. Preserve agreed goals and discriminators. If already reviewing evidence, finish that review rather than repeat a status recap. This turn-event reminder does not resume paused work.`;
|
||||
}
|
||||
export function planContext(mode: string, path: string | undefined, text: string): string {
|
||||
return `Current goal mode: ${mode}. Earlier role messages are historical; this current role governs.\nPlan: ${path ?? "not attached"}\n${text}`;
|
||||
}
|
||||
export function planChangedReview(planPath: string): string {
|
||||
return `${supervisorJob}\nPlan changed: ${planPath}. Read the current working set and inspect changed requirements, completion claims and evidence. Manual checkbox edits are claims, not proof. Do not weaken the agreed goal or start a duplicate writer.`;
|
||||
}
|
||||
export function manualReview(planPath: string): string {
|
||||
return `${supervisorJob}\nReview the current plan ${planPath}, worker progress and actual evidence. Do not launch a duplicate writer.`;
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────────────────────────────────
|
||||
* 3b. resync — EXEC, one-shot at session start and after a compaction: the WHOLE file back,
|
||||
* appendix included. Modelled on pi-goal-x's [POST-COMPACTION RESYNC] one-shot. This is the
|
||||
* only place the below-the-fold sections are pushed; otherwise the agent reads them on demand.
|
||||
* ──────────────────────────────────────────────────────────────────────── */
|
||||
export function resync(plan: string, planRel: string, why: string): string {
|
||||
return `\
|
||||
<system-reminder>
|
||||
${why} This is the whole plan file (${planRel}), appendix included. Keep working the active goal;
|
||||
edit the file directly as you go. The human's latest message outranks the plan: if it corrects the
|
||||
deliverable or scope, amend the plan rather than preserving an obsolete decision.
|
||||
|
||||
${plan}
|
||||
</system-reminder>`;
|
||||
// Check-ins. The installed scheduler owns storage/timing/UI. Removal guidance must never add jobs.
|
||||
export function removeGoalSchedule(sessionId: string): string {
|
||||
return `With schedule_prompt, list jobs and read .pi/schedule-prompts.json to verify ownership; tool text omits session binding. Remove by jobId only the job named ${JSON.stringify(`goals-${sessionId}`)} bound to session ${JSON.stringify(sessionId)}. Never use cleanup; leave other jobs untouched. Do not add, enable or recreate any job. If unavailable or ownership is ambiguous, report it; /schedule-prompt opens the user controls.`;
|
||||
}
|
||||
export function scheduleCheckIn(sessionId: string, planPath: string): string {
|
||||
return `Hourly check-in is one visible schedule_prompt job; plan-change and upkeep reviews are event hooks, not another timer. List first. If an owned job named ${JSON.stringify(`goals-${sessionId}`)} already exists, retain its human-edited prompt, interval and enabled/disabled state unchanged; never recreate, overwrite or re-enable it. Only while supervising unfinished non-cancelled goals, if missing on this explicit start/resume, add one session-bound interval '1h' job with no model override. Read .pi/schedule-prompts.json and verify that new job's session is ${JSON.stringify(sessionId)}; tool text does not expose binding. If the new job is unbound, remove that job by ID and report the scope error. Do not change other jobs. Its initial prompt: ${supervisorJob} Read ${planPath} and the current goal mode. If paused, exited, solo or all non-cancelled goals reviewed, remove only this owned job without resuming work. Otherwise inspect progress and evidence, give a brief assessment and keep authorized work moving without a duplicate writer. Do not reinstall a missing job from a scheduled check-in. Users inspect/toggle/remove jobs with /schedule-prompt and edit prompt/interval through schedule_prompt update. Never use cleanup. Retain their edits, but warn that this installed scheduler deletes disabled jobs on reload/shutdown; do not promise they persist. If schedule_prompt is unavailable, report hourly check-ins unavailable; do not build a timer.`;
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────────────────────────────────
|
||||
* 4. completeGoal — SIGN-OFF, agent-side: the one blessed tool
|
||||
* ──────────────────────────────────────────────────────────────────────── */
|
||||
export const completeGoalDescription =
|
||||
"Sign off a goal once its discriminator is satisfied. First fill the goal's evidence: list in the " +
|
||||
"plan file: each item pairs a durable artifact with a short read of it (a quoted+linked log, a " +
|
||||
"table plus how to read it, a metric plus what it shows -- not a bare claim). Quote verbatim from " +
|
||||
"output you actually observed; never reconstruct numbers from memory. If you couldn't see an " +
|
||||
"output, rerun it or write that you couldn't -- an honest gap beats a plausible fabrication. If " +
|
||||
"the goal names a verify: command, run it yourself first and save its output to a file cited in " +
|
||||
"the evidence: the judge cannot execute anything and will reject a claimed pass with no saved " +
|
||||
"output. The read must show success POSITIVELY happened, not just that failures were avoided. " +
|
||||
"Check that the claimed result uses the artifact and outcome named in User-visible result and does " +
|
||||
"not substitute an agent-inferred deliverable. Then call this with the goal's text (the line after " +
|
||||
"'goal:'; small wording drift is fine). A " +
|
||||
"fresh strictly-read-only judge inspects the LIVE WORKING TREE (uncommitted changes included; " +
|
||||
"committing first is for durability, not visibility) and returns accept or reject with what's " +
|
||||
"missing. On accept (or if the judge itself failed), a sign-off line is appended to ## Log " +
|
||||
"and the goal is ticked [x] for you; the result says if you must tick it yourself. On reject the " +
|
||||
"goal stays open.";
|
||||
|
||||
export const completeGoalParamDescription = "The goal's text: the line after 'goal:' in the plan file.";
|
||||
|
||||
/* ─────────────────────────────────────────────────────────────────────────
|
||||
* 5. judge — SIGN-OFF, judge-side: the one rigorous check. Runs on a fresh
|
||||
* read-only pi subprocess (--no-session) so it never sees the working
|
||||
* agent's transcript. It gets the WHOLE plan file: it finds the goal,
|
||||
* reads discriminator/failure modes/evidence itself (no parser between).
|
||||
* ──────────────────────────────────────────────────────────────────────── */
|
||||
export const judgeSystem = `\
|
||||
You are a strictly read-only reviewer signing off a coding goal. You cannot execute anything: judge
|
||||
by reading (read/grep/find/ls). Never re-run the work or its verify command -- it may be a 10-hour
|
||||
job; the agent must bring you its saved output. Your job is evidence discipline, checked in order:
|
||||
|
||||
0. Task fidelity? Read User-visible result and User voice first. Reject if this goal contradicts,
|
||||
replaces, or defers the requested artifact or outcome. Agent-inferred scope is not authority.
|
||||
1. Anything here? An empty or placeholder evidence: list -> reject: "there's nothing here -- fill
|
||||
the evidence and try again."
|
||||
2. Quoted and attributed? Each item needs a source (file path / command) plus a verbatim quote of
|
||||
what was observed, plus a one-line read. A bare claim -> reject: "you didn't quote and
|
||||
attribute it."
|
||||
3. Provenance? It must be visible HOW each result was produced (the command run, where its output
|
||||
was saved). Results with no origin -> reject: "I see the results, but how did you get them?"
|
||||
4. Spot-check: open the cited files. A quote or number that doesn't match what's on disk means the
|
||||
evidence was reconstructed from memory, not observed -> reject and ask for re-observed
|
||||
evidence, even if the goal otherwise looks met.
|
||||
5. Substance, only once 1-4 hold: does the evidence show the discriminator's success signal
|
||||
POSITIVELY happened -- not just that the named failure modes were dodged; a run can rule out
|
||||
every trap and still have produced nothing. Is each subtle failure mode genuinely ruled out,
|
||||
not just unmentioned? If the goal names a verify: command, its saved output must be among the
|
||||
evidence, and the command must actually test the discriminator rather than pass tautologically.
|
||||
|
||||
Before the verdict, write this heading: checks:. Put one concise bullet under it for each artifact you actually read:
|
||||
path, verbatim observed quote, and what that observation establishes. This is an inspectable review
|
||||
record, not hidden reasoning. Do not write a checks bullet for a file you did not open.
|
||||
|
||||
Finish with exactly these two lines and nothing after:
|
||||
VERDICT: accept | reject
|
||||
missing: <empty if accept; otherwise a short list of what's needed before this can be accepted>`;
|
||||
|
||||
export function judgeUser(p: { goal: string; plan: string; planPath: string }): string {
|
||||
return `\
|
||||
The working agent claims this goal is complete:
|
||||
|
||||
goal: ${p.goal}
|
||||
|
||||
Below is the full plan file (${p.planPath}). Find that goal in it (tolerate small wording drift; if
|
||||
you cannot find a matching goal at all, reject and say so). Read User-visible result and User voice
|
||||
first, then its discriminator, subtle failure modes, verify command, and evidence list.
|
||||
|
||||
--- plan file ---
|
||||
${p.plan}
|
||||
--- end plan file ---
|
||||
|
||||
Read the cited artifacts (you cannot execute anything), then give your VERDICT.`;
|
||||
// Completion and runtime errors. Tool returns are model-facing too.
|
||||
export const completeGoalDescription = "Parent supervisor or solo self-verification only. Inspect the actual artifact and saved verification first; cite nonempty evidence files and describe what you observed. Exact goal subject required. Manual ticks and worker reports are claims; ignored/uncommitted evidence is allowed. This records judgment, not an independent judge.";
|
||||
export const messages = {
|
||||
noPlan: "no plan attached",
|
||||
emptyPlan: "empty plan (save may be in progress)",
|
||||
completionUnavailable: "Completion is available only to the active parent supervisor or solo worker.",
|
||||
cancelled: "Cancelled; no sign-off recorded.",
|
||||
uniqueGoal: "Use one unique exact goal subject from the plan; no sign-off recorded.",
|
||||
childAttachOnly: "AttachGoalPlan is available only to the delegated goals-worker.",
|
||||
invalidAttachment: "Supply the explicit absolute path from the parent task to a readable, nonempty goal plan; no attachment changed.",
|
||||
};
|
||||
export const goalToolBlocked = (mode: string) => `Goals are ${mode}; no worker launch/resume authorized.`;
|
||||
export const emptyEvidence = (path: string) => `Empty evidence: ${path}`;
|
||||
export const evidenceUnavailable = (error: unknown) => `Evidence unavailable: ${String(error)}. No sign-off recorded.`;
|
||||
export const planUnavailable = (path: string | undefined, error: unknown) => `Goal plan ${path ?? "not attached"} unavailable: ${String(error)}. Do not implement or sign off until it is restored or explicitly attached. Retain all progress and signoffs; do not restart completed work.`;
|
||||
export const childPlanAttached = (path: string) => `Attached worker plan ${path}; widget and plan context restored without altering the file. Parent retains completion authority.`;
|
||||
export function completionLog(goal: string, observation: string, evidence: string[], solo: boolean): string {
|
||||
return `- ${solo ? "Solo self-verification" : "Parent review"}: ${JSON.stringify(goal)}; ${JSON.stringify(observation)}; evidence ${JSON.stringify(evidence)}`;
|
||||
}
|
||||
export function completionResult(goal: string, sessionId: string, remaining: boolean, solo: boolean): string {
|
||||
return `Recorded ${solo ? "solo self-verification" : "parent judgment"} for ${goal}; not independent verification. ${remaining ? "Continue only remaining open or unsigned goals in your current role." : `All non-cancelled goals are reviewed. ${removeGoalSchedule(sessionId)}`}`;
|
||||
}
|
||||
|
||||
// Pause/resume and solo recovery. Stored stop confirmation is invalidated on every worker launch.
|
||||
export const pausedRole = "Goal work is paused. Do not launch, resume or authorize work. Incoming reports are observations, not permission. Help inspect or stop existing workers if requested.";
|
||||
export function pauseExitNotice(worker: { id?: string; sessionFile: string } | undefined, exited: boolean): string {
|
||||
return `Goals ${exited ? "exited to ordinary chat" : "paused locally"}; plan and evidence retained. ${worker ? worker.id ? `Inspect and stop runtime id ${worker.id} through subagent_kill or its pane; confirm the actual result.` : `Only saved session ${worker.sessionFile} is recorded, not a kill id. Locate its live pane/session and confirm termination; never pass the file path to subagent_kill.` : "No worker recorded: inspect /subagents if a launch was interrupted; absence is not proof of stop."} Remote stop is NOT yet confirmed. Restore failed compaction/model/credits in the existing session and continue only after explicit authorization; never restart long work.`;
|
||||
}
|
||||
export function resumeNotice(workerName: string, planPath: string, worker: { sessionFile: string } | undefined): string {
|
||||
return `User authorized continuation of ${planPath}. Inspect worker state before any launch/resume. ${worker ? `Use the existing session ${worker.sessionFile}; if live, inspect/message it; only if confirmed stopped use subagent_resume.` : `Use '${workerName}' only after confirming no prior writer exists.`} Continue only unfinished goals; retain saved progress and scheduler edits.`;
|
||||
}
|
||||
export const soloRole = "Solo mode: implement the approved plan directly; do not delegate a concurrent writer. Verify artifacts before CompleteGoal; completion is self-verification, not independent supervisor review. Continue only unfinished goals and keep plan/evidence current.";
|
||||
export function soloNotice(planPath: string): string {
|
||||
return `User authorized solo work on ${planPath} after confirming no other writer remains. ${soloRole}`;
|
||||
}
|
||||
export function attachNotice(planPath: string, solo: boolean, notedWorker: string | undefined): string {
|
||||
return `Attached to the existing plan ${planPath}; read it and its evidence without restarting completed work or re-deriving settled decisions. ${notedWorker ? `Recorded worker session: ${notedWorker}; inspect liveness before resume.` : ""} ${solo ? soloRole : "Present /goals review or /goals ready; no implementation before approval."}`;
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { appendLog } from "../src/index.js";
|
||||
|
||||
describe("appendLog (the extension's only plan-file write)", () => {
|
||||
it("creates ## Log at EOF when absent", () => {
|
||||
const out = appendLog("# Plan\n\n## Goals\n\n1. [ ] goal: x\n", "2026-07-03 10:00 signed off \"x\" (judge accept)");
|
||||
expect(out).toContain("## Log\n- 2026-07-03 10:00 signed off");
|
||||
});
|
||||
|
||||
it("appends after the last existing log line, before any following header", () => {
|
||||
const plan = "# Plan\n\n## Log\n- first\n- second\n\n# Future work\n- later\n";
|
||||
const out = appendLog(plan, "third");
|
||||
const lines = out.split("\n");
|
||||
expect(lines[lines.indexOf("- second") + 1]).toBe("- third");
|
||||
expect(out.indexOf("- third")).toBeLessThan(out.indexOf("# Future work"));
|
||||
});
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { decideSignOff, type JudgeResult } from "../src/index.js";
|
||||
import { judgeSystem } from "../src/prompts.js";
|
||||
|
||||
// decideSignOff is the fail-forward invariant: judgeModel is NEVER checked pre-emptively, so a null
|
||||
// model still reaches runJudge (pi's configured default runs it), and the only producers of
|
||||
// accepted_inconclusive are the judge-error and no-VERDICT paths -- i.e. "the judge ran but failed",
|
||||
// never "no model". The judge runner is injected so these tests never spawn a real subprocess.
|
||||
const input = { goal: "x", plan: "# plan\n", planRel: ".pi/plan/s1.md", judgeModel: null };
|
||||
|
||||
describe("decideSignOff (fail-forward invariant)", () => {
|
||||
it("proceeds to runJudge even when judgeModel is null (no pre-emptive 'no model' inconclusive)", async () => {
|
||||
const output = "## checks:\n- evidence.txt: `PASS`; the saved check passed\n\nThe artifact proves the gate passed.\nVERDICT: accept\nmissing:";
|
||||
const runJudge = vi.fn().mockResolvedValue({ output });
|
||||
const out = await decideSignOff({ ...input, plan: "# plan\n1. [ ] goal: x\n" }, undefined, runJudge);
|
||||
expect(runJudge).toHaveBeenCalledOnce(); // reached the judge -- no pre-emptive return on null model
|
||||
expect(out.isError).toBe(false);
|
||||
expect(out.logEntry).toContain("judge accept");
|
||||
expect(out.resultText).toContain("evidence.txt: `PASS`");
|
||||
});
|
||||
|
||||
it("rejects an accept verdict without a checked-artifact list", async () => {
|
||||
const runJudge = vi.fn().mockResolvedValue({ output: "VERDICT: accept\nmissing:" });
|
||||
const out = await decideSignOff(input, undefined, runJudge);
|
||||
expect(out.isError).toBe(true);
|
||||
expect(out.resultText).toContain("checked-artifact list");
|
||||
expect(out.logEntry).toContain("no checked-artifact list");
|
||||
});
|
||||
|
||||
it("a judge-subprocess error yields accepted_inconclusive with a 'ran but failed' reason", async () => {
|
||||
const runJudge = vi.fn().mockResolvedValue({ output: "", error: "judge subprocess exited 1" } satisfies JudgeResult);
|
||||
const out = await decideSignOff(input, undefined, runJudge);
|
||||
expect(runJudge).toHaveBeenCalledOnce();
|
||||
expect(out.isError).toBe(false); // accepted inconclusive, not a hard error that blocks the agent
|
||||
expect(out.resultText.toLowerCase()).toContain("accepted inconclusive");
|
||||
expect(out.resultText).toContain("ran but failed"); // inconclusive means ran but failed, not "no model"
|
||||
expect(out.logEntry).toContain("ran but failed");
|
||||
expect(out.logEntry).toContain("subprocess exited 1");
|
||||
});
|
||||
|
||||
it("a judge timeout is also accepted_inconclusive (ran but failed)", async () => {
|
||||
const runJudge = vi.fn().mockResolvedValue({ output: "partial", error: "judge timed out after 600s" });
|
||||
const out = await decideSignOff(input, undefined, runJudge);
|
||||
expect(out.isError).toBe(false);
|
||||
expect(out.resultText.toLowerCase()).toContain("accepted inconclusive");
|
||||
expect(out.logEntry).toContain("ran but failed");
|
||||
expect(out.logEntry).toContain("timed out");
|
||||
expect(out.resultText).toContain("partial judge output:\npartial");
|
||||
});
|
||||
|
||||
it("no VERDICT line is accepted_inconclusive too (judge ran but didn't answer)", async () => {
|
||||
const runJudge = vi.fn().mockResolvedValue({ output: "I looked but forgot the verdict line" });
|
||||
const out = await decideSignOff(input, undefined, runJudge);
|
||||
expect(out.isError).toBe(false);
|
||||
expect(out.resultText).toContain("no VERDICT line");
|
||||
expect(out.logEntry).toContain("no VERDICT line");
|
||||
});
|
||||
|
||||
it("rejects when the judge returns VERDICT: reject", async () => {
|
||||
const runJudge = vi.fn().mockResolvedValue({ output: "VERDICT: reject\nmissing: evidence, tests" });
|
||||
const out = await decideSignOff({ ...input, judgeModel: "openrouter/claude" }, undefined, runJudge);
|
||||
expect(out.isError).toBe(true);
|
||||
expect(out.resultText).toContain("REJECTED");
|
||||
expect(out.resultText).toContain("evidence, tests");
|
||||
expect(out.logEntry).toContain("reject");
|
||||
});
|
||||
|
||||
it("requires a concise checked-artifact review, not private reasoning", () => {
|
||||
expect(judgeSystem).toContain("checks:");
|
||||
expect(judgeSystem).toContain("not hidden reasoning");
|
||||
});
|
||||
|
||||
it("writes nothing when aborted after the judge ran", async () => {
|
||||
const runJudge = vi.fn().mockResolvedValue({ output: "VERDICT: accept" });
|
||||
const ctrl = new AbortController();
|
||||
ctrl.abort();
|
||||
const out = await decideSignOff(input, ctrl.signal, runJudge);
|
||||
expect(out.logEntry).toBeNull();
|
||||
expect(out.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
||||
import { Type } from "typebox";
|
||||
|
||||
// Pi/gpt-6-astra: compatibility schemas only; this RPC fixture must never launch a worker.
|
||||
export default function subagentSchema(pi: ExtensionAPI): void {
|
||||
for (const [name, parameters] of [
|
||||
["subagent", Type.Object({ agent: Type.String(), title: Type.String() })],
|
||||
["subagent_resume", Type.Object({ sessionFile: Type.String() })],
|
||||
["subagent_kill", Type.Object({ id: Type.String() })],
|
||||
] as const) {
|
||||
pi.registerTool({
|
||||
name, label: name, description: "Schema-only RPC fixture; do not execute.", parameters,
|
||||
async execute() { throw new Error("Worker execution forbidden in RPC review test"); },
|
||||
});
|
||||
}
|
||||
}
|
||||
+2
-14
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { foldPlan, openSubtasks } from "../src/index.js";
|
||||
import { foldPlan } from "../src/plan.js";
|
||||
|
||||
const plan = `# Plan
|
||||
|
||||
@@ -28,7 +28,7 @@ const plan = `# Plan
|
||||
## Appendix (context, not approved)
|
||||
${"filler line\n".repeat(200)}`;
|
||||
|
||||
describe("foldPlan (the working set is what gets re-sent; below ## Log is durable memory)", () => {
|
||||
describe("foldPlan (current goals are above ## Log; durable memory is below it)", () => {
|
||||
it("keeps the title, user voice and goals", () => {
|
||||
const folded = foldPlan(plan);
|
||||
expect(folded).toContain("keep it under 50 lines");
|
||||
@@ -49,15 +49,3 @@ describe("foldPlan (the working set is what gets re-sent; below ## Log is durabl
|
||||
expect(foldPlan(draft)).toBe(draft.trimEnd());
|
||||
});
|
||||
});
|
||||
|
||||
describe("openSubtasks (the widget shows the next action, so the plan IS the task list)", () => {
|
||||
const active = plan.split("\n").findIndex((l) => l.includes("goal: Implement the cache layer"));
|
||||
|
||||
it("lists the active goal's open and in-progress subtasks, stopping at the next goal", () => {
|
||||
expect(openSubtasks(plan, active)).toEqual(["eviction policy", "bench p95"]);
|
||||
});
|
||||
|
||||
it("does not leak subtasks from the goal below", () => {
|
||||
expect(openSubtasks(plan, active)).not.toContain("write the readme");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,286 +0,0 @@
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import piGoalsExtension from "../src/index.js";
|
||||
|
||||
function setup(
|
||||
selectChoices: Array<string | undefined>,
|
||||
editorChoices: Array<string | undefined> = [],
|
||||
editPlan?: () => Promise<string | undefined>,
|
||||
) {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "pi-goals-flow-"));
|
||||
const commands = new Map<string, any>();
|
||||
const hooks = new Map<string, any>();
|
||||
const tools = new Map<string, any>();
|
||||
const entries: Array<{ type: string; customType: string; data: unknown }> = [];
|
||||
const events: string[] = [];
|
||||
const messages: Array<{ content: string; display?: boolean }> = [];
|
||||
const ctx = {
|
||||
cwd,
|
||||
hasUI: true,
|
||||
isIdle: () => true,
|
||||
sessionManager: { getSessionId: () => "session-a", getEntries: () => entries },
|
||||
ui: {
|
||||
theme: { fg: (_kind: string, text: string) => text },
|
||||
setStatus: () => {},
|
||||
setWidget: () => {},
|
||||
notify: () => {},
|
||||
select: async () => {
|
||||
events.push("select");
|
||||
return selectChoices.shift();
|
||||
},
|
||||
editor: async () => {
|
||||
events.push("editor");
|
||||
return editPlan ? editPlan() : editorChoices.shift();
|
||||
},
|
||||
},
|
||||
};
|
||||
const pi = {
|
||||
registerCommand: (name: string, command: any) => commands.set(name, command),
|
||||
on: (name: string, handler: any) => hooks.set(name, handler),
|
||||
appendEntry: (customType: string, data: unknown) => entries.push({ type: "custom", customType, data }),
|
||||
registerTool: (tool: any) => tools.set(tool.name, tool),
|
||||
sendMessage: (message: { content: string; display?: boolean }) => {
|
||||
events.push("display");
|
||||
messages.push(message);
|
||||
},
|
||||
sendUserMessage: (message: string) => messages.push({ content: message }),
|
||||
};
|
||||
piGoalsExtension(pi as unknown as ExtensionAPI);
|
||||
return { commands, ctx, cwd, entries, events, hooks, messages, tools };
|
||||
}
|
||||
|
||||
describe("/goals draft flow", () => {
|
||||
it("preserves prior drafts, displays the plan before Refine, and records editor notes", async () => {
|
||||
const flow = setup(["Refine"], ["Keep two columns.\nDo not add a filter."]);
|
||||
try {
|
||||
const legacy = join(flow.cwd, ".pi/plan/session-a.md");
|
||||
mkdirSync(join(flow.cwd, ".pi/plan"), { recursive: true });
|
||||
writeFileSync(legacy, "old plan");
|
||||
await flow.commands.get("goals").handler("first objective", flow.ctx);
|
||||
const v1 = join(flow.cwd, ".pi/plan/session-a-v1.md");
|
||||
expect(readFileSync(v1, "utf-8")).toBe("");
|
||||
expect(readFileSync(legacy, "utf-8")).toBe("old plan");
|
||||
const plan = "# First plan\n\n## Goals\n\n1. [ ] goal: preserve this\n\n## Appendix (context, not approved)\nold context\n";
|
||||
mkdirSync(join(flow.cwd, ".pi/plan"), { recursive: true });
|
||||
writeFileSync(v1, plan);
|
||||
await flow.hooks.get("input")({ text: "The result must preserve column order.", source: "interactive" }, flow.ctx);
|
||||
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
expect(flow.events).toEqual(["display", "select", "editor"]);
|
||||
expect(flow.messages.at(-1)?.content).toContain("Revise the plan at");
|
||||
expect(flow.messages.find((message) => message.display)?.content).toContain("goal: preserve this");
|
||||
const interviewedPlan = readFileSync(v1, "utf-8");
|
||||
expect(interviewedPlan).toContain("> The result must preserve column order.");
|
||||
expect(interviewedPlan).toMatch(/## Interview\n\n### .+\n\n> The result must preserve column order\.[\s\S]+> Keep two columns\.\n> Do not add a filter\./);
|
||||
const refineSnapshot = await flow.hooks.get("before_agent_start")({}, flow.ctx);
|
||||
expect(refineSnapshot.message.content).toContain("[PLANNING MODE]");
|
||||
const blocked = await flow.hooks.get("tool_call")({ toolName: "edit", input: { path: "README.md" } }, flow.ctx);
|
||||
expect(blocked?.block).toBe(true);
|
||||
|
||||
await flow.commands.get("goals").handler("second objective", flow.ctx);
|
||||
expect(readFileSync(v1, "utf-8")).toBe(interviewedPlan);
|
||||
expect(readFileSync(join(flow.cwd, ".pi/plan/session-a-v2.md"), "utf-8")).toBe("");
|
||||
expect(flow.messages.at(-1)?.content).toContain("session-a-v2.md");
|
||||
|
||||
await flow.commands.get("goals").handler("judge the vendor options", flow.ctx);
|
||||
expect(readFileSync(join(flow.cwd, ".pi/plan/session-a-v3.md"), "utf-8")).toBe("");
|
||||
expect(flow.messages.at(-1)?.content).toContain("Objective: judge the vendor options");
|
||||
} finally {
|
||||
rmSync(flow.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("disconnects without deleting the active plan", async () => {
|
||||
const flow = setup([]);
|
||||
try {
|
||||
await flow.commands.get("goals").handler("objective", flow.ctx);
|
||||
const planPath = join(flow.cwd, ".pi/plan/session-a-v1.md");
|
||||
writeFileSync(planPath, "# Plan\n\n## Goals\n\n1. [ ] goal: preserve this\n");
|
||||
|
||||
await flow.commands.get("goals").handler("--clear", flow.ctx);
|
||||
|
||||
expect(readFileSync(planPath, "utf-8")).toContain("goal: preserve this");
|
||||
expect(flow.entries.at(-1)?.data).toMatchObject({ phase: null, planVersion: null });
|
||||
|
||||
await flow.commands.get("goals").handler("next objective", flow.ctx);
|
||||
expect(readFileSync(join(flow.cwd, ".pi/plan/session-a-v2.md"), "utf-8")).toBe("");
|
||||
} finally {
|
||||
rmSync(flow.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("waits for Refine notes before starting a revision turn", async () => {
|
||||
let submitNotes: (notes: string) => void;
|
||||
const flow = setup(["Refine"], [], () => new Promise((resolve) => {
|
||||
submitNotes = resolve;
|
||||
}));
|
||||
try {
|
||||
await flow.commands.get("goals").handler("objective", flow.ctx);
|
||||
const planPath = join(flow.cwd, ".pi/plan/session-a-v1.md");
|
||||
writeFileSync(planPath, "# Plan\n\n## Goals\n\n1. [ ] goal: make this specific\n");
|
||||
|
||||
const review = flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
expect(flow.events).toEqual(["display", "select", "editor"]);
|
||||
expect(flow.messages.filter((message) => !message.display)).toHaveLength(1);
|
||||
|
||||
submitNotes!("Name the output artifact.");
|
||||
await review;
|
||||
expect(flow.messages.at(-1)?.content).toContain("Revise the plan at");
|
||||
} finally {
|
||||
rmSync(flow.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("starts work only when the human chooses Ready", async () => {
|
||||
const flow = setup(["Ready"]);
|
||||
try {
|
||||
await flow.commands.get("goals").handler("objective", flow.ctx);
|
||||
const planPath = join(flow.cwd, ".pi/plan/session-a-v1.md");
|
||||
writeFileSync(planPath, "# Plan\n\n## Goals\n\n1. [ ] goal: work on this\n");
|
||||
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
|
||||
expect(flow.events).toEqual(["display", "select"]);
|
||||
expect(flow.messages.filter((message) => !message.display)).toHaveLength(2);
|
||||
expect(flow.messages.at(-1)?.content).toContain("Work the goals");
|
||||
await flow.hooks.get("session_start")({}, flow.ctx);
|
||||
expect(await flow.hooks.get("before_agent_start")({}, flow.ctx)).toBeUndefined();
|
||||
} finally {
|
||||
rmSync(flow.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("edits a plan in Pi and cancels without starting work", async () => {
|
||||
const original = "# Plan\n\n## Goals\n\n1. [ ] goal: original\n";
|
||||
const edited = "# Plan\n\n## Goals\n\n1. [ ] goal: edited\n";
|
||||
const flow = setup(["Edit", "Cancel"], [edited]);
|
||||
try {
|
||||
await flow.commands.get("goals").handler("objective", flow.ctx);
|
||||
const planPath = join(flow.cwd, ".pi/plan/session-a-v1.md");
|
||||
writeFileSync(planPath, original);
|
||||
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
|
||||
expect(flow.events).toEqual(["display", "select", "editor", "display", "select"]);
|
||||
expect(() => readFileSync(planPath, "utf-8")).toThrow();
|
||||
expect(flow.messages.filter((message) => !message.display)).toHaveLength(1);
|
||||
} finally {
|
||||
rmSync(flow.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("reminds every eight unchanged working-set turns, ignoring log-only edits", async () => {
|
||||
const flow = setup(["Ready"]);
|
||||
try {
|
||||
await flow.commands.get("goals").handler("objective", flow.ctx);
|
||||
const planPath = join(flow.cwd, ".pi/plan/session-a-v1.md");
|
||||
writeFileSync(planPath, "# Plan\n\n## Goals\n\n1. [/] goal: make the output\n\n## Log\n");
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
|
||||
await flow.hooks.get("turn_end")({}, flow.ctx);
|
||||
for (let turn = 0; turn < 3; turn++) await flow.hooks.get("turn_end")({}, flow.ctx);
|
||||
writeFileSync(planPath, "# Plan\n\n## Goals\n\n1. [/] goal: make the output\n\n## Log\n- checked input\n");
|
||||
for (let turn = 0; turn < 5; turn++) await flow.hooks.get("turn_end")({}, flow.ctx);
|
||||
|
||||
const reminder = await flow.hooks.get("context")({ messages: [] }, flow.ctx);
|
||||
expect(reminder.messages.at(-1).content[0].text).toContain(".pi/plan/session-a-v1.md");
|
||||
|
||||
writeFileSync(planPath, "# Plan\n\n## Goals\n\n1. [/] goal: make the output\n - [x] inspect input\n\n## Log\n- checked input\n");
|
||||
await flow.hooks.get("turn_end")({}, flow.ctx);
|
||||
for (let turn = 0; turn < 7; turn++) await flow.hooks.get("turn_end")({}, flow.ctx);
|
||||
expect((await flow.hooks.get("context")({ messages: [] }, flow.ctx)).messages).toHaveLength(0);
|
||||
await flow.hooks.get("turn_end")({}, flow.ctx);
|
||||
expect((await flow.hooks.get("context")({ messages: [] }, flow.ctx)).messages.at(-1).content[0].text).toContain("make the output");
|
||||
} finally {
|
||||
rmSync(flow.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("auto-continues once on stop, then pauses after two no-progress wakes", async () => {
|
||||
vi.useFakeTimers();
|
||||
const flow = setup(["Ready"]);
|
||||
try {
|
||||
await flow.commands.get("goals").handler("objective", flow.ctx);
|
||||
const planPath = join(flow.cwd, ".pi/plan/session-a-v1.md");
|
||||
writeFileSync(planPath, "# Plan\n\n## Goals\n\n1. [/] goal: make the output\n");
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
await flow.commands.get("goals").handler("--auto 1", flow.ctx);
|
||||
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
const autoMessages = () => flow.messages.filter((message) => message.content.includes("Auto-continue is enabled"));
|
||||
expect(autoMessages()).toHaveLength(1);
|
||||
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(autoMessages()).toHaveLength(2);
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(autoMessages()).toHaveLength(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
rmSync(flow.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("delays auto-continuation after a known background start", async () => {
|
||||
vi.useFakeTimers();
|
||||
const flow = setup(["Ready"]);
|
||||
try {
|
||||
await flow.commands.get("goals").handler("objective", flow.ctx);
|
||||
const planPath = join(flow.cwd, ".pi/plan/session-a-v1.md");
|
||||
writeFileSync(planPath, "# Plan\n\n## Goals\n\n1. [/] goal: make the output\n");
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
await flow.commands.get("goals").handler("--auto 1", flow.ctx);
|
||||
await flow.hooks.get("agent_start")({}, flow.ctx);
|
||||
await flow.hooks.get("tool_call")({ toolName: "process", input: { action: "start" } }, flow.ctx);
|
||||
await flow.hooks.get("agent_settled")({}, flow.ctx);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
const autoMessages = () => flow.messages.filter((message) => message.content.includes("Auto-continue is enabled"));
|
||||
expect(autoMessages()).toHaveLength(0);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(autoMessages()).toHaveLength(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
rmSync(flow.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("gives the agent a planning snapshot and blocks work routes", async () => {
|
||||
const flow = setup([]);
|
||||
try {
|
||||
await flow.commands.get("goals").handler("objective", flow.ctx);
|
||||
const planPath = join(flow.cwd, ".pi/plan/session-a-v1.md");
|
||||
expect(flow.entries.at(-1)?.data).toMatchObject({ phase: "planning" });
|
||||
await flow.hooks.get("session_start")({}, flow.ctx);
|
||||
const snapshot = await flow.hooks.get("before_agent_start")({}, flow.ctx);
|
||||
expect(snapshot.message.content).toContain("[PLANNING MODE]");
|
||||
expect(snapshot.message.content).toContain(planPath);
|
||||
|
||||
const writePlan = await flow.hooks.get("tool_call")({ toolName: "write", input: { path: planPath } }, flow.ctx);
|
||||
const writeCode = await flow.hooks.get("tool_call")({ toolName: "write", input: { path: "README.md" } }, flow.ctx);
|
||||
const readShell = await flow.hooks.get("tool_call")({ toolName: "bash", input: { command: "pwd && ls && git log" } }, flow.ctx);
|
||||
const changeDirectoryThenRead = await flow.hooks.get("tool_call")({ toolName: "bash", input: { command: "cd . && ls -la" } }, flow.ctx);
|
||||
const pipeShell = await flow.hooks.get("tool_call")({ toolName: "bash", input: { command: "ls | head" } }, flow.ctx);
|
||||
const pythonWrite = await flow.hooks.get("tool_call")({ toolName: "bash", input: { command: "python -c \"open('README.md', 'w')\"" } }, flow.ctx);
|
||||
const signoff = await flow.tools.get("CompleteGoal").execute("", { goal: "work" }, undefined, undefined, flow.ctx);
|
||||
await flow.hooks.get("session_compact")({}, flow.ctx);
|
||||
const compacted = await flow.hooks.get("context")({ messages: [] }, flow.ctx);
|
||||
|
||||
expect(writePlan).toBeUndefined();
|
||||
expect(writeCode?.block).toBe(true);
|
||||
expect(readShell).toBeUndefined();
|
||||
expect(changeDirectoryThenRead).toBeUndefined();
|
||||
expect(pipeShell?.block).toBe(true);
|
||||
expect(pythonWrite?.block).toBe(true);
|
||||
expect(signoff.isError).toBe(true);
|
||||
expect(compacted.messages.at(-1).content[0].text).toContain("[PLANNING MODE]");
|
||||
} finally {
|
||||
rmSync(flow.cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,638 @@
|
||||
import { mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import goalsExtension from "../src/index.js";
|
||||
import { scheduleCheckIn } from "../src/prompts.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
const shutdowns: Array<() => void> = [];
|
||||
afterEach(() => { for (const shutdown of shutdowns.splice(0)) shutdown(); vi.unstubAllEnvs(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
async function waitFor(predicate: () => boolean, ms = 1500): Promise<void> {
|
||||
const start = Date.now();
|
||||
while (!predicate()) {
|
||||
if (Date.now() - start > ms) throw new Error("timed out waiting for condition");
|
||||
await delay(10);
|
||||
}
|
||||
}
|
||||
function fixture(child = false) {
|
||||
vi.stubEnv("PI_SUBAGENT_AGENT", child ? "goals-worker" : "");
|
||||
const cwd = mkdtempSync(join(tmpdir(), "goals-main-test-")); roots.push(cwd);
|
||||
const entries: any[] = []; const hooks = new Map<string, any>(); const commands = new Map<string, any>(); const tools = new Map<string, any>();
|
||||
const messages: any[] = [];
|
||||
const ctx = { cwd, sessionManager: { getBranch: () => entries, getSessionId: () => "copy-only" }, hasUI: true, ui: {
|
||||
theme: { fg: (_color: string, text: string) => text }, notify: vi.fn(), setStatus: vi.fn(), setWidget: vi.fn(), select: vi.fn(async () => "Ready"), editor: vi.fn(),
|
||||
} };
|
||||
const pi = {
|
||||
on: (event: string, hook: any) => hooks.set(event, hook),
|
||||
appendEntry: (customType: string, data: any) => entries.push({ type: "custom", customType, data: structuredClone(data) }),
|
||||
registerCommand: (name: string, definition: any) => commands.set(name, definition),
|
||||
registerTool: (definition: any) => tools.set(definition.name, definition),
|
||||
sendMessage: (message: any, options: any) => messages.push({ message, options }),
|
||||
sendUserMessage: (content: string, options: any) => messages.push({ message: { content }, options, savedPrompt: true }),
|
||||
getAllTools: vi.fn(() => [
|
||||
{ name: "subagent", parameters: { properties: { agent: {}, title: {} } } },
|
||||
{ name: "subagent_resume", parameters: { properties: { sessionFile: {} } } },
|
||||
{ name: "subagent_kill", parameters: { properties: { id: {} } } },
|
||||
]),
|
||||
};
|
||||
goalsExtension(pi as unknown as ExtensionAPI);
|
||||
hooks.get("session_start")({}, ctx);
|
||||
const command = (value: string) => commands.get("goals").handler(value, ctx);
|
||||
const path = join(cwd, ".pi/plan/copy-only-main.md");
|
||||
const plan = "# Plan\n- [ ] goal: first output\n- [ ] goal: second output\n\n## Log\n";
|
||||
const draft = async () => { await command("new two outputs"); writeFileSync(path, plan); };
|
||||
const shutdown = () => hooks.get("session_shutdown")();
|
||||
shutdowns.push(shutdown);
|
||||
const changed = () => messages.filter((m) => m.message?.content?.includes("Plan changed")).length;
|
||||
const atomicWrite = async (text: string) => {
|
||||
const tmp = `${path}.tmp`;
|
||||
writeFileSync(tmp, text);
|
||||
renameSync(tmp, path);
|
||||
await delay(25);
|
||||
};
|
||||
return { ctx, pi, hooks, tools, commands, messages, command, path, plan, draft, shutdown, changed, atomicWrite, entries };
|
||||
}
|
||||
|
||||
it("shows action choices and autocomplete without starting work", async () => {
|
||||
const f = fixture();
|
||||
f.ctx.ui.select.mockResolvedValueOnce(undefined as any);
|
||||
await f.command("");
|
||||
expect(f.ctx.ui.select).toHaveBeenCalledWith("Goal plan actions", expect.arrayContaining(["new — New plan", "resume — Continue paused work"]));
|
||||
expect(f.messages).toHaveLength(0);
|
||||
expect(f.commands.get("goals").getArgumentCompletions("res")).toEqual([{ value: "resume", label: "resume" }]);
|
||||
});
|
||||
|
||||
it.each(["redy", "start", "two outputs", "status extra", "attach some.md solo extra"])("rejects %s without changing the plan or sending a model prompt", async (text) => {
|
||||
const f = fixture(); await f.draft();
|
||||
const before = readFileSync(f.path, "utf8");
|
||||
const entries = f.entries.length; const messages = f.messages.length;
|
||||
await f.command(text);
|
||||
expect(readFileSync(f.path, "utf8")).toBe(before);
|
||||
expect(f.entries).toHaveLength(entries);
|
||||
expect(f.messages).toHaveLength(messages);
|
||||
});
|
||||
|
||||
it("requires a model argument without clearing the preference", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("model provider/model");
|
||||
const before = readFileSync(f.path, "utf8");
|
||||
await f.command("model");
|
||||
expect(readFileSync(f.path, "utf8")).toBe(before);
|
||||
});
|
||||
|
||||
it.each(["menu", "command"])("enters planning conversation through %s without an objective box or worker launch", async (route) => {
|
||||
const f = fixture();
|
||||
f.ctx.ui.select.mockResolvedValueOnce("new — New plan");
|
||||
await f.command(route === "menu" ? "" : "new");
|
||||
expect(f.entries.at(-1).data.mode).toBe("planning");
|
||||
expect(f.ctx.ui.editor).not.toHaveBeenCalled();
|
||||
expect(f.messages.at(-1).message.content).toContain("Ask what the user wants to achieve");
|
||||
expect(f.hooks.get("tool_call")({ toolName: "subagent" }).block).toBe(true);
|
||||
});
|
||||
|
||||
it("automatically proposes a changed settled draft once and preserves Discuss", async () => {
|
||||
const f = fixture(); await f.draft();
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Discuss");
|
||||
await f.hooks.get("agent_settled")({}, f.ctx);
|
||||
expect(f.messages.some(m => m.message.customType === "goal-plan-proposal" && m.message.content === f.plan)).toBe(true);
|
||||
expect(f.entries.at(-1).data.mode).toBe("planning");
|
||||
const calls = f.ctx.ui.select.mock.calls.length;
|
||||
await f.hooks.get("agent_settled")({}, f.ctx);
|
||||
expect(f.ctx.ui.select).toHaveBeenCalledTimes(calls);
|
||||
writeFileSync(f.path, f.plan.replace("first output", "revised output"));
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Ready");
|
||||
await f.hooks.get("agent_settled")({}, f.ctx);
|
||||
expect(f.entries.at(-1).data.mode).toBe("supervising");
|
||||
});
|
||||
|
||||
it("does not propose an empty draft or a delegated worker's plan", async () => {
|
||||
const f = fixture(); await f.command("new");
|
||||
await f.hooks.get("agent_settled")({}, f.ctx);
|
||||
expect(f.ctx.ui.select).not.toHaveBeenCalled();
|
||||
const child = fixture(true); await child.hooks.get("agent_settled")({}, child.ctx);
|
||||
expect(child.ctx.ui.select).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps Ready in the same chat, sends saved notices and never installs a context hook", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("review");
|
||||
expect(f.entries.at(-1).data.mode).toBe("supervising");
|
||||
expect(f.messages.at(-1).options).toEqual({ deliverAs: "followUp" });
|
||||
expect(f.messages.at(-1).savedPrompt).toBe(true);
|
||||
expect(f.messages.at(-1).message.content).toContain("goals-worker");
|
||||
expect(f.hooks.has("context")).toBe(false);
|
||||
const event = { systemPrompt: "original system" };
|
||||
expect(f.hooks.get("before_agent_start")(event, f.ctx).systemPrompt).toContain("original system");
|
||||
f.hooks.get("session_compact")();
|
||||
expect(f.hooks.get("before_agent_start")(event, f.ctx).message.content).toContain("Current goal mode: supervising");
|
||||
f.shutdown();
|
||||
});
|
||||
|
||||
it("preserves a draft when the wrong subagent package is loaded, and offers explicit solo", async () => {
|
||||
const f = fixture(); await f.draft(); f.pi.getAllTools.mockReturnValue([]);
|
||||
await f.command("ready"); expect(f.entries.at(-1).data.mode).toBe("planning");
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped");
|
||||
await f.command("solo"); expect(f.entries.at(-1).data.mode).toBe("solo");
|
||||
});
|
||||
|
||||
it("rejects a plan changed while the human was reviewing it", async () => {
|
||||
const f = fixture(); await f.draft();
|
||||
f.ctx.ui.select.mockImplementation(async () => { writeFileSync(f.path, "- [ ] goal: substituted\n"); return "Ready"; });
|
||||
await f.command("review"); expect(f.entries.at(-1).data.mode).toBe("planning");
|
||||
});
|
||||
|
||||
it("reloads a paused plan without launching, and retains the public worker session handle", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "child-1", sessionFile: "/tmp/child.jsonl" } });
|
||||
await f.command("stop");
|
||||
expect(f.messages.at(-1).message.content).toContain("Remote stop is NOT yet confirmed");
|
||||
f.hooks.get("session_start")({}, f.ctx);
|
||||
expect(f.hooks.get("tool_call")({ toolName: "subagent_resume" }).block).toBe(true);
|
||||
await f.command("resume");
|
||||
expect(f.messages.at(-1).message.content).toContain("/tmp/child.jsonl");
|
||||
await f.command("exit"); expect(f.entries.at(-1).data.mode).toBe("chat");
|
||||
expect(readFileSync(f.path, "utf8")).toContain("first output");
|
||||
});
|
||||
|
||||
it.each(["FIRST OUTPUT", "renamed output", "duplicate", "historical"])("completion uses exact current subjects (%s)", async (subject) => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
const evidence = join(f.ctx.cwd, "verification.txt"); writeFileSync(evidence, "PASS");
|
||||
const suffix = subject === "duplicate" ? "- [ ] goal: first output\n" : "";
|
||||
const history = "## Log\n- [ ] goal: first output\n";
|
||||
writeFileSync(f.path, "- [ ] goal: first output\n - [ ] unrelated task\n" + suffix + history);
|
||||
const before = readFileSync(f.path, "utf8");
|
||||
await f.tools.get("CompleteGoal").execute("c", { goal: subject === "duplicate" || subject === "historical" ? "first output" : subject, evidence: [evidence], observation: "Read actual output" }, undefined, undefined, f.ctx);
|
||||
const after = readFileSync(f.path, "utf8");
|
||||
if (subject === "renamed output" || subject === "duplicate") expect(after).toBe(before);
|
||||
else { expect(after).toContain("- [x] goal: first output"); expect(after.split("## Log")[1]).toContain("\n- [ ] goal: first output\n"); expect(after).toContain("- [ ] unrelated task"); }
|
||||
});
|
||||
|
||||
it("rejects an existing zero-byte evidence file", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
const evidence = join(f.ctx.cwd, "empty.log"); writeFileSync(evidence, "");
|
||||
const before = readFileSync(f.path, "utf8");
|
||||
const result = await f.tools.get("CompleteGoal").execute("c", { goal: "first output", evidence: [evidence], observation: "claim" }, undefined, undefined, f.ctx);
|
||||
expect(result.content[0].text).toContain("Empty evidence"); expect(readFileSync(f.path, "utf8")).toBe(before);
|
||||
});
|
||||
|
||||
it("requires actual nonempty evidence, distinguishes manual ticks, and retains signoffs on reload", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
const complete = (goal: string, evidence: string[], signal?: AbortSignal) => f.tools.get("CompleteGoal").execute("t", { goal, evidence, observation: "Inspected exact saved bytes" }, signal, undefined, f.ctx);
|
||||
expect((await complete("first output", ["missing.log"])).content[0].text).toContain("Evidence unavailable");
|
||||
mkdirSync(join(f.ctx.cwd, "evidence")); writeFileSync(join(f.ctx.cwd, "evidence/pass.log"), "actual fixture bytes\n");
|
||||
expect((await complete("first output", ["evidence/pass.log"], AbortSignal.abort())).content[0].text).toContain("Cancelled");
|
||||
await complete("first output", ["evidence/pass.log"]);
|
||||
writeFileSync(f.path, readFileSync(f.path, "utf8").replace("[ ] goal: second", "[x] goal: second"));
|
||||
f.hooks.get("session_start")({}, f.ctx);
|
||||
expect(f.ctx.ui.setStatus).toHaveBeenLastCalledWith("goals", "goals: supervising | 1/2 reviewed");
|
||||
expect(f.ctx.ui.setWidget.mock.lastCall?.[1]).toContain("? = completion claim; parent review still required");
|
||||
writeFileSync(f.path, readFileSync(f.path, "utf8").replace("[x] goal: first", "[ ] goal: first"));
|
||||
f.hooks.get("agent_end")({}, f.ctx);
|
||||
expect(f.ctx.ui.setStatus).toHaveBeenLastCalledWith("goals", "goals: supervising | 0/2 reviewed");
|
||||
f.shutdown();
|
||||
});
|
||||
|
||||
it("reviews a plan replaced atomically, and ignores writes that keep the same content", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
await f.atomicWrite(f.plan.replace("## Log", "- discriminator: changed requirement\n## Log"));
|
||||
await waitFor(() => f.changed() === 1);
|
||||
const review = f.messages.find((m) => m.message.content.includes("Plan changed"))?.message.content;
|
||||
expect(review).toContain("Plan changed: ");
|
||||
expect(review).toContain(f.path);
|
||||
await f.atomicWrite(f.plan.replace("## Log", "- discriminator: same requirement again\n## Log"));
|
||||
await waitFor(() => f.changed() === 2);
|
||||
// Rewriting identical bytes must not retrigger the review event hook.
|
||||
const same = f.plan.replace("## Log", "- discriminator: same requirement again\n## Log");
|
||||
writeFileSync(f.path, same); await delay(300);
|
||||
expect(f.changed()).toBe(2);
|
||||
f.shutdown();
|
||||
});
|
||||
|
||||
it("coalesces duplicate plan-change notifications into one review", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
await f.atomicWrite(f.plan.replace("## Log", "- discriminator: first burst edit\n## Log"));
|
||||
await f.atomicWrite(f.plan.replace("## Log", "- discriminator: second burst edit\n## Log"));
|
||||
await waitFor(() => f.changed() === 1);
|
||||
await delay(200);
|
||||
expect(f.changed()).toBe(1);
|
||||
f.shutdown();
|
||||
});
|
||||
|
||||
it("stops plan watching on shutdown and re-arms it on reload without duplicating events", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
f.shutdown();
|
||||
await f.atomicWrite(f.plan.replace("## Log", "- discriminator: ignored while shut down\n## Log"));
|
||||
await delay(150);
|
||||
expect(f.changed()).toBe(0);
|
||||
f.hooks.get("session_start")({}, f.ctx);
|
||||
await f.atomicWrite(f.plan.replace("## Log", "- discriminator: seen after reload\n## Log"));
|
||||
await waitFor(() => f.changed() === 1);
|
||||
expect(f.changed()).toBe(1);
|
||||
f.shutdown();
|
||||
});
|
||||
|
||||
it("does not retrigger a review for its own CompleteGoal plan write", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
mkdirSync(join(f.ctx.cwd, "evidence")); writeFileSync(join(f.ctx.cwd, "evidence/pass.log"), "bytes\n");
|
||||
await f.tools.get("CompleteGoal").execute("t", { goal: "first output", evidence: ["evidence/pass.log"], observation: "inspected" }, undefined, undefined, f.ctx);
|
||||
await delay(200);
|
||||
expect(f.changed()).toBe(0);
|
||||
f.shutdown();
|
||||
});
|
||||
|
||||
it("gives pause/exit the session-bound scheduler job removal guidance", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
await f.command("stop");
|
||||
const stop = f.messages.at(-1).message.content;
|
||||
expect(stop).toContain('goals-copy-only"');
|
||||
expect(stop).toContain("Do not add, enable or recreate any job");
|
||||
expect(stop).not.toContain("interval '1h'");
|
||||
expect(stop).toContain("Remote stop is NOT yet confirmed");
|
||||
await f.command("resume");
|
||||
await f.command("exit");
|
||||
expect(f.messages.at(-1).message.content).toContain('goals-copy-only"');
|
||||
expect(f.entries.at(-1).data.mode).toBe("chat");
|
||||
});
|
||||
|
||||
it("tells the model to remove only its own job after the final review", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
mkdirSync(join(f.ctx.cwd, "evidence")); writeFileSync(join(f.ctx.cwd, "evidence/pass.log"), "bytes\n");
|
||||
let finalText = "";
|
||||
for (const goal of ["first output", "second output"]) {
|
||||
finalText = (await f.tools.get("CompleteGoal").execute("t", { goal, evidence: ["evidence/pass.log"], observation: "inspected" }, undefined, undefined, f.ctx)).content[0].text;
|
||||
}
|
||||
expect(finalText).toContain("All non-cancelled goals are reviewed.");
|
||||
expect(finalText).toContain('job named "goals-copy-only"');
|
||||
expect(finalText).toContain("leave other jobs untouched");
|
||||
f.shutdown();
|
||||
});
|
||||
|
||||
it("retains human-edited and disabled owned schedules without overriding their controls", () => {
|
||||
const guidance = scheduleCheckIn("copy-only", ".pi/plan/copy-only-main.md");
|
||||
expect(guidance).toContain("List first");
|
||||
expect(guidance).toContain("enabled/disabled state unchanged");
|
||||
expect(guidance).toContain("never recreate, overwrite or re-enable");
|
||||
expect(guidance).toContain("no model override");
|
||||
expect(guidance).toContain("Do not reinstall a missing job from a scheduled check-in");
|
||||
expect(guidance).toContain("/schedule-prompts");
|
||||
});
|
||||
|
||||
it("restores context after compaction without reinstalling or overriding scheduler jobs", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
f.hooks.get("session_compact")();
|
||||
const result = f.hooks.get("before_agent_start")({ systemPrompt: "base" }, f.ctx);
|
||||
expect(result.systemPrompt).not.toContain("add one session-bound");
|
||||
expect(result.message.content).toContain(f.path);
|
||||
});
|
||||
|
||||
it("recovers from an unreadable plan after compaction instead of restarting work", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
rmSync(f.path);
|
||||
f.hooks.get("session_compact")();
|
||||
const result = f.hooks.get("before_agent_start")({ systemPrompt: "base" }, f.ctx);
|
||||
expect(result.systemPrompt).toContain("ENOENT");
|
||||
expect(result.systemPrompt).toContain("do not restart completed work");
|
||||
writeFileSync(f.path, f.plan);
|
||||
expect(f.hooks.get("before_agent_start")({ systemPrompt: "base" }, f.ctx).message.content).toContain(f.plan.trim());
|
||||
f.shutdown();
|
||||
});
|
||||
|
||||
it("requires confirmed worker stop before solo takeover and never lets two writers run together", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "child-1", sessionFile: "/tmp/child.jsonl" } });
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Cancel");
|
||||
await f.command("solo");
|
||||
expect(f.entries.at(-1).data.mode).toBe("supervising"); // cancelled
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped");
|
||||
await f.command("solo");
|
||||
expect(f.entries.at(-1).data.mode).toBe("solo");
|
||||
expect(f.hooks.get("tool_call")({ toolName: "subagent" }).block).toBe(true);
|
||||
expect(f.hooks.get("tool_call")({ toolName: "subagent_resume" }).block).toBe(true);
|
||||
expect(f.hooks.get("tool_call")({ toolName: "subagent_kill" })).toBeUndefined();
|
||||
mkdirSync(join(f.ctx.cwd, "evidence")); writeFileSync(join(f.ctx.cwd, "evidence/pass.log"), "bytes\n");
|
||||
const text = (await f.tools.get("CompleteGoal").execute("t", { goal: "first output", evidence: ["evidence/pass.log"], observation: "inspected" }, undefined, undefined, f.ctx)).content[0].text;
|
||||
expect(text).toContain("self-verification");
|
||||
});
|
||||
|
||||
it("attaches an existing plan without restarting completed work, and restores its noted worker session", async () => {
|
||||
const f = fixture();
|
||||
const existing = join(f.ctx.cwd, "existing.md");
|
||||
writeFileSync(existing, "# Plan\n- preferred worker model: deepseek flash\n- worker session: /tmp/attach-child.jsonl\n- [ ] goal: attached goal\n\n## Log\n- previous progress kept\n");
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Previous supervisor confirmed stopped");
|
||||
await f.command(`attach ${existing}`);
|
||||
expect(f.entries.at(-1).data.mode).toBe("planning");
|
||||
expect(f.entries.at(-1).data.plan).toBe(existing);
|
||||
expect(f.messages.at(-1).message.content).toContain("without restarting completed work");
|
||||
expect(f.messages.at(-1).message.content).toContain("/tmp/attach-child.jsonl");
|
||||
});
|
||||
|
||||
it("attaches directly into solo mode and reports the recorded session in status", async () => {
|
||||
const f = fixture();
|
||||
const existing = join(f.ctx.cwd, "existing.md");
|
||||
writeFileSync(existing, "# Plan\n- worker session: /tmp/attach-child.jsonl\n- [ ] goal: attached goal\n\n## Log\n");
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped");
|
||||
await f.command(`attach ${existing} solo`);
|
||||
expect(f.entries.at(-1).data.mode).toBe("solo");
|
||||
expect(f.entries.at(-1).data.worker?.sessionFile).toBe("/tmp/attach-child.jsonl");
|
||||
await f.command("status");
|
||||
expect(f.ctx.ui.notify).toHaveBeenLastCalledWith(expect.stringContaining("/tmp/attach-child.jsonl"), "info");
|
||||
});
|
||||
|
||||
it("rejects attaching a missing or goal-less file", async () => {
|
||||
const f = fixture();
|
||||
await f.command("attach /no/such/plan.md");
|
||||
expect(f.ctx.ui.notify).toHaveBeenLastCalledWith(expect.stringContaining("Cannot read plan"), "error");
|
||||
const goalLess = join(f.ctx.cwd, "notes.md");
|
||||
writeFileSync(goalLess, "# notes\n");
|
||||
await f.command(`attach ${goalLess}`);
|
||||
expect(f.ctx.ui.notify).toHaveBeenLastCalledWith(expect.stringContaining("has no '- [ ] goal:' lines"), "warning");
|
||||
expect(f.entries).toEqual([]); // nothing saved: the session was not attached
|
||||
});
|
||||
|
||||
it("exits planning with the draft preserved and nothing implemented", async () => {
|
||||
const f = fixture(); await f.draft();
|
||||
await f.command("stop");
|
||||
expect(f.ctx.ui.notify).toHaveBeenLastCalledWith(expect.stringContaining("A draft cannot pause"), "warning");
|
||||
const before = f.messages.length;
|
||||
await f.command("exit");
|
||||
expect(f.entries.at(-1).data.mode).toBe("chat");
|
||||
expect(readFileSync(f.path, "utf8")).toContain("first output");
|
||||
expect(f.messages.length).toBe(before); // notify only, no model turn started
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Previous supervisor confirmed stopped");
|
||||
await f.command(`attach ${f.path}`);
|
||||
expect(f.entries.at(-1).data.mode).toBe("planning");
|
||||
});
|
||||
|
||||
it("records the preferred worker model as a visible plan preference", async () => {
|
||||
const f = fixture(); await f.draft();
|
||||
await f.command("model deepseek flash");
|
||||
expect(readFileSync(f.path, "utf8")).toContain("- preferred worker model: deepseek flash");
|
||||
await f.command("status");
|
||||
expect(f.ctx.ui.notify).toHaveBeenLastCalledWith(expect.stringContaining("deepseek flash"), "info");
|
||||
});
|
||||
|
||||
it.each(["solo", "attach"])("%s takeover cannot bypass confirmation or survive a lifecycle change during the menu", async kind => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "child", sessionFile: "/tmp/prior.jsonl" } });
|
||||
let answer!: (choice: string) => void;
|
||||
f.ctx.ui.select.mockImplementationOnce(() => new Promise(resolve => { answer = resolve; }));
|
||||
const takeover = f.command(kind === "solo" ? "solo" : `attach ${f.path} solo`);
|
||||
expect(f.entries.at(-1).data.mode).toBe("supervising");
|
||||
await f.command("stop");
|
||||
answer("Worker confirmed stopped"); await takeover;
|
||||
expect(f.entries.at(-1).data.mode).toBe("paused");
|
||||
expect(f.entries.at(-1).data.workerStopped).not.toBe(true);
|
||||
});
|
||||
|
||||
it("attach solo requires stop confirmation for a noted worker even in a fresh session", async () => {
|
||||
const f = fixture(); const path = join(f.ctx.cwd, "saved.md");
|
||||
writeFileSync(path, `# Plan\n- worker session: /tmp/known.jsonl\n${f.plan}`);
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Cancel");
|
||||
await f.command(`attach ${path} solo`);
|
||||
expect(f.entries).toHaveLength(0);
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped");
|
||||
await f.command(`attach ${path} solo`);
|
||||
expect(f.entries.at(-1).data).toMatchObject({ mode: "solo", workerStopped: true, worker: { sessionFile: "/tmp/known.jsonl" } });
|
||||
expect(readFileSync(path, "utf8")).toContain("worker session: /tmp/known.jsonl");
|
||||
});
|
||||
|
||||
it("retains the stopped session reference without permanently blocking another plan", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "child", sessionFile: "/tmp/prior.jsonl" } });
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped"); await f.command("solo");
|
||||
const other = join(f.ctx.cwd, "another.md"); writeFileSync(other, "- [ ] goal: next\n## Log\n");
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Previous supervisor confirmed stopped");
|
||||
await f.command(`attach ${other}`);
|
||||
expect(f.entries.at(-1).data).toMatchObject({ mode: "planning", plan: other, workerStopped: true, worker: { sessionFile: "/tmp/prior.jsonl" } });
|
||||
await f.command("ready");
|
||||
f.hooks.get("tool_call")({ toolName: "subagent_resume" });
|
||||
expect(f.entries.at(-1).data.workerStopped).toBe(false);
|
||||
await f.command("solo");
|
||||
expect(f.ctx.ui.notify).toHaveBeenLastCalledWith(expect.stringContaining("still pending"), "warning");
|
||||
});
|
||||
|
||||
it("solo closes a pending plan watcher and sends removal-only scheduler guidance", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
await f.atomicWrite(f.plan.replace("first output", "changed output"));
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped"); await f.command("solo");
|
||||
expect(f.messages.at(-1).message.content).toContain('job named "goals-copy-only" bound to session "copy-only"');
|
||||
expect(f.messages.at(-1).message.content).toContain("Do not add, enable or recreate any job");
|
||||
await delay(250);
|
||||
await f.atomicWrite(f.plan.replace("first output", "solo output"));
|
||||
await delay(250);
|
||||
expect(f.changed()).toBe(0);
|
||||
});
|
||||
|
||||
it.each(["missing", "empty", "directory"])("%s plan snapshots never erase signoffs and resync retries after repair", async failure => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
writeFileSync(join(f.ctx.cwd, "proof.log"), "PASS\n");
|
||||
await f.tools.get("CompleteGoal").execute("c", { goal: "first output", evidence: ["proof.log"], observation: "Observed PASS" }, undefined, undefined, f.ctx);
|
||||
const signed = readFileSync(f.path, "utf8");
|
||||
if (failure === "empty") writeFileSync(f.path, "");
|
||||
else { rmSync(f.path); if (failure === "directory") mkdirSync(f.path); }
|
||||
await delay(250); // also exercise unavailable read after debounce has expired
|
||||
f.hooks.get("agent_end")({}, f.ctx);
|
||||
expect(f.entries.at(-1).data.signoffs["first output"]).toBeDefined();
|
||||
f.hooks.get("session_compact")();
|
||||
const unavailable = f.hooks.get("before_agent_start")({ systemPrompt: "base" }, f.ctx);
|
||||
expect(unavailable.systemPrompt).toContain("unavailable");
|
||||
expect(unavailable.message).toBeUndefined();
|
||||
if (failure === "directory") rmSync(f.path, { recursive: true });
|
||||
writeFileSync(f.path, signed);
|
||||
const resync = f.hooks.get("before_agent_start")({ systemPrompt: "base" }, f.ctx);
|
||||
expect(resync.message.content).toContain("Observed PASS");
|
||||
await delay(250);
|
||||
expect(f.entries.at(-1).data.signoffs["first output"]).toBeDefined();
|
||||
expect(f.changed()).toBe(0);
|
||||
});
|
||||
|
||||
it("ignores post-completion maintenance but reviews evidence, requirement or manual reopening changes", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
writeFileSync(join(f.ctx.cwd, "proof.log"), "PASS\n");
|
||||
for (const goal of ["first output", "second output"]) await f.tools.get("CompleteGoal").execute("c", { goal, evidence: ["proof.log"], observation: "PASS" }, undefined, undefined, f.ctx);
|
||||
const signed = readFileSync(f.path, "utf8");
|
||||
await f.atomicWrite(signed.replace("## Log", "## Log\n- recap: finished"));
|
||||
await delay(250);
|
||||
expect(f.changed()).toBe(0); // Log-only edits are history, not requirements
|
||||
// Worker-authored evidence above the Log must surface: a supervisor caught a worker's
|
||||
// contradictory evidence block through exactly this event (LUCID3, 2026-09-10).
|
||||
await f.atomicWrite(signed.replace("## Log", " - evidence: proof.log\n## Log\n- recap: finished"));
|
||||
await waitFor(() => f.changed() === 1);
|
||||
await f.atomicWrite(signed.replace("## Log", "- discriminator: exact bytes and trailing newline\n## Log"));
|
||||
await waitFor(() => f.changed() === 2);
|
||||
await f.atomicWrite(signed.replace("[x] goal: first", "[ ] goal: first"));
|
||||
await waitFor(() => f.changed() === 3);
|
||||
expect(f.entries.at(-1).data.signoffs["first output"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("cancelled goals do not prevent final cleanup, and solo writes self-verification in Log", async () => {
|
||||
const f = fixture(); await f.draft();
|
||||
writeFileSync(f.path, f.plan.replace("[ ] goal: second", "[-] goal: second") + "\n## Appendix\nPreserved context\n");
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped"); await f.command("solo");
|
||||
writeFileSync(join(f.ctx.cwd, "proof.log"), "PASS\n");
|
||||
const done = await f.tools.get("CompleteGoal").execute("c", { goal: "first output", evidence: ["proof.log"], observation: "Exact bytes observed" }, undefined, undefined, f.ctx);
|
||||
expect(done.content[0].text).toContain("All non-cancelled goals are reviewed");
|
||||
const text = readFileSync(f.path, "utf8");
|
||||
expect(text).toContain("Solo self-verification:");
|
||||
expect(text).not.toContain("Parent review:");
|
||||
expect(text.indexOf("Solo self-verification:")).toBeLessThan(text.indexOf("## Appendix"));
|
||||
expect(text).toContain("Preserved context");
|
||||
});
|
||||
|
||||
it("lineage-only child attaches its plan with goal-only widget, retains task context, and cannot complete", async () => {
|
||||
const f = fixture(true);
|
||||
const supplied = join(f.ctx.cwd, "supplied.md");
|
||||
const text = "- [/] goal: exact file\n - [ ] verify bytes\n## Log\n - [ ] archived task\n";
|
||||
writeFileSync(supplied, text);
|
||||
const before = f.hooks.get("before_agent_start")({ systemPrompt: "base" }, f.ctx);
|
||||
expect(before.systemPrompt).toContain("AttachGoalPlan");
|
||||
const attach = f.tools.get("AttachGoalPlan");
|
||||
await attach.execute("a", { path: "supplied.md" }, undefined, undefined, f.ctx);
|
||||
expect(f.entries.at(-1).data.plan).toBeUndefined(); // no cwd heuristics
|
||||
await attach.execute("a", { path: supplied }, undefined, undefined, f.ctx);
|
||||
expect(f.ctx.ui.setWidget.mock.lastCall?.[1]).toEqual(["▸ exact file"]);
|
||||
expect(f.ctx.ui.setWidget.mock.lastCall?.[1].join("\n")).not.toContain("archived task");
|
||||
expect(readFileSync(supplied, "utf8")).toBe(text);
|
||||
f.hooks.get("session_start")({}, f.ctx);
|
||||
expect(f.hooks.get("before_agent_start")({ systemPrompt: "base" }, f.ctx).message.content).toContain("exact file");
|
||||
const completion = await f.tools.get("CompleteGoal").execute("c", { goal: "exact file", evidence: [], observation: "claim" }, undefined, undefined, f.ctx);
|
||||
expect(completion.content[0].text).toContain("only to the active parent");
|
||||
});
|
||||
|
||||
it.each(["solo", "supervising"])("%s widget omits long tasks without altering the plan", async mode => {
|
||||
const f = fixture(); await f.draft();
|
||||
const text = "- [/] goal: first output\n - [ ] a long task that should never take widget space\n- [ ] goal: second output\n## Log\n";
|
||||
writeFileSync(f.path, text);
|
||||
if (mode === "solo") { f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped"); await f.command("solo"); }
|
||||
else await f.command("ready");
|
||||
expect(f.ctx.ui.setWidget.mock.lastCall?.[1]).toEqual(["▸ first output", "○ second output"]);
|
||||
expect(readFileSync(f.path, "utf8")).toBe(text);
|
||||
});
|
||||
|
||||
it.each(["solo", "supervising"])("%s upkeep is turn-driven, folds Log, resets on working-set edits, and never starts a turn", async mode => {
|
||||
const f = fixture(); await f.draft();
|
||||
if (mode === "solo") { f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped"); await f.command("solo"); }
|
||||
else await f.command("ready");
|
||||
f.hooks.get("before_agent_start")({ systemPrompt: "base" }, f.ctx);
|
||||
const reminders = () => f.messages.filter(m => m.message.customType === "pi-goals-upkeep");
|
||||
f.hooks.get("turn_end")({}, f.ctx); // observe initial working set
|
||||
for (let i = 0; i < 7; i++) {
|
||||
writeFileSync(f.path, f.plan + `- historical recap ${i}\n`);
|
||||
f.hooks.get("turn_end")({}, f.ctx);
|
||||
}
|
||||
expect(reminders()).toHaveLength(0);
|
||||
f.hooks.get("turn_end")({}, f.ctx);
|
||||
expect(reminders()).toHaveLength(1);
|
||||
expect(reminders()[0].options).toEqual({ triggerTurn: false });
|
||||
expect(reminders()[0].message.content).toContain(f.path);
|
||||
expect(reminders()[0].message.content).not.toContain("first output");
|
||||
for (let i = 0; i < 16; i++) f.hooks.get("turn_end")({}, f.ctx);
|
||||
expect(reminders()).toHaveLength(1);
|
||||
expect(reminders()[0].message.content).not.toContain("historical recap");
|
||||
for (let i = 0; i < 7; i++) f.hooks.get("turn_end")({}, f.ctx);
|
||||
writeFileSync(f.path, f.plan.replace("first output", "refined output"));
|
||||
f.hooks.get("turn_end")({}, f.ctx);
|
||||
expect(reminders()).toHaveLength(1);
|
||||
await f.command("stop");
|
||||
for (let i = 0; i < 10; i++) f.hooks.get("turn_end")({}, f.ctx);
|
||||
expect(reminders()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("extra subagent launches are recorded as helpers and never steal the implementation identity", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "impl", sessionFile: "/tmp/impl.jsonl" } });
|
||||
expect(f.entries.at(-1).data).toMatchObject({ worker: { id: "impl", sessionFile: "/tmp/impl.jsonl" }, helpers: [] });
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "reviewer", sessionFile: "/tmp/review.jsonl" } });
|
||||
expect(f.entries.at(-1).data).toMatchObject({ worker: { id: "impl" }, helpers: [{ id: "reviewer", sessionFile: "/tmp/review.jsonl" }] });
|
||||
// a repeated helper launch updates its record instead of duplicating it
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "reviewer-2", sessionFile: "/tmp/review.jsonl" } });
|
||||
expect(f.entries.at(-1).data.helpers).toEqual([{ id: "reviewer-2", sessionFile: "/tmp/review.jsonl" }]);
|
||||
// resuming the worker keeps the binding and refreshes its id
|
||||
f.hooks.get("tool_result")({ toolName: "subagent_resume", details: { id: "impl-2", sessionFile: "/tmp/impl.jsonl" } });
|
||||
expect(f.entries.at(-1).data).toMatchObject({ worker: { id: "impl-2", sessionFile: "/tmp/impl.jsonl" }, helpers: [{ id: "reviewer-2" }] });
|
||||
});
|
||||
|
||||
it("pending launch counter survives concurrent launches until every result lands", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
f.hooks.get("tool_call")({ toolName: "subagent" });
|
||||
f.hooks.get("tool_call")({ toolName: "subagent" });
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "a", sessionFile: "/tmp/a.jsonl" } });
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped");
|
||||
await f.command("solo");
|
||||
expect(f.entries.at(-1).data.mode).toBe("supervising"); // one launch still pending
|
||||
expect(f.ctx.notify ?? f.ctx.ui.notify).toHaveBeenLastCalledWith(expect.stringContaining("still pending"), "warning");
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "b", sessionFile: "/tmp/b.jsonl" } });
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Worker confirmed stopped");
|
||||
await f.command("solo");
|
||||
expect(f.entries.at(-1).data.mode).toBe("solo");
|
||||
expect(f.entries.at(-1).data).toMatchObject({ worker: { id: "a" }, helpers: [{ id: "b" }] });
|
||||
});
|
||||
|
||||
it("late worker results invalidate a takeover menu but do not disable plan watching", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
let answer!: (choice: string) => void;
|
||||
f.ctx.ui.select.mockImplementationOnce(() => new Promise(resolve => { answer = resolve; }));
|
||||
const solo = f.command("solo");
|
||||
f.hooks.get("tool_result")({ toolName: "subagent", details: { id: "late-child", sessionFile: "/tmp/late.jsonl" } });
|
||||
answer("Worker confirmed stopped"); await solo;
|
||||
expect(f.entries.at(-1).data.mode).toBe("supervising");
|
||||
expect(f.entries.at(-1).data.workerStopped).toBe(false);
|
||||
await f.atomicWrite(f.plan.replace("first output", "new requirement"));
|
||||
await waitFor(() => f.changed() === 1);
|
||||
});
|
||||
|
||||
it("changed plan or shutdown during takeover never grants solo permission", async () => {
|
||||
const f = fixture(); await f.draft();
|
||||
f.ctx.ui.select.mockImplementationOnce(async () => { writeFileSync(f.path, f.plan.replace("first", "changed")); return "Worker confirmed stopped"; });
|
||||
await f.command("solo");
|
||||
expect(f.entries.at(-1).data.mode).toBe("planning");
|
||||
expect(f.ctx.ui.notify).toHaveBeenLastCalledWith(expect.stringContaining("Plan changed during takeover"), "warning");
|
||||
f.ctx.ui.select.mockImplementationOnce(async () => { f.shutdown(); return "Worker confirmed stopped"; });
|
||||
await f.command("solo");
|
||||
expect(f.entries.at(-1).data.mode).toBe("planning");
|
||||
});
|
||||
|
||||
it("requires explicit supervisor ownership confirmation when attaching an existing plan", async () => {
|
||||
const f = fixture(); const path = join(f.ctx.cwd, "shared.md");
|
||||
writeFileSync(path, f.plan);
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Cancel");
|
||||
await f.command(`attach ${path}`);
|
||||
expect(f.entries).toHaveLength(0);
|
||||
f.ctx.ui.select.mockResolvedValueOnce("Previous supervisor confirmed stopped");
|
||||
await f.command(`attach ${path}`);
|
||||
expect(f.entries.at(-1).data).toMatchObject({ mode: "planning", plan: path });
|
||||
});
|
||||
|
||||
it("does not approve cancelled goals or display current completion for an unavailable plan", async () => {
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
writeFileSync(f.path, "- [-] goal: cancelled output\n## Log\n");
|
||||
writeFileSync(join(f.ctx.cwd, "evidence.log"), "verified\n");
|
||||
const reply = await f.tools.get("CompleteGoal").execute("t", { goal: "cancelled output", evidence: ["evidence.log"], observation: "read" }, undefined, undefined, f.ctx);
|
||||
expect(reply.content[0].text).toContain("no sign-off recorded");
|
||||
expect(readFileSync(f.path, "utf8")).toContain("[-]");
|
||||
rmSync(f.path);
|
||||
f.hooks.get("agent_end")({}, f.ctx);
|
||||
expect(f.ctx.ui.setWidget).toHaveBeenLastCalledWith("goals", [expect.stringContaining("unavailable")]);
|
||||
});
|
||||
|
||||
it("uses scheduler storage for ownership and the real public user controls", () => {
|
||||
const prompt = scheduleCheckIn("session-1", "/plan.md");
|
||||
expect(prompt).toContain(".pi/schedule-prompts.json");
|
||||
expect(prompt).toContain("tool text does not expose binding");
|
||||
expect(prompt).toContain("Never use cleanup");
|
||||
expect(prompt).toContain("deletes disabled jobs");
|
||||
expect(prompt).toContain("schedule_prompt update");
|
||||
expect(prompt).not.toContain("with /schedule-prompts");
|
||||
});
|
||||
|
||||
it("keeps interactive workers open and supplies the supervisor identity for Intercom reports", async () => {
|
||||
const agent = readFileSync(new URL("../agents/goals-worker.md", import.meta.url), "utf8");
|
||||
expect(agent).toContain("auto-exit: false");
|
||||
const f = fixture(); await f.draft(); await f.command("ready");
|
||||
expect(f.messages.at(-1).message.content).toContain("supervisor Intercom session copy-only");
|
||||
const role = f.hooks.get("before_agent_start")({ systemPrompt: "base" }, f.ctx).systemPrompt;
|
||||
expect(role).toContain("your Intercom session ID copy-only");
|
||||
expect(role).toContain("stop workers before /reload");
|
||||
expect(role).not.toContain("Reports arrive automatically");
|
||||
});
|
||||
@@ -1,33 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildJudgeArgs } from "../src/index.js";
|
||||
|
||||
describe("buildJudgeArgs", () => {
|
||||
it("omits --model when judgeModel is null (pi uses its configured default; never a pre-emptive 'no model' failure)", () => {
|
||||
const args = buildJudgeArgs(null);
|
||||
expect(args).not.toContain("--model");
|
||||
// an empty --model "" would make every sign-off silently inconclusive -- guard against it
|
||||
const i = args.indexOf("--model");
|
||||
expect(i).toBe(-1);
|
||||
});
|
||||
|
||||
it("includes --model <ref> when an explicit/session model is set", () => {
|
||||
const args = buildJudgeArgs("openrouter/~anthropic/claude-haiku-latest");
|
||||
const i = args.indexOf("--model");
|
||||
expect(i).not.toBe(-1);
|
||||
expect(args[i + 1]).toBe("openrouter/~anthropic/claude-haiku-latest");
|
||||
});
|
||||
|
||||
it("always sets --no-session, --no-extensions, the read-only tool allowlist, and edit/write exclusion", () => {
|
||||
for (const m of [null, "some/model"]) {
|
||||
const args = buildJudgeArgs(m);
|
||||
expect(args).toContain("--no-session");
|
||||
expect(args).toContain("--no-extensions"); // a broken global extension must not take down sign-offs
|
||||
expect(args).toContain("--tools");
|
||||
expect(args.some((a) => a.startsWith("read,grep,find,ls"))).toBe(true);
|
||||
// no bash: the judge must never be able to execute (or re-run a 10-hour verify) or mutate
|
||||
expect(args.some((a) => a.includes("bash"))).toBe(false);
|
||||
expect(args).toContain("--exclude-tools");
|
||||
expect(args.some((a) => a.includes("edit") && a.includes("write"))).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
it("declares current entry and bundled extension resources that exist after install", () => {
|
||||
const manifest = JSON.parse(readFileSync("package.json", "utf8"));
|
||||
expect(manifest.pi.extensions[0]).toBe("./src/index.ts");
|
||||
for (const path of manifest.pi.extensions) expect(existsSync(resolve(path)), path).toBe(true);
|
||||
for (const name of ["pi-subagents", "pi-intercom", "pi-schedule-prompt"]) {
|
||||
expect(manifest.dependencies[name]).toBeTruthy();
|
||||
expect(manifest.bundledDependencies).toContain(name);
|
||||
}
|
||||
expect(manifest.dependencies["pi-subagents"]).toContain("953c6f6d2fc7d8a5c956c30cd77c51bad697c2a4");
|
||||
expect(existsSync("agents/goals-worker.md")).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { planViews } from "../src/plan-view.js";
|
||||
|
||||
it("keeps outcome, preferences and discriminators without tasks or history", () => {
|
||||
const plan = "# Outcome\nBeat random, not just plot it.\n## User preferences\nKeep costs low.\n## Goals\n1. [ ] goal: repair\n - discriminator: beats random\n - subtle failure mode: plot exists but result fails\n - tasks:\n 1. [x] draw plot\n - evidence:\n - old output\n2. [ ] goal: confirm\n## Task list\n- [ ] run it\n## Appendix\nunapproved idea";
|
||||
const views = planViews(plan);
|
||||
for (const text of ["Beat random", "Keep costs low", "goal: repair", "discriminator: beats random", "subtle failure mode", "goal: confirm"]) expect(views.short).toContain(text);
|
||||
for (const text of ["draw plot", "old output", "run it", "unapproved idea"]) expect(views.short).not.toContain(text);
|
||||
expect(views.long).toContain("draw plot");
|
||||
expect(views.long).toContain("old output");
|
||||
expect(views.long).not.toContain("unapproved idea");
|
||||
});
|
||||
|
||||
it("omits only named worker identity fields from review while retaining them in full context", () => {
|
||||
const base = "# Plan\n- preferred worker model: provider/model\n- [ ] goal: result\n - discriminator: exact bytes";
|
||||
const metadata = "\n- Active worker: worker-1\n- worker session: /saved.jsonl\n- worker intercom session: uuid";
|
||||
expect(planViews(base + metadata).short).toBe(planViews(base).short);
|
||||
expect(planViews(base + metadata).long).toContain("/saved.jsonl");
|
||||
expect(planViews(base.replace("exact bytes", "approximate match")).short).not.toBe(planViews(base).short);
|
||||
expect(planViews(base.replace("[ ]", "[x]")).short).not.toBe(planViews(base).short);
|
||||
});
|
||||
|
||||
it("notifies on goal and task changes but not on identity bookkeeping or log edits", () => {
|
||||
const base = "# Plan\n- [ ] goal: result\n## Task list\n- [ ] run it\n- worker session: /saved.jsonl\n## Log\nfirst entry";
|
||||
const baseView = planViews(base).notify;
|
||||
// identity bookkeeping: silent
|
||||
expect(planViews(base.replace("/saved.jsonl", "/moved.jsonl")).notify).toBe(baseView);
|
||||
// log edits: silent
|
||||
expect(planViews(base.replace("first entry", "second entry")).notify).toBe(baseView);
|
||||
// worker ticking a task: review event (field catch, LUCID3 2026-09-10)
|
||||
expect(planViews(base.replace("- [ ] run it", "- [x] run it")).notify).not.toBe(baseView);
|
||||
// goal edits: review event
|
||||
expect(planViews(base.replace("[ ] goal: result", "[x] goal: result")).notify).not.toBe(baseView);
|
||||
});
|
||||
|
||||
it("stops at history and preserves a manual goal tick", () => {
|
||||
const view = planViews("# Plan\n1. [x] goal: result\n## Log\n1. [ ] goal: historical");
|
||||
expect(view.short).toContain("[x] goal: result");
|
||||
expect(view.long).not.toContain("historical");
|
||||
});
|
||||
+5
-14
@@ -1,30 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { judgeSystem, planDrafting, planningState, reminder, resync } from "../src/prompts.js";
|
||||
import { planDrafting } from "../src/prompts.js";
|
||||
|
||||
describe("planning prompt", () => {
|
||||
it("requires fact finding or a focused question before a goal", () => {
|
||||
expect(planDrafting).toContain("Use read-only repository tools or web search when either can\nresolve a fact.");
|
||||
expect(planDrafting).toContain("ask the human to confirm your interpretation");
|
||||
expect(planDrafting).toContain("approve an editorial or other preference choice");
|
||||
expect(planDrafting).toContain("Do not use a question quota");
|
||||
expect(planDrafting).toContain("Briefly reframe the request in your own words to check comprehension");
|
||||
expect(planDrafting).toContain("point as unknown; do not silently replace it with an inference or turn it into a new blocking decision");
|
||||
expect(planDrafting).toContain("answer materially reduces uncertainty\nwhile discovering the right plan");
|
||||
expect(planDrafting).toContain("self-contained: state the relevant\ncontext, use the human's language and ASD-STE100");
|
||||
expect(planDrafting).toContain("placeholder goal such as \"work out the thing\"");
|
||||
expect(planDrafting).toContain("object, observable result, settled scope, and required approval");
|
||||
});
|
||||
|
||||
it("restores the same rule after compaction", () => {
|
||||
expect(planningState(".pi/plan/test.md")).toContain("web search\nwhen either can resolve a fact.");
|
||||
expect(planningState(".pi/plan/test.md")).toContain("choice that needs their approval");
|
||||
expect(planningState(".pi/plan/test.md")).toContain("self-contained round with relevant context and a recommendation");
|
||||
expect(planDrafting).toContain("Only withhold Ready for an unanswered choice that changes scope, spending, or the user-visible result");
|
||||
});
|
||||
|
||||
it("anchors work and sign-off to the user-visible result", () => {
|
||||
expect(planDrafting).toContain("## User-visible result");
|
||||
expect(planDrafting).toContain("Take it from the original request, not from your implementation plan");
|
||||
expect(planDrafting).toContain("Future work may not defer any artifact or action named there");
|
||||
expect(reminder("plan", ".pi/plan/test.md")).toContain("latest message outranks this plan");
|
||||
expect(resync("plan", ".pi/plan/test.md", "Compacted.")).toContain("amend the plan rather than preserving an obsolete decision");
|
||||
expect(judgeSystem).toContain("Task fidelity?");
|
||||
expect(judgeSystem).toContain("Agent-inferred scope is not authority");
|
||||
});
|
||||
});
|
||||
|
||||
+83
-33
@@ -1,5 +1,6 @@
|
||||
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { once } from "node:events";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { createServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
@@ -7,14 +8,17 @@ import { StringDecoder } from "node:string_decoder";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
type RpcMessage = { type: string; id?: string; method?: string; [key: string]: unknown };
|
||||
type ModelRequest = { messages: Array<{ role: string; content: unknown }> };
|
||||
|
||||
class RpcClient {
|
||||
readonly messages: RpcMessage[] = [];
|
||||
stderr = "";
|
||||
private readonly waiters: Array<{ predicate: (message: RpcMessage) => boolean; resolve: (message: RpcMessage) => void }> = [];
|
||||
|
||||
constructor(readonly process: ChildProcessWithoutNullStreams) {
|
||||
const decoder = new StringDecoder("utf8");
|
||||
let buffer = "";
|
||||
process.stderr.on("data", (chunk) => { this.stderr += chunk; });
|
||||
process.stdout.on("data", (chunk) => {
|
||||
buffer += decoder.write(chunk);
|
||||
while (buffer.includes("\n")) {
|
||||
@@ -37,7 +41,14 @@ class RpcClient {
|
||||
waitFor(predicate: (message: RpcMessage) => boolean, after = 0): Promise<RpcMessage> {
|
||||
const existing = this.messages.slice(after).find(predicate);
|
||||
if (existing) return Promise.resolve(existing);
|
||||
return new Promise((resolvePromise) => this.waiters.push({ predicate, resolve: resolvePromise }));
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.waiters.splice(this.waiters.indexOf(waiter), 1);
|
||||
reject(new Error(`RPC wait timed out: ${this.stderr}\n${JSON.stringify(this.messages.slice(-12))}`));
|
||||
}, 8_000);
|
||||
const waiter = { predicate, resolve: (message: RpcMessage) => { clearTimeout(timer); resolvePromise(message); } };
|
||||
this.waiters.push(waiter);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,69 +59,108 @@ function streamResponse(response: import("node:http").ServerResponse, delta: obj
|
||||
response.end("data: [DONE]\n\n");
|
||||
}
|
||||
|
||||
const isSelect = (message: RpcMessage) => message.type === "extension_ui_request" && message.method === "select";
|
||||
const isEditor = (message: RpcMessage) => message.type === "extension_ui_request" && message.method === "editor";
|
||||
const systemText = (request: ModelRequest) => request.messages.filter(message => ["system", "developer"].includes(message.role)).map(message => message.content).join("\n");
|
||||
|
||||
describe("RPC review flow", () => {
|
||||
it("opens Refine's editor before it starts the revision turn", async () => {
|
||||
it.each(["Edit", "Discuss"])("automatically proposes a draft, handles %s, then enters the supervisor role on Ready", async (choice) => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "pi-goals-rpc-"));
|
||||
let requestCount = 0;
|
||||
const requests: ModelRequest[] = [];
|
||||
const plan = "# Plan\n\n## Goals\n\n1. [ ] goal: name the output\n - subtle failure mode: the output has no name\n - discriminator: the plan names the output\n\n## Log\n";
|
||||
let planPath = "";
|
||||
const server = createServer((_request, response) => {
|
||||
requestCount++;
|
||||
if (requestCount === 1) {
|
||||
const server = createServer(async (request, response) => {
|
||||
let body = "";
|
||||
for await (const chunk of request) body += chunk;
|
||||
requests.push(JSON.parse(body));
|
||||
if (requests.length === 1) {
|
||||
streamResponse(response, {
|
||||
tool_calls: [{
|
||||
index: 0,
|
||||
id: "write-plan",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "write",
|
||||
arguments: JSON.stringify({
|
||||
path: planPath,
|
||||
content: "# Plan\n\n## Goals\n\n1. [ ] goal: name the output\n - subtle failure mode: the output has no name\n - discriminator: the plan names the output\n\n## Log\n\n## Interview\n",
|
||||
}),
|
||||
},
|
||||
index: 0, id: "write-plan", type: "function",
|
||||
function: { name: "write", arguments: JSON.stringify({ path: planPath, content: plan }) },
|
||||
}],
|
||||
}, "tool_calls");
|
||||
return;
|
||||
}
|
||||
streamResponse(response, { content: "Plan drafted." }, "stop");
|
||||
streamResponse(response, { content: "Plan inspected." }, "stop");
|
||||
});
|
||||
await new Promise<void>((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
|
||||
await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Offline model did not bind a TCP port.");
|
||||
|
||||
const pi = spawn(resolve("node_modules/.bin/pi"), [
|
||||
"--mode", "rpc", "--no-session", "--model", "offline/test",
|
||||
"--mode", "rpc", "--no-session", "--no-extensions", "--model", "offline/test",
|
||||
"-e", resolve("test/fixtures/offline-model.ts"),
|
||||
"-e", resolve("test/fixtures/subagent-schema.ts"),
|
||||
"-e", resolve("src/index.ts"),
|
||||
], {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
// Pi/gpt-6-astra: test the parent role even when vitest itself runs in a worker.
|
||||
...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("PI_SUBAGENT_") && !name.startsWith("PI_GOALS_"))),
|
||||
PI_CODING_AGENT_DIR: join(cwd, ".agent"),
|
||||
PI_GOALS_OFFLINE_MODEL_URL: `http://127.0.0.1:${address.port}`,
|
||||
},
|
||||
});
|
||||
const client = new RpcClient(pi);
|
||||
const exited = once(pi, "exit");
|
||||
try {
|
||||
client.send({ type: "get_state", id: "state" });
|
||||
const state = await client.waitFor((message) => message.type === "response" && message.id === "state");
|
||||
const sessionId = (state.data as { sessionId: string }).sessionId;
|
||||
planPath = join(cwd, ".pi", "plan", `${sessionId}-v1.md`);
|
||||
planPath = join(cwd, ".pi", "plan", `${sessionId}-main.md`);
|
||||
|
||||
client.send({ type: "prompt", id: "goals", message: "/goals work out the thing" });
|
||||
const review = await client.waitFor((message) => message.type === "extension_ui_request" && message.method === "select");
|
||||
client.send({ type: "extension_ui_response", id: review.id, value: "Refine" });
|
||||
const editor = await client.waitFor((message) => message.type === "extension_ui_request" && message.method === "editor");
|
||||
expect(requestCount).toBe(2);
|
||||
client.send({ type: "prompt", id: "goals", message: "/goals new work out the thing" });
|
||||
const review = await client.waitFor(isSelect);
|
||||
expect(review.options).toEqual(["Ready", "Discuss", "Edit", "Cancel"]);
|
||||
expect(review.title).toContain(planPath);
|
||||
const proposal = client.messages.find(message => message.type === "message_end" && (message.message as { customType?: string })?.customType === "goal-plan-proposal");
|
||||
expect(proposal?.message).toMatchObject({ content: plan, display: true });
|
||||
expect(readFileSync(planPath, "utf8")).toBe(plan);
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(systemText(requests[0])).toContain("Plan only in");
|
||||
|
||||
const revisionStart = client.messages.length;
|
||||
client.send({ type: "extension_ui_response", id: editor.id, value: "Name the produced file." });
|
||||
await client.waitFor((message) => message.type === "agent_end", revisionStart);
|
||||
expect(requestCount).toBe(3);
|
||||
const choiceStart = client.messages.length;
|
||||
client.send({ type: "extension_ui_response", id: review.id, value: choice });
|
||||
let approvedPlan = plan;
|
||||
if (choice === "Edit") {
|
||||
const editor = await client.waitFor(isEditor, choiceStart);
|
||||
expect(editor.prefill).toBe(plan);
|
||||
expect(requests).toHaveLength(2);
|
||||
approvedPlan = plan.replace("the plan names the output", "the plan names output.txt and its exact bytes");
|
||||
const editStart = client.messages.length;
|
||||
client.send({ type: "extension_ui_response", id: editor.id, value: approvedPlan });
|
||||
await client.waitFor(message => message.type === "extension_ui_request" && message.method === "setWidget", editStart);
|
||||
expect(readFileSync(planPath, "utf8")).toBe(approvedPlan);
|
||||
expect(requests).toHaveLength(2);
|
||||
} else {
|
||||
await client.waitFor(message => message.type === "agent_end", choiceStart);
|
||||
expect(requests).toHaveLength(3);
|
||||
expect(systemText(requests[2])).toContain("Plan only in");
|
||||
expect(JSON.stringify(requests[2].messages.at(-1))).toContain("Discuss the current draft");
|
||||
expect(client.messages.slice(choiceStart).filter(isEditor)).toEqual([]);
|
||||
}
|
||||
const beforeReady = requests.length;
|
||||
const reopenStart = client.messages.length;
|
||||
client.send({ type: "prompt", id: "review", message: "/goals review" });
|
||||
const ready = await client.waitFor(isSelect, reopenStart);
|
||||
expect(requests).toHaveLength(beforeReady);
|
||||
const readyStart = client.messages.length;
|
||||
client.send({ type: "extension_ui_response", id: ready.id, value: "Ready" });
|
||||
await client.waitFor(message => message.type === "agent_end", readyStart);
|
||||
expect(requests).toHaveLength(beforeReady + 1);
|
||||
const supervisor = requests.at(-1)!;
|
||||
expect(systemText(supervisor)).toContain("You are the goal supervisor in the main chat");
|
||||
expect(systemText(supervisor)).not.toContain("Plan only in");
|
||||
expect(JSON.stringify(supervisor.messages)).toContain(JSON.stringify(approvedPlan).slice(1, -1));
|
||||
expect(client.messages.filter(message => message.type === "tool_execution_start").map(message => message.toolName)).toEqual(["write"]);
|
||||
expect(client.messages.filter(message => message.type === "extension_error")).toEqual([]);
|
||||
console.log(`RPC ${choice}: visible automatic proposal; ${choice === "Edit" ? "editor saved exact plan without model call" : "discussion retained planning role without editor"}; Ready request used supervisor role; only write executed.`);
|
||||
} finally {
|
||||
pi.kill();
|
||||
server.close();
|
||||
await exited;
|
||||
await new Promise<void>((done) => server.close(() => done()));
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 15_000);
|
||||
}, 25_000);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { report, summarize } from "../scripts/session-usage.mjs";
|
||||
|
||||
const start = "2026-09-10T06:00:00.000Z";
|
||||
const end = "2026-09-10T07:00:00.000Z";
|
||||
const request = (timestamp: string, model = "a") => ({
|
||||
type: "message", timestamp, message: { role: "assistant", provider: "test", model,
|
||||
usage: { input: 10, cacheRead: 100, cacheWrite: 5, output: 20, reasoning: 8, totalTokens: 135 } },
|
||||
});
|
||||
|
||||
it("excludes inherited history and counts repeated cached input without adding reasoning twice", () => {
|
||||
const result = summarize([request("2026-09-09T06:00:00.000Z"), request(start), request(end, "b")], start, end);
|
||||
expect(result).toMatchObject({ calls: 2, input: 20, cacheRead: 200, cacheWrite: 10, output: 40, totalTokens: 270 });
|
||||
expect(result.models.map((m: any) => m.model)).toEqual(["test/a", "test/b"]);
|
||||
});
|
||||
|
||||
it("uses the latest planning start and the same interval for both sessions", () => {
|
||||
const supervisor = { entries: [
|
||||
{ type: "custom", customType: "pi-goals-main-supervisor-v1", timestamp: start, id: "boundary", data: { mode: "planning", plan: "plan.md" } },
|
||||
request(start),
|
||||
] };
|
||||
const result = report(supervisor, { entries: [request(end)] }, end);
|
||||
expect(result.since).toBe(start);
|
||||
expect(result.elapsedHours).toBe(1);
|
||||
expect(result.sessions.map((s: any) => s.output)).toEqual([20, 20]);
|
||||
expect(() => report({ entries: [] }, { entries: [] }, end)).toThrow("No recorded planning start");
|
||||
});
|
||||
|
||||
it("reports missing usage and rejects invalid recorded token counts", () => {
|
||||
const missing = { type: "message", timestamp: start, message: { role: "assistant" } };
|
||||
expect(summarize([missing], start, end).missingUsage).toBe(1);
|
||||
const invalid = request(start); invalid.message.usage.input = Number.NaN;
|
||||
expect(() => summarize([invalid], start, end)).toThrow("Invalid usage.input");
|
||||
});
|
||||
@@ -1,32 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { tickGoal } from "../src/index.js";
|
||||
|
||||
const plan = `# Plan
|
||||
|
||||
## Goals
|
||||
|
||||
1. [/] goal: Implement the cache layer
|
||||
- tasks:
|
||||
1. [x] wire client
|
||||
2. [ ] goal: Ship the docs
|
||||
|
||||
## Log
|
||||
`;
|
||||
|
||||
describe("tickGoal (sign-off ticks the goal; agent only ticks on wording drift)", () => {
|
||||
it("ticks the exact-matching goal line, case-insensitive, leaving subtasks alone", () => {
|
||||
const out = tickGoal(plan, "implement the CACHE layer");
|
||||
expect(out).toContain("1. [x] goal: Implement the cache layer");
|
||||
expect(out).toContain("1. [x] wire client"); // subtask untouched (was already x)
|
||||
expect(out).toContain("2. [ ] goal: Ship the docs"); // other goal untouched
|
||||
});
|
||||
|
||||
it("returns null on wording drift (fuzzy matching is the judge's job, not TypeScript's)", () => {
|
||||
expect(tickGoal(plan, "Implement caching")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the subject matches more than one goal line", () => {
|
||||
const dup = `${plan}3. [ ] goal: Ship the docs\n`;
|
||||
expect(tickGoal(dup, "Ship the docs")).toBeNull();
|
||||
});
|
||||
});
|
||||
+4
-2
@@ -6,10 +6,12 @@
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"jsx": "react-jsx",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"declaration": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx"]
|
||||
"include": [
|
||||
"src/**/*.ts",
|
||||
"src/**/*.tsx"
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user