Skip to main content

spec_driven_docs/domain/
rule_id.rs

1//! Rule identifiers: one variant per requirement the specs define.
2//!
3//! A rule ID is an address — `domain:rule` — that a failure message cites and
4//! a reader follows to the sentence that binds. This enum is the compile-time
5//! form of every `` ### `domain:rule` `` heading under the canon's specs; a
6//! parity test in `embedded` holds the two sets equal. Rule prose lives in
7//! the specs, never here.
8
9use std::fmt;
10
11macro_rules! rule_ids {
12    ($($variant:ident => $id:literal,)+) => {
13        /// A `domain:rule` requirement address defined by a spec.
14        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
15        pub enum RuleId {
16            $(
17                #[doc = $id]
18                $variant,
19            )+
20        }
21
22        impl RuleId {
23            /// Every rule the specs define, in slug order.
24            pub const ALL: &'static [Self] = &[$(Self::$variant),+];
25
26            /// The `domain:rule` slug pair this variant addresses.
27            #[must_use]
28            pub const fn as_str(self) -> &'static str {
29                match self {
30                    $(Self::$variant => $id),+
31                }
32            }
33
34            /// The rule one slug pair addresses, where a spec defines it.
35            #[must_use]
36            pub fn parse(id: &str) -> Option<Self> {
37                match id {
38                    $($id => Some(Self::$variant),)+
39                    _ => None,
40                }
41            }
42        }
43
44        impl serde::Serialize for RuleId {
45            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
46                serializer.serialize_str(self.as_str())
47            }
48        }
49
50        impl<'de> serde::Deserialize<'de> for RuleId {
51            fn deserialize<D: serde::Deserializer<'de>>(
52                deserializer: D,
53            ) -> Result<Self, D::Error> {
54                let id = <std::borrow::Cow<'_, str> as serde::Deserialize>::deserialize(
55                    deserializer,
56                )?;
57                Self::parse(&id).ok_or_else(|| {
58                    serde::de::Error::custom(format!("no spec defines the rule {id}"))
59                })
60            }
61        }
62    };
63}
64
65rule_ids! {
66    RecordedDimensionOnlyShrinks => "budget-debt:a-recorded-dimension-only-shrinks",
67    DebtIsCreatedByAnExplicitAct => "budget-debt:debt-is-created-by-an-explicit-act",
68    CellCarriesOneReference => "comparison-docs:a-cell-carries-one-reference",
69    ComparisonCarriesALegend => "comparison-docs:a-comparison-carries-a-legend",
70    VerdictCarriesItsWord => "comparison-docs:a-verdict-carries-its-word",
71    EveryTableIsDated => "comparison-docs:every-table-is-dated",
72    TablePipesAreEscaped => "comparison-docs:table-pipes-are-escaped",
73    CitationResolvesToARule => "decision-records:a-citation-resolves-to-a-rule",
74    BodyStaysWithinWordCap => "decision-records:body-stays-within-350-words",
75    FilenameCarriesNoDigit => "decision-records:filename-carries-no-digit",
76    MergedRecordIsPermanent => "decision-records:merged-record-is-permanent",
77    RecordIsNotRevised => "decision-records:record-is-not-revised",
78    DeclaredLocationIsNamedByItsVariable => "distribution:a-declared-location-is-named-by-its-variable",
79    LandingClassifiesItsTargetFirst => "distribution:a-landing-classifies-its-target-first",
80    SeededRuleRunsNoCanonCommand => "distribution:a-seeded-rule-runs-no-canon-command",
81    SkillChecksItsHostBeforeItPlans => "distribution:a-skill-checks-its-host-before-it-plans",
82    SkillHasOneOwner => "distribution:a-skill-has-one-owner",
83    SkillInstallRestoresOnFailure => "distribution:a-skill-install-restores-on-failure",
84    SkillObeysThePortableFormat => "distribution:a-skill-obeys-the-portable-format",
85    SkillPlansBeforeItActs => "distribution:a-skill-plans-before-it-acts",
86    InstallSweepsWhatThePayloadDropped => "distribution:an-install-sweeps-what-the-payload-dropped",
87    InitializationPreservesProjectContent => "distribution:initialization-preserves-project-content",
88    InstancesOperateOffline => "distribution:instances-operate-offline",
89    ManifestIdentifiesEveryOwnedFile => "distribution:manifest-identifies-every-owned-file",
90    DeclarationIsSeededOnceAndThenOwned => "distribution:the-declaration-is-seeded-once-and-then-owned",
91    SkillPackageIsSelfContained => "distribution:a-skill-package-is-self-contained",
92    SkillInstallPreviewsBeforeWriting => "distribution:skill-install-previews-before-writing",
93    SkillUninstallRemovesOnlyWhatItWrote => "distribution:skill-uninstall-removes-only-what-it-wrote",
94    SkillsArePartOfThePayload => "distribution:skills-are-part-of-the-payload",
95    TheDoctorAnswersForTheInstalledSkills => "distribution:the-doctor-answers-for-the-installed-skills",
96    ThePayloadNamesNoOtherProject => "distribution:the-payload-names-no-other-project",
97    ThePayloadNamesNoPlanningTool => "distribution:the-payload-names-no-planning-tool",
98    ThePayloadRootsAreDeclaredOnce => "distribution:the-payload-roots-are-declared-once",
99    UpgradeConflictsAreAtomic => "distribution:upgrade-conflicts-are-atomic",
100    UserScopeFilesStayUnrecorded => "distribution:user-scope-files-stay-unrecorded",
101    UserScopeReceiptIsRequiredState => "distribution:a-user-scope-receipt-is-required-state",
102    PlanIsStoredAndAppliedByItsId => "reconcile:a-plan-is-stored-and-applied-by-its-id",
103    ApplyRefusesAPlanWhoseInputsMoved => "reconcile:an-apply-refuses-a-plan-whose-inputs-moved",
104    OneWriterHoldsATarget => "reconcile:one-writer-holds-a-target",
105    PlanWritesNothing => "reconcile:a-plan-writes-nothing",
106    DecisionPrecedesWhatDependsOnIt => "reconcile:a-decision-precedes-what-depends-on-it",
107    FindingIsSomethingTheProgramProved => "reconcile:a-finding-is-something-the-program-proved",
108    WriteIntoAdoptedStateIsAnOperatorAct => "reconcile:a-write-into-adopted-state-is-an-operator-act",
109    IncrementalScopeLeavesNoStructuralFinding => "reconcile:an-incremental-scope-leaves-no-structural-finding",
110    OnePlanIsTheInputToEveryWrite => "reconcile:one-plan-is-the-input-to-every-write",
111    ReadinessIsTheWorstPrecondition => "reconcile:readiness-is-the-worst-precondition",
112    FingerprintCoversWhatTheApplyWouldDo => "reconcile:the-fingerprint-covers-what-the-apply-would-do",
113    PlannerIsDeterministic => "reconcile:the-planner-is-deterministic",
114    TargetDecidesItsClassification => "reconcile:the-target-decides-its-classification",
115    ReleaseIsReadThroughOneSeam => "bundle:a-release-is-read-through-one-seam",
116    ReleaseDeclaresWhatItLands => "bundle:a-release-declares-what-it-lands",
117    ProtocolVersionIsARangeTheEngineDeclares => "bundle:the-protocol-version-is-a-range-the-engine-declares",
118    PreSchemaReleaseIsCatalogedOrUnavailable => "bundle:a-pre-schema-release-is-cataloged-or-unavailable",
119    FetchedArchiveIsVerifiedBeforeItIsRead => "bundle:a-fetched-archive-is-verified-before-it-is-read",
120    ResolutionHappensOnceAndWritesOnlyTheCache => "bundle:resolution-happens-once-and-writes-only-the-cache",
121    RunThatDidNotFinishIsRolledBack => "reconcile:a-run-that-did-not-finish-is-rolled-back",
122    ApplyProvesEveryPostconditionItReports => "reconcile:an-apply-proves-every-postcondition-it-reports",
123    DestinationIsContainedBeforeItIsWritten => "reconcile:a-destination-is-contained-before-it-is-written",
124    PlanIdIsAFingerprintAndNeverAPath => "reconcile:a-plan-id-is-a-fingerprint-and-never-a-path",
125    ApplyResolvesNothing => "reconcile:an-apply-resolves-nothing",
126    TargetRecordsTheReleaseItHolds => "reconcile:a-target-records-the-release-it-holds",
127    ReleaseDeclaresWhatItAsksOfItsOperator => "reconcile:a-release-declares-what-it-asks-of-its-operator",
128    OneCatalogDescribesEveryServedDocument => "docs-discovery:one-catalog-describes-every-served-document",
129    InstanceIsRoutedToTheIndex => "docs-discovery:an-instance-is-routed-to-the-index",
130    AuthorInstructionsStayWithinBudget => "docs-format:author-instructions-stay-within-budget",
131    ChapterStaysWithinLineCap => "docs-format:chapter-stays-within-200-lines",
132    DocumentStatesThePresent => "docs-format:document-states-the-present",
133    DocumentUsesStructuralMarkdownOnly => "docs-format:document-uses-structural-markdown-only",
134    EveryBudgetCarriesAGate => "docs-format:every-budget-carries-a-gate",
135    FenceDeclaresALanguage => "docs-format:fence-declares-a-language",
136    ProseStaysUnwrapped => "docs-format:prose-stays-unwrapped",
137    DocumentCarriesNoPersonalPath => "docs-foundations:a-document-carries-no-personal-path",
138    DocumentDirectoryExplainsItself => "docs-foundations:a-document-directory-explains-itself",
139    DocumentOwnsWhatItGoverns => "docs-foundations:a-document-owns-what-it-governs",
140    KindPrefixCarriesASlug => "docs-foundations:a-kind-prefix-carries-a-slug",
141    ArtifactFilenamesCarryAKindPrefix => "docs-foundations:artifact-filenames-carry-a-kind-prefix",
142    CompanionArtifactsShareTheSpecName => "docs-foundations:companion-artifacts-share-the-spec-name",
143    SpecStatesThePresent => "docs-foundations:spec-states-the-present",
144    SpecWinsOverRecord => "docs-foundations:spec-wins-over-record",
145    SpecsAreCentralized => "docs-foundations:specs-are-centralized",
146    ProhibitionsAreCapped => "docs-specs:prohibitions-are-capped",
147    RequirementCarriesAVerification => "docs-specs:requirement-carries-a-verification",
148    RequirementCarriesFiveParts => "docs-specs:requirement-carries-five-parts",
149    RuleIdIsUniqueAndSlugged => "docs-specs:rule-id-is-unique-and-slugged",
150    RuleIdOutlivesItsSentence => "docs-specs:rule-id-outlives-its-sentence",
151    SpecStaysWithinLineCap => "docs-specs:spec-stays-within-300-lines",
152    StatementUsesAnEarsPattern => "docs-specs:statement-uses-an-ears-pattern",
153    UnenforcedRulesAreDeclared => "docs-specs:unenforced-rules-are-declared",
154    VerificationNamesALiveHook => "docs-specs:verification-names-a-live-hook",
155    DivergentResultNamesItsDestination => "guides:a-divergent-result-names-its-destination",
156    ManualStepEnumeratesItsInteraction => "guides:a-manual-step-enumerates-its-interaction",
157    StepFollowsItsProducers => "guides:a-step-follows-its-producers",
158    StepIsOneImperativeAction => "guides:a-step-is-one-imperative-action",
159    ExternalFactIsVerifiedUpstream => "guides:an-external-fact-is-verified-upstream",
160    CitationsLiveInTheReferenceZone => "guides:citations-live-in-the-reference-zone",
161    EveryStepCarriesItsCheck => "guides:every-step-carries-its-check",
162    PreconditionsOpenAndVerificationCloses => "guides:preconditions-open-and-verification-closes",
163    TheManifestStaysReadable => "instance:the-manifest-stays-readable",
164    AgentsBlockStaysManaged => "instance:the-agents-block-stays-managed",
165    TrackingRegistryStaysValid => "instance:the-tracking-registry-stays-valid",
166    ProjectDeclaresWhatItsGatesJudge => "instance:the-project-declares-what-its-gates-judge",
167    ManagedBlockAgreesWithTheDeclaration => "instance:the-managed-block-agrees-with-the-declaration",
168    BugzillaReportBodyFitsReportWidth => "known-issues:a-bugzilla-report-body-fits-in-79-columns",
169    FiledRecordCarriesItsReport => "known-issues:a-filed-record-carries-its-report",
170    RecordCarriesItsRetirementCondition => "known-issues:a-record-carries-its-retirement-condition",
171    RecordCarriesOneFilingState => "known-issues:a-record-carries-one-filing-state",
172    RecordCarriesOneState => "known-issues:a-record-carries-one-state",
173    RecordRecordsItsLastCheck => "known-issues:a-record-records-its-last-check",
174    RecordWalksTheMechanism => "known-issues:a-record-walks-the-mechanism",
175    CaseIdIsASlug => "known-issues:case-id-is-a-slug",
176    CanonGateIsNotDelivered => "release:a-canon-gate-is-not-delivered",
177    DeliveredGateReadsWhatTheConventionOwns => "release:a-delivered-gate-reads-what-the-convention-owns",
178    ReleasedVersionIsNotReAuthored => "release:a-released-version-is-not-re-authored",
179    TagDerivesFromTheVersionFile => "release:a-tag-derives-from-the-version-file",
180    EveryReleaseDeclaresWhatItAsks => "release:every-release-declares-what-it-asks",
181    LicenseDeclaresBothHalves => "release:license-declares-both-halves",
182    CanonRecordDescribesItsTree => "release:the-canon-record-describes-its-tree",
183    RkPinHasTwoFactsAndOneMover => "release:the-rk-pin-has-two-facts-and-one-mover",
184    DeliveredGateSetIsDeclaredOnce => "release:the-delivered-gate-set-is-declared-once",
185    ThirdPartyNoticesTravelWithThePayload => "release:third-party-notices-travel-with-the-payload",
186    VersionsAreSemanticAndAligned => "release:versions-are-semantic-and-aligned",
187    CommentCitesTheRule => "spec-to-code:a-comment-cites-the-rule",
188    CommentNamesNoRecord => "spec-to-code:a-comment-names-no-record",
189    GateMessageCitesTheRule => "spec-to-code:a-gate-message-cites-the-rule",
190    SpecChangeIsTyped => "spec-to-code:a-spec-change-is-typed",
191    SpecMayLeadItsCode => "spec-to-code:a-spec-may-lead-its-code",
192    SuppressionNamesItsCase => "spec-to-code:a-suppression-names-its-case",
193    EntryDocumentCitesRuleIds => "spec-to-code:an-entry-document-cites-rule-ids",
194    UnenactedRulesAreTheBacklog => "spec-to-code:unenacted-rules-are-the-backlog",
195    DeclaredDependentExists => "tracking:a-declared-dependent-exists",
196    PerishableSourceIsRegistered => "tracking:a-perishable-source-is-registered",
197    EntryDeclaresHowToRevalidate => "tracking:an-entry-declares-how-to-revalidate",
198    OverdueEntryBlocks => "tracking:an-overdue-entry-blocks",
199    UpstreamCheckDoesNotEditTheTree => "tracking:an-upstream-check-does-not-edit-the-tree",
200    UpstreamDerivationPinsARevision => "tracking:an-upstream-derivation-pins-a-revision",
201    RegistryHasOneReadableShape => "tracking:the-registry-has-one-readable-shape",
202    ExistingDocumentConvertsWhenEdited => "writing-style:an-existing-document-converts-when-edited",
203    NoDeliveredGateJudgesProse => "writing-style:no-delivered-gate-judges-prose",
204    SourcesNameTheRevisionRead => "writing-style:sources-name-the-revision-read",
205    DocumentationBlockRoutesToTheStyle => "writing-style:the-documentation-block-routes-to-the-style",
206    StyleLivesInOneDocument => "writing-style:the-style-lives-in-one-document",
207    NoneImposesNoObligation => "writing-policy:none-imposes-no-obligation",
208    ProjectSelectsOneSource => "writing-policy:the-project-selects-one-source",
209}
210
211impl fmt::Display for RuleId {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        f.write_str(self.as_str())
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn slugs_are_well_formed_and_unique() {
223        let mut seen = std::collections::BTreeSet::new();
224        for rule in RuleId::ALL {
225            let id = rule.as_str();
226            let (domain, name) = id.split_once(':').unwrap();
227            let assert_slug = |part: &str| {
228                assert!(!part.is_empty(), "{id} has an empty half");
229                assert!(
230                    part.bytes()
231                        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'),
232                    "{id} is not a slug pair"
233                );
234            };
235            assert_slug(domain);
236            assert_slug(name);
237            assert!(seen.insert(id), "{id} is duplicated");
238        }
239    }
240
241    #[test]
242    fn display_renders_the_slug_pair() {
243        assert_eq!(
244            RuleId::ChapterStaysWithinLineCap.to_string(),
245            "docs-format:chapter-stays-within-200-lines"
246        );
247    }
248}