agent-spec 0.3.0

AI-native BDD/Spec verification tool for contract-driven agent coding
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Spec hierarchy level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SpecLevel {
    Org,
    Project,
    /// Capability scope: a long-lived living-spec holding Rules proven by tasks (Phase 3).
    Capability,
    Task,
}

/// Language used in the spec.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Lang {
    Zh,
    En,
}

/// Front-matter metadata of a spec file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecMeta {
    pub level: SpecLevel,
    pub name: String,
    pub inherits: Option<String>,
    pub lang: Vec<Lang>,
    pub tags: Vec<String>,
    /// Spec-level dependencies: names of other specs this spec depends on.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub depends: Vec<String>,
    /// Estimated effort (e.g., "0.5d", "2d", "1w").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub estimate: Option<String>,
    /// Capability this task contributes to (Phase 3). Additive; `None` for
    /// specs that declare no `capability:`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capability: Option<String>,
}

/// An author's deliberate waiver of a lint rule, recorded inline as
/// `<!-- lint-ack: <code> — <reason> -->` (Phase 5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LintAck {
    pub code: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub reason: String,
}

/// A parsed .spec document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecDocument {
    pub meta: SpecMeta,
    pub sections: Vec<Section>,
    /// Inline lint-ack waivers (Phase 5). Additive; empty for specs with none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub lint_acks: Vec<LintAck>,
    #[serde(skip)]
    pub source_path: PathBuf,
}

/// A top-level section in the spec body.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Section {
    Intent {
        content: String,
        span: Span,
    },
    Constraints {
        items: Vec<Constraint>,
        span: Span,
    },
    Decisions {
        items: Vec<String>,
        span: Span,
    },
    Boundaries {
        items: Vec<Boundary>,
        span: Span,
    },
    AcceptanceCriteria {
        scenarios: Vec<Scenario>,
        /// BDD behavior rules grouping scenarios under this section.
        /// Additive (Phase 1 BDD semantics); empty for specs without `Rule:` lines.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        rules: Vec<BehaviorRule>,
        /// `Rule:` lines whose id was not a valid kebab-case identifier.
        /// Retained (not promoted to a [`BehaviorRule`]) so the `bdd-rule-id`
        /// lint can flag them. Additive.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        malformed_rules: Vec<MalformedRule>,
        span: Span,
    },
    OutOfScope {
        items: Vec<String>,
        span: Span,
    },
    /// Discovery questions (Phase 4): unresolved items to clarify before
    /// implementation. Not scenarios; does not affect verification.
    Questions {
        items: Vec<String>,
        span: Span,
    },
}

/// A single constraint line.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Constraint {
    pub text: String,
    pub category: ConstraintCategory,
    pub span: Span,
}

/// Constraint categories matching the DSL sections.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConstraintCategory {
    Must,
    MustNot,
    Decided,
    General,
}

/// A task boundary item.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Boundary {
    pub text: String,
    pub category: BoundaryCategory,
    pub span: Span,
}

/// Boundary categories for task contracts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BoundaryCategory {
    Allow,
    Deny,
    General,
}

/// Scenario execution mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ScenarioMode {
    #[default]
    Standard,
    Optimize,
}

impl ScenarioMode {
    pub fn is_standard(&self) -> bool {
        *self == Self::Standard
    }
}

/// Review mode for a scenario: whether it needs human review after passing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReviewMode {
    #[default]
    Auto,
    Human,
}

impl ReviewMode {
    pub fn is_auto(&self) -> bool {
        *self == Self::Auto
    }
}

/// Scope of a BDD behavior rule. The keystone of the BDD-spine roadmap:
/// the same Rule primitive lifts across task/capability/project scope by
/// changing only this field, never the stable `id`.
///
/// Phase 1 only produces `Task`; `Capability` and `Project` are reserved
/// variants written into the AST but not parsed/loaded/promoted yet.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RuleScope {
    /// Task scope, namespaced by the spec file stem (not the human display name).
    Task(String),
    /// Capability scope (reserved; Phase 3).
    Capability(String),
    /// Project scope (reserved; Phase 3).
    Project,
}

/// Stable identity of a behavior rule: `{ scope, id }`.
/// `id` is the stable kebab-case identifier; the human display text lives in
/// `BehaviorRule.name` and may change freely without breaking references.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuleKey {
    pub scope: RuleScope,
    pub id: String,
}

/// Lifecycle event in a behavior rule's provenance log (Phase 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleEventKind {
    Created,
    Promoted,
    Affirmed,
    Deprecated,
}

/// A single provenance event on a behavior rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuleEvent {
    pub kind: RuleEventKind,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub note: String,
}

/// A BDD behavior rule: a promise the system should keep, proven by one or
/// more scenarios (examples). Formulation-layer primitive (Phase 1).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BehaviorRule {
    pub key: RuleKey,
    /// Human-readable display text. Defaults to `key.id` when no display name given.
    pub name: String,
    /// Names of scenarios grouped under this rule, in document order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scenario_names: Vec<String>,
    /// Provenance event log (Phase 3). Additive; empty for freshly-parsed rules.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub events: Vec<RuleEvent>,
    pub span: Span,
}

/// A `Rule:` header whose leading token was not a valid kebab-case id, so it
/// was not promoted to a [`BehaviorRule`]. Carries the raw content for the
/// `bdd-rule-id` lint to report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MalformedRule {
    pub raw: String,
    pub span: Span,
}

/// A BDD scenario.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Scenario {
    pub name: String,
    pub steps: Vec<Step>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test_selector: Option<TestSelector>,
    pub tags: Vec<String>,
    #[serde(default, skip_serializing_if = "ReviewMode::is_auto")]
    pub review: ReviewMode,
    #[serde(default, skip_serializing_if = "ScenarioMode::is_standard")]
    pub mode: ScenarioMode,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub depends_on: Vec<String>,
    /// `id` of the owning [`BehaviorRule`], if this scenario is grouped under one.
    /// Additive (Phase 1 BDD semantics); `None` for ungrouped/legacy scenarios.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rule: Option<String>,
    pub span: Span,
}

impl Scenario {
    /// Returns `true` if this scenario is marked as critical — either via a
    /// `critical` tag or a `(critical)` / `(critical)` name suffix (case-insensitive).
    pub fn is_critical(&self) -> bool {
        let has_tag = self.tags.iter().any(|t| t.eq_ignore_ascii_case("critical"));
        if has_tag {
            return true;
        }
        let lower = self.name.to_lowercase();
        lower.ends_with("(critical)") || lower.ends_with("(critical)")
    }

    /// Returns the scenario name with any trailing `(critical)` / `(critical)`
    /// suffix stripped, suitable for display purposes.
    pub fn display_name(&self) -> &str {
        let name = self.name.trim_end();
        // Try ASCII parentheses first
        if let Some(idx) = name.rfind('(') {
            let suffix = &name[idx..];
            if suffix.to_lowercase() == "(critical)" {
                return name[..idx].trim_end();
            }
        }
        // Try fullwidth parentheses
        if let Some(idx) = name.rfind('') {
            let suffix = &name[idx..];
            if suffix.to_lowercase() == "(critical)" {
                return name[..idx].trim_end();
            }
        }
        name
    }
}

/// Structured test selector for binding a scenario to test execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TestSelector {
    pub filter: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub package: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub level: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test_double: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub targets: Option<String>,
}

impl TestSelector {
    pub fn filter_only(filter: impl Into<String>) -> Self {
        Self {
            filter: filter.into(),
            package: None,
            level: None,
            test_double: None,
            targets: None,
        }
    }

    pub fn label(&self) -> String {
        match &self.package {
            Some(package) => format!("{package}::{}", self.filter),
            None => self.filter.clone(),
        }
    }
}

/// A verifiable binding for a scenario (Phase 6.5). `Test` is the binding that
/// exists today; the other variants are reserved mounting points for Phase 7
/// runners (structural checks, benchmarks, external probes, AI inference).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Probe {
    Test(TestSelector),
    /// A structural/static check expression (Phase 7).
    Static(String),
    /// A benchmark probe with a runner, filter, and threshold (Phase 7).
    Benchmark {
        runner: String,
        filter: String,
        threshold: String,
    },
    /// An external probe invoked via a runner with args (Phase 7).
    External {
        runner: String,
        args: Vec<String>,
    },
    /// An inferential (AI) probe (Phase 7).
    Inferential,
}

impl Probe {
    /// Derive a scenario's probe. Back-compat shim: a scenario with a
    /// `test_selector` derives `Probe::Test`; `Test:` remains sugar for it.
    pub fn from_scenario(scenario: &Scenario) -> Option<Probe> {
        scenario.test_selector.clone().map(Probe::Test)
    }

    /// Stable kind label for reporting.
    pub fn kind_label(&self) -> &'static str {
        match self {
            Probe::Test(_) => "test",
            Probe::Static(_) => "static",
            Probe::Benchmark { .. } => "benchmark",
            Probe::External { .. } => "external",
            Probe::Inferential => "inferential",
        }
    }
}

/// BDD step keyword.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StepKind {
    Given,
    When,
    Then,
    And,
    But,
}

/// A single Given/When/Then step.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Step {
    pub kind: StepKind,
    pub text: String,
    pub params: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub table: Vec<Vec<String>>,
    pub span: Span,
}

/// Source location span.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Span {
    pub start_line: usize,
    pub end_line: usize,
    pub start_col: usize,
    pub end_col: usize,
}

impl Span {
    pub fn new(start_line: usize, start_col: usize, end_line: usize, end_col: usize) -> Self {
        Self {
            start_line,
            end_line,
            start_col,
            end_col,
        }
    }

    pub fn line(line: usize) -> Self {
        Self {
            start_line: line,
            end_line: line,
            start_col: 0,
            end_col: 0,
        }
    }
}

/// A resolved spec with inherited constraints merged.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedSpec {
    pub task: SpecDocument,
    pub inherited_constraints: Vec<Constraint>,
    pub inherited_decisions: Vec<String>,
    pub all_scenarios: Vec<Scenario>,
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod probe_tests {
    use super::*;

    #[test]
    fn test_probe_kind_label_test() {
        let p = Probe::Test(TestSelector::filter_only("test_x"));
        assert_eq!(p.kind_label(), "test");
    }

    #[test]
    fn test_probe_kind_label_reserved_variants() {
        assert_eq!(Probe::Static("x".into()).kind_label(), "static");
        assert_eq!(
            Probe::Benchmark {
                runner: "criterion".into(),
                filter: "b".into(),
                threshold: "p95<2s".into()
            }
            .kind_label(),
            "benchmark"
        );
        assert_eq!(
            Probe::External {
                runner: "curl".into(),
                args: vec![]
            }
            .kind_label(),
            "external"
        );
        assert_eq!(Probe::Inferential.kind_label(), "inferential");
    }

    #[test]
    fn test_probe_roundtrips() {
        let p = Probe::Benchmark {
            runner: "criterion".into(),
            filter: "bench_x".into(),
            threshold: "p95<2000ms".into(),
        };
        let json = serde_json::to_string(&p).unwrap();
        let back: Probe = serde_json::from_str(&json).unwrap();
        assert_eq!(back, p);
    }
}