@llman-sdd/core 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llman-sdd/core",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "Pure domain logic for llman-sdd (config, gherkin specs, validation, templates)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -27,8 +27,10 @@
27
27
  "7z-wasm": "^1.2.0",
28
28
  "@cucumber/gherkin": "^42.0.1",
29
29
  "@cucumber/messages": "^34.2.1",
30
+ "@statelyai/graph": "^2.6.0",
30
31
  "@toon-format/toon": "^4.1.1",
31
32
  "nunjucks": "^3.2.4",
33
+ "xstate": "^5.33.2",
32
34
  "yaml": "^2.9.1",
33
35
  "zod": "^4.6.5"
34
36
  },
@@ -29,6 +29,12 @@ export const specsSchema = z.object({
29
29
  'Spec verification command executed by validate for spec targets (opt-in via --check; default skips). Placeholders: {feature_path}, {feature_dir}, {feature_name}; without placeholders it runs once per validate invocation (batch-once). Legacy `bdd.run_command` is elevated onto this key at load time.',
30
30
  ),
31
31
  verify_prompt: z.string().nullish().describe('Extra prompt text injected during verify phase.'),
32
+ check_transitions: z
33
+ .boolean()
34
+ .nullish()
35
+ .describe(
36
+ 'When true, automatically discovers Gherkin Scenario Outline state transition tables (from/event/to) and enforces strict XState graph gates (determinism, reachability, deadlock, and step placeholder binding). Default: false.',
37
+ ),
32
38
  });
33
39
 
34
40
  export const archiveSchema = z.object({
package/src/index.ts CHANGED
@@ -31,6 +31,7 @@ export type {
31
31
  ScenarioStep,
32
32
  SpecStructuralError,
33
33
  } from './spec/ir.ts';
34
+ export { assignSpecIds, featureRelPath, preferredSpecIdFromRel } from './spec/assignSpecIds.ts';
34
35
  export { ruleHasRunnableScenario, specIdOf } from './spec/ir.ts';
35
36
  export {
36
37
  SpecParseError,
@@ -96,6 +97,12 @@ export type {
96
97
  } from './validation/validate.ts';
97
98
  export { validateAllSpecs, validateCapability } from './validation/validate.ts';
98
99
  export { buildDuplicatesFor, formatTotals } from './validation/validate.ts';
100
+ export {
101
+ isTransitionOutline,
102
+ parseTransitionExpr,
103
+ validateTransitionScenario,
104
+ type TransitionEdge,
105
+ } from './validation/transitions.ts';
99
106
  export { splitVerb } from './config/changeId.ts';
100
107
  export {
101
108
  checkChangeDoc,
@@ -17,12 +17,28 @@ export interface MigrationEntry {
17
17
  }
18
18
 
19
19
  export const MIGRATIONS: readonly MigrationEntry[] = [
20
+ {
21
+ id: '0.8.1->0.9.0',
22
+ title: 'Retire `# capability:` header; assign spec ids from paths (r101)',
23
+ steps: [
24
+ 'Run `llman-sdd project migrate strip-legacy-headers --dry-run` to preview spec header strips.',
25
+ 'Run `llman-sdd project migrate strip-legacy-headers` to remove `# capability:` (and any remaining `# scope:` / `# reviewed-through:`) lines.',
26
+ 'Ensure each `功能:` / `Feature:` title equals the assigned spec id (`llman-sdd list --specs` for ids).',
27
+ 'Run `llman-sdd init --update` to refresh managed skills and feature-contract guidance.',
28
+ 'Run `llman-sdd validate --all --strict` — it must pass.',
29
+ ],
30
+ checks: [
31
+ 'No `# capability:` lines remain under `llmanspec/specs/**`.',
32
+ 'Each spec file `功能:` title matches `llman-sdd show <spec-id>` id.',
33
+ '`llman-sdd list --specs` reports stable ids for flat and directory layouts.',
34
+ ],
35
+ },
20
36
  {
21
37
  id: '0.7.5->0.8.0',
22
38
  title: 'Governance metadata retirement (`# reviewed-through:` stamp & `# scope:` header)',
23
39
  steps: [
24
40
  'Run `llman-sdd project migrate strip-legacy-headers --dry-run` to preview the affected spec files.',
25
- 'Run `llman-sdd project migrate strip-legacy-headers` to strip the legacy `# scope:` / `# reviewed-through:` header comment lines (idempotent).',
41
+ 'Run `llman-sdd project migrate strip-legacy-headers` to strip legacy `# scope:` / `# reviewed-through:` / `# capability:` header comment lines (idempotent).',
26
42
  'Run `llman-sdd init --update` to refresh the managed AGENTS blocks and agent skills.',
27
43
  'Run `llman-sdd validate --all --strict` — it must pass.',
28
44
  ],
@@ -1,3 +1,4 @@
1
+ import { assignSpecIds } from '../spec/assignSpecIds.ts';
1
2
  import { officialKeywords, officialKeywordsOrEn } from '../spec/keywords.ts';
2
3
  import { localeToGherkinLang, parseCapability } from '../spec/parser.ts';
3
4
  import { buildReqRegistry } from '../spec/reqRegistry.ts';
@@ -6,6 +7,7 @@ import { buildReqRegistry } from '../spec/reqRegistry.ts';
6
7
  * skeleton generation + global next req id. Pure, IO injected.
7
8
  */
8
9
  import { localeFallbacks } from '../templates/locale.ts';
10
+ import type { SpecEntry } from '../validation/validate.ts';
9
11
 
10
12
  export interface SpecHelperIo {
11
13
  exists(path: string): boolean;
@@ -16,13 +18,8 @@ export interface SpecHelperIo {
16
18
  listDir(path: string): string[];
17
19
  }
18
20
 
19
- interface ParsedEntry {
20
- fileName: string;
21
- doc: ReturnType<typeof parseCapability>;
22
- }
23
-
24
- function collectSpecEntries(io: SpecHelperIo, specsDir: string): ParsedEntry[] {
25
- const entries: ParsedEntry[] = [];
21
+ function collectSpecEntries(io: SpecHelperIo, specsDir: string): SpecEntry[] {
22
+ const entries: SpecEntry[] = [];
26
23
  const walk = (dir: string): void => {
27
24
  if (!io.exists(dir)) return;
28
25
  for (const name of io.listDir(dir)) {
@@ -35,6 +32,7 @@ function collectSpecEntries(io: SpecHelperIo, specsDir: string): ParsedEntry[] {
35
32
  }
36
33
  };
37
34
  walk(specsDir);
35
+ assignSpecIds(entries, specsDir);
38
36
  return entries;
39
37
  }
40
38
 
@@ -63,8 +61,8 @@ export function skeletonContent(capability: string, reqId: string, locale: strin
63
61
  const language = officialKeywords(mapped) !== null ? mapped : 'en';
64
62
  const kw = officialKeywordsOrEn(language);
65
63
  const header = zh
66
- ? `# language: ${language}\n# capability: ${capability}\n# purpose: TODO: 一句话描述该能力与其目的。`
67
- : `# language: ${language}\n# capability: ${capability}\n# purpose: TODO: Describe this capability and its purpose.`;
64
+ ? `# language: ${language}\n# purpose: TODO: 一句话描述该能力与其目的。`
65
+ : `# language: ${language}\n# purpose: TODO: Describe this capability and its purpose.`;
68
66
  const ruleDesc = zh ? 'TODO: 需求描述(自由文本)。' : 'TODO: requirement statement (free text).';
69
67
  // Skeleton placeholder prose is not vocabulary — the zh/en copy stays; keywords do not.
70
68
  const steps = zh
@@ -22,6 +22,7 @@ export interface ReviewInput {
22
22
  activeChanges?: readonly { name: string; completedTasks: number; totalTasks: number }[];
23
23
  /** Restrict per-capability signals (unbound) to this capability. */
24
24
  capability?: string;
25
+ checkTransitions?: boolean;
25
26
  }
26
27
 
27
28
  export interface ReviewResult {
@@ -41,7 +42,7 @@ export function buildReview(input: ReviewInput, io: SpecIo): ReviewResult {
41
42
  signals.push({ kind, capability, count, detail });
42
43
  };
43
44
 
44
- const sweep = validateAllSpecs(entries, io);
45
+ const sweep = validateAllSpecs(entries, io, { checkTransitions: input.checkTransitions });
45
46
  const sorted = [...entries].toSorted((a, b) => a.fileName.localeCompare(b.fileName));
46
47
 
47
48
  for (const entry of sorted) {
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Global spec-id assignment (spec-parsing r101): after discovering all
3
+ * `.feature` files under one `llmanspec/specs/` instance, each entry gets a
4
+ * unique `specId` from path preference + collision disambiguation.
5
+ */
6
+ /** Minimal entry shape for id assignment (avoids validation↔spec cycle). */
7
+ export interface SpecIdAssignable {
8
+ fileName: string;
9
+ specId?: string;
10
+ }
11
+
12
+ /** `rel` path relative to specs root (POSIX slashes, includes `.feature`). */
13
+ export function featureRelPath(fileName: string, specsDir: string): string {
14
+ const norm = (p: string): string => p.replace(/\\/g, '/').replace(/\/$/u, '');
15
+ const root = norm(specsDir);
16
+ let rel = norm(fileName);
17
+ const prefix = `${root}/`;
18
+ if (rel.startsWith(prefix)) rel = rel.slice(prefix.length);
19
+ return rel;
20
+ }
21
+
22
+ /** Preference id before instance-wide collision resolution (r101). */
23
+ export function preferredSpecIdFromRel(rel: string): string {
24
+ const withoutExt = rel.replace(/\.feature$/u, '');
25
+ const parts = withoutExt.split('/');
26
+ const stem = parts.at(-1) ?? '';
27
+ if (parts.length === 1) return stem;
28
+ if (parts.length === 2 && parts[0] === stem) return stem;
29
+ return withoutExt;
30
+ }
31
+
32
+ function finalSpecIdFromRel(rel: string, preferredCount: number): string {
33
+ const preferred = preferredSpecIdFromRel(rel);
34
+ if (preferredCount === 1) return preferred;
35
+ return rel.replace(/\.feature$/u, '');
36
+ }
37
+
38
+ /**
39
+ * Mutates `entries[].specId`. Returns spec ids that appear on more than one
40
+ * file after assignment (layout error).
41
+ */
42
+ export function assignSpecIds(entries: SpecIdAssignable[], specsDir: string): Set<string> {
43
+ const rels = entries.map((entry) => ({
44
+ entry,
45
+ rel: featureRelPath(entry.fileName, specsDir),
46
+ }));
47
+
48
+ const preferredCounts = new Map<string, number>();
49
+ for (const { rel } of rels) {
50
+ const preferred = preferredSpecIdFromRel(rel);
51
+ preferredCounts.set(preferred, (preferredCounts.get(preferred) ?? 0) + 1);
52
+ }
53
+
54
+ for (const { entry, rel } of rels) {
55
+ const preferred = preferredSpecIdFromRel(rel);
56
+ const count = preferredCounts.get(preferred) ?? 0;
57
+ entry.specId = finalSpecIdFromRel(rel, count);
58
+ }
59
+
60
+ const byId = new Map<string, number>();
61
+ for (const { entry } of rels) {
62
+ const id = entry.specId ?? '';
63
+ byId.set(id, (byId.get(id) ?? 0) + 1);
64
+ }
65
+ return new Set([...byId.entries()].filter(([, n]) => n > 1).map(([id]) => id));
66
+ }
package/src/spec/ir.ts CHANGED
@@ -11,7 +11,6 @@
11
11
  */
12
12
 
13
13
  export interface CapabilityHeader {
14
- capability: string | null;
15
14
  purpose: string | null;
16
15
  }
17
16
 
@@ -22,6 +21,14 @@ export interface ScenarioStep {
22
21
  text: string;
23
22
  }
24
23
 
24
+ export interface ExamplesBlockIR {
25
+ name: string;
26
+ /** Trimmed header column names, e.g. ['from', 'event', 'to']. */
27
+ headers: string[];
28
+ /** Each row is a list of trimmed cell values aligned with `headers`. */
29
+ rows: string[][];
30
+ }
31
+
25
32
  export interface ScenarioIR {
26
33
  name: string;
27
34
  /** Non-`@req` tags on this scenario (e.g. `@skip`, `@experimental`). */
@@ -32,6 +39,10 @@ export interface ScenarioIR {
32
39
  steps: ScenarioStep[];
33
40
  /** Step-texts joined (retrieval/context surface); empty for a stepless scenario. */
34
41
  statement: string;
42
+ /** True when the scenario has at least one Examples block or uses Scenario Outline keyword. */
43
+ isOutline?: boolean;
44
+ /** Parsed Examples blocks attached to this scenario. */
45
+ examples?: ExamplesBlockIR[];
35
46
  }
36
47
 
37
48
  export interface RuleIR {
@@ -76,11 +87,11 @@ export function ruleHasRunnableScenario(rule: RuleIR): boolean {
76
87
  }
77
88
 
78
89
  /**
79
- * Single spec-id caliber (r25) for every consumer that labels a discovered
80
- * spec entry: the `# capability:` header wins, else the fileName minus the
81
- * `.feature` suffix. Unifies the former dual caliber (bare `fileName` vs
82
- * stripped stem) shared by review/context-tree/specs-report/validate paths.
90
+ * Spec id for a discovered entry (r101): `entry.specId` after assignSpecIds;
91
+ * inline-parse fallback uses the basename stem only.
83
92
  */
84
- export function specIdOf(entry: { fileName: string; doc: CapabilityDoc }): string {
85
- return entry.doc.header.capability ?? entry.fileName.replace(/\.feature$/u, '');
93
+ export function specIdOf(entry: { fileName: string; doc: CapabilityDoc; specId?: string }): string {
94
+ if (entry.specId !== undefined && entry.specId !== '') return entry.specId;
95
+ const base = entry.fileName.replace(/\\/g, '/').split('/').pop() ?? entry.fileName;
96
+ return base.replace(/\.feature$/u, '');
86
97
  }
@@ -17,6 +17,8 @@ export interface GherkinKeywords {
17
17
  feature: string;
18
18
  rule: string;
19
19
  scenario: string;
20
+ scenarioOutline: string;
21
+ examples: string;
20
22
  given: string;
21
23
  when: string;
22
24
  thenText: string;
@@ -29,6 +31,8 @@ const TABLE_KEY_PAIRS = [
29
31
  ['feature', 'feature'],
30
32
  ['rule', 'rule'],
31
33
  ['scenario', 'scenario'],
34
+ ['scenarioOutline', 'scenarioOutline'],
35
+ ['examples', 'examples'],
32
36
  ['given', 'given'],
33
37
  ['when', 'when'],
34
38
  ['then', 'thenText'],
@@ -40,6 +44,8 @@ const LOCKED_KEYWORDS: Record<string, GherkinKeywords> = {
40
44
  feature: 'Feature',
41
45
  rule: 'Rule',
42
46
  scenario: 'Scenario',
47
+ scenarioOutline: 'Scenario Outline',
48
+ examples: 'Examples',
43
49
  given: 'Given',
44
50
  when: 'When',
45
51
  thenText: 'Then',
@@ -48,6 +54,8 @@ const LOCKED_KEYWORDS: Record<string, GherkinKeywords> = {
48
54
  feature: '功能',
49
55
  rule: '规则',
50
56
  scenario: '场景',
57
+ scenarioOutline: '场景大纲',
58
+ examples: '例子',
51
59
  given: '假如',
52
60
  when: '当',
53
61
  thenText: '那么',
@@ -63,6 +71,8 @@ function keywordsFromTable(table: Dialect): GherkinKeywords | null {
63
71
  feature: pickKeyword(table.feature),
64
72
  rule: pickKeyword(table.rule),
65
73
  scenario: pickKeyword(table.scenario),
74
+ scenarioOutline: pickKeyword(table.scenarioOutline),
75
+ examples: pickKeyword(table.examples),
66
76
  given: pickKeyword(table.given),
67
77
  when: pickKeyword(table.when),
68
78
  thenText: pickKeyword(table.then),
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * Legacy governance-header strip (drop-review-stamp-and-scope): removes
3
- * `# scope:` / `# reviewed-through:` comment lines anywhere in a .feature —
4
- * both are inert comments since the header contract shrank to
5
- * capability+purpose. Pure: source in, result out; idempotent by construction
3
+ * `# scope:` / `# reviewed-through:` / `# capability:` comment lines anywhere in
4
+ * a .feature — inert since the header contract is `# language:` + `# purpose:`.
5
+ * Pure: source in, result out; idempotent by construction
6
6
  * (a stripped source yields zero removals on the second pass).
7
7
  */
8
8
  export function stripLegacyHeaderLines(source: string): { content: string; removed: number } {
9
9
  const lines = source.split('\n');
10
- const kept = lines.filter((line) => !/^#\s*(scope|reviewed-through):/u.test(line));
10
+ const kept = lines.filter((line) => !/^#\s*(scope|reviewed-through|capability):/u.test(line));
11
11
  return { content: kept.join('\n'), removed: lines.length - kept.length };
12
12
  }
@@ -14,6 +14,7 @@ import type { GherkinDocument } from '@cucumber/messages';
14
14
  import {
15
15
  type CapabilityDoc,
16
16
  type CapabilityHeader,
17
+ type ExamplesBlockIR,
17
18
  type RuleIR,
18
19
  type ScenarioIR,
19
20
  type ScenarioStepKind,
@@ -79,21 +80,15 @@ function stepKeywordToKind(keyword: string): ScenarioStepKind {
79
80
  return stepKeywordToOfficialKind(keyword) ?? 'given';
80
81
  }
81
82
 
82
- const HEADER_RE = /^#\s*(capability|purpose):\s*(.*)$/u;
83
+ const PURPOSE_HEADER_RE = /^#\s*purpose:\s*(.*)$/u;
83
84
 
84
85
  function extractHeader(source: string): CapabilityHeader {
85
- const header: CapabilityHeader = {
86
- capability: null,
87
- purpose: null,
88
- };
86
+ const header: CapabilityHeader = { purpose: null };
89
87
  for (const line of source.split('\n')) {
90
88
  if (line.trim() === '') continue;
91
89
  if (!line.trimStart().startsWith('#')) break;
92
- const m = line.trimStart().match(HEADER_RE);
93
- if (m?.[1]) {
94
- const field = m[1] as 'capability' | 'purpose';
95
- header[field] = m[2]?.trim() ?? null;
96
- }
90
+ const m = line.trimStart().match(PURPOSE_HEADER_RE);
91
+ if (m) header.purpose = m[1]?.trim() ?? null;
97
92
  }
98
93
  return header;
99
94
  }
@@ -110,18 +105,45 @@ function parseTags(tags: readonly { name: string }[]): RawTags {
110
105
  return { names, reqId: req ?? '' };
111
106
  }
112
107
 
108
+ function collectExamples(
109
+ examples: readonly {
110
+ name: string;
111
+ tableHeader?: { cells: readonly { value: string }[] } | null;
112
+ tableBody: readonly { cells: readonly { value: string }[] }[];
113
+ }[],
114
+ ): ExamplesBlockIR[] {
115
+ return examples.map((ex) => ({
116
+ name: ex.name ?? '',
117
+ headers: (ex.tableHeader?.cells ?? []).map((c) => c.value.trim()),
118
+ rows: ex.tableBody.map((row) => row.cells.map((c) => c.value.trim())),
119
+ }));
120
+ }
121
+
113
122
  function collectScenario(sc: {
123
+ keyword?: string;
114
124
  tags: readonly { name: string }[];
115
125
  name: string;
116
126
  steps: readonly { keyword: string; text: string }[];
127
+ examples?: readonly {
128
+ name: string;
129
+ tableHeader?: { cells: readonly { value: string }[] } | null;
130
+ tableBody: readonly { cells: readonly { value: string }[] }[];
131
+ }[];
117
132
  }): ScenarioIR {
118
133
  const { names, reqId: _ignored } = parseTags(sc.tags);
119
134
  const skipTokens = new Set(['skip', 'experimental']);
120
- const runnable = !names.some((n) => skipTokens.has(n));
135
+ let runnable = !names.some((n) => skipTokens.has(n));
121
136
  const steps = sc.steps.map((s) => ({
122
137
  kind: stepKeywordToKind(s.keyword),
123
138
  text: s.text.trim(),
124
139
  }));
140
+ const examplesBlocks = collectExamples(sc.examples ?? []);
141
+ const hasDataRows = examplesBlocks.some((b) => b.rows.length > 0);
142
+ const keyword = sc.keyword ?? '';
143
+ const isOutline = /outline|大纲/iu.test(keyword) || examplesBlocks.length > 0;
144
+ if (runnable && examplesBlocks.length > 0 && !hasDataRows) {
145
+ runnable = false;
146
+ }
125
147
  return {
126
148
  name: sc.name,
127
149
  tags: names.filter(
@@ -136,6 +158,8 @@ function collectScenario(sc: {
136
158
  stepCount: steps.length,
137
159
  steps,
138
160
  statement: steps.map((s) => s.text).join('\n'),
161
+ isOutline,
162
+ examples: examplesBlocks.length > 0 ? examplesBlocks : undefined,
139
163
  };
140
164
  }
141
165
 
@@ -143,10 +167,11 @@ function collectScenario(sc: {
143
167
  export function parseCapability(source: string, fileName = '<inline>'): CapabilityDoc {
144
168
  const errors: SpecStructuralError[] = [];
145
169
  const header = extractHeader(source);
146
- for (const key of ['capability', 'purpose'] as const) {
147
- if (header[key] === null) {
148
- errors.push({ code: `missing-header:${key}`, message: `missing # ${key}: header comment` });
149
- }
170
+ if (header.purpose === null) {
171
+ errors.push({
172
+ code: 'missing-header:purpose',
173
+ message: 'missing # purpose: header comment',
174
+ });
150
175
  }
151
176
 
152
177
  const { doc, language } = parseFeatureSource(source);
@@ -1,3 +1,4 @@
1
+ import { assignSpecIds } from '../spec/assignSpecIds.ts';
1
2
  import { parseCapability } from '../spec/parser.ts';
2
3
  /**
3
4
  * Spec discovery (validation capability): walk llmanspec/specs/** for
@@ -23,8 +24,11 @@ export function discoverSpecs(specsDir: string, io: DiscoveryIo): SpecEntry[] {
23
24
  }
24
25
  return out;
25
26
  };
26
- return walk(specsDir).map((path) => ({
27
+ const normDir = specsDir.replace(/\\/g, '/').replace(/\/$/u, '');
28
+ const entries = walk(normDir).map((path) => ({
27
29
  fileName: path,
28
30
  doc: parseCapability(io.readText(path), path),
29
31
  }));
32
+ assignSpecIds(entries, normDir);
33
+ return entries;
30
34
  }
@@ -0,0 +1,328 @@
1
+ /**
2
+ * XState-powered transition-table validation (validation r104): auto-discovery,
3
+ * zero Tag, Examples-table driven gates E1–E4. Pure — no I/O.
4
+ */
5
+ import { createGraph, addNode, addEdge, genBFS, hasPath } from '@statelyai/graph';
6
+ import { createMachine } from 'xstate';
7
+
8
+ import type { RuleIR, ScenarioIR } from '../spec/ir.ts';
9
+ import type { ValidationItem } from './validate.ts';
10
+
11
+ export interface TransitionEdge {
12
+ from: string;
13
+ event: string;
14
+ to: string;
15
+ guard?: string;
16
+ }
17
+
18
+ const FROM_HEADERS = new Set(['from', '初始状态']);
19
+ const EVENT_HEADERS = new Set(['event', '事件']);
20
+ const TO_HEADERS = new Set(['to', '目标状态']);
21
+ const GUARD_HEADERS = new Set(['guard', '守卫']);
22
+
23
+ export interface ColumnMap {
24
+ from: string;
25
+ event: string;
26
+ to: string;
27
+ guard?: string;
28
+ }
29
+
30
+ function headerMatches(headers: string[], names: Set<string>): boolean {
31
+ return headers.some((h) => names.has(h) || names.has(h.toLowerCase()));
32
+ }
33
+
34
+ function headerIndex(headers: string[], names: Set<string>): number {
35
+ for (let i = 0; i < headers.length; i++) {
36
+ const h = headers[i] ?? '';
37
+ if (names.has(h) || names.has(h.toLowerCase())) return i;
38
+ }
39
+ return -1;
40
+ }
41
+
42
+ export function resolveTransitionColumns(headers: string[]): ColumnMap | null {
43
+ const fromIdx = headerIndex(headers, FROM_HEADERS);
44
+ const eventIdx = headerIndex(headers, EVENT_HEADERS);
45
+ const toIdx = headerIndex(headers, TO_HEADERS);
46
+ if (fromIdx === -1 || eventIdx === -1 || toIdx === -1) return null;
47
+ const guardIdx = headerIndex(headers, GUARD_HEADERS);
48
+ const fromCol = headers[fromIdx] ?? 'from';
49
+ const eventCol = headers[eventIdx] ?? 'event';
50
+ const toCol = headers[toIdx] ?? 'to';
51
+ const guardCol = guardIdx === -1 ? undefined : headers[guardIdx];
52
+ return { from: fromCol, event: eventCol, to: toCol, guard: guardCol };
53
+ }
54
+
55
+ /** Auto-discovery: at least two of {from, event, to} column families present. */
56
+ export function isTransitionOutline(sc: ScenarioIR): boolean {
57
+ if (!sc.examples || sc.examples.length === 0) return false;
58
+ for (const ex of sc.examples) {
59
+ const h = ex.headers;
60
+ const hasFrom = headerMatches(h, FROM_HEADERS);
61
+ const hasEvent = headerMatches(h, EVENT_HEADERS);
62
+ const hasTo = headerMatches(h, TO_HEADERS);
63
+ if ((hasFrom && hasTo) || (hasFrom && hasEvent) || (hasEvent && hasTo)) return true;
64
+ }
65
+ return false;
66
+ }
67
+
68
+ function placeholderVariants(col: string): string[] {
69
+ return [`<${col}>`, `<${col.toLowerCase()}>`];
70
+ }
71
+
72
+ function stepBindsPlaceholder(text: string, col: string): boolean {
73
+ return placeholderVariants(col).some((v) => text.includes(v));
74
+ }
75
+
76
+ function extractTransitions(sc: ScenarioIR): TransitionEdge[] {
77
+ const transitions: TransitionEdge[] = [];
78
+ for (const block of sc.examples ?? []) {
79
+ const cols = resolveTransitionColumns(block.headers);
80
+ if (!cols) continue;
81
+ const fromIdx = block.headers.indexOf(cols.from);
82
+ const eventIdx = block.headers.indexOf(cols.event);
83
+ const toIdx = block.headers.indexOf(cols.to);
84
+ const guardIdx = cols.guard === undefined ? -1 : block.headers.indexOf(cols.guard);
85
+ for (const row of block.rows) {
86
+ transitions.push({
87
+ from: row[fromIdx] ?? '',
88
+ event: row[eventIdx] ?? '',
89
+ to: row[toIdx] ?? '',
90
+ guard: guardIdx === -1 ? undefined : (row[guardIdx] ?? ''),
91
+ });
92
+ }
93
+ }
94
+ return transitions;
95
+ }
96
+
97
+ function distinctStates(transitions: readonly TransitionEdge[]): Set<string> {
98
+ const states = new Set<string>();
99
+ for (const t of transitions) {
100
+ states.add(t.from);
101
+ states.add(t.to);
102
+ }
103
+ return states;
104
+ }
105
+
106
+ function anchor(cap: string, rule: RuleIR): string {
107
+ return `${cap}/transitions/${rule.reqId || rule.title}`;
108
+ }
109
+
110
+ /** E1–E4 for one transition outline; returns ERROR items only. */
111
+ export function validateTransitionScenario(
112
+ cap: string,
113
+ rule: RuleIR,
114
+ sc: ScenarioIR,
115
+ ): ValidationItem[] {
116
+ const items: ValidationItem[] = [];
117
+ const id = anchor(cap, rule);
118
+ const push = (message: string): void => {
119
+ items.push({ level: 'ERROR', id, message });
120
+ };
121
+
122
+ const transitions = extractTransitions(sc);
123
+ const states = distinctStates(transitions);
124
+
125
+ const cols =
126
+ sc.examples?.map((ex) => resolveTransitionColumns(ex.headers)).find((c) => c !== null) ?? null;
127
+
128
+ const e1Table =
129
+ !sc.runnable ||
130
+ !sc.examples ||
131
+ sc.examples.length === 0 ||
132
+ cols === null ||
133
+ transitions.length < 1 ||
134
+ transitions.some((t) => t.from === '' || t.event === '' || t.to === '') ||
135
+ states.size < 2;
136
+
137
+ if (e1Table) {
138
+ push(
139
+ `transition scenario \`${sc.name}\` requires a runnable non-empty Examples table with columns [from, event, to] and at least 2 distinct states`,
140
+ );
141
+ return items;
142
+ }
143
+
144
+ const given = sc.steps.find((s) => s.kind === 'given');
145
+ const when = sc.steps.find((s) => s.kind === 'when');
146
+ const then = sc.steps.find((s) => s.kind === 'then');
147
+ const needsGuard = cols.guard !== undefined;
148
+ const givenOk =
149
+ given !== undefined &&
150
+ stepBindsPlaceholder(given.text, cols.from) &&
151
+ (!needsGuard ||
152
+ stepBindsPlaceholder(given.text, cols.guard!) ||
153
+ (when !== undefined && stepBindsPlaceholder(when.text, cols.guard!)));
154
+ const whenOk = when !== undefined && stepBindsPlaceholder(when.text, cols.event);
155
+ const thenOk = then !== undefined && stepBindsPlaceholder(then.text, cols.to);
156
+
157
+ if (!givenOk || !whenOk || !thenOk) {
158
+ push(
159
+ `transition scenario \`${sc.name}\` steps must bind placeholders <from> in Given, <event> in When, and <to> in Then`,
160
+ );
161
+ return items;
162
+ }
163
+
164
+ const seen = new Set<string>();
165
+ for (const t of transitions) {
166
+ const key = `${t.from}\0${t.event}\0${t.guard ?? ''}`;
167
+ if (seen.has(key)) {
168
+ const guardPart = t.guard ? ` [${t.guard}]` : '';
169
+ push(
170
+ `non-deterministic or duplicate transition in \`${sc.name}\`: state \`${t.from}\` on event \`${t.event}\`${guardPart} has conflicting targets`,
171
+ );
172
+ return items;
173
+ }
174
+ seen.add(key);
175
+ }
176
+
177
+ const initial = transitions[0]?.from ?? '';
178
+ try {
179
+ createMachine({
180
+ id: 'transitions',
181
+ initial,
182
+ states: Object.fromEntries([...states].map((s) => [s, {}])) as Record<string, object>,
183
+ });
184
+ } catch {
185
+ // createMachine structural sanity — transitions drive graph below
186
+ }
187
+
188
+ const graph = createGraph();
189
+ for (const s of states) addNode(graph, { id: s });
190
+ let edgeSeq = 0;
191
+ for (const t of transitions) {
192
+ addEdge(graph, {
193
+ id: `e${String(edgeSeq++)}`,
194
+ sourceId: t.from,
195
+ targetId: t.to,
196
+ });
197
+ }
198
+
199
+ const reachable = new Set(
200
+ [...genBFS(graph, initial)]
201
+ .map((n) => (typeof n === 'object' && n !== null && 'id' in n ? String(n.id) : String(n)))
202
+ .filter((nid) => nid !== ''),
203
+ );
204
+ const unreachable = [...states].filter((s) => !reachable.has(s));
205
+ if (unreachable.length > 0) {
206
+ push(
207
+ `unreachable state(s) in transition table \`${sc.name}\` from initial state \`${initial}\`: ${unreachable.join(', ')}`,
208
+ );
209
+ return items;
210
+ }
211
+
212
+ const outTargets = new Map<string, Set<string>>();
213
+ for (const t of transitions) {
214
+ const set = outTargets.get(t.from) ?? new Set<string>();
215
+ set.add(t.to);
216
+ outTargets.set(t.from, set);
217
+ }
218
+
219
+ const terminalStates = [...states].filter((s) => (outTargets.get(s)?.size ?? 0) === 0);
220
+
221
+ if (terminalStates.length > 0) {
222
+ const deadlocks: string[] = [];
223
+ for (const s of states) {
224
+ if (terminalStates.includes(s)) continue;
225
+ const canReachTerminal = terminalStates.some((term) => hasPath(graph, s, term));
226
+ if (!canReachTerminal) deadlocks.push(s);
227
+ }
228
+ if (deadlocks.length > 0) {
229
+ push(
230
+ `deadlock state(s) in transition table \`${sc.name}\` (cannot reach any terminal state): ${deadlocks.join(', ')}`,
231
+ );
232
+ return items;
233
+ }
234
+ } else {
235
+ for (const s of states) {
236
+ const targets = outTargets.get(s) ?? new Set<string>();
237
+ const onlySelf = targets.size === 1 && targets.has(s);
238
+ const hasIncomingFromOther = transitions.some((t) => t.to === s && t.from !== s);
239
+ const hasOutgoingToOther = transitions.some((t) => t.from === s && t.to !== s);
240
+ if (onlySelf && !hasIncomingFromOther && !hasOutgoingToOther) {
241
+ push(
242
+ `deadlock state(s) in transition table \`${sc.name}\` (cannot reach any terminal state): ${s}`,
243
+ );
244
+ return items;
245
+ }
246
+ }
247
+ for (const s of states) {
248
+ if (!hasPath(graph, s, initial) && s !== initial) {
249
+ const canReturn = hasPath(graph, s, initial);
250
+ if (!canReturn) {
251
+ push(
252
+ `deadlock state(s) in transition table \`${sc.name}\` (cannot reach any terminal state): ${s}`,
253
+ );
254
+ return items;
255
+ }
256
+ }
257
+ }
258
+ }
259
+
260
+ return items;
261
+ }
262
+
263
+ export function validateTransitionsForRule(
264
+ cap: string,
265
+ rule: RuleIR,
266
+ checkTransitions: boolean,
267
+ ): ValidationItem[] {
268
+ if (!checkTransitions) return [];
269
+ const items: ValidationItem[] = [];
270
+ for (const sc of rule.scenarios) {
271
+ if (!isTransitionOutline(sc)) continue;
272
+ items.push(...validateTransitionScenario(cap, rule, sc));
273
+ }
274
+ return items;
275
+ }
276
+
277
+ /** Authoring self-check: transitions only (synthetic scenario). */
278
+ export function validateTransitionTableSelfCheck(
279
+ transitions: readonly TransitionEdge[],
280
+ scenarioName = 'authoring-check',
281
+ ): void {
282
+ const sc: ScenarioIR = {
283
+ name: scenarioName,
284
+ tags: [],
285
+ runnable: true,
286
+ stepCount: 3,
287
+ steps: [
288
+ { kind: 'given', text: 'state <from>' },
289
+ { kind: 'when', text: 'event <event>' },
290
+ { kind: 'then', text: 'state <to>' },
291
+ ],
292
+ statement: '',
293
+ isOutline: true,
294
+ examples: [
295
+ {
296
+ name: '',
297
+ headers: ['from', 'event', 'to'],
298
+ rows: transitions.map((t) => [t.from, t.event, t.to]),
299
+ },
300
+ ],
301
+ };
302
+ const rule = { reqId: 'r0', title: '', description: '', scenarios: [], tags: [] } as RuleIR;
303
+ const issues = validateTransitionScenario('authoring', rule, sc);
304
+ if (issues.length > 0) {
305
+ throw new Error(issues[0]?.message ?? 'invalid transition table');
306
+ }
307
+ }
308
+
309
+ export function parseTransitionExpr(expr: string): TransitionEdge {
310
+ const trimmed = expr.trim();
311
+ const m = trimmed.match(/^([^:]+):([\w-]+)(?:\[([^\]]+)\])?->(.+)$/u);
312
+ if (!m) {
313
+ throw new Error(`invalid transition expression: ${expr}`);
314
+ }
315
+ const from = m[1];
316
+ const event = m[2];
317
+ const guard = m[3];
318
+ const to = m[4];
319
+ if (from === undefined || event === undefined || to === undefined) {
320
+ throw new Error(`invalid transition expression: ${expr}`);
321
+ }
322
+ return {
323
+ from: from.trim(),
324
+ event: event.trim(),
325
+ to: to.trim(),
326
+ guard: guard?.trim() === '' ? undefined : guard?.trim(),
327
+ };
328
+ }
@@ -4,9 +4,11 @@
4
4
  * `spec/validation.rs` observable issue order). Pure — filesystem access is
5
5
  * injected via SpecIo.
6
6
  */
7
+ import { assignSpecIds } from '../spec/assignSpecIds.ts';
7
8
  import type { CapabilityDoc } from '../spec/ir.ts';
8
9
  import { ruleHasRunnableScenario, specIdOf } from '../spec/ir.ts';
9
10
  import { buildReqRegistry } from '../spec/reqRegistry.ts';
11
+ import { validateTransitionsForRule } from './transitions.ts';
10
12
 
11
13
  export type ValidationLevel = 'ERROR' | 'WARNING' | 'INFO';
12
14
 
@@ -20,6 +22,8 @@ export interface ValidationItem {
20
22
  export interface SpecEntry {
21
23
  fileName: string;
22
24
  doc: CapabilityDoc;
25
+ /** Set by discoverSpecs / assignSpecIds (r101). */
26
+ specId?: string;
23
27
  }
24
28
 
25
29
  export interface SpecIo {
@@ -47,7 +51,11 @@ export function validateCapability(
47
51
  entry: SpecEntry,
48
52
  duplicatesFor: (reqId: string) => boolean,
49
53
  _io: SpecIo,
50
- _opts: { strict?: boolean } = {},
54
+ opts: {
55
+ strict?: boolean;
56
+ duplicateSpecId?: boolean;
57
+ checkTransitions?: boolean;
58
+ } = {},
51
59
  ): SpecVerdict {
52
60
  const { doc } = entry;
53
61
  const cap = specIdOf(entry);
@@ -57,30 +65,26 @@ export function validateCapability(
57
65
  items.push({ level, id, message });
58
66
  };
59
67
 
60
- // Header gates (r12 / predecessor spec_meta). predecessor treats a missing `# capability:`
61
- // header as a parse-level failure: only `file` + registry-scan issues are
62
- // emitted and all single-track gates are skipped.
63
- if (doc.header.capability === null) {
64
- const msg = `spec \`${cap}\`: missing \`# capability:\` header comment`;
65
- push('ERROR', 'file', msg);
66
- push('ERROR', 'llmanspec/specs', `Failed to scan req_id index: ${msg}`);
67
- return { fileName: entry.fileName, capability: cap, ok: false, items };
68
+ if (opts.duplicateSpecId) {
69
+ push(
70
+ 'ERROR',
71
+ `${cap}/spec-id`,
72
+ `duplicate assigned spec id \`${cap}\` — adjust feature file paths`,
73
+ );
68
74
  }
75
+
69
76
  if (doc.header.purpose === null || doc.header.purpose.trim() === '') {
70
77
  push('ERROR', `${cap}/purpose`, '`# purpose:` header comment must not be empty');
71
78
  }
72
- // Spec name must match the capability id (flat stem).
73
- if (doc.header.capability !== null && doc.header.capability.trim() !== cap) {
74
- push(
75
- 'WARNING',
76
- `${cap}/meta.name`,
77
- `Spec \`# capability:\` header must match spec id (flat file stem or directory name): \`${doc.header.capability.trim()}\` != \`${cap}\``,
78
- );
79
- }
80
79
 
81
- // Feature title must be non-empty.
82
80
  if ((doc.featureName ?? '').trim() === '') {
83
81
  push('ERROR', `${cap}/feature`, 'Feature line must carry a title');
82
+ } else if (doc.featureName.trim() !== cap) {
83
+ push(
84
+ 'ERROR',
85
+ `${cap}/feature`,
86
+ `Feature title must match assigned spec id: \`${doc.featureName.trim()}\` != \`${cap}\``,
87
+ );
84
88
  }
85
89
 
86
90
  // Parser-level structural errors. Header gates are owned here (mapped below);
@@ -130,6 +134,14 @@ export function validateCapability(
130
134
  );
131
135
  }
132
136
 
137
+ if (opts.checkTransitions === true) {
138
+ for (const rule of rules) {
139
+ for (const item of validateTransitionsForRule(cap, rule, true)) {
140
+ push(item.level, item.id, item.message);
141
+ }
142
+ }
143
+ }
144
+
133
145
  return {
134
146
  fileName: entry.fileName,
135
147
  capability: cap,
@@ -158,10 +170,23 @@ export function formatTotals(passed: number, failed: number, total: number): str
158
170
  return `Totals: ${passed} passed, ${failed} failed (${total} items)`;
159
171
  }
160
172
 
161
- export function validateAllSpecs(entries: readonly SpecEntry[], io: SpecIo): ValidationReport {
162
- const duplicatesFor = buildDuplicatesFor(entries);
173
+ export function validateAllSpecs(
174
+ entries: readonly SpecEntry[],
175
+ io: SpecIo,
176
+ opts: { specsDir?: string; checkTransitions?: boolean } = {},
177
+ ): ValidationReport {
178
+ const specsDir = opts.specsDir ?? 'llmanspec/specs';
179
+ const list: SpecEntry[] = entries.map((e) => ({ ...e }));
180
+ const duplicateSpecIds = assignSpecIds(list, specsDir);
181
+ const duplicatesFor = buildDuplicatesFor(list);
182
+
183
+ const verdicts = list.map((e) =>
184
+ validateCapability(e, duplicatesFor, io, {
185
+ duplicateSpecId: duplicateSpecIds.has(specIdOf(e)),
186
+ checkTransitions: opts.checkTransitions,
187
+ }),
188
+ );
163
189
 
164
- const verdicts = entries.map((e) => validateCapability(e, duplicatesFor, io));
165
190
  const failed = verdicts.some((v) => !v.ok);
166
191
  const passed = verdicts.filter((v) => v.ok).length;
167
192
 
@@ -28,6 +28,7 @@ flowchart LR
28
28
 
29
29
  - **Single-source-of-truth driven**: `proposal.md` / `design.md` / `tasks.md` and `llmanspec/specs/**` on the branch; every behavioral-contract requirement in specs must be fulfilled.
30
30
  - **Scope-locked**: only implement the current change's scope; never fix "unrelated issues" on the side; keep changes minimal.
31
+ - **Governing scope**: the SDD flow (change branch, proposal, spec-edit gates) governs the behavior-contract surface only — `llmanspec/**` and its artifact alignment (e.g. `.agents/skills` render freshness). Everything else in the repo (build scripts, CI, general docs, test implementations) follows the project's regular engineering flow with direct edits and commits; no change wrapping required. Return to the corresponding skill flow only when a change reaches behavior-contract semantics.
31
32
  - **No guessing**: unclear requirements or specs contradicting reality → STOP and report; don't assume.
32
33
  - **No legacy compatibility layers**: if the change requires new behavior, upgrade all call sites directly, unless tasks/proposal explicitly require compatibility.
33
34
  - **Close-out**: this loop ends by suggesting `llman-sdd-verify`; finalize/archive belongs to `llman-sdd-archive` (do not finalize inside the self-healing loop).
@@ -44,7 +45,7 @@ flowchart LR
44
45
  - Read and obey `llmanspec/config.yaml`, `AGENTS.md` (if present).
45
46
  - `git status --porcelain`: if the tree is dirty with changes not belonging to this change → `git stash push -u -m "llman-sdd-apply autopilot backup"` first.
46
47
  - `llman-sdd validate --all --strict`: if it fails for reasons unrelated to this change → stop and report (inconsistent artifacts prevent source-of-truth-driven implementation).
47
- - **Check spec valid_scope integrity**: `llman-sdd list --specs --json` lists all specs; for each, verify every `valid_scope` path exists on disk. On missing paths → stop and suggest updating the spec (remove the deleted path).
48
+ - **Specs list readable**: `llman-sdd list --specs` returns the list without errors; on anomaly → stop and report.
48
49
 
49
50
  ### 1) Select the change id and check prerequisites
50
51
  - If provided, use it; otherwise infer from context, and if ambiguous run `llman-sdd list --json` and let the user pick. Always announce "Using change: <id>" and how to override.
@@ -70,14 +71,13 @@ For each unchecked task:
70
71
  4. Task unclear, blocker hit, or specs/design contradict reality → STOP and report; don't assume.
71
72
 
72
73
  ### 5) Verification and self-healing loop (after each task or batch)
73
- Run the project gates as appropriate:
74
- - Test suite: `just test` or `cargo test --all`; format/lint: `just check` or `just lint` + `just fmt`
74
+ - Tests and static gates: run the verification means this repo has declared — as recorded in repo docs and configuration; for repos with `specs.check_command` configured, use the command reported by `llman-sdd config`. If the repo declares none, ask the user; never assume a specific task runner exists.
75
75
  - Edit `llmanspec/specs/<capability>.feature` on the branch as needed (flat or directory main file; canonical native layout: `@req:<id>` on the `规则:` block header, nested `场景:` as executable examples); run `llman-sdd validate --specs` after spec edits; commit on the branch freely.
76
76
  - SDD validation: `llman-sdd validate <id> --strict`
77
77
 
78
78
  **Verification ladder (opt-in discipline, escalate by cost)**:
79
- - L1 minimal unit: `bun test tests/unit/<relevant>` (<1s, direct import), covers only the current change point.
80
- - L2 targeted behavior: `bun test tests/bdd -t "<scenario/rule title pattern>"` — exercises only the relevant real-CLI path.
79
+ - L1 minimal unit: the fastest declared verification means that loads the changed module directly; covers only the current change point.
80
+ - L2 targeted behavior: run the subset of declared verification means matching the current scenario (prefer targeted `specs.check_command` invocation when configured); reproduce the target behavior only.
81
81
  - L3 explicit full harness: `llman-sdd validate --check` (with `specs.check_command` configured; plain `validate` no longer runs the harness).
82
82
  - L4 close-out backstop: `change finalize` runs the real harness pre-merge — at least one full run per close-out.
83
83
  - Self-heal loops default to L1/L2 for fast reproduction; use L3 only when full-acceptance evidence is needed; avoid paying full-suite cost needlessly.
@@ -47,7 +47,7 @@ If the user just wants to **capture an idea** ("draft a proposal", "note down X"
47
47
  ### 0) Preflight
48
48
  - Read `llmanspec/config.yaml` for project context, rules, locale.
49
49
  - `llman-sdd validate --all --strict` to ensure current artifacts are clean; on pre-existing errors, STOP and report (stacking a new change on dirty artifacts causes cascading errors).
50
- - **Check spec valid_scope integrity**: `llman-sdd list --specs --json` lists all specs; for each, verify every `valid_scope` path exists on disk. On missing paths, STOP and suggest updating the spec (remove the deleted path).
50
+ - **Specs list readable**: `llman-sdd list --specs` returns the list without errors; on anomaly, STOP and report.
51
51
 
52
52
  ### 1) Assess change scale
53
53
  1. Classify:
@@ -79,9 +79,9 @@ If the user just wants to **capture an idea** ("draft a proposal", "note down X"
79
79
 
80
80
  ### 4) Validate
81
81
  ```bash
82
- llman-sdd validate <change-id> --strict
82
+ llman-sdd validate <change-id>
83
83
  ```
84
- This MUST pass before proceeding; failing items are listed one by one in the validate output's `items[].issues[]` — fix each and re-run.
84
+ The structure gate MUST pass before proceeding; failing items are listed one by one in the validate output's `items[].issues[]` — fix each and re-run. `--strict` promotes warnings (including unchecked tasks) to failures — reserve it for the post-implementation completion check, once every task is checked.
85
85
 
86
86
  ### 4a) Optional BDD runner (`specs:` block)
87
87
  - Read `llmanspec/config.yaml`. Is there a `specs:` block?
@@ -1,10 +1,11 @@
1
1
  Validation fixes (single-track feature-as-spec):
2
2
 
3
- 1) Missing header comments (`missing # capability: header comment`): every capability `.feature` (`llmanspec/specs/<capability>.feature` or the same-named main file in a directory) MUST start with:
3
+ 1) Missing `# purpose:` header: every capability `.feature` MUST carry a non-empty `# purpose:`; the Feature title MUST equal the assigned spec id (`llman-sdd list --specs` for ids).
4
4
  ```
5
5
  # language: zh-CN
6
- # capability: <capability>
7
6
  # purpose: One-line overview.
7
+
8
+ Feature: <spec-id>
8
9
  ```
9
10
 
10
11
  2) Native layout (`rule must carry an @req:<req_id> tag on the rule header`):
@@ -13,7 +14,7 @@ Validation fixes (single-track feature-as-spec):
13
14
  - Legacy tags `@executable`/`@rule`/`@human`/`@manual` are gone and parse inert; when old files hit structural problems run `llman-sdd spec migrate-native`.
14
15
  - Top-level `场景:` outside any `规则:` are plain feature-level examples: no rule handle, no warning, not part of rule accounting (native Gherkin).
15
16
 
16
- Branch guardrail:
17
- - First `change start` / `attach` to bind the branch, then edit `.feature` on the bound non-default branch and commit (land specs).
18
- - Locked rules (report-only): editing/removing an existing `规则:` block yields a WARNING and never blocks validate / finalize / `change diff`; the report names the rule by `@req:<id>`. Control points: git branch diff plus `llman-sdd review` / `change diff`. Legacy lock-ack metadata (frontmatter `rules_touched` / `agent_acked`, the `@agent` tag, the `--yes` ack semantics) is fully removed — no aliases, no compat layer.
19
- - Enter apply when `stage=full` and the specs-landed gate passes (specsLanded ∨ `needs_specs_change: false`); verify/finalize require `readyToImplement=true` (completion signal). Close-out prefers `change finalize`.
17
+ Branch guardrails:
18
+ - Bind with `change start` / `attach` first, then edit `.feature` on the bound branch and commit (land specs).
19
+ - Locked rules (report-only): editing/deleting existing `规则:` blocks emits WARNING only — does not block validate / finalize / `change diff`; reports name the changed rule via `@req:<id>`. Control points: git branch diff + `llman-sdd review` / `change diff`. Legacy lock metadata (`rules_touched` / `agent_acked` / `@agent` tag / `--yes` confirm semantics) is fully removed — no aliases, no compatibility layer.
20
+ - `stage=full` with specs-landed gate green (`specsLanded` ∨ `needs_specs_change: false`) is enough to enter apply; verify/finalize requires `readyToImplement=true` (completion signal). Prefer `change finalize` for close-out.
@@ -6,7 +6,6 @@ The format is the **native Gherkin hierarchy**: `功能:` → `规则:` (the req
6
6
 
7
7
  ```gherkin
8
8
  # language: zh-CN
9
- # capability: sample
10
9
  # purpose: One-line overview.
11
10
 
12
11
  功能: sample
@@ -29,7 +28,7 @@ The format is the **native Gherkin hierarchy**: `功能:` → `规则:` (the req
29
28
  down or converting them.
30
29
  ```
31
30
 
32
- - Header comments (`# capability:` / `# purpose:`) are REQUIRED.
31
+ - Header comments: `# language:` (dialect) and `# purpose:` (one-line overview) are REQUIRED. The capability / spec id is assigned per instance from file paths after discover (flat and directory layouts may mix); the `功能:` title MUST equal that id.
33
32
  - **Executable scenarios preferred**: express behavior as nested `场景:` (`Given/When/Then`) bound to BDD step code and executed by the runner — the default. Only use a `规则:` block without executable scenarios for requirements that cannot be expressed programmatically (abstract goals, architecture decisions, governance/human judgment) or are not yet converted; record the rationale in proposal/design.
34
33
  - `@req:<id>` lives on the `规则:` block header: the global unique requirement handle (shared by resolve-req/next-req-id/citation). Missing or duplicate ids are validate ERRORs.
35
34
  - Rule description is free text: no MUST/SHALL enforcement; wrap long text across lines for reviewability, with no `- ` list marker (it would enter the description verbatim).
@@ -28,6 +28,7 @@ flowchart LR
28
28
 
29
29
  - **唯一事实来源驱动**:`proposal.md` / `design.md` / `tasks.md` 与分支上的 `llmanspec/specs/**`;specs 的行为合约条款逐条落实。
30
30
  - **范围锁定**:只做当前 change 范围,不得顺手修无关问题;改动保持最小。
31
+ - **管辖范围**:SDD 流程(change 分支、proposal、specs 编辑门)只约束行为合约面——`llmanspec/**` 及其产物对齐(如 `.agents/skills` 渲染新鲜度)。仓库其余文件(构建脚本、CI、一般文档、测试实现)按项目常规工程流程直改直提交,不经 change 包装;改动触及行为合约语义时,回到对应 skill 流程。
31
32
  - **不得猜测**:需求不明或 specs 与现实矛盾 → STOP 报告,不自行假定。
32
33
  - **不留旧兼容层**:change 要求改行为就全量升级到新写法,除非 tasks/proposal 明确要兼容。
33
34
  - **收尾**:该轮以宜接 `llman-sdd-verify` 收束;finalize/archive 归 `llman-sdd-archive`(不得在自修复循环里 finalize)。
@@ -44,7 +45,7 @@ flowchart LR
44
45
  - 读取并遵守 `llmanspec/config.yaml`、`AGENTS.md`(若存在)。
45
46
  - `git status --porcelain`:工作区不干净且改动不属于本 change → 先 `git stash push -u -m "llman-sdd-apply autopilot backup"`。
46
47
  - `llman-sdd validate --all --strict`:失败且与本 change 无关 → 停下报告(工件不一致则无法以事实来源驱动实现)。
47
- - **检查 spec valid_scope 完整性**:`llman-sdd list --specs --json` 列出所有 spec,逐个核对 `valid_scope` 路径存在于磁盘;有缺失 → 停下并宜更新 spec(移除已删路径)。
48
+ - **specs 清单可读**:`llman-sdd list --specs` 返回清单且无错误;异常 → 停下报告。
48
49
 
49
50
  ### 1) 选定 change id 并查前置
50
51
  - 已提供则直接用;否则从上下文推断,不明确就跑 `llman-sdd list --json` 让用户选。始终说明“使用变更:<id>”并告知如何覆盖。
@@ -70,14 +71,13 @@ flowchart LR
70
71
  4. task 不明、遇 blocker、或 specs/design 与现实不一致 → STOP 报告,不自行假定。
71
72
 
72
73
  ### 5) 验证与自修复循环(每个 task 或每批 task 后跑一次)
73
- 按项目实际跑门禁:
74
- - 测试集:`just test` 或 `cargo test --all`;格式/lint:`just check` 或 `just lint` + `just fmt`
74
+ - 测试与静态门禁:执行本仓已声明的验证手段——以仓库文档与配置记载为准;已配置 `specs.check_command` 的项目,以 `llman-sdd config` 读得的命令为准。仓库未声明时,询问用户;不假定任何具体任务工具存在。
75
75
  - 分支上按需编辑 `llmanspec/specs/<capability>.feature`(扁平或目录主文件;统一原生分层:`@req:<id>` 挂 `规则:` 块头、嵌套 `场景:` 为可执行示例),spec 改动后跑 `llman-sdd validate --specs`;分支上可自由提交。
76
76
  - SDD 校验:`llman-sdd validate <id> --strict`
77
77
 
78
78
  **验证阶梯(opt-in 纪律,按成本逐级扩大)**:
79
- - L1 最小单元:`bun test tests/unit/<改动对应目录>`(<1s,直接导入),仅覆盖当前改动点。
80
- - L2 定向行为:`bun test tests/bdd -t "<场景/规则标题模式>"`——只跑匹配 -t 模式场景的真实 CLI 调用。
79
+ - L1 最小单元:已声明验证手段中能直接加载被改模块的最快一层,仅覆盖当前改动点。
80
+ - L2 定向行为:定向执行已声明验证手段中匹配当前场景的子集(已配置 `specs.check_command` 时优先),只复现目标行为。
81
81
  - L3 显式全量:`llman-sdd validate --check`(配置 `specs.check_command` 时执行全量 harness;缺省 validate 不再执行 harness)。
82
82
  - L4 收口兜底:`change finalize` 预合并强制真实 harness——每次收口至少 1 次全量。
83
83
  - 自修复循环默认用 L1/L2 快速复现;只有需要全量验收时才 L3;避免无谓白付全量成本。
@@ -47,7 +47,7 @@ flowchart LR
47
47
  ### 0) 预检
48
48
  - 读 `llmanspec/config.yaml` 获取项目上下文、规则、locale。
49
49
  - `llman-sdd validate --all --strict` 确认现有工件干净;有错误则 STOP 并报告(脏工件上叠新 change 会级联出错)。
50
- - **检查 spec valid_scope 完整性**:`llman-sdd list --specs --json` 列出全部 specs,逐个核对 `valid_scope` 路径在磁盘上存在;有缺失则 STOP 并宜更新该 spec(移除已删路径)。
50
+ - **specs 清单可读**:`llman-sdd list --specs` 返回清单且无错误;异常则 STOP 报告。
51
51
 
52
52
  ### 1) 判断变更规模
53
53
  1. 分类:
@@ -79,9 +79,9 @@ flowchart LR
79
79
 
80
80
  ### 4) 校验
81
81
  ```bash
82
- llman-sdd validate <change-id> --strict
82
+ llman-sdd validate <change-id>
83
83
  ```
84
- 必须 通过才能继续;失败项在 validate 输出的 `items[].issues[]` 逐条指明,按条修复后重跑。
84
+ 结构门必须 通过才能继续;失败项在 validate 输出的 `items[].issues[]` 逐条指明,按条修复后重跑。`--strict` 会把警告(含未勾 task)一并升级为失败——留到实施收口、task 全勾后作完成判定。
85
85
 
86
86
  ### 4a) 可选 BDD runner(`specs:` 段)
87
87
  - 读 `llmanspec/config.yaml` 是否含 `specs:` 段:
@@ -1,10 +1,11 @@
1
1
  校验修复(单轨 feature-as-spec):
2
2
 
3
- 1)缺头注释(`missing # capability: header comment`):每个 capability `.feature`(`llmanspec/specs/<capability>.feature` 或目录内同名主文件)必须以下列注释开头:
3
+ 1)缺 `# purpose:` 头注释:每个 capability `.feature` 必须含非空 `# purpose:`;`功能:` 标题必须等于 discover 分配后的 spec id(`llman-sdd list --specs` 查看 id)。
4
4
  ```
5
5
  # language: zh-CN
6
- # capability: <capability>
7
6
  # purpose: 一句话概述
7
+
8
+ 功能: <spec-id>
8
9
  ```
9
10
 
10
11
  2)原生分层格式(`rule must carry an @req:<req_id> tag on the rule header`):
@@ -6,7 +6,6 @@
6
6
 
7
7
  ```gherkin
8
8
  # language: zh-CN
9
- # capability: sample
10
9
  # purpose: One-line overview.
11
10
 
12
11
  功能: sample
@@ -27,7 +26,7 @@
27
26
  specs-compact 持续压降。
28
27
  ```
29
28
 
30
- - 头注释(`# capability:` / `# purpose:`)必填。
29
+ - 头注释:`# language:`(方言)与 `# purpose:`(一句话概述)必填。capability / spec id 由 discover 在实例内从路径分配(扁平或目录式可混搭),`功能:` 标题必须等于该 id。
31
30
  - **可执行场景优先**:行为一律以嵌套 `场景:`(假如/当/那么)表达并绑定 BDD 步骤代码、由 runner 执行——默认首选。仅当需求无法程序化表达(抽象目标、架构决策、治理/人工约束)或暂不转写时,才以 `规则:` 块承载,并在 proposal/design 记录理由。
32
31
  - `@req:<id>` 挂在 `规则:` 头标签,是全局唯一的需求句柄(resolve-req/next-req-id/条款引用共用);重复或缺失由 validate 判 ERROR。
33
32
  - 规则描述为自由文本:不强制 MUST/SHALL 词;较长时拆多行便于审查,不使用 `- ` 列表前缀(会原样进入描述)。