@llman-sdd/core 0.10.1 → 0.12.0

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.
Files changed (119) hide show
  1. package/package.json +11 -8
  2. package/src/archive/freeze.ts +41 -15
  3. package/src/archive/frozenCard.ts +57 -9
  4. package/src/archive/ignoreChain.ts +2 -6
  5. package/src/archive/sevenzip.ts +0 -1
  6. package/src/change/closeOutHarness.ts +17 -0
  7. package/src/change/collect.ts +0 -5
  8. package/src/change/frontmatter.ts +15 -7
  9. package/src/change/id.ts +0 -2
  10. package/src/change/lifecycle.ts +53 -94
  11. package/src/config/changeId.ts +0 -2
  12. package/src/config/load.ts +0 -4
  13. package/src/config/schema.ts +24 -13
  14. package/src/config/surface.ts +2 -12
  15. package/src/context/sddState.ts +23 -18
  16. package/src/git/spawnGit.ts +0 -3
  17. package/src/hints/jitHints.ts +82 -0
  18. package/src/index.ts +462 -39
  19. package/src/init/defaultConfig.ts +4 -13
  20. package/src/init/init.ts +108 -36
  21. package/src/init/skillCheck.ts +60 -0
  22. package/src/init/uncommentConfig.ts +909 -0
  23. package/src/locale.ts +0 -2
  24. package/src/project/migrateNotes.ts +0 -9
  25. package/src/project/migrations.ts +151 -9
  26. package/src/report/graph/analysis.ts +0 -4
  27. package/src/report/graph/nodes.ts +0 -6
  28. package/src/report/show.ts +7 -23
  29. package/src/report/specHelpers.ts +10 -14
  30. package/src/review/review.ts +0 -12
  31. package/src/spec/assignSpecIds.ts +0 -3
  32. package/src/spec/authoring.ts +16 -24
  33. package/src/spec/ir.ts +14 -5
  34. package/src/spec/keywords.ts +0 -2
  35. package/src/spec/machineKey.ts +49 -0
  36. package/src/spec/migrateNative.ts +4 -18
  37. package/src/spec/parser.ts +10 -19
  38. package/src/spec/reqRef.ts +135 -0
  39. package/src/studio/changeScope.ts +50 -0
  40. package/src/studio/changeScopeDiff.ts +195 -0
  41. package/src/studio/contracts.ts +493 -0
  42. package/src/studio/decisionTree.ts +206 -0
  43. package/src/studio/deeplink.ts +116 -0
  44. package/src/studio/demos.ts +167 -0
  45. package/src/studio/diff.ts +494 -0
  46. package/src/studio/drift.ts +738 -0
  47. package/src/studio/extract.ts +360 -0
  48. package/src/studio/featureSync.ts +592 -0
  49. package/src/studio/forest.ts +570 -0
  50. package/src/studio/index.ts +32 -0
  51. package/src/studio/model.ts +254 -0
  52. package/src/studio/revisions.ts +476 -0
  53. package/src/studio/search.ts +337 -0
  54. package/src/studio/store.ts +811 -0
  55. package/src/studio/sync.ts +912 -0
  56. package/src/studio/textfold.ts +72 -0
  57. package/src/studio/time.ts +107 -0
  58. package/src/studio/validate.ts +363 -0
  59. package/src/templates/embedded.ts +4 -6
  60. package/src/templates/engine.ts +1 -1
  61. package/src/templates/skills.ts +76 -51
  62. package/src/theorems/guard.ts +52 -0
  63. package/src/theorems/index.ts +56 -0
  64. package/src/theorems/migrate.ts +133 -0
  65. package/src/theorems/schema.ts +67 -0
  66. package/src/theorems/scope.ts +68 -0
  67. package/src/theorems/serialize.ts +60 -0
  68. package/src/theorems/transactionMachine.ts +247 -0
  69. package/src/theorems/validate.ts +141 -0
  70. package/src/util/nextNumber.ts +0 -2
  71. package/src/validation/changeCheck.ts +0 -24
  72. package/src/validation/flowAndNesting.ts +434 -0
  73. package/src/validation/harness.ts +108 -65
  74. package/src/validation/validate.ts +26 -12
  75. package/src/validation/xstateTransitions.ts +483 -184
  76. package/templates/zh-Hans/llmanspec-agents-stub.md +17 -2
  77. package/templates/zh-Hans/skills/llman-sdd-autopilot/SKILL.md +34 -0
  78. package/templates/zh-Hans/skills/llman-sdd-change/SKILL.md +44 -0
  79. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/archive.md +15 -0
  80. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/draft.md +9 -0
  81. package/templates/zh-Hans/skills/llman-sdd-review/SKILL.md +71 -0
  82. package/templates/zh-Hans/skills/llman-sdd-specs/SKILL.md +70 -0
  83. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/compact.md +12 -0
  84. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/doctor.md +26 -0
  85. package/templates/zh-Hans/skills/llman-sdd-specs/references/graph-dsl.md +33 -0
  86. package/templates/zh-Hans/skills/llman-sdd-studio/SKILL.md +33 -0
  87. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/collab.md +20 -0
  88. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/drift.md +52 -0
  89. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/onboard.md +33 -0
  90. package/templates/zh-Hans/units/skills/cli-footer.md +2 -2
  91. package/src/context/indexStore.ts +0 -171
  92. package/src/context/retrieve.ts +0 -332
  93. package/src/context/tree.ts +0 -112
  94. package/templates/zh-Hans/agents-root-stub.md +0 -9
  95. package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +0 -69
  96. package/templates/zh-Hans/skills/llman-sdd-apply.md +0 -117
  97. package/templates/zh-Hans/skills/llman-sdd-arch-review.md +0 -58
  98. package/templates/zh-Hans/skills/llman-sdd-archive.md +0 -79
  99. package/templates/zh-Hans/skills/llman-sdd-continue.md +0 -34
  100. package/templates/zh-Hans/skills/llman-sdd-draft.md +0 -53
  101. package/templates/zh-Hans/skills/llman-sdd-explore.md +0 -64
  102. package/templates/zh-Hans/skills/llman-sdd-ff.md +0 -33
  103. package/templates/zh-Hans/skills/llman-sdd-graph.md +0 -56
  104. package/templates/zh-Hans/skills/llman-sdd-propose.md +0 -107
  105. package/templates/zh-Hans/skills/llman-sdd-quick.md +0 -41
  106. package/templates/zh-Hans/skills/llman-sdd-research.md +0 -35
  107. package/templates/zh-Hans/skills/llman-sdd-specs-compact.md +0 -41
  108. package/templates/zh-Hans/skills/llman-sdd-validate.md +0 -28
  109. package/templates/zh-Hans/skills/llman-sdd-verify.md +0 -77
  110. package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +0 -83
  111. package/templates/zh-Hans/units/skills/ethics-governance.md +0 -6
  112. package/templates/zh-Hans/units/skills/git-native-flow.md +0 -56
  113. package/templates/zh-Hans/units/skills/human-readable-summary.md +0 -9
  114. package/templates/zh-Hans/units/skills/index-fallback.md +0 -1
  115. package/templates/zh-Hans/units/skills/stage-guard.md +0 -17
  116. package/templates/zh-Hans/units/skills/structured-protocol.md +0 -19
  117. package/templates/zh-Hans/units/skills/validation-hints.md +0 -20
  118. package/templates/zh-Hans/units/skills/version-drift.md +0 -3
  119. package/templates/zh-Hans/units/spec/feature-contract.md +0 -8
@@ -1,169 +1,427 @@
1
1
  /**
2
- * XState-powered transition-table validation (validation r104): tag-scoped
3
- * discovery (@transitions force / @no-transitions escape / shape sniff),
4
- * Examples-table driven gates E1–E4. Pure — no I/O.
2
+ * Transition-table validation (validation r104, r124–r127): whitelist tag discovery
3
+ * (@flow / @state / @nodes / @decision_table), zh-Hans column families only,
4
+ * Examples-driven graph gates. Pure — no I/O.
5
5
  */
6
6
  import { createGraph, addNode, addEdge, genBFS, hasPath } from '@statelyai/graph';
7
- import { createMachine } from 'xstate';
8
7
 
9
8
  import type { RuleIR, ScenarioIR } from '../spec/ir.ts';
9
+ import { parseReqRef, tokenizeReqRefs, type ReqRef } from '../spec/reqRef.ts';
10
10
  import type { ValidationItem } from './validate.ts';
11
11
 
12
12
  export interface TransitionEdge {
13
13
  from: string;
14
14
  event: string;
15
15
  to: string;
16
- guard?: string;
16
+ condition?: string;
17
+ action?: string;
18
+ actor?: string;
19
+ edgeKind?: string;
20
+ meta?: string;
21
+ verify?: string;
17
22
  }
18
23
 
19
- const FROM_HEADERS = new Set(['from', '初始状态']);
20
- const EVENT_HEADERS = new Set(['event', '事件']);
21
- const TO_HEADERS = new Set(['to', '目标状态']);
22
- const GUARD_HEADERS = new Set(['guard', '守卫']);
23
-
24
- export interface ColumnMap {
24
+ export const FLOW_TAG = 'flow';
25
+ export const STATE_TAG = 'state';
26
+ export const NODES_TAG = 'nodes';
27
+ export const DECISION_TABLE_TAG = 'decision_table';
28
+
29
+ export const DIALECT_TAGS = [FLOW_TAG, STATE_TAG, NODES_TAG, DECISION_TABLE_TAG] as const;
30
+ export type DialectTag = (typeof DIALECT_TAGS)[number];
31
+
32
+ const STATE_EDGE_REQUIRED = ['当前', '触发', '目标'] as const;
33
+ const FLOW_EDGE_REQUIRED = ['当前步骤', '分支', '下一步'] as const;
34
+ const EDGE_OPTIONAL = ['条件', '动作', '执行方', '边类型', '元信息'] as const;
35
+ const FLOW_EDGE_OPTIONAL = [...EDGE_OPTIONAL, '验证'] as const;
36
+
37
+ const NODES_REQUIRED = ['节点'] as const;
38
+ const NODES_OPTIONAL = ['类型', '引用', '执行方', '人类说明', '完成标准'] as const;
39
+
40
+ const FORBIDDEN_HEADERS = new Set([
41
+ 'from',
42
+ 'event',
43
+ 'to',
44
+ 'guard',
45
+ 'current',
46
+ 'trigger',
47
+ 'target',
48
+ '初始状态',
49
+ '事件',
50
+ '目标状态',
51
+ '守卫',
52
+ 'state',
53
+ 'submachine',
54
+ 'gateway',
55
+ '状态',
56
+ '子机',
57
+ '网关',
58
+ ]);
59
+
60
+ export const START_PSEUDO = '[开始]';
61
+ const END_NAMED_RE = /^\[结束:([^[\]]+)\]$/u;
62
+ const ABORT_NAMED_RE = /^\[终止:([^[\]]+)\]$/u;
63
+
64
+ export interface EdgeColumnMap {
25
65
  from: string;
26
66
  event: string;
27
67
  to: string;
28
- guard?: string;
68
+ condition?: string;
69
+ action?: string;
70
+ actor?: string;
71
+ edgeKind?: string;
72
+ meta?: string;
73
+ verify?: string;
74
+ }
75
+
76
+ export interface NodesColumnMap {
77
+ node: string;
78
+ nodeKind?: string;
79
+ nestKey?: string;
80
+ actor?: string;
81
+ summary?: string;
82
+ done?: string;
29
83
  }
30
84
 
31
- function headerMatches(headers: string[], names: Set<string>): boolean {
32
- return headers.some((h) => names.has(h) || names.has(h.toLowerCase()));
85
+ function headerIndex(headers: string[], name: string): number {
86
+ return headers.indexOf(name);
33
87
  }
34
88
 
35
- function headerIndex(headers: string[], names: Set<string>): number {
36
- for (let i = 0; i < headers.length; i++) {
37
- const h = headers[i] ?? '';
38
- if (names.has(h) || names.has(h.toLowerCase())) return i;
89
+ function pickOptional(headers: string[], names: readonly string[]): Partial<EdgeColumnMap> {
90
+ const out: Partial<EdgeColumnMap> = {};
91
+ for (const n of names) {
92
+ if (headers.includes(n)) {
93
+ if (n === '条件') out.condition = n;
94
+ else if (n === '动作') out.action = n;
95
+ else if (n === '执行方') out.actor = n;
96
+ else if (n === '边类型') out.edgeKind = n;
97
+ else if (n === '元信息') out.meta = n;
98
+ else if (n === '验证') out.verify = n;
99
+ }
39
100
  }
40
- return -1;
101
+ return out;
41
102
  }
42
103
 
43
- export function resolveTransitionColumns(headers: string[]): ColumnMap | null {
44
- const fromIdx = headerIndex(headers, FROM_HEADERS);
45
- const eventIdx = headerIndex(headers, EVENT_HEADERS);
46
- const toIdx = headerIndex(headers, TO_HEADERS);
47
- if (fromIdx === -1 || eventIdx === -1 || toIdx === -1) return null;
48
- const guardIdx = headerIndex(headers, GUARD_HEADERS);
49
- const fromCol = headers[fromIdx] ?? 'from';
50
- const eventCol = headers[eventIdx] ?? 'event';
51
- const toCol = headers[toIdx] ?? 'to';
52
- const guardCol = guardIdx === -1 ? undefined : headers[guardIdx];
53
- return { from: fromCol, event: eventCol, to: toCol, guard: guardCol };
104
+ export function resolveStateEdgeColumns(headers: string[]): EdgeColumnMap | null {
105
+ for (const req of STATE_EDGE_REQUIRED) {
106
+ if (!headers.includes(req)) return null;
107
+ }
108
+ return {
109
+ from: '当前',
110
+ event: '触发',
111
+ to: '目标',
112
+ ...pickOptional(headers, EDGE_OPTIONAL),
113
+ };
54
114
  }
55
115
 
56
- /** Auto-discovery: at least two of {from, event, to} column families present. */
57
- export function isTransitionOutline(sc: ScenarioIR): boolean {
58
- if (!sc.examples || sc.examples.length === 0) return false;
59
- for (const ex of sc.examples) {
60
- const h = ex.headers;
61
- const hasFrom = headerMatches(h, FROM_HEADERS);
62
- const hasEvent = headerMatches(h, EVENT_HEADERS);
63
- const hasTo = headerMatches(h, TO_HEADERS);
64
- if ((hasFrom && hasTo) || (hasFrom && hasEvent) || (hasEvent && hasTo)) return true;
116
+ export function resolveFlowEdgeColumns(headers: string[]): EdgeColumnMap | null {
117
+ for (const req of FLOW_EDGE_REQUIRED) {
118
+ if (!headers.includes(req)) return null;
65
119
  }
66
- return false;
120
+ return {
121
+ from: '当前步骤',
122
+ event: '分支',
123
+ to: '下一步',
124
+ ...pickOptional(headers, FLOW_EDGE_OPTIONAL),
125
+ };
67
126
  }
68
127
 
69
- export const FORCE_TRANSITIONS_TAG = 'transitions';
70
- export const ESCAPE_TRANSITIONS_TAG = 'no-transitions';
128
+ export function resolveNodesColumns(headers: string[]): NodesColumnMap | null {
129
+ if (!headers.includes('节点')) return null;
130
+ const map: NodesColumnMap = { node: '节点' };
131
+ if (headers.includes('类型')) map.nodeKind = '类型';
132
+ if (headers.includes('引用')) map.nestKey = '引用';
133
+ if (headers.includes('执行方')) map.actor = '执行方';
134
+ if (headers.includes('人类说明')) map.summary = '人类说明';
135
+ if (headers.includes('完成标准')) map.done = '完成标准';
136
+ return map;
137
+ }
71
138
 
72
- /**
73
- * Single source of truth for `spec transitions` introspection (peripheral r105):
74
- * the discovery contract as enforced above — alias families, sniff rule, tags
75
- * and gates. The CLI renders this verbatim; do not duplicate it elsewhere.
76
- */
77
- export const TRANSITIONS_INTROSPECTION = {
78
- columnFamilies: [
79
- { role: 'from', aliases: ['from', '初始状态'] },
80
- { role: 'event', aliases: ['event', '事件'] },
81
- { role: 'to', aliases: ['to', '目标状态'] },
82
- { role: 'guard', aliases: ['guard', '守卫'], optional: true },
83
- ],
84
- discovery:
85
- 'no-tag scenario outline: examples header hitting at least 2 of the 3 families (from/event/to) is scoped in as a transition table',
86
- tags: [
87
- {
88
- tag: '@transitions',
89
- semantics: 'force validation even when no alias family matches (malformed tables fail E1)',
90
- },
91
- {
92
- tag: '@no-transitions',
93
- semantics: 'total escape even when the sniff matches (both tags together is an ERROR)',
94
- },
95
- ],
96
- gates: [
97
- 'E1 structure & placeholder binding (columns from/event/to, runnable, steps bind <from>/<event>/<to>/<guard>)',
98
- 'E2 determinism (same (from, event, guard) must not target different states)',
99
- 'E3 reachability (every state reachable from the first-row from state)',
100
- 'E4 deadlock/trap (with terminal states: reach one; without: return to the initial state)',
101
- ],
102
- } as const;
139
+ export function isNodesOutline(sc: ScenarioIR): boolean {
140
+ return sc.tags.includes(NODES_TAG);
141
+ }
142
+
143
+ /** Whitelist dialect tags present on a scenario (excludes unknown legacy tags). */
144
+ export function dialectTagsOn(sc: ScenarioIR): DialectTag[] {
145
+ return DIALECT_TAGS.filter((t) => sc.tags.includes(t));
146
+ }
147
+
148
+ export type GraphScope = DialectTag | 'skip' | 'conflict';
149
+
150
+ export function resolveGraphScope(sc: ScenarioIR): GraphScope {
151
+ const hits = dialectTagsOn(sc);
152
+ if (hits.length > 1) return 'conflict';
153
+ if (hits.length === 1) return hits[0]!;
154
+ return 'skip';
155
+ }
156
+
157
+ function expectedEdgeHeaders(isFlow: boolean): readonly string[] {
158
+ return isFlow
159
+ ? [...FLOW_EDGE_REQUIRED, ...FLOW_EDGE_OPTIONAL]
160
+ : [...STATE_EDGE_REQUIRED, ...EDGE_OPTIONAL];
161
+ }
162
+
163
+ function collectUnsupportedEdgeHeaders(headers: string[], isFlow: boolean): string[] {
164
+ const allowed = new Set<string>(expectedEdgeHeaders(isFlow));
165
+ const bad: string[] = [];
166
+ for (const h of headers) {
167
+ if (FORBIDDEN_HEADERS.has(h) || !allowed.has(h)) bad.push(h);
168
+ }
169
+ return bad;
170
+ }
171
+
172
+ function collectUnsupportedNodesHeaders(headers: string[]): string[] {
173
+ const allowed = new Set<string>([...NODES_REQUIRED, ...NODES_OPTIONAL]);
174
+ const bad: string[] = [];
175
+ for (const h of headers) {
176
+ if (FORBIDDEN_HEADERS.has(h) || !allowed.has(h)) bad.push(h);
177
+ }
178
+ return bad;
179
+ }
180
+
181
+ function unsupportedHeadersMessage(scenarioName: string, bad: string[], expected: string): string {
182
+ return `scenario \`${scenarioName}\` has unsupported column headers [${bad.join(', ')}] — expected zh-Hans columns: ${expected}; migrate from legacy from/event/to or 初始状态/事件/目标状态`;
183
+ }
103
184
 
104
- export type TransitionDecision = 'conflict' | 'skip' | 'force' | 'sniff';
185
+ /** Nest reference shape — the shared `reqRef` parser output. */
186
+ export type NestRef = ReqRef;
105
187
 
106
188
  /**
107
- * Per-scenario scoping (r104), short-circuiting in order: both tags → ERROR,
108
- * @no-transitions → total escape, @transitions → forced entry, no tag →
109
- * shape sniff. Tags carry no leading `@` in the IR (parser strips it).
189
+ * Parse `@req:<id>`, `@req:<id>#<场景名>` or `@req:<id>#"带空格 场景"`.
190
+ * The `@req:` prefix is mandatory in specs — a bare `r12` or a
191
+ * `@llmanspec:req:r12` source anchor is rejected. Invalid / empty → null.
110
192
  */
111
- export function resolveTransitionDecision(sc: ScenarioIR): TransitionDecision {
112
- const force = sc.tags.includes(FORCE_TRANSITIONS_TAG);
113
- const escape = sc.tags.includes(ESCAPE_TRANSITIONS_TAG);
114
- if (force && escape) return 'conflict';
115
- if (escape) return 'skip';
116
- if (force) return 'force';
117
- return 'sniff';
193
+ export function parseNestRef(cell: string): NestRef | null {
194
+ return parseReqRef(cell, 'spec');
118
195
  }
119
196
 
120
- function placeholderVariants(col: string): string[] {
121
- return [`<${col}>`, `<${col.toLowerCase()}>`];
197
+ /**
198
+ * Split a `验证` cell into nest refs via the shared quote-aware tokenizer.
199
+ * Empty cell → []; a syntactically invalid token keeps `reqId: ''`.
200
+ */
201
+ export function parseVerifyPointers(cell: string): NestRef[] {
202
+ const out: NestRef[] = [];
203
+ for (const token of tokenizeReqRefs(cell)) {
204
+ const ref = parseReqRef(token, 'spec');
205
+ if (ref !== null) out.push(ref);
206
+ }
207
+ return out;
122
208
  }
123
209
 
124
- function stepBindsPlaceholder(text: string, col: string): boolean {
125
- return placeholderVariants(col).some((v) => text.includes(v));
210
+ export function isJudgmentKind(value: string): boolean {
211
+ return value.trim() === '判断';
126
212
  }
127
213
 
128
- function extractTransitions(sc: ScenarioIR): TransitionEdge[] {
214
+ export function extractTransitions(sc: ScenarioIR): TransitionEdge[] {
129
215
  const transitions: TransitionEdge[] = [];
216
+ const isFlow = sc.tags.includes(FLOW_TAG);
130
217
  for (const block of sc.examples ?? []) {
131
- const cols = resolveTransitionColumns(block.headers);
218
+ const cols = isFlow
219
+ ? resolveFlowEdgeColumns(block.headers)
220
+ : resolveStateEdgeColumns(block.headers);
132
221
  if (!cols) continue;
133
- const fromIdx = block.headers.indexOf(cols.from);
134
- const eventIdx = block.headers.indexOf(cols.event);
135
- const toIdx = block.headers.indexOf(cols.to);
136
- const guardIdx = cols.guard === undefined ? -1 : block.headers.indexOf(cols.guard);
222
+ const fromIdx = headerIndex(block.headers, cols.from);
223
+ const eventIdx = headerIndex(block.headers, cols.event);
224
+ const toIdx = headerIndex(block.headers, cols.to);
225
+ const condIdx = cols.condition === undefined ? -1 : headerIndex(block.headers, cols.condition);
226
+ const actIdx = cols.action === undefined ? -1 : headerIndex(block.headers, cols.action);
227
+ const actorIdx = cols.actor === undefined ? -1 : headerIndex(block.headers, cols.actor);
228
+ const kindIdx = cols.edgeKind === undefined ? -1 : headerIndex(block.headers, cols.edgeKind);
229
+ const metaIdx = cols.meta === undefined ? -1 : headerIndex(block.headers, cols.meta);
230
+ const verifyIdx = cols.verify === undefined ? -1 : headerIndex(block.headers, cols.verify);
137
231
  for (const row of block.rows) {
138
232
  transitions.push({
139
233
  from: row[fromIdx] ?? '',
140
234
  event: row[eventIdx] ?? '',
141
235
  to: row[toIdx] ?? '',
142
- guard: guardIdx === -1 ? undefined : (row[guardIdx] ?? ''),
236
+ ...(condIdx === -1 ? {} : { condition: row[condIdx] ?? '' }),
237
+ ...(actIdx === -1 ? {} : { action: row[actIdx] ?? '' }),
238
+ ...(actorIdx === -1 ? {} : { actor: row[actorIdx] ?? '' }),
239
+ ...(kindIdx === -1 ? {} : { edgeKind: row[kindIdx] ?? '' }),
240
+ ...(metaIdx === -1 ? {} : { meta: row[metaIdx] ?? '' }),
241
+ ...(verifyIdx === -1 ? {} : { verify: row[verifyIdx] ?? '' }),
143
242
  });
144
243
  }
145
244
  }
146
245
  return transitions;
147
246
  }
148
247
 
149
- function distinctStates(transitions: readonly TransitionEdge[]): Set<string> {
150
- const states = new Set<string>();
248
+ export function namedExitsInGraph(transitions: readonly TransitionEdge[]): Set<string> {
249
+ const names = new Set<string>();
151
250
  for (const t of transitions) {
152
- states.add(t.from);
153
- states.add(t.to);
251
+ for (const cell of [t.from, t.to]) {
252
+ const trimmed = cell.trim();
253
+ const endM = END_NAMED_RE.exec(trimmed);
254
+ const abortM = ABORT_NAMED_RE.exec(trimmed);
255
+ if (endM?.[1]) names.add(endM[1].trim());
256
+ if (abortM?.[1]) names.add(abortM[1].trim());
257
+ }
154
258
  }
155
- return states;
259
+ return names;
260
+ }
261
+
262
+ function distinctNodes(transitions: readonly TransitionEdge[]): Set<string> {
263
+ const nodes = new Set<string>();
264
+ for (const t of transitions) {
265
+ if (t.from.trim() !== '') nodes.add(t.from.trim());
266
+ if (t.to.trim() !== '') nodes.add(t.to.trim());
267
+ }
268
+ return nodes;
269
+ }
270
+
271
+ function resolveInitialState(transitions: readonly TransitionEdge[]): string {
272
+ const nodes = distinctNodes(transitions);
273
+ if (nodes.has(START_PSEUDO)) return START_PSEUDO;
274
+ return transitions[0]?.from.trim() ?? '';
275
+ }
276
+
277
+ function isTerminalNode(name: string, outDegree: number): boolean {
278
+ const trimmed = name.trim();
279
+ if (trimmed === '[结束]' || trimmed === '[终止]') return true;
280
+ if (END_NAMED_RE.test(trimmed) || ABORT_NAMED_RE.test(trimmed)) return true;
281
+ return outDegree === 0;
156
282
  }
157
283
 
158
284
  function anchor(cap: string, rule: RuleIR): string {
159
285
  return `${cap}/transitions/${rule.reqId || rule.title}`;
160
286
  }
161
287
 
162
- /** E1–E4 for one transition outline; returns ERROR items only. */
288
+ const DEFAULT_ROW_MARKERS = new Set(['*', '—', '-', '缺省']);
289
+
290
+ function isDefaultDecisionRow(row: readonly string[], condColCount: number): boolean {
291
+ for (let i = 0; i < condColCount; i += 1) {
292
+ const cell = (row[i] ?? '').trim();
293
+ if (DEFAULT_ROW_MARKERS.has(cell)) return true;
294
+ }
295
+ return false;
296
+ }
297
+
298
+ /**
299
+ * Single source of truth for `spec transitions` introspection (peripheral r105).
300
+ */
301
+ export const TRANSITIONS_INTROSPECTION = {
302
+ note: '本命令只打印图怎么校验,不导出边。validate 通过只说明表格结构合法,不说明代码按表执行。',
303
+ columnFamilies: {
304
+ state: {
305
+ required: [...STATE_EDGE_REQUIRED],
306
+ optional: [...EDGE_OPTIONAL],
307
+ },
308
+ flow: {
309
+ required: [...FLOW_EDGE_REQUIRED],
310
+ optional: [...FLOW_EDGE_OPTIONAL],
311
+ },
312
+ nodes: {
313
+ required: [...NODES_REQUIRED],
314
+ optional: [...NODES_OPTIONAL],
315
+ },
316
+ },
317
+ discovery:
318
+ 'whitelist scenario tags only — @flow @state @nodes @decision_table; no header sniffing; untagged examples tables are never scoped in',
319
+ tags: [
320
+ {
321
+ tag: '@state',
322
+ semantics: 'state-machine edge table — E1–E4 on zh-Hans 当前/触发/目标 columns',
323
+ },
324
+ { tag: '@flow', semantics: 'flowchart edge table — E1–E3 plus F3/F4 warnings, skip E4' },
325
+ {
326
+ tag: '@nodes',
327
+ semantics: 'node attribute table — N1–N6, A1 warning; never an edge or decision table',
328
+ },
329
+ { tag: '@decision_table', semantics: 'decision table — D1/D2 gates' },
330
+ ],
331
+ gates: [
332
+ 'E1 structure (non-empty Examples, zh-Hans columns, 0-step dialect outline, >=2 distinct nodes)',
333
+ 'E2 determinism (当前, 触发, 条件) unless @nodes marks 类型=并行',
334
+ 'E3 reachability at [开始] or first-row 当前',
335
+ 'E4 terminal/liveness (skipped for @flow)',
336
+ 'F3 (warning, @flow) nodeKind 判断 out-degree < 2',
337
+ 'F4 (warning, @flow) placeholder step names',
338
+ 'N1–N5 nested @req references via 引用 column',
339
+ 'N6 nested exit: parent edges must cover [结束:X]/[终止:Y] named in child',
340
+ 'D1/D2 decision table shape and consistency',
341
+ 'A1 (warning) leaf lacking 引用 with empty 人类说明',
342
+ ],
343
+ } as const;
344
+
345
+ export function validateDecisionScenario(
346
+ cap: string,
347
+ rule: RuleIR,
348
+ sc: ScenarioIR,
349
+ ): ValidationItem[] {
350
+ const items: ValidationItem[] = [];
351
+ const id = anchor(cap, rule);
352
+ const push = (message: string): void => {
353
+ items.push({ level: 'ERROR', id, message });
354
+ };
355
+
356
+ if (sc.stepCount > 0) {
357
+ push(`decision-table scenario \`${sc.name}\` dialect outline must not carry placeholder steps`);
358
+ return items;
359
+ }
360
+
361
+ const block = sc.examples?.[0];
362
+ if (block?.headers.includes('验证')) {
363
+ push(
364
+ `decision-table scenario \`${sc.name}\` has unsupported column headers [验证] — 验证 belongs to @flow edge tables only`,
365
+ );
366
+ return items;
367
+ }
368
+ if (!block || block.headers.length < 2 || block.rows.length < 2) {
369
+ push(
370
+ `decision-table scenario \`${sc.name}\` decision table requires at least 2 columns and 2 data rows`,
371
+ );
372
+ return items;
373
+ }
374
+
375
+ const outCol = block.headers.length - 1;
376
+ const condColCount = outCol;
377
+ const tupleToOutcome = new Map<string, string>();
378
+ for (const row of block.rows) {
379
+ if (isDefaultDecisionRow(row, condColCount)) continue;
380
+ const tuple = row
381
+ .slice(0, outCol)
382
+ .map((c) => c.trim())
383
+ .join('\0');
384
+ const outcome = (row[outCol] ?? '').trim();
385
+ const prev = tupleToOutcome.get(tuple);
386
+ if (prev !== undefined && prev !== outcome) {
387
+ push(
388
+ `decision-table scenario \`${sc.name}\` decision table: conflicting outcomes for the same condition tuple`,
389
+ );
390
+ return items;
391
+ }
392
+ tupleToOutcome.set(tuple, outcome);
393
+ }
394
+ return items;
395
+ }
396
+
397
+ function parallelSourcesInRule(rule: RuleIR): Set<string> {
398
+ const parallel = new Set<string>();
399
+ for (const sc of rule.scenarios) {
400
+ if (!sc.tags.includes(NODES_TAG)) continue;
401
+ for (const block of sc.examples ?? []) {
402
+ const cols = resolveNodesColumns(block.headers);
403
+ if (!cols) continue;
404
+ const nodeIdx = headerIndex(block.headers, cols.node);
405
+ const kindIdx = cols.nodeKind === undefined ? -1 : headerIndex(block.headers, cols.nodeKind);
406
+ if (kindIdx === -1) continue;
407
+ for (const row of block.rows) {
408
+ const kind = (row[kindIdx] ?? '').trim();
409
+ if (kind === '并行') {
410
+ const name = (row[nodeIdx] ?? '').trim();
411
+ if (name !== '') parallel.add(name);
412
+ }
413
+ }
414
+ }
415
+ }
416
+ return parallel;
417
+ }
418
+
419
+ /** E1–E4 for one edge outline; returns ERROR items only. */
163
420
  export function validateTransitionScenario(
164
421
  cap: string,
165
422
  rule: RuleIR,
166
423
  sc: ScenarioIR,
424
+ parallelSources?: Set<string>,
167
425
  ): ValidationItem[] {
168
426
  const items: ValidationItem[] = [];
169
427
  const id = anchor(cap, rule);
@@ -171,11 +429,31 @@ export function validateTransitionScenario(
171
429
  items.push({ level: 'ERROR', id, message });
172
430
  };
173
431
 
432
+ const isFlow = sc.tags.includes(FLOW_TAG);
433
+
434
+ if (sc.stepCount > 0) {
435
+ push(`transition scenario \`${sc.name}\` dialect outline must not carry placeholder steps`);
436
+ return items;
437
+ }
438
+
439
+ for (const block of sc.examples ?? []) {
440
+ const bad = collectUnsupportedEdgeHeaders(block.headers, isFlow);
441
+ if (bad.length > 0) {
442
+ const expected = expectedEdgeHeaders(isFlow).join(', ');
443
+ push(unsupportedHeadersMessage(sc.name, bad, expected));
444
+ return items;
445
+ }
446
+ }
447
+
174
448
  const transitions = extractTransitions(sc);
175
- const states = distinctStates(transitions);
449
+ const nodes = distinctNodes(transitions);
176
450
 
177
451
  const cols =
178
- sc.examples?.map((ex) => resolveTransitionColumns(ex.headers)).find((c) => c !== null) ?? null;
452
+ sc.examples
453
+ ?.map((ex) =>
454
+ isFlow ? resolveFlowEdgeColumns(ex.headers) : resolveStateEdgeColumns(ex.headers),
455
+ )
456
+ .find((c) => c !== null) ?? null;
179
457
 
180
458
  const e1Table =
181
459
  !sc.runnable ||
@@ -183,8 +461,8 @@ export function validateTransitionScenario(
183
461
  sc.examples.length === 0 ||
184
462
  cols === null ||
185
463
  transitions.length < 1 ||
186
- transitions.some((t) => t.from === '' || t.event === '' || t.to === '') ||
187
- states.size < 2;
464
+ transitions.some((t) => t.from.trim() === '' || t.event.trim() === '' || t.to.trim() === '') ||
465
+ nodes.size < 2;
188
466
 
189
467
  if (e1Table) {
190
468
  push(
@@ -193,58 +471,34 @@ export function validateTransitionScenario(
193
471
  return items;
194
472
  }
195
473
 
196
- const given = sc.steps.find((s) => s.kind === 'given');
197
- const when = sc.steps.find((s) => s.kind === 'when');
198
- const then = sc.steps.find((s) => s.kind === 'then');
199
- const needsGuard = cols.guard !== undefined;
200
- const givenOk =
201
- given !== undefined &&
202
- stepBindsPlaceholder(given.text, cols.from) &&
203
- (!needsGuard ||
204
- stepBindsPlaceholder(given.text, cols.guard!) ||
205
- (when !== undefined && stepBindsPlaceholder(when.text, cols.guard!)));
206
- const whenOk = when !== undefined && stepBindsPlaceholder(when.text, cols.event);
207
- const thenOk = then !== undefined && stepBindsPlaceholder(then.text, cols.to);
208
-
209
- if (!givenOk || !whenOk || !thenOk) {
210
- push(
211
- `transition scenario \`${sc.name}\` steps must bind placeholders <from> in Given, <event> in When, and <to> in Then`,
212
- );
213
- return items;
214
- }
474
+ const parallel = parallelSources ?? parallelSourcesInRule(rule);
215
475
 
216
- const seen = new Set<string>();
476
+ const seen = new Map<string, string>();
217
477
  for (const t of transitions) {
218
- const key = `${t.from}\0${t.event}\0${t.guard ?? ''}`;
219
- if (seen.has(key)) {
220
- const guardPart = t.guard ? ` [${t.guard}]` : '';
478
+ const src = t.from.trim();
479
+ if (parallel.has(src)) continue;
480
+ const key = `${src}\0${t.event.trim()}\0${t.condition?.trim() ?? ''}`;
481
+ const prevTo = seen.get(key);
482
+ if (prevTo !== undefined) {
483
+ const condPart = t.condition?.trim() ? ` [${t.condition.trim()}]` : '';
221
484
  push(
222
- `non-deterministic or duplicate transition in \`${sc.name}\`: state \`${t.from}\` on event \`${t.event}\`${guardPart} has conflicting targets`,
485
+ `non-deterministic or duplicate transition in \`${sc.name}\`: state \`${src}\` on event \`${t.event.trim()}\`${condPart} has conflicting targets`,
223
486
  );
224
487
  return items;
225
488
  }
226
- seen.add(key);
489
+ seen.set(key, t.to.trim());
227
490
  }
228
491
 
229
- const initial = transitions[0]?.from ?? '';
230
- try {
231
- createMachine({
232
- id: 'transitions',
233
- initial,
234
- states: Object.fromEntries([...states].map((s) => [s, {}])) as Record<string, object>,
235
- });
236
- } catch {
237
- // createMachine structural sanity — transitions drive graph below
238
- }
492
+ const initial = resolveInitialState(transitions);
239
493
 
240
494
  const graph = createGraph();
241
- for (const s of states) addNode(graph, { id: s });
495
+ for (const s of nodes) addNode(graph, { id: s });
242
496
  let edgeSeq = 0;
243
497
  for (const t of transitions) {
244
498
  addEdge(graph, {
245
499
  id: `e${String(edgeSeq++)}`,
246
- sourceId: t.from,
247
- targetId: t.to,
500
+ sourceId: t.from.trim(),
501
+ targetId: t.to.trim(),
248
502
  });
249
503
  }
250
504
 
@@ -253,7 +507,7 @@ export function validateTransitionScenario(
253
507
  .map((n) => (typeof n === 'object' && n !== null && 'id' in n ? String(n.id) : String(n)))
254
508
  .filter((nid) => nid !== ''),
255
509
  );
256
- const unreachable = [...states].filter((s) => !reachable.has(s));
510
+ const unreachable = [...nodes].filter((s) => !reachable.has(s));
257
511
  if (unreachable.length > 0) {
258
512
  push(
259
513
  `unreachable state(s) in transition table \`${sc.name}\` from initial state \`${initial}\`: ${unreachable.join(', ')}`,
@@ -262,21 +516,26 @@ export function validateTransitionScenario(
262
516
  }
263
517
 
264
518
  const outTargets = new Map<string, Set<string>>();
519
+ const outDegree = new Map<string, number>();
265
520
  for (const t of transitions) {
266
- const set = outTargets.get(t.from) ?? new Set<string>();
267
- set.add(t.to);
268
- outTargets.set(t.from, set);
521
+ const from = t.from.trim();
522
+ const set = outTargets.get(from) ?? new Set<string>();
523
+ set.add(t.to.trim());
524
+ outTargets.set(from, set);
525
+ outDegree.set(from, (outDegree.get(from) ?? 0) + 1);
526
+ }
527
+
528
+ if (isFlow) {
529
+ return items;
269
530
  }
270
531
 
271
- // E4 unified invariant (r104): with terminal states (out-degree 0) every
272
- // non-terminal state must reach one; without any terminal state (cyclic
273
- // machine) every state must be able to return to the initial state. E3 has
274
- // already guaranteed all states are reachable FROM the initial state.
275
- const terminalStates = [...states].filter((s) => (outTargets.get(s)?.size ?? 0) === 0);
532
+ const terminalStates = [...nodes].filter((s) => isTerminalNode(s, outDegree.get(s) ?? 0));
276
533
 
277
534
  if (terminalStates.length > 0) {
278
- const deadlocks = [...states].filter(
279
- (s) => !terminalStates.includes(s) && !terminalStates.some((term) => hasPath(graph, s, term)),
535
+ const deadlocks = [...nodes].filter(
536
+ (s) =>
537
+ !isTerminalNode(s, outDegree.get(s) ?? 0) &&
538
+ !terminalStates.some((term) => hasPath(graph, s, term)),
280
539
  );
281
540
  if (deadlocks.length > 0) {
282
541
  push(
@@ -285,7 +544,7 @@ export function validateTransitionScenario(
285
544
  return items;
286
545
  }
287
546
  } else {
288
- const trapped = [...states].filter((s) => s !== initial && !hasPath(graph, s, initial));
547
+ const trapped = [...nodes].filter((s) => s !== initial && !hasPath(graph, s, initial));
289
548
  if (trapped.length > 0) {
290
549
  push(
291
550
  `trap state(s) in transition table \`${sc.name}\` (cannot return to the initial state \`${initial}\`): ${trapped.join(', ')}`,
@@ -297,44 +556,84 @@ export function validateTransitionScenario(
297
556
  return items;
298
557
  }
299
558
 
559
+ export function validateNodesScenario(cap: string, rule: RuleIR, sc: ScenarioIR): ValidationItem[] {
560
+ const items: ValidationItem[] = [];
561
+ const id = anchor(cap, rule);
562
+ const push = (level: 'ERROR' | 'WARNING', message: string): void => {
563
+ items.push({ level, id, message });
564
+ };
565
+
566
+ if (sc.stepCount > 0) {
567
+ push('ERROR', `nodes scenario \`${sc.name}\` dialect outline must not carry placeholder steps`);
568
+ return items;
569
+ }
570
+
571
+ for (const block of sc.examples ?? []) {
572
+ const bad = collectUnsupportedNodesHeaders(block.headers);
573
+ if (bad.length > 0) {
574
+ const expected = [...NODES_REQUIRED, ...NODES_OPTIONAL].join(', ');
575
+ push('ERROR', unsupportedHeadersMessage(sc.name, bad, expected));
576
+ return items;
577
+ }
578
+ }
579
+
580
+ const cols =
581
+ sc.examples?.map((ex) => resolveNodesColumns(ex.headers)).find((c) => c !== null) ?? null;
582
+ if (!sc.runnable || !sc.examples || sc.examples.length === 0 || cols === null) {
583
+ push(
584
+ 'ERROR',
585
+ `nodes scenario \`${sc.name}\` requires a runnable Examples table with a 节点 column`,
586
+ );
587
+ return items;
588
+ }
589
+
590
+ const nodeIdx = headerIndex(sc.examples[0]!.headers, cols.node);
591
+ const nestIdx =
592
+ cols.nestKey === undefined ? -1 : headerIndex(sc.examples[0]!.headers, cols.nestKey);
593
+ const sumIdx =
594
+ cols.summary === undefined ? -1 : headerIndex(sc.examples[0]!.headers, cols.summary);
595
+
596
+ for (const block of sc.examples) {
597
+ for (const row of block.rows) {
598
+ const nestCell = nestIdx === -1 ? '' : (row[nestIdx] ?? '');
599
+ const ref = parseNestRef(nestCell);
600
+ const hasNest = ref !== null && ref.reqId !== '';
601
+ if (hasNest) continue;
602
+ const summary = sumIdx === -1 ? '' : (row[sumIdx] ?? '').trim();
603
+ const nodeName = (row[nodeIdx] ?? '').trim();
604
+ if (summary === '') {
605
+ push('WARNING', `A1: leaf node \`${nodeName}\` in \`${sc.name}\` lacks 人类说明`);
606
+ }
607
+ }
608
+ }
609
+ return items;
610
+ }
611
+
300
612
  export function validateTransitionsForRule(cap: string, rule: RuleIR): ValidationItem[] {
301
613
  const items: ValidationItem[] = [];
614
+ const parallel = parallelSourcesInRule(rule);
302
615
  for (const sc of rule.scenarios) {
303
- const decision = resolveTransitionDecision(sc);
304
- if (decision === 'conflict') {
616
+ const scope = resolveGraphScope(sc);
617
+ if (scope === 'conflict') {
305
618
  items.push({
306
619
  level: 'ERROR',
307
620
  id: anchor(cap, rule),
308
- message: `scenario \`${sc.name}\` carries conflicting @transitions and @no-transitions tags — keep exactly one`,
621
+ message: `scenario \`${sc.name}\` carries conflicting dialect tags — keep exactly one of @flow/@state/@nodes/@decision_table`,
309
622
  });
310
623
  continue;
311
624
  }
312
- // Escape is total: skip even malformed tables; force enters validation so
313
- // a malformed table fails E1 loudly.
314
- if (decision === 'skip') continue;
315
- if (decision === 'sniff' && !isTransitionOutline(sc)) continue;
316
- items.push(...validateTransitionScenario(cap, rule, sc));
625
+ if (scope === 'skip') continue;
626
+ if (scope === DECISION_TABLE_TAG) {
627
+ items.push(...validateDecisionScenario(cap, rule, sc));
628
+ continue;
629
+ }
630
+ if (scope === NODES_TAG) {
631
+ items.push(...validateNodesScenario(cap, rule, sc));
632
+ continue;
633
+ }
634
+ if (scope === FLOW_TAG || scope === STATE_TAG) {
635
+ items.push(...validateTransitionScenario(cap, rule, sc, parallel));
636
+ }
317
637
  }
318
638
  return items;
319
639
  }
320
-
321
- export function parseTransitionExpr(expr: string): TransitionEdge {
322
- const trimmed = expr.trim();
323
- const m = trimmed.match(/^([^:]+):([\w-]+)(?:\[([^\]]+)\])?->(.+)$/u);
324
- if (!m) {
325
- throw new Error(`invalid transition expression: ${expr}`);
326
- }
327
- const from = m[1];
328
- const event = m[2];
329
- const guard = m[3];
330
- const to = m[4];
331
- if (from === undefined || event === undefined || to === undefined) {
332
- throw new Error(`invalid transition expression: ${expr}`);
333
- }
334
- return {
335
- from: from.trim(),
336
- event: event.trim(),
337
- to: to.trim(),
338
- guard: guard?.trim() === '' ? undefined : guard?.trim(),
339
- };
340
- }