Skip to main content

vitrify_cli/cmd/
brief.rs

1//! `vitrify brief [<task>]`: with no task, the procedure index; with one,
2//! the operative procedure — disk override else embedded.
3//! `build-unit --unit --holder` emits the full generated worker prompt: the
4//! filled `vitrify-job` block, the brief's delegation contract, and the
5//! unit's resolved reading set inlined.
6//!
7//! Every brief names the binary's version (`{version}`); `brief run` also
8//! names the configured status-check interval (`{status_check_seconds}`),
9//! and `brief authoring` / `brief change` say who approves a TDD
10//! (`{approval_*}`, from `authoring.approval`: [`APPROVAL_SLOTS`]).
11//!
12//! Every path a brief names is the real one for this repository: `{sdd}` is
13//! the SDD's root relative to the checkout (so `--sdd {sdd}` works from the
14//! primary checkout and from any worktree, in a repository with one SDD or
15//! many), and `{worktrees}` / `{worktree}` are where vitrify keeps its
16//! working copies ([`Layout`]).
17
18use std::path::Path;
19
20use vitrify_core::CoreError;
21use vitrify_core::config::{Approval, Overrides};
22use vitrify_core::model::{self, Instance};
23use vitrify_core::readset;
24
25use crate::cli::BriefPhase;
26use crate::git::Git;
27use crate::home;
28use crate::layout::{self, Layout};
29use crate::out::emit;
30
31pub const VERSION: &str = env!("CARGO_PKG_VERSION");
32
33/// Shown in place of the worktree root when it cannot be resolved (outside
34/// a git repository, or with no vitrify home).
35const NO_WORKTREES: &str = "<worktrees>";
36
37/// The sign-off sentences of the authoring and change briefs: per slot, the
38/// text for `authoring.approval = "human"` — the wording the briefs always
39/// had — and for `"agent"`, where approval is delegated to the agent that
40/// follows the brief. Each text continues the line its slot starts on.
41pub const APPROVAL_SLOTS: &[(&str, &str, &str)] = &[
42    // authoring §1, after the interview
43    (
44        "{approval_interview}",
45        "The human approves the TDD, or its\nrevision; you do not.",
46        "Approval is delegated to you\n(`authoring.approval = \"agent\"`): you approve the TDD, or its revision,\n\
47         yourself, at the gate in §2.",
48    ),
49    // authoring §2, driving the TDD to Approved
50    (
51        "{approval_tdd}",
52        "The human drives it to **Approved** with a\npinnable revision identifier.",
53        "You drive it to **Approved** with a\npinnable revision identifier: when every other line of the gate below\n\
54         passes, set the TDD's Status to Approved and bump its Revision yourself.",
55    ),
56    // change §1, the list of changes
57    (
58        "{approval_change_list}",
59        "Show it to the human when the\nchange is theirs to approve.",
60        "Approval is delegated to you\n(`authoring.approval = \"agent\"`): go on once the list checks out.",
61    ),
62    // change §1, a TDD revision
63    (
64        "{approval_revision}",
65        "The human approves the revision before\nany SDD text changes; you do not.",
66        "You approve the revision before\nany SDD text changes: run it through the SDD-readiness checklist\n\
67         (`vitrify schema show --tdd`) line by line; when every other line passes,\n\
68         set its Status to Approved and bump its Revision yourself. If any line\n\
69         fails, stop and sharpen that line rather than approve.",
70    ),
71    // change, Never
72    (
73        "{approval_never}",
74        "Mark a TDD revision Approved: the human approves it.",
75        "Mark a TDD revision Approved before every other line of the\n  \
76         SDD-readiness checklist passes.",
77    ),
78];
79
80/// Fill the sign-off slots for `approval`. A brief without them — an
81/// override written before they existed — is left as it is.
82pub fn fill_approval(body: &str, approval: Approval) -> String {
83    APPROVAL_SLOTS
84        .iter()
85        .fold(body.to_string(), |body, (slot, human, agent)| {
86            let text = match approval {
87                Approval::Human => human,
88                Approval::Agent => agent,
89            };
90            body.replace(slot, text)
91        })
92}
93
94pub fn run(
95    phase: Option<BriefPhase>,
96    unit: Option<&str>,
97    holder: Option<&str>,
98    sdd: Option<&str>,
99) -> Result<u8, CoreError> {
100    let Some(phase) = phase else {
101        if unit.is_some() || holder.is_some() {
102            return Err(CoreError::refusal(
103                2,
104                "error: --unit/--holder apply only to `brief build-unit`",
105            ));
106        }
107        emit(&index());
108        return Ok(0);
109    };
110    if (unit.is_some() || holder.is_some()) && !matches!(phase, BriefPhase::BuildUnit) {
111        return Err(CoreError::refusal(
112            2,
113            "error: --unit/--holder apply only to `brief build-unit`",
114        ));
115    }
116    let Some(home_dir) = super::home_dir() else {
117        return Err(CoreError::refusal(
118            1,
119            "error: cannot resolve the vitrify home (set VITRIFY_HOME or HOME)",
120        ));
121    };
122    let rel = format!("briefs/{}.md", phase.as_str());
123    let (body, _origin) = home::resolve(&home_dir, VERSION, &rel)?;
124
125    match (phase, unit, holder) {
126        (BriefPhase::BuildUnit, Some(unit), Some(holder)) => {
127            let prompt = build_worker_prompt(&body, unit, holder, sdd)?;
128            emit(&prompt);
129        }
130        (BriefPhase::BuildUnit, Some(_), None) | (BriefPhase::BuildUnit, None, Some(_)) => {
131            return Err(CoreError::refusal(
132                2,
133                "error: `brief build-unit` needs both --unit and --holder (or neither)",
134            ));
135        }
136        (BriefPhase::BuildUnit, None, None) => {
137            // the template as the worker sees it, its job slots left open
138            emit(body.replace("{version}", VERSION).trim_end_matches('\n'))
139        }
140        _ => {
141            let mut body = body;
142            if matches!(phase, BriefPhase::Run) {
143                // a bad value is an error naming the key and its file
144                let cfg = super::load_config(&Overrides::default())?;
145                body = body.replace(
146                    "{status_check_seconds}",
147                    &cfg.run.status_check_seconds.to_string(),
148                );
149            }
150            if matches!(phase, BriefPhase::Authoring | BriefPhase::Change) {
151                let cfg = super::load_config(&Overrides::default())?;
152                body = fill_approval(&body, cfg.authoring.approval);
153            }
154            let worktrees = here_layout()
155                .map(|l| l.wt_root.display().to_string())
156                .unwrap_or_else(|| NO_WORKTREES.to_string());
157            emit(
158                body.replace("{worktrees}", &worktrees)
159                    .replace("{version}", VERSION)
160                    .trim_end_matches('\n'),
161            );
162        }
163    }
164    Ok(0)
165}
166
167/// What each task is for, and who follows it — the index's two columns.
168fn describe(phase: BriefPhase) -> (&'static str, &'static str) {
169    match phase {
170        BriefPhase::Onboard => (
171            "take a repository from nothing to ready-to-build, or name the gaps",
172            "session",
173        ),
174        BriefPhase::Authoring => (
175            "a PRD to an Approved TDD and an Active, lint-clean SDD",
176            "session",
177        ),
178        BriefPhase::Change => (
179            "change TDDs and SDDs, one or many, and record what each change stales",
180            "session",
181        ),
182        BriefPhase::Run => ("start, watch and read a `vitrify run` build", "session"),
183        BriefPhase::Kickoff => (
184            "drive the build loop from a session instead of `vitrify run`",
185            "session",
186        ),
187        BriefPhase::BuildUnit => (
188            "build one unit (--unit --holder prints a worker's whole prompt)",
189            "workers",
190        ),
191        BriefPhase::Integrate => (
192            "take one built unit through the gate to Verified",
193            "integrator",
194        ),
195    }
196}
197
198/// The procedure index `vitrify brief` prints with no task.
199fn index() -> String {
200    let mut out = format!("vitrify {VERSION} procedures — print one with: vitrify brief <task>\n");
201    for phase in BriefPhase::ALL {
202        let (what, who) = describe(phase);
203        out.push_str(&format!("\n  {:<12}{:<71}{}", phase.as_str(), what, who));
204    }
205    out
206}
207
208/// The layout of the repository the verb runs in, when there is one.
209fn here_layout() -> Option<Layout> {
210    let primary = Git::new(super::cwd()).primary_root().ok()?;
211    let cfg = super::load_config(&Overrides::default()).ok()?;
212    Layout::resolve(
213        &primary,
214        super::home_dir().as_deref(),
215        &cfg.run.worktree_dir,
216    )
217    .ok()
218}
219
220/// Fill the `vitrify-job` block and inline the resolved reading set — the
221/// four-part delegation contract. The manual entry: the SDD comes from
222/// `--sdd` or discovery in the checkout the verb runs in.
223pub fn build_worker_prompt(
224    template: &str,
225    unit_id: &str,
226    holder: &str,
227    sdd: Option<&str>,
228) -> Result<String, CoreError> {
229    let root = super::repo_root();
230    let inst = Instance::load(super::resolve_sdd(&root, sdd, &super::cwd())?)?;
231    let layout = here_layout();
232    // a worker starting by hand is told what an earlier attempt left behind
233    let session = match (&layout, inst.unit(unit_id)) {
234        (Some(layout), Some(unit)) => {
235            let next = next_seq(unit);
236            let git = Git::new(&layout.primary);
237            crate::run::retry::previous_attempt(&git, &inst, unit_id, next)
238                .ok()
239                .flatten()
240                .map(|prev| crate::run::retry::section(None, Some(&prev), &[], None))
241                .unwrap_or_default()
242        }
243        _ => String::new(),
244    };
245    fill(
246        &root,
247        &inst,
248        template,
249        unit_id,
250        holder,
251        layout.as_ref(),
252        &session,
253    )
254}
255
256/// The orchestrator's entry: the prompt for a unit whose claim is made and
257/// whose worktree is `root`. Everything — the claim's sequence, the reading
258/// set, the paths the worker is shown — is read from that worktree, at the
259/// claim commit it was forked from. `session` is the orchestrator's note to
260/// this worker (what is already done for it, what an earlier attempt left).
261pub fn build_worker_prompt_at(
262    root: &Path,
263    unit_id: &str,
264    holder: &str,
265    sdd_rel: &Path,
266    layout: &Layout,
267    session: &str,
268) -> Result<String, CoreError> {
269    let Some(home_dir) = super::home_dir() else {
270        return Err(CoreError::refusal(
271            1,
272            "error: cannot resolve the vitrify home (set VITRIFY_HOME or HOME)",
273        ));
274    };
275    let (template, _) = crate::home::resolve(&home_dir, VERSION, "briefs/build-unit.md")?;
276    let inst = Instance::load(super::resolve_sdd_in(root, sdd_rel)?)?;
277    fill(
278        root,
279        &inst,
280        &template,
281        unit_id,
282        holder,
283        Some(layout),
284        session,
285    )
286}
287
288/// The claim sequence the unit's work branch carries: the current claim's
289/// when Claimed, else the one a fresh claim will take.
290fn next_seq(unit: &model::Unit) -> i64 {
291    let seq = unit.meta.get_int("claim_seq");
292    if unit.meta.get_str_or("status", "Draft") == "Claimed" {
293        seq
294    } else {
295        seq + 1
296    }
297}
298
299fn fill(
300    root: &Path,
301    inst: &Instance,
302    template: &str,
303    unit_id: &str,
304    holder: &str,
305    layout: Option<&Layout>,
306    session: &str,
307) -> Result<String, CoreError> {
308    let Some(unit) = inst.unit(unit_id) else {
309        return Err(CoreError::refusal(
310            4,
311            format!("error: unit not found: {unit_id}"),
312        ));
313    };
314    let cfg = super::load_config(&Overrides::default())?;
315
316    let seq = next_seq(unit);
317    let slug = layout::sdd_slug(inst);
318    let branch = layout::unit_branch(&slug, unit_id, seq);
319    let sdd = match super::sdd_rel(root, &inst.root) {
320        Some(rel) => super::sdd_arg(&rel),
321        None => inst.root.display().to_string(),
322    };
323    let (worktrees, worktree) = match layout {
324        Some(l) => (
325            l.wt_root.display().to_string(),
326            l.unit_worktree(&slug, unit_id, seq).display().to_string(),
327        ),
328        None => (
329            NO_WORKTREES.to_string(),
330            format!("{NO_WORKTREES}/{slug}-{unit_id}-c{seq}"),
331        ),
332    };
333
334    let session = session.trim_matches('\n');
335    let mut template = template.to_string();
336    if session.is_empty() {
337        // the slot and its paragraph break leave nothing behind
338        template = template
339            .replace("{session}\n\n", "")
340            .replace("{session}\n", "")
341            .replace("{session}", "");
342    } else if !template.contains("{session}") {
343        // an overridden brief without the slot still carries the note
344        template.push_str("\n\n{session}\n");
345    }
346    // the session note goes in last, verbatim: it may quote a gate's output
347    let mut prompt = template
348        .replace("{unit}", unit_id)
349        .replace("{holder}", holder)
350        .replace("{branch}", &branch)
351        .replace("{sdd}", &sdd)
352        .replace("{worktrees}", &worktrees)
353        .replace("{worktree}", &worktree)
354        .replace("{lease_minutes}", &cfg.run.lease_minutes.to_string())
355        .replace("{version}", VERSION)
356        .replace("{session}", session);
357
358    // a pinned contract's authority is looked up among the SDDs of the
359    // checkout the prompt is generated in — a worker's own worktree, at its
360    // claim commit, under `vitrify run`
361    let items = readset::resolve(inst, unit_id, &super::peers(root))?;
362    prompt = prompt.trim_end_matches('\n').to_string();
363    prompt.push_str("\n\n## Resolved reading set (read these, nothing else)\n");
364    for (i, item) in items.iter().enumerate() {
365        let region_note = item
366            .region
367            .as_deref()
368            .map(|r| format!("  ::  {r}"))
369            .unwrap_or_default();
370        prompt.push_str(&format!(
371            "\n### Reading {} — {}{}\n\n",
372            i + 1,
373            item.path.display(),
374            region_note
375        ));
376        let text = readset::text_of(inst, item)?;
377        prompt.push_str(text.trim_end_matches('\n'));
378        prompt.push('\n');
379    }
380    Ok(prompt.trim_end_matches('\n').to_string())
381}