1use std::fmt::Write as _;
14
15use camino::{Utf8Path, Utf8PathBuf};
16
17use crate::cli::Commands;
18use crate::domain::manifest::{MANIFEST_PATH, Manifest};
19use crate::domain::version::CanonVersion;
20use crate::error::AppError;
21use crate::self_depend::guidance::MOVED;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Class {
26 Exempt,
28 PreLanding,
32 Upgrade,
34 ReadOnly,
36 Writing,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Writes {
43 Never,
45 WithApply,
47 Always,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum TargetSource {
54 Flag,
56 CurrentFolder,
58 None,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct Row {
65 pub path: &'static str,
67 pub class: Class,
69 pub writes: Writes,
71 pub target: TargetSource,
73}
74
75const fn row(path: &'static str, class: Class, writes: Writes, target: TargetSource) -> Row {
76 Row {
77 path,
78 class,
79 writes,
80 target,
81 }
82}
83
84pub const TABLE: &[Row] = &[
86 row(
87 "init",
88 Class::PreLanding,
89 Writes::WithApply,
90 TargetSource::Flag,
91 ),
92 row("verify", Class::ReadOnly, Writes::Never, TargetSource::Flag),
93 row(
94 "upgrade",
95 Class::Upgrade,
96 Writes::WithApply,
97 TargetSource::Flag,
98 ),
99 row(
100 "gate",
101 Class::ReadOnly,
102 Writes::Never,
103 TargetSource::CurrentFolder,
104 ),
105 row(
106 "hooks",
107 Class::Writing,
108 Writes::WithApply,
109 TargetSource::Flag,
110 ),
111 row(
112 "debt baseline",
113 Class::Writing,
114 Writes::WithApply,
115 TargetSource::Flag,
116 ),
117 row(
118 "debt migrate",
119 Class::Writing,
120 Writes::WithApply,
121 TargetSource::Flag,
122 ),
123 row(
124 "debt tighten",
125 Class::Writing,
126 Writes::WithApply,
127 TargetSource::Flag,
128 ),
129 row(
130 "policy reconcile",
131 Class::Writing,
132 Writes::WithApply,
133 TargetSource::Flag,
134 ),
135 row(
136 "ki list",
137 Class::ReadOnly,
138 Writes::Never,
139 TargetSource::Flag,
140 ),
141 row("docs", Class::Exempt, Writes::Never, TargetSource::None),
142 row("method", Class::Exempt, Writes::Never, TargetSource::None),
143 row("spec", Class::Exempt, Writes::Never, TargetSource::None),
144 row("template", Class::Exempt, Writes::Never, TargetSource::None),
145 row(
146 "skill list",
147 Class::Exempt,
148 Writes::Never,
149 TargetSource::None,
150 ),
151 row(
152 "skill show",
153 Class::Exempt,
154 Writes::Never,
155 TargetSource::None,
156 ),
157 row(
158 "skill install",
159 Class::Exempt,
160 Writes::Never,
161 TargetSource::None,
162 ),
163 row(
164 "skill uninstall",
165 Class::Exempt,
166 Writes::Never,
167 TargetSource::None,
168 ),
169 row(
170 "stage",
171 Class::PreLanding,
172 Writes::Never,
173 TargetSource::Flag,
174 ),
175 row(
176 "stage clean",
177 Class::PreLanding,
178 Writes::Never,
179 TargetSource::None,
180 ),
181 row(
182 "stage compare",
183 Class::PreLanding,
184 Writes::Never,
185 TargetSource::Flag,
186 ),
187 row("status", Class::Exempt, Writes::Never, TargetSource::None),
188 row(
192 "env",
193 Class::PreLanding,
194 Writes::WithApply,
195 TargetSource::Flag,
196 ),
197 row("lint", Class::PreLanding, Writes::Never, TargetSource::Flag),
198 row(
199 "lint prove",
200 Class::PreLanding,
201 Writes::Never,
202 TargetSource::Flag,
203 ),
204 row(
205 "migrate inventory",
206 Class::PreLanding,
207 Writes::Never,
208 TargetSource::Flag,
209 ),
210 row(
211 "migrate archive",
212 Class::PreLanding,
213 Writes::WithApply,
214 TargetSource::Flag,
215 ),
216 row(
217 "migrate mark",
218 Class::PreLanding,
219 Writes::Always,
220 TargetSource::Flag,
221 ),
222 row(
223 "migrate status",
224 Class::PreLanding,
225 Writes::Never,
226 TargetSource::Flag,
227 ),
228 row(
229 "migrate close",
230 Class::PreLanding,
231 Writes::WithApply,
232 TargetSource::Flag,
233 ),
234 row(
235 "track status",
236 Class::ReadOnly,
237 Writes::Never,
238 TargetSource::Flag,
239 ),
240 row(
241 "track check",
242 Class::ReadOnly,
243 Writes::Never,
244 TargetSource::Flag,
245 ),
246 row("doctor", Class::Exempt, Writes::Never, TargetSource::None),
247 row(
248 "assess",
249 Class::PreLanding,
250 Writes::Never,
251 TargetSource::Flag,
252 ),
253 row("license", Class::Exempt, Writes::Never, TargetSource::None),
254 row(
255 "self-manifest",
256 Class::Exempt,
257 Writes::Never,
258 TargetSource::None,
259 ),
260 row(
261 "self-depend status",
262 Class::Exempt,
263 Writes::Never,
264 TargetSource::None,
265 ),
266 row(
267 "self-depend add",
268 Class::Exempt,
269 Writes::Never,
270 TargetSource::None,
271 ),
272 row(
273 "self-depend check",
274 Class::Exempt,
275 Writes::Never,
276 TargetSource::None,
277 ),
278 row(
279 "self-depend sync",
280 Class::Exempt,
281 Writes::Never,
282 TargetSource::None,
283 ),
284 row(
285 "self-depend clean",
286 Class::Exempt,
287 Writes::Never,
288 TargetSource::None,
289 ),
290 row(
291 "completions",
292 Class::Exempt,
293 Writes::Never,
294 TargetSource::None,
295 ),
296 row("man", Class::Exempt, Writes::Never, TargetSource::None),
297];
298
299#[must_use]
301pub fn row_of(path: &str) -> Option<&'static Row> {
302 TABLE.iter().find(|row| row.path == path)
303}
304
305#[derive(Debug, Clone, PartialEq, Eq)]
307pub struct Invocation {
308 pub path: &'static str,
310 pub applied: bool,
312 pub target: Option<Utf8PathBuf>,
314}
315
316fn invocation(path: &'static str, applied: bool, target: Option<&Utf8Path>) -> Invocation {
317 Invocation {
318 path,
319 applied,
320 target: target.map(Utf8Path::to_owned),
321 }
322}
323
324#[must_use]
326pub fn invocation_of(command: &Commands) -> Invocation {
327 use crate::cli::debt::DebtVerb;
328 use crate::cli::ki::KiCommand;
329 use crate::cli::lint::LintCommand;
330 use crate::cli::migrate::MigrateCommand;
331 use crate::cli::policy::PolicyVerb;
332 use crate::cli::self_depend::SelfDependCommand;
333 use crate::cli::skill::SkillCommand;
334 use crate::cli::stage::StageCommand;
335 use crate::cli::track::TrackCommand;
336
337 match command {
338 Commands::Init(args) => {
339 let target = args
342 .target
343 .clone()
344 .or_else(|| args.stage.as_ref().map(|_| Utf8PathBuf::from(".")));
345 invocation("init", args.apply, target.as_deref())
346 }
347 Commands::Verify(args) => invocation("verify", false, Some(&args.target)),
348 Commands::Upgrade(args) => invocation("upgrade", false, Some(&args.target)),
349 Commands::Gate(args) => {
350 if args.id.is_some() {
351 invocation("gate", false, Some(Utf8Path::new(".")))
352 } else {
353 invocation("gate", false, None)
355 }
356 }
357 Commands::Hooks(args) => invocation("hooks", args.apply, Some(Utf8Path::new(&args.target))),
358 Commands::Debt(args) => match &args.verb {
359 DebtVerb::Baseline(verb) => invocation("debt baseline", verb.apply, Some(&verb.target)),
360 DebtVerb::Migrate(verb) => invocation("debt migrate", verb.apply, Some(&verb.target)),
361 DebtVerb::Tighten(verb) => invocation("debt tighten", verb.apply, Some(&verb.target)),
362 },
363 Commands::Policy(args) => match &args.verb {
364 PolicyVerb::Reconcile(verb) => {
365 invocation("policy reconcile", verb.apply, Some(&verb.target))
366 }
367 },
368 Commands::Ki(args) => match &args.command {
369 KiCommand::List(list) => invocation("ki list", false, Some(&list.target)),
370 },
371 Commands::Docs(_) => invocation("docs", false, None),
372 Commands::Method(_) => invocation("method", false, None),
373 Commands::Spec(_) => invocation("spec", false, None),
374 Commands::Template(_) => invocation("template", false, None),
375 Commands::Skill(args) => match &args.command {
376 SkillCommand::List => invocation("skill list", false, None),
377 SkillCommand::Show(_) => invocation("skill show", false, None),
378 SkillCommand::Install(_) => invocation("skill install", false, None),
379 SkillCommand::Uninstall(_) => invocation("skill uninstall", false, None),
380 },
381 Commands::Stage(args) => match &args.command {
382 None => invocation("stage", false, Some(&args.target)),
383 Some(StageCommand::Clean(_)) => invocation("stage clean", false, None),
384 Some(StageCommand::Compare(compare)) => {
385 invocation("stage compare", false, Some(&compare.target))
386 }
387 },
388 Commands::Status(_) => invocation("status", false, None),
389 Commands::Env(args) => invocation("env", args.apply.is_some(), Some(&args.target)),
390 Commands::Lint(args) => match &args.command {
391 None => invocation("lint", false, Some(&args.target)),
392 Some(LintCommand::Prove(prove)) => invocation("lint prove", false, Some(&prove.target)),
393 },
394 Commands::Migrate(args) => match &args.command {
395 MigrateCommand::Inventory(verb) => {
396 invocation("migrate inventory", false, Some(&verb.target))
397 }
398 MigrateCommand::Archive(verb) => {
399 invocation("migrate archive", verb.apply, Some(&verb.target))
400 }
401 MigrateCommand::Mark(verb) => invocation("migrate mark", true, Some(&verb.target)),
402 MigrateCommand::Status(verb) => invocation("migrate status", false, Some(&verb.target)),
403 MigrateCommand::Close(verb) => {
404 invocation("migrate close", verb.apply, Some(&verb.target))
405 }
406 },
407 Commands::Track(args) => match &args.command {
408 TrackCommand::Status(verb) => invocation("track status", false, Some(&verb.target)),
409 TrackCommand::Check(verb) => invocation("track check", false, Some(&verb.target)),
410 },
411 Commands::Doctor(_) => invocation("doctor", false, None),
412 Commands::Assess(args) => invocation("assess", false, Some(&args.target)),
413 Commands::License(_) => invocation("license", false, None),
414 Commands::SelfManifest => invocation("self-manifest", false, None),
415 Commands::SelfDepend(args) => match &args.command {
416 SelfDependCommand::Status(_) => invocation("self-depend status", false, None),
417 SelfDependCommand::Add(_) => invocation("self-depend add", false, None),
418 SelfDependCommand::Check(_) => invocation("self-depend check", false, None),
419 SelfDependCommand::Sync(_) => invocation("self-depend sync", false, None),
420 SelfDependCommand::Clean(_) => invocation("self-depend clean", false, None),
421 },
422 Commands::Completions(_) => invocation("completions", false, None),
423 Commands::Man => invocation("man", false, None),
424 }
425}
426
427#[derive(Debug, Clone, PartialEq, Eq)]
429pub enum Passed {
430 Quiet,
432 Warn(String),
434}
435
436#[derive(Debug, Clone, PartialEq, Eq)]
438pub struct Recorded {
439 pub version: CanonVersion,
441 pub older_schema: Option<u32>,
443}
444
445#[must_use]
450pub fn recorded(target: &Utf8Path) -> Option<Result<Recorded, String>> {
451 let path = target.join(MANIFEST_PATH);
452 if !path.is_file() {
453 return None;
454 }
455 let text = match std::fs::read_to_string(&path) {
456 Ok(text) => text,
457 Err(error) => return Some(Err(error.to_string())),
458 };
459 Some(
460 Manifest::parse_any(&text)
461 .map(|(manifest, older_schema)| Recorded {
462 version: manifest.canon_version,
463 older_schema,
464 })
465 .map_err(|error| error.to_string()),
466 )
467}
468
469const NO_INSTANCE: &str = "This repository has no spec-driven-docs instance. Run `sdd init` to land it. Read the setup skill with `sdd skill show sdd-setup`, and each file it names with `sdd skill show sdd-setup --file <path>`.";
471
472fn pinned(target: &Utf8Path) -> Option<String> {
474 crate::self_depend::manager::detect(target)
475 .into_iter()
476 .find_map(|detected| detected.pin.map(|pin| pin.version.to_string()))
477}
478
479fn older(left: &str, right: &str) -> bool {
481 let parse = |version: &str| -> Option<Vec<u64>> {
482 version
483 .split('.')
484 .map(|part| part.parse().ok())
485 .collect::<Option<Vec<u64>>>()
486 };
487 matches!((parse(left), parse(right)), (Some(a), Some(b)) if a < b)
488}
489
490pub fn require_aligned(row: &Row, applied: bool, target: &Utf8Path) -> Result<Passed, AppError> {
497 let writes = match row.writes {
498 Writes::Never => false,
499 Writes::WithApply => applied,
500 Writes::Always => true,
501 };
502 let Some(record) = recorded(target) else {
503 return match row.class {
504 Class::ReadOnly | Class::Writing => Err(AppError::Refused(format!(
505 "{NO_INSTANCE} (setup:a-gated-command-names-its-fix)"
506 ))),
507 Class::Exempt | Class::PreLanding | Class::Upgrade => Ok(Passed::Quiet),
508 };
509 };
510 let effective = match (row.class, writes) {
511 (Class::Exempt | Class::Upgrade, _) | (Class::PreLanding, false) => {
512 return Ok(Passed::Quiet);
513 }
514 (Class::PreLanding | Class::Writing | Class::ReadOnly, true) => Class::Writing,
515 (Class::ReadOnly | Class::Writing, false) => Class::ReadOnly,
516 };
517 let Ok(record) = record else {
519 return Ok(Passed::Quiet);
520 };
521 let binary = CanonVersion::current().to_string();
522 let instance = record.version.to_string();
523 if older(&binary, &instance) {
524 let mut text = format!(
525 "The instance is at sdd {instance} and this sdd is {binary}, which is older. Run the sdd of this project's environment, for example `direnv exec . sdd ...`."
526 );
527 if let Some(pin) = pinned(target).filter(|pin| older(pin, &instance)) {
528 let _ = write!(text, " The pin names {pin}. Move it to {instance}.");
529 }
530 return Err(AppError::Refused(format!(
531 "{text} (setup:a-gated-command-names-its-fix)"
532 )));
533 }
534 if older(&instance, &binary) || record.older_schema.is_some() {
535 let schema = record
536 .older_schema
537 .map(|schema| format!(", recorded in schema {schema},"))
538 .unwrap_or_default();
539 let fix = if older(&instance, &binary) {
542 MOVED
543 } else {
544 "Run `sdd upgrade` to move the record."
545 };
546 if effective == Class::Writing {
547 return Err(AppError::Refused(format!(
548 "The instance is at sdd {instance}{schema} and this sdd is {binary}. {fix} Then run this command again. (setup:a-gated-command-names-its-fix)"
549 )));
550 }
551 return Ok(Passed::Warn(format!(
552 "warning: the instance is at sdd {instance}{schema} and this sdd is {binary}. {fix} (setup:a-gated-command-names-its-fix)"
553 )));
554 }
555 Ok(Passed::Quiet)
556}
557
558pub fn gate(command: &Commands, cwd: &Utf8Path) -> Result<(), AppError> {
567 let invocation = invocation_of(command);
568 let Some(row) = row_of(invocation.path) else {
569 return Ok(());
570 };
571 let Some(target) = invocation.target else {
572 return Ok(());
573 };
574 if row.class == Class::Exempt || row.target == TargetSource::None {
575 return Ok(());
576 }
577 let target = if target.is_absolute() {
578 target
579 } else if target == "." {
580 cwd.to_owned()
581 } else {
582 cwd.join(target)
583 };
584 if !target.is_dir() {
586 return Ok(());
587 }
588 if let Passed::Warn(line) = require_aligned(row, invocation.applied, &target)? {
589 eprintln!("{line}");
590 }
591 Ok(())
592}