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