@llman-sdd/core 0.8.1 → 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.1",
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
 
@@ -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).
@@ -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 词;较长时拆多行便于审查,不使用 `- ` 列表前缀(会原样进入描述)。