1use 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
33const NO_WORKTREES: &str = "<worktrees>";
36
37pub const APPROVAL_SLOTS: &[(&str, &str, &str)] = &[
42 (
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 (
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 (
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 (
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 (
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
80pub 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 emit(body.replace("{version}", VERSION).trim_end_matches('\n'))
139 }
140 _ => {
141 let mut body = body;
142 if matches!(phase, BriefPhase::Run) {
143 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
167fn 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
198fn 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
208fn 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
220pub 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 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
256pub 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
288fn 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 template = template
339 .replace("{session}\n\n", "")
340 .replace("{session}\n", "")
341 .replace("{session}", "");
342 } else if !template.contains("{session}") {
343 template.push_str("\n\n{session}\n");
345 }
346 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 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}