From 3ec8358cf88f4917841b646638327c0c7007e430 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 17:50:07 -0400 Subject: [PATCH 01/26] feat(8-1): add the plan judge's spine and member walk A submitted plan needs one pure entry point that judges it against the phase's facts before anything records it. This adds the plan module, the facts T9 fills, the refusal type and the accepted plan, and reads each of the plan's ten members in a fixed order, keeping every text as written. --- crates/baley-core/src/lib.rs | 1 + crates/baley-core/src/plan/content.rs | 134 +++++++++++++++ crates/baley-core/src/plan/fixtures.rs | 220 +++++++++++++++++++++++++ crates/baley-core/src/plan/judge.rs | 198 ++++++++++++++++++++++ crates/baley-core/src/plan/mod.rs | 17 ++ 5 files changed, 570 insertions(+) create mode 100644 crates/baley-core/src/plan/content.rs create mode 100644 crates/baley-core/src/plan/fixtures.rs create mode 100644 crates/baley-core/src/plan/judge.rs create mode 100644 crates/baley-core/src/plan/mod.rs diff --git a/crates/baley-core/src/lib.rs b/crates/baley-core/src/lib.rs index a2b47bd1..a484ff5c 100644 --- a/crates/baley-core/src/lib.rs +++ b/crates/baley-core/src/lib.rs @@ -10,6 +10,7 @@ pub mod catalog; pub mod checkout; pub mod forge; pub mod guard; +pub mod plan; pub mod policy; pub mod questions; pub mod reconcile; diff --git a/crates/baley-core/src/plan/content.rs b/crates/baley-core/src/plan/content.rs new file mode 100644 index 00000000..1d02e683 --- /dev/null +++ b/crates/baley-core/src/plan/content.rs @@ -0,0 +1,134 @@ +//! Step (1) of the plan judge: the plan's own members read in a fixed order +//! (PLN-R11, D-03), the first fault answering `typed-content` with its +//! path. No text is trimmed or rewritten. + +use serde_json::{Map, Value}; + +use super::judge::{Plan, PlanRefusal}; + +/// Reads a plan into the accepted plan, each member in the judge's order: +/// `phase`, `stories`, `files`, `directories`, `goal`, `context`, `notes`, +/// `tasks`, `evidence_map`, then the presence of `questions`, whose value +/// step (2) judges. +pub(super) fn read(value: &Value) -> Result { + let Value::Object(plan) = value else { + return Err(PlanRefusal::TypedContent { path: None }); + }; + let phase = whole(plan.get("phase")).ok_or_else(|| PlanRefusal::typed("phase"))?; + let stories = list(plan, "stories")? + .iter() + .enumerate() + .map(|(n, story)| { + whole(Some(story)).ok_or_else(|| PlanRefusal::typed(format!("stories[{n}]"))) + }) + .collect::, _>>()?; + let files = list(plan, "files")?.clone(); + let directories = list(plan, "directories")?.clone(); + let goal = text(plan, "goal")?; + let context = text(plan, "context")?; + let notes = text(plan, "notes")?; + let tasks = list(plan, "tasks")?.clone(); + let evidence_map = list(plan, "evidence_map")?.clone(); + let questions = plan + .get("questions") + .ok_or_else(|| PlanRefusal::typed("questions"))? + .clone(); + Ok(Plan { + phase, + stories, + files, + directories, + goal, + context, + notes, + tasks, + evidence_map, + questions, + }) +} + +/// A whole number, or `None` when the value is missing or anything else. +fn whole(value: Option<&Value>) -> Option { + value.and_then(Value::as_u64) +} + +/// The list member `name`, refused naming it when missing or not a list. +fn list<'a>(plan: &'a Map, name: &str) -> Result<&'a Vec, PlanRefusal> { + match plan.get(name) { + Some(Value::Array(entries)) => Ok(entries), + _ => Err(PlanRefusal::typed(name)), + } +} + +/// The text member `name` as written, blank allowed, refused naming it when +/// missing or not text. +fn text(plan: &Map, name: &str) -> Result { + match plan.get(name) { + Some(Value::String(text)) => Ok(text.clone()), + _ => Err(PlanRefusal::typed(name)), + } +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use serde_json::json; + + use crate::plan::PlanRefusal; + use crate::plan::fixtures::{accepted, f1, p0, p1, refusal, typed, with, without}; + + #[test] + fn a_plan_member_missing_or_of_another_type_accepted_is_caught() { + let facts = f1(); + assert_eq!( + refusal(&json!([p1()]), &facts), + PlanRefusal::TypedContent { path: None } + ); + for member in [ + "phase", + "stories", + "files", + "directories", + "goal", + "context", + "notes", + "tasks", + "evidence_map", + "questions", + ] { + assert_eq!( + refusal(&without(p1(), "", member), &facts), + typed(member), + "without {member}" + ); + } + let cases = [ + (with(p1(), "", "phase", json!(8.5)), "phase"), + (with(p1(), "", "stories", json!("1")), "stories"), + (with(p1(), "", "stories", json!(["1"])), "stories[0]"), + (with(p1(), "", "goal", json!(3)), "goal"), + (with(p1(), "", "tasks", json!({})), "tasks"), + (with(p1(), "", "evidence_map", json!(null)), "evidence_map"), + ]; + for (plan, path) in cases { + assert_eq!(refusal(&plan, &facts), typed(path), "{plan}"); + } + } + + #[test] + fn an_accepted_plan_trimmed_or_an_empty_member_refused_is_caught() { + let facts = f1(); + let plan = with( + with(p1(), "", "goal", json!(" Judge a plan whole. ")), + "", + "context", + json!(""), + ); + let plan = accepted(&plan, &facts); + assert_eq!(plan.goal(), " Judge a plan whole. "); + assert_eq!(plan.context(), ""); + assert!(accepted(&p0(), &facts).stories().is_empty()); + } +} diff --git a/crates/baley-core/src/plan/fixtures.rs b/crates/baley-core/src/plan/fixtures.rs new file mode 100644 index 00000000..7976ae05 --- /dev/null +++ b/crates/baley-core/src/plan/fixtures.rs @@ -0,0 +1,220 @@ +//! The plan judge's test data, written out from design 0005 and the phase's +//! decisions, never from running the judge: one copy every test of the +//! module reads. + +// Later tasks of the plan read the builders this one does not. +#![allow(dead_code)] + +use serde_json::{Value, json}; + +use super::{CommittedStory, CurrentTruth, Plan, PlanFacts, PlanRefusal, judge_plan}; + +fn truth( + id: &str, + version: u32, + trigger: &str, + observer: &str, + outcome: &str, + human_verify: Option<&str>, +) -> CurrentTruth { + CurrentTruth { + id: id.into(), + version, + trigger: trigger.into(), + observer: observer.into(), + outcome: outcome.into(), + human_verify: human_verify.map(str::to_owned), + } +} + +/// F1: committed stories 1 then 2, no approved items, size 0, no capacity. +pub(super) fn f1() -> PlanFacts { + PlanFacts { + stories: vec![ + CommittedStory { + id: 1, + truths: vec![ + truth( + "t1", + 1, + "a plan names a task file outside its lease", + "the session", + "lease, a valid refusal", + None, + ), + truth( + "t2", + 2, + "the owner opens a plan preview", + "the owner", + "every task title in order", + Some("a browser"), + ), + ], + }, + CommittedStory { + id: 2, + truths: vec![truth( + "t1", + 3, + "a session reads an approved plan", + "the session", + "each check level", + None, + )], + }, + ], + approved: Vec::new(), + size: 0, + capacity: None, + } +} + +/// F0: F1 with both stories holding no truth. +pub(super) fn f0() -> PlanFacts { + let mut facts = f1(); + for story in &mut facts.stories { + story.truths.clear(); + } + facts +} + +/// F2: F1 with story 1 holding no truth. +pub(super) fn f2() -> PlanFacts { + let mut facts = f1(); + facts.stories[0].truths.clear(); + facts +} + +/// K1, a task. +pub(super) fn k1() -> Value { + json!({"id": "k1", "title": "The judge", "files": ["src/judge.rs", "docs/plan.md"], + "action": "Judge the plan whole.", "verify": ["cargo test judge"]}) +} + +/// C1, a unit check for story 1's `t1`. +pub(super) fn c1() -> Value { + json!({"id": "c1", "story": 1, "truth": "t1", "truth_version": 1, "kind": "check", + "spec": {"command": "cargo test lease", + "expected": {"kind": "literal", "value": "lease"}, + "test": {"file": "src/judge.rs", "function": "outside_lease"}, + "setup": "a task file outside the lease", "call": "judge the plan", + "level": "unit", "boundary": "the plan judge", "fakes": []}, + "reason": "a task file outside the lease accepted"}) +} + +/// C2, an integration check for story 1's `t2`. +pub(super) fn c2() -> Value { + json!({"id": "c2", "story": 1, "truth": "t2", "truth_version": 2, "kind": "check", + "spec": {"command": "cargo test preview", + "expected": {"kind": "property", "value": "every task title in order"}, + "test": {"file": "src/preview.rs", "function": "titles_in_order"}, + "setup": "a plan of two tasks", "call": "render the preview", + "level": "integration", "boundary": "the plan judge and the preview render", + "fakes": ["the clock"]}, + "reason": "a task title dropped from the preview"}) +} + +/// O1, an observation for story 1's `t2`. +pub(super) fn o1() -> Value { + json!({"id": "o1", "story": 1, "truth": "t2", "truth_version": 2, "kind": "observation", + "spec": {"what": "every task title in order in the preview", "by": "the owner"}, + "reason": "the browser preview drops a task"}) +} + +/// C4: C1 for story 2's `t1`. +pub(super) fn c4() -> Value { + let mut item = c1(); + item["id"] = json!("c4"); + item["story"] = json!(2); + item["truth_version"] = json!(3); + item["spec"]["command"] = json!("cargo test read"); + item +} + +/// Ar, an artifact for story 1's `t1`. +pub(super) fn ar() -> Value { + json!({"id": "a1", "story": 1, "truth": "t1", "truth_version": 1, "kind": "artifact", + "spec": {"path": "src/judge.rs"}, "reason": "the judge file removed"}) +} + +/// L1, a link for story 1's `t1`. +pub(super) fn l1() -> Value { + json!({"id": "l1", "story": 1, "truth": "t1", "truth_version": 1, "kind": "link", + "spec": {"caller": "the judge", "callee": "the refusal", "value": "lease"}, + "reason": "the refusal names another code"}) +} + +/// Qa, a question with no dependency. +pub(super) fn qa() -> Value { + json!({"id": "q1", "question": "Which store backs the ledger?", "recommended": "SQLite", + "depends_on": []}) +} + +/// Qb, a question depending on `q1`. +pub(super) fn qb() -> Value { + json!({"id": "q2", "question": "Where does the ledger live?", + "recommended": "Outside the checkout", "depends_on": ["q1"]}) +} + +/// P1, a plan for story 1. +pub(super) fn p1() -> Value { + json!({"phase": 8, "stories": [1], "files": ["src/judge.rs"], "directories": ["docs"], + "goal": "Judge a plan whole.", "context": "Pure core.", "notes": "", + "tasks": [k1()], "evidence_map": [c1(), c2(), o1()], "questions": []}) +} + +/// P0: P1 serving no story and holding no evidence item. +pub(super) fn p0() -> Value { + let mut plan = p1(); + plan["stories"] = json!([]); + plan["evidence_map"] = json!([]); + plan +} + +/// P3: P1 for story 2, proved by C4. +pub(super) fn p3() -> Value { + let mut plan = p1(); + plan["stories"] = json!([2]); + plan["evidence_map"] = json!([c4()]); + plan +} + +/// `value` with member `member` of the object at `pointer` set to `to`, +/// added when absent. +pub(super) fn with(mut value: Value, pointer: &str, member: &str, to: Value) -> Value { + value + .pointer_mut(pointer) + .and_then(Value::as_object_mut) + .expect("an object at the pointer") + .insert(member.into(), to); + value +} + +/// `value` with member `member` of the object at `pointer` removed. +pub(super) fn without(mut value: Value, pointer: &str, member: &str) -> Value { + value + .pointer_mut(pointer) + .and_then(Value::as_object_mut) + .expect("an object at the pointer") + .remove(member) + .expect("the member is present"); + value +} + +/// The `typed-content` refusal naming `path`. +pub(super) fn typed(path: &str) -> PlanRefusal { + PlanRefusal::TypedContent { + path: Some(path.into()), + } +} + +/// The refusal of `plan` under `facts`. +pub(super) fn refusal(plan: &Value, facts: &PlanFacts) -> PlanRefusal { + judge_plan(plan, facts).expect_err("refused") +} + +/// The accepted plan of `plan` under `facts`. +pub(super) fn accepted(plan: &Value, facts: &PlanFacts) -> Plan { + judge_plan(plan, facts).expect("accepted") +} diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs new file mode 100644 index 00000000..8ac3fa93 --- /dev/null +++ b/crates/baley-core/src/plan/judge.rs @@ -0,0 +1,198 @@ +//! The judgement of one submitted plan whole (design 0005 sections 3 and 6, +//! PLN-R11 to PLN-R13). +//! +//! A plan arrives as plain JSON and the phase's facts as plain values the +//! binary gathered from its views. The plan is judged in one fixed order, +//! the first fault answering, so one plan always gets one answer: (1) the +//! plan's own members. The judge trusts the facts and judges the plan. +//! Nothing here records anything. + +use std::num::NonZeroU32; + +use serde_json::Value; + +use super::content; + +/// The refusal code for a plan out of its grammar: not an object, or a +/// member unknown, missing, of another type or out of range. It names the +/// path of the first fault. +pub const TYPED_CONTENT: &str = "typed-content"; + +/// Why a plan is refused. Positions count from 0 in the list as submitted. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PlanRefusal { + /// The plan breaks its grammar at `path`: member names joined by `.` + /// and a list position written `[]`, such as `tasks[0].verify[1]`. + /// `None` when the plan is not an object. + TypedContent { path: Option }, +} + +impl PlanRefusal { + /// The refusal's public code. + pub fn code(&self) -> &'static str { + match self { + Self::TypedContent { .. } => TYPED_CONTENT, + } + } + + /// A `typed-content` refusal naming `path`. + pub(super) fn typed(path: impl Into) -> Self { + Self::TypedContent { + path: Some(path.into()), + } + } +} + +/// The kind of an evidence item (design 0005 section 6). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EvidenceKind { + /// A file or record that must exist. + Artifact, + /// A value that must pass from a caller to a callee. + Link, + /// A command whose result proves the truth. + Check, + /// Something a named person must see. + Observation, +} + +/// What a plan is judged on besides itself. The binary gathers every value +/// from its views (D-09) and the judge trusts them. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlanFacts { + /// The phase's committed stories, in commitment order. + pub stories: Vec, + /// The evidence items of the phase's approved plans. + pub approved: Vec, + /// The phase's current size: the tasks of its approved plans, each + /// plan's counted once. + pub size: u32, + /// The phase's capacity in tasks, or `None` when none is set. + pub capacity: Option, +} + +/// One story committed to the phase. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CommittedStory { + /// The story's id. + pub id: u32, + /// Its current truths, in the story's order. Empty when the story holds + /// no approved truth. + pub truths: Vec, +} + +/// One current truth of a committed story, its slot texts as approved. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurrentTruth { + /// Its id, unique within its story. + pub id: String, + /// Its current version. + pub version: u32, + /// The one trigger, or a `for-any` truth's input. + pub trigger: String, + /// The one observer. + pub observer: String, + /// The one outcome. + pub outcome: String, + /// The tool or live service a person needs to prove it, if any. + pub human_verify: Option, +} + +/// One evidence item of an approved plan of the phase, as recorded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApprovedItem { + /// The number of the approved plan that holds it. + pub plan: u32, + /// Its id. + pub id: String, + /// The story of the truth it serves. + pub story: u32, + /// The id of the truth it serves. + pub truth: String, + /// The version of the truth it serves. + pub truth_version: u32, + /// Its kind. + pub kind: EvidenceKind, + /// Its whole definition as recorded. + pub definition: Value, +} + +/// A plan judged whole and accepted, every member kept exactly as +/// submitted. Only [`judge_plan`] builds one, so nothing unjudged can be +/// recorded. +#[derive(Debug, Clone, PartialEq)] +pub struct Plan { + pub(super) phase: u64, + pub(super) stories: Vec, + pub(super) files: Vec, + pub(super) directories: Vec, + pub(super) goal: String, + pub(super) context: String, + pub(super) notes: String, + pub(super) tasks: Vec, + pub(super) evidence_map: Vec, + pub(super) questions: Value, +} + +impl Plan { + /// The phase the plan is for. + pub fn phase(&self) -> u64 { + self.phase + } + + /// The stories the plan serves, in submitted order. + pub fn stories(&self) -> &[u64] { + &self.stories + } + + /// The lease's files, in submitted order. + pub fn files(&self) -> &[Value] { + &self.files + } + + /// The lease's directories, in submitted order. + pub fn directories(&self) -> &[Value] { + &self.directories + } + + /// The plan's goal. + pub fn goal(&self) -> &str { + &self.goal + } + + /// The plan's context. + pub fn context(&self) -> &str { + &self.context + } + + /// The plan's notes. + pub fn notes(&self) -> &str { + &self.notes + } + + /// The tasks, in submitted order. + pub fn tasks(&self) -> &[Value] { + &self.tasks + } + + /// The evidence items, in submitted order. + pub fn evidence_map(&self) -> &[Value] { + &self.evidence_map + } + + /// The `questions` member as submitted. + pub fn questions(&self) -> &Value { + &self.questions + } + + /// The plan's size: the number of its tasks. + pub fn size(&self) -> usize { + self.tasks.len() + } +} + +/// Judges the submitted plan `plan` against the phase's `facts` in the +/// fixed order, the first fault answering: (1) the plan's own members. +pub fn judge_plan(plan: &Value, _facts: &PlanFacts) -> Result { + content::read(plan) +} diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs new file mode 100644 index 00000000..5dbd00f8 --- /dev/null +++ b/crates/baley-core/src/plan/mod.rs @@ -0,0 +1,17 @@ +//! Plans' pure half (design 0005 sections 3 and 6, PLN-R5, PLN-R9's judge, +//! PLN-R11 to PLN-R13): the judgement of one submitted plan whole against +//! the phase's facts, the refusal codes it answers with, and the accepted +//! plan only that judgement builds. +//! +//! Nothing here reads a store, a file or a clock: the binary supplies every +//! value it judges. + +mod content; +#[cfg(test)] +mod fixtures; +mod judge; + +pub use judge::{ + ApprovedItem, CommittedStory, CurrentTruth, EvidenceKind, Plan, PlanFacts, PlanRefusal, + TYPED_CONTENT, judge_plan, +}; From bf1bb379ab0a323c210ebf9f56f2fac074587e39 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 17:51:00 -0400 Subject: [PATCH 02/26] feat(8-1): refuse unknown members and out-of-range plan counters Baley writes the plan number, question set, size and suite at approval, so a plan naming one, or any other unknown member, is refused before any member is read. Phase and story numbers must fit the counters they name, and a story served twice is named where it repeats. --- crates/baley-core/src/plan/content.rs | 87 +++++++++++++++++++++++++-- crates/baley-core/src/plan/judge.rs | 8 +-- 2 files changed, 85 insertions(+), 10 deletions(-) diff --git a/crates/baley-core/src/plan/content.rs b/crates/baley-core/src/plan/content.rs index 1d02e683..f076dc9d 100644 --- a/crates/baley-core/src/plan/content.rs +++ b/crates/baley-core/src/plan/content.rs @@ -2,11 +2,30 @@ //! (PLN-R11, D-03), the first fault answering `typed-content` with its //! path. No text is trimmed or rewritten. +use std::collections::HashSet; + use serde_json::{Map, Value}; use super::judge::{Plan, PlanRefusal}; -/// Reads a plan into the accepted plan, each member in the judge's order: +/// The plan's members, in the order they are judged. The plan number, the +/// question set, the size and the suite are written by Baley at approval, +/// so a plan naming one is refused as naming an unknown member (D-03). +const MEMBERS: [&str; 10] = [ + "phase", + "stories", + "files", + "directories", + "goal", + "context", + "notes", + "tasks", + "evidence_map", + "questions", +]; + +/// Reads a plan into the accepted plan: an unknown member first, the first +/// by name, then each member in the judge's order: /// `phase`, `stories`, `files`, `directories`, `goal`, `context`, `notes`, /// `tasks`, `evidence_map`, then the presence of `questions`, whose value /// step (2) judges. @@ -14,12 +33,24 @@ pub(super) fn read(value: &Value) -> Result { let Value::Object(plan) = value else { return Err(PlanRefusal::TypedContent { path: None }); }; - let phase = whole(plan.get("phase")).ok_or_else(|| PlanRefusal::typed("phase"))?; + // Key order depends on serde_json's features, so the first is chosen. + if let Some(unknown) = plan + .keys() + .filter(|name| !MEMBERS.contains(&name.as_str())) + .min() + { + return Err(PlanRefusal::typed(unknown.as_str())); + } + let phase = counter(plan.get("phase")).ok_or_else(|| PlanRefusal::typed("phase"))?; + // A repeated story is named at its later position. + let mut seen = HashSet::new(); let stories = list(plan, "stories")? .iter() .enumerate() .map(|(n, story)| { - whole(Some(story)).ok_or_else(|| PlanRefusal::typed(format!("stories[{n}]"))) + counter(Some(story)) + .filter(|id| seen.insert(*id)) + .ok_or_else(|| PlanRefusal::typed(format!("stories[{n}]"))) }) .collect::, _>>()?; let files = list(plan, "files")?.clone(); @@ -47,9 +78,13 @@ pub(super) fn read(value: &Value) -> Result { }) } -/// A whole number, or `None` when the value is missing or anything else. -fn whole(value: Option<&Value>) -> Option { - value.and_then(Value::as_u64) +/// A whole number from 1 to `u32::MAX`, as phase and story counters run, +/// or `None` when the value is missing or anything else. +fn counter(value: Option<&Value>) -> Option { + value + .and_then(Value::as_u64) + .filter(|number| *number >= 1) + .and_then(|number| u32::try_from(number).ok()) } /// The list member `name`, refused naming it when missing or not a list. @@ -131,4 +166,44 @@ mod tests { assert_eq!(plan.context(), ""); assert!(accepted(&p0(), &facts).stories().is_empty()); } + + #[test] + fn a_phase_or_story_number_out_of_range_or_repeated_accepted_is_caught() { + let facts = f1(); + let cases = [ + (with(p1(), "", "phase", json!(0)), "phase"), + (with(p1(), "", "phase", json!(4_294_967_296_u64)), "phase"), + (with(p1(), "", "stories", json!([0])), "stories[0]"), + ( + with(p1(), "", "stories", json!([4_294_967_297_u64])), + "stories[0]", + ), + (with(p1(), "", "stories", json!([1, 2, 1])), "stories[2]"), + ]; + for (plan, path) in cases { + assert_eq!(refusal(&plan, &facts), typed(path), "{plan}"); + } + } + + #[test] + fn faults_in_the_plan_members_judged_in_another_order_are_caught() { + let facts = f1(); + let owner = with(p1(), "", "owner", json!("Ada")); + let both = with(with(p1(), "", "zeta", json!(1)), "", "alpha", json!(1)); + let cases = [ + (without(owner, "", "goal"), "owner"), + (both, "alpha"), + ( + without(with(p1(), "", "phase", json!("8")), "", "goal"), + "phase", + ), + ( + without(with(p1(), "", "stories", json!(["x"])), "", "goal"), + "stories[0]", + ), + ]; + for (plan, path) in cases { + assert_eq!(refusal(&plan, &facts), typed(path), "{plan}"); + } + } } diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index 8ac3fa93..267ab64e 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -122,8 +122,8 @@ pub struct ApprovedItem { /// recorded. #[derive(Debug, Clone, PartialEq)] pub struct Plan { - pub(super) phase: u64, - pub(super) stories: Vec, + pub(super) phase: u32, + pub(super) stories: Vec, pub(super) files: Vec, pub(super) directories: Vec, pub(super) goal: String, @@ -136,12 +136,12 @@ pub struct Plan { impl Plan { /// The phase the plan is for. - pub fn phase(&self) -> u64 { + pub fn phase(&self) -> u32 { self.phase } /// The stories the plan serves, in submitted order. - pub fn stories(&self) -> &[u64] { + pub fn stories(&self) -> &[u32] { &self.stories } From b3c6ab7d4981065460f09edcf7cd5e2c51651778 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 17:52:25 -0400 Subject: [PATCH 03/26] feat(8-1): judge the plan's lease and its path rule Every lease entry must be a plain relative path, declared once, within the 256-declaration limit, and a lease must declare something. The path rule and the inside-the-lease test are public so the later risk check and the lease check at close read the same path set. --- crates/baley-core/src/plan/content.rs | 10 +- crates/baley-core/src/plan/judge.rs | 8 +- crates/baley-core/src/plan/lease.rs | 221 ++++++++++++++++++++++++++ crates/baley-core/src/plan/mod.rs | 2 + 4 files changed, 233 insertions(+), 8 deletions(-) create mode 100644 crates/baley-core/src/plan/lease.rs diff --git a/crates/baley-core/src/plan/content.rs b/crates/baley-core/src/plan/content.rs index f076dc9d..1b883bd0 100644 --- a/crates/baley-core/src/plan/content.rs +++ b/crates/baley-core/src/plan/content.rs @@ -7,6 +7,7 @@ use std::collections::HashSet; use serde_json::{Map, Value}; use super::judge::{Plan, PlanRefusal}; +use super::lease; /// The plan's members, in the order they are judged. The plan number, the /// question set, the size and the suite are written by Baley at approval, @@ -25,8 +26,8 @@ const MEMBERS: [&str; 10] = [ ]; /// Reads a plan into the accepted plan: an unknown member first, the first -/// by name, then each member in the judge's order: -/// `phase`, `stories`, `files`, `directories`, `goal`, `context`, `notes`, +/// by name, then each member in the judge's order: `phase`, `stories`, +/// `files`, `directories` with the lease rules, `goal`, `context`, `notes`, /// `tasks`, `evidence_map`, then the presence of `questions`, whose value /// step (2) judges. pub(super) fn read(value: &Value) -> Result { @@ -53,8 +54,9 @@ pub(super) fn read(value: &Value) -> Result { .ok_or_else(|| PlanRefusal::typed(format!("stories[{n}]"))) }) .collect::, _>>()?; - let files = list(plan, "files")?.clone(); - let directories = list(plan, "directories")?.clone(); + let files = list(plan, "files")?; + let directories = list(plan, "directories")?; + let (files, directories) = lease::read(files, directories)?; let goal = text(plan, "goal")?; let context = text(plan, "context")?; let notes = text(plan, "notes")?; diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index 267ab64e..a384a9cd 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -124,8 +124,8 @@ pub struct ApprovedItem { pub struct Plan { pub(super) phase: u32, pub(super) stories: Vec, - pub(super) files: Vec, - pub(super) directories: Vec, + pub(super) files: Vec, + pub(super) directories: Vec, pub(super) goal: String, pub(super) context: String, pub(super) notes: String, @@ -146,12 +146,12 @@ impl Plan { } /// The lease's files, in submitted order. - pub fn files(&self) -> &[Value] { + pub fn files(&self) -> &[String] { &self.files } /// The lease's directories, in submitted order. - pub fn directories(&self) -> &[Value] { + pub fn directories(&self) -> &[String] { &self.directories } diff --git a/crates/baley-core/src/plan/lease.rs b/crates/baley-core/src/plan/lease.rs new file mode 100644 index 00000000..3e1cb13c --- /dev/null +++ b/crates/baley-core/src/plan/lease.rs @@ -0,0 +1,221 @@ +//! The lease: the files and directories a plan's tasks may touch, and the +//! one path rule every lease entry and every lease check reads (design 0005 +//! PLN-R11, D-05, D-11). + +use std::collections::HashSet; + +use serde_json::Value; + +use super::judge::PlanRefusal; + +/// The most declarations one lease holds, files and directories counted +/// together (PLN-R11). +const LEASE_LIMIT: usize = 256; + +/// Whether `path` is a plain relative path: not empty, not starting with +/// `/`, holding no `\`, and split on `/` with no empty, `.` or `..` part, +/// so a trailing separator and `//` are refused. Every lease entry, file or +/// directory, is one (D-05), and every check of a path against a lease +/// reads this rule. It matches `safe_relative_path` in the binary's patch +/// code. +pub fn plain_relative_path(path: &str) -> bool { + !path.is_empty() + && !path.starts_with('/') + && !path.contains('\\') + && !path + .split('/') + .any(|part| part.is_empty() || matches!(part, "." | "..")) +} + +/// Whether `path` lies inside the lease of `files` and `directories`: it +/// is a plain relative path and either equals a declared file or has every +/// part of a declared directory as its leading parts and at least one part +/// more, compared part by part. A directory is not inside itself, and a +/// file is never taken as a directory. +pub fn inside_lease(path: &str, files: &[String], directories: &[String]) -> bool { + if !plain_relative_path(path) { + return false; + } + if files.iter().any(|file| file == path) { + return true; + } + let parts: Vec<&str> = path.split('/').collect(); + directories.iter().any(|directory| { + let leading: Vec<&str> = directory.split('/').collect(); + parts.len() > leading.len() && parts.starts_with(&leading) + }) +} + +/// Reads a plan's lease from its `files` and `directories` lists, the +/// first fault answering `typed-content`: each entry of `files`, then of +/// `directories`, that is not text passing the path rule; then an entry +/// equal to an earlier one, both lists scanned as one, named at its later +/// position; then the 257th declaration, files first; then a lease with no +/// file and no directory, named `files` (D-11). +pub(super) fn read( + files: &[Value], + directories: &[Value], +) -> Result<(Vec, Vec), PlanRefusal> { + let files = entries(files, "files")?; + let directories = entries(directories, "directories")?; + let declared: Vec<(&str, usize, &str)> = files + .iter() + .enumerate() + .map(|(n, path)| ("files", n, path.as_str())) + .chain( + directories + .iter() + .enumerate() + .map(|(n, path)| ("directories", n, path.as_str())), + ) + .collect(); + let named = |(list, n, _): &(&str, usize, &str)| PlanRefusal::typed(format!("{list}[{n}]")); + let mut seen = HashSet::new(); + if let Some(repeat) = declared.iter().find(|(_, _, path)| !seen.insert(*path)) { + return Err(named(repeat)); + } + if let Some(over) = declared.get(LEASE_LIMIT) { + return Err(named(over)); + } + if declared.is_empty() { + return Err(PlanRefusal::typed("files")); + } + Ok((files, directories)) +} + +/// The entries of the lease list `name`, each text passing the path rule, +/// else refused naming its position. +fn entries(list: &[Value], name: &str) -> Result, PlanRefusal> { + list.iter() + .enumerate() + .map(|(n, entry)| { + entry + .as_str() + .filter(|path| plain_relative_path(path)) + .map(str::to_owned) + .ok_or_else(|| PlanRefusal::typed(format!("{name}[{n}]"))) + }) + .collect() +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use serde_json::{Value, json}; + + use super::*; + use crate::plan::fixtures::{accepted, f1, p1, refusal, typed, with}; + + /// P1 with its lease replaced. + fn leased(files: Value, directories: Value) -> Value { + with( + with(p1(), "", "files", files), + "", + "directories", + directories, + ) + } + + fn texts(paths: &[&str]) -> Vec { + paths.iter().map(|path| (*path).to_owned()).collect() + } + + #[test] + fn a_lease_entry_with_a_trailing_separator_or_another_bad_part_is_caught() { + for path in [ + "docs/", + "/src/judge.rs", + "src\\judge.rs", + "src//judge.rs", + "./src", + "src/./judge.rs", + "src/../judge.rs", + "..", + "", + ] { + assert!(!plain_relative_path(path), "{path:?} refused"); + } + for path in [ + "src/judge.rs", + "docs", + ".github/workflows/test.yml", + "a..b/c", + ] { + assert!(plain_relative_path(path), "{path:?} accepted"); + } + } + + #[test] + fn a_repeated_lease_entry_accepted_or_named_at_the_first_is_caught() { + let facts = f1(); + let cases = [ + ( + leased(json!(["src/judge.rs", "src/judge.rs"]), json!(["docs"])), + "files[1]", + ), + ( + leased(json!(["src/judge.rs"]), json!(["src/judge.rs", "docs"])), + "directories[0]", + ), + ( + leased(json!(["src/judge.rs"]), json!(["docs", "docs"])), + "directories[1]", + ), + ]; + for (plan, path) in cases { + assert_eq!(refusal(&plan, &facts), typed(path), "{plan}"); + } + } + + #[test] + fn a_lease_over_its_limit_accepted_or_one_at_it_refused_is_caught() { + let facts = f1(); + let mut directories = vec![json!("docs")]; + directories.extend((0..=253).map(|n| json!(format!("d/{n}")))); + let at_limit = with(p1(), "", "directories", Value::Array(directories.clone())); + accepted(&at_limit, &facts); + directories.push(json!("d/254")); + let over = with(p1(), "", "directories", Value::Array(directories)); + assert_eq!(refusal(&over, &facts), typed("directories[255]")); + } + + #[test] + fn an_empty_lease_or_files_beside_directories_judged_wrongly_is_caught() { + let facts = f1(); + accepted(&leased(json!([]), json!(["docs", "src"])), &facts); + assert_eq!( + refusal(&leased(json!([]), json!([])), &facts), + typed("files") + ); + accepted( + &leased(json!(["src/judge.rs", "docs/plan.md"]), json!([])), + &facts, + ); + } + + #[test] + fn a_path_inside_the_lease_refused_or_one_outside_accepted_is_caught() { + let files = texts(&["src/judge.rs"]); + let directories = texts(&["docs"]); + for path in ["src/judge.rs", "docs/plan.md", "docs/design/a.md"] { + assert!(inside_lease(path, &files, &directories), "{path} inside"); + } + for path in [ + "docs", + "docsx/a.md", + "src/judge.rs/x", + "src/judge.rss", + "src", + "docs/../src/x.rs", + "/docs/a.md", + "docs/", + ] { + assert!(!inside_lease(path, &files, &directories), "{path} outside"); + } + let private = texts(&["docs/private"]); + assert!(inside_lease("docs/private/a.md", &[], &private)); + assert!(!inside_lease("docs/public/a.md", &[], &private)); + } +} diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index 5dbd00f8..64ba3626 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -10,8 +10,10 @@ mod content; #[cfg(test)] mod fixtures; mod judge; +mod lease; pub use judge::{ ApprovedItem, CommittedStory, CurrentTruth, EvidenceKind, Plan, PlanFacts, PlanRefusal, TYPED_CONTENT, judge_plan, }; +pub use lease::{inside_lease, plain_relative_path}; From f57a9c231c2b473e0e732b4b2fb0971140b25a48 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 17:54:05 -0400 Subject: [PATCH 04/26] feat(8-1): judge a plan's tasks and refuse files outside the lease Each task is read whole at its place in the member walk, so its faults answer before later members are judged: exact members, a unique id and at least one verify command with none blank. A task file outside the lease is the one case refused `lease`. --- crates/baley-core/src/plan/content.rs | 26 ++-- crates/baley-core/src/plan/judge.rs | 25 ++- crates/baley-core/src/plan/mod.rs | 4 +- crates/baley-core/src/plan/task.rs | 213 ++++++++++++++++++++++++++ 4 files changed, 253 insertions(+), 15 deletions(-) create mode 100644 crates/baley-core/src/plan/task.rs diff --git a/crates/baley-core/src/plan/content.rs b/crates/baley-core/src/plan/content.rs index 1b883bd0..123d5788 100644 --- a/crates/baley-core/src/plan/content.rs +++ b/crates/baley-core/src/plan/content.rs @@ -7,7 +7,7 @@ use std::collections::HashSet; use serde_json::{Map, Value}; use super::judge::{Plan, PlanRefusal}; -use super::lease; +use super::{lease, task}; /// The plan's members, in the order they are judged. The plan number, the /// question set, the size and the suite are written by Baley at approval, @@ -34,13 +34,8 @@ pub(super) fn read(value: &Value) -> Result { let Value::Object(plan) = value else { return Err(PlanRefusal::TypedContent { path: None }); }; - // Key order depends on serde_json's features, so the first is chosen. - if let Some(unknown) = plan - .keys() - .filter(|name| !MEMBERS.contains(&name.as_str())) - .min() - { - return Err(PlanRefusal::typed(unknown.as_str())); + if let Some(unknown) = first_unknown(plan, &MEMBERS) { + return Err(PlanRefusal::typed(unknown)); } let phase = counter(plan.get("phase")).ok_or_else(|| PlanRefusal::typed("phase"))?; // A repeated story is named at its later position. @@ -60,7 +55,7 @@ pub(super) fn read(value: &Value) -> Result { let goal = text(plan, "goal")?; let context = text(plan, "context")?; let notes = text(plan, "notes")?; - let tasks = list(plan, "tasks")?.clone(); + let tasks = task::read(list(plan, "tasks")?)?; let evidence_map = list(plan, "evidence_map")?.clone(); let questions = plan .get("questions") @@ -80,6 +75,19 @@ pub(super) fn read(value: &Value) -> Result { }) } +/// The first member of `object`, by name, that is not among `members`. +pub(super) fn first_unknown<'a>( + object: &'a Map, + members: &[&str], +) -> Option<&'a str> { + // Key order depends on serde_json's features, so the first is chosen. + object + .keys() + .map(String::as_str) + .filter(|name| !members.contains(name)) + .min() +} + /// A whole number from 1 to `u32::MAX`, as phase and story counters run, /// or `None` when the value is missing or anything else. fn counter(value: Option<&Value>) -> Option { diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index a384a9cd..45cb6588 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -4,7 +4,8 @@ //! A plan arrives as plain JSON and the phase's facts as plain values the //! binary gathered from its views. The plan is judged in one fixed order, //! the first fault answering, so one plan always gets one answer: (1) the -//! plan's own members. The judge trusts the facts and judges the plan. +//! plan's own members, task by task within `tasks`; (3) each task file +//! inside the lease. The judge trusts the facts and judges the plan. //! Nothing here records anything. use std::num::NonZeroU32; @@ -12,11 +13,14 @@ use std::num::NonZeroU32; use serde_json::Value; use super::content; +use super::task::{self, Task}; /// The refusal code for a plan out of its grammar: not an object, or a /// member unknown, missing, of another type or out of range. It names the /// path of the first fault. pub const TYPED_CONTENT: &str = "typed-content"; +/// The refusal code for a task naming a file outside the plan's lease. +pub const LEASE: &str = "lease"; /// Why a plan is refused. Positions count from 0 in the list as submitted. #[derive(Debug, Clone, PartialEq, Eq)] @@ -25,6 +29,13 @@ pub enum PlanRefusal { /// and a list position written `[]`, such as `tasks[0].verify[1]`. /// `None` when the plan is not an object. TypedContent { path: Option }, + /// The task at `position`, whose id is `id`, names `file`, which lies + /// outside the plan's lease. + Lease { + position: usize, + id: String, + file: String, + }, } impl PlanRefusal { @@ -32,6 +43,7 @@ impl PlanRefusal { pub fn code(&self) -> &'static str { match self { Self::TypedContent { .. } => TYPED_CONTENT, + Self::Lease { .. } => LEASE, } } @@ -129,7 +141,7 @@ pub struct Plan { pub(super) goal: String, pub(super) context: String, pub(super) notes: String, - pub(super) tasks: Vec, + pub(super) tasks: Vec, pub(super) evidence_map: Vec, pub(super) questions: Value, } @@ -171,7 +183,7 @@ impl Plan { } /// The tasks, in submitted order. - pub fn tasks(&self) -> &[Value] { + pub fn tasks(&self) -> &[Task] { &self.tasks } @@ -192,7 +204,10 @@ impl Plan { } /// Judges the submitted plan `plan` against the phase's `facts` in the -/// fixed order, the first fault answering: (1) the plan's own members. +/// fixed order, the first fault answering: (1) the plan's own members; +/// (3) `lease`, task by task and file by file. pub fn judge_plan(plan: &Value, _facts: &PlanFacts) -> Result { - content::read(plan) + let plan = content::read(plan)?; + task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; + Ok(plan) } diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index 64ba3626..1df360e1 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -11,9 +11,11 @@ mod content; mod fixtures; mod judge; mod lease; +mod task; pub use judge::{ - ApprovedItem, CommittedStory, CurrentTruth, EvidenceKind, Plan, PlanFacts, PlanRefusal, + ApprovedItem, CommittedStory, CurrentTruth, EvidenceKind, LEASE, Plan, PlanFacts, PlanRefusal, TYPED_CONTENT, judge_plan, }; pub use lease::{inside_lease, plain_relative_path}; +pub use task::Task; diff --git a/crates/baley-core/src/plan/task.rs b/crates/baley-core/src/plan/task.rs new file mode 100644 index 00000000..6dd20071 --- /dev/null +++ b/crates/baley-core/src/plan/task.rs @@ -0,0 +1,213 @@ +//! A plan's tasks (design 0005 PLN-R11): each task's grammar, read at +//! `tasks`'s place in the member walk, and step (3), a task file outside +//! the lease (PLN-R13, D-11). Task prose is never read for paths. + +use std::collections::HashSet; + +use serde_json::{Map, Value}; + +use super::content::first_unknown; +use super::judge::PlanRefusal; +use super::lease::inside_lease; + +/// A task's members, in the order they are judged. +const MEMBERS: [&str; 5] = ["id", "title", "files", "action", "verify"]; + +/// One task of an accepted plan, its texts kept exactly as written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Task { + /// Its id, unique within the plan. + pub id: String, + /// Its title. + pub title: String, + /// The files it touches, in submitted order. + pub files: Vec, + /// What it does. + pub action: String, + /// The commands that verify it, at least one, none blank. + pub verify: Vec, +} + +/// Reads a plan's tasks in submitted order, each whole before the next. +pub(super) fn read(tasks: &[Value]) -> Result, PlanRefusal> { + let mut seen = HashSet::new(); + tasks + .iter() + .enumerate() + .map(|(n, entry)| task(n, entry, &mut seen)) + .collect() +} + +/// Step (3): the first task file, in task order and file order, outside +/// the lease of `files` and `directories` is refused `lease`. +pub(super) fn within_lease( + tasks: &[Task], + files: &[String], + directories: &[String], +) -> Result<(), PlanRefusal> { + for (position, task) in tasks.iter().enumerate() { + if let Some(file) = task + .files + .iter() + .find(|file| !inside_lease(file, files, directories)) + { + return Err(PlanRefusal::Lease { + position, + id: task.id.clone(), + file: file.clone(), + }); + } + } + Ok(()) +} + +/// One task read: an unknown member first, the first by name, then each +/// member in order, every fault `typed-content` named by its path. +fn task(n: usize, entry: &Value, seen: &mut HashSet) -> Result { + let at = |member: &str| PlanRefusal::typed(format!("tasks[{n}].{member}")); + let Value::Object(task) = entry else { + return Err(PlanRefusal::typed(format!("tasks[{n}]"))); + }; + if let Some(unknown) = first_unknown(task, &MEMBERS) { + return Err(at(unknown)); + } + let id = text(task, "id") + .filter(|id| !id.trim().is_empty() && seen.insert(id.clone())) + .ok_or_else(|| at("id"))?; + let title = text(task, "title").ok_or_else(|| at("title"))?; + let entry = |name: &'static str| { + move |fault: Option| match fault { + None => at(name), + Some(m) => at(&format!("{name}[{m}]")), + } + }; + let files = texts(task, "files", |_| true).map_err(entry("files"))?; + let action = text(task, "action").ok_or_else(|| at("action"))?; + // PLN-R11: one or more verify commands, none blank. + let verify = + texts(task, "verify", |command| !command.trim().is_empty()).map_err(entry("verify"))?; + if verify.is_empty() { + return Err(at("verify")); + } + Ok(Task { + id, + title, + files, + action, + verify, + }) +} + +/// The text member `name` as written, or `None` when missing or not text. +fn text(task: &Map, name: &str) -> Option { + task.get(name).and_then(Value::as_str).map(str::to_owned) +} + +/// The list of texts `name`, each passing `keep`. The error is `None` when +/// the member is missing or not a list, else the first failing position. +fn texts( + task: &Map, + name: &str, + keep: impl Fn(&str) -> bool, +) -> Result, Option> { + let Some(Value::Array(entries)) = task.get(name) else { + return Err(None); + }; + entries + .iter() + .enumerate() + .map(|(m, entry)| { + entry + .as_str() + .filter(|entry| keep(entry)) + .map(str::to_owned) + .ok_or(Some(m)) + }) + .collect() +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use serde_json::{Value, json}; + + use crate::plan::PlanRefusal; + use crate::plan::fixtures::{accepted, f1, k1, p1, refusal, typed, with, without}; + + /// P1 with K1's member `member` set to `to`. + fn k1_with(member: &str, to: Value) -> Value { + with(p1(), "/tasks/0", member, to) + } + + fn lease(position: usize, id: &str, file: &str) -> PlanRefusal { + PlanRefusal::Lease { + position, + id: id.into(), + file: file.into(), + } + } + + #[test] + fn a_task_with_a_bad_member_accepted_is_caught() { + let facts = f1(); + let listed = with(p1(), "", "tasks", json!(["k1"])); + let cases = [ + (k1_with("owner", json!("Ada")), "tasks[0].owner"), + (without(p1(), "/tasks/0", "verify"), "tasks[0].verify"), + (without(p1(), "/tasks/0", "action"), "tasks[0].action"), + (k1_with("verify", json!([])), "tasks[0].verify"), + ( + k1_with("verify", json!(["cargo test judge", " "])), + "tasks[0].verify[1]", + ), + ( + k1_with("files", json!(["src/judge.rs", 3])), + "tasks[0].files[1]", + ), + (k1_with("title", json!(3)), "tasks[0].title"), + (listed.clone(), "tasks[0]"), + (without(listed, "", "questions"), "tasks[0]"), + ]; + for (plan, path) in cases { + assert_eq!(refusal(&plan, &facts), typed(path), "{plan}"); + } + } + + #[test] + fn a_task_id_blank_or_repeated_accepted_is_caught() { + let facts = f1(); + let twice = with(p1(), "", "tasks", json!([k1(), k1()])); + assert_eq!(refusal(&twice, &facts), typed("tasks[1].id")); + assert_eq!( + refusal(&k1_with("id", json!(" ")), &facts), + typed("tasks[0].id") + ); + } + + #[test] + fn a_task_file_outside_the_lease_named_wrongly_is_caught() { + let facts = f1(); + assert_eq!( + refusal(&k1_with("files", json!(["docs"])), &facts), + lease(0, "k1", "docs") + ); + let mut k2 = k1(); + k2["id"] = json!("k2"); + k2["files"] = json!(["docs/../src/x.rs"]); + let two = with(p1(), "", "tasks", json!([k1(), k2])); + assert_eq!(refusal(&two, &facts), lease(1, "k2", "docs/../src/x.rs")); + accepted( + &k1_with("files", json!(["src/judge.rs", "docs/a/b.md"])), + &facts, + ); + } + + #[test] + fn an_empty_task_list_or_task_files_refused_is_caught() { + let facts = f1(); + accepted(&with(p1(), "", "tasks", json!([])), &facts); + accepted(&k1_with("files", json!([])), &facts); + } +} From a2d9d47faf84355e1110af42e8ea0b764e354e05 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 17:55:13 -0400 Subject: [PATCH 05/26] feat(8-1): judge a plan's questions through the question set judge The plan's questions field is the same kind of set an analyzer returns, so it is judged by `judge_set` and its refusal is passed on with its code and positions unchanged. The accepted plan keeps the accepted set. --- crates/baley-core/src/plan/content.rs | 11 ++-- crates/baley-core/src/plan/judge.rs | 72 ++++++++++++++++++++++++--- 2 files changed, 73 insertions(+), 10 deletions(-) diff --git a/crates/baley-core/src/plan/content.rs b/crates/baley-core/src/plan/content.rs index 123d5788..4c2a67ad 100644 --- a/crates/baley-core/src/plan/content.rs +++ b/crates/baley-core/src/plan/content.rs @@ -8,6 +8,7 @@ use serde_json::{Map, Value}; use super::judge::{Plan, PlanRefusal}; use super::{lease, task}; +use crate::questions::judge_set; /// The plan's members, in the order they are judged. The plan number, the /// question set, the size and the suite are written by Baley at approval, @@ -28,8 +29,8 @@ const MEMBERS: [&str; 10] = [ /// Reads a plan into the accepted plan: an unknown member first, the first /// by name, then each member in the judge's order: `phase`, `stories`, /// `files`, `directories` with the lease rules, `goal`, `context`, `notes`, -/// `tasks`, `evidence_map`, then the presence of `questions`, whose value -/// step (2) judges. +/// `tasks`, `evidence_map`, then the presence of `questions`; then step (2), +/// the `questions` value through the question set judge. pub(super) fn read(value: &Value) -> Result { let Value::Object(plan) = value else { return Err(PlanRefusal::TypedContent { path: None }); @@ -59,8 +60,10 @@ pub(super) fn read(value: &Value) -> Result { let evidence_map = list(plan, "evidence_map")?.clone(); let questions = plan .get("questions") - .ok_or_else(|| PlanRefusal::typed("questions"))? - .clone(); + .ok_or_else(|| PlanRefusal::typed("questions"))?; + // Step (2) follows at once: the value through the question set judge, + // its refusal passed on unchanged (D-10). + let questions = judge_set(questions).map_err(PlanRefusal::Questions)?; Ok(Plan { phase, stories, diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index 45cb6588..04602c27 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -4,8 +4,9 @@ //! A plan arrives as plain JSON and the phase's facts as plain values the //! binary gathered from its views. The plan is judged in one fixed order, //! the first fault answering, so one plan always gets one answer: (1) the -//! plan's own members, task by task within `tasks`; (3) each task file -//! inside the lease. The judge trusts the facts and judges the plan. +//! plan's own members, task by task within `tasks`; (2) the `questions` +//! member through the question set judge; (3) each task file inside the +//! lease. The judge trusts the facts and judges the plan. //! Nothing here records anything. use std::num::NonZeroU32; @@ -14,6 +15,7 @@ use serde_json::Value; use super::content; use super::task::{self, Task}; +use crate::questions::{QuestionSet, SetRefusal}; /// The refusal code for a plan out of its grammar: not an object, or a /// member unknown, missing, of another type or out of range. It names the @@ -36,6 +38,9 @@ pub enum PlanRefusal { id: String, file: String, }, + /// The question set judge refused the `questions` member: its refusal + /// unchanged, positions counting within `questions` (D-10). + Questions(SetRefusal), } impl PlanRefusal { @@ -44,6 +49,7 @@ impl PlanRefusal { match self { Self::TypedContent { .. } => TYPED_CONTENT, Self::Lease { .. } => LEASE, + Self::Questions(refusal) => refusal.code(), } } @@ -143,7 +149,7 @@ pub struct Plan { pub(super) notes: String, pub(super) tasks: Vec, pub(super) evidence_map: Vec, - pub(super) questions: Value, + pub(super) questions: QuestionSet, } impl Plan { @@ -192,8 +198,8 @@ impl Plan { &self.evidence_map } - /// The `questions` member as submitted. - pub fn questions(&self) -> &Value { + /// The plan's accepted question set, its questions as written. + pub fn questions(&self) -> &QuestionSet { &self.questions } @@ -205,9 +211,63 @@ impl Plan { /// Judges the submitted plan `plan` against the phase's `facts` in the /// fixed order, the first fault answering: (1) the plan's own members; -/// (3) `lease`, task by task and file by file. +/// (2) the `questions` member through `judge_set`; (3) `lease`, task by +/// task and file by file. pub fn judge_plan(plan: &Value, _facts: &PlanFacts) -> Result { let plan = content::read(plan)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; Ok(plan) } + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use serde_json::json; + + use super::*; + use crate::plan::fixtures::{accepted, f1, p1, qa, qb, refusal, with}; + use crate::questions::Question; + + #[test] + fn a_question_refusal_renamed_or_a_plan_question_rule_added_is_caught() { + let facts = f1(); + let plan = accepted(&with(p1(), "", "questions", json!([qa(), qb()])), &facts); + assert_eq!( + plan.questions().questions(), + [ + Question { + id: "q1".into(), + question: "Which store backs the ledger?".into(), + recommended: "SQLite".into(), + depends_on: Vec::new(), + }, + Question { + id: "q2".into(), + question: "Where does the ledger live?".into(), + recommended: "Outside the checkout".into(), + depends_on: vec!["q1".into()], + }, + ] + ); + let twice = refusal(&with(p1(), "", "questions", json!([qa(), qa()])), &facts); + assert_eq!( + twice, + PlanRefusal::Questions(SetRefusal::QuestionId { + position: 1, + id: "q1".into() + }) + ); + assert_eq!(twice.code(), "question-id"); + let waiting = refusal(&with(p1(), "", "questions", json!([qb()])), &facts); + assert_eq!( + waiting, + PlanRefusal::Questions(SetRefusal::QuestionDependency { + position: 0, + id: "q2".into() + }) + ); + assert_eq!(waiting.code(), "question-dependency"); + } +} From 742c18aa22c92c1a3e3e1332a71aafb216a131f7 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 17:57:12 -0400 Subject: [PATCH 06/26] feat(8-1): judge each evidence item and its spec in the plan grammar Each item names its story, truth and version and carries a spec typed by its kind. A check's spec holds its level, boundary and fakes, and a check with no level or another one is out of grammar, so every check T9 records can be run at either level. --- crates/baley-core/src/plan/content.rs | 9 +- crates/baley-core/src/plan/evidence.rs | 475 +++++++++++++++++++++++++ crates/baley-core/src/plan/judge.rs | 13 +- crates/baley-core/src/plan/mod.rs | 4 + 4 files changed, 491 insertions(+), 10 deletions(-) create mode 100644 crates/baley-core/src/plan/evidence.rs diff --git a/crates/baley-core/src/plan/content.rs b/crates/baley-core/src/plan/content.rs index 4c2a67ad..dafdd920 100644 --- a/crates/baley-core/src/plan/content.rs +++ b/crates/baley-core/src/plan/content.rs @@ -7,7 +7,7 @@ use std::collections::HashSet; use serde_json::{Map, Value}; use super::judge::{Plan, PlanRefusal}; -use super::{lease, task}; +use super::{evidence, lease, task}; use crate::questions::judge_set; /// The plan's members, in the order they are judged. The plan number, the @@ -57,7 +57,7 @@ pub(super) fn read(value: &Value) -> Result { let context = text(plan, "context")?; let notes = text(plan, "notes")?; let tasks = task::read(list(plan, "tasks")?)?; - let evidence_map = list(plan, "evidence_map")?.clone(); + let evidence_map = evidence::read(list(plan, "evidence_map")?)?; let questions = plan .get("questions") .ok_or_else(|| PlanRefusal::typed("questions"))?; @@ -91,9 +91,10 @@ pub(super) fn first_unknown<'a>( .min() } -/// A whole number from 1 to `u32::MAX`, as phase and story counters run, +/// A whole number from 1 to `u32::MAX`, as phase, story and version +/// counters run, /// or `None` when the value is missing or anything else. -fn counter(value: Option<&Value>) -> Option { +pub(super) fn counter(value: Option<&Value>) -> Option { value .and_then(Value::as_u64) .filter(|number| *number >= 1) diff --git a/crates/baley-core/src/plan/evidence.rs b/crates/baley-core/src/plan/evidence.rs new file mode 100644 index 00000000..d8ebc41e --- /dev/null +++ b/crates/baley-core/src/plan/evidence.rs @@ -0,0 +1,475 @@ +//! A plan's evidence items (design 0005 section 6, PLN-R12, D-01, D-12): +//! each item's grammar, read at `evidence_map`'s place in the member walk, +//! its spec judged by its kind. Every fault is `typed-content` named by its +//! full path, such as `evidence_map[0].spec.expected.kind`. + +use std::collections::HashSet; + +use serde_json::{Map, Value}; + +use super::content::{counter, first_unknown}; +use super::judge::{EvidenceKind, PlanRefusal}; + +/// An item's members, in the order they are judged. +const ITEM: [&str; 7] = [ + "id", + "story", + "truth", + "truth_version", + "kind", + "spec", + "reason", +]; +/// An artifact spec's members, exactly one of which it holds. +const ARTIFACT: [&str; 2] = ["path", "record"]; +/// A link spec's members, in the order they are judged. +const LINK: [&str; 3] = ["caller", "callee", "value"]; +/// An observation spec's members, in the order they are judged. +const OBSERVATION: [&str; 2] = ["what", "by"]; +/// A check spec's members, in the order they are judged (D-12). +const CHECK: [&str; 8] = [ + "command", "expected", "test", "setup", "call", "level", "boundary", "fakes", +]; +/// A check's expected value's members. +const EXPECTED: [&str; 2] = ["kind", "value"]; +/// A check's test's members. +const TEST: [&str; 2] = ["file", "function"]; + +/// One evidence item of an accepted plan, its texts kept exactly as +/// written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EvidenceItem { + /// Its id, unique within the plan. + pub id: String, + /// The story of the truth it serves (D-01). + pub story: u32, + /// The id of the truth it serves, unique within that story. + pub truth: String, + /// The version of the truth it serves. + pub truth_version: u32, + /// What it holds, by its kind. + pub spec: Spec, + /// The defect it catches. + pub reason: String, +} + +impl EvidenceItem { + /// The item's kind, as its spec has it. + pub fn kind(&self) -> EvidenceKind { + match self.spec { + Spec::Artifact(_) => EvidenceKind::Artifact, + Spec::Link(_) => EvidenceKind::Link, + Spec::Check(_) => EvidenceKind::Check, + Spec::Observation(_) => EvidenceKind::Observation, + } + } +} + +/// An evidence item's spec, typed by the item's kind. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Spec { + /// A file or record that must exist. + Artifact(Artifact), + /// A value that must pass from a caller to a callee. + Link(Link), + /// A command whose result proves the truth. + Check(Check), + /// Something a named person must see. + Observation(Observation), +} + +/// What an artifact names: a path or a record, never both. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Artifact { + /// A file's path. + Path(String), + /// A record's name. + Record(String), +} + +/// A link's spec. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Link { + /// What passes the value. + pub caller: String, + /// What receives it. + pub callee: String, + /// The value, which the served truth names. + pub value: String, +} + +/// An observation's spec. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Observation { + /// What is to be seen. + pub what: String, + /// By whom. + pub by: String, +} + +/// A check's spec (D-12, ADR 0042). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Check { + /// The command that runs it. + pub command: String, + /// What it expects. + pub expected: Expected, + /// The test it runs. + pub test: CheckTest, + /// The state it sets up. + pub setup: String, + /// The call it makes. + pub call: String, + /// Whether it exercises one unit or several. + pub level: Level, + /// The unit or units it exercises. + pub boundary: String, + /// Every seam it fakes, in submitted order. + pub fakes: Vec, +} + +/// A check's expected value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Expected { + /// A literal the check's output must match. + Literal(String), + /// A property the check's output must hold. + Property(String), +} + +/// The test a check runs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CheckTest { + /// The test's file. + pub file: String, + /// The test's function. + pub function: String, +} + +/// A check's level (ADR 0042). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Level { + /// It exercises one unit. + Unit, + /// It exercises several units across a mocked boundary. + Integration, +} + +/// Reads a plan's evidence items in submitted order, each whole before the +/// next. +pub(super) fn read(items: &[Value]) -> Result, PlanRefusal> { + let mut seen = HashSet::new(); + items + .iter() + .enumerate() + .map(|(n, entry)| item(&format!("evidence_map[{n}]"), entry, &mut seen)) + .collect() +} + +/// One item read: an unknown member first, the first by name, then each +/// member in order. +fn item( + path: &str, + entry: &Value, + seen: &mut HashSet, +) -> Result { + let item = object(path, entry, &ITEM)?; + let id = item + .get("id") + .and_then(Value::as_str) + .filter(|id| !id.trim().is_empty() && seen.insert((*id).to_owned())) + .ok_or_else(|| typed(path, "id"))? + .to_owned(); + let story = counter(item.get("story")).ok_or_else(|| typed(path, "story"))?; + let truth = text(path, item, "truth")?; + let truth_version = + counter(item.get("truth_version")).ok_or_else(|| typed(path, "truth_version"))?; + let kind = item.get("kind").and_then(Value::as_str); + let at = format!("{path}.spec"); + let spec = item.get("spec").unwrap_or(&Value::Null); + let spec = match kind { + Some("artifact") => Spec::Artifact(artifact(&at, spec)?), + Some("link") => Spec::Link(link(&at, spec)?), + Some("check") => Spec::Check(check(&at, spec)?), + Some("observation") => Spec::Observation(observation(&at, spec)?), + _ => return Err(typed(path, "kind")), + }; + let reason = text(path, item, "reason")?; + Ok(EvidenceItem { + id, + story, + truth, + truth_version, + spec, + reason, + }) +} + +/// An artifact's spec: exactly one of `path` or `record`, as text. +fn artifact(path: &str, value: &Value) -> Result { + let spec = object(path, value, &ARTIFACT)?; + if spec.len() != 1 { + return Err(PlanRefusal::typed(path)); + } + if spec.contains_key("path") { + Ok(Artifact::Path(text(path, spec, "path")?)) + } else { + Ok(Artifact::Record(text(path, spec, "record")?)) + } +} + +/// A link's spec. +fn link(path: &str, value: &Value) -> Result { + let spec = object(path, value, &LINK)?; + Ok(Link { + caller: text(path, spec, "caller")?, + callee: text(path, spec, "callee")?, + value: text(path, spec, "value")?, + }) +} + +/// An observation's spec. +fn observation(path: &str, value: &Value) -> Result { + let spec = object(path, value, &OBSERVATION)?; + Ok(Observation { + what: text(path, spec, "what")?, + by: text(path, spec, "by")?, + }) +} + +/// A check's spec, each member in D-12's order. +fn check(path: &str, value: &Value) -> Result { + let spec = object(path, value, &CHECK)?; + let command = text(path, spec, "command")?; + let at = format!("{path}.expected"); + let expected = object(&at, spec.get("expected").unwrap_or(&Value::Null), &EXPECTED)?; + let kind = expected.get("kind").and_then(Value::as_str); + if !matches!(kind, Some("literal" | "property")) { + return Err(typed(&at, "kind")); + } + let value = text(&at, expected, "value")?; + let expected = if kind == Some("literal") { + Expected::Literal(value) + } else { + Expected::Property(value) + }; + let at = format!("{path}.test"); + let test = object(&at, spec.get("test").unwrap_or(&Value::Null), &TEST)?; + let test = CheckTest { + file: text(&at, test, "file")?, + function: text(&at, test, "function")?, + }; + let setup = text(path, spec, "setup")?; + let call = text(path, spec, "call")?; + // ADR 0042: a check without a level, or with another, is out of grammar. + let level = match spec.get("level").and_then(Value::as_str) { + Some("unit") => Level::Unit, + Some("integration") => Level::Integration, + _ => return Err(typed(path, "level")), + }; + let boundary = text(path, spec, "boundary")?; + let Some(Value::Array(fakes)) = spec.get("fakes") else { + return Err(typed(path, "fakes")); + }; + let fakes = fakes + .iter() + .enumerate() + .map(|(m, fake)| { + fake.as_str() + .map(str::to_owned) + .ok_or_else(|| typed(path, &format!("fakes[{m}]"))) + }) + .collect::>()?; + Ok(Check { + command, + expected, + test, + setup, + call, + level, + boundary, + fakes, + }) +} + +/// The object at `path` with no member outside `members`, else refused +/// naming `path`, or the first unknown member by name. +fn object<'a>( + path: &str, + value: &'a Value, + members: &[&str], +) -> Result<&'a Map, PlanRefusal> { + let Value::Object(object) = value else { + return Err(PlanRefusal::typed(path)); + }; + match first_unknown(object, members) { + Some(unknown) => Err(typed(path, unknown)), + None => Ok(object), + } +} + +/// The text member `name` of the object at `path` as written, blank +/// allowed, else refused naming it. +fn text(path: &str, object: &Map, name: &str) -> Result { + object + .get(name) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| typed(path, name)) +} + +/// The `typed-content` refusal naming member `name` of the object at +/// `path`. +fn typed(path: &str, name: &str) -> PlanRefusal { + PlanRefusal::typed(format!("{path}.{name}")) +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use serde_json::{Value, json}; + + use super::*; + use crate::plan::fixtures::{accepted, ar, f1, l1, p1, refusal, typed, with, without}; + + /// P1 with member `member` of the object at `pointer` within C1 set to + /// `to`. + fn c1_with(pointer: &str, member: &str, to: Value) -> Value { + with(p1(), &format!("/evidence_map/0{pointer}"), member, to) + } + + /// P1 with `item` added after O1. + fn plus(item: Value) -> Value { + let mut plan = p1(); + plan["evidence_map"].as_array_mut().unwrap().push(item); + plan + } + + #[test] + fn an_evidence_item_with_a_bad_member_accepted_is_caught() { + let facts = f1(); + let listed = with(p1(), "", "evidence_map", json!(["c1"])); + let cases = [ + (c1_with("", "owner", json!("Ada")), "evidence_map[0].owner"), + ( + without(p1(), "/evidence_map/0", "story"), + "evidence_map[0].story", + ), + (c1_with("", "story", json!(0)), "evidence_map[0].story"), + ( + c1_with("", "truth_version", json!("1")), + "evidence_map[0].truth_version", + ), + ( + without(p1(), "/evidence_map/0", "truth_version"), + "evidence_map[0].truth_version", + ), + (c1_with("", "truth", json!(1)), "evidence_map[0].truth"), + (c1_with("", "kind", json!("test")), "evidence_map[0].kind"), + ( + without(p1(), "/evidence_map/0", "reason"), + "evidence_map[0].reason", + ), + (c1_with("", "spec", json!("x")), "evidence_map[0].spec"), + (listed.clone(), "evidence_map[0]"), + (without(listed, "", "questions"), "evidence_map[0]"), + ]; + for (plan, path) in cases { + assert_eq!(refusal(&plan, &facts), typed(path), "{plan}"); + } + } + + #[test] + fn an_item_id_blank_or_repeated_in_one_plan_accepted_is_caught() { + let facts = f1(); + assert_eq!( + refusal(&c1_with("", "id", json!(" ")), &facts), + typed("evidence_map[0].id") + ); + assert_eq!( + refusal(&with(p1(), "/evidence_map/1", "id", json!("c1")), &facts), + typed("evidence_map[1].id") + ); + } + + #[test] + fn a_check_spec_out_of_grammar_accepted_is_caught() { + let facts = f1(); + let cases = [ + ( + c1_with("/spec", "owner", json!("Ada")), + "evidence_map[0].spec.owner", + ), + ( + c1_with("/spec/expected", "kind", json!("exact")), + "evidence_map[0].spec.expected.kind", + ), + ( + without(p1(), "/evidence_map/0/spec/expected", "value"), + "evidence_map[0].spec.expected.value", + ), + ( + without(p1(), "/evidence_map/0/spec/test", "function"), + "evidence_map[0].spec.test.function", + ), + ( + c1_with("/spec", "fakes", json!("the clock")), + "evidence_map[0].spec.fakes", + ), + ( + c1_with("/spec", "fakes", json!(["the clock", 3])), + "evidence_map[0].spec.fakes[1]", + ), + ( + c1_with("/spec", "setup", json!(null)), + "evidence_map[0].spec.setup", + ), + ]; + for (plan, path) in cases { + assert_eq!(refusal(&plan, &facts), typed(path), "{plan}"); + } + } + + #[test] + fn an_artifact_link_or_observation_spec_out_of_grammar_accepted_is_caught() { + let facts = f1(); + let plan = accepted(&plus(ar()), &facts); + assert_eq!( + plan.evidence_map()[3].spec, + Spec::Artifact(Artifact::Path("src/judge.rs".into())) + ); + let ar_with = |spec: Value| with(plus(ar()), "/evidence_map/3", "spec", spec); + let plan = accepted(&ar_with(json!({"record": "plan.approved"})), &facts); + assert_eq!( + plan.evidence_map()[3].spec, + Spec::Artifact(Artifact::Record("plan.approved".into())) + ); + assert_eq!( + refusal(&ar_with(json!({})), &facts), + typed("evidence_map[3].spec") + ); + assert_eq!( + refusal( + &ar_with(json!({"path": "src/judge.rs", "record": "plan.approved"})), + &facts + ), + typed("evidence_map[3].spec") + ); + assert_eq!( + refusal( + &without(plus(l1()), "/evidence_map/3/spec", "value"), + &facts + ), + typed("evidence_map[3].spec.value") + ); + let o1_with = with( + p1(), + "/evidence_map/2", + "spec", + json!({"what": "every task title", "who": "the owner"}), + ); + assert_eq!(refusal(&o1_with, &facts), typed("evidence_map[2].spec.who")); + } +} diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index 04602c27..a7aa7b7a 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -4,16 +4,17 @@ //! A plan arrives as plain JSON and the phase's facts as plain values the //! binary gathered from its views. The plan is judged in one fixed order, //! the first fault answering, so one plan always gets one answer: (1) the -//! plan's own members, task by task within `tasks`; (2) the `questions` -//! member through the question set judge; (3) each task file inside the -//! lease. The judge trusts the facts and judges the plan. -//! Nothing here records anything. +//! plan's own members, task by task within `tasks` and item by item within +//! `evidence_map`; (2) the `questions` member through the question set +//! judge; (3) each task file inside the lease. The judge trusts the facts +//! and judges the plan. Nothing here records anything. use std::num::NonZeroU32; use serde_json::Value; use super::content; +use super::evidence::EvidenceItem; use super::task::{self, Task}; use crate::questions::{QuestionSet, SetRefusal}; @@ -148,7 +149,7 @@ pub struct Plan { pub(super) context: String, pub(super) notes: String, pub(super) tasks: Vec, - pub(super) evidence_map: Vec, + pub(super) evidence_map: Vec, pub(super) questions: QuestionSet, } @@ -194,7 +195,7 @@ impl Plan { } /// The evidence items, in submitted order. - pub fn evidence_map(&self) -> &[Value] { + pub fn evidence_map(&self) -> &[EvidenceItem] { &self.evidence_map } diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index 1df360e1..b9dce81b 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -7,12 +7,16 @@ //! value it judges. mod content; +mod evidence; #[cfg(test)] mod fixtures; mod judge; mod lease; mod task; +pub use evidence::{ + Artifact, Check, CheckTest, EvidenceItem, Expected, Level, Link, Observation, Spec, +}; pub use judge::{ ApprovedItem, CommittedStory, CurrentTruth, EvidenceKind, LEASE, Plan, PlanFacts, PlanRefusal, TYPED_CONTENT, judge_plan, From e9668e64179f0c54c50ce09b962c612e5eac9a05 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 17:58:54 -0400 Subject: [PATCH 07/26] feat(8-1): refuse a check with a blank command, expected value, file or boundary A check that names nothing to run, nothing to expect, no test file or no boundary cannot prove its truth, so each is refused under its own code at either level. The new `check-boundary` code sits beside the other three; a blank setup, call or test function has no code and is accepted. --- crates/baley-core/src/plan/evidence.rs | 166 +++++++++++++++++++++++++ crates/baley-core/src/plan/judge.rs | 32 ++++- crates/baley-core/src/plan/mod.rs | 4 +- 3 files changed, 196 insertions(+), 6 deletions(-) diff --git a/crates/baley-core/src/plan/evidence.rs b/crates/baley-core/src/plan/evidence.rs index d8ebc41e..f94800e3 100644 --- a/crates/baley-core/src/plan/evidence.rs +++ b/crates/baley-core/src/plan/evidence.rs @@ -166,6 +166,34 @@ pub(super) fn read(items: &[Value]) -> Result, PlanRefusal> { .collect() } +/// Step (4): the first check, in submitted order, with a blank command, +/// expected value, test file or boundary, judged in that field order at +/// either level (PLN-R13, D-07). A blank setup, call or test function has +/// no code and is accepted. +pub(super) fn blank_fields(items: &[EvidenceItem]) -> Result<(), PlanRefusal> { + let blank = |text: &str| text.trim().is_empty(); + for (position, item) in items.iter().enumerate() { + let Spec::Check(check) = &item.spec else { + continue; + }; + let id = item.id.clone(); + let (Expected::Literal(expected) | Expected::Property(expected)) = &check.expected; + if blank(&check.command) { + return Err(PlanRefusal::CheckCommand { position, id }); + } + if blank(expected) { + return Err(PlanRefusal::CheckExpected { position, id }); + } + if blank(&check.test.file) { + return Err(PlanRefusal::CheckTestFile { position, id }); + } + if blank(&check.boundary) { + return Err(PlanRefusal::CheckBoundary { position, id }); + } + } + Ok(()) +} + /// One item read: an unknown member first, the first by name, then each /// member in order. fn item( @@ -332,6 +360,7 @@ mod tests { use serde_json::{Value, json}; use super::*; + use crate::plan::PlanRefusal; use crate::plan::fixtures::{accepted, ar, f1, l1, p1, refusal, typed, with, without}; /// P1 with member `member` of the object at `pointer` within C1 set to @@ -472,4 +501,141 @@ mod tests { ); assert_eq!(refusal(&o1_with, &facts), typed("evidence_map[2].spec.who")); } + + /// P1 with member `member` of the object at `pointer` within the item + /// at `at` set to `to`. + fn item_with(at: usize, pointer: &str, member: &str, to: Value) -> Value { + with(p1(), &format!("/evidence_map/{at}{pointer}"), member, to) + } + + #[test] + fn a_check_without_a_level_or_with_a_blank_field_accepted_or_refused_under_another_code_is_caught() + { + let facts = f1(); + let plan = accepted(&p1(), &facts); + let level = |at: usize| match &plan.evidence_map()[at].spec { + Spec::Check(check) => (check.level, check.fakes.clone()), + other => panic!("a check, not {other:?}"), + }; + assert_eq!(level(0), (Level::Unit, Vec::new())); + assert_eq!(level(1), (Level::Integration, vec!["the clock".to_owned()])); + accepted( + &item_with(0, "/spec", "level", json!("integration")), + &facts, + ); + accepted(&item_with(1, "/spec", "fakes", json!([])), &facts); + assert_eq!( + refusal(&without(p1(), "/evidence_map/0/spec", "level"), &facts), + typed("evidence_map[0].spec.level") + ); + assert_eq!( + refusal(&item_with(0, "/spec", "level", json!("system")), &facts), + typed("evidence_map[0].spec.level") + ); + let c1 = |position: usize, id: &str| (position, id.to_owned()); + let command = |(position, id)| PlanRefusal::CheckCommand { position, id }; + let expected = |(position, id)| PlanRefusal::CheckExpected { position, id }; + let test_file = |(position, id)| PlanRefusal::CheckTestFile { position, id }; + let boundary = |(position, id)| PlanRefusal::CheckBoundary { position, id }; + let cases = [ + ( + item_with(0, "/spec", "command", json!(" ")), + command(c1(0, "c1")), + ), + ( + item_with(0, "/spec/expected", "value", json!("")), + expected(c1(0, "c1")), + ), + ( + item_with(0, "/spec/test", "file", json!(" ")), + test_file(c1(0, "c1")), + ), + ( + item_with(0, "/spec", "boundary", json!("")), + boundary(c1(0, "c1")), + ), + ( + item_with(1, "/spec", "boundary", json!(" ")), + boundary(c1(1, "c2")), + ), + ( + item_with(1, "/spec", "command", json!(" ")), + command(c1(1, "c2")), + ), + ( + item_with(1, "/spec/expected", "value", json!("")), + expected(c1(1, "c2")), + ), + ( + item_with(1, "/spec/test", "file", json!("")), + test_file(c1(1, "c2")), + ), + ]; + for (plan, refused) in cases { + assert_eq!(refusal(&plan, &facts), refused, "{plan}"); + } + } + + #[test] + fn a_check_judged_on_its_fields_in_another_order_or_on_a_field_without_a_code_is_caught() { + let facts = f1(); + let c1 = || ("c1".to_owned(), 0); + let both = |first: (&str, &str, Value), second: (&str, &str, Value)| { + let plan = with( + p1(), + &format!("/evidence_map/0{}", first.0), + first.1, + first.2, + ); + with( + plan, + &format!("/evidence_map/0{}", second.0), + second.1, + second.2, + ) + }; + let (id, position) = c1(); + assert_eq!( + refusal( + &both( + ("/spec", "command", json!("")), + ("/spec", "boundary", json!("")) + ), + &facts + ), + PlanRefusal::CheckCommand { position, id } + ); + let (id, position) = c1(); + assert_eq!( + refusal( + &both( + ("/spec/expected", "value", json!(" ")), + ("/spec/test", "file", json!("")) + ), + &facts + ), + PlanRefusal::CheckExpected { position, id } + ); + let (id, position) = c1(); + assert_eq!( + refusal( + &both( + ("/spec/test", "file", json!("")), + ("/spec", "boundary", json!(" ")) + ), + &facts + ), + PlanRefusal::CheckTestFile { position, id } + ); + let unnamed = both(("/spec", "setup", json!("")), ("/spec", "call", json!(""))); + accepted( + &with(unnamed, "/evidence_map/0/spec/test", "function", json!("")), + &facts, + ); + let command = with(p1(), "/evidence_map/0/spec", "command", json!("")); + assert_eq!( + refusal(&without(command, "/evidence_map/1/spec", "level"), &facts), + typed("evidence_map[1].spec.level") + ); + } } diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index a7aa7b7a..b7b62d79 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -6,15 +6,16 @@ //! the first fault answering, so one plan always gets one answer: (1) the //! plan's own members, task by task within `tasks` and item by item within //! `evidence_map`; (2) the `questions` member through the question set -//! judge; (3) each task file inside the lease. The judge trusts the facts -//! and judges the plan. Nothing here records anything. +//! judge; (3) each task file inside the lease; (4) no check field with a +//! code blank. The judge trusts the facts and judges the plan. Nothing here +//! records anything. use std::num::NonZeroU32; use serde_json::Value; use super::content; -use super::evidence::EvidenceItem; +use super::evidence::{self, EvidenceItem}; use super::task::{self, Task}; use crate::questions::{QuestionSet, SetRefusal}; @@ -24,6 +25,15 @@ use crate::questions::{QuestionSet, SetRefusal}; pub const TYPED_CONTENT: &str = "typed-content"; /// The refusal code for a task naming a file outside the plan's lease. pub const LEASE: &str = "lease"; +/// The refusal code for a check whose command is blank. +pub const CHECK_COMMAND: &str = "check-command"; +/// The refusal code for a check whose expected value is blank. +pub const CHECK_EXPECTED: &str = "check-expected"; +/// The refusal code for a check whose test file is blank. +pub const CHECK_TEST_FILE: &str = "check-test-file"; +/// The refusal code for a check whose boundary is blank, at either level +/// (D-07). +pub const CHECK_BOUNDARY: &str = "check-boundary"; /// Why a plan is refused. Positions count from 0 in the list as submitted. #[derive(Debug, Clone, PartialEq, Eq)] @@ -42,6 +52,15 @@ pub enum PlanRefusal { /// The question set judge refused the `questions` member: its refusal /// unchanged, positions counting within `questions` (D-10). Questions(SetRefusal), + /// The check at `position`, whose id is `id`, has a blank command. + CheckCommand { position: usize, id: String }, + /// The check at `position`, whose id is `id`, has a blank expected + /// value. + CheckExpected { position: usize, id: String }, + /// The check at `position`, whose id is `id`, has a blank test file. + CheckTestFile { position: usize, id: String }, + /// The check at `position`, whose id is `id`, has a blank boundary. + CheckBoundary { position: usize, id: String }, } impl PlanRefusal { @@ -51,6 +70,10 @@ impl PlanRefusal { Self::TypedContent { .. } => TYPED_CONTENT, Self::Lease { .. } => LEASE, Self::Questions(refusal) => refusal.code(), + Self::CheckCommand { .. } => CHECK_COMMAND, + Self::CheckExpected { .. } => CHECK_EXPECTED, + Self::CheckTestFile { .. } => CHECK_TEST_FILE, + Self::CheckBoundary { .. } => CHECK_BOUNDARY, } } @@ -213,10 +236,11 @@ impl Plan { /// Judges the submitted plan `plan` against the phase's `facts` in the /// fixed order, the first fault answering: (1) the plan's own members; /// (2) the `questions` member through `judge_set`; (3) `lease`, task by -/// task and file by file. +/// task and file by file; (4) the blank check fields, item by item. pub fn judge_plan(plan: &Value, _facts: &PlanFacts) -> Result { let plan = content::read(plan)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; + evidence::blank_fields(&plan.evidence_map)?; Ok(plan) } diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index b9dce81b..62b32ca7 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -18,8 +18,8 @@ pub use evidence::{ Artifact, Check, CheckTest, EvidenceItem, Expected, Level, Link, Observation, Spec, }; pub use judge::{ - ApprovedItem, CommittedStory, CurrentTruth, EvidenceKind, LEASE, Plan, PlanFacts, PlanRefusal, - TYPED_CONTENT, judge_plan, + ApprovedItem, CHECK_BOUNDARY, CHECK_COMMAND, CHECK_EXPECTED, CHECK_TEST_FILE, CommittedStory, + CurrentTruth, EvidenceKind, LEASE, Plan, PlanFacts, PlanRefusal, TYPED_CONTENT, judge_plan, }; pub use lease::{inside_lease, plain_relative_path}; pub use task::Task; From a339dc62885eba032fb87497ef88e0adfa69dfd7 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 18:00:44 -0400 Subject: [PATCH 08/26] feat(8-1): refuse a plan for a phase with no truths or an uncommitted story A plan for a phase nobody refined has nothing to prove, and a plan serving a story the phase never committed would plan work outside it. Both are judged on the phase's committed stories alone, after the plan's own grammar, lease and check fields. --- crates/baley-core/src/plan/fixtures.rs | 3 - crates/baley-core/src/plan/judge.rs | 168 ++++++++++++++++++++++++- crates/baley-core/src/plan/mod.rs | 4 +- crates/baley-core/src/plan/stories.rs | 57 +++++++++ 4 files changed, 222 insertions(+), 10 deletions(-) create mode 100644 crates/baley-core/src/plan/stories.rs diff --git a/crates/baley-core/src/plan/fixtures.rs b/crates/baley-core/src/plan/fixtures.rs index 7976ae05..e5c6dc2e 100644 --- a/crates/baley-core/src/plan/fixtures.rs +++ b/crates/baley-core/src/plan/fixtures.rs @@ -2,9 +2,6 @@ //! decisions, never from running the judge: one copy every test of the //! module reads. -// Later tasks of the plan read the builders this one does not. -#![allow(dead_code)] - use serde_json::{Value, json}; use super::{CommittedStory, CurrentTruth, Plan, PlanFacts, PlanRefusal, judge_plan}; diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index b7b62d79..f948bdd8 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -7,16 +7,17 @@ //! plan's own members, task by task within `tasks` and item by item within //! `evidence_map`; (2) the `questions` member through the question set //! judge; (3) each task file inside the lease; (4) no check field with a -//! code blank. The judge trusts the facts and judges the plan. Nothing here -//! records anything. +//! code blank; (5) a committed story holding a truth; (6) every story the +//! plan serves committed to the phase. The judge trusts the facts and +//! judges the plan. Nothing here records anything. use std::num::NonZeroU32; use serde_json::Value; -use super::content; use super::evidence::{self, EvidenceItem}; use super::task::{self, Task}; +use super::{content, stories}; use crate::questions::{QuestionSet, SetRefusal}; /// The refusal code for a plan out of its grammar: not an object, or a @@ -34,6 +35,11 @@ pub const CHECK_TEST_FILE: &str = "check-test-file"; /// The refusal code for a check whose boundary is blank, at either level /// (D-07). pub const CHECK_BOUNDARY: &str = "check-boundary"; +/// The refusal code for a plan for a phase none of whose committed stories +/// holds a current truth. +pub const NO_TRUTHS: &str = "no-truths"; +/// The refusal code for a plan serving a story not committed to the phase. +pub const STORY_NOT_IN_PHASE: &str = "story-not-in-phase"; /// Why a plan is refused. Positions count from 0 in the list as submitted. #[derive(Debug, Clone, PartialEq, Eq)] @@ -61,6 +67,10 @@ pub enum PlanRefusal { CheckTestFile { position: usize, id: String }, /// The check at `position`, whose id is `id`, has a blank boundary. CheckBoundary { position: usize, id: String }, + /// No committed story of the phase holds a current truth. + NoTruths, + /// The plan serves `story`, which is not committed to the phase. + StoryNotInPhase { story: u32 }, } impl PlanRefusal { @@ -74,6 +84,8 @@ impl PlanRefusal { Self::CheckExpected { .. } => CHECK_EXPECTED, Self::CheckTestFile { .. } => CHECK_TEST_FILE, Self::CheckBoundary { .. } => CHECK_BOUNDARY, + Self::NoTruths => NO_TRUTHS, + Self::StoryNotInPhase { .. } => STORY_NOT_IN_PHASE, } } @@ -236,11 +248,14 @@ impl Plan { /// Judges the submitted plan `plan` against the phase's `facts` in the /// fixed order, the first fault answering: (1) the plan's own members; /// (2) the `questions` member through `judge_set`; (3) `lease`, task by -/// task and file by file; (4) the blank check fields, item by item. -pub fn judge_plan(plan: &Value, _facts: &PlanFacts) -> Result { +/// task and file by file; (4) the blank check fields, item by item; +/// (5) `no-truths`; (6) `story-not-in-phase`, in the plan's story order. +pub fn judge_plan(plan: &Value, facts: &PlanFacts) -> Result { let plan = content::read(plan)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; evidence::blank_fields(&plan.evidence_map)?; + stories::holds_truths(facts)?; + stories::committed(&plan.stories, facts)?; Ok(plan) } @@ -252,7 +267,7 @@ mod tests { use serde_json::json; use super::*; - use crate::plan::fixtures::{accepted, f1, p1, qa, qb, refusal, with}; + use crate::plan::fixtures::{accepted, f0, f1, p1, qa, qb, refusal, typed, with, without}; use crate::questions::Question; #[test] @@ -295,4 +310,145 @@ mod tests { ); assert_eq!(waiting.code(), "question-dependency"); } + + fn lease(position: usize, id: &str, file: &str) -> PlanRefusal { + PlanRefusal::Lease { + position, + id: id.into(), + file: file.into(), + } + } + + #[test] + fn a_plan_with_bad_content_a_bad_lease_or_an_uncommitted_story_accepted_or_named_wrongly_is_caught() + { + let facts = f1(); + assert_eq!(accepted(&p1(), &facts).size(), 1); + let mut over = vec![json!("docs")]; + over.extend((0..=254).map(|n| json!(format!("d/{n}")))); + let cases = [ + (with(p1(), "", "plan", json!(1)), typed("plan")), + ( + with( + p1(), + "", + "question_set", + json!("5d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"), + ), + typed("question_set"), + ), + (with(p1(), "", "size", json!(1)), typed("size")), + (with(p1(), "", "suite", json!("cargo test")), typed("suite")), + (with(p1(), "", "owner", json!("Ada")), typed("owner")), + (without(p1(), "", "goal"), typed("goal")), + (with(p1(), "", "phase", json!("8")), typed("phase")), + ( + with(p1(), "", "stories", json!([1, 1])), + typed("stories[1]"), + ), + ( + with(p1(), "", "directories", json!(["docs/"])), + typed("directories[0]"), + ), + ( + with(p1(), "", "files", json!(["/src/judge.rs"])), + typed("files[0]"), + ), + ( + with(p1(), "", "files", json!(["src/../judge.rs"])), + typed("files[0]"), + ), + ( + with(p1(), "", "files", json!(["src/judge.rs", "src/judge.rs"])), + typed("files[1]"), + ), + ( + with( + with(p1(), "", "files", json!([])), + "", + "directories", + json!([]), + ), + typed("files"), + ), + ( + with(p1(), "", "directories", Value::Array(over)), + typed("directories[255]"), + ), + ( + with( + p1(), + "/tasks/0", + "files", + json!(["src/judge.rs", "src/other.rs"]), + ), + lease(0, "k1", "src/other.rs"), + ), + ( + with(p1(), "", "stories", json!([1, 4])), + PlanRefusal::StoryNotInPhase { story: 4 }, + ), + ( + with( + p1(), + "", + "questions", + json!([{"id": "q1", "question": "Which store backs the ledger?", + "recommended": "SQLite", "depends_on": ["q9"]}]), + ), + PlanRefusal::Questions(SetRefusal::QuestionDependency { + position: 0, + id: "q1".into(), + }), + ), + ( + with(p1(), "", "questions", json!("none")), + PlanRefusal::Questions(SetRefusal::TypedContent { position: None }), + ), + ]; + for (plan, refused) in cases { + assert_eq!(refusal(&plan, &facts), refused, "{plan}"); + } + assert_eq!(refusal(&p1(), &f0()), PlanRefusal::NoTruths); + } + + #[test] + fn faults_judged_in_another_order_are_caught() { + let facts = f1(); + let other = |plan| with(plan, "/tasks/0", "files", json!(["src/other.rs"])); + let blank = |plan| with(plan, "/evidence_map/0/spec", "command", json!("")); + let waiting = |plan| with(plan, "", "questions", json!([qb()])); + let owner = with(p1(), "", "owner", json!("Ada")); + let cases = [ + ( + with(owner, "", "directories", json!(["docs/"])), + &facts, + typed("owner"), + ), + (waiting(without(p1(), "", "goal")), &facts, typed("goal")), + ( + waiting(other(p1())), + &facts, + PlanRefusal::Questions(SetRefusal::QuestionDependency { + position: 0, + id: "q2".into(), + }), + ), + (blank(other(p1())), &facts, lease(0, "k1", "src/other.rs")), + ]; + for (plan, facts, refused) in cases { + assert_eq!(refusal(&plan, facts), refused, "{plan}"); + } + assert_eq!( + refusal(&blank(p1()), &f0()), + PlanRefusal::CheckCommand { + position: 0, + id: "c1".into() + } + ); + assert_eq!( + refusal(&with(p1(), "", "stories", json!([1, 4])), &f0()), + PlanRefusal::NoTruths + ); + } } diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index 62b32ca7..cceeb452 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -12,6 +12,7 @@ mod evidence; mod fixtures; mod judge; mod lease; +mod stories; mod task; pub use evidence::{ @@ -19,7 +20,8 @@ pub use evidence::{ }; pub use judge::{ ApprovedItem, CHECK_BOUNDARY, CHECK_COMMAND, CHECK_EXPECTED, CHECK_TEST_FILE, CommittedStory, - CurrentTruth, EvidenceKind, LEASE, Plan, PlanFacts, PlanRefusal, TYPED_CONTENT, judge_plan, + CurrentTruth, EvidenceKind, LEASE, NO_TRUTHS, Plan, PlanFacts, PlanRefusal, STORY_NOT_IN_PHASE, + TYPED_CONTENT, judge_plan, }; pub use lease::{inside_lease, plain_relative_path}; pub use task::Task; diff --git a/crates/baley-core/src/plan/stories.rs b/crates/baley-core/src/plan/stories.rs new file mode 100644 index 00000000..ebf4d33a --- /dev/null +++ b/crates/baley-core/src/plan/stories.rs @@ -0,0 +1,57 @@ +//! Steps (5) and (6) of the plan judge: the phase's committed stories +//! (PLN-R13). Neither reads any other fact. + +use super::judge::{PlanFacts, PlanRefusal}; + +/// Step (5): a phase none of whose committed stories holds a current truth, +/// including a phase with no committed story, is refused `no-truths`. A +/// story whose approved truth list is empty holds none. +pub(super) fn holds_truths(facts: &PlanFacts) -> Result<(), PlanRefusal> { + if facts.stories.iter().all(|story| story.truths.is_empty()) { + return Err(PlanRefusal::NoTruths); + } + Ok(()) +} + +/// Step (6): the first story the plan serves, in its order, that is not +/// committed to the phase is refused `story-not-in-phase`, naming it. +pub(super) fn committed(stories: &[u32], facts: &PlanFacts) -> Result<(), PlanRefusal> { + match stories + .iter() + .find(|id| !facts.stories.iter().any(|story| story.id == **id)) + { + Some(&story) => Err(PlanRefusal::StoryNotInPhase { story }), + None => Ok(()), + } +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use serde_json::json; + + use crate::plan::PlanRefusal; + use crate::plan::fixtures::{accepted, f0, f1, f2, p1, p3, refusal, with}; + + #[test] + fn a_plan_for_a_phase_without_truths_accepted_or_one_with_truths_refused_is_caught() { + assert_eq!(refusal(&p1(), &f0()), PlanRefusal::NoTruths); + let mut uncommitted = f1(); + uncommitted.stories.clear(); + assert_eq!(refusal(&p1(), &uncommitted), PlanRefusal::NoTruths); + accepted(&p3(), &f2()); + } + + #[test] + fn a_story_not_committed_named_wrongly_is_caught() { + let facts = f1(); + for stories in [json!([4, 5]), json!([2, 4])] { + assert_eq!( + refusal(&with(p1(), "", "stories", stories), &facts), + PlanRefusal::StoryNotInPhase { story: 4 } + ); + } + } +} From 56123fa2c229665f9ecd95ba8a4390137428c492 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 19:01:16 -0400 Subject: [PATCH 09/26] feat(8-2): bind each evidence item to its own story's current truth An item names its truth by story, id and version, since a truth id is unique only within its story; step (7) refuses an item naming no current truth of a served story or another version of it. --- crates/baley-core/src/plan/binding.rs | 130 +++++++++++++++++++++++ crates/baley-core/src/plan/fixtures.rs | 140 ++++++++++++++++++++++++- crates/baley-core/src/plan/judge.rs | 29 ++++- crates/baley-core/src/plan/mod.rs | 5 +- 4 files changed, 297 insertions(+), 7 deletions(-) create mode 100644 crates/baley-core/src/plan/binding.rs diff --git a/crates/baley-core/src/plan/binding.rs b/crates/baley-core/src/plan/binding.rs new file mode 100644 index 00000000..fcd7f442 --- /dev/null +++ b/crates/baley-core/src/plan/binding.rs @@ -0,0 +1,130 @@ +//! Step (7) of the plan judge: each evidence item bound to its own story's +//! current truth (PLN-R13, D-01). A truth id is unique only within its +//! story, so the truth is looked up inside the item's story alone. + +use super::evidence::EvidenceItem; +use super::judge::{CurrentTruth, PlanFacts, PlanRefusal}; + +/// Step (7), item by item in submitted order: an item whose story is not +/// one the plan serves, or whose truth id is not a current truth of that +/// story, is refused `evidence-item-truth`; one naming its truth at another +/// version, older or newer, is refused `truth-version-mismatch` with the +/// current version. Answers each item's truth, in the plan's item order. +pub(super) fn bind<'a>( + stories: &[u32], + items: &[EvidenceItem], + facts: &'a PlanFacts, +) -> Result, PlanRefusal> { + items + .iter() + .enumerate() + .map(|(position, item)| { + let truth = stories + .contains(&item.story) + .then(|| facts.stories.iter().find(|story| story.id == item.story)) + .flatten() + .and_then(|story| story.truths.iter().find(|truth| truth.id == item.truth)); + match truth { + None => Err(PlanRefusal::EvidenceItemTruth { + position, + id: item.id.clone(), + }), + Some(truth) if truth.version != item.truth_version => { + Err(PlanRefusal::TruthVersionMismatch { + position, + id: item.id.clone(), + current: truth.version, + }) + } + Some(truth) => Ok(truth), + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use serde_json::json; + + use crate::plan::PlanRefusal; + use crate::plan::fixtures::{ar, f1, p1, p2, plus, refusal, with}; + + fn untrue(position: usize, id: &str) -> PlanRefusal { + PlanRefusal::EvidenceItemTruth { + position, + id: id.into(), + } + } + + fn mismatch(position: usize, id: &str, current: u32) -> PlanRefusal { + PlanRefusal::TruthVersionMismatch { + position, + id: id.into(), + current, + } + } + + #[test] + fn an_item_naming_no_served_truth_or_an_old_version_accepted_is_caught() { + let facts = f1(); + let cases = [ + ( + with(p1(), "/evidence_map/0", "story", json!(3)), + untrue(0, "c1"), + ), + ( + with(p1(), "/evidence_map/0", "truth", json!("t3")), + untrue(0, "c1"), + ), + ( + plus( + p1(), + with( + with(ar(), "", "truth", json!("t2")), + "", + "truth_version", + json!(1), + ), + ), + mismatch(3, "a1", 2), + ), + ]; + for (plan, refused) in cases { + assert_eq!(refusal(&plan, &facts), refused, "{plan}"); + } + assert_eq!(untrue(0, "c1").code(), "evidence-item-truth"); + assert_eq!(mismatch(3, "a1", 2).code(), "truth-version-mismatch"); + } + + #[test] + fn an_item_bound_by_truth_id_alone_is_caught() { + let facts = f1(); + let cases = [ + ( + with(p2(), "/evidence_map/3", "truth_version", json!(1)), + mismatch(3, "c4", 3), + ), + ( + with(p2(), "/evidence_map/3", "story", json!(1)), + mismatch(3, "c4", 1), + ), + ]; + for (plan, refused) in cases { + assert_eq!(refusal(&plan, &facts), refused, "{plan}"); + } + } + + #[test] + fn a_newer_version_than_the_current_accepted_is_caught() { + assert_eq!( + refusal( + &with(p1(), "/evidence_map/1", "truth_version", json!(3)), + &f1() + ), + mismatch(1, "c2", 2) + ); + } +} diff --git a/crates/baley-core/src/plan/fixtures.rs b/crates/baley-core/src/plan/fixtures.rs index e5c6dc2e..bebbdc9c 100644 --- a/crates/baley-core/src/plan/fixtures.rs +++ b/crates/baley-core/src/plan/fixtures.rs @@ -2,9 +2,17 @@ //! decisions, never from running the judge: one copy every test of the //! module reads. +// Builders the later steps' tests read; removed once every one is read. +#![allow(dead_code)] + +use std::num::NonZeroU32; + use serde_json::{Value, json}; -use super::{CommittedStory, CurrentTruth, Plan, PlanFacts, PlanRefusal, judge_plan}; +use super::{ + ApprovedItem, CommittedStory, CurrentTruth, EvidenceKind, Plan, PlanFacts, PlanRefusal, + judge_plan, +}; fn truth( id: &str, @@ -177,6 +185,136 @@ pub(super) fn p3() -> Value { plan } +/// F3: F1 with story 2's `t1` at version 1, so both stories hold a `t1` at +/// version 1. +pub(super) fn f3() -> PlanFacts { + let mut facts = f1(); + facts.stories[1].truths[0].version = 1; + facts +} + +/// F1 with `approved` as the approved plans' items. +pub(super) fn under(approved: Vec) -> PlanFacts { + let mut facts = f1(); + facts.approved = approved; + facts +} + +/// F1 with capacity `capacity` and current size `size`. +pub(super) fn at(capacity: u32, size: u32) -> PlanFacts { + let mut facts = f1(); + facts.capacity = Some(NonZeroU32::new(capacity).expect("a capacity above 0")); + facts.size = size; + facts +} + +/// `item` as approved plan `plan` recorded it, its definition the item +/// whole. +pub(super) fn approved(plan: u32, item: Value) -> ApprovedItem { + let text = |member: &str| item[member].as_str().expect("a text").to_owned(); + let number = + |member: &str| u32::try_from(item[member].as_u64().expect("a number")).expect("a counter"); + let kind = match item["kind"].as_str() { + Some("artifact") => EvidenceKind::Artifact, + Some("link") => EvidenceKind::Link, + Some("check") => EvidenceKind::Check, + Some("observation") => EvidenceKind::Observation, + other => panic!("no kind {other:?}"), + }; + ApprovedItem { + plan, + id: text("id"), + story: number("story"), + truth: text("truth"), + truth_version: number("truth_version"), + kind, + definition: item, + } +} + +/// A1: plan 1's C1 with reason `another reason`. +pub(super) fn a1() -> Vec { + vec![approved( + 1, + with(c1(), "", "reason", json!("another reason")), + )] +} + +/// A2: plan 1's C1 exactly. +pub(super) fn a2() -> Vec { + vec![approved(1, c1())] +} + +/// C3: C1 with id `c3`, a second check for story 1's `t1`. +pub(super) fn c3() -> Value { + let mut item = c1(); + item["id"] = json!("c3"); + item["spec"]["command"] = json!("cargo test lease_again"); + item +} + +/// C5: C4 for version 1 of story 2's `t1`. +pub(super) fn c5() -> Value { + with(c4(), "", "truth_version", json!(1)) +} + +/// C6: C1 with id `c6`, a third check for story 1's `t1`. +pub(super) fn c6() -> Value { + let mut item = c1(); + item["id"] = json!("c6"); + item["spec"]["command"] = json!("cargo test lease_third"); + item +} + +/// K3: K1 with id `k3`. +pub(super) fn k3() -> Value { + with(k1(), "", "id", json!("k3")) +} + +/// P2: P1 for stories 1 and 2, proved by C1, C2, O1 and C4. +pub(super) fn p2() -> Value { + let mut plan = p1(); + plan["stories"] = json!([1, 2]); + plan["evidence_map"] = json!([c1(), c2(), o1(), c4()]); + plan +} + +/// P4: P1 with tasks K1 and K3. +pub(super) fn p4() -> Value { + with(p1(), "", "tasks", json!([k1(), k3()])) +} + +/// `plan` with `item` added at the end of its evidence map. +pub(super) fn plus(mut plan: Value, item: Value) -> Value { + plan["evidence_map"] + .as_array_mut() + .expect("an evidence map") + .push(item); + plan +} + +/// `plan` without the evidence items whose ids are `ids`. +pub(super) fn dropping(mut plan: Value, ids: &[&str]) -> Value { + plan["evidence_map"] + .as_array_mut() + .expect("an evidence map") + .retain(|item| !ids.contains(&item["id"].as_str().expect("an id"))); + plan +} + +/// `plan` with the evidence item whose id is `id` replaced by `item`. +pub(super) fn replacing(mut plan: Value, id: &str, item: Value) -> Value { + let map = plan["evidence_map"] + .as_array_mut() + .expect("an evidence map"); + let at = map + .iter() + .position(|entry| entry["id"] == id) + .expect("the item is present"); + map[at] = item; + plan +} + /// `value` with member `member` of the object at `pointer` set to `to`, /// added when absent. pub(super) fn with(mut value: Value, pointer: &str, member: &str, to: Value) -> Value { diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index f948bdd8..217762fd 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -8,8 +8,9 @@ //! `evidence_map`; (2) the `questions` member through the question set //! judge; (3) each task file inside the lease; (4) no check field with a //! code blank; (5) a committed story holding a truth; (6) every story the -//! plan serves committed to the phase. The judge trusts the facts and -//! judges the plan. Nothing here records anything. +//! plan serves committed to the phase; (7) each evidence item bound to its +//! own story's current truth. The judge trusts the facts and judges the +//! plan. Nothing here records anything. use std::num::NonZeroU32; @@ -17,7 +18,7 @@ use serde_json::Value; use super::evidence::{self, EvidenceItem}; use super::task::{self, Task}; -use super::{content, stories}; +use super::{binding, content, stories}; use crate::questions::{QuestionSet, SetRefusal}; /// The refusal code for a plan out of its grammar: not an object, or a @@ -40,6 +41,12 @@ pub const CHECK_BOUNDARY: &str = "check-boundary"; pub const NO_TRUTHS: &str = "no-truths"; /// The refusal code for a plan serving a story not committed to the phase. pub const STORY_NOT_IN_PHASE: &str = "story-not-in-phase"; +/// The refusal code for an evidence item naming no current truth of a story +/// the plan serves. +pub const EVIDENCE_ITEM_TRUTH: &str = "evidence-item-truth"; +/// The refusal code for an evidence item naming its truth at a version +/// other than the current one. +pub const TRUTH_VERSION_MISMATCH: &str = "truth-version-mismatch"; /// Why a plan is refused. Positions count from 0 in the list as submitted. #[derive(Debug, Clone, PartialEq, Eq)] @@ -71,6 +78,16 @@ pub enum PlanRefusal { NoTruths, /// The plan serves `story`, which is not committed to the phase. StoryNotInPhase { story: u32 }, + /// The item at `position`, whose id is `id`, names no current truth of + /// a story the plan serves. + EvidenceItemTruth { position: usize, id: String }, + /// The item at `position`, whose id is `id`, names its truth at a + /// version other than `current`, the truth's current version. + TruthVersionMismatch { + position: usize, + id: String, + current: u32, + }, } impl PlanRefusal { @@ -86,6 +103,8 @@ impl PlanRefusal { Self::CheckBoundary { .. } => CHECK_BOUNDARY, Self::NoTruths => NO_TRUTHS, Self::StoryNotInPhase { .. } => STORY_NOT_IN_PHASE, + Self::EvidenceItemTruth { .. } => EVIDENCE_ITEM_TRUTH, + Self::TruthVersionMismatch { .. } => TRUTH_VERSION_MISMATCH, } } @@ -249,13 +268,15 @@ impl Plan { /// fixed order, the first fault answering: (1) the plan's own members; /// (2) the `questions` member through `judge_set`; (3) `lease`, task by /// task and file by file; (4) the blank check fields, item by item; -/// (5) `no-truths`; (6) `story-not-in-phase`, in the plan's story order. +/// (5) `no-truths`; (6) `story-not-in-phase`, in the plan's story order; +/// (7) `evidence-item-truth` and `truth-version-mismatch`, item by item. pub fn judge_plan(plan: &Value, facts: &PlanFacts) -> Result { let plan = content::read(plan)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; evidence::blank_fields(&plan.evidence_map)?; stories::holds_truths(facts)?; stories::committed(&plan.stories, facts)?; + binding::bind(&plan.stories, &plan.evidence_map, facts)?; Ok(plan) } diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index cceeb452..21ce241f 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -6,6 +6,7 @@ //! Nothing here reads a store, a file or a clock: the binary supplies every //! value it judges. +mod binding; mod content; mod evidence; #[cfg(test)] @@ -20,8 +21,8 @@ pub use evidence::{ }; pub use judge::{ ApprovedItem, CHECK_BOUNDARY, CHECK_COMMAND, CHECK_EXPECTED, CHECK_TEST_FILE, CommittedStory, - CurrentTruth, EvidenceKind, LEASE, NO_TRUTHS, Plan, PlanFacts, PlanRefusal, STORY_NOT_IN_PHASE, - TYPED_CONTENT, judge_plan, + CurrentTruth, EVIDENCE_ITEM_TRUTH, EvidenceKind, LEASE, NO_TRUTHS, Plan, PlanFacts, + PlanRefusal, STORY_NOT_IN_PHASE, TRUTH_VERSION_MISMATCH, TYPED_CONTENT, judge_plan, }; pub use lease::{inside_lease, plain_relative_path}; pub use task::Task; From ff0c0a1fc9fc3bab638afac9ff771f4ff0e181ec Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 19:02:13 -0400 Subject: [PATCH 10/26] feat(8-2): refuse a link whose value its truth does not name A link's value must be a delimited token of one slot of its truth, so a value inside a word, across two slots or blank names nothing; step (9) refuses it as link-value-not-named. --- crates/baley-core/src/plan/judge.rs | 19 ++++-- crates/baley-core/src/plan/link.rs | 99 +++++++++++++++++++++++++++++ crates/baley-core/src/plan/mod.rs | 5 +- 3 files changed, 116 insertions(+), 7 deletions(-) create mode 100644 crates/baley-core/src/plan/link.rs diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index 217762fd..9e399517 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -9,8 +9,9 @@ //! judge; (3) each task file inside the lease; (4) no check field with a //! code blank; (5) a committed story holding a truth; (6) every story the //! plan serves committed to the phase; (7) each evidence item bound to its -//! own story's current truth. The judge trusts the facts and judges the -//! plan. Nothing here records anything. +//! own story's current truth; (9) each link's value named by its truth. +//! The judge trusts the facts and judges the plan. Nothing here records +//! anything. use std::num::NonZeroU32; @@ -18,7 +19,7 @@ use serde_json::Value; use super::evidence::{self, EvidenceItem}; use super::task::{self, Task}; -use super::{binding, content, stories}; +use super::{binding, content, link, stories}; use crate::questions::{QuestionSet, SetRefusal}; /// The refusal code for a plan out of its grammar: not an object, or a @@ -47,6 +48,8 @@ pub const EVIDENCE_ITEM_TRUTH: &str = "evidence-item-truth"; /// The refusal code for an evidence item naming its truth at a version /// other than the current one. pub const TRUTH_VERSION_MISMATCH: &str = "truth-version-mismatch"; +/// The refusal code for a link whose value its truth does not name. +pub const LINK_VALUE_NOT_NAMED: &str = "link-value-not-named"; /// Why a plan is refused. Positions count from 0 in the list as submitted. #[derive(Debug, Clone, PartialEq, Eq)] @@ -88,6 +91,9 @@ pub enum PlanRefusal { id: String, current: u32, }, + /// The link at `position`, whose id is `id`, carries a value its truth + /// does not name. + LinkValueNotNamed { position: usize, id: String }, } impl PlanRefusal { @@ -105,6 +111,7 @@ impl PlanRefusal { Self::StoryNotInPhase { .. } => STORY_NOT_IN_PHASE, Self::EvidenceItemTruth { .. } => EVIDENCE_ITEM_TRUTH, Self::TruthVersionMismatch { .. } => TRUTH_VERSION_MISMATCH, + Self::LinkValueNotNamed { .. } => LINK_VALUE_NOT_NAMED, } } @@ -269,14 +276,16 @@ impl Plan { /// (2) the `questions` member through `judge_set`; (3) `lease`, task by /// task and file by file; (4) the blank check fields, item by item; /// (5) `no-truths`; (6) `story-not-in-phase`, in the plan's story order; -/// (7) `evidence-item-truth` and `truth-version-mismatch`, item by item. +/// (7) `evidence-item-truth` and `truth-version-mismatch`, item by item; +/// (9) `link-value-not-named`, link by link. pub fn judge_plan(plan: &Value, facts: &PlanFacts) -> Result { let plan = content::read(plan)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; evidence::blank_fields(&plan.evidence_map)?; stories::holds_truths(facts)?; stories::committed(&plan.stories, facts)?; - binding::bind(&plan.stories, &plan.evidence_map, facts)?; + let truths = binding::bind(&plan.stories, &plan.evidence_map, facts)?; + link::named(&plan.evidence_map, &truths)?; Ok(plan) } diff --git a/crates/baley-core/src/plan/link.rs b/crates/baley-core/src/plan/link.rs new file mode 100644 index 00000000..ce5cb36b --- /dev/null +++ b/crates/baley-core/src/plan/link.rs @@ -0,0 +1,99 @@ +//! Step (9) of the plan judge: a link's value named by its truth (PLN-R12, +//! D-13). The rule matches the parked `names` in +//! `crates/baley/src/plan/limits.rs`, written anew here; the parked one +//! goes with the rest of that engine in Build 9. + +use super::evidence::{EvidenceItem, Spec}; +use super::judge::{CurrentTruth, PlanRefusal}; + +/// Step (9), each link in submitted order: its value, trimmed at both +/// ends, must be named by its bound truth's trigger, observer or outcome, +/// each slot on its own. The first link no slot names is refused +/// `link-value-not-named`. `truths` holds each item's bound truth, in the +/// plan's item order. +pub(super) fn named(items: &[EvidenceItem], truths: &[&CurrentTruth]) -> Result<(), PlanRefusal> { + for (position, (item, truth)) in items.iter().zip(truths).enumerate() { + let Spec::Link(link) = &item.spec else { + continue; + }; + let value = link.value.trim(); + if ![&truth.trigger, &truth.observer, &truth.outcome] + .iter() + .any(|slot| names(slot, value)) + { + return Err(PlanRefusal::LinkValueNotNamed { + position, + id: item.id.clone(), + }); + } + } + Ok(()) +} + +/// Whether `slot` holds `value` as a delimited token: where the value +/// begins with a word character (a letter, a digit or `_`), none precedes +/// it, and where it ends with one, none follows it. Every occurrence is +/// tried, so a word holding the value does not hide a later delimited +/// one. An empty value is named nowhere. +fn names(slot: &str, value: &str) -> bool { + let word = |c: char| c.is_alphanumeric() || c == '_'; + let (Some(first), Some(last)) = (value.chars().next(), value.chars().next_back()) else { + return false; + }; + slot.char_indices().any(|(at, _)| { + let end = at + value.len(); + slot[at..].starts_with(value) + && !(word(first) && slot[..at].chars().next_back().is_some_and(word)) + && !(word(last) && slot[end..].chars().next().is_some_and(word)) + }) +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use serde_json::json; + + use crate::plan::PlanRefusal; + use crate::plan::fixtures::{accepted, f1, l1, p1, plus, refusal, with}; + + fn linked(value: &str) -> serde_json::Value { + plus(p1(), with(l1(), "/spec", "value", json!(value))) + } + + fn unnamed() -> PlanRefusal { + PlanRefusal::LinkValueNotNamed { + position: 3, + id: "l1".into(), + } + } + + #[test] + fn a_link_value_inside_a_word_across_slots_or_blank_accepted_is_caught() { + let facts = f1(); + for value in ["lea", "session lease", " ", "plans"] { + assert_eq!(refusal(&linked(value), &facts), unnamed(), "{value:?}"); + } + for value in [ + "plan", + " lease ", + "a valid refusal", + "refusal", + "the session", + ] { + accepted(&linked(value), &facts); + } + let mut suffixed = f1(); + suffixed.stories[0].truths[0].outcome = "the id_suffix".into(); + assert_eq!(refusal(&linked("id"), &suffixed), unnamed()); + assert_eq!(unnamed().code(), "link-value-not-named"); + } + + #[test] + fn a_later_delimited_occurrence_hidden_by_an_embedded_one_is_caught() { + let mut facts = f1(); + facts.stories[0].truths[0].outcome = "a valid id".into(); + accepted(&linked("id"), &facts); + } +} diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index 21ce241f..bcc1d883 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -13,6 +13,7 @@ mod evidence; mod fixtures; mod judge; mod lease; +mod link; mod stories; mod task; @@ -21,8 +22,8 @@ pub use evidence::{ }; pub use judge::{ ApprovedItem, CHECK_BOUNDARY, CHECK_COMMAND, CHECK_EXPECTED, CHECK_TEST_FILE, CommittedStory, - CurrentTruth, EVIDENCE_ITEM_TRUTH, EvidenceKind, LEASE, NO_TRUTHS, Plan, PlanFacts, - PlanRefusal, STORY_NOT_IN_PHASE, TRUTH_VERSION_MISMATCH, TYPED_CONTENT, judge_plan, + CurrentTruth, EVIDENCE_ITEM_TRUTH, EvidenceKind, LEASE, LINK_VALUE_NOT_NAMED, NO_TRUTHS, Plan, + PlanFacts, PlanRefusal, STORY_NOT_IN_PHASE, TRUTH_VERSION_MISMATCH, TYPED_CONTENT, judge_plan, }; pub use lease::{inside_lease, plain_relative_path}; pub use task::Task; From f2449eed68291a29c06dfc4fb124996209791460 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 19:03:18 -0400 Subject: [PATCH 11/26] feat(8-2): refuse an item id an approved plan holds with another definition Coverage is judged over the phase's plans together, so one item id must mean one item across them; step (8) compares the whole item and names the approved plan that differs. --- crates/baley-core/src/plan/coverage.rs | 90 ++++++++++++++++++++++++++ crates/baley-core/src/plan/judge.rs | 31 +++++++-- crates/baley-core/src/plan/mod.rs | 6 +- 3 files changed, 118 insertions(+), 9 deletions(-) create mode 100644 crates/baley-core/src/plan/coverage.rs diff --git a/crates/baley-core/src/plan/coverage.rs b/crates/baley-core/src/plan/coverage.rs new file mode 100644 index 00000000..0cf2f28f --- /dev/null +++ b/crates/baley-core/src/plan/coverage.rs @@ -0,0 +1,90 @@ +//! The evidence map judged over the phase as it would stand with the plan +//! approved (PLN-R12, PLN-R13, D-06): this plan's items beside the items of +//! the phase's approved plans. + +use serde_json::Value; + +use super::evidence::EvidenceItem; +use super::judge::{ApprovedItem, PlanRefusal}; + +/// Step (8), item by item in submitted order: the first approved item, in +/// the facts' order, with the item's id and another definition refuses it +/// `evidence-item-conflict`. A definition is the whole item, compared as a +/// JSON value, so an approved item equal to it is the same item. Approved +/// items that differ only from each other were judged at their approval +/// and are not judged again. `submitted` holds the items as submitted, in +/// the order of `items`. +pub(super) fn consistent( + submitted: &[Value], + items: &[EvidenceItem], + approved: &[ApprovedItem], +) -> Result<(), PlanRefusal> { + for (position, (definition, item)) in submitted.iter().zip(items).enumerate() { + if let Some(other) = approved + .iter() + .find(|other| other.id == item.id && other.definition != *definition) + { + return Err(PlanRefusal::EvidenceItemConflict { + position, + id: item.id.clone(), + plan: other.plan, + }); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use serde_json::json; + + use crate::plan::PlanRefusal; + use crate::plan::fixtures::{approved, c1, p1, refusal, under, with}; + + fn conflict(plan: u32) -> PlanRefusal { + PlanRefusal::EvidenceItemConflict { + position: 0, + id: "c1".into(), + plan, + } + } + + #[test] + fn an_item_id_reused_with_another_definition_accepted_is_caught() { + let cases = [ + ( + vec![approved( + 1, + with(c1(), "/spec", "level", json!("integration")), + )], + conflict(1), + ), + ( + vec![ + approved(2, c1()), + approved(3, with(c1(), "", "reason", json!("another reason"))), + ], + conflict(3), + ), + ( + vec![approved( + 1, + with( + with(c1(), "", "story", json!(2)), + "", + "truth_version", + json!(3), + ), + )], + conflict(1), + ), + ]; + for (items, refused) in cases { + assert_eq!(refusal(&p1(), &under(items)), refused); + } + assert_eq!(conflict(1).code(), "evidence-item-conflict"); + } +} diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index 9e399517..b81f815b 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -9,9 +9,9 @@ //! judge; (3) each task file inside the lease; (4) no check field with a //! code blank; (5) a committed story holding a truth; (6) every story the //! plan serves committed to the phase; (7) each evidence item bound to its -//! own story's current truth; (9) each link's value named by its truth. -//! The judge trusts the facts and judges the plan. Nothing here records -//! anything. +//! own story's current truth; (8) each item id holding one definition +//! across the phase; (9) each link's value named by its truth. The judge +//! trusts the facts and judges the plan. Nothing here records anything. use std::num::NonZeroU32; @@ -19,7 +19,7 @@ use serde_json::Value; use super::evidence::{self, EvidenceItem}; use super::task::{self, Task}; -use super::{binding, content, link, stories}; +use super::{binding, content, coverage, link, stories}; use crate::questions::{QuestionSet, SetRefusal}; /// The refusal code for a plan out of its grammar: not an object, or a @@ -48,6 +48,9 @@ pub const EVIDENCE_ITEM_TRUTH: &str = "evidence-item-truth"; /// The refusal code for an evidence item naming its truth at a version /// other than the current one. pub const TRUTH_VERSION_MISMATCH: &str = "truth-version-mismatch"; +/// The refusal code for an evidence item whose id an approved plan of the +/// phase holds with another definition. +pub const EVIDENCE_ITEM_CONFLICT: &str = "evidence-item-conflict"; /// The refusal code for a link whose value its truth does not name. pub const LINK_VALUE_NOT_NAMED: &str = "link-value-not-named"; @@ -91,6 +94,13 @@ pub enum PlanRefusal { id: String, current: u32, }, + /// The item at `position`, whose id is `id`, differs from the item of + /// approved plan `plan` that holds the same id. + EvidenceItemConflict { + position: usize, + id: String, + plan: u32, + }, /// The link at `position`, whose id is `id`, carries a value its truth /// does not name. LinkValueNotNamed { position: usize, id: String }, @@ -111,6 +121,7 @@ impl PlanRefusal { Self::StoryNotInPhase { .. } => STORY_NOT_IN_PHASE, Self::EvidenceItemTruth { .. } => EVIDENCE_ITEM_TRUTH, Self::TruthVersionMismatch { .. } => TRUTH_VERSION_MISMATCH, + Self::EvidenceItemConflict { .. } => EVIDENCE_ITEM_CONFLICT, Self::LinkValueNotNamed { .. } => LINK_VALUE_NOT_NAMED, } } @@ -271,20 +282,26 @@ impl Plan { } } -/// Judges the submitted plan `plan` against the phase's `facts` in the +/// Judges the submitted plan `submitted` against the phase's `facts` in the /// fixed order, the first fault answering: (1) the plan's own members; /// (2) the `questions` member through `judge_set`; (3) `lease`, task by /// task and file by file; (4) the blank check fields, item by item; /// (5) `no-truths`; (6) `story-not-in-phase`, in the plan's story order; /// (7) `evidence-item-truth` and `truth-version-mismatch`, item by item; +/// (8) `evidence-item-conflict`, item by item; /// (9) `link-value-not-named`, link by link. -pub fn judge_plan(plan: &Value, facts: &PlanFacts) -> Result { - let plan = content::read(plan)?; +pub fn judge_plan(submitted: &Value, facts: &PlanFacts) -> Result { + let plan = content::read(submitted)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; evidence::blank_fields(&plan.evidence_map)?; stories::holds_truths(facts)?; stories::committed(&plan.stories, facts)?; let truths = binding::bind(&plan.stories, &plan.evidence_map, facts)?; + // The member walk has read `evidence_map` as a list by now. + let definitions = submitted["evidence_map"] + .as_array() + .map_or(&[][..], Vec::as_slice); + coverage::consistent(definitions, &plan.evidence_map, &facts.approved)?; link::named(&plan.evidence_map, &truths)?; Ok(plan) } diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index bcc1d883..be574512 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -8,6 +8,7 @@ mod binding; mod content; +mod coverage; mod evidence; #[cfg(test)] mod fixtures; @@ -22,8 +23,9 @@ pub use evidence::{ }; pub use judge::{ ApprovedItem, CHECK_BOUNDARY, CHECK_COMMAND, CHECK_EXPECTED, CHECK_TEST_FILE, CommittedStory, - CurrentTruth, EVIDENCE_ITEM_TRUTH, EvidenceKind, LEASE, LINK_VALUE_NOT_NAMED, NO_TRUTHS, Plan, - PlanFacts, PlanRefusal, STORY_NOT_IN_PHASE, TRUTH_VERSION_MISMATCH, TYPED_CONTENT, judge_plan, + CurrentTruth, EVIDENCE_ITEM_CONFLICT, EVIDENCE_ITEM_TRUTH, EvidenceKind, LEASE, + LINK_VALUE_NOT_NAMED, NO_TRUTHS, Plan, PlanFacts, PlanRefusal, STORY_NOT_IN_PHASE, + TRUTH_VERSION_MISMATCH, TYPED_CONTENT, judge_plan, }; pub use lease::{inside_lease, plain_relative_path}; pub use task::Task; From 898590b312adfee644affcd47079dd0804ef815b Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 19:05:16 -0400 Subject: [PATCH 12/26] feat(8-2): refuse a served truth uncovered or without a check across the phase A plan serving a story need not prove again what an approved plan already proves, so steps (10) and (11) judge the union of the approved plans' items with this plan's, by story, truth and current version. --- crates/baley-core/src/plan/coverage.rs | 152 ++++++++++++++++++++++++- crates/baley-core/src/plan/judge.rs | 35 +++++- crates/baley-core/src/plan/mod.rs | 2 +- 3 files changed, 183 insertions(+), 6 deletions(-) diff --git a/crates/baley-core/src/plan/coverage.rs b/crates/baley-core/src/plan/coverage.rs index 0cf2f28f..4a004431 100644 --- a/crates/baley-core/src/plan/coverage.rs +++ b/crates/baley-core/src/plan/coverage.rs @@ -5,7 +5,7 @@ use serde_json::Value; use super::evidence::EvidenceItem; -use super::judge::{ApprovedItem, PlanRefusal}; +use super::judge::{ApprovedItem, CurrentTruth, EvidenceKind, PlanFacts, PlanRefusal}; /// Step (8), item by item in submitted order: the first approved item, in /// the facts' order, with the item's id and another definition refuses it @@ -34,6 +34,106 @@ pub(super) fn consistent( Ok(()) } +/// One item of the union: the truth it serves and its kind. +struct Proof<'a> { + story: u32, + truth: &'a str, + version: u32, + kind: EvidenceKind, +} + +/// The phase as it would stand with the plan approved: the truths the plan +/// serves and the union of the approved plans' items with its own. +pub(super) struct Phase<'a> { + /// The current truths of the plan's stories, in the plan's story order + /// and then each story's own order, each with its story. + served: Vec<(u32, &'a CurrentTruth)>, + /// The approved items in the facts' order, then this plan's items in + /// submitted order. + union: Vec>, +} + +impl<'a> Phase<'a> { + /// The phase for a plan serving `stories` with `items`, judged after + /// step (8). An item listed again with an equal definition is the same + /// item and stands in the union once. + pub(super) fn new(stories: &[u32], items: &'a [EvidenceItem], facts: &'a PlanFacts) -> Self { + let served = stories + .iter() + .filter_map(|id| facts.stories.iter().find(|story| story.id == *id)) + .flat_map(|story| story.truths.iter().map(|truth| (story.id, truth))) + .collect(); + let approved = facts.approved.iter().enumerate().filter(|&(n, item)| { + !facts.approved[..n] + .iter() + .any(|earlier| earlier.id == item.id && earlier.definition == item.definition) + }); + // Step (8) has refused any item whose id an approved item holds with + // another definition, so an approved id here is the same item. + let submitted = items + .iter() + .filter(|item| !facts.approved.iter().any(|other| other.id == item.id)); + let approved = approved.map(|(_, item)| Proof { + story: item.story, + truth: &item.truth, + version: item.truth_version, + kind: item.kind, + }); + let submitted = submitted.map(|item| Proof { + story: item.story, + truth: &item.truth, + version: item.truth_version, + kind: item.kind(), + }); + Self { + served, + union: approved.chain(submitted).collect(), + } + } + + /// The kinds of the union's items that name `truth` of `story` at its + /// current version. An item naming another version proves nothing here. + fn kinds(&self, story: u32, truth: &CurrentTruth) -> Vec { + self.union + .iter() + .filter(|proof| { + proof.story == story && proof.truth == truth.id && proof.version == truth.version + }) + .map(|proof| proof.kind) + .collect() + } + + /// Step (10): the first served truth no item names is refused + /// `uncovered-truth`. + pub(super) fn covered(&self) -> Result<(), PlanRefusal> { + for &(story, truth) in &self.served { + if self.kinds(story, truth).is_empty() { + return Err(PlanRefusal::UncoveredTruth { + story, + truth: truth.id.clone(), + version: truth.version, + }); + } + } + Ok(()) + } + + /// Step (11): the first served truth whose items hold no check is + /// refused `truth-without-check`. + pub(super) fn checked(&self) -> Result<(), PlanRefusal> { + for &(story, truth) in &self.served { + if !self.kinds(story, truth).contains(&EvidenceKind::Check) { + return Err(PlanRefusal::TruthWithoutCheck { + story, + truth: truth.id.clone(), + version: truth.version, + }); + } + } + Ok(()) + } +} + #[cfg(test)] mod tests { //! Expected answers are written out from design 0005, the phase's @@ -42,7 +142,9 @@ mod tests { use serde_json::json; use crate::plan::PlanRefusal; - use crate::plan::fixtures::{approved, c1, p1, refusal, under, with}; + use crate::plan::fixtures::{ + accepted, approved, ar, c1, c2, dropping, f1, f3, p1, p2, refusal, replacing, under, with, + }; fn conflict(plan: u32) -> PlanRefusal { PlanRefusal::EvidenceItemConflict { @@ -87,4 +189,50 @@ mod tests { } assert_eq!(conflict(1).code(), "evidence-item-conflict"); } + + fn uncovered(story: u32, truth: &str, version: u32) -> PlanRefusal { + PlanRefusal::UncoveredTruth { + story, + truth: truth.into(), + version, + } + } + + #[test] + fn a_truth_covered_by_another_storys_item_or_an_old_version_is_caught() { + assert_eq!( + refusal(&dropping(p2(), &["c4"]), &f1()), + uncovered(2, "t1", 3) + ); + let mut moved = under(vec![approved(1, c1())]); + moved.stories[0].truths[0].version = 2; + assert_eq!( + refusal(&dropping(p1(), &["c1"]), &moved), + uncovered(1, "t1", 2) + ); + assert_eq!( + refusal(&dropping(p2(), &["c4"]), &f3()), + uncovered(2, "t1", 1) + ); + assert_eq!(uncovered(2, "t1", 3).code(), "uncovered-truth"); + } + + #[test] + fn a_check_in_an_approved_plan_ignored_is_caught() { + accepted(&dropping(p1(), &["c2"]), &under(vec![approved(1, c2())])); + } + + #[test] + fn an_artifact_taken_for_a_check_is_caught() { + let refused = refusal(&replacing(p1(), "c1", ar()), &f1()); + assert_eq!( + refused, + PlanRefusal::TruthWithoutCheck { + story: 1, + truth: "t1".into(), + version: 1, + } + ); + assert_eq!(refused.code(), "truth-without-check"); + } } diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index b81f815b..5ecb99ad 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -10,8 +10,10 @@ //! code blank; (5) a committed story holding a truth; (6) every story the //! plan serves committed to the phase; (7) each evidence item bound to its //! own story's current truth; (8) each item id holding one definition -//! across the phase; (9) each link's value named by its truth. The judge -//! trusts the facts and judges the plan. Nothing here records anything. +//! across the phase; (9) each link's value named by its truth; (10) every +//! truth the plan serves named by an item of the phase; (11) each such +//! truth holding a check. The judge trusts the facts and judges the plan. +//! Nothing here records anything. use std::num::NonZeroU32; @@ -53,6 +55,12 @@ pub const TRUTH_VERSION_MISMATCH: &str = "truth-version-mismatch"; pub const EVIDENCE_ITEM_CONFLICT: &str = "evidence-item-conflict"; /// The refusal code for a link whose value its truth does not name. pub const LINK_VALUE_NOT_NAMED: &str = "link-value-not-named"; +/// The refusal code for a truth the plan serves that no evidence item of +/// the phase names. +pub const UNCOVERED_TRUTH: &str = "uncovered-truth"; +/// The refusal code for a truth the plan serves whose evidence items across +/// the phase hold no check. +pub const TRUTH_WITHOUT_CHECK: &str = "truth-without-check"; /// Why a plan is refused. Positions count from 0 in the list as submitted. #[derive(Debug, Clone, PartialEq, Eq)] @@ -104,6 +112,20 @@ pub enum PlanRefusal { /// The link at `position`, whose id is `id`, carries a value its truth /// does not name. LinkValueNotNamed { position: usize, id: String }, + /// No item of the phase names `truth` of `story` at `version`, its + /// current version. + UncoveredTruth { + story: u32, + truth: String, + version: u32, + }, + /// The items of the phase naming `truth` of `story` at `version`, its + /// current version, hold no check. + TruthWithoutCheck { + story: u32, + truth: String, + version: u32, + }, } impl PlanRefusal { @@ -123,6 +145,8 @@ impl PlanRefusal { Self::TruthVersionMismatch { .. } => TRUTH_VERSION_MISMATCH, Self::EvidenceItemConflict { .. } => EVIDENCE_ITEM_CONFLICT, Self::LinkValueNotNamed { .. } => LINK_VALUE_NOT_NAMED, + Self::UncoveredTruth { .. } => UNCOVERED_TRUTH, + Self::TruthWithoutCheck { .. } => TRUTH_WITHOUT_CHECK, } } @@ -289,7 +313,9 @@ impl Plan { /// (5) `no-truths`; (6) `story-not-in-phase`, in the plan's story order; /// (7) `evidence-item-truth` and `truth-version-mismatch`, item by item; /// (8) `evidence-item-conflict`, item by item; -/// (9) `link-value-not-named`, link by link. +/// (9) `link-value-not-named`, link by link; then over the served truths +/// in order, with the approved plans' items, (10) `uncovered-truth` and +/// (11) `truth-without-check`. pub fn judge_plan(submitted: &Value, facts: &PlanFacts) -> Result { let plan = content::read(submitted)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; @@ -303,6 +329,9 @@ pub fn judge_plan(submitted: &Value, facts: &PlanFacts) -> Result Date: Fri, 23 Oct 2026 19:06:12 -0400 Subject: [PATCH 13/26] feat(8-2): refuse a truth a person must prove with no observation A truth with human_verify cannot be proven by mocked checks alone, so step (12) asks the phase's items for an observation of its current version, after step (11) has asked for its one check. --- crates/baley-core/src/plan/coverage.rs | 48 +++++++++++++++++++++++++- crates/baley-core/src/plan/judge.rs | 23 +++++++++--- crates/baley-core/src/plan/mod.rs | 3 +- 3 files changed, 68 insertions(+), 6 deletions(-) diff --git a/crates/baley-core/src/plan/coverage.rs b/crates/baley-core/src/plan/coverage.rs index 4a004431..4d513fa2 100644 --- a/crates/baley-core/src/plan/coverage.rs +++ b/crates/baley-core/src/plan/coverage.rs @@ -132,6 +132,27 @@ impl<'a> Phase<'a> { } Ok(()) } + + /// Step (12): the first served truth a person must prove + /// (`human_verify`) whose items hold no observation is refused + /// `truth-without-observation` (D-04). Step (11) has already asked it + /// for its one check. + pub(super) fn observed(&self) -> Result<(), PlanRefusal> { + for &(story, truth) in &self.served { + if truth.human_verify.is_some() + && !self + .kinds(story, truth) + .contains(&EvidenceKind::Observation) + { + return Err(PlanRefusal::TruthWithoutObservation { + story, + truth: truth.id.clone(), + version: truth.version, + }); + } + } + Ok(()) + } } #[cfg(test)] @@ -143,7 +164,8 @@ mod tests { use crate::plan::PlanRefusal; use crate::plan::fixtures::{ - accepted, approved, ar, c1, c2, dropping, f1, f3, p1, p2, refusal, replacing, under, with, + accepted, approved, ar, c1, c2, dropping, f1, f3, o1, p1, p2, refusal, replacing, under, + with, }; fn conflict(plan: u32) -> PlanRefusal { @@ -235,4 +257,28 @@ mod tests { ); assert_eq!(refused.code(), "truth-without-check"); } + + #[test] + fn an_observation_for_another_truth_or_in_an_approved_plan_judged_wrongly_is_caught() { + let unobserved = PlanRefusal::TruthWithoutObservation { + story: 1, + truth: "t2".into(), + version: 2, + }; + let elsewhere = with( + with(p1(), "/evidence_map/2", "truth", json!("t1")), + "/evidence_map/2", + "truth_version", + json!(1), + ); + assert_eq!(refusal(&elsewhere, &f1()), unobserved); + let unlisted = dropping(p1(), &["o1"]); + accepted(&unlisted, &under(vec![approved(1, o1())])); + let stale = with(o1(), "", "truth_version", json!(1)); + assert_eq!( + refusal(&unlisted, &under(vec![approved(1, stale)])), + unobserved + ); + assert_eq!(unobserved.code(), "truth-without-observation"); + } } diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index 5ecb99ad..c2729000 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -12,8 +12,9 @@ //! own story's current truth; (8) each item id holding one definition //! across the phase; (9) each link's value named by its truth; (10) every //! truth the plan serves named by an item of the phase; (11) each such -//! truth holding a check. The judge trusts the facts and judges the plan. -//! Nothing here records anything. +//! truth holding a check; (12) each such truth a person must prove holding +//! an observation. The judge trusts the facts and judges the plan. Nothing +//! here records anything. use std::num::NonZeroU32; @@ -61,6 +62,10 @@ pub const UNCOVERED_TRUTH: &str = "uncovered-truth"; /// The refusal code for a truth the plan serves whose evidence items across /// the phase hold no check. pub const TRUTH_WITHOUT_CHECK: &str = "truth-without-check"; +/// The refusal code for a truth the plan serves that a person must prove +/// live (`human_verify`) and whose evidence items across the phase hold no +/// observation (D-04). Its one check is still required. +pub const TRUTH_WITHOUT_OBSERVATION: &str = "truth-without-observation"; /// Why a plan is refused. Positions count from 0 in the list as submitted. #[derive(Debug, Clone, PartialEq, Eq)] @@ -126,6 +131,14 @@ pub enum PlanRefusal { truth: String, version: u32, }, + /// `truth` of `story` at `version`, its current version, needs a person + /// to prove it, and the items of the phase naming it hold no + /// observation. + TruthWithoutObservation { + story: u32, + truth: String, + version: u32, + }, } impl PlanRefusal { @@ -147,6 +160,7 @@ impl PlanRefusal { Self::LinkValueNotNamed { .. } => LINK_VALUE_NOT_NAMED, Self::UncoveredTruth { .. } => UNCOVERED_TRUTH, Self::TruthWithoutCheck { .. } => TRUTH_WITHOUT_CHECK, + Self::TruthWithoutObservation { .. } => TRUTH_WITHOUT_OBSERVATION, } } @@ -314,8 +328,8 @@ impl Plan { /// (7) `evidence-item-truth` and `truth-version-mismatch`, item by item; /// (8) `evidence-item-conflict`, item by item; /// (9) `link-value-not-named`, link by link; then over the served truths -/// in order, with the approved plans' items, (10) `uncovered-truth` and -/// (11) `truth-without-check`. +/// in order, with the approved plans' items, (10) `uncovered-truth`, +/// (11) `truth-without-check` and (12) `truth-without-observation`. pub fn judge_plan(submitted: &Value, facts: &PlanFacts) -> Result { let plan = content::read(submitted)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; @@ -332,6 +346,7 @@ pub fn judge_plan(submitted: &Value, facts: &PlanFacts) -> Result Date: Fri, 23 Oct 2026 19:08:03 -0400 Subject: [PATCH 14/26] feat(8-2): refuse a second check for one story, truth and version Exactly one check proves a truth version across the phase, so step (13) counts distinct check ids over the approved plans' items and this plan's, an id listed again unchanged counted once, and names every one found. --- crates/baley-core/src/plan/coverage.rs | 91 ++++++++++++++--- crates/baley-core/src/plan/judge.rs | 132 ++++++++++++++++++++++++- crates/baley-core/src/plan/mod.rs | 4 +- 3 files changed, 208 insertions(+), 19 deletions(-) diff --git a/crates/baley-core/src/plan/coverage.rs b/crates/baley-core/src/plan/coverage.rs index 4d513fa2..75618e28 100644 --- a/crates/baley-core/src/plan/coverage.rs +++ b/crates/baley-core/src/plan/coverage.rs @@ -34,8 +34,9 @@ pub(super) fn consistent( Ok(()) } -/// One item of the union: the truth it serves and its kind. +/// One item of the union: its id, the truth it serves and its kind. struct Proof<'a> { + id: &'a str, story: u32, truth: &'a str, version: u32, @@ -74,12 +75,14 @@ impl<'a> Phase<'a> { .iter() .filter(|item| !facts.approved.iter().any(|other| other.id == item.id)); let approved = approved.map(|(_, item)| Proof { + id: &item.id, story: item.story, truth: &item.truth, version: item.truth_version, kind: item.kind, }); let submitted = submitted.map(|item| Proof { + id: &item.id, story: item.story, truth: &item.truth, version: item.truth_version, @@ -91,23 +94,31 @@ impl<'a> Phase<'a> { } } - /// The kinds of the union's items that name `truth` of `story` at its - /// current version. An item naming another version proves nothing here. - fn kinds(&self, story: u32, truth: &CurrentTruth) -> Vec { + /// The union's items that name `truth` of `story` at its current + /// version, in union order. An item naming another version proves + /// nothing here. + fn naming(&self, story: u32, truth: &CurrentTruth) -> Vec<&Proof<'a>> { self.union .iter() .filter(|proof| { proof.story == story && proof.truth == truth.id && proof.version == truth.version }) - .map(|proof| proof.kind) .collect() } + /// Whether an item naming `truth` of `story` at its current version is + /// of `kind`. + fn holds(&self, story: u32, truth: &CurrentTruth, kind: EvidenceKind) -> bool { + self.naming(story, truth) + .iter() + .any(|proof| proof.kind == kind) + } + /// Step (10): the first served truth no item names is refused /// `uncovered-truth`. pub(super) fn covered(&self) -> Result<(), PlanRefusal> { for &(story, truth) in &self.served { - if self.kinds(story, truth).is_empty() { + if self.naming(story, truth).is_empty() { return Err(PlanRefusal::UncoveredTruth { story, truth: truth.id.clone(), @@ -122,7 +133,7 @@ impl<'a> Phase<'a> { /// refused `truth-without-check`. pub(super) fn checked(&self) -> Result<(), PlanRefusal> { for &(story, truth) in &self.served { - if !self.kinds(story, truth).contains(&EvidenceKind::Check) { + if !self.holds(story, truth, EvidenceKind::Check) { return Err(PlanRefusal::TruthWithoutCheck { story, truth: truth.id.clone(), @@ -139,10 +150,7 @@ impl<'a> Phase<'a> { /// for its one check. pub(super) fn observed(&self) -> Result<(), PlanRefusal> { for &(story, truth) in &self.served { - if truth.human_verify.is_some() - && !self - .kinds(story, truth) - .contains(&EvidenceKind::Observation) + if truth.human_verify.is_some() && !self.holds(story, truth, EvidenceKind::Observation) { return Err(PlanRefusal::TruthWithoutObservation { story, @@ -153,6 +161,29 @@ impl<'a> Phase<'a> { } Ok(()) } + + /// Step (13): the first served truth whose items hold more than one + /// distinct check id is refused `truth-check-limit`, naming every one + /// in union order. An id counts once however many plans list it. + pub(super) fn limited(&self) -> Result<(), PlanRefusal> { + for &(story, truth) in &self.served { + let mut checks: Vec = Vec::new(); + for proof in self.naming(story, truth) { + if proof.kind == EvidenceKind::Check && !checks.iter().any(|id| id == proof.id) { + checks.push(proof.id.to_owned()); + } + } + if checks.len() > 1 { + return Err(PlanRefusal::TruthCheckLimit { + story, + truth: truth.id.clone(), + version: truth.version, + checks, + }); + } + } + Ok(()) + } } #[cfg(test)] @@ -164,8 +195,8 @@ mod tests { use crate::plan::PlanRefusal; use crate::plan::fixtures::{ - accepted, approved, ar, c1, c2, dropping, f1, f3, o1, p1, p2, refusal, replacing, under, - with, + accepted, approved, ar, c1, c2, c3, c5, c6, dropping, f1, f3, o1, p1, p2, plus, refusal, + replacing, under, with, }; fn conflict(plan: u32) -> PlanRefusal { @@ -281,4 +312,38 @@ mod tests { ); assert_eq!(unobserved.code(), "truth-without-observation"); } + + fn limit(checks: &[&str]) -> PlanRefusal { + PlanRefusal::TruthCheckLimit { + story: 1, + truth: "t1".into(), + version: 1, + checks: checks.iter().map(|&id| id.to_owned()).collect(), + } + } + + #[test] + fn a_second_check_in_an_approved_plan_missed_or_a_listed_again_check_counted_twice_is_caught() { + assert_eq!( + refusal(&p1(), &under(vec![approved(1, c3())])), + limit(&["c3", "c1"]) + ); + accepted(&p1(), &under(vec![approved(1, c1()), approved(2, c1())])); + assert_eq!( + refusal(&plus(p1(), c6()), &under(vec![approved(1, c3())])), + limit(&["c3", "c1", "c6"]) + ); + assert_eq!(limit(&["c3", "c1"]).code(), "truth-check-limit"); + } + + #[test] + fn a_check_of_an_older_version_counted_against_the_current_is_caught() { + let mut moved = under(vec![approved(1, c3())]); + moved.stories[0].truths[0].version = 2; + accepted( + &with(p1(), "/evidence_map/0", "truth_version", json!(2)), + &moved, + ); + accepted(&replacing(p2(), "c4", c5()), &f3()); + } } diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index c2729000..849c2d6b 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -13,8 +13,9 @@ //! across the phase; (9) each link's value named by its truth; (10) every //! truth the plan serves named by an item of the phase; (11) each such //! truth holding a check; (12) each such truth a person must prove holding -//! an observation. The judge trusts the facts and judges the plan. Nothing -//! here records anything. +//! an observation; (13) each such truth holding one check at most. The +//! judge trusts the facts and judges the plan. Nothing here records +//! anything. use std::num::NonZeroU32; @@ -66,6 +67,9 @@ pub const TRUTH_WITHOUT_CHECK: &str = "truth-without-check"; /// live (`human_verify`) and whose evidence items across the phase hold no /// observation (D-04). Its one check is still required. pub const TRUTH_WITHOUT_OBSERVATION: &str = "truth-without-observation"; +/// The refusal code for a truth the plan serves whose evidence items across +/// the phase hold more than one distinct check for its current version. +pub const TRUTH_CHECK_LIMIT: &str = "truth-check-limit"; /// Why a plan is refused. Positions count from 0 in the list as submitted. #[derive(Debug, Clone, PartialEq, Eq)] @@ -139,6 +143,15 @@ pub enum PlanRefusal { truth: String, version: u32, }, + /// The items of the phase naming `truth` of `story` at `version`, its + /// current version, hold the distinct checks `checks`, more than one, + /// in the order the approved plans and then this plan list them. + TruthCheckLimit { + story: u32, + truth: String, + version: u32, + checks: Vec, + }, } impl PlanRefusal { @@ -161,6 +174,7 @@ impl PlanRefusal { Self::UncoveredTruth { .. } => UNCOVERED_TRUTH, Self::TruthWithoutCheck { .. } => TRUTH_WITHOUT_CHECK, Self::TruthWithoutObservation { .. } => TRUTH_WITHOUT_OBSERVATION, + Self::TruthCheckLimit { .. } => TRUTH_CHECK_LIMIT, } } @@ -329,7 +343,8 @@ impl Plan { /// (8) `evidence-item-conflict`, item by item; /// (9) `link-value-not-named`, link by link; then over the served truths /// in order, with the approved plans' items, (10) `uncovered-truth`, -/// (11) `truth-without-check` and (12) `truth-without-observation`. +/// (11) `truth-without-check`, (12) `truth-without-observation` and +/// (13) `truth-check-limit`. pub fn judge_plan(submitted: &Value, facts: &PlanFacts) -> Result { let plan = content::read(submitted)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; @@ -347,6 +362,7 @@ pub fn judge_plan(submitted: &Value, facts: &PlanFacts) -> Result (u32, String, u32) { + (story, truth.into(), version) + } + + #[test] + fn an_evidence_map_judged_per_plan_or_by_truth_id_alone_is_caught() { + let facts = f1(); + accepted(&p1(), &facts); + accepted(&p2(), &facts); + let (story, truth, version) = served(1, "t1", 1); + assert_eq!( + refusal(&dropping(p1(), &["c1"]), &facts), + PlanRefusal::UncoveredTruth { + story, + truth, + version + } + ); + accepted(&dropping(p1(), &["c1"]), &under(a2())); + let (story, truth, version) = served(1, "t2", 2); + assert_eq!( + refusal(&dropping(p1(), &["c2"]), &facts), + PlanRefusal::TruthWithoutCheck { + story, + truth, + version + } + ); + let (story, truth, version) = served(1, "t2", 2); + assert_eq!( + refusal(&dropping(p1(), &["o1"]), &facts), + PlanRefusal::TruthWithoutObservation { + story, + truth, + version + } + ); + let (story, truth, version) = served(1, "t1", 1); + assert_eq!( + refusal(&plus(p1(), c3()), &facts), + PlanRefusal::TruthCheckLimit { + story, + truth, + version, + checks: vec!["c1".into(), "c3".into()] + } + ); + accepted(&p1(), &under(a2())); + let untrue = PlanRefusal::EvidenceItemTruth { + position: 0, + id: "c1".into(), + }; + let first = "/evidence_map/0"; + assert_eq!( + refusal(&with(p1(), first, "truth", json!("t9")), &facts), + untrue + ); + assert_eq!( + refusal(&with(p1(), first, "story", json!(2)), &facts), + untrue + ); + let stale = PlanRefusal::TruthVersionMismatch { + position: 0, + id: "c1".into(), + current: 1, + }; + assert_eq!( + refusal(&with(p1(), first, "truth_version", json!(2)), &facts), + stale + ); + assert_eq!( + refusal(&with(p2(), first, "truth_version", json!(3)), &facts), + stale + ); + assert_eq!( + refusal(&p1(), &under(a1())), + PlanRefusal::EvidenceItemConflict { + position: 0, + id: "c1".into(), + plan: 1 + } + ); + accepted(&plus(p1(), l1()), &facts); + assert_eq!( + refusal( + &plus(p1(), with(l1(), "/spec", "value", json!("id"))), + &facts + ), + PlanRefusal::LinkValueNotNamed { + position: 3, + id: "l1".into() + } + ); + accepted(&replacing(p2(), "c4", c5()), &f3()); + let (story, truth, version) = served(2, "t1", 1); + assert_eq!( + refusal(&dropping(p2(), &["c4"]), &f3()), + PlanRefusal::UncoveredTruth { + story, + truth, + version + } + ); + } } diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index 2af2ecfd..7d37fe5f 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -25,8 +25,8 @@ pub use judge::{ ApprovedItem, CHECK_BOUNDARY, CHECK_COMMAND, CHECK_EXPECTED, CHECK_TEST_FILE, CommittedStory, CurrentTruth, EVIDENCE_ITEM_CONFLICT, EVIDENCE_ITEM_TRUTH, EvidenceKind, LEASE, LINK_VALUE_NOT_NAMED, NO_TRUTHS, Plan, PlanFacts, PlanRefusal, STORY_NOT_IN_PHASE, - TRUTH_VERSION_MISMATCH, TRUTH_WITHOUT_CHECK, TRUTH_WITHOUT_OBSERVATION, TYPED_CONTENT, - UNCOVERED_TRUTH, judge_plan, + TRUTH_CHECK_LIMIT, TRUTH_VERSION_MISMATCH, TRUTH_WITHOUT_CHECK, TRUTH_WITHOUT_OBSERVATION, + TYPED_CONTENT, UNCOVERED_TRUTH, judge_plan, }; pub use lease::{inside_lease, plain_relative_path}; pub use task::Task; From 939604f45366f53ce4612f03d95fc8076f562535 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 19:10:06 -0400 Subject: [PATCH 15/26] feat(8-2): refuse a plan that takes the phase over its capacity A phase's size counts each plan's tasks once, so step (14), last, adds this plan's task count to the current size in a wider integer and names every story the plan serves; the owner picks which waits. --- crates/baley-core/src/plan/capacity.rs | 66 +++++++++++++++++++ crates/baley-core/src/plan/fixtures.rs | 3 - crates/baley-core/src/plan/judge.rs | 88 ++++++++++++++++++++++++-- crates/baley-core/src/plan/mod.rs | 7 +- 4 files changed, 152 insertions(+), 12 deletions(-) create mode 100644 crates/baley-core/src/plan/capacity.rs diff --git a/crates/baley-core/src/plan/capacity.rs b/crates/baley-core/src/plan/capacity.rs new file mode 100644 index 00000000..336f5920 --- /dev/null +++ b/crates/baley-core/src/plan/capacity.rs @@ -0,0 +1,66 @@ +//! Step (14) of the plan judge, last: the phase's capacity (PLN-R9, D-02). + +use super::judge::{PlanFacts, PlanRefusal}; + +/// Step (14): with a capacity set, a plan whose `tasks` would take the +/// phase's current size above it is refused `over-capacity`, naming every +/// story it serves and the size the phase would reach. Each task counts +/// once whatever number of stories the plan serves; landing exactly on the +/// capacity is accepted, and with no capacity there is no ceiling. +pub(super) fn within(stories: &[u32], tasks: usize, facts: &PlanFacts) -> Result<(), PlanRefusal> { + let Some(capacity) = facts.capacity else { + return Ok(()); + }; + // Summed wider than the counter, so a size past u32::MAX is over any + // capacity instead of wrapping under it. + let size = u64::from(facts.size) + tasks as u64; + if size > u64::from(capacity.get()) { + return Err(PlanRefusal::OverCapacity { + stories: stories.to_vec(), + size, + }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, the phase's + //! decisions and the plan's test data, never from running this code. + + use crate::plan::PlanRefusal; + use crate::plan::fixtures::{accepted, at, f1, p1, p2, p4, refusal}; + + fn over(stories: &[u32], size: u64) -> PlanRefusal { + PlanRefusal::OverCapacity { + stories: stories.to_vec(), + size, + } + } + + #[test] + fn a_plan_over_capacity_accepted_or_counted_per_story_is_caught() { + accepted(&p1(), &at(3, 2)); + assert_eq!(refusal(&p1(), &at(3, 3)), over(&[1], 4)); + accepted(&p2(), &at(2, 1)); + assert_eq!(refusal(&p2(), &at(2, 2)), over(&[1, 2], 3)); + let mut unbounded = f1(); + unbounded.size = 4_000_000_000; + accepted(&p1(), &unbounded); + accepted(&p4(), &at(4, 2)); + assert_eq!(refusal(&p4(), &at(4, 3)), over(&[1], 5)); + assert_eq!(over(&[1], 4).code(), "over-capacity"); + } + + #[test] + fn a_size_that_wraps_past_the_counter_is_caught() { + assert_eq!( + refusal(&p1(), &at(u32::MAX, u32::MAX)), + over(&[1], 4_294_967_296) + ); + assert_eq!( + refusal(&p4(), &at(u32::MAX, u32::MAX - 1)), + over(&[1], 4_294_967_296) + ); + } +} diff --git a/crates/baley-core/src/plan/fixtures.rs b/crates/baley-core/src/plan/fixtures.rs index bebbdc9c..5e625352 100644 --- a/crates/baley-core/src/plan/fixtures.rs +++ b/crates/baley-core/src/plan/fixtures.rs @@ -2,9 +2,6 @@ //! decisions, never from running the judge: one copy every test of the //! module reads. -// Builders the later steps' tests read; removed once every one is read. -#![allow(dead_code)] - use std::num::NonZeroU32; use serde_json::{Value, json}; diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index 849c2d6b..5152a288 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -13,9 +13,9 @@ //! across the phase; (9) each link's value named by its truth; (10) every //! truth the plan serves named by an item of the phase; (11) each such //! truth holding a check; (12) each such truth a person must prove holding -//! an observation; (13) each such truth holding one check at most. The -//! judge trusts the facts and judges the plan. Nothing here records -//! anything. +//! an observation; (13) each such truth holding one check at most; +//! (14) the plan's tasks within the phase's capacity. The judge trusts the +//! facts and judges the plan. Nothing here records anything. use std::num::NonZeroU32; @@ -23,7 +23,7 @@ use serde_json::Value; use super::evidence::{self, EvidenceItem}; use super::task::{self, Task}; -use super::{binding, content, coverage, link, stories}; +use super::{binding, capacity, content, coverage, link, stories}; use crate::questions::{QuestionSet, SetRefusal}; /// The refusal code for a plan out of its grammar: not an object, or a @@ -70,6 +70,8 @@ pub const TRUTH_WITHOUT_OBSERVATION: &str = "truth-without-observation"; /// The refusal code for a truth the plan serves whose evidence items across /// the phase hold more than one distinct check for its current version. pub const TRUTH_CHECK_LIMIT: &str = "truth-check-limit"; +/// The refusal code for a plan that takes the phase over its capacity. +pub const OVER_CAPACITY: &str = "over-capacity"; /// Why a plan is refused. Positions count from 0 in the list as submitted. #[derive(Debug, Clone, PartialEq, Eq)] @@ -152,6 +154,10 @@ pub enum PlanRefusal { version: u32, checks: Vec, }, + /// The plan, serving `stories` in its order, would take the phase to + /// `size` tasks, over its capacity. Which story waits is the owner's + /// choice (PLN-R10). + OverCapacity { stories: Vec, size: u64 }, } impl PlanRefusal { @@ -175,6 +181,7 @@ impl PlanRefusal { Self::TruthWithoutCheck { .. } => TRUTH_WITHOUT_CHECK, Self::TruthWithoutObservation { .. } => TRUTH_WITHOUT_OBSERVATION, Self::TruthCheckLimit { .. } => TRUTH_CHECK_LIMIT, + Self::OverCapacity { .. } => OVER_CAPACITY, } } @@ -344,7 +351,7 @@ impl Plan { /// (9) `link-value-not-named`, link by link; then over the served truths /// in order, with the approved plans' items, (10) `uncovered-truth`, /// (11) `truth-without-check`, (12) `truth-without-observation` and -/// (13) `truth-check-limit`. +/// (13) `truth-check-limit`; last, (14) `over-capacity`. pub fn judge_plan(submitted: &Value, facts: &PlanFacts) -> Result { let plan = content::read(submitted)?; task::within_lease(&plan.tasks, &plan.files, &plan.directories)?; @@ -363,6 +370,7 @@ pub fn judge_plan(submitted: &Value, facts: &PlanFacts) -> Result Date: Fri, 23 Oct 2026 19:24:48 -0400 Subject: [PATCH 16/26] feat(8-3): add the default test style as its own constant The planner and the executor both receive it when a project has set no test style, so it lives in one place both can reuse. --- crates/baley/src/instruction/mod.rs | 1 + crates/baley/src/instruction/test_style.rs | 23 ++++++++++++++++++++++ crates/baley/src/instruction/tests.rs | 17 ++++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 crates/baley/src/instruction/test_style.rs diff --git a/crates/baley/src/instruction/mod.rs b/crates/baley/src/instruction/mod.rs index 1ea2986b..9995b2cf 100644 --- a/crates/baley/src/instruction/mod.rs +++ b/crates/baley/src/instruction/mod.rs @@ -21,6 +21,7 @@ pub mod read_contract; pub mod rounds; pub mod scope; pub mod start; +pub mod test_style; /// The served text of one instruction, pinned in source. #[derive(Debug, PartialEq, Eq)] diff --git a/crates/baley/src/instruction/test_style.rs b/crates/baley/src/instruction/test_style.rs new file mode 100644 index 00000000..6d2bd162 --- /dev/null +++ b/crates/baley/src/instruction/test_style.rs @@ -0,0 +1,23 @@ +//! The default test style: the guidance on how to write tests that Baley +//! hands over when the project has set no test style of its own (design 0005 +//! section 10, the Default test style row, PLN-R19). The planner receives it +//! inside `bal-phase-planner`'s text, and the executor receives it through +//! design 0006 when the project has set nothing. It is guidance only: Baley +//! never refuses a plan on style. +//! +//! No Cadence tag `v3.9.0` text carries a default test style: none of +//! `skills/`, `cadence-core/workflows/` or `cadence-core/templates/` holds +//! one. So under ADR 0048 it is written for Baley from design 0005's row, +//! and the planner text carries it as an ADR 0049 addition (PLN-R19). It +//! holds no digit and no count word, since the planner text carries it whole. + +/// The default test style's text: design 0005 section 10's Default test +/// style row, one sentence per rule, for a project that has set none. +pub const TEXT: &str = "This is the default test style, for a project that has set no test style of its own. It is guidance: Baley never refuses a plan on style. + +- Test a unit through what it exposes, never through its internals. +- Fake only the outside world, never the project's own code. +- Never start a program from a test. +- Skip trivial code: it needs no test of its own. +- Write the expected value by hand, never from the code under test. +"; diff --git a/crates/baley/src/instruction/tests.rs b/crates/baley/src/instruction/tests.rs index 7f996bca..6f47c4d8 100644 --- a/crates/baley/src/instruction/tests.rs +++ b/crates/baley/src/instruction/tests.rs @@ -707,3 +707,20 @@ fn a_context_door_keyed_by_phase_or_naming_cadence_state_is_caught() { assert!(!body.contains(name), "the context front door names {name}"); } } + +#[test] +fn a_default_test_style_missing_a_rule_of_its_design_row_is_caught() { + // The five rules of design 0005 section 10's Default test style row. + for rule in [ + "Test a unit through what it exposes", + "Fake only the outside world", + "Never start a program", + "Skip trivial code", + "Write the expected value by hand", + ] { + assert!( + test_style::TEXT.contains(rule), + "the default test style lacks {rule}" + ); + } +} From faec2a1049e2d4a5473fb2be23f0f69a72b9f921 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 19:33:05 -0400 Subject: [PATCH 17/26] feat(8-3): serve the planner text as bal-phase-planner The planner needs the plan grammar the judge holds, every refusal it can meet, section 10's test rules and the default test style, ported from Cadence with no number for it to aim at. --- crates/baley/src/instruction/mod.rs | 12 + crates/baley/src/instruction/planner.rs | 291 ++++++++++++++++++++++++ crates/baley/src/instruction/tests.rs | 241 ++++++++++++++++++++ 3 files changed, 544 insertions(+) create mode 100644 crates/baley/src/instruction/planner.rs diff --git a/crates/baley/src/instruction/mod.rs b/crates/baley/src/instruction/mod.rs index 9995b2cf..60de0b2b 100644 --- a/crates/baley/src/instruction/mod.rs +++ b/crates/baley/src/instruction/mod.rs @@ -17,6 +17,7 @@ use crate::help::front_door; pub mod analyzer; pub mod capture; pub mod context; +pub mod planner; pub mod read_contract; pub mod rounds; pub mod scope; @@ -322,6 +323,17 @@ pub static ENTRIES: &[Entry] = &[ body: analyzer::DRAFTING_TEXT, }), }, + // Build 4 serves the planner's text by identity inside a planner order, + // never as a help row. + Entry { + identity: planner::IDENTITY, + build: 4, + text: Some(Text { + version: planner::VERSION, + hash: planner::HASH, + body: planner::TEXT, + }), + }, ]; /// Looks an identity up by exact match. The identity is text compared with the diff --git a/crates/baley/src/instruction/planner.rs b/crates/baley/src/instruction/planner.rs new file mode 100644 index 00000000..bce1651b --- /dev/null +++ b/crates/baley/src/instruction/planner.rs @@ -0,0 +1,291 @@ +//! The planner's served text, pinned in source: what the planner reads once +//! it holds a planning or revision order, to turn one phase into a typed +//! plan (design 0005 sections 6 and 10, PLN-R5, PLN-R9 to PLN-R13, +//! PLN-R17 to PLN-R19, PLN-R23, PLN-R27). It is no help row, so it gets no +//! skill stub: a worker reaches it only through the order that lists it. +//! Its identity follows `bal-start-planner` and cannot be read as one of +//! the `bal-planner-` agent stubs. +//! +//! The text is ported from Cadence (ADR 0048). Besides the names of +//! Cadence's own files, commands and state, which become the order's +//! contents, the plan's members and the host's own tools, it opens with a +//! summary line in place of the skill file's front matter, which names the +//! skill and its agents to Cadence's loader; the line restates the role's +//! job and adds no rule. Cadence's `lease-check` refusal `undeclared-files` +//! becomes the `lease` refusal at submit, and Cadence's return markers +//! become the final message. +//! +//! These changes from Cadence's wording are forced by accepted Baley ADRs: +//! +//! - The plan is typed content returned as the final message, never a file +//! written (ADR 0006). The template's Goal, Context and Notes become +//! `goal`, `context` and `notes`; its front matter becomes `stories`, +//! `files` and `directories`, with every committed story served across +//! the phase's plans where Cadence's requirement ids are covered; its +//! "Must be true when done" becomes the served truths. The guardrails +//! against editing Cadence's own files and on writing plan files with the +//! host's tools become "Write no file and make no commit". The Markdown +//! evidence map and tests table of the `` block become the +//! typed `evidence_map` (D-19): the Criterion column becomes an item's +//! `story`, `truth` and `truth_version`; Command, Test file, Function and +//! Expected the check's `command`, `test` and `expected`; Unit and fakes +//! `level`, `boundary` and `fakes`; Break the item's `reason`, which a +//! check's control breaks it by; the Task column naming the check in the +//! action of the task that writes it; the human-verify row an +//! `observation`. The per-task tests table becomes "name every other test +//! in the task action", its negative-control and deviation rules kept. +//! - One typed plan per order (D-20). Cadence's several plan files, its +//! Plan shape directive and its file-independence test become further +//! plans, each from its own order, submitted on its own and numbered by +//! Baley at approval; ``'s last paragraph says so. +//! Cadence's "PHASE TOO BIG" return becomes a proposed split beginning +//! `Proposed split:` (PLN-R10), and its two other return markers become +//! the plan as the final message. +//! - Truths are mapped, never derived: they belong to the committed stories +//! and are approved before planning (ADR 0017). The goal comes from the +//! order, not from Cadence's roadmap file, and the locked decisions are +//! the approved truths and the owner's recorded answers, not Cadence's +//! context file; Cadence's deferred ideas become scope outside the +//! committed stories. +//! - Every count Cadence hands the planner is dropped (ADR 0017, PLN-R17): +//! the 3-7 truths, the skeleton by commit 2-3, the ~5 files of a task, the +//! task ceiling and the 3-10 task target, the line and sentence counts of +//! the template. Cadence's count words are reworded: the "three" fields, +//! reasons and modes, the "four" concerns, the "six" axes, the "two" +//! tasks or responsibilities and the eighty blind lines and forty-line +//! context of the grep paragraph; the prohibited phrase "v1" becomes +//! "first version" and the 401 of the login example is dropped. The +//! enumerations are bullets, never numbered lists. The capacity reaches +//! the planner only as a fact, from the order. +//! - The lease is checked at submit (`lease`) and at close, where a change +//! outside it waits for the owner's ruling (ADR 0018). A task's `files` +//! hold paths only, so the file-and-symbol anchor moves into the action. +//! - Baley runs every `verify` command (ADR 0014), so a task's Verify +//! becomes one or more commands, and a proof that needs a tool or live +//! service the run cannot reach becomes the truth's `human_verify`, +//! proven by an `observation` beside its check (D-04), never a +//! human-verify Verify. +//! - Decisions go to the owner as typed questions (ADR 0030): missing +//! information, and extra work that looks necessary, become a question in +//! `questions` where Cadence returns them to the human in its marker. +//! Cadence's revision mode becomes the revision order, carrying the draft +//! and every answer and deferral on its set (D-20). +//! - It says owner where Cadence says user, the glossary's term (ADR 0031). +//! - Cadence's own tools are dropped (ADR 0048): the excerpt tools' +//! paragraph, the `skim.mjs` paragraph and the `perl` boundary read of the +//! grep paragraph; the planner reads and searches with the host's own +//! Read, Grep and Glob tools. +//! +//! These parts of Cadence's text are owned by later builds: +//! +//! - Gaps mode and its plans from unresolved acceptance items: Build 5's +//! gap plans. +//! - The revision of the checker's issues: Build 4 T10, the checker. +//! - The recalled memory block and its citing: Build 8, +//! `retired("recall", 8)` in `crate::mcp::operations`. +//! +//! These rules are added under ADR 0049, which lets a ported text carry a +//! rule a design requirement states, each stated by a requirement of design +//! 0005: +//! +//! - The capacity as a fact, "propose a split rather than overfill" and the +//! `over-capacity` refusal (PLN-R9), with the proposed split for the +//! owner (PLN-R10). +//! - The plan grammar and its refusal codes (PLN-R11 to PLN-R13): the +//! members, the lease's path rule of D-05 and its 256 declarations, the +//! task members and `verify`, each evidence item's `story` (D-01), the +//! members Baley writes at approval and refuses at submit (D-03), the +//! `truth-without-observation` refusal (D-04) and the `check-boundary` +//! refusal (D-07). +//! - Section 10's test derivation rules, word for word (PLN-R18). +//! - The default test style, [`super::test_style::TEXT`] word for word +//! (PLN-R19). +//! - The question grammar and its codes (PLN-R23). +//! - The Planner row's rule on decisions, the revision order's answers and +//! deferrals applied, and its `questions` only the decisions not yet made +//! (PLN-R27). +//! - "Call no `baley_apply` operation: the host session submits what you +//! return", with the role's line that the session submits the plan with +//! `plan-submit` (design 0005 section 8, the planning sequence). + +/// The registry identity of the planner's text. +pub const IDENTITY: &str = "bal-phase-planner"; + +/// Pinned by hand: raise it by one whenever [`TEXT`] changes. +pub const VERSION: &str = "1"; + +/// Lowercase hex SHA-256 of [`TEXT`]'s exact bytes, computed outside the +/// code so a changed text without a new pin fails the registry's pin test. +pub const HASH: &str = "11fde32288a4c9baff41036736182c88140caa5c4089e49ae8189eda9a1a4507"; + +/// What the planner reads once it holds a planning or revision order. +/// Ported from Cadence tag `v3.9.0`: `skills/cad-planner-contract/SKILL.md` +/// whole, the `` and `` blocks of the +/// `spawn_planner` step of `cadence-core/workflows/plan.md`, and +/// `cadence-core/templates/PLAN.md`, with design 0005 section 10's Planner +/// row, its test derivation rules and its Default test style row. +pub const TEXT: &str = r#"Baley's planner turns one phase into a typed plan an executor can implement without interpretation, and returns it for the owner to answer its questions and approve. + + +You are Baley's planner. You turn one phase into a typed plan - a plan an executor can implement without interpretation - and return it as your final message, which the host session submits with `plan-submit`. The plan itself is the instruction handed to the executor, not a document someone converts into instructions later. + +Orders (your work order says which): +- **planning** - plan the phase from its goal plus the committed stories' approved truths and the owner's recorded answers. +- **revision** - your order carries a draft plan and every answer and deferral the owner recorded on its question set. Apply them with minimal edits to the draft; do not replan from scratch. An answer that rejects a recommended answer changes the plan to the owner's answer, and a deferral leaves the plan on that question's recommended answer. + + + +You already hold your work order: you read it with `baley_query` `document`, and it sent you here. Each input in the order's `inputs` holds JSON in its `text`, and together they carry: +- the phase's number and goal. +- the stories committed to the phase, in order, each with its approved truths: each truth's id, its version, its sentence slots and its `human_verify` when set. +- the project's approved description. +- when the owner set a capacity, the phase's capacity in tasks and the size the phase's approved plans already hold. +- in a revision order, the draft plan and its question set with every answer and deferral the owner recorded. + +Read before planning the actual source files your tasks will touch. + + + +The committed stories' approved truths and the owner's recorded answers are locked decisions: +- Every locked decision gets a task that implements it exactly as specified. EXACTLY, in both directions - delivering MORE than a decision states is scope invention, not thoroughness: one locked check licenses no second check beside it, and a rule locked for new work is never widened to what already shipped. Extra work that looks necessary goes to the owner as a question in `questions`, never into a task. +- Scope outside the committed stories MUST NOT appear in any plan. +- Where a choice is yours, not the owner's: choose, and record the choice in the task's `action`. + +Never reduce scope to make planning easier. Prohibited in task actions: "first version", "simplified", "for now", "placeholder", "future enhancement", or any phrasing that delivers less than the decision states. The only legitimate reasons to leave something out, and each goes to the owner, never a silent cut: +- Context cost - the phase cannot be executed well in one pass: return a proposed split. +- Missing information - a required detail exists in no source: ask for it in `questions`, with a recommended answer. +- Dependency - it needs a phase that has not shipped: return a proposed split. + + + +Goal-backward, not forward. "What should we build?" produces plausible tasks; "what must be TRUE for the goal to hold?" produces requirements the tasks must satisfy. The sequence: + +- **State the goal** from the phase's goal. It must be outcome-shaped ("working chat interface"), not task-shaped ("build chat components"). +- **Map the truths** - the committed stories' approved truths are what must be true when the phase is done. They are given, never derived: add, drop and reword none. Map each truth to the artifacts, the links and the one check that prove it. +- **Derive artifacts** - for each truth, what must exist. +- **Derive wiring** - for each artifact, what must be connected. Artifacts that exist but are never wired are the most common silent failure. +- **Write tasks** that create the artifacts and the wiring, ordered so each task builds only on completed prior tasks - and skeleton-first: the earliest tasks produce a minimal end-to-end path through every layer the goal touches (a tracer bullet - stubbed-thin but wired and runnable), and later tasks add depth to a spine that already works. A phase should have a working end-to-end skeleton from its earliest tasks, never a pile of polished-but-unconnected parts awaiting a final wiring task. Silent failures live in the seams; the skeleton makes every seam fail loudly on day one. + +Before writing any task, read the actual files it will touch. Never plan from filenames, directory listings, or memory of similar codebases. Read each file once, extract everything you need in that pass, do not re-read. Batch independent probes: greps, globs and reads whose target does not depend on another's result go out in ONE message, never one-then-wait. A probe you could only choose after seeing a prior result stays sequential. + +Read and search with the host's own Read, Grep and Glob tools. + +Locate with Grep carrying NO `-A`/`-B`/`-C`, then read the window those line numbers name. A search returning nothing gets a LOOSER PATTERN, never a wider range; recovering a missed heading by dumping blind lines pays for the miss twice. A wide context on a FIRST probe is the tell that you are reading to find rather than reading to know. + + + +Every task has these members, all concrete: + +- `id` - unique within the plan, never blank. +- `title` - an action-oriented name. +- `files` - exact paths created or modified, each a plain relative path. "src/auth/login.rs", never "the auth files". It is a LEASE: a task file outside the plan's lease is refused `lease` when the plan is submitted, and a change outside it is stopped at close until the owner rules. A dependency change writes the lockfile too (`Cargo.lock`, `package-lock.json`, `uv.lock`, `go.sum`, `Gemfile.lock`). `files` holds paths only, so when the truths, the answers or what you read already point at evidence inside a file this task touches, carry that anchor into the `action` - file plus SYMBOL (function, export, heading), never a line number, which rots between the decision and the task. The anchor says where the executor STARTS reading; it never narrows the lease and never licenses skipping a caller check. +- `action` - what must become true, the constraints that bind it, and what to avoid with WHY. Directive prose, no fenced code blocks. Name symbols that ALREADY EXIST - you read them, so they are facts. Never invent an identifier, signature, field name, line number or call path for code this task has yet to write: you cannot know it, and the guess reaches the executor as an instruction, meets a codebase that disagrees, and becomes a deviation someone must log, defend or work around. "Add a POST /login route validating the credential pair against the existing user store with the password hash this tree already uses, issuing a short-lived session cookie" - never "make login work", and never a signature you have not read. +- `verify` - one or more commands Baley runs, each the narrowest command whose output settles the task, such as `cargo test auth::`. THIS FIELD IS THE TASK'S AUTHORITY: any implementation satisfying it is authorized, and the executor owes no deviation for building it differently than you pictured. So it must be falsifiable and must pin the property the task exists for - everything you left unspecified in `action` is a choice this field is the only check on. "Running X shows Y", never "X works" or "looks good". If proving the task needs a tool or service the run cannot reach (probe with `command -v`; e.g. docker, a cloud CLI, a live endpoint), never write a command the run cannot execute, which only turns into a mid-task deferral that later masquerades as a pass: the truth's `human_verify` names that tool or service, and the plan proves the truth with an `observation` item beside its check. + +Atomic means: ONE concern, independently verifiable, leaves the repo committable. One concern is the binding half: a task whose title needs "and" or a comma to describe it - "scaffolding, license, typed errors and the CLI skeleton" - is that many tasks, however few files it touches. A task touching many files is usually more than one task as well, but the file count is the weaker signal and it catches less. + +Nobody estimates, and no count of tasks is a target: carry no task-count rule of your own. When your order gives a capacity, it is the ceiling on the phase's size in tasks, beside the size the phase's approved plans already hold, and a plan that would take the phase over it is refused `over-capacity`. When the phase needs more than that, propose a split rather than overfill. Compressing several concerns into one task to fit under the capacity is the failure the capacity exists to prevent, and it is worse than the overrun. + + + +Apply separation of concerns to the tasks and artifacts you write: prefer small, single-purpose tasks and artifacts over one shared core. When responsibilities differ on any of the following axes, give them separate tasks or artifacts rather than folding them together: + +- trigger - what invokes the responsibility. +- size - its context cost, how much it carries. +- lifecycle - how often it changes and on what cadence. +- failure-resume - how it fails and how it recovers. +- freshness - how current its data must be. +- ownership - which actor or layer is responsible for it. + +This is a nudge to weigh, not a hard rule: it never forces a split that does not earn itself. A genuinely single-concern phase stays one task, and combining responsibilities that share every axis is correct, not a defect. This governs task/artifact-level decomposition within a plan, distinct from a phase's several plans, each of which comes from its own order - they are not the same decision. + + + +The plan is one JSON object with exactly these members and no other: + +{"phase":,"stories":[],"files":[""],"directories":[""],"goal":"","context":"","notes":"","tasks":[],"evidence_map":[],"questions":[]} + +- `phase` - the phase's number, as your order gives it. +- `stories` - the ids of the stories the plan serves, none twice. A story not committed to the phase is refused `story-not-in-phase`, and a plan for a phase none of whose committed stories holds an approved truth is refused `no-truths`. Across the phase's plans every committed story is served; a story served by no plan is a planning failure. +- `files` and `directories` - the lease. Every entry is a plain relative path: not empty, not starting with `/`, holding no `\`, and with no empty, `.` or `..` part, so no trailing separator and no `//`, on a directory as on a file. No entry appears twice across both lists. The lease holds at most 256 declarations, files and directories counted together. `files` is empty only when `directories` holds an entry. A task file is inside the lease when it equals a declared file or lies under a declared directory. +- `goal` - the phase goal, outcome-shaped. +- `context` - the locked decisions that bind this plan, the existing files and patterns to follow, anything explicitly out of scope. +- `notes` - human-required setup (accounts, env vars you cannot obtain) and assumptions surfaced during planning; empty when there are none. +- `tasks` - in order, each `{"id":"","title":"","files":[""],"action":"","verify":[""]}`, as the task anatomy says. `verify` holds one or more commands, none blank. +- `evidence_map` - the evidence items, as the evidence map says. +- `questions` - the decisions the plan needs from the owner, `[]` when there are none. + +What must be true when the phase is done is the served truths: the committed stories' approved truths, which the plan does not restate. + +Every member is required, and none may be added. An unknown member, a missing one, or one of another type is refused `typed-content`, naming the path of the first fault, such as `tasks[].verify`. Baley writes `plan` (the plan's number), `question_set`, `size` and `suite` itself when the owner approves the plan: never send them, since each is refused `typed-content` as an unknown member. + +One plan per order. Baley numbers a phase's plans as each is approved; a phase that needs further plans gets each from its own order, submitted on its own. + +The rule for decisions: put every decision the plan needs from the owner in `questions` with a recommended answer, write the plan on the recommended answers, and leave no decision in `notes` or task prose. + +Each question is `{"id":"","question":"","recommended":"","depends_on":[]}`: +- `id` is unique within `questions` and not blank, or the plan is refused `question-id`. +- `question` and `recommended` are not blank, or the plan is refused `question-blank`. +- `depends_on` lists the ids of other questions in `questions` whose answers this one needs, `[]` when none. An id outside `questions`, or the question's own, is refused `question-dependency`, and questions that depend on each other in a cycle are refused `question-cycle`. +- Each text is at most 4,096 bytes. A longer text, an unknown member, or a `depends_on` naming an id twice is refused `typed-content`. + + + +`evidence_map` binds every truth the plan serves to evidence items. Every truth the plan serves is bound to exactly one check, and a truth with no check, or a check under no truth, is a plan defect. Each check is written and run red before the behaviour it proves and green after. A check that cannot fail before its behaviour, because it pins something already true, runs red under the break its `reason` names instead: the break is applied, the check is seen to fail, and the code is restored. Expected values come from the design, never from the code under test. + +Each item is `{"id":"","story":,"truth":"","truth_version":,"kind":"","spec":{},"reason":""}`: +- `id` - unique within the plan, not blank. An item one of the phase's approved plans holds may be listed again unchanged; the same id with another definition is refused `evidence-item-conflict`. +- `story`, `truth` and `truth_version` - the truth it serves: a story the plan serves, one of that story's current truths, and that truth's current version. A truth id is unique only within its story. An item naming no current truth of a story the plan serves is refused `evidence-item-truth`, and one naming another version `truth-version-mismatch`. +- `reason` - in one line, the wrong implementation the item must fail under. +- `kind` - one of these, each with its `spec`: + - `artifact` - a file or record that must exist. Its spec holds exactly one member, `path` for a file or `record` for a record: `{"path":""}` or `{"record":""}`. + - `link` - a value that must pass from a caller to a callee. `caller` names what passes the value, `callee` what receives it and `value` the value: `{"caller":"","callee":"","value":""}`. A link is written only where the truth's own words name the value crossing: its `value` appears in the truth's trigger, observer or outcome, never only inside a longer word, or the plan is refused `link-value-not-named`. + - `check` - the command whose result proves the truth: `{"command":"","expected":{"kind":"","value":""},"test":{"file":"","function":""},"setup":"","call":"","level":"","boundary":"","fakes":[""]}`. `command` runs the check. `expected`'s `kind` is `literal` for one exact value or `property` for a property every output holds. `test` names the test's `file` and `function`, `setup` the state it sets up and `call` the call it makes. `level` is `unit` or `integration`; a check with no `level`, or another value, is refused `typed-content`. `fakes` may be empty when the unit touches no seam. A blank `command` is refused `check-command`, a blank expected `value` `check-expected`, a blank test `file` `check-test-file`, and a blank `boundary` `check-boundary`, at either level. + - `observation` - something a named person must see. `what` is what is to be seen and `by` by whom: `{"what":"","by":""}`. Write one only for what can be seen at the phase's close and no check can establish. It never makes a truth met. + +Judged across the phase, this plan's items with those of the phase's approved plans: +- Every truth the plan serves is named by an item, or the plan is refused `uncovered-truth`. +- Every such truth holds exactly one check for its current version: none is refused `truth-without-check`, and a second `truth-check-limit`. A check an approved plan already holds for the truth is its one check. +- A truth with `human_verify` holds an `observation` beside its check, naming what a person must see live, or the plan is refused `truth-without-observation`. + +Name each check in the `action` of the task that writes it, the task in which its red run happens. Name every other test in the task action, each with the meaningful defect it would catch. A test named in no task action is not written, and a test the executor believes is missing is a deviation in its report. Every named test, and every check with a test file, gets a negative control: the guarded behaviour is broken, the test is seen to fail, and the code is restored. A check's control breaks it the way its `reason` names. + + + +Treat a plan step as a container for work; separate its independently testable responsibilities instead of testing the whole step. For each responsibility, choose input classes, decision edges and failure responses justified by the requirement. Take expected values from that requirement; never invent behavior to make an answer available. Put each ambiguity the requirement leaves as a question in the plan's `questions` field, with a recommended answer, for the owner to decide. + +A generated unit test exercises one responsibility and one behavior, using at most one simulated external seam; split a unit that touches two. Run the real logic that owns the decision with supplied observations and independently justified expectations. In the one check's existing fields, connect the approved truth, production responsibility, inputs or seam, expected observable result and test. Name every other test in the task action with the meaningful defect it would catch. Stop when another case would distinguish no new required behavior or meaningful failure. Reuse adequate existing tests and relevant regressions; do not pursue test counts, a test per function, blanket permutations or coverage percentages. Use the managed project's approved language and test framework; Baley being written in Rust does not choose the project's language. + +Give every check a `level`. Write a unit check at one unit: `boundary` is the one unit the check exercises, named as a unit and not as a workflow, and `fakes` names every filesystem, process and clock seam that unit touches; do not leave it empty when the unit touches one. A check never starts a program to get its answer: not the project's binary, not git, not gpg, not a shell. + +When a truth's outcome depends on two or more of the project's own units working together, write its check as an integration check. Run those units together for real, and name them in `boundary`. Mock every outside boundary they reach, the database, the network, a third-party API, the clock, the filesystem or a host program, and name each in `fakes`. A mock sits behind an interface the project owns and serves the results and the failures the test needs. Never mock one of the project's own units inside an integration check. Where the project has no interface of its own at a boundary, say so in the plan and plan the seam first. Integration tests belong to the project's test command, so the suite runs them. + +Naming a fake is not permission to script one. A check builds the values it needs and asserts the rule over them. If the check has to supply the answer the unit is about to reach for, it measures nothing. When the unit stops in the middle of judging to ask git, the filesystem or the clock, that unit is not testable as written: say so in the plan and move the asking out, so the judging takes its facts as arguments. The small function that does the asking gets no check of its own. + +A generated test may rely only on the project's language toolchain and test libraries, including mocking libraries, from that language's package ecosystem. It must need no other language runtime, host-installed program, particular hardware or pre-existing machine state, and give the same result wherever the project builds. Test code starts no program. A test may create a fresh temporary directory as its one filesystem seam, keeps its reads and writes inside it, and makes no assertion depend on filesystem permissions, case sensitivity, symlink support or crash durability. + +When this phase first makes a running-program obligation runnable, add it to the map as a pending observation. Checks with mocked boundaries cannot establish real persistence, a real service, GUI interaction, performance or a live run of the assembled program, and passing them does not close that obligation. State what remains unverified. + +This is the default test style, for a project that has set no test style of its own. It is guidance: Baley never refuses a plan on style. + +- Test a unit through what it exposes, never through its internals. +- Fake only the outside world, never the project's own code. +- Never start a program from a test. +- Skip trivial code: it needs no test of its own. +- Write the expected value by hand, never from the code under test. + + + +As your final message, return exactly one JSON plan and nothing else. + +When the phase cannot be delivered well for context cost or a dependency, or a plan would take the phase over its capacity, return no plan. Return instead a proposed split for the owner, beginning with the words `Proposed split:`, naming which of those reasons applies and the stories or phases you propose, each with its goal. A split counts only when the owner approves it. + +A revision order's plan returns the same way, its `questions` only the decisions not yet made. + + + +- Write no file and make no commit. +- Call no `baley_apply` operation: the host session submits what you return. +- No subagents, no reviews - you are the leaf. + +"#; diff --git a/crates/baley/src/instruction/tests.rs b/crates/baley/src/instruction/tests.rs index 6f47c4d8..2b3d1331 100644 --- a/crates/baley/src/instruction/tests.rs +++ b/crates/baley/src/instruction/tests.rs @@ -186,6 +186,11 @@ const SERVED_EVER: &[(&str, &str, &str)] = &[ "2", "0dad9202903bc4ee1ba81792681c893b3abe5a098cb950fe40135d9fa74ed116", ), + ( + "bal-phase-planner", + "1", + "11fde32288a4c9baff41036736182c88140caa5c4089e49ae8189eda9a1a4507", + ), ]; fn served() -> impl Iterator { @@ -724,3 +729,239 @@ fn a_default_test_style_missing_a_rule_of_its_design_row_is_caught() { ); } } + +/// The only numbers the planner text may hold: the two grammar limits +/// design 0005 states and the two phrases of its section 10 test rules that +/// count units, which the text carries word for word (D-18, D-19). +const PLANNER_NUMBERS: &[&str] = &[ + "at most 256 declarations", + "at most 4,096 bytes", + "two or more of the project's own units", + "split a unit that touches two", +]; + +/// Count words a number handed to the planner would be spelled with. +const COUNT_WORDS: &[&str] = &[ + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "ten", + "eleven", + "twelve", + "thirteen", + "fourteen", + "fifteen", + "sixteen", + "seventeen", + "eighteen", + "nineteen", + "twenty", + "thirty", + "forty", + "fifty", + "sixty", + "seventy", + "eighty", + "ninety", + "hundred", + "thousand", + "dozen", +]; + +#[test] +fn a_number_handed_to_the_planner_is_caught() { + let served = served_text("bal-phase-planner"); + let mut body = served.to_owned(); + for phrase in PLANNER_NUMBERS { + body = body.replace(phrase, ""); + } + if let Some(at) = body.find(|c: char| c.is_ascii_digit()) { + let start = body.floor_char_boundary(at.saturating_sub(40)); + let end = body.ceil_char_boundary((at + 40).min(body.len())); + panic!("the planner text holds a digit: {}", &body[start..end]); + } + for word in body.split(|c: char| !c.is_ascii_alphabetic()) { + assert!( + !COUNT_WORDS.contains(&word.to_ascii_lowercase().as_str()), + "the planner text holds the count word {word}" + ); + } + for name in CADENCE_NAMES { + assert!(!served.contains(name), "the planner text names {name}"); + } + assert_eq!( + lookup("bal-plan"), + Lookup::Unavailable { + identity: "bal-plan", + build: 4 + } + ); +} + +#[test] +fn a_planner_text_missing_its_grammar_or_a_refusal_is_caught() { + let body = served_text("bal-phase-planner"); + // The plan's members, a task's, an item's and each spec's (Plan 1's + // Context, D-01, D-12), the members Baley adds at approval (D-03), and + // every refusal code of PLN-R11 to PLN-R13, PLN-R9 and PLN-R23. + for name in [ + "phase", + "stories", + "files", + "directories", + "goal", + "context", + "notes", + "tasks", + "evidence_map", + "questions", + "id", + "title", + "action", + "verify", + "story", + "truth", + "truth_version", + "kind", + "spec", + "reason", + "artifact", + "link", + "check", + "observation", + "path", + "record", + "caller", + "callee", + "value", + "what", + "by", + "command", + "expected", + "literal", + "property", + "test", + "file", + "function", + "setup", + "call", + "level", + "unit", + "integration", + "boundary", + "fakes", + "human_verify", + "plan", + "question_set", + "size", + "suite", + "typed-content", + "lease", + "story-not-in-phase", + "no-truths", + "evidence-item-truth", + "truth-version-mismatch", + "evidence-item-conflict", + "link-value-not-named", + "uncovered-truth", + "truth-without-check", + "truth-without-observation", + "truth-check-limit", + "check-command", + "check-expected", + "check-test-file", + "check-boundary", + "over-capacity", + "question-id", + "question-blank", + "question-dependency", + "question-cycle", + ] { + assert!( + body.contains(&format!("`{name}`")), + "the planner text lacks `{name}`" + ); + } + for needle in [ + "propose a split rather than overfill", + "put every decision the plan needs from the owner in `questions` with a recommended answer, write the plan on the recommended answers, and leave no decision in `notes` or task prose", + "Proposed split:", + "Call no `baley_apply` operation", + ] { + assert!(body.contains(needle), "the planner text lacks {needle}"); + } +} + +#[test] +fn a_planner_text_without_the_test_rules_word_for_word_or_the_default_style_is_caught() { + let body = served_text("bal-phase-planner"); + // Design 0005 section 10's test derivation rules, copied by hand + // without the quote marks (PLN-R18, D-19). + let rules = [ + "Treat a plan step as a container for work; separate its independently testable responsibilities instead of testing the whole step. For each responsibility, choose input classes, decision edges and failure responses justified by the requirement. Take expected values from that requirement; never invent behavior to make an answer available. Put each ambiguity the requirement leaves as a question in the plan's `questions` field, with a recommended answer, for the owner to decide.", + "A generated unit test exercises one responsibility and one behavior, using at most one simulated external seam; split a unit that touches two. Run the real logic that owns the decision with supplied observations and independently justified expectations. In the one check's existing fields, connect the approved truth, production responsibility, inputs or seam, expected observable result and test. Name every other test in the task action with the meaningful defect it would catch. Stop when another case would distinguish no new required behavior or meaningful failure. Reuse adequate existing tests and relevant regressions; do not pursue test counts, a test per function, blanket permutations or coverage percentages. Use the managed project's approved language and test framework; Baley being written in Rust does not choose the project's language.", + "Give every check a `level`. Write a unit check at one unit: `boundary` is the one unit the check exercises, named as a unit and not as a workflow, and `fakes` names every filesystem, process and clock seam that unit touches; do not leave it empty when the unit touches one. A check never starts a program to get its answer: not the project's binary, not git, not gpg, not a shell.", + "When a truth's outcome depends on two or more of the project's own units working together, write its check as an integration check. Run those units together for real, and name them in `boundary`. Mock every outside boundary they reach, the database, the network, a third-party API, the clock, the filesystem or a host program, and name each in `fakes`. A mock sits behind an interface the project owns and serves the results and the failures the test needs. Never mock one of the project's own units inside an integration check. Where the project has no interface of its own at a boundary, say so in the plan and plan the seam first. Integration tests belong to the project's test command, so the suite runs them.", + "Naming a fake is not permission to script one. A check builds the values it needs and asserts the rule over them. If the check has to supply the answer the unit is about to reach for, it measures nothing. When the unit stops in the middle of judging to ask git, the filesystem or the clock, that unit is not testable as written: say so in the plan and move the asking out, so the judging takes its facts as arguments. The small function that does the asking gets no check of its own.", + "A generated test may rely only on the project's language toolchain and test libraries, including mocking libraries, from that language's package ecosystem. It must need no other language runtime, host-installed program, particular hardware or pre-existing machine state, and give the same result wherever the project builds. Test code starts no program. A test may create a fresh temporary directory as its one filesystem seam, keeps its reads and writes inside it, and makes no assertion depend on filesystem permissions, case sensitivity, symlink support or crash durability.", + "When this phase first makes a running-program obligation runnable, add it to the map as a pending observation. Checks with mocked boundaries cannot establish real persistence, a real service, GUI interaction, performance or a live run of the assembled program, and passing them does not close that obligation. State what remains unverified.", + ]; + for rule in rules { + assert!( + body.contains(rule), + "the planner text lacks the rule beginning {}", + &rule[..40] + ); + } + assert!( + body.contains(test_style::TEXT), + "the planner text lacks the default test style" + ); +} + +#[test] +fn a_planner_text_given_a_help_row_or_a_skill_stub_is_caught() { + let identity = "bal-phase-planner"; + let Lookup::Served { entry, text } = lookup(identity) else { + panic!("{identity} is served"); + }; + assert_eq!(entry.build, 4); + assert_eq!(text.version, "1"); + assert!( + !crate::help::table::COMMANDS + .iter() + .any(|command| command.name == identity), + "{identity} is a help row" + ); + assert!( + !crate::host_artifacts::stubs::front_doors() + .iter() + .any(|(name, _)| *name == identity), + "{identity} is a front door" + ); + assert!(!identity.starts_with("bal-planner-")); +} + +#[test] +fn a_planner_text_naming_cadence_files_or_markers_is_caught() { + let body = served_text("bal-phase-planner"); + for name in [ + "PLAN.md", + "PLAN-", + "frontmatter", + "STATE", + "cursor", + "## ", + "Task ceiling", + "lease-check", + "undeclared-files", + "max_plan_tasks", + ] { + assert!(!body.contains(name), "the planner text names {name}"); + } +} From dfc69344c377a8f30bc7ffe0fc2ebbffb39e58b1 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 19:35:44 -0400 Subject: [PATCH 18/26] feat(8-3): port the bal-plan front door text, still unavailable T9 serves it with phase plan, plan submit and plan read, so the door is ported now with every dropped Cadence step listed beside it and stays unavailable until then. --- crates/baley/src/instruction/mod.rs | 1 + crates/baley/src/instruction/plan.rs | 123 ++++++++++++++++++++++++++ crates/baley/src/instruction/tests.rs | 50 +++++++++++ 3 files changed, 174 insertions(+) create mode 100644 crates/baley/src/instruction/plan.rs diff --git a/crates/baley/src/instruction/mod.rs b/crates/baley/src/instruction/mod.rs index 60de0b2b..51e77c57 100644 --- a/crates/baley/src/instruction/mod.rs +++ b/crates/baley/src/instruction/mod.rs @@ -17,6 +17,7 @@ use crate::help::front_door; pub mod analyzer; pub mod capture; pub mod context; +pub mod plan; pub mod planner; pub mod read_contract; pub mod rounds; diff --git a/crates/baley/src/instruction/plan.rs b/crates/baley/src/instruction/plan.rs new file mode 100644 index 00000000..6e019d82 --- /dev/null +++ b/crates/baley/src/instruction/plan.rs @@ -0,0 +1,123 @@ +//! The `bal-plan` front door's text, compiled but not served: how a host +//! session turns one phase into its typed plan with its owner, from the +//! planner's order to the plan the owner approves at the terminal (design +//! 0005 sections 5, 8 and 10, PLN-R7, PLN-R9, PLN-R10, PLN-R15, PLN-R24, +//! PLN-R26, PLN-R27). The registry entry, help row and stub of `bal-plan` +//! stay unavailable at build 4 until Build 4 T9 serves this text with +//! `phase plan`, `plan submit` and `plan read`, and pins its version and +//! hash then, so this module holds neither. +//! +//! The text is ported from Cadence (ADR 0048). Cadence's own files, +//! commands and state are replaced by Baley's: the skill's objective +//! becomes the opening summary line; `parse` and `load_phase` become +//! resolving the phase, the owner naming it or the session reading the +//! roadmap with `document` and asking; `spawn_planner` becomes +//! `phase-plan` and the order's `launch`, and the dispatch bracket becomes +//! `work-order-fail` and `work-order-retry`; `handle_return` becomes +//! `plan-submit`, with Cadence's "PHASE TOO BIG" return and its `too_big` +//! step becoming a proposed split put to the owner; `done` becomes the +//! owner's preview and approval at the terminal. Where Cadence names a +//! command, the text names the Baley operation with how its request ids, +//! receipts, refusals, settings lines and parts are read, as `bal-context` +//! does. The operation shapes follow design 0005 section 5, and T9 aligns +//! them with what it builds when it serves the text. +//! +//! The text carries only the steps T8 and T9 own (D-17). These steps of +//! Cadence's are dropped, each with the ADR or the build that owns it: +//! +//! - The plan-checker gate and its `--skip-check` flag: Build 4 T10. +//! - The `plan` review fire: Build 4 T13 and T14. +//! - `--gaps` and its gap plans: Build 5. +//! - `--inline` and the `route` step: every role runs from a work order +//! (ADR 0046). +//! - `plan-size`, `check_size`, the task ceiling and the byte ceiling: no +//! number is handed to the planner (ADR 0017, PLN-R17); `over-capacity` +//! at submit takes their place. +//! - `check_census`: Cadence's census of its own counts; the lease check +//! at close is Build 5's (ADR 0018). +//! - `count_planned`, `count_committed` and the recalled memory: Build 8, +//! `retired("recall", 8)` in `crate::mcp::operations`. +//! - `commit`, `seed-reqs`, the cursor and every planning-file commit: the +//! ledger records each step (ADR 0006). +//! - The dispatch bracket's trace lines, which are Cadence's own +//! `planning.mjs` calls. +//! - The test switches and the `` block they gate: Baley +//! always requires the evidence map (PLN-R12, ADR 0014), which the +//! planner's own text carries. +//! - The ask to replan from scratch or abort when plans exist: no plan is +//! overwritten, and a further plan is numbered at approval (ADR 0006, +//! D-20). +//! - The consult offer of `too_big`, which ADR 0048's table ports to no +//! Baley part. +//! - The closing suggestion of Cadence's execute command: Build 5's +//! `bal-execute`. +//! +//! These changes from Cadence's wording are forced by accepted Baley ADRs: +//! +//! - The owner commits stories to the phase in order when it is planned, +//! since a phase delivers stories (ADR 0017), and says owner where +//! Cadence says user (ADR 0031). +//! - The owner approves at the terminal, with no lock-or-edit question put +//! by the session (ADR 0044). +//! +//! These rules are added under ADR 0049, each stated by a requirement of +//! design 0005: +//! +//! - The draft's question set put to the owner through `bal-rounds`, and +//! the revision order for a set closed with a rejected recommendation, +//! its plan submitted as a new draft (PLN-R24, PLN-R27). +//! - `question-open` refusing the approval while a question is open +//! (PLN-R26). +//! - The proposed split, which the owner decides on (PLN-R10), with +//! `over-capacity` (PLN-R9). + +/// What a session is told when it follows the plan command. Ported from +/// Cadence tag `v3.9.0`: `skills/cad-plan/SKILL.md` and +/// `cadence-core/workflows/plan.md`, step by step. +pub const TEXT: &str = r#"Baley plan turns one phase into a typed plan: atomic tasks, each with files, an action and a falsifiable verification, and the evidence map that binds every truth the phase serves to its proof. The planner writes it in a fresh context from its work order, and the owner answers its questions and approves it at the terminal. + + +Take the phase the owner names. If none is named, read the accepted roadmap with `baley_query` `{"operation":"document","identity":{"kind":"roadmap"}}` and ask the owner which phase to plan, by its number. If the roadmap holds no such phase, stop and say so: there is no phase to plan until the roadmap holds it, and a phase is declared through `bal-phase` first. An answer too long for one part names its `next` part. Ask for it by adding `"part":`, and join the bodies in order. + + + +Ask the owner which stories the phase commits, in order: by default the next backlog stories the owner picks. Ask for the planner's order with one `baley_apply` call: `{"operation":"phase-plan","request_id":"","phase":,"stories":[],"instruction":"bal-plan"}`. + +Show the owner a refusal of `phase-plan` with its `code`, `slot` and `reason`: `phase-active` while another phase is active, `no-such-phase` and `no-such-story` for a phase or story the roadmap does not hold, `story-unrefined` for a story with no approved truths, which is refined through `bal-context` first, and `story-in-phase` for a story committed to another open phase. + +When the stories change what the phase commits, the answer is a draft of that change: give the owner its digest to preview with `baley scope preview ` and approve with `baley scope approve ` at the terminal, then call `phase-plan` again. + +The receipt names the order in `work_order` and gives the worker's `prompt` and `launch`. When the answer holds `settings` lines, show them to the owner. Launch the worker exactly as `launch` says, with `prompt` as its whole prompt. Change nothing in the order and add nothing to the prompt. The order binds the phase, its committed stories with their approved truths and the project's description as they stood when it was issued, so the worker reads them from the order. Then wait - do not read, edit, or plan anything else while the worker runs. + +When the worker cannot launch, or returns without its result, call `baley_apply` with `{"operation":"work-order-fail","request_id":"","work_order":"","reason":"","instruction":"bal-plan"}`, then with `{"operation":"work-order-retry","request_id":"","work_order":"","instruction":"bal-plan"}`, and launch the retried order from its receipt the same way. Never fail or retry an order only because its worker has not answered yet. + + + +The planner returns one typed plan, or a proposed split beginning `Proposed split:`. + +Submit a plan with one `baley_apply` call: `{"operation":"plan-submit","request_id":"","work_order":"","plan":}`. Send the plan exactly as returned: never edit it. On a refusal, show the owner its `code`, `slot` and `reason`. The receipt gives the draft's `digest`, its preview, the plan's size and the phase's size against its capacity, and the draft's question set. + +A returned `Proposed split:`, or a plan refused `over-capacity`, goes to the owner. State the planner's reason, or the size the phase would reach and its capacity, in one line. The owner decides which story waits, or splits a story or the phase through `bal-story` or `bal-phase`; then plan again from the top. A split counts only when the owner approves it. + + + +Put the draft's question set to the owner. Read the rounds relay with `baley_query` `{"operation":"instruction","identity":"bal-rounds"}`, and put each round to the owner as it says. A draft with no questions has an empty set, closed at once. + +When the set closes with an answer that rejects a recommended answer, the draft is not approved as written: Baley issues the planner a revision order carrying the draft and every answer and deferral on its set. Launch it exactly as its `launch` says, with its `prompt` as the whole prompt, and submit its plan with `plan-submit` as a new draft, as above. A deferral leaves the plan on that question's recommended answer. + + + +Give the owner the draft's digest. The owner previews it with `baley scope preview ` and approves it with `baley plan approve ` at the terminal, which records the plan with its number. While a question of the draft's set is open, the approval is refused `question-open`. Nothing is approved over MCP, so approve nothing yourself. + +A phase that needs another plan gets it from another planner order, submitted on its own and numbered when it is approved. + + +Use a fresh request id for each call. Send a request id again only to retry the same call, with every other argument unchanged. + +On a `refused` answer, show the owner its `code`, `slot` and `reason`. On a `failed` answer marked `retryable`, send the same call again unchanged. On any other `failed` answer, show the owner its `code` and `reason`. + + +- The planner runs in a fresh context from its work order. Never plan in the main context. +- Never modify source code. Write no file and make no commit: the plan, its questions and their answers live only in the ledger. + +"#; diff --git a/crates/baley/src/instruction/tests.rs b/crates/baley/src/instruction/tests.rs index 2b3d1331..5881254d 100644 --- a/crates/baley/src/instruction/tests.rs +++ b/crates/baley/src/instruction/tests.rs @@ -965,3 +965,53 @@ fn a_planner_text_naming_cadence_files_or_markers_is_caught() { assert!(!body.contains(name), "the planner text names {name}"); } } + +#[test] +fn a_plan_door_missing_a_step_it_owns_is_caught() { + // The steps D-17 keeps: the planner order, its launch, failure and + // retry, the submit, the rounds, the split and the terminal approval. + for needle in [ + "phase-plan", + r#""instruction":"bal-plan""#, + "launch", + "prompt", + "work-order-fail", + "work-order-retry", + "plan-submit", + "bal-rounds", + "Proposed split:", + "over-capacity", + "question-open", + "baley scope preview", + "baley plan approve", + "Nothing is approved over MCP", + ] { + assert!( + plan::TEXT.contains(needle), + "the plan front door lacks {needle}" + ); + } +} + +#[test] +fn a_plan_door_naming_cadence_state_or_a_later_tasks_step_is_caught() { + for name in CADENCE_NAMES.iter().chain(&[ + "STATE", + "cursor", + "PLAN.md", + "checker", + "plan_check", + "--gaps", + "--inline", + "--skip-check", + "seed-reqs", + "cite-count", + "lease-check", + "max_plan_tasks", + ]) { + assert!( + !plan::TEXT.contains(name), + "the plan front door names {name}" + ); + } +} From 273c70ed9217627b48fb344d0f8b770582219864 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 23 Oct 2026 20:05:51 -0400 Subject: [PATCH 19/26] fix(8-3): make the planner's verify entries bare commands Baley runs each verify entry as written, so the retained "Running X shows Y" form would launch a program named Running. The text now asks for the bare command and puts the expected output in the action or a check's expected. Version 1 has not shipped, so its hash is re-pinned. --- crates/baley/src/instruction/planner.rs | 9 ++++++--- crates/baley/src/instruction/tests.rs | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/baley/src/instruction/planner.rs b/crates/baley/src/instruction/planner.rs index bce1651b..46a8b62a 100644 --- a/crates/baley/src/instruction/planner.rs +++ b/crates/baley/src/instruction/planner.rs @@ -64,7 +64,10 @@ //! becomes one or more commands, and a proof that needs a tool or live //! service the run cannot reach becomes the truth's `human_verify`, //! proven by an `observation` beside its check (D-04), never a -//! human-verify Verify. +//! human-verify Verify. Cadence's "Running X shows Y" form is dropped, +//! since Baley runs each entry as written: an entry is the bare command, +//! and what its output must show goes in the action or a check's +//! `expected`. //! - Decisions go to the owner as typed questions (ADR 0030): missing //! information, and extra work that looks necessary, become a question in //! `questions` where Cadence returns them to the human in its marker. @@ -116,7 +119,7 @@ pub const VERSION: &str = "1"; /// Lowercase hex SHA-256 of [`TEXT`]'s exact bytes, computed outside the /// code so a changed text without a new pin fails the registry's pin test. -pub const HASH: &str = "11fde32288a4c9baff41036736182c88140caa5c4089e49ae8189eda9a1a4507"; +pub const HASH: &str = "65a03cb2fcbee8ff52445f5363a51054404085166b9ff2e285117f084315d8c6"; /// What the planner reads once it holds a planning or revision order. /// Ported from Cadence tag `v3.9.0`: `skills/cad-planner-contract/SKILL.md` @@ -180,7 +183,7 @@ Every task has these members, all concrete: - `title` - an action-oriented name. - `files` - exact paths created or modified, each a plain relative path. "src/auth/login.rs", never "the auth files". It is a LEASE: a task file outside the plan's lease is refused `lease` when the plan is submitted, and a change outside it is stopped at close until the owner rules. A dependency change writes the lockfile too (`Cargo.lock`, `package-lock.json`, `uv.lock`, `go.sum`, `Gemfile.lock`). `files` holds paths only, so when the truths, the answers or what you read already point at evidence inside a file this task touches, carry that anchor into the `action` - file plus SYMBOL (function, export, heading), never a line number, which rots between the decision and the task. The anchor says where the executor STARTS reading; it never narrows the lease and never licenses skipping a caller check. - `action` - what must become true, the constraints that bind it, and what to avoid with WHY. Directive prose, no fenced code blocks. Name symbols that ALREADY EXIST - you read them, so they are facts. Never invent an identifier, signature, field name, line number or call path for code this task has yet to write: you cannot know it, and the guess reaches the executor as an instruction, meets a codebase that disagrees, and becomes a deviation someone must log, defend or work around. "Add a POST /login route validating the credential pair against the existing user store with the password hash this tree already uses, issuing a short-lived session cookie" - never "make login work", and never a signature you have not read. -- `verify` - one or more commands Baley runs, each the narrowest command whose output settles the task, such as `cargo test auth::`. THIS FIELD IS THE TASK'S AUTHORITY: any implementation satisfying it is authorized, and the executor owes no deviation for building it differently than you pictured. So it must be falsifiable and must pin the property the task exists for - everything you left unspecified in `action` is a choice this field is the only check on. "Running X shows Y", never "X works" or "looks good". If proving the task needs a tool or service the run cannot reach (probe with `command -v`; e.g. docker, a cloud CLI, a live endpoint), never write a command the run cannot execute, which only turns into a mid-task deferral that later masquerades as a pass: the truth's `human_verify` names that tool or service, and the plan proves the truth with an `observation` item beside its check. +- `verify` - one or more commands Baley runs, each the narrowest command whose output settles the task, such as `cargo test auth::`. THIS FIELD IS THE TASK'S AUTHORITY: any implementation satisfying it is authorized, and the executor owes no deviation for building it differently than you pictured. So it must be falsifiable and must pin the property the task exists for - everything you left unspecified in `action` is a choice this field is the only check on. Write each entry as the bare command and nothing around it: `cargo test auth::`, never "Running cargo test auth:: shows the auth tests pass", "X works" or "looks good". What its output must show goes in the task's `action`, and for a check in its `expected`. If proving the task needs a tool or service the run cannot reach (probe with `command -v`; e.g. docker, a cloud CLI, a live endpoint), never write a command the run cannot execute, which only turns into a mid-task deferral that later masquerades as a pass: the truth's `human_verify` names that tool or service, and the plan proves the truth with an `observation` item beside its check. Atomic means: ONE concern, independently verifiable, leaves the repo committable. One concern is the binding half: a task whose title needs "and" or a comma to describe it - "scaffolding, license, typed errors and the CLI skeleton" - is that many tasks, however few files it touches. A task touching many files is usually more than one task as well, but the file count is the weaker signal and it catches less. diff --git a/crates/baley/src/instruction/tests.rs b/crates/baley/src/instruction/tests.rs index 5881254d..19e99699 100644 --- a/crates/baley/src/instruction/tests.rs +++ b/crates/baley/src/instruction/tests.rs @@ -189,7 +189,7 @@ const SERVED_EVER: &[(&str, &str, &str)] = &[ ( "bal-phase-planner", "1", - "11fde32288a4c9baff41036736182c88140caa5c4089e49ae8189eda9a1a4507", + "65a03cb2fcbee8ff52445f5363a51054404085166b9ff2e285117f084315d8c6", ), ]; From f044fc57ea27d569172506b5ebca3d4f8fca8ccc Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 30 Oct 2026 17:10:27 -0400 Subject: [PATCH 20/26] docs(8-4): count a phase's size per plan and name the new refusals Design 0005's terms and requirements now match the core plan judge: a phase's size counts each plan's tasks once, over-capacity names every served story and the size reached, the lease path rule and the members Baley writes at approval are stated, an evidence item names its story, and PLN-R13 gains check-boundary and truth-without-observation. --- docs/design/0005-context-plans-and-acceptance.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/design/0005-context-plans-and-acceptance.md b/docs/design/0005-context-plans-and-acceptance.md index ae0efb15..5d62004c 100644 --- a/docs/design/0005-context-plans-and-acceptance.md +++ b/docs/design/0005-context-plans-and-acceptance.md @@ -45,7 +45,7 @@ In the component view of [0002](0002-system-design.md) (Figure 4) this area is o | Phase planning | Committing stories to a phase and writing its plans. | | Increment | What a completed phase delivers: something the owner can use, proven by its stories' truths and the suite. | | Unit of work | One task: one signed commit with one narrowest verify command. | -| Size | The number of tasks a story's approved plans need; a phase's size is the sum over its stories. | +| Size | A story's size counts the tasks of the approved plans that serve it; a phase's size counts each of its approved plans' tasks once, so a plan serving two stories is counted once. | | Capacity | The owner's ceiling on a phase's size, in tasks. | | Velocity | Tasks completed per phase, as a fact shown, never a decision input. | | Plan | One typed document for a phase: the stories it serves, its file lease, its tasks, its suite and its evidence map. A phase may have several plans. | @@ -74,11 +74,11 @@ In the component view of [0002](0002-system-design.md) (Figure 4) this area is o | PLN-R6 | Refinement dispatches the analyzer twice. The first work order carries the story, the project description, the roadmap and the code; the analyzer finds the facts itself from the code and the records and returns questions (PLN-R23) only for the decisions left to the owner, never draft truths. The host session submits the questions as returned, and they go to the owner in rounds (PLN-R24). When no question of the set is open, Baley issues the second work order, carrying the story, the questions and every recorded answer and deferral; the analyzer returns draft truths drawn from them. The host session drops a draft truth that contradicts a fact the code holds or an answer the owner gave, keeping a truth about behaviour the story has not built yet, and the owner edits, attests and approves the truths (PLN-R26). | What the owner did not say is found and decided before it is built on, a fact the code already holds is never put to the owner, and truths are drafted on decisions already made. | SYS-P2, SYS-P5, PLN-R23, PLN-R24 | Active | | PLN-R7 | A phase ([0004](0004-starting-a-project-and-changing-scope.md)) is a goal and the stories committed to it. Phase planning commits stories in backlog order unless the owner reorders, and writes the phase's plans. One phase is active per project; a second is refused with `phase-active` until the first is complete or withdrawn. | One phase at a time is the discipline; the record shows which. | PRJ-R7, PRJ-R11 | Active | | PLN-R8 | A phase is a working increment: its exit proof is its committed stories' truths, each verified by its one check, plus the suite. There is no separate whole-application test command. | Progress is real at every step. | PLN-R19 | Active | -| PLN-R9 | Nobody estimates. A story's size is the number of tasks its approved plans need; a phase's size is the sum. `planning.phase_capacity` (tasks, default none) is the ceiling: a plan whose tasks would take the phase over capacity is refused with `over-capacity`, naming the story and the count, and the story waits for the next phase. Size changes only when a plan is approved or replaced. Velocity is shown per phase and never used to decide. | Units of work are counted, not guessed, so there is no churn and no number for the model to hit. | PLN-R17 | Active | +| PLN-R9 | Nobody estimates. A story's size counts the tasks of the approved plans that serve it; a phase's size counts each of its approved plans' tasks once, so a plan serving two stories is counted once. `planning.phase_capacity` (tasks, default none) is the ceiling: a plan whose tasks would take the phase over capacity is refused with `over-capacity`, naming every story the plan serves and the size the phase would reach, and the owner decides which story waits for the next phase (PLN-R10). Size changes only when a plan is approved or replaced. Velocity is shown per phase and never used to decide. | Units of work are counted, not guessed, so there is no churn and no number for the model to hit. | PLN-R17 | Active | | PLN-R10 | One phase by default. The planner may propose splitting a story or a phase; a split counts only when the owner approves it. | Scope never changes without the owner. | SYS-P5 | Active | -| PLN-R11 | A plan is typed content: phase, plan number, the story ids it serves, `files` and `directories` (the lease: exact paths, no trailing separator on a file, at most 256 declarations, no duplicates, `files: []` only with directories), goal, context, notes, ordered `tasks` (unique id, title, files within the lease, action, one or more `verify` commands each naming the narrowest command that settles the task), the suite, the evidence map, and `questions` (the decisions the plan needs from the owner, each in the shape of PLN-R23, empty when there are none). Unknown keys and prose bodies are refused (`typed-content`). Task prose never contributes paths, and a decision the owner must make is never left in `notes` or task prose. | Baley reads records, never documents. | ADR 0006, SYS-P3, PLN-R23 | Active | -| PLN-R12 | The evidence map binds every truth a plan serves to evidence items of four kinds: `artifact`, `link`, `check`, `observation`. Each item names its truth and version and a one-line reason ("what change would break this"). Exactly one `check` per truth version across the phase; a second is refused with `truth-check-limit`. A `check` names its command, its expected literal or property, its test file and function, its setup, its call, its `level` (`unit` or `integration`), its `boundary` (the one unit a unit check exercises, or the project units an integration check runs together) and its `fakes` (every filesystem, process and clock seam a unit check's unit touches, or every outside boundary an integration check mocks). A `link` is allowed only where the truth's own words name the value crossing (`link-value-not-named`). An `observation` is written only when what it names can be seen at the phase's close and no check can establish it, and can never make a truth met, only `concerns` ([0007](0007-verification.md)). | The check is the truth; the other kinds are things the verifier inspects; nothing multiplies. | PLN-R4 | Active | -| PLN-R13 | Baley refuses at plan submit: a truth the plan serves with no item (`uncovered-truth`); an item naming no truth or a stale truth version (`evidence-item-truth`, `truth-version-mismatch`); a truth with items but no check (`truth-without-check`); a check with a blank command, expected value or test file (`check-command`, `check-expected`, `check-test-file`); a task file outside the lease (`lease`); a story not committed to the phase (`story-not-in-phase`); a plan for a phase with no refined stories (`no-truths`); the same item id with a different definition across plans (`evidence-item-conflict`). | The map must be complete and consistent before anyone builds against it. | PLN-R11, PLN-R12 | Active | +| PLN-R11 | A plan is typed content. The planner submits `phase`, the story ids it serves (`stories`), `files` and `directories` (the lease: each entry a plain relative path, not empty, not absolute, with no backslash, no trailing separator and no empty, `.` or `..` part; at most 256 declarations counting both lists; no entry twice; `files: []` only with directories), `goal`, `context`, `notes`, ordered `tasks` (unique id, title, files within the lease, action, one or more `verify` commands each naming the narrowest command that settles the task), the evidence map (`evidence_map`), and `questions` (the decisions the plan needs from the owner, each in the shape of PLN-R23, empty when there are none). Baley writes the plan number, the question set, the size and the suite when the plan is approved, the suite from `workflow.test_command`, so a submitted plan carrying any of them is refused `typed-content`. Unknown keys, wrong types, a malformed lease and prose bodies are refused `typed-content`, naming the entry by its path, such as `files[2]` or `tasks[0].verify[1]`. Task prose never contributes paths, and a decision the owner must make is never left in `notes` or task prose. | Baley reads records, never documents. | ADR 0006, SYS-P3, PLN-R23 | Active | +| PLN-R12 | The evidence map binds every truth a plan serves to evidence items of four kinds: `artifact`, `link`, `check`, `observation`. Each item names its story, truth and version, since a truth id is unique only within its story, and a one-line reason ("what change would break this"). Exactly one `check` per story, truth and version across the phase; a second is refused with `truth-check-limit`. A truth with `human_verify` also has an `observation` item for what a person must see, beside its one check. A `check` names its command, its expected literal or property, its test file and function, its setup, its call, its `level` (`unit` or `integration`), its `boundary` (the one unit a unit check exercises, or the project units an integration check runs together) and its `fakes` (every filesystem, process and clock seam a unit check's unit touches, or every outside boundary an integration check mocks). A `link` is allowed only where the truth's own words name the value crossing (`link-value-not-named`). An `observation` is written only when what it names can be seen at the phase's close and no check can establish it, and can never make a truth met, only `concerns` ([0007](0007-verification.md)). | The check is the truth; the other kinds are things the verifier inspects; nothing multiplies. | PLN-R4 | Active | +| PLN-R13 | Baley refuses at plan submit: a truth the plan serves with no item (`uncovered-truth`); an item naming no truth or a stale truth version (`evidence-item-truth`, `truth-version-mismatch`); a truth with items but no check (`truth-without-check`); a truth with `human_verify` whose items include no `observation` (`truth-without-observation`); a check, at either level, with a blank command, expected value, test file or boundary (`check-command`, `check-expected`, `check-test-file`, `check-boundary`); a task file outside the lease (`lease`); a story not committed to the phase (`story-not-in-phase`); a plan for a phase with no refined stories (`no-truths`); the same item id with a different definition across plans (`evidence-item-conflict`). `uncovered-truth`, `truth-without-check`, `truth-without-observation` and `truth-check-limit` are judged over the phase as it would stand with the plan approved: its items and the approved plans' items, an item counting only at its truth's current version. | The map must be complete and consistent before anyone builds against it. | PLN-R11, PLN-R12 | Active | | PLN-R14 | Plan numbers within a phase are assigned in order and never reused. Replacing an approved plan needs its own owner approval naming the plan and the digest it replaces; a plan admitted to execution is not replaced (`admitted-plan`); a gap plan gets a new number ([0006](0006-execution.md)). | Every plan the record ever named can be found. | EVD-R2 | Active | | PLN-R15 | A plan is submitted whole, previewed, and approved by the owner by digest with owner and time. Every draft is recorded in the ledger when it is submitted ([ADR 0043](../adr/0043-submissions-recorded-as-drafts.md)): it survives a restart, is read by its digest from any session or from the terminal, and is approved by its digest only at the terminal ([ADR 0044](../adr/0044-owner-acts-on-the-command-line.md)). A draft stops being approvable only when a newer submission replaces it or this project purges its body, never because a session ended. Approving an older digest when a newer draft exists is refused with `stale-draft`, naming the first differing part. A retry of the same approval is answered once. How a pending checker revision is keyed, and how a draft whose re-check was refused leaves that state, remain open for Build 4 (section 12). | The owner approves exactly what was shown. | SYS-P5, SYS-R6 | Active | | PLN-R16 | Between submit and preview, when `review.triggers.plan.gate` is not `off`, Baley dispatches the checker with the plan and its stories' versioned truths. The checker returns findings, each with a severity: a truth no task makes true is a blocker; a task no truth needs is a warning; a finding without severity is refused. A blocker buys one planner revision and one re-check, then the plan goes to the owner with the findings. The first check reads the whole submitted plan against its stories' versioned truths. The re-check uses `review.triggers.plan.recheck`, either `full` or `diff`, with default `full`. Full reads the whole revised plan against the same truths. Diff reads every addition, modification and deletion since the checked draft, with before-and-after context. Both scopes check whether every first-round blocker is closed and may return new findings. Scope changes neither the number of rounds nor the gate's effect. Warnings never buy a round. The gate value says what the findings do ([0008](0008-review.md)). The round-2 work order binds the first check, the original and revised plan digests, the truth versions, the actual scope, the material references and the policy version that selected the scope. Before issue, the retained inputs must match the named first check and submitted revision. `plan submit` records this binding in `plan.check_issued` before returning the work order. A retry must keep that recorded binding. Missing or mismatched inputs refuse the re-check, without substituting current source or another scope. | The plan is judged against the goal before the owner spends time on it, at the cheapest effort, and the owner can turn it off. | PLN-R7, CFG-R12 | Active | From 003e4711dda9af11be3f98864f250318fb010ff8 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 30 Oct 2026 17:11:14 -0400 Subject: [PATCH 21/26] docs(8-4): describe the plan and evidence item records as judged Section 6 now says which plan members the planner submits and which Baley writes at approval, gives the evidence item its story and each spec kind its members as the core judge reads them, and ties a human_verify truth to an observation item. Figure 5's over-capacity refusal names every served story and the size the phase would reach. --- .../design/0005-context-plans-and-acceptance.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/design/0005-context-plans-and-acceptance.md b/docs/design/0005-context-plans-and-acceptance.md index 5d62004c..20159c06 100644 --- a/docs/design/0005-context-plans-and-acceptance.md +++ b/docs/design/0005-context-plans-and-acceptance.md @@ -213,7 +213,7 @@ Baley recognizes a checker revision from the draft awaiting the one revision gra | `trigger`, `observer`, `verb`, `outcome` | text | The sentence's slots; `verb` is `sees`, `gets` or `is refused` | | `kind` | `literal`, `property` | Whether the outcome is one value or a property | | `observable`, `fixed_oracle` | bool | The owner's attestations, true in every recorded truth | -| `human_verify` | text, or absent | The tool or live service a person needs to prove the truth; absent when none is needed | +| `human_verify` | text, or absent | The tool or live service a person needs to prove the truth; absent when none is needed. Such a truth also needs an `observation` item in the phase's evidence map, beside its one check (`truth-without-observation`, PLN-R13) | Each of a truth's texts, `id`, `form`, `trigger`, `observer`, `verb`, `outcome`, `kind` and `human_verify`, is at most 4,096 bytes as written, before any trimming, the limit questions and answers use; an over-long one is refused `truth-form` with nothing recorded. @@ -225,23 +225,26 @@ Each of a truth's texts, `id`, `form`, `trigger`, `observer`, `verb`, `outcome`, |---|---|---| | `phase`, `plan` | integers | The phase and the plan number | | `stories` | list of story ids | The stories it serves | -| `files`, `directories` | lists of paths | The lease | +| `files`, `directories` | lists of paths | The lease: each entry a plain relative path under the PLN-R11 rule | | `goal`, `context`, `notes` | text | For the executor | -| `tasks` | list | `id`, `title`, `files`, `action`, `verify` | +| `tasks` | list | `id`, `title`, `files`, `action`, `verify` (one or more commands) | | `suite` | command | The suite Baley runs at close | | `evidence_map` | list of items | See below | | `questions` | list of questions | The plan's questions (PLN-R23), as submitted | | `question_set` | set id | The set its questions were put to the owner in; the answers and deferrals are that set's records | | `size` | integer | The number of tasks | +The planner submits `phase`, `stories`, `files`, `directories`, `goal`, `context`, `notes`, `tasks`, `evidence_map` and `questions`. Baley writes `plan`, `question_set`, `size` and `suite` when the plan is approved, `suite` from `workflow.test_command`, so a submitted plan carrying any of them is refused `typed-content` (PLN-R11). + ### evidence item | Field | Type | Meaning | |---|---|---| -| `id` | item id | Unique within the phase | -| `truth`, `truth_version` | truth id, integer | The truth it serves | +| `id` | item id | Unique within the phase: the same id in another plan is the same item and must keep one definition (`evidence-item-conflict`) | +| `story` | story id | The story whose truth it serves | +| `truth`, `truth_version` | truth id, integer | The truth it serves, found by its story, id and version, since a truth id is unique only within its story | | `kind` | `artifact`, `link`, `check`, `observation` | | -| `spec` | table | `artifact`: path or record. `link`: caller, callee, value. `check`: command, expected {literal or property, value}, test {file, function}, setup, call, level (`unit` or `integration`), boundary, fakes. `observation`: what is to be seen, by whom. | +| `spec` | table | `artifact`: exactly one of `path` or `record`. `link`: `caller`, `callee`, `value`. `check`: `command`, `expected` {`kind` `literal` or `property`, `value`}, `test` {`file`, `function`}, `setup`, `call`, `level` (`unit` or `integration`), `boundary`, `fakes`. `observation`: `what`, what is to be seen, and `by`, by whom. | | `reason` | text | What change would break this | ### questions.opened (event; `roadmap` stream for a story's set, `phase/` stream for a plan draft's set) @@ -499,7 +502,7 @@ sequenceDiagram alt map or grammar refused B-->>H: refusal naming the item else over capacity - B-->>H: over-capacity, naming the story and count + B-->>H: over-capacity, naming every story the plan serves and the size the phase would reach else alt plan gate on B-->>H: checker work order with the full plan and versioned truths From ae2c659d133e667074ca68b97af8ff46d1d60185 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 30 Oct 2026 17:13:34 -0400 Subject: [PATCH 22/26] docs(8-4): cite the core plan judge and the served planner text Section 10 names bal-phase-planner, the default test style's constant and the ported bal-plan text, which stays unavailable until Build 4 T9 serves it. Section 11 moves PLN-R4, R5, R9, R11 to R13, R17 to R19 and R27 off the parked engine onto the core plan module and the served text, citing ADR 0042 for each check's level, boundary and fakes. --- .../0005-context-plans-and-acceptance.md | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/docs/design/0005-context-plans-and-acceptance.md b/docs/design/0005-context-plans-and-acceptance.md index 20159c06..c04e0c4e 100644 --- a/docs/design/0005-context-plans-and-acceptance.md +++ b/docs/design/0005-context-plans-and-acceptance.md @@ -620,10 +620,10 @@ sequenceDiagram |---|---|---| | Analyzer questions | The analyzer, as `bal-analyzer-questions`, listed by its questions work order: the question grammar and its refusals; find every fact yourself from the code and the records and never ask the owner for one; ask only for the decisions left to the owner, each with a recommended answer and the ids of the questions it depends on; draft no truths yet; never decide. The text is ported from Cadence v3.9.0's analyzer contract (`skills/cad-assumptions-analyzer-contract/SKILL.md`) with the evidence rules of its context workflow (`cadence-core/workflows/context.md`) under [ADR 0048](../adr/0048-port-what-cadence-hands-agents.md), and each difference from Cadence's wording is listed beside it, in its module's doc comment, with the ADR that forces it or with [ADR 0049](../adr/0049-rules-added-to-ported-texts.md) and the design requirement that states it (`crates/baley/src/instruction/analyzer.rs`, `QUESTIONS_TEXT`) | PLN-R6, PLN-R23 | | Analyzer drafting | The analyzer, as `bal-analyzer-drafting`, listed by its drafting work order: the truth form, the refusals, the story's questions with every answer and deferral; draft truths on the owner's answers, not on the recommendations; assume no answer to a deferred question; a restated truth keeps its id; name in `human_verify` the tool or live service a truth's proof needs; leave the attestations to the owner; never decide. The text is ported from the same analyzer contract and the `acceptance_criteria` step of the same context workflow under [ADR 0048](../adr/0048-port-what-cadence-hands-agents.md), each difference from Cadence's wording listed beside it, in its module's doc comment, with the ADR that forces it or with [ADR 0049](../adr/0049-rules-added-to-ported-texts.md) and the design requirement that states it (`crates/baley/src/instruction/analyzer.rs`, `DRAFTING_TEXT`). Neither analyzer text is a help row, so neither has a stub | PLN-R2, PLN-R3, PLN-R4, PLN-R6, PLN-R25 | -| Planner | The planner, in its planning work order: the plan grammar with its `questions` field, the question grammar, the lease rules, the evidence map grammar, one check per truth, the test derivation rules below, the capacity ceiling as a fact, "propose a split rather than overfill", "put every decision the plan needs from the owner in `questions` with a recommended answer, write the plan on the recommended answers, and leave no decision in `notes` or task prose". In a revision work order it also receives the draft and every answer and deferral on its set, and applies them | PLN-R5, PLN-R9 to PLN-R13, PLN-R17, PLN-R18, PLN-R23, PLN-R27 | +| Planner | The planner, as `bal-phase-planner`, listed by its planning work order: the plan grammar with its `questions` field, the members Baley writes at approval, the question grammar, the lease rules, the evidence map grammar with each item's story and each check's `level`, `boundary` and `fakes`, one check per truth, an observation beside the check of a truth with `human_verify`, the refusal codes, the test derivation rules below, the default test style, the capacity ceiling as a fact, "propose a split rather than overfill", "put every decision the plan needs from the owner in `questions` with a recommended answer, write the plan on the recommended answers, and leave no decision in `notes` or task prose". In a revision work order it also receives the draft and every answer and deferral on its set, and applies them. The text holds no number but the grammar limits (PLN-R17). It is ported from Cadence v3.9.0's planner contract (`skills/cad-planner-contract/SKILL.md`), the planning-context and test-method blocks of its plan workflow (`cadence-core/workflows/plan.md`) and its plan template (`cadence-core/templates/PLAN.md`) under [ADR 0048](../adr/0048-port-what-cadence-hands-agents.md), each difference from Cadence's wording listed beside it, in its module's doc comment, with the ADR that forces it or with [ADR 0049](../adr/0049-rules-added-to-ported-texts.md) and the design requirement that states it (`crates/baley/src/instruction/planner.rs`, `TEXT`). It is no help row, so it has no stub | PLN-R5, PLN-R9 to PLN-R13, PLN-R17 to PLN-R19, PLN-R23, PLN-R27 | | Checker | The checker, in its check work order: the six dimensions (story coverage, task completeness, sequencing, goal-backward truths, scope sanity, proportionality), severity rules, derive what must be true from the goal before opening the plan. For round 2, follow the work order's scope, check every first-round blocker and report new defects in the selected material | PLN-R16 | -| Default test style | The planner and, through [0006](0006-execution.md), the executor, when the project has set nothing: test a unit through what it exposes; fake only the outside world; never start a program; skip trivial code; write the expected value by hand | PLN-R19 | -| Stubs | The host session: which operation each of `story refine`, `story questions submit`, `questions round`, `questions answer`, `story truths submit`, `phase plan`, `plan submit`, `phase close` calls, and that the owner approves each preview. The `bal-context` front door, a help row with a stub, takes a story id and walks one refinement: the refinement read with `document` or `context-intake`, `story-refine` and the order's launch, `work-order-fail` and `work-order-retry` for an order that fails, the rounds through `bal-rounds`, the drafted truths checked and put to the owner for edits and attestations, `context-submit`, and the owner's preview and approval at the terminal with `baley scope preview` and `baley story truths approve`. It is ported from Cadence v3.9.0's `skills/cad-context/SKILL.md` and `cadence-core/workflows/context.md` under [ADR 0048](../adr/0048-port-what-cadence-hands-agents.md), each difference from Cadence's wording listed beside it, in its module's doc comment, with the ADR that forces it or with [ADR 0049](../adr/0049-rules-added-to-ported-texts.md) and the design requirement that states it (`crates/baley/src/instruction/context.rs`, `TEXT`) | PLN-R1 to PLN-R6, PLN-R15 | +| Default test style | The planner, inside `bal-phase-planner`'s text, and, through [0006](0006-execution.md), the executor, when the project has set nothing: test a unit through what it exposes; fake only the outside world; never start a program; skip trivial code; write the expected value by hand. No Cadence v3.9.0 text carries a default test style, so it is written for Baley under [ADR 0048](../adr/0048-port-what-cadence-hands-agents.md) and held as its own constant, which the planner's text carries whole (`crates/baley/src/instruction/test_style.rs`, `TEXT`) | PLN-R19 | +| Stubs | The host session: which operation each of `story refine`, `story questions submit`, `questions round`, `questions answer`, `story truths submit`, `phase plan`, `plan submit`, `phase close` calls, and that the owner approves each preview. The `bal-context` front door, a help row with a stub, takes a story id and walks one refinement: the refinement read with `document` or `context-intake`, `story-refine` and the order's launch, `work-order-fail` and `work-order-retry` for an order that fails, the rounds through `bal-rounds`, the drafted truths checked and put to the owner for edits and attestations, `context-submit`, and the owner's preview and approval at the terminal with `baley scope preview` and `baley story truths approve`. It is ported from Cadence v3.9.0's `skills/cad-context/SKILL.md` and `cadence-core/workflows/context.md` under [ADR 0048](../adr/0048-port-what-cadence-hands-agents.md), each difference from Cadence's wording listed beside it, in its module's doc comment, with the ADR that forces it or with [ADR 0049](../adr/0049-rules-added-to-ported-texts.md) and the design requirement that states it (`crates/baley/src/instruction/context.rs`, `TEXT`). The `bal-plan` front door, a help row with a stub, takes a phase and walks its planning: `phase plan` and the planner order's launch, `work-order-fail` and `work-order-retry` for an order that fails, `plan submit`, the rounds through `bal-rounds`, the revision order, and the owner's preview and approval at the terminal. It is ported from Cadence v3.9.0's `skills/cad-plan/SKILL.md` and `cadence-core/workflows/plan.md` under [ADR 0048](../adr/0048-port-what-cadence-hands-agents.md), each difference from Cadence's wording listed beside it, in its module's doc comment, with the ADR or the build that owns it (`crates/baley/src/instruction/plan.rs`, `TEXT`). This text is compiled but not served: the `bal-plan` registry entry holds no text (`crates/baley/src/instruction/mod.rs`, `ENTRIES`), so `bal-plan` answers unavailable naming Build 4 until Build 4 T9 serves it with `phase plan`, `plan submit` and `plan read` | PLN-R1 to PLN-R7, PLN-R10, PLN-R15, PLN-R27 | | Rounds | The host session, with every question set, served by its identity `bal-rounds` at version 2 and named by `bal-context`, the round read and the answer receipt; it has no help row and no stub. Its first step submits the analyzer's questions as returned with `story-questions-submit`, an empty set's receipt naming the drafting order; then read the round with `document`; put every question of the current round to the owner with its recommended answer and show the waiting questions; relay each answer and deferral unchanged through `questions-answer`; answer, drop, merge, reword and reorder none; read again after each call until the set is closed, and return to the instruction that sent it there, whose next step launches the drafting order (`crates/baley/src/instruction/rounds.rs`, `TEXT`) | PLN-R6, PLN-R24, PLN-R25, PLN-R26 | The test derivation rules the planner receives, as served: @@ -649,22 +649,23 @@ The binary parks the inherited engine for Build 9 to delete, and nothing in prod | Requirement | Status | Where | |---|---|---| | PLN-R1 | Partly built | The `backlog` view lists every story approved scope declared, in priority order, which an approved `backlog reorder` changes, keeps a dropped story with status `dropped`, and records each story's latest question set, refined marker and truth count (`crates/baley-core/src/scope/backlog.rs`, `BacklogProjector`). The backlog read works out each story's refinement state from its latest set (`crates/baley/src/scope/read.rs`, `backlog`, through `crates/baley-core/src/truth/state.rs`, `refinement`), and `baley backlog show` prints it (`crates/baley/src/scope/command.rs`, `backlog_render`). A story carries its truths, with every version, in the `truths` view (`crates/baley-core/src/truth/view.rs`, `TruthsProjector`). A story's size, and a phase's truths read as the sum of its committed stories' truths, are phase planning's, Build 4 T9 | -| PLN-R7 to PLN-R10, PLN-R20 to PLN-R22 | Not built | In the parked engine truths are per phase (`crates/baley/src/context/model.rs`, `Submission`), and nothing knows committed stories, size or capacity | +| PLN-R7, PLN-R8, PLN-R10, PLN-R20 to PLN-R22 | Not built | In the parked engine truths are per phase (`crates/baley/src/context/model.rs`, `Submission`), and nothing records committed stories, size or capacity; the plan judge takes them as facts (the PLN-R9 and PLN-R12 rows). The planner text tells the planner to propose a split (`crates/baley/src/instruction/planner.rs`, `TEXT`); the owner's approval of one is Build 4 T9's | +| PLN-R9 | Partly built | The plan judge refuses `over-capacity` last, over the phase's current size and capacity it is given, counting each plan's tasks once and naming every story the plan serves and the size the phase would reach (`crates/baley-core/src/plan/capacity.rs`, `within`, through `crates/baley-core/src/plan/judge.rs`, `judge_plan` and `PlanFacts`). The size recorded at approval, the `planning.phase_capacity` setting and its reader are Build 4 T9's | | PLN-R2, PLN-R3 | Built | `judge_truths` (`crates/baley-core/src/truth/submission.rs`) judges a submission truth by truth, its shape, its id, its form and its two attestations, refusing `truth-form`, `truth-id`, `truth-attestation`, `truth-internal` and `truth-prose-oracle`, and classifies no sentence. `context-submit` (`crates/baley/src/mcp/refine.rs`, `serve_context`) judges the truths through it before anything is prepared. The parked engine's own validation (`crates/baley/src/context/validation.rs`, `validate`) is reached by no served path and goes in Build 9 | -| PLN-R4 | Partly built | A truth draft is recorded with no version (`crates/baley/src/refine/submit.rs`, `check` and `record`) and approved only by `baley story truths approve` (`crates/baley/src/refine/command.rs`, `approve`), whose two steps (`crates/baley/src/refine/approve.rs`, `judge` and `record`) give each truth its version (`crates/baley-core/src/truth/version.rs`, `versions`) and record `story.refined` with the story's whole truth list (`crates/baley-core/src/truth/event.rs`, `refined_payload`). The `truths` view keeps every version, and the refinement read returns them (`crates/baley/src/refine/read.rs`, `read`). Evidence written against an older version being stale is the plan's, Build 4 T8 and T9, which bind to these versions | -| PLN-R5 | Partly built | `judge_truths` accepts any number of truths, none included, and the backlog, the roadmap and `baley story show` show each story's count. The parked engine's `seven-truths` cap (`crates/baley/src/context/validation.rs`, `validate`) is reached by no served path and goes in Build 9. The planner's proposed split is Build 4 T9 | +| PLN-R4 | Partly built | A truth draft is recorded with no version (`crates/baley/src/refine/submit.rs`, `check` and `record`) and approved only by `baley story truths approve` (`crates/baley/src/refine/command.rs`, `approve`), whose two steps (`crates/baley/src/refine/approve.rs`, `judge` and `record`) give each truth its version (`crates/baley-core/src/truth/version.rs`, `versions`) and record `story.refined` with the story's whole truth list (`crates/baley-core/src/truth/event.rs`, `refined_payload`). The `truths` view keeps every version, and the refinement read returns them (`crates/baley/src/refine/read.rs`, `read`). The plan judge refuses an evidence item bound to another version of its truth `truth-version-mismatch` (`crates/baley-core/src/plan/binding.rs`, `bind`) and counts an approved plan's item toward a served truth only at the truth's current version (`crates/baley-core/src/plan/coverage.rs`, `Phase`), so evidence written against an older version proves nothing in a new plan. Running the judge at plan submit, over the approved plans' items read from the records, is Build 4 T9's | +| PLN-R5 | Partly built | `judge_truths` accepts any number of truths, none included, and the backlog, the roadmap and `baley story show` show each story's count. The parked engine's `seven-truths` cap (`crates/baley/src/context/validation.rs`, `validate`) is reached by no served path and goes in Build 9. The served planner text tells the planner to return a proposed split rather than overfill a phase (`crates/baley/src/instruction/planner.rs`, `TEXT`); the owner's approval of a split is Build 4 T9's | | PLN-R6 | Built | `story-refine` (`crates/baley/src/mcp/refine.rs`, `serve`) chooses and issues the questions order or the drafting order (`crates/baley/src/refine/order.rs`, `check` and `issue`), refusing `analyzer-order-pending` and `question-open`, with the inputs it binds at issue (`crates/baley/src/refine/inputs.rs`, `read`). `story-questions-submit` (`crates/baley/src/mcp/refine.rs`, `serve_questions`, through `crates/baley/src/refine/questions.rs`, `check` and `record`) records the set as returned and, for an empty set, issues the drafting order, and a closing `questions-answer` over MCP issues it with the answers (`crates/baley/src/mcp/questions.rs`, `serve`). The analyzer's texts are `bal-analyzer-questions` and `bal-analyzer-drafting` (`crates/baley/src/instruction/analyzer.rs`), and `bal-context` walks a session through one refinement (`crates/baley/src/instruction/context.rs`). `baley context-instructions` still prints the parked context text, which says "Do not dispatch an analyzer" (`crates/baley/src/context/instructions.rs`, `ROLE`), until Build 9 removes it | -| PLN-R11 | Not built | Only the parked engine holds typed content and lease rules (`crates/baley/src/plan/model.rs`, `Task` and `Content`, and `crates/baley/src/plan/validation.rs`, `typed_content` and `arguments`), and its plan has no `questions` field. The session server answers `plan-submit` as unavailable (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`) until Build 4 | -| PLN-R12, PLN-R13 | Not built | Only the parked engine checks a plan's evidence map, associations and limits, and it has no refusals about committed stories (`story-not-in-phase`, `no-truths`) (`crates/baley/src/plan/associations.rs`, `validate_items`, `validate` and `validate_union`; `crates/baley/src/plan/limits.rs`, `content`, `checks` and `links`; `crates/baley/src/plan/evidence.rs`, `Map` and `Item`). The session server answers `plan-submit` as unavailable (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`) until Build 4 | +| PLN-R11 | Partly built | The plan judge reads a plan's members in a fixed order, refusing `typed-content` named by its path for an unknown key, a member Baley writes at approval, a missing member or a wrong type (`crates/baley-core/src/plan/content.rs`, `read`), the lease under one path rule (`crates/baley-core/src/plan/lease.rs`, `read` and `plain_relative_path`), each task's members (`crates/baley-core/src/plan/task.rs`, `read` and `Task`), and the `questions` field through `judge_set`. Recording a plan, its number, its size and its suite at approval are Build 4 T9's, and the session server answers `plan-submit` as unavailable (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`) until then. The parked engine's own typed content and lease rules are reached by no served path and go in Build 9 | +| PLN-R12, PLN-R13 | Partly built | `judge_plan` (`crates/baley-core/src/plan/judge.rs`) judges a submitted plan whole in one fixed order, the first fault answering, with every refusal of PLN-R13: each item's grammar and each check's `level`, `boundary` and `fakes` ([ADR 0042](../adr/0042-mocked-boundary-integration-checks.md)) (`crates/baley-core/src/plan/evidence.rs`, `EvidenceItem` and `Check`), each task file inside the lease (`crates/baley-core/src/plan/task.rs`, `within_lease`), the blank check fields (`crates/baley-core/src/plan/evidence.rs`, `blank_fields`), the committed stories (`crates/baley-core/src/plan/stories.rs`, `holds_truths` and `committed`), each item bound to its own story's current truth (`crates/baley-core/src/plan/binding.rs`, `bind`), one definition per item id (`crates/baley-core/src/plan/coverage.rs`, `consistent`), each link's value named by its truth (`crates/baley-core/src/plan/link.rs`, `named`), and coverage, the check, the observation and the one-check limit over the phase with its approved plans' items (`crates/baley-core/src/plan/coverage.rs`, `Phase`). The judge runs at plan submit once Build 4 T9 serves it; until then the session server answers `plan-submit` as unavailable (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`). The parked engine's own evidence map checks are reached by no served path and go in Build 9 | | PLN-R14 | Not built | Only the parked engine numbers a phase's plans and refuses to replace an admitted plan (`crates/baley/src/plan/inventory.rs`, `with_records`, and `crates/baley/src/plan/validation.rs`, `replacement_inner` and `admitted`). The session server answers `plan-submit` as unavailable (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`) until Build 4 | | PLN-R15 | Not built | Only the parked engine holds a plan draft, approves it by digest and refuses `stale-draft` (`crates/baley/src/plan_service.rs`, `execute`). Its drafts are memory-only and lost on restart (`crates/baley/src/session/mod.rs`, `Drafts` and `drafts`). The session server answers `plan-submit` as unavailable (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`) until Build 4. Drafts recorded in the ledger and approved by digest at the terminal are built for the start's scope submission ([0004](0004-starting-a-project-and-changing-scope.md) section 11) and for a story's truths (the PLN-R4 row); plan drafts are Build 4 T9 | -| PLN-R16 | Not built | `/bal-plan` forbids checker dispatch (`crates/baley/src/plan/instructions.rs`, `ROLE`), and the parked engine still holds the 3.x checker verdict record as a fact kind (`crates/baley/src/evidence/mod.rs`, `Fact`, and `crates/baley/src/evidence/checker.rs`, `Checker`). Re-check scope selection, retained comparison material, `plan.check_issued` and pending-check lookup are not built | -| PLN-R17, PLN-R18, PLN-R19 | Built as text | The derivation rules are compiled into the parked planner text (`crates/baley/src/plan/instructions.rs`, `ROLE`), which `baley plan-instructions` prints. That text still tells the planner to flag ambiguity for the owner in prose, has no check `level`, and still sends integration to a pending observation | +| PLN-R16 | Not built | The parked plan text forbids checker dispatch (`crates/baley/src/plan/instructions.rs`, `ROLE`), and the ported `bal-plan` text leaves the checker gate to Build 4 T10 (`crates/baley/src/instruction/plan.rs`, its module comment). The parked engine still holds the 3.x checker verdict record as a fact kind (`crates/baley/src/evidence/mod.rs`, `Fact`, and `crates/baley/src/evidence/checker.rs`, `Checker`). Re-check scope selection, retained comparison material, `plan.check_issued` and pending-check lookup are not built | +| PLN-R17, PLN-R18, PLN-R19 | Built | The planner's text is served by its identity `bal-phase-planner` (`crates/baley/src/instruction/planner.rs`, `TEXT`, registered in `crates/baley/src/instruction/mod.rs`, `ENTRIES`), carrying section 10's test derivation rules word for word, each check's `level` and integration checks ([ADR 0042](../adr/0042-mocked-boundary-integration-checks.md)), and the default test style (`crates/baley/src/instruction/test_style.rs`, `TEXT`). It holds no number but the grammar limits, and a test fails when one is added (`crates/baley/src/instruction/tests.rs`, `a_number_handed_to_the_planner_is_caught`). The planning work order that lists it is Build 4 T9's. `baley plan-instructions` still prints the parked planner text (`crates/baley/src/plan/instructions.rs`, `ROLE`), which flags ambiguity in prose, has no check `level` and sends integration to a pending observation, until Build 9 removes it | | PLN-R23 | Partly built | `judge_set` (`crates/baley-core/src/questions/set.rs`) judges a set whole with every refusal of PLN-R23, and refuses `typed-content` for a text over 4,096 bytes and a `depends_on` naming an id twice. `open` and `abandon` (`crates/baley/src/questions/record.rs`) record `questions.opened` and `questions.abandoned` inside a caller's transaction. `story questions submit` calls them (`crates/baley/src/refine/questions.rs`, `record`) to open a story's set and abandon the story's earlier set, which is closed by then, since `question-open` refuses `story-refine` and `story-questions-submit` while it is open. `plan submit`, which opens a plan draft's set and abandons the replaced draft's, is Build 4 T9 | | PLN-R24 | Built | `round_of` (`crates/baley-core/src/questions/round.rs`) works out the round from the questions in submitted order and the records, and `judge_call` and `judge_answers` (`crates/baley-core/src/questions/answer.rs`) judge a call against the round as it stood before it. The round is read with `document` (`crates/baley/src/mcp/document.rs`, `questions_answer`) and `baley questions round` (`crates/baley/src/questions/command.rs`, `round_render`), and a round is answered with `questions-answer` (`crates/baley/src/mcp/questions.rs`, `serve`) and `baley questions answer` (`crates/baley/src/questions/command.rs`, `record_answers`). The rounds relay is served as `bal-rounds` at version 2, whose first step submits a story's questions as returned (`crates/baley/src/instruction/rounds.rs`). It runs over the sets the PLN-R23 row's library functions open | | PLN-R25 | Partly built | `check` and `record` (`crates/baley/src/questions/answer.rs`) record every answer and deferral of a call in one transaction with its round, owner and time, a take with the recommended text and `accepted` true and an own answer in the owner's words with `accepted` false; `question-closed`, `answer-blank` and `question-set-abandoned` are judged by `judge_answers`, and the `questions` view refuses any record that would replace one (`crates/baley-core/src/questions/view.rs`, `QuestionsProjector`). A story's set is abandoned `superseded` by the story's next set only once it is closed: `question-open` refuses `story-refine` (`crates/baley/src/refine/order.rs`, `check`) and `story-questions-submit` (`crates/baley/src/refine/questions.rs`, `check`) while a question of it is open. A replaced plan draft abandons its set once Build 4 T9 calls `abandon` | | PLN-R26 | Partly built | `deferral-reason`, a deferral closing a waiting question, and a question waiting on a deferred one never entering a round are built (`judge_answers`, `round_of`). `baley story truths approve` refuses `question-open`, naming each open question of the story's latest set, and `question-set-abandoned` for a draft drafted from an older set (`crates/baley-core/src/truth/approval.rs`, `judge_truth_approval`). `question-open` on `plan approve` is Build 4 T9 | -| PLN-R27 | Not built | A plan's `questions` field is Build 4 T8 and T9, judged by `judge_set`. The draft's set opened with the preview, `answer-not-applied` and the planner's revision work order are Build 4 T9. A story set's close-time output, the analyzer's drafting work order, is built (the PLN-R6 row); a plan draft's, `ready` or the revision work order, plugs in at `receipt_value` (`crates/baley/src/questions/answer.rs`), which until then answers only `closed` for a plan draft's set | +| PLN-R27 | Partly built | A plan's `questions` field is judged by `judge_set` through the plan judge (`crates/baley-core/src/plan/content.rs`, `read`). The draft's set opened with the preview, `answer-not-applied` and the planner's revision work order are Build 4 T9. A story set's close-time output, the analyzer's drafting work order, is built (the PLN-R6 row); a plan draft's, `ready` or the revision work order, plugs in at `receipt_value` (`crates/baley/src/questions/answer.rs`), which until then answers only `closed` for a plan draft's set | ## 12. Open questions From fa08c216be5ba5c8657490ba027e87dcbac7041c Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 30 Oct 2026 17:14:16 -0400 Subject: [PATCH 23/26] docs(8-4): list bal-phase-planner among the served instructions Design 0012 names the planner's text as a work-order instruction with no help row, gives its identity, and adds it to HST-R11's served texts with its pins, beside bal-plan's compiled text that stays unavailable until Build 4 T9. The count of texts with no help row is corrected to the six the list holds. --- docs/design/0012-host-interface.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/design/0012-host-interface.md b/docs/design/0012-host-interface.md index 090e3988..dde72cfb 100644 --- a/docs/design/0012-host-interface.md +++ b/docs/design/0012-host-interface.md @@ -777,7 +777,7 @@ No setting selects, loads or overrides an instruction, because every instruction | Skill stubs | The host, on disk once `baley install` places them: per served front door, frontmatter with the help table's `name` and `description`, and one line asking the session to call `baley_query` with `{"operation":"instruction","identity":""}` and follow what it returns. A stub holds no instruction text and no `allowed-tools` line | HST-R12 | | Agent stubs (Claude Code) | The host, on disk once `baley install` places them: per role and rung, `bal--`, thirty in all, frontmatter with `name`, a `description` saying to use the agent only when a Baley work order names it, `model: inherit`, the rung's own `effort` and `mcpServers` naming the session's `baley` entry, then one line telling the worker to read the work order whose id its prompt gives with `baley_query` `document` kind `work_order` and follow it. A stub fixes no model and defines no inline server, so every subagent shares the session's connection ([ADR 0034](../adr/0034-one-server-per-session.md)) | HST-R12, HST-R14 | | Front-door instructions | The host session, by identity: what the command does, which operations it calls, that the owner approves and answers, that the session relays and adjudicates and never decides. Served: `bal-help`, `bal-capture`, the five scope front doors `bal-project` (project start, the work-order failure and retry, and `project-describe`), `bal-scope` (reading a draft and how the owner approves it), `bal-phase`, `bal-story` and `bal-backlog` (their change operations), and `bal-context`, which refines one story by its id: the refinement read, `story-refine` and the analyzer orders it issues, the rounds through `bal-rounds`, `context-submit`, and the owner's approval with `baley story truths approve`. `bal-context` is ported from Cadence `v3.9.0`'s `cad-context` skill and `context.md` workflow, with each difference from Cadence's wording listed beside the text with the ADR that forces it, or with [ADR 0049](../adr/0049-rules-added-to-ported-texts.md) and the design requirement that states it ([ADR 0048](../adr/0048-port-what-cadence-hands-agents.md), `crates/baley/src/instruction/context.rs`) | HST-R9, HST-R14 | -| Work-order instructions | A worker, by identity, through the order that lists them: `bal-start-planner`, which tells the start planner where the brief is, the shape of the start submission, the story statuses and the rule that an active story is delivered by at most one phase, and to submit with `scope-submit` naming its order; and `bal-start-survey`, which a start order lists only when the checkout holds existing code. Each is a compiled registry entry served by identity with its version and hash, and the order records that evidence. Neither is a help row, so neither gets a skill stub and no session reaches one outside an order | HST-R11, HST-R14 | +| Work-order instructions | A worker, by identity, through the order that lists them: `bal-start-planner`, which tells the start planner where the brief is, the shape of the start submission, the story statuses and the rule that an active story is delivered by at most one phase, and to submit with `scope-submit` naming its order; `bal-start-survey`, which a start order lists only when the checkout holds existing code; and `bal-phase-planner`, which a phase's planning work order lists: the plan grammar with its `questions` field, the lease, the evidence map with each check's `level`, `boundary` and `fakes`, the refusals, the test derivation rules and the default test style of [0005](0005-context-plans-and-acceptance.md) section 10, and the capacity as a fact. `bal-phase-planner` is ported from Cadence `v3.9.0`'s planner contract, plan workflow and plan template, each difference from Cadence's wording listed beside the text with the ADR that forces it, or with [ADR 0049](../adr/0049-rules-added-to-ported-texts.md) and the design requirement that states it ([ADR 0048](../adr/0048-port-what-cadence-hands-agents.md), `crates/baley/src/instruction/planner.rs`). Each is a compiled registry entry served by identity with its version and hash, and the order records that evidence. None is a help row, so none gets a skill stub and no session reaches one outside an order | HST-R11, HST-R14 | | Analyzer instructions | A worker, by identity, through the analyzer order that lists one: `bal-analyzer-questions`, which a story's questions order lists, tells the analyzer to gather evidence from the order's inputs and the code and return typed questions, each `{id, question, recommended, depends_on}`, to the session, which submits them as returned with `story-questions-submit`; `bal-analyzer-drafting`, which a story's drafting order lists, tells it to draft the story's truths from the set's answers and deferrals, each in the fixed form, with a `human_verify` naming the tool or live service a person needs to prove it where its proof needs one, leaving its two attestations to the owner, and return them to the session, which drops a draft truth that contradicts a fact the code holds or an answer the owner gave, puts the rest to the owner and submits them with `context-submit`. Both are ported from Cadence `v3.9.0`'s `cad-assumptions-analyzer-contract` skill and `context.md` workflow, each difference from Cadence's wording listed beside the text with the ADR that forces it, or with [ADR 0049](../adr/0049-rules-added-to-ported-texts.md) and the design requirement that states it ([ADR 0048](../adr/0048-port-what-cadence-hands-agents.md), `crates/baley/src/instruction/analyzer.rs`). Neither is a help row, so neither gets a skill stub | HST-R11, HST-R14 | | Rounds relay | The host session, by identity, as `bal-rounds` at version 2, which `bal-context`, the round read and the `questions-answer` receipt name: submit a questions order's return as returned with `story-questions-submit`, then read the round with `document`, put every question of the current round to the owner with its recommended answer and show each waiting question with what it waits on, relay each of the owner's acts unchanged through `questions-answer`, decide nothing, and read the round again after each call until the set is closed; the owner can also use `baley questions round` and `baley questions answer`. It is no help row, so it gets no skill stub ([0005](0005-context-plans-and-acceptance.md) section 10) | HST-R9 | | Read contract | Every worker and session, by identity: read records and instructions by identity in parts; read source with the host's tools; never search for instructions | HST-R6 | @@ -785,7 +785,7 @@ No setting selects, loads or overrides an instruction, because every instruction The text of every instruction is owned by the area it serves; this area serves it. -Each instruction is compiled into the binary with an identity, a version and a hash. A front door's identity is its help-table name, the read contract's is `bal-read-contract`, the start planner's and survey's are `bal-start-planner` and `bal-start-survey`, the analyzer's questions and drafting texts' are `bal-analyzer-questions` and `bal-analyzer-drafting`, and the rounds relay's is `bal-rounds`. The version is a number pinned beside the text, raised whenever the text changes, and the hash is the lowercase hex SHA-256 of the text, which is every part joined. `instruction` serves the text by identity in parts, and answers an identity whose work is not built yet with the build that owns it. Of the `baley_apply` operations, only `capture`, `project-start`, `work-order-fail`, `work-order-retry` and `story-refine` take `instruction` (section 5). A front door's text asks the session to send its identity as `instruction` on those calls made under it, and the scope front doors' texts tell the session to send none on the change operations, whose shapes take none. The help text, `bal-help` at version 3, and the help answer's `request` name `story-refine` among those operations (`crates/baley/src/help/front_door.rs`, `VERSION` and `TEXT`, `crates/baley/src/help/table.rs`, `REQUEST`). +Each instruction is compiled into the binary with an identity, a version and a hash. A front door's identity is its help-table name, the read contract's is `bal-read-contract`, the start planner's and survey's are `bal-start-planner` and `bal-start-survey`, the analyzer's questions and drafting texts' are `bal-analyzer-questions` and `bal-analyzer-drafting`, the rounds relay's is `bal-rounds`, and the planner's is `bal-phase-planner`. The version is a number pinned beside the text, raised whenever the text changes, and the hash is the lowercase hex SHA-256 of the text, which is every part joined. `instruction` serves the text by identity in parts, and answers an identity whose work is not built yet with the build that owns it. Of the `baley_apply` operations, only `capture`, `project-start`, `work-order-fail`, `work-order-retry` and `story-refine` take `instruction` (section 5). A front door's text asks the session to send its identity as `instruction` on those calls made under it, and the scope front doors' texts tell the session to send none on the change operations, whose shapes take none. The help text, `bal-help` at version 3, and the help answer's `request` name `story-refine` among those operations (`crates/baley/src/help/front_door.rs`, `VERSION` and `TEXT`, `crates/baley/src/help/table.rs`, `REQUEST`). Claude Code loads five artifacts Baley renders as content. Each is built from the compiled tables and supplied values only. The library renders them and writes none of them, and `baley install` writes them (section 5). @@ -814,7 +814,7 @@ The library holds the per-session server (`crates/baley/src/mcp/`), and `baley s | HST-R8 | Not built | Only the parked engine runs a suite inside one call (`crates/baley/src/execution_service.rs`, `native_answer`, `crates/baley/src/execution/runner.rs`, `observe_child`). The session server answers the execution operations as unavailable (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`) until Build 5, so no call it serves runs a suite | | HST-R9 | Partly built | A question set's round reaches the session in tool results: the `document` read of a set (`crates/baley/src/mcp/document.rs`, `questions_answer`) and the `questions-answer` receipt (`crates/baley/src/questions/answer.rs`, `record`) carry the round, each question with its recommended answer and each waiting question with what it waits on, and name the rounds relay `bal-rounds` (`crates/baley/src/instruction/rounds.rs`), which tells the session to put every question to the owner and relay each act unchanged. `questions-answer` records the owner's answers and deferrals all or none, each with `owner.name`, falling back to git `user.name`, and Baley's clock, under actor `baley` with the session as the caller (`crates/baley/src/mcp/questions.rs`, `serve`), and `baley questions answer` records the same with actor `owner` and no caller (`crates/baley/src/questions/command.rs`, `record_answers`, [ADR 0047](../adr/0047-owner-acts-relayed-by-a-session.md)). A set lives in the ledger, so it survives the session's exit and a restart, and only a recorded abandonment ends it. No approval is relayed. Elicitation is not built, and no adapter uses it before the probe of section 12. `story-questions-submit` opens a story's set from the analyzer's questions as returned, abandoning the story's earlier set as `superseded`, and only once no question of that set is open (`crates/baley/src/refine/questions.rs`, `record`, `crates/baley/src/questions/record.rs`, `open` and `abandon`); `bal-rounds` at version 2 tells the session to submit them so, and `bal-context` walks the session through a story's rounds. A close over MCP returns the story's drafting order, and a close at the terminal issues none (`crates/baley/src/questions/answer.rs`, `receipt_value`). `plan submit` (Build 4 T9) will open a plan draft's set the same way. The parked engine's owner questions, gate records answered by `execution-authorize` with any non-blank owner and time (`crates/baley/src/execution_service.rs`, `native_answer`), stay unreachable: the session server answers that operation as unavailable (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`) until Build 5 | | HST-R10 | Built | The owner reader takes `owner.name` from the global settings and, only when it is absent, git's `user.name` through the registered owner-identity git caller with its 60 second deadline, refusing `owner-identity-missing` with the fix when neither gives a name (`crates/baley/src/providers/identity.rs`, `OWNER_IDENTITY_MISSING`, `OWNER_NAME`, `name_launch`, `owner`, `owner_name` and `judge`, `crates/baley/src/git_process.rs`, `deadline`). `baley scope approve` reads it after the policy step and records the approval with actor `owner`, that name and the time Baley's clock gave the command, with no caller (`crates/baley/src/scope/command.rs`, `approve`, `approve_command` and `owner_command`, `crates/baley/src/scope/approve.rs`, `record`). `baley story truths approve` reads it the same way and records `story.refined` with actor `owner`, that name and Baley's time, with no caller (`crates/baley/src/refine/command.rs`, `approve`, `crates/baley/src/refine/approve.rs`, `record`). `baley questions answer` reads the owner the same way after the policy step and records its call with actor `owner` and no caller, and `questions-answer` reads it from the policy its step recorded and puts the name in each answer and deferral it records as Baley's (HST-R9). The provider acknowledgement reads the owner through the same reader (`crates/baley/src/config_command/interview/providers.rs`, `stage`). No MCP operation approves, scope or truths: `scope-approve` is not a `baley_apply` spelling, so a call naming it is refused `unknown-operation` (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`). The interview asks no `owner.name` question, and no MCP shape carries an owner or a time | -| HST-R11 | Partly built | The compiled registry gives every instruction an identity, a version and a SHA-256 hash pinned beside its text (`crates/baley/src/instruction/mod.rs`, `ENTRIES`, `crates/baley/src/instruction/rounds.rs`, `crates/baley/src/help/front_door.rs`, `IDENTITY`, `VERSION` and `HASH`, `crates/baley/src/instruction/read_contract.rs`, `IDENTITY`, `VERSION` and `HASH`, `crates/baley/src/instruction/capture.rs`, `IDENTITY`, `VERSION` and `HASH`, `crates/baley/src/instruction/scope.rs`, `PROJECT_IDENTITY`, `PROJECT_VERSION` and `PROJECT_HASH`, `crates/baley/src/instruction/start.rs`, `PLANNER_IDENTITY`, `PLANNER_VERSION`, `PLANNER_HASH`, `SURVEY_IDENTITY`, `SURVEY_VERSION` and `SURVEY_HASH`). A test fails when a text changes without its version and hash (`crates/baley/src/instruction/tests.rs`, `SERVED_EVER` and `a_served_text_changed_without_its_pinned_hash_or_a_new_version_row_fails`). The lookup reads no file, environment variable or setting (`crates/baley/src/instruction/mod.rs`, `lookup`). `bal-help`, `bal-read-contract`, `bal-capture`, the five scope front doors `bal-project`, `bal-scope`, `bal-phase`, `bal-story` and `bal-backlog`, `bal-context`, the start order's `bal-start-planner` and `bal-start-survey`, the analyzer orders' `bal-analyzer-questions` and `bal-analyzer-drafting`, and the rounds relay's `bal-rounds` at version 2, the last four with no help row, are served (`crates/baley/src/instruction/context.rs`, `crates/baley/src/instruction/analyzer.rs`, `QUESTIONS_IDENTITY` and `DRAFTING_IDENTITY`), and every other front door answers unavailable naming its build (`crates/baley/src/instruction/mod.rs`, `ENTRIES`). `bal-read-contract` is served at version 2, which names the `document` read of a capture (`crates/baley/src/instruction/read_contract.rs`, `VERSION` and `TEXT`). The caller has a place for each instruction's identity, version and hash (`crates/baley-store/src/caller.rs`, `InstructionEvidence`), and the registry turns a session's identity into instruction evidence carrying its own version and hash (`crates/baley/src/instruction/mod.rs`, `evidence`). `capture`, `project-start`, `work-order-fail`, `work-order-retry` and `story-refine` attach that evidence before handing their caller to preparation, so every event of the call carries it (`crates/baley/src/mcp/capture.rs`, `judge_arguments`, `evidenced`, `Prepare`, `prepare_capture` and `serve`, `crates/baley/src/mcp/work_order.rs`, `evidenced`). A start order records the evidence of `bal-start-planner`, then of `bal-start-survey` when the checkout holds code, in its `instructions` (`crates/baley/src/mcp/work_order.rs`, `issue_start_order`, `crates/baley-core/src/work_order/event.rs`, `issued_payload`), and a retry records the registry's current evidence for each instruction its parent listed (`crates/baley/src/mcp/work_order.rs`, `issue_retry`). A story's analyzer order records the evidence of `bal-analyzer-questions` or `bal-analyzer-drafting` (`crates/baley/src/refine/order.rs`, `issue`). A `scope-submit` naming the order reads that evidence from the order and puts it on its command's caller, so the draft's events carry the order and the instructions the worker followed, and `story-questions-submit` and `context-submit` do the same with an analyzer order's (`crates/baley/src/mcp/refine.rs`, `serve_questions` and `serve_context`, `crates/baley/src/scope/submit.rs`, `start_order_check` and `order_evidence`, `crates/baley/src/mcp/scope.rs`, `bind_instructions`). The change operations take no `instruction`, and their front doors' texts tell the session to send none. `bal-help`, at version 3, and the help answer's `request` ask for `bal-help` as `instruction` only on `capture`, `project-start`, `story-refine`, `work-order-fail` and `work-order-retry`, and never on a `baley_query` call (`crates/baley/src/help/front_door.rs`, `TEXT`, `crates/baley/src/help/table.rs`, `REQUEST`), and a test fails when either names a `baley_apply` operation whose shape refuses the field (`crates/baley/src/help/table.rs`, `tests::a_help_text_asking_for_instruction_on_an_operation_whose_shape_refuses_it_is_caught`). The skill stub manifest renders from the registry and the help table, with each stub's SHA-256, and reads no file (`crates/baley/src/host_artifacts/stubs.rs`, `front_doors`, `render`, `Kind`, `Entry`, `DuplicateIdentity` and `manifest`). The other front doors' texts and writes are their builds' | +| HST-R11 | Partly built | The compiled registry gives every instruction an identity, a version and a SHA-256 hash pinned beside its text (`crates/baley/src/instruction/mod.rs`, `ENTRIES`, `crates/baley/src/instruction/rounds.rs`, `crates/baley/src/help/front_door.rs`, `IDENTITY`, `VERSION` and `HASH`, `crates/baley/src/instruction/read_contract.rs`, `IDENTITY`, `VERSION` and `HASH`, `crates/baley/src/instruction/capture.rs`, `IDENTITY`, `VERSION` and `HASH`, `crates/baley/src/instruction/scope.rs`, `PROJECT_IDENTITY`, `PROJECT_VERSION` and `PROJECT_HASH`, `crates/baley/src/instruction/start.rs`, `PLANNER_IDENTITY`, `PLANNER_VERSION`, `PLANNER_HASH`, `SURVEY_IDENTITY`, `SURVEY_VERSION` and `SURVEY_HASH`). A test fails when a text changes without its version and hash (`crates/baley/src/instruction/tests.rs`, `SERVED_EVER` and `a_served_text_changed_without_its_pinned_hash_or_a_new_version_row_fails`). The lookup reads no file, environment variable or setting (`crates/baley/src/instruction/mod.rs`, `lookup`). `bal-help`, `bal-read-contract`, `bal-capture`, the five scope front doors `bal-project`, `bal-scope`, `bal-phase`, `bal-story` and `bal-backlog`, `bal-context`, the start order's `bal-start-planner` and `bal-start-survey`, the analyzer orders' `bal-analyzer-questions` and `bal-analyzer-drafting`, the rounds relay's `bal-rounds` at version 2, and the planning order's `bal-phase-planner`, the last six with no help row, are served (`crates/baley/src/instruction/context.rs`, `crates/baley/src/instruction/analyzer.rs`, `QUESTIONS_IDENTITY` and `DRAFTING_IDENTITY`, `crates/baley/src/instruction/planner.rs`, `IDENTITY`, `VERSION` and `HASH`), and every other front door answers unavailable naming its build (`crates/baley/src/instruction/mod.rs`, `ENTRIES`). `bal-plan`'s text is compiled (`crates/baley/src/instruction/plan.rs`, `TEXT`) while its entry answers unavailable until Build 4 T9 serves it. `bal-read-contract` is served at version 2, which names the `document` read of a capture (`crates/baley/src/instruction/read_contract.rs`, `VERSION` and `TEXT`). The caller has a place for each instruction's identity, version and hash (`crates/baley-store/src/caller.rs`, `InstructionEvidence`), and the registry turns a session's identity into instruction evidence carrying its own version and hash (`crates/baley/src/instruction/mod.rs`, `evidence`). `capture`, `project-start`, `work-order-fail`, `work-order-retry` and `story-refine` attach that evidence before handing their caller to preparation, so every event of the call carries it (`crates/baley/src/mcp/capture.rs`, `judge_arguments`, `evidenced`, `Prepare`, `prepare_capture` and `serve`, `crates/baley/src/mcp/work_order.rs`, `evidenced`). A start order records the evidence of `bal-start-planner`, then of `bal-start-survey` when the checkout holds code, in its `instructions` (`crates/baley/src/mcp/work_order.rs`, `issue_start_order`, `crates/baley-core/src/work_order/event.rs`, `issued_payload`), and a retry records the registry's current evidence for each instruction its parent listed (`crates/baley/src/mcp/work_order.rs`, `issue_retry`). A story's analyzer order records the evidence of `bal-analyzer-questions` or `bal-analyzer-drafting` (`crates/baley/src/refine/order.rs`, `issue`). A `scope-submit` naming the order reads that evidence from the order and puts it on its command's caller, so the draft's events carry the order and the instructions the worker followed, and `story-questions-submit` and `context-submit` do the same with an analyzer order's (`crates/baley/src/mcp/refine.rs`, `serve_questions` and `serve_context`, `crates/baley/src/scope/submit.rs`, `start_order_check` and `order_evidence`, `crates/baley/src/mcp/scope.rs`, `bind_instructions`). The change operations take no `instruction`, and their front doors' texts tell the session to send none. `bal-help`, at version 3, and the help answer's `request` ask for `bal-help` as `instruction` only on `capture`, `project-start`, `story-refine`, `work-order-fail` and `work-order-retry`, and never on a `baley_query` call (`crates/baley/src/help/front_door.rs`, `TEXT`, `crates/baley/src/help/table.rs`, `REQUEST`), and a test fails when either names a `baley_apply` operation whose shape refuses the field (`crates/baley/src/help/table.rs`, `tests::a_help_text_asking_for_instruction_on_an_operation_whose_shape_refuses_it_is_caught`). The skill stub manifest renders from the registry and the help table, with each stub's SHA-256, and reads no file (`crates/baley/src/host_artifacts/stubs.rs`, `front_doors`, `render`, `Kind`, `Entry`, `DuplicateIdentity` and `manifest`). The other front doors' texts and writes are their builds' | | HST-R12 | Partly built | The skill stub content and manifest are built from the help table and the registry, eight stubs in all (`crates/baley/src/host_artifacts/stubs.rs`, `front_doors`, `render`, `Kind`, `Entry`, `DuplicateIdentity` and `manifest`), and the thirty agent stubs from the role, rung and name tables, each with `name`, `description`, `model: inherit`, the rung's `effort` and `mcpServers` naming `baley`, then the one-line `document` call for the order (`crates/baley/src/host_artifacts/agents.rs`, `render` and `manifest`). Install, the guard and the doctor read one manifest, the skill stubs then the agent stubs (`crates/baley/src/host_artifacts/stubs.rs`, `installed_manifest`, `crates/baley/src/install/command.rs`, `manifest`, `crates/baley/src/guard_hook/context.rs`, `manifest`, `crates/baley/src/host_doctor/mod.rs`, `manifest`), and a stub's kind sets its path, `skills//SKILL.md` or `agents/.md` under the Claude folder (`crates/baley/src/host_artifacts/installed.rs`, `stub_path`). The placement map projects the stub paths into the files the doctor expects and the protected list, which names each agent file and never the `agents` folder (`crates/baley/src/host_artifacts/placement.rs`, `PlacementMap::expected_files`, `PlacementMap::protected_paths` and `PlacementMap::write_only_folders`). `baley install` writes the stubs through the digest-checked replacement. It replaces one only when its bytes equal this binary's render or a hash the install record holds for that identity, and refuses the whole install otherwise (`crates/baley/src/install/stubs.rs`, `judge`, `crates/baley/src/install/plan.rs`, `judge`, `crates/baley/src/install/apply.rs`, `write_files`). It removes a stub this binary no longer ships, recorded at its own skill or agent path, when the file still holds the recorded bytes, keeps the record entry of one it cannot read or that is recorded anywhere else, and leaves any other file there as the owner's (`crates/baley/src/install/plan.rs`, `Retired`, `RetiredStubs`, `retired`, `Retiring`, `retiring` and `judge`, `crates/baley/src/install/apply.rs`, `run`, `crates/baley/src/replace.rs`, `remove`). The guard's protected list holds each placed stub, derived from the environment and passed at `guard_hook::context::judge` (`crates/baley/src/guard_hook/context.rs`, `judge`). The doctor compares a placed stub byte for byte with the manifest and reports both digests when it differs, as an older stub Baley placed when the record holds that digest for the identity (`crates/baley/src/host_doctor/placed.rs`, `StubJudgement`, `stub` and `RegistrationJudgement`, `crates/baley/src/host_doctor/mod.rs`, `recorded_hashes`, `differing_stub` and `judge`), over a map built from the install record, so a stub the record does not list is reported as not installed (`crates/baley/src/host_doctor/mod.rs`, `installed_placements`). `baley artifact stub ` prints a skill stub's manifest bytes (`crates/baley/src/host_artifacts/command.rs`, `select`). The inherited render commands still print full skills (`crates/baley/src/main.rs`, the render arms of `run_command`). The effort table and the route records are built ([0003](0003-configuration-and-routing.md), CFG-R15). A new session answered that it listed both installed stubs of that build, and a session started before the install reported listing them at its next turn. These are the sessions' own answers: the host showed only a count of skills and no file, ledger row or receipt shows the list, so whether Claude Code finds a newly written stub in a running session is unverified (sheet `spikes/host-matrix/install-live-2026-10-11-run1.md`, `#inst.after.stubs`, `#inst.old-session.stub`, `#inst.old-session.server`). Before an install rerun from a newer version the doctor named a stub the new manifest no longer ships as stale, and install replaced the changed stub (`#rerun.doctor-stale`, `#rerun.receipt`). In the repeat install also removed the retired stub's file and left its empty folder (`spikes/host-matrix/install-live-2026-10-11-run2.md` `#rerun.dropped-stub-file`). No live session has loaded the agent stubs, the five scope skill stubs or `bal-context`'s yet. Whether Claude Code accepts the agent frontmatter, runs a stub at its `effort`, and takes the Agent tool's `model` parameter over `model: inherit` is Build 4 T15's live acceptance, and unverified until then. | | HST-R13 | Built | The initialize instructions are one line naming `help` (`crates/baley/src/mcp/tools.rs`, `INSTRUCTIONS` and `info`, asserted by `the_instructions_are_one_short_line_naming_help` in `crates/baley/src/mcp/tools.rs`) | | HST-R14 | Built | An issued order's receipt carries its id, the agent stub for its route, the one-line prompt naming the id and the launch sentence, which names the route's model as the Agent tool's `model` parameter or says to pass none so `model: inherit` applies (`crates/baley/src/work_order/issue.rs`, `prompt`, `launch` and `record`). `project-start`, `work-order-retry` and `story-refine` answer with it, `story-refine`'s adding `analyzer`, and a closing `questions-answer` and an empty set's `story-questions-submit` carry a drafting order's as `drafting` (`crates/baley/src/refine/order.rs`, `issue`, `crates/baley/src/mcp/work_order.rs`, `issue_start_order`, `serve_start` and `issue_retry`). The worker reads its order by the id through `document` (`crates/baley/src/mcp/document.rs`, `work_order_answer`), and nothing the session sends changes a recorded order. The parked engine's dispatch answer of an id and a route, never a prompt (`crates/baley/src/execution/boundary.rs`, `Success`, `ExecutionEnvelope` and `DispatchIdentities`), stays until Build 9, and `execute-next` answers unavailable (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS`, its `execute-next` entry) until Build 5. Whether a live session launches the stub as the sentence says is Build 4 T15's live acceptance | From 53f01eb8b131df862b9f376cc97f4145c864f99c Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 30 Oct 2026 17:15:24 -0400 Subject: [PATCH 24/26] docs(8-4): show build 4 t7 merged and t8 in progress The roadmap's status, Figure 5 and task table move T7 to merged as #296 and T8 to in progress, the Cadence sources line names v3.9.0 for T8's planner and bal-plan texts, and a T8 paragraph says what the plan judge and the planner's served text deliver. --- docs/roadmap.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 3502bd94..310fb2cb 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap -This file is the order of work from now to Baley's first public release: nine builds, then the release design, a live acceptance run on Claude Code, and publishing. Status is Build 2 complete, Build 3 T1 to T17 merged (T17 is [#262](https://github.com/jcrenshaw-dev/baley/pull/262)) with [#24](https://github.com/jcrenshaw-dev/baley/issues/24) open for what T17 left open, Build 4 T1 merged ([#268](https://github.com/jcrenshaw-dev/baley/pull/268)), Build 4 T2 merged ([#271](https://github.com/jcrenshaw-dev/baley/pull/271)), Build 4 T3 merged ([#276](https://github.com/jcrenshaw-dev/baley/pull/276)), Build 4 T4 merged ([#282](https://github.com/jcrenshaw-dev/baley/pull/282)), Build 4 T5 merged ([#290](https://github.com/jcrenshaw-dev/baley/pull/290)), Build 4 T6 merged ([#292](https://github.com/jcrenshaw-dev/baley/pull/292)), and Build 4 T7 in progress on this branch, based on main `397fa9fe`, dated 2026-10-23, taken from the GitHub issues, milestones and pull requests of jcrenshaw-dev/baley and from the [design documents](design/) and [decision records](adr/). No issue, milestone or design document gives a date, so this file shows order only. The plan re-check design [#134](https://github.com/jcrenshaw-dev/baley/issues/134) is recorded as landed on 2026-10-06 in [ADR 0037](adr/0037-plan-recheck-scope.md); its implementation belongs to Builds 4 and 5. The integration check design [#229](https://github.com/jcrenshaw-dev/baley/issues/229) is recorded as landed on 2026-10-08 in [ADR 0042](adr/0042-mocked-boundary-integration-checks.md); its implementation belongs to Builds 4 and 5. The repository upkeep design [#47](https://github.com/jcrenshaw-dev/baley/issues/47) is recorded as landed on 2026-10-06 in [0015](design/0015-repository-upkeep-and-build-gate.md); its remaining implementation belongs to #54, while UPK-R2 is implemented by [Build 3 delivery tasks T14 to T17](#build-3-hosts) ([#24](https://github.com/jcrenshaw-dev/baley/issues/24)). The delivery and credential designs are recorded as landed on 2026-10-06 in [ADR 0038](adr/0038-installer-and-opt-in-updates.md) and [ADR 0039](adr/0039-session-owned-provider-credentials.md). Build 3 T17 is merged. Its installed run is recorded in `spikes/host-matrix` (`install-live-2026-10-11-run1.md` and a repeat of the install rerun, `install-live-2026-10-11-run2.md`), and what the run left open is listed in the Build 3 table and notes below, so Build 3 is not complete. Build 4 ([#25](https://github.com/jcrenshaw-dev/baley/issues/25)) T2 removed the built key reader, `baley exec --key` and the HTTPS model lister ([#271](https://github.com/jcrenshaw-dev/baley/pull/271)). Each build pull request updates this roadmap. +This file is the order of work from now to Baley's first public release: nine builds, then the release design, a live acceptance run on Claude Code, and publishing. Status is Build 2 complete, Build 3 T1 to T17 merged (T17 is [#262](https://github.com/jcrenshaw-dev/baley/pull/262)) with [#24](https://github.com/jcrenshaw-dev/baley/issues/24) open for what T17 left open, Build 4 T1 merged ([#268](https://github.com/jcrenshaw-dev/baley/pull/268)), Build 4 T2 merged ([#271](https://github.com/jcrenshaw-dev/baley/pull/271)), Build 4 T3 merged ([#276](https://github.com/jcrenshaw-dev/baley/pull/276)), Build 4 T4 merged ([#282](https://github.com/jcrenshaw-dev/baley/pull/282)), Build 4 T5 merged ([#290](https://github.com/jcrenshaw-dev/baley/pull/290)), Build 4 T6 merged ([#292](https://github.com/jcrenshaw-dev/baley/pull/292)), Build 4 T7 merged ([#296](https://github.com/jcrenshaw-dev/baley/pull/296)), and Build 4 T8 in progress on this branch, based on main `779f4687`, dated 2026-10-30, taken from the GitHub issues, milestones and pull requests of jcrenshaw-dev/baley and from the [design documents](design/) and [decision records](adr/). No issue, milestone or design document gives a date, so this file shows order only. The plan re-check design [#134](https://github.com/jcrenshaw-dev/baley/issues/134) is recorded as landed on 2026-10-06 in [ADR 0037](adr/0037-plan-recheck-scope.md); its implementation belongs to Builds 4 and 5. The integration check design [#229](https://github.com/jcrenshaw-dev/baley/issues/229) is recorded as landed on 2026-10-08 in [ADR 0042](adr/0042-mocked-boundary-integration-checks.md); its implementation belongs to Builds 4 and 5. The repository upkeep design [#47](https://github.com/jcrenshaw-dev/baley/issues/47) is recorded as landed on 2026-10-06 in [0015](design/0015-repository-upkeep-and-build-gate.md); its remaining implementation belongs to #54, while UPK-R2 is implemented by [Build 3 delivery tasks T14 to T17](#build-3-hosts) ([#24](https://github.com/jcrenshaw-dev/baley/issues/24)). The delivery and credential designs are recorded as landed on 2026-10-06 in [ADR 0038](adr/0038-installer-and-opt-in-updates.md) and [ADR 0039](adr/0039-session-owned-provider-credentials.md). Build 3 T17 is merged. Its installed run is recorded in `spikes/host-matrix` (`install-live-2026-10-11-run1.md` and a repeat of the install rerun, `install-live-2026-10-11-run2.md`), and what the run left open is listed in the Build 3 table and notes below, so Build 3 is not complete. Build 4 ([#25](https://github.com/jcrenshaw-dev/baley/issues/25)) T2 removed the built key reader, `baley exec --key` and the HTTPS model lister ([#271](https://github.com/jcrenshaw-dev/baley/pull/271)). Each build pull request updates this roadmap. ## The path to the first release @@ -266,9 +266,11 @@ Build 4 T6 builds question sets and their rounds. A question set is judged whole Build 4 T7 refines a story before it is planned. `story-refine` on `baley_apply` issues the analyzer's questions order for a story and, once the story's question set is closed, its drafting order. A story keeps one live analyzer order: a `story-refine` while one is pending is refused `analyzer-order-pending`, naming it, and one while a question of the story's set is open is refused `question-open`, each with nothing recorded. The session submits the analyzer's questions as returned with `story-questions-submit`, which opens the story's set and abandons its earlier, closed one. The answer that closes the set over MCP returns the drafting order, and an empty set's submit returns it at once; a close at the terminal issues none, and the session's next `story-refine` does. The session submits the drafted truths with `context-submit`, recorded as a `record` draft once each truth passes its form and its two attestations, and the owner approves the draft by its digest at the terminal with `baley story truths approve`, which records `story.refined` with the question set, the digest and the story's whole truth list, each truth with its version. No MCP operation approves truths ([ADR 0044](adr/0044-owner-acts-on-the-command-line.md)). An unchanged truth keeps its version, a changed one gets the next, a new one starts at 1, and an id added back continues past its highest earlier version. A story's refinement, the approved description, its roadmap entry and phase, and its truths with every kept version, is read as `context-intake`, as the `document` kind `refinement` and with `baley story refinement`, and none of them records anything. The backlog shows each story as unrefined, questions open with the current round, drafting or refined, worked out when read. The analyzer's questions and drafting texts and the `bal-context` front door are ported from Cadence `v3.9.0` ([ADR 0048](adr/0048-port-what-cadence-hands-agents.md)), and the rounds relay `bal-rounds` goes to version 2 with the step that submits the analyzer's questions. The new `truths` view raises the view set to 13. +Build 4 T8 judges a submitted plan whole, as pure core, before anything records it, over plain values the planning operations supply: the phase's committed stories with their current truths, the evidence items of its approved plans, its size and its capacity. A plan is typed content: an unknown key, a wrong type, or a member Baley writes at approval (the plan number, the question set, the size and the suite) is refused `typed-content` naming the entry by its path, as is a lease entry that is not a plain relative path, a lease entry given twice, more than 256 declarations, or `files: []` with no directories. A task file outside the lease is refused `lease`, and the `questions` field goes through the question set judge with its own codes. Each evidence item names its story, truth and version, and each check its `level` (`unit` or `integration`), `boundary` and `fakes` ([ADR 0042](adr/0042-mocked-boundary-integration-checks.md)), a blank boundary being refused `check-boundary`. Coverage and one check per truth version are judged over the phase with its approved plans' items, a truth a person must see proven (`human_verify`) needs an observation item (`truth-without-observation`), and `over-capacity` counts each plan's tasks once and names every story the plan serves and the size the phase would reach. The planner's text is served as `bal-phase-planner` with design 0005's test derivation rules and the default test style, and holds no number but the grammar limits. The `bal-plan` front door is ported from Cadence `v3.9.0` ([ADR 0048](adr/0048-port-what-cadence-hands-agents.md)) and is served by T9 with its operations. + - Designs: [0001 evidence ledger](design/0001-evidence-ledger.md), [0002 system design](design/0002-system-design.md), [0003 configuration and routing](design/0003-configuration-and-routing.md), [0004 starting a project and changing scope](design/0004-starting-a-project-and-changing-scope.md), [0005 context, plans and acceptance](design/0005-context-plans-and-acceptance.md), [0008 review](design/0008-review.md), [0009 risk](design/0009-risk.md), [0012 host interface](design/0012-host-interface.md), [0014 support families](design/0014-support-families.md) - ADRs: [0013 host session calls outside models](adr/0013-host-session-calls-outside-models.md), [0017 stories and sprints](adr/0017-stories-and-sprints.md), [0019 reviews adjudicated and ruled](adr/0019-reviews-adjudicated-and-ruled.md), [0030 question rounds](adr/0030-question-rounds.md), [0031 one term per concept](adr/0031-one-term-per-concept.md), [0037 plan re-check scope](adr/0037-plan-recheck-scope.md), [0039 session-owned provider credentials](adr/0039-session-owned-provider-credentials.md), [0042 mocked-boundary integration checks](adr/0042-mocked-boundary-integration-checks.md), [0043 submissions recorded as drafts](adr/0043-submissions-recorded-as-drafts.md), [0044 owner acts on the command line](adr/0044-owner-acts-on-the-command-line.md), [0045 project start from a session](adr/0045-project-start-from-a-session.md), [0046 agent stubs per role and rung](adr/0046-agent-stubs-per-role-and-rung.md), [0047 owner acts relayed by a session](adr/0047-owner-acts-relayed-by-a-session.md) -- Cadence sources ([ADR 0048](adr/0048-port-what-cadence-hands-agents.md)), each from the Cadence release current when its task is planned: T7's analyzer texts from `skills/cad-assumptions-analyzer-contract/SKILL.md` and `cadence-core/workflows/context.md`, and its `bal-context` from `skills/cad-context/SKILL.md` and the same `context.md`, all at Cadence `v3.9.0`; T8's planner text from `skills/cad-planner-contract/SKILL.md`, `cadence-core/workflows/plan.md` and `cadence-core/templates/PLAN.md`; T10's checker text from `skills/cad-plan-checker-contract/SKILL.md`; T11's lease risk from `planning.mjs risk-check` and `cadence-core/references/risk-surface.md`; T13's reviewer text from `skills/cad-reviewer-contract/SKILL.md`, `cadence-core/references/reviewer-brief.md` and `cadence-core/references/review-triggers.md`; T14's adjudication and rulings from `planning.mjs adjudication`, `cadence-core/references/triage-gate.md` and `cadence-core/references/review-record.md`; the front doors `bal-plan`, `bal-review`, `bal-plan-review`, `bal-decision-review` and `bal-minimalism-review` from `/cad-plan`, `fire()` in `review-triggers.md`, `/cad-plan-review`, `/cad-decision-review` and `/cad-minimalism-review` +- Cadence sources ([ADR 0048](adr/0048-port-what-cadence-hands-agents.md)), each from the Cadence release current when its task is planned: T7's analyzer texts from `skills/cad-assumptions-analyzer-contract/SKILL.md` and `cadence-core/workflows/context.md`, and its `bal-context` from `skills/cad-context/SKILL.md` and the same `context.md`, all at Cadence `v3.9.0`; T8's planner text from `skills/cad-planner-contract/SKILL.md`, `cadence-core/workflows/plan.md` and `cadence-core/templates/PLAN.md`, and its `bal-plan` text from `skills/cad-plan/SKILL.md` and the same `plan.md`, all at Cadence `v3.9.0`; T10's checker text from `skills/cad-plan-checker-contract/SKILL.md`; T11's lease risk from `planning.mjs risk-check` and `cadence-core/references/risk-surface.md`; T13's reviewer text from `skills/cad-reviewer-contract/SKILL.md`, `cadence-core/references/reviewer-brief.md` and `cadence-core/references/review-triggers.md`; T14's adjudication and rulings from `planning.mjs adjudication`, `cadence-core/references/triage-gate.md` and `cadence-core/references/review-record.md`; the front doors `bal-plan`, `bal-review`, `bal-plan-review`, `bal-decision-review` and `bal-minimalism-review` from `/cad-plan`, `fire()` in `review-triggers.md`, `/cad-plan-review`, `/cad-decision-review` and `/cad-minimalism-review` - Carries: [#40](https://github.com/jcrenshaw-dev/baley/issues/40), [#68](https://github.com/jcrenshaw-dev/baley/issues/68), [#69](https://github.com/jcrenshaw-dev/baley/issues/69), [#72](https://github.com/jcrenshaw-dev/baley/issues/72) - Blocked by: Build 3 ([#24](https://github.com/jcrenshaw-dev/baley/issues/24)) @@ -328,9 +330,9 @@ flowchart TD classDef progress fill:#9a6700,stroke:#7d4e00,color:#ffffff classDef planned fill:#eaeef2,stroke:#6e7781,color:#24292f class B3T15,B3T16,B3T17 done - class T1,T2,T3,T4,T5,T6 done - class T7 progress - class T8,T9,T10,T11,T12,T13,T14,T15 planned + class T1,T2,T3,T4,T5,T6,T7 done + class T8 progress + class T9,T10,T11,T12,T13,T14,T15 planned ``` Figure 5. Build 4's tasks. Arrows point from a task to what waits on it, and a dotted arrow is a wait on a Build 3 task. Build 3 T14 to T17 are merged ([#250](https://github.com/jcrenshaw-dev/baley/pull/250), [#253](https://github.com/jcrenshaw-dev/baley/pull/253), [#257](https://github.com/jcrenshaw-dev/baley/pull/257), [#262](https://github.com/jcrenshaw-dev/baley/pull/262)). One pull request per Build 4 task. @@ -343,8 +345,8 @@ Figure 5. Build 4's tasks. Arrows point from a task to what waits on it, and a d | T4 | Scope changes | [#282](https://github.com/jcrenshaw-dev/baley/pull/282) | Merged | | T5 | Routing, work orders and the first dispatch | [#290](https://github.com/jcrenshaw-dev/baley/pull/290) | Merged | | T6 | Question sets and rounds | [#292](https://github.com/jcrenshaw-dev/baley/pull/292) | Merged | -| T7 | Refinement and versioned truths | | In progress | -| T8 | Plan grammar, evidence map and the planner's rules | | Planned | +| T7 | Refinement and versioned truths | [#296](https://github.com/jcrenshaw-dev/baley/pull/296) | Merged | +| T8 | Plan grammar, evidence map and the planner's rules | | In progress | | T9 | Phase planning, drafts and plan approval | | Planned | | T10 | The plan checker and re-check scope | | Planned | | T11 | Risk at plan submit and git facts in the transaction | | Planned | From 0850fcd8077f2150baa82480c0d68b2235ac5f13 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 30 Oct 2026 17:41:12 -0400 Subject: [PATCH 25/26] docs(8-4): let a unit of work carry one or more verify commands The Terms row said a task has one verify command, while PLN-R11, the tasks record and the core task judge allow one or more. --- docs/design/0005-context-plans-and-acceptance.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/0005-context-plans-and-acceptance.md b/docs/design/0005-context-plans-and-acceptance.md index c04e0c4e..1241385a 100644 --- a/docs/design/0005-context-plans-and-acceptance.md +++ b/docs/design/0005-context-plans-and-acceptance.md @@ -44,7 +44,7 @@ In the component view of [0002](0002-system-design.md) (Figure 4) this area is o | Phase | The working increment of the roadmap, defined in [0004](0004-starting-a-project-and-changing-scope.md) (Terms): a goal and the stories committed to it. One phase is active per project (PLN-R7). | | Phase planning | Committing stories to a phase and writing its plans. | | Increment | What a completed phase delivers: something the owner can use, proven by its stories' truths and the suite. | -| Unit of work | One task: one signed commit with one narrowest verify command. | +| Unit of work | One task: one signed commit with one or more verify commands, each the narrowest command that settles the task. | | Size | A story's size counts the tasks of the approved plans that serve it; a phase's size counts each of its approved plans' tasks once, so a plan serving two stories is counted once. | | Capacity | The owner's ceiling on a phase's size, in tasks. | | Velocity | Tasks completed per phase, as a fact shown, never a decision input. | From 3f5efba2782aa86f7a61c4228f07aefe5d883757 Mon Sep 17 00:00:00 2001 From: John Crenshaw Date: Fri, 30 Oct 2026 17:55:50 -0400 Subject: [PATCH 26/26] docs(glossary): count a phase's size per plan, as design 0005 does The glossary still called a phase's size the sum over its stories, which counts a plan serving two stories twice. --- CONTEXT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTEXT.md b/CONTEXT.md index 808d7515..c4789705 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -101,7 +101,7 @@ Two notes on history: | Deferral | The owner's recorded choice to leave a question undecided for now, with a reason ([0005](docs/design/0005-context-plans-and-acceptance.md#2-terms)). | skip, postponement | | Phase planning | Committing stories to a phase and writing its plans ([0005](docs/design/0005-context-plans-and-acceptance.md#2-terms)). | sprint planning | | Increment | What a completed phase delivers: something the owner can use, proven by its truths and the suite ([0005](docs/design/0005-context-plans-and-acceptance.md#2-terms)). | deliverable, release (a release is a tagged version) | -| Size | The number of tasks a story's approved plans need; a phase's size is the sum ([0005](docs/design/0005-context-plans-and-acceptance.md#2-terms)). | estimate, story points | +| Size | A story's size counts the tasks of the approved plans that serve it; a phase's size counts each of its approved plans' tasks once, so a plan serving two stories is counted once ([0005](docs/design/0005-context-plans-and-acceptance.md#2-terms)). | estimate, story points | | Capacity | The owner's ceiling on a phase's size in tasks, `planning.phase_capacity` ([0005](docs/design/0005-context-plans-and-acceptance.md#2-terms)). | budget, sprint capacity | | Velocity | Tasks completed per closed phase, shown as a fact and never used to decide ([0005](docs/design/0005-context-plans-and-acceptance.md#2-terms)). | throughput, speed | | Plan | One typed document for a phase: the stories it serves, its file lease, its tasks, its suite, its evidence map and its questions. A phase may have several ([0005](docs/design/0005-context-plans-and-acceptance.md#2-terms)). | roadmap, spec, PLAN file |