@llman-sdd/core 0.8.2 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llman-sdd/core",
3
- "version": "0.8.2",
3
+ "version": "0.9.0",
4
4
  "description": "Pure domain logic for llman-sdd (config, gherkin specs, validation, templates)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -73,6 +73,9 @@ export function harvestUniqueNumbers(io: NextIdIo, root: string): IdHarvest {
73
73
  * failure degrades to the current tree only (best-effort, same grade as the
74
74
  * archive sweep) with the cause recorded in warnings; the same number visible
75
75
  * in more than one worktree raises a warning naming it and the worktrees.
76
+ * r35 (issue #8): `prunable` worktree entries and kept entries whose
77
+ * `llmanspec/` directory is absent count as empty trees — silently skipped,
78
+ * never warned; only real read errors reach warnings.
76
79
  */
77
80
  export function harvestAcrossWorktrees(git: GitLike, io: NextIdIo, root: string): IdHarvest {
78
81
  const warnings: string[] = [];
@@ -81,6 +84,7 @@ export function harvestAcrossWorktrees(git: GitLike, io: NextIdIo, root: string)
81
84
  const seen = new Set<string>();
82
85
  paths = [];
83
86
  for (const entry of worktreeList(git)) {
87
+ if (entry.prunable) continue;
84
88
  const path = entry.path.replace(/\/+$/u, '');
85
89
  if (!seen.has(path)) {
86
90
  seen.add(path);
@@ -94,7 +98,9 @@ export function harvestAcrossWorktrees(git: GitLike, io: NextIdIo, root: string)
94
98
  );
95
99
  }
96
100
  const trees = paths === null ? [root] : paths.map((p) => `${p}/llmanspec`);
97
- const perTree = trees.map((at) => ({ at, ...collectNumbers(io, at) }));
101
+ const perTree = trees
102
+ .filter((at) => io.isDirectory(at))
103
+ .map((at) => ({ at, ...collectNumbers(io, at) }));
98
104
  for (const tree of perTree) warnings.push(...tree.warnings);
99
105
  const where = new Map<number, Set<string>>();
100
106
  for (const tree of perTree) {
@@ -66,13 +66,39 @@ export function elevateLegacyBdd(data: unknown): { data: unknown; legacyBddEleva
66
66
  return { data: rec, legacyBddElevated: true };
67
67
  }
68
68
 
69
+ /**
70
+ * Removed-key stripping (config-schema r102): `specs.check_transitions` is
71
+ * gone — transition validation is tag-scoped per scenario (validation r104).
72
+ * Any value (booleans included) is dropped before schema parsing and the
73
+ * caller surfaces the migration warning. Pure — never mutates the input.
74
+ */
75
+ export function stripLegacyCheckTransitions(data: unknown): { data: unknown; stripped: boolean } {
76
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
77
+ return { data, stripped: false };
78
+ }
79
+ const rec = data as Record<string, unknown>;
80
+ const specs = rec['specs'];
81
+ if (typeof specs !== 'object' || specs === null || Array.isArray(specs)) {
82
+ return { data, stripped: false };
83
+ }
84
+ if (!('check_transitions' in specs)) return { data, stripped: false };
85
+ const nextSpecs: Record<string, unknown> = { ...(specs as Record<string, unknown>) };
86
+ delete nextSpecs['check_transitions'];
87
+ return { data: { ...rec, specs: nextSpecs }, stripped: true };
88
+ }
89
+
69
90
  /**
70
91
  * Load + validate, returning the parsed config and whether a legacy `bdd:`
71
92
  * section was elevated. The CLI surfaces the migration warning from the flag.
93
+ * `localeExplicit` reports whether the raw mapping carried a `locale` key at
94
+ * all — the schema default ('en') erases that distinction, but init needs it
95
+ * for the effective-locale precedence chain (init-generators r50).
72
96
  */
73
97
  export function loadConfigDetail(source: string): {
74
98
  config: SddConfig;
75
99
  legacyBddElevated: boolean;
100
+ legacyCheckTransitionsStripped: boolean;
101
+ localeExplicit: boolean;
76
102
  } {
77
103
  let data: unknown;
78
104
  try {
@@ -82,8 +108,11 @@ export function loadConfigDetail(source: string): {
82
108
  `YAML parse error: ${error instanceof Error ? error.message : String(error)}`,
83
109
  ]);
84
110
  }
111
+ const localeExplicit =
112
+ typeof data === 'object' && data !== null && !Array.isArray(data) && 'locale' in data;
85
113
  const elevated = elevateLegacyBdd(data);
86
- const result = sddConfigSchema.safeParse(elevated.data);
114
+ const stripped = stripLegacyCheckTransitions(elevated.data);
115
+ const result = sddConfigSchema.safeParse(stripped.data);
87
116
  if (!result.success) {
88
117
  const issues = result.error.issues.map((iss) => {
89
118
  const path = iss.path.map(String).join('/');
@@ -104,7 +133,12 @@ export function loadConfigDetail(source: string): {
104
133
  throw new ConfigValidationError([(error as Error).message]);
105
134
  }
106
135
  }
107
- return { config: result.data, legacyBddElevated: elevated.legacyBddElevated };
136
+ return {
137
+ config: result.data,
138
+ legacyBddElevated: elevated.legacyBddElevated,
139
+ legacyCheckTransitionsStripped: stripped.stripped,
140
+ localeExplicit,
141
+ };
108
142
  }
109
143
 
110
144
  export function loadConfig(source: string): SddConfig {
@@ -29,12 +29,6 @@ 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
- ),
38
32
  });
39
33
 
40
34
  export const archiveSchema = z.object({
@@ -141,6 +141,8 @@ export interface WorktreeEntry {
141
141
  head: string | null;
142
142
  /** Checked-out local branch (`refs/heads/` stripped); null when detached/bare. */
143
143
  branch: string | null;
144
+ /** `prunable` porcelain attribute: the worktree directory is missing or broken. */
145
+ prunable: boolean;
144
146
  }
145
147
 
146
148
  /** Parse `git worktree list --porcelain` into entries (r69 held-target detection). */
@@ -151,13 +153,15 @@ export function worktreeList(git: GitLike): WorktreeEntry[] {
151
153
  for (const line of out.split('\n')) {
152
154
  if (line.startsWith('worktree ')) {
153
155
  if (current !== null) entries.push(current);
154
- current = { path: line.slice('worktree '.length), head: null, branch: null };
156
+ current = { path: line.slice('worktree '.length), head: null, branch: null, prunable: false };
155
157
  } else if (current === null) {
156
158
  continue;
157
159
  } else if (line.startsWith('HEAD ')) {
158
160
  current.head = line.slice('HEAD '.length);
159
161
  } else if (line.startsWith('branch ')) {
160
162
  current.branch = line.slice('branch '.length).replace(/^refs\/heads\//u, '');
163
+ } else if (line.startsWith('prunable')) {
164
+ current.prunable = true;
161
165
  }
162
166
  // `detached` / `bare` marker lines leave branch null on purpose.
163
167
  }
package/src/index.ts CHANGED
@@ -64,12 +64,15 @@ export {
64
64
  export { stripLegacyHeaderLines } from './spec/migrateScope.ts';
65
65
  export {
66
66
  MIGRATIONS,
67
- findMigration,
68
- knownMigrationIds,
69
- isValidMigrationExpr,
70
- migrationPrompt,
67
+ compareVersions,
68
+ isValidVersion,
69
+ knownMigrationVersions,
71
70
  migrationOverviewLines,
72
- type MigrationEntry,
71
+ migrationPrompt,
72
+ parseVersionExpr,
73
+ resolveMigrations,
74
+ type MigrationDoc,
75
+ type MigrationItem,
73
76
  } from './project/migrations.ts';
74
77
  export {
75
78
  MIGRATE_KINDS,
@@ -98,11 +101,16 @@ export type {
98
101
  export { validateAllSpecs, validateCapability } from './validation/validate.ts';
99
102
  export { buildDuplicatesFor, formatTotals } from './validation/validate.ts';
100
103
  export {
104
+ ESCAPE_TRANSITIONS_TAG,
105
+ FORCE_TRANSITIONS_TAG,
106
+ TRANSITIONS_INTROSPECTION,
101
107
  isTransitionOutline,
102
108
  parseTransitionExpr,
109
+ resolveTransitionDecision,
110
+ type TransitionDecision,
103
111
  validateTransitionScenario,
104
112
  type TransitionEdge,
105
- } from './validation/transitions.ts';
113
+ } from './validation/xstateTransitions.ts';
106
114
  export { splitVerb } from './config/changeId.ts';
107
115
  export {
108
116
  checkChangeDoc,
@@ -212,6 +220,7 @@ export {
212
220
  export {
213
221
  TEMPLATES_ROOT,
214
222
  refreshSubRootBlocks,
223
+ resolveEffectiveLocale,
215
224
  runInit,
216
225
  updateFileWithMarkers,
217
226
  type InitIo,
package/src/init/init.ts CHANGED
@@ -8,7 +8,8 @@
8
8
  */
9
9
  import { join } from 'node:path';
10
10
 
11
- import { loadConfig } from '../config/load.ts';
11
+ import { loadConfigDetail } from '../config/load.ts';
12
+ import type { SddConfig } from '../config/schema.ts';
12
13
  import { writeSddState } from '../context/sddState.ts';
13
14
  import { renderTemplate } from '../templates/engine.ts';
14
15
  import { localeFallbacks } from '../templates/locale.ts';
@@ -80,6 +81,47 @@ function writeDefaultConfig(io: InitIo, locale: string): void {
80
81
  io.writeText('llmanspec/config.yaml', prependSchemaHeader(raw, LLMANSPEC_SCHEMA_URL));
81
82
  }
82
83
 
84
+ /**
85
+ * Effective-locale precedence (init-generators r50): an explicit `locale` key
86
+ * in the workspace config wins; a CLI option fills a missing key; the schema
87
+ * default ('en', already baked into config.locale here) is the built-in floor.
88
+ * Per-instance: callers resolve per workspace root, no cross-instance inheritance.
89
+ */
90
+ export function resolveEffectiveLocale(input: {
91
+ configLocale: string;
92
+ configLocaleExplicit: boolean;
93
+ optionLocale?: string;
94
+ }): string {
95
+ if (input.configLocaleExplicit) return input.configLocale;
96
+ return input.optionLocale ?? input.configLocale;
97
+ }
98
+
99
+ /**
100
+ * Config as rendered: resolve the effective locale per r50 and attach the
101
+ * missing-key WARNING when an existing config lacks the key (a freshly
102
+ * written default config always carries the key, so no warning there).
103
+ */
104
+ function withEffectiveLocale(
105
+ detail: ReturnType<typeof loadConfigDetail>,
106
+ optionLocale: string | undefined,
107
+ configExisted: boolean,
108
+ onWarning: ((message: string) => void) | undefined,
109
+ ): SddConfig {
110
+ const { config, localeExplicit } = detail;
111
+ if (localeExplicit) return config;
112
+ const effective = resolveEffectiveLocale({
113
+ configLocale: config.locale,
114
+ configLocaleExplicit: false,
115
+ optionLocale,
116
+ });
117
+ if (configExisted) {
118
+ onWarning?.(
119
+ `WARNING: config.yaml has no explicit 'locale' key; rendering fell back to '${effective}' (set locale: in config.yaml or pass --locale)`,
120
+ );
121
+ }
122
+ return { ...config, locale: effective };
123
+ }
124
+
83
125
  export interface InitResult {
84
126
  /** Skill dirs written, in render order ([] when skills injection is off). */
85
127
  skills: string[];
@@ -94,7 +136,7 @@ const SKILLS_BASE = '.agents/skills';
94
136
  function writeManagedBlocks(
95
137
  io: InitIo,
96
138
  templates: TemplateIo,
97
- config: ReturnType<typeof loadConfig>,
139
+ config: SddConfig,
98
140
  version: string,
99
141
  ): void {
100
142
  const vars = buildTemplateVars(config, version);
@@ -114,14 +156,26 @@ function writeManagedBlocks(
114
156
  export function runInit(
115
157
  io: InitIo,
116
158
  templates: TemplateIo,
117
- opts: { update: boolean; locale?: string; version: string; skills: boolean },
159
+ opts: {
160
+ update: boolean;
161
+ locale?: string;
162
+ version: string;
163
+ skills: boolean;
164
+ onWarning?: (message: string) => void;
165
+ },
118
166
  ): InitResult {
119
167
  io.mkdirp('llmanspec');
120
168
 
121
169
  // 1) config: create with defaults if missing, then always load.
122
170
  const configPath = 'llmanspec/config.yaml';
123
- if (!io.exists(configPath)) writeDefaultConfig(io, opts.locale ?? 'en');
124
- const config = loadConfig(io.readText(configPath));
171
+ const configExisted = io.exists(configPath);
172
+ if (!configExisted) writeDefaultConfig(io, opts.locale ?? 'en');
173
+ const config = withEffectiveLocale(
174
+ loadConfigDetail(io.readText(configPath)),
175
+ opts.locale,
176
+ configExisted,
177
+ opts.onWarning,
178
+ );
125
179
 
126
180
  // 1b) scaffold-state stamp: record the rendering version for drift notices
127
181
  // (version-awareness). Corrupt/missing state on later reads is silent-OK.
@@ -175,10 +229,20 @@ export function runInit(
175
229
  * (blocks only — no scaffold, no config touch, no skills). Returns false for
176
230
  * a missing config (discovery guarantees validity; a race is not fatal).
177
231
  */
178
- export function refreshSubRootBlocks(io: InitIo, templates: TemplateIo, version: string): boolean {
232
+ export function refreshSubRootBlocks(
233
+ io: InitIo,
234
+ templates: TemplateIo,
235
+ version: string,
236
+ onWarning?: (message: string) => void,
237
+ ): boolean {
179
238
  const configPath = 'llmanspec/config.yaml';
180
239
  if (!io.exists(configPath)) return false;
181
- const config = loadConfig(io.readText(configPath));
240
+ const config = withEffectiveLocale(
241
+ loadConfigDetail(io.readText(configPath)),
242
+ undefined,
243
+ true,
244
+ onWarning,
245
+ );
182
246
  writeManagedBlocks(io, templates, config, version);
183
247
  return true;
184
248
  }
@@ -1,14 +1,13 @@
1
1
  /**
2
- * Versioned migration registry (project migrate, drop-review-stamp-and-scope
3
- * follow-up): one entry per supported upgrade path. Prompt bodies are English
2
+ * Per-version migration registry (project migrate, migrate-prompt-per-version):
3
+ * each release declares its own migration items, and a range query `(from, to]`
4
+ * aggregates every registered version in between. Prompt bodies are English
4
5
  * per the house language convention (CLI output language) and are meant to be
5
6
  * handed to any agent verbatim — steps are executable commands, checks are
6
7
  * user-verifiable assertions. Pure: no IO, no clock.
7
8
  */
8
9
 
9
- export interface MigrationEntry {
10
- /** Registry key, shape `<from>-><to>` (exact-match lookup). */
11
- id: string;
10
+ export interface MigrationItem {
12
11
  title: string;
13
12
  /** Agent-executable commands, in order. */
14
13
  steps: readonly string[];
@@ -16,86 +15,153 @@ export interface MigrationEntry {
16
15
  checks: readonly string[];
17
16
  }
18
17
 
19
- export const MIGRATIONS: readonly MigrationEntry[] = [
18
+ export interface MigrationDoc {
19
+ /** Release version this migration set belongs to, `x.y.z`. */
20
+ version: string;
21
+ items: readonly MigrationItem[];
22
+ }
23
+
24
+ export const MIGRATIONS: readonly MigrationDoc[] = [
20
25
  {
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.',
26
+ version: '0.8.0',
27
+ items: [
28
+ {
29
+ title: 'Governance metadata retirement (`# reviewed-through:` stamp & `# scope:` header)',
30
+ steps: [
31
+ 'Run `llman-sdd project migrate strip-legacy-headers --dry-run` to preview the affected spec files.',
32
+ 'Run `llman-sdd project migrate strip-legacy-headers` to strip legacy `# scope:` / `# reviewed-through:` / `# capability:` header comment lines (idempotent).',
33
+ 'Run `llman-sdd init --update` to refresh the managed AGENTS blocks and agent skills.',
34
+ 'Run `llman-sdd validate --all --strict` — it must pass.',
35
+ ],
36
+ checks: [
37
+ 'No `# scope:` / `# reviewed-through:` header lines remain under `llmanspec/specs/**`.',
38
+ '`llman-sdd review` signal kinds are exactly unbound / locked / validate (no `stale`).',
39
+ '`llman-sdd validate --specs --json` output carries no `staleness` key.',
40
+ 'A subsequent `llman-sdd` invocation prints no version-drift NOTE.',
41
+ ],
42
+ },
34
43
  ],
35
44
  },
36
45
  {
37
- id: '0.7.5->0.8.0',
38
- title: 'Governance metadata retirement (`# reviewed-through:` stamp & `# scope:` header)',
39
- steps: [
40
- 'Run `llman-sdd project migrate strip-legacy-headers --dry-run` to preview the affected spec files.',
41
- 'Run `llman-sdd project migrate strip-legacy-headers` to strip legacy `# scope:` / `# reviewed-through:` / `# capability:` header comment lines (idempotent).',
42
- 'Run `llman-sdd init --update` to refresh the managed AGENTS blocks and agent skills.',
43
- 'Run `llman-sdd validate --all --strict` — it must pass.',
44
- ],
45
- checks: [
46
- 'No `# scope:` / `# reviewed-through:` header lines remain under `llmanspec/specs/**`.',
47
- '`llman-sdd review` signal kinds are exactly unbound / locked / validate (no `stale`).',
48
- '`llman-sdd validate --specs --json` output carries no `staleness` key.',
49
- 'A subsequent `llman-sdd` invocation prints no version-drift NOTE.',
46
+ version: '0.9.0',
47
+ items: [
48
+ {
49
+ title: 'Retire `# capability:` header; assign spec ids from paths (r101)',
50
+ steps: [
51
+ 'Run `llman-sdd project migrate strip-legacy-headers --dry-run` to preview spec header strips.',
52
+ 'Run `llman-sdd project migrate strip-legacy-headers` to remove `# capability:` (and any remaining `# scope:` / `# reviewed-through:`) lines.',
53
+ 'Ensure each `功能:` / `Feature:` title equals the assigned spec id (`llman-sdd list --specs` for ids).',
54
+ 'Run `llman-sdd init --update` to refresh managed skills and feature-contract guidance.',
55
+ 'Run `llman-sdd validate --all --strict` — it must pass.',
56
+ ],
57
+ checks: [
58
+ 'No `# capability:` lines remain under `llmanspec/specs/**`.',
59
+ 'Each spec file `功能:` title matches `llman-sdd show <spec-id>` id.',
60
+ '`llman-sdd list --specs` reports stable ids for flat and directory layouts.',
61
+ ],
62
+ },
63
+ {
64
+ title: '`specs.check_transitions` removed — transition validation is tag-scoped',
65
+ steps: [
66
+ 'Delete `specs.check_transitions` from `llmanspec/config.yaml` (any leftover value is stripped at load with a WARNING).',
67
+ 'Tag example tables that merely look like transition tables with `@no-transitions` on the scenario outline.',
68
+ 'Tag real transition tables whose column names miss the sniff aliases with `@transitions` to force validation.',
69
+ 'Run `llman-sdd spec transitions` for the authoritative aliases, tags and E1–E4 gates.',
70
+ 'Run `llman-sdd validate --all --strict` — it must pass.',
71
+ ],
72
+ checks: [
73
+ '`llmanspec/config.yaml` carries no `specs.check_transitions` key and loading prints no strip WARNING.',
74
+ 'Untagged example tables hitting at least two of the from/event/to alias families pass E1–E4.',
75
+ ],
76
+ },
77
+ {
78
+ title: 'init locale precedence chain and per-workspace `--update` sweep',
79
+ steps: [
80
+ 'Add an explicit `locale:` key to `llmanspec/config.yaml` (e.g. `locale: zh-Hans`) to pin the rendering language and silence the missing-key WARNING.',
81
+ 'Run `llman-sdd init --update` from any instance root — it refreshes managed blocks of every discovered root in the workspace (skills stay repo-root only).',
82
+ 'Run `llman-sdd validate --all --strict` — it must pass.',
83
+ ],
84
+ checks: [
85
+ '`llmanspec/config.yaml` carries an explicit `locale:` key; `init --update` prints no locale WARNING.',
86
+ 'Managed AGENTS.md blocks render in the configured locale across every workspace instance.',
87
+ ],
88
+ },
50
89
  ],
51
90
  },
52
91
  ];
53
92
 
93
+ const VERSION_RE = /^\d+\.\d+\.\d+$/u;
54
94
  const EXPR_RE = /^\d+\.\d+\.\d+->\d+\.\d+\.\d+$/u;
55
95
 
56
- /** Exact-match lookup; null when the expr is well-formed but unknown. */
57
- export function findMigration(expr: string): MigrationEntry | null {
58
- return MIGRATIONS.find((m) => m.id === expr) ?? null;
96
+ export function isValidVersion(version: string): boolean {
97
+ return VERSION_RE.test(version);
59
98
  }
60
99
 
61
- export function knownMigrationIds(): string[] {
62
- return MIGRATIONS.map((m) => m.id);
100
+ /** Numeric `x.y.z` comparison; negative when a < b, 0 when equal. */
101
+ export function compareVersions(a: string, b: string): number {
102
+ const [aMajor, aMinor, aPatch] = a.split('.').map(Number) as [number, number, number];
103
+ const [bMajor, bMinor, bPatch] = b.split('.').map(Number) as [number, number, number];
104
+ if (aMajor !== bMajor) return aMajor - bMajor;
105
+ if (aMinor !== bMinor) return aMinor - bMinor;
106
+ return aPatch - bPatch;
63
107
  }
64
108
 
65
- export function isValidMigrationExpr(expr: string): boolean {
66
- return EXPR_RE.test(expr);
109
+ /** Versions `(from, to]` that carry registered migrations, ascending. */
110
+ export function resolveMigrations(from: string, to: string): MigrationDoc[] {
111
+ return MIGRATIONS.filter(
112
+ (d) => compareVersions(d.version, from) > 0 && compareVersions(d.version, to) <= 0,
113
+ ).toSorted((a, b) => compareVersions(a.version, b.version));
67
114
  }
68
115
 
69
- /** Agent-facing playbook for one migration — deterministic, English. */
70
- export function migrationPrompt(entry: MigrationEntry): string {
71
- const steps = entry.steps.map((s, i) => `${i + 1}. ${s}`).join('\n');
72
- const checks = entry.checks.map((c) => `- [ ] ${c}`).join('\n');
73
- return [
74
- `# Migration playbook: ${entry.id}`,
75
- '',
76
- `${entry.title}.`,
77
- '',
78
- '## Steps',
79
- '',
80
- steps,
81
- '',
82
- '## Verification checklist',
83
- '',
84
- checks,
85
- '',
86
- ].join('\n');
116
+ /** Parse a deprecated `'<from>-><to>'` expression; null when malformed. */
117
+ export function parseVersionExpr(expr: string): { from: string; to: string } | null {
118
+ if (!EXPR_RE.test(expr)) return null;
119
+ const [from, to] = expr.split('->') as [string, string];
120
+ return { from, to };
121
+ }
122
+
123
+ export function knownMigrationVersions(): string[] {
124
+ return MIGRATIONS.map((d) => d.version);
125
+ }
126
+
127
+ /** Agent-facing playbook for a range — deterministic, English. */
128
+ export function migrationPrompt(from: string, to: string): string {
129
+ const docs = resolveMigrations(from, to);
130
+ if (docs.length === 0) {
131
+ return `No documented migrations for ${from} -> ${to}.\n`;
132
+ }
133
+ const sections = docs.map((doc) => {
134
+ const items = doc.items.map((item) => {
135
+ const steps = item.steps.map((s, i) => `${i + 1}. ${s}`).join('\n');
136
+ const checks = item.checks.map((c) => `- [ ] ${c}`).join('\n');
137
+ return [
138
+ `### ${item.title}`,
139
+ '',
140
+ '#### Steps',
141
+ '',
142
+ steps,
143
+ '',
144
+ '#### Verification checklist',
145
+ '',
146
+ checks,
147
+ '',
148
+ ].join('\n');
149
+ });
150
+ return [`## ${doc.version}`, '', items.join('\n')].join('\n');
151
+ });
152
+ return [`# Migration playbook: ${from} -> ${to}`, '', sections.join('\n---\n\n'), ''].join('\n');
87
153
  }
88
154
 
89
155
  /** Lines appended to the bare `project migrate` overview. */
90
156
  export function migrationOverviewLines(): string[] {
91
- const ids = knownMigrationIds()
92
- .map((id) => ` - ${id}`)
157
+ const versions = knownMigrationVersions()
158
+ .map((v) => ` - ${v}`)
93
159
  .join('\n');
94
160
  return [
95
161
  '',
96
162
  'Versioned migration playbooks (agent-readable, via `project migrate prompt`):',
97
- ids,
98
- "Usage: llman-sdd project migrate prompt --version-expr '<from>-><to>'",
163
+ versions,
164
+ 'Usage: llman-sdd project migrate prompt --from-version <from> --to-version <to>',
99
165
  'Mechanical spec-header strip: llman-sdd project migrate strip-legacy-headers [--dry-run]',
100
166
  ];
101
167
  }
@@ -22,7 +22,6 @@ 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;
26
25
  }
27
26
 
28
27
  export interface ReviewResult {
@@ -42,7 +41,7 @@ export function buildReview(input: ReviewInput, io: SpecIo): ReviewResult {
42
41
  signals.push({ kind, capability, count, detail });
43
42
  };
44
43
 
45
- const sweep = validateAllSpecs(entries, io, { checkTransitions: input.checkTransitions });
44
+ const sweep = validateAllSpecs(entries, io);
46
45
  const sorted = [...entries].toSorted((a, b) => a.fileName.localeCompare(b.fileName));
47
46
 
48
47
  for (const entry of sorted) {
@@ -8,7 +8,7 @@ import { assignSpecIds } from '../spec/assignSpecIds.ts';
8
8
  import type { CapabilityDoc } from '../spec/ir.ts';
9
9
  import { ruleHasRunnableScenario, specIdOf } from '../spec/ir.ts';
10
10
  import { buildReqRegistry } from '../spec/reqRegistry.ts';
11
- import { validateTransitionsForRule } from './transitions.ts';
11
+ import { validateTransitionsForRule } from './xstateTransitions.ts';
12
12
 
13
13
  export type ValidationLevel = 'ERROR' | 'WARNING' | 'INFO';
14
14
 
@@ -52,9 +52,7 @@ export function validateCapability(
52
52
  duplicatesFor: (reqId: string) => boolean,
53
53
  _io: SpecIo,
54
54
  opts: {
55
- strict?: boolean;
56
55
  duplicateSpecId?: boolean;
57
- checkTransitions?: boolean;
58
56
  } = {},
59
57
  ): SpecVerdict {
60
58
  const { doc } = entry;
@@ -134,11 +132,10 @@ export function validateCapability(
134
132
  );
135
133
  }
136
134
 
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
- }
135
+ // Transition-table gates (r104) are tag-scoped per scenario — no config switch.
136
+ for (const rule of rules) {
137
+ for (const item of validateTransitionsForRule(cap, rule)) {
138
+ push(item.level, item.id, item.message);
142
139
  }
143
140
  }
144
141
 
@@ -173,7 +170,7 @@ export function formatTotals(passed: number, failed: number, total: number): str
173
170
  export function validateAllSpecs(
174
171
  entries: readonly SpecEntry[],
175
172
  io: SpecIo,
176
- opts: { specsDir?: string; checkTransitions?: boolean } = {},
173
+ opts: { specsDir?: string } = {},
177
174
  ): ValidationReport {
178
175
  const specsDir = opts.specsDir ?? 'llmanspec/specs';
179
176
  const list: SpecEntry[] = entries.map((e) => ({ ...e }));
@@ -183,7 +180,6 @@ export function validateAllSpecs(
183
180
  const verdicts = list.map((e) =>
184
181
  validateCapability(e, duplicatesFor, io, {
185
182
  duplicateSpecId: duplicateSpecIds.has(specIdOf(e)),
186
- checkTransitions: opts.checkTransitions,
187
183
  }),
188
184
  );
189
185
 
@@ -1,6 +1,7 @@
1
1
  /**
2
- * XState-powered transition-table validation (validation r104): auto-discovery,
3
- * zero Tag, Examples-table driven gates E1–E4. Pure — no I/O.
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.
4
5
  */
5
6
  import { createGraph, addNode, addEdge, genBFS, hasPath } from '@statelyai/graph';
6
7
  import { createMachine } from 'xstate';
@@ -65,6 +66,57 @@ export function isTransitionOutline(sc: ScenarioIR): boolean {
65
66
  return false;
66
67
  }
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
+
68
120
  function placeholderVariants(col: string): string[] {
69
121
  return [`<${col}>`, `<${col.toLowerCase()}>`];
70
122
  }
@@ -216,15 +268,16 @@ export function validateTransitionScenario(
216
268
  outTargets.set(t.from, set);
217
269
  }
218
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.
219
275
  const terminalStates = [...states].filter((s) => (outTargets.get(s)?.size ?? 0) === 0);
220
276
 
221
277
  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
- }
278
+ const deadlocks = [...states].filter(
279
+ (s) => !terminalStates.includes(s) && !terminalStates.some((term) => hasPath(graph, s, term)),
280
+ );
228
281
  if (deadlocks.length > 0) {
229
282
  push(
230
283
  `deadlock state(s) in transition table \`${sc.name}\` (cannot reach any terminal state): ${deadlocks.join(', ')}`,
@@ -232,43 +285,34 @@ export function validateTransitionScenario(
232
285
  return items;
233
286
  }
234
287
  } 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
- }
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;
257
294
  }
258
295
  }
259
296
 
260
297
  return items;
261
298
  }
262
299
 
263
- export function validateTransitionsForRule(
264
- cap: string,
265
- rule: RuleIR,
266
- checkTransitions: boolean,
267
- ): ValidationItem[] {
268
- if (!checkTransitions) return [];
300
+ export function validateTransitionsForRule(cap: string, rule: RuleIR): ValidationItem[] {
269
301
  const items: ValidationItem[] = [];
270
302
  for (const sc of rule.scenarios) {
271
- if (!isTransitionOutline(sc)) continue;
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;
272
316
  items.push(...validateTransitionScenario(cap, rule, sc));
273
317
  }
274
318
  return items;