fix: pin the loop's phase and keep its session locked on resume

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-03 04:04:09 -08:00
1 parent 2acfd8907d
commit c1e32b8aca
6 files changed
+212 -55

No files matched your search

+1 -1
View File
@@ -418,7 +418,7 @@ pub fn unbacked_marks(
.as_array()
.map(|all| {
all.iter()
.filter(|p| p["marker"].as_str() == Some("x"))
.filter(|p| crate::loop_driver::checklist_done(p))
.filter_map(|p| u32::try_from(p["number"].as_u64()?).ok())
.collect()
})
+165 -38
View File
@@ -494,14 +494,15 @@ fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
// ---------------------------------------------------------- pure judgment
/// The first prompt of a phase's fresh agent.
pub fn phase_prompt(spec: &str, setup: &LoopSetup) -> String {
/// The first prompt of a phase's fresh agent. `phase` names the phase to build,
/// so the agent never picks one by its own rules and reports another.
pub fn phase_prompt(spec: &str, phase: u32, setup: &LoopSetup) -> String {
let skill = if setup.review {
"plan2code-3-implement-review"
} else {
"plan2code-3-implement"
};
let mut prompt = format!("/{skill} {spec}/overview.md --web --loop");
let mut prompt = format!("/{skill} {spec}/overview.md --web --loop --phase {phase}");
if setup.review {
if setup.fix_mode == FixMode::Smart {
prompt.push_str(" --fix smart");
@@ -882,6 +883,12 @@ pub fn validate_spec(project: &Path, spec: &str) -> Result<(), String> {
Ok(())
}
/// Whether a phase row from `specs.mjs status` is done in its Phase Checklist:
/// the script's own `checklist` state, so `[X]` and `[?]` count as `[x]` does.
pub fn checklist_done(phase: &Value) -> bool {
matches!(phase["checklist"].as_str(), Some("complete" | "assumed"))
}
static NEXT_RUN: AtomicU64 = AtomicU64::new(1);
/// Everything Start checks before the confirm: the spec, the saved setup, the
@@ -927,7 +934,10 @@ pub fn prepare_with(
all.iter()
.filter_map(|p| {
let n = u32::try_from(p["number"].as_u64()?).ok()?;
if p["marker"].as_str() == Some("x") && !rebuilt.contains(&n) {
// Done is what `specs.mjs` calls done: `[x]`, `[X]` and `[?]`.
// A blocked `[!]` phase stays in, so the loop stops on it
// with its reason rather than building past it.
if checklist_done(p) && !rebuilt.contains(&n) {
return None;
}
Some(PhaseRecord {
@@ -1347,7 +1357,7 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> {
rec.phase_started_at = Instant::now();
rec.activity_checked = Instant::now();
rec.last_activity = SystemTime::now();
phase_prompt(&rec.spec, &rec.setup)
phase_prompt(&rec.spec, rec.phases[index].n, &rec.setup)
};
// Said before the agent starts: the banner is up from the moment of Start,
// and says what is happening between phases.
@@ -2564,8 +2574,14 @@ fn finish(ctx: &Ctx) {
} else {
format!("All {built} phases built")
};
let markdown = summary_markdown(&rec, &date);
let written = write_atomic(&spec_dir.join(&file), &markdown);
// Written before Finalize starts, saying what is planned; rewritten below
// when what happened differs, so the file never claims a Finalize that
// did not start.
let planned = finalize_note(&rec.setup, stop_requested(ctx), None);
let written = write_atomic(
&spec_dir.join(&file),
&summary_markdown(&rec, &date, &planned),
);
if written.is_ok() {
// The project holds the report now. A failure here only means the next
// loop on this spec starts from this report, so it is not worth a stop.
@@ -2578,6 +2594,13 @@ fn finish(ctx: &Ctx) {
} else {
None
};
let happened = finalize_note(&rec.setup, skip_finalize, finalize_error.as_deref());
if written.is_ok() && happened != planned {
let _ = write_atomic(
&spec_dir.join(&file),
&summary_markdown(&rec, &date, &happened),
);
}
// The page always hears the end; a summary that could not be written or a
// Finalize that could not start is said in the line.
let mut said = line.clone();
@@ -2726,9 +2749,32 @@ pub(crate) fn write_atomic(file: &Path, text: &str) -> Result<(), String> {
})
}
/// `LOOP-SUMMARY-<date>.md`: the setup used, each phase, the end state and the
/// Finalize offer.
pub fn summary_markdown(rec: &RunningRecord, date: &str) -> String {
/// What the summary says about Finalize.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FinalizeNote {
/// After last: Stop and offer Finalize.
Offer,
/// After last: Run Finalize, and it is starting.
Starting,
/// After last: Run Finalize, but Stop now came first.
Skipped,
/// After last: Run Finalize, and it could not start (why, on one line).
Failed(String),
}
/// The Finalize note for the setup, a Stop now and a start's error.
pub fn finalize_note(setup: &LoopSetup, stopped: bool, error: Option<&str>) -> FinalizeNote {
match (setup.after_last, stopped, error) {
(AfterLast::OfferFinalize, _, _) => FinalizeNote::Offer,
(AfterLast::RunFinalize, true, _) => FinalizeNote::Skipped,
(AfterLast::RunFinalize, false, Some(e)) => FinalizeNote::Failed(one_line(e)),
(AfterLast::RunFinalize, false, None) => FinalizeNote::Starting,
}
}
/// `LOOP-SUMMARY-<date>.md`: the setup used, each phase, the end state and
/// what became of Finalize.
pub fn summary_markdown(rec: &RunningRecord, date: &str, finalize: &FinalizeNote) -> String {
let setup = &rec.setup;
let name = rec.spec.strip_prefix("specs/").unwrap_or(&rec.spec);
let yes = |on: bool| if on { "on" } else { "off" };
@@ -2771,17 +2817,17 @@ pub fn summary_markdown(rec: &RunningRecord, date: &str) -> String {
"\n## End state\n\nPhases built by this loop: {}.\n\n",
phase_rows(rec).as_array().map_or(0, Vec::len)
));
if setup.after_last == AfterLast::RunFinalize {
md.push_str(&format!(
"Finalize was started in a fresh session: `/plan2code-4-finalize {}/overview.md`.\n",
rec.spec
));
} else {
md.push_str(&format!(
"Next: run Finalize with `/plan2code-4-finalize {}/overview.md`.\n",
rec.spec
));
}
let command = format!("`/plan2code-4-finalize {}/overview.md`", rec.spec);
md.push_str(&match finalize {
FinalizeNote::Starting => format!("Finalize was started in a fresh session: {command}.\n"),
FinalizeNote::Offer => format!("Next: run Finalize with {command}.\n"),
FinalizeNote::Skipped => format!(
"Finalize was not started, as you asked the loop to stop. Next: run Finalize with {command}.\n"
),
FinalizeNote::Failed(why) => format!(
"Finalize could not start ({why}). Next: run Finalize with {command}.\n"
),
});
md
}
@@ -2868,11 +2914,41 @@ mod tests {
fn the_summary_never_holds_the_web_address() {
let mut rec = record("specs/x", vec![phase(1)]);
rec.setup.notify_url = "https://e.com/hook?token=secret".into();
let md = summary_markdown(&rec, "2026-11-01");
let md = summary_markdown(&rec, "2026-11-01", &FinalizeNote::Offer);
assert!(md.contains("Send a notification when it stops: on"));
assert!(!md.contains("secret"));
}
#[test]
fn the_summary_says_what_became_of_finalize() {
let mut rec = record("specs/x", vec![phase(1)]);
assert_eq!(
finalize_note(&rec.setup, true, Some("x")),
FinalizeNote::Offer
);
rec.setup.after_last = AfterLast::RunFinalize;
let note = |stopped, error| finalize_note(&rec.setup, stopped, error);
assert_eq!(note(false, None), FinalizeNote::Starting);
assert_eq!(note(true, None), FinalizeNote::Skipped);
assert_eq!(
note(false, Some("no\nagent")),
FinalizeNote::Failed("no agent".into())
);
let md = |n: FinalizeNote| summary_markdown(&rec, "2026-11-01", &n);
assert!(md(FinalizeNote::Starting).contains("Finalize was started in a fresh session"));
for n in [
FinalizeNote::Skipped,
FinalizeNote::Failed("no agent".into()),
] {
let text = md(n);
assert!(!text.contains("was started"), "{text}");
assert!(text
.contains("Next: run Finalize with `/plan2code-4-finalize specs/x/overview.md`."));
}
assert!(md(FinalizeNote::Failed("no agent".into()))
.contains("Finalize could not start (no agent)."));
}
#[test]
fn a_new_setup_starts_on_smart_pick_and_best_guess() {
assert_eq!(LoopSetup::default().fix_mode, FixMode::Smart);
@@ -2937,26 +3013,26 @@ mod tests {
fn the_prompt_follows_review_fix_and_guess() {
let mut s = setup();
assert_eq!(
phase_prompt("specs/x", &s),
"/plan2code-3-implement-review specs/x/overview.md --web --loop --fix critical,warning,suggestion"
phase_prompt("specs/x", 1, &s),
"/plan2code-3-implement-review specs/x/overview.md --web --loop --phase 1 --fix critical,warning,suggestion"
);
s.fix = vec![FixLevel::Warning];
s.on_question = OnQuestion::Guess;
assert_eq!(
phase_prompt("specs/x", &s),
"/plan2code-3-implement-review specs/x/overview.md --web --loop --fix warning --guess"
phase_prompt("specs/x", 3, &s),
"/plan2code-3-implement-review specs/x/overview.md --web --loop --phase 3 --fix warning --guess"
);
s.fix_mode = FixMode::Smart;
assert!(phase_prompt("specs/x", &s).contains(" --fix smart --guess"));
assert!(phase_prompt("specs/x", 1, &s).contains(" --fix smart --guess"));
s.fix.clear();
s.fix_mode = FixMode::Levels;
s.on_question = OnQuestion::Pause;
assert!(!phase_prompt("specs/x", &s).contains("--fix"));
assert!(!phase_prompt("specs/x", 1, &s).contains("--fix"));
s.review = false;
s.fix = vec![FixLevel::Critical];
assert_eq!(
phase_prompt("specs/x", &s),
"/plan2code-3-implement specs/x/overview.md --web --loop"
phase_prompt("specs/x", 2, &s),
"/plan2code-3-implement specs/x/overview.md --web --loop --phase 2"
);
}
@@ -3305,23 +3381,38 @@ second line"
fn the_prompt_orders_levels_fixed_and_drops_fix_without_review() {
let mut s = setup();
s.fix = vec![FixLevel::Suggestion, FixLevel::Critical];
assert!(phase_prompt("specs/x", &s).ends_with(" --fix critical,suggestion"));
assert!(phase_prompt("specs/x", 1, &s).ends_with(" --fix critical,suggestion"));
s.fix_mode = FixMode::Smart;
assert!(phase_prompt("specs/x", &s).ends_with("--web --loop --fix smart"));
assert!(!phase_prompt("specs/x", &s).contains("critical"));
assert!(phase_prompt("specs/x", 1, &s).ends_with("--web --loop --phase 1 --fix smart"));
assert!(!phase_prompt("specs/x", 1, &s).contains("critical"));
s.review = false;
assert_eq!(
phase_prompt("specs/x", &s),
"/plan2code-3-implement specs/x/overview.md --web --loop"
phase_prompt("specs/x", 1, &s),
"/plan2code-3-implement specs/x/overview.md --web --loop --phase 1"
);
s.fix_mode = FixMode::Levels;
s.on_question = OnQuestion::Guess;
assert_eq!(
phase_prompt("specs/x", &s),
"/plan2code-3-implement specs/x/overview.md --web --loop --guess"
phase_prompt("specs/x", 1, &s),
"/plan2code-3-implement specs/x/overview.md --web --loop --phase 1 --guess"
);
}
#[test]
fn done_is_the_checklist_state_so_capital_x_and_assumed_phases_count() {
for state in ["complete", "assumed"] {
assert!(checklist_done(
&json!({ "marker": "X", "checklist": state })
));
}
for state in ["pending", "in-progress", "blocked", "unknown"] {
assert!(!checklist_done(
&json!({ "marker": "x", "checklist": state })
));
}
assert!(!checklist_done(&json!({ "marker": "x" })));
}
#[test]
fn an_unknown_result_is_not_approved() {
let mut o = passed();
@@ -3503,7 +3594,7 @@ second line"
..ReportEntry::default()
});
rec.step = Step::Commit;
let md = summary_markdown(&rec, "2026-11-01");
let md = summary_markdown(&rec, "2026-11-01", &FinalizeNote::Offer);
assert!(md.contains(
"| Phase 3: Driver \\| core | a1b2c3d | Add the driver | 0 | 1 | 0 | 0 | 0 | 0 |"
));
@@ -4676,6 +4767,42 @@ second line"
assert!(!confirm_text(&rec).contains("You are on"));
}
#[test]
fn start_skips_phases_specs_mjs_calls_done_and_keeps_a_blocked_one() {
if !harness_ready("checklist states") {
return;
}
let repo = throwaway_repo("checklist-states");
let spec = repo.join("specs/lunch");
std::fs::write(
spec.join("overview.md"),
"# Lunch - Overview\n\n## Phase Checklist\n\n- [X] [Phase 1: P1](./phase-1.md)\n- [!] [Phase 2: P2](./phase-2.md)\n- [?] [Phase 3: P3](./phase-3.md)\n- [ ] [Phase 4: P4](./phase-4.md)\n",
)
.unwrap();
for n in [1, 4] {
std::fs::write(
spec.join(format!("phase-{n}.md")),
format!("# Phase {n}: P{n}\n\n## Tasks\n\n- [ ] **Task {n}.1:** First\n"),
)
.unwrap();
}
git_in(&repo, &["add", "-A"]);
git_in(&repo, &["commit", "-q", "-m", "checklist states"]);
let rec = prepare_with(
&repo,
"specs/lunch",
prepare_setup(),
&LoopReport::new("specs/lunch", "now"),
PermissionMode::Bypass,
true,
false,
)
.expect("prepare");
let numbers: Vec<u32> = rec.phases.iter().map(|p| p.n).collect();
assert_eq!(numbers, vec![2, 4]);
assert!(phase_prompt(&rec.spec, rec.phases[0].n, &rec.setup).contains(" --phase 2"));
}
#[test]
fn the_stop_screen_leaves_out_what_was_dirty_at_start() {
if !harness_ready("own dirty") {
+14 -1
View File
@@ -237,10 +237,19 @@ test("each bad loopOutcome field is refused with a message naming it", () => {
assert.deepEqual(tryPatch(loopState(), { loopOutcome: edge }).problems, [], "100 characters, 50 entries and 200 characters are the limits, not over them");
});
test("an unfixed finding's title and file are one line, as in the fixed and skipped lists", () => {
const o = goodOutcome();
o.review.unfixed = [{ level: "suggestion", title: "Name\nthe timer", file: "src/x.js\nsrc/y.js" }];
const problems = tryPatch(loopState(), { loopOutcome: o }).problems.join("\n");
assert.match(problems, /review\.unfixed\[0\]\.title must be a non-empty one-line string/);
assert.match(problems, /review\.unfixed\[0\]\.file must be a one-line string when present/);
});
test("loopOutcome is refused outside a loop session and a second time", () => {
const unlocked = loopState();
delete unlocked.loop;
assert.match(tryPatch(unlocked, { loopOutcome: goodOutcome() }).problems.join("\n"), /loopOutcome: is only accepted in a loop session/);
assert.match(tryPatch(unlocked, { loopOutcome: goodOutcome() }).problems.join("\n"), /--workflow <yours> --loop, then post this again/, "the refusal says how to lock the session again");
const first = tryPatch(loopState(), { loopOutcome: goodOutcome() });
assert.deepEqual(first.problems, []);
@@ -560,6 +569,9 @@ test("loop-setup: GET /loop-setup lists the phases left for a spec and refuses a
"- [x] **Phase 1:** Setup - [phase-1.md](phase-1.md)",
"- [ ] **Phase 2:** Build the screen - [phase-2.md](phase-2.md)",
"- [/] **Phase 3:** Ship it - [phase-3.md](phase-3.md)",
"- [X] **Phase 4:** Done in capitals - [phase-4.md](phase-4.md)",
"- [?] **Phase 5:** Assumed done - [phase-5.md](phase-5.md)",
"- [!] **Phase 6:** Blocked - [phase-6.md](phase-6.md)",
"",
"## Notes",
"",
@@ -592,7 +604,8 @@ test("loop-setup: GET /loop-setup lists the phases left for a spec and refuses a
const demo = await get("?spec=specs/demo");
assert.equal(demo.status, 200);
assert.deepEqual(demo.body.phasesLeft, [{ n: 2, name: "Build the screen" }, { n: 3, name: "Ship it" }]);
// Done as specs.mjs reads it: [x], [X] and [?]. A blocked phase is still left, as the app's Start counts it.
assert.deepEqual(demo.body.phasesLeft, [{ n: 2, name: "Build the screen" }, { n: 3, name: "Ship it" }, { n: 6, name: "Blocked" }]);
assert.equal(demo.body.suggestedQuickCheck, "npm run build");
assert.equal(demo.body.remembered, false);
+24 -10
View File
@@ -15,7 +15,12 @@ approve.
`loopOutcome` and `handledBy` are refused. If it exits 3, the run is not inside
the app: say "Loop mode runs only inside the Plan2Code desktop app." in the
terminal and continue as an ordinary run with the person's sign-off. Skip
nothing below unless that `open` succeeded.
nothing below unless that `open` succeeded. Every later `open --resume` in
this run (the server went away: `chat` or `wait` exit 20) carries `--loop`
too, as `open --resume <sid> --workflow <yours> --loop`: a resume without it
unlocks the session, and the `loopOutcome` post is then refused.
- `--phase <N>`: the phase the app is building. Build exactly that one (see
Choosing the phase); the app refuses a report that names another.
- `--fix <levels>`: a comma list from `critical`, `warning`, `suggestion`, the
levels to fix in the one fix round. Absent means findings are reported, not
fixed.
@@ -30,7 +35,7 @@ approve.
## What changes in loop mode
- Pick the phase without asking (Choosing the phase).
- Build the phase `--phase` names, without asking (Choosing the phase).
- No sign-off card, no "Approve this phase", no Show me it working, no Continue
offer.
- Never run `specs.mjs mark --to done`, and never set `[x]` on the phase in
@@ -61,14 +66,23 @@ shows as Build, so do not invent new ones in loop mode. Keep `cleared` and
## Choosing the phase
Run `node "<S>/specs.mjs" status specs/<feature>`. A phase whose checklist marker
is `[/]` goes first; otherwise take `next.phase.number` (the first of
`next.options` when `next.action` is `choose`). Never post the "Resume?" question
or the parallel-phase pick. Set the phase in progress with
`specs.mjs mark <spec> --phase N --to in-progress`, exactly as an ordinary run
does: that mark is allowed, and only `--to done` is the app's. When `next.action`
is `none` or `checkoff` (no open phase), post a `loopOutcome` with
`result: "failed"`, `reason: "other"` and
The phase is N from `--phase N`, whatever `next` in `specs.mjs status` would
pick. Never post the "Resume?" question or the parallel-phase pick. Run
`node "<S>/specs.mjs" status specs/<feature>` and find phase N in `phases`:
- Its `checklist` is `pending` or `in-progress`: build it. Set it in progress with
`specs.mjs mark <spec> --phase N --to in-progress`, exactly as an ordinary run
does: that mark is allowed, and only `--to done` is the app's.
- It is `blocked` (`[!]`): build nothing; post a `loopOutcome` with
`result: "failed"`, `reason: "blocked"`, its `blockedTasks` ids (like `2.4`)
in `tasks.blocked` and `summary: "Phase N is marked blocked in overview.md"`.
- It is `complete` or `assumed`, or not in the checklist: build nothing; post
`result: "failed"`, `reason: "other"` and
`summary: "Phase N is not an open phase in this spec"`.
No `--phase` (an older app): take `next.phase.number` (the first of
`next.options` when `next.action` is `choose`), and when `next.action` is `none`
or `checkoff` post `result: "failed"`, `reason: "other"` and
`summary: "No open phase left in this spec"`.
## Questions and cards the loop handles
+5 -3
View File
@@ -572,7 +572,9 @@ export function applyPatch(state, patch) {
case "loopOutcome":
// The skill's one report of a phase built under the loop. The shape is
// checked by validate(); here only who may send it, and how often.
if (!state.loop?.driving) throw new Error(rule("", "loopOutcome", "is only accepted in a loop session"));
if (!state.loop?.driving) {
throw new Error(rule("", "loopOutcome", "is only accepted in a loop session; a resume without --loop unlocked it, so run open --resume <sid> --workflow <yours> --loop, then post this again"));
}
if (state.loopOutcome !== undefined) throw new Error(rule("", "loopOutcome", "was already posted for this session"));
next.loopOutcome = v;
break;
@@ -1143,9 +1145,9 @@ export function loopOutcomeProblems(o) {
r.unfixed.forEach((u, i) => {
if (!isPlainObject(u)) return bad(`review.unfixed[${i}]`, "must be an object { level, title, file? }");
if (!LOOP_LEVELS.includes(u.level)) bad(`review.unfixed[${i}].level`, `must be one of ${LOOP_LEVELS.join(", ")}`);
if (typeof u.title !== "string" || !u.title.trim()) bad(`review.unfixed[${i}].title`, "must be a non-empty string");
if (typeof u.title !== "string" || !u.title.trim() || /[\r\n]/.test(u.title)) bad(`review.unfixed[${i}].title`, "must be a non-empty one-line string");
else prose(`review.unfixed[${i}].title`, u.title);
if (u.file !== undefined && typeof u.file !== "string") bad(`review.unfixed[${i}].file`, "must be a string when present");
if (u.file !== undefined && (typeof u.file !== "string" || /[\r\n]/.test(u.file))) bad(`review.unfixed[${i}].file`, "must be a one-line string when present");
else prose(`review.unfixed[${i}].file`, u.file);
});
}
+3 -2
View File
@@ -32,7 +32,7 @@ import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
import { specKey } from "./workspace.mjs";
import { readLoopSetup, saveLoopSetup } from "./loop-setup.mjs";
import { phaseChecklist } from "./spec-files.mjs";
import { MARKERS, phaseChecklist } from "./spec-files.mjs";
import {
PR_HOST_KINDS,
readSubagentSetting,
@@ -1334,8 +1334,9 @@ function loopSetupGet(req, res, ctx, url) {
let phasesLeft = [];
try {
const overview = fs.readFileSync(path.join(loopProject(ctx), spec, "overview.md"), "utf8");
// Done as specs.mjs reads it ([x], [X], [?]), the same rule the app's Start uses.
phasesLeft = phaseChecklist(overview)
.filter((p) => p.marker !== "x" && p.marker !== "X")
.filter((p) => !["complete", "assumed"].includes(MARKERS[p.marker]))
.map((p) => ({ n: p.number, name: p.name }));
} catch {
/* no overview.md: nothing to build */