@llman-sdd/core 0.8.1 → 0.9.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.
@@ -0,0 +1,372 @@
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.
5
+ */
6
+ import { createGraph, addNode, addEdge, genBFS, hasPath } from '@statelyai/graph';
7
+ import { createMachine } from 'xstate';
8
+
9
+ import type { RuleIR, ScenarioIR } from '../spec/ir.ts';
10
+ import type { ValidationItem } from './validate.ts';
11
+
12
+ export interface TransitionEdge {
13
+ from: string;
14
+ event: string;
15
+ to: string;
16
+ guard?: string;
17
+ }
18
+
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 {
25
+ from: string;
26
+ event: string;
27
+ to: string;
28
+ guard?: string;
29
+ }
30
+
31
+ function headerMatches(headers: string[], names: Set<string>): boolean {
32
+ return headers.some((h) => names.has(h) || names.has(h.toLowerCase()));
33
+ }
34
+
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;
39
+ }
40
+ return -1;
41
+ }
42
+
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 };
54
+ }
55
+
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;
65
+ }
66
+ return false;
67
+ }
68
+
69
+ export const FORCE_TRANSITIONS_TAG = 'transitions';
70
+ export const ESCAPE_TRANSITIONS_TAG = 'no-transitions';
71
+
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;
103
+
104
+ export type TransitionDecision = 'conflict' | 'skip' | 'force' | 'sniff';
105
+
106
+ /**
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).
110
+ */
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';
118
+ }
119
+
120
+ function placeholderVariants(col: string): string[] {
121
+ return [`<${col}>`, `<${col.toLowerCase()}>`];
122
+ }
123
+
124
+ function stepBindsPlaceholder(text: string, col: string): boolean {
125
+ return placeholderVariants(col).some((v) => text.includes(v));
126
+ }
127
+
128
+ function extractTransitions(sc: ScenarioIR): TransitionEdge[] {
129
+ const transitions: TransitionEdge[] = [];
130
+ for (const block of sc.examples ?? []) {
131
+ const cols = resolveTransitionColumns(block.headers);
132
+ 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);
137
+ for (const row of block.rows) {
138
+ transitions.push({
139
+ from: row[fromIdx] ?? '',
140
+ event: row[eventIdx] ?? '',
141
+ to: row[toIdx] ?? '',
142
+ guard: guardIdx === -1 ? undefined : (row[guardIdx] ?? ''),
143
+ });
144
+ }
145
+ }
146
+ return transitions;
147
+ }
148
+
149
+ function distinctStates(transitions: readonly TransitionEdge[]): Set<string> {
150
+ const states = new Set<string>();
151
+ for (const t of transitions) {
152
+ states.add(t.from);
153
+ states.add(t.to);
154
+ }
155
+ return states;
156
+ }
157
+
158
+ function anchor(cap: string, rule: RuleIR): string {
159
+ return `${cap}/transitions/${rule.reqId || rule.title}`;
160
+ }
161
+
162
+ /** E1–E4 for one transition outline; returns ERROR items only. */
163
+ export function validateTransitionScenario(
164
+ cap: string,
165
+ rule: RuleIR,
166
+ sc: ScenarioIR,
167
+ ): ValidationItem[] {
168
+ const items: ValidationItem[] = [];
169
+ const id = anchor(cap, rule);
170
+ const push = (message: string): void => {
171
+ items.push({ level: 'ERROR', id, message });
172
+ };
173
+
174
+ const transitions = extractTransitions(sc);
175
+ const states = distinctStates(transitions);
176
+
177
+ const cols =
178
+ sc.examples?.map((ex) => resolveTransitionColumns(ex.headers)).find((c) => c !== null) ?? null;
179
+
180
+ const e1Table =
181
+ !sc.runnable ||
182
+ !sc.examples ||
183
+ sc.examples.length === 0 ||
184
+ cols === null ||
185
+ transitions.length < 1 ||
186
+ transitions.some((t) => t.from === '' || t.event === '' || t.to === '') ||
187
+ states.size < 2;
188
+
189
+ if (e1Table) {
190
+ push(
191
+ `transition scenario \`${sc.name}\` requires a runnable non-empty Examples table with columns [from, event, to] and at least 2 distinct states`,
192
+ );
193
+ return items;
194
+ }
195
+
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
+ }
215
+
216
+ const seen = new Set<string>();
217
+ 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}]` : '';
221
+ push(
222
+ `non-deterministic or duplicate transition in \`${sc.name}\`: state \`${t.from}\` on event \`${t.event}\`${guardPart} has conflicting targets`,
223
+ );
224
+ return items;
225
+ }
226
+ seen.add(key);
227
+ }
228
+
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
+ }
239
+
240
+ const graph = createGraph();
241
+ for (const s of states) addNode(graph, { id: s });
242
+ let edgeSeq = 0;
243
+ for (const t of transitions) {
244
+ addEdge(graph, {
245
+ id: `e${String(edgeSeq++)}`,
246
+ sourceId: t.from,
247
+ targetId: t.to,
248
+ });
249
+ }
250
+
251
+ const reachable = new Set(
252
+ [...genBFS(graph, initial)]
253
+ .map((n) => (typeof n === 'object' && n !== null && 'id' in n ? String(n.id) : String(n)))
254
+ .filter((nid) => nid !== ''),
255
+ );
256
+ const unreachable = [...states].filter((s) => !reachable.has(s));
257
+ if (unreachable.length > 0) {
258
+ push(
259
+ `unreachable state(s) in transition table \`${sc.name}\` from initial state \`${initial}\`: ${unreachable.join(', ')}`,
260
+ );
261
+ return items;
262
+ }
263
+
264
+ const outTargets = new Map<string, Set<string>>();
265
+ 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);
269
+ }
270
+
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);
276
+
277
+ if (terminalStates.length > 0) {
278
+ const deadlocks = [...states].filter(
279
+ (s) => !terminalStates.includes(s) && !terminalStates.some((term) => hasPath(graph, s, term)),
280
+ );
281
+ if (deadlocks.length > 0) {
282
+ push(
283
+ `deadlock state(s) in transition table \`${sc.name}\` (cannot reach any terminal state): ${deadlocks.join(', ')}`,
284
+ );
285
+ return items;
286
+ }
287
+ } else {
288
+ const trapped = [...states].filter((s) => s !== initial && !hasPath(graph, s, initial));
289
+ if (trapped.length > 0) {
290
+ push(
291
+ `trap state(s) in transition table \`${sc.name}\` (cannot return to the initial state \`${initial}\`): ${trapped.join(', ')}`,
292
+ );
293
+ return items;
294
+ }
295
+ }
296
+
297
+ return items;
298
+ }
299
+
300
+ export function validateTransitionsForRule(cap: string, rule: RuleIR): ValidationItem[] {
301
+ const items: ValidationItem[] = [];
302
+ for (const sc of rule.scenarios) {
303
+ const decision = resolveTransitionDecision(sc);
304
+ if (decision === 'conflict') {
305
+ items.push({
306
+ level: 'ERROR',
307
+ id: anchor(cap, rule),
308
+ message: `scenario \`${sc.name}\` carries conflicting @transitions and @no-transitions tags — keep exactly one`,
309
+ });
310
+ continue;
311
+ }
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));
317
+ }
318
+ return items;
319
+ }
320
+
321
+ /** Authoring self-check: transitions only (synthetic scenario). */
322
+ export function validateTransitionTableSelfCheck(
323
+ transitions: readonly TransitionEdge[],
324
+ scenarioName = 'authoring-check',
325
+ ): void {
326
+ const sc: ScenarioIR = {
327
+ name: scenarioName,
328
+ tags: [],
329
+ runnable: true,
330
+ stepCount: 3,
331
+ steps: [
332
+ { kind: 'given', text: 'state <from>' },
333
+ { kind: 'when', text: 'event <event>' },
334
+ { kind: 'then', text: 'state <to>' },
335
+ ],
336
+ statement: '',
337
+ isOutline: true,
338
+ examples: [
339
+ {
340
+ name: '',
341
+ headers: ['from', 'event', 'to'],
342
+ rows: transitions.map((t) => [t.from, t.event, t.to]),
343
+ },
344
+ ],
345
+ };
346
+ const rule = { reqId: 'r0', title: '', description: '', scenarios: [], tags: [] } as RuleIR;
347
+ const issues = validateTransitionScenario('authoring', rule, sc);
348
+ if (issues.length > 0) {
349
+ throw new Error(issues[0]?.message ?? 'invalid transition table');
350
+ }
351
+ }
352
+
353
+ export function parseTransitionExpr(expr: string): TransitionEdge {
354
+ const trimmed = expr.trim();
355
+ const m = trimmed.match(/^([^:]+):([\w-]+)(?:\[([^\]]+)\])?->(.+)$/u);
356
+ if (!m) {
357
+ throw new Error(`invalid transition expression: ${expr}`);
358
+ }
359
+ const from = m[1];
360
+ const event = m[2];
361
+ const guard = m[3];
362
+ const to = m[4];
363
+ if (from === undefined || event === undefined || to === undefined) {
364
+ throw new Error(`invalid transition expression: ${expr}`);
365
+ }
366
+ return {
367
+ from: from.trim(),
368
+ event: event.trim(),
369
+ to: to.trim(),
370
+ guard: guard?.trim() === '' ? undefined : guard?.trim(),
371
+ };
372
+ }
@@ -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 词;较长时拆多行便于审查,不使用 `- ` 列表前缀(会原样进入描述)。