diff --git a/crates/baley-core/src/plan/approval.rs b/crates/baley-core/src/plan/approval.rs new file mode 100644 index 00000000..dc78601a --- /dev/null +++ b/crates/baley-core/src/plan/approval.rs @@ -0,0 +1,489 @@ +//! The judgement of an approval of a plan draft by digest (design 0005 +//! section 5 `plan approve`, PLN-R15, PLN-R26, PLN-R27, D-16). +//! +//! An approval is judged on facts the binary read, in one fixed order, so +//! one approval always gets one answer: the draft, its staleness, an earlier +//! approval, then the draft's question set. Judging the plan again against +//! the phase as it stands is the binary's next step, with `judge_plan`. + +use std::collections::HashSet; + +use baley_store::Hash; +use serde_json::{Value, json}; + +use super::submission::{RecordedPlan, Replaces}; +use crate::questions::SetFacts; +use crate::scope::{DRAFT_APPROVED, PriorApproval, STALE_DRAFT, UNKNOWN_DRAFT}; +use crate::truth::QUESTION_OPEN; + +/// The refusal code for approving a plan draft while an answer of its +/// question set rejected the recommended answer, so the plan does not yet +/// apply it (PLN-R27). +pub const ANSWER_NOT_APPLIED: &str = "answer-not-applied"; + +// The members in the order the plan judge reads them, which is the order a +// stale path is looked for in. +const PLAN: [&str; 10] = [ + "phase", + "stories", + "files", + "directories", + "goal", + "context", + "notes", + "tasks", + "evidence_map", + "questions", +]; +const TASK: [&str; 5] = ["id", "title", "files", "action", "verify"]; +const ITEM: [&str; 7] = [ + "id", + "story", + "truth", + "truth_version", + "kind", + "spec", + "reason", +]; +const ARTIFACT: [&str; 2] = ["path", "record"]; +const LINK: [&str; 3] = ["caller", "callee", "value"]; +const OBSERVATION: [&str; 2] = ["what", "by"]; +const CHECK: [&str; 8] = [ + "command", "expected", "test", "setup", "call", "level", "boundary", "fakes", +]; +const EXPECTED: [&str; 2] = ["kind", "value"]; +const TEST: [&str; 2] = ["file", "function"]; +const QUESTION: [&str; 4] = ["id", "question", "recommended", "depends_on"]; + +/// Why an approval of a plan draft is refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PlanApprovalRefusal { + /// No recorded plan draft has the digest. + UnknownDraft, + /// A newer plan draft of the phase was submitted. `path` names the + /// first part that differs from the newest, such as `tasks[0].title`. + StaleDraft { path: String }, + /// The draft was approved by `owner` at `at` after its latest + /// submission. + DraftApproved { owner: String, at: String }, + /// These questions of the draft's set are neither answered nor + /// deferred, in submitted order. + QuestionOpen { questions: Vec }, + /// These questions' answers rejected the recommended answer, in + /// submitted order. + AnswerNotApplied { questions: Vec }, +} + +impl PlanApprovalRefusal { + /// The refusal's public code. + pub fn code(&self) -> &'static str { + match self { + Self::UnknownDraft => UNKNOWN_DRAFT, + Self::StaleDraft { .. } => STALE_DRAFT, + Self::DraftApproved { .. } => DRAFT_APPROVED, + Self::QuestionOpen { .. } => QUESTION_OPEN, + Self::AnswerNotApplied { .. } => ANSWER_NOT_APPLIED, + } + } + + /// What the refusal names, as its answer's details, or none. + pub fn details(&self) -> Option { + match self { + Self::UnknownDraft => None, + Self::StaleDraft { path } => Some(json!({"path": path})), + Self::DraftApproved { owner, at } => Some(json!({"owner": owner, "at": at})), + Self::QuestionOpen { questions } | Self::AnswerNotApplied { questions } => { + Some(json!({"questions": questions})) + } + } + } +} + +/// A recorded plan draft: its digest and its body read back. +#[derive(Debug, Clone, Copy)] +pub struct DraftRead<'a> { + /// The draft's digest. + pub digest: Hash, + /// The draft's body read back. + pub plan: &'a RecordedPlan, +} + +/// What an approval of one plan draft is judged on. +#[derive(Debug, Clone, Copy)] +pub struct PlanApprovalFacts<'a> { + /// The target draft, or `None` when no `draft` document has its + /// digest. + pub target: Option>, + /// Whether the target's `scope.submitted` was found among the events. + pub recorded: bool, + /// The newest plan draft of the phase, or `None` when none is listed. + pub newest: Option>, + /// The `plan.approved` of this digest recorded after its latest + /// submission, or `None`. + pub approved: Option>, + /// Everything recorded about the target draft's question set. + pub set: &'a SetFacts, +} + +/// Judges an approval of a plan draft in D-16's order: `unknown-draft` +/// when the draft or its event is missing, or no newest draft is listed; +/// `stale-draft` when the newest plan draft of the phase is not this one, +/// with the first differing path; `draft-approved` naming the earlier +/// approval; `question-open` naming every question neither answered nor +/// deferred; and `answer-not-applied` naming every question whose answer +/// rejected its recommendation. A deferral leaves the plan on the +/// recommended answer, so it is never taken for a rejection (PLN-R27). +pub fn judge_plan_approval(facts: &PlanApprovalFacts) -> Result<(), PlanApprovalRefusal> { + let Some(target) = facts.target.filter(|_| facts.recorded) else { + return Err(PlanApprovalRefusal::UnknownDraft); + }; + let Some(newest) = facts.newest else { + return Err(PlanApprovalRefusal::UnknownDraft); + }; + if newest.digest != target.digest { + // A digest is taken over the plan, its kind and its binding, and + // both are plan drafts, so they differ in the plan or the binding. + let path = + difference(target.plan, newest.plan).expect("differing digests differ in content"); + return Err(PlanApprovalRefusal::StaleDraft { path }); + } + if let Some(approved) = facts.approved { + return Err(PlanApprovalRefusal::DraftApproved { + owner: approved.owner.into(), + at: approved.at.into(), + }); + } + let set = facts.set; + let answered: HashSet<&str> = set.answers.iter().map(|a| a.question.as_str()).collect(); + let deferred: HashSet<&str> = set.deferrals.iter().map(|d| d.question.as_str()).collect(); + let open: Vec = set + .questions + .iter() + .map(|question| question.id.as_str()) + .filter(|id| !answered.contains(id) && !deferred.contains(id)) + .map(str::to_owned) + .collect(); + if !open.is_empty() { + return Err(PlanApprovalRefusal::QuestionOpen { questions: open }); + } + let rejected: HashSet<&str> = set + .answers + .iter() + .filter(|answer| !answer.accepted) + .map(|answer| answer.question.as_str()) + .collect(); + let rejected: Vec = set + .questions + .iter() + .map(|question| question.id.as_str()) + .filter(|id| rejected.contains(id)) + .map(str::to_owned) + .collect(); + if !rejected.is_empty() { + return Err(PlanApprovalRefusal::AnswerNotApplied { + questions: rejected, + }); + } + Ok(()) +} + +/// The first part of two plan drafts that differs: `replaces`, then the +/// plan's members in the judge's order. `None` when they are equal. +fn difference(a: &RecordedPlan, b: &RecordedPlan) -> Option { + replaces(a.replaces, b.replaces).or_else(|| { + PLAN.iter().find_map(|&name| { + let (x, y) = (&a.plan[name], &b.plan[name]); + match name { + "tasks" => list(name, x, y, |at, x, y| members(&at, x, y, &TASK)), + "evidence_map" => list(name, x, y, |at, x, y| item(&at, x, y)), + "questions" => list(name, x, y, |at, x, y| members(&at, x, y, &QUESTION)), + _ => leaf(name.into(), x, y), + } + }) + }) +} + +/// The replacement binding's path when the two differ: `replaces` when only +/// one draft holds it, its member otherwise. +fn replaces(a: Option, b: Option) -> Option { + match (a, b) { + (None, None) => None, + (Some(a), Some(b)) if a.plan != b.plan => Some("replaces.plan".into()), + (Some(a), Some(b)) if a.digest != b.digest => Some("replaces.digest".into()), + (Some(_), Some(_)) => None, + _ => Some("replaces".into()), + } +} + +/// The first differing member of two evidence items, looking inside the +/// spec in the order of its kind. The kinds are equal by the time the spec +/// is compared, since `kind` is compared first. +fn item(path: &str, a: &Value, b: &Value) -> Option { + ITEM.iter().find_map(|&name| { + let at = format!("{path}.{name}"); + let (x, y) = (&a[name], &b[name]); + if name != "spec" { + return leaf(at, x, y); + } + match a["kind"].as_str() { + Some("artifact") => members(&at, x, y, &ARTIFACT), + Some("link") => members(&at, x, y, &LINK), + Some("observation") => members(&at, x, y, &OBSERVATION), + Some("check") => CHECK.iter().find_map(|&member| { + let inner = format!("{at}.{member}"); + let (x, y) = (&x[member], &y[member]); + match member { + "expected" => members(&inner, x, y, &EXPECTED), + "test" => members(&inner, x, y, &TEST), + _ => leaf(inner, x, y), + } + }), + _ => leaf(at, x, y), + } + }) +} + +/// The first of `names`, in that order, whose values differ under `path`. +/// A member one value lacks differs from one the other holds. +fn members(path: &str, a: &Value, b: &Value, names: &[&str]) -> Option { + names + .iter() + .find_map(|name| leaf(format!("{path}.{name}"), &a[*name], &b[*name])) +} + +/// `path` when two values differ, looking inside lists entry by entry. +fn leaf(path: String, a: &Value, b: &Value) -> Option { + match (a, b) { + (Value::Array(_), Value::Array(_)) => list(&path, a, b, leaf), + _ => (a != b).then_some(path), + } +} + +/// The first entry `each` finds differing, or the first position only one +/// list holds, or `path` itself when either value is not a list. +fn list( + path: &str, + a: &Value, + b: &Value, + each: impl Fn(String, &Value, &Value) -> Option, +) -> Option { + let (Value::Array(a), Value::Array(b)) = (a, b) else { + return (a != b).then(|| path.to_owned()); + }; + (0..a.len().max(b.len())).find_map(|index| { + let at = format!("{path}[{index}]"); + match (a.get(index), b.get(index)) { + (Some(x), Some(y)) => each(at, x, y), + _ => Some(at), + } + }) +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from D-16, design 0005's refusal + //! table and the plan's test data, never from running this code. + + use serde_json::json; + + use super::*; + use crate::plan::fixtures::{c4, p1, plus, qa, qb, with}; + use crate::questions::{Answer, Deferral, Question}; + + const T: &str = "2026-10-31T09:00:03Z"; + + fn x() -> Hash { + Hash([0x5c; 32]) + } + + fn y() -> Hash { + Hash([0x6d; 32]) + } + + fn p1q() -> Value { + with(p1(), "", "questions", json!([qa(), qb()])) + } + + fn recorded(plan: Value) -> RecordedPlan { + RecordedPlan { + plan, + replaces: None, + } + } + + fn question(value: Value) -> Question { + Question { + id: value["id"].as_str().unwrap().into(), + question: value["question"].as_str().unwrap().into(), + recommended: value["recommended"].as_str().unwrap().into(), + depends_on: value["depends_on"] + .as_array() + .unwrap() + .iter() + .map(|id| id.as_str().unwrap().into()) + .collect(), + } + } + + fn answer(id: &str, accepted: bool) -> Answer { + Answer { + question: id.into(), + answer: if accepted { "Yes" } else { "No" }.into(), + accepted, + round: 1, + owner: "Ada Owner".into(), + at: T.into(), + } + } + + fn deferral(id: &str) -> Deferral { + Deferral { + question: id.into(), + reason: "Decide once the store is chosen.".into(), + round: 1, + owner: "Ada Owner".into(), + at: T.into(), + } + } + + fn set(answers: Vec, deferrals: Vec) -> SetFacts { + SetFacts { + questions: vec![question(qa()), question(qb())], + answers, + deferrals, + abandoned: None, + } + } + + fn answer_of(facts: &PlanApprovalFacts) -> Result<(), (&'static str, Option)> { + judge_plan_approval(facts).map_err(|refusal| (refusal.code(), refusal.details())) + } + + #[test] + fn a_plan_approval_judged_in_another_order_is_caught() { + let target = recorded(p1q()); + let other = recorded(p1()); + let q2_open = set(vec![answer("q1", false)], Vec::new()); + let rejected = set(vec![answer("q1", false), answer("q2", true)], Vec::new()); + let applied = set(vec![answer("q1", true), answer("q2", true)], Vec::new()); + let mut facts = PlanApprovalFacts { + target: Some(DraftRead { + digest: x(), + plan: &target, + }), + recorded: false, + newest: Some(DraftRead { + digest: y(), + plan: &other, + }), + approved: Some(PriorApproval { + owner: "Ada Owner", + at: T, + }), + set: &q2_open, + }; + + assert_eq!(answer_of(&facts), Err(("unknown-draft", None))); + facts.recorded = true; + assert_eq!( + answer_of(&facts), + Err(("stale-draft", Some(json!({"path": "questions[0]"})))) + ); + facts.newest = facts.target; + assert_eq!( + answer_of(&facts), + Err(( + "draft-approved", + Some(json!({"owner": "Ada Owner", "at": T})) + )) + ); + facts.approved = None; + assert_eq!( + answer_of(&facts), + Err(("question-open", Some(json!({"questions": ["q2"]})))) + ); + + facts.set = &rejected; + assert_eq!( + answer_of(&facts), + Err(("answer-not-applied", Some(json!({"questions": ["q1"]})))) + ); + + facts.set = &applied; + assert_eq!(answer_of(&facts), Ok(())); + } + + #[test] + fn a_stale_plan_draft_named_at_the_wrong_path_is_caught() { + let target = recorded(p1()); + let empty = set(Vec::new(), Vec::new()); + let stale = |newest: &RecordedPlan| { + judge_plan_approval(&PlanApprovalFacts { + target: Some(DraftRead { + digest: x(), + plan: &target, + }), + recorded: true, + newest: Some(DraftRead { + digest: y(), + plan: newest, + }), + approved: None, + set: &empty, + }) + }; + let path = |path: &str| Err(PlanApprovalRefusal::StaleDraft { path: path.into() }); + + let retitled = recorded(with(p1(), "/tasks/0", "title", json!("Another"))); + assert_eq!(stale(&retitled), path("tasks[0].title")); + // `goal` comes before `tasks` in the judge's order. + let regoaled = recorded(with( + with(p1(), "", "goal", json!("Another goal.")), + "/tasks/0", + "title", + json!("Another"), + )); + assert_eq!(stale(®oaled), path("goal")); + let extended = recorded(plus(p1(), c4())); + assert_eq!(stale(&extended), path("evidence_map[3]")); + let replacing = RecordedPlan { + plan: p1(), + replaces: Some(Replaces { + plan: 1, + digest: x(), + }), + }; + assert_eq!(stale(&replacing), path("replaces")); + } + + #[test] + fn a_deferral_taken_for_a_rejection_or_an_open_question_missed_is_caught() { + let target = recorded(p1q()); + let draft = DraftRead { + digest: x(), + plan: &target, + }; + let judged = |set: &SetFacts| { + answer_of(&PlanApprovalFacts { + target: Some(draft), + recorded: true, + newest: Some(draft), + approved: None, + set, + }) + }; + + assert_eq!( + judged(&set(vec![answer("q1", true)], vec![deferral("q2")])), + Ok(()) + ); + assert_eq!( + judged(&set(vec![answer("q1", false)], vec![deferral("q2")])), + Err(("answer-not-applied", Some(json!({"questions": ["q1"]})))) + ); + assert_eq!( + judged(&set(Vec::new(), Vec::new())), + Err(("question-open", Some(json!({"questions": ["q1", "q2"]})))) + ); + } +} diff --git a/crates/baley-core/src/plan/commitment.rs b/crates/baley-core/src/plan/commitment.rs new file mode 100644 index 00000000..7f3e971d --- /dev/null +++ b/crates/baley-core/src/plan/commitment.rs @@ -0,0 +1,443 @@ +//! What one `phase-plan` call does with a selection, and whether a plan may +//! be submitted for its phase (design 0005 section 5 `phase plan` and `plan +//! submit`, PLN-R7, PRJ-R4, PRJ-R18, D-01, D-02, D-10, D-11, D-15). +//! +//! The selection's readiness is judged first, then the path: hand over an +//! approved continuation's order, refuse beside a pending planner order, +//! draft a changed selection, issue a due revision, or issue a planning +//! order. The binary reads every fact; nothing here reads a store. + +use serde_json::{Value, json}; + +/// The refusal code for planning a phase while another phase is active; it +/// names that phase (PLN-R7). +pub const PHASE_ACTIVE: &str = "phase-active"; +/// The refusal code for submitting a plan while a phase other than the +/// plan's is active; it names the active phase (D-02). +pub const PHASE_NOT_ACTIVE: &str = "phase-not-active"; +/// The refusal code for a selected story with no approved truth; it names +/// the story (D-10). +pub const STORY_UNREFINED: &str = "story-unrefined"; +/// The refusal code for a selected story committed to another phase; it +/// names the story and that phase (PRJ-R4). +pub const STORY_IN_PHASE: &str = "story-in-phase"; +/// The refusal code for a `phase-plan` while a planner order of the phase +/// is pending; it names that order, since a phase has one live planner +/// order (D-11). +pub const PLANNER_ORDER_PENDING: &str = "planner-order-pending"; + +/// Why a `phase-plan` call is refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CommitmentRefusal { + /// Phase `phase`, another phase, is active. + PhaseActive { phase: u32 }, + /// The roadmap does not hold phase `phase`, or it is withdrawn. + NoSuchPhase { phase: u32 }, + /// The roadmap does not hold story `story`, or it is dropped. + NoSuchStory { story: u32 }, + /// Story `story` holds no approved truth. + StoryUnrefined { story: u32 }, + /// Story `story` is committed to phase `phase`, another phase. + StoryInPhase { story: u32, phase: u32 }, + /// Planner order `work_order` of the phase is pending. + PlannerOrderPending { work_order: String }, +} + +impl CommitmentRefusal { + /// The refusal's public code. + pub fn code(&self) -> &'static str { + match self { + Self::PhaseActive { .. } => PHASE_ACTIVE, + Self::NoSuchPhase { .. } => crate::capture::NO_SUCH_PHASE, + Self::NoSuchStory { .. } => crate::scope::NO_SUCH_STORY, + Self::StoryUnrefined { .. } => STORY_UNREFINED, + Self::StoryInPhase { .. } => STORY_IN_PHASE, + Self::PlannerOrderPending { .. } => PLANNER_ORDER_PENDING, + } + } + + /// What the refusal names, as its answer's details. + pub fn details(&self) -> Value { + match self { + Self::PhaseActive { phase } | Self::NoSuchPhase { phase } => json!({"phase": phase}), + Self::NoSuchStory { story } | Self::StoryUnrefined { story } => { + json!({"story": story}) + } + Self::StoryInPhase { story, phase } => json!({"story": story, "phase": phase}), + Self::PlannerOrderPending { work_order } => json!({"work_order": work_order}), + } + } +} + +/// One selected story as the roadmap and the `truths` view hold it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SelectedStory { + /// Its id. + pub id: u32, + /// Whether the roadmap holds it and it is not dropped. + pub held: bool, + /// The phase it is committed to, `None` when none. + pub phase: Option, + /// Whether it holds an approved truth. + pub refined: bool, +} + +/// What a selection's readiness is judged on. +#[derive(Debug, Clone, Copy)] +pub struct Readiness<'a> { + /// The phase being planned. + pub phase: u32, + /// Whether the roadmap holds the phase and it is not withdrawn. + pub phase_held: bool, + /// The active phases. The phase being planned may be among them. + pub active: &'a [u32], + /// The selection, in order. + pub stories: &'a [SelectedStory], +} + +/// A phase's latest planning continuation. +#[derive(Debug, Clone, Copy)] +pub struct Continuation<'a> { + /// The selection it binds, in order. + pub stories: &'a [u32], + /// The planner order its approval issues. + pub work_order: &'a str, + /// Whether that order is pending. + pub pending: bool, + /// Whether that order was already handed to a session. + pub followed: bool, +} + +/// What one `phase-plan` call is judged on. +#[derive(Debug, Clone, Copy)] +pub struct CommitmentFacts<'a> { + /// The selection and what its readiness needs. + pub readiness: Readiness<'a>, + /// The phase's committed stories, in order. + pub committed: &'a [u32], + /// The phase's pending planner order, if any. + pub pending_order: Option<&'a str>, + /// The phase's latest continuation, if any. + pub continuation: Option>, + /// Whether a revision is due: the phase's current unapproved draft's + /// question set closed with an answer that rejected a recommendation. + pub revision_due: bool, +} + +/// What a ready `phase-plan` call does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PhasePlanPath { + /// Hand over the approved continuation's order `work_order` (D-01). + HandOver { work_order: String }, + /// Draft the selection as a `phase edit` of the phase's stories (D-09). + Draft, + /// Issue the due planner revision order (D-15). + Revision, + /// Issue a planning order for the phase's stories. + Planning, +} + +/// Judges a selection's readiness, the first fault answering in design +/// 0005's order: `phase-active` naming the lowest active phase other than +/// this one, `no-such-phase`, `no-such-story`, `story-unrefined`, then +/// `story-in-phase`, each naming the first selected story at fault. The +/// commitment approval rechecks a continuation with this same rule (D-01). +pub fn judge_readiness(readiness: &Readiness) -> Result<(), CommitmentRefusal> { + let phase = readiness.phase; + if let Some(other) = readiness + .active + .iter() + .copied() + .filter(|p| *p != phase) + .min() + { + return Err(CommitmentRefusal::PhaseActive { phase: other }); + } + if !readiness.phase_held { + return Err(CommitmentRefusal::NoSuchPhase { phase }); + } + let stories = readiness.stories; + if let Some(story) = stories.iter().find(|story| !story.held) { + return Err(CommitmentRefusal::NoSuchStory { story: story.id }); + } + if let Some(story) = stories.iter().find(|story| !story.refined) { + return Err(CommitmentRefusal::StoryUnrefined { story: story.id }); + } + for story in stories { + if let Some(other) = story.phase.filter(|other| *other != phase) { + return Err(CommitmentRefusal::StoryInPhase { + story: story.id, + phase: other, + }); + } + } + Ok(()) +} + +/// Judges one `phase-plan` call: readiness first, then the path. When the +/// selection equals both the phase's stories and the latest continuation's, +/// and that continuation's order is pending and not yet followed, the order +/// is handed over. Otherwise a pending planner order is refused +/// `planner-order-pending`; a selection that differs from the phase's +/// stories, in content or in order, is drafted; a due revision is issued; +/// and otherwise a planning order is. +pub fn judge_commitment(facts: &CommitmentFacts) -> Result { + judge_readiness(&facts.readiness)?; + let selection: Vec = facts.readiness.stories.iter().map(|s| s.id).collect(); + let unchanged = selection == facts.committed; + if let Some(continuation) = facts.continuation + && unchanged + && continuation.stories == selection + && continuation.pending + && !continuation.followed + { + return Ok(PhasePlanPath::HandOver { + work_order: continuation.work_order.to_owned(), + }); + } + if let Some(order) = facts.pending_order { + return Err(CommitmentRefusal::PlannerOrderPending { + work_order: order.to_owned(), + }); + } + if !unchanged { + return Ok(PhasePlanPath::Draft); + } + if facts.revision_due { + return Ok(PhasePlanPath::Revision); + } + Ok(PhasePlanPath::Planning) +} + +/// A plan submitted while another phase is active. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PhaseNotActive { + /// The active phase. + pub phase: u32, +} + +impl PhaseNotActive { + /// Always `phase-not-active`. + pub fn code(&self) -> &'static str { + PHASE_NOT_ACTIVE + } + + /// What the refusal names, as its answer's details. + pub fn details(&self) -> Value { + json!({"phase": self.phase}) + } +} + +/// Judges a plan's phase at submit: refused naming the lowest active phase +/// other than `phase`, and let through when none is active or only `phase` +/// is, so a phase's first plan can be submitted (D-02). +pub fn judge_submit_phase(phase: u32, active: &[u32]) -> Result<(), PhaseNotActive> { + match active.iter().copied().filter(|p| *p != phase).min() { + Some(other) => Err(PhaseNotActive { phase: other }), + None => Ok(()), + } +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005 section 5, D-01, + //! D-02, D-10, D-11, D-15 and the plan's test data, never from running + //! this code. + + use super::*; + + const O: &str = "6a1f0c3e-2b4d-4e5f-8a7b-9c0d1e2f3a4b"; + const O2: &str = "7b2e1d4f-3c5e-4f60-9b8c-0d1e2f3a4b5c"; + + /// A story the roadmap holds, refined and in no phase. + fn ready(id: u32) -> SelectedStory { + SelectedStory { + id, + held: true, + phase: None, + refined: true, + } + } + + /// Phase 1, held, with nothing active, nothing pending, no continuation + /// and no revision due. + fn facts<'a>( + committed: &'a [u32], + stories: &'a [SelectedStory], + active: &'a [u32], + ) -> CommitmentFacts<'a> { + CommitmentFacts { + readiness: Readiness { + phase: 1, + phase_held: true, + active, + stories, + }, + committed, + pending_order: None, + continuation: None, + revision_due: false, + } + } + + #[test] + fn a_selection_judged_in_another_order_is_caught() { + let mut stories = [ + SelectedStory { + held: false, + ..ready(4) + }, + SelectedStory { + held: false, + ..ready(5) + }, + SelectedStory { + refined: false, + ..ready(3) + }, + SelectedStory { + phase: Some(2), + ..ready(2) + }, + ]; + let mut active = vec![2]; + let mut held = false; + let judged = |stories: &[SelectedStory], active: &[u32], held: bool| { + let mut facts = facts(&[1], stories, active); + facts.readiness.phase_held = held; + judge_commitment(&facts) + }; + assert_eq!( + judged(&stories, &active, held), + Err(CommitmentRefusal::PhaseActive { phase: 2 }) + ); + active.clear(); + let refusal = judged(&stories, &active, held).unwrap_err(); + assert_eq!(refusal, CommitmentRefusal::NoSuchPhase { phase: 1 }); + assert_eq!(refusal.code(), "no-such-phase"); + held = true; + let refusal = judged(&stories, &active, held).unwrap_err(); + assert_eq!(refusal, CommitmentRefusal::NoSuchStory { story: 4 }); + assert_eq!(refusal.code(), "no-such-story"); + stories[0].held = true; + assert_eq!( + judged(&stories, &active, held), + Err(CommitmentRefusal::NoSuchStory { story: 5 }) + ); + stories[1].held = true; + assert_eq!( + judged(&stories, &active, held), + Err(CommitmentRefusal::StoryUnrefined { story: 3 }) + ); + stories[2].refined = true; + let refusal = judged(&stories, &active, held).unwrap_err(); + assert_eq!( + refusal, + CommitmentRefusal::StoryInPhase { story: 2, phase: 2 } + ); + assert_eq!(refusal.details(), json!({"story": 2, "phase": 2})); + stories[3].phase = None; + assert_eq!(judged(&stories, &active, held), Ok(PhasePlanPath::Draft)); + // The missing story comes later, so judging story by story would + // answer story-unrefined first. + let mixed = [ + SelectedStory { + refined: false, + ..ready(3) + }, + SelectedStory { + held: false, + ..ready(4) + }, + ]; + assert_eq!( + judged(&mixed, &active, held), + Err(CommitmentRefusal::NoSuchStory { story: 4 }) + ); + } + + #[test] + fn a_reordered_selection_issued_without_a_draft_is_caught() { + for (selection, expected) in [ + (vec![2, 1], PhasePlanPath::Draft), + (vec![1], PhasePlanPath::Draft), + (vec![1, 2], PhasePlanPath::Planning), + ] { + let stories: Vec = selection.iter().copied().map(ready).collect(); + assert_eq!( + judge_commitment(&facts(&[1, 2], &stories, &[])), + Ok(expected), + "{selection:?}" + ); + } + } + + #[test] + fn a_second_planner_order_or_a_continuation_order_handed_over_twice_is_caught() { + let judged = |selection: &[u32], continuation: Continuation| { + let stories: Vec = selection.iter().copied().map(ready).collect(); + let mut facts = facts(&[1, 4], &stories, &[]); + facts.pending_order = Some(O); + facts.continuation = Some(continuation); + judge_commitment(&facts) + }; + let latest = Continuation { + stories: &[1, 4], + work_order: O, + pending: true, + followed: false, + }; + let pending = Err(CommitmentRefusal::PlannerOrderPending { + work_order: O.into(), + }); + assert_eq!( + judged(&[1, 4], latest), + Ok(PhasePlanPath::HandOver { + work_order: O.into() + }) + ); + let followed = Continuation { + followed: true, + ..latest + }; + assert_eq!(judged(&[1, 4], followed), pending); + assert_eq!(judged(&[4, 1], latest), pending); + let other = Continuation { + stories: &[1], + work_order: O2, + pending: false, + followed: false, + }; + assert_eq!(judged(&[1, 4], other), pending); + } + + #[test] + fn a_due_revision_skipped_or_issued_beside_a_pending_order_is_caught() { + let stories = [ready(1)]; + let judged = |due: bool, order: Option<&str>| { + let mut facts = facts(&[1], &stories, &[]); + facts.revision_due = due; + facts.pending_order = order; + judge_commitment(&facts) + }; + assert_eq!(judged(true, None), Ok(PhasePlanPath::Revision)); + let refusal = judged(true, Some(O)).unwrap_err(); + assert_eq!( + refusal, + CommitmentRefusal::PlannerOrderPending { + work_order: O.into() + } + ); + assert_eq!(refusal.code(), "planner-order-pending"); + assert_eq!(judged(false, None), Ok(PhasePlanPath::Planning)); + } + + #[test] + fn a_submit_refused_for_its_own_active_phase_or_let_through_beside_another_is_caught() { + assert_eq!(judge_submit_phase(1, &[]), Ok(())); + assert_eq!(judge_submit_phase(1, &[1]), Ok(())); + let refusal = judge_submit_phase(1, &[2]).unwrap_err(); + assert_eq!(refusal, PhaseNotActive { phase: 2 }); + assert_eq!(refusal.code(), "phase-not-active"); + } +} diff --git a/crates/baley-core/src/plan/content.rs b/crates/baley-core/src/plan/content.rs index dafdd920..44bd0100 100644 --- a/crates/baley-core/src/plan/content.rs +++ b/crates/baley-core/src/plan/content.rs @@ -75,6 +75,7 @@ pub(super) fn read(value: &Value) -> Result { tasks, evidence_map, questions, + submitted: plan.clone(), }) } diff --git a/crates/baley-core/src/plan/event.rs b/crates/baley-core/src/plan/event.rs new file mode 100644 index 00000000..9babbc13 --- /dev/null +++ b/crates/baley-core/src/plan/event.rs @@ -0,0 +1,259 @@ +//! The four plan events: their types, their registration, their stream and +//! their payloads (design 0005 section 6, design 0001 Streams). +//! +//! Every plan event goes on its phase's stream, `phase/`, the stream a +//! plan draft's question set takes. Owner and time are payload members, as +//! `scope.approved` and `story.refined` carry them. + +use baley_store::{Hash, PayloadRef}; +use serde_json::{Value, json}; + +use crate::registry::{Registry, RegistryError}; + +/// A plan approved, on its phase's stream: `{phase, plan, digest, stories, +/// size, suite, question_set, evidence_map, body, owner, at}`. +/// +/// The evidence map is inline so its view rebuilds from events alone and +/// survives a purge of the draft's body; the plan's text is only the +/// draft's `record` reference, since plan text is an attachment (D-06). +pub const PLAN_APPROVED: &str = "plan.approved"; +/// The current `plan.approved` payload version. +pub const PLAN_APPROVED_VERSION: u32 = 1; +/// A plan replaced, on its phase's stream: `{phase, plan, old_digest, +/// new_digest, owner, at}`, `plan` the old number (D-07). +pub const PLAN_REPLACED: &str = "plan.replaced"; +/// The current `plan.replaced` payload version. +pub const PLAN_REPLACED_VERSION: u32 = 1; +/// A planning continuation, on its phase's stream: `{phase, stories, edit, +/// work_order}`, recorded with the `phase edit` draft it waits on (D-09). +pub const PLAN_CONTINUATION: &str = "plan.continuation"; +/// The current `plan.continuation` payload version. +pub const PLAN_CONTINUATION_VERSION: u32 = 1; +/// A continuation's planner order handed to the session, on its phase's +/// stream: `{phase, edit, work_order}` (D-09). +pub const PLAN_CONTINUATION_FOLLOWED: &str = "plan.continuation_followed"; +/// The current `plan.continuation_followed` payload version. +pub const PLAN_CONTINUATION_FOLLOWED_VERSION: u32 = 1; + +/// Registers the four plan types at version 1 with no upcasters. +pub fn register_plan_events(registry: &mut Registry) -> Result<(), RegistryError> { + registry.register(PLAN_APPROVED, PLAN_APPROVED_VERSION, [])?; + registry.register(PLAN_REPLACED, PLAN_REPLACED_VERSION, [])?; + registry.register(PLAN_CONTINUATION, PLAN_CONTINUATION_VERSION, [])?; + registry.register( + PLAN_CONTINUATION_FOLLOWED, + PLAN_CONTINUATION_FOLLOWED_VERSION, + [], + ) +} + +/// The stream of phase `phase`: `phase/`, spelled as a plan draft's +/// question set stream is. +pub fn phase_stream(phase: u32) -> String { + format!("phase/{phase}") +} + +/// What one plan approval records. +#[derive(Debug, Clone, Copy)] +pub struct PlanApproval<'a> { + /// The phase the plan is for. + pub phase: u32, + /// The number the plan is given. + pub plan: u32, + /// The approved draft's digest. + pub digest: Hash, + /// The stories the plan serves, in its order. + pub stories: &'a [u32], + /// The plan's size in tasks. + pub size: usize, + /// The project's test command, or `None` when none is set (D-14). + pub suite: Option<&'a str>, + /// The id of the draft's question set. + pub question_set: &'a str, + /// The evidence items exactly as submitted. + pub evidence_map: &'a [Value], + /// The draft's `record` payload reference, never its text. + pub body: &'a PayloadRef, + /// The owner's name. + pub owner: &'a str, + /// The time of the approval. + pub at: &'a str, +} + +impl PlanApproval<'_> { + /// The payload of `plan.approved`. An absent suite is written as null. + pub fn payload(&self) -> Value { + json!({ + "phase": self.phase, + "plan": self.plan, + "digest": self.digest.to_hex(), + "stories": self.stories, + "size": self.size, + "suite": self.suite, + "question_set": self.question_set, + "evidence_map": self.evidence_map, + "body": self.body.to_value(), + "owner": self.owner, + "at": self.at, + }) + } +} + +/// The payload of `plan.replaced`: plan `plan` of phase `phase`, approved +/// as `old_digest`, replaced by the draft `new_digest` by `owner` at `at`. +pub fn replaced_payload( + phase: u32, + plan: u32, + old_digest: Hash, + new_digest: Hash, + owner: &str, + at: &str, +) -> Value { + json!({ + "phase": phase, + "plan": plan, + "old_digest": old_digest.to_hex(), + "new_digest": new_digest.to_hex(), + "owner": owner, + "at": at, + }) +} + +/// The payload of `plan.continuation`: phase `phase` waits on the `phase +/// edit` draft `edit` to commit `stories` in order, and that edit's +/// approval issues the planner order `work_order`, fixed when the edit is +/// drafted so a rerun finds the same order. +pub fn continuation_payload(phase: u32, stories: &[u32], edit: Hash, work_order: &str) -> Value { + json!({ + "phase": phase, + "stories": stories, + "edit": edit.to_hex(), + "work_order": work_order, + }) +} + +/// The payload of `plan.continuation_followed`: the planner order +/// `work_order` the approved edit `edit` issued was handed to the session. +pub fn continuation_followed_payload(phase: u32, edit: Hash, work_order: &str) -> Value { + json!({ + "phase": phase, + "edit": edit.to_hex(), + "work_order": work_order, + }) +} + +#[cfg(test)] +mod tests { + //! Expected payloads are written out from design 0005 section 6, D-06, + //! D-07, D-14 and the plan's test data, never from running this code. + + use baley_store::RetentionClass; + use serde_json::json; + + use super::*; + use crate::plan::fixtures::c1; + use crate::questions::{Subject, register_question_events, set_stream}; + use crate::scope::register_scope_events; + use crate::truth::register_truth_events; + + const S: &str = "5d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + const T: &str = "2026-10-31T09:00:00Z"; + + /// R: a `record` reference with hash Y and 1,024 bytes. + fn r() -> PayloadRef { + PayloadRef { + hash: Hash([0x6d; 32]), + bytes: 1_024, + class: RetentionClass::Record, + } + } + + #[test] + fn a_plan_approval_payload_without_its_map_or_with_its_body_inlined_is_caught() { + let map = [c1()]; + let body = r(); + let mut approval = PlanApproval { + phase: 1, + plan: 2, + digest: Hash([0x5c; 32]), + stories: &[1], + size: 1, + suite: Some("cargo test"), + question_set: S, + evidence_map: &map, + body: &body, + owner: "Ada Owner", + at: T, + }; + let payload = approval.payload(); + let mut members: Vec<&str> = payload + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + members.sort_unstable(); + assert_eq!( + members, + [ + "at", + "body", + "digest", + "evidence_map", + "owner", + "phase", + "plan", + "question_set", + "size", + "stories", + "suite" + ] + ); + assert_eq!( + payload, + json!({"phase": 1, "plan": 2, "digest": "5c".repeat(32), "stories": [1], + "size": 1, "suite": "cargo test", "question_set": S, + "evidence_map": [c1()], + "body": {"payload": "6d".repeat(32), "bytes": 1_024, "class": "record"}, + "owner": "Ada Owner", "at": T}) + ); + assert!(payload.get("tasks").is_none()); + approval.suite = None; + assert_eq!(approval.payload()["suite"], Value::Null); + } + + #[test] + fn a_replacement_payload_missing_a_digest_or_the_old_number_is_caught() { + assert_eq!( + replaced_payload(1, 1, Hash([0x5c; 32]), Hash([0x6d; 32]), "Ada Owner", T), + json!({"phase": 1, "plan": 1, "old_digest": "5c".repeat(32), + "new_digest": "6d".repeat(32), "owner": "Ada Owner", "at": T}) + ); + } + + #[test] + fn a_phase_stream_spelled_apart_from_its_question_sets_or_an_event_left_unregistered_is_caught() + { + let set = Subject::Plan { + phase: 7, + plan_digest: Hash([0x5c; 32]), + }; + assert_eq!(phase_stream(7), "phase/7"); + assert_eq!(phase_stream(7), set_stream(&set)); + + let mut registry = Registry::new(); + register_scope_events(&mut registry).unwrap(); + register_question_events(&mut registry).unwrap(); + register_truth_events(&mut registry).unwrap(); + register_plan_events(&mut registry).unwrap(); + for name in [ + "plan.approved", + "plan.replaced", + "plan.continuation", + "plan.continuation_followed", + ] { + assert_eq!(registry.current_version(name), Some(1), "{name}"); + } + assert!(register_plan_events(&mut registry).is_err()); + } +} diff --git a/crates/baley-core/src/plan/judge.rs b/crates/baley-core/src/plan/judge.rs index 5152a288..6a92a305 100644 --- a/crates/baley-core/src/plan/judge.rs +++ b/crates/baley-core/src/plan/judge.rs @@ -19,7 +19,7 @@ use std::num::NonZeroU32; -use serde_json::Value; +use serde_json::{Map, Value, json}; use super::evidence::{self, EvidenceItem}; use super::task::{self, Task}; @@ -185,6 +185,72 @@ impl PlanRefusal { } } + /// What the refusal names, as its answer's details, under the names the + /// design's refusal rows use, or none for `no-truths`, which names + /// nothing beyond the phase the caller already sent. + pub fn details(&self) -> Option { + let item = |position: &usize, id: &String| json!({"position": position, "id": id}); + let truth = |story: &u32, truth: &String, version: &u32| json!({"story": story, "truth": truth, "version": version}); + Some(match self { + Self::TypedContent { path } => json!({"path": path}), + Self::Lease { position, id, file } => { + json!({"position": position, "id": id, "file": file}) + } + Self::Questions(refusal) => match refusal { + SetRefusal::TypedContent { position } => json!({"position": position}), + SetRefusal::QuestionId { position, id } + | SetRefusal::QuestionBlank { position, id } + | SetRefusal::QuestionDependency { position, id } => item(position, id), + SetRefusal::QuestionCycle { questions } => { + let ids: Vec<&str> = questions.iter().map(|(_, id)| id.as_str()).collect(); + json!({"questions": ids}) + } + }, + Self::CheckCommand { position, id } + | Self::CheckExpected { position, id } + | Self::CheckTestFile { position, id } + | Self::CheckBoundary { position, id } + | Self::EvidenceItemTruth { position, id } + | Self::LinkValueNotNamed { position, id } => item(position, id), + Self::NoTruths => return None, + Self::StoryNotInPhase { story } => json!({"story": story}), + Self::TruthVersionMismatch { + position, + id, + current, + } => json!({"position": position, "id": id, "current": current}), + Self::EvidenceItemConflict { position, id, plan } => { + json!({"position": position, "id": id, "plan": plan}) + } + Self::UncoveredTruth { + story, + truth: id, + version, + } + | Self::TruthWithoutCheck { + story, + truth: id, + version, + } + | Self::TruthWithoutObservation { + story, + truth: id, + version, + } => truth(story, id, version), + Self::TruthCheckLimit { + story, + truth: id, + version, + checks, + } => { + let mut named = truth(story, id, version); + named["checks"] = json!(checks); + named + } + Self::OverCapacity { stories, size } => json!({"stories": stories, "size": size}), + }) + } + /// A `typed-content` refusal naming `path`. pub(super) fn typed(path: impl Into) -> Self { Self::TypedContent { @@ -282,6 +348,9 @@ pub struct Plan { pub(super) tasks: Vec, pub(super) evidence_map: Vec, pub(super) questions: QuestionSet, + // The plan object as submitted, kept so its draft body is exactly what + // was judged (D-05). + pub(super) submitted: Map, } impl Plan { @@ -429,6 +498,55 @@ mod tests { assert_eq!(waiting.code(), "question-dependency"); } + #[test] + fn a_plan_refusal_answered_without_what_it_names_is_caught() { + let cases = [ + ( + typed("tasks[0].verify[1]"), + json!({"path": "tasks[0].verify[1]"}), + ), + ( + lease(0, "k1", "src/x.rs"), + json!({"position": 0, "id": "k1", "file": "src/x.rs"}), + ), + ( + PlanRefusal::TruthVersionMismatch { + position: 0, + id: "c1".into(), + current: 2, + }, + json!({"position": 0, "id": "c1", "current": 2}), + ), + ( + PlanRefusal::EvidenceItemConflict { + position: 0, + id: "c1".into(), + plan: 1, + }, + json!({"position": 0, "id": "c1", "plan": 1}), + ), + ( + PlanRefusal::TruthCheckLimit { + story: 1, + truth: "t1".into(), + version: 1, + checks: vec!["c1".into(), "c3".into()], + }, + json!({"story": 1, "truth": "t1", "version": 1, "checks": ["c1", "c3"]}), + ), + ( + PlanRefusal::OverCapacity { + stories: vec![1, 2], + size: 4, + }, + json!({"stories": [1, 2], "size": 4}), + ), + ]; + for (refusal, details) in cases { + assert_eq!(refusal.details(), Some(details), "{}", refusal.code()); + } + } + fn lease(position: usize, id: &str, file: &str) -> PlanRefusal { PlanRefusal::Lease { position, diff --git a/crates/baley-core/src/plan/map_view.rs b/crates/baley-core/src/plan/map_view.rs new file mode 100644 index 00000000..b98ba9f7 --- /dev/null +++ b/crates/baley-core/src/plan/map_view.rs @@ -0,0 +1,305 @@ +//! The `evidence_map` view: one document per approved plan, keyed by its +//! phase and number, holding the plan's evidence items exactly as approved +//! (design 0005 section 6 Views, D-07, D-17). +//! +//! Only `plan.approved` and `plan.replaced` reach it, so a draft's map never +//! appears. Readiness against the current truths is never stored: it is +//! worked out when the map is read. + +use baley_store::{ + Change, DocKey, Event, FieldKind, FieldSpec, Projector, ProjectorError, ViewSpec, +}; +use serde_json::{Value, json}; + +use super::event::{PLAN_APPROVED, PLAN_REPLACED}; +use super::judge::{ApprovedItem, EvidenceKind}; +use super::phase_plan::{REPLACED, text, whole}; +use super::plan_view::{APPROVED, key_of, plan_key}; + +/// The view's name. +pub const EVIDENCE_MAP_VIEW: &str = "evidence_map"; + +/// The view's declaration: the phase and the plan number as integer keys, +/// and no index. +pub fn evidence_map_spec() -> ViewSpec { + ViewSpec { + name: EVIDENCE_MAP_VIEW.into(), + version: 1, + key: vec![ + FieldSpec { + name: "phase".into(), + kind: FieldKind::Integer, + }, + FieldSpec { + name: "plan".into(), + kind: FieldKind::Integer, + }, + ], + indexes: Vec::new(), + page_bound: 100, + } +} + +/// The key of plan `plan` of phase `phase`'s map. +pub fn evidence_map_key(phase: u32, plan: u32) -> DocKey { + plan_key(phase, plan) +} + +/// Keeps the `evidence_map` view current from `plan.approved` and +/// `plan.replaced`. +/// +/// An approval puts a document holding `phase`, `plan`, `items` (the +/// event's inline map, each item whole as approved, its check ids, truth +/// versions and `level` among them) and `state` `approved`. A replacement +/// sets `state` `replaced` and keeps the items, so the replaced plan's map +/// stays readable (D-07); one for a plan not held is refused. +pub struct EvidenceMapProjector { + spec: ViewSpec, +} + +impl EvidenceMapProjector { + /// Makes the projector. + pub fn new() -> Self { + Self { + spec: evidence_map_spec(), + } + } +} + +impl Default for EvidenceMapProjector { + fn default() -> Self { + Self::new() + } +} + +impl Projector for EvidenceMapProjector { + fn spec(&self) -> &ViewSpec { + &self.spec + } + + fn handles(&self) -> &[&str] { + &[PLAN_APPROVED, PLAN_REPLACED] + } + + fn keys(&self, event: &Event) -> Vec { + key_of(&event.payload).into_iter().collect() + } + + fn apply( + &self, + event: &Event, + documents: &[(DocKey, Value)], + ) -> Result, ProjectorError> { + let refuse = |message: &str| { + ProjectorError(format!( + "{} at seq {}: {message}", + event.type_name, event.seq + )) + }; + let payload = &event.payload; + let key = key_of(payload).ok_or_else(|| refuse("the phase or plan is not a number"))?; + let body = if event.type_name == PLAN_REPLACED { + let Some((_, Value::Object(held))) = documents.iter().find(|(at, _)| *at == key) else { + return Err(refuse("the replaced plan's map is not held")); + }; + let mut held = held.clone(); + held.insert("state".into(), json!(REPLACED)); + Value::Object(held) + } else { + let Some(Value::Array(items)) = payload.get("evidence_map") else { + return Err(refuse("evidence_map is not a list")); + }; + json!({ + "phase": whole(payload, "phase").map_err(|message| refuse(&message))?, + "plan": whole(payload, "plan").map_err(|message| refuse(&message))?, + "items": items, + "state": APPROVED, + }) + }; + Ok(vec![Change::Put { key, body }]) + } +} + +/// The items of an `evidence_map` document as the plan judge takes them, +/// each with the document's plan number and the item whole as its +/// definition, so the facts the binary gathers come from one reading. The +/// caller chooses which documents to read, a replaced plan's or not. +/// `None` when the plan number or any item cannot be read: an item is never +/// skipped. +pub fn approved_items(document: &Value) -> Option> { + let plan = whole(document, "plan").ok()?; + document + .get("items")? + .as_array()? + .iter() + .map(|item| { + let kind = match text(item, "kind").ok()? { + "artifact" => EvidenceKind::Artifact, + "link" => EvidenceKind::Link, + "check" => EvidenceKind::Check, + "observation" => EvidenceKind::Observation, + _ => return None, + }; + Some(ApprovedItem { + plan, + id: text(item, "id").ok()?.to_owned(), + story: whole(item, "story").ok()?, + truth: text(item, "truth").ok()?.to_owned(), + truth_version: whole(item, "truth_version").ok()?, + kind, + definition: item.clone(), + }) + }) + .collect() +} + +#[cfg(test)] +mod tests { + //! Expected documents and items are written out from design 0005 + //! section 6, D-07, D-17, phase 8 D-06 and the plan's test data, never + //! from running this code. + + use baley_store::{Actor, Hash, PayloadRef, ProjectId, RequestId, RetentionClass}; + + use super::*; + use crate::plan::event::{PlanApproval, replaced_payload}; + use crate::plan::fixtures::{c1, c2, o1}; + use crate::scope::submitted_payload; + + const S: &str = "5d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + const T: &str = "2026-10-31T09:00:00Z"; + + fn x() -> Hash { + Hash([0x5c; 32]) + } + + fn y() -> Hash { + Hash([0x6d; 32]) + } + + /// R: a `record` reference with hash Y and 1,024 bytes. + fn r() -> PayloadRef { + PayloadRef { + hash: y(), + bytes: 1_024, + class: RetentionClass::Record, + } + } + + fn event(seq: u64, type_name: &str, payload: Value) -> Event { + Event { + project_id: ProjectId("6f1c2a4e-8b1d-4c3a-9e2f-0a5b7c9d1e3f".into()), + seq, + stream: "phase/1".into(), + stream_version: seq, + type_name: type_name.into(), + type_version: 1, + actor: Actor::Owner, + caller: None, + recorded_at: format!("2026-10-31T09:00:{seq:02}Z"), + request_id: RequestId("9d0c1b7e-2f4a-4b6c-8d1e-3a5b7c9d0e2f".into()), + git: None, + policy_version: 0, + payload, + prev_hash: None, + hash: Hash([0; 32]), + } + } + + /// Plan 2 of phase 1 approved at X for story 1 with size 1 and `map`. + fn approved_two(map: &[Value]) -> Event { + let body = r(); + let approval = PlanApproval { + phase: 1, + plan: 2, + digest: x(), + stories: &[1], + size: 1, + suite: None, + question_set: S, + evidence_map: map, + body: &body, + owner: "Ada Owner", + at: T, + }; + event(1, "plan.approved", approval.payload()) + } + + fn put(changes: Vec) -> (DocKey, Value) { + let [Change::Put { key, body }] = &changes[..] else { + panic!("one document put, got {changes:?}"); + }; + (key.clone(), body.clone()) + } + + #[test] + fn an_evidence_map_changed_on_replay_or_holding_a_draft_is_caught() { + let projector = EvidenceMapProjector::new(); + let approved = approved_two(&[c1(), c2(), o1()]); + let first = put(projector.apply(&approved, &[]).unwrap()); + let second = put(projector.apply(&approved, &[]).unwrap()); + assert_eq!(first, second); + let (key, document) = first; + assert_eq!( + key, + DocKey(vec![ + baley_store::KeyValue::Integer(1), + baley_store::KeyValue::Integer(2) + ]) + ); + assert_eq!(document["items"], json!([c1(), c2(), o1()])); + assert_eq!(document["items"][0]["spec"]["level"], "unit"); + assert_eq!(document["items"][1]["spec"]["level"], "integration"); + assert_eq!(document["state"], "approved"); + + let draft = event( + 2, + "scope.submitted", + submitted_payload(x(), "plan", "phase/1", &r()), + ); + assert!(projector.keys(&draft).is_empty()); + + let replaced = event( + 3, + "plan.replaced", + replaced_payload(1, 2, x(), y(), "Ada Owner", T), + ); + assert_eq!(projector.keys(&replaced), std::slice::from_ref(&key)); + let (_, after) = put(projector.apply(&replaced, &[(key, document)]).unwrap()); + assert_eq!(after["items"], json!([c1(), c2(), o1()])); + assert_eq!(after["state"], "replaced"); + } + + #[test] + fn a_map_read_into_items_of_another_plan_or_kind_is_caught() { + let projector = EvidenceMapProjector::new(); + let (_, document) = put(projector.apply(&approved_two(&[c1(), o1()]), &[]).unwrap()); + assert_eq!( + approved_items(&document), + Some(vec![ + ApprovedItem { + plan: 2, + id: "c1".into(), + story: 1, + truth: "t1".into(), + truth_version: 1, + kind: EvidenceKind::Check, + definition: c1(), + }, + ApprovedItem { + plan: 2, + id: "o1".into(), + story: 1, + truth: "t2".into(), + truth_version: 2, + kind: EvidenceKind::Observation, + definition: o1(), + }, + ]) + ); + + let mut broken = document; + broken["items"][1].as_object_mut().unwrap().remove("kind"); + assert_eq!(approved_items(&broken), None); + } +} diff --git a/crates/baley-core/src/plan/mod.rs b/crates/baley-core/src/plan/mod.rs index 97570cae..23769121 100644 --- a/crates/baley-core/src/plan/mod.rs +++ b/crates/baley-core/src/plan/mod.rs @@ -1,24 +1,56 @@ -//! 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. +//! Plans' pure half (design 0005 sections 3, 5 and 6, PLN-R5, PLN-R9's +//! judge, PLN-R11 to PLN-R15, PLN-R26 and PLN-R27): 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; a plan +//! draft's body, digest and target, built from an accepted plan alone; the +//! judgement of a plan approval and of a replacement, with the phase facts a +//! replacement is judged under; and the four plan events on a phase's +//! stream, `plan.approved`, `plan.replaced`, `plan.continuation` and +//! `plan.continuation_followed`, with their payloads; and the `phase_plan` +//! view, a phase's planning state, the `plan` view, each approved plan's +//! record, and the `evidence_map` view, each approved plan's map with its +//! reading into the items the judge takes, all projected from those events +//! alone; and the commitment judge, what a `phase-plan` call does with a +//! selection and whether a plan may be submitted for its phase. //! //! Nothing here reads a store, a file or a clock: the binary supplies every //! value it judges. +mod approval; mod binding; mod capacity; +mod commitment; mod content; mod coverage; +mod event; mod evidence; #[cfg(test)] mod fixtures; mod judge; mod lease; mod link; +mod map_view; +mod phase_plan; +mod plan_view; +mod replace; mod stories; +mod submission; mod task; +pub use approval::{ + ANSWER_NOT_APPLIED, DraftRead, PlanApprovalFacts, PlanApprovalRefusal, judge_plan_approval, +}; +pub use commitment::{ + CommitmentFacts, CommitmentRefusal, Continuation, PHASE_ACTIVE, PHASE_NOT_ACTIVE, + PLANNER_ORDER_PENDING, PhaseNotActive, PhasePlanPath, Readiness, STORY_IN_PHASE, + STORY_UNREFINED, SelectedStory, judge_commitment, judge_readiness, judge_submit_phase, +}; +pub use event::{ + PLAN_APPROVED, PLAN_APPROVED_VERSION, PLAN_CONTINUATION, PLAN_CONTINUATION_FOLLOWED, + PLAN_CONTINUATION_FOLLOWED_VERSION, PLAN_CONTINUATION_VERSION, PLAN_REPLACED, + PLAN_REPLACED_VERSION, PlanApproval, continuation_followed_payload, continuation_payload, + phase_stream, register_plan_events, replaced_payload, +}; pub use evidence::{ Artifact, Check, CheckTest, EvidenceItem, Expected, Level, Link, Observation, Spec, }; @@ -30,4 +62,17 @@ pub use judge::{ TRUTH_WITHOUT_OBSERVATION, TYPED_CONTENT, UNCOVERED_TRUTH, judge_plan, }; pub use lease::{inside_lease, plain_relative_path}; +pub use map_view::{ + EVIDENCE_MAP_VIEW, EvidenceMapProjector, approved_items, evidence_map_key, evidence_map_spec, +}; +pub use phase_plan::{ + ACTIVE, IN_FORCE, INACTIVE, PHASE_PLAN_STATUS_INDEX, PHASE_PLAN_VIEW, PhasePlanProjector, + REPLACED, phase_plan_key, phase_plan_spec, +}; +pub use plan_view::{APPROVED, PLAN_VIEW, PlanProjector, plan_key, plan_spec}; +pub use replace::{ + ADMITTED_PLAN, NO_SUCH_PLAN, PlanInForce, ReplacementFacts, ReplacementRefusal, + judge_replacement, +}; +pub use submission::{PLAN_KIND, PlanDraft, RecordedPlan, Replaces, read_plan_draft}; pub use task::Task; diff --git a/crates/baley-core/src/plan/phase_plan.rs b/crates/baley-core/src/plan/phase_plan.rs new file mode 100644 index 00000000..117ebe69 --- /dev/null +++ b/crates/baley-core/src/plan/phase_plan.rs @@ -0,0 +1,700 @@ +//! The `phase_plan` view: one document per phase, keyed by its number, +//! holding the phase's planning state (design 0005 section 6 Views, PLN-R9, +//! PLN-R14, Figure 3). +//! +//! A phase is active while one of its plans is in force and it is not +//! withdrawn. Completion (`phase.completed`) is Build 5's, so until then +//! only a withdrawal or every plan replaced away ends a phase's activity, +//! and a project with an approved plan cannot plan another phase (D-02). + +use baley_store::{ + Change, DocKey, Event, FieldKind, FieldSpec, IndexField, IndexSpec, KeyValue, Order, Projector, + ProjectorError, ViewSpec, +}; +use serde_json::{Map, Value, json}; + +use super::event::{PLAN_APPROVED, PLAN_CONTINUATION, PLAN_CONTINUATION_FOLLOWED, PLAN_REPLACED}; +use crate::questions::QUESTIONS_OPENED; +use crate::scope::PHASE_WITHDRAWN; + +/// The view's name. +pub const PHASE_PLAN_VIEW: &str = "phase_plan"; +/// The index that lists phases by status, then number, so the active +/// phases are found without reading every phase. +pub const PHASE_PLAN_STATUS_INDEX: &str = "by_status"; +/// The status of a phase with a plan in force that is not withdrawn. +pub const ACTIVE: &str = "active"; +/// The status of every other phase. +pub const INACTIVE: &str = "inactive"; +/// The state of a plan in force. +pub const IN_FORCE: &str = "in-force"; +/// The state of a plan a later plan replaced. +pub const REPLACED: &str = "replaced"; + +/// The key field: the phase number. +const PHASE_FIELD: &str = "phase"; +/// The phase's status, which the index leads with. +const STATUS_FIELD: &str = "status"; + +/// The view's declaration: the phase number as an integer key and one +/// index over the status, then the number. +pub fn phase_plan_spec() -> ViewSpec { + ViewSpec { + name: PHASE_PLAN_VIEW.into(), + version: 1, + key: vec![FieldSpec { + name: PHASE_FIELD.into(), + kind: FieldKind::Integer, + }], + indexes: vec![IndexSpec { + name: PHASE_PLAN_STATUS_INDEX.into(), + fields: vec![ + IndexField { + name: STATUS_FIELD.into(), + kind: FieldKind::Text, + order: Order::Ascending, + }, + IndexField { + name: PHASE_FIELD.into(), + kind: FieldKind::Integer, + order: Order::Ascending, + }, + ], + }], + page_bound: 100, + } +} + +/// The key of phase `phase`'s document. +pub fn phase_plan_key(phase: u32) -> DocKey { + DocKey(vec![KeyValue::Integer(i64::from(phase))]) +} + +/// Keeps the `phase_plan` view current from `plan.approved`, +/// `plan.replaced`, `phase.withdrawn`, a plan draft's `questions.opened`, +/// `plan.continuation` and `plan.continuation_followed`. +/// +/// A document holds these members: +/// - `phase`: the phase's number. +/// - `plans`: its approved plans in number order, each `{plan, digest, +/// stories, size, state, replaced_by}`, `state` `in-force` or `replaced` +/// and `replaced_by` the replacing draft's digest or null. +/// - `highest`: the highest plan number ever assigned, replaced plans +/// included, 0 before the first. +/// - `size`: the tasks of the plans in force, each plan counted once +/// however many stories it serves. +/// - `withdrawn`: whether the phase was withdrawn. +/// - `status`: `active` while a plan is in force and the phase is not +/// withdrawn, `inactive` otherwise, worked out on every change. +/// - `draft`: the phase's one unapproved plan draft, `{digest, set}` from +/// the latest plan draft's set, or null; its approval clears it (D-03). +/// - `continuation`: the phase's latest planning continuation, `{stories, +/// edit, work_order, followed}`, or null (D-09, D-11). +/// +/// An approval whose number is not above `highest` is refused, so no +/// number is projected twice (PLN-R14, D-07), and so is one whose size would +/// take the phase's size past a `u64`. A replacement of a plan not +/// in force, or at a digest other than the one approved, is refused; the +/// replaced plan keeps its digest, stories and size. A withdrawal, a draft +/// or a continuation of a phase with no document creates one. A story's +/// question set changes nothing. A followed marker naming another edit or +/// order than the latest continuation's, or one already followed, is +/// refused. +pub struct PhasePlanProjector { + spec: ViewSpec, +} + +impl PhasePlanProjector { + /// Makes the projector. + pub fn new() -> Self { + Self { + spec: phase_plan_spec(), + } + } +} + +impl Default for PhasePlanProjector { + fn default() -> Self { + Self::new() + } +} + +impl Projector for PhasePlanProjector { + fn spec(&self) -> &ViewSpec { + &self.spec + } + + fn handles(&self) -> &[&str] { + &[ + PLAN_APPROVED, + PLAN_REPLACED, + PHASE_WITHDRAWN, + QUESTIONS_OPENED, + PLAN_CONTINUATION, + PLAN_CONTINUATION_FOLLOWED, + ] + } + + fn keys(&self, event: &Event) -> Vec { + phase_of(event).map(phase_plan_key).into_iter().collect() + } + + fn apply( + &self, + event: &Event, + documents: &[(DocKey, Value)], + ) -> Result, ProjectorError> { + let refuse = |message: &str| { + ProjectorError(format!( + "{} at seq {}: {message}", + event.type_name, event.seq + )) + }; + // A story's question set is no plan draft, so it changes nothing here. + if event.type_name == QUESTIONS_OPENED && !plan_set(&event.payload) { + return Ok(Vec::new()); + } + let phase = phase_of(event).ok_or_else(|| refuse("the phase is not a phase number"))?; + let key = phase_plan_key(phase); + let mut document = match documents.iter().find(|(at, _)| *at == key) { + Some((_, Value::Object(document))) => document.clone(), + Some(_) => return Err(refuse("the phase's document is not an object")), + None => fresh(phase), + }; + let payload = &event.payload; + match event.type_name.as_str() { + PLAN_APPROVED => approve(&mut document, payload), + PLAN_REPLACED => replace(&mut document, payload), + PHASE_WITHDRAWN => { + document.insert("withdrawn".into(), json!(true)); + Ok(()) + } + QUESTIONS_OPENED => open_draft(&mut document, payload), + PLAN_CONTINUATION => continuation(&mut document, payload), + PLAN_CONTINUATION_FOLLOWED => follow(&mut document, payload), + _ => Err("the view does not handle this event".into()), + } + .and_then(|()| settle(&mut document)) + .map_err(|message| refuse(&message))?; + Ok(vec![Change::Put { + key, + body: Value::Object(document), + }]) + } +} + +/// The document of a phase nothing has been projected for. +fn fresh(phase: u32) -> Map { + let Value::Object(document) = json!({ + PHASE_FIELD: phase, + "plans": [], + "highest": 0, + "size": 0, + "withdrawn": false, + STATUS_FIELD: INACTIVE, + "draft": null, + "continuation": null, + }) else { + unreachable!("a JSON object literal is an object") + }; + document +} + +/// Adds the approved plan in force and raises `highest` to its number. +fn approve(document: &mut Map, payload: &Value) -> Result<(), String> { + let plan = whole(payload, "plan")?; + let digest = text(payload, "digest")?; + let stories = wholes(payload, "stories")?; + let size = payload + .get("size") + .and_then(Value::as_u64) + .ok_or("size is not a whole number")?; + let highest = document + .get("highest") + .and_then(Value::as_u64) + .ok_or("the document's highest is not a whole number")?; + if u64::from(plan) <= highest { + return Err(format!( + "plan {plan} is not above the highest number assigned, {highest}" + )); + } + plans(document)?.push(json!({ + "plan": plan, + "digest": digest, + "stories": stories, + "size": size, + "state": IN_FORCE, + "replaced_by": null, + })); + document.insert("highest".into(), json!(plan)); + // The approved draft no longer waits. + if document.get("draft").and_then(|draft| draft.get("digest")) == Some(&json!(digest)) { + document.insert("draft".into(), Value::Null); + } + Ok(()) +} + +/// Makes a plan draft's set the phase's current draft, replacing any +/// earlier one, since a phase holds one unapproved draft (D-03). +fn open_draft(document: &mut Map, payload: &Value) -> Result<(), String> { + let digest = text(payload, "plan_digest")?; + let set = text(payload, "set")?; + document.insert("draft".into(), json!({"digest": digest, "set": set})); + Ok(()) +} + +/// Makes a continuation the phase's latest, not yet followed. +fn continuation(document: &mut Map, payload: &Value) -> Result<(), String> { + let stories = wholes(payload, "stories")?; + let edit = text(payload, "edit")?; + let work_order = text(payload, "work_order")?; + document.insert( + "continuation".into(), + json!({"stories": stories, "edit": edit, "work_order": work_order, "followed": false}), + ); + Ok(()) +} + +/// Marks the latest continuation followed. One naming another edit or +/// order, or one already followed, is refused, so an order is handed to a +/// session once (D-09, D-11). +fn follow(document: &mut Map, payload: &Value) -> Result<(), String> { + let edit = text(payload, "edit")?; + let work_order = text(payload, "work_order")?; + let Some(Value::Object(latest)) = document.get_mut("continuation") else { + return Err("the phase has no continuation".into()); + }; + if latest.get("edit") != Some(&json!(edit)) + || latest.get("work_order") != Some(&json!(work_order)) + { + return Err(format!( + "the latest continuation is not edit {edit} with order {work_order}" + )); + } + if latest.get("followed") != Some(&json!(false)) { + return Err(format!("order {work_order} was already followed")); + } + latest.insert("followed".into(), json!(true)); + Ok(()) +} + +/// Marks the plan in force at `old_digest` replaced by `new_digest`. +fn replace(document: &mut Map, payload: &Value) -> Result<(), String> { + let plan = whole(payload, "plan")?; + let old = text(payload, "old_digest")?; + let new = text(payload, "new_digest")?; + let held = plans(document)? + .iter_mut() + .find(|held| held["plan"] == plan && held["state"] == IN_FORCE) + .ok_or_else(|| format!("plan {plan} is not in force"))?; + if held["digest"] != old { + return Err(format!("plan {plan} was not approved at {old}")); + } + held["state"] = json!(REPLACED); + held["replaced_by"] = json!(new); + Ok(()) +} + +/// Works out the size and status from the plans in force and the +/// withdrawal, so neither can drift from the plans. +fn settle(document: &mut Map) -> Result<(), String> { + let mut size = 0u64; + let mut in_force = false; + for held in plans(document)?.iter() { + if held["state"] == IN_FORCE { + in_force = true; + let plan_size = held["size"] + .as_u64() + .ok_or("a held plan's size is not a whole number")?; + // A total past u64 would panic or wrap, so it is refused. + size = size + .checked_add(plan_size) + .ok_or("the phase's size would exceed a u64")?; + } + } + let withdrawn = document + .get("withdrawn") + .and_then(Value::as_bool) + .ok_or("the document's withdrawn is not true or false")?; + let status = if in_force && !withdrawn { + ACTIVE + } else { + INACTIVE + }; + document.insert("size".into(), json!(size)); + document.insert(STATUS_FIELD.into(), json!(status)); + Ok(()) +} + +fn plans(document: &mut Map) -> Result<&mut Vec, String> { + match document.get_mut("plans") { + Some(Value::Array(plans)) => Ok(plans), + _ => Err("the document's plans are not a list".into()), + } +} + +/// Whether a `questions.opened` payload is a plan draft's set. +fn plan_set(payload: &Value) -> bool { + payload.get("subject").and_then(Value::as_str) == Some("plan") +} + +/// The phase an event names: `number` on `phase.withdrawn`, `phase` on a +/// plan event or a plan draft's set, none on a story's set. +fn phase_of(event: &Event) -> Option { + let member = match event.type_name.as_str() { + PHASE_WITHDRAWN => "number", + QUESTIONS_OPENED if !plan_set(&event.payload) => return None, + _ => PHASE_FIELD, + }; + whole(&event.payload, member).ok() +} + +/// The member `name` of `payload` as a whole number within `u32`. +pub(super) fn whole(payload: &Value, name: &str) -> Result { + payload + .get(name) + .and_then(Value::as_u64) + .and_then(|value| u32::try_from(value).ok()) + .ok_or_else(|| format!("{name} is not a whole number")) +} + +/// The member `name` of `payload` as text. +pub(super) fn text<'a>(payload: &'a Value, name: &str) -> Result<&'a str, String> { + payload + .get(name) + .and_then(Value::as_str) + .ok_or_else(|| format!("{name} is not text")) +} + +/// The member `name` of `payload` as a list of whole numbers within `u32`. +pub(super) fn wholes(payload: &Value, name: &str) -> Result, String> { + payload + .get(name) + .and_then(Value::as_array) + .and_then(|values| { + values + .iter() + .map(|value| value.as_u64().and_then(|value| u32::try_from(value).ok())) + .collect() + }) + .ok_or_else(|| format!("{name} is not a list of whole numbers")) +} + +#[cfg(test)] +mod tests { + //! Expected documents are written out from design 0005 Figure 3, PLN-R9, + //! PLN-R14, D-02, D-07 and the plan's test data, never from running this + //! code. + + use std::collections::BTreeMap; + + use baley_store::{Actor, Hash, PayloadRef, ProjectId, RequestId, RetentionClass}; + + use super::*; + use crate::plan::event::{ + PlanApproval, continuation_followed_payload, continuation_payload, replaced_payload, + }; + use crate::plan::fixtures::{c1, c2, o1}; + use crate::scope::phase_withdrawn_payload; + + const S: &str = "5d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + const T: &str = "2026-10-31T09:00:00Z"; + + type View = BTreeMap; + + fn x() -> Hash { + Hash([0x5c; 32]) + } + + fn y() -> Hash { + Hash([0x6d; 32]) + } + + fn z() -> Hash { + Hash([0x7e; 32]) + } + + fn event(seq: u64, type_name: &str, payload: Value) -> Event { + Event { + project_id: ProjectId("6f1c2a4e-8b1d-4c3a-9e2f-0a5b7c9d1e3f".into()), + seq, + stream: "phase/1".into(), + stream_version: seq, + type_name: type_name.into(), + type_version: 1, + actor: Actor::Owner, + caller: None, + recorded_at: format!("2026-10-31T09:00:{seq:02}Z"), + request_id: RequestId("9d0c1b7e-2f4a-4b6c-8d1e-3a5b7c9d0e2f".into()), + git: None, + policy_version: 0, + payload, + prev_hash: None, + hash: Hash([0; 32]), + } + } + + /// A(n, p, d, s, k): plan `n` of phase `p` approved at digest `d` for + /// stories `s` with size `k`, map `[C1, C2, O1]`, no suite and set S. + fn a(seq: u64, n: u32, p: u32, d: Hash, s: &[u32], k: usize) -> Event { + let map = [c1(), c2(), o1()]; + let body = PayloadRef { + hash: y(), + bytes: 1_024, + class: RetentionClass::Record, + }; + let approval = PlanApproval { + phase: p, + plan: n, + digest: d, + stories: s, + size: k, + suite: None, + question_set: S, + evidence_map: &map, + body: &body, + owner: "Ada Owner", + at: T, + }; + event(seq, "plan.approved", approval.payload()) + } + + fn replaced(seq: u64, phase: u32, plan: u32, old: Hash, new: Hash) -> Event { + event( + seq, + "plan.replaced", + replaced_payload(phase, plan, old, new, "Ada Owner", T), + ) + } + + fn withdrawn(seq: u64, phase: u32) -> Event { + event(seq, "phase.withdrawn", phase_withdrawn_payload(phase, z())) + } + + /// Applies `event` to `view` as the store would, or gives the refusal. + fn step(view: &mut View, event: &Event) -> Result<(), ProjectorError> { + let projector = PhasePlanProjector::new(); + let read: Vec<(DocKey, Value)> = projector + .keys(event) + .into_iter() + .filter_map(|key| view.get(&key).cloned().map(|body| (key, body))) + .collect(); + for change in projector.apply(event, &read)? { + match change { + Change::Put { key, body } => { + view.insert(key, body); + } + Change::Delete { key } => { + view.remove(&key); + } + } + } + Ok(()) + } + + fn fold(events: &[Event]) -> View { + let mut view = View::new(); + for event in events { + step(&mut view, event).unwrap(); + } + view + } + + fn held( + plan: u32, + digest: Hash, + stories: &[u32], + size: u32, + replaced_by: Option, + ) -> Value { + json!({"plan": plan, "digest": digest.to_hex(), "stories": stories, "size": size, + "state": if replaced_by.is_some() { "replaced" } else { "in-force" }, + "replaced_by": replaced_by.map(|digest| digest.to_hex())}) + } + + fn one() -> DocKey { + DocKey(vec![KeyValue::Integer(1)]) + } + + #[test] + fn a_phase_size_counted_per_story_or_left_after_replacement_is_caught() { + let approvals = [ + a(1, 1, 1, x(), &[1, 2], 2), + a(2, 2, 1, y(), &[1], 1), + a(3, 3, 1, z(), &[2], 3), + ]; + let view = fold(&approvals); + let phase = &view[&one()]; + assert_eq!(phase["size"], 6); + assert_eq!(phase["highest"], 3); + assert_eq!(phase["status"], "active"); + + let mut events = approvals.to_vec(); + events.push(replaced(4, 1, 1, x(), z())); + let view = fold(&events); + assert_eq!(view.len(), 1); + assert_eq!( + view[&one()], + json!({"phase": 1, "highest": 3, "size": 4, "withdrawn": false, + "status": "active", "draft": null, "continuation": null, + "plans": [held(1, x(), &[1, 2], 2, Some(z())), held(2, y(), &[1], 1, None), + held(3, z(), &[2], 3, None)]}) + ); + } + + #[test] + fn a_phase_left_active_after_withdrawal_or_its_last_plan_replaced_is_caught() { + let mut view = View::new(); + step(&mut view, &a(1, 1, 1, x(), &[1], 1)).unwrap(); + assert_eq!(view[&one()]["status"], "active"); + step(&mut view, &withdrawn(2, 1)).unwrap(); + assert_eq!(view[&one()]["status"], "inactive"); + assert_eq!(view[&one()]["withdrawn"], true); + + let two = DocKey(vec![KeyValue::Integer(2)]); + let mut view = View::new(); + step(&mut view, &a(1, 1, 2, x(), &[1], 1)).unwrap(); + assert_eq!(view[&two]["status"], "active"); + step(&mut view, &replaced(2, 2, 1, x(), y())).unwrap(); + assert_eq!(view[&two]["status"], "inactive"); + assert_eq!(view[&two]["size"], 0); + + let view = fold(&[withdrawn(1, 3)]); + assert_eq!( + view[&DocKey(vec![KeyValue::Integer(3)])], + json!({"phase": 3, "plans": [], "highest": 0, "size": 0, "withdrawn": true, + "status": "inactive", "draft": null, "continuation": null}) + ); + } + + #[test] + fn a_plan_number_reused_or_a_plan_replaced_twice_accepted_is_caught() { + let refused = |first: &[Event], second: &Event| { + let mut view = fold(first); + let before = view.clone(); + assert!(step(&mut view, second).is_err(), "{}", second.payload); + assert_eq!(view, before); + }; + refused(&[a(1, 2, 1, x(), &[1], 1)], &a(2, 2, 1, y(), &[1], 1)); + refused(&[a(1, 2, 1, x(), &[1], 1)], &a(2, 1, 1, y(), &[1], 1)); + refused( + &[a(1, 1, 1, x(), &[1], 1), replaced(2, 1, 1, x(), y())], + &replaced(3, 1, 1, x(), y()), + ); + refused(&[a(1, 1, 1, x(), &[1], 1)], &replaced(2, 1, 1, y(), z())); + // A replaced plan's number stays assigned though nothing is in force. + refused( + &[a(1, 1, 1, x(), &[1], 1), replaced(2, 1, 1, x(), y())], + &a(3, 1, 1, y(), &[1], 1), + ); + } + + #[test] + fn a_phase_size_overflowing_its_total_is_caught() { + let mut huge = a(1, 1, 1, x(), &[1], 1); + huge.payload["size"] = json!(u64::MAX); + let mut view = fold(&[huge]); + assert_eq!(view[&one()]["size"], json!(u64::MAX)); + let before = view.clone(); + assert!(step(&mut view, &a(2, 2, 1, y(), &[1], 1)).is_err()); + assert_eq!(view, before); + } + + #[test] + fn a_phase_event_missing_from_the_handled_types_is_caught() { + assert_eq!( + PhasePlanProjector::new().handles(), + [ + "plan.approved", + "plan.replaced", + "phase.withdrawn", + "questions.opened", + "plan.continuation", + "plan.continuation_followed", + ] + ); + } + + /// A plan draft's set `set` of phase 1 for the draft at `digest`. + fn plan_set(seq: u64, set: &str, digest: Hash) -> Event { + event( + seq, + "questions.opened", + json!({"set": set, "subject": "plan", "phase": 1, "plan_digest": digest.to_hex(), + "questions": [], "at": T}), + ) + } + + #[test] + fn a_plan_draft_kept_after_a_newer_draft_or_its_approval_is_caught() { + let draft = |set: &str, digest: Hash| json!({"digest": digest.to_hex(), "set": set}); + let mut view = View::new(); + step(&mut view, &plan_set(1, "A", x())).unwrap(); + assert_eq!(view[&one()]["draft"], draft("A", x())); + step(&mut view, &plan_set(2, "B", y())).unwrap(); + assert_eq!(view[&one()]["draft"], draft("B", y())); + + let story = event( + 3, + "questions.opened", + json!({"set": "C", "subject": "story", "story": 1, "work_order": "W1", + "questions": [], "at": T}), + ); + step(&mut view, &story).unwrap(); + assert_eq!(view.len(), 1); + assert_eq!(view[&one()]["draft"], draft("B", y())); + + step(&mut view, &a(4, 1, 1, y(), &[1], 1)).unwrap(); + assert_eq!(view[&one()]["draft"], Value::Null); + } + + #[test] + fn a_continuation_replaced_by_an_older_one_or_followed_twice_is_caught() { + let mut view = View::new(); + let first = event( + 1, + "plan.continuation", + continuation_payload(1, &[1, 2], x(), "O1"), + ); + step(&mut view, &first).unwrap(); + assert_eq!( + view[&one()]["continuation"], + json!({"stories": [1, 2], "edit": x().to_hex(), "work_order": "O1", + "followed": false}) + ); + let second = event( + 2, + "plan.continuation", + continuation_payload(1, &[2, 1], y(), "O2"), + ); + step(&mut view, &second).unwrap(); + assert_eq!( + view[&one()]["continuation"], + json!({"stories": [2, 1], "edit": y().to_hex(), "work_order": "O2", + "followed": false}) + ); + + let followed = |seq, edit, order| { + event( + seq, + "plan.continuation_followed", + continuation_followed_payload(1, edit, order), + ) + }; + // Stale in both, in only the edit, and in only the order. + for (seq, edit, order) in [(3, x(), "O1"), (3, x(), "O2"), (3, y(), "O1")] { + let before = view.clone(); + assert!(step(&mut view, &followed(seq, edit, order)).is_err()); + assert_eq!(view, before); + } + step(&mut view, &followed(4, y(), "O2")).unwrap(); + assert_eq!( + view[&one()]["continuation"], + json!({"stories": [2, 1], "edit": y().to_hex(), "work_order": "O2", + "followed": true}) + ); + let before = view.clone(); + assert!(step(&mut view, &followed(5, y(), "O2")).is_err()); + assert_eq!(view, before); + } +} diff --git a/crates/baley-core/src/plan/plan_view.rs b/crates/baley-core/src/plan/plan_view.rs new file mode 100644 index 00000000..f3d4abac --- /dev/null +++ b/crates/baley-core/src/plan/plan_view.rs @@ -0,0 +1,291 @@ +//! The `plan` view: one document per approved plan, keyed by its phase and +//! number, holding the plan's approval binding (design 0005 section 6 +//! Views, D-07, D-17). +//! +//! Only `plan.approved` and `plan.replaced` reach it, so an unapproved +//! draft never appears. It does not handle `payload.purged`: the record +//! holds the hash of the draft's body, never its text, so a purge of the +//! body leaves the record whole (D-06). + +use baley_store::{ + Change, DocKey, Event, FieldKind, FieldSpec, KeyValue, PayloadRef, Projector, ProjectorError, + ViewSpec, +}; +use serde_json::{Value, json}; + +use super::event::{PLAN_APPROVED, PLAN_REPLACED}; +use super::phase_plan::{REPLACED, text, whole, wholes}; + +/// The view's name. +pub const PLAN_VIEW: &str = "plan"; +/// The state of an approved plan no later plan replaced. +pub const APPROVED: &str = "approved"; + +/// The view's declaration: the phase and the plan number as integer keys, +/// and no index. +pub fn plan_spec() -> ViewSpec { + ViewSpec { + name: PLAN_VIEW.into(), + version: 1, + key: vec![ + FieldSpec { + name: "phase".into(), + kind: FieldKind::Integer, + }, + FieldSpec { + name: "plan".into(), + kind: FieldKind::Integer, + }, + ], + indexes: Vec::new(), + page_bound: 100, + } +} + +/// The key of plan `plan` of phase `phase`. +pub fn plan_key(phase: u32, plan: u32) -> DocKey { + DocKey(vec![ + KeyValue::Integer(i64::from(phase)), + KeyValue::Integer(i64::from(plan)), + ]) +} + +/// Keeps the `plan` view current from `plan.approved` and `plan.replaced`. +/// +/// An approval puts a document holding `phase`, `plan`, the approved +/// `digest`, `stories`, `size`, `suite` (null when none was set), +/// `question_set`, `body` (the hex hash of the draft's `record` payload), +/// `owner`, `at`, `state` `approved` and `replaced_by` null. A replacement +/// sets `state` `replaced` and `replaced_by` to the new digest and keeps +/// every other field, so the binding stays readable (D-07); one for a plan +/// not held is refused. +pub struct PlanProjector { + spec: ViewSpec, +} + +impl PlanProjector { + /// Makes the projector. + pub fn new() -> Self { + Self { spec: plan_spec() } + } +} + +impl Default for PlanProjector { + fn default() -> Self { + Self::new() + } +} + +impl Projector for PlanProjector { + fn spec(&self) -> &ViewSpec { + &self.spec + } + + fn handles(&self) -> &[&str] { + &[PLAN_APPROVED, PLAN_REPLACED] + } + + fn keys(&self, event: &Event) -> Vec { + key_of(&event.payload).into_iter().collect() + } + + fn apply( + &self, + event: &Event, + documents: &[(DocKey, Value)], + ) -> Result, ProjectorError> { + let refuse = |message: &str| { + ProjectorError(format!( + "{} at seq {}: {message}", + event.type_name, event.seq + )) + }; + let payload = &event.payload; + let key = key_of(payload).ok_or_else(|| refuse("the phase or plan is not a number"))?; + let body = if event.type_name == PLAN_REPLACED { + let new = text(payload, "new_digest").map_err(|message| refuse(&message))?; + let Some((_, Value::Object(held))) = documents.iter().find(|(at, _)| *at == key) else { + return Err(refuse("the replaced plan is not held")); + }; + let mut held = held.clone(); + held.insert("state".into(), json!(REPLACED)); + held.insert("replaced_by".into(), json!(new)); + Value::Object(held) + } else { + approved(payload).map_err(|message| refuse(&message))? + }; + Ok(vec![Change::Put { key, body }]) + } +} + +/// The document of a `plan.approved` payload. +fn approved(payload: &Value) -> Result { + let suite = match payload.get("suite") { + Some(Value::Null) => None, + Some(Value::String(suite)) => Some(suite.as_str()), + _ => return Err("suite is not text or null".into()), + }; + let body = payload + .get("body") + .and_then(PayloadRef::from_value) + .ok_or("body is not a payload reference")?; + Ok(json!({ + "phase": whole(payload, "phase")?, + "plan": whole(payload, "plan")?, + "digest": text(payload, "digest")?, + "stories": wholes(payload, "stories")?, + "size": payload.get("size").and_then(Value::as_u64).ok_or("size is not a whole number")?, + "suite": suite, + "question_set": text(payload, "question_set")?, + "body": body.hash.to_hex(), + "owner": text(payload, "owner")?, + "at": text(payload, "at")?, + "state": APPROVED, + "replaced_by": null, + })) +} + +/// The key a plan event names: its phase and its plan number. +pub(super) fn key_of(payload: &Value) -> Option { + Some(plan_key( + whole(payload, "phase").ok()?, + whole(payload, "plan").ok()?, + )) +} + +#[cfg(test)] +mod tests { + //! Expected documents are written out from design 0005 section 6, D-06, + //! D-07, D-17 and the plan's test data, never from running this code. + + use baley_store::{Actor, Hash, ProjectId, PurgedEvent, RequestId, RetentionClass}; + + use super::*; + use crate::plan::event::{PlanApproval, replaced_payload}; + use crate::plan::fixtures::{c1, c2, o1}; + use crate::scope::submitted_payload; + + const S: &str = "5d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + const T: &str = "2026-10-31T09:00:00Z"; + + fn x() -> Hash { + Hash([0x5c; 32]) + } + + fn y() -> Hash { + Hash([0x6d; 32]) + } + + /// R: a `record` reference with hash Y and 1,024 bytes. + fn r() -> PayloadRef { + PayloadRef { + hash: y(), + bytes: 1_024, + class: RetentionClass::Record, + } + } + + fn event(seq: u64, type_name: &str, payload: Value) -> Event { + Event { + project_id: ProjectId("6f1c2a4e-8b1d-4c3a-9e2f-0a5b7c9d1e3f".into()), + seq, + stream: "phase/1".into(), + stream_version: seq, + type_name: type_name.into(), + type_version: 1, + actor: Actor::Owner, + caller: None, + recorded_at: format!("2026-10-31T09:00:{seq:02}Z"), + request_id: RequestId("9d0c1b7e-2f4a-4b6c-8d1e-3a5b7c9d0e2f".into()), + git: None, + policy_version: 0, + payload, + prev_hash: None, + hash: Hash([0; 32]), + } + } + + #[test] + fn an_approved_plan_record_dropped_or_rebound_on_replacement_is_caught() { + let map = [c1(), c2(), o1()]; + let body = r(); + let approval = PlanApproval { + phase: 1, + plan: 1, + digest: x(), + stories: &[1], + size: 1, + suite: Some("cargo test"), + question_set: S, + evidence_map: &map, + body: &body, + owner: "Ada Owner", + at: T, + }; + let approved = event(1, "plan.approved", approval.payload()); + let projector = PlanProjector::new(); + let key = DocKey(vec![KeyValue::Integer(1), KeyValue::Integer(1)]); + assert_eq!(projector.keys(&approved), std::slice::from_ref(&key)); + let record = json!({"phase": 1, "plan": 1, "digest": "5c".repeat(32), "stories": [1], + "size": 1, "suite": "cargo test", "question_set": S, "body": "6d".repeat(32), + "owner": "Ada Owner", "at": T, "state": "approved", "replaced_by": null}); + assert_eq!( + projector.apply(&approved, &[]).unwrap(), + [Change::Put { + key: key.clone(), + body: record.clone(), + }] + ); + + let replaced = event( + 2, + "plan.replaced", + replaced_payload(1, 1, x(), y(), "Ada Owner", T), + ); + assert_eq!(projector.keys(&replaced), std::slice::from_ref(&key)); + assert_eq!( + projector + .apply(&replaced, &[(key.clone(), record)]) + .unwrap(), + [Change::Put { + key, + body: json!({"phase": 1, "plan": 1, "digest": "5c".repeat(32), + "stories": [1], "size": 1, "suite": "cargo test", "question_set": S, + "body": "6d".repeat(32), "owner": "Ada Owner", "at": T, + "state": "replaced", "replaced_by": "6d".repeat(32)}), + }] + ); + } + + #[test] + fn a_draft_or_a_purge_reaching_the_plan_view_is_caught() { + let projector = PlanProjector::new(); + assert_eq!(projector.handles(), ["plan.approved", "plan.replaced"]); + let draft = event( + 1, + "scope.submitted", + submitted_payload(x(), "plan", "phase/1", &r()), + ); + assert!(projector.keys(&draft).is_empty()); + let purge = event( + 2, + "payload.purged", + PurgedEvent { + requested: vec![y()], + released: vec![(1, y())], + removed: vec![], + shared: vec![], + reason: "pasted a secret".into(), + } + .to_value(), + ); + assert!(projector.keys(&purge).is_empty()); + + let replaced = event( + 3, + "plan.replaced", + replaced_payload(1, 4, x(), y(), "Ada Owner", T), + ); + assert!(projector.apply(&replaced, &[]).is_err()); + } +} diff --git a/crates/baley-core/src/plan/replace.rs b/crates/baley-core/src/plan/replace.rs new file mode 100644 index 00000000..008228b2 --- /dev/null +++ b/crates/baley-core/src/plan/replace.rs @@ -0,0 +1,214 @@ +//! The judgement of a plan replacement and the phase facts the new plan is +//! judged under (design 0005 section 5 `plan replace`, PLN-R14, D-04). +//! +//! A replacement names the plan in force it replaces by number and the +//! digest that plan was approved at. Once accepted, the new plan is judged +//! as if the old one were gone: its tasks off the phase's size and its +//! evidence items off the approved items. + +use baley_store::Hash; +use serde_json::{Value, json}; + +use super::judge::PlanFacts; +use super::submission::Replaces; + +/// The refusal code for a replacement naming no plan in force by that +/// number, or naming one at a digest it was not approved at (PRJ-R18). +pub const NO_SUCH_PLAN: &str = "no-such-plan"; +/// The refusal code for replacing a plan whose execution is admitted +/// (PLN-R14). +pub const ADMITTED_PLAN: &str = "admitted-plan"; + +/// Why a replacement is refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReplacementRefusal { + /// No plan in force has number `plan` at the digest named. + NoSuchPlan { plan: u32 }, + /// Plan `plan`'s execution is admitted. + AdmittedPlan { plan: u32 }, +} + +impl ReplacementRefusal { + /// The refusal's public code. + pub fn code(&self) -> &'static str { + match self { + Self::NoSuchPlan { .. } => NO_SUCH_PLAN, + Self::AdmittedPlan { .. } => ADMITTED_PLAN, + } + } + + /// What the refusal names, as its answer's details. + pub fn details(&self) -> Value { + match self { + Self::NoSuchPlan { plan } | Self::AdmittedPlan { plan } => json!({"plan": plan}), + } + } +} + +/// One approved plan of the phase that no replacement has replaced. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PlanInForce { + /// Its number. + pub plan: u32, + /// The digest it was approved at. + pub digest: Hash, + /// Its size: the number of its tasks. + pub size: u32, +} + +/// What a replacement is judged on. +#[derive(Debug, Clone, Copy)] +pub struct ReplacementFacts<'a> { + /// The phase's plans in force. + pub in_force: &'a [PlanInForce], + /// Whether the named plan's execution is admitted. The binary reads it + /// as false until Build 5 records admission. + pub admitted: bool, + /// The phase's facts as they stand, the replaced plan still counted. + pub phase: &'a PlanFacts, +} + +/// Judges a replacement of `replaces`: `no-such-plan` when no plan in force +/// has its number at its digest, then `admitted-plan`. Accepted, it gives +/// the phase's facts with the replaced plan's evidence items taken out of +/// `approved` and its size taken off `size`, never below 0, so the new plan +/// is judged as the phase would stand once the old one is gone. +pub fn judge_replacement( + replaces: Replaces, + facts: &ReplacementFacts, +) -> Result { + let plan = replaces.plan; + let Some(old) = facts + .in_force + .iter() + .find(|old| old.plan == plan && old.digest == replaces.digest) + else { + return Err(ReplacementRefusal::NoSuchPlan { plan }); + }; + if facts.admitted { + return Err(ReplacementRefusal::AdmittedPlan { plan }); + } + let mut phase = facts.phase.clone(); + phase.approved.retain(|item| item.plan != plan); + phase.size = phase.size.saturating_sub(old.size); + Ok(phase) +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005, D-04 and the + //! plan's test data, never from running this code. + + use std::num::NonZeroU32; + + use super::*; + use crate::plan::PlanRefusal; + use crate::plan::fixtures::{accepted, approved, c1, c4, f1, p1, refusal}; + + /// X: `5c` repeated 32 times. + fn x() -> Hash { + Hash([0x5c; 32]) + } + + /// Z: `7e` repeated 32 times. + fn z() -> Hash { + Hash([0x7e; 32]) + } + + fn in_force() -> Vec { + vec![ + PlanInForce { + plan: 1, + digest: x(), + size: 2, + }, + PlanInForce { + plan: 3, + digest: z(), + size: 1, + }, + ] + } + + #[test] + fn a_replacement_of_a_plan_not_in_force_or_admitted_accepted_is_caught() { + let plans = in_force(); + let phase = f1(); + let judged = |plan: u32, digest: Hash, admitted: bool| { + judge_replacement( + Replaces { plan, digest }, + &ReplacementFacts { + in_force: &plans, + admitted, + phase: &phase, + }, + ) + .map_err(|refusal| (refusal.code(), refusal.details())) + }; + + assert_eq!( + judged(2, x(), false), + Err(("no-such-plan", json!({"plan": 2}))) + ); + assert_eq!( + judged(1, z(), false), + Err(("no-such-plan", json!({"plan": 1}))) + ); + assert_eq!( + judged(1, x(), true), + Err(("admitted-plan", json!({"plan": 1}))) + ); + assert!(judged(1, x(), false).is_ok()); + } + + #[test] + fn a_replaced_plan_still_counted_in_the_phase_is_caught() { + let mut phase = f1(); + phase.approved = vec![approved(1, c1()), approved(3, c4())]; + phase.size = 3; + phase.capacity = NonZeroU32::new(2); + let plans = in_force(); + + let replaced = judge_replacement( + Replaces { + plan: 1, + digest: x(), + }, + &ReplacementFacts { + in_force: &plans, + admitted: false, + phase: &phase, + }, + ) + .expect("accepted"); + assert_eq!(replaced.approved, vec![approved(3, c4())]); + assert_eq!(replaced.size, 1); + accepted(&p1(), &replaced); + assert_eq!( + refusal(&p1(), &phase), + PlanRefusal::OverCapacity { + stories: vec![1], + size: 4, + } + ); + + let larger = [PlanInForce { + plan: 1, + digest: x(), + size: 5, + }]; + let shrunk = judge_replacement( + Replaces { + plan: 1, + digest: x(), + }, + &ReplacementFacts { + in_force: &larger, + admitted: false, + phase: &phase, + }, + ) + .expect("accepted"); + assert_eq!(shrunk.size, 0); + } +} diff --git a/crates/baley-core/src/plan/submission.rs b/crates/baley-core/src/plan/submission.rs new file mode 100644 index 00000000..491f853c --- /dev/null +++ b/crates/baley-core/src/plan/submission.rs @@ -0,0 +1,273 @@ +//! A plan draft's body, digest and target, and a recorded body read back +//! (design 0005 sections 5 and 6, PLN-R14, PLN-R15, D-03, D-05). +//! +//! A plan draft is `scope.submitted` of kind `plan`. Its body is the plan +//! exactly as submitted with `kind` added, and for a replacement the plan +//! number and digest it replaces; nothing a call carries enters it, so the +//! digest names the plan alone. Every draft of one phase is filed under +//! `phase/`, so the newest of any kind makes the others stale. + +use baley_store::{Hash, canonical_json, request_digest}; +use serde_json::{Map, Value, json}; + +use super::content::counter; +use super::event::phase_stream; +use super::judge::Plan; + +/// The kind a plan draft's body and `scope.submitted` spell. +pub const PLAN_KIND: &str = "plan"; + +const KIND_MEMBER: &str = "kind"; +const REPLACES_MEMBER: &str = "replaces"; + +/// The approved plan a replacement draft replaces (PLN-R14). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Replaces { + /// The replaced plan's number. + pub plan: u32, + /// The digest the replaced plan was approved at. + pub digest: Hash, +} + +/// A plan draft built from an accepted plan. Only an accepted [`Plan`] +/// gives one, so nothing unjudged is recorded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlanDraft { + body: Vec, + digest: Hash, + target: String, +} + +impl PlanDraft { + /// The draft of `plan` submitted as a new plan. + pub fn new(plan: &Plan) -> Self { + Self::build(plan, None) + } + + /// The draft of `plan` submitted to replace `replaces`. Its body names + /// the replaced plan, so its digest is never the plain draft's. + pub fn replacing(plan: &Plan, replaces: Replaces) -> Self { + Self::build(plan, Some(replaces)) + } + + fn build(plan: &Plan, replaces: Option) -> Self { + let mut body = plan.submitted.clone(); + body.insert(KIND_MEMBER.into(), Value::String(PLAN_KIND.into())); + if let Some(Replaces { plan, digest }) = replaces { + body.insert( + REPLACES_MEMBER.into(), + json!({"plan": plan, "digest": digest.to_hex()}), + ); + } + let value = Value::Object(body); + // Every leaf of an accepted plan is text or a counter within u32, + // so it always has a canonical form. + let digest = request_digest(&value).expect("an accepted plan is canonical"); + let body = canonical_json(&value).expect("an accepted plan is canonical"); + Self { + body, + digest, + target: phase_stream(plan.phase()), + } + } + + /// The canonical JSON bytes the digest is taken over, stored as the + /// draft's body. + pub fn body(&self) -> &[u8] { + &self.body + } + + /// The SHA-256 of the body and nothing else. + pub fn digest(&self) -> Hash { + self.digest + } + + /// What the draft is filed under among plan drafts: `phase/`, for a + /// new plan and a replacement alike, so a phase has one draft line. + pub fn target(&self) -> &str { + &self.target + } +} + +/// A recorded plan draft body read back. +#[derive(Debug, Clone, PartialEq)] +pub struct RecordedPlan { + /// The plan's members as submitted, without `kind` or `replaces`, for + /// the plan judge to read again. + pub plan: Value, + /// The plan it replaces, for a replacement draft. + pub replaces: Option, +} + +/// Reads a recorded plan draft body, or `None` when it is not an object, +/// its `kind` is not `plan`, or its `replaces` is not an object holding a +/// whole `plan` from 1 and a 64-character lowercase hex `digest` and no +/// other member. The plan +/// itself is not judged here: callers judge it again against the phase as +/// it stands. +pub fn read_plan_draft(body: &Value) -> Option { + let Value::Object(members) = body else { + return None; + }; + let mut plan: Map = members.clone(); + if plan.remove(KIND_MEMBER)? != PLAN_KIND { + return None; + } + let replaces = match plan.remove(REPLACES_MEMBER) { + None => None, + Some(binding) => { + // The digest covers every member of the binding, so one this + // read would drop could make two drafts of different digests + // read back the same. + let binding = binding.as_object()?; + if binding + .keys() + .any(|name| name != "plan" && name != "digest") + { + return None; + } + Some(Replaces { + plan: counter(binding.get("plan"))?, + digest: lowercase_digest(binding.get("digest"))?, + }) + } + }; + Some(RecordedPlan { + plan: Value::Object(plan), + replaces, + }) +} + +/// A digest written as Baley writes one: 64 lowercase hex digits. +fn lowercase_digest(value: Option<&Value>) -> Option { + let text = value?.as_str()?; + if !text + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) + { + return None; + } + Hash::from_hex(text) +} + +#[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, c1, c2, f1, k1, o1, p1}; + + /// X: `5c` repeated 32 times. + fn x() -> Hash { + Hash([0x5c; 32]) + } + + fn replaces(plan: u32) -> Replaces { + Replaces { plan, digest: x() } + } + + fn reversed(value: &Value) -> Value { + let members = value.as_object().expect("an object"); + let mut names: Vec<&String> = members.keys().collect(); + names.reverse(); + Value::Object( + names + .into_iter() + .map(|name| (name.clone(), members[name].clone())) + .collect(), + ) + } + + #[test] + fn a_plan_digest_over_more_than_the_plan_or_not_its_body_is_caught() { + let by_hand = 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": [], + "kind": "plan"}); + let draft = PlanDraft::new(&accepted(&p1(), &f1())); + assert_eq!(draft.body(), canonical_json(&by_hand).unwrap()); + assert_eq!(draft.digest(), request_digest(&by_hand).unwrap()); + assert_eq!(draft.target(), "phase/8"); + + let reordered = PlanDraft::new(&accepted(&reversed(&p1()), &f1())); + assert_eq!(reordered.body(), draft.body()); + assert_eq!(reordered.digest(), draft.digest()); + } + + #[test] + fn a_replacement_sharing_a_digest_or_another_line_with_a_new_plan_is_caught() { + let plan = accepted(&p1(), &f1()); + let plain = PlanDraft::new(&plan); + let of_one = PlanDraft::replacing(&plan, replaces(1)); + let of_two = PlanDraft::replacing(&plan, replaces(2)); + assert_ne!(plain.digest(), of_one.digest()); + assert_ne!(plain.digest(), of_two.digest()); + assert_ne!(of_one.digest(), of_two.digest()); + for draft in [&plain, &of_one, &of_two] { + assert_eq!(draft.target(), "phase/8"); + } + let binding = |draft: &PlanDraft| { + serde_json::from_slice::(draft.body()).unwrap()["replaces"].clone() + }; + let x = "5c".repeat(32); + assert_eq!(binding(&of_one), json!({"plan": 1, "digest": x})); + assert_eq!(binding(&of_two), json!({"plan": 2, "digest": x})); + + // Only the replaced digest differs, so a digest that skipped it + // would give both replacements one digest. + let by_hand = |digest: &str| { + 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": [], + "kind": "plan", "replaces": {"plan": 1, "digest": digest}}) + }; + let at_y = PlanDraft::replacing( + &plan, + Replaces { + plan: 1, + digest: Hash([0x6d; 32]), + }, + ); + assert_eq!(of_one.digest(), request_digest(&by_hand(&x)).unwrap()); + assert_eq!( + at_y.digest(), + request_digest(&by_hand(&"6d".repeat(32))).unwrap() + ); + assert_ne!(of_one.digest(), at_y.digest()); + } + + #[test] + fn a_recorded_plan_body_read_back_wrongly_is_caught() { + let draft = PlanDraft::replacing(&accepted(&p1(), &f1()), replaces(1)); + let body: Value = serde_json::from_slice(draft.body()).unwrap(); + assert_eq!( + read_plan_draft(&body), + Some(RecordedPlan { + plan: p1(), + replaces: Some(Replaces { + plan: 1, + digest: x() + }), + }) + ); + + let altered = |member: &str, to: Value| { + let mut altered = body.clone(); + altered[member] = to; + altered + }; + let x = "5c".repeat(32); + for refused in [ + altered("kind", json!("phase-edit")), + altered("replaces", json!({"plan": 1, "digest": "XYZ"})), + altered("replaces", json!({"plan": 0, "digest": x})), + // A member the digest covers but the binding would drop. + altered("replaces", json!({"plan": 1, "digest": x, "note": "extra"})), + ] { + assert_eq!(read_plan_draft(&refused), None, "{refused}"); + } + } +} diff --git a/crates/baley-core/src/policy/config_command/file.rs b/crates/baley-core/src/policy/config_command/file.rs index 46789946..c62b6ed3 100644 --- a/crates/baley-core/src/policy/config_command/file.rs +++ b/crates/baley-core/src/policy/config_command/file.rs @@ -74,10 +74,10 @@ fn child<'t>(table: &'t mut Table, key: &str) -> &'t mut Table { slot.as_table_mut().expect("the slot holds a table") } -/// The TOML type each kind reads back: a boolean, an array of strings for a -/// branch or reviewer list, or a string for a rung name, a model name, a -/// remote name, an `https://` address, a person's name and an `on_protected` -/// name. +/// The TOML type each kind reads back: a boolean, an integer for a capacity, +/// an array of strings for a branch or reviewer list, or a string for a rung +/// name, a model name, a remote name, an `https://` address, a person's name, +/// a command line and an `on_protected` name. fn toml_value(value: &Value) -> TomlValue { match value { Value::Bool(value) => TomlValue::Boolean(*value), @@ -87,6 +87,8 @@ fn toml_value(value: &Value) -> TomlValue { Value::OnProtected(on) => TomlValue::String(on.name().to_owned()), Value::HttpsAddress(address) => TomlValue::String(address.clone()), Value::PersonName(name) => TomlValue::String(name.clone()), + Value::Capacity(capacity) => TomlValue::Integer(i64::from(capacity.get())), + Value::Command(command) => TomlValue::String(command.clone()), Value::BranchList(names) | Value::ReviewerList(names) => { TomlValue::Array(names.iter().cloned().map(TomlValue::String).collect()) } @@ -121,6 +123,7 @@ pub fn changed_pairs(current: Option<&ParsedLayer>, pairs: &[TypedPair]) -> Vec< pub(super) fn value_text(value: &Value) -> String { match value { Value::Bool(value) => value.to_string(), + Value::Capacity(capacity) => capacity.to_string(), Value::Rung(rung) => format!("\"{}\"", rung.name()), Value::OnProtected(on) => format!("\"{}\"", on.name()), Value::BranchList(names) | Value::ReviewerList(names) => { @@ -130,7 +133,8 @@ pub(super) fn value_text(value: &Value) -> String { Value::ModelName(name) | Value::RemoteName(name) | Value::HttpsAddress(name) - | Value::PersonName(name) => quoted(name), + | Value::PersonName(name) + | Value::Command(name) => quoted(name), } } diff --git a/crates/baley-core/src/policy/config_command/set.rs b/crates/baley-core/src/policy/config_command/set.rs index 0236655c..14ae2a91 100644 --- a/crates/baley-core/src/policy/config_command/set.rs +++ b/crates/baley-core/src/policy/config_command/set.rs @@ -3,6 +3,7 @@ use std::collections::BTreeMap; use std::fmt; +use std::num::NonZeroU32; use super::{INVALID_VALUE, LIST_NOT_SETTABLE, NOT_A_PROJECT, UNKNOWN_SETTING, WRONG_LAYER}; use crate::policy::schema::{is_https_address, is_person_name}; @@ -138,10 +139,11 @@ impl fmt::Display for SetRefusal { Kind::HttpsAddress => { "an https:// address with no spaces, query or fragment".to_owned() } - Kind::PersonName => { + Kind::PersonName | Kind::Command => { "one line of text that is not blank and holds no control character" .to_owned() } + Kind::Capacity => format!("a whole number from 1 to {}", u32::MAX), }; write!( f, @@ -206,6 +208,12 @@ fn convert(kind: Kind, text: &str) -> Option { Kind::HttpsAddress => is_https_address(text).then(|| Value::HttpsAddress(text.to_owned())), // Taken as written: spaces either side of a name are kept. Kind::PersonName => is_person_name(text).then(|| Value::PersonName(text.to_owned())), + // Decimal digits only: `u32`'s own parse would also take a leading `+`. + Kind::Capacity => (!text.is_empty() && text.bytes().all(|b| b.is_ascii_digit())) + .then(|| text.parse().ok().and_then(NonZeroU32::new)) + .flatten() + .map(Value::Capacity), + Kind::Command => is_person_name(text).then(|| Value::Command(text.to_owned())), } } diff --git a/crates/baley-core/src/policy/config_command/show.rs b/crates/baley-core/src/policy/config_command/show.rs index c6abd71d..88c375e8 100644 --- a/crates/baley-core/src/policy/config_command/show.rs +++ b/crates/baley-core/src/policy/config_command/show.rs @@ -159,6 +159,8 @@ fn kind_text(kind: Kind) -> &'static str { Kind::ReviewerList => "list of host, openai or deepseek", Kind::HttpsAddress => "https:// address", Kind::PersonName => "name", + Kind::Capacity => "whole number from 1 to 4294967295", + Kind::Command => "command line", } } diff --git a/crates/baley-core/src/policy/config_command/tests.rs b/crates/baley-core/src/policy/config_command/tests.rs index 118faef3..5d3946e9 100644 --- a/crates/baley-core/src/policy/config_command/tests.rs +++ b/crates/baley-core/src/policy/config_command/tests.rs @@ -2021,3 +2021,37 @@ fn config_set_accepting_a_blank_multi_line_or_control_owner_name_or_trimming_a_v assert_eq!(String::from_utf8(bytes).unwrap(), written, "{value:?}"); } } + +#[test] +fn config_set_writing_a_capacity_as_a_string_or_taking_zero_is_caught() { + let set = |name: &str, value: &str| { + judge_pairs( + Schema::standard(), + FileLayer::Project, + true, + None, + &[(name, value)], + ) + }; + let five = set("planning.phase_capacity", "5").unwrap(); + let bytes = render_file(Schema::standard(), FileLayer::Project, None, &five).unwrap(); + assert_eq!( + String::from_utf8(bytes).unwrap(), + "[planning]\nphase_capacity = 5\n" + ); + for value in ["0", "five"] { + let refusal = set("planning.phase_capacity", value).expect_err(value); + assert_eq!(refusal.code(), "invalid-value", "{value}"); + let message = refusal.to_string(); + assert!( + message.ends_with("which is not a whole number from 1 to 4294967295"), + "{message}" + ); + } + let command = set("workflow.test_command", "cargo test").unwrap(); + let bytes = render_file(Schema::standard(), FileLayer::Project, None, &command).unwrap(); + assert_eq!( + String::from_utf8(bytes).unwrap(), + "[workflow]\ntest_command = \"cargo test\"\n" + ); +} diff --git a/crates/baley-core/src/policy/parse.rs b/crates/baley-core/src/policy/parse.rs index cb770c2d..d83ebc76 100644 --- a/crates/baley-core/src/policy/parse.rs +++ b/crates/baley-core/src/policy/parse.rs @@ -3,6 +3,7 @@ //! (design 0003, CFG-R5, CFG-R7, CFG-R9). use std::fmt; +use std::num::NonZeroU32; use std::path::{Path, PathBuf}; use toml::Spanned; @@ -60,6 +61,10 @@ pub enum Value { HttpsAddress(String), /// A person's name, as written: not blank, with no control character. PersonName(String), + /// A phase's capacity in tasks. + Capacity(NonZeroU32), + /// A command line, as written: not blank, with no control character. + Command(String), } /// One setting a file writes, typed and within its scope. @@ -232,6 +237,10 @@ pub enum Expected { HttpsAddress, /// A person's name. PersonName, + /// A whole number from 1 to `u32::MAX`. + Capacity, + /// A command on one line. + Command, } impl From for Expected { fn from(kind: Kind) -> Expected { @@ -245,6 +254,8 @@ impl From for Expected { Kind::ReviewerList => Expected::ReviewerList, Kind::HttpsAddress => Expected::HttpsAddress, Kind::PersonName => Expected::PersonName, + Kind::Capacity => Expected::Capacity, + Kind::Command => Expected::Command, } } } @@ -313,6 +324,8 @@ fn describe(f: &mut fmt::Formatter<'_>, path: &str, fault: &Fault) -> fmt::Resul Expected::ReviewerList => format!("a list of {}", reviewer_names()), Expected::HttpsAddress => "an https:// address".to_owned(), Expected::PersonName => "a name on one line".to_owned(), + Expected::Capacity => format!("a whole number from 1 to {}", u32::MAX), + Expected::Command => "a command on one line".to_owned(), }; write!( f, @@ -355,6 +368,15 @@ fn describe(f: &mut fmt::Formatter<'_>, path: &str, fault: &Fault) -> fmt::Resul f, "is \"{written}\"; write one line of text that is not blank and holds no control character, or remove the line" ), + Kind::Capacity => write!( + f, + "is {written}, which is not a whole number from 1 to {}; write one or remove the line", + u32::MAX + ), + Kind::Command => write!( + f, + "is \"{written}\"; write a command on one line that is not blank and holds no control character, or remove the line" + ), } } Fault::Project { @@ -652,6 +674,24 @@ fn typed(kind: Kind, value: &DeValue<'_>) -> Result { Err(Mismatch::Grammar(written.to_owned(), None)) } } + Kind::Capacity => { + let integer = value.as_integer().ok_or_else(wrong)?; + // Parsed in its own radix, so a hex or signed capacity is judged too. + u32::from_str_radix(integer.as_str(), integer.radix()) + .ok() + .and_then(NonZeroU32::new) + .map(Value::Capacity) + .ok_or_else(|| Mismatch::Grammar(integer.to_string(), None)) + } + // One line, as a person's name is. + Kind::Command => { + let written = value.as_str().ok_or_else(wrong)?; + if is_person_name(written) { + Ok(Value::Command(written.to_owned())) + } else { + Err(Mismatch::Grammar(written.to_owned(), None)) + } + } } } diff --git a/crates/baley-core/src/policy/recorded/event.rs b/crates/baley-core/src/policy/recorded/event.rs index 985b6611..1c8006cf 100644 --- a/crates/baley-core/src/policy/recorded/event.rs +++ b/crates/baley-core/src/policy/recorded/event.rs @@ -113,6 +113,8 @@ fn value_json(value: Option<&Value>) -> Json { Some(Value::BranchList(names) | Value::ReviewerList(names)) => names.clone().into(), Some(Value::HttpsAddress(address)) => address.clone().into(), Some(Value::PersonName(name)) => name.clone().into(), + Some(Value::Capacity(capacity)) => capacity.get().into(), + Some(Value::Command(command)) => command.clone().into(), } } diff --git a/crates/baley-core/src/policy/schema.rs b/crates/baley-core/src/policy/schema.rs index fe009670..6dbecab5 100644 --- a/crates/baley-core/src/policy/schema.rs +++ b/crates/baley-core/src/policy/schema.rs @@ -190,6 +190,11 @@ pub enum Kind { /// control character, which also keeps it to one line. It is taken as /// written, never trimmed. PersonName, + /// A phase's capacity in tasks: a TOML integer from 1 to `u32::MAX`. + Capacity, + /// A command line: text that is not blank and holds no control character, + /// so one line, taken as written and never trimmed, as a person's name is. + Command, } /// The names a reviewer list may hold (design 0003 section 9): the host's own @@ -289,7 +294,8 @@ impl Schema { /// The schema: each role's model and effort, `escalate_on_failure`, /// `git.remote`, the guard's settings under `git`, the two `updates` - /// settings, `review.reviewers` and `owner.name`. + /// settings, `review.reviewers`, `owner.name`, `planning.phase_capacity` + /// and `workflow.test_command`. pub fn standard() -> &'static Schema { static STANDARD: OnceLock = OnceLock::new(); STANDARD.get_or_init(|| { @@ -380,6 +386,22 @@ impl Schema { scope: Scope::Global, owner: "0012", }); + // No default: with no capacity set, no plan is refused for size. + entries.push(Entry { + name: "planning.phase_capacity".into(), + kind: Kind::Capacity, + default: Default::Absent, + scope: Scope::Both, + owner: "0005", + }); + // No default: the suite is the project's own, never guessed. + entries.push(Entry { + name: "workflow.test_command".into(), + kind: Kind::Command, + default: Default::Absent, + scope: Scope::Project, + owner: "0006", + }); Schema::new(entries) }) } diff --git a/crates/baley-core/src/policy/tests.rs b/crates/baley-core/src/policy/tests.rs index 03dcdd41..f6d48d9d 100644 --- a/crates/baley-core/src/policy/tests.rs +++ b/crates/baley-core/src/policy/tests.rs @@ -131,7 +131,7 @@ fn standard_schema_holds_every_entry_with_its_kind_default_scope_and_owner() { ("escalate_on_failure", Kind::Bool, Bool(false)), ]; let schema = Schema::standard(); - assert_eq!(schema.entries().len(), 21); + assert_eq!(schema.entries().len(), 23); for (name, kind, default) in expected { let entry = schema .get(name) @@ -697,7 +697,7 @@ fn an_empty_file_and_no_file_both_give_the_defaults_but_only_the_file_has_a_dige let with = effective_policy(Schema::standard(), None, Some(&empty), None).unwrap(); let without = effective_policy(Schema::standard(), None, None, None).unwrap(); for policy in [&with, &without] { - assert_eq!(policy.settings.len(), 21); + assert_eq!(policy.settings.len(), 23); assert!( policy .settings @@ -1459,7 +1459,7 @@ fn an_update_setting_missing_or_open_to_project_files_is_caught() { (source.kind, source.default, source.scope, source.owner), (Kind::HttpsAddress, Builtin::Absent, Scope::Global, "0012") ); - assert_eq!(schema.entries().len(), 21); + assert_eq!(schema.entries().len(), 23); } #[test] @@ -1622,7 +1622,7 @@ fn an_owner_name_entry_with_another_kind_default_scope_or_owner_is_caught() { (owner.kind, owner.default, owner.scope, owner.owner), (Kind::PersonName, Builtin::Absent, Scope::Global, "0012") ); - assert_eq!(schema.entries().len(), 21); + assert_eq!(schema.entries().len(), 23); } #[test] @@ -1648,3 +1648,99 @@ fn an_owner_name_with_a_line_break_reported_on_two_lines_is_caught() { "config-unavailable: /c/config.toml:2:8: owner.name is \"Ada\\nOwner\"; write one line of text that is not blank and holds no control character, or remove the line" ); } + +#[test] +fn a_phase_capacity_of_zero_text_or_past_u32_accepted_is_caught() { + let capacity = |n: u32| Some(Value::Capacity(NonZeroU32::new(n).unwrap())); + let project = |line: &str| standard(None, None, Some(&format!("[planning]\n{line}\n"))); + let three = project("phase_capacity = 3").unwrap(); + assert_eq!( + value_of(&three, "planning.phase_capacity").value, + capacity(3) + ); + let most = project("phase_capacity = 4294967295").unwrap(); + assert_eq!( + value_of(&most, "planning.phase_capacity").value, + capacity(4_294_967_295) + ); + for line in ["phase_capacity = 0", "phase_capacity = 4294967296"] { + let refusal = project(line).expect_err(line); + assert_eq!(refusal.code(), "config-unavailable", "{line}"); + assert!( + matches!( + refusal.fault, + Fault::OutsideGrammar { + kind: Kind::Capacity, + line: 2, + .. + } + ), + "{line}: {refusal:?}" + ); + } + let text = project("phase_capacity = \"3\"").expect_err("a string"); + assert!( + matches!( + text.fault, + Fault::WrongType { + expected: Expected::Capacity, + found: "string", + line: 2, + .. + } + ), + "{text:?}" + ); + // Both scopes: the global file's capacity applies. + let global = standard(None, Some("[planning]\nphase_capacity = 3\n"), None).unwrap(); + let effective = value_of(&global, "planning.phase_capacity"); + assert_eq!(effective.value, capacity(3)); + assert_eq!(effective.source.layer, Layer::Global); +} + +#[test] +fn a_test_command_blank_multiline_trimmed_or_set_globally_is_caught() { + let project = |line: &str| standard(None, None, Some(&format!("[workflow]\n{line}\n"))); + for (line, kept) in [ + ("test_command = \"cargo nextest run\"", "cargo nextest run"), + ("test_command = \" cargo test \"", " cargo test "), + ] { + let policy = project(line).unwrap(); + assert_eq!( + value_of(&policy, "workflow.test_command").value, + Some(Value::Command(kept.into())), + "{line}" + ); + } + for line in ["test_command = \" \"", "test_command = \"cargo\\ntest\""] { + let refusal = project(line).expect_err(line); + assert!( + matches!( + refusal.fault, + Fault::OutsideGrammar { + kind: Kind::Command, + line: 2, + .. + } + ), + "{line}: {refusal:?}" + ); + } + let global = standard( + None, + Some("[workflow]\ntest_command = \"cargo test\"\n"), + None, + ) + .unwrap(); + assert_eq!(value_of(&global, "workflow.test_command").value, None); + assert_eq!( + global + .diagnostics + .iter() + .map(ToString::to_string) + .collect::>(), + [ + "/c/config.toml:2:1: workflow.test_command is a project setting and was ignored in the global file" + ] + ); +} diff --git a/crates/baley-core/src/scope/backlog.rs b/crates/baley-core/src/scope/backlog.rs index 4c0cbd4f..67b74759 100644 --- a/crates/baley-core/src/scope/backlog.rs +++ b/crates/baley-core/src/scope/backlog.rs @@ -11,6 +11,7 @@ use super::event::{ STORY_REPRIORITIZED, }; use super::roadmap::reprioritized; +use crate::plan::{PLAN_APPROVED, PLAN_REPLACED}; use crate::questions::QUESTIONS_OPENED; use crate::truth::STORY_REFINED; @@ -27,7 +28,7 @@ const PROJECT_KEY: &str = "project"; pub fn backlog_spec() -> ViewSpec { ViewSpec { name: BACKLOG_VIEW.into(), - version: 3, + version: 4, key: vec![FieldSpec { name: KEY_FIELD.into(), kind: FieldKind::Text, @@ -43,20 +44,27 @@ pub fn backlog_key() -> DocKey { } /// Keeps the `backlog` view current from the story events, -/// `phase.declared`, a story's `questions.opened` and `story.refined`. +/// `phase.declared`, a story's `questions.opened`, `story.refined`, +/// `plan.approved` and `plan.replaced`. /// /// The stories are kept in declaration order, which is priority order /// until stories are reprioritized. Each records its latest question set /// (`set`), the set its latest `story.refined` names (`refined`) and that -/// refinement's truth count, and holds none, none and 0 when declared, with -/// no size until sizing records one. Its refinement state is never stored: +/// refinement's truth count, and holds none, none and 0 when declared. Each +/// also keeps the plans in force that serve it (`plans`), each by phase, +/// number and size, and its `size` is their tasks summed, or null when none +/// serves it (PLN-R9). An approval adds the plan to every story it serves, +/// and a replacement takes the old plan off every story that holds it, so +/// exactly what that plan added comes off. A plan naming a story not held +/// is refused. Its refinement state is never stored: /// the reader works it out from the latest set's round, so nothing stored /// can drift from it. A story's set makes that set its latest and a plan /// draft's set changes nothing; a refinement replaces the marker and the /// count, and a later set leaves both, since approved truths stay until new /// ones are approved. A set or a refinement of a story not held is refused, /// as a correction of one is. A later declaration of an -/// id already held replaces that entry in place, so it keeps its priority. +/// id already held replaces that entry in place, so it keeps its priority, +/// and keeps its plans and size, as every other story event does. /// A correction, a move and a drop change a story in place; a dropped /// story stays with status `dropped` and no phase. A reprioritization puts /// the stories it lists first and every other story after them in its @@ -96,6 +104,8 @@ impl Projector for BacklogProjector { STORY_REPRIORITIZED, QUESTIONS_OPENED, STORY_REFINED, + PLAN_APPROVED, + PLAN_REPLACED, ] } @@ -139,7 +149,7 @@ impl Projector for BacklogProjector { match event.type_name.as_str() { STORY_DECLARED => { let id = whole("id")?; - let entry = json!({ + let mut entry = json!({ "id": id, "sentence": text("sentence")?, "status": text("status")?, @@ -147,10 +157,15 @@ impl Projector for BacklogProjector { "set": null, "refined": null, "truths": 0, + "plans": [], "size": null, }); match stories.iter().position(|story| story["id"] == id) { - Some(at) => stories[at] = entry, + Some(at) => { + entry["plans"] = stories[at]["plans"].take(); + entry["size"] = stories[at]["size"].take(); + stories[at] = entry; + } None => stories.push(entry), } } @@ -212,6 +227,39 @@ impl Projector for BacklogProjector { story["refined"] = json!(set); story["truths"] = json!(count); } + PLAN_APPROVED => { + let (number, plan, size) = (whole("phase")?, whole("plan")?, whole("size")?); + let listed: Vec = payload + .get("stories") + .and_then(Value::as_array) + .and_then(|ids| ids.iter().map(Value::as_u64).collect()) + .ok_or_else(fault)?; + if !listed + .iter() + .all(|id| stories.iter().any(|s| s["id"] == *id)) + { + return Err(no_story()); + } + let served = json!({"phase": number, "plan": plan, "size": size}); + for story in &mut stories { + if story["id"].as_u64().is_some_and(|id| listed.contains(&id)) { + plans_mut(story).ok_or_else(fault)?.push(served.clone()); + settle(story) + .ok_or_else(|| refuse("the story's size would exceed a u64"))?; + } + } + } + PLAN_REPLACED => { + let (number, plan) = (whole("phase")?, whole("plan")?); + for story in &mut stories { + let plans = plans_mut(story).ok_or_else(fault)?; + let before = plans.len(); + plans.retain(|held| held["phase"] != number || held["plan"] != plan); + if plans.len() != before { + settle(story).ok_or_else(fault)?; + } + } + } _ => return Err(refuse("not a backlog event")), } Ok(vec![Change::Put { @@ -226,6 +274,27 @@ fn story_mut(stories: &mut [Value], id: u64) -> Option<&mut Value> { stories.iter_mut().find(|story| story["id"] == id) } +/// A story's plans in force, `None` when the entry holds no list. +fn plans_mut(story: &mut Value) -> Option<&mut Vec> { + story.get_mut("plans").and_then(Value::as_array_mut) +} + +/// Sets a story's `size` to its plans' sizes summed, null when it has none; +/// `None` when a size is unreadable or the sum passes `u64`. +fn settle(story: &mut Value) -> Option<()> { + let plans = story.get("plans")?.as_array()?; + let mut total: Option = None; + for plan in plans { + total = Some( + total + .unwrap_or(0) + .checked_add(plan.get("size")?.as_u64()?)?, + ); + } + story["size"] = json!(total); + Some(()) +} + #[cfg(test)] mod tests { //! Expected documents are written out from design 0005's backlog shape @@ -355,11 +424,13 @@ mod tests { fold(&events), json!([ {"id": 3, "sentence": "Teammates see the backlog", "status": "deferred", - "phase": null, "set": null, "refined": null, "truths": 0, "size": null}, + "phase": null, "set": null, "refined": null, "truths": 0, "plans": [], + "size": null}, {"id": 1, "sentence": "Every step is recorded", "status": "active", "phase": 1, - "set": null, "refined": null, "truths": 0, "size": null}, + "set": null, "refined": null, "truths": 0, "plans": [], "size": null}, {"id": 2, "sentence": "The owner approves scope", "status": "active", - "phase": 2, "set": null, "refined": null, "truths": 0, "size": null} + "phase": 2, "set": null, "refined": null, "truths": 0, "plans": [], + "size": null} ]) ); } @@ -457,10 +528,12 @@ mod tests { "story.dropped", "story.reprioritized", "questions.opened", - "story.refined" + "story.refined", + "plan.approved", + "plan.replaced" ] ); - assert_eq!(backlog_spec().version, 3); + assert_eq!(backlog_spec().version, 4); } #[test] @@ -588,7 +661,7 @@ mod tests { #[test] fn a_backlog_storing_a_state_or_missing_the_latest_set_is_caught() { - assert_eq!(backlog_spec().version, 3); + assert_eq!(backlog_spec().version, 4); let plan_set = event( 17, "questions.opened", @@ -623,4 +696,63 @@ mod tests { assert!(answer.is_err(), "{}: {answer:?}", undeclared.type_name); } } + + /// Plan `plan` of phase 1 approved, serving `stories` with `size` tasks. + fn approved(seq: u64, plan: u32, stories: &[u32], size: usize) -> Event { + let body = PayloadRef { + hash: Hash([0xab; 32]), + bytes: 24, + class: RetentionClass::Record, + }; + let approval = crate::plan::PlanApproval { + phase: 1, + plan, + digest: Hash([0x5c; 32]), + stories, + size, + suite: None, + question_set: S, + evidence_map: &[], + body: &body, + owner: "Ada Owner", + at: "2026-10-31T09:00:00Z", + }; + event(seq, "plan.approved", approval.payload()) + } + + /// The sizes of stories 1, 2 and 3. + fn sizes(stories: &Value) -> [Value; 3] { + [1, 2, 3].map(|id| entry(stories, id)["size"].clone()) + } + + #[test] + fn a_story_size_counted_from_estimates_or_left_after_replacement_is_caught() { + let mut events = vec![approved(14, 1, &[1, 2], 2)]; + assert_eq!( + sizes(&after_s1(events.clone())), + [json!(2), json!(2), Value::Null] + ); + events.push(approved(15, 2, &[1], 3)); + assert_eq!( + sizes(&after_s1(events.clone())), + [json!(5), json!(2), Value::Null] + ); + events.push(approved(16, 3, &[2], 1)); + let replaced = crate::plan::replaced_payload( + 1, + 1, + Hash([0x5c; 32]), + Hash([0x7e; 32]), + "Ada Owner", + "2026-10-31T09:00:00Z", + ); + events.push(event(17, "plan.replaced", replaced)); + let stories = after_s1(events); + assert_eq!(sizes(&stories), [json!(3), json!(1), Value::Null]); + + let document = json!({KEY_FIELD: PROJECT_KEY, "stories": stories}); + let unheld = approved(18, 4, &[9], 1); + let answer = BacklogProjector::new().apply(&unheld, &[(backlog_key(), document)]); + assert!(answer.is_err(), "{answer:?}"); + } } diff --git a/crates/baley-core/src/work_order/event.rs b/crates/baley-core/src/work_order/event.rs index 29bcc9c0..1ed02ca5 100644 --- a/crates/baley-core/src/work_order/event.rs +++ b/crates/baley-core/src/work_order/event.rs @@ -1,18 +1,23 @@ //! The work-order events: their types, their registration, their streams //! and their payloads (design 0001 Streams and Payloads, design 0012). //! -//! An order's failure goes on the stream its issue went on. No payload holds -//! a caller or a time: the envelope carries both, hashed with the event. +//! The start's and a story's orders go on `roadmap`, and a phase planner's +//! on its phase's stream, `phase/`. An order's failure goes on the +//! stream its issue went on. No payload holds a caller or a time: the +//! envelope carries both, hashed with the event. + +use std::borrow::Cow; use baley_store::{InstructionEvidence, PayloadRef}; use serde_json::{Value, json}; +use crate::plan::phase_stream; use crate::policy::{Role, Rung}; use crate::registry::{Registry, RegistryError}; use crate::scope::ROADMAP_STREAM; /// One work order issued, on its subject's stream (`roadmap` for the start -/// and a story's analyzer orders): +/// and a story's analyzer orders, `phase/` for a phase's planner orders): /// `{id, request, parent, role, subject, attempt, route, agent, /// instructions, inputs}`. `request` is the id of its chain's first order, /// `parent` the failed order it retries or null, `instructions` a list of @@ -50,7 +55,29 @@ pub fn story_subject(story: u32) -> String { /// text. Only the spelling [`story_subject`] writes is read, decimal with /// no sign or leading zero, so one story never has two subjects. pub fn subject_story(subject: &str) -> Option { - let digits = subject.strip_prefix(STORY_SUBJECT_PREFIX)?; + canonical_number(subject.strip_prefix(STORY_SUBJECT_PREFIX)?) +} + +/// What a planner order's subject starts with, before its phase's number. +const PHASE_SUBJECT_PREFIX: &str = "phase/"; + +/// The subject of phase `phase`'s planner orders, `phase/`. The planning +/// and revision orders both carry it, so one look at the `live` index finds +/// either one pending (D-11). +pub fn phase_subject(phase: u32) -> String { + format!("{PHASE_SUBJECT_PREFIX}{phase}") +} + +/// The phase a planner order's subject names, or none for any other text. +/// Only the spelling [`phase_subject`] writes is read, decimal with no sign +/// or leading zero, so one phase never has two subjects. +pub fn subject_phase(subject: &str) -> Option { + canonical_number(subject.strip_prefix(PHASE_SUBJECT_PREFIX)?) +} + +/// `digits` as a number when it is spelled decimal with no sign or leading +/// zero, or none. +fn canonical_number(digits: &str) -> Option { let canonical = !digits.is_empty() && !digits.starts_with('0') && digits.bytes().all(|byte| byte.is_ascii_digit()); @@ -58,10 +85,14 @@ pub fn subject_story(subject: &str) -> Option { } /// The stream an order of `subject` is recorded on: `roadmap` for the -/// start and for a story's analyzer orders. Other subjects get theirs with -/// the builds that issue them. -pub fn order_stream(subject: &str) -> Option<&'static str> { - (subject == START_SUBJECT || subject_story(subject).is_some()).then_some(ROADMAP_STREAM) +/// start and for a story's analyzer orders, and the phase's own stream, +/// `phase/`, for a phase's planner orders (D-11). Other subjects get +/// theirs with the builds that issue them. +pub fn order_stream(subject: &str) -> Option> { + if subject == START_SUBJECT || subject_story(subject).is_some() { + return Some(Cow::Borrowed(ROADMAP_STREAM)); + } + subject_phase(subject).map(|phase| Cow::Owned(phase_stream(phase))) } /// The agent stub a role runs at a rung, `bal--`. Install places @@ -232,7 +263,7 @@ mod tests { #[test] fn a_start_order_off_the_roadmap_stream_or_an_agent_off_the_name_rule_is_caught() { - assert_eq!(order_stream("start"), Some("roadmap")); + assert_eq!(order_stream("start").as_deref(), Some("roadmap")); let names: BTreeSet = Role::ALL .into_iter() .flat_map(|role| Rung::ALL.map(|rung| agent_name(role, rung))) @@ -251,11 +282,25 @@ mod tests { #[test] fn an_analyzer_order_off_the_roadmap_stream_or_misread_subject_is_caught() { assert_eq!(story_subject(12), "story/12"); - assert_eq!(order_stream("story/12"), Some("roadmap")); + assert_eq!(order_stream("story/12").as_deref(), Some("roadmap")); assert_eq!(subject_story("story/12"), Some(12)); - for other in ["story/012", "story/0", "story/", "story/x", "phase/12"] { + for other in ["story/012", "story/0", "story/", "story/x"] { assert_eq!(subject_story(other), None, "{other}"); assert_eq!(order_stream(other), None, "{other}"); } + assert_eq!(subject_story("phase/12"), None); + } + + #[test] + fn a_phase_subject_spelled_two_ways_or_recorded_off_its_stream_is_caught() { + assert_eq!(phase_subject(7), "phase/7"); + assert_eq!(subject_phase("phase/7"), Some(7)); + for other in ["phase/07", "phase/", "phase/x", "phase/+7"] { + assert_eq!(subject_phase(other), None, "{other}"); + assert_eq!(order_stream(other), None, "{other}"); + } + assert_eq!(order_stream("phase/7").as_deref(), Some("phase/7")); + assert_eq!(order_stream("story/1").as_deref(), Some("roadmap")); + assert_eq!(order_stream("start").as_deref(), Some("roadmap")); } } diff --git a/crates/baley-core/src/work_order/mod.rs b/crates/baley-core/src/work_order/mod.rs index 1ceab497..d9339330 100644 --- a/crates/baley-core/src/work_order/mod.rs +++ b/crates/baley-core/src/work_order/mod.rs @@ -13,7 +13,8 @@ mod view; pub use event::{ IssuedOrder, OrderInput, START_SUBJECT, WORK_ORDER_FAILED, WORK_ORDER_FAILED_VERSION, WORK_ORDER_ISSUED, WORK_ORDER_ISSUED_VERSION, agent_name, failed_payload, issued_payload, - order_stream, register_work_order_events, story_subject, subject_story, + order_stream, phase_subject, register_work_order_events, story_subject, subject_phase, + subject_story, }; pub use retry::{ ANALYZER_ORDER_PENDING, MATERIAL_UNAVAILABLE, NO_SUCH_WORK_ORDER, Retry, RetryRefusal, diff --git a/crates/baley/src/guard_hook/context.rs b/crates/baley/src/guard_hook/context.rs index dd445e90..c5710208 100644 --- a/crates/baley/src/guard_hook/context.rs +++ b/crates/baley/src/guard_hook/context.rs @@ -233,6 +233,7 @@ mod tests { "/u/.claude/skills/bal-story/SKILL.md", "/u/.claude/skills/bal-backlog/SKILL.md", "/u/.claude/skills/bal-context/SKILL.md", + "/u/.claude/skills/bal-plan/SKILL.md", "/u/.claude/skills/bal-capture/SKILL.md", "/u/.claude/skills/bal-help/SKILL.md", "/u/.claude.json", @@ -404,7 +405,7 @@ mod tests { let skills = stubs::manifest(&stubs::front_doors()).unwrap(); let agents = agents::manifest(); - assert_eq!(skills.len(), 8); + assert_eq!(skills.len(), 9); assert_eq!(agents.len(), 30); let expected: Vec = skills.into_iter().chain(agents).collect(); assert_eq!(stubs::installed_manifest(), expected); diff --git a/crates/baley/src/help/front_door.rs b/crates/baley/src/help/front_door.rs index f601ed84..62de1979 100644 --- a/crates/baley/src/help/front_door.rs +++ b/crates/baley/src/help/front_door.rs @@ -6,11 +6,11 @@ pub const IDENTITY: &str = "bal-help"; /// Pinned by hand: raise it by one whenever [`TEXT`] changes. -pub const VERSION: &str = "3"; +pub const VERSION: &str = "4"; /// 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 = "31ecd5654bebed4db300e611dc9bb8dfa4cd2993c79e251bef681ed6495e3f5a"; +pub const HASH: &str = "8e5cc78fc9084512af3a9700565869b33ed2181579fbf72132125f8f07df0cfd"; /// What a session is told when it follows the help command. pub const TEXT: &str = r#"Baley help lists the commands Baley offers and says what each one does. @@ -23,5 +23,5 @@ When an answer carries a `next` that is not null, call again with the same argum Read nothing else, search nothing and write nothing. Help reads only what Baley has compiled. -Send `bal-help`, the identity of this instruction, as `instruction` when you call the `baley_apply` operation `capture`, `project-start`, `story-refine`, `work-order-fail` or `work-order-retry` while following it. Send it on no other `baley_apply` operation, since their shapes refuse it. Never send it on a `baley_query` call. +Send `bal-help`, the identity of this instruction, as `instruction` when you call the `baley_apply` operation `capture`, `phase-plan`, `project-start`, `story-refine`, `work-order-fail` or `work-order-retry` while following it. Send it on no other `baley_apply` operation, since their shapes refuse it. Never send it on a `baley_query` call. "#; diff --git a/crates/baley/src/help/table.rs b/crates/baley/src/help/table.rs index 3c8b938c..29e34386 100644 --- a/crates/baley/src/help/table.rs +++ b/crates/baley/src/help/table.rs @@ -53,7 +53,7 @@ pub const COMMANDS: &[Command] = &[ Command { name: "bal-plan", cluster: "Build spine", - description: "Author a phase's plans and publish the exact owner-approved content through Baley", + description: "Plan a phase with its owner: the committed stories, the planner's typed plan and its questions in rounds, then the draft the owner approves at the terminal.", }, Command { name: "bal-execute", @@ -209,7 +209,7 @@ pub fn render_description(name: &str, markdown: &str) -> Option { const ABOUT: &str = "Baley keeps AI coding agents accountable to the person who answers for their work. It records what the agents did, and the proof that it works, in a hash-chained ledger the owner controls, and it refuses to let work move on an unproven claim. Claude Code is the host it serves."; /// The request a session follows so the ledger can say which instruction guided a write. -const REQUEST: &str = "Send `bal-help` as `instruction` on the `baley_apply` operations `capture`, `project-start`, `story-refine`, `work-order-fail` and `work-order-retry` called while following help, on no other `baley_apply` operation, and on no `baley_query` call."; +const REQUEST: &str = "Send `bal-help` as `instruction` on the `baley_apply` operations `capture`, `phase-plan`, `project-start`, `story-refine`, `work-order-fail` and `work-order-retry` called while following help, on no other `baley_apply` operation, and on no `baley_query` call."; /// The help instruction's identity, version and hash, as the registry serves them. fn help_instruction() -> Value { @@ -287,7 +287,7 @@ mod tests { ("bal-help", true, 3), ("bal-capture", true, 3), ("bal-context", true, 4), - ("bal-plan", false, 4), + ("bal-plan", true, 4), ("bal-review", false, 4), ("bal-plan-review", false, 4), ("bal-decision-review", false, 4), @@ -340,7 +340,7 @@ mod tests { let plan = answer(Some("plan")); let rows = plan["rows"].as_array().unwrap(); assert_eq!(rows.len(), 1); - assert_eq!(triple(&rows[0]), ("bal-plan".to_owned(), false, 4)); + assert_eq!(triple(&rows[0]), ("bal-plan".to_owned(), true, 4)); let help = answer(Some("/bal-help")); assert_eq!( triple(&help["rows"].as_array().unwrap()[0]), diff --git a/crates/baley/src/host_artifacts/command.rs b/crates/baley/src/host_artifacts/command.rs index c6871fa9..1ebbc5e2 100644 --- a/crates/baley/src/host_artifacts/command.rs +++ b/crates/baley/src/host_artifacts/command.rs @@ -267,7 +267,8 @@ mod tests { }], }); assert_eq!(stdout_bytes(&partial), bytes.as_slice()); - let refused: Result = Err(Refusal::UnknownStub("bal-plan".to_owned())); + let refused: Result = + Err(Refusal::UnknownStub("bal-review".to_owned())); assert!(stdout_bytes(&refused).is_empty()); } @@ -297,6 +298,7 @@ mod tests { "bal-context", "bal-help", "bal-phase", + "bal-plan", "bal-project", "bal-scope", "bal-story", @@ -378,11 +380,11 @@ mod tests { #[test] fn an_unknown_stub_printed_as_another_or_refused_without_its_name_is_caught() { let request = Request::Stub { - identity: "bal-plan".to_owned(), + identity: "bal-review".to_owned(), }; let refused = select(&request).unwrap_err(); - assert_eq!(refused, Refusal::UnknownStub("bal-plan".to_owned())); - assert!(refused.to_string().contains("bal-plan")); + assert_eq!(refused, Refusal::UnknownStub("bal-review".to_owned())); + assert!(refused.to_string().contains("bal-review")); } #[test] diff --git a/crates/baley/src/host_artifacts/installed.rs b/crates/baley/src/host_artifacts/installed.rs index 3b8bd5ae..baf4a47e 100644 --- a/crates/baley/src/host_artifacts/installed.rs +++ b/crates/baley/src/host_artifacts/installed.rs @@ -202,6 +202,10 @@ mod tests { Artifact::Stub("bal-context".into()), PathBuf::from(format!("{folder}/skills/bal-context/SKILL.md")), ), + ( + Artifact::Stub("bal-plan".into()), + PathBuf::from(format!("{folder}/skills/bal-plan/SKILL.md")), + ), ( Artifact::Stub("bal-capture".into()), PathBuf::from(format!("{folder}/skills/bal-capture/SKILL.md")), @@ -298,6 +302,7 @@ mod tests { "/home/o/.claude/skills/bal-story/SKILL.md", "/home/o/.claude/skills/bal-backlog/SKILL.md", "/home/o/.claude/skills/bal-context/SKILL.md", + "/home/o/.claude/skills/bal-plan/SKILL.md", "/home/o/.claude/skills/bal-capture/SKILL.md", "/home/o/.claude/skills/bal-help/SKILL.md", ] @@ -381,6 +386,7 @@ mod tests { PathBuf::from("/home/o/.claude/skills/bal-story/SKILL.md"), PathBuf::from("/home/o/.claude/skills/bal-backlog/SKILL.md"), PathBuf::from("/home/o/.claude/skills/bal-context/SKILL.md"), + PathBuf::from("/home/o/.claude/skills/bal-plan/SKILL.md"), PathBuf::from("/home/o/.claude/skills/bal-capture/SKILL.md"), PathBuf::from("/home/o/.claude/skills/bal-help/SKILL.md"), PathBuf::from("/home/o/.claude.json"), diff --git a/crates/baley/src/host_artifacts/stubs.rs b/crates/baley/src/host_artifacts/stubs.rs index cfadc82c..bf3f8104 100644 --- a/crates/baley/src/host_artifacts/stubs.rs +++ b/crates/baley/src/host_artifacts/stubs.rs @@ -117,10 +117,9 @@ mod tests { use super::*; - /// The eighteen front doors not served yet, written out by hand as + /// The seventeen front doors not served yet, written out by hand as /// `instruction/tests.rs` lists them. const UNAVAILABLE: &[&str] = &[ - "bal-plan", "bal-review", "bal-plan-review", "bal-decision-review", @@ -163,11 +162,12 @@ mod tests { "bal-story", "bal-backlog", "bal-context", + "bal-plan", "bal-capture", "bal-help", ] ); - assert_eq!(UNAVAILABLE.len(), 18); + assert_eq!(UNAVAILABLE.len(), 17); for identity in UNAVAILABLE.iter().chain(&["bal-read-contract"]) { assert!(!identities.contains(identity), "{identity} has a stub"); } @@ -192,6 +192,7 @@ mod tests { "bal-story", "bal-backlog", "bal-context", + "bal-plan", "bal-capture", "bal-help", ] @@ -246,6 +247,7 @@ mod tests { "bal-context", "bal-help", "bal-phase", + "bal-plan", "bal-project", "bal-scope", "bal-story", diff --git a/crates/baley/src/host_doctor/mod.rs b/crates/baley/src/host_doctor/mod.rs index e218f4b7..54b2f7e1 100644 --- a/crates/baley/src/host_doctor/mod.rs +++ b/crates/baley/src/host_doctor/mod.rs @@ -1311,6 +1311,7 @@ mod tests { "bal-story", "bal-backlog", "bal-context", + "bal-plan", "bal-capture", "bal-help", ], @@ -1347,6 +1348,10 @@ mod tests { Artifact::Stub("bal-context".into()), "/home/o/.claude/skills/bal-context/SKILL.md".to_owned() ), + ( + Artifact::Stub("bal-plan".into()), + "/home/o/.claude/skills/bal-plan/SKILL.md".to_owned() + ), ( Artifact::Stub("bal-capture".into()), "/home/o/.claude/skills/bal-capture/SKILL.md".to_owned() @@ -1384,6 +1389,7 @@ mod tests { Artifact::Stub("bal-story".into()), Artifact::Stub("bal-backlog".into()), Artifact::Stub("bal-context".into()), + Artifact::Stub("bal-plan".into()), Artifact::Stub("bal-capture".into()), Artifact::Stub("bal-help".into()), Artifact::Registration, @@ -1429,6 +1435,7 @@ mod tests { Artifact::Stub("bal-story".into()), Artifact::Stub("bal-backlog".into()), Artifact::Stub("bal-context".into()), + Artifact::Stub("bal-plan".into()), Artifact::Stub("bal-help".into()), Artifact::Registration, ] @@ -1455,6 +1462,7 @@ mod tests { Artifact::Stub("bal-story".into()), Artifact::Stub("bal-backlog".into()), Artifact::Stub("bal-context".into()), + Artifact::Stub("bal-plan".into()), Artifact::Stub("bal-capture".into()), Artifact::Hook, Artifact::Settings, diff --git a/crates/baley/src/host_doctor/writable.rs b/crates/baley/src/host_doctor/writable.rs index 80427736..ced3193e 100644 --- a/crates/baley/src/host_doctor/writable.rs +++ b/crates/baley/src/host_doctor/writable.rs @@ -163,6 +163,7 @@ mod tests { "/home/o/.claude/skills/bal-story", "/home/o/.claude/skills/bal-backlog", "/home/o/.claude/skills/bal-context", + "/home/o/.claude/skills/bal-plan", "/home/o/.claude/skills/bal-capture", "/home/o/.claude/skills/bal-help", "/home/o/.claude", @@ -193,6 +194,7 @@ mod tests { "/srv/claude/skills/bal-story", "/srv/claude/skills/bal-backlog", "/srv/claude/skills/bal-context", + "/srv/claude/skills/bal-plan", "/srv/claude/skills/bal-capture", "/srv/claude/skills/bal-help", "/srv/claude", diff --git a/crates/baley/src/install/mod.rs b/crates/baley/src/install/mod.rs index 3d9845f2..76d6dc6d 100644 --- a/crates/baley/src/install/mod.rs +++ b/crates/baley/src/install/mod.rs @@ -116,6 +116,7 @@ pub(crate) mod fixtures { "Edit(//home/o/.claude/skills/bal-story/SKILL.md)", "Edit(//home/o/.claude/skills/bal-backlog/SKILL.md)", "Edit(//home/o/.claude/skills/bal-context/SKILL.md)", + "Edit(//home/o/.claude/skills/bal-plan/SKILL.md)", "Edit(//home/o/.local/lib/crenshawdev/baley/versions/**)", "Edit(//home/o/.config/crenshawdev/baley/**)", "Read(//home/o/.config/crenshawdev/baley/**)", @@ -143,6 +144,7 @@ pub(crate) mod fixtures { "/home/o/.claude/skills/bal-story/SKILL.md", "/home/o/.claude/skills/bal-backlog/SKILL.md", "/home/o/.claude/skills/bal-context/SKILL.md", + "/home/o/.claude/skills/bal-plan/SKILL.md", "/home/o/.local/lib/crenshawdev/baley/versions", "/home/o/.config/crenshawdev/baley", "/home/o/.local/share/crenshawdev/baley", diff --git a/crates/baley/src/install/plan.rs b/crates/baley/src/install/plan.rs index 72621727..2b7f8493 100644 --- a/crates/baley/src/install/plan.rs +++ b/crates/baley/src/install/plan.rs @@ -838,6 +838,10 @@ mod tests { PathBuf::from("/home/o/.claude/skills/bal-context/SKILL.md"), seen(FileState::Absent), ), + ( + PathBuf::from("/home/o/.claude/skills/bal-plan/SKILL.md"), + seen(FileState::Absent), + ), (capture.clone(), seen(FileState::Absent)), (help.clone(), seen(FileState::Bytes(b"mine".to_vec()))), ]); @@ -879,6 +883,7 @@ mod tests { (Artifact::Stub("bal-story".into()), stubs.clone()), (Artifact::Stub("bal-backlog".into()), stubs.clone()), (Artifact::Stub("bal-context".into()), stubs.clone()), + (Artifact::Stub("bal-plan".into()), stubs.clone()), (Artifact::Stub("bal-capture".into()), stubs.clone()), (Artifact::Stub("bal-help".into()), stubs), (Artifact::Registration, ArtifactOutcome::NotWritten), @@ -924,7 +929,7 @@ mod tests { assert_eq!(facts.hook, None); assert_eq!(facts.sandbox, None); assert!(!facts.complete); - assert_eq!(facts.stubs.len(), 8); + assert_eq!(facts.stubs.len(), 9); // A completed installation left unchanged stays in the record. let complete = complete_settings(); @@ -947,8 +952,8 @@ mod tests { "/home/o/.config/crenshawdev/baley" ] ); - assert_eq!(sandbox.deny_write.len(), 14); - assert_eq!(sandbox.permissions_deny.len(), 16); + assert_eq!(sandbox.deny_write.len(), 15); + assert_eq!(sandbox.permissions_deny.len(), 17); // The write failed over Baley's own older entries. let old_hook = json!({ @@ -1203,7 +1208,7 @@ mod tests { assert!(plan.writes.is_empty(), "{:?}", plan.writes); assert_eq!(plan.registration, Step::Unchanged); - assert_eq!(plan.outcomes.len(), 11); + assert_eq!(plan.outcomes.len(), 12); for (artifact, outcome) in &plan.outcomes { assert_eq!(*outcome, ArtifactOutcome::Unchanged, "{artifact}"); } @@ -1231,6 +1236,7 @@ mod tests { Artifact::Stub("bal-context".into()), ArtifactOutcome::Written, ), + (Artifact::Stub("bal-plan".into()), ArtifactOutcome::Written), ( Artifact::Stub("bal-capture".into()), ArtifactOutcome::Written, @@ -1333,14 +1339,14 @@ mod tests { assert_eq!(document["sandbox"]["enabled"], true); assert_eq!( document["permissions"]["deny"].as_array().unwrap().len(), - 16 + 17 ); let stubs = plan .writes .iter() .filter(|write| matches!(write.artifacts[0], Artifact::Stub(_))) .count(); - assert_eq!(stubs, 8); + assert_eq!(stubs, 9); assert_eq!(plan.writes[0].artifacts, [Artifact::Settings]); let wiring = plan.wiring.as_ref().expect("the wiring is held back"); assert!(wiring.gap.contains(stable), "{}", wiring.gap); @@ -1667,6 +1673,10 @@ mod tests { Artifact::Stub("bal-context".into()), ArtifactOutcome::Unchanged, ), + ( + Artifact::Stub("bal-plan".into()), + ArtifactOutcome::Unchanged, + ), ( Artifact::Stub("bal-capture".into()), ArtifactOutcome::Unchanged, @@ -1713,6 +1723,7 @@ mod tests { "bal-story", "bal-backlog", "bal-context", + "bal-plan", "bal-capture", "bal-help", ] @@ -1729,13 +1740,14 @@ mod tests { "bal-story", "bal-backlog", "bal-context", + "bal-plan", "bal-capture", "bal-help", "bal-old", ] ); assert_eq!( - left.stubs[8], + left.stubs[9], event::Stub { identity: "bal-old".into(), path: OLD.into(), @@ -1755,6 +1767,7 @@ mod tests { "bal-story", "bal-backlog", "bal-context", + "bal-plan", "bal-capture", "bal-help", "bal-old", diff --git a/crates/baley/src/install/receipt.rs b/crates/baley/src/install/receipt.rs index fadf5739..6f135ec9 100644 --- a/crates/baley/src/install/receipt.rs +++ b/crates/baley/src/install/receipt.rs @@ -278,6 +278,7 @@ mod tests { (Artifact::Stub("bal-story".into()), outcome.clone()), (Artifact::Stub("bal-backlog".into()), outcome.clone()), (Artifact::Stub("bal-context".into()), outcome.clone()), + (Artifact::Stub("bal-plan".into()), outcome.clone()), (Artifact::Stub("bal-capture".into()), outcome.clone()), (Artifact::Stub("bal-help".into()), outcome.clone()), (Artifact::Registration, outcome.clone()), @@ -315,6 +316,10 @@ mod tests { Artifact::Stub("bal-context".into()), ArtifactOutcome::Unchanged, ), + ( + Artifact::Stub("bal-plan".into()), + ArtifactOutcome::Unchanged, + ), ( Artifact::Stub("bal-capture".into()), ArtifactOutcome::Replaced, @@ -339,15 +344,15 @@ mod tests { &Ok(true), ); assert_eq!( - receipt.lines[8], + receipt.lines[9], "stub `bal-capture` at /home/o/.claude/skills/bal-capture/SKILL.md: replaced" ); assert_eq!( - receipt.lines[9], + receipt.lines[10], "stub `bal-help` at /home/o/.claude/skills/bal-help/SKILL.md: unchanged" ); - applied.outcomes[7].1 = ArtifactOutcome::Failed("Permission denied".into()); + applied.outcomes[8].1 = ArtifactOutcome::Failed("Permission denied".into()); applied.failure = Some( "not-writable: /home/o/.claude/skills/bal-help/SKILL.md: Permission denied".into(), ); @@ -360,7 +365,7 @@ mod tests { &Err(StoreError::Busy), ); assert_eq!( - receipt.lines[9], + receipt.lines[10], "stub `bal-help` at /home/o/.claude/skills/bal-help/SKILL.md: not written: Permission denied" ); assert!(receipt.lines.contains(applied.failure.as_ref().unwrap())); @@ -390,7 +395,7 @@ mod tests { .any(|line| line == "install outcome: complete") ); assert_eq!( - receipt.lines[2..13], + receipt.lines[2..14], [ "stub `bal-project` at /home/o/.claude/skills/bal-project/SKILL.md: not written", "stub `bal-scope` at /home/o/.claude/skills/bal-scope/SKILL.md: not written", @@ -398,6 +403,7 @@ mod tests { "stub `bal-story` at /home/o/.claude/skills/bal-story/SKILL.md: not written", "stub `bal-backlog` at /home/o/.claude/skills/bal-backlog/SKILL.md: not written", "stub `bal-context` at /home/o/.claude/skills/bal-context/SKILL.md: not written", + "stub `bal-plan` at /home/o/.claude/skills/bal-plan/SKILL.md: not written", "stub `bal-capture` at /home/o/.claude/skills/bal-capture/SKILL.md: not written", "stub `bal-help` at /home/o/.claude/skills/bal-help/SKILL.md: not written", "registration at /home/o/.claude.json: not written", @@ -422,7 +428,7 @@ mod tests { ); assert_eq!(receipt.lines[1], "baley 0.2.0 at /home/o/.local/bin/baley"); assert_eq!( - receipt.lines[14..], + receipt.lines[15..], [ "start a new Claude Code session to load the wiring", "run baley init in each checkout Baley should manage", @@ -447,7 +453,7 @@ mod tests { &Err(StoreError::Busy), ); assert_eq!( - receipt.lines[13], + receipt.lines[14], "the model catalog seed was not recorded: the ledger is busy; run the command again" ); assert_eq!(receipt.lines[0], "install outcome: partial"); @@ -473,7 +479,7 @@ mod tests { "the model catalog seed with hint table version {HINT_VERSION} is already recorded" ) }; - assert_eq!(receipt.lines[13], expected); + assert_eq!(receipt.lines[14], expected); } } #[test] @@ -530,6 +536,10 @@ mod tests { "/home/o/.claude/skills/bal-context/SKILL.md".into(), seen(FileState::Absent), ), + ( + "/home/o/.claude/skills/bal-plan/SKILL.md".into(), + seen(FileState::Absent), + ), ( "/home/o/.claude/skills/bal-capture/SKILL.md".into(), seen(FileState::Absent), @@ -833,11 +843,11 @@ mod tests { let removed = render_with(RetiredOutcome::Removed); assert_eq!(removed.lines[0], "install outcome: complete"); assert_eq!( - removed.lines[13], + removed.lines[14], "stub `bal-old` at /home/o/.claude/skills/bal-old/SKILL.md: removed, since this binary no longer ships it" ); assert!( - removed.lines[14].contains("model catalog"), + removed.lines[15].contains("model catalog"), "{:?}", removed.lines ); @@ -846,7 +856,7 @@ mod tests { let left = render_with(RetiredOutcome::Failed("not-removable: denied".into())); assert_eq!(left.lines[0], "install outcome: partial"); assert_eq!( - left.lines[13], + left.lines[14], "stub `bal-old` at /home/o/.claude/skills/bal-old/SKILL.md: not removed: not-removable: denied" ); assert_eq!(left.code, 1); @@ -856,7 +866,7 @@ mod tests { let carried = render_with(RetiredOutcome::Carried); assert_eq!(carried.lines[0], "install outcome: complete"); assert!( - carried.lines[13].contains("model catalog"), + carried.lines[14].contains("model catalog"), "{:?}", carried.lines ); diff --git a/crates/baley/src/install/record.rs b/crates/baley/src/install/record.rs index d0f02504..125671a9 100644 --- a/crates/baley/src/install/record.rs +++ b/crates/baley/src/install/record.rs @@ -193,13 +193,14 @@ mod tests { } /// The shipped front doors in manifest order, written out by hand. - const STUBS: [&str; 8] = [ + const STUBS: [&str; 9] = [ "bal-project", "bal-scope", "bal-phase", "bal-story", "bal-backlog", "bal-context", + "bal-plan", "bal-capture", "bal-help", ]; diff --git a/crates/baley/src/install/settings.rs b/crates/baley/src/install/settings.rs index 3a17da48..00a0ced0 100644 --- a/crates/baley/src/install/settings.rs +++ b/crates/baley/src/install/settings.rs @@ -800,6 +800,7 @@ mod tests { "/home/o/.claude/skills/bal-story/SKILL.md", "/home/o/.claude/skills/bal-backlog/SKILL.md", "/home/o/.claude/skills/bal-context/SKILL.md", + "/home/o/.claude/skills/bal-plan/SKILL.md", "/home/o/.claude/skills/bal-capture/SKILL.md", "/home/o/.claude/skills/bal-help/SKILL.md", "/home/o/.claude.json", @@ -821,6 +822,7 @@ mod tests { "Edit(//home/o/.claude/skills/bal-story/SKILL.md)", "Edit(//home/o/.claude/skills/bal-backlog/SKILL.md)", "Edit(//home/o/.claude/skills/bal-context/SKILL.md)", + "Edit(//home/o/.claude/skills/bal-plan/SKILL.md)", "Edit(//home/o/.claude/skills/bal-capture/SKILL.md)", "Edit(//home/o/.claude/skills/bal-help/SKILL.md)", "Edit(//home/o/.claude.json)", @@ -1069,6 +1071,7 @@ mod tests { "Edit(//home/o/.claude/skills/bal-story/SKILL.md)", "Edit(//home/o/.claude/skills/bal-backlog/SKILL.md)", "Edit(//home/o/.claude/skills/bal-context/SKILL.md)", + "Edit(//home/o/.claude/skills/bal-plan/SKILL.md)", "Edit(//home/o/.claude/skills/bal-capture/SKILL.md)", "Edit(//home/o/.claude/skills/bal-help/SKILL.md)", "Edit(//home/o/.claude.json)", diff --git a/crates/baley/src/instruction/mod.rs b/crates/baley/src/instruction/mod.rs index 51e77c57..cc2ba64b 100644 --- a/crates/baley/src/instruction/mod.rs +++ b/crates/baley/src/instruction/mod.rs @@ -131,11 +131,16 @@ pub static ENTRIES: &[Entry] = &[ body: context::TEXT, }), }, - // Build 4 adds this text beside its operations. + // Build 4 serves the plan front door beside `phase-plan`, `plan-submit`, + // `plan-replace`, `plan-read` and the owner's plan commands. Entry { - identity: "bal-plan", + identity: plan::IDENTITY, build: 4, - text: None, + text: Some(Text { + version: plan::VERSION, + hash: plan::HASH, + body: plan::TEXT, + }), }, // Build 5 adds this text beside its operations. Entry { diff --git a/crates/baley/src/instruction/plan.rs b/crates/baley/src/instruction/plan.rs index 6e019d82..fbd9c7ef 100644 --- a/crates/baley/src/instruction/plan.rs +++ b/crates/baley/src/instruction/plan.rs @@ -1,11 +1,8 @@ -//! The `bal-plan` front door's text, compiled but not served: how a host +//! The `bal-plan` front door's served text, pinned in source: 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. +//! 0005 sections 5, 8 and 10, PLN-R7, PLN-R9, PLN-R10, PLN-R14, PLN-R15, +//! PLN-R24, PLN-R26, PLN-R27). It is a help row, so it gets a skill stub. //! //! The text is ported from Cadence (ADR 0048). Cadence's own files, //! commands and state are replaced by Baley's: the skill's objective @@ -19,14 +16,24 @@ //! 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. +//! does. The operation shapes, receipts and refusals are those Build 4 T9 +//! built: `phase-plan` in `crate::mcp::planning` (`serve`), `plan-submit` +//! and `plan-replace` there (`serve_submit`), `plan-read` there +//! (`serve_read`), the revision order in `crate::questions::answer`, and +//! the terminal commands `baley scope approve`, `baley plan approve` and +//! `baley plan show`. //! //! 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. +//! - The plan-checker gate and its `--skip-check` flag: Build 4 T10, whose +//! checker order is issued between `plan-submit`'s check and its +//! recording (`crate::planning::submit`, `record`). +//! - The lease's risk check at submit: Build 4 T11, at that same seam. +//! - The `plan` review fire: Build 4 T13, which admits the review over a +//! checked draft whose rounds are closed, before `baley plan approve`; +//! and T14, whose `review-unsettled` refuses the approval after its draft +//! refusals (`crate::planning::approve`, `judge`). //! - `--gaps` and its gap plans: Build 5. //! - `--inline` and the `route` step: every role runs from a work order //! (ADR 0046). @@ -60,16 +67,33 @@ //! - 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: +//! These rules are added under ADR 0049, each stated by 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 draft's question set put to the owner through `bal-rounds`, `ready` +//! at a close on the recommended answers, 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`, `answer-not-applied` and `stale-draft` refusing the +//! approval (PLN-R15, PLN-R26, PLN-R27). //! - The proposed split, which the owner decides on (PLN-R10), with //! `over-capacity` (PLN-R9). +//! - A changed selection drafted as a `phase edit` the owner approves, and +//! the one live planner order with its `planner-order-pending` refusal +//! (section 5, `phase plan`). +//! - `plan-replace` for an approved plan the owner replaces, with its +//! `no-such-plan` and `admitted-plan` refusals (PLN-R14). +//! - The approved plans read with `plan-read` or `baley plan show`, a draft +//! never among them (section 6, the `evidence_map` view). + +/// The registry identity of the plan front door. +pub const IDENTITY: &str = "bal-plan"; + +/// 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 = "54f7d52ad86a2c9fb5b0c1bd175e1d5d7e9de47df8976373b819993c4456d2a0"; /// What a session is told when it follows the plan command. Ported from /// Cadence tag `v3.9.0`: `skills/cad-plan/SKILL.md` and @@ -83,9 +107,11 @@ Take the phase the owner names. If none is named, read the accepted roadmap with 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. +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 phase. + +A phase has one live planner order. A `planner-order-pending` refusal names the pending order in `details`: read it with `baley_query` `{"operation":"document","identity":{"kind":"work_order","id":""}}` and launch it, or fail it and retry it as below. -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. +When the stories change what the phase commits, a reorder included, the answer is the draft of that `phase edit` and no order is issued: give the owner its `digest` to preview with `baley scope preview ` and approve with `baley scope approve ` at the terminal. The approval commits the stories and issues the planner's order. Then call `phase-plan` again with the same stories, and its receipt is that approved order. An approval refused at the terminal commits nothing and issues no order. 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. @@ -95,7 +121,11 @@ When the worker cannot launch, or returns without its result, call `baley_apply` 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. +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. Send no `instruction` on this call, since its shape takes none. The receipt gives the draft's `digest`; its `preview`, or the `document` read that shows it when the plan is large; the plan's `size` and the size the phase reaches with it in `reaching`, against the phase's `capacity`; and the draft's question set in `set`, with its first round in `now`. A phase holds one draft at a time: a new submit makes the earlier draft stale and abandons its question set. + +Show the owner a refusal of `plan-submit` with its `code`, `slot` and `reason`: `phase-not-active` while another phase is active, `no-such-work-order` or `wrong-work-order` for an order that is not a planner order of this phase, and a refusal of the plan itself, which names the part of the plan it refuses. + +When the owner replaces an approved plan, submit the planner's new plan with `plan-replace` in place of `plan-submit`: `{"operation":"plan-replace","request_id":"","work_order":"","plan":,"replaces":{"plan":,"digest":""}}`. Read that number and digest with `plan-read`, as below. It is refused `no-such-plan` when no plan of the phase is in force at that number and digest, and `admitted-plan` when the plan is admitted to execution. Its receipt is a submit's. 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. @@ -103,11 +133,13 @@ A returned `Proposed split:`, or a plan refused `over-capacity`, goes to the own 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. +When the set closes on the recommended answers, the receipt that closes it says `ready`: the draft waits for the owner's approval. When it 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, named in the receipt's `revision`. 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 set the owner closed at the terminal gives no such receipt: call `phase-plan` again with the phase's stories, and its receipt is the revision order. 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. +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, one never given in the phase before. While a question of the draft's set is open, the approval is refused `question-open`; when an answer rejected a recommendation, `answer-not-applied`, so the revision's plan is submitted instead; and when a newer submit replaced the draft, `stale-draft`. Nothing is approved over MCP, so approve nothing yourself. + +Read the phase's approved plans, each with its number, its digest and its evidence map, and whether its items still name their truths' current versions, with `baley_query` `{"operation":"plan-read","phase":}`. The owner reads them with `baley plan show `. A replaced plan stays among them, marked replaced; a draft is never among them. A phase that needs another plan gets it from another planner order, submitted on its own and numbered when it is approved. diff --git a/crates/baley/src/instruction/planner.rs b/crates/baley/src/instruction/planner.rs index 46a8b62a..b4395a74 100644 --- a/crates/baley/src/instruction/planner.rs +++ b/crates/baley/src/instruction/planner.rs @@ -115,11 +115,11 @@ pub const IDENTITY: &str = "bal-phase-planner"; /// Pinned by hand: raise it by one whenever [`TEXT`] changes. -pub const VERSION: &str = "1"; +pub const VERSION: &str = "2"; /// 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 = "65a03cb2fcbee8ff52445f5363a51054404085166b9ff2e285117f084315d8c6"; +pub const HASH: &str = "2cfbbeb4b7f766a275204f5ac3bbbad9ff286e7d209bb4d7cb2ddbc3f90210f9"; /// 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` @@ -139,10 +139,11 @@ Orders (your work order says which): 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 phase's number, goal and detail. +- the stories committed to the phase, in order, each with its sentence and 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. +- the evidence items of the phase's approved plans, each with its plan's number: a truth one of them already checks has its one check. - 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. diff --git a/crates/baley/src/instruction/tests.rs b/crates/baley/src/instruction/tests.rs index 19e99699..60acbf75 100644 --- a/crates/baley/src/instruction/tests.rs +++ b/crates/baley/src/instruction/tests.rs @@ -2,10 +2,9 @@ use serde_json::json; use super::*; -/// The eighteen front doors not served yet, with their owning builds, written out from the +/// The seventeen front doors not served yet, with their owning builds, written out from the /// design rather than read from the table under test. const UNAVAILABLE: &[(&str, u32)] = &[ - ("bal-plan", 4), ("bal-review", 4), ("bal-plan-review", 4), ("bal-decision-review", 4), @@ -27,7 +26,7 @@ const UNAVAILABLE: &[(&str, u32)] = &[ #[test] fn an_unavailable_front_door_is_never_presented_as_usable_and_names_its_owning_build() { - assert_eq!(UNAVAILABLE.len(), 18); + assert_eq!(UNAVAILABLE.len(), 17); for (identity, build) in UNAVAILABLE { assert_eq!( lookup(identity), @@ -44,13 +43,13 @@ fn an_unavailable_front_door_is_never_presented_as_usable_and_names_its_owning_b #[test] fn the_unavailable_refusal_names_the_build_in_words_and_as_an_integer_in_slot_identity() { - let refusal = unavailable("bal-plan", 4); + let refusal = unavailable("bal-review", 4); assert_eq!(refusal["status"], "refused"); assert_eq!(refusal["code"], "instruction-unavailable"); assert_eq!(refusal["slot"], "identity"); assert_eq!(refusal["details"], json!({"build": 4})); let reason = refusal["reason"].as_str().unwrap(); - assert!(reason.contains("Build 4") && reason.contains("bal-plan")); + assert!(reason.contains("Build 4") && reason.contains("bal-review")); } #[test] @@ -191,6 +190,21 @@ const SERVED_EVER: &[(&str, &str, &str)] = &[ "1", "65a03cb2fcbee8ff52445f5363a51054404085166b9ff2e285117f084315d8c6", ), + ( + "bal-phase-planner", + "2", + "2cfbbeb4b7f766a275204f5ac3bbbad9ff286e7d209bb4d7cb2ddbc3f90210f9", + ), + ( + "bal-help", + "4", + "8e5cc78fc9084512af3a9700565869b33ed2181579fbf72132125f8f07df0cfd", + ), + ( + "bal-plan", + "1", + "54f7d52ad86a2c9fb5b0c1bd175e1d5d7e9de47df8976373b819993c4456d2a0", + ), ]; fn served() -> impl Iterator { @@ -332,8 +346,8 @@ fn every_served_entry_fits_the_caller_records_limits_as_evidence() { #[test] fn an_unavailable_or_unknown_identity_is_refused_and_given_no_evidence() { assert_eq!( - evidence("bal-plan").unwrap_err(), - unavailable("bal-plan", 4) + evidence("bal-review").unwrap_err(), + unavailable("bal-review", 4) ); assert_eq!(evidence("no-such-instruction").unwrap_err(), unknown()); } @@ -794,13 +808,6 @@ fn a_number_handed_to_the_planner_is_caught() { 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] @@ -931,7 +938,7 @@ fn a_planner_text_given_a_help_row_or_a_skill_stub_is_caught() { panic!("{identity} is served"); }; assert_eq!(entry.build, 4); - assert_eq!(text.version, "1"); + assert_eq!(text.version, "2"); assert!( !crate::help::table::COMMANDS .iter() @@ -947,6 +954,28 @@ fn a_planner_text_given_a_help_row_or_a_skill_stub_is_caught() { assert!(!identity.starts_with("bal-planner-")); } +#[test] +fn a_planner_input_list_missing_the_approved_plans_items_is_caught() { + let Lookup::Served { text, .. } = lookup("bal-phase-planner") else { + panic!("bal-phase-planner is served"); + }; + let start = text + .body + .find("") + .expect("the text has an input list"); + let end = text.body.find("").expect("the input list ends"); + let list = &text.body[start..end]; + assert!( + list.contains("the evidence items of the phase's approved plans"), + "the input list lacks the approved plans' items: {list}" + ); + assert!( + list.contains("the phase's number, goal and detail"), + "{list}" + ); + assert_eq!(text.version, "2"); +} + #[test] fn a_planner_text_naming_cadence_files_or_markers_is_caught() { let body = served_text("bal-phase-planner"); @@ -1015,3 +1044,126 @@ fn a_plan_door_naming_cadence_state_or_a_later_tasks_step_is_caught() { ); } } + +/// The backticked call in `body` whose operation is `name`. +fn call<'a>(body: &'a str, name: &str) -> &'a str { + let opening = format!(r#"`{{"operation":"{name}""#); + let start = body + .find(&opening) + .unwrap_or_else(|| panic!("the text holds no {name} call")) + + 1; + let end = start + body[start..].find('`').expect("the call's span closes"); + &body[start..end] +} + +#[test] +fn a_bal_plan_text_naming_an_operation_shape_that_was_not_built_is_caught() { + use crate::mcp::operations::{self, Tool}; + let Lookup::Served { entry, text } = lookup("bal-plan") else { + panic!("bal-plan is served"); + }; + assert_eq!(entry.build, 4); + assert_eq!(text.version, "1"); + let body = text.body; + // The members each call's served shape takes (D-04, D-08, D-13). + let phase_plan = call(body, "phase-plan"); + for member in [ + r#""request_id":"#, + r#""phase":"#, + r#""stories":["#, + r#""instruction":"bal-plan""#, + ] { + assert!(phase_plan.contains(member), "{phase_plan} lacks {member}"); + } + let submit = call(body, "plan-submit"); + for member in [r#""request_id":"#, r#""work_order":"#, r#""plan":"#] { + assert!(submit.contains(member), "{submit} lacks {member}"); + } + let replace = call(body, "plan-replace"); + for member in [ + r#""work_order":"#, + r#""plan":"#, + r#""replaces":{"plan":"#, + r#""digest":"#, + ] { + assert!(replace.contains(member), "{replace} lacks {member}"); + } + let read = call(body, "plan-read"); + assert!(read.contains(r#""phase":"#), "{read}"); + // Neither submission's shape nor the read's takes an instruction. + for refusing in [submit, replace, read] { + assert!(!refusing.contains("instruction"), "{refusing}"); + } + for needle in [ + "planner-order-pending", + "`ready`", + "baley scope approve", + "baley plan approve", + "baley plan show", + ] { + assert!(body.contains(needle), "the plan front door lacks {needle}"); + } + for word in ["retired", "unavailable"] { + assert!(!body.contains(word), "the plan front door says {word}"); + } + // Every operation the text sends is served on its tool. + let mut named = Vec::new(); + for (at, _) in body.match_indices(r#"{"operation":""#) { + let rest = &body[at + r#"{"operation":""#.len()..]; + named.push(&rest[..rest.find('"').expect("the name closes")]); + } + let applied = [ + "phase-plan", + "work-order-fail", + "work-order-retry", + "plan-submit", + "plan-replace", + ]; + for name in applied { + assert!(named.contains(&name), "the text sends no {name}"); + } + for name in named { + let tool = if applied.contains(&name) { + Tool::Apply + } else { + Tool::Query + }; + assert!( + matches!( + operations::lookup(tool, Some(name)), + operations::Lookup::Available { .. } + ), + "{name} is not served on {}", + tool.name() + ); + } +} + +#[test] +fn bal_plan_left_unserved_or_without_its_stub_is_caught() { + use crate::host_artifacts::stubs; + let answer = crate::help::table::answer(Some("plan")); + let rows = answer["rows"].as_array().expect("help rows"); + assert_eq!(rows.len(), 1, "{answer}"); + assert_eq!(rows[0]["name"], "bal-plan"); + assert_eq!(rows[0]["available"], true); + assert_eq!(rows[0]["build"], 4); + let manifest = stubs::manifest(&stubs::front_doors()).expect("a manifest"); + let stub = manifest + .iter() + .find(|entry| entry.identity == "bal-plan") + .expect("the manifest holds a bal-plan stub"); + let stub = std::str::from_utf8(&stub.bytes).expect("a stub is text"); + let (_, body) = stub.split_once("\n---\n").expect("a frontmatter block"); + let lines: Vec<&str> = body + .lines() + .filter(|line| !line.trim().is_empty()) + .collect(); + assert_eq!(lines.len(), 1, "{body:?}"); + assert!(lines[0].contains("`baley_query`"), "{}", lines[0]); + assert!( + lines[0].contains(r#"{"operation":"instruction","identity":"bal-plan"}"#), + "{}", + lines[0] + ); +} diff --git a/crates/baley/src/ledger/open.rs b/crates/baley/src/ledger/open.rs index d19c18ea..1ac9f4f1 100644 --- a/crates/baley/src/ledger/open.rs +++ b/crates/baley/src/ledger/open.rs @@ -8,6 +8,9 @@ use baley_core::capture::{CaptureProjector, register_capture_events}; use baley_core::catalog::{ModelCatalogProjector, register_model_events}; use baley_core::checkout::{CheckoutProjector, register_checkout_events}; use baley_core::guard::{GuardPolicyProjector, GuardProjector, register_guard_events}; +use baley_core::plan::{ + EvidenceMapProjector, PhasePlanProjector, PlanProjector, register_plan_events, +}; use baley_core::policy::recorded::{PolicyProjector, register_policy_events}; use baley_core::questions::{QuestionsProjector, register_question_events}; use baley_core::scope::{ @@ -33,16 +36,19 @@ use crate::update::events::register_update_events; /// `story.reprioritized`, `story.dropped`, `phase.declared`, /// `phase.reordered` and `phase.withdrawn`, `work_order.issued` and /// `work_order.failed`, the four question types `questions.opened`, -/// `question.answered`, `question.deferred` and `questions.abandoned`, and -/// `story.refined` understood by the CLI, and declares view set version 13 -/// over seventeen views, the sixteen of view set 12 and `truths`: `backlog -/// capture checkout claim_scope draft guard guard_policy install -/// model_catalog phase phase_detail policy questions request roadmap truths -/// work_order`. View set 13 also covers the `work_order` view's version 2, -/// the `roadmap` view's version 3 and the `backlog` view's version 3. The -/// install view holds only install records. Update outcomes and provider -/// acknowledgements are read from their streams and have no projector. A -/// project brought to view set 13 is read-only for older binaries. +/// `question.answered`, `question.deferred` and `questions.abandoned`, +/// `story.refined`, and the four plan types `plan.approved`, +/// `plan.replaced`, `plan.continuation` and `plan.continuation_followed` +/// understood by the CLI, and declares view set version 14 over twenty +/// views, the seventeen of view set 13 and `evidence_map`, `phase_plan` and +/// `plan`: `backlog capture checkout claim_scope draft evidence_map guard +/// guard_policy install model_catalog phase phase_detail phase_plan plan +/// policy questions request roadmap truths work_order`. View set 13 covered +/// the `work_order` view's version 2 and the `roadmap` view's version 3; +/// view set 14 also covers the `backlog` view's version 4. The install view +/// holds only install records. Update outcomes and provider acknowledgements +/// are read from their streams and have no projector. A project brought to +/// view set 14 is read-only for older binaries. /// The startup `quick_check` is off for command-line callers. pub(crate) fn options() -> Options { let mut registry = Registry::new(); @@ -60,6 +66,7 @@ pub(crate) fn options() -> Options { register_work_order_events(&mut registry).expect("unique work order types"); register_question_events(&mut registry).expect("unique question types"); register_truth_events(&mut registry).expect("unique truth types"); + register_plan_events(&mut registry).expect("unique plan types"); Options { schema: Box::new(registry), projectors: vec![ @@ -78,8 +85,11 @@ pub(crate) fn options() -> Options { Box::new(WorkOrderProjector::new()), Box::new(QuestionsProjector::new()), Box::new(TruthsProjector::new()), + Box::new(PhasePlanProjector::new()), + Box::new(PlanProjector::new()), + Box::new(EvidenceMapProjector::new()), ], - view_set_version: NonZeroU32::new(13).expect("nonzero"), + view_set_version: NonZeroU32::new(14).expect("nonzero"), ..Options::default() } } @@ -322,6 +332,31 @@ pub(crate) mod tests { options } + /// The options as they stood at view set 13, before the plan events and + /// the `phase_plan`, `plan` and `evidence_map` views. + fn view_set_13() -> Options { + let mut options = view_set_12(); + let mut registry = Registry::new(); + register_anchor_events(&mut registry).unwrap(); + register_project_events(&mut registry).unwrap(); + register_model_events(&mut registry).unwrap(); + register_policy_events(&mut registry).unwrap(); + register_checkout_events(&mut registry).unwrap(); + register_capture_events(&mut registry).unwrap(); + register_guard_events(&mut registry).unwrap(); + register_install_events(&mut registry).unwrap(); + register_update_events(&mut registry).unwrap(); + register_provider_events(&mut registry).unwrap(); + register_scope_events(&mut registry).unwrap(); + register_work_order_events(&mut registry).unwrap(); + register_question_events(&mut registry).unwrap(); + register_truth_events(&mut registry).unwrap(); + options.schema = Box::new(registry); + options.projectors.push(Box::new(TruthsProjector::new())); + options.view_set_version = NonZeroU32::new(13).unwrap(); + options + } + /// The domain views of view set 13, sorted: the fourteen of view set 12 /// and `truths`. const VIEW_SET_13: [&str; 15] = [ @@ -342,6 +377,29 @@ pub(crate) mod tests { "work_order", ]; + /// The domain views of view set 14, sorted: the fifteen of view set 13 + /// and `evidence_map`, `phase_plan` and `plan`. + const VIEW_SET_14: [&str; 18] = [ + "backlog", + "capture", + "checkout", + "draft", + "evidence_map", + "guard", + "guard_policy", + "install", + "model_catalog", + "phase", + "phase_detail", + "phase_plan", + "plan", + "policy", + "questions", + "roadmap", + "truths", + "work_order", + ]; + /// The names of the views the options declare, in order. fn view_names(options: &Options) -> Vec { options @@ -631,10 +689,10 @@ pub(crate) mod tests { "{name}" ); } - assert_eq!(opened.view_set_version, NonZeroU32::new(13).unwrap()); + assert_eq!(opened.view_set_version, NonZeroU32::new(14).unwrap()); let mut names = view_names(&opened); names.sort(); - assert_eq!(names, VIEW_SET_13); + assert_eq!(names, VIEW_SET_14); } } @@ -659,10 +717,10 @@ pub(crate) mod tests { .schema .reads(PROVIDERS_ACKNOWLEDGED, PROVIDERS_ACKNOWLEDGED_VERSION + 1) ); - assert_eq!(opened.view_set_version, NonZeroU32::new(13).unwrap()); + assert_eq!(opened.view_set_version, NonZeroU32::new(14).unwrap()); let mut names = view_names(&opened); names.sort(); - assert_eq!(names, VIEW_SET_13); + assert_eq!(names, VIEW_SET_14); } } @@ -693,10 +751,10 @@ pub(crate) mod tests { assert!(opened.schema.reads("scope.submitted", 1)); assert!(opened.schema.reads("scope.submitted", 2)); assert!(!opened.schema.reads("scope.submitted", 3)); - assert_eq!(opened.view_set_version, NonZeroU32::new(13).unwrap()); + assert_eq!(opened.view_set_version, NonZeroU32::new(14).unwrap()); let mut names = view_names(&opened); names.sort(); - assert_eq!(names, VIEW_SET_13); + assert_eq!(names, VIEW_SET_14); } } @@ -713,10 +771,10 @@ pub(crate) mod tests { assert!(opened.schema.reads(name, 1), "{name}"); assert!(!opened.schema.reads(name, 2), "{name}"); } - assert_eq!(opened.view_set_version, NonZeroU32::new(13).unwrap()); + assert_eq!(opened.view_set_version, NonZeroU32::new(14).unwrap()); let mut names = view_names(&opened); names.sort(); - assert_eq!(names, VIEW_SET_13); + assert_eq!(names, VIEW_SET_14); } } @@ -738,10 +796,10 @@ pub(crate) mod tests { assert!(opened.schema.reads(name, 1), "{name}"); assert!(!opened.schema.reads(name, 2), "{name}"); } - assert_eq!(opened.view_set_version, NonZeroU32::new(13).unwrap()); + assert_eq!(opened.view_set_version, NonZeroU32::new(14).unwrap()); let mut names = view_names(&opened); names.sort(); - assert_eq!(names, VIEW_SET_13); + assert_eq!(names, VIEW_SET_14); } } @@ -1105,10 +1163,10 @@ pub(crate) mod tests { ] { assert!(opened.schema.reads("story.refined", 1)); assert!(!opened.schema.reads("story.refined", 2)); - assert_eq!(opened.view_set_version, NonZeroU32::new(13).unwrap()); + assert_eq!(opened.view_set_version, NonZeroU32::new(14).unwrap()); let mut names = view_names(&opened); names.sort(); - assert_eq!(names, VIEW_SET_13); + assert_eq!(names, VIEW_SET_14); } } @@ -1244,4 +1302,99 @@ pub(crate) mod tests { assert_eq!(roadmap.body["stories"][0]["id"], 1); assert_eq!(roadmap.body["stories"][0]["truths"], 2); } + + // Catches a plan event the store would refuse at append, a planning view + // left out so a plan write projects nothing, or the views added without + // raising the set, which an older binary would misread. + #[test] + fn a_planning_view_or_event_left_unregistered_or_the_set_left_at_13_is_caught() { + use baley_core::plan::{ + PlanApproval, evidence_map_key, phase_plan_key, phase_stream, plan_key, + }; + use baley_store::{ + Actor, Admin, Command, CommandKind, Decision, Hash, NewEvent, Observed, OutcomeKind, + ProjectId, RequestId, RetentionClass, StreamName, Views, + }; + + let opened = options(); + assert_eq!(opened.view_set_version, NonZeroU32::new(14).unwrap()); + let mut names = view_names(&opened); + names.sort(); + assert_eq!(names, VIEW_SET_14); + for name in [ + "plan.approved", + "plan.replaced", + "plan.continuation", + "plan.continuation_followed", + ] { + assert!(opened.schema.reads(name, 1), "{name}"); + assert!(!opened.schema.reads(name, 2), "{name}"); + } + + let older_options = view_set_13(); + let mut older_names = view_names(&older_options); + older_names.sort(); + assert_eq!(older_names, VIEW_SET_13); + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + let project = ProjectId("6f1c2a4e-8b1d-4c3a-9e2f-0a5b7c9d1e3f".into()); + let older = store(&home, T0, older_options).unwrap(); + older.create_project(&project, "sample", T0).unwrap(); + drop(older); + + let reopened = store(&home, T1, options()).unwrap(); + let command = Command { + project: project.clone(), + kind: CommandKind("test.approve".into()), + request_id: RequestId("4d5e6f7a-8b9c-4d0e-9f1a-2b3c4d5e6f73".into()), + digest: Hash([0x33; 32]), + scope: Vec::new(), + policy_version: 0, + recorded_at: T1.into(), + actor: Actor::Owner, + caller: None, + }; + reopened + .transact(&command, &mut |tx| { + let body = tx.put_payload(b"the plan's body", RetentionClass::Record)?; + // Serving no story, so the backlog has none to refuse. + let approval = PlanApproval { + phase: 1, + plan: 1, + digest: Hash([0x5c; 32]), + stories: &[], + size: 1, + suite: None, + question_set: "5d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d", + evidence_map: &[], + body: &body, + owner: "Ada Owner", + at: T1, + }; + tx.append(NewEvent { + stream: StreamName(phase_stream(1)), + type_name: "plan.approved".into(), + type_version: 1, + git: None, + payload: approval.payload(), + attachments: vec![body], + })?; + Ok(Decision { + kind: OutcomeKind::Done, + answer: serde_json::json!({}), + sensitive: false, + observed: Observed::default(), + git: None, + }) + }) + .unwrap(); + for (view, key) in [ + ("phase_plan", phase_plan_key(1)), + ("plan", plan_key(1, 1)), + ("evidence_map", evidence_map_key(1, 1)), + ] { + let held = reopened.get(&project, view, &key).unwrap(); + assert!(held.is_some(), "{view} holds no document for plan 1"); + } + } } diff --git a/crates/baley/src/lib.rs b/crates/baley/src/lib.rs index cc34463c..00df0df0 100644 --- a/crates/baley/src/lib.rs +++ b/crates/baley/src/lib.rs @@ -77,6 +77,8 @@ pub mod ledger; pub mod mcp; /// `baley models`: the per-user model catalog and the seeding step before each use. pub mod models; +/// A phase's planning over the storage port: what a planner order binds and the planner's work order. +pub mod planning; /// The policy step: records the effective policy a command ran under when it changed. pub mod policy_step; /// Which paths the guard protects, and the decisions that judge a tool call's paths against them. diff --git a/crates/baley/src/main.rs b/crates/baley/src/main.rs index 08a18fe2..38da1218 100644 --- a/crates/baley/src/main.rs +++ b/crates/baley/src/main.rs @@ -40,6 +40,8 @@ enum Command { Story(baley::scope::command::StoryArgs), /// Show a question set's current round and what it has settled. Questions(baley::questions::command::QuestionsArgs), + /// Approve a plan draft by its digest as the owner, or show a phase's approved plans and evidence maps. + Plan(baley::planning::command::PlanArgs), /// Check the update source and stage a newer version behind the stable path. Update(baley::update::command::UpdateArgs), /// Install Claude Code's user-level wiring and seed the model catalog. @@ -128,6 +130,7 @@ fn run_command(command: Command) -> std::process::ExitCode { Command::Backlog(args) => return baley::scope::command::run_backlog(args), Command::Story(args) => return baley::scope::command::run_story(args), Command::Questions(args) => return baley::questions::command::run(args), + Command::Plan(args) => return baley::planning::command::run(args), Command::Update(args) => return baley::update::command::run(args), Command::Install(args) => return baley::install::command::run(args), other => other, @@ -143,6 +146,7 @@ fn run_command(command: Command) -> std::process::ExitCode { | Command::Backlog(_) | Command::Story(_) | Command::Questions(_) + | Command::Plan(_) | Command::Install(_) | Command::Update(_) => { unreachable!("dispatched above") diff --git a/crates/baley/src/mcp/capture.rs b/crates/baley/src/mcp/capture.rs index f1005108..7d689649 100644 --- a/crates/baley/src/mcp/capture.rs +++ b/crates/baley/src/mcp/capture.rs @@ -1078,7 +1078,7 @@ mod tests { #[test] fn an_unserved_instruction_accepted_or_refused_without_its_build_is_caught() { - let refusal = refused(&arguments(json!({"instruction": "bal-plan"}))); + let refusal = refused(&arguments(json!({"instruction": "bal-review"}))); assert_eq!(refusal["code"], "instruction-unavailable"); assert_eq!(refusal["slot"], "instruction"); assert_eq!(refusal["details"]["build"], 4); diff --git a/crates/baley/src/mcp/document.rs b/crates/baley/src/mcp/document.rs index 5c632bb5..85664aaa 100644 --- a/crates/baley/src/mcp/document.rs +++ b/crates/baley/src/mcp/document.rs @@ -13,12 +13,16 @@ //! answer's receipt carries, and a sentence naming the rounds relay //! instruction (design 0005 `questions round`). A story's refinement by its //! id comes from `refine::read`, the read `context-intake` and `baley story -//! refinement` give too (D-10). +//! refinement` give too (D-10). A phase by its number, with its approved +//! plans, and one approved plan by its phase and number come from +//! `planning::read`, the read `plan-read` and `baley plan show` give too, so +//! a draft is never answered (D-17). use std::io::Read; use std::path::Path; use baley_core::capture::{CAPTURE_ID_INDEX, CAPTURE_VIEW, NO_SUCH_PHASE}; +use baley_core::plan::NO_SUCH_PLAN; use baley_core::questions::UnreadableSet; use baley_core::scope::UNKNOWN_DRAFT; use baley_core::work_order::NO_SUCH_WORK_ORDER; @@ -36,6 +40,7 @@ use crate::mcp::capture::{PLACE_LEDGER, failed, store_failed}; use crate::mcp::handler::Preparation; use crate::mcp::parts::{Cut, PART_BOUND, cut}; use crate::mcp::prepare::{LEDGER_UNAVAILABLE, prepare}; +use crate::planning::read as planning; use crate::questions::read::{self as questions, SetRead}; use crate::refine::read::StoryRefinement; use crate::scope::read::{ @@ -103,6 +108,21 @@ pub enum Identity { /// The story id Baley assigned when the scope was approved. story: u32, }, + /// A phase as the roadmap gives it, with every plan approved in it and + /// its evidence map, in plan-number order, replaced plans included. + #[serde(rename = "phase")] + Phase { + /// The phase's number, as the roadmap gives it. + phase: u32, + }, + /// One approved plan of a phase with its evidence map. + #[serde(rename = "plan")] + Plan { + /// The phase's number, as the roadmap gives it. + phase: u32, + /// The plan's number, as its approval gave it. + plan: u32, + }, } /// The tagged form a call's arguments arrive in, so `operation` is read and @@ -274,7 +294,8 @@ const SCOPE_NOT_READ_BUSY: &str = "the ledger is busy, so the scope was not read /// read from its view document by id, then its body only when the view says /// this project still holds it; a draft, the roadmap and a story through /// `scope::read`; a work order through `work_order::read`; a question set -/// through `questions::read`; a story's refinement through `refine::read`. +/// through `questions::read`; a story's refinement through `refine::read`; +/// a phase and its approved plans, or one of them, through `planning::read`. /// Nothing is appended. pub fn read( store: &S, @@ -308,6 +329,70 @@ pub fn read( Ok(refinement) => refinement_answer(Some(identity), refinement, shape.part), Err(error) => read_failed(error), }, + Identity::Phase { phase } => phase_answer(store, project, identity, *phase, shape.part), + Identity::Plan { phase, plan } => { + plan_answer(store, project, identity, *phase, *plan, shape.part) + } + } +} + +/// The answer for phase `number`'s read: the phase as the roadmap gives it +/// and its approved plans as `planning::read` gives them to `plan-read`, in +/// parts when large. A phase the roadmap does not hold is `no-such-phase`, +/// echoing none of its number. +fn phase_answer( + store: &S, + project: &ProjectId, + identity: &Identity, + number: u32, + part: Option, +) -> Value { + let held = match scope::roadmap(store, project) { + Ok(roadmap) => roadmap + .phases + .into_iter() + .find(|held| held.number == number), + Err(error) => return read_failed(error), + }; + let Some(held) = held else { + return read_failed(ReadError::NoSuchPhase); + }; + match planning::read(store, project, number) { + Ok(read) => in_parts( + json!({"status": "ok", "identity": identity, "phase": held, "plans": read.plans}), + part, + ), + Err(error) => read_failed(error), + } +} + +/// The answer for plan `plan` of phase `phase`: that one plan with its +/// evidence map from the read [`phase_answer`] shares, in parts when large. +/// A plan number never approved in the phase is `no-such-plan` naming it. +fn plan_answer( + store: &S, + project: &ProjectId, + identity: &Identity, + phase: u32, + plan: u32, + part: Option, +) -> Value { + let read = match planning::read(store, project, phase) { + Ok(read) => read, + Err(error) => return read_failed(error), + }; + match read.plans.into_iter().find(|held| held.plan == plan) { + Some(held) => in_parts( + json!({"status": "ok", "identity": identity, "phase": phase, "plan": held}), + part, + ), + None => Refusal::new( + NO_SUCH_PLAN, + format!("this phase has no plan {plan}: no plan of that number was approved in it"), + ) + .slot("identity") + .details(json!({"plan": plan})) + .value(), } } @@ -588,7 +673,7 @@ fn gone_status(status: &PayloadStatus) -> Value { /// `answer` whole when its JSON text fits one part, or one numbered part of /// that text, as `help` cuts its answer. -fn in_parts(answer: Value, part: Option) -> Value { +pub(crate) fn in_parts(answer: Value, part: Option) -> Value { let text = serde_json::to_string(&answer).expect("a document answer serializes"); match cut(&text, part) { Cut::Whole(_) => answer, @@ -854,7 +939,7 @@ mod tests { "instruction": "bal-capture"}), json!({"operation": "document", "identity": {"kind": "capture", "id": ID, "phase": 1}}), - json!({"operation": "document", "identity": {"kind": "plan", "id": ID}}), + json!({"operation": "document", "identity": {"kind": "review", "id": ID}}), json!({"operation": "document", "identity": {"kind": "questions", "set": "5d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d", "id": "x"}}), json!({"operation": "document", "identity": {"kind": "capture", "id": ID}, @@ -867,6 +952,171 @@ mod tests { } } + #[test] + fn a_phase_or_plan_document_shape_judged_wrongly_is_caught() { + let judged = |identity: Value| { + judge_arguments(&json!({"operation": "document", "identity": identity})) + }; + assert_eq!( + judged(json!({"kind": "phase", "phase": 1})) + .unwrap() + .identity, + Identity::Phase { phase: 1 } + ); + assert_eq!( + judged(json!({"kind": "plan", "phase": 1, "plan": 2})) + .unwrap() + .identity, + Identity::Plan { phase: 1, plan: 2 } + ); + for identity in [ + json!({"kind": "phase", "phase": "1"}), + json!({"kind": "plan", "phase": 1}), + json!({"kind": "plan", "phase": 1, "plan": 2, "digest": "x"}), + ] { + let refusal = judged(identity.clone()).expect_err("refused"); + assert_eq!(refusal["code"], "invalid-arguments", "{identity}"); + } + } + + mod plans { + //! Store C with order O over the real store: PL1 approved as plan 1, + //! PL3 with E1 alone approved as plan 2, and PL2 submitted and never + //! approved; phase 2's plan 1, F1 alone under its own digest, is + //! appended by hand, since one phase active at a time keeps the + //! approval path from approving it beside phase 1's. Expected answers are written out from design 0012's + //! `document` identities, D-07, D-17 and the plan's data, never from + //! running this code. + + use serde_json::{Value, json}; + + use super::super::*; + use baley_store::Hash; + + use crate::planning::approve::tests::{approved, digest_of}; + use crate::planning::fixtures::*; + use crate::planning::order::tests::O; + use crate::planning::submit::tests::{order_o, plan_submitted}; + use crate::scope::fixtures::*; + + fn shape(identity: Identity) -> DocumentShape { + DocumentShape { + identity, + part: None, + } + } + + #[test] + fn a_plan_document_answering_a_draft_another_plan_or_a_missing_one_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let first = plan_submitted(&store, &pl1(), O, None, R2, T5); + let x1 = digest_of(&first); + assert_eq!(approved(&store, x1, &p0(), R3, T5)["status"], "ok"); + let mut pl3 = pl3(); + pl3["evidence_map"] = json!([e1()]); + let second = plan_submitted(&store, &pl3, O, None, R4, T6); + let x3 = digest_of(&second); + assert_eq!(approved(&store, x3, &p0(), R5, T6)["status"], "ok"); + let x2 = digest_of(&plan_submitted(&store, &pl2(), O, None, R6, T7)); + // Phase 2's plan 1 shares phase 1's plan numbers under another + // digest, so a read of the wrong phase answers a plan that differs. + let mut f1 = e1(); + f1["id"] = json!("f1"); + f1["story"] = json!(2); + let y = Hash([0x7e; 32]); + approve_by_hand(&store, R7, 2, 1, y, &[2], 1, &[f1.clone()], Vec::new()); + let before = head(&store); + + let phase = read(&store, &project(), &shape(Identity::Phase { phase: 1 })); + assert_eq!(phase["status"], "ok", "{phase}"); + assert_eq!(phase["identity"], json!({"kind": "phase", "phase": 1})); + assert_eq!(phase["phase"]["number"], 1, "{phase}"); + assert_eq!(phase["phase"]["name"], "Records", "{phase}"); + assert_eq!(phase["phase"]["goal"], "Steps are recorded", "{phase}"); + assert_eq!(phase["phase"]["stories"], json!([1]), "{phase}"); + let plans = phase["plans"].as_array().expect("plans"); + assert_eq!(plans.len(), 2, "{phase}"); + assert_eq!(plans[0]["plan"], 1); + assert_eq!(plans[0]["digest"], x1.to_hex()); + assert_eq!(plans[0]["items"], json!([e1(), e2()])); + assert_eq!(plans[1]["plan"], 2); + assert_eq!(plans[1]["digest"], x3.to_hex()); + assert_eq!(plans[1]["items"], json!([e1()])); + assert!( + !phase.to_string().contains(&x2.to_hex()), + "a draft answered as a plan: {phase}" + ); + assert_eq!(head(&store), before); + + let plan = read( + &store, + &project(), + &shape(Identity::Plan { phase: 1, plan: 2 }), + ); + assert_eq!(plan["status"], "ok", "{plan}"); + assert_eq!( + plan["identity"], + json!({"kind": "plan", "phase": 1, "plan": 2}) + ); + assert_eq!(plan["plan"]["plan"], 2, "{plan}"); + assert_eq!(plan["plan"]["digest"], x3.to_hex(), "{plan}"); + assert_eq!(plan["plan"]["items"], json!([e1()]), "{plan}"); + assert!(plan.get("plans").is_none(), "{plan}"); + assert_eq!(head(&store), before); + + let missing = read( + &store, + &project(), + &shape(Identity::Plan { phase: 1, plan: 3 }), + ); + assert_eq!(missing["status"], "refused", "{missing}"); + assert_eq!(missing["code"], "no-such-plan", "{missing}"); + assert_eq!(missing["details"], json!({"plan": 3}), "{missing}"); + assert_eq!(head(&store), before); + + let unknown: Value = read(&store, &project(), &shape(Identity::Phase { phase: 9 })); + assert_eq!(unknown["status"], "refused", "{unknown}"); + assert_eq!(unknown["code"], "no-such-phase", "{unknown}"); + assert_eq!(head(&store), before); + + let first = read( + &store, + &project(), + &shape(Identity::Plan { phase: 1, plan: 1 }), + ); + assert_eq!(first["status"], "ok", "{first}"); + assert_eq!(first["phase"], 1, "{first}"); + assert_eq!(first["plan"]["plan"], 1, "{first}"); + assert_eq!(first["plan"]["digest"], x1.to_hex(), "{first}"); + assert_eq!(first["plan"]["items"], json!([e1(), e2()]), "{first}"); + let other = read( + &store, + &project(), + &shape(Identity::Plan { phase: 2, plan: 1 }), + ); + assert_eq!(other["status"], "ok", "{other}"); + assert_eq!(other["phase"], 2, "{other}"); + assert_eq!(other["plan"]["plan"], 1, "{other}"); + assert_eq!( + other["plan"]["digest"], + y.to_hex(), + "another phase's plan: {other}" + ); + assert_eq!(other["plan"]["items"], json!([f1]), "{other}"); + assert_eq!(head(&store), before); + + let absent = read( + &store, + &project(), + &shape(Identity::Plan { phase: 9, plan: 1 }), + ); + assert_eq!(absent["status"], "refused", "{absent}"); + assert_eq!(absent["code"], "no-such-phase", "{absent}"); + assert_eq!(head(&store), before); + } + } + mod reads { use baley_core::capture::{CaptureKind, capture_id}; use baley_store::{ diff --git a/crates/baley/src/mcp/handler.rs b/crates/baley/src/mcp/handler.rs index e9253591..da084441 100644 --- a/crates/baley/src/mcp/handler.rs +++ b/crates/baley/src/mcp/handler.rs @@ -10,10 +10,12 @@ //! `scope-submit`, the ten change operations from `project-describe` to //! `backlog-reorder`, `project-start`, `work-order-fail`, `work-order-retry`, //! `questions-answer`, `story-refine`, `story-questions-submit`, -//! `context-submit`, `document`, `context-intake` and `route` set -//! `needs_project`, and in their [`operate`] arms the writes prepare a write -//! from it, `document` and `context-intake` a read and `route` a read that -//! also reads the settings. +//! `phase-plan`, `plan-submit`, `plan-replace`, `context-submit`, `document`, +//! `context-intake`, `plan-read` and `route` set `needs_project`, and in +//! their [`operate`] arms the writes prepare a write from it, `plan-submit` +//! and `plan-replace` after a settings read that records nothing, `document`, +//! `context-intake` and `plan-read` a read and `route` a read that also +//! reads the settings. //! rmcp has already validated the request's metadata by the time any //! of this runs, so a protocol-required metadata error stays a protocol error //! and runs nothing. @@ -39,6 +41,7 @@ use super::context::{SessionContext, call_context}; use super::document; use super::gate::{Admitted, After, Called, after_queue, encode}; use super::operations::{help_answer, instruction_answer, schema_answer, unknown_operation}; +use super::planning; use super::questions; use super::refine; use super::scope; @@ -164,7 +167,8 @@ fn run_decision( /// project call's [`Preparation`] together, so an arm that needs a project /// names the input in its pattern and the arms that need none ignore it. /// `capture`, `scope-submit` and the ten change operations prepare a write -/// from the [`Preparation`], and `document` and `context-intake` a read. +/// from the [`Preparation`], and `document`, `context-intake` and +/// `plan-read` a read. pub(crate) fn operate( called: &Called, arguments: Option<&Value>, @@ -209,12 +213,23 @@ pub(crate) fn operate( { refine::serve_questions(arguments_or_null, preparation) } + (Called::Operation(_, spelling), Some(preparation)) if spelling == "phase-plan" => { + planning::serve(arguments_or_null, preparation) + } + (Called::Operation(_, spelling), Some(preparation)) + if spelling == "plan-submit" || spelling == "plan-replace" => + { + planning::serve_submit(arguments_or_null, preparation) + } (Called::Operation(_, spelling), Some(preparation)) if spelling == "context-submit" => { refine::serve_context(arguments_or_null, preparation) } (Called::Operation(_, spelling), Some(preparation)) if spelling == "context-intake" => { refine::serve_intake(arguments_or_null, preparation) } + (Called::Operation(_, spelling), Some(preparation)) if spelling == "plan-read" => { + planning::serve_read(arguments_or_null, preparation) + } (Called::Operation(_, spelling), Some(preparation)) if spelling == "route" => { work_order::serve_route(arguments_or_null, preparation) } diff --git a/crates/baley/src/mcp/mod.rs b/crates/baley/src/mcp/mod.rs index 0a4938df..1cab3426 100644 --- a/crates/baley/src/mcp/mod.rs +++ b/crates/baley/src/mcp/mod.rs @@ -3,8 +3,8 @@ //! queue, the worker and the transports that carry the calls. The judging is //! pure and tested with supplied values. The stdio, the worker thread and the //! store are reached only by the gathering in `serve`, `transport`, `worker`, -//! `prepare`, `capture`, `document`, `scope`, `work_order`, `questions` and -//! `refine`. +//! `prepare`, `capture`, `document`, `scope`, `work_order`, `questions`, +//! `refine` and `planning`. /// The session's project, working directory and ids, gathered once and judged. pub mod context; @@ -68,3 +68,6 @@ pub mod questions; /// `story-refine`: a session asks for the analyzer's next order for one story. pub mod refine; + +/// `phase-plan`: a session asks for one phase's planner with an ordered selection of stories. +pub mod planning; diff --git a/crates/baley/src/mcp/operations.rs b/crates/baley/src/mcp/operations.rs index 0a743677..8874eeab 100644 --- a/crates/baley/src/mcp/operations.rs +++ b/crates/baley/src/mcp/operations.rs @@ -104,7 +104,7 @@ pub const QUERY_OPERATIONS: &[Operation] = &[ retired("verification-audit", 5), retired("execution-history", 5), retired("evidence-read", 5), - retired("plan-read", 4), + with_project("plan-read"), with_project("context-intake"), with_project("route"), retired("config-entry", 2), @@ -153,7 +153,7 @@ pub const APPLY_OPERATIONS: &[Operation] = &[ retired("execution-admit", 5), retired("execution-extend", 5), retired("execution-authorize", 5), - retired("plan-submit", 4), + with_project("plan-submit"), with_project("context-submit"), retired("review-admit", 4), retired("review-observation", 4), @@ -212,6 +212,8 @@ pub const APPLY_OPERATIONS: &[Operation] = &[ with_project("questions-answer"), with_project("story-refine"), with_project("story-questions-submit"), + with_project("phase-plan"), + with_project("plan-replace"), ]; /// A spelling served only from a project, which its call prepares. @@ -387,6 +389,18 @@ enum RequestShape { // `story-questions-submit` parses its own arguments, so this variant is here for its schema. #[serde(rename = "story-questions-submit")] StoryQuestionsSubmit(#[allow(dead_code)] crate::mcp::refine::QuestionsShape), + // `phase-plan` parses its own arguments, so this variant is here for its schema. + #[serde(rename = "phase-plan")] + PhasePlan(#[allow(dead_code)] crate::mcp::planning::PhasePlanShape), + // `plan-submit` parses its own arguments, so this variant is here for its schema. + #[serde(rename = "plan-submit")] + PlanSubmit(#[allow(dead_code)] crate::mcp::planning::PlanSubmitShape), + // `plan-replace` parses its own arguments, so this variant is here for its schema. + #[serde(rename = "plan-replace")] + PlanReplace(#[allow(dead_code)] crate::mcp::planning::PlanReplaceShape), + // `plan-read` parses its own arguments, so this variant is here for its schema. + #[serde(rename = "plan-read")] + PlanRead(#[allow(dead_code)] crate::mcp::planning::PlanReadShape), // `context-intake` parses its own arguments, so this variant is here for its schema. #[serde(rename = "context-intake")] ContextIntake(#[allow(dead_code)] crate::mcp::refine::IntakeShape), @@ -674,6 +688,8 @@ pub(crate) mod expected { "questions-answer", "story-refine", "story-questions-submit", + "phase-plan", + "plan-replace", ]; } @@ -743,7 +759,11 @@ mod tests { "questions-answer", "story-refine", "story-questions-submit", + "phase-plan", + "plan-submit", + "plan-replace", "context-submit", + "plan-read", "context-intake", "route", ] @@ -761,7 +781,7 @@ mod tests { needs_project: true } ); - for name in ["document", "context-intake", "route"] { + for name in ["document", "plan-read", "context-intake", "route"] { assert_eq!( lookup(Tool::Query, Some(name)), Lookup::Available { @@ -788,6 +808,9 @@ mod tests { "questions-answer", "story-refine", "story-questions-submit", + "phase-plan", + "plan-submit", + "plan-replace", "context-submit", ] { assert_eq!( @@ -808,7 +831,6 @@ mod tests { }; assert_eq!(build(Tool::Query, "config-entry"), 2); assert_eq!(build(Tool::Apply, "config-apply"), 2); - assert_eq!(build(Tool::Query, "plan-read"), 4); assert_eq!(build(Tool::Apply, "review-admit"), 4); assert_eq!(build(Tool::Apply, "risk-fire"), 4); assert_eq!(build(Tool::Query, "detect-surfaces"), 4); @@ -1036,22 +1058,29 @@ mod tests { fn the_document_schema_does_not_omit_or_widen_the_capture_identity() { // Design 0012: a capture by its string id, a draft by its string // digest, the roadmap with no other field, a story by its integer id, - // a work order by its string id, a question set by its string set id - // and a refinement by its integer story id, each refusing any other - // field. + // a work order by its string id, a question set by its string set id, + // a refinement by its integer story id, a phase by its integer number + // and a plan by its integer phase and plan numbers, each refusing any + // other field. let schema = served_schema("document").unwrap(); let identities = schema["properties"]["identity"]["oneOf"] .as_array() .unwrap(); - assert_eq!(identities.len(), 7, "{identities:?}"); - for (identity, kind, field) in [ - (&identities[0], "capture", Some(("id", "string"))), - (&identities[1], "draft", Some(("digest", "string"))), - (&identities[2], "roadmap", None), - (&identities[3], "story", Some(("id", "integer"))), - (&identities[4], "work_order", Some(("id", "string"))), - (&identities[5], "questions", Some(("set", "string"))), - (&identities[6], "refinement", Some(("story", "integer"))), + assert_eq!(identities.len(), 9, "{identities:?}"); + for (identity, kind, fields) in [ + (&identities[0], "capture", &[("id", "string")][..]), + (&identities[1], "draft", &[("digest", "string")]), + (&identities[2], "roadmap", &[]), + (&identities[3], "story", &[("id", "integer")]), + (&identities[4], "work_order", &[("id", "string")]), + (&identities[5], "questions", &[("set", "string")]), + (&identities[6], "refinement", &[("story", "integer")]), + (&identities[7], "phase", &[("phase", "integer")]), + ( + &identities[8], + "plan", + &[("phase", "integer"), ("plan", "integer")], + ), ] { assert_eq!(identity["type"], "object", "{identity}"); assert_eq!(identity["properties"]["kind"]["const"], kind, "{identity}"); @@ -1064,19 +1093,14 @@ mod tests { .collect(); required.sort_unstable(); let properties = identity["properties"].as_object().unwrap(); - match field { - Some((name, kind)) => { - assert_eq!(identity["properties"][name]["type"], kind, "{identity}"); - let mut expected = vec!["kind", name]; - expected.sort_unstable(); - assert_eq!(required, expected, "{identity}"); - assert_eq!(properties.len(), 2, "{identity}"); - } - None => { - assert_eq!(required, ["kind"], "{identity}"); - assert_eq!(properties.len(), 1, "{identity}"); - } + for (name, kind) in fields { + assert_eq!(identity["properties"][name]["type"], *kind, "{identity}"); } + let mut expected: Vec<&str> = fields.iter().map(|(name, _)| *name).collect(); + expected.push("kind"); + expected.sort_unstable(); + assert_eq!(required, expected, "{identity}"); + assert_eq!(properties.len(), fields.len() + 1, "{identity}"); } } @@ -1127,7 +1151,7 @@ mod tests { #[test] fn an_unavailable_instruction_is_refused_naming_its_build() { - let answer = instruction_call("bal-plan"); + let answer = instruction_call("bal-review"); assert_eq!(answer["code"], "instruction-unavailable"); assert_eq!(answer["slot"], "identity"); assert_eq!(answer["details"], json!({"build": 4})); @@ -1312,12 +1336,15 @@ mod tests { fn the_work_order_operations_out_of_the_baseline_order_or_unserved_are_caught() { let names: Vec<&str> = APPLY_OPERATIONS.iter().map(|op| op.name).collect(); let served = ["project-start", "work-order-fail", "work-order-retry"]; - // The three directly precede `questions-answer`, `story-refine` and - // `story-questions-submit`, appended after them. - assert_eq!( - names[names.len().saturating_sub(6)..names.len().saturating_sub(3)], - served - ); + // The three follow `backlog-reorder` and directly precede + // `questions-answer`, appended after them. + let at = names + .iter() + .position(|name| *name == "project-start") + .expect("listed"); + assert_eq!(names[at - 1], "backlog-reorder"); + assert_eq!(names[at..at + 3], served); + assert_eq!(names[at + 3], "questions-answer"); for name in served { assert_eq!( lookup(Tool::Apply, Some(name)), @@ -1348,10 +1375,12 @@ mod tests { #[test] fn a_questions_answer_spelling_left_unserved_or_out_of_the_baseline_order_is_caught() { let names: Vec<&str> = APPLY_OPERATIONS.iter().map(|op| op.name).collect(); - assert_eq!( - names[names.len() - 4..names.len() - 1], - ["work-order-retry", "questions-answer", "story-refine"] - ); + let at = names + .iter() + .position(|name| *name == "questions-answer") + .expect("listed"); + assert_eq!(names[at - 1], "work-order-retry"); + assert_eq!(names[at + 1], "story-refine"); assert_eq!( lookup(Tool::Apply, Some("questions-answer")), Lookup::Available { diff --git a/crates/baley/src/mcp/planning.rs b/crates/baley/src/mcp/planning.rs new file mode 100644 index 00000000..c5d4544c --- /dev/null +++ b/crates/baley/src/mcp/planning.rs @@ -0,0 +1,767 @@ +//! `phase-plan` on `baley_apply`: a session asks for one phase's planner with +//! an ordered selection of stories (design 0005 `phase plan`, PLN-R7, D-08 to +//! D-11, D-15). A changed selection is answered with the `phase edit` draft +//! the owner approves at the terminal; an unchanged one with a planning or +//! revision order; an approved commitment with the order its approval issued. +//! Nothing here approves anything (ADR 0044), and `phase-plan` has no +//! terminal command. +//! +//! The arguments are judged before anything is prepared. The write is then +//! prepared with the `phase plan` check as its own check, so every refusal +//! comes before checkout admission and the policy step and records nothing, +//! and the judged path is run through [`crate::planning::phase_plan`]. +//! +//! `plan-submit` and `plan-replace` on `baley_apply` (design 0005 `plan +//! submit` and `plan replace`, D-04, D-08, D-13): a session submits the +//! plan a planner order returned, as a new plan or as the replacement of +//! one in force. The arguments are judged first; the settings are read for +//! the capacity, recording nothing; then the write is prepared under the +//! caller carrying the order, with the submit's or the replacement's check +//! as its own check, and the draft is recorded through +//! [`crate::planning::submit::record`]. The owner approves the draft at the +//! terminal with `baley plan approve`. +//! +//! `plan-read` on `baley_query` (design 0001 Appendix B `plan-read`, D-08, +//! D-17): a phase's approved plans with their evidence maps and readiness, +//! read through [`crate::planning::read`] as `baley plan show` reads them, +//! prepared as `context-intake` is and recording nothing. + +use std::cell::RefCell; +use std::num::NonZeroU32; +use std::path::Path; + +use baley_core::capture::NO_SUCH_PHASE; +use baley_core::plan::Replaces; +use baley_store::{ + CommandKind, Hash, InstructionEvidence, ProjectId, RequestId, Views, request_digest, +}; +use baley_store_sqlite::SqliteStore; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::{Map, Value, json}; + +use crate::envelope::Refusal; +use crate::mcp::capture::{PLACE_LEDGER, failed, store_failed}; +use crate::mcp::document::{in_parts, prepared_read, read_failed}; +use crate::mcp::handler::Preparation; +use crate::mcp::prepare::{LEDGER_UNAVAILABLE, WriteRequest, prepare_settings_read}; +use crate::mcp::scope::{bind_instructions, order_caller}; +use crate::mcp::work_order::{ + evidenced, judge_instruction, judge_order_id, judge_request_id, prepared_write, shape_fault, +}; +use crate::planning::phase_plan::{self, PHASE_PLAN_COMMAND}; +use crate::planning::{facts, read, replace, submit}; +use crate::process::Process; +use crate::scope::read::ReadError; +use crate::scope::submit::{NOT_RECORDED_BUSY, SUBMIT_COMMAND}; +use crate::work_order::issue as recording; +use crate::work_order::route::host_names; + +// `schema` serves this same declaration, so its doc comments are wire text. +/// The arguments `phase-plan` takes beside its `operation`. Unknown fields +/// are refused. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PhasePlanShape { + /// A fresh UUID for this call in lowercase hyphenated form. A retry of + /// the same call sends the same id. + pub request_id: String, + /// The number of the phase to plan, as the roadmap gives it. + pub phase: u32, + /// The ids of the stories to commit to the phase, in the order they are + /// planned. A list that differs from the phase's stories, a reorder + /// included, is answered with a draft the owner approves first. + pub stories: Vec, + /// The identity of the instruction the session followed, if it followed + /// one. + pub instruction: Option, +} + +/// The tagged form `phase-plan`'s arguments arrive in. +#[derive(Deserialize)] +#[serde(tag = "operation")] +enum PhasePlanCall { + #[serde(rename = "phase-plan")] + Plan(PhasePlanShape), +} + +/// A `phase-plan` call whose arguments passed every check made before +/// preparation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JudgedPhasePlan { + /// The write preparation carries into the domain command. + pub request: WriteRequest, + /// The phase to plan. + pub phase: u32, + /// The selection, in order. + pub stories: Vec, + /// The registry's evidence for the instruction the session named, if any. + pub instruction: Option, +} + +/// Judges `phase-plan`'s arguments before anything is prepared or recorded: +/// the shape, then the request id, then the instruction. A fault is the +/// `refused` answer, which records nothing. The request digest covers the +/// command kind, the phase and the stories in order, so a retry replays and +/// a reorder under the same request id is a reused id. +pub fn judge_arguments(arguments: &Value) -> Result { + let shape = match serde_json::from_value::(arguments.clone()) { + Ok(PhasePlanCall::Plan(shape)) => shape, + Err(error) => return Err(shape_fault(&error)), + }; + judge_request_id(&shape.request_id, "call")?; + let instruction = judge_instruction(shape.instruction.as_deref())?; + let digest = request_digest(&json!({"command": PHASE_PLAN_COMMAND, + "phase": shape.phase, "stories": shape.stories})) + .expect("numbers are canonical"); + Ok(JudgedPhasePlan { + request: WriteRequest { + kind: CommandKind(PHASE_PLAN_COMMAND.into()), + request_id: RequestId(shape.request_id), + digest, + }, + phase: shape.phase, + stories: shape.stories, + instruction, + }) +} + +/// Serves one `phase-plan` call for the session's `preparation`. The +/// arguments are judged first; then the write is prepared under the caller +/// with the instruction evidence attached and the `phase plan` check as its +/// own check; then, for a write that ran its steps, the host catalog is read +/// and the judged path is run under a fresh lowercase UUID with the prepared +/// policy and host. A replay goes to the recording with nothing to record, +/// and the store answers it from its record. +pub fn serve(arguments: &Value, preparation: &Preparation) -> Value { + let judged = match judge_arguments(arguments) { + Ok(judged) => judged, + Err(refusal) => return refusal, + }; + // Kept for the run to record and observe. A replay skips the check. + let kept = RefCell::new(None); + let check = |store: &SqliteStore, project: &ProjectId| { + *kept.borrow_mut() = Some(phase_plan::check( + store, + project, + judged.phase, + &judged.stories, + )?); + Ok(()) + }; + let caller = evidenced(&preparation.caller, judged.instruction.as_ref()); + let (store, command, stepped) = + match prepared_write(preparation, &caller, &judged.request, &check) { + Ok(prepared) => prepared, + Err(answer) => return answer, + }; + let kept = kept.borrow(); + let (Some(stepped), Some(checked)) = (stepped, kept.as_ref()) else { + return recording::answer(recording::record(store, &command, None), store); + }; + let names = match host_names(store, preparation.host) { + Ok(names) => names, + Err(error) => return store_failed(&error, NOT_RECORDED_BUSY), + }; + phase_plan::run( + store, + &command, + checked, + &stepped.policy, + preparation.host, + &names, + &uuid::Uuid::new_v4().to_string(), + ) +} + +// `schema` serves this same declaration, so its doc comments are wire text. +/// The arguments `plan-submit` takes beside its `operation`. Unknown fields +/// are refused. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PlanSubmitShape { + /// A fresh UUID for this plan submission in lowercase hyphenated form. A + /// retry of the same plan submission sends the same id. + pub request_id: String, + /// The id of the planner work order this plan answers, as its receipt + /// gave it, a UUID in lowercase hyphenated form. + pub work_order: String, + /// The plan exactly as the planner returned it. + // Typed as an object in the schema, or a client may send it as a string. + #[schemars(with = "Map")] + pub plan: Value, +} + +// `schema` serves this same declaration, so its doc comments are wire text. +/// The arguments `plan-replace` takes beside its `operation`. Unknown fields +/// are refused. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PlanReplaceShape { + /// A fresh UUID for this plan submission in lowercase hyphenated form. A + /// retry of the same plan submission sends the same id. + pub request_id: String, + /// The id of the planner work order this plan answers, as its receipt + /// gave it, a UUID in lowercase hyphenated form. + pub work_order: String, + /// The new plan exactly as the planner returned it. + // Typed as an object in the schema, or a client may send it as a string. + #[schemars(with = "Map")] + pub plan: Value, + /// The approved plan in force this plan replaces. + pub replaces: ReplacesShape, +} + +// `schema` serves this same declaration, so its doc comments are wire text. +/// The approved plan a replacement names. Unknown fields are refused. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReplacesShape { + /// The number of the plan to replace, as its approval gave it. + pub plan: u32, + /// The digest that plan was approved at: 64 lowercase hexadecimal + /// characters. + pub digest: String, +} + +/// The tagged forms the two submissions' arguments arrive in. +#[derive(Deserialize)] +#[serde(tag = "operation")] +enum SubmitCall { + #[serde(rename = "plan-submit")] + Submit(PlanSubmitShape), + #[serde(rename = "plan-replace")] + Replace(PlanReplaceShape), +} + +/// A `plan-submit` or `plan-replace` call whose arguments passed every check +/// made before preparation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JudgedSubmit { + /// The write preparation carries into the domain command. + pub request: WriteRequest, + /// The planner order the plan answers. + pub work_order: String, + /// The plan as given, for the judge to judge. + pub plan: Value, + /// The plan a replacement replaces, or none for `plan-submit`. + pub replaces: Option, +} + +/// Judges `plan-submit`'s or `plan-replace`'s arguments before anything is +/// prepared or recorded: the shape, then the request id, the order id's +/// form, and a `replaces` digest that is not 64 lowercase hexadecimal +/// characters, `invalid-arguments` at slot `replaces`. A fault is the +/// `refused` answer, which records nothing. The request digest covers the +/// command kind, the plan as given, the order and, for a replacement, the +/// binding, so a retry replays and other content under the same id is a +/// reused id; a plan holding a number with no canonical form is +/// `invalid-arguments` at slot `plan`. +pub fn judge_submit_arguments(arguments: &Value) -> Result { + let (request_id, work_order, plan, replaces) = + match serde_json::from_value::(arguments.clone()) { + Ok(SubmitCall::Submit(shape)) => (shape.request_id, shape.work_order, shape.plan, None), + Ok(SubmitCall::Replace(shape)) => ( + shape.request_id, + shape.work_order, + shape.plan, + Some(shape.replaces), + ), + Err(error) => return Err(shape_fault(&error)), + }; + judge_request_id(&request_id, "submission")?; + judge_order_id(&work_order)?; + let replaces = match replaces { + None => None, + Some(binding) => Some(Replaces { + plan: binding.plan, + digest: lowercase_digest(&binding.digest).ok_or_else(|| { + Refusal::new( + "invalid-arguments", + "replaces.digest must be the digest the plan was approved at, 64 lowercase hexadecimal characters", + ) + .slot("replaces") + .value() + })?, + }), + }; + let mut covered = json!({"command": SUBMIT_COMMAND, "plan": plan, "work_order": work_order}); + if let Some(Replaces { plan, digest }) = replaces { + covered["replaces"] = json!({"plan": plan, "digest": digest.to_hex()}); + } + let digest = request_digest(&covered).map_err(|error| { + Refusal::new( + "invalid-arguments", + format!("the plan holds a number with no canonical form: {error}"), + ) + .slot("plan") + .value() + })?; + Ok(JudgedSubmit { + request: WriteRequest { + kind: CommandKind(SUBMIT_COMMAND.into()), + request_id: RequestId(request_id), + digest, + }, + work_order, + plan, + replaces, + }) +} + +/// `text` as a digest when it is 64 lowercase hexadecimal characters. +fn lowercase_digest(text: &str) -> Option { + if !text + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) + { + return None; + } + Hash::from_hex(text) +} + +/// Serves one `plan-submit` or `plan-replace` call for the session's +/// `preparation`. The arguments are judged first; then the settings are read +/// for `planning.phase_capacity`, recording nothing; then the write is +/// prepared under the caller carrying the order, with the submit's or the +/// replacement's check as its own check, so every refusal comes before +/// checkout admission and the policy step and records nothing. A failed +/// settings read is answered by that check, so a retry of a recorded request +/// still replays as preparation keeps it. The command's caller then takes +/// the order's instruction evidence and the draft is recorded. A replay goes +/// to the recording with no read, and the store answers it from its record. +pub fn serve_submit(arguments: &Value, preparation: &Preparation) -> Value { + submit_through(arguments, preparation, &mut crate::process::System) +} + +/// [`serve_submit`] with the settings read for the capacity running git +/// through `process`, the seam a test supplies. +fn submit_through( + arguments: &Value, + preparation: &Preparation, + process: &mut dyn Process, +) -> Value { + let judged = match judge_submit_arguments(arguments) { + Ok(judged) => judged, + Err(refusal) => return refusal, + }; + let caller = match order_caller(&preparation.caller, &judged.work_order) { + Ok(caller) => caller, + Err(refusal) => return refusal, + }; + let capacity = capacity(preparation, process); + // Kept for the binding and the recording. A replay skips the check. + let kept = RefCell::new(None); + let check = |store: &SqliteStore, project: &ProjectId| { + let capacity = capacity.clone()?; + let checked = match judged.replaces { + None => submit::check(store, project, &judged.plan, &judged.work_order, capacity), + Some(replaces) => replace::check( + store, + project, + &judged.plan, + &judged.work_order, + replaces, + capacity, + ), + }?; + *kept.borrow_mut() = Some(checked); + Ok(()) + }; + let (store, command, _) = match prepared_write(preparation, &caller, &judged.request, &check) { + Ok(prepared) => prepared, + Err(answer) => return answer, + }; + let kept = kept.borrow(); + let evidence = kept.as_ref().map(|checked| checked.evidence.as_slice()); + match bind_instructions(command, evidence) { + Ok(command) => { + crate::scope::submit::answer(submit::record(store, &command, kept.as_ref()), store) + } + Err(answer) => answer, + } +} + +/// The capacity the session's settings set, read and judged with nothing +/// recorded, or the answer that read ended with. Git runs through `process`. +fn capacity( + preparation: &Preparation, + process: &mut dyn Process, +) -> Result, Value> { + let ledger = preparation.ledger.as_deref(); + // With no ledger, the read fails at the project check, before any + // settings are read from the config folder. + let config = ledger.map_or(Path::new(""), |ledger| ledger.config.as_path()); + let prepared = prepare_settings_read( + ledger.map(|ledger| &ledger.store), + &preparation.caller, + config, + preparation.host, + &preparation.at, + process, + )?; + prepared + .policy + .as_ref() + .map(facts::capacity) + .ok_or_else(|| { + failed( + LEDGER_UNAVAILABLE, + "the settings were read without a policy", + PLACE_LEDGER, + ) + }) +} + +// `schema` serves this same declaration, so its doc comments are wire text. +/// The arguments `plan-read` takes beside its `operation`. Unknown fields +/// are refused. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PlanReadShape { + /// The number of the phase whose approved plans to read, as the roadmap + /// gives it. + pub phase: u32, + /// One-based part for answers over 24,576 bytes; defaults to 1. + /// Concatenate the returned bodies in order. + pub part: Option, +} + +/// The tagged form `plan-read`'s arguments arrive in. +#[derive(Deserialize)] +#[serde(tag = "operation")] +enum ReadCall { + #[serde(rename = "plan-read")] + Read(PlanReadShape), +} + +/// Judges `plan-read`'s arguments. A shape fault is `invalid-arguments`, +/// answered before anything is prepared. +pub fn judge_read_arguments(arguments: &Value) -> Result { + match serde_json::from_value::(arguments.clone()) { + Ok(ReadCall::Read(shape)) => Ok(shape), + Err(error) => Err(Refusal::new("invalid-arguments", error.to_string()) + .slot("arguments") + .value()), + } +} + +/// Serves one `plan-read` call for the session's `preparation`, as +/// `context-intake` serves its read: the arguments are judged first, then +/// the read is prepared, which records nothing, then [`read_answer`] reads +/// the phase's approved plans. A `failed` preparation answer is returned as +/// it is (D-17). +pub fn serve_read(arguments: &Value, preparation: &Preparation) -> Value { + let shape = match judge_read_arguments(arguments) { + Ok(shape) => shape, + Err(refusal) => return refusal, + }; + match prepared_read(preparation) { + Ok((store, project)) => read_answer(store, &project, &shape), + Err(answer) => answer, + } +} + +/// The answer for `plan-read` over `store`: the phase's approved plans in +/// plan-number order, each with its evidence map and its readiness, cut +/// into parts when large. A phase the roadmap does not hold is refused +/// `no-such-phase` echoing none of its number; any other fault is the read's +/// `failed` answer. +pub fn read_answer( + store: &S, + project: &ProjectId, + shape: &PlanReadShape, +) -> Value { + match read::read(store, project, shape.phase) { + Ok(read) => in_parts( + json!({"status": "ok", "phase": read.phase, "plans": read.plans}), + shape.part, + ), + Err(ReadError::NoSuchPhase) => { + Refusal::new(NO_SUCH_PHASE, "this project has no such phase") + .slot("phase") + .value() + } + Err(error) => read_failed(error), + } +} + +#[cfg(test)] +mod tests { + //! Expected answers are written out from design 0005 `phase plan` and + //! D-08, never from running this code. + + use super::*; + use crate::mcp::operations::expected::APPLY; + use crate::mcp::operations::{APPLY_OPERATIONS, Lookup, Tool, lookup}; + + const R1: &str = "9d0c1b7e-2f4a-4b6c-8d1e-3a5b7c9d0e2f"; + + fn plan(stories: Value) -> Value { + json!({"operation": "phase-plan", "request_id": R1, "phase": 1, "stories": stories}) + } + + fn refused(arguments: &Value) -> Value { + let refusal = judge_arguments(arguments).expect_err("refused"); + assert_eq!(refusal["status"], "refused", "{refusal}"); + refusal + } + + #[test] + fn a_phase_plan_shape_or_digest_judged_wrongly_is_caught() { + let mut unknown = plan(json!([1, 4])); + unknown["plan"] = json!(1); + let refusal = refused(&unknown); + assert_eq!(refusal["code"], "invalid-arguments"); + assert_eq!(refusal["slot"], "arguments"); + + let mut bad_id = plan(json!([1, 4])); + bad_id["request_id"] = json!("X"); + let refusal = refused(&bad_id); + assert_eq!(refusal["code"], "invalid-arguments"); + assert_eq!(refusal["slot"], "request_id"); + + let refusal = refused(&plan(json!("1"))); + assert_eq!(refusal["code"], "invalid-arguments"); + assert_eq!(refusal["slot"], "arguments"); + + let mut nothing = plan(json!([1, 4])); + nothing["instruction"] = json!("bal-nothing"); + let refusal = refused(¬hing); + assert_eq!(refusal["code"], "unknown-instruction"); + assert_eq!(refusal["slot"], "instruction"); + + // A retry sends the identical call, which must replay, while a + // reorder under the same request id is another request. + let first = judge_arguments(&plan(json!([1, 4]))).expect("accepted"); + assert_eq!(first.request.kind, CommandKind("phase.plan".into())); + assert_eq!((first.phase, first.stories.as_slice()), (1, &[1, 4][..])); + let again = judge_arguments(&plan(json!([1, 4]))).expect("accepted"); + assert_eq!(again.request.digest, first.request.digest); + let reordered = judge_arguments(&plan(json!([4, 1]))).expect("accepted"); + assert_ne!(reordered.request.digest, first.request.digest); + } + + #[test] + fn a_phase_plan_left_unserved_or_out_of_baseline_order_is_caught() { + assert_eq!( + lookup(Tool::Apply, Some("phase-plan")), + Lookup::Available { + needs_project: true + } + ); + assert_eq!(lookup(Tool::Query, Some("phase-plan")), Lookup::Unknown); + let names: Vec<&str> = APPLY_OPERATIONS.iter().map(|op| op.name).collect(); + let at = names + .iter() + .position(|name| *name == "phase-plan") + .expect("phase-plan is listed"); + // Every spelling up to `phase-plan` stays where it was when + // `phase-plan` was appended, written out by hand in `expected`. + assert_eq!(&names[..=at], &APPLY[..=at]); + assert_eq!(names[at - 1], "story-questions-submit"); + } + + /// O and O2, two planner orders' ids. + const O: &str = "1f2e3d4c-5b6a-4978-8695-a4b3c2d1e0f1"; + const O2: &str = "2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"; + + fn submit(order: &str) -> Value { + json!({"operation": "plan-submit", "request_id": R1, "work_order": order, + "plan": crate::planning::fixtures::pl1()}) + } + + fn replace(plan: u32, digest: &str) -> Value { + json!({"operation": "plan-replace", "request_id": R1, "work_order": O, + "plan": crate::planning::fixtures::pl1(), + "replaces": {"plan": plan, "digest": digest}}) + } + + fn submit_refused(arguments: &Value) -> Value { + let refusal = judge_submit_arguments(arguments).expect_err("refused"); + assert_eq!(refusal["status"], "refused", "{refusal}"); + refusal + } + + #[test] + fn a_plan_submission_shape_or_digest_judged_wrongly_is_caught() { + let mut instruction = submit(O); + instruction["instruction"] = json!("bal-phase-planner"); + let refusal = submit_refused(&instruction); + assert_eq!(refusal["code"], "invalid-arguments"); + assert_eq!(refusal["slot"], "arguments"); + + let refusal = submit_refused(&submit("ORDER")); + assert_eq!(refusal["code"], "invalid-arguments"); + assert_eq!(refusal["slot"], "work_order"); + + // A retry sends the identical call, which must replay, while the + // same plan answering another order is another request. + let first = judge_submit_arguments(&submit(O)).expect("accepted"); + assert_eq!(first.request.kind, CommandKind("scope.submit".into())); + assert_eq!(first.replaces, None); + let again = judge_submit_arguments(&submit(O)).expect("accepted"); + assert_eq!(again.request.digest, first.request.digest); + let other = judge_submit_arguments(&submit(O2)).expect("accepted"); + assert_ne!(other.request.digest, first.request.digest); + + let refusal = submit_refused(&replace(1, "ABC")); + assert_eq!(refusal["code"], "invalid-arguments"); + assert_eq!(refusal["slot"], "replaces"); + + let digest = "5c".repeat(32); + let one = judge_submit_arguments(&replace(1, &digest)).expect("accepted"); + let two = judge_submit_arguments(&replace(2, &digest)).expect("accepted"); + assert_eq!( + one.replaces, + Some(baley_core::plan::Replaces { + plan: 1, + digest: Hash([0x5c; 32]) + }) + ); + assert_ne!(one.request.digest, two.request.digest); + assert_ne!(one.request.digest, first.request.digest); + } + + #[test] + fn plan_submit_left_retired_or_plan_replace_out_of_baseline_order_is_caught() { + for name in ["plan-submit", "plan-replace"] { + assert_eq!( + lookup(Tool::Apply, Some(name)), + Lookup::Available { + needs_project: true + }, + "{name}" + ); + } + let names: Vec<&str> = APPLY_OPERATIONS.iter().map(|op| op.name).collect(); + // `plan-submit` keeps the place its retired spelling held, written + // out by hand in `expected`, right after `execution-authorize`. + let at = names.iter().position(|name| *name == "plan-submit"); + assert_eq!(at, APPLY.iter().position(|name| *name == "plan-submit")); + assert_eq!( + names[at.expect("plan-submit is listed") - 1], + "execution-authorize" + ); + let (last, earlier) = names.split_last().expect("a baseline"); + assert_eq!(*last, "plan-replace"); + assert_eq!(earlier.last(), Some(&"phase-plan")); + } + + #[test] + fn a_replacement_resent_after_its_approval_judged_instead_of_replayed_is_caught() { + use baley_core::policy::Host; + use baley_store::ServerCaller; + + use crate::mcp::handler::SessionLedger; + use crate::mcp::prepare::prepared_command; + use crate::planning::approve::tests::{approved, digest_of}; + use crate::planning::fixtures::{p0, pl1, store_c}; + use crate::planning::submit::tests::{order_o, plan_submitted}; + use crate::scope::fixtures::{ID, R2, R3, R4, R5, SESSION, T5, T6, T7, T8, head, project}; + + let (dir, store) = store_c(); + // The checkout the session is in: a project file naming the + // project and a `.git` entry, which discovery only looks for. + let root = dir.path().join("r"); + std::fs::create_dir_all(root.join(".git")).unwrap(); + std::fs::write( + root.join("baley.toml"), + format!("[project]\nid = \"{ID}\"\nname = \"r\"\n"), + ) + .unwrap(); + let directory = root.to_str().unwrap(); + let session = + ServerCaller::new(directory, directory, "claude-code", SESSION, &json!(7)).unwrap(); + + order_o(&store, R1); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R2, T5)); + assert_eq!(approved(&store, x1, &p0(), R3, T5)["status"], "ok"); + // PL1r replacing plan 1 at X1, recorded as `plan-replace` records + // it below the session, then approved, so plan 1 is no longer in + // force when the same request is sent again. + let mut pl1r = pl1(); + pl1r["goal"] = json!("Record every step, revised"); + let arguments = json!({"operation": "plan-replace", "request_id": R4, + "work_order": O, "plan": pl1r, + "replaces": {"plan": 1, "digest": x1.to_hex()}}); + let judged = judge_submit_arguments(&arguments).expect("accepted"); + let checked = replace::check( + &store, + &project(), + &judged.plan, + &judged.work_order, + judged.replaces.expect("a replacement"), + None, + ) + .expect("plan 1 is in force"); + let on = order_caller(&session, O).expect("O's form"); + let command = bind_instructions( + prepared_command(&project(), &judged.request, 8, T6, &on), + Some(&checked.evidence), + ) + .expect("the instructions are carried"); + let receipt = + crate::scope::submit::answer(submit::record(&store, &command, Some(&checked)), &store); + let x1r = digest_of(&receipt); + assert_eq!(approved(&store, x1r, &p0(), R5, T7)["status"], "ok"); + + let preparation = Preparation { + ledger: Some(std::sync::Arc::new(SessionLedger { + store, + config: dir.path().join("config"), + })), + host: Host::ClaudeCode, + caller: session, + at: T8.into(), + }; + let ledger = preparation.ledger.as_deref().unwrap(); + let before = head(&ledger.store); + // The capacity's settings read fails at git, which a replay never + // needs. + let mut process = + crate::process::Recorded::new().unavailable(std::io::Error::other("no git in tests")); + let resent = submit_through(&arguments, &preparation, &mut process); + assert_eq!(resent, receipt); + assert_eq!(head(&ledger.store), before); + } + + #[test] + fn a_plan_read_left_retired_or_answering_a_missing_phase_wrongly_is_caught() { + use crate::mcp::operations::QUERY_OPERATIONS; + use crate::mcp::operations::expected::QUERY; + + assert_eq!( + lookup(Tool::Query, Some("plan-read")), + Lookup::Available { + needs_project: true + } + ); + assert_eq!(lookup(Tool::Apply, Some("plan-read")), Lookup::Unknown); + let names: Vec<&str> = QUERY_OPERATIONS.iter().map(|op| op.name).collect(); + // `plan-read` keeps the place its retired spelling held, written out + // by hand in `expected`, between `evidence-read` and `context-intake`. + let at = names.iter().position(|name| *name == "plan-read"); + assert_eq!(at, QUERY.iter().position(|name| *name == "plan-read")); + let at = at.expect("plan-read is listed"); + assert_eq!( + (names[at - 1], names[at + 1]), + ("evidence-read", "context-intake") + ); + + let refusal = + judge_read_arguments(&json!({"operation": "plan-read", "phase": 1, "plans": [1]})) + .expect_err("an unknown member is refused"); + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], "invalid-arguments", "{refusal}"); + + let (_dir, store) = crate::planning::fixtures::store_c(); + let shape = + judge_read_arguments(&json!({"operation": "plan-read", "phase": 9})).expect("accepted"); + let missing = read_answer(&store, &crate::scope::fixtures::project(), &shape); + assert_eq!(missing["status"], "refused", "{missing}"); + assert_eq!(missing["code"], "no-such-phase", "{missing}"); + assert_eq!(missing["slot"], "phase", "{missing}"); + assert!(!missing.to_string().contains('9'), "{missing}"); + } +} diff --git a/crates/baley/src/mcp/questions.rs b/crates/baley/src/mcp/questions.rs index 2575c4fc..e38ed137 100644 --- a/crates/baley/src/mcp/questions.rs +++ b/crates/baley/src/mcp/questions.rs @@ -11,7 +11,10 @@ //! whether the owner gave the answer, so the record does not claim it, and //! the owner's name travels in each event's payload. A call that closes a //! story's set also issues the analyzer's drafting order with the answers -//! (D-08), which `baley questions answer` never does (ADR 0044). +//! (D-08), and one that closes a plan draft's set with an answer rejecting a +//! recommendation the planner's revision order (D-15), which `baley +//! questions answer` never does (ADR 0044). A plan draft's set closed on +//! its recommendations answers `ready` on either surface. use std::cell::RefCell; use std::collections::BTreeSet; @@ -33,8 +36,11 @@ use crate::mcp::capture::store_failed; use crate::mcp::handler::Preparation; use crate::mcp::prepare::WriteRequest; use crate::mcp::work_order::{judge_request_id, prepared_write, shape_fault}; +use crate::planning::inputs::Revision; +use crate::planning::order::{pending_planner_order, prepare_revision}; use crate::providers::identity::{self, OWNER_IDENTITY_MISSING}; use crate::questions::answer::{self, ANSWER_COMMAND, Drafting}; +use crate::questions::read::PlanSubject; use crate::refine::order::{pending_analyzer_order, prepare_drafting}; use crate::scope::submit::NOT_RECORDED_BUSY; use crate::work_order::route::host_names; @@ -111,45 +117,70 @@ pub fn judge_arguments(arguments: &Value) -> Result { } /// What a relayed answer call's check read: the answer check's read of the -/// set and, for a story's set, the story's pending analyzer order. +/// set and the live order of its subject: for a story's set, the story's +/// pending analyzer order; for a plan draft's, the phase's pending planner +/// order. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Relayed { /// The answer check's read. pub checked: answer::Checked, - /// The `work_order` document of the set's story's analyzer order pending - /// at the check, at the sequence that produced it, or none. + /// The `work_order` document of that order pending at the check, at the + /// sequence that produced it, or none. pub pending: Option, } +/// The order a relayed call's close issues, with the facts it binds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Closing { + /// The analyzer's drafting order of this story (D-08). + Drafting(u32, SetFacts), + /// The planner's revision order of this plan draft (D-15). + Revision(PlanSubject, SetFacts), +} + impl Relayed { - /// The story and its set's facts after the call when the call, recorded - /// by `owner` at `at`, closes a story's set and no analyzer order of the - /// story was pending at the check: the call then issues the drafting - /// order (D-08). None otherwise: a pending order keeps the story's one - /// live analyzer order (D-09), which the session's next `story-refine` - /// follows once it is settled, and a plan draft's set gets T9's outputs. - pub(crate) fn closing(&self, owner: &str, at: &str) -> Option<(u32, SetFacts)> { - let story = self.checked.story?; + /// The order the call, recorded by `owner` at `at`, issues with its set's + /// facts after the call, when no order of the set's subject was pending + /// at the check: the drafting order when it closes a story's set (D-08), + /// the planner's revision order when it closes a plan draft's set with an + /// answer rejecting a recommendation (D-15, PLN-R27). None otherwise: a + /// pending order keeps its subject's one live order (D-09, D-11), which + /// the session's next `story-refine` or `phase-plan` follows once it is + /// settled, and a plan draft's set closed on recommendations is `ready`. + pub(crate) fn closing(&self, owner: &str, at: &str) -> Option { if self.pending.is_some() { return None; } - Some((story, self.checked.closed_facts(owner, at)?)) + self.due(owner, at) } - /// The pending analyzer order's document when the call, recorded by - /// `owner` at `at`, closes a story's set beside it, so that order alone - /// keeps the call from issuing the drafting order. None otherwise. + /// The order the call would issue were nothing pending, by the rules + /// [`Self::closing`] gives. + fn due(&self, owner: &str, at: &str) -> Option { + let facts = self.checked.closed_facts(owner, at)?; + match (self.checked.story, self.checked.plan) { + (Some(story), _) => Some(Closing::Drafting(story, facts)), + (None, Some(plan)) if facts.answers.iter().any(|answer| !answer.accepted) => { + Some(Closing::Revision(plan, facts)) + } + _ => None, + } + } + + /// The pending order's document when the call, recorded by `owner` at + /// `at`, would issue an order beside it, so that order alone keeps the + /// call from issuing one. None otherwise. fn held_by(&self, owner: &str, at: &str) -> Option<&ObservedDocument> { - self.checked.story?; - self.checked.closed_facts(owner, at)?; + self.due(owner, at)?; self.pending.as_ref() } } /// A relayed answer call's check, run before admission and recording -/// nothing: the answer check, then for a story's set the story's pending -/// analyzer order with the document it was read from. A refusal or a read -/// fault is the answer to give. +/// nothing: the answer check, then the pending order of the set's subject +/// with the document it was read from: a story's analyzer order, or a plan +/// draft's phase's planner order. A refusal or a read fault is the answer to +/// give. pub(crate) fn relay_check( store: &S, project: &ProjectId, @@ -157,29 +188,34 @@ pub(crate) fn relay_check( call: &Call, ) -> Result { let checked = answer::check(store, project, set, call)?; - let pending = match checked.story { - Some(story) => pending_analyzer_order(store, project, story) - .map_err(|error| store_failed(&error, NOT_RECORDED_BUSY))? - .map(|document| ObservedDocument { - view: WORK_ORDER_VIEW.into(), - key: document.key, - produced_seq: Some(document.produced_seq), - }), - None => None, - }; + let pending = match (checked.story, checked.plan) { + (Some(story), _) => pending_analyzer_order(store, project, story), + (None, Some(plan)) => pending_planner_order(store, project, plan.phase), + (None, None) => Ok(None), + } + .map_err(|error| store_failed(&error, NOT_RECORDED_BUSY))? + .map(|document| ObservedDocument { + view: WORK_ORDER_VIEW.into(), + key: document.key, + produced_seq: Some(document.produced_seq), + }); Ok(Relayed { checked, pending }) } /// Records a relayed call `relayed` under `command` as `owner` once the write /// is prepared. When the call closes a story's set with no analyzer order of -/// the story pending, the drafting order is prepared as `drafting_id` under +/// the story pending, the drafting order is prepared as `order_id` under /// `policy`, the write's effective policy, for `host` with the catalog /// `names`, its `questions` input holding the set's answers and deferrals -/// with this call's own, and is issued with the answers. When a pending -/// analyzer order held the drafting order back, the recording observes that -/// order's document, so an order settled since the check makes the call -/// `ledger-busy` and the session's retry checks again. The answer is the -/// receipt, or why nothing was recorded. +/// with this call's own, and is issued with the answers. When it closes a +/// plan draft's set with an answer rejecting a recommendation and no planner +/// order of the phase pending, the planner's revision order is prepared the +/// same way, attempt 1 of a new chain, binding the planning inputs for the +/// phase's stories, the draft and the set's facts with this call's own, and +/// is issued with the answers. When a pending order held the new one back, +/// the recording observes that order's document, so an order settled since +/// the check makes the call `ledger-busy` and the session's retry checks +/// again. The answer is the receipt, or why nothing was recorded. #[allow(clippy::too_many_arguments)] pub(crate) fn relay_record( store: &S, @@ -189,34 +225,39 @@ pub(crate) fn relay_record( policy: &EffectivePolicy, host: Host, names: &AcceptedNames, - drafting_id: &str, + order_id: &str, ) -> Value { let at = &command.recorded_at; - let prepared = match relayed.closing(owner, at) { - Some((story, facts)) => { - match prepare_drafting( - store, - command, - story, - &facts, - policy, - host, - names, - drafting_id, + let (mut drafting, mut revision) = (None, None); + match relayed.closing(owner, at) { + Some(Closing::Drafting(story, facts)) => { + match prepare_drafting(store, command, story, &facts, policy, host, names, order_id) { + Ok(prepared) => drafting = Some(prepared), + Err(answer) => return answer, + } + } + Some(Closing::Revision(plan, facts)) => { + let draft = Revision { + draft: plan.draft, + set: &relayed.checked.set, + }; + match prepare_revision( + store, command, plan.phase, draft, &facts, policy, host, names, order_id, ) { - Ok(prepared) => Some(prepared), + Ok(prepared) => revision = Some(prepared), Err(answer) => return answer, } } - None => None, - }; - let drafting = match (&prepared, relayed.held_by(owner, at)) { - (Some(order), _) => Drafting::Issue(order), - (None, Some(pending)) => Drafting::HeldBy(pending), - (None, None) => Drafting::None, + None => {} + } + let order = match (&drafting, &revision, relayed.held_by(owner, at)) { + (Some(order), _, _) => Drafting::Issue(order), + (None, Some(order), _) => Drafting::Revise(order), + (None, None, Some(pending)) => Drafting::HeldBy(pending), + (None, None, None) => Drafting::None, }; answer::answer( - answer::record(store, command, owner, Some(&relayed.checked), drafting), + answer::record(store, command, owner, Some(&relayed.checked), order), store, ) } @@ -226,8 +267,9 @@ pub(crate) fn relay_record( /// session's caller with the relayed check as its own check; then the owner /// is read from the write's policy, falling back to git's `user.name`, and /// the call is recorded over the set the check read, with the drafting order -/// when it closes a story's set (D-08). A replay goes to the recording with -/// no read, and the store answers it from its record. +/// when it closes a story's set (D-08) and the revision order when it closes +/// a plan draft's set on a rejected recommendation (D-15). A replay goes to +/// the recording with no read, and the store answers it from its record. pub fn serve(arguments: &Value, preparation: &Preparation) -> Value { let judged = match judge_arguments(arguments) { Ok(judged) => judged, @@ -260,7 +302,7 @@ pub fn serve(arguments: &Value, preparation: &Preparation) -> Value { Ok(owner) => owner, Err(reason) => return Refusal::new(OWNER_IDENTITY_MISSING, reason).value(), }; - // The catalog is read only for a drafting order, and unused otherwise. + // The catalog is read only for an order to issue, and unused otherwise. let names = if relayed.closing(&owner, &command.recorded_at).is_some() { match host_names(store, preparation.host) { Ok(names) => names, @@ -285,11 +327,21 @@ pub fn serve(arguments: &Value, preparation: &Preparation) -> Value { } #[cfg(test)] -mod tests { +pub(crate) mod tests { //! Expected answers are written out from design 0005 `questions answer` - //! and design 0012's write rules, never from running this code. + //! and design 0012's write rules, never from running this code. Stores + //! are real SQLite stores in fresh temporary directories, with times + //! supplied, built from the plan's data store C, P0, N0 and PL2. + + use baley_core::questions::judge_call; + use baley_store_sqlite::SqliteStore; use super::*; + use crate::planning::fixtures::{n0, p0, pl2, store_c}; + use crate::planning::order::tests::{O, fail_by_hand, prepared}; + use crate::planning::submit::tests::{as_drafted, order_o, plan_submitted}; + use crate::refine::order::tests::{input_body, input_names, issued}; + use crate::scope::fixtures::{R1, R2, R3, R4, R5, T5, T6, T7, command, head, project}; const SET: &str = "5d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; const OTHER: &str = "6e2d3c4b-5f60-4b7c-9d8e-0f1a2b3c4d5e"; @@ -338,4 +390,176 @@ mod tests { let defer = |reason: &str| json!([{"question": "q2", "act": "defer", "reason": reason}]); assert_ne!(digest(SET, defer("a")), digest(SET, defer("b"))); } + + /// R, the revision order's id. + pub(crate) const REVISION: &str = "7c8d9e0f-1a2b-4c3d-8e4f-5a6b7c8d9e0f"; + /// Q, a planning order of phase 1 issued by hand. + const Q: &str = "8d9e0f1a-2b3c-4d4e-9f5a-6b7c8d9e0f1a"; + + /// `q1` answered `Postgres`, not its recommendation. + pub(crate) fn postgres() -> Value { + json!([{"question": "q1", "act": "answer", "answer": "Postgres"}]) + } + + /// Relays `items` on `set` under `request_id` at `at` through the relay + /// check and record under P0 and N0 for Claude Code as `Ada Owner`, as + /// `questions-answer` runs them below the session, any order issued as + /// `order_id`. Gives the answer. + pub(crate) fn relayed( + store: &SqliteStore, + set: &str, + items: &Value, + request_id: &str, + at: &str, + order_id: &str, + ) -> Value { + let call = judge_call(items).expect("the call's grammar holds"); + let relayed = match relay_check(store, &project(), set, &call) { + Ok(relayed) => relayed, + Err(refusal) => return refusal, + }; + let command = command(ANSWER_COMMAND, request_id, 9, at); + relay_record( + store, + &command, + "Ada Owner", + &relayed, + &p0(), + Host::ClaudeCode, + &n0(), + order_id, + ) + } + + /// Store C with O, PL2 submitted under O by R2 at T5. Gives the store + /// and S2. + fn pl2_drafted() -> (tempfile::TempDir, SqliteStore, String) { + let (dir, store) = store_c(); + order_o(&store, R1); + let receipt = plan_submitted(&store, &pl2(), O, None, R2, T5); + assert_eq!(receipt["status"], "ok", "{receipt}"); + let s2 = receipt["set"].as_str().unwrap().to_owned(); + (dir, store, s2) + } + + /// The ids of every order the store issued, oldest first. + fn issued_ids(store: &SqliteStore) -> Vec { + issued(store) + .iter() + .map(|event| event.payload["id"].as_str().unwrap().to_owned()) + .collect() + } + + #[test] + fn a_plan_set_closed_on_a_rejected_recommendation_without_its_revision_order_is_caught() { + let (_dir, store, s2) = pl2_drafted(); + let receipt = relayed(&store, &s2, &postgres(), R3, T6, REVISION); + assert_eq!(receipt["status"], "ok", "{receipt}"); + assert_eq!(receipt["now"]["state"], "closed", "{receipt}"); + assert_eq!(receipt["revision"]["work_order"], REVISION, "{receipt}"); + assert!(receipt.get("ready").is_none(), "{receipt}"); + + let order = crate::work_order::read::order(&store, &project(), REVISION) + .unwrap() + .expect("R is held"); + assert_eq!(order["state"], "pending", "{order}"); + let events = issued(&store); + let event = events + .iter() + .find(|event| event.payload["id"] == REVISION) + .expect("R is issued"); + assert_eq!(event.request_id.0, R3); + let payload = &event.payload; + assert_eq!(payload["role"], "planner"); + assert_eq!(payload["subject"], "phase/1"); + assert_eq!(payload["attempt"], 1); + assert_eq!(payload["request"], REVISION); + assert_eq!(payload["parent"], Value::Null); + let identities: Vec<&str> = payload["instructions"] + .as_array() + .unwrap() + .iter() + .map(|evidence| evidence["identity"].as_str().unwrap()) + .collect(); + assert_eq!(identities, ["bal-phase-planner"]); + assert_eq!( + input_names(event), + [ + "phase", + "stories", + "description", + "approved_items", + "draft", + "questions" + ] + ); + assert_eq!(input_body(&store, event, "draft"), as_drafted(pl2())); + let questions = input_body(&store, event, "questions"); + assert_eq!(questions["set"], s2.as_str()); + assert_eq!( + questions["answers"], + json!([{"question": "q1", "answer": "Postgres", "accepted": false, "round": 1, + "owner": "Ada Owner", "at": T6}]) + ); + let stories = input_body(&store, event, "stories"); + let ids: Vec<&Value> = stories + .as_array() + .unwrap() + .iter() + .map(|story| &story["id"]) + .collect(); + assert_eq!(ids, [&json!(1)]); + } + + #[test] + fn a_plan_set_closing_without_ready_or_a_revision_beside_a_pending_planner_order_is_caught() { + let (_dir, store, s2) = pl2_drafted(); + let take = json!([{"question": "q1", "act": "take"}]); + let receipt = relayed(&store, &s2, &take, R3, T6, REVISION); + assert_eq!(receipt["status"], "ok", "{receipt}"); + assert_eq!(receipt["now"]["state"], "closed", "{receipt}"); + assert_eq!(receipt["ready"], true, "{receipt}"); + assert!(receipt.get("revision").is_none(), "{receipt}"); + assert_eq!(issued_ids(&store), [O]); + + // Q pending at the check holds the revision back. + let (_dir, store, s2) = pl2_drafted(); + let (command_q, q) = prepared(&store, &[1], Q, R3, T6); + assert_eq!( + crate::planning::order::issue(&store, &command_q, &q)["status"], + "ok" + ); + let receipt = relayed(&store, &s2, &postgres(), R4, T7, REVISION); + assert_eq!(receipt["status"], "ok", "{receipt}"); + assert_eq!(receipt["now"]["state"], "closed", "{receipt}"); + assert!(receipt.get("revision").is_none(), "{receipt}"); + assert!(receipt.get("ready").is_none(), "{receipt}"); + assert_eq!(issued_ids(&store), [O, Q]); + + // Q failed between the check and the record: the set does not close + // with no revision. + let (_dir, store, s2) = pl2_drafted(); + let (command_q, q) = prepared(&store, &[1], Q, R3, T6); + assert_eq!( + crate::planning::order::issue(&store, &command_q, &q)["status"], + "ok" + ); + let call = judge_call(&postgres()).unwrap(); + let checked = relay_check(&store, &project(), &s2, &call).expect("checked"); + fail_by_hand(&store, Q, R4); + let before = head(&store); + let busy = relay_record( + &store, + &command(ANSWER_COMMAND, R5, 9, T7), + "Ada Owner", + &checked, + &p0(), + Host::ClaudeCode, + &n0(), + REVISION, + ); + assert_eq!(busy["status"], "failed", "{busy}"); + assert_eq!(busy["code"], "ledger-busy", "{busy}"); + assert_eq!(head(&store), before); + } } diff --git a/crates/baley/src/mcp/refine.rs b/crates/baley/src/mcp/refine.rs index c364efb8..0f7e13a5 100644 --- a/crates/baley/src/mcp/refine.rs +++ b/crates/baley/src/mcp/refine.rs @@ -640,10 +640,12 @@ mod tests { #[test] fn story_refine_left_out_of_the_baseline_or_unserved_is_caught() { let names: Vec<&str> = APPLY_OPERATIONS.iter().map(|op| op.name).collect(); - assert_eq!( - names[names.len() - 3..names.len() - 1], - ["questions-answer", "story-refine"] - ); + let at = names + .iter() + .position(|name| *name == "story-refine") + .expect("listed"); + assert_eq!(names[at - 1], "questions-answer"); + assert_eq!(names[at + 1], "story-questions-submit"); assert_eq!( lookup(Tool::Apply, Some("story-refine")), Lookup::Available { @@ -744,10 +746,12 @@ mod tests { #[test] fn story_questions_submit_out_of_the_baseline_or_unserved_is_caught() { let names: Vec<&str> = APPLY_OPERATIONS.iter().map(|op| op.name).collect(); - assert_eq!( - names[names.len() - 3..], - ["questions-answer", "story-refine", "story-questions-submit"] - ); + let at = names + .iter() + .position(|name| *name == "story-questions-submit") + .expect("listed"); + assert_eq!(names[at - 2..at], ["questions-answer", "story-refine"]); + assert_eq!(names[at + 1], "phase-plan"); let answer = schema_answer( &json!({"operation": "schema", "tool": "apply", "for": "story-questions-submit"}), ); diff --git a/crates/baley/src/mcp/tools.rs b/crates/baley/src/mcp/tools.rs index 1adf6383..f16d42fd 100644 --- a/crates/baley/src/mcp/tools.rs +++ b/crates/baley/src/mcp/tools.rs @@ -349,15 +349,15 @@ mod tests { let schema = input_schema(Tool::Query); let identity = alternative_of_type(&schema["properties"]["identity"], "object"); let objects = leaves(&identity); - assert_eq!(objects.len(), 7, "{identity}"); + assert_eq!(objects.len(), 9, "{identity}"); let object = &objects[0]; assert_eq!(object["properties"]["kind"]["const"], "capture"); assert_eq!(object["properties"]["id"]["type"], "string"); assert_eq!(object["required"], json!(["kind", "id"])); assert_eq!(object["additionalProperties"], false); - // The scope, work-order, question-set and refinement kinds are objects - // with their own typed fields too, so no identity leaves room for loose - // text. + // The scope, work-order, question-set, refinement, phase and plan kinds + // are objects with their own typed fields too, so no identity leaves + // room for loose text. for (object, kind) in objects[1..].iter().zip([ "draft", "roadmap", @@ -365,6 +365,8 @@ mod tests { "work_order", "questions", "refinement", + "phase", + "plan", ]) { assert_eq!(object["type"], "object", "{object}"); assert_eq!(object["properties"]["kind"]["const"], kind, "{object}"); @@ -374,6 +376,9 @@ mod tests { assert_eq!(objects[4]["properties"]["id"]["type"], "string"); assert_eq!(objects[5]["properties"]["set"]["type"], "string"); assert_eq!(objects[6]["properties"]["story"]["type"], "integer"); + assert_eq!(objects[7]["properties"]["phase"]["type"], "integer"); + assert_eq!(objects[8]["properties"]["phase"]["type"], "integer"); + assert_eq!(objects[8]["properties"]["plan"]["type"], "integer"); let parts = alternatives(&schema["properties"]["part"]); assert!(!parts.is_empty(), "no part in {schema}"); for part in parts { @@ -396,9 +401,11 @@ mod tests { // questions-answer takes request_id, set and items, // story-refine takes request_id, story and instruction, // story-questions-submit takes request_id, story, work_order and - // questions, context-submit takes request_id, work_order, story, set - // and truths, - // context-intake takes story and part, + // questions, phase-plan takes request_id, phase, stories and + // instruction, plan-submit takes request_id, work_order and plan, + // plan-replace takes those and replaces, context-submit takes + // request_id, work_order, story, set and truths, + // context-intake takes story and part, plan-read takes phase and part, // and route takes role or work_order. let names = |tool| { let schema = input_schema(tool); @@ -419,6 +426,7 @@ mod tests { "name", "operation", "part", + "phase", "role", "story", "tool", @@ -434,10 +442,13 @@ mod tests { "kind", "operation", "phase", + "plan", "questions", "reason", + "replaces", "request_id", "set", + "stories", "story", "submission", "text", @@ -476,7 +487,7 @@ mod tests { assert!( parts .iter() - .any(|d| d.ends_with("Taken by help and context-intake.")), + .any(|d| d.ends_with("Taken by help, plan-read and context-intake.")), "{parts:?}" ); assert!( @@ -529,7 +540,13 @@ mod tests { ); } assert_eq!(submissions.len(), 11, "{submissions:?}"); - assert!(description(&apply["properties"]["phase"]).ends_with("Taken by capture.")); + let phases: Vec = alternatives(&apply["properties"]["phase"]) + .iter() + .map(description) + .collect(); + for sentence in ["Taken by capture.", "Taken by phase-plan (required)."] { + assert!(phases.iter().any(|d| d.ends_with(sentence)), "{phases:?}"); + } } #[test] diff --git a/crates/baley/src/mcp/work_order.rs b/crates/baley/src/mcp/work_order.rs index 7e7134c3..5c747ace 100644 --- a/crates/baley/src/mcp/work_order.rs +++ b/crates/baley/src/mcp/work_order.rs @@ -21,7 +21,7 @@ use baley_core::policy::{AcceptedNames, CONFIG_UNAVAILABLE, EffectivePolicy, Hos use baley_core::work_order::{ ANSWERED, MATERIAL_UNAVAILABLE, NO_SUCH_WORK_ORDER, PENDING, Retry, RetryRefusal, START_ORDER_PENDING, START_SUBJECT, WORK_ORDER_NOT_FAILED, WORK_ORDER_NOT_PENDING, - WORK_ORDER_RETRIED, WORK_ORDER_VIEW, judge_retry, subject_story, work_order_key, + WORK_ORDER_RETRIED, WORK_ORDER_VIEW, judge_retry, subject_phase, subject_story, work_order_key, }; use baley_store::{ Absence, Command, CommandKind, Document, Hash, InstructionEvidence, Ledger, ObservedDocument, @@ -43,6 +43,7 @@ use crate::mcp::prepare::{ CHECKOUT_FACTS_UNAVAILABLE, LEDGER_UNAVAILABLE, Prepared, Stepped, WriteRequest, prepare_checked, prepare_settings_read, }; +use crate::planning::order::{pending_planner, planner_absences, planner_order_pending}; use crate::process::Process; use crate::refine::order::{ analyzer_absences, analyzer_order_pending, pending_analyzer, refinement_state, @@ -694,7 +695,9 @@ pub struct CheckedRetry { /// live analyzer order (D-09), and then `question-open` while a question of /// the story's latest set is open, as `story-refine` is, so a retried order /// neither drafts before the owner decided nor returns questions that would -/// abandon an open set. +/// abandon an open set. A phase's planner order is refused +/// `planner-order-pending` while another planner order of the phase is +/// pending, so a phase keeps one live planner order (D-11). pub fn retry_check( store: &S, project: &ProjectId, @@ -750,6 +753,17 @@ pub fn retry_check( // since the check makes it `ledger-busy`. documents.extend(refinement_state(store, project, story)?.documents); } + if let Some(phase) = planner_phase(&retry) { + let pending = pending_planner(store, project, phase) + .map_err(|error| store_failed(&error, NOT_RECORDED_BUSY))?; + if let Some(order) = pending { + return Err(planner_order_pending( + phase, + &order, + &format!("so no retry of {id} was issued"), + )); + } + } let instructions = match parent.body.get("instructions") { Some(Value::Array(listed)) => listed .iter() @@ -783,6 +797,13 @@ fn analyzer_story(retry: &Retry) -> Option { .flatten() } +/// The phase whose planner order `retry` re-issues, if it is one. +fn planner_phase(retry: &Retry) -> Option { + (retry.role == Role::Planner) + .then(|| subject_phase(&retry.subject)) + .flatten() +} + /// Order `id`'s document as a decision observes it. fn observed(id: &str, document: &Document) -> ObservedDocument { ObservedDocument { @@ -859,8 +880,9 @@ fn retry_refused(id: &str, refusal: RetryRefusal) -> Value { /// purge landing since makes the call `ledger-busy` with nothing recorded. A /// retried start order also declares a start order's two absences, no /// pending start order and no start approval, so a start approved since the -/// check makes it `ledger-busy` too, and a retried analyzer order declares no -/// pending analyzer order of its story, so one issued since does the same. +/// check makes it `ledger-busy` too, a retried analyzer order declares no +/// pending analyzer order of its story, and a retried planner order no +/// pending planner order of its phase, so one issued since does the same. pub fn issue_retry( store: &SqliteStore, command: &Command, @@ -895,6 +917,8 @@ pub fn issue_retry( start_absences() } else if let Some(story) = analyzer_story(retry) { analyzer_absences(story) + } else if let Some(phase) = planner_phase(retry) { + planner_absences(phase) } else { Vec::new() }; diff --git a/crates/baley/src/planning/approve.rs b/crates/baley/src/planning/approve.rs new file mode 100644 index 00000000..e4e066ec --- /dev/null +++ b/crates/baley/src/planning/approve.rs @@ -0,0 +1,1171 @@ +//! The owner's approval of a plan draft by its digest (design 0005 section +//! 5 `plan approve`, PLN-R14, PLN-R15, PLN-R26, PLN-R27, D-02, D-06, D-07, +//! D-14, D-16), in two steps. +//! +//! The first step reads and judges outside any transaction, so a refusal +//! records nothing: the draft in D-16's order, then `phase-not-active` when +//! a different phase is active, then the plan judged again against the +//! phase as it stands now. Build 4 T14 adds `review-unsettled` after these +//! refusals, judged against the same digest. A replacement draft is judged +//! by the replacement judge again before its plan is. A first step whose +//! capacity or suite differs from the policy the approval is recorded under +//! is run again under that policy. The second step records one +//! `plan.approved` as the owner with the next plan number, and for a +//! replacement `plan.replaced` with it, confirming inside its transaction +//! that nothing the first step read has moved. + +use std::collections::BTreeMap; +use std::num::NonZeroU32; + +use baley_core::plan::{ + DraftRead, PHASE_PLAN_VIEW, PLAN_APPROVED, PLAN_APPROVED_VERSION, PLAN_KIND, PLAN_REPLACED, + PLAN_REPLACED_VERSION, Plan, PlanApproval, PlanApprovalFacts, PlanApprovalRefusal, PlanDraft, + RecordedPlan, Replaces, judge_plan, judge_plan_approval, judge_submit_phase, phase_plan_key, + phase_stream, read_plan_draft, replaced_payload, +}; +use baley_core::policy::{EffectivePolicy, Value as Setting}; +use baley_core::questions::{QUESTIONS_VIEW, SetFacts, questions_key}; +use baley_core::scope::{DRAFT_VIEW, PROJECT_STREAM, PriorApproval, SCOPE_SUBMITTED, draft_key}; +use baley_store::{ + Absence, Actor, Command, Decision, Document, EVENT_PAGE_BOUND, EventMatch, Hash, HistoryFilter, + Ledger, NewEvent, Observed, ObservedDocument, OutcomeKind, PageRequest, PayloadRef, Payloads, + ProjectId, Recorded, StaleInput, StoreError, StreamName, Transaction, Views, +}; +use serde_json::{Value, json}; + +use crate::envelope::Refusal; +use crate::mcp::capture::{PLACE_LEDGER, failed, store_failed}; +use crate::mcp::prepare::LEDGER_UNAVAILABLE; +use crate::planning::submit::{phase_not_active, plan_refused}; +use crate::planning::{facts, replace}; +use crate::questions::read::{SetRead, read as read_set}; +use crate::scope::approve::newest_query; +use crate::scope::read::{Preview, PreviewError, preview, preview_of}; +use crate::scope::submit::NOT_RECORDED_BUSY; + +/// What a refused approval did not do. +const NOT_APPROVED: &str = "nothing was approved"; + +/// The setting the suite is read from. +const SUITE_SETTING: &str = "workflow.test_command"; + +/// What the first step read and judged, which the second step confirms and +/// records. +#[derive(Debug, Clone, PartialEq)] +pub struct Judged { + /// The approved draft's digest. + digest: Hash, + /// The sequence of its latest submission. + seq: u64, + /// The newest plan draft of its phase, digest and sequence. + newest: (Hash, u64), + /// Whether a `plan.approved` naming the digest was recorded before its + /// latest submission. + approved_before: bool, + /// The plan, judged again against the phase as it stands. + plan: Plan, + /// The approved plan the draft replaces, or none for a new plan. + replaces: Option, + /// The evidence items exactly as submitted. + evidence_map: Vec, + /// The id of the draft's question set. + set: String, + /// The capacity the plan was judged under, or none. + capacity: Option, + /// The project's test command, or none (D-14). + suite: Option, + /// The draft body's reference, as its `scope.submitted` holds it. + body: PayloadRef, + /// The `phase_plan` document, the draft's set's `questions` document, + /// then the facts' documents, each at the sequence that produced it. + documents: Vec, + /// What the recording relies on being absent. + absences: Vec, +} + +/// One recorded approval of a digest. +struct Approval { + seq: u64, + owner: String, + at: String, +} + +/// The first step of approving the plan draft `digest` in `project` under +/// `policy`, the effective policy: reads the draft (none, or one that is +/// not kind `plan`, is `unknown-draft`; a body that does not read back as a +/// plan draft is a ledger fault, never approved), its `scope.submitted` at +/// its sequence with the body's reference, the newest plan draft of its +/// phase, the phase's `phase_plan` document with its current draft's set and +/// that set's facts (a different current draft there, submitted after the +/// newest read, standing as the newest, so the draft is `stale-draft` +/// rather than a ledger fault), and last every `plan.approved` naming the +/// digest, so one landing after that read moves the `phase_plan` document +/// the second step observes. It judges them in D-16's order, then refuses +/// `phase-not-active` naming another active phase (D-02), then gathers the +/// phase's facts now with the policy's capacity and judges the plan again +/// with `judge_plan` (D-16), every refusal at slot `digest`. The suite is +/// the policy's `workflow.test_command`, none when it is not set (D-14). +/// A draft whose body names the plan it replaces is judged, after +/// `phase-not-active`, by the replacement judge again over the phase now, +/// `no-such-plan` or `admitted-plan` at slot `replaces`, and its plan judged +/// with the replaced plan's tasks and items off the phase (D-04). Nothing is +/// recorded. +pub fn judge( + store: &S, + project: &ProjectId, + digest: Hash, + policy: &EffectivePolicy, +) -> Result { + let busy = |error: StoreError| store_failed(&error, NOT_RECORDED_BUSY); + let (target, seq) = match preview(store, project, digest) { + Ok(read) if read.kind == PLAN_KIND => accept(&read)?, + Ok(_) | Err(PreviewError::UnknownDraft) => { + return Err(refused(&PlanApprovalRefusal::UnknownDraft)); + } + Err(error) => return Err(preview_failed(error)), + }; + let phase = target + .plan + .get("phase") + .and_then(Value::as_u64) + .and_then(|phase| u32::try_from(phase).ok()) + .ok_or_else(|| unreadable("the draft's phase cannot be read"))?; + let body = submitted_body(store, project, digest, seq).map_err(busy)?; + let newest = match store + .find( + project, + DRAFT_VIEW, + &newest_query(PLAN_KIND, &phase_stream(phase)), + ) + .map_err(busy)? + .items + .into_iter() + .next() + { + Some(document) => { + let read = preview_of(store, &document).map_err(preview_failed)?; + let (plan, newest_seq) = accept(&read)?; + Some((read.digest, newest_seq, plan)) + } + None => None, + }; + let key = phase_plan_key(phase); + let phase_plan = store.get(project, PHASE_PLAN_VIEW, &key).map_err(busy)?; + let mut documents = vec![ObservedDocument { + view: PHASE_PLAN_VIEW.into(), + key, + produced_seq: phase_plan.as_ref().map(|document| document.produced_seq), + }]; + let current = current_draft(phase_plan.as_ref().map(|document| &document.body), digest)?; + // The `phase_plan` document is read after the newest index, so a draft + // it holds in this one's place was submitted since: judged the newest, + // this draft is refused `stale-draft`, as a later run refuses it. + let newest = match current { + Current::Other(other) + if newest + .as_ref() + .is_none_or(|(newest, _, _)| *newest != other) => + { + let read = preview(store, project, other).map_err(preview_failed)?; + let (plan, other_seq) = accept(&read)?; + Some((read.digest, other_seq, plan)) + } + _ => newest, + }; + let set = match current { + Current::This(set) => Some(set), + Current::None | Current::Other(_) => None, + }; + let facts = match &set { + Some(set) => match read_set(store, project, set).map_err(busy)? { + SetRead::Held(held) => { + documents.push(ObservedDocument { + view: QUESTIONS_VIEW.into(), + key: questions_key(set), + produced_seq: Some(held.produced_seq), + }); + held.facts + } + SetRead::NotHeld | SetRead::Unreadable(_) => { + return Err(unreadable("the draft's question set cannot be read")); + } + }, + None => SetFacts { + questions: Vec::new(), + answers: Vec::new(), + deferrals: Vec::new(), + abandoned: None, + }, + }; + // Read after the `phase_plan` document: an approval landing before this + // read is seen here, and one landing after it moves that document. + let approvals = approvals_of(store, project, phase, digest).map_err(busy)?; + let prior = approvals.iter().find(|approval| approval.seq > seq); + judge_plan_approval(&PlanApprovalFacts { + target: Some(DraftRead { + digest, + plan: &target, + }), + recorded: body.is_some(), + newest: newest.as_ref().map(|(digest, _, plan)| DraftRead { + digest: *digest, + plan, + }), + approved: prior.map(|approval| PriorApproval { + owner: &approval.owner, + at: &approval.at, + }), + set: &facts, + }) + .map_err(|refusal| refused(&refusal))?; + // An approved judgement had its event, a newest draft and, as the + // phase's current draft, a set: a draft replaced since was refused + // stale above, so a missing one here is the ledger's fault. + let (Some(body), Some((newest_digest, newest_seq, _)), Some(set)) = (body, newest, set) else { + return Err(unreadable( + "the draft's record or its question set cannot be read", + )); + }; + + let capacity = facts::capacity(policy); + let read = facts::read(store, project, phase, capacity)?; + judge_submit_phase(phase, &read.active) + .map_err(|refusal| phase_not_active(&refusal, "digest", NOT_APPROVED))?; + let facts = match target.replaces { + None => read.facts.clone(), + Some(replaces) => { + replace::facts_without(store, project, phase, replaces, &read, NOT_APPROVED)? + } + }; + let plan = judge_plan(&target.plan, &facts) + .map_err(|refusal| plan_refused(&refusal, "digest", NOT_APPROVED))?; + let draft = match target.replaces { + None => PlanDraft::new(&plan), + Some(replaces) => PlanDraft::replacing(&plan, replaces), + }; + if draft.digest() != digest { + return Err(unreadable( + "the draft's body no longer reads as the plan it was submitted as", + )); + } + documents.extend_from_slice(read.documents()); + let evidence_map = target.plan["evidence_map"] + .as_array() + .cloned() + .unwrap_or_default(); + Ok(Judged { + digest, + seq, + newest: (newest_digest, newest_seq), + approved_before: approvals.iter().any(|approval| approval.seq < seq), + plan, + replaces: target.replaces, + evidence_map, + set, + capacity, + suite: suite(policy), + body, + documents, + absences: read.absences().to_vec(), + }) +} + +/// The first step's `judged` held to `policy`, the policy the approval is +/// recorded under: `judged` itself when `policy` sets the capacity and the +/// suite it was judged under, otherwise the first step run again under +/// `policy`. The terminal reads the settings once to judge and again at +/// the policy step, so a change between the two reads is judged under the +/// version the approval names, never recorded on the first read's +/// judgement. Nothing is recorded. +pub fn rejudged( + store: &S, + project: &ProjectId, + judged: Judged, + policy: &EffectivePolicy, +) -> Result { + if judged.capacity == facts::capacity(policy) && judged.suite == suite(policy) { + return Ok(judged); + } + judge(store, project, judged.digest, policy) +} + +/// The second step: records the approval judged by the first step under a +/// copy of `command` whose actor is the owner, with `owner` as the owner's +/// name and the command's time as Baley's (D-06). Inside the transaction it +/// confirms the draft at the sequence read with its `scope.submitted`, the +/// newest plan draft of the phase unchanged by digest and sequence, and no +/// `plan.approved` of the digest since; then takes one more than the highest +/// number ever assigned in the phase from `phase_plan`, 1 when none, a +/// number past `u32::MAX` being a store fault with nothing recorded (D-07); +/// and appends `plan.approved` on `phase/` with the phase, the number, +/// the digest, the stories, the size, the suite or null, the set, the +/// evidence map inline exactly as submitted and the body's reference +/// attached as it is held; for a replacement, then `plan.replaced` naming +/// the phase, the old number, the old digest and the new one, the owner and +/// the time, in the same transaction (D-04, D-07). The decision observes every document the first +/// step read and declares its absences, so anything moved since, a phase +/// made active among them, makes the call `ledger-busy` with nothing +/// recorded. A retry of a request the store holds is answered from its +/// record before any decision runs; a decision run without the first step's +/// reads records nothing. +/// +/// The receipt: `status`, `kind`, `digest`, `phase`, `plan`, `stories`, +/// `size`, `suite` (null when none, with `notice` naming +/// `workflow.test_command` and why it matters), `set`, `owner`, `at` and, +/// for a replacement, `replaces` naming the plan replaced and its digest. +pub fn record( + store: &L, + command: &Command, + judged: Option<&Judged>, + owner: &str, +) -> Result { + let command = Command { + actor: Actor::Owner, + ..command.clone() + }; + let at = command.recorded_at.clone(); + store.transact(&command, &mut |tx| { + let Some(judged) = judged else { + return Err(StoreError::Unavailable( + "a plan approval reached its transaction without its first step's reads".into(), + )); + }; + let phase = judged.plan.phase(); + confirm_draft(tx, judged)?; + // A transaction cannot ask for an approval after a sequence, so when + // one preceded the latest submission a later one is left to the + // `phase_plan` document, which every approval of the phase moves. + let approved = approval_of(phase, judged.digest); + if !judged.approved_before && tx.event_exists(&approved)? { + return Err(StoreError::Stale(StaleInput::Absence(Absence::Event( + approved, + )))); + } + confirm_newest(tx, phase, judged)?; + let number = next_number(tx, phase)?; + let approval = PlanApproval { + phase, + plan: number, + digest: judged.digest, + stories: judged.plan.stories(), + size: judged.plan.size(), + suite: judged.suite.as_deref(), + question_set: &judged.set, + evidence_map: &judged.evidence_map, + body: &judged.body, + owner, + at: &at, + }; + tx.append(NewEvent { + stream: StreamName(phase_stream(phase)), + type_name: PLAN_APPROVED.into(), + type_version: PLAN_APPROVED_VERSION, + git: None, + payload: approval.payload(), + attachments: vec![judged.body.clone()], + })?; + // The new number is assigned first, so the replaced plan's number + // stays counted in `highest` and is never assigned again (D-07). + if let Some(replaces) = judged.replaces { + tx.append(NewEvent { + stream: StreamName(phase_stream(phase)), + type_name: PLAN_REPLACED.into(), + type_version: PLAN_REPLACED_VERSION, + git: None, + payload: replaced_payload( + phase, + replaces.plan, + replaces.digest, + judged.digest, + owner, + &at, + ), + attachments: Vec::new(), + })?; + } + let mut receipt = json!({ + "status": "ok", + "kind": PLAN_KIND, + "digest": judged.digest.to_hex(), + "phase": phase, + "plan": number, + "stories": judged.plan.stories(), + "size": judged.plan.size(), + "suite": judged.suite, + "set": judged.set, + "owner": owner, + "at": at, + }); + if let Some(replaces) = judged.replaces { + receipt["replaces"] = + json!({"plan": replaces.plan, "digest": replaces.digest.to_hex()}); + } + if judged.suite.is_none() { + receipt["notice"] = json!(format!( + "{SUITE_SETTING} is not set, so the plan was approved with no suite and cannot be admitted to execution until it is set" + )); + } + Ok(Decision { + kind: OutcomeKind::Done, + answer: receipt, + sensitive: false, + observed: Observed { + documents: judged.documents.clone(), + absences: judged.absences.clone(), + ..Observed::default() + }, + git: None, + }) + }) +} + +/// A `plan.approved` on phase `phase`'s stream naming `digest`. +fn approval_of(phase: u32, digest: Hash) -> EventMatch { + EventMatch { + type_name: PLAN_APPROVED.into(), + stream: Some(StreamName(phase_stream(phase))), + fields: BTreeMap::from([("digest".to_string(), json!(digest.to_hex()))]), + } +} + +/// The draft is at the sequence read and its `scope.submitted` is there. +fn confirm_draft(tx: &mut dyn Transaction, judged: &Judged) -> Result<(), StoreError> { + let key = draft_key(judged.digest); + let now = tx.get(DRAFT_VIEW, &key)?.as_ref().and_then(sequence); + let submitted = EventMatch { + type_name: SCOPE_SUBMITTED.into(), + stream: Some(StreamName(PROJECT_STREAM.into())), + fields: BTreeMap::from([("digest".to_string(), json!(judged.digest.to_hex()))]), + }; + if now != Some(judged.seq) || !tx.event_exists(&submitted)? { + return Err(StoreError::Stale(StaleInput::Document { + view: DRAFT_VIEW.into(), + key, + seen: Some(judged.seq), + now, + })); + } + Ok(()) +} + +/// The newest plan draft of phase `phase` is the one the first step read, +/// by digest and sequence, never by time: two submissions can share a time. +fn confirm_newest(tx: &mut dyn Transaction, phase: u32, judged: &Judged) -> Result<(), StoreError> { + let newest = tx + .find(DRAFT_VIEW, &newest_query(PLAN_KIND, &phase_stream(phase)))? + .items + .into_iter() + .next(); + let now = newest.as_ref().and_then(|document| { + let digest = document + .body + .get("digest") + .and_then(Value::as_str) + .and_then(Hash::from_hex)?; + Some((digest, sequence(document)?)) + }); + if now != Some(judged.newest) { + return Err(StoreError::Stale(StaleInput::Document { + view: DRAFT_VIEW.into(), + key: draft_key(judged.newest.0), + seen: Some(judged.newest.1), + now: now.map(|(_, seq)| seq), + })); + } + Ok(()) +} + +/// One more than the highest plan number ever assigned in phase `phase`, +/// read from `phase_plan` inside `tx`, 1 when none was (D-07). +fn next_number(tx: &mut dyn Transaction, phase: u32) -> Result { + let highest = match tx.get(PHASE_PLAN_VIEW, &phase_plan_key(phase))? { + None => 0, + Some(document) => document + .body + .get("highest") + .and_then(Value::as_u64) + .ok_or_else(|| { + StoreError::Unavailable(format!("phase {phase}'s plan numbers cannot be read")) + })?, + }; + highest + .checked_add(1) + .and_then(|next| u32::try_from(next).ok()) + .ok_or_else(|| StoreError::Unavailable(format!("phase {phase} has no plan number left"))) +} + +/// The latest submission's sequence a `draft` document holds. +fn sequence(document: &Document) -> Option { + document.body.get("seq").and_then(Value::as_u64) +} + +/// The suite `policy` sets, or none. +fn suite(policy: &EffectivePolicy) -> Option { + match policy + .settings + .get(SUITE_SETTING) + .and_then(|effective| effective.value.as_ref()) + { + Some(Setting::Command(command)) => Some(command.clone()), + _ => None, + } +} + +/// A recorded plan draft read back, with its latest submission's sequence. +/// A body that does not read back as a plan draft is a ledger fault. +fn accept(read: &Preview) -> Result<(RecordedPlan, u64), Value> { + read_plan_draft(&read.submission) + .map(|plan| (plan, read.seq)) + .ok_or_else(|| unreadable("the draft's body no longer reads as a plan draft")) +} + +/// The body reference of `project`'s `scope.submitted` at `seq` naming +/// `digest`, or none when no such event is there. +fn submitted_body( + store: &L, + project: &ProjectId, + digest: Hash, + seq: u64, +) -> Result, StoreError> { + let filter = HistoryFilter { + types: vec![SCOPE_SUBMITTED.into()], + git_commit: None, + }; + let page = PageRequest { + limit: 1, + after: None, + }; + let digest = json!(digest.to_hex()); + Ok(store + .history(project, seq..=seq, &filter, page)? + .items + .iter() + .find(|event| event.payload.get("digest") == Some(&digest)) + .and_then(|event| PayloadRef::from_value(&event.payload["body"]))) +} + +/// The phase's current plan draft as its `phase_plan` document holds it, +/// beside the draft being approved. +enum Current { + /// The phase holds no unapproved draft. + None, + /// The draft being approved is current, with its set's id. + This(String), + /// Another draft, by its digest, replaced it (D-03). + Other(Hash), +} + +/// The phase's current draft beside `digest`. A draft that cannot be read +/// is a ledger fault. +fn current_draft(phase_plan: Option<&Value>, digest: Hash) -> Result { + let draft = match phase_plan.and_then(|body| body.get("draft")) { + None | Some(Value::Null) => return Ok(Current::None), + Some(draft) => draft, + }; + let held = draft + .get("digest") + .and_then(Value::as_str) + .and_then(Hash::from_hex); + match (held, draft.get("set").and_then(Value::as_str)) { + (Some(held), Some(set)) if held == digest => Ok(Current::This(set.to_owned())), + (Some(held), Some(_)) => Ok(Current::Other(held)), + _ => Err(unreadable("the phase's current plan draft cannot be read")), + } +} + +/// Every `plan.approved` on phase `phase`'s stream naming `digest`, oldest +/// first, read from the events. +fn approvals_of( + store: &L, + project: &ProjectId, + phase: u32, + digest: Hash, +) -> Result, StoreError> { + let filter = HistoryFilter { + types: vec![PLAN_APPROVED.into()], + git_commit: None, + }; + let stream = phase_stream(phase); + let digest = json!(digest.to_hex()); + let text = |value: &Value, name: &str| { + value + .get(name) + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned() + }; + let mut approvals = Vec::new(); + let mut after = None; + loop { + let page = store.history( + project, + 1..=u64::MAX, + &filter, + PageRequest { + limit: EVENT_PAGE_BOUND, + after, + }, + )?; + approvals.extend( + page.items + .iter() + .filter(|event| { + event.stream == stream && event.payload.get("digest") == Some(&digest) + }) + .map(|event| Approval { + seq: event.seq, + owner: text(&event.payload, "owner"), + at: text(&event.payload, "at"), + }), + ); + match page.next { + Some(next) => after = Some(next), + None => return Ok(approvals), + } + } +} + +fn preview_failed(error: PreviewError) -> Value { + match error { + PreviewError::Store(error) => store_failed(&error, NOT_RECORDED_BUSY), + PreviewError::UnknownDraft | PreviewError::Unreadable(_) => { + unreadable("the draft is recorded, but its document or body cannot be read") + } + } +} + +fn unreadable(reason: &str) -> Value { + failed(LEDGER_UNAVAILABLE, reason, PLACE_LEDGER) +} + +/// The `refused` answer for a plan approval, slot `digest`, with what the +/// refusal names in its details. +fn refused(refusal: &PlanApprovalRefusal) -> Value { + let reason = match refusal { + PlanApprovalRefusal::UnknownDraft => { + "no plan draft has this digest, so nothing was approved" + } + PlanApprovalRefusal::StaleDraft { .. } => { + "a newer plan draft of the same phase was submitted after this one, so it was not approved. The details name the first part that differs" + } + PlanApprovalRefusal::DraftApproved { .. } => { + "this draft was already approved after its latest submission, so it was not approved again. The details name that approval" + } + PlanApprovalRefusal::QuestionOpen { .. } => { + "a question of the draft's set is neither answered nor deferred, so the plan was not approved. The details name each open question" + } + PlanApprovalRefusal::AnswerNotApplied { .. } => { + "an answer on the draft's set rejected its recommended answer, so the plan does not yet apply it and was not approved. The details name each such question" + } + }; + let answer = Refusal::new(refusal.code(), reason).slot("digest"); + match refusal.details() { + Some(details) => answer.details(details), + None => answer, + } + .value() +} + +#[cfg(test)] +pub(crate) mod tests { + //! Stores are real SQLite stores in fresh temporary directories, with + //! times supplied; expected answers are written out from design 0005 + //! sections 5 and 6, D-02, D-03, D-05, D-06, D-07, D-14, D-16 and the + //! plan's data store C, P0, P3, PL1, PL2 and PL3, never from running this + //! code. + + use std::cell::RefCell; + use std::ops::RangeInclusive; + use std::path::Path; + + use baley_core::policy::{Host, Schema, effective_policy}; + use baley_core::scope::{PROJECT_STREAM, SCOPE_SUBMITTED_VERSION, submitted_payload}; + use baley_store::{ + Anchor, Claim, ClaimId, ClaimOwner, Claimed, Decide, DecideClaim, DecideReconcile, + Decision, DocKey, Event, Head, IndexQuery, NewEvent, Observed, OutcomeKind, Page, + PayloadBody, PayloadStatus, ReconcileAuthority, RetentionClass, StreamName, VerifyReport, + canonical_json, + }; + use baley_store_sqlite::SqliteStore; + + use super::*; + use crate::planning::fixtures::*; + use crate::planning::order::tests::O; + use crate::planning::submit::tests::{order_o, order_q, plan_submitted}; + use crate::scope::fixtures::*; + + /// P0 with a project file setting `planning.phase_capacity = 1`. + fn capacity_one() -> EffectivePolicy { + let file = crate::settings::file( + Path::new("/r/baley.toml"), + b"[planning]\nphase_capacity = 1\n".to_vec(), + ); + effective_policy( + Schema::standard(), + Some(Host::ClaudeCode), + None, + Some(&file), + ) + .expect("the capacity is read") + } + + /// The digest a submit receipt names. + pub(crate) fn digest_of(receipt: &Value) -> Hash { + assert_eq!(receipt["status"], "ok", "{receipt}"); + Hash::from_hex(receipt["digest"].as_str().unwrap()).unwrap() + } + + /// The first step of `digest` under `policy`, which must refuse with + /// `code` at slot `digest` and record nothing. Gives the refusal. + fn refused_with( + store: &SqliteStore, + digest: Hash, + policy: &EffectivePolicy, + code: &str, + ) -> Value { + let before = head(store); + let refusal = + judge(store, &project(), digest, policy).expect_err("the approval is refused"); + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], code, "{refusal}"); + assert_eq!(refusal["slot"], "digest", "{refusal}"); + assert_eq!(head(store), before); + refusal + } + + /// Records a draft of `kind` filed under `target` by hand, its body a + /// `record` payload, under `request_id`. Gives its digest. + fn drafted_by_hand( + store: &SqliteStore, + kind: &str, + target: &str, + digest: Hash, + request_id: &str, + ) -> Hash { + let body = canonical_json(&json!({"kind": kind})).unwrap(); + store + .transact(&command("test.draft", request_id, 9, T5), &mut |tx| { + let body = tx.put_payload(&body, RetentionClass::Record)?; + tx.append(NewEvent { + stream: StreamName(PROJECT_STREAM.into()), + type_name: SCOPE_SUBMITTED.into(), + type_version: SCOPE_SUBMITTED_VERSION, + git: None, + payload: submitted_payload(digest, kind, target, &body), + attachments: vec![body], + })?; + Ok(Decision { + kind: OutcomeKind::Done, + answer: json!({"status": "ok"}), + sensitive: false, + observed: Observed::default(), + git: None, + }) + }) + .expect("the draft is recorded"); + digest + } + + #[test] + fn a_plan_approval_judged_against_the_phase_as_submitted_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R2, T5)); + approve_by_hand(&store, R3, 1, 1, Hash([0x7d; 32]), &[1], 1, &[], Vec::new()); + let refusal = refused_with(&store, x1, &capacity_one(), "over-capacity"); + assert_eq!(refusal["details"], json!({"stories": [1], "size": 2})); + } + + #[test] + fn an_approval_recorded_on_settings_other_than_its_policy_steps_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R2, T5)); + approve_by_hand(&store, R3, 1, 1, Hash([0x7d; 32]), &[1], 1, &[], Vec::new()); + // Judged under P0, with no capacity and no suite set; the policy + // step then reads a capacity of 1, or a suite. + let judged = judge(&store, &project(), x1, &p0()).expect("PL1 fits with no capacity"); + + let before = head(&store); + let refusal = rejudged(&store, &project(), judged.clone(), &capacity_one()) + .expect_err("PL1 takes phase 1 to 2 tasks, over a capacity of 1"); + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], "over-capacity", "{refusal}"); + assert_eq!(refusal["slot"], "digest", "{refusal}"); + assert_eq!(refusal["details"], json!({"stories": [1], "size": 2})); + assert_eq!(head(&store), before); + + let suited = rejudged(&store, &project(), judged, &p3()).expect("PL1 fits under P3"); + assert_eq!(suited.suite.as_deref(), Some("cargo nextest run")); + } + + #[test] + fn a_truth_or_scope_draft_approved_as_a_plan_is_caught() { + let (_dir, store) = store_c(); + let truths = drafted_by_hand(&store, "story-truths", "story/1", Hash([0x3a; 32]), R1); + let phase_edit = edit(&store, &[1, 4], O, R2, T5); + for digest in [truths, phase_edit] { + refused_with(&store, digest, &p0(), "unknown-draft"); + } + } + + #[test] + fn a_replaced_plan_draft_approvable_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let x2 = digest_of(&plan_submitted(&store, &pl2(), O, None, R2, T5)); + digest_of(&plan_submitted(&store, &pl3(), O, None, R3, T6)); + let refusal = refused_with(&store, x2, &p0(), "stale-draft"); + assert_eq!(refusal["details"], json!({"path": "goal"})); + } + + #[test] + fn a_draft_replaced_between_the_approvals_reads_answered_as_an_unreadable_ledger_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let x2 = digest_of(&plan_submitted(&store, &pl2(), O, None, R2, T5)); + let reading = SubmitsDuring::new(&store, || { + digest_of(&plan_submitted(&store, &pl3(), O, None, R3, T6)); + }); + let refusal = + judge(&reading, &project(), x2, &p0()).expect_err("the replaced draft is refused"); + assert!(reading.landed(), "PL3 was submitted between the reads"); + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], "stale-draft", "{refusal}"); + assert_eq!(refusal["slot"], "digest", "{refusal}"); + assert_eq!(refusal["details"], json!({"path": "goal"})); + } + + /// The real store, with `land` run once just after the first read of + /// the `draft` view's index returns: the window in which another plan + /// draft of the phase can be submitted between the first step's reads. + struct SubmitsDuring<'a> { + store: &'a SqliteStore, + land: RefCell>>, + } + + impl<'a> SubmitsDuring<'a> { + fn new(store: &'a SqliteStore, land: impl FnOnce() + 'a) -> Self { + Self { + store, + land: RefCell::new(Some(Box::new(land))), + } + } + + fn landed(&self) -> bool { + self.land.borrow().is_none() + } + } + + impl Ledger for SubmitsDuring<'_> { + fn transact( + &self, + command: &Command, + decide: &mut Decide<'_>, + ) -> Result { + Ledger::transact(self.store, command, decide) + } + + fn claim( + &self, + command: &Command, + decide: &mut DecideClaim<'_>, + ) -> Result { + Ledger::claim(self.store, command, decide) + } + + fn renew_lease( + &self, + project: &ProjectId, + claim: &ClaimId, + owner: &ClaimOwner, + at: &str, + ) -> Result<(), StoreError> { + Ledger::renew_lease(self.store, project, claim, owner, at) + } + + fn complete( + &self, + command: &Command, + owner: &ClaimOwner, + decide: &mut Decide<'_>, + ) -> Result { + Ledger::complete(self.store, command, owner, decide) + } + + fn reconcile( + &self, + command: &Command, + claim: &ClaimId, + authority: ReconcileAuthority, + decide: &mut DecideReconcile<'_>, + ) -> Result { + Ledger::reconcile(self.store, command, claim, authority, decide) + } + + fn open_claims(&self, project: &ProjectId) -> Result, StoreError> { + Ledger::open_claims(self.store, project) + } + + fn stream( + &self, + project: &ProjectId, + stream: &StreamName, + from_version: u64, + page: PageRequest, + ) -> Result, StoreError> { + Ledger::stream(self.store, project, stream, from_version, page) + } + + fn history( + &self, + project: &ProjectId, + range: RangeInclusive, + filter: &HistoryFilter, + page: PageRequest, + ) -> Result, StoreError> { + Ledger::history(self.store, project, range, filter, page) + } + + fn head(&self, project: &ProjectId) -> Result, StoreError> { + Ledger::head(self.store, project) + } + + fn verify( + &self, + project: &ProjectId, + anchor: Option<&Anchor>, + ) -> Result { + Ledger::verify(self.store, project, anchor) + } + } + + impl Views for SubmitsDuring<'_> { + fn get( + &self, + project: &ProjectId, + view: &str, + key: &DocKey, + ) -> Result, StoreError> { + Views::get(self.store, project, view, key) + } + + fn get_many( + &self, + project: &ProjectId, + view: &str, + keys: &[DocKey], + ) -> Result>, StoreError> { + Views::get_many(self.store, project, view, keys) + } + + fn find( + &self, + project: &ProjectId, + view: &str, + query: &IndexQuery, + ) -> Result, StoreError> { + let read = Views::find(self.store, project, view, query); + if view == DRAFT_VIEW { + let land = self.land.borrow_mut().take(); + if let Some(land) = land { + land(); + } + } + read + } + } + + impl Payloads for SubmitsDuring<'_> { + fn open(&self, hash: &Hash) -> Result, StoreError> { + Payloads::open(self.store, hash) + } + + fn status(&self, hash: &Hash) -> Result { + Payloads::status(self.store, hash) + } + } + + #[test] + fn a_plan_approved_while_another_phase_is_active_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + order_q(&store, R2); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R3, T5)); + activate_phase_2(&store, R4); + let refusal = refused_with(&store, x1, &p0(), "phase-not-active"); + assert_eq!(refusal["details"], json!({"phase": 2})); + } + + /// P3: P0 with a project file setting + /// `workflow.test_command = "cargo nextest run"`. + fn p3() -> EffectivePolicy { + let file = crate::settings::file( + Path::new("/r/baley.toml"), + b"[workflow]\ntest_command = \"cargo nextest run\"\n".to_vec(), + ); + effective_policy( + Schema::standard(), + Some(Host::ClaudeCode), + None, + Some(&file), + ) + .expect("the test command is read") + } + + /// The owner's command for an approval under `request_id` at `at`, as + /// the terminal runs it with no session caller. + fn owner_command(request_id: &str, at: &str) -> Command { + let mut command = command("plan.approve", request_id, 10, at); + command.caller = None; + command + } + + /// Records `judged` as `Ada Owner` under `request_id` at `at`. Gives the + /// answer. + fn recorded(store: &SqliteStore, judged: &Judged, request_id: &str, at: &str) -> Value { + let command = owner_command(request_id, at); + crate::scope::submit::answer(record(store, &command, Some(judged), "Ada Owner"), store) + } + + /// Approves `digest` through both steps under `policy`. Gives the answer. + pub(crate) fn approved( + store: &SqliteStore, + digest: Hash, + policy: &EffectivePolicy, + request_id: &str, + at: &str, + ) -> Value { + match judge(store, &project(), digest, policy) { + Ok(judged) => recorded(store, &judged, request_id, at), + Err(refusal) => refusal, + } + } + + /// Every `plan.approved` in the store, oldest first. + fn approvals(store: &SqliteStore) -> Vec { + history(store) + .into_iter() + .filter(|event| event.type_name == "plan.approved") + .collect() + } + + #[test] + fn a_plan_number_reused_or_a_map_left_out_of_its_approval_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let submitted = plan_submitted(&store, &pl1(), O, None, R2, T5); + let x1 = digest_of(&submitted); + let first = approved(&store, x1, &p3(), R3, T6); + assert_eq!(first["status"], "ok", "{first}"); + assert_eq!(first["plan"], 1); + let x3 = digest_of(&plan_submitted(&store, &pl3(), O, None, R4, T7)); + let second = approved(&store, x3, &p3(), R5, T8); + assert_eq!(second["status"], "ok", "{second}"); + + let events = history(&store); + let draft = events + .iter() + .find(|event| { + event.type_name == "scope.submitted" && event.payload["digest"] == x1.to_hex() + }) + .unwrap(); + let approvals = approvals(&store); + assert_eq!(approvals.len(), 2); + let event = &approvals[0]; + assert_eq!(event.stream, "phase/1"); + assert_eq!(event.actor, Actor::Owner); + assert_eq!(event.payload["plan"], 1); + assert_eq!(event.payload["digest"], x1.to_hex()); + assert_eq!(event.payload["evidence_map"], json!([e1(), e2()])); + assert_eq!(event.payload["body"], draft.payload["body"]); + assert_eq!(event.payload["question_set"], submitted["set"]); + assert_eq!(event.payload["suite"], "cargo nextest run"); + assert_eq!(event.payload["owner"], "Ada Owner"); + assert_eq!(event.payload["stories"], json!([1])); + assert_eq!(event.payload["size"], 1); + assert_eq!(approvals[1].payload["plan"], 2); + assert_eq!(approvals[1].payload["digest"], x3.to_hex()); + + let phase_plan = store + .get(&project(), PHASE_PLAN_VIEW, &phase_plan_key(1)) + .unwrap() + .unwrap(); + assert_eq!(phase_plan.body["size"], 2); + assert_eq!(phase_plan.body["highest"], 2); + } + + #[test] + fn a_missing_test_command_refusing_approval_or_inventing_a_suite_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R2, T5)); + let answer = approved(&store, x1, &p0(), R3, T6); + assert_eq!(answer["status"], "ok", "{answer}"); + assert_eq!(answer["suite"], Value::Null); + assert!( + answer["notice"] + .as_str() + .is_some_and(|notice| notice.contains("workflow.test_command")), + "{answer}" + ); + let approvals = approvals(&store); + assert_eq!(approvals.len(), 1); + assert_eq!(approvals[0].payload["suite"], Value::Null); + } + + #[test] + fn an_approval_landing_twice_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R2, T5)); + let one = judge(&store, &project(), x1, &p0()).expect("the first is judged"); + let two = judge(&store, &project(), x1, &p0()).expect("the second is judged"); + assert_eq!(recorded(&store, &one, R3, T6)["status"], "ok"); + let busy = recorded(&store, &two, R4, T7); + assert_eq!(busy["status"], "failed", "{busy}"); + assert_eq!(busy["code"], "ledger-busy", "{busy}"); + assert_eq!(approvals(&store).len(), 1); + } + + #[test] + fn an_approval_landing_beside_a_newly_active_phase_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + order_q(&store, R2); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R3, T5)); + let judged = judge(&store, &project(), x1, &p0()).expect("PL1 is judged"); + activate_phase_2(&store, R4); + let busy = recorded(&store, &judged, R5, T6); + assert_eq!(busy["status"], "failed", "{busy}"); + assert_eq!(busy["code"], "ledger-busy", "{busy}"); + assert!( + approvals(&store) + .iter() + .all(|event| event.payload["digest"] != x1.to_hex()) + ); + } + + #[test] + fn a_plan_approved_on_an_unmade_or_rejected_decision_is_caught() { + use crate::mcp::questions::tests::{REVISION, postgres, relayed}; + + let (_dir, store) = store_c(); + order_o(&store, R1); + let submitted = plan_submitted(&store, &pl2(), O, None, R2, T5); + let x2 = digest_of(&submitted); + let s2 = submitted["set"].as_str().unwrap().to_owned(); + + refused_with(&store, Hash([0x11; 32]), &p0(), "unknown-draft"); + let open = refused_with(&store, x2, &p0(), "question-open"); + assert_eq!(open["details"], json!({"questions": ["q1"]})); + + let closed = relayed(&store, &s2, &postgres(), R3, T6, REVISION); + assert_eq!(closed["revision"]["work_order"], REVISION, "{closed}"); + let rejected = refused_with(&store, x2, &p0(), "answer-not-applied"); + assert_eq!(rejected["details"], json!({"questions": ["q1"]})); + + digest_of(&plan_submitted(&store, &pl1(), REVISION, None, R4, T7)); + refused_with(&store, x2, &p0(), "stale-draft"); + } +} diff --git a/crates/baley/src/planning/command.rs b/crates/baley/src/planning/command.rs new file mode 100644 index 00000000..71d4fc2a --- /dev/null +++ b/crates/baley/src/planning/command.rs @@ -0,0 +1,422 @@ +//! `baley plan approve `: the owner approves a plan draft by its +//! digest at the terminal, the only way a plan is approved (design 0005 +//! section 5 `plan approve`, D-16, ADR 0044). `baley plan show `: +//! the owner reads a phase's approved plans with their evidence maps and +//! readiness, through the read `plan-read` serves (D-17), recording nothing. +//! +//! Gathering finds the project, opens the ledger and reads the settings; the +//! approval's two steps are `planning::approve`'s, and what is printed is +//! judged by the pure render below, every text from the ledger printed +//! through `escaped`, so a recorded line break cannot forge a line. + +use std::process::ExitCode; + +use serde_json::Value; + +use crate::ledger::clock::SystemClock; +use crate::ledger::commands::new_request_id; +use crate::ledger::display::Render; +use crate::planning::approve; +use crate::planning::read::{self, PhasePlans}; +use crate::providers::identity; +use crate::scope::command::{ + admitted, approve_command, checkout, effective, emit, escaped, judge_digest, judge_number, + open as open_ledger, read_error, reading, +}; +use crate::scope::read::ReadError; +use crate::scope::submit; + +/// The setting a plan's suite is read from. +const SUITE_SETTING: &str = "workflow.test_command"; + +/// `baley plan`: the owner's commands on a phase's plans. +#[derive(clap::Args, Debug)] +pub struct PlanArgs { + /// The plan command to run. + #[command(subcommand)] + pub command: PlanCommand, +} + +/// One `baley plan` command. +#[derive(clap::Subcommand, Debug, PartialEq, Eq)] +pub enum PlanCommand { + /// Approve a plan draft by its digest as the owner, giving it the + /// phase's next plan number and, for a replacement, replacing the plan + /// it names. + Approve { + /// The draft's digest, as its submission's receipt gives it. + #[arg(value_name = "DIGEST")] + digest: String, + }, + /// Show a phase's approved plans in plan-number order, replaced ones + /// included, each with its evidence map and whether its items still + /// name their truths' current versions. + Show { + /// The phase's number, as the roadmap gives it. + #[arg(value_name = "PHASE")] + phase: String, + }, +} + +/// Runs one `baley plan` command and prints its result. +pub fn run(args: PlanArgs) -> ExitCode { + emit(match args.command { + PlanCommand::Approve { digest } => approve(&digest), + PlanCommand::Show { phase } => show(&phase), + }) +} + +/// `plan approve`: the digest is judged before anything is read; then the +/// checkout and the ledger; the settings read and judged into the effective +/// policy, recording nothing, since the first step needs the capacity and +/// the suite while a refusal must leave no policy step behind; the +/// approval's first step under that policy, whose refusal prints and records +/// nothing; checkout admission and the policy step, which reads the settings +/// again; the judgement held to the policy the step recorded, judged again +/// when its capacity or suite differs from the first read's, so the +/// approval never names one read's version over the other read's judgement +/// (a refusal there leaves only the policy step behind); the owner over the +/// policy the step recorded, falling back to git's `user.name`; the owner's +/// command; the second step; and the answer printed. +fn approve(digest: &str) -> Result { + let digest = judge_digest(digest)?; + let checkout = checkout()?; + let store = open_ledger(&checkout)?; + let project = &checkout.project; + let policy = effective(&checkout, None)?; + let judged = approve::judge(&store, project, digest, &policy) + .map_err(|answer| approval_render(&answer))?; + let (policy, version) = admitted(&store, &checkout)?; + let judged = approve::rejudged(&store, project, judged, &policy) + .map_err(|answer| approval_render(&answer))?; + + let owner = identity::owner(identity::owner_name(&policy), &mut crate::process::System) + .map_err(Render::refusal)?; + let command = approve_command( + project, + version, + digest, + new_request_id(), + &SystemClock::now(), + ) + .map_err(|e| Render::refusal(e.to_string()))?; + let recorded = approve::record(&store, &command, Some(&judged), &owner); + Ok(approval_render(&submit::answer(recorded, &store))) +} + +/// `plan show`: the phase number is judged before anything is read; then +/// the phase's approved plans are read, recording nothing (ADR 0044). +fn show(phase: &str) -> Result { + let phase = judge_number(phase)?; + reading(|store, project| show_render(read::read(store, project, phase))) +} + +/// What `baley plan show` prints for a phase's plans read: each plan as +/// `plan at : `, the state `replaced by ` for +/// a replaced one, then `ready` or `not ready:` and the items bound to a +/// version that is not current; then its stories, its size and its suite or +/// `suite: none`; then one line per item as `item : story , truth +/// version , `, with `level ` for a check. A phase with +/// no approved plan prints one line saying so. A refusal prints `: +/// `, exit 2, and a failure exit 1. Every text from the ledger is +/// printed through `escaped`. +pub(crate) fn show_render(read: Result) -> Render { + let plans = match read { + Ok(plans) => plans, + Err(error) => return read_error(error), + }; + let text = |value: &Value| escaped(value.as_str().unwrap_or_default()); + let mut lines = Vec::new(); + if plans.plans.is_empty() { + lines.push(format!("phase {} has no approved plan", plans.phase)); + } + for plan in &plans.plans { + let state = match &plan.replaced_by { + Some(by) => format!("{} by {}", escaped(&plan.state), escaped(by)), + None => escaped(&plan.state), + }; + let readiness = if plan.readiness.ready { + "ready".to_owned() + } else { + let named: Vec = plan + .readiness + .not_ready + .iter() + .map(|id| escaped(id)) + .collect(); + format!("not ready: {}", named.join(", ")) + }; + lines.push(format!( + "plan {} at {}: {state}, {readiness}", + plan.plan, + escaped(&plan.digest) + )); + let stories: Vec = plan.stories.iter().map(u32::to_string).collect(); + lines.push(format!("stories: {}", stories.join(", "))); + lines.push(format!("size: {} tasks", plan.size)); + lines.push(match &plan.suite { + Some(suite) => format!("suite: {}", escaped(suite)), + None => "suite: none".to_owned(), + }); + for item in &plan.items { + let mut line = format!( + "item {}: story {}, truth {} version {}, {}", + text(&item["id"]), + item["story"], + text(&item["truth"]), + item["truth_version"], + text(&item["kind"]) + ); + if item["kind"] == "check" { + line = format!("{line}, level {}", text(&item["spec"]["level"])); + } + lines.push(line); + } + } + Render { + lines, + code: 0, + error: false, + } +} + +/// What a plan approval's answer prints: an `ok` receipt as `approved plan +/// of phase

as at `, then the digest, the stories, the +/// size, the suite or a line naming `workflow.test_command` when none is +/// set, and for a replacement the plan it replaced, exit 0; a refusal as +/// `: ` with what its details name, exit 2; a failure the +/// same way, exit 1. Every text from the ledger is printed through +/// `escaped`. +pub(crate) fn approval_render(answer: &Value) -> Render { + let text = |value: &Value| escaped(value.as_str().unwrap_or_default()); + let numbers = |value: &Value| { + value + .as_array() + .map(|items| { + items + .iter() + .map(Value::to_string) + .collect::>() + .join(", ") + }) + .unwrap_or_default() + }; + if answer["status"] == "ok" { + let mut lines = vec![ + format!( + "approved plan {} of phase {} as {} at {}", + answer["plan"], + answer["phase"], + text(&answer["owner"]), + text(&answer["at"]) + ), + format!("digest: {}", text(&answer["digest"])), + format!("stories: {}", numbers(&answer["stories"])), + format!("size: {} tasks", answer["size"]), + ]; + lines.push(match answer["suite"].as_str() { + Some(suite) => format!("suite: {}", escaped(suite)), + None => format!( + "suite: none, since {SUITE_SETTING} is not set; the plan cannot be admitted to execution until it is" + ), + }); + let replaces = &answer["replaces"]; + if replaces.is_object() { + lines.push(format!( + "replaces plan {} approved at {}", + replaces["plan"], + text(&replaces["digest"]) + )); + } + return Render { + lines, + code: 0, + error: false, + }; + } + let mut line = format!("{}: {}", text(&answer["code"]), text(&answer["reason"])); + let details = &answer["details"]; + if let Some(questions) = details["questions"].as_array() { + let named: Vec = questions.iter().map(text).collect(); + line = format!("{line}: {}", named.join(", ")); + } else if let Some(path) = details["path"].as_str() { + line = format!("{line}: {}", escaped(path)); + } else if let (Some(owner), Some(at)) = (details["owner"].as_str(), details["at"].as_str()) { + line = format!("{line}: approved by {} at {}", escaped(owner), escaped(at)); + } else if details.is_object() { + // Any other refusal's details, such as a phase, a plan, stories or + // a size, printed whole. + line = format!("{line}: {}", escaped(&details.to_string())); + } + match answer["status"].as_str() { + Some("refused") => Render::refusal(line), + _ => Render { + lines: vec![line], + code: 1, + error: true, + }, + } +} + +#[cfg(test)] +mod tests { + //! Renders and parses are pure; expected lines are written out from + //! design 0005 `plan approve`, D-14 and D-16, never from running this + //! code. + + use clap::Parser; + use serde_json::json; + + use super::*; + + const X: &str = "5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c"; + const OLD: &str = "7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d"; + const AT: &str = "2026-10-31T09:00:00Z"; + + /// An `ok` receipt for plan 3 of phase 1 serving `[1]` with size 1, as + /// `owner`, with `suite` and replacing plan 1. + fn receipt(owner: &str, suite: Value) -> Value { + json!({"status": "ok", "kind": "plan", "digest": X, "phase": 1, "plan": 3, + "stories": [1], "size": 1, "suite": suite, "set": "s", "owner": owner, "at": AT, + "replaces": {"plan": 1, "digest": OLD}}) + } + + #[test] + fn a_plan_approval_printed_without_its_number_suite_line_or_replacement_is_caught() { + let approved = approval_render(&receipt("Ada Owner", json!("cargo nextest run"))); + assert_eq!(approved.code, 0); + assert!(!approved.error); + assert_eq!( + approved.lines, + [ + format!("approved plan 3 of phase 1 as Ada Owner at {AT}"), + format!("digest: {X}"), + "stories: 1".to_owned(), + "size: 1 tasks".to_owned(), + "suite: cargo nextest run".to_owned(), + format!("replaces plan 1 approved at {OLD}"), + ] + ); + + let unset = approval_render(&receipt("Ada Owner", Value::Null)); + assert_eq!(unset.code, 0); + assert!( + unset + .lines + .iter() + .any(|line| line.starts_with("suite: none") + && line.contains("workflow.test_command")), + "{:?}", + unset.lines + ); + + let stale = approval_render(&json!({"status": "refused", "code": "stale-draft", + "reason": "a newer plan draft was submitted", "slot": "digest", + "details": {"path": "goal"}})); + assert_eq!(stale.code, 2); + assert!(stale.error); + assert_eq!( + stale.lines, + ["stale-draft: a newer plan draft was submitted: goal"] + ); + + let forged = approval_render(&receipt("Ada\nbaley: approved plan 9", json!("cargo test"))); + assert_eq!(forged.lines.len(), 6, "{:?}", forged.lines); + assert_eq!( + forged.lines[0], + format!("approved plan 3 of phase 1 as Ada\\nbaley: approved plan 9 at {AT}") + ); + } + + #[test] + fn a_plan_shown_without_its_levels_versions_or_readiness_is_caught() { + use crate::planning::fixtures::{e1, e2}; + use crate::planning::read::{ApprovedPlan, Readiness}; + + const Y: &str = "6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d"; + let plan = |number: u32, digest: &str, suite: Option<&str>| ApprovedPlan { + plan: number, + digest: digest.into(), + stories: vec![1], + size: 1, + suite: suite.map(str::to_owned), + set: "s".into(), + owner: "Ada Owner".into(), + at: AT.into(), + state: "approved".into(), + replaced_by: None, + readiness: Readiness { + ready: true, + not_ready: Vec::new(), + }, + items: vec![e1(), e2()], + }; + let mut one = plan(1, X, None); + one.state = "replaced".into(); + one.replaced_by = Some(Y.into()); + let mut two = plan(2, OLD, Some("cargo test\nplan 9 at x: approved, ready")); + two.readiness = Readiness { + ready: false, + not_ready: vec!["e1".into()], + }; + let shown = show_render(Ok(PhasePlans { + phase: 1, + plans: vec![one, two], + })); + assert_eq!(shown.code, 0); + assert!(!shown.error); + assert_eq!( + shown.lines[..6], + [ + format!("plan 1 at {X}: replaced by {Y}, ready"), + "stories: 1".to_owned(), + "size: 1 tasks".to_owned(), + "suite: none".to_owned(), + "item e1: story 1, truth t1 version 1, check, level unit".to_owned(), + "item e2: story 1, truth t2 version 1, check, level integration".to_owned(), + ] + ); + assert_eq!( + shown.lines[6], + format!("plan 2 at {OLD}: approved, not ready: e1") + ); + assert_eq!( + shown.lines[9], + "suite: cargo test\\nplan 9 at x: approved, ready" + ); + assert_eq!(shown.lines.len(), 12, "{:?}", shown.lines); + } + + /// The `baley plan` part of the command line, over the library's own + /// arguments. + #[derive(Parser)] + struct Line { + #[command(subcommand)] + top: Top, + } + + #[derive(clap::Subcommand)] + enum Top { + Plan(PlanArgs), + } + + #[test] + fn a_plan_approve_command_parsed_otherwise_is_caught() { + let Top::Plan(args) = Line::try_parse_from(["baley", "plan", "approve", X]) + .expect("parsed") + .top; + assert_eq!(args.command, PlanCommand::Approve { digest: X.into() }); + + let missing = Line::try_parse_from(["baley", "plan", "approve"]) + .err() + .expect("a usage error"); + assert_eq!( + missing.kind(), + clap::error::ErrorKind::MissingRequiredArgument + ); + let extra = Line::try_parse_from(["baley", "plan", "approve", "a", "b"]) + .err() + .expect("a usage error"); + assert_eq!(extra.kind(), clap::error::ErrorKind::UnknownArgument); + } +} diff --git a/crates/baley/src/planning/facts.rs b/crates/baley/src/planning/facts.rs new file mode 100644 index 00000000..a1a4bfa7 --- /dev/null +++ b/crates/baley/src/planning/facts.rs @@ -0,0 +1,197 @@ +//! The facts a plan is judged on, read from the views (design 0005 sections +//! 5 and 6, PLN-R9, PLN-R13, D-02, D-13, D-16): the phase's committed +//! stories in commitment order, each with its current truths; the evidence +//! items of the phase's plans in force; the phase's size; the capacity the +//! caller gives; and the active phases. `plan submit`'s check and the +//! approval's first step both gather them here, so an approval judges the +//! plan again on the same reading the submit judged it on. +//! +//! Nothing here judges or records anything. Every document a fact came from +//! is kept at the sequence that produced it, so a recording can confirm +//! none moved. + +use std::num::NonZeroU32; + +use baley_core::plan::{ + ApprovedItem, CommittedStory, CurrentTruth, EVIDENCE_MAP_VIEW, IN_FORCE, PHASE_PLAN_VIEW, + PlanFacts, approved_items, evidence_map_key, phase_plan_key, +}; +use baley_core::policy::{EffectivePolicy, Value as Setting}; +use baley_store::{Absence, DocKey, ObservedDocument, ProjectId, StoreError, Views}; +use serde_json::Value; + +use crate::mcp::capture::{PLACE_LEDGER, failed, store_failed}; +use crate::mcp::prepare::LEDGER_UNAVAILABLE; +use crate::planning::phase_plan::read_readiness; +use crate::refine::submit::current_truths; +use crate::scope::submit::NOT_RECORDED_BUSY; + +/// The setting the capacity is read from. +const CAPACITY_SETTING: &str = "planning.phase_capacity"; + +/// A phase's facts with the documents they came from, read outside any +/// transaction. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PhaseFacts { + /// What the plan judge takes. + pub facts: PlanFacts, + /// The active phases in number order, which may include this one. + pub active: Vec, + /// The phase's `phase_plan` document, or none before anything was + /// projected for it. + pub phase_plan: Option, + /// The `roadmap` document, each committed story's `truths` document, + /// the `phase_plan` document and each plan in force's `evidence_map` + /// document, each at the sequence that produced it. + documents: Vec, + /// What a recording relies on being absent. + absences: Vec, +} + +impl PhaseFacts { + /// The documents the facts were read from. + pub fn documents(&self) -> &[ObservedDocument] { + &self.documents + } + + /// What a recording relies on being absent: with no phase active, + /// `phase_plan`'s status index still holding none, since an empty read + /// leaves no document to observe (D-02). + pub fn absences(&self) -> &[Absence] { + &self.absences + } +} + +/// The capacity `policy` sets, or none. +pub fn capacity(policy: &EffectivePolicy) -> Option { + match policy + .settings + .get(CAPACITY_SETTING) + .and_then(|effective| effective.value.as_ref()) + { + Some(Setting::Capacity(capacity)) => Some(*capacity), + _ => None, + } +} + +/// Reads phase `phase` of `project`'s facts with `capacity`: the committed +/// stories and the active phases through `read_readiness`, each committed +/// story's current truths from the `truths` view, and the size and the +/// approved items of the plans in force, in plan-number order, from +/// `phase_plan` and each plan's `evidence_map` document. A phase the +/// roadmap does not hold, or a withdrawn one, commits no story. A fault is +/// the `failed` answer. +pub fn read( + store: &S, + project: &ProjectId, + phase: u32, + capacity: Option, +) -> Result { + let readiness = read_readiness(store, project, phase, &[])?; + let mut documents = readiness.documents().to_vec(); + let mut stories = Vec::with_capacity(readiness.committed().len()); + for story in readiness.committed() { + let current = current_truths(store, project, *story)?; + documents.push(current.document); + let truths = current + .truths + .into_iter() + .map(|(truth, version)| CurrentTruth { + id: truth.id, + version, + trigger: truth.trigger, + observer: truth.observer, + outcome: truth.outcome, + human_verify: truth.human_verify, + }) + .collect(); + stories.push(CommittedStory { id: *story, truths }); + } + let key = phase_plan_key(phase); + let document = store.get(project, PHASE_PLAN_VIEW, &key).map_err(busy)?; + documents.push(observed( + PHASE_PLAN_VIEW, + key, + document.as_ref().map(|document| document.produced_seq), + )); + let phase_plan = document.map(|document| document.body); + let (size, approved) = match &phase_plan { + None => (0, Vec::new()), + Some(body) => { + let size = body + .get("size") + .and_then(Value::as_u64) + .and_then(|size| u32::try_from(size).ok()) + .ok_or_else(|| unreadable(PHASE_PLAN_VIEW))?; + (size, in_force(store, project, phase, body, &mut documents)?) + } + }; + Ok(PhaseFacts { + facts: PlanFacts { + stories, + approved, + size, + capacity, + }, + active: readiness.readiness().active.to_vec(), + phase_plan, + absences: readiness.absences(), + documents, + }) +} + +/// The approved items of the plans in force that `phase_plan` lists, in +/// plan-number order, each read through the judge's reading of its plan's +/// `evidence_map` document, which is added to `documents`. +fn in_force( + store: &S, + project: &ProjectId, + phase: u32, + phase_plan: &Value, + documents: &mut Vec, +) -> Result, Value> { + let plans = phase_plan + .get("plans") + .and_then(Value::as_array) + .ok_or_else(|| unreadable(PHASE_PLAN_VIEW))?; + let mut items = Vec::new(); + // The view keeps a phase's plans in number order. + for held in plans { + if held.get("state").and_then(Value::as_str) != Some(IN_FORCE) { + continue; + } + let plan = held + .get("plan") + .and_then(Value::as_u64) + .and_then(|plan| u32::try_from(plan).ok()) + .ok_or_else(|| unreadable(PHASE_PLAN_VIEW))?; + let key = evidence_map_key(phase, plan); + let map = store + .get(project, EVIDENCE_MAP_VIEW, &key) + .map_err(busy)? + .ok_or_else(|| unreadable(EVIDENCE_MAP_VIEW))?; + documents.push(observed(EVIDENCE_MAP_VIEW, key, Some(map.produced_seq))); + items.extend(approved_items(&map.body).ok_or_else(|| unreadable(EVIDENCE_MAP_VIEW))?); + } + Ok(items) +} + +fn observed(view: &str, key: DocKey, produced_seq: Option) -> ObservedDocument { + ObservedDocument { + view: view.into(), + key, + produced_seq, + } +} + +fn busy(error: StoreError) -> Value { + store_failed(&error, NOT_RECORDED_BUSY) +} + +fn unreadable(view: &str) -> Value { + failed( + LEDGER_UNAVAILABLE, + format!("the {view} view document cannot be read, so nothing was recorded"), + PLACE_LEDGER, + ) +} diff --git a/crates/baley/src/planning/inputs.rs b/crates/baley/src/planning/inputs.rs new file mode 100644 index 00000000..3bbc7b37 --- /dev/null +++ b/crates/baley/src/planning/inputs.rs @@ -0,0 +1,614 @@ +//! What a planner order binds at issue (design 0005 section 4 Planner row, +//! D-12, D-15): the phase's number, goal and detail; the stories it commits, +//! in the order given, each with its current truths; the approved +//! description; the capacity and the phase's size when a capacity is set; +//! and the evidence items of the phase's plans in force. A revision order +//! also binds the draft it revises and its question set with every answer +//! and deferral. Each input is canonical JSON a `record` payload holds. +//! +//! Nothing here records anything. The selection is the caller's, never read +//! from the phase, so an approval binds the stories it is committing. A +//! retry carries its parent's inputs as they were. + +use std::num::NonZeroU32; + +use baley_core::plan::{ + EVIDENCE_MAP_VIEW, IN_FORCE, PHASE_PLAN_VIEW, PLAN_KIND, approved_items, evidence_map_key, + phase_plan_key, +}; +use baley_core::policy::{EffectivePolicy, Value as Setting}; +use baley_core::questions::{QUESTIONS_VIEW, SetFacts, questions_key}; +use baley_core::scope::{ + DRAFT_VIEW, PHASE_DETAIL_VIEW, PHASE_VIEW, ROADMAP_VIEW, draft_key, phase_key, roadmap_key, +}; +use baley_core::truth::{TRUTHS_VIEW, truths_key}; +use baley_store::{Hash, ObservedDocument, Payloads, ProjectId, StoreError, Views}; +use serde_json::{Map, Value, json}; + +use crate::envelope::LEDGER_BUSY; +use crate::mcp::capture::{PLACE_LEDGER, TEXT_PURGED, failed, store_failed}; +use crate::mcp::prepare::LEDGER_UNAVAILABLE; +use crate::questions::read::{SetRead, read as read_set}; +use crate::refine::inputs::{bytes, questions_body}; +use crate::scope::read::{self, Detail, PreviewError}; +use crate::scope::submit::{NOT_RECORDED_BUSY, scope_unread}; + +/// The input holding the phase's number, goal and detail. +pub const PHASE_INPUT: &str = "phase"; +/// The input holding the committed stories in order, each with its current +/// truths. +pub const STORIES_INPUT: &str = "stories"; +/// The input holding the approved description. +pub const DESCRIPTION_INPUT: &str = "description"; +/// The input holding the capacity and the phase's size, present only when a +/// capacity is set. +pub const CAPACITY_INPUT: &str = "capacity"; +/// The input holding the evidence items of the phase's plans in force. +pub const APPROVED_ITEMS_INPUT: &str = "approved_items"; +/// The input holding a revision order's draft plan. +pub const DRAFT_INPUT: &str = "draft"; +/// The input holding a revision order's question set with every answer and +/// deferral. +pub const QUESTIONS_INPUT: &str = "questions"; + +/// The setting the capacity is read from. +const CAPACITY_SETTING: &str = "planning.phase_capacity"; + +/// The members of a truth a planner order carries, besides `human_verify`, +/// which it carries only when set. +const TRUTH_MEMBERS: [&str; 8] = [ + "id", "version", "form", "trigger", "observer", "verb", "outcome", "kind", +]; + +/// The draft a revision order revises and its question set. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Revision<'a> { + /// The draft's digest. + pub draft: Hash, + /// The id of the draft's question set. + pub set: &'a str, +} + +/// What a planner order binds, read outside any transaction. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlannerInputs { + /// Each input's name and canonical JSON bytes, in order: `phase`, + /// `stories`, `description`, `capacity` when one is set, + /// `approved_items`, then for a revision `draft` and `questions`. + pub inputs: Vec<(&'static str, Vec)>, + /// The documents the inputs were read from, each at the sequence that + /// produced it and read before its content, so the issue can confirm + /// none moved: `roadmap`, `phase`, the phase's `phase_detail`, each + /// story's `truths`, `phase_plan`, and for a revision the draft's + /// `draft` and the set's `questions`. + pub documents: Vec, +} + +/// Reads what a planner order of phase `phase` in `project` binds for the +/// selection `stories`, in that order, under `policy`, and for a revision +/// the draft and set `revision` names. A phase detail this project purged is +/// `text-purged`, as the approval of an edit keeping it answers. A fault is +/// the `failed` answer to give. +pub fn read( + store: &S, + project: &ProjectId, + phase: u32, + stories: &[u32], + policy: &EffectivePolicy, + revision: Option>, +) -> Result { + read_with(store, project, phase, stories, policy, revision, None) +} + +/// Reads what the revision order a set's close issues binds, as [`read`] +/// reads a revision, but with its `questions` input built from `closed`, +/// the set's facts with the closing call's own answers and deferrals, which +/// are not yet recorded (D-15). The closing call's recording observes the +/// set's document, so it is not among the documents read here. +pub fn read_closing( + store: &S, + project: &ProjectId, + phase: u32, + stories: &[u32], + policy: &EffectivePolicy, + revision: Revision<'_>, + closed: &SetFacts, +) -> Result { + read_with( + store, + project, + phase, + stories, + policy, + Some(revision), + Some(closed), + ) +} + +/// [`read`], with a revision's set facts taken from `closed` when given. +fn read_with( + store: &S, + project: &ProjectId, + phase: u32, + stories: &[u32], + policy: &EffectivePolicy, + revision: Option>, + closed: Option<&SetFacts>, +) -> Result { + // Every sequence is read before the content it covers, so a document + // that moves before its content is read shows as moved at the issue. + let roadmap_seq = produced(store, project, ROADMAP_VIEW, roadmap_key())?; + let phase_seq = produced(store, project, PHASE_VIEW, phase_key(phase))?; + let detail = + read::detail_document(store, project, phase).map_err(|error| scope_unread(&error))?; + let mut documents = vec![ + observed(ROADMAP_VIEW, roadmap_key(), roadmap_seq), + observed(PHASE_VIEW, phase_key(phase), phase_seq), + ]; + if let Some((key, seq)) = detail { + documents.push(observed(PHASE_DETAIL_VIEW, key, Some(seq))); + } + let mut truths = Vec::with_capacity(stories.len()); + for story in stories { + let document = store + .get(project, TRUTHS_VIEW, &truths_key(*story)) + .map_err(busy)?; + documents.push(observed( + TRUTHS_VIEW, + truths_key(*story), + document.as_ref().map(|document| document.produced_seq), + )); + truths.push(document.map(|document| document.body)); + } + let phase_plan = store + .get(project, PHASE_PLAN_VIEW, &phase_plan_key(phase)) + .map_err(busy)?; + documents.push(observed( + PHASE_PLAN_VIEW, + phase_plan_key(phase), + phase_plan.as_ref().map(|document| document.produced_seq), + )); + let phase_plan = phase_plan.map(|document| document.body); + + let held = read::phase(store, project, phase).map_err(|error| scope_unread(&error))?; + let detail = match held.detail { + Detail::Text(text) => text, + Detail::Purged(_) => return Err(detail_purged(phase)), + }; + let accepted = read::roadmap(store, project).map_err(|error| scope_unread(&error))?; + let description = accepted + .description + .as_ref() + .ok_or_else(|| unreadable(ROADMAP_VIEW))?; + let mut committed = Vec::with_capacity(stories.len()); + for (story, truths) in stories.iter().zip(&truths) { + // The caller judged the selection on this roadmap, so a story it + // no longer holds means the roadmap moved since. + let entry = accepted + .stories + .iter() + .find(|entry| entry.id == *story) + .ok_or_else(moved)?; + committed.push(json!({ + "id": entry.id, + "sentence": entry.sentence, + "truths": current_truths(truths.as_ref())?, + })); + } + + let mut inputs = vec![ + ( + PHASE_INPUT, + encoded(&json!({"number": phase, "goal": held.goal, "detail": detail}))?, + ), + (STORIES_INPUT, encoded(&committed)?), + (DESCRIPTION_INPUT, encoded(description)?), + ]; + if let Some(capacity) = capacity(policy) { + let size = match &phase_plan { + Some(document) => document + .get("size") + .and_then(Value::as_u64) + .ok_or_else(|| unreadable(PHASE_PLAN_VIEW))?, + None => 0, + }; + inputs.push(( + CAPACITY_INPUT, + encoded(&json!({"capacity": capacity.get(), "size": size}))?, + )); + } + let items = in_force_items(store, project, phase, phase_plan.as_ref())?; + inputs.push((APPROVED_ITEMS_INPUT, encoded(&items)?)); + + if let Some(revision) = revision { + let (draft, draft_seq, set, set_seq) = revised(store, project, revision, closed)?; + inputs.push((DRAFT_INPUT, encoded(&draft)?)); + inputs.push((QUESTIONS_INPUT, encoded(&set)?)); + documents.push(observed( + DRAFT_VIEW, + draft_key(revision.draft), + Some(draft_seq), + )); + if let Some(set_seq) = set_seq { + documents.push(observed( + QUESTIONS_VIEW, + questions_key(revision.set), + Some(set_seq), + )); + } + } + Ok(PlannerInputs { inputs, documents }) +} + +/// The capacity `policy` sets, or none. +fn capacity(policy: &EffectivePolicy) -> Option { + match policy + .settings + .get(CAPACITY_SETTING) + .and_then(|effective| effective.value.as_ref()) + { + Some(Setting::Capacity(capacity)) => Some(*capacity), + _ => None, + } +} + +/// A story's current truths from its `truths` document, each with the +/// members a planner reads, or none before its first refinement. +fn current_truths(document: Option<&Value>) -> Result, Value> { + let Some(document) = document else { + return Ok(Vec::new()); + }; + let listed = document + .get("truths") + .and_then(Value::as_array) + .ok_or_else(|| unreadable(TRUTHS_VIEW))?; + listed + .iter() + .map(|truth| { + let mut carried = Map::new(); + for name in TRUTH_MEMBERS { + let value = truth.get(name).ok_or_else(|| unreadable(TRUTHS_VIEW))?; + carried.insert(name.into(), value.clone()); + } + match truth.get("human_verify") { + None | Some(Value::Null) => {} + Some(value) => { + carried.insert("human_verify".into(), value.clone()); + } + } + Ok(Value::Object(carried)) + }) + .collect() +} + +/// The evidence items of the plans in force that `phase_plan`, phase +/// `phase`'s document, lists, in plan-number order, each `{plan, item}`, +/// read through the judge's reading of each plan's `evidence_map` document. +fn in_force_items( + store: &S, + project: &ProjectId, + phase: u32, + phase_plan: Option<&Value>, +) -> Result, Value> { + let Some(document) = phase_plan else { + return Ok(Vec::new()); + }; + let plans = document + .get("plans") + .and_then(Value::as_array) + .ok_or_else(|| unreadable(PHASE_PLAN_VIEW))?; + let mut items = Vec::new(); + // The view keeps a phase's plans in number order. + for held in plans { + if held.get("state").and_then(Value::as_str) != Some(IN_FORCE) { + continue; + } + let plan = held + .get("plan") + .and_then(Value::as_u64) + .and_then(|plan| u32::try_from(plan).ok()) + .ok_or_else(|| unreadable(PHASE_PLAN_VIEW))?; + let map = store + .get(project, EVIDENCE_MAP_VIEW, &evidence_map_key(phase, plan)) + .map_err(busy)? + .ok_or_else(|| unreadable(EVIDENCE_MAP_VIEW))?; + let approved = approved_items(&map.body).ok_or_else(|| unreadable(EVIDENCE_MAP_VIEW))?; + items.extend( + approved + .into_iter() + .map(|item| json!({"plan": item.plan, "item": item.definition})), + ); + } + Ok(items) +} + +/// A revision's draft plan and its set's body, with the sequences that +/// produced the `draft` and `questions` documents, each read before its +/// content. With `closed` given, the set's body is built from it and the +/// set is not read, so no `questions` sequence comes back. +fn revised( + store: &S, + project: &ProjectId, + revision: Revision<'_>, + closed: Option<&SetFacts>, +) -> Result<(Value, u64, Value, Option), Value> { + let draft_seq = produced(store, project, DRAFT_VIEW, draft_key(revision.draft))? + .ok_or_else(|| unreadable(DRAFT_VIEW))?; + let draft = match read::preview(store, project, revision.draft) { + Ok(preview) if preview.kind == PLAN_KIND => preview.submission, + Ok(_) | Err(PreviewError::UnknownDraft | PreviewError::Unreadable(_)) => { + return Err(unreadable(DRAFT_VIEW)); + } + Err(PreviewError::Store(error)) => return Err(busy(error)), + }; + if let Some(closed) = closed { + return Ok((draft, draft_seq, questions_body(revision.set, closed), None)); + } + let held = match read_set(store, project, revision.set).map_err(busy)? { + SetRead::Held(held) => held, + SetRead::NotHeld | SetRead::Unreadable(_) => return Err(unreadable(QUESTIONS_VIEW)), + }; + let set = questions_body(revision.set, &held.facts); + Ok((draft, draft_seq, set, Some(held.produced_seq))) +} + +/// The sequence that produced the document `key` of `view`, or none. +fn produced( + store: &S, + project: &ProjectId, + view: &str, + key: baley_store::DocKey, +) -> Result, Value> { + Ok(store + .get(project, view, &key) + .map_err(busy)? + .map(|document| document.produced_seq)) +} + +fn observed(view: &str, key: baley_store::DocKey, produced_seq: Option) -> ObservedDocument { + ObservedDocument { + view: view.into(), + key, + produced_seq, + } +} + +fn encoded(value: &T) -> Result, Value> { + bytes(value).map_err(|error| scope_unread(&error)) +} + +fn busy(error: StoreError) -> Value { + store_failed(&error, NOT_RECORDED_BUSY) +} + +fn moved() -> Value { + failed( + LEDGER_BUSY, + "the project's scope moved while this call was prepared, so nothing was recorded. The same call can be sent again", + PLACE_LEDGER, + ) +} + +fn detail_purged(phase: u32) -> Value { + failed( + TEXT_PURGED, + format!( + "phase {phase}'s detail was purged from this project, so no planner order can carry it and nothing was recorded. An approved phase edit can give it a new detail" + ), + "detail", + ) +} + +fn unreadable(view: &str) -> Value { + failed( + LEDGER_UNAVAILABLE, + format!("the {view} view document cannot be read, so nothing was recorded"), + PLACE_LEDGER, + ) +} + +#[cfg(test)] +mod tests { + //! Stores are real SQLite stores in fresh temporary directories, with + //! times supplied; expected inputs are written out from design 0005, + //! D-12, D-15 and the plan's data store C, P0, P2, E1, E2 and PL2, never + //! from running this code. + + use baley_core::plan::PlanDraft; + use baley_core::plan::{CommittedStory, CurrentTruth, PLAN_REPLACED, PLAN_REPLACED_VERSION}; + use baley_core::plan::{PlanFacts, judge_plan, phase_stream, replaced_payload}; + use baley_core::questions::answered_payload; + use baley_core::questions::{QUESTION_ANSWERED, QUESTION_ANSWERED_VERSION, Subject}; + use baley_core::scope::submitted_payload; + use baley_core::scope::{PROJECT_STREAM, SCOPE_SUBMITTED, SCOPE_SUBMITTED_VERSION}; + use baley_store::{Decision, NewEvent, Observed, OutcomeKind, RetentionClass, StreamName}; + use baley_store_sqlite::SqliteStore; + + use super::*; + use crate::planning::fixtures::*; + use crate::scope::fixtures::*; + + fn parsed(read: &PlannerInputs, name: &str) -> Option { + read.inputs + .iter() + .find(|(input, _)| *input == name) + .map(|(_, bytes)| serde_json::from_slice(bytes).unwrap()) + } + + fn names(read: &PlannerInputs) -> Vec<&str> { + read.inputs.iter().map(|(name, _)| *name).collect() + } + + #[test] + fn a_planner_order_bound_to_the_phase_as_stored_instead_of_the_selection_is_caught() { + let (_dir, store) = store_c(); + let read = read(&store, &project(), 1, &[1, 4], &p0(), None).unwrap(); + + assert_eq!( + names(&read), + ["phase", "stories", "description", "approved_items"] + ); + assert_eq!( + parsed(&read, "phase"), + Some(json!({"number": 1, "goal": "Steps are recorded", + "detail": "The ledger and its views"})) + ); + let t1 = json!({"id": "t1", "version": 1, "form": "when", + "trigger": "the owner approves a draft by a stale digest", + "observer": "the owner", "verb": "is refused", + "outcome": "stale-draft naming the first differing part", "kind": "literal"}); + let t2 = json!({"id": "t2", "version": 1, "form": "for-any", + "trigger": "order the answers of a set are recorded in", + "observer": "a ledger reader", "verb": "gets", "outcome": "the same round", + "kind": "property"}); + assert_eq!( + parsed(&read, "stories"), + Some(json!([ + {"id": 1, "sentence": "Every step is recorded", "truths": [t1, t2.clone()]}, + {"id": 4, "sentence": "Plans are approved by digest", "truths": [t2]}])) + ); + assert_eq!( + parsed(&read, "description"), + Some(json!({"what": "A ledger for agent work", + "core_value": "Nothing moves on an unproven claim", + "constraints": ["One binary"]})) + ); + assert_eq!(parsed(&read, "capacity"), None); + + let read = super::read(&store, &project(), 1, &[1, 4], &p2(), None).unwrap(); + assert_eq!( + parsed(&read, "capacity"), + Some(json!({"capacity": 2, "size": 0})) + ); + } + + #[test] + fn an_approved_plans_items_left_out_of_a_planner_order_or_a_replaced_ones_kept_is_caught() { + let (_dir, store) = store_c(); + let x = Hash([0x5c; 32]); + let y = Hash([0x6d; 32]); + approve_by_hand(&store, R1, 1, 1, x, &[1], 1, &[e1()], Vec::new()); + let items = |store: &SqliteStore| { + let read = read(store, &project(), 1, &[1], &p0(), None).unwrap(); + parsed(&read, "approved_items").expect("the items are bound") + }; + assert_eq!(items(&store), json!([{"plan": 1, "item": e1()}])); + + let replaced = NewEvent { + stream: StreamName(phase_stream(1)), + type_name: PLAN_REPLACED.into(), + type_version: PLAN_REPLACED_VERSION, + git: None, + payload: replaced_payload(1, 1, x, y, "Ada Owner", T5), + attachments: Vec::new(), + }; + approve_by_hand(&store, R2, 1, 2, y, &[1], 1, &[e2()], vec![replaced]); + assert_eq!(items(&store), json!([{"plan": 2, "item": e2()}])); + } + + /// The facts PL2 is judged under: story 1 with T1 and T2 at version 1. + fn pl2_facts() -> PlanFacts { + let truth = |id: &str, trigger: &str, observer: &str, outcome: &str| CurrentTruth { + id: id.into(), + version: 1, + trigger: trigger.into(), + observer: observer.into(), + outcome: outcome.into(), + human_verify: None, + }; + PlanFacts { + stories: vec![CommittedStory { + id: 1, + truths: vec![ + truth( + "t1", + "the owner approves a draft by a stale digest", + "the owner", + "stale-draft naming the first differing part", + ), + truth( + "t2", + "order the answers of a set are recorded in", + "a ledger reader", + "the same round", + ), + ], + }], + approved: Vec::new(), + size: 0, + capacity: None, + } + } + + #[test] + fn a_revision_order_bound_without_its_draft_or_its_answers_is_caught() { + let (_dir, store) = store_c(); + let plan = judge_plan(&pl2(), &pl2_facts()).expect("PL2 is accepted"); + let draft = PlanDraft::new(&plan); + let mut set = String::new(); + store + .transact(&command("test.plan", R1, 8, T4), &mut |tx| { + let body = tx.put_payload(draft.body(), RetentionClass::Record)?; + tx.append(NewEvent { + stream: StreamName(PROJECT_STREAM.into()), + type_name: SCOPE_SUBMITTED.into(), + type_version: SCOPE_SUBMITTED_VERSION, + git: None, + payload: submitted_payload(draft.digest(), PLAN_KIND, draft.target(), &body), + attachments: vec![body], + })?; + let subject = Subject::Plan { + phase: 1, + plan_digest: draft.digest(), + }; + set = crate::questions::record::open(tx, plan.questions(), &subject, T4)?; + Ok(Decision { + kind: OutcomeKind::Done, + answer: json!({"status": "ok"}), + sensitive: false, + observed: Observed::default(), + git: None, + }) + }) + .unwrap(); + append( + &store, + R2, + T5, + vec![NewEvent { + stream: StreamName(phase_stream(1)), + type_name: QUESTION_ANSWERED.into(), + type_version: QUESTION_ANSWERED_VERSION, + git: None, + payload: answered_payload(&set, "q1", 1, "Postgres", false, "Ada Owner", T5), + attachments: Vec::new(), + }], + ); + + let revision = Revision { + draft: draft.digest(), + set: &set, + }; + let read = read(&store, &project(), 1, &[1], &p0(), Some(revision)).unwrap(); + assert_eq!( + names(&read), + [ + "phase", + "stories", + "description", + "approved_items", + "draft", + "questions" + ] + ); + let recorded: Value = serde_json::from_slice(draft.body()).unwrap(); + assert_eq!(parsed(&read, "draft"), Some(recorded)); + let questions = parsed(&read, "questions").expect("the set is bound"); + assert_eq!(questions["set"], set.as_str()); + assert_eq!( + questions["answers"], + json!([{"question": "q1", "answer": "Postgres", "accepted": false, "round": 1, + "owner": "Ada Owner", "at": T5}]) + ); + } +} diff --git a/crates/baley/src/planning/mod.rs b/crates/baley/src/planning/mod.rs new file mode 100644 index 00000000..8d4c0f09 --- /dev/null +++ b/crates/baley/src/planning/mod.rs @@ -0,0 +1,500 @@ +//! A phase's planning over the storage port (design 0005 sections 4 and 5, +//! D-01, D-08 to D-12, D-15): what a planner order binds at issue, read from +//! the views; the planner order itself, issued on its phase's stream with +//! one live per phase and handed to a session once an approval issued it; +//! and `phase plan`, which chooses between drafting a changed commitment, +//! issuing an order and handing one over; then `plan submit`, which checks a +//! planner's plan against its order and the phase, over facts read from the +//! views, and records it as the phase's one draft with its question set; +//! `plan replace`, recorded as a submit is and approved into a new number; +//! and the owner's approval of that draft, in two steps, at the terminal +//! through `baley plan approve`; and a phase's approved plans read back with +//! their evidence maps and readiness, for `plan-read` and `baley plan show`. + +/// The owner's approval of a plan draft: the first step and the recording. +pub mod approve; + +/// `baley plan approve`: the owner's approval of a plan draft at the +/// terminal. +pub mod command; + +/// The facts a plan is judged on, read from the views. +pub mod facts; + +/// What a planner order binds at issue, read outside any transaction. +pub mod inputs; + +/// The planner's work order: its preparation, its issue on `phase/`, the +/// pending lookup and refusal, and the hand-over of an approved order. +pub mod order; + +/// `phase plan`: the check run before admission and the run after it. +pub mod phase_plan; + +/// A phase's approved plans with their evidence maps, read back. +pub mod read; + +/// `plan replace`: the check of a replacement, recorded as a submit is. +pub mod replace; + +/// `plan submit`: the check run before admission and the recording after +/// it. +pub mod submit; + +#[cfg(test)] +pub(crate) mod fixtures { + //! The store, policies, catalog and plans the planning tests share, + //! written out from design 0005, the phase's decisions and phase 8's + //! check items, never produced by the code under test. + + use std::collections::BTreeSet; + use std::path::Path; + + use baley_core::plan::{ + CommittedStory, CurrentTruth, PLAN_APPROVED, PLAN_APPROVED_VERSION, PLAN_KIND, + PlanApproval, PlanDraft, PlanFacts, judge_plan, phase_stream, + }; + use baley_core::policy::{AcceptedNames, EffectivePolicy, Host, Schema, effective_policy}; + use baley_core::questions::answered_payload; + use baley_core::questions::{QUESTION_ANSWERED, QUESTION_ANSWERED_VERSION, Subject}; + use baley_core::scope::{ + ChangeKind, PROJECT_STREAM, PhaseFields, ROADMAP_STREAM, SCOPE_SUBMITTED, + SCOPE_SUBMITTED_VERSION, submitted_payload, + }; + use baley_core::truth::{STORY_REFINED, STORY_REFINED_VERSION}; + use baley_store::{ + Decision, Hash, NewEvent, Observed, OutcomeKind, RetentionClass, StreamName, canonical_json, + }; + use baley_store_sqlite::SqliteStore; + use serde_json::{Value, json}; + + use crate::planning::phase_plan::PHASE_PLAN_COMMAND; + use crate::refine::submit::tests::{t1, t2}; + use crate::scope::approve::{self, APPROVE_COMMAND, OrderRoute}; + use crate::scope::fixtures::*; + use crate::scope::submit::{PlanningContinuation, submit_phase_edit}; + + /// The request ids store C is built under, apart from every test's own. + const DECLARE: &str = "4d5e6f70-8192-4a3b-9c4d-5e6f70819203"; + const DECLARE_APPROVE: &str = "4d5e6f70-8192-4a3b-9c4d-5e6f70819204"; + const REFINED: &str = "4d5e6f70-8192-4a3b-9c4d-5e6f70819205"; + + /// The question set every hand-appended approval names. + pub(crate) const APPROVAL_SET: &str = "3c4d5e6f-7081-4a2b-8c3d-4e5f60718293"; + + /// `truth` at version 1, as a refinement carries it. + pub(crate) fn versioned(truth: Value) -> Value { + let mut truth = truth; + truth["version"] = json!(1); + truth + } + + /// A `story.refined` of `story` carrying `truths`, naming a made-up set. + pub(crate) fn refined(story: u32, set: &str, truths: Vec) -> NewEvent { + NewEvent { + stream: StreamName(ROADMAP_STREAM.into()), + type_name: STORY_REFINED.into(), + type_version: STORY_REFINED_VERSION, + git: None, + payload: json!({"story": story, "set": set, "submission": "5c".repeat(32), + "owner": "Ada Owner", "at": T2, "truths": truths}), + attachments: Vec::new(), + } + } + + /// Store C: S1 approved; story 4, active in the backlog, declared by an + /// approved `story-declare`; story 1 refined with T1 and T2, story 2 + /// with T1 and story 4 with T2, each at version 1. Story 3 holds no + /// truth. Phase 1 commits `[1]`, phase 2 `[2]` and depends on 1. + pub(crate) fn store_c() -> (tempfile::TempDir, SqliteStore) { + let (dir, store) = crate::refine::order::tests::approved(); + let story = json!({"sentence": "Plans are approved by digest", "status": "active", + "phase": null}); + let declared = submit_change(&store, ChangeKind::StoryDeclare, &story, DECLARE, T2) + .expect("story 4 is submitted"); + let digest = receipt(&declared)["digest"] + .as_str() + .and_then(Hash::from_hex) + .expect("the receipt names its digest"); + let judged = approve::judge(&store, &project(), digest).expect("story 4 is approvable"); + approve::record( + &store, + &command(APPROVE_COMMAND, DECLARE_APPROVE, 6, T2), + Some(&judged), + "Ada Owner", + ) + .expect("story 4 is approved"); + append( + &store, + REFINED, + T2, + vec![ + refined( + 1, + "1a1a1a1a-1a1a-4a1a-8a1a-1a1a1a1a1a1a", + vec![versioned(t1()), versioned(t2())], + ), + refined( + 2, + "2b2b2b2b-2b2b-4b2b-8b2b-2b2b2b2b2b2b", + vec![versioned(t1())], + ), + refined( + 4, + "4d4d4d4d-4d4d-4d4d-8d4d-4d4d4d4d4d4d", + vec![versioned(t2())], + ), + ], + ); + (dir, store) + } + + /// P0: the standard schema for Claude Code with no settings file. + pub(crate) fn p0() -> EffectivePolicy { + effective_policy(Schema::standard(), Some(Host::ClaudeCode), None, None) + .expect("the defaults merge") + } + + /// P2: P0 with a project file setting `planning.phase_capacity = 2`. + pub(crate) fn p2() -> EffectivePolicy { + let file = crate::settings::file( + Path::new("/r/baley.toml"), + b"[planning]\nphase_capacity = 2\n".to_vec(), + ); + effective_policy( + Schema::standard(), + Some(Host::ClaudeCode), + None, + Some(&file), + ) + .expect("the capacity is read") + } + + /// N0: no accepted name, at version 0. + pub(crate) fn n0() -> AcceptedNames { + AcceptedNames { + names: BTreeSet::new(), + version: 0, + } + } + + /// K, PL1's one task. + pub(crate) fn k() -> Value { + json!({"id": "k1", "title": "Record", "files": ["src/ledger.rs"], + "action": "Record each step.", "verify": ["cargo test ledger"]}) + } + + /// E1, a unit check of story 1's `t1` at version 1. + pub(crate) fn e1() -> Value { + json!({"id": "e1", "story": 1, "truth": "t1", "truth_version": 1, "kind": "check", + "spec": {"command": "cargo test stale", + "expected": {"kind": "literal", "value": "stale-draft"}, + "test": {"file": "src/ledger.rs", "function": "stale_digest"}, + "setup": "a draft approved by a stale digest", "call": "approve the draft", + "level": "unit", "boundary": "the approval judge", "fakes": []}, + "reason": "a stale digest approved"}) + } + + /// E2, an integration check of story 1's `t2` at version 1. + pub(crate) fn e2() -> Value { + json!({"id": "e2", "story": 1, "truth": "t2", "truth_version": 1, "kind": "check", + "spec": {"command": "cargo test round", + "expected": {"kind": "property", "value": "the same round"}, + "test": {"file": "src/ledger.rs", "function": "same_round"}, + "setup": "a set answered in two orders", "call": "read the round", + "level": "integration", "boundary": "the answer recording and the round read", + "fakes": ["the clock"]}, + "reason": "a round that depends on the answers' order"}) + } + + /// PL1: one plan of phase 1 serving story 1 with task K and checks E1 + /// and E2. + pub(crate) fn pl1() -> Value { + json!({"phase": 1, "stories": [1], "files": ["src/ledger.rs"], "directories": [], + "goal": "Record every step", "context": "", "notes": "", "tasks": [k()], + "evidence_map": [e1(), e2()], "questions": []}) + } + + /// PL2: PL1 asking `q1`. + pub(crate) fn pl2() -> Value { + let mut plan = pl1(); + plan["questions"] = json!([{"id": "q1", "question": "Which store holds the ledger?", + "recommended": "SQLite", "depends_on": []}]); + plan + } + + /// PL3: a second plan of phase 1, PL1 with another goal and task id and + /// PL1's items unchanged. + pub(crate) fn pl3() -> Value { + let mut plan = pl1(); + plan["goal"] = json!("Record again"); + plan["tasks"][0]["id"] = json!("k2"); + plan + } + + /// PL1r: PL1 with goal `Record every step, revised`. + pub(crate) fn pl1r() -> Value { + let mut plan = pl1(); + plan["goal"] = json!("Record every step, revised"); + plan + } + + /// Submits `plan` answering order `work_order` as the replacement of plan + /// `number` at `digest`, with no capacity, through the replacement's + /// check and the submit's recording, as `plan-replace` runs them below + /// the session, under `request_id` at `at`. Gives the answer. + pub(crate) fn plan_replaced( + store: &SqliteStore, + plan: &Value, + work_order: &str, + number: u32, + digest: Hash, + request_id: &str, + at: &str, + ) -> Value { + let replaces = baley_core::plan::Replaces { + plan: number, + digest, + }; + let checked = match crate::planning::replace::check( + store, + &project(), + plan, + work_order, + replaces, + None, + ) { + Ok(checked) => checked, + Err(refusal) => return refusal, + }; + let mut command = command("plan.replace", request_id, 8, at); + let on = caller() + .with_work_order(work_order) + .expect("an order id") + .with_instructions(checked.evidence.clone()) + .expect("the plan's instructions"); + command.caller = Some(baley_store::Caller::Server(on)); + crate::scope::submit::answer( + crate::planning::submit::record(store, &command, Some(&checked)), + store, + ) + } + + /// Records the `phase edit` of phase 1's stories to `stories` with its + /// continuation naming order `work_order`, through `submit_phase_edit` + /// under `request_id` at `at`, as `phase-plan` records a changed + /// selection. Gives the draft's digest. + pub(crate) fn edit( + store: &SqliteStore, + stories: &[u32], + work_order: &str, + request_id: &str, + at: &str, + ) -> Hash { + let fields = PhaseFields { + stories: Some(stories.to_vec()), + ..PhaseFields::default() + }; + let continuation = PlanningContinuation { + stories, + work_order, + documents: &[], + absences: &[], + }; + submit_phase_edit( + store, + &command(PHASE_PLAN_COMMAND, request_id, 7, at), + 1, + &fields, + Some(continuation), + ) + .expect("the edit is recorded") + } + + /// The commitment `digest` approved through the approval's two steps as + /// `Ada Owner` under `request_id` at `at`, its order routed under P0 + /// for Claude Code with N0. Gives the second step's answer. + pub(crate) fn approve_commitment( + store: &SqliteStore, + digest: Hash, + request_id: &str, + at: &str, + ) -> Value { + let judged = approve::judge(store, &project(), digest).expect("the commitment is judged"); + let (policy, names) = (p0(), n0()); + approve::record_commitment( + store, + &command(APPROVE_COMMAND, request_id, 6, at), + &judged, + "Ada Owner", + OrderRoute { + policy: &policy, + host: Host::ClaudeCode, + names: &names, + }, + ) + } + + /// The store in `dir` opened again, as a restart opens it. + pub(crate) fn reopen(dir: &tempfile::TempDir) -> SqliteStore { + crate::ledger::open::store(&dir.path().join("home"), T9, crate::ledger::open::options()) + .expect("the store opens again") + } + + /// Makes phase 2 active: its plan 1 approved by hand under `request_id`. + pub(crate) fn activate_phase_2(store: &SqliteStore, request_id: &str) { + approve_by_hand( + store, + request_id, + 2, + 1, + Hash([0x7e; 32]), + &[2], + 1, + &[], + Vec::new(), + ); + } + + /// Records PL2 as phase 1's draft with its set opened, under `request_id` + /// at T4, then `q1` answered `Postgres`, not the recommendation, under + /// `answer_request_id` at T5, as phase 8's set close leaves a rejected + /// recommendation. Gives the draft's body as recorded and the set's id. + pub(crate) fn pl2_rejected( + store: &SqliteStore, + request_id: &str, + answer_request_id: &str, + ) -> (Value, String) { + let truth = |id: &str, trigger: &str, observer: &str, outcome: &str| CurrentTruth { + id: id.into(), + version: 1, + trigger: trigger.into(), + observer: observer.into(), + outcome: outcome.into(), + human_verify: None, + }; + let facts = PlanFacts { + stories: vec![CommittedStory { + id: 1, + truths: vec![ + truth( + "t1", + "the owner approves a draft by a stale digest", + "the owner", + "stale-draft naming the first differing part", + ), + truth( + "t2", + "order the answers of a set are recorded in", + "a ledger reader", + "the same round", + ), + ], + }], + approved: Vec::new(), + size: 0, + capacity: None, + }; + let plan = judge_plan(&pl2(), &facts).expect("PL2 is accepted"); + let draft = PlanDraft::new(&plan); + let mut set = String::new(); + store + .transact(&command("test.plan", request_id, 8, T4), &mut |tx| { + let body = tx.put_payload(draft.body(), RetentionClass::Record)?; + tx.append(NewEvent { + stream: StreamName(PROJECT_STREAM.into()), + type_name: SCOPE_SUBMITTED.into(), + type_version: SCOPE_SUBMITTED_VERSION, + git: None, + payload: submitted_payload(draft.digest(), PLAN_KIND, draft.target(), &body), + attachments: vec![body], + })?; + let subject = Subject::Plan { + phase: 1, + plan_digest: draft.digest(), + }; + set = crate::questions::record::open(tx, plan.questions(), &subject, T4)?; + Ok(Decision { + kind: OutcomeKind::Done, + answer: json!({"status": "ok"}), + sensitive: false, + observed: Observed::default(), + git: None, + }) + }) + .expect("PL2 is drafted"); + append( + store, + answer_request_id, + T5, + vec![NewEvent { + stream: StreamName(phase_stream(1)), + type_name: QUESTION_ANSWERED.into(), + type_version: QUESTION_ANSWERED_VERSION, + git: None, + payload: answered_payload(&set, "q1", 1, "Postgres", false, "Ada Owner", T5), + attachments: Vec::new(), + }], + ); + let body = serde_json::from_slice(draft.body()).expect("a draft body is JSON"); + (body, set) + } + + /// Appends, under `request_id` in its own transaction, a `plan.approved` + /// of plan `plan` of phase `phase` at `digest`, serving `stories` with + /// `size` tasks and evidence map `map`, as an approval would leave it, + /// with a body stored as a `record` payload in the same transaction so + /// its reference is held. Every `events` entry is appended after it. + #[allow(clippy::too_many_arguments)] + pub(crate) fn approve_by_hand( + store: &SqliteStore, + request_id: &str, + phase: u32, + plan: u32, + digest: Hash, + stories: &[u32], + size: usize, + map: &[Value], + events: Vec, + ) { + let body = canonical_json(&json!({"phase": phase, "plan": plan, "evidence_map": map})) + .expect("a plan body is canonical"); + let command = command("test.approve", request_id, 9, T5); + store + .transact(&command, &mut |tx| { + let body = tx.put_payload(&body, RetentionClass::Record)?; + let approval = PlanApproval { + phase, + plan, + digest, + stories, + size, + suite: None, + question_set: APPROVAL_SET, + evidence_map: map, + body: &body, + owner: "Ada Owner", + at: T5, + }; + tx.append(NewEvent { + stream: StreamName(phase_stream(phase)), + type_name: PLAN_APPROVED.into(), + type_version: PLAN_APPROVED_VERSION, + git: None, + payload: approval.payload(), + attachments: vec![body], + })?; + for event in events.clone() { + tx.append(event)?; + } + Ok(Decision { + kind: OutcomeKind::Done, + answer: json!({"status": "ok"}), + sensitive: false, + observed: Observed::default(), + git: None, + }) + }) + .expect("the approval is appended"); + } +} diff --git a/crates/baley/src/planning/order.rs b/crates/baley/src/planning/order.rs new file mode 100644 index 00000000..7bea5e54 --- /dev/null +++ b/crates/baley/src/planning/order.rs @@ -0,0 +1,869 @@ +//! A phase's planner order (design 0005 sections 4 and 5, D-11, D-12, +//! D-15): a planning or revision order prepared outside any transaction and +//! issued on the phase's stream, `phase/`, with subject `phase/`, in +//! its own transaction or inside a caller's. +//! +//! A phase has one live planner order: an issue declares that no planner +//! order of the phase is pending, so a second one recorded since the caller +//! looked makes the call `ledger-busy` with nothing recorded. A revision +//! starts a new chain at attempt 1, as a planning order does. +//! +//! An order the approval of a changed selection issued is handed to the +//! session once (D-01, D-09): `plan.continuation_followed` is recorded and +//! the answer is the order's receipt as its issue gave it, so the session +//! launches it as it would a fresh order. An order no longer pending, or one +//! whose continuation is followed or replaced, is refused before anything is +//! recorded. + +use std::num::NonZeroU32; + +use baley_core::plan::{ + PHASE_PLAN_VIEW, PLAN_CONTINUATION_FOLLOWED, PLAN_CONTINUATION_FOLLOWED_VERSION, + PLANNER_ORDER_PENDING, continuation_followed_payload, phase_plan_key, phase_stream, +}; +use baley_core::policy::{AcceptedNames, EffectivePolicy, Host, Role}; +use baley_core::questions::SetFacts; +use baley_core::work_order::{ + PENDING, WORK_ORDER_LIVE_INDEX, WORK_ORDER_NOT_PENDING, WORK_ORDER_VIEW, phase_subject, + work_order_key, +}; +use baley_store::{ + Absence, Command, Decision, Document, Hash, IndexQuery, InstructionEvidence, KeyValue, Ledger, + NewEvent, Observed, ObservedDocument, OutcomeKind, PageRequest, Payloads, ProjectId, + StoreError, StreamName, Transaction, Views, +}; +use serde_json::{Map, Value, json}; + +use crate::envelope::Refusal; +use crate::instruction::planner::IDENTITY; +use crate::mcp::capture::{PLACE_LEDGER, failed, store_failed}; +use crate::mcp::prepare::LEDGER_UNAVAILABLE; +use crate::planning::inputs::{self, Revision}; +use crate::planning::phase_plan::read_readiness; +use crate::scope::submit::NOT_RECORDED_BUSY; +use crate::work_order::issue::{self, Input, Issue, launch, prompt}; +use crate::work_order::route::{IssuedRoute, compose}; + +/// A planner order prepared outside any transaction: everything it is +/// issued with. +#[derive(Debug, Clone, PartialEq)] +pub struct PreparedOrder { + /// The order's id, also its request. + id: String, + /// The phase it plans. + phase: u32, + /// The route it runs under. + route: IssuedRoute, + /// The evidence of the planner's text. + instructions: Vec, + /// The inputs read from the ledger, in order. + inputs: Vec<(&'static str, Vec)>, + /// The documents the inputs were read from, at the sequence that + /// produced each. + documents: Vec, +} + +impl PreparedOrder { + /// The order's id. + pub fn id(&self) -> &str { + &self.id + } + + /// The phase the order plans. + pub fn phase(&self) -> u32 { + self.phase + } + + /// The documents its inputs were read from, which the recording's + /// decision observes. + pub fn documents(&self) -> &[ObservedDocument] { + &self.documents + } + + /// Issues the order inside `tx`, a transaction its caller runs, + /// recorded at `recorded_at`. The caller declares [`planner_absences`] + /// and observes [`Self::documents`] in its own decision. The answer is + /// the receipt's members other than `status`. + pub fn issue_within( + &self, + tx: &mut dyn Transaction, + recorded_at: &str, + ) -> Result, StoreError> { + self.with_issue(&[], &[], |issue| { + issue::issue_within(tx, issue, recorded_at) + }) + } + + /// Runs `then` over the order as `issue::record` takes it, with + /// `absences` and `documents` as its caller's. + fn with_issue( + &self, + absences: &[Absence], + documents: &[ObservedDocument], + then: impl FnOnce(&Issue<'_>) -> T, + ) -> T { + let inputs: Vec> = self + .inputs + .iter() + .map(|(name, bytes)| Input::Bytes { name, bytes }) + .collect(); + let subject = phase_subject(self.phase); + then(&Issue { + id: &self.id, + request: &self.id, + parent: None, + subject: &subject, + route: &self.route, + instructions: &self.instructions, + inputs: &inputs, + absences, + streams: &[], + documents, + further: &Map::new(), + }) + } +} + +/// Prepares phase `phase`'s planner order as `id` for `command`'s project, +/// committing `stories` in that order: the route for `planner` at attempt 1 +/// under `policy`, the host's effective policy, at the command's policy +/// version, with the catalog `names`; the evidence of `bal-phase-planner`; +/// and the inputs read now (D-12), a revision's draft and set among them +/// when `revision` names one (D-15). It has no parent and its id is also its +/// request, so a revision starts a new chain. Nothing is recorded. A fault +/// is the answer to give. +#[allow(clippy::too_many_arguments)] +pub fn prepare( + store: &S, + command: &Command, + phase: u32, + stories: &[u32], + revision: Option>, + policy: &EffectivePolicy, + host: Host, + names: &AcceptedNames, + id: &str, +) -> Result { + let instructions = vec![crate::instruction::evidence(IDENTITY)?]; + let route = route(command, policy, host, names)?; + let read = inputs::read(store, &command.project, phase, stories, policy, revision)?; + Ok(PreparedOrder { + id: id.into(), + phase, + route, + instructions, + inputs: read.inputs, + documents: read.documents, + }) +} + +/// Prepares the revision order a close of plan draft `revision.draft`'s set +/// issues over MCP, as `id` for `command`'s project (D-15, PLN-R27): as +/// [`prepare`] prepares a revision for phase `phase`'s committed stories in +/// their order, its `questions` input built from `closed`, the set's facts +/// with the closing call's own answers and deferrals. Its documents hold the +/// `roadmap` document the committed stories were read from as well as the +/// inputs', so a commitment changed between the two reads is never issued +/// for. The caller issues it inside its own transaction with +/// [`PreparedOrder::issue_within`]. Nothing is recorded. A fault is the +/// answer to give. +#[allow(clippy::too_many_arguments)] +pub fn prepare_revision( + store: &S, + command: &Command, + phase: u32, + revision: Revision<'_>, + closed: &SetFacts, + policy: &EffectivePolicy, + host: Host, + names: &AcceptedNames, + id: &str, +) -> Result { + let readiness = read_readiness(store, &command.project, phase, &[])?; + let stories = readiness.committed(); + let instructions = vec![crate::instruction::evidence(IDENTITY)?]; + let route = route(command, policy, host, names)?; + let read = inputs::read_closing( + store, + &command.project, + phase, + stories, + policy, + revision, + closed, + )?; + // The selection came from the readiness read, so its documents are + // observed beside the inputs': a commitment changed between the two + // reads makes the issue `ledger-busy`. + let mut documents = readiness.documents().to_vec(); + documents.extend(read.documents); + Ok(PreparedOrder { + id: id.into(), + phase, + route, + instructions, + inputs: read.inputs, + documents, + }) +} + +/// The planner's route at attempt 1 under `policy` at `command`'s policy +/// version, for `host` with the catalog `names`. +fn route( + command: &Command, + policy: &EffectivePolicy, + host: Host, + names: &AcceptedNames, +) -> Result { + compose( + policy, + command.policy_version, + host, + Role::Planner, + NonZeroU32::MIN, + names, + ) + .map_err(|refusal| Refusal::new(refusal.code(), refusal.to_string()).value()) +} + +/// Issues `prepared` under `command`, the command its caller prepared, in +/// its own transaction. The decision declares no pending planner order of +/// the phase and observes every document the inputs were read from, so an +/// order issued, a truth revised or a plan approved since makes the call +/// `ledger-busy` with nothing recorded. +pub fn issue( + store: &S, + command: &Command, + prepared: &PreparedOrder, +) -> Value { + let absences = planner_absences(prepared.phase); + prepared.with_issue(&absences, &prepared.documents, |issue| { + issue::answer(issue::record(store, command, Some(issue)), store) + }) +} + +/// The fact a planner order of phase `phase` relies on being absent: a +/// pending planner order of the same phase on the `live` index (D-11). +pub fn planner_absences(phase: u32) -> Vec { + vec![Absence::Documents { + view: WORK_ORDER_VIEW.into(), + index: WORK_ORDER_LIVE_INDEX.into(), + equals: live(phase), + }] +} + +/// The id of phase `phase`'s pending planner order in `project`, the newest +/// the `live` index gives for `planner`, the phase's subject and `pending`, +/// or none. A planning and a revision order share the subject, so either +/// one is found. +pub fn pending_planner( + store: &S, + project: &ProjectId, + phase: u32, +) -> Result, StoreError> { + Ok( + pending_planner_order(store, project, phase)?.map(|document| { + document + .body + .get("id") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }), + ) +} + +/// The `work_order` document of phase `phase`'s pending planner order, the +/// one [`pending_planner`] names, or none. +pub fn pending_planner_order( + store: &S, + project: &ProjectId, + phase: u32, +) -> Result, StoreError> { + let query = IndexQuery { + index: WORK_ORDER_LIVE_INDEX.into(), + equals: live(phase), + page: PageRequest { + limit: 1, + after: None, + }, + }; + Ok(store + .find(project, WORK_ORDER_VIEW, &query)? + .items + .into_iter() + .next()) +} + +/// The refusal for phase `phase`'s pending planner order `pending`, with +/// `not_issued` saying what was not issued. +pub fn planner_order_pending(phase: u32, pending: &str, not_issued: &str) -> Value { + Refusal::new( + PLANNER_ORDER_PENDING, + format!( + "phase {phase}'s planner work order {pending} is still pending, {not_issued}, since a phase has one live planner order. Read that order with `document`, or fail it with `work-order-fail` and retry it with `work-order-retry`" + ), + ) + .slot("operation") + .details(json!({"work_order": pending})) + .value() +} + +/// What a hand-over read: the order's receipt as its issue gave it, the +/// documents it was read from, and what its caller read when it judged the +/// hand-over. +#[derive(Debug, Clone, PartialEq)] +pub struct HandOver { + /// The phase the order plans. + phase: u32, + /// The approved `phase edit` draft whose continuation names the order. + edit: Hash, + /// The order's id. + work_order: String, + /// The receipt's members other than `status`. + receipt: Map, + /// The `phase_plan` document, then the order's `work_order` document, + /// each at the sequence that produced it, then the caller's. + documents: Vec, + /// What the caller relies on being absent, none unless it added some. + absences: Vec, +} + +impl HandOver { + /// The hand-over also observing `documents` and declaring `absences`, + /// what its caller read when it judged that the order is handed over, so + /// a change since that the caller's judgement would refuse, such as a + /// phase made active or a story's truths emptied, makes the hand-over + /// `ledger-busy` with nothing recorded. + pub fn observing(mut self, documents: &[ObservedDocument], absences: Vec) -> Self { + self.documents.extend_from_slice(documents); + self.absences.extend(absences); + self + } +} + +/// Reads the hand-over of order `work_order` of phase `phase` in `project`, +/// which the approval of the `phase edit` draft `edit` issued (D-01): the +/// `phase_plan` document first, then the order's `work_order` document, from +/// which its receipt is built as its issue gave it: its id, request, attempt, +/// agent, model, `prompt`, `launch` and the time it was recorded. Nothing is +/// recorded. An order that failed or was answered is refused +/// `work-order-not-pending` naming its state. A pending order whose phase's +/// latest continuation is followed, or names another edit or order, is +/// refused `planner-order-pending` naming it, so it is handed over once +/// (D-09). Both are judged on the documents whose sequences the hand-over +/// observes. An order whose document is not held or cannot be read is a +/// ledger fault. +pub fn read_hand_over( + store: &S, + project: &ProjectId, + phase: u32, + edit: Hash, + work_order: &str, +) -> Result { + let busy = |error: StoreError| store_failed(&error, NOT_RECORDED_BUSY); + let phase_plan = store + .get(project, PHASE_PLAN_VIEW, &phase_plan_key(phase)) + .map_err(busy)?; + let order = store + .get(project, WORK_ORDER_VIEW, &work_order_key(work_order)) + .map_err(busy)? + .ok_or_else(order_unreadable)?; + match order.body.get("state").and_then(Value::as_str) { + Some(PENDING) => {} + Some(state) => return Err(order_not_pending(work_order, state)), + None => return Err(order_unreadable()), + } + let Some(phase_plan) = phase_plan + .filter(|document| continues(document.body.get("continuation"), edit, work_order)) + else { + return Err(planner_order_pending( + phase, + work_order, + "so it was not handed over", + )); + }; + let receipt = receipt_of(&order.body).ok_or_else(order_unreadable)?; + Ok(HandOver { + phase, + edit, + work_order: work_order.into(), + receipt, + documents: vec![ + ObservedDocument { + view: PHASE_PLAN_VIEW.into(), + key: phase_plan_key(phase), + produced_seq: Some(phase_plan.produced_seq), + }, + ObservedDocument { + view: WORK_ORDER_VIEW.into(), + key: work_order_key(work_order), + produced_seq: Some(order.produced_seq), + }, + ], + absences: Vec::new(), + }) +} + +/// Hands `read`'s order to the session under `command`, in one +/// transaction: one `plan.continuation_followed` on `phase/` naming the +/// edit and the order. The decision observes the `phase_plan` and +/// `work_order` documents the read saw and declares what the read's caller +/// added through [`HandOver::observing`], so an order failed or answered, a +/// continuation replaced or followed, or anything the caller judged moved +/// since the read makes the call `ledger-busy` with nothing recorded. The +/// answer is the order's receipt with `status` `ok`. +pub fn hand_over(store: &S, command: &Command, read: &HandOver) -> Value { + let mut answer = Map::new(); + answer.insert("status".into(), json!("ok")); + answer.extend(read.receipt.clone()); + let answer = Value::Object(answer); + let result = store.transact(command, &mut |tx| { + tx.append(NewEvent { + stream: StreamName(phase_stream(read.phase)), + type_name: PLAN_CONTINUATION_FOLLOWED.into(), + type_version: PLAN_CONTINUATION_FOLLOWED_VERSION, + git: None, + payload: continuation_followed_payload(read.phase, read.edit, &read.work_order), + attachments: Vec::new(), + })?; + Ok(Decision { + kind: OutcomeKind::Done, + answer: answer.clone(), + sensitive: false, + observed: Observed { + absences: read.absences.clone(), + documents: read.documents.clone(), + ..Observed::default() + }, + git: None, + }) + }); + issue::answer(result, store) +} + +/// The receipt members an order's `work_order` document gives, as its issue +/// gave them, or none when a member cannot be read. +fn receipt_of(order: &Value) -> Option> { + let text = |field: &str| order.get(field).and_then(Value::as_str); + let id = text("id")?; + let agent = text("agent")?; + let model = match order.get("route")?.get("model")? { + Value::Null => None, + Value::String(model) => Some(model.as_str()), + _ => return None, + }; + let mut receipt = Map::new(); + receipt.insert("work_order".into(), json!(id)); + receipt.insert("request".into(), json!(text("request")?)); + receipt.insert("attempt".into(), json!(order.get("attempt")?.as_u64()?)); + receipt.insert("agent".into(), json!(agent)); + receipt.insert("model".into(), json!(model)); + receipt.insert("prompt".into(), json!(prompt(id))); + receipt.insert("launch".into(), json!(launch(agent, model))); + receipt.insert("recorded_at".into(), json!(text("recorded_at")?)); + Some(receipt) +} + +/// Whether `latest`, a phase's latest continuation, names `edit` and +/// `work_order` and is not yet followed. A null or missing one does not. +fn continues(latest: Option<&Value>, edit: Hash, work_order: &str) -> bool { + latest.is_some_and(|latest| { + latest.get("edit").and_then(Value::as_str) == Some(edit.to_hex().as_str()) + && latest.get("work_order").and_then(Value::as_str) == Some(work_order) + && latest.get("followed") == Some(&Value::Bool(false)) + }) +} + +/// The refusal for order `work_order`, which is `state` rather than pending, +/// in `work-order-fail`'s shape. +fn order_not_pending(work_order: &str, state: &str) -> Value { + Refusal::new( + WORK_ORDER_NOT_PENDING, + format!( + "work order {work_order} is {state}, so it was not handed over. A failed order is retried with `work-order-retry`, and an answered one has already returned" + ), + ) + .slot("work_order") + .details(json!({"state": state})) + .value() +} + +fn order_unreadable() -> Value { + failed( + LEDGER_UNAVAILABLE, + "the ledger holds no readable document for the planner order the approval issued, so nothing was recorded", + PLACE_LEDGER, + ) +} + +/// The `live` index prefix of phase `phase`'s pending planner orders. +fn live(phase: u32) -> Vec { + let text = |value: &str| KeyValue::Text(value.into()); + vec![ + text(Role::Planner.name()), + text(&phase_subject(phase)), + text(PENDING), + ] +} + +#[cfg(test)] +pub(crate) mod tests { + //! Stores are real SQLite stores in fresh temporary directories, with + //! times supplied; expected values are written out from design 0005, + //! D-11, D-12, D-15 and the plan's data store C, P0 and N0, never from + //! running this code. + + use baley_core::plan::phase_stream; + use baley_core::work_order::{WORK_ORDER_FAILED, WORK_ORDER_FAILED_VERSION, failed_payload}; + use baley_store::{NewEvent, StreamName}; + use baley_store_sqlite::SqliteStore; + + use super::*; + use crate::planning::fixtures::*; + use crate::refine::order::tests::issued; + use crate::scope::fixtures::*; + + /// O, phase 1's first planning order. + pub(crate) const O: &str = "1f2e3d4c-5b6a-4978-8695-a4b3c2d1e0f1"; + /// O2, a second planner order of phase 1. + pub(crate) const O2: &str = "2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"; + + /// Phase 1's planning order for `stories` prepared as `id` under P0 and + /// N0 for a command under `request_id` at `at`. + pub(crate) fn prepared( + store: &SqliteStore, + stories: &[u32], + id: &str, + request_id: &str, + at: &str, + ) -> (Command, PreparedOrder) { + let command = command("phase.plan", request_id, 7, at); + let prepared = prepare( + store, + &command, + 1, + stories, + None, + &p0(), + Host::ClaudeCode, + &n0(), + id, + ) + .expect("the order is prepared"); + (command, prepared) + } + + /// Fails order `id` of phase 1 by hand under `request_id`. + pub(crate) fn fail_by_hand(store: &SqliteStore, id: &str, request_id: &str) { + append( + store, + request_id, + T6, + vec![NewEvent { + stream: StreamName(phase_stream(1)), + type_name: WORK_ORDER_FAILED.into(), + type_version: WORK_ORDER_FAILED_VERSION, + git: None, + payload: failed_payload(id, "the planner stopped"), + attachments: Vec::new(), + }], + ); + } + + #[test] + fn a_planner_order_recorded_off_its_phase_or_beside_a_pending_one_is_caught() { + let (_dir, store) = store_c(); + let (command_o, o) = prepared(&store, &[1], O, R1, T4); + let (command_o2, o2) = prepared(&store, &[1], O2, R2, T4); + let receipt = issue(&store, &command_o, &o); + assert_eq!(receipt["status"], "ok", "{receipt}"); + + let issued = issued(&store); + assert_eq!(issued.len(), 1); + assert_eq!(issued[0].stream, "phase/1"); + let payload = &issued[0].payload; + assert_eq!(payload["subject"], "phase/1"); + assert_eq!(payload["role"], "planner"); + assert_eq!(payload["attempt"], 1); + assert_eq!(payload["request"], O); + assert_eq!(payload["parent"], Value::Null); + assert_eq!(payload["agent"], "bal-planner-high"); + let identities: Vec<&str> = payload["instructions"] + .as_array() + .unwrap() + .iter() + .map(|entry| entry["identity"].as_str().unwrap()) + .collect(); + assert_eq!(identities, ["bal-phase-planner"]); + assert_eq!( + pending_planner(&store, &project(), 1).unwrap().as_deref(), + Some(O) + ); + + let before = head(&store); + let busy = issue(&store, &command_o2, &o2); + assert_eq!(busy["status"], "failed", "{busy}"); + assert_eq!(busy["code"], "ledger-busy", "{busy}"); + assert_eq!(head(&store), before); + } + + /// Store C with a continuation of phase 1 for `[1]` naming edit X and + /// order O appended by hand, then O issued under P0 and N0 as that id. + /// Gives O's issue receipt. + fn continued(store: &SqliteStore) -> Value { + append( + store, + R1, + T4, + vec![NewEvent { + stream: StreamName(phase_stream(1)), + type_name: baley_core::plan::PLAN_CONTINUATION.into(), + type_version: baley_core::plan::PLAN_CONTINUATION_VERSION, + git: None, + payload: baley_core::plan::continuation_payload(1, &[1], x(), O), + attachments: Vec::new(), + }], + ); + let (command_o, o) = prepared(store, &[1], O, R2, T5); + let receipt = issue(store, &command_o, &o); + assert_eq!(receipt["status"], "ok", "{receipt}"); + receipt + } + + /// X, the approved edit's digest. + fn x() -> Hash { + Hash([0x5c; 32]) + } + + #[test] + fn an_approved_order_handed_over_without_its_launch_or_its_marker_is_caught() { + let (_dir, store) = store_c(); + let issued_receipt = continued(&store); + let read = read_hand_over(&store, &project(), 1, x(), O).unwrap(); + let answer = hand_over(&store, &command("phase.plan", R3, 7, T6), &read); + + assert_eq!(answer["status"], "ok", "{answer}"); + for member in [ + "work_order", + "request", + "attempt", + "agent", + "model", + "prompt", + "launch", + ] { + assert_eq!(answer[member], issued_receipt[member], "{member}"); + } + assert_eq!( + answer["prompt"], + format!("Read Baley work order {O} and follow it.") + ); + let events = history(&store); + let followed = of_type(&events, "plan.continuation_followed"); + assert_eq!(followed.len(), 1); + assert_eq!(followed[0].stream, "phase/1"); + assert_eq!( + followed[0].payload, + json!({"phase": 1, "edit": "5c".repeat(32), "work_order": O}) + ); + assert_eq!(issued(&store).len(), 1); + } + + #[test] + fn an_order_failed_since_it_was_read_handed_over_is_caught() { + let (_dir, store) = store_c(); + continued(&store); + let read = read_hand_over(&store, &project(), 1, x(), O).unwrap(); + fail_by_hand(&store, O, R3); + let before = head(&store); + let answer = hand_over(&store, &command("phase.plan", R4, 7, T7), &read); + + assert_eq!(answer["status"], "failed", "{answer}"); + assert_eq!(answer["code"], "ledger-busy", "{answer}"); + assert_eq!(head(&store), before); + assert!(of_type(&history(&store), "plan.continuation_followed").is_empty()); + } + + #[test] + fn an_order_failed_before_it_was_read_handed_over_is_caught() { + let (_dir, store) = store_c(); + continued(&store); + fail_by_hand(&store, O, R3); + let before = head(&store); + let refusal = read_hand_over(&store, &project(), 1, x(), O) + .expect_err("a failed order is not handed over"); + + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], "work-order-not-pending", "{refusal}"); + assert_eq!(refusal["slot"], "work_order", "{refusal}"); + assert_eq!(refusal["details"], json!({"state": "failed"})); + assert_eq!(head(&store), before); + assert!(of_type(&history(&store), "plan.continuation_followed").is_empty()); + } + + #[test] + fn a_followed_continuation_handed_over_again_is_caught() { + let (_dir, store) = store_c(); + continued(&store); + let read = read_hand_over(&store, &project(), 1, x(), O).unwrap(); + let first = hand_over(&store, &command("phase.plan", R3, 7, T6), &read); + assert_eq!(first["status"], "ok", "{first}"); + let before = head(&store); + let refusal = read_hand_over(&store, &project(), 1, x(), O) + .expect_err("a followed continuation is not handed over again"); + + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], "planner-order-pending", "{refusal}"); + assert_eq!(refusal["slot"], "operation", "{refusal}"); + assert_eq!(refusal["details"], json!({"work_order": O})); + assert_eq!(head(&store), before); + assert_eq!( + of_type(&history(&store), "plan.continuation_followed").len(), + 1 + ); + } + + #[test] + fn a_planner_retry_issued_beside_a_pending_planner_order_is_caught() { + let (_dir, store) = store_c(); + let (command_o, o) = prepared(&store, &[1], O, R1, T4); + assert_eq!(issue(&store, &command_o, &o)["status"], "ok"); + fail_by_hand(&store, O, R2); + let (command_o2, o2) = prepared(&store, &[1], O2, R3, T6); + assert_eq!(issue(&store, &command_o2, &o2)["status"], "ok"); + + let before = head(&store); + let refusal = crate::mcp::work_order::retry_check(&store, &project(), O) + .expect_err("the retry is refused"); + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], "planner-order-pending", "{refusal}"); + assert_eq!(refusal["slot"], "operation", "{refusal}"); + assert_eq!(refusal["details"], json!({"work_order": O2})); + assert_eq!(head(&store), before); + } + + /// Commits `[1, 4]` to phase 1 through a plain `phase edit`, with no + /// continuation, approved by the owner under R5 and R6 at T7. + fn story_4_committed(store: &SqliteStore) { + let fields = baley_core::scope::PhaseFields { + stories: Some(vec![1, 4]), + ..baley_core::scope::PhaseFields::default() + }; + let submit = command(crate::scope::submit::SUBMIT_COMMAND, R5, 7, T7); + let digest = crate::scope::submit::submit_phase_edit(store, &submit, 1, &fields, None) + .expect("the edit is recorded"); + let judged = crate::scope::approve::judge(store, &project(), digest) + .expect("the edit is approvable"); + let approval = command(crate::scope::approve::APPROVE_COMMAND, R6, 6, T7); + let answer = crate::scope::submit::answer( + crate::scope::approve::record(store, &approval, Some(&judged), "Ada Owner"), + store, + ); + assert_eq!(answer["status"], "ok", "{answer}"); + } + + /// The real store, with `land` run once just after the first read of + /// `phase_plan`'s status index returns: the end of the readiness read + /// a revision's selection comes from, before its inputs are read. + struct CommitsDuring<'a> { + store: &'a SqliteStore, + land: std::cell::RefCell>>, + } + + impl Views for CommitsDuring<'_> { + fn get( + &self, + project: &ProjectId, + view: &str, + key: &baley_store::DocKey, + ) -> Result, StoreError> { + Views::get(self.store, project, view, key) + } + + fn get_many( + &self, + project: &ProjectId, + view: &str, + keys: &[baley_store::DocKey], + ) -> Result>, StoreError> { + Views::get_many(self.store, project, view, keys) + } + + fn find( + &self, + project: &ProjectId, + view: &str, + query: &IndexQuery, + ) -> Result, StoreError> { + let read = Views::find(self.store, project, view, query); + if view == PHASE_PLAN_VIEW { + let land = self.land.borrow_mut().take(); + if let Some(land) = land { + land(); + } + } + read + } + } + + impl Payloads for CommitsDuring<'_> { + fn open(&self, hash: &Hash) -> Result, StoreError> { + Payloads::open(self.store, hash) + } + + fn status(&self, hash: &Hash) -> Result { + Payloads::status(self.store, hash) + } + } + + #[test] + fn a_revision_issued_for_a_selection_changed_between_its_reads_is_caught() { + use crate::planning::approve::tests::digest_of; + use crate::planning::submit::tests::{order_o, plan_submitted}; + + let (_dir, store) = store_c(); + order_o(&store, R1); + let submitted = plan_submitted(&store, &pl2(), O, None, R2, T5); + let x2 = digest_of(&submitted); + let s2 = submitted["set"].as_str().unwrap().to_owned(); + let closed = SetFacts { + questions: Vec::new(), + answers: Vec::new(), + deferrals: Vec::new(), + abandoned: None, + }; + let moving = CommitsDuring { + store: &store, + land: std::cell::RefCell::new(Some(Box::new(|| story_4_committed(&store)))), + }; + let command = command("questions.answer", R3, 9, T6); + let prepared = prepare_revision( + &moving, + &command, + 1, + Revision { + draft: x2, + set: &s2, + }, + &closed, + &p0(), + Host::ClaudeCode, + &n0(), + O2, + ) + .expect("the revision is prepared"); + assert!( + moving.land.borrow().is_none(), + "story 4 was committed between the reads" + ); + + // Phase 1 commits `[1, 4]` now, so a revision bound to `[1]` alone + // is refused rather than recorded. + let before = head(&store); + let busy = issue(&store, &command, &prepared); + assert_eq!(busy["status"], "failed", "{busy}"); + assert_eq!(busy["code"], "ledger-busy", "{busy}"); + assert_eq!(head(&store), before); + } +} diff --git a/crates/baley/src/planning/phase_plan.rs b/crates/baley/src/planning/phase_plan.rs new file mode 100644 index 00000000..9134a544 --- /dev/null +++ b/crates/baley/src/planning/phase_plan.rs @@ -0,0 +1,871 @@ +//! `phase plan` (design 0005 section 5, PLN-R7, D-01, D-02, D-08 to D-11, +//! D-15): a session asks for one phase's planner with an ordered selection of +//! stories. The check runs before admission and records nothing: it gathers +//! the facts the commitment judge decides on, with the documents they came +//! from, and judges them; for a changed selection it also judges the `phase +//! edit` of the stories and checks it against accepted scope, so the edit's +//! own refusals come before admission too. The run then takes the judged +//! path: a changed selection is recorded as that edit with its planning +//! continuation and answered with the draft and the commands that preview +//! and approve it, issuing no order; an unchanged one issues a planning +//! order, or the pending revision when an answer rejected a recommendation; +//! and the order a commitment's approval issued is handed over. +//! +//! Every recording observes the documents the check read, so anything moved +//! since makes the call `ledger-busy` with nothing recorded. The commitment's +//! approval rechecks a continuation's selection through the same gathering +//! ([`read_readiness`]). + +use baley_core::plan::{ + ACTIVE, CommitmentFacts, CommitmentRefusal, Continuation, PHASE_PLAN_STATUS_INDEX, + PHASE_PLAN_VIEW, PhasePlanPath, Readiness, SelectedStory, judge_commitment, phase_plan_key, +}; +use baley_core::policy::{AcceptedNames, EffectivePolicy, Host}; +use baley_core::questions::{QUESTIONS_VIEW, SetState, questions_key}; +use baley_core::scope::{ChangeKind, PhaseFields, ROADMAP_VIEW, judge_change, roadmap_key}; +use baley_core::truth::{TRUTHS_VIEW, truths_key}; +use baley_core::work_order::PENDING; +use baley_store::{ + Absence, Command, Decision, DocKey, Hash, IndexQuery, KeyValue, Ledger, Observed, + ObservedDocument, OutcomeKind, PageRequest, Payloads, ProjectId, StoreError, Views, +}; +use serde_json::{Map, Value, json}; + +use crate::envelope::Refusal; +use crate::mcp::capture::{PLACE_LEDGER, failed, store_failed}; +use crate::mcp::prepare::LEDGER_UNAVAILABLE; +use crate::planning::inputs::Revision; +use crate::planning::order::{ + self, HandOver, pending_planner, planner_absences, planner_order_pending, read_hand_over, +}; +use crate::questions::read::{SetRead, read as read_set}; +use crate::scope::read; +use crate::scope::submit::{ + NOT_RECORDED_BUSY, PlanningContinuation, check_change, scope_unread, submission_refused, + submit_planning_edit, +}; +use crate::work_order::issue; + +/// The command kind a `phase-plan` call is recorded under. +pub const PHASE_PLAN_COMMAND: &str = "phase.plan"; + +/// The status a withdrawn phase holds in the roadmap. +const WITHDRAWN: &str = "withdrawn"; +/// The status a dropped story holds in the roadmap. +const DROPPED: &str = "dropped"; +/// The `phase_plan` view's page bound, so the active phases are read in as +/// few pages as it allows. +const ACTIVE_PAGE: u32 = 100; + +/// A selection's readiness facts with the documents they came from, read +/// outside any transaction. `phase-plan`'s check and the commitment's +/// approval both gather them here, so the approval rechecks the same facts +/// the call was judged on (D-01). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReadinessRead { + /// The phase being planned. + phase: u32, + /// Whether the roadmap holds the phase and it is not withdrawn. + phase_held: bool, + /// The phase's committed stories, in order, none when it is not held. + committed: Vec, + /// The active phases from `phase_plan`'s status index. + active: Vec, + /// The selection, in order, as the roadmap and `truths` hold it. + stories: Vec, + /// The `roadmap` document, then each selected story's `truths` + /// document, each at the sequence that produced it. + documents: Vec, +} + +impl ReadinessRead { + /// The facts `judge_readiness` takes. + pub fn readiness(&self) -> Readiness<'_> { + Readiness { + phase: self.phase, + phase_held: self.phase_held, + active: &self.active, + stories: &self.stories, + } + } + + /// The phase's committed stories, in order. + pub fn committed(&self) -> &[u32] { + &self.committed + } + + /// The documents the facts were read from. + pub fn documents(&self) -> &[ObservedDocument] { + &self.documents + } + + /// What a recording relies on being absent. An empty read of the active + /// phases leaves no document to observe, so when none was active a + /// recording declares that `phase_plan`'s status index still holds no + /// active phase, and a phase made active since makes it `ledger-busy` + /// (D-02). With one active, the readiness judgement names it, so + /// nothing is declared. + pub fn absences(&self) -> Vec { + if !self.active.is_empty() { + return Vec::new(); + } + vec![Absence::Documents { + view: PHASE_PLAN_VIEW.into(), + index: PHASE_PLAN_STATUS_INDEX.into(), + equals: active_prefix(), + }] + } +} + +/// Gathers the readiness of `stories`, in that order, for phase `phase` of +/// `project`: the phase and its stories and each selected story's status and +/// phase from the `roadmap` view, whether each holds an approved truth from +/// the `truths` view, and the active phases from `phase_plan`'s status +/// index. Nothing is judged or recorded. A fault is the `failed` answer. +pub fn read_readiness( + store: &S, + project: &ProjectId, + phase: u32, + stories: &[u32], +) -> Result { + // The sequence before the content, so a roadmap that moves after its + // read shows as moved when the recording confirms it. + let roadmap_seq = produced(store, project, ROADMAP_VIEW, roadmap_key())?; + let roadmap = read::roadmap(store, project).map_err(|error| scope_unread(&error))?; + let mut documents = vec![observed(ROADMAP_VIEW, roadmap_key(), roadmap_seq)]; + let held = roadmap + .phases + .iter() + .find(|held| held.number == phase && held.status != WITHDRAWN); + let committed = held.map(|held| held.stories.clone()).unwrap_or_default(); + let mut selected = Vec::with_capacity(stories.len()); + for id in stories { + let truths = store + .get(project, TRUTHS_VIEW, &truths_key(*id)) + .map_err(busy)?; + documents.push(observed( + TRUTHS_VIEW, + truths_key(*id), + truths.as_ref().map(|document| document.produced_seq), + )); + // An approved truth is one the `truths` document lists (D-10). + let refined = truths + .as_ref() + .and_then(|document| document.body.get("truths")) + .and_then(Value::as_array) + .is_some_and(|listed| !listed.is_empty()); + let entry = roadmap + .stories + .iter() + .find(|story| story.id == *id && story.status != DROPPED); + selected.push(SelectedStory { + id: *id, + held: entry.is_some(), + phase: entry.and_then(|story| story.phase), + refined, + }); + } + Ok(ReadinessRead { + phase, + phase_held: held.is_some(), + committed, + active: active_phases(store, project)?, + stories: selected, + documents, + }) +} + +/// The refusal for `refusal`, a readiness judgement's, at `slot`, its reason +/// ending `not_done` and its details naming the story, phase or order. +pub fn readiness_refused(refusal: &CommitmentRefusal, slot: &str, not_done: &str) -> Value { + let reason = match refusal { + CommitmentRefusal::PhaseActive { phase } => format!( + "phase {phase} is active, and one phase is planned at a time, so {not_done}. A phase stays active until it is completed or withdrawn" + ), + CommitmentRefusal::NoSuchPhase { phase } => { + format!("this project has no phase {phase} that can be planned, so {not_done}") + } + CommitmentRefusal::NoSuchStory { story } => { + format!("this project has no story {story} that can be committed, so {not_done}") + } + CommitmentRefusal::StoryUnrefined { story } => format!( + "story {story} holds no approved truth, so it cannot be committed and {not_done}. It is refined with story-refine first" + ), + CommitmentRefusal::StoryInPhase { story, phase } => format!( + "story {story} is committed to phase {phase}, and a story belongs to one phase at most, so {not_done}" + ), + CommitmentRefusal::PlannerOrderPending { work_order } => format!( + "the phase's planner work order {work_order} is still pending, and a phase has one live planner order, so {not_done}" + ), + }; + Refusal::new(refusal.code(), reason) + .slot(slot) + .details(refusal.details()) + .value() +} + +/// What `phase-plan`'s check found, which the run records and observes. +#[derive(Debug, Clone, PartialEq)] +pub struct Checked { + /// The phase being planned. + phase: u32, + /// The selection, in order. + stories: Vec, + /// The path the commitment judge chose. + path: Planned, + /// The documents the check read, at the sequence that produced each. + documents: Vec, + /// What a recording relies on being absent beside its own. + absences: Vec, +} + +/// A judged path, with what its run needs. +#[derive(Debug, Clone, PartialEq)] +enum Planned { + /// Hand over the order the commitment's approval issued. + HandOver(Box), + /// Record the `phase edit` of the stories with its continuation. + Draft(PhaseFields), + /// Issue the revision of the phase's current draft and its set. + Revision { draft: Hash, set: String }, + /// Issue a planning order. + Planning, +} + +/// The latest continuation as the `phase_plan` document holds it. +pub(crate) struct Latest { + /// The selection it binds, in order. + pub stories: Vec, + /// The `phase edit` draft it was recorded with. + pub edit: Hash, + /// The planner order its approval issues. + pub work_order: String, + /// Whether that order was handed to a session. + pub followed: bool, +} + +/// `phase-plan`'s check for phase `phase` of `project` with the selection +/// `stories`, run before admission and recording nothing. It gathers the +/// readiness facts, the phase's `phase_plan` document with its latest +/// continuation and current draft, the phase's pending planner order and +/// the continuation's order's state from `work_order`, and whether the +/// current draft's set closed with an answer that rejected a recommendation, +/// then judges them (D-10, D-11, D-15). A refusal names its code at slot +/// `phase`, `stories` or `operation`. A changed selection's `phase edit` is +/// judged and checked against accepted scope here, its refusals at slot +/// `stories`; a hand-over is read here, so an order no longer pending is +/// refused here. A read fault is the `failed` answer. +pub fn check( + store: &S, + project: &ProjectId, + phase: u32, + stories: &[u32], +) -> Result { + let readiness = read_readiness(store, project, phase, stories)?; + let mut documents = readiness.documents().to_vec(); + let key = phase_plan_key(phase); + let phase_plan = store.get(project, PHASE_PLAN_VIEW, &key).map_err(busy)?; + documents.push(observed( + PHASE_PLAN_VIEW, + key, + phase_plan.as_ref().map(|document| document.produced_seq), + )); + let body = phase_plan.map(|document| document.body); + let pending = pending_planner(store, project, phase).map_err(busy)?; + let latest = latest_continuation(body.as_ref())?; + let latest_pending = match &latest { + Some(latest) => crate::work_order::read::order(store, project, &latest.work_order) + .map_err(busy)? + .is_some_and(|order| order.get("state").and_then(Value::as_str) == Some(PENDING)), + None => false, + }; + let (revision, revision_due) = match current_draft(body.as_ref())? { + Some((draft, set)) => match read_set(store, project, &set).map_err(busy)? { + SetRead::Held(held) => { + documents.push(observed( + QUESTIONS_VIEW, + questions_key(&set), + Some(held.produced_seq), + )); + let due = held.round.state == SetState::Closed + && held.facts.answers.iter().any(|answer| !answer.accepted); + (Some((draft, set)), due) + } + SetRead::NotHeld | SetRead::Unreadable(_) => return Err(unreadable(QUESTIONS_VIEW)), + }, + None => (None, false), + }; + let facts = CommitmentFacts { + readiness: readiness.readiness(), + committed: readiness.committed(), + pending_order: pending.as_deref(), + continuation: latest.as_ref().map(|latest| Continuation { + stories: &latest.stories, + work_order: &latest.work_order, + pending: latest_pending, + followed: latest.followed, + }), + revision_due, + }; + let path = match judge_commitment(&facts).map_err(|refusal| refused(phase, &refusal))? { + PhasePlanPath::HandOver { work_order } => { + // The judge hands over only the latest continuation's order. + let edit = latest + .as_ref() + .map(|latest| latest.edit) + .ok_or_else(|| unreadable(PHASE_PLAN_VIEW))?; + // The hand-over observes what this check read, so a phase made + // active or a story unrefined since it is not handed over. + let read = read_hand_over(store, project, phase, edit, &work_order)? + .observing(&documents, readiness.absences()); + Planned::HandOver(Box::new(read)) + } + PhasePlanPath::Draft => { + let members = json!({"phase": phase, "stories": stories}); + let change = judge_change(ChangeKind::PhaseEdit, &members) + .map_err(|refusal| at_stories(submission_refused(&refusal)))?; + check_change(store, project, &change).map_err(at_stories)?; + Planned::Draft(PhaseFields { + stories: Some(stories.to_vec()), + ..PhaseFields::default() + }) + } + PhasePlanPath::Revision => match revision { + Some((draft, set)) => Planned::Revision { draft, set }, + // A revision is due only over a current draft. + None => return Err(unreadable(PHASE_PLAN_VIEW)), + }, + PhasePlanPath::Planning => Planned::Planning, + }; + Ok(Checked { + phase, + stories: stories.to_vec(), + path, + absences: readiness.absences(), + documents, + }) +} + +/// Runs the path `checked` judged under `command`, the command its caller +/// prepared. A changed selection records the `phase edit` of the stories +/// with its continuation naming `id` as the order its approval issues, and +/// answers with the recorded receipt: the draft's digest, its kind, the time +/// it was recorded, the phase, the selection and the commands `baley scope +/// preview ` and `baley scope approve `, issuing no order +/// (D-09), so a replay answered from the record gets the same answer. A +/// planning order, or the due revision, is issued as `id` for the selection +/// under `policy`, the host's effective policy, for `host` with the catalog +/// `names` (D-15); its +/// decision declares no pending planner order of the phase and observes the +/// check's documents and the inputs'. An approved continuation's order is +/// handed over (D-01), observing the check's documents and declaring its +/// absences beside the hand-over's own. +#[allow(clippy::too_many_arguments)] +pub fn run( + store: &S, + command: &Command, + checked: &Checked, + policy: &EffectivePolicy, + host: Host, + names: &AcceptedNames, + id: &str, +) -> Value { + let phase = checked.phase; + let revision = match &checked.path { + Planned::HandOver(read) => return order::hand_over(store, command, read), + Planned::Draft(fields) => { + let continuation = PlanningContinuation { + stories: &checked.stories, + work_order: id, + documents: &checked.documents, + absences: &checked.absences, + }; + return submit_planning_edit(store, command, phase, fields, continuation) + .unwrap_or_else(|answer| answer); + } + Planned::Revision { draft, set } => Some(Revision { + draft: *draft, + set: set.as_str(), + }), + Planned::Planning => None, + }; + let prepared = match order::prepare( + store, + command, + phase, + &checked.stories, + revision, + policy, + host, + names, + id, + ) { + Ok(prepared) => prepared, + Err(answer) => return answer, + }; + let mut absences = planner_absences(phase); + absences.extend(checked.absences.iter().cloned()); + let documents: Vec = prepared + .documents() + .iter() + .chain(&checked.documents) + .cloned() + .collect(); + let result = store.transact(command, &mut |tx| { + let mut receipt = Map::new(); + receipt.insert("status".into(), json!("ok")); + receipt.extend(prepared.issue_within(tx, &command.recorded_at)?); + Ok(Decision { + kind: OutcomeKind::Done, + answer: Value::Object(receipt), + sensitive: false, + observed: Observed { + absences: absences.clone(), + documents: documents.clone(), + ..Observed::default() + }, + git: None, + }) + }); + issue::answer(result, store) +} + +/// The refusal a `phase-plan` call gets for `refusal`: a pending planner +/// order at slot `operation` as a retry beside one gets it, an active phase +/// there too, the phase at `phase` and a story at `stories`. +fn refused(phase: u32, refusal: &CommitmentRefusal) -> Value { + let slot = match refusal { + CommitmentRefusal::PlannerOrderPending { work_order } => { + return planner_order_pending( + phase, + work_order, + "so no other planner order was issued", + ); + } + CommitmentRefusal::PhaseActive { .. } => "operation", + CommitmentRefusal::NoSuchPhase { .. } => "phase", + _ => "stories", + }; + readiness_refused(refusal, slot, "nothing was recorded") +} + +/// A refusal of the drafted edit, put at slot `stories`, the only member a +/// session sent. A `failed` answer is returned as it is. +fn at_stories(mut answer: Value) -> Value { + if answer["status"] == "refused" { + answer["slot"] = json!("stories"); + } + answer +} + +/// The latest continuation a `phase_plan` document holds, or none. One +/// that cannot be read is a ledger fault. +pub(crate) fn latest_continuation(body: Option<&Value>) -> Result, Value> { + let latest = match body.and_then(|body| body.get("continuation")) { + None | Some(Value::Null) => return Ok(None), + Some(latest) => latest, + }; + let read = || -> Option { + let stories = latest + .get("stories")? + .as_array()? + .iter() + .map(|story| story.as_u64().and_then(|story| u32::try_from(story).ok())) + .collect::>>()?; + Some(Latest { + stories, + edit: Hash::from_hex(latest.get("edit")?.as_str()?)?, + work_order: latest.get("work_order")?.as_str()?.to_owned(), + followed: latest.get("followed")?.as_bool()?, + }) + }; + read().map(Some).ok_or_else(|| unreadable(PHASE_PLAN_VIEW)) +} + +/// The phase's current unapproved draft and its set, or none. +fn current_draft(body: Option<&Value>) -> Result, Value> { + let draft = match body.and_then(|body| body.get("draft")) { + None | Some(Value::Null) => return Ok(None), + Some(draft) => draft, + }; + let digest = draft + .get("digest") + .and_then(Value::as_str) + .and_then(Hash::from_hex); + let set = draft.get("set").and_then(Value::as_str); + match (digest, set) { + (Some(digest), Some(set)) => Ok(Some((digest, set.to_owned()))), + _ => Err(unreadable(PHASE_PLAN_VIEW)), + } +} + +/// Every active phase in number order, read from `phase_plan`'s status +/// index page by page. +fn active_phases(store: &S, project: &ProjectId) -> Result, Value> { + let mut phases = Vec::new(); + let mut after = None; + loop { + let query = IndexQuery { + index: PHASE_PLAN_STATUS_INDEX.into(), + equals: active_prefix(), + page: PageRequest { + limit: ACTIVE_PAGE, + after, + }, + }; + let page = store.find(project, PHASE_PLAN_VIEW, &query).map_err(busy)?; + for document in &page.items { + let phase = document + .body + .get("phase") + .and_then(Value::as_u64) + .and_then(|phase| u32::try_from(phase).ok()) + .ok_or_else(|| unreadable(PHASE_PLAN_VIEW))?; + phases.push(phase); + } + match page.next { + Some(next) => after = Some(next), + None => return Ok(phases), + } + } +} + +/// The status index prefix of the active phases. +fn active_prefix() -> Vec { + vec![KeyValue::Text(ACTIVE.into())] +} + +/// The sequence that produced the document `key` of `view`, or none. +fn produced( + store: &S, + project: &ProjectId, + view: &str, + key: DocKey, +) -> Result, Value> { + Ok(store + .get(project, view, &key) + .map_err(busy)? + .map(|document| document.produced_seq)) +} + +fn observed(view: &str, key: DocKey, produced_seq: Option) -> ObservedDocument { + ObservedDocument { + view: view.into(), + key, + produced_seq, + } +} + +fn busy(error: StoreError) -> Value { + store_failed(&error, NOT_RECORDED_BUSY) +} + +fn unreadable(view: &str) -> Value { + failed( + LEDGER_UNAVAILABLE, + format!("the {view} view document cannot be read, so nothing was recorded"), + PLACE_LEDGER, + ) +} + +#[cfg(test)] +pub(crate) mod tests { + //! Stores are real SQLite stores in fresh temporary directories, with + //! times supplied; expected answers are written out from design 0005 + //! section 5, design 0004's `phase edit`, D-02, D-09 to D-11, D-15 and + //! the plan's data store C, P0, N0 and PL2, never from running this code. + //! The digests are `sha256sum` over each edit's canonical body. + + use baley_store_sqlite::SqliteStore; + + use super::*; + use crate::planning::fixtures::*; + use crate::planning::order::tests::O; + use crate::refine::order::tests::{input_body, input_names, issued}; + use crate::scope::fixtures::*; + + /// The `[1, 4]` edit of phase 1, `{"kind":"phase-edit","phase":1,"stories":[1,4]}`. + pub(crate) const E1_DIGEST: &str = + "8eabf037f141c7d617bbb783e762cfb4622014a0927fcad74d0b2feef8dc0de1"; + + /// Phase 1's `phase-plan` with `stories`, checked and run under P0 and + /// N0 as `request_id` at `at`, naming `id` as its order. + pub(crate) fn planned( + store: &SqliteStore, + stories: &[u32], + request_id: &str, + at: &str, + id: &str, + ) -> Value { + let checked = check(store, &project(), 1, stories).expect("the call passes its check"); + run( + store, + &command(PHASE_PLAN_COMMAND, request_id, 7, at), + &checked, + &p0(), + Host::ClaudeCode, + &n0(), + id, + ) + } + + /// The story ids an order's `stories` input binds, in order. + pub(crate) fn bound_stories(store: &SqliteStore, event: &baley_store::Event) -> Vec { + input_body(store, event, "stories") + .as_array() + .expect("the stories input is a list") + .iter() + .map(|story| story["id"].as_u64().unwrap()) + .collect() + } + + /// The check of phase `phase` with `stories`, which must refuse with + /// `code` at `slot` and record nothing. + fn refused_with( + store: &SqliteStore, + phase: u32, + stories: &[u32], + code: &str, + slot: &str, + ) -> Value { + let before = head(store); + let refusal = check(store, &project(), phase, stories).expect_err("the call is refused"); + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], code, "{refusal}"); + assert_eq!(refusal["slot"], slot, "{refusal}"); + assert_eq!(head(store), before); + refusal + } + + #[test] + fn a_phase_plan_refusal_recording_anything_is_caught() { + let (_dir, store) = store_c(); + let refusal = refused_with(&store, 9, &[1], "no-such-phase", "phase"); + assert_eq!(refusal["details"], json!({"phase": 9})); + let refusal = refused_with(&store, 1, &[1, 9], "no-such-story", "stories"); + assert_eq!(refusal["details"], json!({"story": 9})); + let refusal = refused_with(&store, 1, &[1, 3], "story-unrefined", "stories"); + assert_eq!(refusal["details"], json!({"story": 3})); + let refusal = refused_with(&store, 1, &[1, 2], "story-in-phase", "stories"); + assert_eq!(refusal["details"], json!({"story": 2, "phase": 2})); + refused_with(&store, 1, &[1, 4, 4], "malformed-submission", "stories"); + + activate_phase_2(&store, R1); + let refusal = refused_with(&store, 1, &[1], "phase-active", "operation"); + assert_eq!(refusal["details"], json!({"phase": 2})); + } + + #[test] + fn an_unchanged_selection_ordered_twice_or_a_changed_one_ordered_at_all_is_caught() { + let (_dir, store) = store_c(); + let answer = planned(&store, &[1], R1, T4, O); + assert_eq!(answer["status"], "ok", "{answer}"); + assert_eq!(answer["work_order"], O, "{answer}"); + let orders = issued(&store); + assert_eq!(orders.len(), 1); + assert_eq!(orders[0].payload["subject"], "phase/1"); + assert_eq!(bound_stories(&store, &orders[0]), [1]); + + let refusal = refused_with(&store, 1, &[1], "planner-order-pending", "operation"); + assert_eq!(refusal["details"], json!({"work_order": O})); + + let (_dir, store) = store_c(); + let answer = planned(&store, &[1, 4], R1, T4, O); + assert_eq!( + answer, + json!({"status": "ok", "digest": E1_DIGEST, "kind": "phase-edit", + "recorded_at": T4, "phase": 1, "stories": [1, 4], + "preview": format!("baley scope preview {E1_DIGEST}"), + "approve": format!("baley scope approve {E1_DIGEST}")}) + ); + let events = history(&store); + let edits: Vec<_> = of_type(&events, "scope.submitted") + .into_iter() + .filter(|event| event.payload["kind"] == "phase-edit") + .collect(); + assert_eq!(edits.len(), 1); + assert_eq!(of_type(&events, "plan.continuation").len(), 1); + assert!(issued(&store).is_empty()); + } + + #[test] + fn a_phase_plan_landing_beside_a_newly_active_phase_is_caught() { + let (_dir, store) = store_c(); + let checked = check(&store, &project(), 1, &[1]).expect("nothing is active yet"); + activate_phase_2(&store, R1); + let before = head(&store); + let answer = run( + &store, + &command(PHASE_PLAN_COMMAND, R2, 7, T6), + &checked, + &p0(), + Host::ClaudeCode, + &n0(), + O, + ); + assert_eq!(answer["status"], "failed", "{answer}"); + assert_eq!(answer["code"], "ledger-busy", "{answer}"); + assert_eq!(head(&store), before); + assert!(issued(&store).is_empty()); + } + + #[test] + fn a_replayed_draft_answered_without_its_phase_plan_members_is_caught() { + let (_dir, store) = store_c(); + let first = planned(&store, &[1, 4], R1, T4, O); + assert_eq!(first["status"], "ok", "{first}"); + // A retry of the same request is answered from its record, as + // `mcp::planning::serve` answers a replay, so it must be the first + // answer whole. + let replayed = issue::answer( + issue::record(&store, &command(PHASE_PLAN_COMMAND, R1, 7, T5), None), + &store, + ); + assert_eq!(replayed, first); + assert_eq!( + replayed, + json!({"status": "ok", "digest": E1_DIGEST, "kind": "phase-edit", + "recorded_at": T4, "phase": 1, "stories": [1, 4], + "preview": format!("baley scope preview {E1_DIGEST}"), + "approve": format!("baley scope approve {E1_DIGEST}")}) + ); + } + + #[test] + fn a_draft_landing_beside_a_newly_active_phase_is_caught() { + let (_dir, store) = store_c(); + let checked = check(&store, &project(), 1, &[1, 4]).expect("nothing is active yet"); + activate_phase_2(&store, R1); + let before = head(&store); + let answer = run( + &store, + &command(PHASE_PLAN_COMMAND, R2, 7, T6), + &checked, + &p0(), + Host::ClaudeCode, + &n0(), + O, + ); + assert_eq!(answer["status"], "failed", "{answer}"); + assert_eq!(answer["code"], "ledger-busy", "{answer}"); + assert_eq!(head(&store), before); + assert!(of_type(&history(&store), "plan.continuation").is_empty()); + } + + #[test] + fn a_due_revision_issued_as_a_planning_order_is_caught() { + let (_dir, store) = store_c(); + let (draft, _set) = pl2_rejected(&store, R1, R2); + let answer = planned(&store, &[1], R3, T6, O); + assert_eq!(answer["status"], "ok", "{answer}"); + let orders = issued(&store); + assert_eq!(orders.len(), 1); + assert_eq!( + input_names(&orders[0]), + [ + "phase", + "stories", + "description", + "approved_items", + "draft", + "questions" + ] + ); + assert_eq!(input_body(&store, &orders[0], "draft"), draft); + let questions = input_body(&store, &orders[0], "questions"); + assert_eq!(questions["answers"][0]["question"], "q1"); + assert_eq!(questions["answers"][0]["answer"], "Postgres"); + assert_eq!(questions["answers"][0]["accepted"], false); + } + + #[test] + fn a_commitment_approval_rerun_issuing_a_second_order_or_losing_its_order_is_caught() { + use crate::planning::order::tests::O2; + + let (dir, store) = store_c(); + let e2 = edit(&store, &[4, 1], O, R1, T4); + let approved = approve_commitment(&store, e2, R2, T5); + assert_eq!(approved["status"], "ok", "{approved}"); + drop(store); + let store = reopen(&dir); + + let answer = planned(&store, &[4, 1], R3, T6, O2); + assert_eq!(answer["status"], "ok", "{answer}"); + assert_eq!(answer["work_order"], O, "{answer}"); + assert_eq!( + answer["prompt"], + format!("Read Baley work order {O} and follow it.") + ); + assert_eq!(answer["launch"], approved["launch"], "{answer}"); + let events = history(&store); + let followed = of_type(&events, "plan.continuation_followed"); + assert_eq!(followed.len(), 1); + assert_eq!( + followed[0].payload, + json!({"phase": 1, "edit": e2.to_hex(), "work_order": O}) + ); + let orders = issued(&store); + assert_eq!(orders.len(), 1); + assert_eq!(orders[0].payload["subject"], "phase/1"); + + let refusal = refused_with(&store, 1, &[4, 1], "planner-order-pending", "operation"); + assert_eq!(refusal["details"], json!({"work_order": O})); + } + + /// Store C with the `[4, 1]` edit E2 approved through the commitment + /// approval's two steps, issuing O, and phase 1's `phase-plan` with + /// `[4, 1]` checked, so its run hands O over. + fn hand_over_checked() -> (tempfile::TempDir, SqliteStore, Checked) { + let (dir, store) = store_c(); + let e2 = edit(&store, &[4, 1], O, R1, T4); + let approved = approve_commitment(&store, e2, R2, T5); + assert_eq!(approved["status"], "ok", "{approved}"); + let checked = check(&store, &project(), 1, &[4, 1]).expect("O is handed over"); + (dir, store, checked) + } + + /// The run of `checked`, which must fail `ledger-busy` with nothing + /// recorded and O not handed over. + fn handed_over_busy(store: &SqliteStore, checked: &Checked) { + use crate::planning::order::tests::O2; + + let before = head(store); + let answer = run( + store, + &command(PHASE_PLAN_COMMAND, R4, 7, T7), + checked, + &p0(), + Host::ClaudeCode, + &n0(), + O2, + ); + assert_eq!(answer["status"], "failed", "{answer}"); + assert_eq!(answer["code"], "ledger-busy", "{answer}"); + assert_eq!(head(store), before); + assert!(of_type(&history(store), "plan.continuation_followed").is_empty()); + } + + #[test] + fn a_hand_over_landing_beside_a_newly_active_phase_or_an_unrefined_story_is_caught() { + // Phase 2 made active after the check, which a fresh check refuses + // `phase-active`. + let (_dir, store, checked) = hand_over_checked(); + activate_phase_2(&store, R3); + handed_over_busy(&store, &checked); + + // Story 4's approved truths emptied after the check, which a fresh + // check refuses `story-unrefined`. + let (_dir, store, checked) = hand_over_checked(); + append( + &store, + R3, + T6, + vec![refined( + 4, + "4f4f4f4f-4f4f-4f4f-8f4f-4f4f4f4f4f4f", + Vec::new(), + )], + ); + handed_over_busy(&store, &checked); + } +} diff --git a/crates/baley/src/planning/read.rs b/crates/baley/src/planning/read.rs new file mode 100644 index 00000000..30dbeea4 --- /dev/null +++ b/crates/baley/src/planning/read.rs @@ -0,0 +1,394 @@ +//! A phase's approved plans read back with their evidence maps (design 0005 +//! section 6 Views, design 0001 Appendix B `plan-read`, PLN-R4, PLN-R14, +//! PLN-R15, D-07, D-17). `plan-read` over MCP and `baley plan show` both +//! read through here, so the session and the owner see the same thing. +//! +//! Only the views an approval writes are read, `phase_plan`, `plan` and +//! `evidence_map`, so a draft's map never appears. A replaced plan is read +//! with the rest, its map unchanged. Readiness is worked out here from the +//! `truths` view each time and never stored, so a truth revised after an +//! approval shows at once. Nothing is appended. + +use std::collections::BTreeMap; +use std::collections::btree_map::Entry; + +use baley_core::plan::{ + EVIDENCE_MAP_VIEW, PHASE_PLAN_VIEW, PLAN_VIEW, approved_items, evidence_map_key, + phase_plan_key, plan_key, +}; +use baley_core::truth::{TRUTHS_VIEW, truths_key}; +use baley_store::{DocKey, ProjectId, Views}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::scope::read::{ReadError, roadmap}; + +/// A phase's approved plans, in plan-number order. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct PhasePlans { + /// The phase's number. + pub phase: u32, + /// Every plan ever approved in the phase, replaced ones included. + pub plans: Vec, +} + +/// One approved plan joined with its evidence map. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ApprovedPlan { + /// Its number in the phase, never reused. + pub plan: u32, + /// The digest the owner approved. + pub digest: String, + /// The stories it serves. + pub stories: Vec, + /// Its size in tasks. + pub size: u64, + /// The suite command it was approved with, or none. + pub suite: Option, + /// The id of its draft's question set. + pub set: String, + /// The owner who approved it. + pub owner: String, + /// When it was approved. + pub at: String, + /// `approved` or `replaced`. + pub state: String, + /// The digest of the plan that replaced it, or none. + pub replaced_by: Option, + /// Whether its items still name their truths' current versions. + pub readiness: Readiness, + /// Its evidence items, whole, as approved. + pub items: Vec, +} + +/// A plan's readiness, worked out when read. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Readiness { + /// True when every item names its truth's current version. + pub ready: bool, + /// The ids of the items bound to a version that is not current. + pub not_ready: Vec, +} + +/// Reads phase `phase` of `project`'s approved plans, recording nothing: a +/// phase the roadmap does not hold is `ReadError::NoSuchPhase`; its plans +/// are the ones its `phase_plan` document lists, in plan-number order, +/// replaced ones included, each joined from its `plan` and `evidence_map` +/// documents; each plan's readiness is worked out from the current truths +/// of the stories its items name. A plan listed with a document that is +/// missing or cannot be read is a ledger fault, never skipped. +pub fn read( + store: &S, + project: &ProjectId, + phase: u32, +) -> Result { + if !roadmap(store, project)? + .phases + .iter() + .any(|held| held.number == phase) + { + return Err(ReadError::NoSuchPhase); + } + let listed = match document::( + store, + project, + PHASE_PLAN_VIEW, + &phase_plan_key(phase), + )? { + Some(document) => document.plans, + None => Vec::new(), + }; + let mut numbers: Vec = listed.into_iter().map(|listed| listed.plan).collect(); + numbers.sort_unstable(); + let mut current = BTreeMap::new(); + let mut plans = Vec::with_capacity(numbers.len()); + for number in numbers { + let held = + document::(store, project, PLAN_VIEW, &plan_key(phase, number))? + .ok_or_else(|| unreadable(PLAN_VIEW))?; + let map = store + .get(project, EVIDENCE_MAP_VIEW, &evidence_map_key(phase, number)) + .map_err(ReadError::Store)? + .ok_or_else(|| unreadable(EVIDENCE_MAP_VIEW))? + .body; + let bound = approved_items(&map).ok_or_else(|| unreadable(EVIDENCE_MAP_VIEW))?; + let mut not_ready = Vec::new(); + for item in &bound { + let truths = match current.entry(item.story) { + Entry::Occupied(held) => held.into_mut(), + Entry::Vacant(empty) => empty.insert(versions(store, project, item.story)?), + }; + if truths.get(&item.truth) != Some(&item.truth_version) { + not_ready.push(item.id.clone()); + } + } + plans.push(ApprovedPlan { + plan: number, + digest: held.digest, + stories: held.stories, + size: held.size, + suite: held.suite, + set: held.question_set, + owner: held.owner, + at: held.at, + state: held.state, + replaced_by: held.replaced_by, + readiness: Readiness { + ready: not_ready.is_empty(), + not_ready, + }, + items: bound.into_iter().map(|item| item.definition).collect(), + }); + } + Ok(PhasePlans { phase, plans }) +} + +/// The `phase_plan` document as its projector writes it; only its plan +/// list is read. +#[derive(Deserialize)] +struct PhasePlanDocument { + plans: Vec, +} + +/// One plan as `phase_plan` lists it. +#[derive(Deserialize)] +struct ListedPlan { + plan: u32, +} + +/// The `plan` document as its projector writes it; the members a read does +/// not need are left out. +#[derive(Deserialize)] +struct PlanDocument { + digest: String, + stories: Vec, + size: u64, + suite: Option, + question_set: String, + owner: String, + at: String, + state: String, + replaced_by: Option, +} + +/// The `truths` document as its projector writes it; only the current +/// truths' ids and versions are read. +#[derive(Deserialize)] +struct TruthsDocument { + truths: Vec, +} + +/// One current truth's id and version. +#[derive(Deserialize)] +struct TruthVersion { + id: String, + version: u32, +} + +/// Story `story`'s current truth versions by id; none before its first +/// refinement. +fn versions( + store: &S, + project: &ProjectId, + story: u32, +) -> Result, ReadError> { + Ok( + document::(store, project, TRUTHS_VIEW, &truths_key(story))? + .map(|document| { + document + .truths + .into_iter() + .map(|truth| (truth.id, truth.version)) + .collect() + }) + .unwrap_or_default(), + ) +} + +/// One view document read as `T`, or none when the view holds no such key. +fn document Deserialize<'de>, S: Views + ?Sized>( + store: &S, + project: &ProjectId, + view: &str, + key: &DocKey, +) -> Result, ReadError> { + match store.get(project, view, key).map_err(ReadError::Store)? { + Some(document) => serde_json::from_value(document.body) + .map(Some) + .map_err(|_| unreadable(view)), + None => Ok(None), + } +} + +fn unreadable(view: &str) -> ReadError { + ReadError::Unreadable(format!("the {view} view document cannot be read")) +} + +#[cfg(test)] +pub(crate) mod tests { + //! Stores are real SQLite stores in fresh temporary directories, with + //! times supplied; expected values are written out from design 0001 + //! Appendix B `plan-read`, design 0005 section 6 Views, D-07, D-17 and + //! the plan's data store C, O, PL1 and PL2, with PL3 and PL1r given maps + //! of their own here, never from running this code. + + use baley_store::Hash; + use serde_json::json; + + use super::*; + use crate::planning::approve::tests::{approved, digest_of}; + use crate::planning::fixtures::*; + use crate::planning::order::tests::O; + use crate::planning::submit::tests::{order_o, plan_submitted}; + use crate::refine::submit::tests::{t1, t2}; + use crate::scope::fixtures::*; + + /// The approval of `digest` under P0, which must be `ok`. + fn approved_ok(store: &baley_store_sqlite::SqliteStore, digest: Hash, request: &str, at: &str) { + let answer = approved(store, digest, &p0(), request, at); + assert_eq!(answer["status"], "ok", "{answer}"); + } + + /// E3, a unit check of story 1's `t2` at version 1, where E2 checks it + /// at the integration level. + fn e3() -> Value { + json!({"id": "e3", "story": 1, "truth": "t2", "truth_version": 1, "kind": "check", + "spec": {"command": "cargo test round_unit", + "expected": {"kind": "literal", "value": "one round"}, + "test": {"file": "src/ledger.rs", "function": "one_round"}, + "setup": "a set answered once", "call": "read the round", + "level": "unit", "boundary": "the round read", "fakes": []}, + "reason": "a round read wrongly"}) + } + + /// PL3 with E1 alone, so plan 2's map differs from plan 1's. Plan 1's + /// E2 still checks `t2`, and a truth takes one check id in a phase. + fn pl3_e1() -> Value { + let mut plan = pl3(); + plan["evidence_map"] = json!([e1()]); + plan + } + + /// PL1r with E1 and E3, so the replacement checks `t2` at another level + /// than the plan it replaces. E2 leaves the phase with plan 1. + fn pl1r_e3() -> Value { + let mut plan = pl1r(); + plan["evidence_map"] = json!([e1(), e3()]); + plan + } + + /// The plan read expects for plan `plan` at `digest` with set `set`, + /// approved at `at`, carrying `items`, ready. + fn expected(plan: u32, digest: Hash, set: &Value, at: &str, items: Vec) -> ApprovedPlan { + ApprovedPlan { + plan, + digest: digest.to_hex(), + stories: vec![1], + size: 1, + suite: None, + set: set.as_str().expect("a set id").to_owned(), + owner: "Ada Owner".into(), + at: at.into(), + state: "approved".into(), + replaced_by: None, + readiness: Readiness { + ready: true, + not_ready: Vec::new(), + }, + items, + } + } + + #[test] + fn an_evidence_map_read_unapproved_out_of_order_or_changed_by_a_rebuild_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let first = plan_submitted(&store, &pl1(), O, None, R2, T5); + let x1 = digest_of(&first); + approved_ok(&store, x1, R3, T5); + let second = plan_submitted(&store, &pl3_e1(), O, None, R4, T6); + let x3 = digest_of(&second); + approved_ok(&store, x3, R5, T6); + let x2 = digest_of(&plan_submitted(&store, &pl2(), O, None, R6, T7)); + + // Each plan's map is its own: one read under another plan's key fails. + let one = expected(1, x1, &first["set"], T5, vec![e1(), e2()]); + let two = expected(2, x3, &second["set"], T6, vec![e1()]); + let read_1 = read(&store, &project(), 1).expect("phase 1 is read"); + assert_eq!( + read_1, + PhasePlans { + phase: 1, + plans: vec![one.clone(), two.clone()] + } + ); + assert!( + read_1.plans.iter().all(|plan| plan.digest != x2.to_hex()), + "a draft's map read as approved" + ); + // Each item keeps its truth's version and its check's level. + assert_eq!(read_1.plans[0].items[0]["truth"], "t1"); + assert_eq!(read_1.plans[0].items[0]["truth_version"], 1); + assert_eq!(read_1.plans[0].items[0]["spec"]["level"], "unit"); + assert_eq!(read_1.plans[0].items[1]["truth"], "t2"); + assert_eq!(read_1.plans[0].items[1]["spec"]["level"], "integration"); + + store.rebuild(&project()).expect("the views rebuild"); + assert_eq!(read(&store, &project(), 1).expect("read again"), read_1); + + let replaced = plan_replaced(&store, &pl1r_e3(), O, 1, x1, R7, T7); + let x1r = digest_of(&replaced); + approved_ok(&store, x1r, R8, T8); + let mut one_replaced = one.clone(); + one_replaced.state = "replaced".into(); + one_replaced.replaced_by = Some(x1r.to_hex()); + let three = expected(3, x1r, &replaced["set"], T8, vec![e1(), e3()]); + let after_replacement = read(&store, &project(), 1).expect("read after the replacement"); + assert_eq!( + after_replacement, + PhasePlans { + phase: 1, + plans: vec![one_replaced.clone(), two.clone(), three.clone()] + } + ); + // The replaced plan keeps E2 at integration, its replacement has E3 + // at unit. + assert_eq!(after_replacement.plans[0].items[1]["id"], "e2"); + assert_eq!( + after_replacement.plans[0].items[1]["spec"]["level"], + "integration" + ); + assert_eq!(after_replacement.plans[2].items[1]["id"], "e3"); + assert_eq!(after_replacement.plans[2].items[1]["spec"]["level"], "unit"); + + let revised = with_version(t1(), 2); + append( + &store, + R9, + T9, + vec![refined( + 1, + "1a1a1a1a-1a1a-4a1a-8a1a-1a1a1a1a1a1a", + vec![revised, versioned(t2())], + )], + ); + let stale = Readiness { + ready: false, + not_ready: vec!["e1".into()], + }; + let after = read(&store, &project(), 1).expect("read after the revision"); + for (plan, before) in after.plans.iter().zip([&one_replaced, &two, &three]) { + assert_eq!(plan.readiness, stale, "plan {}", plan.plan); + assert_eq!(plan.items, before.items, "plan {}", plan.plan); + assert_eq!(plan.items[0]["truth_version"], 1, "plan {}", plan.plan); + } + assert_eq!(after.plans.len(), 3); + } + + /// `truth` at `version`. + fn with_version(truth: Value, version: u32) -> Value { + let mut truth = truth; + truth["version"] = json!(version); + truth + } +} diff --git a/crates/baley/src/planning/replace.rs b/crates/baley/src/planning/replace.rs new file mode 100644 index 00000000..5ba8f15b --- /dev/null +++ b/crates/baley/src/planning/replace.rs @@ -0,0 +1,347 @@ +//! `plan replace` (design 0005 section 5, PLN-R14, D-04, D-07): a session +//! submits a planner's plan to replace an approved plan in force, named by +//! its number and the digest it was approved at. +//! +//! A replacement is checked as a submit is, then judged by the replacement +//! judge over the phase's plans in force, and the new plan is judged as if +//! the replaced one were gone. It is recorded as a submit records, on the +//! phase's one draft line, its body naming the plan it replaces. The +//! owner's approval judges the replacement again and records `plan.approved` +//! with a new number and `plan.replaced` together. + +use std::num::NonZeroU32; + +use baley_core::plan::{ + IN_FORCE, PlanFacts, PlanInForce, ReplacementFacts, ReplacementRefusal, Replaces, + judge_replacement, +}; +use baley_store::{Hash, ProjectId, Views}; +use serde_json::Value; + +use crate::envelope::Refusal; +use crate::mcp::capture::{PLACE_LEDGER, failed}; +use crate::mcp::prepare::LEDGER_UNAVAILABLE; +use crate::planning::facts::PhaseFacts; +use crate::planning::submit::{self, Checked}; + +/// The check of the plan `submitted` replacing `replaces`, answering work +/// order `work_order` under `capacity`, run before admission and recording +/// nothing (D-04): the submit's check in its order, the order and +/// `phase-not-active` first; then the replacement, `no-such-plan` or +/// `admitted-plan` at slot `replaces`; then the plan judged by `judge_plan` +/// with the replaced plan's tasks off the phase's size and its items off the +/// approved items. `submit::record` records what it accepts, its draft body +/// naming the plan replaced. +pub fn check( + store: &S, + project: &ProjectId, + submitted: &Value, + work_order: &str, + replaces: Replaces, + capacity: Option, +) -> Result { + submit::checked( + store, + project, + submitted, + work_order, + Some(replaces), + capacity, + ) +} + +/// The facts the new plan of phase `phase` replacing `replaces` is judged +/// under: the replacement judged over the plans in force that `read`'s +/// `phase_plan` document lists and the admitted observation, a refusal at +/// slot `replaces` with its reason ending `not_done`. The submit's check and +/// the approval's first step both take them here, so an approval judges the +/// replacement again on the phase as it stands then. +pub(crate) fn facts_without( + store: &S, + project: &ProjectId, + phase: u32, + replaces: Replaces, + read: &PhaseFacts, + not_done: &str, +) -> Result { + let in_force = in_force(read.phase_plan.as_ref())?; + judge_replacement( + replaces, + &ReplacementFacts { + in_force: &in_force, + admitted: admitted(store, project, phase, replaces.plan), + phase: &read.facts, + }, + ) + .map_err(|refusal| replacement_refused(&refusal, not_done)) +} + +/// Whether plan `plan` of phase `phase`'s execution is admitted. Nothing +/// records admission until Build 5, so this reads false; Build 5's execution +/// admission makes it a read of the ledger here, the one seam the +/// `admitted-plan` refusal waits on (decision 15 of the Build 4 plan). +fn admitted(_store: &S, _project: &ProjectId, _phase: u32, _plan: u32) -> bool { + false +} + +/// The plans in force a `phase_plan` document lists, none before anything +/// was projected for the phase. A document that cannot be read is a ledger +/// fault. +fn in_force(phase_plan: Option<&Value>) -> Result, Value> { + let Some(body) = phase_plan else { + return Ok(Vec::new()); + }; + let plans = body + .get("plans") + .and_then(Value::as_array) + .ok_or_else(unreadable)?; + let mut held = Vec::new(); + for plan in plans { + if plan.get("state").and_then(Value::as_str) != Some(IN_FORCE) { + continue; + } + let whole = |name: &str| { + plan.get(name) + .and_then(Value::as_u64) + .and_then(|value| u32::try_from(value).ok()) + }; + let digest = plan + .get("digest") + .and_then(Value::as_str) + .and_then(Hash::from_hex); + let (Some(number), Some(digest), Some(size)) = (whole("plan"), digest, whole("size")) + else { + return Err(unreadable()); + }; + held.push(PlanInForce { + plan: number, + digest, + size, + }); + } + Ok(held) +} + +/// The refusal for a replacement, at slot `replaces`, naming the plan. +fn replacement_refused(refusal: &ReplacementRefusal, not_done: &str) -> Value { + let reason = match refusal { + ReplacementRefusal::NoSuchPlan { plan } => format!( + "no plan {plan} of the phase is in force at that digest: it was replaced, never approved, or approved at another digest, so {not_done}" + ), + ReplacementRefusal::AdmittedPlan { plan } => format!( + "plan {plan} is admitted to execution and can no longer be replaced, so {not_done}" + ), + }; + Refusal::new(refusal.code(), reason) + .slot("replaces") + .details(refusal.details()) + .value() +} + +fn unreadable() -> Value { + failed( + LEDGER_UNAVAILABLE, + "the phase_plan view document cannot be read, so nothing was recorded", + PLACE_LEDGER, + ) +} + +#[cfg(test)] +mod tests { + //! Stores are real SQLite stores in fresh temporary directories, with + //! times supplied; expected answers are written out from design 0005 + //! sections 5 and 6, D-04, D-07 and the plan's data store C, P0, PL1, + //! PL1r, PL1rr, PL1d and PL3, never from running this code. + + use baley_core::plan::{EVIDENCE_MAP_VIEW, PHASE_PLAN_VIEW, PLAN_VIEW, phase_plan_key}; + use baley_core::plan::{evidence_map_key, plan_key}; + use baley_store::{Hash, Views}; + use baley_store_sqlite::SqliteStore; + use serde_json::json; + + use super::*; + use crate::planning::approve::tests::{approved, digest_of}; + use crate::planning::fixtures::*; + use crate::planning::order::tests::O; + use crate::planning::submit::tests::{order_o, plan_submitted}; + use crate::scope::fixtures::*; + + /// The request ids of the second test, apart from store C's and R1 to + /// R9. + const R10: &str = "6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9d"; + const R11: &str = "7b8c9d0e-1f2a-4b3c-9d4e-5f6a7b8c9d0e"; + + /// PL1r: PL1 with goal `Record every step, revised`. + fn pl1r() -> Value { + let mut plan = pl1(); + plan["goal"] = json!("Record every step, revised"); + plan + } + + /// PL1rr: PL1 with goal `Record every step, third`. + fn pl1rr() -> Value { + let mut plan = pl1(); + plan["goal"] = json!("Record every step, third"); + plan + } + + /// PL1d: PL1r with a second task `k3`, as K with id `k3`. + fn pl1d() -> Value { + let mut plan = pl1r(); + let mut k3 = k(); + k3["id"] = json!("k3"); + plan["tasks"] = json!([k(), k3]); + plan + } + + /// Submits `plan` replacing plan `number` at `digest`, answering order + /// `order` under `capacity`, through the check and the submit's + /// recording, as `plan-replace` runs them below the session. + fn plan_replaced( + store: &SqliteStore, + plan: &Value, + number: u32, + digest: Hash, + capacity: Option, + request_id: &str, + at: &str, + ) -> Value { + let capacity = capacity.map(|capacity| NonZeroU32::new(capacity).unwrap()); + let replaces = Replaces { + plan: number, + digest, + }; + let checked = match check(store, &project(), plan, O, replaces, capacity) { + Ok(checked) => checked, + Err(refusal) => return refusal, + }; + let mut command = command("plan.replace", request_id, 8, at); + let on = caller() + .with_work_order(O) + .unwrap() + .with_instructions(checked.evidence.clone()) + .unwrap(); + command.caller = Some(baley_store::Caller::Server(on)); + crate::scope::submit::answer(submit::record(store, &command, Some(&checked)), store) + } + + /// The approval of `digest` under P0, which must be `ok`. Gives the + /// answer. + fn approved_ok(store: &SqliteStore, digest: Hash, request_id: &str, at: &str) -> Value { + let answer = approved(store, digest, &p0(), request_id, at); + assert_eq!(answer["status"], "ok", "{answer}"); + answer + } + + #[test] + fn a_plan_number_reused_or_a_replacement_keeping_the_old_number_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R2, T5)); + assert_eq!(approved_ok(&store, x1, R3, T5)["plan"], 1); + let x3 = digest_of(&plan_submitted(&store, &pl3(), O, None, R4, T6)); + assert_eq!(approved_ok(&store, x3, R5, T6)["plan"], 2); + + let x1r = digest_of(&plan_replaced(&store, &pl1r(), 1, x1, None, R6, T7)); + let third = approved_ok(&store, x1r, R7, T7); + assert_eq!(third["plan"], 3, "{third}"); + let events = history(&store); + let recorded: Vec<_> = events + .iter() + .filter(|event| event.request_id.0 == R7) + .filter(|event| event.type_name.starts_with("plan.")) + .collect(); + assert_eq!(recorded.len(), 2, "{recorded:?}"); + assert_eq!(recorded[0].type_name, "plan.approved"); + assert_eq!(recorded[0].payload["plan"], 3); + assert_eq!(recorded[1].type_name, "plan.replaced"); + assert_eq!(recorded[1].stream, "phase/1"); + assert_eq!( + recorded[1].payload, + json!({"phase": 1, "plan": 1, "old_digest": x1.to_hex(), + "new_digest": x1r.to_hex(), "owner": "Ada Owner", "at": T7}) + ); + + let x1rr = digest_of(&plan_replaced(&store, &pl1rr(), 3, x1r, None, R8, T8)); + assert_eq!(approved_ok(&store, x1rr, R9, T8)["plan"], 4); + + let numbers: Vec = history(&store) + .iter() + .filter(|event| event.type_name == "plan.approved") + .map(|event| event.payload["plan"].clone()) + .collect(); + assert_eq!(numbers, [json!(1), json!(2), json!(3), json!(4)]); + + let phase_plan = store + .get(&project(), PHASE_PLAN_VIEW, &phase_plan_key(1)) + .unwrap() + .unwrap() + .body; + assert_eq!(phase_plan["highest"], 4); + assert_eq!(phase_plan["size"], 2); + let in_force: Vec = phase_plan["plans"] + .as_array() + .unwrap() + .iter() + .filter(|held| held["state"] == "in-force") + .map(|held| held["plan"].clone()) + .collect(); + assert_eq!(in_force, [json!(2), json!(4)]); + + for (number, digest) in [(1, x1), (3, x1r)] { + let plan = store + .get(&project(), PLAN_VIEW, &plan_key(1, number)) + .unwrap() + .unwrap() + .body; + assert_eq!(plan["state"], "replaced", "{plan}"); + assert_eq!(plan["digest"], digest.to_hex(), "{plan}"); + let map = store + .get(&project(), EVIDENCE_MAP_VIEW, &evidence_map_key(1, number)) + .unwrap() + .unwrap() + .body; + assert_eq!(map["state"], "replaced", "{map}"); + assert_eq!(map["items"], json!([e1(), e2()]), "{map}"); + } + } + + #[test] + fn a_replaced_plan_replaced_again_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R2, T5)); + approved_ok(&store, x1, R3, T5); + let x1r = digest_of(&plan_replaced(&store, &pl1r(), 1, x1, None, R4, T6)); + assert_eq!(approved_ok(&store, x1r, R5, T6)["plan"], 2); + + for (number, request_id) in [(1, R6), (2, R7)] { + let before = head(&store); + let refusal = plan_replaced(&store, &pl1rr(), number, x1, None, request_id, T7); + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], "no-such-plan", "{refusal}"); + assert_eq!(refusal["slot"], "replaces", "{refusal}"); + assert_eq!(refusal["details"], json!({"plan": number}), "{refusal}"); + assert_eq!(head(&store), before); + } + } + + #[test] + fn a_replacement_judged_with_the_replaced_plan_counted_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R2, T5)); + approved_ok(&store, x1, R3, T5); + let x3 = digest_of(&plan_submitted(&store, &pl3(), O, None, R4, T6)); + approved_ok(&store, x3, R5, T6); + + let accepted = plan_replaced(&store, &pl1r(), 1, x1, Some(2), R10, T7); + assert_eq!(accepted["status"], "ok", "{accepted}"); + let before = head(&store); + let over = plan_replaced(&store, &pl1d(), 1, x1, Some(2), R11, T8); + assert_eq!(over["status"], "refused", "{over}"); + assert_eq!(over["code"], "over-capacity", "{over}"); + assert_eq!(over["details"], json!({"stories": [1], "size": 3})); + assert_eq!(head(&store), before); + } +} diff --git a/crates/baley/src/planning/submit.rs b/crates/baley/src/planning/submit.rs new file mode 100644 index 00000000..d7d62ced --- /dev/null +++ b/crates/baley/src/planning/submit.rs @@ -0,0 +1,768 @@ +//! `plan submit` (design 0005 section 5, PLN-R9, PLN-R11 to PLN-R13, +//! PLN-R15, PLN-R25, PLN-R27, D-02, D-03, D-05, D-13): a session submits a +//! planner's plan answering a planner order of its phase. The check runs +//! before admission and records nothing: the order, the phase's activity, +//! then the plan judged whole by `judge_plan` over the phase's facts read +//! from the views. The recording then stores the draft, abandons the +//! phase's earlier draft's set and opens the new draft's set in one +//! transaction, so a phase holds one draft waiting for approval. +//! +//! Two seams sit between the check and the recording, before the preview +//! is given (design 0005 Figure 5), both against the digest the recording +//! takes: Build 4 T11 raises risk at plan submit there, and Build 4 T10's +//! plan checker issues its work order there when the plan gate is on. + +use std::num::NonZeroU32; + +use baley_core::plan::{ + PHASE_PLAN_VIEW, PLAN_KIND, PhaseNotActive, Plan, PlanDraft, PlanFacts, PlanRefusal, Replaces, + judge_plan, judge_submit_phase, phase_plan_key, +}; +use baley_core::policy::Role; +use baley_core::questions::{Cause, Subject, round_of}; +use baley_core::scope::{ + PROJECT_STREAM, SCOPE_SUBMITTED, SCOPE_SUBMITTED_VERSION, submitted_payload, +}; +use baley_core::work_order::{ + FAILED, NO_SUCH_WORK_ORDER, WORK_ORDER_VIEW, WRONG_WORK_ORDER, phase_subject, work_order_key, +}; +use baley_store::{ + Absence, Command, Decision, InstructionEvidence, Ledger, NewEvent, Observed, ObservedDocument, + OutcomeKind, ProjectId, Recorded, RetentionClass, StoreError, StreamName, Transaction, Views, +}; +use serde_json::{Map, Value, json}; + +use crate::envelope::Refusal; +use crate::mcp::capture::{PLACE_LEDGER, failed, store_failed}; +use crate::mcp::parts::PART_BOUND; +use crate::mcp::prepare::LEDGER_UNAVAILABLE; +use crate::planning::{facts, replace}; +use crate::questions::answer::with_now; +use crate::questions::record::{AbandonError, abandon, open}; +use crate::refine::order::order_evidence; +use crate::refine::questions::opened_facts; +use crate::scope::submit::NOT_RECORDED_BUSY; +use crate::work_order::read::order_document; + +/// What a refused submit did not do. +const NOT_RECORDED: &str = "nothing was recorded"; + +/// What the check read and accepted, which the recording records and +/// observes. +#[derive(Debug, Clone, PartialEq)] +pub struct Checked { + /// The plan, judged whole and accepted. + pub plan: Plan, + /// The planner order's instruction evidence, which the submission's + /// caller carries. + pub evidence: Vec, + /// The phase's size before the plan, in tasks. + pub size: u32, + /// The capacity the plan was judged under, or none. + pub capacity: Option, + /// The approved plan a replacement replaces, or none for a new plan. + pub replaces: Option, + /// The order's document, then the documents the phase's facts came + /// from, each at the sequence that produced it. + documents: Vec, + /// What a recording relies on being absent. + absences: Vec, +} + +impl Checked { + /// The size the phase would reach with the plan approved. + pub fn reaching(&self) -> u64 { + u64::from(self.size) + self.plan.size() as u64 + } +} + +/// The check of the plan `submitted` answering work order `work_order` +/// under `capacity`, run before admission and recording nothing (D-13). In +/// order: the order, none `no-such-work-order` at slot `work_order`; a plan +/// whose `phase` cannot be read gets the plan judge's own `typed-content` +/// answer at slot `plan`, since the order is judged against that phase; an +/// order that is not a planner order of the plan's phase, or one that +/// failed, `wrong-work-order` at slot `work_order`, while a pending or +/// answered one passes, so a resubmission becomes the newest draft; +/// `phase-not-active` at slot `plan` when another phase is active (D-02); +/// then the plan judged by `judge_plan` over the phase's facts, a refusal at +/// slot `plan` with what it names. A read fault is the `failed` answer. +pub fn check( + store: &S, + project: &ProjectId, + submitted: &Value, + work_order: &str, + capacity: Option, +) -> Result { + checked(store, project, submitted, work_order, None, capacity) +} + +/// The check `check` describes, shared with a replacement's: with +/// `replaces`, after `phase-not-active` the replacement is judged over the +/// phase's plans in force (D-04), and the plan is judged under the facts +/// that judgement gives, the replaced plan's tasks and items taken off. +pub(crate) fn checked( + store: &S, + project: &ProjectId, + submitted: &Value, + work_order: &str, + replaces: Option, + capacity: Option, +) -> Result { + let busy = |error: StoreError| store_failed(&error, NOT_RECORDED_BUSY); + let order = order_document(store, project, work_order) + .map_err(busy)? + .ok_or_else(|| { + Refusal::new( + NO_SUCH_WORK_ORDER, + "this project holds no work order with that id, so nothing was recorded", + ) + .slot("work_order") + .value() + })?; + let Some(phase) = phase_of(submitted) else { + let empty = PlanFacts { + stories: Vec::new(), + approved: Vec::new(), + size: 0, + capacity: None, + }; + // The judge refuses a phase it cannot read before anything else it + // would take from the facts. + let refusal = + judge_plan(submitted, &empty) + .err() + .unwrap_or_else(|| PlanRefusal::TypedContent { + path: Some("phase".into()), + }); + return Err(plan_refused(&refusal, "plan", NOT_RECORDED)); + }; + if !is_planner_order(&order.body, phase) { + return Err(Refusal::new( + WRONG_WORK_ORDER, + format!( + "that work order is not a live or answered planner order of phase {phase}, so this plan cannot answer it, and nothing was recorded" + ), + ) + .slot("work_order") + .value()); + } + let read = facts::read(store, project, phase, capacity)?; + judge_submit_phase(phase, &read.active) + .map_err(|refusal| phase_not_active(&refusal, "plan", NOT_RECORDED))?; + let facts = match replaces { + None => read.facts.clone(), + Some(replaces) => { + replace::facts_without(store, project, phase, replaces, &read, NOT_RECORDED)? + } + }; + let plan = judge_plan(submitted, &facts) + .map_err(|refusal| plan_refused(&refusal, "plan", NOT_RECORDED))?; + let evidence = order_evidence(&order.body).ok_or_else(|| { + failed( + LEDGER_UNAVAILABLE, + "the ledger holds a work order whose instructions cannot be read", + PLACE_LEDGER, + ) + })?; + let mut documents = vec![ObservedDocument { + view: WORK_ORDER_VIEW.into(), + key: work_order_key(work_order), + produced_seq: Some(order.produced_seq), + }]; + documents.extend_from_slice(read.documents()); + Ok(Checked { + plan, + evidence, + size: facts.size, + capacity, + replaces, + documents, + absences: read.absences().to_vec(), + }) +} + +/// Records the plan `checked` accepted under `command`, the command its +/// caller prepared, carrying the planner order it answers and that order's +/// instructions, in one transaction (D-03, D-05, D-13): its draft body as a +/// `record` payload and one `scope.submitted` of kind `plan` with target +/// `phase/` attaching it on the `project` stream, so the `work_order` +/// view marks the order answered and lists the digest; the phase's current +/// draft's set, read from `phase_plan` here, abandoned with cause +/// `draft-replaced` when it is held and not yet abandoned; and the draft's +/// set opened on `phase/` with the plan's questions, an empty set closing +/// at once. Every call records, so the same plan submitted again is the +/// newest draft again with a new set; only a retry of the same request +/// replays, before any decision runs. +/// +/// The decision observes the order's and the facts' documents, so a phase +/// made active, a plan approved or a truth revised since the check makes the +/// call `ledger-busy` with nothing recorded; with no phase active at the +/// check it declares that the active index still holds none. A decision run +/// without the check's read records nothing. +/// +/// The receipt: `status`, `digest`, `kind`, `phase`, `stories`, `size` (the +/// plan's tasks), `phase_size`, `reaching` (the phase's size with the plan +/// approved), `capacity` or null, `set`, `recorded_at`, `now` (round 1 in +/// the questions round's shape) and `preview`: the draft's submission when +/// the receipt stays within the part bound, otherwise +/// `{"read": {"kind": "draft", "digest": ..}}`, which `document` serves +/// whole in parts, since a receipt is never cut into parts. +pub fn record( + store: &L, + command: &Command, + checked: Option<&Checked>, +) -> Result { + let at = command.recorded_at.as_str(); + store.transact(command, &mut |tx| { + let Some(checked) = checked else { + return Err(StoreError::Unavailable( + "a plan submission reached its transaction without its check's read".into(), + )); + }; + let plan = &checked.plan; + let phase = plan.phase(); + // Read before anything is appended, so the set found is the earlier + // draft's, never the one opened below. + let earlier = current_set(tx, phase)?; + let draft = match checked.replaces { + None => PlanDraft::new(plan), + Some(replaces) => PlanDraft::replacing(plan, replaces), + }; + let body = tx.put_payload(draft.body(), RetentionClass::Record)?; + tx.append(NewEvent { + stream: StreamName(PROJECT_STREAM.into()), + type_name: SCOPE_SUBMITTED.into(), + type_version: SCOPE_SUBMITTED_VERSION, + git: None, + payload: submitted_payload(draft.digest(), PLAN_KIND, draft.target(), &body), + attachments: vec![body], + })?; + if let Some(set) = earlier { + match abandon(tx, &set, Cause::DraftReplaced, at) { + // A set already abandoned, or one the view no longer holds, + // has nothing left to abandon. + Ok(()) | Err(AbandonError::NotHeld | AbandonError::Abandoned) => {} + Err(AbandonError::Store(error)) => return Err(error), + } + } + let subject = Subject::Plan { + phase, + plan_digest: draft.digest(), + }; + let id = open(tx, plan.questions(), &subject, at)?; + let mut receipt = Map::new(); + receipt.insert("status".into(), json!("ok")); + receipt.insert("digest".into(), json!(draft.digest().to_hex())); + receipt.insert("kind".into(), json!(PLAN_KIND)); + receipt.insert("phase".into(), json!(phase)); + receipt.insert("stories".into(), json!(plan.stories())); + receipt.insert("size".into(), json!(plan.size())); + receipt.insert("phase_size".into(), json!(checked.size)); + receipt.insert("reaching".into(), json!(checked.reaching())); + receipt.insert( + "capacity".into(), + json!(checked.capacity.map(NonZeroU32::get)), + ); + receipt.insert("set".into(), json!(id)); + receipt.insert("recorded_at".into(), json!(at)); + let answer = with_now(receipt, &id, &round_of(&opened_facts(plan.questions()))); + Ok(Decision { + kind: OutcomeKind::Done, + answer: with_preview(answer, &draft), + sensitive: false, + observed: Observed { + documents: checked.documents.clone(), + absences: checked.absences.clone(), + ..Observed::default() + }, + git: None, + }) + }) +} + +/// The set of phase `phase`'s current draft, as `phase_plan` holds it inside +/// `tx`, or none. A draft that cannot be read is a ledger fault. +fn current_set(tx: &mut dyn Transaction, phase: u32) -> Result, StoreError> { + let Some(document) = tx.get(PHASE_PLAN_VIEW, &phase_plan_key(phase))? else { + return Ok(None); + }; + match document.body.get("draft") { + None | Some(Value::Null) => Ok(None), + Some(draft) => match draft.get("set").and_then(Value::as_str) { + Some(set) => Ok(Some(set.to_owned())), + None => Err(StoreError::Unavailable(format!( + "phase {phase}'s current plan draft cannot be read" + ))), + }, + } +} + +/// `answer` with `preview`, the draft's submission when the whole answer +/// stays within the part bound, otherwise the `document` read of the draft. +fn with_preview(answer: Value, draft: &PlanDraft) -> Value { + let Value::Object(mut receipt) = answer else { + return answer; + }; + // An accepted plan's draft body is canonical JSON. + let submission: Value = serde_json::from_slice(draft.body()).expect("a draft body is JSON"); + receipt.insert("preview".into(), submission); + let text = serde_json::to_string(&receipt).expect("a receipt serializes"); + if text.len() > PART_BOUND { + receipt.insert( + "preview".into(), + json!({"read": {"kind": "draft", "digest": draft.digest().to_hex()}}), + ); + } + Value::Object(receipt) +} + +/// The plan's `phase` when it is a whole number from 1 to `u32::MAX`, as +/// the plan judge reads it. +fn phase_of(submitted: &Value) -> Option { + submitted + .get("phase") + .and_then(Value::as_u64) + .and_then(|phase| u32::try_from(phase).ok()) + .filter(|phase| *phase > 0) +} + +/// Whether `order` is a planner order of phase `phase` that has not failed. +fn is_planner_order(order: &Value, phase: u32) -> bool { + let text = |field: &str| order.get(field).and_then(Value::as_str); + text("role") == Some(Role::Planner.name()) + && text("subject") == Some(phase_subject(phase).as_str()) + && text("state") != Some(FAILED) +} + +/// The refusal for `refusal`, another phase being active, at `slot`, its +/// reason ending `not_done`. +pub(crate) fn phase_not_active(refusal: &PhaseNotActive, slot: &str, not_done: &str) -> Value { + Refusal::new( + refusal.code(), + format!( + "phase {} is active, and plans are made for one phase at a time, so {not_done}. A phase stays active until it is completed or withdrawn", + refusal.phase + ), + ) + .slot(slot) + .details(refusal.details()) + .value() +} + +/// The refusal for `refusal`, the plan judge's, at `slot`, its reason +/// ending `not_done` and its details naming what it is about. +pub(crate) fn plan_refused(refusal: &PlanRefusal, slot: &str, not_done: &str) -> Value { + let reason = match refusal { + PlanRefusal::TypedContent { path: None } => { + format!("the plan is not an object, so {not_done}") + } + PlanRefusal::TypedContent { path: Some(path) } => format!( + "the plan breaks its grammar at {path}: a member unknown, missing, of another type or out of range, or one Baley writes at approval, so {not_done}" + ), + PlanRefusal::Lease { id, file, .. } => format!( + "task {id} names {file}, which lies outside the plan's files and directories, so {not_done}" + ), + PlanRefusal::Questions(_) => format!( + "the plan's questions break the question set's rules, as the code says, so {not_done}. The details name the question" + ), + PlanRefusal::CheckCommand { id, .. } => { + format!("check {id} has a blank command, so {not_done}") + } + PlanRefusal::CheckExpected { id, .. } => { + format!("check {id} has a blank expected value, so {not_done}") + } + PlanRefusal::CheckTestFile { id, .. } => { + format!("check {id} has a blank test file, so {not_done}") + } + PlanRefusal::CheckBoundary { id, .. } => { + format!("check {id} has a blank boundary, so {not_done}") + } + PlanRefusal::NoTruths => { + format!("no story committed to the plan's phase holds an approved truth, so {not_done}") + } + PlanRefusal::StoryNotInPhase { story } => format!( + "the plan serves story {story}, which is not committed to its phase, so {not_done}" + ), + PlanRefusal::EvidenceItemTruth { id, .. } => format!( + "evidence item {id} names no current truth of a story the plan serves, so {not_done}" + ), + PlanRefusal::TruthVersionMismatch { id, current, .. } => format!( + "evidence item {id} names its truth at a version other than its current version, {current}, so {not_done}" + ), + PlanRefusal::EvidenceItemConflict { id, plan, .. } => format!( + "evidence item {id} differs from the item approved plan {plan} holds under that id, so {not_done}" + ), + PlanRefusal::LinkValueNotNamed { id, .. } => { + format!("link {id} carries a value its truth does not name, so {not_done}") + } + PlanRefusal::UncoveredTruth { story, truth, .. } => format!( + "truth {truth} of story {story} has no evidence item in the phase, so {not_done}" + ), + PlanRefusal::TruthWithoutCheck { story, truth, .. } => format!( + "truth {truth} of story {story} has no check among the phase's evidence items, so {not_done}" + ), + PlanRefusal::TruthWithoutObservation { story, truth, .. } => format!( + "truth {truth} of story {story} needs a person to prove it and has no observation among the phase's evidence items, so {not_done}" + ), + PlanRefusal::TruthCheckLimit { story, truth, .. } => format!( + "truth {truth} of story {story} has more than one check across the phase, so {not_done}" + ), + PlanRefusal::OverCapacity { size, .. } => format!( + "the plan would take its phase to {size} tasks, over the phase's capacity, so {not_done}. The owner decides which of the stories it serves waits for a later phase" + ), + }; + let answer = Refusal::new(refusal.code(), reason).slot(slot); + match refusal.details() { + Some(details) => answer.details(details), + None => answer, + } + .value() +} + +#[cfg(test)] +pub(crate) mod tests { + //! Stores are real SQLite stores in fresh temporary directories, with + //! times supplied; expected answers are written out from design 0005 + //! sections 5 and 6, D-02, D-03, D-05, D-13 and the plan's data store + //! C, P0, P2, PL1, PL2 and PL3, never from running this code. + + use baley_core::policy::Host; + use baley_store_sqlite::SqliteStore; + use serde_json::json; + + use super::*; + use crate::planning::fixtures::*; + use crate::planning::order::tests::{O, fail_by_hand, prepared}; + use crate::planning::order::{issue, prepare}; + use crate::refine::order::tests::issue_by_hand; + use crate::scope::fixtures::*; + + /// Q, phase 2's planning order. + pub(crate) const Q: &str = "3b4c5d6e-7f80-4a91-8b2c-3d4e5f607182"; + /// Story 1's analyzer questions order, issued by hand. + const A: &str = "4c5d6e7f-8091-4ab2-9c3d-4e5f60718293"; + /// An id no order has. + const UNKNOWN: &str = "5d6e7f80-91a2-4bc3-8d4e-5f6071829304"; + + /// Issues phase 1's planning order O for `[1]` under `request_id` at T4. + pub(crate) fn order_o(store: &SqliteStore, request_id: &str) { + let (command, o) = prepared(store, &[1], O, request_id, T4); + assert_eq!(issue(store, &command, &o)["status"], "ok"); + } + + /// Issues phase 2's planning order Q for `[2]` under `request_id` at T4. + pub(crate) fn order_q(store: &SqliteStore, request_id: &str) { + let command = command("phase.plan", request_id, 7, T4); + let q = prepare( + store, + &command, + 2, + &[2], + None, + &p0(), + Host::ClaudeCode, + &n0(), + Q, + ) + .expect("Q is prepared"); + assert_eq!(issue(store, &command, &q)["status"], "ok"); + } + + /// Makes phase 1 active: its plan 1, PL1's map, approved by hand. + pub(crate) fn activate_phase_1(store: &SqliteStore, request_id: &str) { + approve_by_hand( + store, + request_id, + 1, + 1, + baley_store::Hash([0x7d; 32]), + &[1], + 1, + &[e1(), e2()], + Vec::new(), + ); + } + + /// `plan` as its draft body holds it: with `kind` `plan`. + pub(crate) fn as_drafted(plan: Value) -> Value { + let mut plan = plan; + plan["kind"] = json!("plan"); + plan + } + + /// Submits `plan` answering `order` under `capacity` through the check + /// and the recording, under a command whose caller carries the order and + /// its instructions, as `plan-submit` runs them below the session. + pub(crate) fn plan_submitted( + store: &SqliteStore, + plan: &Value, + order: &str, + capacity: Option, + request_id: &str, + at: &str, + ) -> Value { + let capacity = capacity.map(|capacity| NonZeroU32::new(capacity).unwrap()); + let checked = match check(store, &project(), plan, order, capacity) { + Ok(checked) => checked, + Err(refusal) => return refusal, + }; + let mut command = command("plan.submit", request_id, 8, at); + let on = caller() + .with_work_order(order) + .unwrap() + .with_instructions(checked.evidence.clone()) + .unwrap(); + command.caller = Some(baley_store::Caller::Server(on)); + crate::scope::submit::answer(record(store, &command, Some(&checked)), store) + } + + /// The digest the `draft` view's newest index names for phase 1's plan + /// drafts. + pub(crate) fn newest_plan_draft(store: &SqliteStore) -> Value { + let newest = store + .find( + &project(), + baley_core::scope::DRAFT_VIEW, + &crate::scope::approve::newest_query("plan", "phase/1"), + ) + .unwrap(); + newest.items[0].body["digest"].clone() + } + + #[test] + fn a_plan_draft_lost_on_reopen_sized_by_estimate_or_left_newest_once_replaced_is_caught() { + let (dir, store) = store_c(); + order_o(&store, R1); + let first = plan_submitted(&store, &pl2(), O, Some(2), R2, T5); + assert_eq!(first["status"], "ok", "{first}"); + assert_eq!(first["kind"], "plan"); + assert_eq!(first["preview"], as_drafted(pl2())); + assert_eq!(first["size"], 1); + assert_eq!(first["phase_size"], 0); + assert_eq!(first["reaching"], 1); + assert_eq!(first["capacity"], 2); + assert_eq!(first["now"]["round"], 1); + assert_eq!( + first["now"]["current"], + json!([{"id": "q1", "question": "Which store holds the ledger?", + "recommended": "SQLite"}]) + ); + let x2 = first["digest"].as_str().unwrap().to_owned(); + let s2 = first["set"].as_str().unwrap().to_owned(); + let order = crate::work_order::read::order(&store, &project(), O) + .unwrap() + .unwrap(); + assert_eq!(order["state"], "answered", "{order}"); + assert_eq!(order["drafts"], json!([x2]), "{order}"); + + drop(store); + let store = reopen(&dir); + let digest = baley_store::Hash::from_hex(&x2).unwrap(); + let crate::scope::read::Draft::Held(held) = + crate::scope::read::draft(&store, &project(), digest).unwrap() + else { + panic!("X2's body is held"); + }; + assert_eq!(held.kind, "plan"); + assert_eq!(held.submission, as_drafted(pl2())); + + approve_by_hand( + &store, + R3, + 1, + 1, + baley_store::Hash([0x7d; 32]), + &[1], + 2, + &[e1(), e2()], + Vec::new(), + ); + let before = head(&store); + let over = plan_submitted(&store, &pl3(), O, Some(2), R4, T6); + assert_eq!(over["status"], "refused", "{over}"); + assert_eq!(over["code"], "over-capacity", "{over}"); + assert_eq!(over["details"], json!({"stories": [1], "size": 3})); + assert_eq!(head(&store), before); + + let second = plan_submitted(&store, &pl3(), O, None, R5, T7); + assert_eq!(second["status"], "ok", "{second}"); + let x3 = second["digest"].clone(); + let events = history(&store); + let abandoned = of_type(&events, "questions.abandoned"); + assert_eq!(abandoned.len(), 1); + assert_eq!(abandoned[0].payload["set"], s2.as_str()); + assert_eq!(abandoned[0].payload["cause"], "draft-replaced"); + assert_eq!(abandoned[0].request_id.0, R5); + assert_eq!(newest_plan_draft(&store), x3); + assert_ne!(x3, json!(x2)); + } + + /// The bytes of the payload `event`'s `body` references. + fn body_bytes(store: &SqliteStore, event: &baley_store::Event) -> Vec { + use std::io::Read; + let hash = baley_store::Hash::from_hex(event.payload["body"]["payload"].as_str().unwrap()) + .unwrap(); + let baley_store::PayloadBody::Present(mut reader) = + baley_store::Payloads::open(store, &hash).unwrap() + else { + panic!("the body is present"); + }; + let mut bytes = Vec::new(); + reader.read_to_end(&mut bytes).unwrap(); + bytes + } + + #[test] + fn a_plan_draft_recorded_off_its_order_or_without_record_retention_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let receipt = plan_submitted(&store, &pl1(), O, None, R2, T5); + assert_eq!(receipt["status"], "ok", "{receipt}"); + let digest = receipt["digest"].as_str().unwrap(); + + let events = history(&store); + let drafts = of_type(&events, "scope.submitted"); + let drafts: Vec<_> = drafts + .into_iter() + .filter(|event| event.payload["kind"] == "plan") + .collect(); + assert_eq!(drafts.len(), 1); + let draft = drafts[0]; + assert_eq!(draft.stream, "project"); + assert_eq!(draft.payload["target"], "phase/1"); + assert_eq!(draft.payload["digest"], digest); + assert_eq!(draft.payload["body"]["class"], "record"); + assert_eq!( + body_bytes(&store, draft), + baley_store::canonical_json(&as_drafted(pl1())).unwrap() + ); + let Some(baley_store::Caller::Server(on)) = &draft.caller else { + panic!("a server caller: {:?}", draft.caller); + }; + assert_eq!(on.work_order(), Some(O)); + let identities: Vec<&str> = on.instructions().iter().map(|e| e.identity()).collect(); + assert_eq!(identities, ["bal-phase-planner"]); + + let opened = of_type(&events, "questions.opened"); + let opened: Vec<_> = opened + .into_iter() + .filter(|event| event.payload["subject"] == "plan") + .collect(); + assert_eq!(opened.len(), 1); + assert_eq!(opened[0].stream, "phase/1"); + assert_eq!(opened[0].payload["phase"], 1); + assert_eq!(opened[0].payload["plan_digest"], digest); + assert_eq!(opened[0].payload["questions"], json!([])); + assert_eq!(receipt["now"]["state"], "closed", "{receipt}"); + assert_eq!(receipt["set"], opened[0].payload["set"]); + } + + #[test] + fn a_plan_set_opened_on_the_roadmap_or_two_drafts_left_open_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + let first = plan_submitted(&store, &pl2(), O, None, R2, T5); + let second = plan_submitted(&store, &pl2(), O, None, R3, T6); + assert_eq!(first["status"], "ok", "{first}"); + assert_eq!(second["status"], "ok", "{second}"); + assert_eq!(second["digest"], first["digest"]); + assert_ne!(second["set"], first["set"]); + + let events = history(&store); + let abandoned = of_type(&events, "questions.abandoned"); + assert_eq!(abandoned.len(), 1); + assert_eq!(abandoned[0].payload["set"], first["set"]); + assert_eq!(abandoned[0].payload["cause"], "draft-replaced"); + assert_eq!(abandoned[0].stream, "phase/1"); + assert_eq!(abandoned[0].request_id.0, R3); + let opened: Vec<_> = of_type(&events, "questions.opened") + .into_iter() + .filter(|event| event.request_id.0 == R3) + .collect(); + assert_eq!(opened.len(), 1); + assert_eq!(opened[0].stream, "phase/1"); + assert_eq!(opened[0].payload["plan_digest"], first["digest"]); + assert_eq!(opened[0].payload["set"], second["set"]); + + let phase_plan = store + .get( + &project(), + baley_core::plan::PHASE_PLAN_VIEW, + &phase_plan_key(1), + ) + .unwrap() + .unwrap(); + assert_eq!( + phase_plan.body["draft"], + json!({"digest": first["digest"], "set": second["set"]}) + ); + } + + #[test] + fn a_submit_landing_beside_a_newly_active_phase_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + order_q(&store, R2); + let checked = check(&store, &project(), &pl1(), O, None).expect("PL1 is accepted"); + activate_phase_2(&store, R3); + let before = head(&store); + let mut command = command("plan.submit", R4, 8, T5); + command.caller = Some(baley_store::Caller::Server( + caller().with_work_order(O).unwrap(), + )); + let answer = crate::scope::submit::answer(record(&store, &command, Some(&checked)), &store); + assert_eq!(answer["status"], "failed", "{answer}"); + assert_eq!(answer["code"], "ledger-busy", "{answer}"); + assert_eq!(head(&store), before); + } + + /// The check of `plan` under `order` with no capacity, which must refuse + /// with `code` at `slot` and record nothing. Gives the refusal. + fn refused_with( + store: &SqliteStore, + plan: &Value, + order: &str, + code: &str, + slot: &str, + ) -> Value { + let before = head(store); + let refusal = check(store, &project(), plan, order, None).expect_err("the plan is refused"); + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], code, "{refusal}"); + assert_eq!(refusal["slot"], slot, "{refusal}"); + assert_eq!(head(store), before); + refusal + } + + #[test] + fn a_plan_answering_another_phases_or_a_failed_order_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + order_q(&store, R2); + issue_by_hand(&store, A, 1, R3); + + refused_with(&store, &pl1(), UNKNOWN, "no-such-work-order", "work_order"); + refused_with(&store, &pl1(), Q, "wrong-work-order", "work_order"); + refused_with(&store, &pl1(), A, "wrong-work-order", "work_order"); + fail_by_hand(&store, O, R4); + refused_with(&store, &pl1(), O, "wrong-work-order", "work_order"); + } + + #[test] + fn a_plan_refused_while_its_own_phase_is_active_or_let_through_beside_another_is_caught() { + let (_dir, store) = store_c(); + order_o(&store, R1); + order_q(&store, R2); + activate_phase_2(&store, R3); + let refusal = refused_with(&store, &pl1(), O, "phase-not-active", "plan"); + assert_eq!(refusal["details"], json!({"phase": 2})); + + let (_dir, store) = store_c(); + order_o(&store, R1); + order_q(&store, R2); + activate_phase_1(&store, R3); + let checked = check(&store, &project(), &pl1(), O, None).expect("PL1 is accepted"); + assert_eq!(checked.plan.phase(), 1); + } +} diff --git a/crates/baley/src/questions/answer.rs b/crates/baley/src/questions/answer.rs index 9e5ec7bc..115969b8 100644 --- a/crates/baley/src/questions/answer.rs +++ b/crates/baley/src/questions/answer.rs @@ -25,7 +25,10 @@ use crate::envelope::{LEDGER_BUSY, Refusal}; use crate::mcp::capture::{PLACE_LEDGER, failed, store_failed}; use crate::mcp::parts::PART_BOUND; use crate::mcp::prepare::LEDGER_UNAVAILABLE; -use crate::questions::read::{RELAY, SetRead, no_such_question_set, read as read_set, round_value}; +use crate::planning::order::{self as planner, planner_absences}; +use crate::questions::read::{ + PlanSubject, RELAY, SetRead, no_such_question_set, read as read_set, round_value, +}; use crate::refine::order::{PreparedOrder, analyzer_absences}; /// The command kind an answer call is recorded under, on either surface. @@ -48,6 +51,8 @@ pub struct Checked { pub settled: Settled, /// The story whose set this is, or none for a plan draft's set. pub story: Option, + /// The plan draft whose set this is, or none for a story's set. + pub plan: Option, /// The set's questions as submitted. pub questions: Vec, } @@ -135,23 +140,30 @@ pub fn check( produced_seq: held.produced_seq, settled, story: held.story, + plan: held.plan, questions: held.facts.questions, }) } -/// What an answer call's recording does about its story's drafting order. +/// What an answer call's recording does about the order its set's close +/// issues. #[derive(Debug, Clone, Copy)] pub enum Drafting<'a> { - /// Nothing: the call leaves a question open, answers a plan draft's set, - /// or is given at the terminal, where an owner command issues no work - /// order (ADR 0044). + /// Nothing: the call leaves a question open, closes a plan draft's set + /// with no answer rejecting a recommendation, or is given at the + /// terminal, where an owner command issues no work order (ADR 0044). None, /// The call closes a story's set over MCP, so this prepared drafting /// order is issued with the answers (D-08). Issue(&'a PreparedOrder), + /// The call closes a plan draft's set over MCP with an answer rejecting + /// a recommendation, so this prepared planner revision order is issued + /// with the answers (D-15, PLN-R27). + Revise(&'a planner::PreparedOrder), /// The call closes a story's set over MCP beside the story's pending - /// analyzer order, read from this `work_order` document, so no order is - /// issued (D-09). + /// analyzer order, or a plan draft's set that a revision would follow + /// beside the phase's pending planner order, read from this `work_order` + /// document, so no order is issued (D-09, D-11). HeldBy(&'a ObservedDocument), } @@ -161,10 +173,12 @@ pub enum Drafting<'a> { /// caller are recorded as the caller built them. A drafting order to issue /// is issued in the same transaction (D-08), its decision declaring that no /// analyzer order of the story is pending (D-09) and observing the documents -/// its inputs were read from beside the set's. A drafting order held back by -/// a pending analyzer order observes that order's document instead, so an -/// order settled since makes the call `ledger-busy` with nothing recorded -/// rather than closing the set with no drafting order. A request the store +/// its inputs were read from beside the set's; a planner revision order to +/// issue is issued the same way, declaring that no planner order of the +/// phase is pending (D-11, D-15). An order held back by a pending analyzer +/// or planner order observes that order's document instead, so an order +/// settled since makes the call `ledger-busy` with nothing recorded rather +/// than closing the set with no order. A request the store /// already holds is replayed from its record before any decision runs; a /// decision asked to run without the check's read records nothing. pub fn record( @@ -199,12 +213,18 @@ pub fn record( }], ..Observed::default() }; - let drafted = match drafting { + let issued = match drafting { Drafting::Issue(order) => { let members = order.issue_within(tx, &checked.set, &command.recorded_at)?; observed.documents.extend(order.documents().iter().cloned()); observed.absences = analyzer_absences(order.story()); - Some(members) + Some(("drafting", members)) + } + Drafting::Revise(order) => { + let members = order.issue_within(tx, &command.recorded_at)?; + observed.documents.extend(order.documents().iter().cloned()); + observed.absences = planner_absences(order.phase()); + Some(("revision", members)) } Drafting::HeldBy(pending) => { observed.documents.push(pending.clone()); @@ -213,9 +233,17 @@ pub fn record( Drafting::None => None, }; let after = checked.settled.round_after(owner, &command.recorded_at); + let ready = checked.plan.is_some() && after.answered.iter().all(|answer| answer.accepted); Ok(Decision { kind: OutcomeKind::Done, - answer: receipt_value(&checked.set, round, &command.recorded_at, &after, drafted), + answer: receipt_value( + &checked.set, + round, + &command.recorded_at, + &after, + ready, + issued, + ), sensitive: false, observed, git: None, @@ -226,15 +254,20 @@ pub fn record( /// The receipt of a call recorded in `round` at `at`: the set, the round /// recorded, the time, and in `now` the set's round as it stands after the /// call. A call that closed a story's set over MCP adds `drafting`, the -/// analyzer's drafting order it issued (D-08). A receipt cannot be cut into -/// parts, so when that round would pass the part bound `now` names the -/// `document` read instead. +/// analyzer's drafting order it issued (D-08). A call that closed a plan +/// draft's set with no answer rejecting a recommendation adds `ready` true +/// on either surface, since the draft may then be approved; one that closed +/// it over MCP with such an answer adds `revision`, the planner's revision +/// order it issued (D-15, PLN-R27). A receipt cannot be cut into parts, so +/// when that round would pass the part bound `now` names the `document` read +/// instead. fn receipt_value( set: &str, round: u32, at: &str, after: &Round, - drafting: Option>, + ready: bool, + issued: Option<(&str, Map)>, ) -> Value { let mut receipt = Map::new(); receipt.insert("status".into(), json!("ok")); @@ -242,11 +275,14 @@ fn receipt_value( receipt.insert("round".into(), json!(round)); receipt.insert("recorded_at".into(), json!(at)); if after.state == SetState::Closed { - // Every question is answered or deferred. A plan draft's close - // outputs, `ready` or the planner's revision order, are T9's and plug - // in here; until then a plan draft's receipt only says `closed`. - if let Some(drafting) = drafting { - receipt.insert("drafting".into(), Value::Object(drafting)); + // Every question is answered or deferred, so the close's outputs + // are given: a story's drafting order, or a plan draft's `ready` or + // revision order. A close at the terminal issues no order. + if ready { + receipt.insert("ready".into(), json!(true)); + } + if let Some((name, order)) = issued { + receipt.insert(name.into(), Value::Object(order)); } } with_now(receipt, set, after) @@ -964,4 +1000,58 @@ pub(crate) mod tests { assert!(close.get("drafting").is_none(), "{close}"); assert!(of_type(&history(&store), "work_order.issued").is_empty()); } + + #[test] + fn a_terminal_close_issuing_a_revision_or_a_story_set_saying_ready_is_caught() { + use crate::planning::fixtures::{pl2, store_c}; + use crate::planning::order::tests::O; + use crate::planning::submit::tests::{order_o, plan_submitted}; + + let (_dir, store) = store_c(); + order_o(&store, R1); + let submitted = plan_submitted(&store, &pl2(), O, None, R2, T5); + assert_eq!(submitted["status"], "ok", "{submitted}"); + let s2 = submitted["set"].as_str().unwrap().to_owned(); + let orders = |store: &SqliteStore| { + of_type(&history(store), "work_order.issued") + .iter() + .map(|event| event.payload["id"].clone()) + .collect::>() + }; + let before = orders(&store); + assert_eq!(before, [json!(O)]); + + // As `baley questions answer` runs it: the owner's command, no + // session caller. + let terminal = |request_id: &str| { + let mut command = command(ANSWER_COMMAND, request_id, 4, T6); + command.actor = baley_store::Actor::Owner; + command.caller = None; + command + }; + let plan = run( + &store, + &s2, + &json!([own("q1", "Postgres")]), + &terminal(R3), + OWNER, + ); + assert_eq!(plan["status"], "ok", "{plan}"); + assert_eq!(plan["now"]["state"], "closed", "{plan}"); + assert!(plan.get("ready").is_none(), "{plan}"); + assert!(plan.get("revision").is_none(), "{plan}"); + + let one = judge_set( + &json!([{"id": "q1", "question": "Which store backs the ledger?", + "recommended": "SQLite", "depends_on": []}]), + ) + .unwrap(); + let set = open_set(&store, R4, &one, &story(1)); + let story_set = run(&store, &set, &json!([take("q1")]), &terminal(R5), OWNER); + assert_eq!(story_set["status"], "ok", "{story_set}"); + assert_eq!(story_set["now"]["state"], "closed", "{story_set}"); + assert!(story_set.get("ready").is_none(), "{story_set}"); + assert!(story_set.get("drafting").is_none(), "{story_set}"); + assert_eq!(orders(&store), before); + } } diff --git a/crates/baley/src/questions/read.rs b/crates/baley/src/questions/read.rs index a4d593fd..815c2721 100644 --- a/crates/baley/src/questions/read.rs +++ b/crates/baley/src/questions/read.rs @@ -9,7 +9,7 @@ use baley_core::questions::{ Pending, QUESTIONS_VIEW, Round, SetFacts, UnreadableSet, questions_key, round_of, set_facts, }; -use baley_store::{ProjectId, StoreError, Views}; +use baley_store::{Hash, ProjectId, StoreError, Views}; use serde_json::{Value, json}; use crate::envelope::Refusal; @@ -106,6 +106,18 @@ pub struct HeldSet { /// The story whose set this is, read from the set's subject, or none for /// a plan draft's set. pub story: Option, + /// The plan draft whose set this is, read from the set's subject, or none + /// for a story's set. + pub plan: Option, +} + +/// The plan draft a set belongs to: its phase and the draft's digest. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PlanSubject { + /// The phase the draft plans. + pub phase: u32, + /// The draft's digest. + pub draft: Hash, } /// What a read of one set found. @@ -139,7 +151,7 @@ pub fn read( "the set's stream cannot be read".into(), ))); }; - let Some(story) = story_of(&document.body) else { + let Some((story, plan)) = subject_of(&document.body) else { return Ok(SetRead::Unreadable(UnreadableSet( "the set's subject cannot be read".into(), ))); @@ -150,21 +162,36 @@ pub fn read( facts, stream: stream.into(), story, + plan, }))) } -/// The story a set's document names as its subject: `Some(Some(id))` for a -/// story's set, `Some(None)` for a plan draft's, and `None` for a subject -/// that cannot be read. -fn story_of(document: &Value) -> Option> { +/// The subject a set's document names: the story for a story's set, the +/// phase and draft digest for a plan draft's, and `None` for a subject that +/// cannot be read. +fn subject_of(document: &Value) -> Option<(Option, Option)> { let subject = document.get("subject")?; - match subject.get("kind").and_then(Value::as_str)? { - "story" => subject - .get("story") + let whole = |name: &str| { + subject + .get(name) .and_then(Value::as_u64) - .and_then(|story| u32::try_from(story).ok()) - .map(Some), - "plan" => Some(None), + .and_then(|value| u32::try_from(value).ok()) + }; + match subject.get("kind").and_then(Value::as_str)? { + "story" => Some((Some(whole("story")?), None)), + "plan" => { + let draft = subject + .get("plan_digest") + .and_then(Value::as_str) + .and_then(Hash::from_hex)?; + Some(( + None, + Some(PlanSubject { + phase: whole("phase")?, + draft, + }), + )) + } _ => None, } } diff --git a/crates/baley/src/scope/approve.rs b/crates/baley/src/scope/approve.rs index c0fb1c6f..291c17e0 100644 --- a/crates/baley/src/scope/approve.rs +++ b/crates/baley/src/scope/approve.rs @@ -9,9 +9,21 @@ //! against accepted scope as it stands at approval (D-12). The second step //! records the approval as the owner, confirming inside its transaction that //! nothing the first step read has moved. +//! +//! A `phase-edit` draft whose phase's latest planning continuation names +//! its digest is a commitment (owner ruling 9, D-01): its first step also +//! rechecks the continuation's selection with the readiness `phase-plan` +//! judges and refuses beside a pending planner order of the phase, and its +//! second step, given the route, issues the continuation's planner order in +//! the same transaction as the stories. Every other draft is approved as +//! before, with no order. use std::collections::BTreeMap; +use baley_core::plan::{ + CommitmentRefusal, PHASE_PLAN_VIEW, PLAN_KIND, judge_readiness, phase_plan_key, +}; +use baley_core::policy::{AcceptedNames, EffectivePolicy, Host}; use baley_core::scope::{ AcceptedScope, ApprovalFacts, ApprovalRefusal, ChangeApprovalFacts, ChangeApprovalRefusal, ChangeSubmission, DRAFT_NEWEST_INDEX, DRAFT_VIEW, NumbersExhausted, PHASE_DECLARED, @@ -24,8 +36,9 @@ use baley_core::scope::{ use baley_core::truth::STORY_TRUTHS; use baley_store::{ Absence, Actor, Command, Decision, DocKey, Document, EVENT_PAGE_BOUND, EventMatch, Hash, - HistoryFilter, IndexQuery, KeyValue, Ledger, Observed, OutcomeKind, PageRequest, Payloads, - ProjectId, Recorded, RetentionClass, StaleInput, StoreError, StreamName, Transaction, Views, + HistoryFilter, IndexQuery, KeyValue, Ledger, Observed, ObservedDocument, OutcomeKind, + PageRequest, Payloads, ProjectId, Recorded, RetentionClass, StaleInput, StoreError, StreamName, + Transaction, Views, }; use serde_json::{Value, json}; @@ -33,6 +46,8 @@ use crate::envelope::Refusal; use crate::mcp::capture::{PLACE_LEDGER, TEXT_PURGED, failed, store_failed}; use crate::mcp::prepare::LEDGER_UNAVAILABLE; use crate::mcp::scope::change_kind; +use crate::planning::order::{self, PreparedOrder, pending_planner, planner_absences}; +use crate::planning::phase_plan::{latest_continuation, read_readiness, readiness_refused}; use crate::scope::read::{ self, Detail, Preview, PreviewError, ReadError, ScopeRead, preview, preview_of, }; @@ -79,6 +94,50 @@ struct ChangeDraft { scope: ScopeRead, /// The detail in force a `phase-edit` that gives none keeps. detail: Option, + /// The commitment a `phase-edit` its phase's continuation names makes. + commitment: Option, +} + +/// A commitment the first step rechecked (D-01): what its planner order is +/// issued for, and what the second step observes. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Commitment { + /// The phase it commits. + phase: u32, + /// The continuation's selection, in order. + stories: Vec, + /// The planner order the continuation names, issued under this id. + work_order: String, + /// The `phase_plan` document, then the readiness documents, each at the + /// sequence that produced it. + documents: Vec, + /// The active-index absence when no phase was active. + absences: Vec, +} + +impl Judged { + /// The id of the planner order the second step issues when the draft is + /// a commitment, so its caller knows to route one; none otherwise. + pub fn planner_order(&self) -> Option<&str> { + self.commitment() + .map(|commitment| commitment.work_order.as_str()) + } + + fn commitment(&self) -> Option<&Commitment> { + match &self.approving { + Approving::Change(draft) => draft.commitment.as_ref(), + Approving::Start(_) => None, + } + } +} + +/// A phase's latest continuation that names the draft being approved, with +/// the `phase_plan` document it was read from. +struct Named { + phase: u32, + stories: Vec, + work_order: String, + document: ObservedDocument, } /// The detail in force a `phase-edit` keeps, with the `phase_detail` @@ -99,12 +158,13 @@ struct CarriedDetail { /// draft; for a change, what `judge_change_draft` names. Then it judges the /// approval. A story's truth draft is refused `unknown-draft`, its reason /// naming `baley story truths approve `, which approves it (owner -/// ruling R2). It runs outside any transaction, since a transaction has no +/// ruling R2), and a plan draft the same way naming `baley plan approve +/// ` (D-05). It runs outside any transaction, since a transaction has no /// payload read (D-02). A refusal is the `refused` answer, slot `digest`; a /// body that is gone or no longer judges clean is a ledger fault, never -/// approved. Nothing is recorded. It is also the first step of approving a -/// `phase-edit` draft T9's `phase plan` records, called with a digest its -/// caller supplies. +/// approved. Nothing is recorded. A commitment, a `phase-edit` its phase's +/// latest continuation names, is also rechecked here (D-01), and +/// [`Judged::planner_order`] then names the order its second step issues. pub fn judge( store: &S, project: &ProjectId, @@ -112,6 +172,7 @@ pub fn judge( ) -> Result { let target = match preview(store, project, digest) { Ok(read) if read.kind == STORY_TRUTHS => return Err(truth_draft(digest)), + Ok(read) if read.kind == PLAN_KIND => return Err(plan_draft(digest)), Ok(read) if read.kind != START_KIND => return judge_change_draft(store, project, &read), Ok(read) => Some(accept(&read)?), Err(PreviewError::UnknownDraft) => None, @@ -161,6 +222,12 @@ pub fn judge( /// now, refused as at submission with slot `digest` (D-12). A `phase-edit` that /// gives no detail keeps the one in force, read here, since a transaction /// has no payload read; one this project purged is never opened. +/// +/// A `phase-edit` its phase's latest continuation names is a commitment: +/// a `draft-approved` refusal of it also names the planner order its +/// approval issued, when the `work_order` view holds it, and after the +/// approval judgement and before the scope judgement its selection is +/// rechecked by [`recheck`]. fn judge_change_draft( store: &S, project: &ProjectId, @@ -200,10 +267,27 @@ fn judge_change_draft( }), newest: newest.as_ref().map(|(newest, _)| newest), }; - judge_change_approval(&facts).map_err(|refusal| change_refused(&refusal))?; + let named = continuation_naming(store, project, &change)?; + if let Err(refusal) = judge_change_approval(&facts) { + let answer = change_refused(&refusal); + return Err(match (&refusal, &named) { + (ChangeApprovalRefusal::DraftApproved { .. }, Some(named)) + if order_held(store, project, &named.work_order)? => + { + naming_order(answer, &named.work_order) + } + _ => answer, + }); + } // An approved judgement had a newest draft. let (newest, newest_seq) = newest.ok_or_else(|| change_refused(&ChangeApprovalRefusal::UnknownDraft))?; + // Readiness before the scope judgement, so a story in another phase is + // `story-in-phase`, not `story-double-assigned` (D-10). + let commitment = match named { + Some(named) => Some(recheck(store, project, named)?), + None => None, + }; let accepted = scope .accepted() .ok_or_else(|| scope_unread(&ReadError::Unreadable(String::new())))?; @@ -219,10 +303,94 @@ fn judge_change_draft( approved_before: approvals.iter().any(|approval| approval.seq < seq), scope, detail, + commitment, })), }) } +/// The continuation naming `change` when it is a `phase-edit` and its +/// phase's latest continuation in `phase_plan` names its digest, or none. +fn continuation_naming( + store: &S, + project: &ProjectId, + change: &ChangeSubmission, +) -> Result, Value> { + let ScopeChange::PhaseEdit { phase, .. } = &change.change else { + return Ok(None); + }; + let key = phase_plan_key(*phase); + let document = store.get(project, PHASE_PLAN_VIEW, &key).map_err(busy)?; + let latest = latest_continuation(document.as_ref().map(|document| &document.body))?; + Ok(latest + .filter(|latest| latest.edit == change.digest()) + .map(|latest| Named { + phase: *phase, + stories: latest.stories, + work_order: latest.work_order, + document: ObservedDocument { + view: PHASE_PLAN_VIEW.into(), + key, + produced_seq: document.map(|document| document.produced_seq), + }, + })) +} + +/// Rechecks a commitment's selection over facts read now, through the +/// gathering `phase-plan` judges (D-01): a readiness refusal, then a pending +/// planner order of the phase, each at slot `digest`, so an approval beside +/// a pending order says why rather than failing `ledger-busy` at its second +/// step on every retry (D-11). +fn recheck( + store: &S, + project: &ProjectId, + named: Named, +) -> Result { + const NOT_DONE: &str = "nothing was approved"; + let readiness = read_readiness(store, project, named.phase, &named.stories)?; + judge_readiness(&readiness.readiness()) + .map_err(|refusal| readiness_refused(&refusal, "digest", NOT_DONE))?; + if let Some(pending) = pending_planner(store, project, named.phase).map_err(busy)? { + let refusal = CommitmentRefusal::PlannerOrderPending { + work_order: pending, + }; + return Err(readiness_refused(&refusal, "digest", NOT_DONE)); + } + let mut documents = vec![named.document]; + documents.extend(readiness.documents().iter().cloned()); + Ok(Commitment { + phase: named.phase, + stories: named.stories, + work_order: named.work_order, + documents, + absences: readiness.absences(), + }) +} + +/// Whether the `work_order` view holds order `id`. +fn order_held(store: &S, project: &ProjectId, id: &str) -> Result { + crate::work_order::read::order(store, project, id) + .map(|order| order.is_some()) + .map_err(busy) +} + +/// A `draft-approved` refusal of a commitment, naming in its details and +/// its reason the planner order its approval issued, so a rerun still tells +/// the owner the order (flagged assumption 2). +fn naming_order(mut answer: Value, work_order: &str) -> Value { + if let Some(reason) = answer["reason"].as_str() { + answer["reason"] = json!(format!( + "{reason}. That approval issued planner work order {work_order}, which a session's phase-plan with the same stories launches" + )); + } + match answer["details"].as_object_mut() { + Some(details) => { + details.insert("work_order".into(), json!(work_order)); + } + None => answer["details"] = json!({"work_order": work_order}), + } + answer +} + /// The detail in force of the phase a `phase-edit` giving no detail /// changes, or none for any other change. fn detail_in_force( @@ -387,13 +555,76 @@ fn change_refused(refusal: &ChangeApprovalRefusal) -> Value { /// any decision runs, so it needs no reads; a decision asked to run without /// them records nothing. /// -/// It is also the second step of approving a `phase-edit` draft T9's `phase -/// plan` records, with a command and owner its caller supplies. +/// A commitment (D-01) is recorded through [`record_commitment`], which +/// routes its planner order; given one here, the decision records nothing. pub fn record( store: &L, command: &Command, judged: Option<&Judged>, owner: &str, +) -> Result { + record_with(store, command, judged, owner, None) +} + +/// What a commitment's planner order is routed under at the second step. +#[derive(Debug, Clone, Copy)] +pub struct OrderRoute<'a> { + /// The host's effective policy. + pub policy: &'a EffectivePolicy, + /// The host the order is composed for. + pub host: Host, + /// The host's accepted model names. + pub names: &'a AcceptedNames, +} + +/// The second step for a draft whose first step may have judged a +/// commitment (D-01): [`record`], and for a commitment its planner order +/// prepared first, outside the transaction, as the continuation's id for the +/// continuation's selection under `route`, then issued in the approval's +/// transaction after the stories. The decision declares no pending planner +/// order of the phase, and the active-index absence when the recheck found +/// no active phase, and observes the `phase_plan` document, the readiness +/// documents and the inputs', so an order issued, a phase made active or a +/// truth revised since the reads makes the approval `ledger-busy` with +/// nothing recorded. The receipt adds the order's receipt members. A fault +/// preparing the order is the answer, with nothing approved. +pub fn record_commitment( + store: &S, + command: &Command, + judged: &Judged, + owner: &str, + route: OrderRoute<'_>, +) -> Value { + let prepared = match judged.commitment() { + Some(commitment) => match order::prepare( + store, + command, + commitment.phase, + &commitment.stories, + None, + route.policy, + route.host, + route.names, + &commitment.work_order, + ) { + Ok(prepared) => Some(prepared), + Err(answer) => return answer, + }, + None => None, + }; + crate::scope::submit::answer( + record_with(store, command, Some(judged), owner, prepared.as_ref()), + store, + ) +} + +/// [`record`] with a commitment's prepared planner order. +fn record_with( + store: &L, + command: &Command, + judged: Option<&Judged>, + owner: &str, + prepared: Option<&PreparedOrder>, ) -> Result { let command = Command { actor: Actor::Owner, @@ -408,7 +639,9 @@ pub fn record( }; let submission = match &judged.approving { Approving::Start(submission) => submission, - Approving::Change(draft) => return change_decision(tx, judged, draft, owner, &at), + Approving::Change(draft) => { + return change_decision(tx, judged, draft, owner, &at, prepared); + } }; confirm(tx, judged)?; let (highest_phase, highest_story) = highest(tx.get(ROADMAP_VIEW, &roadmap_key())?)?; @@ -462,15 +695,29 @@ pub fn record( } /// Records an approved change inside the transaction, once what the first -/// step read is confirmed. +/// step read is confirmed, and a commitment's planner order `prepared` after +/// its events. A commitment reaching here without its order records +/// nothing. fn change_decision( tx: &mut dyn Transaction, judged: &Judged, draft: &ChangeDraft, owner: &str, at: &str, + prepared: Option<&PreparedOrder>, ) -> Result { let change = &draft.change; + let ordered = match (&draft.commitment, prepared) { + (None, _) => None, + (Some(commitment), Some(prepared)) if prepared.id() == commitment.work_order => { + Some((commitment, prepared)) + } + (Some(_), _) => { + return Err(StoreError::Unavailable( + "a commitment approval reached its transaction without its planner order".into(), + )); + } + }; confirm_draft(tx, judged)?; // A transaction cannot ask for an approval after a sequence, so when // one preceded the latest submission a second is left to the scope @@ -517,7 +764,7 @@ fn change_decision( .map(|event| event.payload[field].clone()) .collect() }; - let receipt = json!({ + let mut receipt = json!({ "status": "ok", "kind": change.kind().as_str(), "digest": judged.digest.to_hex(), @@ -532,11 +779,26 @@ fn change_decision( for event in events { tx.append(event)?; } + let mut observed = Observed::default(); + if let Some((commitment, prepared)) = ordered { + let members = prepared.issue_within(tx, at)?; + if let Some(receipt) = receipt.as_object_mut() { + receipt.extend(members); + } + observed.absences = planner_absences(commitment.phase); + observed + .absences + .extend(commitment.absences.iter().cloned()); + observed.documents = commitment.documents.clone(); + observed + .documents + .extend(prepared.documents().iter().cloned()); + } Ok(Decision { kind: OutcomeKind::Done, answer: receipt, sensitive: false, - observed: Observed::default(), + observed, git: None, }) } @@ -755,6 +1017,22 @@ fn truth_draft(digest: Hash) -> Value { .value() } +/// The `refused` answer for a plan draft given to the scope approval: +/// `unknown-draft`, since no scope draft has the digest, its reason naming +/// the command that approves plans with this digest, so the owner is never +/// told the ledger is damaged (D-05). +fn plan_draft(digest: Hash) -> Value { + Refusal::new( + ApprovalRefusal::UnknownDraft.code(), + format!( + "this digest is a plan draft, not a scope draft, so nothing was approved. Approve it with baley plan approve {}", + digest.to_hex() + ), + ) + .slot("digest") + .value() +} + /// The `refused` answer for an approval, slot `digest`. fn refused(refusal: &ApprovalRefusal) -> Value { let answer = match refusal { @@ -1645,4 +1923,249 @@ mod tests { ); assert_eq!(head(&store), before); } + + #[test] + fn a_plan_draft_approved_as_scope_or_reported_as_damage_is_caught() { + use crate::planning::fixtures::{pl1, store_c}; + use crate::planning::order::tests::O; + use crate::planning::submit::tests::{order_o, plan_submitted}; + + let (_dir, store) = store_c(); + order_o(&store, R1); + let receipt = plan_submitted(&store, &pl1(), O, None, R2, T5); + assert_eq!(receipt["status"], "ok", "{receipt}"); + let x = receipt["digest"].as_str().unwrap().to_owned(); + let before = head(&store); + let refusal = judge(&store, &project(), Hash::from_hex(&x).unwrap()).unwrap_err(); + assert_eq!(refusal["status"], "refused", "{refusal}"); + assert_eq!(refusal["code"], "unknown-draft", "{refusal}"); + assert_eq!(refusal["slot"], "digest", "{refusal}"); + let reason = refusal["reason"].as_str().unwrap(); + assert!( + reason.contains(&format!("baley plan approve {x}")), + "{reason}" + ); + assert_eq!(head(&store), before); + } + + /// The commitment tests: store C, the `[1, 4]` edit E1 and the `[4, 1]` + /// edit E2 recorded with their continuations, approved under P0 and N0 + /// (design 0005 `phase plan`, design 0004 `phase edit`, D-01, D-09 to + /// D-11). + mod commitment { + use baley_core::scope::ChangeKind; + use baley_store_sqlite::SqliteStore; + + use super::*; + use crate::planning::fixtures::{ + activate_phase_2, approve_commitment, edit, n0, p0, refined, reopen, store_c, versioned, + }; + use crate::planning::order::tests::{O, O2}; + use crate::planning::phase_plan::tests::bound_stories; + use crate::refine::order::tests::issued; + use crate::refine::submit::tests::t1; + + /// Phase 1's stories as the roadmap holds them. + pub(super) fn phase_1_stories(store: &SqliteStore) -> Vec { + read::phase(store, &project(), 1).unwrap().stories + } + + /// The first step of `digest`, which must refuse with `code` at slot + /// `digest` and change neither phase 1's stories nor the orders. + pub(super) fn refused_with(store: &SqliteStore, digest: Hash, code: &str) -> Value { + let before = head(store); + let refusal = judge(store, &project(), digest).expect_err("the approval is refused"); + assert_refused(&refusal, code); + assert_eq!(head(store), before); + assert_eq!(phase_1_stories(store), [1]); + assert!(issued(store).is_empty()); + refusal + } + + #[test] + fn a_planner_launched_before_its_commitment_is_approved_or_a_refused_approval_recording_is_caught() + { + let (_dir, store) = store_c(); + let e1 = edit(&store, &[1, 4], O, R1, T4); + let e2 = edit(&store, &[4, 1], O2, R2, T5); + refused_with(&store, e1, "stale-draft"); + + let answer = approve_commitment(&store, e2, R3, T6); + assert_eq!(answer["status"], "ok", "{answer}"); + assert_eq!(phase_1_stories(&store), [4, 1]); + let events = history(&store); + let named = of_type(&events, "plan.continuation") + .into_iter() + .find(|event| event.payload["edit"] == e2.to_hex()) + .expect("E2 has its continuation") + .payload["work_order"] + .clone(); + assert_eq!(named, O2); + let orders = issued(&store); + assert_eq!(orders.len(), 1); + assert_eq!(orders[0].stream, "phase/1"); + assert_eq!(orders[0].payload["subject"], "phase/1"); + assert_eq!(orders[0].payload["id"], named); + assert_eq!(bound_stories(&store, &orders[0]), [4, 1]); + assert_eq!(answer["work_order"], named, "{answer}"); + + // Story 4 moved to phase 2 by an approved reassignment. + let (_dir, store) = store_c(); + let e1 = edit(&store, &[1, 4], O, R1, T4); + let reassign = submit_change( + &store, + ChangeKind::StoryReassign, + &json!({"story": 4, "phase": 2}), + R2, + T5, + ) + .unwrap(); + let judged = judge(&store, &project(), digest_of(&reassign)).unwrap(); + approve(&store, Some(&judged), R3, 6, T5).unwrap(); + let refusal = refused_with(&store, e1, "story-in-phase"); + assert_eq!(refusal["details"], json!({"story": 4, "phase": 2})); + + // Phase 2 made active. + let (_dir, store) = store_c(); + let e1 = edit(&store, &[1, 4], O, R1, T4); + activate_phase_2(&store, R2); + let refusal = refused_with(&store, e1, "phase-active"); + assert_eq!(refusal["details"], json!({"phase": 2})); + + // Story 4's truths emptied. + let (_dir, store) = store_c(); + let e1 = edit(&store, &[1, 4], O, R1, T4); + append( + &store, + R2, + T5, + vec![refined( + 4, + "4e4e4e4e-4e4e-4e4e-8e4e-4e4e4e4e4e4e", + Vec::new(), + )], + ); + let refusal = refused_with(&store, e1, "story-unrefined"); + assert_eq!(refusal["details"], json!({"story": 4})); + } + + /// E1's second step as `Ada Owner` under P0 and N0, as + /// `request_id` at `at`. + fn second_step(store: &SqliteStore, judged: &Judged, request_id: &str, at: &str) -> Value { + let (policy, names) = (p0(), n0()); + record_commitment( + store, + &command(APPROVE_COMMAND, request_id, 6, at), + judged, + OWNER, + OrderRoute { + policy: &policy, + host: Host::ClaudeCode, + names: &names, + }, + ) + } + + #[test] + fn a_commitment_landing_beside_a_moved_truth_or_a_new_planner_order_is_caught() { + let (_dir, store) = store_c(); + let e1 = edit(&store, &[1, 4], O, R1, T4); + let judged = judge(&store, &project(), e1).unwrap(); + append( + &store, + R2, + T5, + vec![refined( + 4, + "4f4f4f4f-4f4f-4f4f-8f4f-4f4f4f4f4f4f", + vec![versioned(t1())], + )], + ); + let before = head(&store); + assert_busy(&second_step(&store, &judged, R3, T6)); + assert_eq!(head(&store), before); + + let (_dir, store) = store_c(); + let e1 = edit(&store, &[1, 4], O, R1, T4); + let judged = judge(&store, &project(), e1).unwrap(); + let (command_q, q) = crate::planning::order::tests::prepared(&store, &[1], O2, R2, T5); + let issued_q = crate::planning::order::issue(&store, &command_q, &q); + assert_eq!(issued_q["status"], "ok", "{issued_q}"); + let before = head(&store); + assert_busy(&second_step(&store, &judged, R3, T6)); + assert_eq!(head(&store), before); + assert_eq!(issued(&store).len(), 1); + } + + #[test] + fn a_commitment_approval_rerun_naming_no_order_or_recording_is_caught() { + let (dir, store) = store_c(); + let e2 = edit(&store, &[4, 1], O, R1, T4); + let approved = approve_commitment(&store, e2, R2, T5); + assert_eq!(approved["status"], "ok", "{approved}"); + drop(store); + let store = reopen(&dir); + + let before = head(&store); + let refusal = judge(&store, &project(), e2).expect_err("E2 is approved"); + assert_refused(&refusal, "draft-approved"); + assert_eq!(refusal["details"]["work_order"], O, "{refusal}"); + assert!(refusal["reason"].as_str().unwrap().contains(O), "{refusal}"); + assert_eq!(head(&store), before); + assert_eq!(issued(&store).len(), 1); + } + + #[test] + fn a_commitment_approved_beside_a_pending_planner_order_without_naming_it_is_caught() { + let (_dir, store) = store_c(); + let e1 = edit(&store, &[1, 4], O, R1, T4); + let (command_q, q) = crate::planning::order::tests::prepared(&store, &[1], O2, R2, T5); + let issued_q = crate::planning::order::issue(&store, &command_q, &q); + assert_eq!(issued_q["status"], "ok", "{issued_q}"); + + let before = head(&store); + let refusal = judge(&store, &project(), e1).expect_err("Q is pending"); + assert_refused(&refusal, "planner-order-pending"); + assert_eq!(refusal["details"], json!({"work_order": O2})); + assert_eq!(head(&store), before); + } + + #[test] + fn a_commitment_landing_beside_a_newly_active_phase_is_caught() { + let (_dir, store) = store_c(); + let e1 = edit(&store, &[1, 4], O, R1, T4); + let judged = judge(&store, &project(), e1).unwrap(); + activate_phase_2(&store, R2); + let before = head(&store); + assert_busy(&second_step(&store, &judged, R3, T6)); + assert_eq!(head(&store), before); + assert_eq!(phase_1_stories(&store), [1]); + assert!(issued(&store).is_empty()); + } + + #[test] + fn a_plain_phase_edit_approval_issuing_an_order_is_caught() { + let (_dir, store) = store_c(); + let fields = baley_core::scope::PhaseFields { + goal: Some("The owner approves every change".into()), + ..Default::default() + }; + let digest = crate::scope::submit::submit_phase_edit( + &store, + &command(crate::scope::submit::SUBMIT_COMMAND, R1, 7, T4), + 2, + &fields, + None, + ) + .unwrap(); + let judged = judge(&store, &project(), digest).unwrap(); + let answer = second_step(&store, &judged, R2, T5); + assert_eq!(answer["status"], "ok", "{answer}"); + assert_eq!( + read::phase(&store, &project(), 2).unwrap().goal, + "The owner approves every change" + ); + assert!(issued(&store).is_empty()); + } + } } diff --git a/crates/baley/src/scope/command.rs b/crates/baley/src/scope/command.rs index 65fd39af..688f0c26 100644 --- a/crates/baley/src/scope/command.rs +++ b/crates/baley/src/scope/command.rs @@ -10,6 +10,12 @@ //! truths approve ` and `baley story refinement ` are //! `refine::command`'s: the first approves a story's truth draft as `scope //! approve` approves a scope draft, the second prints a story's refinement. +//! A plan draft is approved only by `baley plan approve `: `scope +//! approve` refuses its digest naming that command, and `scope preview` +//! prints the plan draft with it (D-05). +//! Approving a commitment, the `phase edit` a session's `phase-plan` drafted +//! for a changed selection, also issues the phase's planner order, routed for +//! Claude Code, and prints its id (D-01). //! //! Gathering finds the project and opens the ledger; judging, the arguments, //! the commands an approval or a submission is recorded under and what is @@ -22,17 +28,19 @@ use std::path::PathBuf; use std::process::ExitCode; use baley_core::capture::NO_SUCH_PHASE; +use baley_core::plan::{PLAN_KIND, read_plan_draft}; use baley_core::policy::recorded::recorded_policy; -use baley_core::policy::{CONFIG_UNAVAILABLE, EffectivePolicy, SettingsFile}; +use baley_core::policy::{CONFIG_UNAVAILABLE, EffectivePolicy, Host, SettingsFile}; use baley_core::scope::{ - ChangeKind, ChangeSubmission, Destination, START_KIND, ScopeChange, UNKNOWN_DRAFT, - judge_change, judge_submission, + ChangeKind, ChangeSubmission, DRAFT_APPROVED, Destination, START_KIND, ScopeChange, + UNKNOWN_DRAFT, judge_change, judge_submission, }; use baley_core::truth::{STORY_TRUTHS, TruthSubmission, Versions, judge_truths, versions}; use baley_store::{ Actor, Admin, CanonicalError, Command, CommandKind, Hash, ProjectId, RequestId, request_digest, }; use baley_store_sqlite::SqliteStore; +use serde::Deserialize; use serde_json::{Value, json}; use crate::checkout::{Site, gather_and_admit}; @@ -46,12 +54,13 @@ use crate::mcp::scope::change_kind; use crate::providers::identity; use crate::refine::command::{sentence, truth_detail}; use crate::refine::submit::{current_truths, mark_str}; -use crate::scope::approve::{self, APPROVE_COMMAND}; +use crate::scope::approve::{self, APPROVE_COMMAND, OrderRoute}; use crate::scope::read::{ self, BacklogStory, Detail, Draft, NO_SUCH_STORY, Phase, Preview, PreviewError, ReadError, Roadmap, Story, }; use crate::scope::submit::{self, SUBMIT_COMMAND}; +use crate::work_order::route::host_names; use crate::{init, policy_step, settings}; /// `baley scope`: the owner's approval of scope, and its reads. @@ -323,6 +332,12 @@ pub(crate) fn open(checkout: &Checkout) -> Result { /// so a refused approval records nothing at all. The owner is read over the /// policy the policy step recorded, and the second step records the /// approval under the version in force. +/// +/// A commitment's approval issues its planner order (D-01), so its policy +/// step records Claude Code's effective policy, as a session's write records +/// its host's, and the order is routed for Claude Code with its accepted +/// model names. Claude Code is the only host (`Host::ALL`); a second host +/// needs a host choice for an order the terminal issues. fn approve(digest: &str) -> Result { let digest = judge_digest(digest)?; let checkout = checkout()?; @@ -330,7 +345,11 @@ fn approve(digest: &str) -> Result { let project = &checkout.project; let judged = approve::judge(&store, project, digest).map_err(|answer| answer_render(&answer))?; - let (policy, version) = admitted(&store, &checkout)?; + let [host] = Host::ALL; + let (policy, version) = match judged.planner_order() { + Some(_) => host_admitted(&store, &checkout, host)?, + None => admitted(&store, &checkout)?, + }; let owner = identity::owner(identity::owner_name(&policy), &mut crate::process::System) .map_err(Render::refusal)?; @@ -342,8 +361,19 @@ fn approve(digest: &str) -> Result { &SystemClock::now(), ) .map_err(|e| Render::refusal(e.to_string()))?; - let recorded = approve::record(&store, &command, Some(&judged), &owner); - Ok(answer_render(&submit::answer(recorded, &store))) + if judged.planner_order().is_none() { + let recorded = approve::record(&store, &command, Some(&judged), &owner); + return Ok(answer_render(&submit::answer(recorded, &store))); + } + let names = host_names(&store, host).map_err(|e| display::store_error(&e, Some(&project.0)))?; + let route = OrderRoute { + policy: &policy, + host, + names: &names, + }; + Ok(answer_render(&approve::record_commitment( + &store, &command, &judged, &owner, route, + ))) } /// One of the owner's change commands: the words are judged before anything @@ -380,14 +410,44 @@ pub(crate) fn admitted( store: &SqliteStore, checkout: &Checkout, ) -> Result<(EffectivePolicy, u64), Render> { - let project = &checkout.project; + stepped(store, checkout, effective(checkout, None)?) +} + +/// [`admitted`] for an owner command that issues an order for `host`: the +/// policy step records `host`'s effective policy, so the order's route names +/// a recorded policy version. +pub(crate) fn host_admitted( + store: &SqliteStore, + checkout: &Checkout, + host: Host, +) -> Result<(EffectivePolicy, u64), Render> { + stepped(store, checkout, effective(checkout, Some(host))?) +} + +/// The checkout's effective policy for `host`, or with none, read from both +/// settings files and judged, recording nothing, so a command can judge +/// against it before it records. +pub(crate) fn effective( + checkout: &Checkout, + host: Option, +) -> Result { let reads = policy_step::gather( &checkout.folders.config, &checkout.root, checkout.working.as_ref(), &mut crate::process::System, ); - let policy = policy_step::build(&reads, None).map_err(|e| Render::refusal(e.to_string()))?; + policy_step::build(&reads, host).map_err(|e| Render::refusal(e.to_string())) +} + +/// Checkout admission, then the policy step recording `policy`. Gives the +/// policy and the version the step returned. +fn stepped( + store: &SqliteStore, + checkout: &Checkout, + policy: EffectivePolicy, +) -> Result<(EffectivePolicy, u64), Render> { + let project = &checkout.project; let recorded = recorded_policy(&checkout.root, &policy).map_err(|e| Render::refusal(e.to_string()))?; let site = Site { @@ -506,8 +566,31 @@ pub(crate) fn owner_command( /// three lines, an empty list as `none`, exit 0; a refusal as `: /// `, exit 2, a stale draft's naming the first part that differs, a /// malformed submission's naming its section and field; a failure the same -/// way, exit 1. +/// way, exit 1. A commitment's receipt, or a `draft-approved` refusal of one, +/// names the planner order its approval issued, and a further line says so +/// with the order's id (D-01). Any other refusal naming an order, such as +/// `planner-order-pending`, names one this approval did not issue, so it +/// gets no such line. pub(crate) fn answer_render(answer: &Value) -> Render { + let mut render = approval_lines(answer); + let order = match answer["status"].as_str() { + Some("ok") => answer["work_order"].as_str(), + Some("refused") if answer["code"] == DRAFT_APPROVED => { + answer["details"]["work_order"].as_str() + } + _ => None, + }; + if let Some(order) = order { + render.lines.push(format!( + "planner work order: {}, which a session's phase-plan with the same stories launches", + escaped(order) + )); + } + render +} + +/// [`answer_render`]'s lines before any planner order's. +fn approval_lines(answer: &Value) -> Render { let text = |name: &str| escaped(answer[name].as_str().unwrap_or_default()); let joined = |name: &str| { let numbers: Vec = answer[name] @@ -703,14 +786,16 @@ pub(crate) fn command_change(words: &ChangeWords) -> Result Render { match read::draft(store, project, digest) { Ok(Draft::Held(preview)) if preview.kind == STORY_TRUTHS => { truth_preview(store, project, &preview) } + Ok(Draft::Held(preview)) if preview.kind == PLAN_KIND => plan_preview(&preview), read => preview_render(read), } } @@ -799,6 +884,127 @@ fn truth_preview_render( printed(lines) } +/// A plan draft's body as its preview reads it: the members it prints. The +/// body was judged whole at submit; here it is only read back. +#[derive(Deserialize)] +struct PlanBody { + phase: u32, + stories: Vec, + files: Vec, + directories: Vec, + tasks: Vec, + evidence_map: Vec, + questions: Vec, +} + +/// One task as a plan body holds it. +#[derive(Deserialize)] +struct PlanTask { + id: String, + title: String, + files: Vec, + verify: Vec, +} + +/// One evidence item as a plan body holds it; a check's level is in its +/// `spec`. +#[derive(Deserialize)] +struct PlanItem { + id: String, + story: u32, + truth: String, + truth_version: u32, + kind: String, + spec: Value, +} + +/// One question as a plan body holds it. +#[derive(Deserialize)] +struct PlanQuestion { + id: String, + question: String, + recommended: String, +} + +/// What `scope preview` prints for a held plan draft (design 0005 `plan +/// submit` preview, D-05): the header every draft prints; for a +/// replacement, `replaces plan approved at `; the phase, the +/// stories and the lease's files and directories; each task as `task : +/// ` with its files and one `verify:` line per command; each evidence +/// item as `item <id>: story <s>, truth <t> version <v>, <kind>`, with +/// `level <level>` for a check; each question as `question <id>: <text>` +/// with its recommended answer; and the command that approves it. A body +/// that does not read back as a plan prints the unavailable line a change +/// prints. +fn plan_preview(preview: &Preview) -> Render { + let recorded = read_plan_draft(&preview.submission); + let body = recorded + .as_ref() + .and_then(|recorded| serde_json::from_value::<PlanBody>(recorded.plan.clone()).ok()); + let (Some(recorded), Some(body)) = (recorded, body) else { + return unavailable("the draft is recorded, but its body no longer reads as a plan"); + }; + let texts = |items: &[String]| or_none(items.iter().map(|item| escaped(item)).collect()); + let mut lines = vec![format!( + "draft {} ({}), submitted {}", + preview.digest.to_hex(), + escaped(&preview.kind), + escaped(&preview.recorded_at) + )]; + if let Some(replaces) = recorded.replaces { + lines.push(format!( + "replaces plan {} approved at {}", + replaces.plan, + replaces.digest.to_hex() + )); + } + lines.extend([ + format!("phase: {}", body.phase), + format!("stories: {}", list(&body.stories)), + format!("files: {}", texts(&body.files)), + format!("directories: {}", texts(&body.directories)), + ]); + for task in &body.tasks { + lines.push(format!( + "task {}: {}", + escaped(&task.id), + escaped(&task.title) + )); + lines.push(format!(" files: {}", texts(&task.files))); + for command in &task.verify { + lines.push(format!(" verify: {}", escaped(command))); + } + } + for item in &body.evidence_map { + let mut line = format!( + "item {}: story {}, truth {} version {}, {}", + escaped(&item.id), + item.story, + escaped(&item.truth), + item.truth_version, + escaped(&item.kind) + ); + if item.kind == "check" { + let level = item.spec["level"].as_str().unwrap_or_default(); + line = format!("{line}, level {}", escaped(level)); + } + lines.push(line); + } + for question in &body.questions { + lines.push(format!( + "question {}: {}", + escaped(&question.id), + escaped(&question.question) + )); + lines.push(format!(" recommended: {}", escaped(&question.recommended))); + } + lines.push(format!( + "approve it with: baley plan approve {}", + preview.digest.to_hex() + )); + printed(lines) +} + /// What `scope preview` prints for a draft read: the header, the /// description, the stories by label and the phases by position, each with /// its detail and dependencies, since that is what the owner approves. A @@ -1383,6 +1589,60 @@ mod tests { assert_eq!((busy.code, busy.error), (1, true)); } + #[test] + fn a_commitment_approval_printed_without_its_order_or_a_plain_one_naming_one_is_caught() { + const O: &str = "1f2e3d4c-5b6a-4978-8695-a4b3c2d1e0f1"; + let names_order = |lines: &[String]| { + lines + .iter() + .any(|line| line.contains(O) && line.contains("phase-plan")) + }; + let plain = json!({"status": "ok", "kind": "phase-edit", "digest": D, + "owner": "Ada Owner", "at": T, "phases": [], "stories": []}); + let mut committed = plain.clone(); + committed["work_order"] = json!(O); + committed["prompt"] = json!(format!("Read Baley work order {O} and follow it.")); + + let done = answer_render(&committed); + assert!(names_order(&done.lines), "{:?}", done.lines); + assert_eq!((done.code, done.error), (0, false)); + + let done = answer_render(&plain); + assert_eq!( + done.lines, + [ + format!("approved the phase-edit submission {D} as Ada Owner at {T}"), + "phases: none".into(), + "stories: none".into(), + ] + ); + + let rerun = answer_render(&json!({"status": "refused", "code": "draft-approved", + "reason": "this draft was already approved after its latest submission, so it was not approved again. The details name that approval", + "slot": "digest", + "details": {"owner": "Ada Owner", "at": T, "work_order": O}})); + assert!( + rerun.lines[0].starts_with("draft-approved:"), + "{:?}", + rerun.lines + ); + assert!(names_order(&rerun.lines), "{:?}", rerun.lines); + assert_eq!((rerun.code, rerun.error), (2, true)); + } + + #[test] + fn a_pending_planner_order_refusal_printed_as_this_approvals_order_is_caught() { + // Q is another selection's order, still pending, which this + // approval did not issue and a phase-plan cannot launch. + const Q: &str = "2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"; + let reason = "the phase's planner work order Q is still pending, and a phase has one live planner order, so nothing was approved"; + let pending = answer_render(&json!({"status": "refused", + "code": "planner-order-pending", "reason": reason, "slot": "digest", + "details": {"work_order": Q}})); + assert_eq!(pending.lines, [format!("planner-order-pending: {reason}")]); + assert_eq!((pending.code, pending.error), (2, true)); + } + #[test] fn a_malformed_submission_refusal_printed_without_its_section_and_field_is_caught() { let reason = "a field of the submission is missing, blank, of the wrong type, unknown or out of range, so nothing was recorded. The details name it"; @@ -1870,4 +2130,50 @@ mod tests { "{lines:?}" ); } + #[test] + fn a_plan_draft_previewed_as_unavailable_or_without_its_approving_command_is_caught() { + use crate::planning::approve::tests::{approved, digest_of}; + use crate::planning::fixtures::{p0, pl1, pl1r, pl2, plan_replaced, store_c}; + use crate::planning::order::tests::O; + use crate::planning::submit::tests::{order_o, plan_submitted}; + use crate::scope::fixtures::{R1, R2, R3, R4, R5, T5, T6, T7, project}; + + let (_dir, store) = store_c(); + order_o(&store, R1); + let x2 = digest_of(&plan_submitted(&store, &pl2(), O, None, R2, T5)); + let render = preview(&store, &project(), x2); + let lines = shown(&render); + let x2 = x2.to_hex(); + for line in [ + format!("draft {x2} (plan), submitted {T5}").as_str(), + "phase: 1", + "stories: 1", + "task k1: Record", + " files: src/ledger.rs", + " verify: cargo test ledger", + "item e1: story 1, truth t1 version 1, check, level unit", + "question q1: Which store holds the ledger?", + " recommended: SQLite", + format!("approve it with: baley plan approve {x2}").as_str(), + ] { + assert!(lines.contains(&line), "{line} in {lines:?}"); + } + assert!( + !lines.iter().any(|line| line.starts_with("replaces")), + "{lines:?}" + ); + + let x1 = digest_of(&plan_submitted(&store, &pl1(), O, None, R3, T6)); + let answer = approved(&store, x1, &p0(), R4, T6); + assert_eq!(answer["status"], "ok", "{answer}"); + let x1r = digest_of(&plan_replaced(&store, &pl1r(), O, 1, x1, R5, T7)); + let render = preview(&store, &project(), x1r); + let lines = shown(&render); + for line in [ + format!("replaces plan 1 approved at {}", x1.to_hex()).as_str(), + format!("approve it with: baley plan approve {}", x1r.to_hex()).as_str(), + ] { + assert!(lines.contains(&line), "{line} in {lines:?}"); + } + } } diff --git a/crates/baley/src/scope/submit.rs b/crates/baley/src/scope/submit.rs index c363cbb3..acc1919a 100644 --- a/crates/baley/src/scope/submit.rs +++ b/crates/baley/src/scope/submit.rs @@ -13,6 +13,9 @@ use std::collections::BTreeMap; +use baley_core::plan::{ + PLAN_CONTINUATION, PLAN_CONTINUATION_VERSION, continuation_payload, phase_stream, +}; use baley_core::policy::Role; use baley_core::scope::{ ChangeKind, ChangeSubmission, PROJECT_ALREADY_STARTED, PROJECT_STREAM, PhaseFields, @@ -23,9 +26,9 @@ use baley_core::scope::{ use baley_core::work_order::{NO_SUCH_WORK_ORDER, START_SUBJECT, WRONG_WORK_ORDER}; use baley_store::{ Absence, Command, Decision, EVENT_PAGE_BOUND, EventMatch, Hash, HistoryFilter, - InstructionEvidence, Ledger, NewEvent, Observed, OutcomeKind, PageRequest, Payloads, ProjectId, - REQUEST_VIEW, Recorded, Refusal as StoreRefusal, RetentionClass, StoreError, StreamName, Views, - request_key, request_state, + InstructionEvidence, Ledger, NewEvent, Observed, ObservedDocument, OutcomeKind, PageRequest, + Payloads, ProjectId, REQUEST_VIEW, Recorded, Refusal as StoreRefusal, RetentionClass, + StoreError, StreamName, Views, request_key, request_state, }; use serde_json::{Map, Value, json}; @@ -326,20 +329,70 @@ fn listed(noun: &str, numbers: &[u32]) -> String { /// `read`, the check's, named is unchanged, so a change whose scope moved /// since its check records nothing and `answer` gives `failed` /// `ledger-busy`. A decision asked to run without the check's read records -/// nothing. The answer is the receipt, which never holds the change. +/// nothing. The answer is the receipt, which never holds the change. It +/// records no planning continuation and observes nothing more; T9's `phase +/// plan` records one through [`submit_phase_edit`]. pub fn record_change<L: Ledger + ?Sized>( store: &L, command: &Command, change: &ChangeSubmission, read: Option<&ScopeRead>, +) -> Result<Recorded, StoreError> { + record_with(store, command, change, read, None) +} + +/// A planning continuation recorded with a `phase edit` of phase `phase`'s +/// stories (D-09): the selection the edit commits and the planner order its +/// approval issues, with the documents the caller read when it chose to +/// draft and what it relied on being absent. +#[derive(Debug, Clone, Copy)] +pub struct PlanningContinuation<'a> { + /// The selection, in order. + pub stories: &'a [u32], + /// The id of the planner order the edit's approval issues, fixed now so + /// a rerun finds the same order. + pub work_order: &'a str, + /// The documents the caller read when it chose to draft, at the sequence + /// that produced each, so an order issued or a story moved since makes + /// the call `ledger-busy` with nothing recorded. + pub documents: &'a [ObservedDocument], + /// What the caller relied on being absent when it chose to draft, such + /// as an active phase an empty read of `phase_plan`'s status index left + /// no document for, so one recorded since makes the call `ledger-busy` + /// with nothing recorded. + pub absences: &'a [Absence], +} + +/// [`record_change`] with a planning continuation of phase `phase`: in the +/// same transaction, after the draft, one `plan.continuation` on `phase/<n>` +/// naming the phase, the selection in order, the draft's digest and the +/// order, and the decision observes the continuation's documents and +/// declares its absences. The receipt then also names the phase, the +/// selection and the commands `baley scope preview <digest>` and `baley +/// scope approve <digest>`, the answer `phase-plan` gives, so a replay of +/// the call is answered the same from its record. Without one it records, +/// observes and answers exactly what `record_change` does. +fn record_with<L: Ledger + ?Sized>( + store: &L, + command: &Command, + change: &ChangeSubmission, + read: Option<&ScopeRead>, + continuation: Option<(u32, PlanningContinuation<'_>)>, ) -> Result<Recorded, StoreError> { let kind = change.kind().as_str(); - let receipt = json!({ + let digest = change.digest().to_hex(); + let mut receipt = json!({ "status": "ok", - "digest": change.digest().to_hex(), + "digest": digest, "kind": kind, "recorded_at": command.recorded_at, }); + if let Some((phase, continuation)) = continuation { + receipt["phase"] = json!(phase); + receipt["stories"] = json!(continuation.stories); + receipt["preview"] = json!(format!("baley scope preview {digest}")); + receipt["approve"] = json!(format!("baley scope approve {digest}")); + } store.transact(command, &mut |tx| { let Some(read) = read else { return Err(StoreError::Unavailable( @@ -356,11 +409,29 @@ pub fn record_change<L: Ledger + ?Sized>( payload: submitted_payload(change.digest(), kind, change.target(), &body), attachments: vec![body], })?; + let mut observed = Observed::default(); + if let Some((phase, continuation)) = continuation { + tx.append(NewEvent { + stream: StreamName(phase_stream(phase)), + type_name: PLAN_CONTINUATION.into(), + type_version: PLAN_CONTINUATION_VERSION, + git: None, + payload: continuation_payload( + phase, + continuation.stories, + change.digest(), + continuation.work_order, + ), + attachments: Vec::new(), + })?; + observed.documents = continuation.documents.to_vec(); + observed.absences = continuation.absences.to_vec(); + } Ok(Decision { kind: OutcomeKind::Done, answer: receipt.clone(), sensitive: false, - observed: Observed::default(), + observed, git: None, }) }) @@ -380,12 +451,44 @@ pub fn record_change<L: Ledger + ?Sized>( /// change recorded under the same command is a reused request id, since this /// edit was never recorded. The draft is approved through `approve::judge` /// and `approve::record`. +/// +/// T9's `phase plan` passes `continuation` for a changed selection, and the +/// edit is then recorded with its `plan.continuation` in one transaction or +/// not at all, observing the documents the caller read and declaring what it +/// relied on being absent (D-09). With none, +/// the edit records exactly what `record_change` records. pub fn submit_phase_edit<S: Ledger + Views + Payloads>( store: &S, command: &Command, phase: u32, fields: &PhaseFields, + continuation: Option<PlanningContinuation<'_>>, ) -> Result<Hash, Value> { + submit_edit(store, command, phase, fields, continuation).map(|(digest, _)| digest) +} + +/// [`submit_phase_edit`] with `continuation`, answered with the recorded +/// receipt instead of its digest: the receipt `phase-plan` gives for a +/// changed selection, which a replay of the same request is answered with +/// from its record. +pub fn submit_planning_edit<S: Ledger + Views + Payloads>( + store: &S, + command: &Command, + phase: u32, + fields: &PhaseFields, + continuation: PlanningContinuation<'_>, +) -> Result<Value, Value> { + submit_edit(store, command, phase, fields, Some(continuation)).map(|(_, receipt)| receipt) +} + +/// [`submit_phase_edit`]'s work, giving the digest and the recorded receipt. +fn submit_edit<S: Ledger + Views + Payloads>( + store: &S, + command: &Command, + phase: u32, + fields: &PhaseFields, + continuation: Option<PlanningContinuation<'_>>, +) -> Result<(Hash, Value), Value> { let mut members = Map::new(); members.insert("phase".into(), json!(phase)); let texts = [ @@ -409,25 +512,26 @@ pub fn submit_phase_edit<S: Ledger + Views + Payloads>( } let change = judge_change(ChangeKind::PhaseEdit, &Value::Object(members)) .map_err(|refusal| submission_refused(&refusal))?; + let continuation = continuation.map(|continuation| (phase, continuation)); let result = if held(store, command)? { - record_change(store, command, &change, None) + record_with(store, command, &change, None, continuation) } else { match check_change(store, &command.project, &change) { - Ok(read) => record_change(store, command, &change, Some(&read)), + Ok(read) => record_with(store, command, &change, Some(&read), continuation), // The original can commit between the lookup and the check, and // the check may refuse because of it, so the request is looked // up again before a refusal is answered. Err(refusal) if !held(store, command)? => return Err(refusal), - Err(_) => record_change(store, command, &change, None), + Err(_) => record_with(store, command, &change, None, continuation), } }; recorded_digest(answer(result, store), &change) } /// The digest `answer`, a scope call's recorded answer, names when it is -/// `change`'s. An `ok` receipt for another change is a reused request id; -/// any other answer is returned as it is. -fn recorded_digest(answer: Value, change: &ChangeSubmission) -> Result<Hash, Value> { +/// `change`'s, with that answer. An `ok` receipt for another change is a +/// reused request id; any other answer is returned as it is. +fn recorded_digest(answer: Value, change: &ChangeSubmission) -> Result<(Hash, Value), Value> { if answer["status"] != "ok" { return Err(answer); } @@ -436,7 +540,7 @@ fn recorded_digest(answer: Value, change: &ChangeSubmission) -> Result<Hash, Val .and_then(Value::as_str) .and_then(Hash::from_hex) { - Some(digest) if digest == change.digest() => Ok(digest), + Some(digest) if digest == change.digest() => Ok((digest, answer)), _ => Err(request_id_reused()), } } @@ -820,7 +924,7 @@ mod tests { ..PhaseFields::default() }; let digest = - submit_phase_edit(&store, &command(SUBMIT_COMMAND, R4, 4, T4), 2, &goal).unwrap(); + submit_phase_edit(&store, &command(SUBMIT_COMMAND, R4, 4, T4), 2, &goal, None).unwrap(); assert_eq!(digest.to_hex(), E_B_DIGEST); let events = history(&store); let drafts: Vec<&Value> = of_type(&events, "scope.submitted") @@ -833,7 +937,8 @@ mod tests { let before = head(&store); let empty = PhaseFields::default(); let refusal = - submit_phase_edit(&store, &command(SUBMIT_COMMAND, R6, 6, T5), 2, &empty).unwrap_err(); + submit_phase_edit(&store, &command(SUBMIT_COMMAND, R6, 6, T5), 2, &empty, None) + .unwrap_err(); assert_eq!(refusal["status"], "refused", "{refusal}"); assert_eq!(refusal["code"], "malformed-submission", "{refusal}"); assert_eq!(refusal["slot"], "submission", "{refusal}"); @@ -854,7 +959,7 @@ mod tests { ..PhaseFields::default() }; let edit = command(SUBMIT_COMMAND, R4, 4, T4); - submit_phase_edit(&store, &edit, 2, &goal).unwrap(); + submit_phase_edit(&store, &edit, 2, &goal, None).unwrap(); append( &store, R6, @@ -867,7 +972,7 @@ mod tests { ); let before = head(&store); - let again = submit_phase_edit(&store, &edit, 2, &goal); + let again = submit_phase_edit(&store, &edit, 2, &goal, None); assert_eq!(again, Ok(Hash::from_hex(E_B_DIGEST).unwrap())); assert_eq!(head(&store), before); let drafts = of_type(&history(&store), "scope.submitted") @@ -1029,7 +1134,7 @@ mod tests { let racing = CommitsAtLookup { store: &store, land: RefCell::new(Some(Box::new(|| { - submit_phase_edit(&store, &edit, 2, &goal).unwrap(); + submit_phase_edit(&store, &edit, 2, &goal, None).unwrap(); append( &store, R6, @@ -1043,7 +1148,7 @@ mod tests { }))), }; - let retry = submit_phase_edit(&racing, &edit, 2, &goal); + let retry = submit_phase_edit(&racing, &edit, 2, &goal, None); assert!(racing.land.borrow().is_none(), "the lookup was not made"); assert_eq!(retry, Ok(Hash::from_hex(E_B_DIGEST).unwrap())); let drafts = of_type(&history(&store), "scope.submitted") @@ -1063,20 +1168,20 @@ mod tests { ..PhaseFields::default() }; let edit = command(SUBMIT_COMMAND, R4, 4, T4); - submit_phase_edit(&store, &edit, 2, &goal).unwrap(); + submit_phase_edit(&store, &edit, 2, &goal, None).unwrap(); let before = head(&store); let name = PhaseFields { name: Some("Approvals".into()), ..PhaseFields::default() }; - let other = submit_phase_edit(&store, &edit, 2, &name).unwrap_err(); + let other = submit_phase_edit(&store, &edit, 2, &name, None).unwrap_err(); assert_eq!(other["status"], "refused", "{other}"); assert_eq!(other["code"], "request-id-reuse", "{other}"); assert_eq!(other["slot"], "request_id", "{other}"); assert_eq!(head(&store), before); - let again = submit_phase_edit(&store, &edit, 2, &goal); + let again = submit_phase_edit(&store, &edit, 2, &goal, None); assert_eq!(again, Ok(Hash::from_hex(E_B_DIGEST).unwrap())); assert_eq!(head(&store), before); } @@ -1164,4 +1269,127 @@ mod tests { } assert_eq!(head(&store), before); } + + /// The JSON body a `scope.submitted` attaches. + fn submitted_body(store: &baley_store_sqlite::SqliteStore, event: &Event) -> Value { + let body = PayloadRef::from_value(&event.payload["body"]).unwrap(); + let PayloadBody::Present(mut reader) = store.open(&body.hash).unwrap() else { + panic!("the body is present"); + }; + let mut bytes = Vec::new(); + reader.read_to_end(&mut bytes).unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + + fn on_stream<'a>(events: &'a [Event], stream: &str) -> Vec<&'a Event> { + events + .iter() + .filter(|event| event.stream == stream) + .collect() + } + + #[test] + fn a_continuation_recorded_apart_from_its_edit_is_caught() { + use baley_core::scope::{ChangeKind, PHASE_VIEW, PhaseFields, phase_key}; + + use crate::planning::fixtures::store_c; + use crate::scope::approve::{self, APPROVE_COMMAND}; + + const O: &str = "1f2e3d4c-5b6a-4978-8695-a4b3c2d1e0f1"; + let (_dir, store) = store_c(); + let stories = PhaseFields { + stories: Some(vec![1, 4]), + ..PhaseFields::default() + }; + let continuation = PlanningContinuation { + stories: &[1, 4], + work_order: O, + documents: &[], + absences: &[], + }; + let edit = command(SUBMIT_COMMAND, R1, 1, T4); + let digest = submit_phase_edit(&store, &edit, 1, &stories, Some(continuation)).unwrap(); + + let events = history(&store); + let drafts: Vec<&Event> = of_type(&events, "scope.submitted") + .into_iter() + .filter(|event| event.payload["kind"] == "phase-edit") + .collect(); + assert_eq!(drafts.len(), 1); + assert_eq!(drafts[0].payload["digest"], digest.to_hex()); + assert_eq!( + submitted_body(&store, drafts[0]), + json!({"kind": "phase-edit", "phase": 1, "stories": [1, 4]}) + ); + let continuations = of_type(&events, "plan.continuation"); + assert_eq!(continuations.len(), 1); + assert_eq!(continuations[0].stream, "phase/1"); + assert_eq!( + continuations[0].payload, + json!({"phase": 1, "stories": [1, 4], "edit": digest.to_hex(), "work_order": O}) + ); + assert_eq!(continuations[0].request_id, drafts[0].request_id); + assert_eq!(continuations[0].request_id.0, R1); + + // Phase 2's document as the caller read it, before an approved edit + // of phase 2 moves it. + let read = store + .get(&project(), PHASE_VIEW, &phase_key(2)) + .unwrap() + .expect("phase 2 is held"); + let observed = [ObservedDocument { + view: PHASE_VIEW.into(), + key: phase_key(2), + produced_seq: Some(read.produced_seq), + }]; + let e_b = submit_change(&store, ChangeKind::PhaseEdit, &e_b(), R2, T5).unwrap(); + let judged = approve::judge(&store, &project(), digest_of(&e_b)).unwrap(); + approve::record( + &store, + &command(APPROVE_COMMAND, R3, 3, T5), + Some(&judged), + "Ada Owner", + ) + .unwrap(); + let before = head(&store); + let continuation = PlanningContinuation { + documents: &observed, + ..continuation + }; + let busy = submit_phase_edit( + &store, + &command(SUBMIT_COMMAND, R4, 1, T6), + 1, + &stories, + Some(continuation), + ) + .unwrap_err(); + assert_failed(&busy, "ledger-busy", "ledger", true); + assert_eq!(head(&store), before); + assert_eq!(of_type(&history(&store), "plan.continuation").len(), 1); + } + + #[test] + fn a_phase_edit_recorded_differently_once_continuations_exist_is_caught() { + use baley_core::scope::PhaseFields; + + use crate::planning::fixtures::store_c; + + let (_dir, store) = store_c(); + let goal = PhaseFields { + goal: Some("The owner approves every change".into()), + ..PhaseFields::default() + }; + let digest = + submit_phase_edit(&store, &command(SUBMIT_COMMAND, R1, 1, T4), 2, &goal, None).unwrap(); + assert_eq!(digest.to_hex(), E_B_DIGEST); + let events = history(&store); + let drafts = of_type(&events, "scope.submitted") + .into_iter() + .filter(|event| event.payload["digest"] == E_B_DIGEST) + .count(); + assert_eq!(drafts, 1); + assert!(on_stream(&events, "phase/2").is_empty()); + assert!(of_type(&events, "plan.continuation").is_empty()); + } } diff --git a/crates/baley/src/work_order/issue.rs b/crates/baley/src/work_order/issue.rs index 63e4498e..e8ccfcbc 100644 --- a/crates/baley/src/work_order/issue.rs +++ b/crates/baley/src/work_order/issue.rs @@ -100,8 +100,9 @@ pub fn prompt(id: &str) -> String { /// The sentence telling the session how to start the worker: the stub /// `agent` with the Agent tool and the prompt, with the route's model as the /// Agent tool's `model` parameter, or with none so the stub's `model: -/// inherit` applies (D-23). -fn launch(agent: &str, model: Option<&str>) -> String { +/// inherit` applies (D-23). An order handed over after its issue is launched +/// with the same sentence. +pub fn launch(agent: &str, model: Option<&str>) -> String { match model { Some(model) => format!( "Start the subagent {agent} with the Agent tool, giving it the prompt above, and pass {model} as the Agent tool's model parameter." diff --git a/docs/adr/0050-phase-plan-commits-stories-through-an-approved-edit.md b/docs/adr/0050-phase-plan-commits-stories-through-an-approved-edit.md new file mode 100644 index 00000000..510e8986 --- /dev/null +++ b/docs/adr/0050-phase-plan-commits-stories-through-an-approved-edit.md @@ -0,0 +1,75 @@ +# 0050: Commit a phase plan's stories through an approved phase edit that issues the planner's order + +| | | +|---|---| +| Status | Accepted | +| Date | 2026-11-01 | +| Deciders | John Crenshaw | +| Design document | [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) | +| Supersedes | | +| Superseded by | | + +## Context and problem + +`phase plan` starts a phase's planning. A session sends the phase's number and the stories to commit to it, in order, and the answer is the planner's work order, which the session launches. When the stories sent are the ones the phase already commits, nothing about scope changes and the order can be issued at once. When they differ, because a story is added, left out or moved, the call changes what the phase commits, and every scope change is a draft the owner approves by digest at the terminal ([0004](../design/0004-starting-a-project-and-changing-scope.md) PRJ-R19, [ADR 0043](0043-submissions-recorded-as-drafts.md), [ADR 0044](0044-owner-acts-on-the-command-line.md)). The session cannot approve it, since over MCP nothing proves a person answered. + +So one call has two acts in it: a change of commitment that only the owner may make, and a work order for a planner. A planner launched on stories nobody approved would write a plan for a commitment that may never stand, and the owner would then be asked to approve the plan with the commitment under it already assumed. The question is where the planner's order comes from when the commitment changes, and which step records it. + +The refinement path has a precedent: a story's drafting order is issued by the call that closes its question set, or, after a close at the terminal, by the session's next `story refine` ([0005](../design/0005-context-plans-and-acceptance.md) section 5). That keeps work orders out of the terminal, but it leaves the owner's approval and the order it makes possible in two separate steps. + +## Decision drivers + +- No planner order exists for a commitment the owner has not approved. +- The owner's approval of the commitment is the act that starts planning, so approving it and getting the planner's order are one step, not two the owner must remember to join. +- A crash or a restart between any two steps leaves nothing half done: an approved commitment either has its order recorded or has neither. +- A rerun of the approval, or a second `phase plan`, never issues a second order for the same commitment, since a phase has one live planner order. +- Approvals are given only at the terminal, and a work order is launched only by a session ([ADR 0044](0044-owner-acts-on-the-command-line.md)). + +## Considered options + +1. The approval records only the commitment, and the session's next `phase plan` issues the order +2. `phase plan` commits the stories directly and issues the order +3. The approval records the commitment and the planner's order together, and the session's next `phase plan` hands that order over + +## Decision + +Chosen option: **3**, because it is the only option where the owner's approval is what starts planning, while the order still reaches the planner only through a session. + +`phase plan` with a selection that differs from the phase's committed stories, a reorder included, records the `phase edit` draft of the phase's `stories` and, in the same transaction, a planning continuation on the phase's stream: `plan.continuation`, naming the phase, the selection in order, the edit's digest and the id the planner's order will have. It answers with the draft's digest and the commands that preview and approve it, and issues no order. + +`baley scope approve` on that digest is a commitment approval. Its first step rechecks the selection over facts read at approval, with the same rules `phase plan` judged it by: another phase active (`phase-active`), the phase and each story held, each story refined (`story-unrefined`), no story committed to another phase (`story-in-phase`), and no planner order of the phase pending (`planner-order-pending`). A refusal records nothing. Its second step records, in one transaction, the edit's `phase.declared` and `scope.approved` and the planner's `work_order.issued` under the id the continuation named, and the terminal prints that id. Running the approval again is refused `draft-approved`, naming the same order. + +The session's next `phase plan` with the same selection finds the approved continuation and its pending order, records `plan.continuation_followed`, and answers with that order's receipt, which the session launches as it would a fresh order. A further `phase plan` while the order is pending is refused `planner-order-pending`, naming it. + +## Consequences + +### Positive + +- No planner order is recorded until the owner has approved the stories it plans, and a stale or refused approval changes neither the stories nor the work orders. +- The commitment and its order are one transaction, so after a restart the ledger holds both or neither, and the order id is fixed when the edit is drafted, so every read of the approval names the same order. +- The owner approves once, and the session's next call picks up the order without the owner doing anything more. +- An unchanged selection still issues its order directly, so planning a phase whose stories were already approved costs no extra step. + +### Negative + +- The terminal issues a work order, which until now only a session did. It must compose the order's route, and it composes it for Claude Code, the one supported host, under the checkout's effective policy for that host. Supporting a second host needs a way to choose which host a terminal-issued order is routed for. +- `scope approve` treats a `phase edit` differently when a continuation names it, so the same kind of draft has two approval paths to keep in step. +- Two new events, `plan.continuation` and `plan.continuation_followed`, exist only to carry the selection and the hand-over across the gap between the session and the terminal. + +### Follow-up + +- Design 0004 describes the continuation in `phase edit` and `scope approve`, and design 0005 describes `phase plan`, its paths and its refusals, and the two events. + +## Options in detail + +### Option 1: the approval records only the commitment + +The approval records the edit as any other, and the session's next `phase plan`, now finding the selection equal to the committed stories, issues the order, as a story's drafting order is issued by the next `story refine` after a close at the terminal. No new event and no route at the terminal. But the owner's approval does not start planning: it is one step, and the order is another that happens only if a session calls again, and between them the phase has an approved commitment and no planner. Fails the second driver. + +### Option 2: `phase plan` commits the stories directly + +The call records the new commitment itself and issues the order. One step, and no draft. But the commitment changes on a call that comes from the model, with no owner approval, which every other scope change requires. Fails the first driver and PRJ-R19. + +### Option 3: the approval records the commitment and issues the order (chosen) + +The edit is drafted with a continuation, approved at the terminal, and the approval records the order in the same transaction; the session's next call hands it over. Meets every driver. Costs a route composed at the terminal for the one supported host, two continuation events, and a second approval path for a `phase edit` a continuation names. diff --git a/docs/adr/README.md b/docs/adr/README.md index 42c7399e..f7c4c4df 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -56,3 +56,4 @@ Start a new record from [TEMPLATE.md](TEMPLATE.md) with the next free four-digit | [0047](0047-owner-acts-relayed-by-a-session.md) | Record an owner's act a session relays as Baley's, naming the session | Accepted | | [0048](0048-port-what-cadence-hands-agents.md) | Port what Cadence hands its agents into the binary | Accepted | | [0049](0049-rules-added-to-ported-texts.md) | Let a ported text add a rule an accepted design requirement states | Accepted | +| [0050](0050-phase-plan-commits-stories-through-an-approved-edit.md) | Commit a phase plan's stories through an approved phase edit that issues the planner's order | Accepted | diff --git a/docs/design/0001-evidence-ledger.md b/docs/design/0001-evidence-ledger.md index d00fee92..db75613f 100644 --- a/docs/design/0001-evidence-ledger.md +++ b/docs/design/0001-evidence-ledger.md @@ -412,10 +412,12 @@ The anchor command records its result on the `project` stream. `anchor.pushed` v The detached updater opens the per-user store itself, as the manual `baley update` does. Both record update checks as ordinary events in `user`: `command.claimed` on `command/update.check` records each claimed attempt; one `update.checked` or `update.failed`, version 1, on `install` records its outcome, with the installation, UTC day, claim identity and active and staged versions. The store records `command.completed` in the same transaction as that result event and, after interruption, `command.reconciled` through its existing protocol. No update event has a caller. There is no separate update-check table, no view or projector of update outcomes, and no new port operation. [0012 section 6](0012-host-interface.md#6-records) specifies the daily claim and exact outcome fields. -A work order is recorded on its subject's stream; the start planner's order and a story's analyzer orders, the orders this build issues, go on `roadmap` (`crates/baley-core/src/work_order/event.rs`, `order_stream`). `work_order.issued` version 1 is exactly `{"id", "request", "parent", "role", "subject", "attempt", "route", "agent", "instructions", "inputs"}`: the order's lower-case UUID; the id of its chain's first order, its own id at attempt 1; the failed order it retries, or `null`; the role and subject, `planner` and `start` for the start, `analyzer` and `story/<id>` for both of a story's analyzer orders, its questions order and its drafting order; the attempt from 1; the route record ([0003](0003-configuration-and-routing.md) section 6); the agent stub to launch, `bal-<role>-<rung>`; the instructions as a list of `{ "identity", "version", "hash" }`; and the inputs as a list of `{ "name", "body" }`, each body a reference to a `record` payload, such as the start's `brief`, or an analyzer order's `story`, `description`, `roadmap`, the story's current `truths` once it was refined, and a drafting order's `questions` with every answer and deferral (`crates/baley/src/refine/inputs.rs`). `work_order.failed` version 1 is exactly `{"id", "reason"}` and goes on the stream its order's issue went on. Neither payload holds a caller or a time: the envelope carries both. Both are core types registered at version 1 with no upcasters (`crates/baley-core/src/work_order/event.rs`, `WORK_ORDER_ISSUED`, `WORK_ORDER_FAILED` and `register_work_order_events`). +A work order is recorded on its subject's stream: the start planner's order and a story's analyzer orders go on `roadmap`, and a phase's planner orders on that phase's stream, `phase/<n>` (`crates/baley-core/src/work_order/event.rs`, `order_stream`). `work_order.issued` version 1 is exactly `{"id", "request", "parent", "role", "subject", "attempt", "route", "agent", "instructions", "inputs"}`: the order's lower-case UUID; the id of its chain's first order, its own id at attempt 1; the failed order it retries, or `null`; the role and subject, `planner` and `start` for the start, `analyzer` and `story/<id>` for both of a story's analyzer orders, its questions order and its drafting order, and `planner` and `phase/<n>` for a phase's planning and revision orders; the attempt from 1; the route record ([0003](0003-configuration-and-routing.md) section 6); the agent stub to launch, `bal-<role>-<rung>`; the instructions as a list of `{ "identity", "version", "hash" }`; and the inputs as a list of `{ "name", "body" }`, each body a reference to a `record` payload, such as the start's `brief`, or an analyzer order's `story`, `description`, `roadmap`, the story's current `truths` once it was refined, and a drafting order's `questions` with every answer and deferral (`crates/baley/src/refine/inputs.rs`), or a planner order's `phase`, `stories`, `description`, `capacity` when one is set and `approved_items`, and a revision's `draft` and `questions` (`crates/baley/src/planning/inputs.rs`). `work_order.failed` version 1 is exactly `{"id", "reason"}` and goes on the stream its order's issue went on. Neither payload holds a caller or a time: the envelope carries both. Both are core types registered at version 1 with no upcasters (`crates/baley-core/src/work_order/event.rs`, `WORK_ORDER_ISSUED`, `WORK_ORDER_FAILED` and `register_work_order_events`). A story's truths approved by the owner are recorded as `story.refined` on `roadmap`, with actor `owner`. Version 1 is exactly `{"story", "set", "submission", "owner", "at", "truths"}`: the story's id; the question set the truths were drafted from; the approved draft's lower-case hex digest; the owner's name from `owner.name`, falling back to git `user.name`; the time by Baley's clock; and the story's whole truth list, each truth inline with its `version` (`crates/baley-core/src/truth/event.rs`, `refined_payload`). It is a core type registered at version 1 with no upcasters (`register_truth_events`). +A plan approved by the owner is recorded as `plan.approved` on `phase/<n>`, with actor `owner`. Version 1 is exactly `{"phase", "plan", "digest", "stories", "size", "suite", "question_set", "evidence_map", "body", "owner", "at"}`: the phase and the plan number; the approved draft's lower-case hex digest; the stories it serves; its size in tasks; the suite from `workflow.test_command`, or `null` when none is set; the draft's question set; the evidence map inline exactly as submitted, so the `evidence_map` view rebuilds from the event and survives a purge of the draft's body; a reference to that body, the draft's `record` payload, which holds the plan text; the owner's name; and the time by Baley's clock. `plan.replaced` version 1 is exactly `{"phase", "plan", "old_digest", "new_digest", "owner", "at"}`, recorded with the replacement's `plan.approved` in one transaction. `plan.continuation` version 1 is exactly `{"phase", "stories", "edit", "work_order"}`: a `phase plan` that changes the phase's stories records it with its `phase edit` draft, naming the selection, the edit's digest and the id of the planner order the edit's approval issues. `plan.continuation_followed` version 1 is exactly `{"phase", "edit", "work_order"}`, recorded when that order is handed to a session ([0005](0005-context-plans-and-acceptance.md), [ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md)). All four are core types registered at version 1 with no upcasters (`crates/baley-core/src/plan/event.rs`, `register_plan_events`). + A question set is recorded on its subject's stream: a story's set on `roadmap` and a plan draft's on `phase/<n>`. Every answer, deferral and abandonment of a set goes on the stream the set was opened on, which the `questions` view records. `questions.opened` version 1 is exactly `{"set", "subject", "story", "work_order", "questions", "at"}` for a story's set and `{"set", "subject", "phase", "plan_digest", "questions", "at"}` for a plan draft's: the set's id, a lowercase UUID Baley mints when it opens the set and never derives from the content; `story` or `plan`; the story and the analyzer's questions work order, or the phase and the draft's lower-case hex digest; the questions in submitted order, each exactly `{"id", "question", "recommended", "depends_on"}`; and the time. `question.answered` version 1 is exactly `{"set", "question", "round", "answer", "accepted", "owner", "at"}` and `question.deferred` version 1 is exactly `{"set", "question", "round", "reason", "owner", "at"}`: the question settled, the round it was settled in, the answer and whether it took the recommended one, or the reason, the owner's name from `owner.name`, falling back to git `user.name`, and the time of the command that recorded it, by Baley's clock. `questions.abandoned` version 1 is exactly `{"set", "cause", "at"}`, with the cause `superseded` or `draft-replaced`. Every text is inline and at most 4,096 bytes, never a payload. Unlike the work-order events, these payloads carry a time of their own, as an approval's does, so the record says who settled a question and when in its own words. An answer or deferral a session relays over MCP is recorded under a command with actor `baley` and the session as the caller, and one given at the terminal with actor `owner` and no caller ([ADR 0047](../adr/0047-owner-acts-relayed-by-a-session.md)). All four are core types registered at version 1 with no upcasters (`crates/baley-core/src/questions/event.rs`, `register_question_events`). Streams used by the record families: @@ -424,7 +426,7 @@ Streams used by the record families: |---|---| | `project` | `project.initialized`, `scope.submitted`, `project.described`, `scope.approved`, `forge.checked`, `policy.effective`, `checkout.seen`, `anchor.pushed`, `anchor.failed`, `anchor.restore_acknowledged` | | `roadmap` | `phase.declared`, `phase.reordered`, `phase.withdrawn`, `story.declared`, `story.corrected`, `story.reassigned`, `story.reprioritized`, `story.dropped` ([0004](0004-starting-a-project-and-changing-scope.md)), `work_order.issued` and `work_order.failed` for the start planner's order and a story's analyzer orders, `story.refined` for a story's approved truths, and `questions.opened`, `question.answered`, `question.deferred` and `questions.abandoned` for a story's question set ([0005](0005-context-plans-and-acceptance.md)) | -| `phase/<n>` | `plan.approved`, `plan.check_issued`, `plan.checked`, `plan.replaced`, `phase.retrospective`, and `questions.opened`, `question.answered`, `question.deferred` and `questions.abandoned` for a plan draft's question set ([0005](0005-context-plans-and-acceptance.md)), `plan.admitted`, `dispatch.issued` (serializes one active dispatch per phase), the task, run, suite and plan outcome events of [0006](0006-execution.md), `phase.completed`, `completion.invalidated`, `phase.undone`, `risk.raised`, `risk.scanned`, `risk.fired`, `risk.overridden`, `risk.settled` ([0009](0009-risk.md)) | +| `phase/<n>` | `plan.approved`, `plan.check_issued`, `plan.checked`, `plan.replaced`, `plan.continuation` and `plan.continuation_followed`, `phase.retrospective`, `work_order.issued` and `work_order.failed` for the phase's planner work orders, and `questions.opened`, `question.answered`, `question.deferred` and `questions.abandoned` for a plan draft's question set ([0005](0005-context-plans-and-acceptance.md)), `plan.admitted`, `dispatch.issued` (serializes one active dispatch per phase), the task, run, suite and plan outcome events of [0006](0006-execution.md), `phase.completed`, `completion.invalidated`, `phase.undone`, `risk.raised`, `risk.scanned`, `risk.fired`, `risk.overridden`, `risk.settled` ([0009](0009-risk.md)) | | `verification/<id>` | `verification.started`, `verification.run`, `verdict.claimed`, `observation.recorded`, `item.overruled`, `truth.waived`, `waiver.revoked`, `verification.completed` ([0007](0007-verification.md)) | | `review/<id>` | `review.admitted`, `review.issued`, `review.returned`, `review.failed`, `review.adjudication`, `review.adjudicated`, `review.settled`, `review.deferred`, `finding.filed`, `finding.declined`, `finding.uncertain` ([0008](0008-review.md)) | | `milestone/<name>` | `milestone.close_ready`, `milestone.archived`, `release.proposed`, `release.confirmed`, `landing.started`, `landing.authorized`, `landing.claimed`, `landing.step`, `landing.reconciled`, `landing.confirmed`, `landing.completed`, `tracker.checked` ([0011](0011-milestones-landing-undo-pause.md)) | @@ -707,7 +709,7 @@ A projector is registered for the event types it cares about. For each appended The old generation is deleted before the rebuild returns, one row at a time in turns of at most 200 document rows, and once one row is removed, no further row after the turn has held the queue 15 ms, each turn followed by the same pause: its rows in every view table `view_catalog` records, including tables of older versions and of views this binary no longer registers, then its `view_gen` stamps. A crash, or a rebuild abandoned between batches, leaves its generation and marker behind, never live; the next rebuild removes them before it starts, together with every generation that is neither live nor being built, found one at a time by keyed seeks on `view_gen` and on every view table. Every removal turn first reads `live_gen` and refuses the live generation before deleting a row: a damaged marker that names it makes the rebuild return `LiveGenerationProtected`, and the live rows stay. If deleting the old generation fails after the flip, the flip stands: `rebuild` returns `CleanupFailed`, naming the generation now live and the error that stopped the cleanup, and the next rebuild removes what is left. Generation numbers only rise, so no number a cursor was issued under is used again. -**Versions.** The binary declares a version for its whole registered view set, `request` and `claim_scope` included, and raises it whenever a view is added, removed or renamed. Version 1 names `request` alone; version 2 is the store's own `claim_scope request` set. A binary adding domain views declares a higher number. The current binary declares version 13: `backlog capture checkout claim_scope draft guard guard_policy install model_catalog phase phase_detail policy questions request roadmap truths work_order`, the store's two views and fifteen domain views. Build 4 T7 raised it to 13 when it added the `truths` view, with the `work_order` view at version 2 and the `roadmap` and `backlog` views at version 3; version 12, which Build 4 T6 declared when it added the `questions` view, named the same views without `truths`, and version 11, which Build 4 T5 declared when it added the `work_order` view, named them without `questions` either. A project brought to version 13 is read-only for an older binary (`crates/baley/src/ledger/open.rs`, `options`). When the store opens, `view_set_catalog` pins each set version to its sorted view names, as `view_catalog` pins each view version to its spec, and a set changed under a version already recorded is refused. Every `view_gen` row of a generation carries the same set version beside its view's projector version. +**Versions.** The binary declares a version for its whole registered view set, `request` and `claim_scope` included, and raises it whenever a view is added, removed or renamed. Version 1 names `request` alone; version 2 is the store's own `claim_scope request` set. A binary adding domain views declares a higher number. The current binary declares version 14: `backlog capture checkout claim_scope draft evidence_map guard guard_policy install model_catalog phase phase_detail phase_plan plan policy questions request roadmap truths work_order`, the store's two views and eighteen domain views. Build 4 T9 raised it to 14 when it added the `phase_plan`, `plan` and `evidence_map` views, with the `backlog` view at version 4 for a story's size; version 13, which Build 4 T7 declared when it added the `truths` view, with the `work_order` view at version 2 and the `roadmap` and `backlog` views at version 3, named the same views without those three; version 12, which Build 4 T6 declared when it added the `questions` view, named version 13's views without `truths`, and version 11, which Build 4 T5 declared when it added the `work_order` view, named them without `questions` either. A project brought to version 14 is read-only for an older binary (`crates/baley/src/ledger/open.rs`, `options`). When the store opens, `view_set_catalog` pins each set version to its sorted view names, as `view_catalog` pins each view version to its spec, and a set changed under a version already recorded is refused. Every `view_gen` row of a generation carries the same set version beside its view's projector version. Before a project's views are used, by a read or a new command, the adapter compares the live stamps with this binary's: a read in the same snapshot as the document or page it returns, a command under the writer queue. A live set version, or a registered view's projector version, newer than this binary's makes the project read-only for this binary: its view reads and new commands are refused with `ProjectReadOnly`, because this binary's table at the newer generation can be empty, and answering from it would report an absence that is not true. History and payload reads still work. An older or missing set stamp, an older or missing view row, or a row for a view this binary retired rebuilds the project forward before use, under the maintenance lock; a caller that waited while another process did it finds the views current and goes on. A store opened for the guard rebuilds nothing and takes no maintenance lock: it refuses that read or command with `NeedsRebuild`, naming the project, with nothing read or written. Lease renewal is the one exception, and it rebuilds forward under the maintenance lock on any store, because the guard never renews a lease. A retired view's name alone never fences a project: the rebuild's cleanup removes its rows and stamps. A project with no events and no generation yet is stamped at generation 0 on first use, with nothing to replay. Open looks at no project, so a project whose views need work never keeps another from opening. A binary never rebuilds a view whose stored version is newer than its own; its `rebuild` and `verify --views` refuse that project too. A retry of a request already answered needs only the live `request` view at this binary's projector version, whatever the set stamp says. @@ -773,10 +775,11 @@ The store-owned `request` view is at version 2. It projects `command.claimed` to | `roadmap` | project | | The accepted description; every phase ever declared with its current declaration, the stories it serves now and its status, `declared` or `withdrawn`; the phase order, which a withdrawn phase leaves while keeping its entry; the stories in priority order with their status, wording, the phase serving them now and truth count, which each story's latest `story.refined` sets, as it sets the backlog's, a dropped story kept with status `dropped` and no phase; and the highest phase number and story id ever declared, withdrawn ones included, which an approval numbers past. Every event that moves a story keeps a phase's stories and the story's phase in step. It is the scope a change is judged against ([0004](0004-starting-a-project-and-changing-scope.md)) | | `phase` | (project, phase) | status | Each declared phase's latest declaration (name, goal, dependencies, the story ids it listed, approving digest, time, the sequence of its `phase.declared` and its detail body hash) and status, `declared` or `withdrawn`. A withdrawal keeps the document with status `withdrawn`, so the phase is still read by its number. The stories a phase serves after a reassignment or drop are the `roadmap` view's, since those events name no earlier phase. Context, plans, execution, completion and whether it still applies are added by later builds | | `phase_detail` | (project, declaring sequence) | | Each declared phase's detail body hash and, once this project purged that body, the purge reason, so `baley phase show` answers the purge without opening the body. It is keyed by the `phase.declared` sequence because `payload.purged` names each released reference by its sequence and hash, as the `capture` view is | -| `backlog` | project | | The stories in priority order with their status, wording, phase and size, and per story the latest question set (`set`), the set its latest `story.refined` names (`refined`) and that refinement's truth count ([0005](0005-context-plans-and-acceptance.md)). It follows every story change: declarations, which go last, corrections, reassignments, drops, reprioritizations, and the phase declarations that commit a story they list or release one they no longer list. A story's `questions.opened` makes that set its latest, and a plan draft's set changes nothing; a `story.refined` replaces the marker and the count, and a later set leaves both, since approved truths stay in force until new ones are approved. A dropped story stays with status `dropped` and no phase. A declared story holds no set, no marker, no truths and no size until sizing records one. The refinement state, `unrefined`, `questions-open` with the current round, `drafting` or `refined`, is never stored: it is worked out when read from the latest set's round and the marker, so nothing stored drifts from the set (`crates/baley-core/src/scope/backlog.rs`, `BacklogProjector`, `crates/baley-core/src/truth/state.rs`, `refinement`) | +| `phase_plan` | (project, phase) | status, then phase | Each phase's planning state: its approved plans in number order, each with its digest, stories, size, `state` (`in-force` or `replaced`) and the replacing digest; the highest plan number ever assigned, replaced plans included, which the next approval numbers past; its size, the tasks of its plans in force, each plan counted once; whether it was withdrawn; its status, `active` while a plan is in force and it is not withdrawn and `inactive` otherwise, which the index finds the active phase by; its one unapproved plan draft with that draft's question set; and its latest planning continuation with whether it was followed. It projects `plan.approved`, `plan.replaced`, `phase.withdrawn`, a plan draft's `questions.opened`, `plan.continuation` and `plan.continuation_followed`, and refuses a plan number not above the highest, so no number is assigned twice ([0005](0005-context-plans-and-acceptance.md), `crates/baley-core/src/plan/phase_plan.rs`, `PhasePlanProjector`) | +| `backlog` | project | | The stories in priority order with their status, wording, phase and size, and per story the latest question set (`set`), the set its latest `story.refined` names (`refined`) and that refinement's truth count ([0005](0005-context-plans-and-acceptance.md)). It follows every story change: declarations, which go last, corrections, reassignments, drops, reprioritizations, and the phase declarations that commit a story they list or release one they no longer list. A story's `questions.opened` makes that set its latest, and a plan draft's set changes nothing; a `story.refined` replaces the marker and the count, and a later set leaves both, since approved truths stay in force until new ones are approved. A dropped story stays with status `dropped` and no phase. Each story lists in `plans` the approved plans in force that serve it, each with its phase, number and size, and its `size` is their tasks summed: a `plan.approved` adds the plan to every story it serves and a `plan.replaced` removes it. A declared story holds no set, no marker, no truths and no size until it is refined and a plan serving it is approved. The refinement state, `unrefined`, `questions-open` with the current round, `drafting` or `refined`, is never stored: it is worked out when read from the latest set's round and the marker, so nothing stored drifts from the set (`crates/baley-core/src/scope/backlog.rs`, `BacklogProjector`, `crates/baley-core/src/truth/state.rs`, `refinement`) | | `draft` | (project, digest) | kind, then target, then latest submission, newest first | Each submitted digest's change kind, its target (the change it belongs to among its kind's drafts), the sequence and time of its latest submission and its body hash. Each draft is filed under its kind and target, so the newest draft of one change is the first the index gives, and this project's purge reason once it purged the body ([0004](0004-starting-a-project-and-changing-scope.md)) | -| `plan` | (project, phase, plan) | status | Current content reference, approval binding, readiness, and completed check rounds with their work-order binding, scope and material references | -| `evidence_map` | (project, phase, plan) | | The acceptance evidence a plan must produce | +| `plan` | (project, phase, plan) | | Each approved plan's binding from its `plan.approved`: its digest, stories, size, suite, question set, the hash of its draft's body, never the text, owner and time, and its `state`, `approved` or `replaced` with the replacing digest, which a `plan.replaced` sets while keeping every other field. No draft reaches it, and a purge of the body leaves it whole. Readiness is worked out when read, never stored. The checker's completed rounds, with their work-order binding, scope and material references, come from `plan.checked` ([0005](0005-context-plans-and-acceptance.md), `crates/baley-core/src/plan/plan_view.rs`, `PlanProjector`) | +| `evidence_map` | (project, phase, plan) | | The acceptance evidence an approved plan must produce: its evidence items exactly as `plan.approved` carries them inline, with their truth versions and each check's `level`, and its `state`, `approved` or `replaced`. Only `plan.approved` and `plan.replaced` reach it, so a draft's map never appears and a replaced plan's map stays. Whether the items still name their truths' current versions is worked out when read, never stored ([0005](0005-context-plans-and-acceptance.md), `crates/baley-core/src/plan/map_view.rs`, `EvidenceMapProjector`) | | `admission` | (project, phase) | checkout | What execution may touch, and in which checkout | | `dispatch` | (project, dispatch id) | phase, state | Active and ended dispatches, task and suite outcomes | | `run` | (project, run id) | dispatch, phase | One run: launch, result, output reference | @@ -796,7 +799,7 @@ The store-owned `request` view is at version 2. It projects `command.claimed` to | `request` | (project, command kind, request id) | state | Each request's open claim, held claim or outcome, for retries and open claims | | `claim_scope` | (project, scope token) | | The open claim holding each scope token, for the scope check | | `model_catalog` | (project, catalog) | | The model names each host and provider accepts, with their source, tier and placement, and the catalog version ([0003](0003-configuration-and-routing.md)) | -| `work_order` | (project, order id) | `live`: role, subject, state, then the issue's sequence, newest first | Each issued order as `work_order.issued` recorded it, with its state, the issue's sequence and time, its failure, the digests of the drafts submitted under it and the retry issued from it. `work_order.issued` adds the order `pending` and sets its parent's retry; `work_order.failed` makes it `failed` with the reason, sequence and time; a `scope.submitted` whose caller names a held order adds the draft's digest once and makes a pending order `answered`, while a failed order stays failed, so a truth draft submitted under a story's drafting order answers it; and a story set's `questions.opened` naming a held order answers that questions order the same way, with the set's id among its returns in place of a digest, while a plan draft's set changes no order. The index answers whether a pending order of one role and subject exists, which a start is refused on ([0004](0004-starting-a-project-and-changing-scope.md)) and a story's next analyzer order is refused on while either of its analyzer orders is pending ([0005](0005-context-plans-and-acceptance.md)) (`crates/baley-core/src/work_order/view.rs`, `WorkOrderProjector`) | +| `work_order` | (project, order id) | `live`: role, subject, state, then the issue's sequence, newest first | Each issued order as `work_order.issued` recorded it, with its state, the issue's sequence and time, its failure, the digests of the drafts submitted under it and the retry issued from it. `work_order.issued` adds the order `pending` and sets its parent's retry; `work_order.failed` makes it `failed` with the reason, sequence and time; a `scope.submitted` whose caller names a held order adds the draft's digest once and makes a pending order `answered`, while a failed order stays failed, so a truth draft submitted under a story's drafting order answers it; and a story set's `questions.opened` naming a held order answers that questions order the same way, with the set's id among its returns in place of a digest, while a plan draft's set changes no order. The index answers whether a pending order of one role and subject exists, which a start is refused on ([0004](0004-starting-a-project-and-changing-scope.md)) and a story's next analyzer order is refused on while either of its analyzer orders is pending, and a phase's next planner order while its planning or revision order is pending ([0005](0005-context-plans-and-acceptance.md)) (`crates/baley-core/src/work_order/view.rs`, `WorkOrderProjector`) | | `truths` | (project, story) | | Each refined story's current truths in submitted order, each with its version, the question set and approved digest its latest `story.refined` names with that event's sequence and time, and, by truth id, every version ever approved, oldest first, each with the sequence of the `story.refined` that first carried it. Each `story.refined` replaces the current list; a truth carried again at the same version adds no kept entry. It holds no refinement state ([0005](0005-context-plans-and-acceptance.md), `crates/baley-core/src/truth/view.rs`, `TruthsProjector`) | | `questions` | (project, set id) | | Each question set's facts as recorded: its id; its subject, `{kind: "story", story, work_order}` or `{kind: "plan", phase, plan_digest}`; the stream it was opened on, which every later record on it goes on; the opening's sequence and time; the questions as submitted; each answer as `{question, answer, accepted, round, owner, at, seq}`; each deferral as `{question, reason, round, owner, at, seq}`; and its abandonment as `{cause, at, seq}`, or null. It holds no state: whether the set is open, closed or abandoned, each question's state and the current round are computed when the set is read, from the questions in submitted order and the records, never from the order the records arrived in ([0005](0005-context-plans-and-acceptance.md)). Its projector refuses an opening for a set already held; an answer or deferral for a set not held, a question the set lacks or a question already answered or deferred; and an abandonment of a set not held or already abandoned, so no recorded fact is ever replaced (`crates/baley-core/src/questions/view.rs`, `QuestionsProjector`) | @@ -1610,7 +1613,7 @@ Found unused in the current code and not carried forward: the store operations ` ## Appendix B: Reads mapped to views -The reads the inherited server served, with the view and key that will serve each. `help`, `schema` and `instruction` read no store. `document` is served for seven identity kinds: a capture by id, read through the `capture` view; a draft by digest, read through the `draft` view and its body; the roadmap, read through the `roadmap` view; a story by id, read through the same view; a work order by id, read through the `work_order` view, with its accepted result from the start approval, its inputs' purges from this project's `retention` stream and its input bodies; a question set's round by the set's id, read through the `questions` view, with the round worked out when read; and a story's refinement, `{"kind":"refinement","story":<id>}`, read as `context-intake` reads it. It refuses any other identity kind as invalid arguments until the build that records it. `context-intake` and `route` are served and record nothing. Every other read answers operation-unavailable until the build that replaces it. All queries page with a cursor and are bounded; lists are ordered as stated. +The reads the inherited server served, with the view and key that will serve each. `help`, `schema` and `instruction` read no store. `document` is served for nine identity kinds: a capture by id, read through the `capture` view; a draft by digest, read through the `draft` view and its body; the roadmap, read through the `roadmap` view; a story by id, read through the same view; a work order by id, read through the `work_order` view, with its accepted result from the start approval, its inputs' purges from this project's `retention` stream and its input bodies; a question set's round by the set's id, read through the `questions` view, with the round worked out when read; a story's refinement, `{"kind":"refinement","story":<id>}`, read as `context-intake` reads it; a phase's approved plans, `{"kind":"phase","phase":<n>}`, and one approved plan, `{"kind":"plan","phase":<n>,"plan":<n>}`, read as `plan-read` reads them. It refuses any other identity kind as invalid arguments until the build that records it. `context-intake`, `plan-read` and `route` are served and record nothing. Every other read answers operation-unavailable until the build that replaces it. All queries page with a cursor and are bounded; lists are ordered as stated. | Query operation | View and key | Order | |---|---|---| @@ -1621,9 +1624,9 @@ The reads the inherited server served, with the view and key that will serve eac | `verification-audit` | `roadmap` stories; `phase` and `verification` by phase | Roadmap order | | `execution-history` | `dispatch` by phase; `run` (project, run id) with a payload stream for output | Sequence | | `evidence-read` | `evidence_map` (project, phase, plan); evidence events for the plan | Sequence | -| `plan-read` | `plan` by phase; `evidence_map` | Plan number | +| `plan-read` | Keyed by phase, with an optional `part`: `roadmap` (project) for whether the roadmap holds the phase; `phase_plan` (project, phase) for the plans it lists, replaced ones included; for each, `plan` and `evidence_map` (project, phase, plan); and `truths` (project, story) for each story its items name, so a plan's readiness against the current truth versions is worked out when read and never stored. Only views an approval writes are read, so no draft appears. It records nothing, and `baley plan show` reads the same (`crates/baley/src/planning/read.rs`, `read`) | Plan number | | `context-intake` | Keyed by story, with an optional `part`: `roadmap` (project) for the approved description and the story's entry; the `phase` document of the phase the story's entry commits it to, none for a backlog story; `truths` (project, story) for its current truths and every kept version, none before its first refinement. It records nothing and issues no order (`crates/baley/src/refine/read.rs`, `read`) | | -| `document` | By identity, as served: `capture` by capture id for a note or story; `draft` by digest; `roadmap` (project) for the accepted roadmap and for a story by id; `work_order` (project, order id) for a work order; `questions` (project, set id) for a question set's round, worked out when read; `roadmap`, `phase` and `truths` for a story's refinement, as `context-intake` reads them; each cut into parts of at most 24,576 bytes. Later builds: `phase` for phase context; `plan` for a phase plan; `dispatch` for a dispatch; `verification` for an attempt; `run` for run output; `review` for a review entry; `task`, `debug`, `spike` by slug | | +| `document` | By identity, as served: `capture` by capture id for a note or story; `draft` by digest; `roadmap` (project) for the accepted roadmap and for a story by id; `work_order` (project, order id) for a work order; `questions` (project, set id) for a question set's round, worked out when read; `roadmap`, `phase` and `truths` for a story's refinement, as `context-intake` reads them; `phase_plan`, `plan`, `evidence_map` and `truths` for a phase's approved plans and for one approved plan, as `plan-read` reads them; each cut into parts of at most 24,576 bytes. Later builds: `dispatch` for a dispatch; `verification` for an attempt; `run` for run output; `review` for a review entry; `task`, `debug`, `spike` by slug | | | `document-search` | `Search` scoped to (project, phase), returning identities and parts | Relevance | | `recall` | `Search` scoped to the project, optionally a phase | Relevance | | `why` | `event(project_id, git_commit)` index, then the events' streams | Sequence | diff --git a/docs/design/0002-system-design.md b/docs/design/0002-system-design.md index 0aa8c16d..39cf40a3 100644 --- a/docs/design/0002-system-design.md +++ b/docs/design/0002-system-design.md @@ -242,7 +242,7 @@ graph LR style 5 fill:#85bbf0,stroke:#5d82a8,color:#000000 6["<div style='font-weight: bold'>Domain areas</div><div style='font-size: 70%; margin-top: 0px'>[Component]</div><div style='font-size: 80%; margin-top:10px'>The rules of each process<br />area: planning, execution,<br />verification, review, risk,<br />landing and the rest.</div>"] style 6 fill:#85bbf0,stroke:#5d82a8,color:#000000 - 7["<div style='font-weight: bold'>Work order composer</div><div style='font-size: 70%; margin-top: 0px'>[Component]</div><div style='font-size: 80%; margin-top:10px'>Builds every work order: the<br />route from policy and the<br />model catalog, instructions<br />by identity from the binary,<br />inputs as references into the<br />record. In this build it<br />issues the start planner's<br />order, the analyzer's<br />questions and drafting orders<br />for a story's refinement, and<br />their retries.</div>"] + 7["<div style='font-weight: bold'>Work order composer</div><div style='font-size: 70%; margin-top: 0px'>[Component]</div><div style='font-size: 80%; margin-top:10px'>Builds every work order: the<br />route from policy and the<br />model catalog, instructions<br />by identity from the binary,<br />inputs as references into the<br />record. In this build it<br />issues the start planner's<br />order, the analyzer's<br />questions and drafting orders<br />for a story's refinement, the<br />phase planner's planning and<br />revision orders on phase/#lt;n#gt;,<br />and their retries.</div>"] style 7 fill:#85bbf0,stroke:#5d82a8,color:#000000 8["<div style='font-weight: bold'>Policy</div><div style='font-size: 70%; margin-top: 0px'>[Component]</div><div style='font-size: 80%; margin-top:10px'>Reads the global and project<br />settings, resolves the values<br />in effect and records which<br />applied.</div>"] style 8 fill:#85bbf0,stroke:#5d82a8,color:#000000 @@ -296,23 +296,23 @@ graph LR | Host interface | The MCP server (stdio), the command line and the guard hook: the only ways in | | Hardin | Derives the state of the work from the ledger's views, answers what may happen next, refuses the rest | | Domain areas | The rules of each process area, one design document each | -| Work order composer | Builds every work order: the route from policy and the model catalog, instructions by identity from the binary, inputs as references into the record. In this build it issues the start planner's order, the analyzer's questions and drafting orders for a story's refinement, and their retries | +| Work order composer | Builds every work order: the route from policy and the model catalog, instructions by identity from the binary, inputs as references into the record. In this build it issues the start planner's order, the analyzer's questions and drafting orders for a story's refinement, the phase planner's planning and revision orders on `phase/<n>`, and their retries | | Policy | Reads the global and project settings, resolves the values in effect, records which applied ([0003](0003-configuration-and-routing.md)) | | Model catalog | The model names each host and provider offers, seeded from the binary, changed by the owner and refreshed from imported lists ([0003](0003-configuration-and-routing.md)) | | Ports and adapters | The store, git and the test runner, the forge, the host adapters | ## 8. Work orders -The one contract between Baley and every worker, including the outside reviews the host session makes. An order is recorded as `work_order.issued` and read back through the `work_order` view ([0001](0001-evidence-ledger.md)). This build issues the start planner's order ([0004](0004-starting-a-project-and-changing-scope.md) section 5), the analyzer's questions and drafting orders for a story's refinement ([0005](0005-context-plans-and-acceptance.md) section 5), and their retries; the other roles' orders are issued by the builds that add them, in the same shape. +The one contract between Baley and every worker, including the outside reviews the host session makes. An order is recorded as `work_order.issued` and read back through the `work_order` view ([0001](0001-evidence-ledger.md)). This build issues the start planner's order ([0004](0004-starting-a-project-and-changing-scope.md) section 5), the analyzer's questions and drafting orders for a story's refinement ([0005](0005-context-plans-and-acceptance.md) section 5), the phase planner's planning and revision orders, issued by `phase-plan`, by the owner's `baley scope approve` of a phase's commitment and by a `questions-answer` closing a plan draft's set ([0005](0005-context-plans-and-acceptance.md) section 5, [0004](0004-starting-a-project-and-changing-scope.md) `scope approve`), and their retries; the other roles' orders are issued by the builds that add them, in the same shape. | Part | Content | Source | |---|---|---| | Identity | The order's id; the logical request, the id of its chain's first order; the failed order it retries, or none; the attempt, from 1 | Ledger | -| Role and subject | Planner, analyzer, checker, executor, verifier or reviewer, and what the order is about: `start` for the start planner and `story/<id>` for a story's analyzer orders, both recorded on the `roadmap` stream | The area that issues it | +| Role and subject | Planner, analyzer, checker, executor, verifier or reviewer, and what the order is about: `start` for the start planner and `story/<id>` for a story's analyzer orders, both recorded on the `roadmap` stream, and `phase/<n>` for a phase planner's planning and revision orders, recorded on the `phase/<n>` stream | The area that issues it | | Route | The route record: the requested rung and the rung the order sends after any escalation, the route's `rung`, the model passed or none, the setting and file that decided each, the level Claude Code's dated effort table supports for that model, and the effective model and effort, recorded `unknown` with the reasons, since no run is observed ([0003](0003-configuration-and-routing.md) section 6); and the agent stub that rung names for the role, `bal-<role>-<rung>` | Policy and the model catalog | -| Instructions | The compiled instructions, each by identity, version and hash, such as `bal-start-planner` and, when the checkout holds code, `bal-start-survey`, or `bal-analyzer-questions` and `bal-analyzer-drafting` for the analyzer's questions and drafting orders | Binary (SYS-P9) | -| Inputs | The records the role needs, each a `record` payload reference read when the order is issued, such as the start's brief, or the analyzer's `story`, `description` (the approved description), `roadmap`, `truths` (the story's current truths, once it was refined) and, in its drafting order, `questions` (the set with every answer and deferral). A retry keeps its parent's inputs | Ledger | -| Expected result | The typed result the worker must return. For the start planner it is a `scope-submit` naming the order in `work_order`. The analyzer returns its questions or its draft truths to the session, which submits them with `story-questions-submit` or `context-submit` naming the order in `work_order` | The issuing area | +| Instructions | The compiled instructions, each by identity, version and hash, such as `bal-start-planner` and, when the checkout holds code, `bal-start-survey`, or `bal-analyzer-questions` and `bal-analyzer-drafting` for the analyzer's questions and drafting orders, or `bal-phase-planner` for the phase planner's orders | Binary (SYS-P9) | +| Inputs | The records the role needs, each a `record` payload reference read when the order is issued, such as the start's brief, or the analyzer's `story`, `description` (the approved description), `roadmap`, `truths` (the story's current truths, once it was refined) and, in its drafting order, `questions` (the set with every answer and deferral), or the phase planner's `phase` (the phase's number, goal and detail), `stories` (the committed stories in order, each with its current truths), `description`, `capacity` (the capacity and the phase's size, only when `planning.phase_capacity` is set) and `approved_items` (the evidence items of the phase's plans in force), and in a revision order `draft` (the draft it revises) and `questions` (that draft's set with every answer and deferral) ([0005](0005-context-plans-and-acceptance.md) section 4). A retry keeps its parent's inputs | Ledger | +| Expected result | The typed result the worker must return. For the start planner it is a `scope-submit` naming the order in `work_order`. The analyzer returns its questions or its draft truths to the session, which submits them with `story-questions-submit` or `context-submit` naming the order in `work_order`. The phase planner returns its plan to the session, which submits it with `plan-submit`, or with `plan-replace` for a plan replacing one in force, naming the order in `work_order` | The issuing area | An order is delivered as its id. The issuing call answers with the id, the agent stub to launch, the model to pass as the Agent tool's `model` parameter or none, so the stub's `model: inherit` applies, the one-line prompt `Read Baley work order <id> and follow it.`, and a launch sentence saying to start that stub with the Agent tool and that prompt. The session starts the subagent with that prompt, and the worker reads its order whole by id through `document`, kind `work_order`, in parts of at most 24,576 bytes ([0012](0012-host-interface.md) section 5, `crates/baley/src/work_order/issue.rs`, `prompt`, `launch` and `record`). diff --git a/docs/design/0003-configuration-and-routing.md b/docs/design/0003-configuration-and-routing.md index 669df4a9..5bfd42c3 100644 --- a/docs/design/0003-configuration-and-routing.md +++ b/docs/design/0003-configuration-and-routing.md @@ -50,7 +50,7 @@ graph LR style 10 fill:#85bbf0,stroke:#5d82a8,color:#000000 4["<div style='font-weight: bold'>Host interface</div><div style='font-size: 70%; margin-top: 0px'>[Component]</div><div style='font-size: 80%; margin-top:10px'>MCP server (stdio), command<br />line and guard hook: the only<br />ways in. The guard hook<br />records its answers in the<br />per-user ledger.</div>"] style 4 fill:#85bbf0,stroke:#5d82a8,color:#000000 - 7["<div style='font-weight: bold'>Work order composer</div><div style='font-size: 70%; margin-top: 0px'>[Component]</div><div style='font-size: 80%; margin-top:10px'>Builds every work order: the<br />route from policy and the<br />model catalog, instructions<br />by identity from the binary,<br />inputs as references into the<br />record. In this build it<br />issues the start planner's<br />order, the analyzer's<br />questions and drafting orders<br />for a story's refinement, and<br />their retries.</div>"] + 7["<div style='font-weight: bold'>Work order composer</div><div style='font-size: 70%; margin-top: 0px'>[Component]</div><div style='font-size: 80%; margin-top:10px'>Builds every work order: the<br />route from policy and the<br />model catalog, instructions<br />by identity from the binary,<br />inputs as references into the<br />record. In this build it<br />issues the start planner's<br />order, the analyzer's<br />questions and drafting orders<br />for a story's refinement, the<br />phase planner's planning and<br />revision orders on phase/#lt;n#gt;,<br />and their retries.</div>"] style 7 fill:#85bbf0,stroke:#5d82a8,color:#000000 8["<div style='font-weight: bold'>Policy</div><div style='font-size: 70%; margin-top: 0px'>[Component]</div><div style='font-size: 80%; margin-top:10px'>Reads the global and project<br />settings, resolves the values<br />in effect and records which<br />applied.</div>"] style 8 fill:#85bbf0,stroke:#5d82a8,color:#000000 @@ -177,12 +177,12 @@ Which policy each command runs under (CFG-R8, CFG-R9). Policy version 0 means th | Baley command line | `baley config` and `baley models` commands | Receipts, fetch commands containing variable names, imported-list results and refusals | Not applicable | | Policy (component) | The settings files and the host; for a route, the host's effective policy with its policy version, a role, an attempt, the host's accepted model names and the host's rung map | The effective policy, or `config-unavailable`; a route, or `unknown-model` | Not applicable | | Model catalog (component) | Seeds, imported lists and owner changes, as events of the per-user project `user`; for a lookup, a host or provider name | The `model_catalog` view; for a lookup, the names that catalog accepts, a host's compiled aliases among them, and the catalog version | Not applicable | -| Work order composer ([0002](0002-system-design.md) section 8) | One order's role, subject, attempt, instructions and inputs, and the host's effective policy with the policy version the write's policy step returned. It reads the host's accepted model names from `user` itself | The route, from `resolve_route` with the host's rung map, its route record and the agent stub `bal-<role>-<rung>` for the rung sent, recorded in one `work_order.issued`; a receipt with the order's id, the stub, the one-line prompt and the launch sentence; or `unknown-model` with no order recorded | Not applicable | +| Work order composer ([0002](0002-system-design.md) section 8) | One order's role, subject, attempt, instructions and inputs, and the host's effective policy with the policy version the write's policy step returned; for the planner order `baley scope approve` issues at the terminal, Claude Code's effective policy with the version that command's policy step returned. It reads the host's accepted model names from `user` itself | The route, from `resolve_route` with the host's rung map, its route record and the agent stub `bal-<role>-<rung>` for the rung sent, recorded in one `work_order.issued`; a receipt with the order's id, the stub, the one-line prompt and the launch sentence; or `unknown-model` with no order recorded | Not applicable | | Guard hook ([0010](0010-guard.md)) | The hook's `CLAUDE_PROJECT_DIR`, and its working directory as the base for tool paths and the commit target where the branch is read | The session project and its guard settings, built with Claude Code's host sections and HEAD's copy of the session project's `baley.toml`, or torn settings naming the file, or no project | Not applicable | | Host adapter ([0012](0012-host-interface.md)) | A host, and for the effort table an exact model id and a rung | Claude Code's compiled tables in the catalog module: its aliases; its rung map, the identity, so rung `high` maps to Claude Code's effort `high`, the level sent; and the effort table's answer for the model at the rung, a level, `not-applicable` or `unknown`. The model is passed to the host as the route gives it, or not at all | Not applicable | -| Dispatched workers (the six roles) | The one-line prompt naming its order's id, started as the agent stub the order names; it reads the order through `document` ([0012](0012-host-interface.md) section 5) | A typed result through `apply`: the start planner's is a `scope-submit` naming its order. The analyzer returns its questions or its draft truths to the session, which submits them with `story-questions-submit` or `context-submit` naming the order | The route, decided by `roles.<role>.model`, `roles.<role>.effort` and `escalate_on_failure`: the stub's `effort` is the level sent for the route's `rung`, and the model is the route's, passed as the Agent tool's `model` parameter, or the session's through the stub's `model: inherit` when the route has none | +| Dispatched workers (the six roles) | The one-line prompt naming its order's id, started as the agent stub the order names; it reads the order through `document` ([0012](0012-host-interface.md) section 5) | A typed result through `apply`: the start planner's is a `scope-submit` naming its order. The analyzer returns its questions or its draft truths to the session, which submits them with `story-questions-submit` or `context-submit` naming the order, and the phase planner returns its plan, which the session submits with `plan-submit` or `plan-replace` naming the order | The route, decided by `roles.<role>.model`, `roles.<role>.effort` and `escalate_on_failure`: the stub's `effort` is the level sent for the route's `rung`, and the model is the route's, passed as the Agent tool's `model` parameter, or the session's through the stub's `model: inherit` when the route has none | -This area dispatches no worker. It supplies the route, the route record and the agent stub, which the composer records in a work order. `project-start` issues the start planner's order; `story-refine` issues the analyzer's questions or drafting order for a story, `story-questions-submit` the drafting order for an empty set and a closing `questions-answer` the drafting order with the answers, each at attempt 1; and `work-order-retry` issues the next attempt of a failed one ([0004](0004-starting-a-project-and-changing-scope.md) section 5, [0005](0005-context-plans-and-acceptance.md) section 5, [0012](0012-host-interface.md) section 5). The session starts the worker. The start planner's and the analyzer's are the only kinds issued so far; the other roles' orders are later builds'. +This area dispatches no worker. It supplies the route, the route record and the agent stub, which the composer records in a work order. Each of these issues its order at attempt 1: `project-start` the start planner's order; `story-refine` the analyzer's questions or drafting order for a story, `story-questions-submit` the drafting order for an empty set and a closing `questions-answer` the drafting order with the answers, each of these two only when no other analyzer order of the story is pending; `phase-plan` the phase planner's planning or revision order, a closing `questions-answer` of a plan draft's set the planner's revision order, only when an answer rejected a recommended answer and no other planner order of the phase is pending, and the owner's `baley scope approve` of a phase's commitment the planner's planning order. `work-order-retry` issues the next attempt of a failed one ([0004](0004-starting-a-project-and-changing-scope.md) section 5, [0005](0005-context-plans-and-acceptance.md) section 5, [0012](0012-host-interface.md) section 5). The session starts the worker, the one `baley scope approve` issued included. The start planner's, the analyzer's and the phase planner's are the only kinds issued so far; the other roles' orders are later builds'. ## 5. Commands and operations @@ -364,16 +364,18 @@ The warning states: Baley never reads your API keys. Keys live in your environme ### Route resolution (internal) -Called by the work order composer, never by a host. Five operations issue a work order through it: `project-start`, which resolves the start planner's route at attempt 1; `story-refine`, `story-questions-submit` for an empty set and a closing `questions-answer`, which resolve the analyzer's route at attempt 1, for role `analyzer` at its rung, `high` by default (CFG-R12, [0005](0005-context-plans-and-acceptance.md) section 5); and `work-order-retry`, which resolves the failed order's role again at the attempt the ledger gives, the failed order's attempt plus one, under the policy and catalog in force at the retry ([0012](0012-host-interface.md) section 5). The read-only `route` query below calls it too and records nothing. The composer resolves the route with `resolve_route`, then builds the route record from it and names the agent stub for the role at the rung sent. +Called by the work order composer, never by a host. These issue a work order through it: `project-start`, which resolves the start planner's route at attempt 1; `story-refine`, and `story-questions-submit` for an empty set and a closing `questions-answer` when no other analyzer order of the story is pending, which resolve the analyzer's route at attempt 1, for role `analyzer` at its rung, `high` by default (CFG-R12, [0005](0005-context-plans-and-acceptance.md) section 5); `phase-plan` when it issues the phase planner's planning or revision order, a closing `questions-answer` of a plan draft's set when an answer rejected a recommended answer and no other planner order of the phase is pending, which issues the planner's revision order, while a close on the recommendations answers `ready` with no order (`crates/baley/src/mcp/questions.rs`, `Relayed::closing` and `relay_record`), and the owner's `baley scope approve` of a phase's commitment, which issues the planner's planning order, each resolving the planner's route at attempt 1 of a new chain, role `planner` at its rung, `high` by default ([0005](0005-context-plans-and-acceptance.md) section 5, [0004](0004-starting-a-project-and-changing-scope.md) `scope approve`); and `work-order-retry`, which resolves the failed order's role again at the attempt the ledger gives, the failed order's attempt plus one, under the policy and catalog in force at the retry ([0012](0012-host-interface.md) section 5). The read-only `route` query below calls it too and records nothing. The composer resolves the route with `resolve_route`, then builds the route record from it and names the agent stub for the role at the rung sent. -- **Inputs:** the host's effective policy for the project and checkout, the one the write's policy step recorded, with that step's policy version; the host; the role; the attempt; the host's accepted model names with the catalog version, read from the per-user project `user`'s `model_catalog` view outside any transaction (the host's aliases alone at catalog version 0 when `user` is absent, or when a newer binary has brought its views past this binary's so the store answers it read-only, and the read never creates or seeds `user`); and the host's rung map. +The terminal has no host of its own, so `baley scope approve` composes the planner order's route for Claude Code, the only host (`Host::ALL`), under Claude Code's effective policy for the checkout, which its policy step records before the approval, and with Claude Code's accepted names (`crates/baley/src/scope/command.rs` (`approve` and `host_admitted`)). A second host needs a host choice for an order the terminal issues. + +- **Inputs:** the host's effective policy for the project and checkout, the one the write's policy step recorded, with that step's policy version (for `baley scope approve`, Claude Code's, recorded by that command's policy step); the host; the role; the attempt; the host's accepted model names with the catalog version, read from the per-user project `user`'s `model_catalog` view outside any transaction (the host's aliases alone at catalog version 0 when `user` is absent, or when a newer binary has brought its views past this binary's so the store answers it read-only, and the read never creates or seeds `user`); and the host's rung map. - **Outputs:** a route, its route record and the agent stub `bal-<role>-<rung>` for the rung sent (section 6). - **Refusals:** | Code | When | Requirement | |---|---|---| | `config-unavailable` | The effective policy cannot be built. Preparation answers it `failed` before the route is resolved, with nothing recorded | CFG-R9 | - | `unknown-model` | A stored model name is not in the host's accepted names (the owner removed it, or a file names one no catalog holds). Answered `refused`, naming the setting, its layer and file and every accepted name. On every operation that issues an order the route is composed after preparation's checkout admission and policy step, each its own transaction, so the refusal records no work order, while a `checkout.seen` the checkout admission recorded or a `policy.effective` the policy step recorded stays. The `route` query records nothing | CFG-R14 | + | `unknown-model` | A stored model name is not in the host's accepted names (the owner removed it, or a file names one no catalog holds). Answered `refused`, naming the setting, its layer and file and every accepted name. On every operation that issues an order the route is composed after preparation's checkout admission and policy step, each its own transaction, so the refusal records no work order, while a `checkout.seen` the checkout admission recorded or a `policy.effective` the policy step recorded stays. `baley scope approve` composes it after its own checkout admission and policy step, and the refusal approves nothing. The `route` query records nothing | CFG-R14 | | `routing-inputs-changed` | At the run, the policy version differs from the one at admission. This is Build 5's execution admission check: no work order issued so far is admitted to a run | CFG-R10 | ### route (query) @@ -637,7 +639,7 @@ sequenceDiagram participant W as Work order composer participant P as Policy participant T as Effort table - S->>O: project-start, story-refine, story-questions-submit or questions-answer, or work-order-retry naming a failed order + S->>O: project-start, story-refine, story-questions-submit, questions-answer or phase-plan, or work-order-retry naming a failed order O->>L: replay lookup, then the operation's own check alt the check refuses O-->>S: refused, nothing recorded @@ -667,7 +669,7 @@ sequenceDiagram end ``` -*Figure 5. Resolving a route for a work order. `project-start` resolves the start planner's route at attempt 1, and `story-refine`, `story-questions-submit` for an empty set and a closing `questions-answer` resolve the analyzer's route, role `analyzer` at its rung, at attempt 1; the two set calls compose the drafting order's route before their transaction and issue the order inside it, beside the set or the answers. `work-order-retry` takes its attempt from the ledger in its own check, the failed order's attempt plus one, and resolves the failed order's role again under the policy and catalog in force now. Each operation's check runs before the settings are read, so a refused check leaves no checkout admission or policy step behind it. The route is composed after checkout admission and the policy step, each its own transaction, so an `unknown-model` refusal records no work order, while a `checkout.seen` or `policy.effective` those steps recorded stays. The policy is the host's effective policy the write's policy step recorded, at that step's version. The accepted names are read from the per-user project `user` outside any transaction, and are the host's aliases alone at version 0 when `user` is absent or answers read-only. With no model, or an alias, the composer asks the effort table nothing and records `unknown`. Not drawn: a request the ledger already holds, which is answered from its record with no route resolved; the `route` query, which resolves a route the same way from settings it reads and judges, with no checkout admission or policy step, and records nothing; the instructions and inputs an order carries ([0012](0012-host-interface.md) section 8); and the check at a run that the routing inputs did not change since admission, `routing-inputs-changed`, which is Build 5's (CFG-R10).* +*Figure 5. Resolving a route for a work order. `project-start` resolves the start planner's route at attempt 1, and `story-refine`, and `story-questions-submit` for an empty set and a closing `questions-answer` when no other analyzer order of the story is pending, resolve the analyzer's route, role `analyzer` at its rung, at attempt 1; the two set calls compose the drafting order's route before their transaction and issue the order inside it, beside the set or the answers. `phase-plan`, when it issues the phase planner's planning or revision order, and a closing `questions-answer` of a plan draft's set when an answer rejected a recommended answer and no other planner order of the phase is pending, which issues the revision order inside its transaction beside the answers, resolve the planner's route, role `planner` at its rung, at attempt 1 of a new chain. A plan draft's set closed on the recommendations answers `ready` and issues no order. `work-order-retry` takes its attempt from the ledger in its own check, the failed order's attempt plus one, and resolves the failed order's role again under the policy and catalog in force now. Each operation's check runs before the settings are read, so a refused check leaves no checkout admission or policy step behind it. The route is composed after checkout admission and the policy step, each its own transaction, so an `unknown-model` refusal records no work order, while a `checkout.seen` or `policy.effective` those steps recorded stays. The policy is the host's effective policy the write's policy step recorded, at that step's version. The accepted names are read from the per-user project `user` outside any transaction, and are the host's aliases alone at version 0 when `user` is absent or answers read-only. With no model, or an alias, the composer asks the effort table nothing and records `unknown`. Not drawn: a request the ledger already holds, which is answered from its record with no route resolved; the owner's `baley scope approve` of a phase's commitment, which runs the same steps at the terminal after its approval's first step and composes the planner's route for Claude Code, the only host, under Claude Code's effective policy, so an `unknown-model` refusal approves nothing; the `route` query, which resolves a route the same way from settings it reads and judges, with no checkout admission or policy step, and records nothing; the instructions and inputs an order carries ([0012](0012-host-interface.md) section 8); and the check at a run that the routing inputs did not change since admission, `routing-inputs-changed`, which is Build 5's (CFG-R10).* ```mermaid sequenceDiagram @@ -807,9 +809,9 @@ The registry of built and planned settings, with the area that owns each setting | `git.forge_repo` | `owner/repo` | absent | project | [0011](0011-milestones-landing-undo-pause.md) | The repository on the forge | | `git.forge_host` | host name, optional port | absent | project | [0011](0011-milestones-landing-undo-pause.md) | The forge's host for self-hosted forges | | `git.remote` | remote name or absent | absent | project | [0001](0001-evidence-ledger.md) | The git remote the project's anchors are pushed to and read from; absent means the project has no forge remote and is verified locally | -| `workflow.test_command` | command line | absent | project | [0006](0006-execution.md) | The suite Baley runs (SYS-R8) | +| `workflow.test_command` | command line: not blank, with no control character, so one line, taken as written | absent | project | [0006](0006-execution.md) | The suite Baley runs (SYS-R8). `baley plan approve` records it as the approved plan's `suite`; with none set the plan is approved with no suite, and the answer says it cannot be admitted to execution until this is set ([0005](0005-context-plans-and-acceptance.md) `plan approve`) | | `workflow.lint_command` | command line | absent | project | [0006](0006-execution.md) | The lint Baley runs | -| `planning.phase_capacity` | integer, min 1, or absent | absent | both | [0005](0005-context-plans-and-acceptance.md) | The ceiling on a phase's size in tasks (PLN-R9) | +| `planning.phase_capacity` | integer, 1 to 4294967295, or absent | absent | both | [0005](0005-context-plans-and-acceptance.md) | The ceiling on a phase's size in tasks (PLN-R9). `plan-submit`, `plan-replace` and `baley plan approve` refuse `over-capacity` for a plan that would take the phase past it, and the planner's order carries it with the phase's size as its `capacity` input. With none set no plan is refused for size | | `planning.max_capture_bullets` | integer, min 1 | 40 | both | [0014](0014-support-families.md) | Report-only bound on active captured items | | `review.reviewers` | list of `host`, `openai`, `deepseek` | `["host"]` | both | [0008](0008-review.md) | Which reviewers run on every triggered review; outside providers need a current recorded acknowledgement (CFG-R28). The schema holds it with the grammar named in the type column: each name exactly `host`, `openai` or `deepseek`, in lower case. `baley config interview` is its setup reader and writer, in the global file's top level, and `config set` refuses it `list-not-settable`. Build 4 adds the review consumer | | `review.request_timeout_ms` | integer, 1 to 600000 | 540000 | both | [0008](0008-review.md) | Timeout of one outside review call | @@ -823,7 +825,7 @@ The registry of built and planned settings, with the area that owns each setting | `review.triggers.risk_surface.waive_routing_floor` | same list | absent | project | [0009](0009-risk.md) | Surfaces whose floor the owner waives | | `debug.attempt_threshold` | integer, min 1 | 3 | both | [0014](0014-support-families.md) | Attempts before a diagnosis review is offered | -The code's schema holds a setting from the task that builds its first reader (CFG-R7). It holds `roles.<role>.model`, `roles.<role>.effort` and `escalate_on_failure`, read by route resolution. It also holds `git.remote`, read by `anchor`, `acknowledge-restore`, anchored `verify` and `doctor`, and `git.protected_branches`, `git.on_protected` and `git.guard_hard_fail`, all project-scoped. The guard's judgement in `baley-core` reads the three guard settings, and the hook builds them from the session project's policy with Claude Code's host sections, as section 11 says. The schema also holds `updates.auto`, read once at `baley serve` startup to decide whether to start the detached updater, and `updates.source`, read by manual and detached checks from the global file with no host section applied (`crates/baley-core/src/policy/schema.rs` (`standard`), `crates/baley/src/update/detached.rs` (`should_start`), `crates/baley/src/update/command.rs` (`check`)). Set them with `baley config set --global updates.auto=true` and `baley config set --global updates.source=https://<source>`. The source grammar requires `https://` followed by at least one character and rejects whitespace, control characters, queries and fragments (`crates/baley-core/src/policy/schema.rs` (`is_https_address`)). A file that names any other setting in this table gets an unknown-name diagnostic until that setting's reader exists, and the command line refuses to write it. The schema also holds `review.reviewers`, a list of `host`, `openai` and `deepseek` that defaults to `["host"]` and is `both`-scoped (`crates/baley-core/src/policy/schema.rs` (`Kind`, `REVIEWER_NAMES` and `standard`)), whose first reader is the interview's setup reader (`crates/baley/src/config_command/reviewers.rs` (`written` and `stored`)) and whose only writer is the interview (`crates/baley/src/config_command/set.rs` (`apply_list` and `replace_list`)). Build 4 adds its review consumer. The schema also holds `owner.name`, global-scoped with no default, whose value is a name that is not blank and holds no control character, which also keeps it to one line (`crates/baley-core/src/policy/schema.rs` (`Kind`, `is_person_name` and `standard`)). Its reader is the owner reader, which the provider acknowledgement and `baley scope approve` call and which falls back to git's `user.name` when the setting is absent (`crates/baley/src/providers/identity.rs` (`owner` and `owner_name`)). A file holding a value that breaks those rules is invalid, as for any setting, and `config set` refuses such a value `invalid-value` (`crates/baley-core/src/policy/config_command/set.rs` (`convert`)). +The code's schema holds a setting from the task that builds its first reader (CFG-R7). It holds `roles.<role>.model`, `roles.<role>.effort` and `escalate_on_failure`, read by route resolution. It also holds `git.remote`, read by `anchor`, `acknowledge-restore`, anchored `verify` and `doctor`, and `git.protected_branches`, `git.on_protected` and `git.guard_hard_fail`, all project-scoped. The guard's judgement in `baley-core` reads the three guard settings, and the hook builds them from the session project's policy with Claude Code's host sections, as section 11 says. The schema also holds `updates.auto`, read once at `baley serve` startup to decide whether to start the detached updater, and `updates.source`, read by manual and detached checks from the global file with no host section applied (`crates/baley-core/src/policy/schema.rs` (`standard`), `crates/baley/src/update/detached.rs` (`should_start`), `crates/baley/src/update/command.rs` (`check`)). Set them with `baley config set --global updates.auto=true` and `baley config set --global updates.source=https://<source>`. The source grammar requires `https://` followed by at least one character and rejects whitespace, control characters, queries and fragments (`crates/baley-core/src/policy/schema.rs` (`is_https_address`)). A file that names any other setting in this table gets an unknown-name diagnostic until that setting's reader exists, and the command line refuses to write it. The schema also holds `review.reviewers`, a list of `host`, `openai` and `deepseek` that defaults to `["host"]` and is `both`-scoped (`crates/baley-core/src/policy/schema.rs` (`Kind`, `REVIEWER_NAMES` and `standard`)), whose first reader is the interview's setup reader (`crates/baley/src/config_command/reviewers.rs` (`written` and `stored`)) and whose only writer is the interview (`crates/baley/src/config_command/set.rs` (`apply_list` and `replace_list`)). Build 4 adds its review consumer. The schema also holds `owner.name`, global-scoped with no default, whose value is a name that is not blank and holds no control character, which also keeps it to one line (`crates/baley-core/src/policy/schema.rs` (`Kind`, `is_person_name` and `standard`)). Its reader is the owner reader, which the provider acknowledgement and `baley scope approve` call and which falls back to git's `user.name` when the setting is absent (`crates/baley/src/providers/identity.rs` (`owner` and `owner_name`)). A file holding a value that breaks those rules is invalid, as for any setting, and `config set` refuses such a value `invalid-value` (`crates/baley-core/src/policy/config_command/set.rs` (`convert`)). The schema also holds `planning.phase_capacity`, `both`-scoped with no default, a whole number from 1 to 4294967295, and `workflow.test_command`, project-scoped with no default, a command line that is not blank and holds no control character, taken as written and never trimmed (`crates/baley-core/src/policy/schema.rs` (`Kind` and `standard`), `crates/baley-core/src/policy/parse.rs` (`Value`)). The capacity's first readers are the planning facts that `plan-submit`, `plan-replace` and `baley plan approve` judge a plan's size against (`crates/baley/src/planning/facts.rs` (`capacity`), `crates/baley/src/mcp/planning.rs` (`capacity`), `crates/baley/src/planning/approve.rs` (`judge` and `rejudged`)) and the planner order's inputs (`crates/baley/src/planning/inputs.rs` (`capacity`)). The test command's first reader is `baley plan approve`, which records it as the plan's `suite` (`crates/baley/src/planning/approve.rs` (`suite`)). `config set` writes either, `config show` shows either, and the recorded policy carries both (`crates/baley-core/src/policy/recorded/event.rs` (`value_json`)). The interview asks neither. Settings removed from the schema because nothing reads them (CFG-R7): `granularity`, `workflow.research`, `workflow.plan_check`, `workflow.verifier`, `workflow.inline_plan_threshold`, `workflow.max_plan_tasks`, `workflow.max_plan_bytes`, `git.create_tag`, `git.on_land_cleanup`, `git.issue_check` (removed for good: tag and reap are the owner's choice at each merge confirmation and the tracker check always runs, [0011](0011-milestones-landing-undo-pause.md)), `review.decision_review.tier`, `review.decision_review.effort`. Removed because the design replaces them: `review.mode` (every reviewer runs, [0008](0008-review.md)), `workflow.skip_discuss` (refinement is never skipped, [0013](0013-next-action-and-progress.md)), `memory.backend` and `review.consult.*` (recall always available; consult is the diagnosis review, [0014](0014-support-families.md)), `review.key_file` (Baley handles no keys, CFG-R24 and CFG-R25) and `planning.commit_docs` (Baley writes no records into the working tree, [0001](0001-evidence-ledger.md) EVD-R18). Phase capacity is designed in [0005](0005-context-plans-and-acceptance.md) (PLN-R9), not as free numbers here. @@ -833,26 +835,26 @@ Not applicable. This area serves no instructions: the model is never told about ## 11. Build status -The binary parks the inherited engine for Build 9 to delete, and nothing in production reaches it (`crates/baley/src/inherited.rs` (its module comment)). The session server answers `config-entry`, `config-facts` and `config-interview` (`crates/baley/src/mcp/operations.rs` (`QUERY_OPERATIONS`)) and `config-apply` and `config-interview-apply` (`crates/baley/src/mcp/operations.rs` (`APPLY_OPERATIONS`)) as `operation-unavailable`, and the operation baseline names Build 2, whose `baley config` commands replace them. It serves `route` as a project query (`crates/baley/src/mcp/operations.rs` (`QUERY_OPERATIONS`), `crates/baley/src/mcp/handler.rs` (`operate`)), which explains a route and records nothing (`crates/baley/src/mcp/work_order.rs` (`judge_route_arguments`, `route_answer` and `serve_route`)). The session server's preparation walks from `CLAUDE_PROJECT_DIR` and checks the project against the ledger for every project call whose arguments pass their checks, and for a new write first runs the write's own check where its operation has one, then validates the settings, admits the checkout and runs the policy step (`crates/baley/src/mcp/prepare.rs` (`prepare` and `prepare_checked`)), while a read or a known replay skips all four. A settings-reading read, the `route` query's, reads and judges the settings after the known-project check and stops there (`crates/baley/src/mcp/prepare.rs` (`prepare_settings_read`), `crates/baley/src/mcp/prepare.rs` (`next`)). `capture` runs the walk, the settings, checkout admission and the policy step, `scope-submit`, `project-start`, `work-order-fail`, `work-order-retry` and `questions-answer` run their checks first and then the same three, and `document` runs the walk and the known-project check only (`crates/baley/src/mcp/capture.rs` (`serve`), `crates/baley/src/mcp/scope.rs` (`prepared`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail` and `serve_retry`), `crates/baley/src/mcp/questions.rs` (`serve`), `crates/baley/src/mcp/document.rs` (`serve`)). Production reaches this area through the `config`, `models`, `init`, `install`, `update` and ledger commands, the session server's startup and preparation, and the guard hook. The hook builds a commit's policy with the policy step's `build` and Claude Code's host sections from capped reads of its own, and never runs the step (`crates/baley/src/guard_hook/policy.rs` (`gather` and `settings`), `crates/baley/src/policy_step/mod.rs` (`step`)). Nothing in production reads the inherited JSON layers any more: only the parked engine and its tests reach the inherited config module. +The binary parks the inherited engine for Build 9 to delete, and nothing in production reaches it (`crates/baley/src/inherited.rs` (its module comment)). The session server answers `config-entry`, `config-facts` and `config-interview` (`crates/baley/src/mcp/operations.rs` (`QUERY_OPERATIONS`)) and `config-apply` and `config-interview-apply` (`crates/baley/src/mcp/operations.rs` (`APPLY_OPERATIONS`)) as `operation-unavailable`, and the operation baseline names Build 2, whose `baley config` commands replace them. It serves `route` as a project query (`crates/baley/src/mcp/operations.rs` (`QUERY_OPERATIONS`), `crates/baley/src/mcp/handler.rs` (`operate`)), which explains a route and records nothing (`crates/baley/src/mcp/work_order.rs` (`judge_route_arguments`, `route_answer` and `serve_route`)). The session server's preparation walks from `CLAUDE_PROJECT_DIR` and checks the project against the ledger for every project call whose arguments pass their checks, and for a new write first runs the write's own check where its operation has one, then validates the settings, admits the checkout and runs the policy step (`crates/baley/src/mcp/prepare.rs` (`prepare` and `prepare_checked`)), while a read or a known replay skips all four. A settings-reading read, the `route` query's and the capacity read of `plan-submit` and `plan-replace`, reads and judges the settings after the known-project check and stops there (`crates/baley/src/mcp/prepare.rs` (`prepare_settings_read`), `crates/baley/src/mcp/prepare.rs` (`next`)). `capture` runs the walk, the settings, checkout admission and the policy step; `scope-submit`, `project-start`, `work-order-fail`, `work-order-retry`, `questions-answer`, `story-refine`, `story-questions-submit`, `context-submit` and `phase-plan` run their checks first and then the same three; `plan-submit` and `plan-replace` first read and judge the settings for the capacity, recording nothing, and then run their checks and the same three; and `document`, `context-intake` and `plan-read` run the walk and the known-project check only (`crates/baley/src/mcp/capture.rs` (`serve`), `crates/baley/src/mcp/scope.rs` (`prepared`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail` and `serve_retry`), `crates/baley/src/mcp/questions.rs` (`serve`), `crates/baley/src/mcp/refine.rs` (`serve`, `serve_questions`, `serve_context` and `serve_intake`), `crates/baley/src/mcp/planning.rs` (`serve`, `serve_submit`, `capacity` and `serve_read`), `crates/baley/src/mcp/document.rs` (`serve`)). Production reaches this area through the `config`, `models`, `init`, `install`, `update` and ledger commands, the owner's recording commands under `scope`, `story`, `questions` and `plan`, the session server's startup and preparation, and the guard hook. The hook builds a commit's policy with the policy step's `build` and Claude Code's host sections from capped reads of its own, and never runs the step (`crates/baley/src/guard_hook/policy.rs` (`gather` and `settings`), `crates/baley/src/policy_step/mod.rs` (`step`)). Nothing in production reads the inherited JSON layers any more: only the parked engine and its tests reach the inherited config module. | Requirement | Status | Where | |---|---|---| | CFG-R1 | Partly built | The policy module reads `config.toml` and `baley.toml` as TOML (`crates/baley-core/src/policy/parse.rs` (`parse_layer` and `document`), `crates/baley/src/settings.rs` (`read`, `gather` and `judge`)), and the guard hook reads them the same way, capped (`crates/baley/src/guard_hook/policy.rs` (`gather`)). Only the parked engine still reads and writes the inherited JSON layers (`crates/baley/src/config/write.rs` (`paths`)), until Build 9 deletes it. | | CFG-R2 | Built | Platform config folders and `BALEY_HOME` in `crates/baley/src/folders.rs` (`resolve`); the global file's path and reader in `crates/baley/src/settings.rs` (`global_path`, `read`, `gather` and `judge`). The guard hook reads the same global file from the config folder it resolves, capped at 1 MiB (`crates/baley/src/guard_hook/policy.rs` (`gather`)). | | CFG-R3 | Built | Discovery takes the nearest `baley.toml` at or below the repository root (`crates/baley/src/discovery.rs` (`discover`)). The policy module reads and checks the project id and name in its `[project]` table and renders the file whole (`crates/baley-core/src/policy/project.rs` (`is_project_id`, `read_project` and `render_project`)), and the project's settings come from the copy committed at HEAD, read through git (`crates/baley/src/committed.rs` (`read` and `sequence`)). A bounded variant of that reader, for the guard, runs the same three launches under its own git caller, each on the timeout the guard's budget grants from the time it has left, and keeps at most 1 MiB of each stream and 256 bytes of git's first stderr line, redacted before the cut (`crates/baley/src/committed.rs` (`GuardRefusal`, `read_for_guard`, `first_line_excerpt` and `stderr_text`)). The guard hook calls it at the session project's root (`crates/baley/src/guard_hook/policy.rs` (`gather`)), and its refusal gives git's excerpt apart so that a guard record can leave it out (`crates/baley/src/committed.rs` (`GuardRefusal`)). `baley init` writes the file at the repository root when none exists (`crates/baley/src/init.rs` (`write_project_file`)), `baley init --new-id` rewrites it with a new project id, keeping every other key, checked against the working-tree file it read (`crates/baley/src/init.rs` (`initialize`)), and `baley config set --project` rewrites the working-tree file whole from its own bytes, keeping its `[project]` table and every other key (`crates/baley-core/src/policy/config_command/file.rs` (`render_file`), `crates/baley/src/config_command/set.rs` (`attempt`)). | -| CFG-R4 | Built | The walk for the command line: `discover` judges the ancestors of the working directory that its gatherer observes, nearest first, stops at the first `.git` and never uses a file above it, and the nearest of nested entries applies alone. Only not-found is absence for either name. A `baley.toml` entry, including a directory or dangling link, or a metadata error other than not-found binds the nearest folder as the project. A `.git` entry or a metadata error other than not-found makes the folder the repository root and ends the walk (`crates/baley/src/discovery.rs` (`discover`, `ancestors`, `observe` and `entry_present`)). `baley init`, `purge`, `baley config set`, `baley config show`, `baley config interview`, `anchor`, `acknowledge-restore`, anchored `verify` and `doctor` call it (`crates/baley/src/init.rs` (`initialize`), `crates/baley/src/ledger/commands.rs` (`purge_policy_version`), `crates/baley/src/ledger/commands.rs` (`gather_settings`), `crates/baley/src/config_command/set.rs` (`found_project`), `crates/baley/src/config_command/show.rs` (`attempt`), `crates/baley/src/config_command/interview.rs` (`attempt`)). A plain project-file set outside a project is refused with `not-a-project`, as is `config show` for a project-scoped setting asked outside one (`crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`), `crates/baley-core/src/policy/config_command/show.rs` (`judge_show`)). The standard schema holds four project-scoped settings, `git.remote` and the three guard settings, so `config show git.remote` outside a project is refused `not-a-project`. `anchor`, `acknowledge-restore` and anchored `verify` act on the discovered project, and a project named on the command line that differs from it, or is named when none is found, is refused (`crates/baley/src/ledger/anchor_plan.rs` (`judge_target`), `crates/baley/src/ledger/command_plan.rs` (`next`)). `config interview` refuses `not-a-project` before its first question, for `--project` and for a default that comes out as the project file, and never falls back to the global file (`crates/baley/src/config_command/interview.rs` (`begin`), `crates/baley/src/config_command/interview.rs` (`begin`)). The server captures `CLAUDE_PROJECT_DIR` once at start (`crates/baley/src/mcp/context.rs` (`gather`)), and its preparation walks from that directory afresh on every project call through the same `ancestors` and `discover`. It answers `failed` with `not-a-project` when no project file is found and `project-context-invalid` when the directory cannot be walked (`crates/baley/src/mcp/prepare.rs` (`next`)). `capture`, `scope-submit`, `document`, `project-start`, `work-order-fail`, `work-order-retry`, `questions-answer` and the `route` query reach that walk on every call whose arguments pass their checks, since an argument refusal is answered before preparation (`crates/baley/src/mcp/capture.rs` (`serve`), `crates/baley/src/mcp/scope.rs` (`serve`), `crates/baley/src/mcp/document.rs` (`serve`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail`, `serve_retry` and `serve_route`), `crates/baley/src/mcp/questions.rs` (`serve`)). The guard hook judges its `CLAUDE_PROJECT_DIR` with the server's rules (`crates/baley/src/mcp/context.rs` (`project_context`)) and walks from it through the same `ancestors` and `discover` on every call, binding a project only when the walk finds a managed checkout. A missing or invalid directory, or one in no project, binds none, and the hook's working directory never stands in for it: a second walk, from the working directory, finds the checkout whose `baley.toml` is protected and whose root keys remembered denials for a commit at cwd (`crates/baley/src/guard_hook/context.rs` (`gather`, `walk` and `judge`)). A commit's target is resolved from the command and supplies the branch directory (`crates/baley/src/guard_hook/decide.rs` (`next`), `crates/baley/src/guard_hook/mod.rs` (`run`)); a redirected commit uses the target walk's checkout root for remembered denials (`crates/baley/src/guard_hook/record.rs` (`judged`)). | -| CFG-R5 | Partly built | Scopes in the schema and the scope diagnostic in the walk (`crates/baley-core/src/policy/schema.rs` (`Scope`), `crates/baley-core/src/policy/parse.rs` (`setting`)); the command-line refusal `wrong-layer` is built, judged over every pair of a `config set` before anything is read (`crates/baley-core/src/policy/config_command/set.rs` (`excludes`), `crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`)). `git.remote` and the three guard settings are project-scoped (`crates/baley-core/src/policy/schema.rs` (`standard`)), so the standard schema produces them: a global `config set` of `git.remote`, `git.on_protected` or `git.guard_hard_fail` refuses `wrong-layer`, a set of `git.protected_branches` in either file refuses `list-not-settable` first, and a global file holding any of the four gets the scope diagnostic. `updates.auto`, `updates.source` and `owner.name` are global-scoped, so a project `config set` refuses `wrong-layer` and a project file holding any of them gets the scope diagnostic (`crates/baley-core/src/policy/schema.rs` (`standard`)). `review.reviewers` is `both`-scoped (`crates/baley-core/src/policy/schema.rs` (`standard`)), so a file of either layer may hold it, and a set of it refuses `list-not-settable` before the layer is judged (`crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`)). The guard hook's policy is built by the policy module, so the same scopes apply to it (`crates/baley/src/guard_hook/policy.rs` (`settings`)). The inherited `GLOBAL_ONLY` list, applied at merge (`crates/baley/src/config/mod.rs` (`GLOBAL_ONLY`), `crates/baley/src/config/merge.rs` (`scoped`)), and the `repo_only` flag in `crates/baley/src/config/schema.json`, refused at write (`crates/baley/src/config/write.rs` (`validate_update`)), are the parked engine's, and both stay until Build 9. | +| CFG-R4 | Built | The walk for the command line: `discover` judges the ancestors of the working directory that its gatherer observes, nearest first, stops at the first `.git` and never uses a file above it, and the nearest of nested entries applies alone. Only not-found is absence for either name. A `baley.toml` entry, including a directory or dangling link, or a metadata error other than not-found binds the nearest folder as the project. A `.git` entry or a metadata error other than not-found makes the folder the repository root and ends the walk (`crates/baley/src/discovery.rs` (`discover`, `ancestors`, `observe` and `entry_present`)). `baley init`, `purge`, `baley config set`, `baley config show`, `baley config interview`, `anchor`, `acknowledge-restore`, anchored `verify` and `doctor` call it (`crates/baley/src/init.rs` (`initialize`), `crates/baley/src/ledger/commands.rs` (`purge_policy_version`), `crates/baley/src/ledger/commands.rs` (`gather_settings`), `crates/baley/src/config_command/set.rs` (`found_project`), `crates/baley/src/config_command/show.rs` (`attempt`), `crates/baley/src/config_command/interview.rs` (`attempt`)). A plain project-file set outside a project is refused with `not-a-project`, as is `config show` for a project-scoped setting asked outside one (`crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`), `crates/baley-core/src/policy/config_command/show.rs` (`judge_show`)). The standard schema holds five project-scoped settings, `git.remote`, the three guard settings and `workflow.test_command`, so `config show git.remote` outside a project is refused `not-a-project`. `anchor`, `acknowledge-restore` and anchored `verify` act on the discovered project, and a project named on the command line that differs from it, or is named when none is found, is refused (`crates/baley/src/ledger/anchor_plan.rs` (`judge_target`), `crates/baley/src/ledger/command_plan.rs` (`next`)). `config interview` refuses `not-a-project` before its first question, for `--project` and for a default that comes out as the project file, and never falls back to the global file (`crates/baley/src/config_command/interview.rs` (`begin`), `crates/baley/src/config_command/interview.rs` (`begin`)). The server captures `CLAUDE_PROJECT_DIR` once at start (`crates/baley/src/mcp/context.rs` (`gather`)), and its preparation walks from that directory afresh on every project call through the same `ancestors` and `discover`. It answers `failed` with `not-a-project` when no project file is found and `project-context-invalid` when the directory cannot be walked (`crates/baley/src/mcp/prepare.rs` (`next`)). `capture`, `scope-submit`, `document`, `project-start`, `work-order-fail`, `work-order-retry`, `questions-answer`, `story-refine`, `story-questions-submit`, `context-intake`, `context-submit`, `phase-plan`, `plan-submit`, `plan-replace`, `plan-read` and the `route` query reach that walk on every call whose arguments pass their checks, since an argument refusal is answered before preparation (`crates/baley/src/mcp/capture.rs` (`serve`), `crates/baley/src/mcp/scope.rs` (`serve`), `crates/baley/src/mcp/document.rs` (`serve`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail`, `serve_retry` and `serve_route`), `crates/baley/src/mcp/questions.rs` (`serve`), `crates/baley/src/mcp/refine.rs` (`serve`, `serve_questions`, `serve_intake` and `serve_context`), `crates/baley/src/mcp/planning.rs` (`serve`, `serve_submit` and `serve_read`)). The guard hook judges its `CLAUDE_PROJECT_DIR` with the server's rules (`crates/baley/src/mcp/context.rs` (`project_context`)) and walks from it through the same `ancestors` and `discover` on every call, binding a project only when the walk finds a managed checkout. A missing or invalid directory, or one in no project, binds none, and the hook's working directory never stands in for it: a second walk, from the working directory, finds the checkout whose `baley.toml` is protected and whose root keys remembered denials for a commit at cwd (`crates/baley/src/guard_hook/context.rs` (`gather`, `walk` and `judge`)). A commit's target is resolved from the command and supplies the branch directory (`crates/baley/src/guard_hook/decide.rs` (`next`), `crates/baley/src/guard_hook/mod.rs` (`run`)); a redirected commit uses the target walk's checkout root for remembered denials (`crates/baley/src/guard_hook/record.rs` (`judged`)). | +| CFG-R5 | Partly built | Scopes in the schema and the scope diagnostic in the walk (`crates/baley-core/src/policy/schema.rs` (`Scope`), `crates/baley-core/src/policy/parse.rs` (`setting`)); the command-line refusal `wrong-layer` is built, judged over every pair of a `config set` before anything is read (`crates/baley-core/src/policy/config_command/set.rs` (`excludes`), `crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`)). `git.remote` and the three guard settings are project-scoped (`crates/baley-core/src/policy/schema.rs` (`standard`)), so the standard schema produces them: a global `config set` of `git.remote`, `git.on_protected` or `git.guard_hard_fail` refuses `wrong-layer`, a set of `git.protected_branches` in either file refuses `list-not-settable` first, and a global file holding any of the four gets the scope diagnostic. `updates.auto`, `updates.source` and `owner.name` are global-scoped, so a project `config set` refuses `wrong-layer` and a project file holding any of them gets the scope diagnostic (`crates/baley-core/src/policy/schema.rs` (`standard`)). `review.reviewers` is `both`-scoped (`crates/baley-core/src/policy/schema.rs` (`standard`)), so a file of either layer may hold it, and a set of it refuses `list-not-settable` before the layer is judged (`crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`)). `planning.phase_capacity` is `both`-scoped and `workflow.test_command` project-scoped, so a global `config set` of `workflow.test_command` refuses `wrong-layer` and a global file holding it gets the scope diagnostic (`crates/baley-core/src/policy/schema.rs` (`standard`)). The guard hook's policy is built by the policy module, so the same scopes apply to it (`crates/baley/src/guard_hook/policy.rs` (`settings`)). The inherited `GLOBAL_ONLY` list, applied at merge (`crates/baley/src/config/mod.rs` (`GLOBAL_ONLY`), `crates/baley/src/config/merge.rs` (`scoped`)), and the `repo_only` flag in `crates/baley/src/config/schema.json`, refused at write (`crates/baley/src/config/write.rs` (`validate_update`)), are the parked engine's, and both stay until Build 9. | | CFG-R6 | Built | In the policy module: five layers in order and only the connected host's section (`crates/baley-core/src/policy/merge.rs` (`merge`)); the command line connects no host, so `config show` applies none unless `--host` names one, and then shows the effective values that host would run under (`crates/baley-core/src/policy/config_command/show.rs` (`render_show`)). `config interview` takes `--host` the same way: that host's sections apply to the value in force it shows with each question (`crates/baley/src/config_command/interview.rs` (`begin`)). The guard hook merges the five layers through the same module with Claude Code's sections (`crates/baley/src/guard_hook/policy.rs` (`settings`)). The inherited merge of defaults, global and repo layers, which has no host sections (`crates/baley/src/config/merge.rs` (`merge`)), is reached only by the parked engine, and Build 9 deletes it. | -| CFG-R7 | Partly built | An unknown name is ignored with a diagnostic (`crates/baley-core/src/policy/parse.rs` (`table`), `crates/baley-core/src/policy/parse.rs` (`unknown`)); the twelve settings without readers are gone from `crates/baley/src/config/schema.json`; the command-line refusal `unknown-setting` is built for `config set` and `config show` (`crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`), `crates/baley-core/src/policy/config_command/show.rs` (`judge_show`)). `review.reviewers` entered the schema with its first reader, the interview's (`crates/baley/src/config_command/reviewers.rs` (`written` and `stored`)), and `config set` refuses it as a list (`crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`)). `owner.name` entered the schema with its reader, the owner reader that the provider acknowledgement and `baley scope approve` call (`crates/baley-core/src/policy/schema.rs` (`standard`), `crates/baley/src/providers/identity.rs` (`owner` and `owner_name`)). The inherited JSON schema, which only the parked engine's merge and writer read, stays until Build 9. | -| CFG-R8 | Partly built | The `policy.effective` event, registered at version 1, and its payload built from the merged policy (`crates/baley-core/src/policy/recorded/event.rs` (`POLICY_EFFECTIVE`, `POLICY_EFFECTIVE_VERSION` and `register_policy_events`), `crates/baley-core/src/policy/recorded/event.rs` (`recorded_policy` and `effective_payload`)); the `policy` view and `PolicyProjector`, which keep the latest record per checkout and host (`crates/baley-core/src/policy/recorded/view.rs` (`policy_spec` and `PolicyProjector`)); and the judge of whether to record (`crates/baley-core/src/policy/recorded/judge.rs` (`COMPARED`, `PolicyJudgement` and `judge_policy`)). The binary's policy step holds the recorder, which appends `policy.effective` as Baley's own `policy.record` command only when the judge finds a change (`crates/baley/src/policy_step/record.rs` (`record` and `record_once`)), and the entry point, which reads the catalog version and returns the version in force (`crates/baley/src/policy_step/mod.rs` (`step` and `observe_catalog_version`)). The command line's store registers `policy.effective`, `checkout.seen`, `capture.recorded`, `guard.answered`, `guard.policy_recorded`, `install.recorded`, `update.checked`, `update.failed`, `providers.acknowledged`, the eleven scope types, `work_order.issued` and `work_order.failed`, the four question types `questions.opened`, `question.answered`, `question.deferred` and `questions.abandoned`, and `story.refined`, and the `model_catalog`, `policy`, `checkout`, `capture`, `guard`, `guard_policy`, `install`, `draft`, `roadmap`, `phase`, `phase_detail`, `backlog`, `work_order`, `questions` and `truths` views, at view set version 13. No view holds `providers.acknowledged` (`crates/baley/src/ledger/open.rs` (`options`)). `baley init` runs the step after `project.initialized` and checkout admission, in the order its plan gives (`crates/baley/src/init.rs` (`plan`), `crates/baley/src/init.rs` (`initialize`)). `purge` runs it only from a checkout of the project it names and records the version in force, otherwise 0 (`crates/baley-core/src/policy/recorded/purge.rs` (`purge_policy`), `crates/baley/src/ledger/commands.rs` (`purge`), `crates/baley/src/ledger/commands.rs` (`purge_policy_version`)). `config set` runs it after its write, in a project in this machine's ledger, and reports the version it returns (`crates/baley/src/config_command/set.rs` (`attempt`), `crates/baley/src/config_command/set.rs` (`record_policy` and `record_version`)). A set outside a project or in a project the ledger does not hold runs no step and reports 0, and one that changes nothing reports the version in force (`crates/baley-core/src/policy/config_command/outcome.rs` (`choose_outcome`)). `anchor` and `acknowledge-restore` run checkout admission and then the step after the settings read and the exact-name check of `git.remote`, and before their own command, which carries the version the step returns (`crates/baley/src/ledger/command_plan.rs` (`next`), `crates/baley/src/ledger/commands.rs` (`settle`), `crates/baley/src/ledger/commands.rs` (`anchor` and `acknowledge_request`), `crates/baley/src/ledger/commands.rs` (`acknowledge`)). Anchored `verify` and `doctor` run no step and append nothing. Every caller runs checkout admission between the settings read and the step. The core judges the checkout against the project's other checkouts, refusing a different remote URL as `project-id-conflict`, and plans `checkout.seen` before the step and the step before the command (`crates/baley-core/src/checkout/judge.rs` (`judge_checkout`), `crates/baley-core/src/checkout/plan.rs` (`plan_checkout_admission`)). The store step records `checkout.seen` as Baley's own `checkout.admit` command, or refuses a fork and records nothing, in one transaction (`crates/baley/src/checkout/admit.rs` (`admit` and `admit_once`)), after the facts are gathered through git (`crates/baley/src/checkout/gather.rs` (`root_commit`), `crates/baley/src/checkout/gather.rs` (`gather` and `remote_url`)) and stripped of user information (`crates/baley/src/checkout/strip.rs` (`strip_user_information`)). `purge`, `config set`, `anchor` and `acknowledge-restore` call it through one entry (`crates/baley/src/checkout/mod.rs` (`gather_and_admit`)), as does the server's write preparation, each right before its step: `purge` (`crates/baley/src/ledger/commands.rs` (`purge_policy_version`)), `config set` (`crates/baley/src/config_command/set.rs` (`attempt` and `admit_checkout`)), `anchor` (`crates/baley/src/ledger/commands.rs` (`anchor`)) and `acknowledge-restore` (`crates/baley/src/ledger/commands.rs` (`acknowledge`)). `baley scope approve` runs checkout admission and then the step after its approval's first step, which reads and judges and records nothing, and before the approval, which carries the version the step returns (`crates/baley/src/scope/command.rs` (`approve`, `admitted`)). `baley questions answer` runs them the same way after its check against the set, which records nothing, and before the answers and deferrals, which carry the version the step returns (`crates/baley/src/questions/command.rs` (`record_answers`)), and so does `baley story truths approve` after its approval's first step and before `story.refined` (`crates/baley/src/refine/command.rs` (`approve`)). `baley init` gathers before it opens the ledger and admits as a step of its plan (`crates/baley/src/init.rs` (`initialize`), `crates/baley/src/init.rs` (`initialize`)). The server's write preparation runs checkout admission and then the step for the call's host, as Baley's own commands carrying the call's caller and the server's time, and the prepared command carries the version the step returned (`crates/baley/src/mcp/prepare.rs` (`write_next` and `perform`), `crates/baley/src/policy_step/mod.rs` (`step` and `observe_catalog_version`)). The step records under the host's key, while checkout admission is keyed by the policy that names no host and so carries the version stored for the checkout and no host (`crates/baley/src/mcp/prepare.rs` (`WritePolicies` and `judge_settings`)). A read and a request the ledger already holds run neither, and neither runs when a write's own check ends the call (`crates/baley/src/mcp/prepare.rs` (`next` and `write_next`)). `capture` reaches this for a request the ledger does not yet hold (`crates/baley/src/mcp/capture.rs` (`serve`)), `scope-submit`, `project-start`, `work-order-fail`, `work-order-retry`, `questions-answer`, `story-refine`, `story-questions-submit` and `context-submit` do once their checks pass (`crates/baley/src/mcp/scope.rs` (`prepared`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail` and `serve_retry`), `crates/baley/src/mcp/questions.rs` (`serve`), `crates/baley/src/mcp/refine.rs` (`serve`, `serve_questions` and `serve_context`)), `document`, `context-intake` and the `route` query never do (`crates/baley/src/mcp/prepare.rs` (`prepare_settings_read`), `crates/baley/src/mcp/refine.rs` (`serve_intake`)), and the guard never runs it: it builds a commit's policy with the step's `build` and records no `policy.effective` (`crates/baley/src/guard_hook/policy.rs` (`settings`)). The parked engine's routes persist its config inputs only (`crates/baley/src/config/reload.rs` (`routing_inputs`)) until Build 9. | -| CFG-R9 | Partly built | Validation and `config-unavailable` naming file, line, column and fault (`crates/baley-core/src/policy/parse.rs` (`Unavailable` and `describe`), `crates/baley-core/src/policy/parse.rs` (`parse_layer`, `document` and `line_and_column`)), and a file that is not a regular file or cannot be read, including a dangling link named as a link to a missing file (`crates/baley/src/settings.rs` (`judge`)). The same reader serves the global `config.toml`: a link there to a missing file gives `config-unavailable` to every command that reads it. The guard treats it as torn settings and asks, subject to its remembered denials (`crates/baley/src/guard_hook/policy.rs` (`settings`), `crates/baley-core/src/guard/answer.rs` (`torn_commit`)). The policy step's read gathers the global file and HEAD's copy of the project file and builds the policy from them, refusing with the first fault (`crates/baley/src/policy_step/read.rs` (`gather` and `build`)). The guard's bounded reader of HEAD's copy refuses as the policy step's reader does, with `config-unavailable` naming the working-tree file, and also when the guard's git time is spent before a launch, which then never starts (`crates/baley/src/committed.rs` (`read_for_guard`)). A parse, type or grammar fault in HEAD's copy is named as HEAD's copy of the file, since that copy carries the working-tree path (`crates/baley-core/src/policy/parse.rs` (`at_head`), `crates/baley-core/src/policy/config_command/show.rs` (`judge_show`)). A checkout or settings path that is not UTF-8 is refused with `config-unavailable` naming the path (`crates/baley-core/src/policy/recorded/event.rs` (`PathNotUtf8`), `crates/baley-core/src/policy/recorded/event.rs` (`recorded_policy`)). `baley init` runs the read and build before it writes a file or opens the ledger (`crates/baley/src/init.rs` (`prepare`), `crates/baley/src/init.rs` (`initialize`)), and `purge` runs them from a checkout of the project it names, refusing a managed checkout whose `baley.toml` yields no id (`crates/baley/src/ledger/commands.rs` (`purge_policy_version`, `purge_project` and `OUTSIDE`)). `config set` refuses `config-unavailable` before it writes or opens the ledger (`crates/baley/src/config_command/set.rs` (`working_tree_id`), `crates/baley/src/config_command/set.rs` (`prepare`)), and `config show` before it prints anything, opening no ledger at all (`crates/baley-core/src/policy/config_command/show.rs` (`judge_show`)). `config interview` refuses it before its first question, running `config set`'s check of the working-tree file's project id first and then the judge `config show` uses (`crates/baley/src/config_command/interview.rs` (`begin`)). `config interview` binds the selected layer, the confirmed target path and its own read digest, or absence, and `set::apply` checks the path and digest after preparation (`crates/baley/src/config_command/interview.rs` (`begin`), `crates/baley/src/config_command/interview.rs` (`execute`), `crates/baley/src/config_command/set.rs` (`attempt`)). The reviewer-list write is bound the same way to the global file's path and the digest read before the questions, and refuses `config-conflict` when the file changed since (`crates/baley/src/config_command/set.rs` (`replace_list` and `check_expected`)). Its pure judges refuse a project that disappeared before pair validation and a changed path or digest after preparation with `config-conflict`. A changed path names both files, and a changed digest says the shown file changed since it was shown. When discovery finds no project, the message says no project covers this folder any more and names the shown file. All three say to run the interview again (`crates/baley/src/config_command/set.rs` (`attempt`, `check_project_expected`, `changed_since_shown` and `check_expected`)). `config-conflict` also comes from the replace's decision, which refuses a file that is not the one read (`crates/baley/src/replace.rs` (`decide`)), and from its whole-file replace, which writes through a temporary file and refuses a link (`crates/baley/src/replace.rs` (`replace`), `crates/baley/src/replace.rs` (`on_disk`)). `config set` also refuses a link before it reads the catalog, so a set that changes nothing refuses on one (`crates/baley/src/config_command/set.rs` (`refuse_link`)). `anchor`, `acknowledge-restore` and anchored `verify` refuse `config-unavailable` before any record, and refuse a managed checkout whose `baley.toml` yields no id the same way (`crates/baley/src/ledger/command_plan.rs` (`discovered`), `crates/baley/src/ledger/command_plan.rs` (`next`), `crates/baley/src/ledger/commands.rs` (`gather_settings`)). `verify --local-only` and `verify --views` read no settings (`crates/baley/src/ledger/command_plan.rs` (`next`)). `doctor` reports such a fault as a finding, leaves the discovered project checked locally and keeps checking every other project (`crates/baley/src/ledger/command_plan.rs` (`doctor_settings`), `crates/baley/src/ledger/anchor_plan.rs` (`doctor_checks`), `crates/baley/src/ledger/display.rs` (`doctor`)). The server's write preparation reads and validates both files after its replay lookup and the write's own check, and before checkout admission, and answers `failed` with `config-unavailable` and nothing recorded when either fails (`crates/baley/src/mcp/prepare.rs` (`judge_settings` and `write_next`)). A plain read validates neither file (`crates/baley/src/mcp/prepare.rs` (`next`)), and a request the ledger already holds is answered before the settings are read. `capture` reaches this for a request the ledger does not yet hold (`crates/baley/src/mcp/capture.rs` (`serve`)), `scope-submit`, `project-start`, `work-order-fail`, `work-order-retry` and `questions-answer` do once their checks pass (`crates/baley/src/mcp/scope.rs` (`prepared`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail` and `serve_retry`), `crates/baley/src/mcp/questions.rs` (`serve`)), and `document` never does. The `route` query reads and validates both files after the known-project check, as a write does, and answers `failed` with `config-unavailable` and nothing recorded when either fails (`crates/baley/src/mcp/prepare.rs` (`next` and `prepare_settings_read`)). `baley scope approve` reads and builds the policy after its approval's first step and before checkout admission, and refuses `config-unavailable` with nothing recorded (`crates/baley/src/scope/command.rs` (`approve`, `admitted`)). `baley questions answer` does the same after its check against the set (`crates/baley/src/questions/command.rs` (`record_answers`)). The guard hook reads the global and working-tree files capped at 1 MiB (`crates/baley/src/settings.rs` (`GUARD_LIMIT`, `read_for_guard`, `gather_for_guard` and `judge_for_guard`)), and takes a file it cannot read, one over the cap or an invalid one as torn settings, which it answers rather than refusing ([0010](0010-guard.md), GRD-R7), with no checkout admitted and nothing recorded in the project (`crates/baley/src/guard_hook/policy.rs` (`settings`)). The parked engine re-reads and validates its JSON layers before each write (`crates/baley/src/config/reload.rs` (`validate_effective`), `crates/baley/src/session/mod.rs` (`config` and `request`)) until Build 9. | +| CFG-R7 | Partly built | An unknown name is ignored with a diagnostic (`crates/baley-core/src/policy/parse.rs` (`table`), `crates/baley-core/src/policy/parse.rs` (`unknown`)); the twelve settings without readers are gone from `crates/baley/src/config/schema.json`; the command-line refusal `unknown-setting` is built for `config set` and `config show` (`crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`), `crates/baley-core/src/policy/config_command/show.rs` (`judge_show`)). `review.reviewers` entered the schema with its first reader, the interview's (`crates/baley/src/config_command/reviewers.rs` (`written` and `stored`)), and `config set` refuses it as a list (`crates/baley-core/src/policy/config_command/set.rs` (`judge_pairs`)). `owner.name` entered the schema with its reader, the owner reader that the provider acknowledgement and `baley scope approve` call (`crates/baley-core/src/policy/schema.rs` (`standard`), `crates/baley/src/providers/identity.rs` (`owner` and `owner_name`)). `planning.phase_capacity` and `workflow.test_command` entered the schema with their first readers: the planning facts and the planner order's inputs read the capacity, and `baley plan approve` reads both (`crates/baley/src/planning/facts.rs` (`capacity`), `crates/baley/src/planning/inputs.rs` (`capacity`), `crates/baley/src/planning/approve.rs` (`suite`)). The inherited JSON schema, which only the parked engine's merge and writer read, stays until Build 9. | +| CFG-R8 | Partly built | The `policy.effective` event, registered at version 1, and its payload built from the merged policy (`crates/baley-core/src/policy/recorded/event.rs` (`POLICY_EFFECTIVE`, `POLICY_EFFECTIVE_VERSION` and `register_policy_events`), `crates/baley-core/src/policy/recorded/event.rs` (`recorded_policy` and `effective_payload`)); the `policy` view and `PolicyProjector`, which keep the latest record per checkout and host (`crates/baley-core/src/policy/recorded/view.rs` (`policy_spec` and `PolicyProjector`)); and the judge of whether to record (`crates/baley-core/src/policy/recorded/judge.rs` (`COMPARED`, `PolicyJudgement` and `judge_policy`)). The binary's policy step holds the recorder, which appends `policy.effective` as Baley's own `policy.record` command only when the judge finds a change (`crates/baley/src/policy_step/record.rs` (`record` and `record_once`)), and the entry point, which reads the catalog version and returns the version in force (`crates/baley/src/policy_step/mod.rs` (`step` and `observe_catalog_version`)). The command line's store registers `policy.effective`, `checkout.seen`, `capture.recorded`, `guard.answered`, `guard.policy_recorded`, `install.recorded`, `update.checked`, `update.failed`, `providers.acknowledged`, the eleven scope types, `work_order.issued` and `work_order.failed`, the four question types `questions.opened`, `question.answered`, `question.deferred` and `questions.abandoned`, `story.refined`, and the four plan types `plan.approved`, `plan.replaced`, `plan.continuation` and `plan.continuation_followed`, and the `model_catalog`, `policy`, `checkout`, `capture`, `guard`, `guard_policy`, `install`, `draft`, `roadmap`, `phase`, `phase_detail`, `backlog`, `work_order`, `questions`, `truths`, `phase_plan`, `plan` and `evidence_map` views, at view set version 14. No view holds `providers.acknowledged` (`crates/baley/src/ledger/open.rs` (`options`)). `baley init` runs the step after `project.initialized` and checkout admission, in the order its plan gives (`crates/baley/src/init.rs` (`plan`), `crates/baley/src/init.rs` (`initialize`)). `purge` runs it only from a checkout of the project it names and records the version in force, otherwise 0 (`crates/baley-core/src/policy/recorded/purge.rs` (`purge_policy`), `crates/baley/src/ledger/commands.rs` (`purge`), `crates/baley/src/ledger/commands.rs` (`purge_policy_version`)). `config set` runs it after its write, in a project in this machine's ledger, and reports the version it returns (`crates/baley/src/config_command/set.rs` (`attempt`), `crates/baley/src/config_command/set.rs` (`record_policy` and `record_version`)). A set outside a project or in a project the ledger does not hold runs no step and reports 0, and one that changes nothing reports the version in force (`crates/baley-core/src/policy/config_command/outcome.rs` (`choose_outcome`)). `anchor` and `acknowledge-restore` run checkout admission and then the step after the settings read and the exact-name check of `git.remote`, and before their own command, which carries the version the step returns (`crates/baley/src/ledger/command_plan.rs` (`next`), `crates/baley/src/ledger/commands.rs` (`settle`), `crates/baley/src/ledger/commands.rs` (`anchor` and `acknowledge_request`), `crates/baley/src/ledger/commands.rs` (`acknowledge`)). Anchored `verify` and `doctor` run no step and append nothing. Every caller runs checkout admission between the settings read and the step. The core judges the checkout against the project's other checkouts, refusing a different remote URL as `project-id-conflict`, and plans `checkout.seen` before the step and the step before the command (`crates/baley-core/src/checkout/judge.rs` (`judge_checkout`), `crates/baley-core/src/checkout/plan.rs` (`plan_checkout_admission`)). The store step records `checkout.seen` as Baley's own `checkout.admit` command, or refuses a fork and records nothing, in one transaction (`crates/baley/src/checkout/admit.rs` (`admit` and `admit_once`)), after the facts are gathered through git (`crates/baley/src/checkout/gather.rs` (`root_commit`), `crates/baley/src/checkout/gather.rs` (`gather` and `remote_url`)) and stripped of user information (`crates/baley/src/checkout/strip.rs` (`strip_user_information`)). `purge`, `config set`, `anchor` and `acknowledge-restore` call it through one entry (`crates/baley/src/checkout/mod.rs` (`gather_and_admit`)), as does the server's write preparation, each right before its step: `purge` (`crates/baley/src/ledger/commands.rs` (`purge_policy_version`)), `config set` (`crates/baley/src/config_command/set.rs` (`attempt` and `admit_checkout`)), `anchor` (`crates/baley/src/ledger/commands.rs` (`anchor`)) and `acknowledge-restore` (`crates/baley/src/ledger/commands.rs` (`acknowledge`)). `baley scope approve` runs checkout admission and then the step after its approval's first step, which reads and judges and records nothing, and before the approval, which carries the version the step returns (`crates/baley/src/scope/command.rs` (`approve`, `admitted`)). For a phase's commitment, whose approval issues the planner order, the step records Claude Code's effective policy rather than the policy with no host, so the order's route names a recorded version (`crates/baley/src/scope/command.rs` (`host_admitted`)). `baley plan approve` reads and builds the policy before its first step, which judges the plan under the capacity that policy sets, then runs checkout admission and the step, judges the plan again when the policy the step recorded sets another capacity or suite, and records the approval under the version the step returns (`crates/baley/src/planning/command.rs` (`approve`), `crates/baley/src/planning/approve.rs` (`judge` and `rejudged`)). `baley questions answer` runs them the same way after its check against the set, which records nothing, and before the answers and deferrals, which carry the version the step returns (`crates/baley/src/questions/command.rs` (`record_answers`)), and so does `baley story truths approve` after its approval's first step and before `story.refined` (`crates/baley/src/refine/command.rs` (`approve`)). `baley init` gathers before it opens the ledger and admits as a step of its plan (`crates/baley/src/init.rs` (`initialize`), `crates/baley/src/init.rs` (`initialize`)). The server's write preparation runs checkout admission and then the step for the call's host, as Baley's own commands carrying the call's caller and the server's time, and the prepared command carries the version the step returned (`crates/baley/src/mcp/prepare.rs` (`write_next` and `perform`), `crates/baley/src/policy_step/mod.rs` (`step` and `observe_catalog_version`)). The step records under the host's key, while checkout admission is keyed by the policy that names no host and so carries the version stored for the checkout and no host (`crates/baley/src/mcp/prepare.rs` (`WritePolicies` and `judge_settings`)). A read and a request the ledger already holds run neither, and neither runs when a write's own check ends the call (`crates/baley/src/mcp/prepare.rs` (`next` and `write_next`)). `capture` reaches this for a request the ledger does not yet hold (`crates/baley/src/mcp/capture.rs` (`serve`)), `scope-submit`, `project-start`, `work-order-fail`, `work-order-retry`, `questions-answer`, `story-refine`, `story-questions-submit`, `context-submit`, `phase-plan`, `plan-submit` and `plan-replace` do once their checks pass (`crates/baley/src/mcp/scope.rs` (`prepared`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail` and `serve_retry`), `crates/baley/src/mcp/questions.rs` (`serve`), `crates/baley/src/mcp/refine.rs` (`serve`, `serve_questions` and `serve_context`), `crates/baley/src/mcp/planning.rs` (`serve` and `serve_submit`)), `document`, `context-intake`, `plan-read` and the `route` query never do (`crates/baley/src/mcp/prepare.rs` (`prepare_settings_read`), `crates/baley/src/mcp/refine.rs` (`serve_intake`), `crates/baley/src/mcp/planning.rs` (`serve_read`)), and the guard never runs it: it builds a commit's policy with the step's `build` and records no `policy.effective` (`crates/baley/src/guard_hook/policy.rs` (`settings`)). The parked engine's routes persist its config inputs only (`crates/baley/src/config/reload.rs` (`routing_inputs`)) until Build 9. | +| CFG-R9 | Partly built | Validation and `config-unavailable` naming file, line, column and fault (`crates/baley-core/src/policy/parse.rs` (`Unavailable` and `describe`), `crates/baley-core/src/policy/parse.rs` (`parse_layer`, `document` and `line_and_column`)), and a file that is not a regular file or cannot be read, including a dangling link named as a link to a missing file (`crates/baley/src/settings.rs` (`judge`)). The same reader serves the global `config.toml`: a link there to a missing file gives `config-unavailable` to every command that reads it. The guard treats it as torn settings and asks, subject to its remembered denials (`crates/baley/src/guard_hook/policy.rs` (`settings`), `crates/baley-core/src/guard/answer.rs` (`torn_commit`)). The policy step's read gathers the global file and HEAD's copy of the project file and builds the policy from them, refusing with the first fault (`crates/baley/src/policy_step/read.rs` (`gather` and `build`)). The guard's bounded reader of HEAD's copy refuses as the policy step's reader does, with `config-unavailable` naming the working-tree file, and also when the guard's git time is spent before a launch, which then never starts (`crates/baley/src/committed.rs` (`read_for_guard`)). A parse, type or grammar fault in HEAD's copy is named as HEAD's copy of the file, since that copy carries the working-tree path (`crates/baley-core/src/policy/parse.rs` (`at_head`), `crates/baley-core/src/policy/config_command/show.rs` (`judge_show`)). A checkout or settings path that is not UTF-8 is refused with `config-unavailable` naming the path (`crates/baley-core/src/policy/recorded/event.rs` (`PathNotUtf8`), `crates/baley-core/src/policy/recorded/event.rs` (`recorded_policy`)). `baley init` runs the read and build before it writes a file or opens the ledger (`crates/baley/src/init.rs` (`prepare`), `crates/baley/src/init.rs` (`initialize`)), and `purge` runs them from a checkout of the project it names, refusing a managed checkout whose `baley.toml` yields no id (`crates/baley/src/ledger/commands.rs` (`purge_policy_version`, `purge_project` and `OUTSIDE`)). `config set` refuses `config-unavailable` before it writes or opens the ledger (`crates/baley/src/config_command/set.rs` (`working_tree_id`), `crates/baley/src/config_command/set.rs` (`prepare`)), and `config show` before it prints anything, opening no ledger at all (`crates/baley-core/src/policy/config_command/show.rs` (`judge_show`)). `config interview` refuses it before its first question, running `config set`'s check of the working-tree file's project id first and then the judge `config show` uses (`crates/baley/src/config_command/interview.rs` (`begin`)). `config interview` binds the selected layer, the confirmed target path and its own read digest, or absence, and `set::apply` checks the path and digest after preparation (`crates/baley/src/config_command/interview.rs` (`begin`), `crates/baley/src/config_command/interview.rs` (`execute`), `crates/baley/src/config_command/set.rs` (`attempt`)). The reviewer-list write is bound the same way to the global file's path and the digest read before the questions, and refuses `config-conflict` when the file changed since (`crates/baley/src/config_command/set.rs` (`replace_list` and `check_expected`)). Its pure judges refuse a project that disappeared before pair validation and a changed path or digest after preparation with `config-conflict`. A changed path names both files, and a changed digest says the shown file changed since it was shown. When discovery finds no project, the message says no project covers this folder any more and names the shown file. All three say to run the interview again (`crates/baley/src/config_command/set.rs` (`attempt`, `check_project_expected`, `changed_since_shown` and `check_expected`)). `config-conflict` also comes from the replace's decision, which refuses a file that is not the one read (`crates/baley/src/replace.rs` (`decide`)), and from its whole-file replace, which writes through a temporary file and refuses a link (`crates/baley/src/replace.rs` (`replace`), `crates/baley/src/replace.rs` (`on_disk`)). `config set` also refuses a link before it reads the catalog, so a set that changes nothing refuses on one (`crates/baley/src/config_command/set.rs` (`refuse_link`)). `anchor`, `acknowledge-restore` and anchored `verify` refuse `config-unavailable` before any record, and refuse a managed checkout whose `baley.toml` yields no id the same way (`crates/baley/src/ledger/command_plan.rs` (`discovered`), `crates/baley/src/ledger/command_plan.rs` (`next`), `crates/baley/src/ledger/commands.rs` (`gather_settings`)). `verify --local-only` and `verify --views` read no settings (`crates/baley/src/ledger/command_plan.rs` (`next`)). `doctor` reports such a fault as a finding, leaves the discovered project checked locally and keeps checking every other project (`crates/baley/src/ledger/command_plan.rs` (`doctor_settings`), `crates/baley/src/ledger/anchor_plan.rs` (`doctor_checks`), `crates/baley/src/ledger/display.rs` (`doctor`)). The server's write preparation reads and validates both files after its replay lookup and the write's own check, and before checkout admission, and answers `failed` with `config-unavailable` and nothing recorded when either fails (`crates/baley/src/mcp/prepare.rs` (`judge_settings` and `write_next`)). A plain read validates neither file (`crates/baley/src/mcp/prepare.rs` (`next`)), and a request the ledger already holds is answered before the settings are read. `capture` reaches this for a request the ledger does not yet hold (`crates/baley/src/mcp/capture.rs` (`serve`)), `scope-submit`, `project-start`, `work-order-fail`, `work-order-retry`, `questions-answer`, `story-refine`, `story-questions-submit`, `context-submit`, `phase-plan`, `plan-submit` and `plan-replace` do once their checks pass (`crates/baley/src/mcp/scope.rs` (`prepared`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail` and `serve_retry`), `crates/baley/src/mcp/questions.rs` (`serve`), `crates/baley/src/mcp/refine.rs` (`serve`, `serve_questions` and `serve_context`), `crates/baley/src/mcp/planning.rs` (`serve` and `serve_submit`)), and `document`, `context-intake` and `plan-read` never do. `plan-submit` and `plan-replace` also read and validate both files before preparation, recording nothing, for the capacity their check judges the plan against, and answer a fault from that read only when the check runs, after the replay lookup (`crates/baley/src/mcp/planning.rs` (`submit_through` and `capacity`)). The `route` query reads and validates both files after the known-project check, as a write does, and answers `failed` with `config-unavailable` and nothing recorded when either fails (`crates/baley/src/mcp/prepare.rs` (`next` and `prepare_settings_read`)). `baley scope approve` reads and builds the policy after its approval's first step and before checkout admission, and refuses `config-unavailable` with nothing recorded (`crates/baley/src/scope/command.rs` (`approve`, `admitted`)). `baley plan approve` reads and builds it before its first step, since that step judges the plan under the capacity it sets, and refuses `config-unavailable` the same way (`crates/baley/src/planning/command.rs` (`approve`)). `baley questions answer` does the same after its check against the set (`crates/baley/src/questions/command.rs` (`record_answers`)). The guard hook reads the global and working-tree files capped at 1 MiB (`crates/baley/src/settings.rs` (`GUARD_LIMIT`, `read_for_guard`, `gather_for_guard` and `judge_for_guard`)), and takes a file it cannot read, one over the cap or an invalid one as torn settings, which it answers rather than refusing ([0010](0010-guard.md), GRD-R7), with no checkout admitted and nothing recorded in the project (`crates/baley/src/guard_hook/policy.rs` (`settings`)). The parked engine re-reads and validates its JSON layers before each write (`crates/baley/src/config/reload.rs` (`validate_effective`), `crates/baley/src/session/mod.rs` (`config` and `request`)) until Build 9. | | CFG-R10 | Not built | Only the parked admission compares the routing inputs (`crates/baley/src/config/reload.rs` (`refresh_expected`), `crates/baley/src/execution/boundary.rs` (`Failure`)). The session server answers `execution-admit` as unavailable (`crates/baley/src/mcp/operations.rs` (`APPLY_OPERATIONS`)) until Build 5 | -| CFG-R11 | Partly built | `baley config interview` binds its settings write to the shown target's path and own digest, or absence, through `set::apply` (`crates/baley/src/config_command/set.rs` (`set`, `Expected`, `apply` and `attempt`)). `baley config set` writes either settings file whole (`crates/baley/src/config_command/set.rs` (`write_file`)). `baley config interview` writes only after the owner types `yes` (`crates/baley/src/config_command/interview.rs` (`accepts` and `confirm`)): the settings through `set::apply`, the global `review.reviewers` list through `set::apply_list`, which renders the whole global file from its own bytes (`crates/baley/src/config_command/set.rs` (`apply_list` and `replace_list`)), and the chosen providers' API hosts into Claude Code's settings file through the settings part of the installation writer (`crates/baley/src/install/hosts.rs` (`write`)), each as one step of the run (`crates/baley/src/config_command/interview.rs` (`execute`)). It also records the acknowledgement in the per-user ledger (`crates/baley/src/config_command/interview.rs` (`acknowledge`)). `baley init` writes the project file when none exists (`crates/baley/src/init.rs` (`write_project_file`)) and rewrites it whole under `--new-id` (`crates/baley/src/init.rs` (`initialize`)); the guard hook denies an agent's `Write`, `Edit` or `NotebookEdit` into the config folder, which holds `config.toml` and any `keys.env` an older build left there, into the home folder, and to the session project's `baley.toml` and the one of the checkout the hook's working directory is in, from any working directory and with or without a project (`crates/baley/src/protected_paths/write.rs` (`write_answer` and `protected_by`), `crates/baley/src/guard_hook/context.rs` (`gather`, `walk` and `judge`), `crates/baley/src/guard_hook/decide.rs` (`path`)). The placement projection that adds the placed stubs, the placed Claude Code settings and registration files and the installed executable to that list is built. It supplies `~/.local/lib/crenshawdev/baley/versions` separately as a write-only folder when placed, protecting its contents without denying reads (`crates/baley/src/host_artifacts/placement.rs` (`protected_paths` and `write_only_folders`)). The live guard derives the placements from `HOME` and `CLAUDE_CONFIG_DIR` at each call and passes them to its judge, so its protected list holds each placed stub, the placed Claude Code settings and registration files and the installed executable, and its write-only folder list holds the versions folder (`crates/baley/src/guard_hook/context.rs` (`judge`), `crates/baley/src/host_artifacts/installed.rs` (`resolve`, `stub_path` and `skill_and_agent`)). The doctor builds its map from the same derivation and the latest install record, so it places only what the record shows (`crates/baley/src/host_doctor/mod.rs` (`installed_placements`)). The sandbox and `Edit` deny-rule content that keeps agents out of the config folder and off the supplied project files is rendered by the proposal (`crates/baley/src/host_artifacts/security.rs` (`propose`)), including a folder-shaped write denial with no read rule for a supplied versions folder, and `baley install` merges it into the user settings file, with the other owner settings kept (`crates/baley/src/install/settings.rs` (`judge`)). The doctor reports the config folder and notes when it is the home folder, as `BALEY_HOME` and macOS make it (`crates/baley/src/host_doctor/store_health.rs` (`judge`), `crates/baley/src/host_doctor/report.rs` (`store_lines`)). It judges the project file and the placed settings files as write-only files of the coverage judge over the settings and hook documents it is given, worded as configuration and not as proof (`crates/baley/src/host_doctor/protection.rs` (`judge`)). It gives the config folder no mode, owner or link judgement and never opens `keys.env`. The session server answers `config-apply` and `config-interview-apply` as unavailable and names Build 2, whose `baley config` commands replace them (`crates/baley/src/mcp/operations.rs` (`APPLY_OPERATIONS`)). The server's preparation writes no settings file and creates no project: it answers an unknown project `failed` and names `baley init` as the owner's step (`crates/baley/src/mcp/prepare.rs` (`next`)), and it calls no `init`, project creation or catalog seeding (`crates/baley/src/mcp/prepare.rs` (`prepare`, `prepare_checked`, `drive` and `perform`)). `capture`, `scope-submit`, `project-start`, `work-order-fail`, `work-order-retry`, `questions-answer`, `document` and the `route` query all reach it (`crates/baley/src/mcp/capture.rs` (`serve`), `crates/baley/src/mcp/scope.rs` (`prepared`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail`, `serve_retry` and `serve_route`), `crates/baley/src/mcp/questions.rs` (`serve`), `crates/baley/src/mcp/document.rs` (`serve`)). A project start whose settings are missing names `baley config interview` in its answer and runs nothing (`crates/baley/src/mcp/work_order.rs` (`settings_lines`)) | +| CFG-R11 | Partly built | `baley config interview` binds its settings write to the shown target's path and own digest, or absence, through `set::apply` (`crates/baley/src/config_command/set.rs` (`set`, `Expected`, `apply` and `attempt`)). `baley config set` writes either settings file whole (`crates/baley/src/config_command/set.rs` (`write_file`)). `baley config interview` writes only after the owner types `yes` (`crates/baley/src/config_command/interview.rs` (`accepts` and `confirm`)): the settings through `set::apply`, the global `review.reviewers` list through `set::apply_list`, which renders the whole global file from its own bytes (`crates/baley/src/config_command/set.rs` (`apply_list` and `replace_list`)), and the chosen providers' API hosts into Claude Code's settings file through the settings part of the installation writer (`crates/baley/src/install/hosts.rs` (`write`)), each as one step of the run (`crates/baley/src/config_command/interview.rs` (`execute`)). It also records the acknowledgement in the per-user ledger (`crates/baley/src/config_command/interview.rs` (`acknowledge`)). `baley init` writes the project file when none exists (`crates/baley/src/init.rs` (`write_project_file`)) and rewrites it whole under `--new-id` (`crates/baley/src/init.rs` (`initialize`)); the guard hook denies an agent's `Write`, `Edit` or `NotebookEdit` into the config folder, which holds `config.toml` and any `keys.env` an older build left there, into the home folder, and to the session project's `baley.toml` and the one of the checkout the hook's working directory is in, from any working directory and with or without a project (`crates/baley/src/protected_paths/write.rs` (`write_answer` and `protected_by`), `crates/baley/src/guard_hook/context.rs` (`gather`, `walk` and `judge`), `crates/baley/src/guard_hook/decide.rs` (`path`)). The placement projection that adds the placed stubs, the placed Claude Code settings and registration files and the installed executable to that list is built. It supplies `~/.local/lib/crenshawdev/baley/versions` separately as a write-only folder when placed, protecting its contents without denying reads (`crates/baley/src/host_artifacts/placement.rs` (`protected_paths` and `write_only_folders`)). The live guard derives the placements from `HOME` and `CLAUDE_CONFIG_DIR` at each call and passes them to its judge, so its protected list holds each placed stub, the placed Claude Code settings and registration files and the installed executable, and its write-only folder list holds the versions folder (`crates/baley/src/guard_hook/context.rs` (`judge`), `crates/baley/src/host_artifacts/installed.rs` (`resolve`, `stub_path` and `skill_and_agent`)). The doctor builds its map from the same derivation and the latest install record, so it places only what the record shows (`crates/baley/src/host_doctor/mod.rs` (`installed_placements`)). The sandbox and `Edit` deny-rule content that keeps agents out of the config folder and off the supplied project files is rendered by the proposal (`crates/baley/src/host_artifacts/security.rs` (`propose`)), including a folder-shaped write denial with no read rule for a supplied versions folder, and `baley install` merges it into the user settings file, with the other owner settings kept (`crates/baley/src/install/settings.rs` (`judge`)). The doctor reports the config folder and notes when it is the home folder, as `BALEY_HOME` and macOS make it (`crates/baley/src/host_doctor/store_health.rs` (`judge`), `crates/baley/src/host_doctor/report.rs` (`store_lines`)). It judges the project file and the placed settings files as write-only files of the coverage judge over the settings and hook documents it is given, worded as configuration and not as proof (`crates/baley/src/host_doctor/protection.rs` (`judge`)). It gives the config folder no mode, owner or link judgement and never opens `keys.env`. The session server answers `config-apply` and `config-interview-apply` as unavailable and names Build 2, whose `baley config` commands replace them (`crates/baley/src/mcp/operations.rs` (`APPLY_OPERATIONS`)). The server's preparation writes no settings file and creates no project: it answers an unknown project `failed` and names `baley init` as the owner's step (`crates/baley/src/mcp/prepare.rs` (`next`)), and it calls no `init`, project creation or catalog seeding (`crates/baley/src/mcp/prepare.rs` (`prepare`, `prepare_checked`, `drive` and `perform`)). `capture`, `scope-submit`, `project-start`, `work-order-fail`, `work-order-retry`, `questions-answer`, `story-refine`, `story-questions-submit`, `context-intake`, `context-submit`, `phase-plan`, `plan-submit`, `plan-replace`, `plan-read`, `document` and the `route` query all reach it (`crates/baley/src/mcp/capture.rs` (`serve`), `crates/baley/src/mcp/scope.rs` (`prepared`), `crates/baley/src/mcp/work_order.rs` (`serve_start`, `serve_fail`, `serve_retry` and `serve_route`), `crates/baley/src/mcp/questions.rs` (`serve`), `crates/baley/src/mcp/refine.rs` (`serve`, `serve_questions`, `serve_intake` and `serve_context`), `crates/baley/src/mcp/planning.rs` (`serve`, `serve_submit` and `serve_read`), `crates/baley/src/mcp/document.rs` (`serve`)). A project start whose settings are missing names `baley config interview` in its answer and runs nothing (`crates/baley/src/mcp/work_order.rs` (`settings_lines`)) | | CFG-R12, CFG-R13 | Built | In the policy module: the six roles and their defaults (`crates/baley-core/src/policy/schema.rs` (`Role` and `standard`)), and an absent model passed as none (`crates/baley-core/src/policy/route.rs` (`resolve_route`)). The route record then carries a null `model`, with `no-model` as the first reason its effective values are unknown (`crates/baley-core/src/work_order/route.rs` (`route_record`)), and an order's launch sentence tells the session to pass no model parameter, so the agent stub's `model: inherit` applies (`crates/baley/src/work_order/issue.rs` (`launch`)). The parked engine's `crates/baley/src/config/roles.rs` (`ROLES`) keeps its `bal-*` roles until Build 9, and nothing in production reaches it. | -| CFG-R14 | Partly built | Resolution refuses `unknown-model` against the supplied accepted names (`crates/baley-core/src/policy/route.rs` (`resolve_route`)). The catalog lookup gives each host's and provider's accepted names with the catalog version (`crates/baley-core/src/catalog/lookup.rs` (`accepted_names`)). The composer reads the host's accepted names for resolution: the host's catalog document and the state document of `user` in one snapshot, or the aliases alone at version 0 when `user` is absent or answers read-only, and it never seeds (`crates/baley/src/work_order/route.rs` (`host_names` and `names`)). `project-start`, the analyzer's orders from `story-refine`, `story-questions-submit` and a closing `questions-answer`, `work-order-retry` and the `route` query resolve through it and answer the refusal `refused` (`crates/baley/src/work_order/route.rs` (`compose`), `crates/baley/src/mcp/work_order.rs` (`issue_start_order`, `serve_start`, `issue_retry` and `route_answer`), `crates/baley/src/refine/order.rs` (`prepare` and `prepare_drafting`)). On each of them but the `route` query the route is composed after preparation's checkout admission and policy step, each its own transaction (`crates/baley/src/mcp/work_order.rs` (`serve_start` and `serve_retry`), `crates/baley/src/mcp/prepare.rs` (its module comment)), so the refusal records no work order, while a `checkout.seen` the checkout admission recorded or a `policy.effective` the policy step recorded stays. The `route` query records nothing. The write-time check is built for `config set`: `judge_models` checks each model name against the accepted names of the host `--host` names, or of at least one host with none, and never against a provider's catalog (`crates/baley-core/src/policy/config_command/set.rs` (`judge_models`)). The names are read from the `model_catalog` view after the seeding step, which runs only when a pair sets a model. Inside a project the store opens for every set, to learn whether this machine's ledger holds the project, and outside one only when a pair sets a model (`crates/baley/src/config_command/set.rs` (`attempt`), `crates/baley/src/config_command/set.rs` (`accepted_by_host`)). `config interview` checks no name while it asks: a model answer is any non-empty text, taken as typed and never asked again (`crates/baley/src/config_command/interview.rs` (`Takes`), `crates/baley/src/config_command/interview.rs` (`judge_answer`)). The answer reaches `judge_models` through the interview's call to `set::apply`, which refuses `unknown-model` there (`crates/baley/src/config_command/interview.rs` (`execute`)), and the catalog is seeded only after the owner accepts with a model answer. The parked engine's role resolution (`crates/baley/src/config/roles.rs` (`resolve`)) still drops unsupported names. | +| CFG-R14 | Partly built | Resolution refuses `unknown-model` against the supplied accepted names (`crates/baley-core/src/policy/route.rs` (`resolve_route`)). The catalog lookup gives each host's and provider's accepted names with the catalog version (`crates/baley-core/src/catalog/lookup.rs` (`accepted_names`)). The composer reads the host's accepted names for resolution: the host's catalog document and the state document of `user` in one snapshot, or the aliases alone at version 0 when `user` is absent or answers read-only, and it never seeds (`crates/baley/src/work_order/route.rs` (`host_names` and `names`)). `project-start`, the analyzer's orders from `story-refine`, `story-questions-submit` and a closing `questions-answer`, the phase planner's orders from `phase-plan`, a closing `questions-answer` of a plan draft's set and `baley scope approve` of a phase's commitment, `work-order-retry` and the `route` query resolve through it and answer the refusal `refused` (`crates/baley/src/work_order/route.rs` (`compose`), `crates/baley/src/mcp/work_order.rs` (`issue_start_order`, `serve_start`, `issue_retry` and `route_answer`), `crates/baley/src/refine/order.rs` (`prepare` and `prepare_drafting`), `crates/baley/src/planning/order.rs` (`prepare`, `prepare_revision` and `route`)). `baley scope approve` composes the planner's route for Claude Code, the only host, after its own checkout admission and policy step, and the refusal approves nothing (`crates/baley/src/scope/command.rs` (`approve`)). On each of them but the `route` query the route is composed after preparation's checkout admission and policy step, each its own transaction (`crates/baley/src/mcp/work_order.rs` (`serve_start` and `serve_retry`), `crates/baley/src/mcp/prepare.rs` (its module comment)), so the refusal records no work order, while a `checkout.seen` the checkout admission recorded or a `policy.effective` the policy step recorded stays. The `route` query records nothing. The write-time check is built for `config set`: `judge_models` checks each model name against the accepted names of the host `--host` names, or of at least one host with none, and never against a provider's catalog (`crates/baley-core/src/policy/config_command/set.rs` (`judge_models`)). The names are read from the `model_catalog` view after the seeding step, which runs only when a pair sets a model. Inside a project the store opens for every set, to learn whether this machine's ledger holds the project, and outside one only when a pair sets a model (`crates/baley/src/config_command/set.rs` (`attempt`), `crates/baley/src/config_command/set.rs` (`accepted_by_host`)). `config interview` checks no name while it asks: a model answer is any non-empty text, taken as typed and never asked again (`crates/baley/src/config_command/interview.rs` (`Takes`), `crates/baley/src/config_command/interview.rs` (`judge_answer`)). The answer reaches `judge_models` through the interview's call to `set::apply`, which refuses `unknown-model` there (`crates/baley/src/config_command/interview.rs` (`execute`)), and the catalog is seeded only after the owner accepts with a model answer. The parked engine's role resolution (`crates/baley/src/config/roles.rs` (`resolve`)) still drops unsupported names. | | CFG-R15 | Built | Claude Code's rung map is the identity, each rung the Claude Code effort of the same name (`crates/baley-core/src/catalog/tables.rs` (`rung_map`)), and `resolve_route` carries the mapped value as `host_effort` (`crates/baley-core/src/policy/route.rs` (`RungMap`, `host_effort` and `resolve_route`)). The effort table holds thirteen rows keyed by exact concrete id, dated 2026-10-18 with its source address, and answers a level, `not-applicable` or `unknown` (`crates/baley-core/src/catalog/effort.rs` (`EFFORT_ROWS` and `supported_effort`)). The route record keeps the stored and sent rungs, the host effort, the table's supported level and the effective model and effort apart, the effective values always `unknown` with their reasons in `unknown_because` (`crates/baley-core/src/work_order/route.rs` (`route_record`)). The agent stub an order names is `bal-<role>-<rung>` for the rung sent (`crates/baley-core/src/work_order/event.rs` (`agent_name`)), and each stub's `effort` is that rung's name ([0012](0012-host-interface.md) section 10). Whether Claude Code runs a stub at its `effort`, and what a managed cap lowers it to, is observed by Build 4 T15's live run. The parked engine's resolution maps a rung to one of 30 agent names (`crates/baley/src/config/roles.rs` (`RUNGS`, `HOST_MODELS` and `AGENTS`)) until Build 9. | -| CFG-R16 | Built | The escalation rule in `resolve_route`: one rung up on any attempt after the first when `escalate_on_failure` is true, held at `max` (`crates/baley-core/src/policy/route.rs` (`resolve_route`)). The attempt comes from the ledger. The retry judge takes the failed order's recorded attempt and adds one, and refuses a retry of a pending or answered order, of one already retried, of one whose chain an earlier attempt's answer ended and of one whose input this project purged (`crates/baley-core/src/work_order/retry.rs` (`judge_retry`)). `work-order-retry` resolves the failed order's role again at that attempt under the current policy and catalog (`crates/baley/src/mcp/work_order.rs` (`issue_retry`)). A replay of its request id answers the recorded order with no second increment, since the request digest covers the order alone (`crates/baley/src/mcp/work_order.rs` (`judge_retry_arguments`)). A project start and an analyzer order a story's refinement issues are attempt 1 (`crates/baley/src/mcp/work_order.rs` (`issue_start_order`), `crates/baley/src/refine/order.rs` (`prepare`)). The parked engine's resolution (`crates/baley/src/config/roles.rs` (`resolve`)) is called with attempt `None` everywhere (#69) until Build 9. | -| CFG-R17 | Built | The route type carries every field `resolve_route` decides (`crates/baley-core/src/policy/route.rs` (`Route`)), and the route record adds the supported and effective fields of section 6 (`crates/baley-core/src/work_order/route.rs` (`route_record`)). `work_order.issued` carries the record under `route`, beside the order's `role`, `attempt` and `agent` (`crates/baley-core/src/work_order/event.rs` (`WORK_ORDER_ISSUED`, `WORK_ORDER_ISSUED_VERSION` and `issued_payload`)), and the issue's transaction records it, or the caller's own transaction for a drafting order issued beside a set or its answers (`crates/baley/src/work_order/issue.rs` (`record` and `issue_within`)). The `route` query serves the same record and records nothing (`crates/baley/src/mcp/work_order.rs` (`route_answer`)). The parked engine's resolution (`crates/baley/src/config/roles.rs` (`resolve`)) has no policy or catalog version. | +| CFG-R16 | Built | The escalation rule in `resolve_route`: one rung up on any attempt after the first when `escalate_on_failure` is true, held at `max` (`crates/baley-core/src/policy/route.rs` (`resolve_route`)). The attempt comes from the ledger. The retry judge takes the failed order's recorded attempt and adds one, and refuses a retry of a pending or answered order, of one already retried, of one whose chain an earlier attempt's answer ended and of one whose input this project purged (`crates/baley-core/src/work_order/retry.rs` (`judge_retry`)). `work-order-retry` resolves the failed order's role again at that attempt under the current policy and catalog (`crates/baley/src/mcp/work_order.rs` (`issue_retry`)). A replay of its request id answers the recorded order with no second increment, since the request digest covers the order alone (`crates/baley/src/mcp/work_order.rs` (`judge_retry_arguments`)). A project start, an analyzer order a story's refinement issues and a phase planner's planning or revision order are attempt 1, the planner's each the start of a new chain (`crates/baley/src/mcp/work_order.rs` (`issue_start_order`), `crates/baley/src/refine/order.rs` (`prepare`), `crates/baley/src/planning/order.rs` (`prepare` and `route`)). The parked engine's resolution (`crates/baley/src/config/roles.rs` (`resolve`)) is called with attempt `None` everywhere (#69) until Build 9. | +| CFG-R17 | Built | The route type carries every field `resolve_route` decides (`crates/baley-core/src/policy/route.rs` (`Route`)), and the route record adds the supported and effective fields of section 6 (`crates/baley-core/src/work_order/route.rs` (`route_record`)). `work_order.issued` carries the record under `route`, beside the order's `role`, `attempt` and `agent` (`crates/baley-core/src/work_order/event.rs` (`WORK_ORDER_ISSUED`, `WORK_ORDER_ISSUED_VERSION` and `issued_payload`)), and the issue's transaction records it, or the caller's own transaction for a drafting order issued beside a set or its answers, a planner revision order issued beside a plan set's answers, or a planner order issued beside a commitment's approval (`crates/baley/src/work_order/issue.rs` (`record` and `issue_within`), `crates/baley/src/planning/order.rs` (`issue_within`)). The `route` query serves the same record and records nothing (`crates/baley/src/mcp/work_order.rs` (`route_answer`)). The parked engine's resolution (`crates/baley/src/config/roles.rs` (`resolve`)) has no policy or catalog version. | | CFG-R18 | Not built | Only the parked engine raises the default plan gate to blocking when the risk floor applies (`crates/baley/src/config/policy.rs` (`with_floor`), `crates/baley/src/config/floor.rs` (`read_with`, `Recommendation` and `recommend`)). Route resolution takes no risk input (`crates/baley-core/src/policy/route.rs` (`RouteRequest`)), so no route built so far changes for risk. The plan-time risk floor itself is Build 4's | | CFG-R19 | Partly built | The catalog is the `model_catalog` view of the per-user project `user` (`crates/baley-core/src/catalog/mod.rs` (`USER_PROJECT`), `crates/baley-core/src/catalog/view.rs` (`ModelCatalogProjector` and `touched`)). `baley models list`, `add`, `remove` and `import` run the seeding step first (`crates/baley/src/models.rs` (`open_seeded`)). `baley init` runs the same step after its steps and its policy step on every run that passes its refusals, an "already initialized" run included, prints the seed line only when the step recorded, and never fails on a seed failure (`crates/baley/src/init.rs` (`initialize`), `crates/baley/src/init.rs` (`seed_step` and `seed_outcome_line`)). The step records the hint table when the seeding judge finds its version differs from the latest one recorded (`crates/baley/src/models.rs` (`seed`), `crates/baley-core/src/catalog/seed.rs` (`seed_due` and `seed_payload`)). The Claude Code alias table and the hint table with its version are compiled in (`crates/baley-core/src/catalog/tables.rs` (`host_aliases`, `rung_map`, `EXACT_HINTS` and `PREFIX_HINTS`)). After activation, the updater attempts claim completion before launching the new version's hidden `baley update seed`, which records its own compiled catalog without a provider call (`crates/baley/src/update/command.rs` (`claimed_check`), `crates/baley/src/update/seed.rs` (`launch_for`, `run` and `seed_compiled`)). `baley install` seeds the catalog in its own process through the same seeding step, after its file writes and before it records the install, and the updater's hidden `seed` child stays the updater's (`crates/baley/src/install/command.rs` (`install`)). Build 4 owns default tier selection and the versioned catalog record extension retaining provider `created` dates and hint order (section 6). The parked engine's fixed list (`crates/baley/src/config/roles.rs` (`HOST_MODELS`)) stays until Build 9. | | CFG-R20, CFG-R21 | Partly built | The pure parser, classifier, tagger, diff and event code in `crates/baley-core/src/catalog/detection/` is built and stays. `baley models update` prints one fetch command per covered provider, and only for a provider with a current acknowledgement (`crates/baley/src/models.rs` (`update` and `update_decision`), `crates/baley/src/detection/fetch.rs` (`fetch_command`)). `baley models import` reads stdin up to the 4 MiB body and its trailer (`crates/baley/src/models.rs` (`IMPORT_INPUT_BYTES` and `import`)), parses the trailer strictly, so a missing or damaged trailer or an oversized body is `incomplete` (`crates/baley/src/detection/trailer.rs` (`parse_fetched`)), seeds, and records `models.detected` or `models.detection_failed` as the owner under `models.import` in one transaction (`crates/baley/src/models.rs` (`record_import`), `crates/baley/src/detection/record.rs` (`record`)). A failed or cut list records its category and keeps the previous catalog (`crates/baley-core/src/catalog/detection/event.rs` (`choose_event`)), and the command reports it and exits 0 (`crates/baley/src/models.rs` (`import_lines` and `HEADER`)). `baley init` seeds the catalog with no list call (`crates/baley/src/init.rs` (`initialize`)), and the HTTPS lister is removed, so Baley sends no list request. Build 4 owns the session's fetch work order after a model error and `models-return`. | @@ -860,7 +862,7 @@ The binary parks the inherited engine for Build 9 to delete, and nothing in prod | CFG-R23 | Built | Every catalog event records the version before it, read in its own transaction: a seed and an owner change (`crates/baley/src/models.rs` (`record_seed`), `crates/baley/src/models.rs` (`change`)), and a detection (`crates/baley/src/detection/record.rs` (`record`)), which reports the version its own command committed (`crates/baley/src/detection/record.rs` (`record`)). A body cut short at the 4 MiB bound records `incomplete` with that version and removes nothing (`crates/baley-core/src/catalog/detection/classify.rs` (`classify`), `crates/baley-core/src/catalog/detection/event.rs` (`choose_event`)). The view keeps the version as the sequence of the latest event that changed an accepted name (`crates/baley-core/src/catalog/view.rs` (`apply`)). The lookup returns it beside the names, which is what a route's `catalog_version` takes (`crates/baley-core/src/policy/route.rs` (`AcceptedNames`), `crates/baley-core/src/policy/route.rs` (`resolve_route`)). Every route an order records carries it, read by the composer from `user` (`crates/baley/src/work_order/route.rs` (`host_names` and `names`), `crates/baley-core/src/work_order/route.rs` (`route_record`)). | | CFG-R24 | Partly built | The `keys.env` reader is removed, and outside the parked engine nothing reads a key or a key file. A `keys.env` an older build wrote stays in the config folder, unread (`crates/baley/src/folders.rs` (`Folders`)), and stays protected, since the guard protects the whole config folder (`crates/baley/src/protected_paths/write.rs` (`ProtectedPaths`)). The parked review engine still reads environment keys and `providers.env` (`crates/baley/src/review/provider/credentials.rs`) until Build 9 deletes it. | | CFG-R25 | Partly built | `baley exec --key` is removed, and `baley exec` is now an unknown subcommand, a usage error with exit 2 (`crates/baley/src/main.rs` (`exec_with_a_key_is_a_usage_error_now_that_the_wrapper_is_gone`)). No built command sets, removes, lists or injects keys. The parked review engine still reads environment values and `providers.env` (`crates/baley/src/review/provider/credentials.rs`) until Build 9 deletes it, and the work order that names the variable for the session is Build 4's. | -| CFG-R26 | Partly built | The key type, redactor and sensitive HTTP header handling are removed with the key reader, `baley exec` and the lister. A detection record names the provider and never a key or anything sent (`crates/baley/src/detection/record.rs` (`detection_request`)), and the fetch command names the environment variable, never a value (`crates/baley/src/detection/fetch.rs` (`fetch_command`)). The acknowledgement record holds no credential or environment value (`crates/baley/src/providers/event.rs` (`acknowledged_event`)). The work-order records built so far hold no credential or environment value: a start planner's order carries its route, its instructions' identities and the brief, and an analyzer order its route, its instructions' identities and the story, the approved description, the roadmap, the story's truths and, for drafting, its question set (`crates/baley-core/src/work_order/event.rs` (`issued_payload`), `crates/baley/src/refine/inputs.rs` (`read` and `questions_body`)). The review and fetch work orders, which name a variable, are Build 4's, and the parked review engine still handles key values until Build 9 deletes it. | +| CFG-R26 | Partly built | The key type, redactor and sensitive HTTP header handling are removed with the key reader, `baley exec` and the lister. A detection record names the provider and never a key or anything sent (`crates/baley/src/detection/record.rs` (`detection_request`)), and the fetch command names the environment variable, never a value (`crates/baley/src/detection/fetch.rs` (`fetch_command`)). The acknowledgement record holds no credential or environment value (`crates/baley/src/providers/event.rs` (`acknowledged_event`)). The work-order records built so far hold no credential or environment value: a start planner's order carries its route, its instructions' identities and the brief, an analyzer order its route, its instructions' identities and the story, the approved description, the roadmap, the story's truths and, for drafting, its question set, and a phase planner's order its route, its instruction's identity and the phase, its committed stories with their truths, the approved description, the capacity when one is set, the approved items and, for a revision, the draft and its set (`crates/baley-core/src/work_order/event.rs` (`issued_payload`), `crates/baley/src/refine/inputs.rs` (`read` and `questions_body`), `crates/baley/src/planning/inputs.rs` (`read`)). The review and fetch work orders, which name a variable, are Build 4's, and the parked review engine still handles key values until Build 9 deletes it. | | CFG-R27 | Partly built | The HTTPS lister and the key lookup are removed. `key_name` and the list addresses stay as request metadata the fetch command names, `OPENAI_API_KEY` and `DEEPSEEK_API_KEY`, without looking either up (`crates/baley/src/detection/trigger.rs` (`key_name` and `list_address`)). The pure catalog detection code stays. Work-order metadata is Build 4's, and the parked review engine still looks keys up until Build 9 deletes it. | | CFG-R28 | Partly built | After its thirteen questions the interview asks which outside providers to use (`crates/baley/src/config_command/interview/providers.rs` (`stage`)), shows the warning for each provider the owner names and takes a typed `yes` (`crates/baley/src/config_command/interview/providers.rs` (`stage`)), and reads the owner: the global `owner.name`, else git's `user.name`, refusing `owner-identity-missing` before the summary when neither gives a name (`crates/baley/src/providers/identity.rs` (`owner`, `owner_name` and `judge`), `crates/baley/src/config_command/interview/providers.rs` (`stage`)). It prints a summary naming every file the writes can change or create (`crates/baley/src/config_command/interview/summary.rs` (`files`, `list_text` and `lines`)). After the final `yes` it records the acknowledgement or reuses a current one (`crates/baley/src/providers/record.rs` (`judge` and `append`), `crates/baley/src/config_command/interview.rs` (`acknowledge`)), adds the providers' API hosts to Claude Code's settings through the installation writer (`crates/baley/src/install/hosts.rs` (`judge`, `read` and `write`)), writes the global `review.reviewers` list (`crates/baley/src/config_command/reviewers.rs` (`decide`), `crates/baley/src/config_command/set.rs` (`apply_list` and `replace_list`)), and then runs the settings through `set::apply` (`crates/baley/src/config_command/interview.rs` (`execute`)). A reworded warning asks again, since a stored acknowledgement covers a provider only at the compiled warning's version and digest (`crates/baley/src/providers/record.rs` (`covered_by` and `judge`)). A fresh install enables no outside provider, and install records no acknowledgement. `baley models update` prints a fetch command only for a provider a stored acknowledgement covers at the compiled warning, reading `review.reviewers` when no provider is named, and otherwise refuses `provider-not-acknowledged` naming `baley config interview` (`crates/baley/src/models.rs` (`update` and `update_decision`)). Build 4 owns the unbuilt part: the acknowledgement check at review and list-fetch work-order issuance, and the review consumer of `review.reviewers`. | | CFG-R29 | Not built | The TOML schema in `crates/baley-core/src/policy/schema.rs` has no `git.forge_provider`. Only the inherited JSON schema lists the values (`crates/baley/src/config/schema.json` (`git.forge_provider`)), and only the parked landing reads them (`crates/baley/src/landing/forge.rs` (`configured`), `crates/baley/src/landing/report.rs` (`tracker`)), with no not-yet-supported report. The session server answers `land-read` and the landing apply spellings as unavailable (`crates/baley/src/mcp/operations.rs` (`QUERY_OPERATIONS` and `APPLY_OPERATIONS`)) until Build 6 | diff --git a/docs/design/0004-starting-a-project-and-changing-scope.md b/docs/design/0004-starting-a-project-and-changing-scope.md index c9fde735..0ff08e4d 100644 --- a/docs/design/0004-starting-a-project-and-changing-scope.md +++ b/docs/design/0004-starting-a-project-and-changing-scope.md @@ -6,7 +6,7 @@ | Design issue | [#46](https://github.com/jcrenshaw-dev/baley/issues/46), [#45](https://github.com/jcrenshaw-dev/baley/issues/45); build issues [#23](https://github.com/jcrenshaw-dev/baley/issues/23), [#25](https://github.com/jcrenshaw-dev/baley/issues/25) | | Requirement prefix | PRJ | | Applies | [0002: System design](0002-system-design.md) | -| Related | ADRs: [0004](../adr/0004-project-identity.md), [0006](../adr/0006-no-markdown-records.md), [0007](../adr/0007-forge-anchors.md), [0009](../adr/0009-served-instructions.md), [0017](../adr/0017-stories-and-sprints.md), [0031](../adr/0031-one-term-per-concept.md) · C4 view: components ([0002](0002-system-design.md) Figure 4) | +| Related | ADRs: [0004](../adr/0004-project-identity.md), [0006](../adr/0006-no-markdown-records.md), [0007](../adr/0007-forge-anchors.md), [0009](../adr/0009-served-instructions.md), [0017](../adr/0017-stories-and-sprints.md), [0031](../adr/0031-one-term-per-concept.md), [0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md) · C4 view: components ([0002](0002-system-design.md) Figure 4) | The current design of this area, and nothing else. Edit it in place when the design changes; git holds the history. It describes the design only, never the work still to do. @@ -152,17 +152,17 @@ Served to a session only, as `project-start` on `baley_apply`: it only issues a ### scope approve - **Inputs:** the digest of any draft, a start's or a change's, alone, as the receipt writes it: 64 lowercase hexadecimal characters. Anything else is refused before the ledger is read. The owner and the time are Baley's: the owner is `owner.name` from the global settings, else git `user.name` ([0012](0012-host-interface.md) HST-R10), and the time is Baley's clock when the approval is recorded. Nothing a caller sends supplies either. -- **Outputs:** for a start, in one transaction, in this order: `project.described`; one `story.declared` per story, in submission order, with ids Baley assigns as the next whole numbers after the highest story id ever declared; one `phase.declared` per phase, in roadmap order, numbered as the next whole numbers after the highest phase number ever declared, withdrawn phases included, with its dependencies as phase numbers, its stories as story ids and its detail stored as a `record` payload; one `phase.reordered` with the new numbers in roadmap order; and `scope.approved` last, binding the digest, with the owner's name and Baley's time. A story's `phase` is the number of the phase that lists it, or none when no phase does. For a change, in one transaction, the events its subsection names, taken over accepted scope as the transaction reads it, then `scope.approved` of the change's kind. Every event is recorded with actor `owner`. The receipt gives the kind, the digest, the owner, the time, the phase numbers and the story ids the approval recorded (for a start, the assigned phase numbers in roadmap order and story ids in submission order; for a change, the phase it declared, edited or withdrew and the stories it declared, corrected, moved or dropped), and the command prints them as three lines, an empty list as `none`, exit 0. +- **Outputs:** for a start, in one transaction, in this order: `project.described`; one `story.declared` per story, in submission order, with ids Baley assigns as the next whole numbers after the highest story id ever declared; one `phase.declared` per phase, in roadmap order, numbered as the next whole numbers after the highest phase number ever declared, withdrawn phases included, with its dependencies as phase numbers, its stories as story ids and its detail stored as a `record` payload; one `phase.reordered` with the new numbers in roadmap order; and `scope.approved` last, binding the digest, with the owner's name and Baley's time. A story's `phase` is the number of the phase that lists it, or none when no phase does. For a change, in one transaction, the events its subsection names, taken over accepted scope as the transaction reads it, then `scope.approved` of the change's kind. Every event is recorded with actor `owner`. The receipt gives the kind, the digest, the owner, the time, the phase numbers and the story ids the approval recorded (for a start, the assigned phase numbers in roadmap order and story ids in submission order; for a change, the phase it declared, edited or withdrew and the stories it declared, corrected, moved or dropped), and the command prints them as three lines, an empty list as `none`, exit 0. A commitment, a `phase edit` its phase's latest planning continuation names, also records in the same transaction, after `scope.approved`, the phase's planner work order as `work_order.issued` on `phase/<n>` with subject `phase/<n>`, under the id the continuation named, at attempt 1, binding the planning inputs of [0005](0005-context-plans-and-acceptance.md) section 4 for the continuation's selection in order ([ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md)). Its receipt adds the order's receipt members, `work_order`, `request`, `attempt`, `agent`, `model`, `prompt` and `launch`, and the command prints a further line, `planner work order: <id>, which a session's phase-plan with the same stories launches`. The terminal composes that order's route for Claude Code, the one supported host, so a commitment's policy step records Claude Code's effective policy for the checkout and the route names that policy's version, with Claude Code's accepted model names; a fault composing it, such as `unknown-model`, or reading the inputs, such as `text-purged` for a purged phase detail, is the answer, with nothing approved. The session's next `phase plan` with the same selection hands that order over ([0005](0005-context-plans-and-acceptance.md) section 5). - **Refusals:** judged in this order, so one approval always gets one answer. Each prints `<code>: <reason>`, a stale draft's followed by the path, and exits 2. | Code | When | Requirement | |---|---|---| - | `unknown-draft` | No draft has the digest, its `scope.submitted` at its latest submission is not found among the events, or no newest draft of its change is listed. A story's truth draft, kind `story-truths`, is refused this way too, its reason naming `baley story truths approve <digest>`, the only command that approves truths ([0005](0005-context-plans-and-acceptance.md)) | PRJ-R19 | + | `unknown-draft` | No draft has the digest, its `scope.submitted` at its latest submission is not found among the events, or no newest draft of its change is listed. A story's truth draft, kind `story-truths`, is refused this way too, its reason naming `baley story truths approve <digest>`, the only command that approves truths ([0005](0005-context-plans-and-acceptance.md)). A plan draft, kind `plan`, is refused the same way, its reason naming `baley plan approve <digest>`, the only command that approves plans | PRJ-R19 | | `project-already-started` | A start draft, and the project's start is approved. Judged before staleness, so once one start draft is approved, approving any other start draft is refused this way, not with `stale-draft` | PRJ-R6 | - | `draft-approved` | A change draft already approved after its latest submission. The details name that approval's `owner` and `at`. Judged before staleness, since the draft was already acted on | PRJ-R19 | + | `draft-approved` | A change draft already approved after its latest submission. The details name that approval's `owner` and `at`, and for a commitment also, in `work_order` and in the reason, the planner order its approval issued, so running the approval again tells the owner the same order and issues none. Judged before staleness, since the draft was already acted on | PRJ-R19 | | `stale-draft` | A newer submission for the same change, the same kind and target, was recorded after this draft's latest submission. The details name the first differing part as a path into the content, looked for in the kind's member order: for a start, the description, then the stories entry by entry, then the roadmap entry by entry, such as `roadmap[1].goal`; for a change, its members in the order its subsection lists them, inside a list entry by entry and inside a withdrawal's decisions member by member, such as `decisions[0].to`. A member one draft holds and the other lacks differs | PRJ-R19 | - A change draft that passes these is judged again against accepted scope as it stands at approval, with the same refusals and the same order as at submission, so an approval after scope moved is refused what a submission now would be. Those refusals name the `digest` as the slot at fault, where a submission's name the `submission`. + A commitment that passes these is rechecked next, over facts read at approval with the same gathering and the same rules `phase plan` judges its selection by, each refusal at slot `digest` and recording nothing: `phase-active` while another phase is active, naming it; `no-such-phase`; `no-such-story`, `story-unrefined` for a story with no approved truths, and `story-in-phase` for a story committed to another phase, each naming the first selected story at fault; then `planner-order-pending` while a planner order of the phase is pending, naming that order, since a phase has one live planner order ([0005](0005-context-plans-and-acceptance.md) section 5). A change draft that passes these is judged again against accepted scope as it stands at approval, with the same refusals and the same order as at submission, so an approval after scope moved is refused what a submission now would be. Those refusals name the `digest` as the slot at fault, where a submission's name the `submission`. Run outside a checkout of a project it is refused `not-a-project`, and for a project the ledger does not list, `project-not-in-ledger`. With neither `owner.name` nor git `user.name` readable it is refused `owner-identity-missing`, naming both ways to set one; that refusal comes after checkout admission and the policy step, whose records stand. A draft whose body this project purged, or whose body no longer judges as the submission its digest names, is never approved: the answer is `failed` `ledger-unavailable`, exit 1. So is an approval of a start, a `phase declare` or a `story declare` whose numbering would pass the largest phase number or story id Baley can hold (4,294,967,295), and its transaction records nothing, since wrapping would reuse a number. A `phase edit` that gives no detail keeps the detail in force; when this project purged that detail the approval is answered `failed` `text-purged`, naming `detail`, with nothing recorded, and the edit must give a new detail. @@ -172,9 +172,9 @@ Served to a session only, as `project-start` on `baley_apply`: it only issues a A refusal of a start submission, a change submission or an approval judged against the ledger records nothing at all. It is judged from the ledger before the write is prepared: over MCP after the replay lookup and before the settings are read, on the command line before checkout admission. So no checkout admission (`checkout.seen`), no policy step (`policy.effective`) and no `command.completed` is recorded for it. A start's order check and start-once check, a project start's start-once and pending-order checks, a change's judgement against accepted scope and an approval's whole judgement are each judged this way. A refusal of the submission's content, its shape, is judged before the ledger is read at all. -A retry of a submission request already completed, the same `request_id` with the same submission, is answered with its recorded receipt and never refused, even when scope moved since: a retried start is not refused `project-already-started` after the start was approved, and a retried change is not refused by the scope it was checked against. When the check refuses, the request is looked up again first, so a request recorded since the first lookup is replayed rather than refused. The library function Build 4 T9's `phase plan` records a `phase edit` with does the same: it looks its request up before the scope check and again after a check that refuses, and answers with the digest its recorded receipt names, so a receipt the ledger holds for another change under the same request is `request-id-reuse`. Each `baley scope approve`, and each of the owner's change commands, is a new request, so it has no retry by id: running an approval again after it was recorded is judged afresh and refused `project-already-started` for a start or `draft-approved` for a change. +A retry of a submission request already completed, the same `request_id` with the same submission, is answered with its recorded receipt and never refused, even when scope moved since: a retried start is not refused `project-already-started` after the start was approved, and a retried change is not refused by the scope it was checked against. When the check refuses, the request is looked up again first, so a request recorded since the first lookup is replayed rather than refused. The library function `phase plan` records its `phase edit` and planning continuation with does the same: it looks its request up before the scope check and again after a check that refuses, and answers with the receipt the ledger recorded for the request, so a receipt the ledger holds for another change under the same request is `request-id-reuse`. Each `baley scope approve`, and each of the owner's change commands, is a new request, so it has no retry by id: running an approval again after it was recorded is judged afresh and refused `project-already-started` for a start or `draft-approved` for a change. -When a call landing between another call's judgement and its transaction moved a fact that transaction confirms, the transaction records nothing. Each transaction confirms only the facts listed here for it. A start submission's transaction confirms that no start approval exists. A project start's confirms that no start approval exists and that no start planner order is pending. A change submission's confirms that the `roadmap` document and every `phase` document its check read are unchanged. A start approval's confirms that the draft's latest submission, its `scope.submitted`, the absence of a start approval and the newest start draft are what the judgement read. A change approval's confirms the draft's latest submission and its `scope.submitted`, that no approval of its digest landed since, that the newest draft of its change is the one read, by digest and sequence, and that every scope document the judgement read is unchanged; for a `phase edit` that keeps the detail in force, it also confirms that the `phase_detail` document the detail came from has not moved and is not purged, so a detail purged between the steps is never stored again. The first step reads accepted scope before the earlier approvals of the digest, so an approval landing between those reads lands after the scope read, moves the `roadmap` document, and the second step refuses. When any of them moved, the call is answered `failed` `ledger-busy`, retryable, and the retry is judged afresh. The checkout admission and policy step recorded before the transaction stand. +When a call landing between another call's judgement and its transaction moved a fact that transaction confirms, the transaction records nothing. Each transaction confirms only the facts listed here for it. A start submission's transaction confirms that no start approval exists. A project start's confirms that no start approval exists and that no start planner order is pending. A change submission's confirms that the `roadmap` document and every `phase` document its check read are unchanged. A start approval's confirms that the draft's latest submission, its `scope.submitted`, the absence of a start approval and the newest start draft are what the judgement read. A change approval's confirms the draft's latest submission and its `scope.submitted`, that no approval of its digest landed since, that the newest draft of its change is the one read, by digest and sequence, and that every scope document the judgement read is unchanged; for a `phase edit` that keeps the detail in force, it also confirms that the `phase_detail` document the detail came from has not moved and is not purged, so a detail purged between the steps is never stored again. A commitment's approval also confirms that no planner order of the phase is pending, that no phase is active when the recheck found none, and that the phase's `phase_plan` document, each selected story's `truths` document and every document the order's inputs were read from are unchanged, so an order issued, a phase made active or a truth revised since leaves both the stories and the work orders as they were. The first step reads accepted scope before the earlier approvals of the digest, so an approval landing between those reads lands after the scope read, moves the `roadmap` document, and the second step refuses. When any of them moved, the call is answered `failed` `ledger-busy`, retryable, and the retry is judged afresh. The checkout admission and policy step recorded before the transaction stand. ### project describe @@ -206,8 +206,9 @@ When a call landing between another call's judgement and its transaction moved a ### phase edit -- **Inputs:** `phase`, the phase's number, and only the fields that change, at least one: `name`, `goal` or `detail` as text, `depends_on` as phase numbers, `stories` as story ids. Over MCP the operation is `phase-edit`; it has no owner command. Build 4 T9's `phase plan` records and approves an edit through the same library functions, with plain values. +- **Inputs:** `phase`, the phase's number, and only the fields that change, at least one: `name`, `goal` or `detail` as text, `depends_on` as phase numbers, `stories` as story ids. Over MCP the operation is `phase-edit`; it has no owner command. `phase plan` ([0005](0005-context-plans-and-acceptance.md) section 5) also drafts a `phase edit`, with `stories` as its only field, when the stories it is sent differ from the ones the phase commits; that draft carries a planning continuation, below. - **Outputs:** the receipt with the digest. On approval a whole new `phase.declared` for the same number: each field the edit gives, and each it leaves out taken from the phase as accepted scope holds it at approval, its stories being those it serves then and its detail the detail in force, stored again as a `record` payload. Then `scope.approved`. The earlier declaration stays in the record. A story the edit adds is committed to the phase, and one it leaves out returns to the backlog and keeps its status. +- **Planning continuation:** a `phase plan` whose selection differs from the phase's committed stories, in content or only in order, records the edit's draft and, in the same transaction, one `plan.continuation` on the phase's stream, `phase/<n>`, naming the phase, the selection in order, the edit's digest and the id of the planner's work order its approval will issue, fixed then so every later read names the same order ([0005](0005-context-plans-and-acceptance.md) section 6). Its receipt adds to a change's the phase, the selection, and in `preview` and `approve` the commands `baley scope preview <digest>` and `baley scope approve <digest>`; no order is issued, and a replay of the call is answered with the same receipt from its record. The edit is judged against accepted scope as any `phase edit` is before anything is recorded, and the transaction confirms that nothing `phase plan` read when it chose to draft has moved, so a change since to the roadmap, a selected story's truths or the phase's planning state, or a phase made active, leaves the call `failed` `ledger-busy` with nothing recorded. An edit a phase's latest continuation names is a commitment, approved as `scope approve` describes, and its approval also issues the planner's order ([ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md)). - **Refusals:** in this order. | Code | When | Requirement | @@ -298,8 +299,8 @@ A story's truths are revised by refining it again, `story refine` to `story trut | Field | Type | Meaning | |---|---|---| | `digest` | digest | The SHA-256 of the submission's canonical JSON, its identity as a draft | -| `kind` | enum | The change kind, as in `scope.approved`, or `story-truths` for a story's truth draft ([0005](0005-context-plans-and-acceptance.md)), which is approved as `story.refined` and never by `scope.approved` | -| `target` | text | The change the draft belongs to among its kind's drafts: `project` for a start; the phase number of a `phase-edit` or `phase-withdraw`; the story id of a `story-edit`, `story-reassign` or `story-drop`; `order` for either reorder; `description` for `project-describe`; the draft's own digest for a `phase-declare` or `story-declare`; `story/<id>` for a `story-truths` draft, so only a newer truth draft for the same story makes it stale | +| `kind` | enum | The change kind, as in `scope.approved`; `story-truths` for a story's truth draft, which is approved as `story.refined`; or `plan` for a plan draft, which is approved as `plan.approved` ([0005](0005-context-plans-and-acceptance.md)). Neither of the last two is ever approved by `scope.approved` | +| `target` | text | The change the draft belongs to among its kind's drafts: `project` for a start; the phase number of a `phase-edit` or `phase-withdraw`; the story id of a `story-edit`, `story-reassign` or `story-drop`; `order` for either reorder; `description` for `project-describe`; the draft's own digest for a `phase-declare` or `story-declare`; `story/<id>` for a `story-truths` draft, so only a newer truth draft for the same story makes it stale; `phase/<n>` for a plan draft, a replacement's included, so a phase holds one plan draft at a time | | `body` | payload reference | The submission's canonical JSON as a `record` payload, which the event attaches | The payload is at version 2. Only starts were recorded at version 1, which had no `target`, so a version-1 event reads with the start's target `project`, and a version-1 event of any other kind is refused rather than filed under a guessed target. Recorded once per submit, a repeated digest included. The accepted scope views ignore it. @@ -370,7 +371,7 @@ Each truth it carries has a `version`, and its `owner` and `at` are the approval ### Views -Every view is kept per project, and only `draft` reads a submission. The accepted scope views, `roadmap`, `phase`, `phase_detail` and `backlog`, change only on the events an approval records, `story.refined` among them, except that `backlog` also records each story's latest question set from its `questions.opened` ([0005](0005-context-plans-and-acceptance.md)). +Every view is kept per project, and only `draft` reads a submission. The accepted scope views, `roadmap`, `phase`, `phase_detail` and `backlog`, change only on the events an approval records, `story.refined`, `plan.approved` and `plan.replaced` among them, except that `backlog` also records each story's latest question set from its `questions.opened` ([0005](0005-context-plans-and-acceptance.md)). | View | Key | Content | |---|---|---| @@ -378,7 +379,7 @@ Every view is kept per project, and only `draft` reads a submission. The accepte | `roadmap` | project | One document: the latest project description; every phase ever declared, by number, each with name, goal, dependencies, the stories it serves now and status, `declared` or `withdrawn`; the latest phase order; the stories in priority order, each with id, wording, status, the phase serving it now and truth count, 0 when declared and set by the story's latest `story.refined`, the same event that sets the backlog's; and the highest phase number and story id ever declared, which never go down, so an approval numbers past every declaration, withdrawn phases included. A withdrawn phase keeps its entry and is outside the order, so a roadmap read, `baley scope show` and `document` alike, gives the phases in order and then each withdrawn phase by number. Every event that moves a story keeps a phase's stories and the story's phase in step: a declaration commits the stories it lists and returns to the backlog those it no longer lists, a reassignment moves the story, and a drop takes it off its phase and keeps it with status `dropped`. A reprioritization puts the stories it lists first and every other story after them in its current relative order. This is the document a change is judged against, and the description read for refinement and planning | | `phase` | project, phase number | One document per declared phase: name, goal, dependencies, the stories its latest declaration listed, status, `declared` or `withdrawn`, the approving digest, the declaration's time and sequence, and the detail body's hash, never the text. Its `by_status` index lists phases by status, then number. A later declaration of the same number replaces the document. A withdrawal keeps it with every field and status `withdrawn`, so a withdrawn phase is still read by its number. A reassignment or drop since the latest declaration names no earlier phase, so the stories a phase serves now are the `roadmap` view's, which a phase read gives. The current context (truth versions), plans, execution and completion state Hardin needs are added by the events that record them | | `phase_detail` | project, `phase.declared` sequence | One document per phase declaration: the phase number and the detail body's hash. It is keyed by the declaration's sequence because a purge names each released body by sequence and hash; a `phase` document names its sequence. When this project purges the body, the document gains `state` `purged` and the purge's reason, so a phase read answers them and never opens the body | -| `backlog` | project | One document: the stories in priority order, each with id, wording, status, phase, its latest question set id, its refined marker (the set its latest `story.refined` names), truth count and size, the view [0005](0005-context-plans-and-acceptance.md) reads. A declared story goes last. It follows corrections, reassignments, drops and reprioritizations, and the phase declarations that commit a story they list or release one they no longer list; a dropped story stays with status `dropped` and no phase. A story's `questions.opened` makes its set the latest, and its `story.refined` replaces the marker and the truth count; a plan draft's set changes nothing. The set and the marker are none, the truth count 0 and the size none until refinement and sizing record them. A story's refinement state, `unrefined`, `questions-open` with the round, `drafting` or `refined`, is never stored: a backlog read works it out from the latest set's `questions` document and the marker | +| `backlog` | project | One document: the stories in priority order, each with id, wording, status, phase, its latest question set id, its refined marker (the set its latest `story.refined` names), truth count and size, the view [0005](0005-context-plans-and-acceptance.md) reads. A declared story goes last. It follows corrections, reassignments, drops and reprioritizations, and the phase declarations that commit a story they list or release one they no longer list; a dropped story stays with status `dropped` and no phase. A story's `questions.opened` makes its set the latest, and its `story.refined` replaces the marker and the truth count; a plan draft's set changes nothing. Each story also lists in `plans` the approved plans in force that serve it, each with its phase, number and size: a `plan.approved` adds the plan to every story it serves, and a `plan.replaced` removes it. The size is those plans' tasks summed. The set and the marker are none, the truth count 0 and the size none until refinement records them and a plan serving the story is approved. A story's refinement state, `unrefined`, `questions-open` with the round, `drafting` or `refined`, is never stored: a backlog read works it out from the latest set's `questions` document and the marker | ## 7. States @@ -400,7 +401,7 @@ stateDiagram-v2 Withdrawn --> [*] ``` -*Figure 1. States of a phase as this area sees them. Execution and completion transitions belong to [0006](0006-execution.md) and [0007](0007-verification.md); a withdraw from Executing is refused `execution-present` until `phase.undone` returns it to Planned; Complete is never withdrawn and is refused `phase-complete`. A withdrawn phase keeps every record and its `phase` and `roadmap` entries with status `withdrawn`, outside the order, and no change, capture or dependency can name it again. The `phase` view records only Declared and Withdrawn until the context, plan, execution and completion events are recorded.* +*Figure 1. States of a phase as this area sees them. Execution and completion transitions belong to [0006](0006-execution.md) and [0007](0007-verification.md); a withdraw from Executing is refused `execution-present` until `phase.undone` returns it to Planned; Complete is never withdrawn and is refused `phase-complete`. A withdrawn phase keeps every record and its `phase` and `roadmap` entries with status `withdrawn`, outside the order, and no change, capture or dependency can name it again. The `phase` view records only Declared and Withdrawn until the context, execution and completion events are recorded. Whether a phase holds an approved plan is the `phase_plan` view's ([0005](0005-context-plans-and-acceptance.md) Figure 3): it is `active` from its first `plan.approved` until it is withdrawn or every plan is replaced away, and `phase plan` for any other phase is refused `phase-active` while it is.* ```mermaid stateDiagram-v2 @@ -531,37 +532,37 @@ Not applicable. This area reads no setting of its own. The start runs no setting ## 11. Build status -The binary parks the inherited engine for Build 9 to delete, and nothing in production reaches it (`crates/baley/src/inherited.rs`, its module comment). Build 4 T3 built the start's scope records, Build 4 T4 the scope changes, Build 4 T5 `project start`, its planner's work order and the binding of a start submission to that order, and Build 4 T7 a story's refinement and its truth revisions ([0005](0005-context-plans-and-acceptance.md) section 11). +The binary parks the inherited engine for Build 9 to delete, and nothing in production reaches it (`crates/baley/src/inherited.rs`, its module comment). Build 4 T3 built the start's scope records, Build 4 T4 the scope changes, Build 4 T5 `project start`, its planner's work order and the binding of a start submission to that order, Build 4 T7 a story's refinement and its truth revisions, and Build 4 T9 phase planning, whose commitment of a phase's stories goes through a `phase edit` this area approves ([0005](0005-context-plans-and-acceptance.md) section 11). A session submits a start with `scope-submit` on `baley_apply`, and each change with its own spelling, `project-describe` to `backlog-reorder`, listed after it (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`, and `crates/baley/src/mcp/handler.rs`, `operate`). A change's arguments are judged before anything is prepared (`crates/baley/src/mcp/scope.rs`, `change_shapes!` and `judge_change_arguments`): each kind's shape, its digest over a body that holds the kind, and its target (`crates/baley-core/src/scope/change.rs`, `judge_change` and `judge_members`). The change is then judged against accepted scope as preparation's own check, after the replay lookup and before checkout admission and the policy step (`crates/baley/src/mcp/scope.rs`, `serve_change`, and `crates/baley/src/scope/submit.rs`, `check_change`), by the rules of section 5 (`crates/baley-core/src/scope/rules.rs`, `judge_scope_change` and `judge_progress`), over the scope read from the events and the `roadmap` and `phase` views, which the recording's transaction confirms has not moved (`crates/baley/src/scope/read.rs`, `scope` and `confirm`, and `crates/baley/src/scope/submit.rs`, `record_change`). The owner's `baley phase reorder`, `baley phase withdraw`, `baley story reassign`, `baley story drop` and `baley backlog reorder` turn their words into the same members and submit through the same functions, as the owner (`crates/baley/src/scope/command.rs`, `run_phase`, `run_backlog`, `run_story`, `submit_change`, `change_members`, `decision_members` and `command_change`). -`baley scope approve` approves a start or a change draft (`crates/baley/src/scope/command.rs`, `approve`), and refuses a story's truth draft `unknown-draft`, its reason naming `baley story truths approve <digest>` (`crates/baley/src/scope/approve.rs`, `judge`). Its first step judges a change draft against the newest draft of the same change and then against accepted scope as it stands, reading the scope before the earlier approvals of the digest (`crates/baley/src/scope/approve.rs`, `judge_change_draft`, and `crates/baley-core/src/scope/approval.rs`, `judge_change_approval`). Its second step confirms what the first read, a carried phase detail included, and records the change's events (`crates/baley/src/scope/approve.rs`, `change_decision` and `confirm_detail`, and `crates/baley-core/src/scope/change_events.rs`, `change_events`). `baley_apply` has no `scope-approve` spelling, so approval is given only on the command line. Build 4 T9's `phase plan` gets a `phase edit` it records from plain values, replayed before the scope check and answered with the digest its recorded receipt names, and approves it through the same two steps (`crates/baley/src/scope/submit.rs`, `submit_phase_edit`, and `crates/baley/src/scope/approve.rs`, `judge` and `record`). +`baley scope approve` approves a start or a change draft (`crates/baley/src/scope/command.rs`, `approve`), and refuses a story's truth draft `unknown-draft`, its reason naming `baley story truths approve <digest>`, and a plan draft the same way, naming `baley plan approve <digest>` (`crates/baley/src/scope/approve.rs`, `judge` and `plan_draft`); `baley scope preview` prints a plan draft with that command (`crates/baley/src/scope/command.rs`, `plan_preview`). Its first step judges a change draft against the newest draft of the same change and then against accepted scope as it stands, reading the scope before the earlier approvals of the digest (`crates/baley/src/scope/approve.rs`, `judge_change_draft`, and `crates/baley-core/src/scope/approval.rs`, `judge_change_approval`). Its second step confirms what the first read, a carried phase detail included, and records the change's events (`crates/baley/src/scope/approve.rs`, `change_decision` and `confirm_detail`, and `crates/baley-core/src/scope/change_events.rs`, `change_events`). `baley_apply` has no `scope-approve` spelling, so approval is given only on the command line. `phase plan` records a changed selection's `phase edit` from plain values with its `plan.continuation` in one transaction, replayed before the scope check and answered with the receipt it recorded (`crates/baley/src/scope/submit.rs`, `submit_planning_edit` and `PlanningContinuation`, called from `crates/baley/src/planning/phase_plan.rs`, `run`). A `phase edit` its phase's latest continuation names is a commitment ([ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md)): the first step finds it and rechecks its selection through the gathering `phase plan` judges, then the phase's pending planner order (`crates/baley/src/scope/approve.rs`, `continuation_naming` and `recheck`, and `crates/baley/src/planning/phase_plan.rs`, `read_readiness`, through `crates/baley-core/src/plan/commitment.rs`, `judge_readiness`); a `draft-approved` refusal of one names its order (`crates/baley/src/scope/approve.rs`, `naming_order`); and the second step prepares the planner order under the continuation's id and issues it in the approval's transaction after the change's events (`crates/baley/src/scope/approve.rs`, `record_commitment` and `OrderRoute`, through `crates/baley/src/planning/order.rs`, `prepare`). The command routes it for Claude Code, recording that host's effective policy at its policy step, and prints the order's line (`crates/baley/src/scope/command.rs`, `approve`, `host_admitted` and `answer_render`). -The five change events are registered beside the six the start records (`crates/baley-core/src/scope/event.rs`, `register_scope_events`), and the `draft`, `roadmap`, `phase` and `backlog` projectors, with their versions raised, are registered in view set 13, beside the `work_order` view that holds the start and analyzer orders, the `questions` view and the `truths` view that `story.refined` keeps ([0005](0005-context-plans-and-acceptance.md)) (`crates/baley/src/ledger/open.rs`, `options`). A session reads a draft of any kind, the accepted roadmap, an accepted story, a work order and a story's refinement with `document` (`crates/baley/src/mcp/document.rs`, `read`). The owner has `baley scope preview`, `baley scope show`, `baley phase show`, `baley backlog show` and `baley story show` (`crates/baley/src/main.rs`, `Command`, and `crates/baley/src/scope/command.rs`, `run`). The description refinement and planning read is the `roadmap` view's latest approved description (`crates/baley/src/scope/read.rs`, `description`); refinement is served it through the analyzer's order inputs and the refinement read ([0005](0005-context-plans-and-acceptance.md) section 11), and serving it to planning is Build 4 T9. The five scope front doors, `bal-project`, `bal-scope`, `bal-phase`, `bal-story` and `bal-backlog`, are help rows whose texts the registry serves, so each is an installed skill stub, and the start planner's and survey's texts are registry entries with no help row (`crates/baley/src/help/table.rs`, `COMMANDS`, `crates/baley/src/instruction/scope.rs`, the five `_TEXT` constants, and `crates/baley/src/instruction/start.rs`, `PLANNER_TEXT` and `SURVEY_TEXT`). +The five change events are registered beside the six the start records (`crates/baley-core/src/scope/event.rs`, `register_scope_events`), and the `draft`, `roadmap`, `phase` and `backlog` projectors, with their versions raised, the `backlog` view's to 4 for a story's size, are registered in view set 14, beside the `work_order` view that holds the start, analyzer and planner orders, the `questions` view, the `truths` view that `story.refined` keeps, and the `phase_plan`, `plan` and `evidence_map` views of phase planning ([0005](0005-context-plans-and-acceptance.md)) (`crates/baley/src/ledger/open.rs`, `options`). A session reads a draft of any kind, the accepted roadmap, an accepted story, a work order, a story's refinement, a phase's approved plans and one approved plan with `document` (`crates/baley/src/mcp/document.rs`, `read`). The owner has `baley scope preview`, `baley scope show`, `baley phase show`, `baley backlog show` and `baley story show` (`crates/baley/src/main.rs`, `Command`, and `crates/baley/src/scope/command.rs`, `run`). The description refinement and planning read is the `roadmap` view's latest approved description (`crates/baley/src/scope/read.rs`, `description`); refinement is served it through the analyzer's order inputs and the refinement read, and planning through the planner order's `description` input ([0005](0005-context-plans-and-acceptance.md) section 11). The five scope front doors, `bal-project`, `bal-scope`, `bal-phase`, `bal-story` and `bal-backlog`, are help rows whose texts the registry serves, so each is an installed skill stub, and the start planner's and survey's texts are registry entries with no help row (`crates/baley/src/help/table.rs`, `COMMANDS`, `crates/baley/src/instruction/scope.rs`, the five `_TEXT` constants, and `crates/baley/src/instruction/start.rs`, `PLANNER_TEXT` and `SURVEY_TEXT`). PRJ-R13's facts are read from the `phase` view, whose statuses in this build are `declared` and `withdrawn` only, so in production no phase has execution or completion, and `execution-present`, `phase-complete` and `story-shipped` are reached only from supplied facts (`crates/baley/src/scope/read.rs`, `progress_of`) until Builds 5 and 6 record execution and completion. One race is not closed. A transaction cannot ask the store for an approval after a sequence, so when a draft was approved before its latest submission, the second step relies on the `roadmap` document moving to catch a second approval of the same digest landing between the steps. Every change approval Baley records appends an event the `roadmap` view projects, so this holds for every path Baley writes; a `scope.approved` appended with no roadmap event would pass. A store query for events after a sequence would close it, and Build 4 T11 adds that query beside the store reader it adds for git facts (`crates/baley/src/scope/approve.rs`, `change_decision`). -A session starts a project with `project-start` on `baley_apply`, listed after the change operations with `work-order-fail` and `work-order-retry`, which `questions-answer`, `story-refine` and `story-questions-submit` follow (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`, and `crates/baley/src/mcp/handler.rs`, `operate`). Its arguments are judged before anything is prepared: the shape, the request id, `brief-blank`, `brief-too-large` past 65,536 bytes and the instruction, and the request digest covers the brief's SHA-256 (`crates/baley/src/mcp/work_order.rs`, `judge_start_arguments`). Its check runs after the replay lookup and before the settings: `project-already-started` from the project's events, then `start-order-pending` from the `work_order` view's `live` index, naming the pending order (`crates/baley/src/mcp/work_order.rs`, `start_check`, `crates/baley/src/scope/submit.rs`, `start_once`, and `crates/baley/src/work_order/read.rs`, `pending_start`). Preparation hands the write the host's policy the step recorded and the root commit checkout admission gathered (`crates/baley/src/mcp/prepare.rs`, `Stepped` and `write_next`). The checkout holds existing code when HEAD has a root commit and its tracked files, listed only then, hold a name besides the project file's (`crates/baley/src/checkout/gather.rs`, `tracked_files` and `holds_existing_code`, and `crates/baley/src/mcp/work_order.rs`, `existing_code`). The settings lines come from the prepared policy (`crates/baley/src/mcp/work_order.rs`, `settings_lines`). The order is composed with the planner's route at attempt 1 and recorded with the brief as a `record` payload, its transaction declaring that no start order is pending and no start is approved (`crates/baley/src/mcp/work_order.rs`, `issue_start_order`, and `crates/baley/src/work_order/issue.rs`, `start_absences` and `record`). The start records no `forge.checked`. A start submission names its order: `scope-submit` judges the order's id with its arguments, prepares under a caller carrying it, checks that the order is this project's start planner order before the start-once check, and puts the order's instruction evidence on its command's caller (`crates/baley/src/mcp/scope.rs`, `judge_arguments`, `order_caller`, `bind_instructions` and `serve`, and `crates/baley/src/scope/submit.rs`, `start_order_check` and `order_evidence`). The `work_order` view marks a pending order answered and lists each draft submitted under it, a story's analyzer orders included ([0005](0005-context-plans-and-acceptance.md)) (`crates/baley-core/src/work_order/view.rs`, `WorkOrderProjector`), and a `document` read of the order gives the start approval's digest as its accepted result when that draft is among them (`crates/baley/src/work_order/read.rs`, `accepted`). A failed start order is retried with `work-order-retry`, which refuses it once the start is approved or while another start order is pending (`crates/baley/src/mcp/work_order.rs`, `retry_check`). The session server serves `context-intake` and `context-submit` for a story's refinement ([0005](0005-context-plans-and-acceptance.md) section 11) and answers `plan-read` and `plan-submit` as `operation-unavailable` (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS` and `APPLY_OPERATIONS`), the operation baseline naming Build 4 for them. It answers `verification-complete`, the roadmap tick, the same way and names Build 5 (`APPLY_OPERATIONS`). `baley init` stays the owner's own command (`crates/baley/src/init.rs`, `run`). Parsing and editing `ROADMAP.md` and `REQUIREMENTS.md` under `.planning/` is the parked engine's. +A session starts a project with `project-start` on `baley_apply`, listed after the change operations with `work-order-fail` and `work-order-retry`, which `questions-answer`, `story-refine`, `story-questions-submit`, `phase-plan` and `plan-replace` follow (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`, and `crates/baley/src/mcp/handler.rs`, `operate`). Its arguments are judged before anything is prepared: the shape, the request id, `brief-blank`, `brief-too-large` past 65,536 bytes and the instruction, and the request digest covers the brief's SHA-256 (`crates/baley/src/mcp/work_order.rs`, `judge_start_arguments`). Its check runs after the replay lookup and before the settings: `project-already-started` from the project's events, then `start-order-pending` from the `work_order` view's `live` index, naming the pending order (`crates/baley/src/mcp/work_order.rs`, `start_check`, `crates/baley/src/scope/submit.rs`, `start_once`, and `crates/baley/src/work_order/read.rs`, `pending_start`). Preparation hands the write the host's policy the step recorded and the root commit checkout admission gathered (`crates/baley/src/mcp/prepare.rs`, `Stepped` and `write_next`). The checkout holds existing code when HEAD has a root commit and its tracked files, listed only then, hold a name besides the project file's (`crates/baley/src/checkout/gather.rs`, `tracked_files` and `holds_existing_code`, and `crates/baley/src/mcp/work_order.rs`, `existing_code`). The settings lines come from the prepared policy (`crates/baley/src/mcp/work_order.rs`, `settings_lines`). The order is composed with the planner's route at attempt 1 and recorded with the brief as a `record` payload, its transaction declaring that no start order is pending and no start is approved (`crates/baley/src/mcp/work_order.rs`, `issue_start_order`, and `crates/baley/src/work_order/issue.rs`, `start_absences` and `record`). The start records no `forge.checked`. A start submission names its order: `scope-submit` judges the order's id with its arguments, prepares under a caller carrying it, checks that the order is this project's start planner order before the start-once check, and puts the order's instruction evidence on its command's caller (`crates/baley/src/mcp/scope.rs`, `judge_arguments`, `order_caller`, `bind_instructions` and `serve`, and `crates/baley/src/scope/submit.rs`, `start_order_check` and `order_evidence`). The `work_order` view marks a pending order answered and lists each draft submitted under it, a story's analyzer orders and a phase's planner orders included ([0005](0005-context-plans-and-acceptance.md)) (`crates/baley-core/src/work_order/view.rs`, `WorkOrderProjector`), and a `document` read of the order gives the start approval's digest as its accepted result when that draft is among them (`crates/baley/src/work_order/read.rs`, `accepted`). A failed start order is retried with `work-order-retry`, which refuses it once the start is approved or while another start order is pending (`crates/baley/src/mcp/work_order.rs`, `retry_check`). The session server serves `context-intake` and `context-submit` for a story's refinement, and `plan-read` on `baley_query` and `plan-submit` on `baley_apply` for a phase's plans, beside `phase-plan` and `plan-replace` ([0005](0005-context-plans-and-acceptance.md) section 11) (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS` and `APPLY_OPERATIONS`). It answers `verification-complete`, the roadmap tick, as `operation-unavailable`, the operation baseline naming Build 5 for it (`APPLY_OPERATIONS`). `baley init` stays the owner's own command (`crates/baley/src/init.rs`, `run`). Parsing and editing `ROADMAP.md` and `REQUIREMENTS.md` under `.planning/` is the parked engine's. | Requirement | Status | Where | |---|---|---| | PRJ-R1, PRJ-R5 | Built | `project-start` takes the brief as text, refuses `brief-blank` and `brief-too-large` before anything is prepared, reads no file for it and stores it as the order's `record` input (`crates/baley/src/mcp/work_order.rs`, `judge_start_arguments` and `issue_start_order`). The order lists `bal-start-survey` after `bal-start-planner` when HEAD has a root commit and its tree tracks a file besides the project file, and the records are otherwise the same (`crates/baley/src/mcp/work_order.rs`, `issue_start_order`, `serve_start` and `existing_code`, and `crates/baley/src/checkout/gather.rs`, `holds_existing_code`). Whether a live planner follows the survey and the brief is Build 4 T15's live run | | PRJ-R2 | Built | A start submission is recorded as a draft, the body as a `record` payload and one `scope.submitted` (`crates/baley/src/scope/submit.rs`, `record`), and its approval records the description, the stories and the roadmap in one transaction (`crates/baley/src/scope/approve.rs`, `record`, and `crates/baley-core/src/scope/approval.rs`, `start_events`). The submission answers the start order it names, which `project-start` issued (`crates/baley/src/scope/submit.rs`, `start_order_check`, and `crates/baley/src/mcp/work_order.rs`, `issue_start_order` and `serve_start`) | | PRJ-R3 | Built | A start submission is judged whole, its shape before story assignment and cycles, and a fault is `malformed-submission` naming the section and the field path (`crates/baley-core/src/scope/submission.rs`, `judge_submission` and `judge_roadmap`). A change is judged whole under its kind the same way (`crates/baley-core/src/scope/change.rs`, `judge_change`). Both are answered before anything is prepared or recorded (`crates/baley/src/mcp/scope.rs`, `judge_arguments` and `judge_change_arguments`), and the terminal prints the section and the field (`crates/baley/src/scope/command.rs`, `answer_render`) | -| PRJ-R4 | Partly built | A start submission listing one story in two phases is refused `story-double-assigned` (`crates/baley-core/src/scope/submission.rs`, `double_assigned`), and a `phase declare` or `phase edit` listing a story another declared phase serves is too (`crates/baley-core/src/scope/rules.rs`, `judge_declaration`); a phase listing a story that is not `active` is `malformed-submission`. The stories keep the submission's order as their priority order, a declared story goes last, and `backlog reorder` sets the order (`crates/baley-core/src/scope/rules.rs`, `judge_backlog_order`, and `crates/baley-core/src/scope/backlog.rs`, `BacklogProjector`). Whether a phase is complete is not recorded until Builds 5 and 6 | +| PRJ-R4 | Partly built | A start submission listing one story in two phases is refused `story-double-assigned` (`crates/baley-core/src/scope/submission.rs`, `double_assigned`), and a `phase declare` or `phase edit` listing a story another declared phase serves is too (`crates/baley-core/src/scope/rules.rs`, `judge_declaration`); a phase listing a story that is not `active` is `malformed-submission`. The stories keep the submission's order as their priority order, a declared story goes last, and `backlog reorder` sets the order (`crates/baley-core/src/scope/rules.rs`, `judge_backlog_order`, and `crates/baley-core/src/scope/backlog.rs`, `BacklogProjector`). `phase plan` refuses a selected story another phase commits `story-in-phase`, naming the story and that phase, before it drafts an edit, rather than answering the edit's `story-double-assigned`, and a commitment's approval rechecks it (`crates/baley-core/src/plan/commitment.rs`, `judge_readiness`). Whether a phase is complete is not recorded until Builds 5 and 6 | | PRJ-R6 | Built | A start for a project the ledger does not list is preparation's `failed` `project-not-in-ledger`, naming `baley init` (`crates/baley/src/mcp/prepare.rs`, `next`), and the start runs neither `baley init` nor the interview (`crates/baley/src/mcp/work_order.rs`, `issue_start_order` and `serve_start`). `project-already-started` is judged from the events at the start, at submit and at a start order's retry (`crates/baley/src/scope/submit.rs`, `start_approved` and `start_once`, and `crates/baley/src/mcp/work_order.rs`, `start_check` and `retry_check`), and at approval, ahead of staleness (`crates/baley-core/src/scope/approval.rs`, `judge_approval`), and confirmed inside each transaction (`crates/baley/src/scope/submit.rs`, `record`, `crates/baley/src/work_order/issue.rs`, `start_absences`, and `crates/baley/src/scope/approve.rs`, `confirm`). `baley init` is built as its own command (`crates/baley/src/init.rs`, `run`) | | PRJ-R7 | Built | The accepted scope views ignore `scope.submitted`, so only an approved submission becomes scope (`crates/baley-core/src/scope/roadmap.rs`, `RoadmapProjector`). The start runs no research step: the survey is an instruction the planner's order lists, and the planner's text tells it to write no file (`crates/baley/src/instruction/start.rs`, `PLANNER_TEXT` and `SURVEY_TEXT`) | | PRJ-R8 | Not built | The start records no `forge.checked` and checks no forge (`crates/baley/src/mcp/work_order.rs`, `issue_start_order` and `serve_start`). The forge check is Build 6's | | PRJ-R9 | Built | A start whose host policy has no global file, or no setting from the project file, carries a line for each naming `baley config interview` and runs nothing (`crates/baley/src/mcp/work_order.rs`, `settings_lines` and `issue_start_order`). The order's route is composed from the host's merged effective policy the policy step recorded, so the other layer's settings stay in force and only settings no layer sets take Baley's defaults (`crates/baley/src/mcp/work_order.rs`, `issue_start_order` and `serve_start`) | | PRJ-R10 | Built | A start numbers its phases after the highest ever declared and records one `phase.reordered` with the full order (`crates/baley-core/src/scope/approval.rs`, `start_events` and `next_numbers`); a `phase declare` takes the next number and records `phase.reordered` with it at its position, and `phase reorder` records the order it is given (`crates/baley-core/src/scope/change_events.rs`, `change_events`). The `roadmap` view keeps the highest number, never lowering it, withdrawn phases included (`crates/baley-core/src/scope/roadmap.rs`, `RoadmapProjector`) | | PRJ-R11 | Built | The start's phases, `phase declare` and `phase edit` use the declaration shape, name, goal, detail, dependencies and stories (`crates/baley-core/src/scope/submission.rs`, `judge_roadmap`, and `crates/baley-core/src/scope/change.rs`, `judge_members`), and a dependency cycle is refused `dependency-cycle` (`crates/baley-core/src/scope/submission.rs`, `phases_on_cycles`, and `crates/baley-core/src/scope/rules.rs`, `on_cycle_with`). An edit records a whole new `phase.declared`, its left-out fields taken from accepted scope at approval (`crates/baley-core/src/scope/change_events.rs`, `change_events`); the later declaration replaces the `phase` document and the earlier event stays (`crates/baley-core/src/scope/phase.rs`, `PhaseProjector`) | -| PRJ-R12 | Partly built | A declared phase is withdrawn with a decision for each story it serves, refused `story-undecided` without one and `phase-has-dependents` while another phase depends on it (`crates/baley-core/src/scope/rules.rs`, `judge_withdrawal`), and its approval records `phase.withdrawn`, each story's move or drop and the order without it (`crates/baley-core/src/scope/change_events.rs`, `change_events`). The `phase` view records no context or plan approval yet, so a phase in those states is not told apart; they come with Build 4's context and plan approvals ([0005](0005-context-plans-and-acceptance.md)) | +| PRJ-R12 | Partly built | A declared phase is withdrawn with a decision for each story it serves, refused `story-undecided` without one and `phase-has-dependents` while another phase depends on it (`crates/baley-core/src/scope/rules.rs`, `judge_withdrawal`), and its approval records `phase.withdrawn`, each story's move or drop and the order without it (`crates/baley-core/src/scope/change_events.rs`, `change_events`). The `phase` view records no context or plan approval, so a phase in those states is not told apart there; whether a phase holds an approved plan in force is the `phase_plan` view's, whose `active` status a withdrawal ends ([0005](0005-context-plans-and-acceptance.md), `crates/baley-core/src/plan/phase_plan.rs`, `PhasePlanProjector`) | | PRJ-R13 | Partly built | `execution-present`, `phase-complete` and `story-shipped`, and `phase-complete` for a story given to a complete phase, are judged over supplied facts per phase (`crates/baley-core/src/scope/rules.rs`, `judge_progress`). In production the facts come from the `phase` view, whose statuses say neither execution nor completion, so every fact is false (`crates/baley/src/scope/read.rs`, `progress_of`) until Builds 5 and 6 record execution and completion, and `phase.undone` is Build 6 ([0011](0011-milestones-landing-undo-pause.md)) | -| PRJ-R14, PRJ-R15, PRJ-R16 | Partly built | A story's truths are revised at any time, including after a phase that committed it started, by refining it again: the session submits the truths with `context-submit` (`crates/baley/src/refine/submit.rs`, `record`) and the owner approves them only with `baley story truths approve` (`crates/baley/src/refine/approve.rs`, `judge` and `record`), which gives each truth its version then, an unchanged truth keeping its version and a changed one taking the next (`crates/baley-core/src/truth/version.rs`, `versions`), and the `truths` view keeps every version (`crates/baley-core/src/truth/view.rs`, `TruthsProjector`). `dispatch-active` is judged at approval (`crates/baley-core/src/truth/approval.rs`, `judge_truth_approval`) over an observation the `phase` view supplies, which says no worker is dispatched until Build 5 records dispatch (`crates/baley/src/refine/order.rs`, `phase_dispatch`). PRJ-R15's plan bound to an older truth version is shown stale by Build 4 T9's `plan` view, which reads the versions the `truths` view keeps, and a completion based on older truths stops applying once Build 5 records completion | +| PRJ-R14, PRJ-R15, PRJ-R16 | Partly built | A story's truths are revised at any time, including after a phase that committed it started, by refining it again: the session submits the truths with `context-submit` (`crates/baley/src/refine/submit.rs`, `record`) and the owner approves them only with `baley story truths approve` (`crates/baley/src/refine/approve.rs`, `judge` and `record`), which gives each truth its version then, an unchanged truth keeping its version and a changed one taking the next (`crates/baley-core/src/truth/version.rs`, `versions`), and the `truths` view keeps every version (`crates/baley-core/src/truth/view.rs`, `TruthsProjector`). `dispatch-active` is judged at approval (`crates/baley-core/src/truth/approval.rs`, `judge_truth_approval`) over an observation the `phase` view supplies, which says no worker is dispatched until Build 5 records dispatch (`crates/baley/src/refine/order.rs`, `phase_dispatch`). PRJ-R15's plan bound to an older truth version is shown not ready by `plan-read` and `baley plan show`, which work out each approved plan's readiness from the versions the `truths` view holds when read, naming each item bound to a version that is not current (`crates/baley/src/planning/read.rs`, `read`), and a completion based on older truths stops applying once Build 5 records completion | | PRJ-R17 | Built | `story edit` records `story.corrected` and keeps every earlier wording (`crates/baley-core/src/scope/change_events.rs`, `change_events`), and an edit of a dropped or excluded story is refused `story-not-served` (`crates/baley-core/src/scope/rules.rs`, `judge_scope_change` and `served`) | -| PRJ-R18 | Partly built | A capture naming a phase the `phase` view does not hold, or holds as withdrawn, is refused `no-such-phase` (`crates/baley/src/mcp/capture.rs`, `record`). A change naming a phase that is not declared or is withdrawn, or a story no story has, is refused `no-such-phase` or `no-such-story` (`crates/baley-core/src/scope/rules.rs`, `judge_scope_change`), and `baley phase show`, `baley story show` and `document` refuse a phase or story the accepted scope lacks the same way (`crates/baley/src/scope/read.rs`, `phase` and `story`, and `crates/baley/src/scope/command.rs`, `read_error`). `no-such-plan` is Build 4 | -| PRJ-R19 | Built | The start and every change are recorded as drafts with their digests and approved by digest at the terminal, with `unknown-draft`, `project-already-started`, `draft-approved` and `stale-draft` judged against the newest draft of the same kind and target (`crates/baley-core/src/scope/approval.rs`, `judge_approval` and `judge_change_approval`, and `crates/baley/src/scope/approve.rs`, `judge` and `judge_change_draft`). `project start` issues the planner's order, and its submission is previewed and approved like any other (`crates/baley/src/mcp/work_order.rs`, `issue_start_order` and `serve_start`). A truth revision is recorded as a `story-truths` draft, previewed with `baley scope preview` and approved by digest with `baley story truths approve` (`crates/baley/src/refine/command.rs`, `approve`), and `baley scope approve` refuses a truth draft `unknown-draft`, naming that command (`crates/baley/src/scope/approve.rs`, `judge`) | -| PRJ-R20 | Partly built | An approved start or `project describe` records `project.described` on the `project` stream (`crates/baley-core/src/scope/change_events.rs`, `change_events`), the `roadmap` view holds the latest (`crates/baley-core/src/scope/roadmap.rs`, `RoadmapProjector`), and the read refinement and planning take is that approved description alone (`crates/baley/src/scope/read.rs`, `description`). `baley scope show` and `document` print it. Refinement is served it: every analyzer order binds it as its `description` input at issue (`crates/baley/src/refine/inputs.rs`, `read`), and the refinement read, `context-intake`, `document` of kind `refinement` and `baley story refinement`, returns it (`crates/baley/src/refine/read.rs`, `read`). Serving it to planning is Build 4 T9 | +| PRJ-R18 | Partly built | A capture naming a phase the `phase` view does not hold, or holds as withdrawn, is refused `no-such-phase` (`crates/baley/src/mcp/capture.rs`, `record`). A change naming a phase that is not declared or is withdrawn, or a story no story has, is refused `no-such-phase` or `no-such-story` (`crates/baley-core/src/scope/rules.rs`, `judge_scope_change`), and `baley phase show`, `baley story show` and `document` refuse a phase or story the accepted scope lacks the same way (`crates/baley/src/scope/read.rs`, `phase` and `story`, and `crates/baley/src/scope/command.rs`, `read_error`). A replacement naming no approved plan in force at its number and digest is refused `no-such-plan` by `plan-replace` and again by `baley plan approve` (`crates/baley-core/src/plan/replace.rs`, `judge_replacement`), and `plan-read` and `baley plan show` refuse a phase the roadmap does not hold `no-such-phase` (`crates/baley/src/planning/read.rs`, `read`) | +| PRJ-R19 | Built | The start and every change are recorded as drafts with their digests and approved by digest at the terminal, with `unknown-draft`, `project-already-started`, `draft-approved` and `stale-draft` judged against the newest draft of the same kind and target (`crates/baley-core/src/scope/approval.rs`, `judge_approval` and `judge_change_approval`, and `crates/baley/src/scope/approve.rs`, `judge` and `judge_change_draft`). `project start` issues the planner's order, and its submission is previewed and approved like any other (`crates/baley/src/mcp/work_order.rs`, `issue_start_order` and `serve_start`). A truth revision is recorded as a `story-truths` draft, previewed with `baley scope preview` and approved by digest with `baley story truths approve` (`crates/baley/src/refine/command.rs`, `approve`), and `baley scope approve` refuses a truth draft `unknown-draft`, naming that command, and a plan draft the same way, naming `baley plan approve` (`crates/baley/src/scope/approve.rs`, `judge`). A `phase plan` that changes a phase's stories records a `phase edit` draft and issues no order, and the approval of that commitment rechecks it and records the stories and the planner's order in one transaction ([ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md), `crates/baley/src/scope/approve.rs`, `recheck` and `record_commitment`) | +| PRJ-R20 | Built | An approved start or `project describe` records `project.described` on the `project` stream (`crates/baley-core/src/scope/change_events.rs`, `change_events`), the `roadmap` view holds the latest (`crates/baley-core/src/scope/roadmap.rs`, `RoadmapProjector`), and the read refinement and planning take is that approved description alone (`crates/baley/src/scope/read.rs`, `description`). `baley scope show` and `document` print it. Refinement is served it: every analyzer order binds it as its `description` input at issue (`crates/baley/src/refine/inputs.rs`, `read`), and the refinement read, `context-intake`, `document` of kind `refinement` and `baley story refinement`, returns it (`crates/baley/src/refine/read.rs`, `read`). Planning is served it too: every planner order binds it as its `description` input at issue (`crates/baley/src/planning/inputs.rs`, `read`) | ## 12. Open questions diff --git a/docs/design/0005-context-plans-and-acceptance.md b/docs/design/0005-context-plans-and-acceptance.md index 1241385a..ae4f55af 100644 --- a/docs/design/0005-context-plans-and-acceptance.md +++ b/docs/design/0005-context-plans-and-acceptance.md @@ -6,7 +6,7 @@ | Design issue | [#134](https://github.com/jcrenshaw-dev/baley/issues/134); build issue [#25](https://github.com/jcrenshaw-dev/baley/issues/25) | | Requirement prefix | PLN | | Applies | [0002: System design](0002-system-design.md) | -| Related | ADRs: [0006](../adr/0006-no-markdown-records.md), [0009](../adr/0009-served-instructions.md), [0017](../adr/0017-stories-and-sprints.md), [0030](../adr/0030-question-rounds.md), [0031](../adr/0031-one-term-per-concept.md), [0037](../adr/0037-plan-recheck-scope.md), [0042](../adr/0042-mocked-boundary-integration-checks.md) · C4 view: components ([0002](0002-system-design.md) Figure 4) | +| Related | ADRs: [0006](../adr/0006-no-markdown-records.md), [0009](../adr/0009-served-instructions.md), [0017](../adr/0017-stories-and-sprints.md), [0030](../adr/0030-question-rounds.md), [0031](../adr/0031-one-term-per-concept.md), [0037](../adr/0037-plan-recheck-scope.md), [0042](../adr/0042-mocked-boundary-integration-checks.md), [0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md) · C4 view: components ([0002](0002-system-design.md) Figure 4) | The current design of this area, and nothing else. Edit it in place when the design changes; git holds the history. It describes the design only, never the work still to do. @@ -100,7 +100,7 @@ In the component view of [0002](0002-system-design.md) (Figure 4) this area is o |---|---|---|---| | Owner | Each round's questions with their recommended answers, and the waiting questions; draft truths; plan previews; checker findings; phase facts at close | Answers (the recommended answer or the owner's own) and deferrals with reasons; approvals by digest; reorders and splits; retrospective notes | Not applicable | | Analyzer (dispatched) | Questions work order: the story, the project description, the roadmap, the code, the question grammar. Drafting work order: the story, its question set with every answer and deferral, the truth form and refusals | Questions (first work order); draft truths (second work order) | `roles.analyzer.*` ([0003](0003-configuration-and-routing.md)) | -| Planner (dispatched) | The phase's goal and stories with their truths, the lease and task grammar, the evidence map grammar, the question grammar, the test derivation rules, the capacity ceiling as a fact; in a revision work order, the draft and every answer and deferral on its set | A typed plan with its evidence map and its questions; a proposed split when needed | `roles.planner.*` | +| Planner (dispatched) | A planning work order on the phase's stream, whose inputs Baley binds as `record` payloads read at issue: `phase`, the phase's number, goal and detail; `stories`, the committed stories in the order given, each with its current truths, each truth with its id, version, form, slot texts and kind, and `human_verify` when set; `description`, the approved project description; `capacity`, the capacity and the phase's current size, only when `planning.phase_capacity` is set; and `approved_items`, the evidence items of the phase's plans in force, so a new plan reuses an item's definition rather than contradicting it. A revision work order binds the same and also `draft`, the draft it revises, and `questions`, that draft's set with every answer and deferral. A retry carries its parent's inputs as they were. The order lists `bal-phase-planner`, which carries the lease and task grammar, the evidence map grammar, the question grammar, the test derivation rules and the capacity ceiling as a fact | A typed plan with its evidence map and its questions; a proposed split when needed | `roles.planner.*` | | Checker (dispatched) | The submitted plan and its stories' versioned truths for round 1; the retained material selected by PLN-R16 and every first-round blocker for round 2 | Findings with severity | `roles.checker.*`, gated by `review.triggers.plan.gate` | | Host session | Work orders to launch; each round's questions; drafts to put to the owner | The analyzer's questions as returned; the owner's answers and deferrals, relayed unchanged; approvals; adjudicated draft truths and checker output | Not applicable | | Baley: this area | Submissions, approvals | Previews, refusals, records | Not applicable | @@ -131,7 +131,7 @@ Every change follows submit (preview and digest), approve (owner, by digest), re ### questions answer - **Inputs:** the set id and one item for each question the owner settles: `{"question":"<id>","act":"take"}` takes the recommended answer, `{"question":"<id>","act":"answer","answer":"<the owner's words>"}` gives the owner's own answer, and `{"question":"<id>","act":"defer","reason":"<the owner's reason>"}` defers it. A session sends them as `questions-answer` on `baley_apply`, with `request_id` (a fresh lowercase UUID, the same on a retry), `set` and `items`. The owner gives them at the terminal as `baley questions answer <set>` with `--take QUESTION`, `--answer QUESTION TEXT` and `--defer QUESTION REASON`, each repeatable, sent as the takes, then the own answers, then the deferrals. The owner and the time are never inputs: Baley records `owner.name`, falling back to git `user.name`, and its own clock, and refuses the call `owner-identity-missing` when neither name is set. The call may settle some or all of the current round, and may defer any open question, waiting or not. -- **Outputs:** every `question.answered` and `question.deferred` of the call recorded in one transaction on the set's stream, all or none, each with the round. A take records the recommended text with `accepted` true and an own answer the owner's words with `accepted` false; no text is compared with the recommendation. The receipt gives the set, the round recorded, the time, and in `now` the round as it stands after the call, in `questions round`'s shape, whose state is `closed` when no question is open. A receipt is never cut into parts, so when that round would pass the 24,576-byte part bound, `now` holds only the state, the round number, the `document` identity to read the round from and the relay sentence. A retry with the same `request_id` is answered from its record; a set that moved between the check and the transaction is answered `ledger-busy` with nothing recorded. When a call relayed over MCP closes a story's set, it also issues the analyzer's drafting work order in the same transaction, its `questions` input holding the set's answers and deferrals with the call's own, and names it in the receipt's `drafting` (PLN-R6); when an analyzer order of the story is pending, no drafting order is issued, so the story keeps one live analyzer order, and the session's next `story refine` follows it. A close at the terminal with `baley questions answer` issues no order, since a work order is issued only to a session ([ADR 0044](../adr/0044-owner-acts-on-the-command-line.md)): its receipt says the set is `closed`, and the session's next `story refine` sees the closed set and issues the drafting order. For a plan draft's set the further outputs are `ready` (the draft may be approved) or, when an answer rejected a recommended answer, the planner's revision work order (PLN-R27); they are Build 4 T9's (section 11), and until then that receipt says only that the set is `closed`. +- **Outputs:** every `question.answered` and `question.deferred` of the call recorded in one transaction on the set's stream, all or none, each with the round. A take records the recommended text with `accepted` true and an own answer the owner's words with `accepted` false; no text is compared with the recommendation. The receipt gives the set, the round recorded, the time, and in `now` the round as it stands after the call, in `questions round`'s shape, whose state is `closed` when no question is open. A receipt is never cut into parts, so when that round would pass the 24,576-byte part bound, `now` holds only the state, the round number, the `document` identity to read the round from and the relay sentence. A retry with the same `request_id` is answered from its record; a set that moved between the check and the transaction is answered `ledger-busy` with nothing recorded. When a call relayed over MCP closes a story's set, it also issues the analyzer's drafting work order in the same transaction, its `questions` input holding the set's answers and deferrals with the call's own, and names it in the receipt's `drafting` (PLN-R6); when an analyzer order of the story is pending, no drafting order is issued, so the story keeps one live analyzer order, and the session's next `story refine` follows it. A close at the terminal with `baley questions answer` issues no order, since a work order is issued only to a session ([ADR 0044](../adr/0044-owner-acts-on-the-command-line.md)): its receipt says the set is `closed`, and the session's next `story refine` sees the closed set and issues the drafting order. A call that closes a plan draft's set with no answer rejecting a recommended answer adds `ready` true to its receipt, on either surface, since the draft may then be approved. One relayed over MCP that closes it with such an answer issues the planner's revision work order in the same transaction, at attempt 1 of a new chain, binding the planning inputs of section 4 for the phase's committed stories, the draft, and its set with every answer and deferral, the call's own included, and names it in the receipt's `revision` (PLN-R27); while a planner order of the phase is pending, none is issued, so the phase keeps one live planner order. A close at the terminal issues no order: its receipt says only that the set is `closed`, and the session's next `phase plan` issues the revision. - **Refusals:** judged in order, and the first refuses the whole call with nothing recorded: the call's grammar, then the set (`no-such-question-set`, then `question-set-abandoned`), then each item in the call's order through `no-such-question`, `question-closed`, `question-not-in-round`, `answer-blank` and `deferral-reason`. Every item is judged against the round as it stood before the call, so an answer to a question that only another answer in the same call would bring into the round is refused `question-not-in-round`. Over MCP a malformed argument or request id is refused `invalid-arguments` before the call's grammar, as for every write ([0012](0012-host-interface.md)). | Code | When | Requirement | @@ -170,29 +170,42 @@ Every change follows submit (preview and digest), approve (owner, by digest), re ### phase plan -- **Inputs:** the phase number; the stories to commit in order (default: the next backlog stories the owner picks). -- **Outputs:** the phase's committed stories recorded through `phase edit` (0004); the planner's work order id. -- **Refusals:** `phase-active` (PLN-R7); `no-such-phase`, `no-such-story` (PRJ-R18); `story-unrefined` when a committed story has no approved truths (PLN-R1); `story-in-phase` when the story is committed to another open phase (PRJ-R4). +- **Inputs:** the phase number and the stories to commit to it, in order (by default the next backlog stories the owner picks). A session sends them as `phase-plan` on `baley_apply`, with `request_id` (a fresh lowercase UUID, the same on a retry), `phase`, `stories` and an optional `instruction`. It is served to a session only and has no command at the terminal, since its only purpose is to issue a work order. The request digest covers the phase and the stories in order, so other stories, or the same ones reordered, under the same request id are `request-id-reuse`. +- **Outputs:** the selection's readiness is judged first (the refusals below), then the call takes one of these paths, in this order ([ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md)): + - **Hand-over.** When the stories are the phase's committed stories in the same order, and the phase's latest planning continuation names that same selection with a planner order that is pending and not yet handed over, that order is handed to the session: `plan.continuation_followed` is recorded on `phase/<n>` naming the edit and the order, and the receipt is the order's receipt as its issue gave it, `work_order`, `request`, `attempt`, `agent`, `model`, `prompt`, `launch` and `recorded_at`, so the session launches it as it would a fresh order. + - Otherwise, while a planner order of the phase is pending, the call is refused `planner-order-pending`, below. + - **Commitment draft.** When the stories differ from the phase's committed stories, in content or only in order, the `phase edit` of the phase's `stories` is recorded as a draft with a planning continuation, in one transaction: `scope.submitted` of kind `phase-edit` and `plan.continuation` naming the phase, the selection, the edit's digest and the id the planner order will have ([0004](0004-starting-a-project-and-changing-scope.md) `phase edit`). No order is issued. The receipt gives the `digest`, the `kind`, `recorded_at`, the phase, the stories, and in `preview` and `approve` the commands `baley scope preview <digest>` and `baley scope approve <digest>`. The owner's approval of that digest at the terminal rechecks the selection, then records the stories and the planner order together and prints the order's id ([0004](0004-starting-a-project-and-changing-scope.md) `scope approve`); the session's next `phase plan` with the same stories hands it over. + - **Revision.** When the stories are unchanged and the phase's current plan draft's question set closed with an answer that rejected a recommended answer, the planner's revision work order for that draft is issued, binding the draft and its set with every answer and deferral beside the planning inputs (PLN-R27). This is how a set closed at the terminal, which issues no order, gets its revision. + - **Planning.** Otherwise a planning work order is issued for the committed stories. + + A planning or revision order is recorded as `work_order.issued` on `phase/<n>` with role `planner`, subject `phase/<n>`, at attempt 1 of a new chain, under the planner's route at the policy step's version, listing `bal-phase-planner`, with the inputs of section 4 read at issue; its receipt is the order's, as a story's analyzer order gives it. A phase has one live planner order: the issue declares that no planner order of the phase is pending, so one recorded since the check leaves the call `ledger-busy` with nothing recorded. Every recording confirms that what the check read has not moved, so a phase made active, a story's truths or commitment changed, or a plan approved since leaves the call `ledger-busy` with nothing recorded. +- **Refusals:** judged in order, each recording nothing: the arguments (`invalid-arguments`, then `unknown-instruction` or `instruction-unavailable` for `instruction`); then the selection's readiness, `phase-active` while another phase is active, naming the lowest such phase (PLN-R7), `no-such-phase` for a phase the roadmap does not hold or a withdrawn one, `no-such-story` for a story the roadmap does not hold or a dropped one (PRJ-R18), `story-unrefined` for a story with no approved truths in the `truths` view (PLN-R1), and `story-in-phase` for a story another phase commits (PRJ-R4), the last three naming the first selected story at fault and `story-in-phase` also that phase; then `planner-order-pending` while a planner order of the phase is pending, naming it in `details.work_order`, since a phase has one live planner order: the session reads that order with `document` and launches it, or fails it with `work-order-fail` and retries it with `work-order-retry`. A commitment draft's `phase edit` is then judged against accepted scope as [0004](0004-starting-a-project-and-changing-scope.md) judges any `phase edit`, its refusals at slot `stories`. A hand-over of an order that failed or was answered since is refused `work-order-not-pending`, naming its state, and one whose continuation was followed or replaced since is refused `planner-order-pending`. `unknown-model` refuses an order whose route names a model the host does not accept, with no order recorded. ### plan submit -- **Inputs:** the typed plan (PLN-R11) with its evidence map (PLN-R12) and its questions (PLN-R23). -- **Outputs:** the checker's work order when the plan gate is on; then the preview, the checker's findings, the plan's size and the phase's size against capacity, and the digest. With the preview Baley records `questions.opened` for the draft and gives the set id and round 1; a draft with no questions has an empty set, closed at once (PLN-R27). A new submit makes the draft it replaces stale, so approving that draft is refused `stale-draft`, and abandons that draft's set (PLN-R15, PLN-R25). The earlier draft keeps its record, and the plan and truth snapshots a check needs from it stay. For round 2, `plan submit` records `plan.check_issued` on `phase/<n>` before returning the work order. It binds the first check, the original and revised plan digests, the truth versions, the resolved scope, the material references and the policy version used to select the scope. Baley resolves the setting when it creates that work order. A retry must keep the binding from `plan.check_issued`. -- **Refusals:** every code of PLN-R13; `typed-content` (PLN-R11), also for a question's id, question or recommended answer over 4,096 bytes and a `depends_on` naming an id twice; `question-id`, `question-blank`, `question-dependency`, `question-cycle` (PLN-R23), each naming the question by its position and id; `over-capacity` (PLN-R9); `phase-not-active` (PLN-R7); `material-unavailable` when the retained draft, revision, truths or required comparison material cannot be read or does not match the work-order binding; `recheck-truths-changed` when the re-check's truths differ from those used by round 1 (PLN-R16). The evidence-map refusal `truth-version-mismatch` keeps its PLN-R13 meaning. After the one revision and re-check, remaining blockers go to the owner under the configured gate (PLN-R16). +- **Inputs:** the typed plan (PLN-R11) with its evidence map (PLN-R12) and its questions (PLN-R23), and the planner order it answers. A session sends them as `plan-submit` on `baley_apply`, with `request_id`, `work_order` and `plan`, the plan exactly as the planner returned it. It is served to a session only, since a plan comes from the planner's work. +- **Outputs:** the checker's work order when the plan gate is on; then the preview, the checker's findings, the plan's size and the phase's size against capacity, and the digest. Baley records, in one transaction: the draft's body, the plan as submitted with `kind` `plan` added, as a `record` payload, and one `scope.submitted` of kind `plan` with target `phase/<n>` on the `project` stream ([ADR 0043](../adr/0043-submissions-recorded-as-drafts.md)), which marks the planner order answered; `questions.abandoned` with cause `draft-replaced` for the set of the phase's earlier draft, when that set is held and not yet abandoned (PLN-R25); and `questions.opened` on `phase/<n>` for the draft's `questions`, an empty set closed at once (PLN-R27). The digest is taken over the body alone, so it names the plan and nothing the call carried. A phase holds one plan draft at a time: every plan draft of a phase, a replacement's included, is filed under `phase/<n>`, so a new submit makes the draft it replaces stale, and approving that draft is refused `stale-draft` (PLN-R15). The earlier draft keeps its record, and the plan and truth snapshots a check needs from it stay. Every call records, so the same plan submitted again is the newest draft again with a new set; only a retry of the same request is answered from its record. The receipt gives the `digest`, `kind`, `phase`, `stories`, `size` (the plan's tasks), `phase_size` (the phase's size now), `reaching` (the size the phase reaches with the plan approved), `capacity` (null when none is set), the set's id in `set`, `recorded_at`, round 1 in `now` in `questions round`'s shape, and `preview`, the draft's submission, or, when the receipt would pass the 24,576-byte part bound, the `document` read of the draft, since a receipt is never cut into parts. The owner previews the draft at the terminal with `baley scope preview <digest>`, which names `baley plan approve <digest>`. For round 2, `plan submit` records `plan.check_issued` on `phase/<n>` before returning the work order. It binds the first check, the original and revised plan digests, the truth versions, the resolved scope, the material references and the policy version used to select the scope. Baley resolves the setting when it creates that work order. A retry must keep the binding from `plan.check_issued`. +- **Refusals:** judged in order, each recording nothing: the arguments (`invalid-arguments`, also for a `work_order` that is not a lowercase UUID); `no-such-work-order` when this project holds no order with that id; `typed-content` when the plan's `phase` cannot be read, since the order is judged against that phase; `wrong-work-order` when the order is not a planner order of the plan's phase or has failed, while a pending or answered one passes, so a resubmission under the same order is the newest draft; `phase-not-active` when a phase other than the plan's is active, naming it (PLN-R7). `phase-not-active` means that a different phase of the project is active; it is never refused because the plan's own phase has no approved plan yet, so a phase's first plan can be submitted. Then the plan judged whole: every code of PLN-R13; `typed-content` (PLN-R11), also for a question's id, question or recommended answer over 4,096 bytes and a `depends_on` naming an id twice; `question-id`, `question-blank`, `question-dependency`, `question-cycle` (PLN-R23), each naming the question by its position and id; and `over-capacity` last (PLN-R9), naming every story the plan serves and the size the phase would reach, while with no `planning.phase_capacity` set no plan is refused for size. Then the re-check's `material-unavailable` when the retained draft, revision, truths or required comparison material cannot be read or does not match the work-order binding, and `recheck-truths-changed` when the re-check's truths differ from those used by round 1 (PLN-R16). The evidence-map refusal `truth-version-mismatch` keeps its PLN-R13 meaning. A phase made active, a plan approved or a truth revised since the check leaves the call `ledger-busy` with nothing recorded. After the one revision and re-check, remaining blockers go to the owner under the configured gate (PLN-R16). -Baley recognizes a checker revision from the draft awaiting the one revision granted by its first `plan.checked` result. The caller supplies the revised plan, not a first-check reference; Baley selects that reference from the draft's check state and validates all retained material against it and the revision. A refused re-check leaves this state intact, so another submit in the same draft lineage remains a revision. The draft survives a server restart, as every draft does ([ADR 0043](../adr/0043-submissions-recorded-as-drafts.md)); how a draft whose re-check was refused leaves that state is an open question for Build 4 in section 12. +The plan checker's work order and the risk check at submit ([0009](0009-risk.md)) sit between the check and the recording, against the digest the recording takes, so the preview follows them. That order is not settled: the checker's revision order for a first-round blocker is issued before the recording, while the planner order the draft answers is marked answered only by the recording's `scope.submitted`, and a phase has one live planner order (`phase plan`). How the two fit is an open question for Build 4 T10 in section 12. Baley recognizes a checker revision from the draft awaiting the one revision granted by its first `plan.checked` result. The caller supplies the revised plan, not a first-check reference; Baley selects that reference from the draft's check state and validates all retained material against it and the revision. A refused re-check leaves this state intact, so another submit in the same draft lineage remains a revision. The draft survives a server restart, as every draft does ([ADR 0043](../adr/0043-submissions-recorded-as-drafts.md)); how a draft whose re-check was refused leaves that state is an open question for Build 4 in section 12. ### plan approve -- **Inputs:** the digest, owner, time. -- **Outputs:** `plan.approved` with the next plan number; the evidence map and the question set id recorded; the phase's size updated. -- **Refusals:** `stale-draft`, `unknown-draft` (PLN-R15); `question-open` while a question of the draft's set is open (PLN-R26); `answer-not-applied` when an answer on the draft's set rejected a recommended answer (PLN-R27). +- **Inputs:** the draft's digest alone, as the submit's receipt writes it: 64 lowercase hexadecimal characters, judged before the ledger is read. It is given only at the terminal, as `baley plan approve <digest>`, and never over MCP ([ADR 0044](../adr/0044-owner-acts-on-the-command-line.md)). The owner and the time are never inputs: Baley records `owner.name`, falling back to git `user.name`, and its own clock, and refuses the call `owner-identity-missing` when neither name is set. +- **Outputs:** one `plan.approved` on `phase/<n>` with actor `owner`, numbered one more than the highest plan number ever assigned in the phase, replaced plans included, and 1 for the first (PLN-R14), carrying the phase, the number, the digest, the stories, the size, the suite from `workflow.test_command` or null when none is set, the question set's id, the evidence map inline exactly as submitted, the draft body's reference, the owner and the time (section 6). For a replacement draft, `plan.replaced` in the same transaction. The phase's size and each served story's size change with it, in the `phase_plan` and `backlog` views. The receipt gives `kind`, `digest`, `phase`, `plan`, `stories`, `size`, `suite`, `set`, `owner`, `at` and, for a replacement, `replaces`, naming the plan replaced and its digest; with no suite set it adds `notice`, saying the plan was approved with no suite and cannot be admitted to execution until `workflow.test_command` is set ([0006](0006-execution.md)). The command prints `approved plan <n> of phase <p> as <owner> at <at>`, then the digest, the stories, the size and the suite, or `suite: none` with the same reason, and for a replacement the plan it replaced, exit 0. +- **Refusals:** the first step reads and judges outside any transaction, in this order, each refusal at slot `digest` and recording nothing: `unknown-draft` when no recorded plan draft has the digest; `stale-draft` when a newer plan draft of the phase was submitted, naming the first differing path, such as `tasks[0].title` (PLN-R15); `draft-approved` when the draft was already approved after its latest submission, naming that approval's owner and time; `question-open` naming each question of the draft's set neither answered nor deferred (PLN-R26); `answer-not-applied` naming each question whose answer rejected its recommendation (PLN-R27), a deferral never counting as one; then `phase-not-active` when a phase other than the plan's is active, as at submit, so two phases never become active together (PLN-R7). For a replacement draft, `no-such-plan` and `admitted-plan` are judged again over the phase as it stands, at slot `replaces`. Then the plan is judged again by the plan judge against the phase as it stands now, under the capacity the approval's policy sets, with every refusal of `plan submit`'s plan judgement, `over-capacity` among them, so an approval after a truth was revised or another plan approved is refused what a submit now would be. A first step judged under settings that changed before the policy step is run again under the policy the approval records. The second step confirms inside its transaction that the draft, its `scope.submitted`, the newest plan draft of the phase and every document the first step read are unchanged and that no approval of the digest landed since, and answers `ledger-busy` with nothing recorded otherwise. Run outside a checkout of a project it is refused `not-a-project`, and for a project the ledger does not list, `project-not-in-ledger`. ### plan replace -- **Inputs:** the plan number, the digest being replaced, the new plan. -- **Outputs:** as `plan submit` then `plan approve`, recording `plan.replaced`. -- **Refusals:** as `plan submit`; `admitted-plan` (PLN-R14); `no-such-plan` (PRJ-R18). +- **Inputs:** the plan number, the digest that plan was approved at, and the new plan. A session sends them as `plan-replace` on `baley_apply`, with `request_id`, `work_order`, `plan`, and `replaces` holding `plan` and `digest`; a `replaces.digest` that is not 64 lowercase hexadecimal characters is `invalid-arguments` at slot `replaces`. +- **Outputs:** as `plan submit`, the draft's body also naming in `replaces` the plan and digest it replaces, so its digest is never the plain draft's. It is filed on the phase's one draft line, so it and a new plan's draft make each other stale. It is approved with `baley plan approve`, which records `plan.approved` with the next number and `plan.replaced` naming the phase, the old number, the old digest and the new one, the owner and the time, in one transaction. The replaced plan keeps its number, its record and its evidence map, marked replaced and readable with `plan read`; the number is never assigned again (PLN-R14). The new plan is judged as the phase would stand once the old one is gone: the old plan's tasks off the phase's size and its evidence items off the approved items. +- **Refusals:** as `plan submit`, with, after `phase-not-active`, `no-such-plan` when no plan of the phase is in force at that number and digest (PRJ-R18), then `admitted-plan` when it is admitted to execution (PLN-R14), judged over an observation execution admission supplies ([0006](0006-execution.md)), which reads false until admission is recorded (section 11). + +### plan read + +- **Inputs:** the phase number. A session reads it as `plan-read` on `baley_query`, with `phase` and an optional `part`; the owner prints it with `baley plan show <phase>`. Both read through the same function, so the session and the owner see the same plans. +- **Outputs:** read only; nothing is recorded. The phase and every plan ever approved in it, in plan-number order, replaced plans included, each with its number, the approved digest, its stories, its size, its suite or null, its question set's id in `set`, the owner and the time of its approval, its `state`, `approved` or `replaced`, `replaced_by`, the replacing draft's digest or null, its evidence items whole as approved, each check's truth version and `level` among them, and its readiness: `ready`, true when every item names its truth's current version, and `not_ready`, the ids of the items bound to a version that is not current, worked out from the `truths` view when read and never stored (PLN-R4). Only the views an approval writes are read, so a draft's map never appears. An answer too long for one part is cut into parts as every `document` read is. `document` serves the same read for the identity `{"kind":"phase","phase":<n>}`, and one approved plan for `{"kind":"plan","phase":<n>,"plan":<n>}`, refused `no-such-plan` for a number never approved in the phase. The terminal prints each plan as `plan <n> at <digest>: <state>`, the state `replaced by <digest>` for a replaced one, then `ready` or `not ready:` with those items, then its stories, its size and its suite or `suite: none`, then one line per item with its story, truth, version and kind, and a check's level, every recorded text escaped; a phase with no approved plan prints one line saying so. +- **Refusals:** `no-such-phase` for a phase the roadmap does not hold, echoing none of its number; over MCP, a malformed argument is `invalid-arguments`. ### phase close @@ -219,22 +232,37 @@ Each of a truth's texts, `id`, `form`, `trigger`, `observer`, `verb`, `outcome`, `story.refined` carries the story, the id of the question set its truths were drafted from, the submission digest, `owner` and `at`, and the story's whole truth list inline, each truth with its version, so a purge of the draft's body removes no truth in force; the answers and deferrals stay on that set's own records. It replaces the story's current truths in the `truths` view and sets the truth count of the story's `roadmap` and `backlog` entries to the length of its truth list. A truth's status (`pending`, `met`, `concerns`, `unmet`, `waived`) is derived by [0007](0007-verification.md), never stored. -### plan (payload of `plan.approved`, `phase/<n>` stream) +### plan draft (body of `scope.submitted` of kind `plan`, `project` stream) | Field | Type | Meaning | |---|---|---| -| `phase`, `plan` | integers | The phase and the plan number | +| `phase` | integer | The phase the plan is for | | `stories` | list of story ids | The stories it serves | | `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` (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 | +| `kind` | `plan` | Added by Baley | +| `replaces` | `{plan, digest}`, or absent | Added by Baley for a replacement: the number of the plan in force it replaces and the digest that plan was approved at | + +The planner submits every member above but the last two, and Baley adds those. The draft's digest is the SHA-256 of this body's canonical JSON and nothing else. Baley writes `plan`, `question_set`, `size` and `suite` when the plan is approved, so a submitted plan carrying any of them is refused `typed-content` (PLN-R11). The body is stored as a `record` payload that `scope.submitted` attaches, filed under the target `phase/<n>`, so a phase holds one plan draft at a time. + +### plan (payload of `plan.approved`, `phase/<n>` stream) + +| Field | Type | Meaning | +|---|---|---| +| `phase`, `plan` | integers | The phase and the plan number, one more than the highest ever assigned in the phase | +| `digest` | digest | The approved draft's digest | +| `stories` | list of story ids | The stories it serves, in the plan's order | | `size` | integer | The number of tasks | +| `suite` | command, or null | The suite Baley runs at close, from `workflow.test_command` at approval; null when none is set | +| `question_set` | set id | The set its questions were put to the owner in; the answers and deferrals are that set's records | +| `evidence_map` | list of items | The plan's evidence items, inline exactly as submitted | +| `body` | payload reference | The draft's `record` payload, which holds the whole plan; never its text | +| `owner`, `at` | owner, time | Who approved it and when: `owner.name`, falling back to git `user.name`, and Baley's clock | -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). +The evidence map is inline and the plan text is not: the `plan`, `evidence_map` and `phase_plan` views rebuild from the events alone, and a purge of the draft's body removes no map or binding in force, while the plan text stays an attachment ([0001](0001-evidence-ledger.md)). ### evidence item @@ -326,18 +354,25 @@ Baley records it in the same transaction as the later set's `questions.opened` o The work order selects the full-plan input or the delta and blocker input from the retained material. Both carry the same versioned truths and every first-round blocker in round 2. The work order id, plan digest, scope, previous-check reference, truth versions, scope policy version and material references are copied from the issued work order, using `plan.check_issued` for round 2, never supplied by the checker or reconstructed from current files. Plan and truth snapshots and all generated checker input, including the delta, use `record` references, kept for the life of the project unless purged (0001). The event envelope records the policy of the command that appends the result; `scope_policy_version` identifies the policy that selected the work order's scope. -### plan.replaced (event), phase.retrospective (event) +### plan.replaced, plan.continuation, plan.continuation_followed (events, `phase/<n>` stream), phase.retrospective (event) + +`plan.replaced`: `phase`, `plan`, the number of the plan replaced, `old_digest` and `new_digest`, the digests it and its replacement were approved at, `owner` and `at`; recorded in the same transaction as the replacement's `plan.approved`. -`plan.replaced`: plan number, old digest, new digest, owner, time. `phase.retrospective`: phase number, the owner's notes, the facts shown, owner, time. +`plan.continuation`: `phase`, `stories`, the selection in order, `edit`, the digest of the `phase edit` draft recorded with it, and `work_order`, the id the planner order its approval issues will have. `phase plan` records it with a commitment draft, and the approval of that draft issues the order under that id ([ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md)). + +`plan.continuation_followed`: `phase`, `edit` and `work_order`, recorded when `phase plan` hands that order to a session, so it is handed over once. + +`phase.retrospective`: phase number, the owner's notes, the facts shown, owner, time. ### Views | View | Key | Content | |---|---|---| -| `backlog` | project | Stories in priority order, each with its latest question set id, the refined marker (the set its latest `story.refined` names), the truth count of that refinement, its size when planned and the phase it is committed to. Its refinement state, unrefined, questions open with the current round, drafting or refined, is worked out when read from the latest set's `questions` document and the marker, never stored | +| `backlog` | project | Stories in priority order, each with its latest question set id, the refined marker (the set its latest `story.refined` names), the truth count of that refinement, the phase it is committed to, the approved plans in force serving it, each with its phase, number and size, and its size, those plans' tasks summed, or null when none serves it. `plan.approved` adds a plan to every story it serves and `plan.replaced` removes it. Its refinement state, unrefined, questions open with the current round, drafting or refined, is worked out when read from the latest set's `questions` document and the marker, never stored | | `truths` | project, story | The story's current truths in submitted order, each with its version, and the set, digest, sequence and time of the latest `story.refined`; and every version each truth id ever had, oldest first, each kept once with the sequence of the `story.refined` that first carried it | -| `phase_plan` | project, phase | Goal, committed stories, plans with sizes, capacity, size, tasks done, definition of done state, velocity of closed phases. It is separate from the `phase` view of [0004](0004-starting-a-project-and-changing-scope.md), which serves Hardin the phase's context, plans, execution and completion state | -| `plan` | project, phase, plan | The approved plan, its evidence map, its question set, and its completed checks with each round's scope, previous-check reference and material references | +| `phase_plan` | project, phase; indexed by status, then phase | The phase's planning state: its approved plans in number order, each with its digest, stories, size, `state` (`in-force` or `replaced`) and the replacing digest; the highest plan number ever assigned, replaced plans included, which the next approval numbers past; its size, the tasks of the plans in force, each plan counted once however many stories it serves; whether it was withdrawn; its status, `active` while a plan is in force and it is not withdrawn and `inactive` otherwise, worked out on every change; its one unapproved plan draft with that draft's set, which an approval of it clears; and its latest planning continuation with whether it was followed. It projects `plan.approved`, `plan.replaced`, `phase.withdrawn`, a plan draft's `questions.opened`, `plan.continuation` and `plan.continuation_followed`, and refuses a plan number not above the highest. It is separate from the `phase` view of [0004](0004-starting-a-project-and-changing-scope.md). Tasks done, the definition of done's state and the velocity of closed phases come from execution and completion ([0006](0006-execution.md), [0007](0007-verification.md)) | +| `plan` | project, phase, plan | Each approved plan's binding: its digest, stories, size, suite, question set, the hash of its draft's body, owner and time, and its `state`, `approved` or `replaced`, with the replacing draft's digest. Only `plan.approved` and `plan.replaced` reach it, so a draft never appears, and a replacement keeps every other field, so a replaced plan's binding stays readable. The checker's completed rounds, each with its scope, previous-check reference and material references, come from `plan.checked` (PLN-R16) | +| `evidence_map` | project, phase, plan | Each approved plan's evidence items exactly as approved, with their truth versions and each check's `level`, and its `state`, `approved` or `replaced`. Only `plan.approved` and `plan.replaced` reach it, so a draft's map never appears, and a replaced plan's map stays. Whether a plan's items still name their truths' current versions is worked out when read (`plan read`), never stored | | `questions` | project, set | The set's facts and records only: its subject, the stream it was opened on, the questions as submitted, each answer with whether it took the recommendation, its round, owner and time, each deferral with its reason, round, owner and time, and its abandonment with the cause and time. Whether the set is open, closed or abandoned, each question's state (waiting and on what, in the current round, answered, deferred) and the current round are computed when the set is read, from the questions in submitted order and these records, never stored | ## 7. States @@ -363,7 +398,7 @@ stateDiagram-v2 ```mermaid stateDiagram-v2 - [*] --> Draft: plan submit + [*] --> Draft: plan submit or plan replace Draft --> Checking: plan gate on Checking --> Draft: first-round blocker, one revision Draft --> Draft: re-check refused, revision still pending @@ -373,17 +408,17 @@ stateDiagram-v2 Previewed --> Answering: questions.opened, a question open Previewed --> Ready: questions.opened, no question Answering --> Answering: a round answered, a question still open - Answering --> Ready: no question open, no recommendation rejected + Answering --> Ready: no question open, no recommendation rejected, the receipt says ready Answering --> Revising: no question open, a recommendation rejected - Ready --> Approved: plan approve + Ready --> Approved: baley plan approve, plan.approved with the next number Revising --> Discarded: the revision submitted as a new draft Answering --> Discarded: replaced by a new submit Ready --> Discarded: replaced by a new submit - Approved --> Replaced: plan replace (not admitted) + Approved --> Replaced: a replacement approved, plan.replaced (not admitted) Approved --> Admitted: execution admits it (0006) ``` -*Figure 2. States of a plan. Every draft is recorded in the ledger when it is submitted, and Discarded means a newer submission replaced it, so it can no longer be approved; its record stays ([ADR 0043](../adr/0043-submissions-recorded-as-drafts.md)). The end of a session changes no state. Previewed is the moment Baley gives the preview and records the draft's question set. `plan approve` is refused in Answering (`question-open`) and in Revising (`answer-not-applied`). Admitted and later states belong to [0006](0006-execution.md). Each check is bound to its submitted draft; the second check uses PLN-R16's recorded scope.* +*Figure 2. States of a plan. Every draft is recorded in the ledger when it is submitted, and Discarded means a newer submission replaced it, so it can no longer be approved; its record stays ([ADR 0043](../adr/0043-submissions-recorded-as-drafts.md)). A phase holds one plan draft: every plan draft of the phase, a replacement's included, is filed under `phase/<n>`, so a new submit discards the draft before it and abandons that draft's set with cause `draft-replaced`. The end of a session changes no state. Previewed is the moment Baley records the draft with its question set and gives the preview, in the submit's one transaction. Revising is a set closed with an answer that rejected a recommended answer: the planner's revision order is issued by the closing `questions-answer` over MCP, or, after a close at the terminal, by the session's next `phase plan`. `baley plan approve` is refused in Answering (`question-open`), in Revising (`answer-not-applied`), once Discarded (`stale-draft`), and in any state while a phase other than the plan's is active (`phase-not-active`); it also judges the plan again against the phase as it stands. A replaced plan keeps its number, its record and its evidence map, read with `plan read`, and its replacement gets the next number. Admitted and later states belong to [0006](0006-execution.md). Each check is bound to its submitted draft; the second check uses PLN-R16's recorded scope.* ```mermaid stateDiagram-v2 @@ -391,11 +426,14 @@ stateDiagram-v2 Planned --> Active: first plan.approved Active --> Active: plan.approved, plan.replaced, execution Active --> Done: definition of done holds - Done --> Closed: owner approves completion; phase.retrospective optional + Done --> Closed: owner approves completion, phase.retrospective optional Active --> Planned: every plan replaced away + Planned --> Withdrawn: phase.withdrawn + Active --> Withdrawn: phase.withdrawn + Withdrawn --> [*] ``` -*Figure 3. States of a phase as this area sees them. The phase lifecycle as a whole is [0004](0004-starting-a-project-and-changing-scope.md) Figure 1.* +*Figure 3. States of a phase as this area sees them. Active is the `phase_plan` view's status `active`: a phase with an approved plan in force that is not withdrawn, worked out from the records on every change and never chosen by a caller. One phase is active per project (PLN-R7). While a phase is Active, `phase plan` for any other phase is refused `phase-active`, and `plan submit` and `plan approve` of a plan for any other phase are refused `phase-not-active`, each naming the active phase. `phase-not-active` means that a different phase is active, never that the plan's own phase has no plan yet: a phase in Planned can have its first plan submitted and approved while no other phase is active, and that approval makes it Active. A phase stays Active until it is complete or withdrawn, so no other phase is planned meanwhile. The phase lifecycle as a whole is [0004](0004-starting-a-project-and-changing-scope.md) Figure 1.* ```mermaid stateDiagram-v2 @@ -488,72 +526,89 @@ sequenceDiagram participant C as Checker participant L as Ledger O->>H: plan phase N with stories S1, S2 - H->>B: phase plan N [S1, S2] - alt another phase active - B-->>H: phase-active - else a story unrefined - B-->>H: story-unrefined - else - B->>L: phase.declared (edit) with committed stories - B-->>H: planner work order + H->>B: phase-plan N [S1, S2] + break another phase active, or a story unrefined or in another phase + B-->>H: phase-active, story-unrefined or story-in-phase, naming it + end + alt S1, S2 differ from N's committed stories + break a planner order of N pending + B-->>H: planner-order-pending, naming it + end + B->>L: scope.submitted of kind phase-edit and plan.continuation + B-->>H: the edit's digest with the preview and approve commands, no work order + H->>O: the digest + O->>B: baley scope preview, then baley scope approve, with the digest + B->>B: recheck the selection's readiness and the phase's pending planner order + B->>L: phase.declared (edit), scope.approved and work_order.issued, the planner order + B-->>O: receipt naming the planner order + H->>B: phase-plan N [S1, S2] again + Note over H,B: readiness is judged again, then the hand-over comes before any pending-order refusal + B->>L: plan.continuation_followed + B-->>H: the planner order the approval issued + else S1, S2 are N's committed stories, no hand-over due + break a planner order of N pending + B-->>H: planner-order-pending, naming it + end + B->>L: work_order.issued, the planning order + B-->>H: the planner order + end + H->>P: launch + P-->>H: plan with evidence map and questions + H->>B: plan-submit naming the order + break the order, the phase or the plan refused + B-->>H: wrong-work-order, phase-not-active, over-capacity or a refusal naming the item + end + opt plan gate on + B-->>H: checker work order with the full plan and versioned truths + H->>C: launch + C-->>H: findings + H->>B: checker findings for the issued work order + B->>L: plan.checked with scope and material references + opt blocker, first round + B-->>H: planner work order for one revision + H->>P: launch revision + P-->>H: revised plan + H->>B: plan-submit revision + B->>B: select scope, retain and validate material against the first check + break retained input unavailable or truth versions changed + B-->>H: material-unavailable or recheck-truths-changed + Note over H,B: revision still pending, exit remains open for Build 4 + end + B->>L: plan.check_issued with work order, scope, policy and material binding + B-->>H: round-2 checker work order from the recorded binding + H->>C: launch re-check + C-->>H: findings + H->>B: checker findings for the issued work order + B->>L: plan.checked with the recorded binding and findings + end + end + B->>L: scope.submitted of kind plan, questions.abandoned for the earlier draft's set, questions.opened + B-->>H: preview, findings, size and phase size against capacity, set id, round 1, digest + H->>O: preview + opt the draft has questions + H->>O: the rounds of Figure 8, until no question is open + end + alt an answer rejected a recommended answer + B->>L: the closing answers and work_order.issued, the planner revision order + B-->>H: revision, the order with the draft and every answer and deferral H->>P: launch - P-->>H: plan with evidence map - H->>B: plan submit - alt map or grammar refused - B-->>H: refusal naming the item - else over capacity - B-->>H: over-capacity, naming every story the plan serves and the size the phase would reach + P-->>H: revised plan + H->>B: plan-submit, a new draft, from the submit above + else no recommendation rejected + B-->>H: ready + H->>O: the digest + O->>B: baley scope preview, then baley plan approve, with the digest + alt a question open, a recommendation rejected, or another phase active + B-->>O: question-open, answer-not-applied or phase-not-active else - alt plan gate on - B-->>H: checker work order with the full plan and versioned truths - H->>C: launch - C-->>H: findings - H->>B: checker findings for the issued work order - B->>L: plan.checked with scope and material references - opt blocker, first round - B-->>H: planner work order for one revision - H->>P: launch revision - P-->>H: revised plan - H->>B: plan submit revision - B->>B: select scope, retain and validate material against the first check - break retained input unavailable or truth versions changed - B-->>H: material-unavailable or recheck-truths-changed - Note over H,B: revision still pending, exit remains open for Build 4 - end - B->>L: plan.check_issued with work order, scope, policy and material binding - B-->>H: round-2 checker work order from the recorded binding - H->>C: launch re-check - C-->>H: findings - H->>B: checker findings for the issued work order - B->>L: plan.checked with the recorded binding and findings - end - end - B->>L: questions.opened for the draft - B-->>H: preview, findings, size and capacity, questions, set id, digest - H->>O: preview - opt the draft has questions - H->>O: the rounds of Figure 8, until no question is open - end - alt an answer rejected a recommended answer - B-->>H: planner revision work order with the draft and every answer and deferral - H->>P: launch - P-->>H: revised plan - H->>B: plan submit, a new draft, from the top of this branch - else - O->>H: yes - H->>B: plan approve - alt a question open - B-->>H: question-open, naming each - else - B->>L: plan.approved, evidence map, question set id, phase size - B-->>H: receipt - end - end + B->>B: judge the plan again against the phase as it stands + B->>L: plan.approved with the next number, the evidence map inline, the set id, the size and the suite + B-->>O: receipt with the plan number end end ``` -*Figure 5. Phase planning and a plan's submission, check, questions and approval. A revised draft is checked and previewed again and opens its own question set. Approving a draft whose set holds a rejected recommendation is refused with `answer-not-applied`. Round 2 reads the full revision or its changes, as selected by PLN-R16, and both scopes check every first-round blocker. Missing or mismatched retained inputs refuse the re-check before dispatch.* +*Figure 5. Phase planning and a plan's submission, check, questions and approval. A `phase-plan` that changes the phase's stories, a reorder included, only drafts the `phase edit` with its continuation; the owner's approval at the terminal rechecks the selection and records the stories and the planner order in one transaction, and the session's next `phase-plan` with the same stories hands that order over once ([ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md)). Every `phase-plan` is judged for readiness first; the hand-over is judged next, so the call that collects the approval's order is never refused for that order, and `planner-order-pending` refuses only a call with no hand-over due. An unchanged selection issues its order at once, the revision order when the current draft's set closed on a rejected recommendation. A revised draft is checked and previewed again and opens its own question set, abandoning the set of the draft it replaces. The revision order is issued by the closing `questions-answer` over MCP; after a close at the terminal, which issues no order, the session's next `phase-plan` issues it. A replacement goes the same way through `plan-replace`, and its approval also records `plan.replaced`. Every refusal records nothing. Round 2 reads the full revision or its changes, as selected by PLN-R16, and both scopes check every first-round blocker. Missing or mismatched retained inputs refuse the re-check before dispatch. The plan gate's path draws the checker's revision order before the draft's `scope.submitted`, which is what answers the planner order the draft came from, so the phase's one live planner order is not yet settled there; section 12 holds that ordering open for Build 4 T10.* ```mermaid sequenceDiagram @@ -597,21 +652,21 @@ sequenceDiagram B-->>H: typed-content / no-such-question-set / question-set-abandoned / no-such-question / question-closed / question-not-in-round / answer-blank / deferral-reason else B->>L: question.answered, question.deferred, in one transaction - B-->>H: receipt with the round recorded and the round as it now stands, or closed + B-->>H: receipt with the round recorded and the round as it now stands, or closed with drafting, ready or revision end end ``` -*Figure 8. Putting a question set to the owner in rounds, for a story's refinement and for a plan draft alike. The host session reads the round with `document`, relays questions and answers through `questions-answer` and decides nothing; the owner can do the same at the terminal with `baley questions round` and `baley questions answer`. The owner may answer part of a round and may defer a waiting question. When a call over MCP closes a story's set, its receipt names the analyzer's drafting work order in `drafting` (Figure 4). A plan draft's set is to yield `ready` or the planner's revision work order, which are Build 4 T9's; until then its receipt says only that the set is closed.* +*Figure 8. Putting a question set to the owner in rounds, for a story's refinement and for a plan draft alike. The host session reads the round with `document`, relays questions and answers through `questions-answer` and decides nothing; the owner can do the same at the terminal with `baley questions round` and `baley questions answer`. The owner may answer part of a round and may defer a waiting question. When a call over MCP closes a story's set, its receipt names the analyzer's drafting work order in `drafting` (Figure 4). When a call closes a plan draft's set with no recommendation rejected, its receipt says `ready` on either surface; when one over MCP closes it with a recommendation rejected, its receipt names the planner's revision work order in `revision` (Figure 5), and a close at the terminal leaves that order to the session's next `phase-plan`.* ## 9. Settings | Setting | Type | Default | Scope | Owner | Effect | |---|---|---|---|---|---| -| `planning.phase_capacity` | integer, min 1, or absent | absent (no ceiling) | both | 0005 | The ceiling on a phase's size in tasks (PLN-R9) | +| `planning.phase_capacity` | a whole number from 1 to 4,294,967,295, or absent | absent (no ceiling) | both | 0005 | The ceiling on a phase's size in tasks (PLN-R9): `plan submit` and `plan approve` refuse a plan over it `over-capacity`, a submit's receipt gives it beside the phase's size, and a planner order binds it with that size as its `capacity` input. With none set, no plan is refused for size | | `review.triggers.plan.gate` | see [0003](0003-configuration-and-routing.md) | `advisory` | both | [0008](0008-review.md) | Whether the checker runs and what its findings do (PLN-R16) | | `review.triggers.plan.recheck` | `full`, `diff` | `full` | both | 0005 | The reading scope of round 2 for a plan check or plan review: `full` reads the whole revised plan; `diff` reads every addition, modification and deletion with before-and-after context. Both scopes check closure: every first-round blocker for the checker (PLN-R16), and every finding the owner ruled `fix` for a plan review (REV-R10). Both may report new defects. It does not control `diff` or `risk_surface` reviews. | -| `workflow.test_command` | command | absent | project | [0006](0006-execution.md) | The suite named in every plan (PLN-R18) | +| `workflow.test_command` | a command on one line, not blank, with no control character, or absent | absent | project | [0006](0006-execution.md) | The suite recorded in every plan `plan approve` approves (PLN-R18). With none set, neither `plan submit` nor `plan approve` is refused: the plan is approved with no suite, and the approval says it cannot be admitted to execution until the setting is set | | `roles.analyzer.*`, `roles.planner.*`, `roles.checker.*` | see [0003](0003-configuration-and-routing.md) | | both | 0003 | The three roles' model and effort | ## 10. Instructions served @@ -623,8 +678,8 @@ sequenceDiagram | 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, 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 | +| 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`; when the stories change, the owner's preview and approval of the commitment at the terminal with `baley scope preview` and `baley scope approve`, then `phase plan` again for the order the approval issued; the planner order's launch, with `work-order-fail` and `work-order-retry` for an order that fails; `plan submit`, or `plan replace` for an approved plan; a proposed split or an `over-capacity` refusal put to the owner; the rounds through `bal-rounds`, ending `ready` or with the revision order; the owner's preview and approval at the terminal with `baley scope preview` and `baley plan approve`; and `plan read` for the approved plans. 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`). The `bal-plan` registry entry serves this text at version 1 (`crates/baley/src/instruction/mod.rs`, `ENTRIES`), and its help row gives it a stub (`crates/baley/src/help/table.rs`, `COMMANDS`) | PLN-R1 to PLN-R7, PLN-R10, PLN-R15, PLN-R27 | +| Rounds | The host session, with every question set, a story's and a plan draft's alike, served by its identity `bal-rounds` at version 2 and named by `bal-context`, `bal-plan`, the round read and the answer receipt; it has no help row and no stub. Its submit step is for a story's analyzer questions, sent as returned with `story-questions-submit`, an empty set's receipt naming the drafting order; a plan draft's set, which `plan-submit` already opened, starts at the round read. 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; and read again after each call until the set is closed. A story set's close returns to the instruction that sent it there, which launches the drafting order the receipt names in `drafting`, or calls `story-refine` again when another analyzer order of the story is still pending and none is named. A plan set's close returns to `bal-plan`, the closing receipt saying `ready` or naming the planner's revision order in `revision` (`crates/baley/src/instruction/rounds.rs`, `TEXT`, and `crates/baley/src/instruction/plan.rs`, `TEXT`) | PLN-R6, PLN-R24, PLN-R25, PLN-R26 | The test derivation rules the planner receives, as served: @@ -644,35 +699,38 @@ The test derivation rules the planner receives, as served: ## 11. Build status -The binary parks the inherited engine for Build 9 to delete, and nothing in production reaches it (`crates/baley/src/inherited.rs`, its module comment). The session server serves `context-intake` on `baley_query` and `context-submit` on `baley_apply` (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS` and `APPLY_OPERATIONS`), and still answers `plan-read` and `plan-submit` as `operation-unavailable`, the operation baseline naming Build 4 for them. `baley context-instructions` and `baley plan-instructions` still print the parked engine's compiled context and plan instructions as text until Build 9 removes them; the parked context text contradicts the served `bal-context`, and no served path reaches it. In the parked engine truths belong to a phase's context, plans are rendered to `PLAN-N.md`, and nothing knows a story, the stories a phase commits, or a size. +The binary parks the inherited engine for Build 9 to delete, and nothing in production reaches it (`crates/baley/src/inherited.rs`, its module comment). The session server serves `context-intake` and `plan-read` on `baley_query`, and `context-submit`, `plan-submit`, `phase-plan` and `plan-replace` on `baley_apply`, the last two listed after `story-questions-submit` (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS` and `APPLY_OPERATIONS`, and `crates/baley/src/mcp/planning.rs`, `serve`, `serve_submit` and `serve_read`). The owner approves a plan with `baley plan approve` and reads a phase's approved plans with `baley plan show` (`crates/baley/src/planning/command.rs`, `run`). The four plan events are registered (`crates/baley-core/src/plan/event.rs`, `register_plan_events`), and the `phase_plan`, `plan` and `evidence_map` views, with the `backlog` view at version 4, are registered in view set 14 (`crates/baley/src/ledger/open.rs`, `options`). `baley context-instructions` and `baley plan-instructions` still print the parked engine's compiled context and plan instructions as text until Build 9 removes them; the parked texts contradict the served `bal-context` and `bal-plan`, and no served path reaches them. In the parked engine truths belong to a phase's context, plans are rendered to `PLAN-N.md`, and nothing knows a story, the stories a phase commits, or a size. | 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, 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-R1 | 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, and its size from the approved plans in force serving it (`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 phase's truths are read as its committed stories' current truths, in commitment order, for the planner order's `stories` input (`crates/baley/src/planning/inputs.rs`, `read`) and for the plan judge's facts at submit and approval (`crates/baley/src/planning/facts.rs`, `read`) | +| PLN-R7 | Partly built | `phase-plan` judges the selection's readiness and its path (`crates/baley-core/src/plan/commitment.rs`, `judge_readiness` and `judge_commitment`) over facts read from the `roadmap`, `truths`, `phase_plan` and `work_order` views (`crates/baley/src/planning/phase_plan.rs`, `read_readiness` and `check`), and commits a changed selection only through the `phase edit` the owner approves, whose approval issues the planner's order ([ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md), [0004](0004-starting-a-project-and-changing-scope.md) section 11). A phase is active while the `phase_plan` view's status says so (`crates/baley-core/src/plan/phase_plan.rs`, `PhasePlanProjector`); `phase-active` refuses `phase-plan` and a commitment's approval, and `phase-not-active` refuses `plan-submit`, `plan-replace` and `baley plan approve` when another phase is active (`crates/baley-core/src/plan/commitment.rs`, `judge_submit_phase`). Completion is not recorded until Build 5, so until then a phase stays active until it is withdrawn, and a project with an approved plan cannot plan another phase | +| PLN-R8, PLN-R20 to PLN-R22 | Not built | Nothing records execution, a phase's completion or its retrospective, and nothing mirrors to the forge. `phase close` is Build 5's, with the definition of done of [0007](0007-verification.md) | +| 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`). `planning.phase_capacity` is a setting of the schema (`crates/baley-core/src/policy/schema.rs`, `Schema::standard`), read for `plan-submit` and `baley plan approve` (`crates/baley/src/planning/facts.rs`, `capacity`) and bound to a planner order with the phase's size (`crates/baley/src/planning/inputs.rs`, `read`). A phase's size is the `phase_plan` view's and a story's the `backlog` view's, each changed only by `plan.approved` and `plan.replaced`. Velocity needs completed phases and is Build 5's | +| PLN-R10 | Built | The planner text tells the planner to return a proposed split rather than overfill a phase (`crates/baley/src/instruction/planner.rs`, `TEXT`), and `bal-plan` puts a proposed split or an `over-capacity` refusal to the owner, who splits a story or the phase through `bal-story` or `bal-phase`, approved by digest as any scope change, then plans again (`crates/baley/src/instruction/plan.rs`, `TEXT`). Whether a live planner proposes one when it should is Build 4 T15's live run | | 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`). 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-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`), and it runs at `plan-submit` and again at `baley plan approve` over the items of the phase's plans in force read from the `evidence_map` view (`crates/baley/src/planning/facts.rs`, `read`). `plan read` names each approved plan's items bound to a version that is not current, worked out from the `truths` view when read (`crates/baley/src/planning/read.rs`, `read`). Evidence recorded by execution and judged stale at verification is Build 5's ([0007](0007-verification.md)) | +| PLN-R5 | 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. A story that reads too large is split as the PLN-R10 row says | | 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 | 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 | 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-R11 | 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`. An accepted plan's draft body is the plan as submitted with `kind` added (`crates/baley-core/src/plan/submission.rs`, `PlanDraft`), and its approval writes the number, the question set, the size and the suite from `workflow.test_command`, or none when the setting is absent (`crates/baley/src/planning/approve.rs`, `record`, and `crates/baley-core/src/plan/event.rs`, `PlanApproval`). 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 | 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`). It runs at `plan-submit` and `plan-replace` (`crates/baley/src/planning/submit.rs`, `check`, and `crates/baley/src/planning/replace.rs`, `check`) and again at `baley plan approve` (`crates/baley/src/planning/approve.rs`, `judge`), over facts read from the views (`crates/baley/src/planning/facts.rs`, `read`). The approved map is recorded inline in `plan.approved` and projected by the `evidence_map` view (`crates/baley-core/src/plan/map_view.rs`, `EvidenceMapProjector`). The parked engine's own evidence map checks are reached by no served path and go in Build 9 | +| PLN-R14 | Partly built | An approval numbers its plan one past the highest number the `phase_plan` view holds, replaced plans included (`crates/baley/src/planning/approve.rs`, `record`), and the view refuses a number not above it (`crates/baley-core/src/plan/phase_plan.rs`, `PhasePlanProjector`). `plan-replace` names the plan in force and its digest, judged `no-such-plan` and `admitted-plan` at submit and again at approval (`crates/baley-core/src/plan/replace.rs`, `judge_replacement`, through `crates/baley/src/planning/replace.rs`, `check`), and its approval records `plan.replaced` with the new plan's `plan.approved` (`crates/baley-core/src/plan/event.rs`, `replaced_payload`). `admitted-plan` is judged over an observation that reads false until Build 5 records execution admission, and gap plans are Build 5's ([0006](0006-execution.md)). The parked engine's own numbering (`crates/baley/src/plan/inventory.rs`, `with_records`, and `crates/baley/src/plan/validation.rs`, `replacement_inner` and `admitted`) is reached by no served path and goes in Build 9 | +| PLN-R15 | Built | `plan-submit` records the draft's body as a `record` payload and one `scope.submitted` of kind `plan` filed under `phase/<n>` (`crates/baley/src/planning/submit.rs`, `record`), so it survives a restart and the newest draft of the phase is the only one approvable. `baley scope preview` prints it (`crates/baley/src/scope/command.rs`, `plan_preview`), and only `baley plan approve` approves it, refusing `unknown-draft`, `stale-draft` naming the first differing path and `draft-approved` (`crates/baley-core/src/plan/approval.rs`, `judge_plan_approval`, through `crates/baley/src/planning/approve.rs`, `judge` and `record`, and `crates/baley/src/planning/command.rs`, `approve`). The parked engine's memory-only drafts (`crates/baley/src/plan_service.rs`, `execute`, and `crates/baley/src/session/mod.rs`, `Drafts`) are reached by no served path and go in Build 9. How a pending checker revision is keyed stays open (section 12) | +| PLN-R16 | Not built | The parked plan text forbids checker dispatch (`crates/baley/src/plan/instructions.rs`, `ROLE`), and the served `bal-plan` text leaves the checker gate to Build 4 T10 (`crates/baley/src/instruction/plan.rs`, its module comment), whose checker order is issued between `plan-submit`'s check and its recording (`crates/baley/src/planning/submit.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`). Every planner order lists it, with the inputs of section 4 (`crates/baley/src/planning/order.rs`, `prepare`, and `crates/baley/src/planning/inputs.rs`, `read`). `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 | 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` calls them to open a plan draft's set and abandon the set of the draft it replaces (`crates/baley/src/planning/submit.rs`, `record`) | | 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 | 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 | +| PLN-R25 | 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 plan draft's set is abandoned `draft-replaced` in the transaction that records the phase's next plan draft (`crates/baley/src/planning/submit.rs`, `record`) | +| PLN-R26 | 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`). `baley plan approve` refuses `question-open`, naming each open question of the draft's set (`crates/baley-core/src/plan/approval.rs`, `judge_plan_approval`) | +| PLN-R27 | Built | A plan's `questions` field is judged by `judge_set` through the plan judge (`crates/baley-core/src/plan/content.rs`, `read`), and `plan-submit` opens the draft's set with the draft (`crates/baley/src/planning/submit.rs`, `record`). `baley plan approve` refuses `answer-not-applied`, naming each question whose answer rejected its recommendation (`crates/baley-core/src/plan/approval.rs`, `judge_plan_approval`). A set's close answers `ready`, or over MCP issues the planner's revision order with the answers, in the receipt's `revision` (`crates/baley/src/questions/answer.rs`, `receipt_value` and `record`, `crates/baley/src/mcp/questions.rs`, `serve`, and `crates/baley/src/planning/order.rs`, `prepare_revision`, with inputs from `crates/baley/src/planning/inputs.rs`, `read_closing`); after a close at the terminal, `phase-plan` issues it (`crates/baley-core/src/plan/commitment.rs`, `judge_commitment`) | ## 12. Open questions | Question | Decided by | |---|---| | How the plan checker's revision and a plan review's revision combine for one plan | Build 4, at the hand-off between `plan submit` and the plan-triggered review in [0008](0008-review.md) | -| How a draft whose re-check was refused leaves that state | Build 4 T9 and T10, at the draft and checker revision state in `plan submit` | +| How a draft whose re-check was refused leaves that state | Build 4 T10, at the draft and checker revision state in `plan submit` | +| How the checker's revision order is issued while a phase has one live planner order. `plan submit` issues the plan checker's work order, and on a first-round blocker the planner's revision order, before it records the draft (section 5, `plan submit`, and Figure 5's plan gate path). The same section says the recording's `scope.submitted` is what marks the planner order the draft answers as answered. `phase plan` allows one pending planner order per phase. Issued in that order, the revision order would be a second pending planner order of the phase, or be refused `planner-order-pending` as `phase plan` refuses one | Build 4 T10, at the plan checker's work order in `plan submit` | | How a pending round-2 binding is keyed and read back before a plan number exists, and how discarding its draft closes the pending check | Build 4, at `plan.check_issued`, `plan.checked` and draft discard | | The exact conditions under which a check's verdict is `rejected` for a test that could not have failed | [0007: Verification](0007-verification.md) | | How the analyzer, planner and checker work orders are delivered to the session's subagents on Claude Code, and how their output is adjudicated there | [0012: Host interface](0012-host-interface.md) | diff --git a/docs/design/0010-guard.md b/docs/design/0010-guard.md index 2dba96f4..31716212 100644 --- a/docs/design/0010-guard.md +++ b/docs/design/0010-guard.md @@ -330,10 +330,10 @@ Not applicable. The guard gives no instructions; an agent sees only the host's o | GRD-R2 | Built | The hook judges `CLAUDE_PROJECT_DIR` with the server's rules (`crates/baley/src/mcp/context.rs:154-167`) and binds a project only when the walk from it finds a managed checkout. The walk treats only not-found as absence for both names, so an unusable nearest `baley.toml` entry still binds the project and a `.git` entry makes the folder the repository root and ends the walk (`crates/baley/src/discovery.rs:44-97`). The walk from the working directory gives the `baley.toml` protected for path tools, never the project. The context walk binds the project and the cwd checkout (`crates/baley/src/guard_hook/context.rs:70-178`). The judge resolves a commit's target directory, the entry reads its branch and walks that directory, and the recorder chooses the checkout root for remembered denials (`crates/baley/src/guard_hook/decide.rs:115-134`, `crates/baley/src/guard_hook/mod.rs:106-110`, `crates/baley/src/guard_hook/record.rs:102-134`). With no project bound, a command or `PowerShell` call passes with nothing recorded, and path calls are judged at the working directory either way (`crates/baley/src/guard_hook/decide.rs:80-204`, `crates/baley-core/src/guard/answer.rs:61-70, 138-144`) | | GRD-R3 | Built | The core scanner returns `GitCommand::Commit(CommitTarget)` or `Push`, with ordered `-C` operands and explicit `Cwd`, `Directory` and `Unestablished` targets (`crates/baley-core/src/guard/scan.rs:13-220`), the PowerShell ask is a core decision (`crates/baley-core/src/guard/answer.rs:133-144`), and the library classifies `Bash`, `Monitor` command and watch forms, and `PowerShell` (`crates/baley/src/hook_input/mod.rs:101-195`). The hook scans a `Bash` or `Monitor` command and passes a declined command or a watch with nothing recorded (`crates/baley/src/guard_hook/decide.rs:81-114`). Claude Code sent `command`, `description` and `timeout_ms` for the `Monitor` command form and `ws`, `description` and `timeout_ms` with no `command` for its watch form, and the names for `PowerShell` are unverified (section 12, `claude-live-2026-10-08-run1.md#fld.monitor`, `#fld.monitor-watch`, `#fld.powershell`). A commit with shell structure the scanner declines passed with nothing recorded and landed on `main` (`claude-live-2026-10-08-run1.md#ctl.declined-syntax`) | | GRD-R4 | Built | The core answer (`crates/baley-core/src/guard/answer.rs:61-73`). The hook asks on every push in a project before it reads a branch or a settings file (`crates/baley/src/guard_hook/decide.rs:115-118`) | -| GRD-R5 | Built | The core answer, with the settings read from a complete policy (`crates/baley-core/src/guard/answer.rs:82-102`, `crates/baley-core/src/guard/settings.rs:12-54`) and the three settings in the schema (`crates/baley-core/src/policy/schema.rs:332-352`). The hook reads the session project's policy with Claude Code's host sections (`crates/baley/src/guard_hook/policy.rs:30-106`) and judges a commit on the branch git read at its target directory. An unestablished target selects a recorded ask with a fixed reason before any branch or policy step (`crates/baley/src/guard_hook/decide.rs:115-149`, `crates/baley-core/src/guard/reason.rs:23-26`) | +| GRD-R5 | Built | The core answer, with the settings read from a complete policy (`crates/baley-core/src/guard/answer.rs:82-102`, `crates/baley-core/src/guard/settings.rs:12-54`) and the three settings in the schema (`crates/baley-core/src/policy/schema.rs` (`standard`)). The hook reads the session project's policy with Claude Code's host sections (`crates/baley/src/guard_hook/policy.rs:30-106`) and judges a commit on the branch git read at its target directory. An unestablished target selects a recorded ask with a fixed reason before any branch or policy step (`crates/baley/src/guard_hook/decide.rs:115-149`, `crates/baley-core/src/guard/reason.rs:23-26`) | | GRD-R6 | Built | The core answer (`crates/baley-core/src/guard/answer.rs:90-100`). The hook asks git for the branch at the resolved commit directory on the guard's budget, reads `.git/HEAD` without following links beside it, and judges the two (`crates/baley/src/guard_hook/branch.rs:23-141`, `crates/baley/src/guard_hook/mod.rs:106-110`). A pass on failure is recorded (`crates/baley/src/guard_hook/decide.rs:242-254`) and printed as one stderr line (`crates/baley/src/guard_hook/render.rs:56-62`). Claude Code's hooks reference sends a hook's stderr on exit 0 to its debug log only, so where the owner sees that line stays unobserved: no loud line was produced in the 2026-10-08 runs (`claude-live-2026-10-08-run1.md#ctl.stderr-line`). The `.git/HEAD` fallback was tried by taking git off `PATH`. The guard then could not read HEAD's copy of `baley.toml`, so it asked on torn settings (GRD-R7) and the pass-on-failure path was not reached, which leaves the fallback name's rule unverified live (`claude-live-2026-10-08-run1.md#ctl.fallback-head`). The doctor carries none of the hook's live observations: they stay in the dated host-matrix record cited here | | GRD-R7 | Built | The shared settings reader refuses a dangling link as a link to a missing file with `config-unavailable`, including a global `config.toml` link whose target is missing (`crates/baley/src/settings.rs:111-135`). The hook treats that global file and an unreadable or non-regular nearest `baley.toml` as torn settings and asks, subject to the remembered denials (`crates/baley/src/guard_hook/policy.rs:60-106`). The core answer for torn settings and the two remembered denials (`crates/baley-core/src/guard/answer.rs:104-131`), and the denials kept, their change judge and the `guard_policy` view (`crates/baley-core/src/guard/remembered.rs:28-226`). Under torn settings the hook reads the denials remembered for the session project root, the target checkout root and Claude Code inside the audit transaction and judges the commit again with them, and a complete policy appends `guard.policy_recorded` beside its answer only when its denials changed (`crates/baley/src/guard_hook/record.rs:102-151, 286-354`) | -| GRD-R8 | Built | The two events, their payloads and the input digest (`crates/baley-core/src/guard/event.rs:19-42, 63-91, 104-181`). The hook selects every ask, deny and pass on failure of a call with an envelope, with its input digest, a path tool's target or a redirected commit's resolved directory in the existing nullable `target`, and a commit's facts (`crates/baley/src/guard_hook/decide.rs:62-78, 115-149, 242-254`), and records it as one `guard.record` command in `user` at policy version 0, by `baley`, with the hook caller, creating `user` when missing (`crates/baley/src/guard_hook/record.rs:165-284, 356-371`). A torn HEAD copy's cause is kept with `[redacted]` in place of git's excerpt, which the bounded reader gives apart (`crates/baley/src/committed.rs:85-138`). Both events stay at version 1, since their field shapes and readers are unchanged. Both views stay registered, in a view set that is now 13, with the install view, the five scope views, the `work_order` view, the `questions` view and the `truths` view (`crates/baley/src/ledger/open.rs` (`options`)) | +| GRD-R8 | Built | The two events, their payloads and the input digest (`crates/baley-core/src/guard/event.rs:19-42, 63-91, 104-181`). The hook selects every ask, deny and pass on failure of a call with an envelope, with its input digest, a path tool's target or a redirected commit's resolved directory in the existing nullable `target`, and a commit's facts (`crates/baley/src/guard_hook/decide.rs:62-78, 115-149, 242-254`), and records it as one `guard.record` command in `user` at policy version 0, by `baley`, with the hook caller, creating `user` when missing (`crates/baley/src/guard_hook/record.rs:165-284, 356-371`). A torn HEAD copy's cause is kept with `[redacted]` in place of git's excerpt, which the bounded reader gives apart (`crates/baley/src/committed.rs:85-138`). Both events stay at version 1, since their field shapes and readers are unchanged. Both views stay registered, in a view set that is now 14, with the install view, the five scope views, the `work_order` view, the `questions` view, the `truths` view and the `phase_plan`, `plan` and `evidence_map` views (`crates/baley/src/ledger/open.rs` (`options`)) | | GRD-R9 | Built | The core mapping from an answer and the audit precondition (`crates/baley-core/src/guard/recording.rs:27-34`). The hook builds the call's identity from its envelope and `CLAUDE_PROJECT_DIR`, or the line saying why it cannot, and invents none (`crates/baley/src/guard_hook/unrecordable.rs:12-41`). Every store failure is unrecordable with its cause named, and needs-rebuild names `baley rebuild user` (`crates/baley/src/guard_hook/unrecordable.rs:43-58`). A call id answered for other input is unrecordable (`crates/baley/src/guard_hook/record.rs:215-236`, `crates/baley/src/guard_hook/unrecordable.rs:60-64`), and a new answer counts as recorded only once its transaction commits (`crates/baley/src/guard_hook/record.rs:275-283`). When that transaction returns successfully without staging or replaying an answer, the entry prints the call-id clash line (`crates/baley/src/guard_hook/record.rs:281-282`, `crates/baley/src/guard_hook/mod.rs:138-141`). Missing recording facts or a policy key that cannot be represented as UTF-8 are unrecordable, as is a redirected target that could not be walked (`crates/baley/src/guard_hook/record.rs:102-151`). Without the protected paths nothing is recorded, and the precondition decides the final answer (`crates/baley/src/guard_hook/mod.rs:73-81, 123-150`). No unrecordable answer was produced in the 2026-10-08 runs, so where the owner sees the loud line stays unobserved (`claude-live-2026-10-08-run1.md#ctl.stderr-line`). The doctor reports the `user` project's views that were behind this binary's when it started and names `baley rebuild user` (`crates/baley/src/host_doctor/guard_records.rs:38-78`, `crates/baley/src/host_doctor/report.rs:446-459`) | | GRD-R10 | Built | The `guard` view, its projector and the redelivery judge (`crates/baley-core/src/guard/redelivery.rs:13-205`). A command with a commit or push verb, or a `PowerShell` call, in a project is looked up on a short store open of its own before any git or policy read (`crates/baley/src/guard_hook/decide.rs:87-93, 108-114`, `crates/baley/src/guard_hook/mod.rs:88-105`, `crates/baley/src/guard_hook/record.rs:378-398`), and the audit transaction reads the view again before it appends (`crates/baley/src/guard_hook/record.rs:215-236`). No `tool_use_id` arrived twice in either 2026-10-08 run, so a live redelivery was not observed and stays unverified (`claude-live-2026-10-08-run1.md#ctl.redelivery`, and the timing read in `claude-live-2026-10-08-run2.md#post-run-reads`) | | GRD-R11 | Partly built | The library write decision takes its lease input and write-only folders, denying a write inside one and leaving reads alone (`crates/baley/src/protected_paths/write.rs:18-117`), with path resolution and containment (`crates/baley/src/protected_paths/resolve.rs:151-238`, `crates/baley/src/protected_paths/contain.rs:14-129`). A protected file that does not exist yet is matched through its deepest existing ancestor, so a case-variant spelling cannot create it (`crates/baley/src/protected_paths/write.rs:127-149`, `crates/baley/src/protected_paths/contain.rs:44-75`). The hook judges `Write`, `Edit` and `NotebookEdit` at the working directory with or without a project, and denies them when the protected paths cannot be resolved (`crates/baley/src/guard_hook/decide.rs:154-204`). It protects the home and config folders, the session project's `baley.toml` and the one that binds the working directory's checkout (`crates/baley/src/guard_hook/context.rs:107-178`). `judge` also takes the installed placements derived from the environment: it adds the placed skill stubs, each of the thirty agent stubs by its own path, never the `agents/` folder, the placed settings and registration files and the installed executable to the protected files once each, and sets the versions folder as the write-only folder (`crates/baley/src/guard_hook/context.rs:139-176`). The placement map projects those files and that folder (`crates/baley/src/host_artifacts/placement.rs:290-330`). A `HOME` or `CLAUDE_CONFIG_DIR` the derivation cannot use becomes a refusal, and the path tools are denied (`crates/baley/src/guard_hook/context.rs:43-59`, `crates/baley/src/guard_hook/decide.rs:181-185`). Build 5 owns the lease | diff --git a/docs/design/0012-host-interface.md b/docs/design/0012-host-interface.md index dde72cfb..4db91f24 100644 --- a/docs/design/0012-host-interface.md +++ b/docs/design/0012-host-interface.md @@ -101,31 +101,31 @@ In the component view of [0002](0002-system-design.md) (Figure 4) this area is t - **Outputs:** the operation's typed result, or one part with the next part's identity. - **Refusals:** `unknown-operation`, `operation-unavailable` (a spelling an earlier server served, naming the build that replaces it), `invalid-arguments` (the reason names the field), plus the operation's own codes. A project that cannot be prepared is not a refusal: the call is answered `failed`, from the table under `baley_apply`. -Query operations are the reads of every area: `help`, `schema`, `document` (a record by identity: capture, draft, roadmap, story, work order, question set, a story's refinement, plan, phase, run, review, verification), `context-intake` (a story's refinement, [0005](0005-context-plans-and-acceptance.md)), `document-search`, `instruction` (an instruction by identity), `progress`, `next` ([0013](0013-next-action-and-progress.md)), `why`, `recall`, `search` ([0014](0014-support-families.md)), `route`, `status` operations per area. +Query operations are the reads of every area: `help`, `schema`, `document` (a record by identity: capture, draft, roadmap, story, work order, question set, a story's refinement, plan, phase, run, review, verification), `context-intake` (a story's refinement, [0005](0005-context-plans-and-acceptance.md)), `plan-read` (a phase's approved plans with their evidence maps, [0005](0005-context-plans-and-acceptance.md) `plan read`), `document-search`, `instruction` (an instruction by identity), `progress`, `next` ([0013](0013-next-action-and-progress.md)), `why`, `recall`, `search` ([0014](0014-support-families.md)), `route`, `status` operations per area. -`help` takes an optional command `name`, `schema` takes `tool` and `for`, `instruction` takes `identity`, and `document` takes `identity` as an object tagged by `kind`: `{"kind": "capture", "id": "<capture id>"}`, `{"kind": "draft", "digest": "<digest>"}`, `{"kind": "roadmap"}`, `{"kind": "story", "id": <story id>}`, where a story id is an integer, `{"kind": "work_order", "id": "<order id>"}`, `{"kind": "questions", "set": "<set id>"}`, or `{"kind": "refinement", "story": <story id>}`. `context-intake` takes `story`, a story id, and refuses any other key, the `phase` an earlier server took among them, as `invalid-arguments`. Each of these five operations takes an optional one-based `part`. Each served operation schema is self-contained, with nested shapes inlined. The input schemas of `baley_query` and `baley_apply` carry the same shapes as properties beside `operation`, so a host is given `identity` as an object and `part` as an integer rather than free text. An argument two operations type differently, such as `identity`, is an `anyOf` of their shapes, and each shape ends by naming the operations that take it and whether each requires it. Other properties stay allowed, so a retired spelling still reaches the server and is answered `operation-unavailable`. The built `document` schema accepts those seven identity kinds, each refusing fields its kind does not take, and any other kind is `invalid-arguments`. An answer that fits in 24,576 bytes comes whole. A larger one comes in parts, each carrying `bound`, `part`, `body` and `next`, where `next` is the next part's number, or null on the last part, and joining the bodies in order gives the answer's bytes. The bound counts body bytes, not the encoded result, and the tool result carries each answer both as text and as structured content. `instruction` answers with the text and its identity, version and hash. `document` answers a capture's text, whole or in parts, and the whole answer and every part carry the identity with the capture's kind, phase, byte count and recording time. When the project released the capture's body, it answers a tombstone with that project's purge reason from its view instead, even while another project still holds the bytes. If only another project purged the body, this project still reads its text. A global body lookup that reports a purge after the view was read triggers a fresh read of this project's view: only its own tombstone supplies the reason. If the view does not confirm that purge, the read answers `failed` `ledger-unavailable` instead of borrowing a global reason. A draft answers with its `kind`, `digest`, the `recorded_at` of its latest submission and the `submission` as recorded. When this project purged the draft's body, it answers the same fields with a `tombstone` holding `state` `purged` and this project's reason from the `draft` view in place of the submission, and the body is not opened; a body lookup that finds the body gone after the view read answers `failed` `ledger-unavailable`, with no second view read. A digest not written as 64 lowercase hexadecimal characters names no draft and is answered `unknown-draft` without a read. The roadmap answers the accepted `description`, the `phases` in roadmap order with their numbers, names, goals, status, dependencies and story ids, and the `stories` in priority order with their ids, wording, status, phase and truth count; a project with no approved scope answers no description and empty lists. A story answers that story nested under `story`, so its own status never stands in for the answer's. A work order answers `order`, its document as the `work_order` view holds it: `id`, `request` (the id of its chain's first order), `parent` (the failed order it retries, or null), `role`, `subject` (`start` for the start planner's order), `attempt`, `route` (the route record, [0003](0003-configuration-and-routing.md) section 6), `agent`, `instructions` (each `{identity, version, hash}`), `inputs` (each `{name, body}`), `state` (`pending`, `failed` or `answered`), `seq`, `recorded_at`, `failure` (`{reason, seq, recorded_at}` or null), `drafts` (what was returned under it, first seen first: the digests of the drafts submitted under it, and for a story's questions order the ids of the question sets opened under it, each read with `document` kind `questions`) and `child` (the retry issued from it, or null). Beside it the answer carries `accepted`, the digest of this project's start approval when that digest is among the order's drafts and otherwise null, read from the project's events since an approval names only a digest; `follow`, one fixed sentence telling the worker to read each instruction the order lists, in order, with `baley_query` `instruction` by its identity, and to follow them; and `inputs`, each with its `name`, `hash` and `bytes` and its `text`. An input this project purged answers a `tombstone` `{"state": "purged", "reason": ...}` with this project's own reason, read from its `retention` stream, in place of the text. A body the store no longer holds whole for any other reason answers `unavailable` with its state, `reduced`, or `purged` with no reason when only another project's purge released the bytes, so another project's reason is never shown. Nothing is rebuilt from current input. A body found purged after the first read of the releases makes the read look at this project's releases again. A question set answers its round, worked out when read from the `questions` view: `state` (`open`, `closed` or `abandoned`), `round`, `current` (each `{id, question, recommended}`), `waiting` (each `{id, question, waits_on}`, every unanswered direct dependency as `{id, state}` with `state` `open` or `deferred`), `answered` (each `{id, answer, accepted, round, owner, at}`), `deferred` (each `{id, reason, round, owner, at}`), `abandoned` (`{cause, at}` or null) and `relay`, a fixed sentence naming the rounds relay instruction `bal-rounds` ([0005](0005-context-plans-and-acceptance.md) `questions round`). A story's refinement, read by `document` as `{"kind":"refinement","story":<id>}` or by `context-intake`, answers the approved `description`, or null before the start, so a pending draft's never stands in for it; the `story` as the roadmap holds it, a dropped story with its status; the `phase` it is committed to, `{number, name, goal, status}` from the `phase` view, or null for a backlog story; and its `truths`, null before its first refinement and otherwise `current`, each truth at its version, and `kept`, every version ever approved, each id's oldest first. The two reads differ only in that `document` carries the `identity`; neither records anything or issues an order (`crates/baley/src/refine/read.rs`, `read`, `crates/baley/src/mcp/document.rs`, `refinement_answer`). A draft, the roadmap, a story, a work order, a question set and a refinement are cut into parts of their answer's JSON text when it is larger than one part, as `help` is. The same reads serve `baley scope preview`, `baley scope show`, `baley story show`, `baley questions round` and `baley story refinement` on the command line. The refusals are `instruction-unavailable`, which names the build that owns an identity not yet served, `unknown-instruction` for any other identity, `no-such-capture` for a capture id the project does not hold, `unknown-draft` for a digest no submission in the project has, `no-such-story` for a story id the accepted roadmap does not hold, for a story's refinement at slot `story` under `context-intake`, `no-such-work-order` for an order id this project's `work_order` view does not hold, `no-such-question-set` for a set id this project's `questions` view does not hold, echoing none of the id, `help-part-not-found`, `schema-part-not-found`, `instruction-part-not-found` and `document-part-not-found` for a part that does not exist, and `invalid-arguments` for a field the shape lacks, so an `instruction` field, the identity a session sends on `baley_apply`, is refused on any read, `document` included. `help`, `schema` and `instruction` need no project, `document`, `context-intake` and `route` need one, and no read records anything. +`help` takes an optional command `name`, `schema` takes `tool` and `for`, `instruction` takes `identity`, and `document` takes `identity` as an object tagged by `kind`: `{"kind": "capture", "id": "<capture id>"}`, `{"kind": "draft", "digest": "<digest>"}`, `{"kind": "roadmap"}`, `{"kind": "story", "id": <story id>}`, where a story id is an integer, `{"kind": "work_order", "id": "<order id>"}`, `{"kind": "questions", "set": "<set id>"}`, `{"kind": "refinement", "story": <story id>}`, `{"kind": "phase", "phase": <phase number>}`, or `{"kind": "plan", "phase": <phase number>, "plan": <plan number>}`. `context-intake` takes `story`, a story id, and refuses any other key, the `phase` an earlier server took among them, as `invalid-arguments`. `plan-read` takes `phase`, a phase number. Each of these six operations takes an optional one-based `part`. Each served operation schema is self-contained, with nested shapes inlined. The input schemas of `baley_query` and `baley_apply` carry the same shapes as properties beside `operation`, so a host is given `identity` as an object and `part` as an integer rather than free text. An argument two operations type differently, such as `identity`, is an `anyOf` of their shapes, and each shape ends by naming the operations that take it and whether each requires it. Other properties stay allowed, so a retired spelling still reaches the server and is answered `operation-unavailable`. The built `document` schema accepts those nine identity kinds, each refusing fields its kind does not take, and any other kind is `invalid-arguments`. An answer that fits in 24,576 bytes comes whole. A larger one comes in parts, each carrying `bound`, `part`, `body` and `next`, where `next` is the next part's number, or null on the last part, and joining the bodies in order gives the answer's bytes. The bound counts body bytes, not the encoded result, and the tool result carries each answer both as text and as structured content. `instruction` answers with the text and its identity, version and hash. `document` answers a capture's text, whole or in parts, and the whole answer and every part carry the identity with the capture's kind, phase, byte count and recording time. When the project released the capture's body, it answers a tombstone with that project's purge reason from its view instead, even while another project still holds the bytes. If only another project purged the body, this project still reads its text. A global body lookup that reports a purge after the view was read triggers a fresh read of this project's view: only its own tombstone supplies the reason. If the view does not confirm that purge, the read answers `failed` `ledger-unavailable` instead of borrowing a global reason. A draft answers with its `kind`, `digest`, the `recorded_at` of its latest submission and the `submission` as recorded. When this project purged the draft's body, it answers the same fields with a `tombstone` holding `state` `purged` and this project's reason from the `draft` view in place of the submission, and the body is not opened; a body lookup that finds the body gone after the view read answers `failed` `ledger-unavailable`, with no second view read. A digest not written as 64 lowercase hexadecimal characters names no draft and is answered `unknown-draft` without a read. The roadmap answers the accepted `description`, the `phases` in roadmap order with their numbers, names, goals, status, dependencies and story ids, and the `stories` in priority order with their ids, wording, status, phase and truth count; a project with no approved scope answers no description and empty lists. A story answers that story nested under `story`, so its own status never stands in for the answer's. A work order answers `order`, its document as the `work_order` view holds it: `id`, `request` (the id of its chain's first order), `parent` (the failed order it retries, or null), `role`, `subject` (`start` for the start planner's order), `attempt`, `route` (the route record, [0003](0003-configuration-and-routing.md) section 6), `agent`, `instructions` (each `{identity, version, hash}`), `inputs` (each `{name, body}`), `state` (`pending`, `failed` or `answered`), `seq`, `recorded_at`, `failure` (`{reason, seq, recorded_at}` or null), `drafts` (what was returned under it, first seen first: the digests of the drafts submitted under it, and for a story's questions order the ids of the question sets opened under it, each read with `document` kind `questions`) and `child` (the retry issued from it, or null). Beside it the answer carries `accepted`, the digest of this project's start approval when that digest is among the order's drafts and otherwise null, read from the project's events since an approval names only a digest; `follow`, one fixed sentence telling the worker to read each instruction the order lists, in order, with `baley_query` `instruction` by its identity, and to follow them; and `inputs`, each with its `name`, `hash` and `bytes` and its `text`. An input this project purged answers a `tombstone` `{"state": "purged", "reason": ...}` with this project's own reason, read from its `retention` stream, in place of the text. A body the store no longer holds whole for any other reason answers `unavailable` with its state, `reduced`, or `purged` with no reason when only another project's purge released the bytes, so another project's reason is never shown. Nothing is rebuilt from current input. A body found purged after the first read of the releases makes the read look at this project's releases again. A question set answers its round, worked out when read from the `questions` view: `state` (`open`, `closed` or `abandoned`), `round`, `current` (each `{id, question, recommended}`), `waiting` (each `{id, question, waits_on}`, every unanswered direct dependency as `{id, state}` with `state` `open` or `deferred`), `answered` (each `{id, answer, accepted, round, owner, at}`), `deferred` (each `{id, reason, round, owner, at}`), `abandoned` (`{cause, at}` or null) and `relay`, a fixed sentence naming the rounds relay instruction `bal-rounds` ([0005](0005-context-plans-and-acceptance.md) `questions round`). A story's refinement, read by `document` as `{"kind":"refinement","story":<id>}` or by `context-intake`, answers the approved `description`, or null before the start, so a pending draft's never stands in for it; the `story` as the roadmap holds it, a dropped story with its status; the `phase` it is committed to, `{number, name, goal, status}` from the `phase` view, or null for a backlog story; and its `truths`, null before its first refinement and otherwise `current`, each truth at its version, and `kept`, every version ever approved, each id's oldest first. The two reads differ only in that `document` carries the `identity`; neither records anything or issues an order (`crates/baley/src/refine/read.rs`, `read`, `crates/baley/src/mcp/document.rs`, `refinement_answer`). A phase, read by `document` as `{"kind":"phase","phase":<n>}`, answers `phase`, the phase as the roadmap holds it, and `plans`, every plan ever approved in it as `plan-read` gives them; `plan-read` answers the phase's number as `phase` beside the same `plans`. Each plan carries its number, approved digest, stories, size, suite or null, question set, owner and time, its `state` (`approved` or `replaced`) and `replaced_by`, its evidence items whole as approved, and its readiness against the current truth versions, worked out when read and never stored. A plan, read as `{"kind":"plan","phase":<n>,"plan":<n>}`, answers `phase` and that one `plan`. Only the views an approval writes are read, so a draft's map never appears ([0005](0005-context-plans-and-acceptance.md) `plan read`, `crates/baley/src/planning/read.rs`, `read`, `crates/baley/src/mcp/document.rs`, `phase_answer` and `plan_answer`, `crates/baley/src/mcp/planning.rs`, `read_answer`). A draft, the roadmap, a story, a work order, a question set, a refinement, a phase and a plan are cut into parts of their answer's JSON text when it is larger than one part, as `help` is, and so is `plan-read`'s. The same reads serve `baley scope preview`, `baley scope show`, `baley story show`, `baley questions round`, `baley story refinement` and `baley plan show` on the command line. The refusals are `instruction-unavailable`, which names the build that owns an identity not yet served, `unknown-instruction` for any other identity, `no-such-capture` for a capture id the project does not hold, `unknown-draft` for a digest no submission in the project has, `no-such-story` for a story id the accepted roadmap does not hold, for a story's refinement at slot `story` under `context-intake`, `no-such-work-order` for an order id this project's `work_order` view does not hold, `no-such-question-set` for a set id this project's `questions` view does not hold, echoing none of the id, `no-such-phase` for a phase the roadmap does not hold, under `document` or `plan-read`, echoing none of its number, `no-such-plan` for a plan number never approved in the phase, naming it, `help-part-not-found`, `schema-part-not-found`, `instruction-part-not-found` and `document-part-not-found` for a part that does not exist, and `invalid-arguments` for a field the shape lacks, so an `instruction` field, the identity a session sends on `baley_apply`, is refused on any read, `document` included. `help`, `schema` and `instruction` need no project, `document`, `context-intake`, `plan-read` and `route` need one, and no read records anything. `route` takes exactly one of `role` and `work_order` and answers the route record, the agent stub and the policy version it was explained at, or null with a note. It reads and judges the settings as a write does, then stops: it admits no checkout, runs no policy step and creates or advances no attempt. [0003](0003-configuration-and-routing.md) section 5 gives its inputs, outputs and refusals. ### baley_apply (tool) -- **Inputs:** `operation`, a request id, which is a UUID in lowercase hyphenated form, and its typed arguments. `capture`, `project-start`, `work-order-fail`, `work-order-retry` and `story-refine` also take `instruction`, the identity of the instruction the session follows. `scope-submit`, `story-questions-submit` and `context-submit` take no `instruction`: each names the work order it answers, and its caller carries that order's instruction evidence. The ten change operations take none either, since their shapes have no place for it, and their front doors' texts tell the session to send none, and neither does `questions-answer`, whose shape has no place for it. +- **Inputs:** `operation`, a request id, which is a UUID in lowercase hyphenated form, and its typed arguments. `capture`, `project-start`, `work-order-fail`, `work-order-retry`, `story-refine` and `phase-plan` also take `instruction`, the identity of the instruction the session follows. `scope-submit`, `story-questions-submit`, `context-submit`, `plan-submit` and `plan-replace` take no `instruction`: each names the work order it answers, and its caller carries that order's instruction evidence. The ten change operations take none either, since their shapes have no place for it, and their front doors' texts tell the session to send none, and neither does `questions-answer`, whose shape has no place for it. - **Outputs:** the operation's typed receipt; a replay of the same request id returns the same receipt. - **Refusals:** as `baley_query`, plus `request-id-reuse` (same id, different payload), which records nothing, and the operation's own codes. A request id in any other form is refused `invalid-arguments` naming `request_id`. The registry judges `instruction`, and an unknown identity or one not served is refused `unknown-instruction` or `instruction-unavailable` naming `instruction`, with nothing recorded. -For `capture`, `project-start`, `work-order-fail`, `work-order-retry` and `story-refine`, the registry's instruction evidence is attached to the caller before preparation begins. The same caller reaches checkout admission, the policy step and the operation's command, so their `checkout.seen`, `policy.effective`, `capture.recorded`, `work_order.issued` or `work_order.failed` and completion events carry it. A call that names no instruction adds no evidence. +For `capture`, `project-start`, `work-order-fail`, `work-order-retry`, `story-refine` and `phase-plan`, the registry's instruction evidence is attached to the caller before preparation begins. The same caller reaches checkout admission, the policy step and the operation's command, so their `checkout.seen`, `policy.effective`, `capture.recorded`, `work_order.issued` or `work_order.failed`, `phase-plan`'s `scope.submitted`, `plan.continuation` or `plan.continuation_followed`, and completion events carry it. A call that names no instruction adds no evidence. `scope-submit` takes a request id, `work_order`, the id of the start planner's work order the submission answers, as that order's receipt gave it, and `submission`, the whole start submission: `description` with `what`, `core_value` and `constraints`; `stories`, each with a local `label`, a `sentence` and a `status` of `active`, `deferred` or `excluded`; and `roadmap`, the phases in order, each with a `name`, a `goal`, a `detail`, `depends_on` as positions in `roadmap` counted from 1, and the `stories` it delivers by label. The input schema declares the submission an object, so a host sends it as one; the request shape still takes it untyped, and the arguments are judged before anything is prepared, in this order: the shape, the request id, the order's id, which must be a UUID in lowercase hyphenated form or is refused `invalid-arguments` naming `work_order`, then the submission whole. A field that is missing, blank, of the wrong type, unknown or out of range is refused `malformed-submission` with its `section` and `field` in the details, never `invalid-arguments`; a story listed by two phases is refused `story-double-assigned`; and phases that depend on each other in a cycle are refused `dependency-cycle`. None of these records anything. The write is prepared under the session's caller carrying the order's id. The write's own check then reads the order from the project's `work_order` view: an id the view does not hold is refused `no-such-work-order`, and an order that is not the start planner's, role `planner` and subject `start`, is refused `wrong-work-order`, both naming `work_order`. It then reads the project's events, and a project whose start is already approved is refused `project-already-started`. Each of these records nothing. An order passes in any state, so a later submission naming an order an earlier one already answered is recorded as the newest draft. Once the check passes, the command's caller also takes the order's instruction evidence, so every event of the submission's transaction carries the order and the instructions it listed. The order rides on the caller and never in the submission, so the draft's digest is the content's alone, while the request digest covers the order too, so one request id cannot answer two orders. An accepted submission is recorded as a draft: one `scope.submitted` on the `project` stream naming its digest, with the submission's canonical JSON stored as a `record` payload. The digest is the SHA-256 of that JSON, so the same content has the same digest from any session. The `work_order` view adds the digest to the order's `drafts`, and a pending order becomes `answered`. The receipt carries `digest`, `kind` (`start`), the `stories` and `phases` counts and `recorded_at`, never the content. Every submission records, so resubmitting a digest makes it the newest draft again. A retry with the same request id and content replays its receipt, and the same id with other content is refused `request-id-reuse`. A submission whose exact bytes were purged from the ledger is answered `failed` `text-purged` ([0004](0004-starting-a-project-and-changing-scope.md) section 5). Each change to accepted scope is its own operation, listed after `scope-submit`: `project-describe`, `phase-declare`, `phase-edit`, `phase-reorder`, `phase-withdraw`, `story-declare`, `story-edit`, `story-reassign`, `story-drop` and `backlog-reorder`. Each takes a request id and `submission`, the change's members, which name phases by number and stories by id ([0004](0004-starting-a-project-and-changing-scope.md) section 5 lists them per change). As for `scope-submit`, the input schema declares the submission an object and the request shape takes it untyped; it is judged whole under the kind the spelling names before anything is prepared, and a fault in it, a `kind` the caller sent included, is `malformed-submission` naming its `section` and `field`, never `invalid-arguments`, with nothing recorded. The write's own check then judges the change against accepted scope as the ledger holds it, after the replay lookup and before the settings read, checkout admission and the policy step: a change before the start is approved is refused `project-not-started`, and each kind's scope rules give their own codes, such as `no-such-phase`, `order-incomplete`, `dependency-order`, `story-undecided` or `phase-has-dependents`, all with nothing recorded. An accepted change is recorded as a draft as a start is, one `scope.submitted` naming its digest, kind and target, with its body, the members with the kind added, stored as a `record` payload; its transaction confirms the scope the check read has not moved and otherwise answers `failed` `ledger-busy`. The receipt carries `digest`, `kind` and `recorded_at`. Replays, `request-id-reuse` and `text-purged` are as for `scope-submit`, and a retry of a completed change replays its receipt whatever the check would say now. The owner's `baley phase reorder`, `baley phase withdraw`, `baley story reassign`, `baley story drop` and `baley backlog reorder` submit the same change through the same functions on the command line (see [Approvals on the command line](#approvals-on-the-command-line)). -Three work-order operations follow the change operations: `project-start`, `work-order-fail` and `work-order-retry`. `questions-answer` follows them, then the two refinement operations `story-refine` and `story-questions-submit`, appended in that order, while `context-submit`, which an earlier server listed among the plan operations, is served in its own place in the list (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`). Each work-order operation is served only by the session server, since an operation that only issues or settles a work order has no command-line form. Each judges its own arguments first, the shape, the request id and then its own fields, each a `refused` answer with nothing recorded. An `instruction` it names is judged by the registry as for `capture`. Then each prepares a write with its own check, after the replay lookup and before the settings, as `scope-submit` does. Each answers a replay from its record, `request-id-reuse` for a request id reused with other arguments, and `failed` `ledger-busy` with nothing recorded when the work orders, the start or the stored inputs its check read moved before its transaction ran. Its receipt is recorded with its command, so a retry under the same request id gets the same receipt and issues nothing new. +Three work-order operations follow the change operations: `project-start`, `work-order-fail` and `work-order-retry`. `questions-answer` follows them, then the two refinement operations `story-refine` and `story-questions-submit`, appended in that order, while `context-submit`, which an earlier server listed among the plan operations, is served in its own place in the list. The two planning operations `phase-plan` and `plan-replace` are appended after them in that order, while `plan-submit` is served in its own earlier place, as `context-submit` is (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`). Each work-order operation is served only by the session server, since an operation that only issues or settles a work order has no command-line form. Each judges its own arguments first, the shape, the request id and then its own fields, each a `refused` answer with nothing recorded. An `instruction` it names is judged by the registry as for `capture`. Then each prepares a write with its own check, after the replay lookup and before the settings, as `scope-submit` does. Each answers a replay from its record, `request-id-reuse` for a request id reused with other arguments, and `failed` `ledger-busy` with nothing recorded when the work orders, the start or the stored inputs its check read moved before its transaction ran. Its receipt is recorded with its command, so a retry under the same request id gets the same receipt and issues nothing new. - **`project-start`** issues the start planner's work order. It takes a request id, `brief`, the brief's whole text, which the session reads in its own sandbox and sends, and an optional `instruction`. The server reads no file for the brief. A brief that is empty or only whitespace is refused `brief-blank`, and one over 65,536 bytes of UTF-8 `brief-too-large`, both naming `brief`. The check refuses `project-already-started` once the project's start is approved, and `start-order-pending` while a start planner order is pending, naming that order in `details.work_order`. The order is recorded as one `work_order.issued` on the project's `roadmap` stream under command kind `project.start`, with the brief stored as a `record` payload and named as the order's one input, `brief`. Its id is a fresh lowercase UUID and also its `request`, its route is the planner's at attempt 1 under the policy the write's policy step recorded, and it lists the instruction `bal-start-planner`, then `bal-start-survey` when the checkout holds existing code ([0004](0004-starting-a-project-and-changing-scope.md), PRJ-R1). The receipt carries `work_order`, `request`, `attempt`, `agent`, `model` (the route's model, or null), `prompt`, `launch`, `recorded_at`, `existing_code`, and `settings` when the settings are missing, as [0004](0004-starting-a-project-and-changing-scope.md) section 5 gives them with every refusal in the order it is judged. -- **`work-order-fail`** records that an order's worker could not launch or returned without a valid result. A session reports a failure: nothing infers one from silence. It takes a request id, `work_order`, the order's id as its receipt gave it, a lowercase UUID, `reason`, plain words that are not blank and hold at most 4,096 bytes of UTF-8, and an optional `instruction`. A malformed id or reason is `invalid-arguments` naming the field. The check refuses `no-such-work-order` for an id this project's `work_order` view does not hold, and `work-order-not-pending` for an order that has already failed or been answered, giving its `state` in `details`. A pending order gets one `work_order.failed`, `{id, reason}`, on the stream it was issued on, under command kind `work_order.fail`, and the view marks it `failed` with that failure. The receipt carries `work_order`, `state` `failed`, `next`, a sentence naming `work-order-retry`, and `recorded_at`. -- **`work-order-retry`** issues the next attempt of a failed order. It takes a request id, `work_order`, the failed order's id, which must be the newest attempt of its chain, and an optional `instruction`. The request digest covers the order alone, so the same retry sent again under its request id replays the same new order and counts one attempt. The check reads the order and each earlier attempt back to its chain's first order, and this project's purge releases, and refuses: `no-such-work-order` for an id the view does not hold; `work-order-not-failed` for an order that is pending or answered, or whose chain an earlier attempt's answer ended, giving the `state` and, for an earlier answer, that attempt's id; `work-order-retried` for an order already retried, naming the retry; and `material-unavailable` for an order one of whose inputs this project purged, naming the input. A retry of the start planner's order is then refused `project-already-started` once the start is approved and `start-order-pending` while another start order is pending, so a project keeps one live start order. A retry of a story's analyzer order is then refused `analyzer-order-pending` while another analyzer order of its story is pending, naming that order in `details.work_order`, and `question-open` while a question of the story's latest set is open, naming the set and the question in `details`, so a story keeps one live analyzer order and no drafting order is issued while a question is open (`crates/baley/src/mcp/work_order.rs`, `retry_check`). The new order is one `work_order.issued` on the parent's stream under command kind `work_order.retry`, with a fresh lowercase UUID, the chain's `request`, the failed order as `parent`, the parent's role, subject and inputs unchanged, the instructions the parent listed at the registry's current version and hash, and the route resolved again under the current policy and catalog at the parent's attempt plus one, one rung up when `escalate_on_failure` is on ([0003](0003-configuration-and-routing.md), CFG-R16). The view sets the parent's `child` to the new order. The receipt carries what `project-start`'s does, with `parent` in place of `settings` and `existing_code`. +- **`work-order-fail`** records that an order's worker could not launch or returned without a valid result. A session reports a failure: nothing infers one from silence. It takes a request id, `work_order`, the order's id as its receipt gave it, a lowercase UUID, `reason`, plain words that are not blank and hold at most 4,096 bytes of UTF-8, and an optional `instruction`. A malformed id or reason is `invalid-arguments` naming the field. The check refuses `no-such-work-order` for an id this project's `work_order` view does not hold, and `work-order-not-pending` for an order that has already failed or been answered, giving its `state` in `details`. `phase-plan` answers the same code when the planner order it would hand over failed or was answered after the commitment's approval issued it (below). A pending order gets one `work_order.failed`, `{id, reason}`, on the stream it was issued on, under command kind `work_order.fail`, and the view marks it `failed` with that failure. The receipt carries `work_order`, `state` `failed`, `next`, a sentence naming `work-order-retry`, and `recorded_at`. +- **`work-order-retry`** issues the next attempt of a failed order. It takes a request id, `work_order`, the failed order's id, which must be the newest attempt of its chain, and an optional `instruction`. The request digest covers the order alone, so the same retry sent again under its request id replays the same new order and counts one attempt. The check reads the order and each earlier attempt back to its chain's first order, and this project's purge releases, and refuses: `no-such-work-order` for an id the view does not hold; `work-order-not-failed` for an order that is pending or answered, or whose chain an earlier attempt's answer ended, giving the `state` and, for an earlier answer, that attempt's id; `work-order-retried` for an order already retried, naming the retry; and `material-unavailable` for an order one of whose inputs this project purged, naming the input. A retry of the start planner's order is then refused `project-already-started` once the start is approved and `start-order-pending` while another start order is pending, so a project keeps one live start order. A retry of a story's analyzer order is then refused `analyzer-order-pending` while another analyzer order of its story is pending, naming that order in `details.work_order`, and `question-open` while a question of the story's latest set is open, naming the set and the question in `details`, so a story keeps one live analyzer order and no drafting order is issued while a question is open. A retry of a phase's planner order is refused `planner-order-pending` while another planner order of the phase is pending, naming that order in `details.work_order`, so a phase keeps one live planner order (`crates/baley/src/mcp/work_order.rs`, `retry_check`). The new order is one `work_order.issued` on the parent's stream under command kind `work_order.retry`, with a fresh lowercase UUID, the chain's `request`, the failed order as `parent`, the parent's role, subject and inputs unchanged, the instructions the parent listed at the registry's current version and hash, and the route resolved again under the current policy and catalog at the parent's attempt plus one, one rung up when `escalate_on_failure` is on ([0003](0003-configuration-and-routing.md), CFG-R16). The view sets the parent's `child` to the new order. The receipt carries what `project-start`'s does, with `parent` in place of `settings` and `existing_code`. -`questions-answer` relays the owner's answers and deferrals for one round of a question set ([0005](0005-context-plans-and-acceptance.md) `questions answer`). It takes a request id, `set`, the set's id as its round read or an earlier receipt gave it, and `items`, one per question the owner settles: `{"question": "<id>", "act": "take"}` takes the recommended answer, `{"question": "<id>", "act": "answer", "answer": "<the owner's words>"}` gives the owner's own, and `{"question": "<id>", "act": "defer", "reason": "<the owner's reason>"}` defers it. It takes no `instruction`. Its arguments are judged before anything is prepared, each a `refused` answer with nothing recorded: the shape and the request id as `invalid-arguments`, then the call's grammar as `typed-content`, which refuses an empty list, an item outside the grammar, a question named twice and a text over 4,096 bytes, naming the item's position when the fault is one item's. The request digest covers the command kind, the set and the items and never the policy version, so a retry after a policy edit replays. The write is then prepared under the session's caller with its own check, after the replay lookup and before the settings read, checkout admission and the policy step: the check reads the set from the project's `questions` view and judges the call against the round as it stood, refusing `no-such-question-set`, `question-set-abandoned`, then per item `no-such-question`, `question-closed`, `question-not-in-round`, `answer-blank` and `deferral-reason`, each naming the question and recording nothing. After the policy step the owner is read from `owner.name` in the policy the step recorded, falling back to git's `user.name`; with neither the call is refused `owner-identity-missing`, after checkout admission and the policy step, which stay recorded. The call is then recorded in one transaction under command kind `questions.answer`, every answer and deferral on the set's stream with the call's round, the owner and the command's time, with actor `baley` and the session as the caller, so the record does not claim the owner gave the act ([ADR 0047](../adr/0047-owner-acts-relayed-by-a-session.md)). The transaction confirms the set's view document has not moved since the check and otherwise answers `failed` `ledger-busy` with nothing recorded. A replay is answered from its record, and the same request id with other arguments is refused `request-id-reuse`. The receipt carries `set`, the `round` recorded, `recorded_at` and `now`, the round as it stands after the call in the `document` read's shape. A receipt is never cut into parts, so when that round would pass the 24,576-byte part bound, `now` carries only its `state`, `round`, the `document` identity `read` to read it from and the relay sentence. When the call closes a story's set, the same transaction issues the story's drafting order, the analyzer order that drafts its truths, and the receipt adds `drafting`, that order's receipt members as `story-refine` gives them; while another analyzer order of the story is pending no order is issued and the receipt has no `drafting` ([0005](0005-context-plans-and-acceptance.md), `crates/baley/src/questions/answer.rs`, `receipt_value`). `baley questions answer` at the terminal judges and records a call through the same functions, as the owner with no caller, and issues no drafting order, since an owner command issues no work order: the session's next `story-refine` on that story issues it (see [Approvals on the command line](#approvals-on-the-command-line)). +`questions-answer` relays the owner's answers and deferrals for one round of a question set ([0005](0005-context-plans-and-acceptance.md) `questions answer`). It takes a request id, `set`, the set's id as its round read or an earlier receipt gave it, and `items`, one per question the owner settles: `{"question": "<id>", "act": "take"}` takes the recommended answer, `{"question": "<id>", "act": "answer", "answer": "<the owner's words>"}` gives the owner's own, and `{"question": "<id>", "act": "defer", "reason": "<the owner's reason>"}` defers it. It takes no `instruction`. Its arguments are judged before anything is prepared, each a `refused` answer with nothing recorded: the shape and the request id as `invalid-arguments`, then the call's grammar as `typed-content`, which refuses an empty list, an item outside the grammar, a question named twice and a text over 4,096 bytes, naming the item's position when the fault is one item's. The request digest covers the command kind, the set and the items and never the policy version, so a retry after a policy edit replays. The write is then prepared under the session's caller with its own check, after the replay lookup and before the settings read, checkout admission and the policy step: the check reads the set from the project's `questions` view and judges the call against the round as it stood, refusing `no-such-question-set`, `question-set-abandoned`, then per item `no-such-question`, `question-closed`, `question-not-in-round`, `answer-blank` and `deferral-reason`, each naming the question and recording nothing. After the policy step the owner is read from `owner.name` in the policy the step recorded, falling back to git's `user.name`; with neither the call is refused `owner-identity-missing`, after checkout admission and the policy step, which stay recorded. The call is then recorded in one transaction under command kind `questions.answer`, every answer and deferral on the set's stream with the call's round, the owner and the command's time, with actor `baley` and the session as the caller, so the record does not claim the owner gave the act ([ADR 0047](../adr/0047-owner-acts-relayed-by-a-session.md)). The transaction confirms the set's view document has not moved since the check and otherwise answers `failed` `ledger-busy` with nothing recorded. A replay is answered from its record, and the same request id with other arguments is refused `request-id-reuse`. The receipt carries `set`, the `round` recorded, `recorded_at` and `now`, the round as it stands after the call in the `document` read's shape. A receipt is never cut into parts, so when that round would pass the 24,576-byte part bound, `now` carries only its `state`, `round`, the `document` identity `read` to read it from and the relay sentence. When the call closes a story's set, the same transaction issues the story's drafting order, the analyzer order that drafts its truths, and the receipt adds `drafting`, that order's receipt members as `story-refine` gives them; while another analyzer order of the story is pending no order is issued and the receipt has no `drafting` ([0005](0005-context-plans-and-acceptance.md), `crates/baley/src/questions/answer.rs`, `receipt_value`). When the call closes a plan draft's set with no answer rejecting a recommended answer, the receipt adds `ready` true, since the draft may then be approved. When an answer rejected one, the same transaction issues the phase planner's revision order, at attempt 1 of a new chain, binding the draft and its set with every answer and deferral beside the planning inputs, and the receipt adds `revision`, that order's receipt members; while a planner order of the phase is pending none is issued and the receipt has no `revision` (`crates/baley/src/mcp/questions.rs`, `serve`, [0005](0005-context-plans-and-acceptance.md) `questions answer`). `baley questions answer` at the terminal judges and records a call through the same functions, as the owner with no caller, and issues no drafting or revision order, since an answer given at the terminal issues no work order: the session's next `story-refine` on that story, or `phase-plan` for that phase, issues it, and a plan draft's receipt still says `ready` (see [Approvals on the command line](#approvals-on-the-command-line)). The refinement operations ([0005](0005-context-plans-and-acceptance.md) `story refine`, `story questions submit` and `story truths submit`) are served only by the session server, as the work-order operations are. Each judges its arguments first, the shape and the request id as `invalid-arguments`, then its own fields, each a `refused` answer with nothing recorded, and then prepares a write with its own check, after the replay lookup and before the settings read, checkout admission and the policy step, so every refusal of the check records nothing. Each answers a replay from its record, `request-id-reuse` for a request id reused with other arguments, and `failed` `ledger-busy` with nothing recorded when the story, its question sets, its orders or its truths moved after the check (`crates/baley/src/mcp/refine.rs`). @@ -133,7 +133,12 @@ The refinement operations ([0005](0005-context-plans-and-acceptance.md) `story r - **`story-questions-submit`** records the questions the analyzer returned as the story's question set. It takes a request id, `story`, `work_order`, the questions order's id, a lowercase hyphenated UUID or `invalid-arguments` naming `work_order`, and `questions`, the analyzer's questions as returned, each `{id, question, recommended, depends_on}`. The set is judged whole before anything is prepared, a fault answered with the set judge's own code at slot `questions`, such as `typed-content` or `question-cycle`. The write is prepared under the session's caller carrying the order's id, and its check refuses, in order: `no-such-story` as `story-refine` does; `no-such-work-order` and `wrong-work-order`, for an order that is not this story's questions order, both naming `work_order`, in any state; `question-open` while a question of the story's latest set is open, naming the set and the question, so a story's open set is never abandoned by a new one; and `dispatch-active`. Once it passes, the command's caller takes the order's instruction evidence. One transaction under command kind `story.questions.submit` abandons the story's earlier set, closed by then, with cause `superseded`, and opens the new set on `roadmap` naming the order. The `work_order` view adds the set's id to the order's `drafts`, and a pending order becomes `answered`, while a failed order stays failed. An empty list closes the set at once, and unless another analyzer order of the story is pending the same transaction issues the drafting order. The receipt carries `set`, `story`, `recorded_at` and `now`, the new set's round, and `drafting`, the drafting order's receipt members, when one was issued (`crates/baley/src/refine/questions.rs`, `check` and `record`). - **`context-submit`** records the truths the analyzer drafted as a draft the owner approves at the terminal. It takes a request id, `work_order`, the drafting order's id, a lowercase hyphenated UUID or `invalid-arguments` naming `work_order`, `story`, `set`, the question set the truths were drafted from, and `truths`, each `{id, form, trigger, observer, verb, outcome, kind, observable, fixed_oracle}` with an optional `human_verify`. The truths are judged whole before anything is prepared, a fault answered at slot `truths` with `truth-form`, `truth-id`, `truth-attestation`, `truth-internal` or `truth-prose-oracle` naming the truth's position and id. The write is prepared under the session's caller carrying the order's id, and its check refuses, in order: `no-such-story`; `no-such-question-set` for a set not held or another story's and `question-set-abandoned` for one that is not the story's latest, both naming `set`, while an open question refuses nothing here; and `no-such-work-order` and `wrong-work-order`, for an order that is not this story's drafting order, both naming `work_order`, in any state. Once it passes, the command's caller takes the order's instruction evidence. The draft is recorded as a start's is: its canonical JSON as a `record` payload and one `scope.submitted` of kind `story-truths` and target `story/<id>` on `project`, under command kind `scope.submit`, whose digest is the content's alone, the same digest the truth-submission function gives for the same content; the `work_order` view adds the digest to the order's `drafts`, and a pending order becomes `answered`, while a failed order stays failed. The receipt carries `digest`, `kind` (`story-truths`), `story`, `set`, `recorded_at`, `marks`, each truth's `{id, mark}` with `mark` `unchanged`, `changed` or `added` against the story's current truths, and `removed`, the current truths the draft leaves out. No version is given: a truth's version is set when the owner approves the draft (`crates/baley/src/refine/submit.rs`, `check` and `record`). -No approval operation is served. The owner approves a draft by its digest on the command line, a scope draft with `baley scope approve <digest>` and a truth draft with `baley story truths approve <digest>`, because over MCP the call comes from the model and nothing proves a person answered, while the sandbox keeps agents from running the command line against Baley's home, where the ledger lives ([ADR 0044](../adr/0044-owner-acts-on-the-command-line.md)). A `baley_apply` call spelled `scope-approve`, or any spelling that would approve truths, is not one of its operations and is refused `unknown-operation`. +The planning operations ([0005](0005-context-plans-and-acceptance.md) `phase plan`, `plan submit` and `plan replace`) are served only by the session server, as the refinement operations are. Each judges its arguments first, the shape and the request id as `invalid-arguments`, then its own fields, each a `refused` answer with nothing recorded, and then prepares a write with its own check, after the replay lookup and before the settings read, checkout admission and the policy step, so every refusal of the check records nothing. Each answers a replay from its record, `request-id-reuse` for a request id reused with other arguments, and `failed` `ledger-busy` with nothing recorded when what its check read moved before its transaction ran (`crates/baley/src/mcp/planning.rs`). + +- **`phase-plan`** commits stories to a phase and issues the phase planner's order ([ADR 0050](../adr/0050-phase-plan-commits-stories-through-an-approved-edit.md)). It takes a request id, `phase`, `stories`, the stories to commit in order, and an optional `instruction`. The request digest covers the phase and the stories in order. The check judges the selection's readiness, refusing in order `phase-active` while another phase is active, `no-such-phase`, `no-such-story`, `story-unrefined` and `story-in-phase`, and then takes the first path that applies. When the stories are the phase's committed stories in order and the phase's latest planning continuation names them with a pending planner order not yet handed over, it records `plan.continuation_followed` and answers with that order's receipt; an order that failed or was answered since is refused `work-order-not-pending`. Otherwise, while a planner order of the phase is pending, it is refused `planner-order-pending`, naming that order in `details.work_order`. When the stories differ from the phase's committed stories, in content or only in order, one transaction records the `phase edit` of the phase's `stories` as a draft, `scope.submitted`, and `plan.continuation` naming the phase, the selection, the edit's digest and the id the planner order will have; no order is issued, and the receipt carries `digest`, `kind`, `recorded_at`, `phase`, `stories`, and the `baley scope preview` and `baley scope approve` commands in `preview` and `approve`. With the stories unchanged it issues the planner's revision order when the phase's current plan draft's set closed with an answer rejecting a recommended answer, and the planning order otherwise. Either order is one `work_order.issued` on `phase/<n>` under command kind `phase.plan`, role `planner`, subject `phase/<n>`, a fresh lowercase UUID as its id and `request`, the planner's route at attempt 1, the instruction `bal-phase-planner`, and the inputs of [0005](0005-context-plans-and-acceptance.md) section 4 bound at issue as `record` payloads. Its receipt carries what `story-refine`'s does, without `analyzer` (`crates/baley/src/planning/phase_plan.rs`, `check` and `run`, `crates/baley/src/planning/order.rs`, `prepare`, `read_hand_over`, `hand_over` and `issue`). +- **`plan-submit`** records the planner's plan as a draft the owner approves at the terminal. It takes a request id, `work_order`, the planner order's id, a lowercase hyphenated UUID or `invalid-arguments` naming `work_order`, and `plan`, the plan exactly as the planner returned it. **`plan-replace`** takes the same and `replaces`, `{plan, digest}`, the approved plan in force it replaces; a digest not written as 64 lowercase hexadecimal characters is `invalid-arguments` at slot `replaces`. Both read and judge the settings for `planning.phase_capacity` before preparation, recording nothing. The check refuses, in order: `no-such-work-order`; `typed-content` when the plan's `phase` cannot be read; `wrong-work-order` for an order that is not a planner order of that phase, or has failed; `phase-not-active` while a different phase is active; for `plan-replace`, `no-such-plan` and `admitted-plan`; then the plan judged whole, `over-capacity` last. Once it passes, the command's caller takes the order's instruction evidence. One transaction under command kind `scope.submit` records the draft, its body as a `record` payload and one `scope.submitted` of kind `plan` and target `phase/<n>` on `project`, abandons the phase's earlier draft's set with cause `draft-replaced`, and opens the draft's question set on `phase/<n>`, an empty set closed at once; the `work_order` view adds the digest to the order's `drafts`, and a pending order becomes `answered`. A phase holds one plan draft, so a new submit or replacement makes the earlier draft stale. The receipt carries `digest`, `kind`, `phase`, `stories`, `size`, `phase_size`, `reaching`, `capacity`, `set`, `recorded_at`, `now`, round 1 of the set, and `preview`, as [0005](0005-context-plans-and-acceptance.md) `plan submit` gives them (`crates/baley/src/planning/submit.rs`, `check` and `record`, `crates/baley/src/planning/replace.rs`, `check`). + +No approval operation is served. The owner approves a draft by its digest on the command line, a scope draft with `baley scope approve <digest>`, a truth draft with `baley story truths approve <digest>` and a plan draft with `baley plan approve <digest>`, because over MCP the call comes from the model and nothing proves a person answered, while the sandbox keeps agents from running the command line against Baley's home, where the ledger lives ([ADR 0044](../adr/0044-owner-acts-on-the-command-line.md)). A `baley_apply` call spelled `scope-approve`, or any spelling that would approve truths or a plan, is not one of its operations and is refused `unknown-operation`. Apply operations are the writes of every area, each named in its document: scope, story, phase and plan operations (0004, 0005); execution operations (0006); verification operations (0007); review operations (0008); risk operations (0009); landing, milestone, release, undo, pause (0011); capture, task, debug, spike (0014); `questions-answer` (the owner's answers and deferrals for one round of a question set, relayed, 0005); `story-refine`, `story-questions-submit` and `context-submit` (a story's refinement, 0005); `worker-exit`; `round-record`; Build 4's `models-return` for a provider list bound to a fetch work order ([0003](0003-configuration-and-routing.md#5-commands-and-operations)). @@ -143,22 +148,22 @@ Before a project read or write runs its operation, the server prepares it (secti | Code | Place | Retryable | Answered | The owner's step | First reached by | |---|---|---|---|---|---| -| `project-context-invalid` | `CLAUDE_PROJECT_DIR` | no | read and write | Restore the project directory, which was removed after the server started. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake` | -| `not-a-project` | `CLAUDE_PROJECT_DIR` | no | read and write | Run `baley init` in the repository, or start the session inside one that holds a `baley.toml`. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake` | -| `config-unavailable` | `settings` | no | read and write | Repair the settings file the reason names. A read judges only the working tree's `baley.toml`, and a write and the `route` query also judge the global file and HEAD's copy. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake` | -| `project-not-in-ledger` | `project` | no | read and write | Run `baley init` in the checkout, which ties its project to this machine's ledger. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake` | -| `ledger-busy` | `ledger` | yes | read and write | None. The caller repeats the same call. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake` | -| `ledger-unavailable` | `ledger` | no | read and write | Run `baley doctor`. A server whose ledger could not be opened at start needs a new session once the ledger opens. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake` | -| `checkout-facts-unavailable` | `git` | no | write only | Fix the git fault the reason names, such as a remote that cannot be read. `project-start` also answers it when HEAD's tracked files cannot be listed. | Build 3 T8, `capture`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail` and `work-order-retry`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit` and `context-submit` | -| `project-id-conflict` | `checkout` | no | write only | Run `baley init --new-id` in the fork's checkout, which gives it its own project. | Build 3 T8, `capture`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail` and `work-order-retry`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit` and `context-submit` | +| `project-context-invalid` | `CLAUDE_PROJECT_DIR` | no | read and write | Restore the project directory, which was removed after the server started. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake`; Build 4 T9, `phase-plan`, `plan-submit`, `plan-replace` and `plan-read` | +| `not-a-project` | `CLAUDE_PROJECT_DIR` | no | read and write | Run `baley init` in the repository, or start the session inside one that holds a `baley.toml`. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake`; Build 4 T9, `phase-plan`, `plan-submit`, `plan-replace` and `plan-read` | +| `config-unavailable` | `settings` | no | read and write | Repair the settings file the reason names. A read judges only the working tree's `baley.toml`, and a write and the `route` query also judge the global file and HEAD's copy. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake`; Build 4 T9, `phase-plan`, `plan-submit`, `plan-replace` and `plan-read` | +| `project-not-in-ledger` | `project` | no | read and write | Run `baley init` in the checkout, which ties its project to this machine's ledger. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake`; Build 4 T9, `phase-plan`, `plan-submit`, `plan-replace` and `plan-read` | +| `ledger-busy` | `ledger` | yes | read and write | None. The caller repeats the same call. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake`; Build 4 T9, `phase-plan`, `plan-submit`, `plan-replace` and `plan-read` | +| `ledger-unavailable` | `ledger` | no | read and write | Run `baley doctor`. A server whose ledger could not be opened at start needs a new session once the ledger opens. | Build 3 T8, `capture` and `document`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail`, `work-order-retry` and `route`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit`, `context-submit` and `context-intake`; Build 4 T9, `phase-plan`, `plan-submit`, `plan-replace` and `plan-read` | +| `checkout-facts-unavailable` | `git` | no | write only | Fix the git fault the reason names, such as a remote that cannot be read. `project-start` also answers it when HEAD's tracked files cannot be listed. | Build 3 T8, `capture`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail` and `work-order-retry`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit` and `context-submit`; Build 4 T9, `phase-plan`, `plan-submit` and `plan-replace` | +| `project-id-conflict` | `checkout` | no | write only | Run `baley init --new-id` in the fork's checkout, which gives it its own project. | Build 3 T8, `capture`; Build 4 T3, `scope-submit`; Build 4 T4, the ten change operations; Build 4 T5, `project-start`, `work-order-fail` and `work-order-retry`; Build 4 T6, `questions-answer`; Build 4 T7, `story-refine`, `story-questions-submit` and `context-submit`; Build 4 T9, `phase-plan`, `plan-submit` and `plan-replace` | -`recorded: false` means the call recorded nothing itself. A write's `ledger-busy` or `ledger-unavailable` answered at the policy step can follow a checkout admission that stays recorded, and a retry records nothing more for an unchanged checkout. A scope transaction's `ledger-busy`, answered when the facts its check judged moved before the transaction, such as a start approved in between or, for a change, a scope document another approval moved, can follow a checkout admission and a policy step that stay recorded, as the policy step's can. So can an answer call's `ledger-busy`, answered when its question set moved after the check, and a refinement call's, answered when the story, its question sets, its analyzer orders or its truths moved after the check. A refusal from a write's own check is not a `failed` answer: it ends preparation before the settings read with nothing recorded and keeps its own code, slot and details. +`recorded: false` means the call recorded nothing itself. A write's `ledger-busy` or `ledger-unavailable` answered at the policy step can follow a checkout admission that stays recorded, and a retry records nothing more for an unchanged checkout. A scope transaction's `ledger-busy`, answered when the facts its check judged moved before the transaction, such as a start approved in between or, for a change, a scope document another approval moved, can follow a checkout admission and a policy step that stay recorded, as the policy step's can. So can an answer call's `ledger-busy`, answered when its question set moved after the check, and a refinement call's, answered when the story, its question sets, its analyzer orders or its truths moved after the check, and a planning call's, answered when a phase was made active, a story's truths or commitment changed, a planner order was issued or a plan was approved after the check. A refusal from a write's own check is not a `failed` answer: it ends preparation before the settings read with nothing recorded and keeps its own code, slot and details. -`owner-identity-missing` is a `refused` answer over MCP only for `questions-answer`, the one session call that reads the owner, to record in each answer and deferral. It comes after checkout admission and the policy step, which stay recorded, and names how to set the name, as the command line's refusal does. A replay reads no owner and is answered from its record. On the command line `baley scope approve`, `baley story truths approve`, `baley questions answer` and `baley config interview` read the owner (see [Approvals on the command line](#approvals-on-the-command-line)). +`owner-identity-missing` is a `refused` answer over MCP only for `questions-answer`, the one session call that reads the owner, to record in each answer and deferral. It comes after checkout admission and the policy step, which stay recorded, and names how to set the name, as the command line's refusal does. A replay reads no owner and is answered from its record. On the command line `baley scope approve`, `baley story truths approve`, `baley plan approve`, `baley questions answer` and `baley config interview` read the owner (see [Approvals on the command line](#approvals-on-the-command-line)). ### Approvals on the command line -Every owner approval is given at the terminal, never through a session (HST-R10, [ADR 0044](../adr/0044-owner-acts-on-the-command-line.md)). For scope it is `baley scope approve <digest>`, and for a story's truths `baley story truths approve <digest>`, below. `baley scope approve <digest>` approves any scope draft a submission's receipt named: a start's from `scope-submit`, or a change's from one of the ten change operations or from the owner's change commands below ([0004](0004-starting-a-project-and-changing-scope.md) section 5). The digest must be written as the receipt writes it, 64 lowercase hexadecimal characters, and anything else is refused before the ledger is read. The command finds its project from its working directory and then runs the approval's first step, which reads the draft and judges it against the ledger outside any transaction. A digest no submission has is refused `unknown-draft`, and so is a truth draft's, with the reason naming `baley story truths approve`; a draft older than the newest draft of the same change, the same kind and target, `stale-draft` naming the first part that differs; a second start `project-already-started`; and a change draft already approved after its latest submission `draft-approved` naming that approval. A change draft is then judged again against accepted scope as it stands, with the refusals its submission would get now. A draft whose body this project purged is answered `ledger-unavailable`. None of them records anything. The command then reads and validates the settings, admits the checkout and runs the policy step, as the command line's other writes do, and reads the owner: the global `owner.name`, or git's `user.name` read in the command's working directory when it is unset, so a repository's own `user.name` applies there. With neither it refuses `owner-identity-missing`, saying what git did and how to fix it: set `owner.name` with `baley config set --global owner.name="Your Name"`, or git's name with `git config --global user.name "Your Name"`. That refusal comes after checkout admission and the policy step, which stay recorded. The approval is recorded with actor `owner`, the owner's name and Baley's clock when the approval arrives, and its transaction confirms that nothing the first step judged has moved, answering `ledger-busy` with nothing recorded when something has. A receipt prints the kind, digest, owner and time and the phase numbers and story ids the approval recorded and exits 0; a refusal prints `<code>: <reason>`, followed by a stale draft's path or a malformed submission's section and field, and exits 2; a failure exits 1 (`crates/baley/src/scope/command.rs`, `approve` and `answer_render`, `crates/baley/src/scope/approve.rs`, `judge`, `judge_change_draft`, `detail_in_force`, `Approval`, `approvals_of`, `accept_change`, `change_refused`, `record`, `change_decision` and `confirm_detail`, `crates/baley/src/providers/identity.rs`, `owner`). +Every owner approval is given at the terminal, never through a session (HST-R10, [ADR 0044](../adr/0044-owner-acts-on-the-command-line.md)). For scope it is `baley scope approve <digest>`, for a story's truths `baley story truths approve <digest>`, and for a plan `baley plan approve <digest>`, below. `baley scope approve <digest>` approves any scope draft a submission's receipt named: a start's from `scope-submit`, or a change's from one of the ten change operations or from the owner's change commands below ([0004](0004-starting-a-project-and-changing-scope.md) section 5). The digest must be written as the receipt writes it, 64 lowercase hexadecimal characters, and anything else is refused before the ledger is read. The command finds its project from its working directory and then runs the approval's first step, which reads the draft and judges it against the ledger outside any transaction. A digest no submission has is refused `unknown-draft`, and so is a truth draft's, with the reason naming `baley story truths approve`, and a plan draft's, naming `baley plan approve`; a draft older than the newest draft of the same change, the same kind and target, `stale-draft` naming the first part that differs; a second start `project-already-started`; and a change draft already approved after its latest submission `draft-approved` naming that approval and, for a commitment, the planner order it issued. A commitment, a `phase edit` draft `phase-plan` recorded with a planning continuation, is then rechecked with the readiness rules `phase-plan` judges by, `phase-active`, `no-such-phase`, `no-such-story`, `story-unrefined` and `story-in-phase`, then `planner-order-pending` while a planner order of the phase is pending ([0004](0004-starting-a-project-and-changing-scope.md) `scope approve`). A change draft is then judged again against accepted scope as it stands, with the refusals its submission would get now. A draft whose body this project purged is answered `ledger-unavailable`. None of them records anything. The command then reads and validates the settings, admits the checkout and runs the policy step, as the command line's other writes do, and reads the owner: the global `owner.name`, or git's `user.name` read in the command's working directory when it is unset, so a repository's own `user.name` applies there. With neither it refuses `owner-identity-missing`, saying what git did and how to fix it: set `owner.name` with `baley config set --global owner.name="Your Name"`, or git's name with `git config --global user.name "Your Name"`. That refusal comes after checkout admission and the policy step, which stay recorded. For a commitment the policy step records Claude Code's effective policy, and the planner order is prepared before the transaction, its route composed for Claude Code, the only host, with Claude Code's accepted model names; a fault there, such as `unknown-model` or `text-purged` for a purged input, is the answer, with nothing approved ([0003](0003-configuration-and-routing.md) section 5). The approval is recorded with actor `owner`, the owner's name and Baley's clock when the approval arrives, and its transaction confirms that nothing the first step judged has moved, answering `ledger-busy` with nothing recorded when something has. A commitment's transaction also records, after `scope.approved`, the planner order as `work_order.issued` on `phase/<n>` under the id the continuation named, and confirms no planner order of the phase is pending. A receipt prints the kind, digest, owner and time and the phase numbers and story ids the approval recorded and exits 0, a commitment's with a further line, `planner work order: <id>, which a session's phase-plan with the same stories launches`, which a `draft-approved` refusal of that commitment prints too; a refusal prints `<code>: <reason>`, followed by a stale draft's path or a malformed submission's section and field, and exits 2; a failure exits 1 (`crates/baley/src/scope/command.rs`, `approve`, `host_admitted` and `answer_render`, `crates/baley/src/scope/approve.rs`, `judge`, `record_commitment`, `OrderRoute`, `judge_change_draft`, `detail_in_force`, `Approval`, `approvals_of`, `accept_change`, `change_refused`, `record`, `change_decision` and `confirm_detail`, `crates/baley/src/providers/identity.rs`, `owner`). The owner also submits the five changes that carry only numbers and ids: `baley phase reorder <NUMBER>...`, `baley phase withdraw <NUMBER> [<STORY>=<PHASE>|<STORY>=drop]...`, `baley story reassign <ID> <PHASE>|backlog`, `baley story drop <ID>` and `baley backlog reorder <ID>...`. Each turns its words into the members a session sends for the same change and goes through the same functions as the session's operation: the same judgement of the shape, the same check against accepted scope before checkout admission and the policy step, so a refused change records nothing, and the same recording, so the same content gets the same draft digest from either surface. The draft is recorded as the owner with no caller, under the policy version the step returned, and the command prints the draft's kind, digest and time and the `baley scope approve` command that approves it (`crates/baley/src/scope/command.rs`, `submit_change`, `admitted`, `submission_render` and `change_members`). Declarations, edits and `project describe` have no command, since an agent drafts their text. @@ -166,6 +171,8 @@ The owner also reads and answers a question set at the terminal ([0005](0005-con The owner approves a story's truths with `baley story truths approve <digest>`, the digest a `context-submit` receipt named, written as 64 lowercase hexadecimal characters ([0005](0005-context-plans-and-acceptance.md) `story truths approve`). No MCP spelling approves truths. The approval's first step reads the draft and judges it outside any transaction, each refusal recording nothing, in this order: `unknown-draft` for a digest that is not a story's truth draft; `stale-draft` for a draft older than its story's newest truth draft, naming the first part that differs; `draft-approved` naming the earlier approval's owner and time; `no-such-story`; `question-set-abandoned` when the draft's set is not the story's latest; `question-open` naming every open question of that set; and `dispatch-active` while a worker is dispatched on the phase the story is committed to. A draft whose body this project purged, or that no longer judges as the truths it was, is answered `ledger-unavailable`. The step gives each truth its version against the story's current truths: an unchanged truth keeps its version, a changed one gets the next, a new id starts at 1 and an id added back continues past its highest earlier version. The command then admits the checkout, runs the policy step and reads the owner as `baley scope approve` does, and records one `story.refined` on `roadmap` with actor `owner`, the owner's name and Baley's clock, carrying the set, the digest and the story's whole truth list with each version. Its transaction confirms that nothing the first step read has moved and otherwise answers `ledger-busy` with nothing recorded. The receipt prints the approval, the story and its set, and one line per truth with its version, and exits 0; a refusal prints `<code>: <reason>` with the open questions, the differing part or the earlier approval, and exits 2; a failure exits 1 (`crates/baley/src/refine/command.rs`, `approve` and `approval_render`, `crates/baley/src/refine/approve.rs`, `judge` and `record`). +The owner approves a plan draft with `baley plan approve <digest>`, the digest a `plan-submit` or `plan-replace` receipt named, written as 64 lowercase hexadecimal characters ([0005](0005-context-plans-and-acceptance.md) `plan approve`). No MCP spelling approves a plan. The command reads and builds the policy first, since the approval's first step judges the plan under the capacity that policy sets. The first step reads the draft and judges it outside any transaction, each refusal recording nothing, in this order: `unknown-draft`; `stale-draft`, naming the first differing path; `draft-approved`, naming the earlier approval's owner and time; `question-open`, naming each open question of the draft's set; `answer-not-applied`, naming each question whose answer rejected its recommendation; and `phase-not-active` while a different phase is active. A replacement is judged again for `no-such-plan` and `admitted-plan`, and the plan is judged again against the phase as it stands, with every refusal of `plan-submit`'s plan judgement, `over-capacity` among them. The command then admits the checkout and runs the policy step, judges the plan again when the policy the step recorded sets another capacity or suite, reads the owner as `baley scope approve` does, and records one `plan.approved` on `phase/<n>` with actor `owner`, the owner's name and Baley's clock, numbered one more than the highest plan number ever assigned in the phase, with the suite from `workflow.test_command` or none, and for a replacement `plan.replaced` in the same transaction. Its transaction confirms that nothing the first step read has moved and otherwise answers `ledger-busy` with nothing recorded. It prints `approved plan <n> of phase <p> as <owner> at <at>`, the digest, the stories, the size and the suite, or `suite: none` with the reason, and for a replacement the plan it replaced, and exits 0; a refusal prints `<code>: <reason>` with what its details name and exits 2; a failure exits 1 (`crates/baley/src/planning/command.rs`, `approve` and `approval_render`, `crates/baley/src/planning/approve.rs`, `judge`, `rejudged` and `record`). `baley plan show <phase>` prints the phase's approved plans through the same read as `plan-read`, every recorded text escaped, and records nothing: it admits no checkout and runs no policy step (`crates/baley/src/planning/command.rs`, `show` and `show_render`). + `baley story refinement <id>` prints a story's refinement through the same read as `context-intake`: the description, the story and its truth count, its committed phase or `phase: backlog`, each current truth at its version with its kind, attestations and any human check, and every earlier version, or `truths: none` before its first refinement. Every recorded text is escaped. It records nothing and issues no order: it admits no checkout and runs no policy step (`crates/baley/src/refine/command.rs`, `refinement` and `refinement_render`). ### Long-call handle @@ -346,7 +353,7 @@ The check takes an `update.check` claim before any fetch. Only a new claim permi 4. Recheck the stable link, create a temporary link beside it and activate with one atomic rename exchange of the two links (`renameat2` with `RENAME_EXCHANGE` on Linux, `renamex_np` with `RENAME_SWAP` on macOS). Sync the stable folder and inspect the displaced link. An unexpected occupant is restored by another exchange. An activation error attempts restoration where an exchange occurred; a failed restoration reports the retained temporary entry for inspection. No running executable is overwritten (`crates/baley/src/update/deliver.rs`, `activation_decision`, `restore_operations`, `swapped_decision`, `apply_activation`, `restore_after_error` and `exchange`). 5. Stop lease renewal and complete the claim with its `update.checked` or `update.failed` event in the same transaction. Only after that completion attempt returns does a successfully activated version run its own hidden `baley update seed`, directly from its staged path, to record its compiled catalog without a provider call. The seed has a 60-second deadline and a 4 KiB output bound. A newer view set raised during seeding therefore cannot fence the older updater's completion attempt. The seed still runs if completion failed; the receipt then reports an incomplete record and the new active version (`crates/baley/src/update/command.rs`, `claimed_check`, `crates/baley/src/update/record.rs`, `complete`, `crates/baley/src/update/seed.rs`, `launch_for`, `interpret`, `gather`, `run` and `seed_compiled`). -Every version is kept. An activation receipt lists the version folders holding regular binaries, including the active version, in numeric order. #14 owns pruning at activation. New sessions start the newly active server, while running servers keep their executable and loaded instructions. Each new hook call follows the stable path. The hook never rebuilds views. The view set is 13: T15's `install` view raised it to 8, the five scope views of Build 4 T3 raised it to 9, Build 4 T4 raised it to 10 with the same views, when it raised the projector versions of the `draft`, `roadmap`, `phase` and `backlog` views for the scope change events, Build 4 T5 raised it to 11 with the `work_order` view, Build 4 T6 raised it to 12 with the `questions` view, and Build 4 T7 raised it to 13 with the `truths` view (`crates/baley/src/ledger/open.rs`, `options`). Update events go only into `user`, so the hook adds no new event type to the running session's project. Each rise has a cost. A binary at an older view set is read-only on `user` once a newer binary has written there and brought its views to the newer set, so it cannot write the guard's records, the model catalog or update outcomes that live in `user`. A project is fenced for older binaries only after a binary at the newer view set has used it, and install writes only `user`. The policy step before every project write reads the model catalog's version from `user` and takes 0 when that read is refused for a newer view set, so the session's own project stays writable for an older server (`crates/baley/src/policy_step/mod.rs`, `observe_catalog_version`). A binary built before that rule (#258) can write no project once `user` is at a newer view set. Binaries built before T14 cannot write `user` once it holds an update event, binaries built before T15 cannot write it once it holds `install.recorded`, and binaries built before T16 cannot write it once it holds `providers.acknowledged`, because they do not know the event types. In the same way a binary built before Build 4 T3 cannot write a project once it holds a scope event, one built before Build 4 T4 cannot once it holds a scope change event or a `scope.submitted` at version 2, one built before Build 4 T5 cannot once it holds a `work_order.issued` or `work_order.failed`, and one built before Build 4 T6 cannot once it holds a question event (`crates/baley-store-sqlite/src/transact.rs`, `SqliteStore::check_readable`). No such binary was released, since only development binaries exist. A later binary that raises the ledger epoch can still make an older server read-only under [ADR 0034](../adr/0034-one-server-per-session.md). A running session keeps the server and tools it started with, and a new session loads the installed ones, as its `/mcp` screen and the `baley_version` result show (`spikes/host-matrix/install-live-2026-10-11-run1.md` `#inst.after.mcp`, `#inst.after.version`). That the session started before the install lacked them rests on its own answer (`#inst.old-session.server`). The same session reported listing the new stubs at its next turn, unverified because the host showed only a count of skills (`#inst.old-session.stub`). A manual `baley update` with a session running left that session on its version and gave a new session the new one, and the opt-in check staged a newer version while the session's server had already finished its handshake (`#man.update.receipt`, `#man.s1.keeps`, `#man.s2.new`, `#optin.staged`, `#optin.no-wait`, the last judged under the rule at the run, which the sheet records). The live run put the newer hook beside an older server: the older server kept answering `baley_version`, the newer hook answered through the stable path with its records in `user`, and the older binary's own guard could not record in `user` and turned its ask into a deny (`#old.s3.version`, `#old.s3.hook`, `#old.user-refusal`). The older server's captures in its own project were refused, the defect that the rule above fixes (issue 258, pull request 260) (`#old.s3.capture-1`, `#old.s3.keeps`). The repeat at Build 4 T3's raise of the view set to 9 put a binary at view set 8 that holds the fix beside one at view set 9 (sheet `spikes/host-matrix/older-server-live-2026-10-15.md`). After install brought `user` to view set 9, the older server kept answering and recorded captures in its own project, the newer hook answered through the stable path, and the older binary's own guard could not record in `user` and denied the call. Once the binary at view set 9 had used the project, the older server's next capture was refused `ProjectReadOnly` and nothing was recorded (`older-server-live-2026-10-15.md#old.s3.keeps`, `#old.s3.hook`, `#old.user-refusal`, `#old.s3.fenced`) (`crates/baley/src/ledger/open.rs`, `options`, `server_options` and `guard_options`). The raises to 10, 11, 12 and 13 were not repeated in a live session. +Every version is kept. An activation receipt lists the version folders holding regular binaries, including the active version, in numeric order. #14 owns pruning at activation. New sessions start the newly active server, while running servers keep their executable and loaded instructions. Each new hook call follows the stable path. The hook never rebuilds views. The view set is 14: T15's `install` view raised it to 8, the five scope views of Build 4 T3 raised it to 9, Build 4 T4 raised it to 10 with the same views, when it raised the projector versions of the `draft`, `roadmap`, `phase` and `backlog` views for the scope change events, Build 4 T5 raised it to 11 with the `work_order` view, Build 4 T6 raised it to 12 with the `questions` view, Build 4 T7 raised it to 13 with the `truths` view, and Build 4 T9 raised it to 14 with the `phase_plan`, `plan` and `evidence_map` views, beside the `backlog` view's version 4 (`crates/baley/src/ledger/open.rs`, `options`). Update events go only into `user`, so the hook adds no new event type to the running session's project. Each rise has a cost. A binary at an older view set is read-only on `user` once a newer binary has written there and brought its views to the newer set, so it cannot write the guard's records, the model catalog or update outcomes that live in `user`. A project is fenced for older binaries only after a binary at the newer view set has used it, and install writes only `user`. The policy step before every project write reads the model catalog's version from `user` and takes 0 when that read is refused for a newer view set, so the session's own project stays writable for an older server (`crates/baley/src/policy_step/mod.rs`, `observe_catalog_version`). A binary built before that rule (#258) can write no project once `user` is at a newer view set. Binaries built before T14 cannot write `user` once it holds an update event, binaries built before T15 cannot write it once it holds `install.recorded`, and binaries built before T16 cannot write it once it holds `providers.acknowledged`, because they do not know the event types. In the same way a binary built before Build 4 T3 cannot write a project once it holds a scope event, one built before Build 4 T4 cannot once it holds a scope change event or a `scope.submitted` at version 2, one built before Build 4 T5 cannot once it holds a `work_order.issued` or `work_order.failed`, one built before Build 4 T6 cannot once it holds a question event, one built before Build 4 T7 cannot once it holds a `story.refined`, and one built before Build 4 T9 cannot once it holds a plan event (`crates/baley-store-sqlite/src/transact.rs`, `SqliteStore::check_readable`). No such binary was released, since only development binaries exist. A later binary that raises the ledger epoch can still make an older server read-only under [ADR 0034](../adr/0034-one-server-per-session.md). A running session keeps the server and tools it started with, and a new session loads the installed ones, as its `/mcp` screen and the `baley_version` result show (`spikes/host-matrix/install-live-2026-10-11-run1.md` `#inst.after.mcp`, `#inst.after.version`). That the session started before the install lacked them rests on its own answer (`#inst.old-session.server`). The same session reported listing the new stubs at its next turn, unverified because the host showed only a count of skills (`#inst.old-session.stub`). A manual `baley update` with a session running left that session on its version and gave a new session the new one, and the opt-in check staged a newer version while the session's server had already finished its handshake (`#man.update.receipt`, `#man.s1.keeps`, `#man.s2.new`, `#optin.staged`, `#optin.no-wait`, the last judged under the rule at the run, which the sheet records). The live run put the newer hook beside an older server: the older server kept answering `baley_version`, the newer hook answered through the stable path with its records in `user`, and the older binary's own guard could not record in `user` and turned its ask into a deny (`#old.s3.version`, `#old.s3.hook`, `#old.user-refusal`). The older server's captures in its own project were refused, the defect that the rule above fixes (issue 258, pull request 260) (`#old.s3.capture-1`, `#old.s3.keeps`). The repeat at Build 4 T3's raise of the view set to 9 put a binary at view set 8 that holds the fix beside one at view set 9 (sheet `spikes/host-matrix/older-server-live-2026-10-15.md`). After install brought `user` to view set 9, the older server kept answering and recorded captures in its own project, the newer hook answered through the stable path, and the older binary's own guard could not record in `user` and denied the call. Once the binary at view set 9 had used the project, the older server's next capture was refused `ProjectReadOnly` and nothing was recorded (`older-server-live-2026-10-15.md#old.s3.keeps`, `#old.s3.hook`, `#old.user-refusal`, `#old.s3.fenced`) (`crates/baley/src/ledger/open.rs`, `options`, `server_options` and `guard_options`). The raises to 10, 11, 12, 13 and 14 were not repeated in a live session. The claim protocol in section 6 prevents manual and detached checks from overlapping. Only a detached check refuses a day already claimed, including one claimed manually. Manual checks can retry that day under a fresh request once the installation scope is free. @@ -440,14 +447,14 @@ The interview's host step adds provider hosts to the same settings file after in ### work_order.issued and work_order.failed (events, the order's stream) -A work order is recorded as one `work_order.issued` on its subject's stream, `roadmap` for the start planner's order, subject `start`, and for a story's analyzer orders, subject `story/<id>` for both the questions order and the drafting order, and its failure as one `work_order.failed` on the same stream. Both are registered at version 1 with no upcasters. Neither payload holds a caller or a time: the envelope carries both, hashed with the event (`crates/baley-core/src/work_order/event.rs`, `WORK_ORDER_ISSUED`, `WORK_ORDER_FAILED`, `register_work_order_events` and `order_stream`). +A work order is recorded as one `work_order.issued` on its subject's stream, `roadmap` for the start planner's order, subject `start`, and for a story's analyzer orders, subject `story/<id>` for both the questions order and the drafting order, and `phase/<n>` for a phase planner's planning and revision orders, subject `phase/<n>`, and its failure as one `work_order.failed` on the same stream. Both are registered at version 1 with no upcasters. Neither payload holds a caller or a time: the envelope carries both, hashed with the event (`crates/baley-core/src/work_order/event.rs`, `WORK_ORDER_ISSUED`, `WORK_ORDER_FAILED`, `register_work_order_events` and `order_stream`). | Event | Payload | |---|---| | `work_order.issued` | `id`, a lowercase UUID; `request`, the id of its chain's first order, its own id at attempt 1; `parent`, the failed order it retries, or null; `role`; `subject`; `attempt`; `route`, the route record ([0003](0003-configuration-and-routing.md) section 6); `agent`, the agent stub `bal-<role>-<rung>`; `instructions`, each `{identity, version, hash}`, in order; and `inputs`, each `{name, body}`, the body a reference to a `record` payload the event attaches | | `work_order.failed` | `id`, the order, and `reason`, the session's plain words | -The `work_order` view holds one document per order, keyed by its id, with the issued payload's members and its `state`, `seq`, `recorded_at`, `failure`, `drafts` and `child` (section 5, `document`). An order is `pending` when issued, `failed` once `work_order.failed` names it, and `answered` once a `scope.submitted` whose caller carries its id names it, which also adds the draft's digest to its `drafts` once. A truth draft's `scope.submitted` answers a story's drafting order the same way. A story set's `questions.opened` naming an order answers that questions order: the set's id is added to its `drafts` once and a pending order becomes `answered`, while a plan draft's set changes no order. A failed order stays failed when a later submission or set names it. A retry sets its parent's `child`. The view's `live` index runs over role, subject and state, newest first, so a transaction can declare that no pending start planner order exists, or no pending analyzer order of one story, since both of its orders share the subject (`crates/baley-core/src/work_order/view.rs`, `WORK_ORDER_VIEW`, `work_order_spec` and `WorkOrderProjector`). The view raised the view set to 11, and its version 2, which reads story sets, is part of view set 13. +The `work_order` view holds one document per order, keyed by its id, with the issued payload's members and its `state`, `seq`, `recorded_at`, `failure`, `drafts` and `child` (section 5, `document`). An order is `pending` when issued, `failed` once `work_order.failed` names it, and `answered` once a `scope.submitted` whose caller carries its id names it, which also adds the draft's digest to its `drafts` once. A truth draft's `scope.submitted` answers a story's drafting order the same way. A story set's `questions.opened` naming an order answers that questions order: the set's id is added to its `drafts` once and a pending order becomes `answered`, while a plan draft's set changes no order. A failed order stays failed when a later submission or set names it. A retry sets its parent's `child`. The view's `live` index runs over role, subject and state, newest first, so a transaction can declare that no pending start planner order exists, no pending analyzer order of one story, since both of its orders share the subject, or no pending planner order of one phase (`crates/baley-core/src/work_order/view.rs`, `WORK_ORDER_VIEW`, `work_order_spec` and `WorkOrderProjector`). The view raised the view set to 11, and its version 2, which reads story sets, came with view set 13. ### The caller on every recorded event @@ -755,7 +762,7 @@ sequenceDiagram Note over S,V: The next hook uses the stable path and never rebuilds views ``` -*Figure 8. Manual and opt-in detached checks share the claim, verification and activation path. Only a detached check applies the daily refusal, and a manual claim also covers the day's automatic check. Delivery stops on failure. The completion attempt returns before the newly activated binary seeds its catalog, even when recording failed, so a newer view set cannot fence that attempt. The detached process discards its receipt, and the server never waits for it. Running servers keep their binaries, the next hook follows the stable path, and the view set is 13, raised to 8 by T15's `install` view, to 9 by the scope views of Build 4 T3, to 10 by the scope change events of Build 4 T4, to 11 by the `work_order` view of Build 4 T5, to 12 by the `questions` view of Build 4 T6 and to 13 by the `truths` view of Build 4 T7, never by an update. `baley install` writes the stubs. A new session reported listing the stubs of the build it ran (its own answer, unverified), and no live session has loaded the agent stubs yet. The live run showed a manual update leaving a running session on its version and a new session on the new one, the opt-in check staging without the session waiting for it, and the newer hook answering beside an older server (`spikes/host-matrix/install-live-2026-10-11-run1.md` `#man.s1.keeps`, `#man.s2.new`, `#optin.no-wait`, `#old.s3.hook`). #14 supplies signature verification at both download-to-staging seams before any release.* +*Figure 8. Manual and opt-in detached checks share the claim, verification and activation path. Only a detached check applies the daily refusal, and a manual claim also covers the day's automatic check. Delivery stops on failure. The completion attempt returns before the newly activated binary seeds its catalog, even when recording failed, so a newer view set cannot fence that attempt. The detached process discards its receipt, and the server never waits for it. Running servers keep their binaries, the next hook follows the stable path, and the view set is 14, raised to 8 by T15's `install` view, to 9 by the scope views of Build 4 T3, to 10 by the scope change events of Build 4 T4, to 11 by the `work_order` view of Build 4 T5, to 12 by the `questions` view of Build 4 T6, to 13 by the `truths` view of Build 4 T7 and to 14 by the `phase_plan`, `plan` and `evidence_map` views of Build 4 T9, never by an update. `baley install` writes the stubs. A new session reported listing the stubs of the build it ran (its own answer, unverified), and no live session has loaded the agent stubs yet. The live run showed a manual update leaving a running session on its version and a new session on the new one, the opt-in check staging without the session waiting for it, and the newer hook answering beside an older server (`spikes/host-matrix/install-live-2026-10-11-run1.md` `#man.s1.keeps`, `#man.s2.new`, `#optin.no-wait`, `#old.s3.hook`). #14 supplies signature verification at both download-to-staging seams before any release.* ## 9. Settings @@ -766,7 +773,7 @@ sequenceDiagram | `owner.name` | one line of text, not blank, with no control character | absent, with git `user.name` as the reader's fallback | global | 0012 | The owner recorded on every approval and on the provider acknowledgement (HST-R10), and in every answer and deferral to a question set (HST-R9), set with `baley config set --global owner.name="Your Name"`. With neither it nor git `user.name`, an approval, an answer call or an acknowledgement is refused `owner-identity-missing`. The interview never asks it | | `[host.<name>]` sections | see [0003](0003-configuration-and-routing.md) | | both | 0003 | Per-host overrides the adapter applies | -Both update settings and `owner.name` are in the standard schema used by `baley config set` and the settings interview (`crates/baley-core/src/policy/schema.rs:199-207, 353-367, 375-382`). The owner reader takes `owner.name` from the global settings and falls back to git `user.name` only when it is absent (`crates/baley/src/providers/identity.rs:24-51`). +Both update settings and `owner.name` are in the standard schema used by `baley config set` and the settings interview (`crates/baley-core/src/policy/schema.rs` (`is_https_address` and `standard`)). The owner reader takes `owner.name` from the global settings and falls back to git `user.name` only when it is absent (`crates/baley/src/providers/identity.rs` (`owner` and `owner_name`)). No setting selects, loads or overrides an instruction, because every instruction is compiled in (HST-R11). No setting chooses an artifact's content or placement either: the content is rendered from the compiled tables and supplied values (section 10), and the placement is derived from `HOME` and `CLAUDE_CONFIG_DIR` by `baley install`, the guard and the doctor alike, not set (section 5). @@ -776,22 +783,22 @@ 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":"<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-<role>-<rung>`, 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; `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 | +| 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), `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`, and `bal-plan`, at version 1, which plans one phase: `phase-plan` and the commitment the owner approves with `baley scope approve`, the planner's order it hands over or issues, `plan-submit` or `plan-replace` with the planner's plan, the draft's rounds through `bal-rounds` and the revision order a rejected recommendation brings, the owner's approval with `baley plan approve`, and `plan-read`. `bal-context` is ported from Cadence `v3.9.0`'s `cad-context` skill and `context.md` workflow, and `bal-plan` from its `cad-plan` skill and `plan.md` workflow, each with every 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`, `crates/baley/src/instruction/plan.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; `bal-start-survey`, which a start order lists only when the checkout holds existing code; and `bal-phase-planner`, which a phase's planning and revision work orders list: 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 | +| Rounds relay | The host session, by identity, as `bal-rounds` at version 2, which `bal-context`, `bal-plan`, the round read and the `questions-answer` receipt name, for a story's set and a plan draft's alike. Its submit step is for a story's analyzer questions only: submit a questions order's return as returned with `story-questions-submit`, an empty set's receipt naming the drafting order; a plan draft's set, which `plan-submit` or `plan-replace` already opened, starts at the round read. 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, `crates/baley/src/instruction/rounds.rs`, `TEXT`) | 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 | | Help | The host session and the owner: the list of commands with one line each, each command's availability and owning build, and help's own identity, version and hash | HST-R13, HST-R16 | 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`, 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`). +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`, `story-refine` and `phase-plan` 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 4, and the help answer's `request` name `story-refine` and `phase-plan` 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). | Artifact | Inputs | Content | Requirement | Placement | |---|---|---|---|---| -| Skill stub, one per served front door (`bal-project`, `bal-scope`, `bal-phase`, `bal-story`, `bal-backlog`, `bal-context`, `bal-capture`, `bal-help`) | The compiled help table and instruction registry | Frontmatter `name` and `description`, then the one-line `baley_query` `instruction` call. There is no `allowed-tools` line, so each `baley_query` call is approved by the owner (`crates/baley/src/host_artifacts/stubs.rs`, `front_doors` and `render`) | HST-R12 | `<Claude folder>/skills/<identity>/SKILL.md`, written by `baley install` | +| Skill stub, one per served front door (`bal-project`, `bal-scope`, `bal-phase`, `bal-story`, `bal-backlog`, `bal-context`, `bal-plan`, `bal-capture`, `bal-help`) | The compiled help table and instruction registry | Frontmatter `name` and `description`, then the one-line `baley_query` `instruction` call. There is no `allowed-tools` line, so each `baley_query` call is approved by the owner (`crates/baley/src/host_artifacts/stubs.rs`, `front_doors` and `render`) | HST-R12 | `<Claude folder>/skills/<identity>/SKILL.md`, written by `baley install` | | Agent stub, one per role and rung (`bal-planner-low` to `bal-reviewer-max`) | The compiled role, rung and name tables and the registration key `baley` | Frontmatter `name`, `description`, `model: inherit`, `effort` and `mcpServers: [baley]`, then the one-line `document` call for the order (`crates/baley/src/host_artifacts/agents.rs`, `render` and `manifest`) | HST-R12 | `<Claude folder>/agents/<name>.md`, written by `baley install` | | MCP registration | The absolute executable, and whether to set `alwaysLoad` | `mcpServers.baley` with `command` the executable and `args` `["serve"]`, `alwaysLoad: true` only on request, and no `cwd`, `env`, URL, headers or token (`crates/baley/src/host_artifacts/registration.rs`, `KEY` and `render`) | HST-R17, HST-R20 | `mcpServers.baley` in `$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json`, written by Claude Code through `claude mcp add-json --scope user`, which `baley install` runs. Install sets no `alwaysLoad` | | Guard hook | The absolute executable | One `PreToolUse` item matching `Bash\|Monitor\|PowerShell\|Read\|Grep\|Glob\|Write\|Edit\|NotebookEdit`, with one command hook that runs the single-quoted executable and `guard` within 10 seconds (`crates/baley/src/host_artifacts/hook.rs`, `EVENT`, `MATCHER`, `render`, `command` and `shell_quote`) | GRD-R1 | The `hooks.PreToolUse` array of `<Claude folder>/settings.json`, written by `baley install` | @@ -801,26 +808,26 @@ The manifest lists each stub's host, kind, skill or agent, identity, bytes and l ## 11. Build status -The library holds the per-session server (`crates/baley/src/mcp/`), and `baley serve` starts it. The same module prepares a project read or write from the session's own project (`crates/baley/src/mcp/prepare.rs`), and twenty-two served operations reach it: `capture`, `scope-submit`, the ten change operations, `project-describe` to `backlog-reorder`, the three work-order operations `project-start`, `work-order-fail` and `work-order-retry`, `questions-answer`, and the three refinement operations `story-refine`, `story-questions-submit` and `context-submit`, writes, and `document`, `context-intake` and `route`, reads (`crates/baley/src/mcp/handler.rs`, `operate`). The change operations are judged and checked against accepted scope before preparation records anything (`crates/baley/src/mcp/scope.rs`, `judge_change_arguments`, `shape_refused`, `judge_request_id`, `write_request`, `bounded`, `order_caller`, `bind_instructions`, `serve` and `serve_change`), and the work-order operations are judged and checked against the project's work orders and its start the same way (`crates/baley/src/mcp/work_order.rs`, from `judge_start_arguments` to `serve_retry`), and `questions-answer` is judged and checked against its question set the same way (`crates/baley/src/mcp/questions.rs`, `judge_arguments` and `serve`, `crates/baley/src/questions/answer.rs`, `check`), and the refinement operations are judged and checked against the story, its question sets and its analyzer orders the same way (`crates/baley/src/mcp/refine.rs`, `judge_arguments`, `judge_questions_arguments`, `judge_context_arguments`, `serve`, `serve_questions` and `serve_context`, `crates/baley/src/refine/order.rs`, `check`, `crates/baley/src/refine/questions.rs`, `check`, `crates/baley/src/refine/submit.rs`, `check`). The library also holds the guard hook (`crates/baley/src/guard_hook/`), which `baley guard` runs once per tool call ([0010](0010-guard.md) section 11). It renders Claude Code's artifacts as content (`crates/baley/src/host_artifacts/`, section 10), and `baley install` writes them (`crates/baley/src/install/`, section 5). `baley artifact` prints each one to standard output and writes no file (`crates/baley/src/main.rs`, `Command::Artifact` and its arm in `run_command`, `crates/baley/src/host_artifacts/command.rs`, `select`, `judged`, `escape_controls`, `stdout_bytes`, `stderr_text`, `exit_code`, `print` and `run`). The binary also holds the inherited engine, parked for Build 9 to delete (`crates/baley/src/inherited.rs`, its module comment). Nothing in production reaches it, and its tests still run. +The library holds the per-session server (`crates/baley/src/mcp/`), and `baley serve` starts it. The same module prepares a project read or write from the session's own project (`crates/baley/src/mcp/prepare.rs`), and twenty-six served operations reach it: `capture`, `scope-submit`, the ten change operations, `project-describe` to `backlog-reorder`, the three work-order operations `project-start`, `work-order-fail` and `work-order-retry`, `questions-answer`, the three refinement operations `story-refine`, `story-questions-submit` and `context-submit`, and the three planning operations `phase-plan`, `plan-submit` and `plan-replace`, writes, and `document`, `context-intake`, `plan-read` and `route`, reads (`crates/baley/src/mcp/handler.rs`, `operate`). The change operations are judged and checked against accepted scope before preparation records anything (`crates/baley/src/mcp/scope.rs`, `judge_change_arguments`, `shape_refused`, `judge_request_id`, `write_request`, `bounded`, `order_caller`, `bind_instructions`, `serve` and `serve_change`), and the work-order operations are judged and checked against the project's work orders and its start the same way (`crates/baley/src/mcp/work_order.rs`, from `judge_start_arguments` to `serve_retry`), and `questions-answer` is judged and checked against its question set the same way (`crates/baley/src/mcp/questions.rs`, `judge_arguments` and `serve`, `crates/baley/src/questions/answer.rs`, `check`), and the refinement operations are judged and checked against the story, its question sets and its analyzer orders the same way (`crates/baley/src/mcp/refine.rs`, `judge_arguments`, `judge_questions_arguments`, `judge_context_arguments`, `serve`, `serve_questions` and `serve_context`, `crates/baley/src/refine/order.rs`, `check`, `crates/baley/src/refine/questions.rs`, `check`, `crates/baley/src/refine/submit.rs`, `check`), and the planning operations are judged and checked against the phase, its stories, its planner orders and its plans the same way (`crates/baley/src/mcp/planning.rs`, `judge_arguments`, `judge_submit_arguments`, `serve` and `serve_submit`, `crates/baley/src/planning/phase_plan.rs`, `check`, `crates/baley/src/planning/submit.rs`, `check`, `crates/baley/src/planning/replace.rs`, `check`). The library also holds the guard hook (`crates/baley/src/guard_hook/`), which `baley guard` runs once per tool call ([0010](0010-guard.md) section 11). It renders Claude Code's artifacts as content (`crates/baley/src/host_artifacts/`, section 10), and `baley install` writes them (`crates/baley/src/install/`, section 5). `baley artifact` prints each one to standard output and writes no file (`crates/baley/src/main.rs`, `Command::Artifact` and its arm in `run_command`, `crates/baley/src/host_artifacts/command.rs`, `select`, `judged`, `escape_controls`, `stdout_bytes`, `stderr_text`, `exit_code`, `print` and `run`). The binary also holds the inherited engine, parked for Build 9 to delete (`crates/baley/src/inherited.rs`, its module comment). Nothing in production reaches it, and its tests still run. | Requirement | Status | Where | |---|---|---| | HST-R1 | Built | `baley serve` runs one stdio server for the session (`crates/baley/src/main.rs`, `Command::Serve` and `run_serve`, `crates/baley/src/mcp/serve.rs`, `run`), and it advertises only the two tested revisions (`crates/baley/src/mcp/tools.rs`, `supported_protocol_versions`, `crates/baley/src/mcp/handler.rs`, `supported_protocol_versions`) | | HST-R2, HST-R3 | Withdrawn | Nothing to build: each session starts its own stdio server (ADR 0034) | | HST-R4 | Built | The 2025 decoder reads `initialize` and the 2026 decoder reads the request's `_meta` (`crates/baley/src/mcp/client.rs`, `decode_2025` and `decode_2026`). The host is selected per call (`crates/baley/src/mcp/client.rs`, `select`, `crates/baley/src/mcp/handler.rs`, `remember`, `selection`, `initialize` and `call_tool`), and a missing or unsupported client is answered `failed` `unknown-host` before the queue (`crates/baley/src/mcp/gate.rs`, `before_queue` and `unknown_host`). The supported hosts are `Host::ALL` (`crates/baley-core/src/policy/schema.rs`, `Host`) | -| HST-R5 | Built | Three tools in a fixed order (`crates/baley/src/mcp/tools.rs`, `tools`), append-only operation names, with `instruction` appended last to the query baseline (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS`, its `instruction` entry) and `scope-submit`, then the ten change spellings `project-describe`, `phase-declare`, `phase-edit`, `phase-reorder`, `phase-withdraw`, `story-declare`, `story-edit`, `story-reassign`, `story-drop` and `backlog-reorder`, appended after it, and `project-start`, `work-order-fail` and `work-order-retry` appended after them, then `questions-answer`, and `story-refine` and `story-questions-submit` appended after it at the end of the apply baseline (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`), with `route` and `context-intake` changed in place in the query baseline, and `context-submit` in the apply baseline, from retired spellings to served ones (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS`, its `route` and `context-intake` entries, and `APPLY_OPERATIONS`, its `context-submit` entry), held by the expected spellings and the test that checks both baselines against them (`crates/baley/src/mcp/operations.rs`, `expected` and `the_baseline_lists_keep_todays_order_with_instruction_appended_last`), a flat schema that types each served operation's arguments from the request shapes `schema` serves, with no combinator at the top (`crates/baley/src/mcp/tools.rs`, `operation_schema`, `Shapes`, `arguments` and `with_takers`, held by the tests in `crates/baley/src/mcp/tools.rs`, `tests`), plus the `schema` operation, which serves each served operation's request shape, the `capture`, `scope-submit`, change, work-order, `questions-answer`, refinement, `context-intake`, `route` and `document` shapes included, with `document` taking the seven identity kinds `capture`, `draft`, `roadmap`, `story`, `work_order`, `questions` and `refinement` (`crates/baley/src/mcp/refine.rs`, `RefineShape`, `QuestionsShape`, `ContextShape` and `IntakeShape`, `crates/baley/src/mcp/operations.rs`, `RequestShape`, `schema_answer` and `served_schema`, `crates/baley/src/mcp/capture.rs`, `CaptureShape`, `crates/baley/src/mcp/scope.rs`, `SubmitShape`, `SubmitCall` and `change_shapes`, `crates/baley/src/mcp/work_order.rs`, `StartShape`, `FailShape`, `RetryShape` and `RouteShape`, `crates/baley/src/mcp/questions.rs`, `AnswerShape`, `crates/baley/src/mcp/document.rs`, `DocumentShape` and `Identity`), and `failed` as its own arm of the envelope (`crates/baley/src/envelope.rs`, `Envelope`, `SERVER_OVERLOADED`, `LEDGER_BUSY` and `RETRYABLE_CODES`). The gate raises a protocol error only for an unknown tool (`crates/baley/src/mcp/gate.rs`, `before_queue` and `unknown_tool`) | -| HST-R6 | Partly built | `help`, `schema`, `instruction` and `document` answer whole, or in parts of at most 24,576 body bytes, through one helper (`crates/baley/src/mcp/parts.rs`, `PART_BOUND`, `Cut` and `cut`) in the four answers (`crates/baley/src/mcp/operations.rs`, `help_answer`, `instruction_answer` and `schema_answer`, `crates/baley/src/mcp/document.rs`, `answer` and `in_parts`). Instructions are read by identity through `instruction`, and the tools carry a fixed order and cache hints (`crates/baley/src/mcp/tools.rs`, `tool_list`). `document` serves captures, drafts by digest, the roadmap, stories by id, work orders by id, question sets by set id and a story's refinement by story id, which `context-intake` also answers, both cut from their JSON text (`crates/baley/src/mcp/document.rs`, `refinement_answer`, `crates/baley/src/mcp/refine.rs`, `intake_answer`, `crates/baley/src/mcp/document.rs`, `Identity` and `read`). A work order answers its view document, its accepted result read from the start approval, the fixed sentence sending the worker to the instructions it lists, and each input. An input this project purged answers this project's own tombstone reason from its `retention` stream, and one the store reports purged with no release of this project's answers `unavailable` with no reason. The answer is cut from its JSON text (`crates/baley/src/mcp/document.rs`, `work_order_answer` and `order_inputs`, `crates/baley/src/work_order/read.rs`, `order`, `order_document`, `pending_start`, `Release`, `Releases`, `releases` and `accepted`). A question set answers its round, worked out when read from the `questions` view and cut from its JSON text, and a set this project does not hold answers `no-such-question-set` (`crates/baley/src/mcp/document.rs`, `questions_answer`, `crates/baley/src/questions/read.rs`, `read` and `round_value`). Every part of a capture carries the identity and the capture's metadata (`crates/baley/src/mcp/document.rs`, `answer`, `read_document` and `gone_answer`), and a draft, the roadmap and a story are cut from their answer's JSON text (`crates/baley/src/mcp/document.rs`, `draft_answer`, `roadmap_answer`, `story_answer` and `in_parts`). A purged capture answers with its own project's tombstone reason, re-reading that view when the body lookup observes a later purge (`crates/baley/src/mcp/document.rs`, `CaptureDocument::source`, `read_document` and `gone_answer`). A draft this project purged answers its tombstone from the `draft` view without opening the body, and does not re-read the view (`crates/baley/src/mcp/document.rs`, `draft_answer`, `crates/baley/src/scope/read.rs`, `draft` and `draft_of`). Its other identity kinds are their builds', and `document-search` answers `operation-unavailable` until Build 8 (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS` and `operation_unavailable`). In the 2026-10-08 runs part 1 of a 33,000-byte capture arrived as 24,576 bytes naming part 2 as next, byte-identical to the first 24,576 bytes of the fixture, in the main session and in a subagent (`claude-live-2026-10-08-run2.md#hand.parts.document-main`, `#hand.parts.document-subagent`). The first run's `document` calls had failed because Claude Code sent the nested identity as JSON text (`claude-live-2026-10-08-run1.md#hand.parts.document-main`, issue #232, fixed in bug pull request #234), and the second run was made against a commit that holds the fix. `help` (4,819 bytes) and `instruction` (1,366 bytes) arrived whole as one answer (`claude-live-2026-10-08-run2.md#hand.parts.help`, `#hand.parts.instruction`). Only part 1 was read, so the arrival of later parts is unverified, and the bytes on the wire were not measured, though each answer travels as text and as structured content (about twice the body) | +| HST-R5 | Built | Three tools in a fixed order (`crates/baley/src/mcp/tools.rs`, `tools`), append-only operation names, with `instruction` appended last to the query baseline (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS`, its `instruction` entry) and `scope-submit`, then the ten change spellings `project-describe`, `phase-declare`, `phase-edit`, `phase-reorder`, `phase-withdraw`, `story-declare`, `story-edit`, `story-reassign`, `story-drop` and `backlog-reorder`, appended after it, and `project-start`, `work-order-fail` and `work-order-retry` appended after them, then `questions-answer`, `story-refine` and `story-questions-submit` appended after it, and `phase-plan` and `plan-replace` appended after them at the end of the apply baseline (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`), with `route`, `context-intake` and `plan-read` changed in place in the query baseline, and `context-submit` and `plan-submit` in the apply baseline, from retired spellings to served ones (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS`, its `route`, `context-intake` and `plan-read` entries, and `APPLY_OPERATIONS`, its `context-submit` and `plan-submit` entries), held by the expected spellings and the test that checks both baselines against them (`crates/baley/src/mcp/operations.rs`, `expected` and `the_baseline_lists_keep_todays_order_with_instruction_appended_last`), a flat schema that types each served operation's arguments from the request shapes `schema` serves, with no combinator at the top (`crates/baley/src/mcp/tools.rs`, `operation_schema`, `Shapes`, `arguments` and `with_takers`, held by the tests in `crates/baley/src/mcp/tools.rs`, `tests`), plus the `schema` operation, which serves each served operation's request shape, the `capture`, `scope-submit`, change, work-order, `questions-answer`, refinement, planning, `context-intake`, `plan-read`, `route` and `document` shapes included, with `document` taking the nine identity kinds `capture`, `draft`, `roadmap`, `story`, `work_order`, `questions`, `refinement`, `phase` and `plan` (`crates/baley/src/mcp/refine.rs`, `RefineShape`, `QuestionsShape`, `ContextShape` and `IntakeShape`, `crates/baley/src/mcp/planning.rs`, `PhasePlanShape`, `PlanSubmitShape`, `PlanReplaceShape`, `ReplacesShape` and `PlanReadShape`, `crates/baley/src/mcp/operations.rs`, `RequestShape`, `schema_answer` and `served_schema`, `crates/baley/src/mcp/capture.rs`, `CaptureShape`, `crates/baley/src/mcp/scope.rs`, `SubmitShape`, `SubmitCall` and `change_shapes`, `crates/baley/src/mcp/work_order.rs`, `StartShape`, `FailShape`, `RetryShape` and `RouteShape`, `crates/baley/src/mcp/questions.rs`, `AnswerShape`, `crates/baley/src/mcp/document.rs`, `DocumentShape` and `Identity`), and `failed` as its own arm of the envelope (`crates/baley/src/envelope.rs`, `Envelope`, `SERVER_OVERLOADED`, `LEDGER_BUSY` and `RETRYABLE_CODES`). The gate raises a protocol error only for an unknown tool (`crates/baley/src/mcp/gate.rs`, `before_queue` and `unknown_tool`) | +| HST-R6 | Partly built | `help`, `schema`, `instruction` and `document` answer whole, or in parts of at most 24,576 body bytes, through one helper (`crates/baley/src/mcp/parts.rs`, `PART_BOUND`, `Cut` and `cut`) in the four answers (`crates/baley/src/mcp/operations.rs`, `help_answer`, `instruction_answer` and `schema_answer`, `crates/baley/src/mcp/document.rs`, `answer` and `in_parts`). Instructions are read by identity through `instruction`, and the tools carry a fixed order and cache hints (`crates/baley/src/mcp/tools.rs`, `tool_list`). `document` serves captures, drafts by digest, the roadmap, stories by id, work orders by id, question sets by set id and a story's refinement by story id, which `context-intake` also answers, both cut from their JSON text (`crates/baley/src/mcp/document.rs`, `refinement_answer`, `crates/baley/src/mcp/refine.rs`, `intake_answer`, `crates/baley/src/mcp/document.rs`, `Identity` and `read`). It also serves a phase by number with every plan approved in it, which `plan-read` also answers, and one approved plan by phase and number, each cut from its JSON text, a draft's map never among them (`crates/baley/src/mcp/document.rs`, `phase_answer` and `plan_answer`, `crates/baley/src/mcp/planning.rs`, `read_answer`, `crates/baley/src/planning/read.rs`, `read`). A work order answers its view document, its accepted result read from the start approval, the fixed sentence sending the worker to the instructions it lists, and each input. An input this project purged answers this project's own tombstone reason from its `retention` stream, and one the store reports purged with no release of this project's answers `unavailable` with no reason. The answer is cut from its JSON text (`crates/baley/src/mcp/document.rs`, `work_order_answer` and `order_inputs`, `crates/baley/src/work_order/read.rs`, `order`, `order_document`, `pending_start`, `Release`, `Releases`, `releases` and `accepted`). A question set answers its round, worked out when read from the `questions` view and cut from its JSON text, and a set this project does not hold answers `no-such-question-set` (`crates/baley/src/mcp/document.rs`, `questions_answer`, `crates/baley/src/questions/read.rs`, `read` and `round_value`). Every part of a capture carries the identity and the capture's metadata (`crates/baley/src/mcp/document.rs`, `answer`, `read_document` and `gone_answer`), and a draft, the roadmap and a story are cut from their answer's JSON text (`crates/baley/src/mcp/document.rs`, `draft_answer`, `roadmap_answer`, `story_answer` and `in_parts`). A purged capture answers with its own project's tombstone reason, re-reading that view when the body lookup observes a later purge (`crates/baley/src/mcp/document.rs`, `CaptureDocument::source`, `read_document` and `gone_answer`). A draft this project purged answers its tombstone from the `draft` view without opening the body, and does not re-read the view (`crates/baley/src/mcp/document.rs`, `draft_answer`, `crates/baley/src/scope/read.rs`, `draft` and `draft_of`). Its other identity kinds are their builds', and `document-search` answers `operation-unavailable` until Build 8 (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS` and `operation_unavailable`). In the 2026-10-08 runs part 1 of a 33,000-byte capture arrived as 24,576 bytes naming part 2 as next, byte-identical to the first 24,576 bytes of the fixture, in the main session and in a subagent (`claude-live-2026-10-08-run2.md#hand.parts.document-main`, `#hand.parts.document-subagent`). The first run's `document` calls had failed because Claude Code sent the nested identity as JSON text (`claude-live-2026-10-08-run1.md#hand.parts.document-main`, issue #232, fixed in bug pull request #234), and the second run was made against a commit that holds the fix. `help` (4,819 bytes) and `instruction` (1,366 bytes) arrived whole as one answer (`claude-live-2026-10-08-run2.md#hand.parts.help`, `#hand.parts.instruction`). Only part 1 was read, so the arrival of later parts is unverified, and the bytes on the wire were not measured, though each answer travels as text and as structured content (about twice the body) | | HST-R7 | Partly built | The session context is gathered once and judged (`crates/baley/src/mcp/context.rs`, `Observation`, `judge` and `project_context`), each call's context and caller are formed (`crates/baley/src/mcp/context.rs`, `call_context` and `form_caller`), and decisions run one at a time on the worker behind one queue (`crates/baley/src/mcp/queue.rs`, `WAITING_SLOTS`, `BYTE_CAP`, `Placed`, `Refused` and `Queue`, `crates/baley/src/mcp/worker.rs`, `Worker` and `work`, `crates/baley/src/mcp/admission.rs`, `admit` and `overloaded`). The worker publishes a completed drain only when the queue is empty and the last answer has been sent, including on close or abandon (`crates/baley/src/mcp/worker.rs`, `State`, `drain_complete`, `Worker::close`, `Worker::abandon`, `Worker::drained` and `work`). The port holds the caller value (`crates/baley-store/src/caller.rs`, `Caller`), `Work::push` stamps the command's caller on every event it appends (`crates/baley-store-sqlite/src/transact.rs`, `Work::push`) and the `event.caller` column stores it (`crates/baley-store-sqlite/src/schema.rs`, `SCHEMA`'s `caller` column). Preparation finds the project afresh from the caller's project directory and checks that the ledger lists it, and a write goes on to the replay lookup, its operation's own check where it has one, the settings, checkout admission and the policy step in that order. The plan is pure and the entry performs each step it asks for (`crates/baley/src/mcp/prepare.rs`, `next`, `judged_settings`, `Found`, `write_next`, `prepare`, `prepare_checked`, `prepare_settings_read`, `Ended`, `drive` and `perform`). A write with a check is prepared through `prepare_checked`, which returns the check's answer as it is, and when the check ends the call the request is looked up a second time, so a request recorded since the first lookup is replayed rather than refused (`crates/baley/src/mcp/prepare.rs`, `write_next` and `prepare_checked`). `scope-submit`'s check reads the start order it names and then makes the start-once read of the project's events (`crates/baley/src/scope/submit.rs`, `start_approval`, `start_approved`, `start_once`, `start_order_check` and `order_evidence`), `project-start`'s is the start-once read and the read of a pending start order (`crates/baley/src/mcp/work_order.rs`, `start_check`), `work-order-fail`'s reads the order (`crates/baley/src/mcp/work_order.rs`, `fail_check`), `work-order-retry`'s reads the order's chain and this project's releases and has the retry judge answer (`crates/baley/src/mcp/work_order.rs`, `retry_check`), a change operation's check is its judgement against accepted scope (`crates/baley/src/scope/submit.rs`, `check_change`), `questions-answer`'s reads the set from the `questions` view and judges the call against its round (`crates/baley/src/questions/answer.rs`, `check`), and the refinement operations' read the story, its `backlog` entry, its latest set and its analyzer orders, and `context-submit`'s also its current truths (`crates/baley/src/refine/order.rs`, `check`, `crates/baley/src/refine/questions.rs`, `check`, `crates/baley/src/refine/submit.rs`, `check`). On the command line `baley scope approve` runs its own first step, which judges the draft against the ledger, before checkout admission and the policy step, and the owner's change commands check the change against accepted scope there too (`crates/baley/src/scope/approve.rs`, `judge` and `judge_change_draft`, `crates/baley/src/scope/command.rs`, `approve` and `submit_change`), and `baley questions answer` checks its call against the set there before them (`crates/baley/src/questions/command.rs`, `record_answers`), as `baley story truths approve` judges its draft (`crates/baley/src/refine/command.rs`, `approve`, `crates/baley/src/refine/approve.rs`, `judge`). Checkout admission and the step take the call's caller and the server's time and record as Baley (`crates/baley/src/checkout/admit.rs`, `admit` and `command`, `crates/baley/src/checkout/mod.rs`, `gather_and_admit`, `crates/baley/src/policy_step/mod.rs`, `step`, `crates/baley/src/policy_step/record.rs`, `record` and `command`), and `run_decision` hands the operation the ledger, the host, the caller and the server's time (`crates/baley/src/mcp/handler.rs`, `Preparation` and `run_decision`). `capture`, `scope-submit`, the ten change operations, the three work-order operations, `questions-answer`, the three refinement operations, `document`, `context-intake` and `route` carry `needs_project: true` (`crates/baley/src/mcp/operations.rs`, `QUERY_OPERATIONS`, `APPLY_OPERATIONS` and `with_project`) and reach preparation from their arms in `handler::operate` (`crates/baley/src/mcp/handler.rs`, `operate`): each judges its arguments first, then `capture`, `scope-submit`, the change operations, the work-order operations, `questions-answer` and the refinement operations prepare a write, `document` and `context-intake` a read, and `route` a read that also reads and judges the settings (`crates/baley/src/mcp/refine.rs`, `serve`, `serve_questions`, `serve_context` and `serve_intake`, `crates/baley/src/mcp/capture.rs`, `serve`, `crates/baley/src/mcp/scope.rs`, `serve`, `serve_change` and `prepared`, `crates/baley/src/mcp/work_order.rs`, `serve_start`, `serve_fail`, `prepared_write`, `serve_retry` and `serve_route`, `crates/baley/src/mcp/questions.rs`, `serve`, `crates/baley/src/mcp/document.rs`, `serve`, `crates/baley/src/mcp/prepare.rs`, `prepare_settings_read`). `scope-submit`, `story-questions-submit` and `context-submit` prepare their write under a caller carrying the order's id, and once the check passes the command's caller takes the order's instruction evidence (`crates/baley/src/mcp/scope.rs`, `order_caller` and `bind_instructions`). The work-order entries and `story-refine` attach the evidence of the instruction a session names before preparation, as capture does (`crates/baley/src/mcp/work_order.rs`, `evidenced`). The capture entry selects the caller with instruction evidence before invoking preparation, so checkout admission, the policy step and the capture command all record that evidence (`crates/baley/src/mcp/capture.rs`, `evidenced`, `Prepare`, `prepare_capture` and `serve`). The guard hook fills the hook form on every record it makes in `user` (`crates/baley/src/guard_hook/unrecordable.rs`, `caller`, `crates/baley/src/guard_hook/record.rs`, `record`) | | 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`, 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/<identity>/SKILL.md` or `agents/<identity>.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 <identity>` 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-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` and `plan-replace` open a plan draft's set on `phase/<n>` the same way, abandoning the set of the phase's earlier draft as `draft-replaced` (`crates/baley/src/planning/submit.rs`, `record`), and `bal-plan` walks the session through its rounds. A close of a plan draft's set says `ready` when no answer rejected a recommended answer, and otherwise, over MCP, returns the planner's revision order in `revision`, while a close at the terminal issues none (`crates/baley/src/mcp/questions.rs`, `serve`, `crates/baley/src/questions/answer.rs`, `receipt_value`). 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 plan approve` reads it the same way and records `plan.approved`, and for a replacement `plan.replaced`, with actor `owner`, that name and Baley's time, with no caller (`crates/baley/src/planning/command.rs`, `approve`, `crates/baley/src/planning/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, truths or plans: `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`, `bal-plan` at version 1, 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 phase planner's orders' `bal-phase-planner` at version 2, the last six with no help row, are served (`crates/baley/src/instruction/context.rs`, `crates/baley/src/instruction/plan.rs`, `IDENTITY`, `VERSION` and `HASH`, `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-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`, `story-refine` and `phase-plan` 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`, `crates/baley/src/mcp/planning.rs`, `serve`). 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`), and a phase planner's order, planning or revision, that of `bal-phase-planner` (`crates/baley/src/planning/order.rs`, `prepare` and `prepare_revision`). 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. `story-questions-submit` and `context-submit` do the same with an analyzer order's, and `plan-submit` and `plan-replace` with a planner order's (`crates/baley/src/mcp/refine.rs`, `serve_questions` and `serve_context`, `crates/baley/src/mcp/planning.rs`, `submit_through`, `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 4, and the help answer's `request` ask for `bal-help` as `instruction` only on `capture`, `phase-plan`, `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, nine 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/<identity>/SKILL.md` or `agents/<identity>.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 <identity>` 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, `bal-context`'s or `bal-plan`'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 | +| 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`, `story-refine` and `phase-plan` answer with it, `story-refine`'s adding `analyzer`, and `phase-plan` also when it hands over the order a commitment's approval issued, with that order's receipt as its issue gave it. A closing `questions-answer` and an empty set's `story-questions-submit` carry a drafting order's as `drafting`, and a `questions-answer` closing a plan draft's set the planner's revision order's as `revision` (`crates/baley/src/refine/order.rs`, `issue`, `crates/baley/src/mcp/work_order.rs`, `issue_start_order`, `serve_start` and `issue_retry`, `crates/baley/src/planning/order.rs`, `issue` and `hand_over`). `baley scope approve` of a phase's commitment adds the planner order's receipt members to its receipt and prints the order's id for the session's next `phase-plan` to launch (`crates/baley/src/scope/command.rs`, `answer_render`). 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 | | HST-R15 | Partly built | `baley exec --key`, the key reader and the HTTPS model lister are removed, so outside the parked engine nothing reads or sends a key and Baley sends no list request. On the command line, `baley models update` prints the fetch command only for a provider with a current acknowledgement, and otherwise refuses the run with `provider-not-acknowledged` naming `baley config interview` (`crates/baley/src/models.rs`, `update` and `update_decision`). The command names the provider's list address, the `Authorization: Bearer` header and the environment variable, which Baley never expands, and feeds the header to curl on stdin so the key stays out of curl's arguments (`crates/baley/src/detection/fetch.rs`, `fetch_command`, `crates/baley/src/detection/trigger.rs`, `key_name` and `list_address`). `baley models import` reads the returned list and its trailer from stdin, parses them and records the result (`crates/baley/src/models.rs`, `IMPORT_INPUT_BYTES`, `import` and `record_import`, `crates/baley/src/detection/trailer.rs`, `parse_fetched`, `crates/baley/src/detection/record.rs`, `record`). Review requests, work orders, `review return` and the session's `models-return` are Build 4's. The parked review engine keeps its own provider calls (`crates/baley/src/review/provider/credentials.rs`) until Build 9 deletes it. | -| HST-R16 | Partly built | The CLI has `serve`, which Claude Code starts and the owner does not, `guard`, which runs the library hook for Claude Code's pre-tool call (`crates/baley/src/main.rs`, `Command::Guard`, `crates/baley/src/guard_hook/mod.rs`, `run`), `skill-description`, the render commands, the ledger commands (`verify`, `doctor`, `export`, `purge`, `scrub`, `rebuild`, `anchor`, `acknowledge-restore`), `artifact`, which prints Claude Code's artifacts and writes no file, `install`, which writes Claude Code's wiring at the stable path (`crates/baley/src/install/command.rs`, `InstallArgs`, `run`, `select_host` and `install`), `init`, `config` (`show`, `set` and `interview`), `models` (`list`, `add`, `remove`, `update` and `import`), `update` (the foreground check and `resolve`, with hidden `detached` and `seed` subcommands) (`crates/baley/src/main.rs`, `Command`, `crates/baley/src/update/command.rs`, `UpdateArgs` and `UpdateCommand`), and the owner's scope commands: `scope approve`, `scope preview`, `scope show`, `phase show`, `backlog show` and `story show`, and the five change submissions `phase reorder`, `phase withdraw`, `story reassign`, `story drop` and `backlog reorder` (`crates/baley/src/main.rs`, `Command` and `run_command`, `crates/baley/src/scope/command.rs`, `ScopeArgs`, `ScopeCommand`, `PhaseArgs`, `PhaseCommand`, `BacklogArgs`, `BacklogCommand`, `StoryArgs` and `StoryCommand`), the owner's question commands `questions round` and `questions answer` (`crates/baley/src/questions/command.rs`, `QuestionsArgs`), and the owner's refinement commands `story truths approve` and `story refinement` (`crates/baley/src/refine/command.rs`, `TruthsArgs`, `approve` and `refinement`). A start, declarations, edits and `project describe` are submitted only from a session, the five id-only changes and a round's answers from a session or here, and scope and truths are approved only here. The `exec` execution group is Build 5's. It has no `service` command, and the other commands are later builds. | -| HST-R17 | Partly built | Binary delivery is built for unsigned development artifacts: the installer verifies SHA-256, stages versions and places the stable link (`install.sh`, from `valid_version` to its stable-link step), and `baley update` claims, downloads, verifies, stages, exchanges the active link, attempts completion with an update event and only then launches the new binary's catalog seed (`crates/baley/src/update/command.rs`, `check`, `reconcile_claim`, `claimed_check` and `gather_check`, `crates/baley/src/update/deliver.rs`, `deliver`, `apply_activation`, `restore_after_error` and `exchange`). `baley serve` starts the opt-in detached check (`crates/baley/src/mcp/serve.rs`, `run`, `crates/baley/src/update/detached.rs`, `should_start`, `launch_for`, `skipped` and `start`). Daily claims, update outcome events and owner recovery through `baley update resolve` are built (`crates/baley/src/update/claim.rs`, `claim_owner`, `invalid`, `Check`, `decide` and `claim_check`, `crates/baley/src/update/events.rs`, `UPDATE_FAILED`, `UPDATE_EVENT_VERSION`, `INSTALL_STREAM`, `register_update_events`, `claim_json`, `version_json`, `on_install_stream`, `checked_event` and `failed_event`, `crates/baley/src/update/reconcile.rs`, `record_reconciliation`, `ResolvedUpdate`, `resolve_from_observation` and `resolve_receipt`). The view set is 13, raised to 8 by the install projector, to 9 by the five scope views, to 10 by Build 4 T4, which raised the projector versions of the `draft`, `roadmap`, `phase` and `backlog` views, to 11 by Build 4 T5's `work_order` view and to 12 by Build 4 T6's `questions` view; Build 4 T7 raised it to 13 with the `truths` view, beside the `work_order` view's version 2 and the `roadmap` and `backlog` views' version 3, and the hook opens without rebuilding views (`crates/baley/src/ledger/open.rs`, `options`, `server_options` and `guard_options`, `crates/baley/src/install/view.rs`, `INSTALL_VIEW`, `install_spec`, `install_key` and `InstallProjector`). The versions folder is carried separately as a write-only folder and rendered with no read denial (`crates/baley/src/host_artifacts/placement.rs`, `PlacementMap::protected_paths` and `PlacementMap::write_only_folders`, `crates/baley/src/host_artifacts/security.rs`, `propose`). The registration, hook, security proposal, composition and coverage judge are built (`crates/baley/src/host_artifacts/registration.rs`, `render`, `crates/baley/src/host_artifacts/hook.rs`, `render`, `crates/baley/src/host_artifacts/compose.rs`, `compose`, `crates/baley/src/host_artifacts/coverage.rs`, `judge`). `baley install` is built: it writes the settings file with the hook, the deny rules and the sandbox block, writes the stubs, runs `claude mcp add-json --scope user baley`, seeds the catalog and records `install.recorded` (`crates/baley/src/install/command.rs`, `install`, `crates/baley/src/install/plan.rs`, `judge`, `crates/baley/src/install/registration.rs`, `judge`, `crates/baley/src/install/record.rs`, `write`). It proves ownership from the install record before replacing anything, refuses an artifact it cannot prove, reports gaps as a partial install, and holds one lock for its whole run (`crates/baley/src/install/stubs.rs`, `judge`, `crates/baley/src/install/settings.rs`, `judge`, `crates/baley/src/install/command.rs`, `LOCK_FILE`, `Observed`, `InstallLock`, `observe`, `refusal` and `acquire`). The script's last step runs it through the stable path (`install.sh`, its last line). The live guard derives the installed placements from the environment and protects them (`crates/baley/src/guard_hook/context.rs`, `judge`). No hook file is tracked in the repository any more, and no test holds one to the renderer: the hook exists as the item install writes from the renderer (`crates/baley/src/host_artifacts/hook.rs`, `render`, `crates/baley/src/guard_budget.rs`, `HOST_TIMEOUT`). Binaries built before T15 cannot write `user` once it holds an `install.recorded`. Provider choice, the typed acknowledgement, the API-host allowances through the installation writer's settings part and the separate global reviewer-list write before settings `config set` are built in `baley config interview` (`crates/baley/src/config_command/interview/providers.rs`, `stage`, `crates/baley/src/providers/record.rs`, `judge` and `append`, `crates/baley/src/install/hosts.rs`, `judge`, `ClaudeSettings`, `read`, `write` and `written`, `crates/baley/src/config_command/reviewers.rs`, `decide`, `crates/baley/src/config_command/interview.rs`, `execute`). The host step takes no install lock and records no `install.recorded`. The runtime doctor gathers, judges and reports the documents and ledger it is given over a placement map built from the install record, so an artifact the record does not show is reported as not installed (`crates/baley/src/host_doctor/mod.rs`, `installed_placements`, `observe` and `judge`, `crates/baley/src/host_doctor/report.rs`, `Report::new`). The doctor's checks of the stable path and version, registration, hook, settings, provider hosts, warning acknowledgement, update setting and writable locations are built (`baley doctor`, section 5). The live qualification ran on Linux with unsigned development artifacts (sheet `spikes/host-matrix/install-live-2026-10-11-run1.md`): the install script and install in a fresh `HOME` (`#inst.script.install-receipt`, `#inst.after.mcp`), the install rerun from a newer version with one hook, one registration and every owner setting kept (`#rerun.receipt`, `#rerun.one-hook`, `#rerun.owner-key`), the manual update and the opt-in update (`#man.update.receipt`, `#optin.staged`), and the agent's reads and writes of Baley's home and config folder and its writes to the versions folder and the stable path refused by the deny rules and the sandbox, while reads of the versions folder stayed allowed (`#prot.home.write`, `#prot.config.bash-read`, `#prot.versions.bash-write`, `#prot.versions.read`, `#prot.stable.write`). The Bash read of Baley's home folder rests on the session's quote of the failed `cat` and is unverified (`#prot.home.bash-read`). A repeat after three fixes (sheet `spikes/host-matrix/install-live-2026-10-11-run2.md`) showed the doctor's older-stub line and install's removal of a retired stub's file (`#rerun.doctor-capture`, `#rerun.dropped-stub-file`). Four things stay open. The older server's captures were refused (`#old.s3.capture-1`, `#old.s3.keeps`, a defect, issue 258, fixed by pull request 260), and the live repeat of that fix at Build 4 T3's raise of the view set to 9 passed: a binary at view set 8 that holds it kept writing its session's project beside one at view set 9 until that binary used the project, and was then refused with nothing recorded (`spikes/host-matrix/older-server-live-2026-10-15.md`). The raises to 10, 11, 12 and 13 were not repeated in a live session. Grep and Glob on Baley's home and config folder in a live session, and the installed hook in bypass-permissions mode, are unverified (`#prot.home.grep`, `#prot.config.glob`). The in-flight exit is unverified for issue 190: the one call sent was recorded exactly once, but it was not shown open inside the server when Claude Code's process ended (`#exit.r1.answered`, `#exit.condition`). macOS was not run. #14 owns signature verification at both `verify_download` seams, the trust root, release format and publication. Both verifiers must be supplied and qualified before any release. #14 also owns pruning at activation. | +| HST-R16 | Partly built | The CLI has `serve`, which Claude Code starts and the owner does not, `guard`, which runs the library hook for Claude Code's pre-tool call (`crates/baley/src/main.rs`, `Command::Guard`, `crates/baley/src/guard_hook/mod.rs`, `run`), `skill-description`, the render commands, the ledger commands (`verify`, `doctor`, `export`, `purge`, `scrub`, `rebuild`, `anchor`, `acknowledge-restore`), `artifact`, which prints Claude Code's artifacts and writes no file, `install`, which writes Claude Code's wiring at the stable path (`crates/baley/src/install/command.rs`, `InstallArgs`, `run`, `select_host` and `install`), `init`, `config` (`show`, `set` and `interview`), `models` (`list`, `add`, `remove`, `update` and `import`), `update` (the foreground check and `resolve`, with hidden `detached` and `seed` subcommands) (`crates/baley/src/main.rs`, `Command`, `crates/baley/src/update/command.rs`, `UpdateArgs` and `UpdateCommand`), and the owner's scope commands: `scope approve`, `scope preview`, `scope show`, `phase show`, `backlog show` and `story show`, and the five change submissions `phase reorder`, `phase withdraw`, `story reassign`, `story drop` and `backlog reorder` (`crates/baley/src/main.rs`, `Command` and `run_command`, `crates/baley/src/scope/command.rs`, `ScopeArgs`, `ScopeCommand`, `PhaseArgs`, `PhaseCommand`, `BacklogArgs`, `BacklogCommand`, `StoryArgs` and `StoryCommand`), the owner's question commands `questions round` and `questions answer` (`crates/baley/src/questions/command.rs`, `QuestionsArgs`), the owner's refinement commands `story truths approve` and `story refinement` (`crates/baley/src/refine/command.rs`, `TruthsArgs`, `approve` and `refinement`), and the owner's plan commands `plan approve` and `plan show` (`crates/baley/src/main.rs`, `Command::Plan`, `crates/baley/src/planning/command.rs`, `PlanArgs`, `PlanCommand` and `run`). A start, declarations, edits, `project describe` and plan drafts are submitted only from a session, the five id-only changes and a round's answers from a session or here, and scope, truths and plans are approved only here. The `exec` execution group is Build 5's. It has no `service` command, and the other commands are later builds. | +| HST-R17 | Partly built | Binary delivery is built for unsigned development artifacts: the installer verifies SHA-256, stages versions and places the stable link (`install.sh`, from `valid_version` to its stable-link step), and `baley update` claims, downloads, verifies, stages, exchanges the active link, attempts completion with an update event and only then launches the new binary's catalog seed (`crates/baley/src/update/command.rs`, `check`, `reconcile_claim`, `claimed_check` and `gather_check`, `crates/baley/src/update/deliver.rs`, `deliver`, `apply_activation`, `restore_after_error` and `exchange`). `baley serve` starts the opt-in detached check (`crates/baley/src/mcp/serve.rs`, `run`, `crates/baley/src/update/detached.rs`, `should_start`, `launch_for`, `skipped` and `start`). Daily claims, update outcome events and owner recovery through `baley update resolve` are built (`crates/baley/src/update/claim.rs`, `claim_owner`, `invalid`, `Check`, `decide` and `claim_check`, `crates/baley/src/update/events.rs`, `UPDATE_FAILED`, `UPDATE_EVENT_VERSION`, `INSTALL_STREAM`, `register_update_events`, `claim_json`, `version_json`, `on_install_stream`, `checked_event` and `failed_event`, `crates/baley/src/update/reconcile.rs`, `record_reconciliation`, `ResolvedUpdate`, `resolve_from_observation` and `resolve_receipt`). The view set is 14, raised to 8 by the install projector, to 9 by the five scope views, to 10 by Build 4 T4, which raised the projector versions of the `draft`, `roadmap`, `phase` and `backlog` views, to 11 by Build 4 T5's `work_order` view and to 12 by Build 4 T6's `questions` view; Build 4 T7 raised it to 13 with the `truths` view, beside the `work_order` view's version 2 and the `roadmap` and `backlog` views' version 3, and Build 4 T9 raised it to 14 with the `phase_plan`, `plan` and `evidence_map` views, beside the `backlog` view's version 4, and the hook opens without rebuilding views (`crates/baley/src/ledger/open.rs`, `options`, `server_options` and `guard_options`, `crates/baley/src/install/view.rs`, `INSTALL_VIEW`, `install_spec`, `install_key` and `InstallProjector`). The versions folder is carried separately as a write-only folder and rendered with no read denial (`crates/baley/src/host_artifacts/placement.rs`, `PlacementMap::protected_paths` and `PlacementMap::write_only_folders`, `crates/baley/src/host_artifacts/security.rs`, `propose`). The registration, hook, security proposal, composition and coverage judge are built (`crates/baley/src/host_artifacts/registration.rs`, `render`, `crates/baley/src/host_artifacts/hook.rs`, `render`, `crates/baley/src/host_artifacts/compose.rs`, `compose`, `crates/baley/src/host_artifacts/coverage.rs`, `judge`). `baley install` is built: it writes the settings file with the hook, the deny rules and the sandbox block, writes the stubs, runs `claude mcp add-json --scope user baley`, seeds the catalog and records `install.recorded` (`crates/baley/src/install/command.rs`, `install`, `crates/baley/src/install/plan.rs`, `judge`, `crates/baley/src/install/registration.rs`, `judge`, `crates/baley/src/install/record.rs`, `write`). It proves ownership from the install record before replacing anything, refuses an artifact it cannot prove, reports gaps as a partial install, and holds one lock for its whole run (`crates/baley/src/install/stubs.rs`, `judge`, `crates/baley/src/install/settings.rs`, `judge`, `crates/baley/src/install/command.rs`, `LOCK_FILE`, `Observed`, `InstallLock`, `observe`, `refusal` and `acquire`). The script's last step runs it through the stable path (`install.sh`, its last line). The live guard derives the installed placements from the environment and protects them (`crates/baley/src/guard_hook/context.rs`, `judge`). No hook file is tracked in the repository any more, and no test holds one to the renderer: the hook exists as the item install writes from the renderer (`crates/baley/src/host_artifacts/hook.rs`, `render`, `crates/baley/src/guard_budget.rs`, `HOST_TIMEOUT`). Binaries built before T15 cannot write `user` once it holds an `install.recorded`. Provider choice, the typed acknowledgement, the API-host allowances through the installation writer's settings part and the separate global reviewer-list write before settings `config set` are built in `baley config interview` (`crates/baley/src/config_command/interview/providers.rs`, `stage`, `crates/baley/src/providers/record.rs`, `judge` and `append`, `crates/baley/src/install/hosts.rs`, `judge`, `ClaudeSettings`, `read`, `write` and `written`, `crates/baley/src/config_command/reviewers.rs`, `decide`, `crates/baley/src/config_command/interview.rs`, `execute`). The host step takes no install lock and records no `install.recorded`. The runtime doctor gathers, judges and reports the documents and ledger it is given over a placement map built from the install record, so an artifact the record does not show is reported as not installed (`crates/baley/src/host_doctor/mod.rs`, `installed_placements`, `observe` and `judge`, `crates/baley/src/host_doctor/report.rs`, `Report::new`). The doctor's checks of the stable path and version, registration, hook, settings, provider hosts, warning acknowledgement, update setting and writable locations are built (`baley doctor`, section 5). The live qualification ran on Linux with unsigned development artifacts (sheet `spikes/host-matrix/install-live-2026-10-11-run1.md`): the install script and install in a fresh `HOME` (`#inst.script.install-receipt`, `#inst.after.mcp`), the install rerun from a newer version with one hook, one registration and every owner setting kept (`#rerun.receipt`, `#rerun.one-hook`, `#rerun.owner-key`), the manual update and the opt-in update (`#man.update.receipt`, `#optin.staged`), and the agent's reads and writes of Baley's home and config folder and its writes to the versions folder and the stable path refused by the deny rules and the sandbox, while reads of the versions folder stayed allowed (`#prot.home.write`, `#prot.config.bash-read`, `#prot.versions.bash-write`, `#prot.versions.read`, `#prot.stable.write`). The Bash read of Baley's home folder rests on the session's quote of the failed `cat` and is unverified (`#prot.home.bash-read`). A repeat after three fixes (sheet `spikes/host-matrix/install-live-2026-10-11-run2.md`) showed the doctor's older-stub line and install's removal of a retired stub's file (`#rerun.doctor-capture`, `#rerun.dropped-stub-file`). Four things stay open. The older server's captures were refused (`#old.s3.capture-1`, `#old.s3.keeps`, a defect, issue 258, fixed by pull request 260), and the live repeat of that fix at Build 4 T3's raise of the view set to 9 passed: a binary at view set 8 that holds it kept writing its session's project beside one at view set 9 until that binary used the project, and was then refused with nothing recorded (`spikes/host-matrix/older-server-live-2026-10-15.md`). The raises to 10, 11, 12, 13 and 14 were not repeated in a live session. Grep and Glob on Baley's home and config folder in a live session, and the installed hook in bypass-permissions mode, are unverified (`#prot.home.grep`, `#prot.config.glob`). The in-flight exit is unverified for issue 190: the one call sent was recorded exactly once, but it was not shown open inside the server when Claude Code's process ended (`#exit.r1.answered`, `#exit.condition`). macOS was not run. #14 owns signature verification at both `verify_download` seams, the trust root, release format and publication. Both verifiers must be supplied and qualified before any release. #14 also owns pruning at activation. | | HST-R18 | Built | The `failed` answer is built: a code, a place, `recorded: false` and `retryable`, returned as a successful tool result (`crates/baley/src/envelope.rs`, `Envelope`, `SERVER_OVERLOADED`, `LEDGER_BUSY` and `RETRYABLE_CODES`, `crates/baley/src/mcp/gate.rs`, `encode`). The server uses it for `unknown-host` (`crates/baley/src/mcp/gate.rs`, `unknown_host`), `server-overloaded` (`crates/baley/src/mcp/admission.rs`, `overloaded`) and the project and caller faults (`crates/baley/src/mcp/gate.rs`, `after_queue`, `failed` and `caller_invalid`). Only `server-overloaded` and `ledger-busy` are retryable (`crates/baley/src/envelope.rs`, `SERVER_OVERLOADED`, `LEDGER_BUSY` and `RETRYABLE_CODES`). Preparation answers each fault as `failed`: its codes and places (`crates/baley/src/mcp/prepare.rs`, the codes from `PROJECT_CONTEXT_INVALID` to `CHECKOUT_FACTS_UNAVAILABLE` and the places from `PLACE_PROJECT_DIR` to `PLACE_CHECKOUT`, `crates/baley-core/src/policy/parse.rs`, `CONFIG_UNAVAILABLE`, `crates/baley-core/src/checkout/judge.rs`, `PROJECT_ID_CONFLICT`), the answers a store failure, a git fault and a fork get (`crates/baley/src/mcp/prepare.rs`, `failed`, `store_failed` and `fault_failed`, `crates/baley/src/checkout/mod.rs`, `EntryError` and `EntryRefusal`) and where the plan raises each (`crates/baley/src/mcp/prepare.rs`, `next`, `judged_settings`, `Found` and `write_next`). A ledger that could not be opened at start answers `ledger-unavailable` (`crates/baley/src/mcp/serve.rs`, `open_store`). Checkout admission and the policy step are separate transactions, so a checkout admission recorded before a later step failed stays recorded (`crates/baley/src/mcp/prepare.rs`, its module comment). `capture` answers a store fault `failed`, `ledger-busy` as retryable and any other as `ledger-unavailable`, answers bytes that were purged before `failed` `text-purged`, not retryable, and answers `request-id-reuse` as a refusal that records nothing (`crates/baley/src/mcp/capture.rs`, `answer`, `NOT_RECORDED_BUSY`, `store_failed` and `failed`). `document` maps its read faults the same way (`crates/baley/src/mcp/document.rs`, `read` and the answers it calls). `scope-submit` and the ten change operations answer their store faults, `request-id-reuse` and `text-purged` as `capture` does, and a transaction refused because a fact its check judged moved, such as a start approved in between or a scope document a change was checked against, `failed` `ledger-busy` with nothing recorded (`crates/baley/src/scope/submit.rs`, `record`, `record_change`, `NOT_READ_BUSY` and `answer`). Their argument refusals, `malformed-submission`, `story-double-assigned` and `dependency-cycle` among them, are answered before preparation and record nothing (`crates/baley/src/mcp/scope.rs`, `judge_arguments`, `judge_change_arguments`, `shape_refused`, `judge_request_id`, `write_request` and `bounded`), and a check's refusal, `scope-submit`'s `no-such-work-order`, `wrong-work-order` or `project-already-started` or a change's refusal by accepted scope, ends preparation with nothing recorded and is answered as the refusal it is (`crates/baley/src/scope/submit.rs`, `start_once`, `start_order_check`, `order_evidence`, `check_change`, `scope_unread` and `scope_refused`, `crates/baley/src/mcp/prepare.rs`, `prepare_checked`). The work-order operations answer their store faults and `request-id-reuse` the same way, and a transaction whose observed work orders, start or stored inputs moved `failed` `ledger-busy` with nothing recorded (`crates/baley/src/work_order/issue.rs`, `NOT_READ_BUSY` and `answer`). Their argument refusals, `brief-blank` and `brief-too-large` among them, are answered before preparation (`crates/baley/src/mcp/work_order.rs`, `judge_start_arguments`, `judge_fail_arguments` and `judge_retry_arguments`), and their checks' refusals end preparation with nothing recorded (`crates/baley/src/mcp/work_order.rs`, `start_check`, `fail_check`, `retry_check`, `is_start`, `observed`, `parent_of` and `retry_refused`). `questions-answer` answers its store faults and `request-id-reuse` the same way and a set that moved since its check `failed` `ledger-busy` with nothing recorded (`crates/baley/src/questions/answer.rs`, `answer`); its argument refusals, `typed-content` among them, are answered before preparation (`crates/baley/src/mcp/questions.rs`, `judge_arguments`), and its check's refusals end preparation with nothing recorded (`crates/baley/src/questions/answer.rs`, `check`). The refinement operations answer their store faults and `request-id-reuse` the same way, and a transaction whose story, question sets, analyzer orders or truths moved `failed` `ledger-busy` with nothing recorded (`crates/baley/src/refine/questions.rs`, `answer`, `crates/baley/src/work_order/issue.rs`, `answer`); their argument refusals, `typed-content`, `question-cycle`, `truth-form` and `truth-attestation` among them, are answered before preparation (`crates/baley/src/mcp/refine.rs`, `judge_arguments`, `judge_questions_arguments` and `judge_context_arguments`), and their checks' refusals, `analyzer-order-pending` and `question-open` among them, end preparation with nothing recorded. `context-intake` maps its read faults as `document` does (`crates/baley/src/mcp/refine.rs`, `intake_answer`). `baley story truths approve` answers its first step's refusals with nothing recorded and `ledger-busy` when something it judged has moved (`crates/baley/src/refine/approve.rs`, `judge` and `record`). On the command line the first step of `baley scope approve` answers `unknown-draft`, `stale-draft`, `project-already-started`, `draft-approved` and a change's refusals by accepted scope with nothing recorded, and its transaction answers `ledger-busy` when something it judged has moved (`crates/baley/src/scope/approve.rs`, `judge`, `judge_change_draft`, `detail_in_force`, `Approval`, `approvals_of`, `accept_change`, `change_refused`, `record`, `change_decision` and `confirm_detail`). A capture's argument refusals are answered before preparation and record nothing (`crates/baley/src/mcp/capture.rs`, `judge_arguments` and `serve`), and a named phase is refused `no-such-phase` inside the capture's transaction and recorded as a refused `command.completed` (`crates/baley/src/mcp/capture.rs`, `record`) | | HST-R19 | Partly built | The decoder bounds a whole frame at 4 MiB and its depth at 128 (`crates/baley/src/mcp/frame.rs`, `MAX_FRAME_BYTES`, `MAX_DEPTH`, `Decoder::push` and `Decoder::start_value`). A frame over a bound or not JSON is discarded to its newline and answered with a JSON-RPC error while reading goes on (`crates/baley/src/mcp/frame.rs`, `error_response`, `crates/baley/src/mcp/transport.rs`, `decide` and `StdioTransport::receive`). Hook input is bounded (`crates/baley/src/hook_input/mod.rs`, `MAX_INPUT_BYTES`, `crates/baley/src/guard_hook/mod.rs`, `run`). Every git child runs with a deadline that `validate_launch` enforces (`crates/baley/src/process.rs`, `validate_launch`, `crates/baley/src/git_process.rs`, `Deadline`, `deadline`, `launch` and `guard_launch`): a caller outside the guard only at its exact registered deadline, and the guard's two callers, for the branch and for HEAD's copy of `baley.toml`, only at the timeout a budget grant gave the launch, above zero and at most 5 seconds, in their own process group. Only a grant sets that timeout, so one set by hand is refused (`crates/baley/src/process.rs`, `Launch::granted_git`, `crates/baley/src/guard_budget.rs`, `git_grant`, `storage_time`, `GitGrant` and `Budget`). The detached updater has no process deadline and is never waited on (`crates/baley/src/update/detached.rs`, `launch_for` and `start`); its downloads are bounded, and the catalog-seed child has a 60-second deadline (`crates/baley/src/update/fetch.rs`, `MANIFEST_BOUND`, `BINARY_BOUND`, `CONNECT_TIMEOUT`, `MANIFEST_TIMEOUT` and `BINARY_TIMEOUT`, `crates/baley/src/update/seed.rs`, `launch_for`). The suite runner's `sh -c` (`crates/baley/src/execution/runner.rs`) runs with none, owned by Build 5. | | HST-R20 | Built | Each descriptor carries the marker (`crates/baley/src/mcp/tools.rs`, `tools`, asserted at `crates/baley/src/mcp/tools.rs`, `tests::every_descriptor_asks_claude_code_to_always_load_it`). The registration renders the server-level `alwaysLoad: true` only when asked (`crates/baley/src/host_artifacts/registration.rs`, `render`), and the 2026-10-08 runs tried the plain form: with a registration that has no `alwaysLoad`, all three tools were callable without a tool search in the main session and in a subagent, in a session that does defer other tools, so the tool-level marker works alone (`claude-live-2026-10-08-run1.md#hand.tools.explicit-main`, `#hand.tools.explicit-subagent`, and again `claude-live-2026-10-08-run2.md#hand.tools.explicit-main`, `#hand.tools.explicit-subagent`). The first two runs had no login into the isolated configuration, so they could not start a session with the `alwaysLoad` form. The third run did, after the owner's login: `claude mcp add-json --scope user` stored a registration with `alwaysLoad: true`, a running session listed `baley` with 3 tools from the user scope, and in that session, which defers other servers' tools, all three tools were callable without a tool search in the main session and in a subagent, whose capture carries the session's `baley_session`. Claude Code accepted the `alwaysLoad` form (`claude-live-2026-10-08-run3.md#ses.b.registered`, `#hand.tools.user-main`, `#hand.tools.user-subagent`) | diff --git a/docs/design/0014-support-families.md b/docs/design/0014-support-families.md index e9d3d014..77c32afc 100644 --- a/docs/design/0014-support-families.md +++ b/docs/design/0014-support-families.md @@ -412,7 +412,7 @@ The binary parks the inherited engine for Build 9 to delete, and nothing in prod | Requirement | Status | Where | |---|---|---| -| SUP-R1 | Partly built | The core holds the `capture.recorded` event, the capture id, the byte threshold, the judgements of kind, text and phase, and the `capture` view and its projector (`crates/baley-core/src/capture/event.rs`, `crates/baley-core/src/capture/judge.rs`, `crates/baley-core/src/capture/view.rs`), registered in the view set the binary declares, version 13 (`crates/baley/src/ledger/open.rs` (`options`)). The arguments are judged before preparation (`crates/baley/src/mcp/capture.rs`, `CaptureShape` and `judge_arguments`), and the capture is recorded in its own domain transaction under the prepared command, with Baley as the actor and the call's caller, and text over 4,096 bytes stored as a `record` payload (`crates/baley/src/mcp/capture.rs`, `record`). The session server serves `capture` (`crates/baley/src/mcp/capture.rs`, `serve`, `crates/baley/src/mcp/handler.rs` (`operate`), `crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`, its `capture` entry), and a replay answers the stored receipt (`crates/baley/src/mcp/capture.rs`, `answer`). A named phase is read from the `phase` view inside the capture's transaction. The view holds only phases an approval declared, so a phase declared that way is recorded with the capture, and one that exists only in a draft or not at all is refused `no-such-phase` (`crates/baley/src/mcp/capture.rs`, `record`, `crates/baley-core/src/capture/judge.rs`, `judge_phase`) | +| SUP-R1 | Partly built | The core holds the `capture.recorded` event, the capture id, the byte threshold, the judgements of kind, text and phase, and the `capture` view and its projector (`crates/baley-core/src/capture/event.rs`, `crates/baley-core/src/capture/judge.rs`, `crates/baley-core/src/capture/view.rs`), registered in the view set the binary declares, version 14 (`crates/baley/src/ledger/open.rs` (`options`)). The arguments are judged before preparation (`crates/baley/src/mcp/capture.rs`, `CaptureShape` and `judge_arguments`), and the capture is recorded in its own domain transaction under the prepared command, with Baley as the actor and the call's caller, and text over 4,096 bytes stored as a `record` payload (`crates/baley/src/mcp/capture.rs`, `record`). The session server serves `capture` (`crates/baley/src/mcp/capture.rs`, `serve`, `crates/baley/src/mcp/handler.rs` (`operate`), `crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`, its `capture` entry), and a replay answers the stored receipt (`crates/baley/src/mcp/capture.rs`, `answer`). A named phase is read from the `phase` view inside the capture's transaction. The view holds only phases an approval declared, so a phase declared that way is recorded with the capture, and one that exists only in a draft or not at all is refused `no-such-phase` (`crates/baley/src/mcp/capture.rs`, `record`, `crates/baley-core/src/capture/judge.rs`, `judge_phase`) | | SUP-R2 | Not built | The served `capture` records captures only, and nothing promotes or declines one. The parked capture service has no promote or decline operation either, and its bound counts every capture ever made | | SUP-R3 | Not built | The capture receipt carries no open count (`crates/baley/src/mcp/capture.rs`, `record`): the bound is reported by progress, which is Build 7's. The inherited bound is the session layer's `capture_report`, which only the parked capture service calls (`crates/baley/src/session/mod.rs`, `Session::capture_report`, `crates/baley/src/config/mod.rs`, `capture_report`) | | SUP-R4 | Not built | Only the parked task service opens and closes a task episode (`crates/baley/src/task_service.rs`, `open` and `close`), and the episode is memory-only without a planning root (`crates/baley/src/task_service.rs`, `Episode` and `Episodes`). The session server answers `task-open` and `task-close` as unavailable (`crates/baley/src/mcp/operations.rs`, `APPLY_OPERATIONS`, its `task-open` and `task-close` entries) until Build 8 | diff --git a/docs/design/c4/workspace.dsl b/docs/design/c4/workspace.dsl index fc91b173..a1097792 100644 --- a/docs/design/c4/workspace.dsl +++ b/docs/design/c4/workspace.dsl @@ -8,7 +8,7 @@ workspace "Baley" "The C4 model behind Baley's design documents. Every structure hostInterface = component "Host interface" "MCP server (stdio), command line and guard hook: the only ways in. The guard hook records its answers in the per-user ledger." hardin = component "Hardin" "Derives the state of the work from the record, answers what may happen next and refuses the rest." domain = component "Domain areas" "The rules of each process area: planning, execution, verification, review, risk, landing and the rest." - composer = component "Work order composer" "Builds every work order: the route from policy and the model catalog, instructions by identity from the binary, inputs as references into the record. In this build it issues the start planner's order, the analyzer's questions and drafting orders for a story's refinement, and their retries." + composer = component "Work order composer" "Builds every work order: the route from policy and the model catalog, instructions by identity from the binary, inputs as references into the record. In this build it issues the start planner's order, the analyzer's questions and drafting orders for a story's refinement, the phase planner's planning and revision orders on phase/<n>, and their retries." policy = component "Policy" "Reads the global and project settings, resolves the values in effect and records which applied." catalog = component "Model catalog" "The models each host and provider offers, seeded from the binary, changed by the owner and refreshed from imported lists." ports = component "Ports and adapters" "Storage, git and test runner, forge and host adapters. The core sees only these ports." diff --git a/docs/roadmap.md b/docs/roadmap.md index 310fb2cb..ef1427e4 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)), 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. +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)), Build 4 T8 merged ([#306](https://github.com/jcrenshaw-dev/baley/pull/306)), and Build 4 T9 in progress on this branch, based on main `12f61dfd`, dated 2026-11-01, 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 @@ -268,8 +268,10 @@ Build 4 T7 refines a story before it is planned. `story-refine` on `baley_apply` 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. +Build 4 T9 plans a phase with its owner. `phase-plan` on `baley_apply` takes a phase and the stories to commit to it in order, and is refused while another phase is active or for a story that is unrefined or committed to another phase. When the stories differ from the phase's committed ones, it records a `phase edit` draft with a planning continuation and issues nothing. The owner's `baley scope approve` of that digest commits the stories and issues the phase planner's work order on `phase/<n>` in one transaction and prints the order's id, routed for Claude Code under its effective policy, and the session's next `phase-plan` with the same stories hands that order over; running the approval again prints the same id and issues none ([ADR 0050](adr/0050-phase-plan-commits-stories-through-an-approved-edit.md)). With the stories already committed, `phase-plan` issues the planning order itself, or the revision order a closed question set calls for. A phase keeps one live planner order: a `phase-plan` while one is pending is refused `planner-order-pending`, naming it. The order binds the phase, its stories with their current truths, the approved description, the capacity when one is set and the evidence items of the plans in force. The session submits the planner's plan with `plan-submit`, or with `plan-replace` naming the plan in force it replaces. Either judges the plan with T8's judge against the phase as it stands and records it as the phase's one draft, abandoning the earlier draft's question set, opening the draft's own and answering with the phase's size against capacity. A draft's set closed with no rejected recommendation answers `ready`; one closed over MCP with a rejected recommendation issues the planner's revision order, and a close at the terminal issues none. The owner approves a plan draft by its digest at the terminal with `baley plan approve`, refused `question-open` or `answer-not-applied` until its set is settled, which records `plan.approved` with the evidence map inline and the next plan number, never assigned twice, a replaced plan's included, and `plan.replaced` beside it for a replacement. `plan-read`, the `document` kinds `phase` and `plan`, and `baley plan show` read a phase's approved plans with their evidence maps and their readiness against the current truth versions, a draft's map never among them. The settings `planning.phase_capacity` and `workflow.test_command` enter the schema with these readers: a plan past the capacity is refused `over-capacity`, and a plan approved with no test command records no suite. The `bal-plan` front door is served with its skill stub, and the new `phase_plan`, `plan` and `evidence_map` views raise the view set to 14. + - 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) +- 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), [0050 phase plan commits stories through an approved edit](adr/0050-phase-plan-commits-stories-through-an-approved-edit.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`, 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)) @@ -330,9 +332,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,T7 done - class T8 progress - class T9,T10,T11,T12,T13,T14,T15 planned + class T1,T2,T3,T4,T5,T6,T7,T8 done + class T9 progress + class 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. @@ -346,8 +348,8 @@ Figure 5. Build 4's tasks. Arrows point from a task to what waits on it, and a d | 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 | [#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 | +| T8 | Plan grammar, evidence map and the planner's rules | [#306](https://github.com/jcrenshaw-dev/baley/pull/306) | Merged | +| T9 | Phase planning, drafts and plan approval | | In progress | | T10 | The plan checker and re-check scope | | Planned | | T11 | Risk at plan submit and git facts in the transaction | | Planned | | T12 | Tier selection and session model lists | | Planned |