@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llman-sdd/core",
3
- "version": "0.8.1",
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": {
@@ -27,8 +27,10 @@
27
27
  "7z-wasm": "^1.2.0",
28
28
  "@cucumber/gherkin": "^42.0.1",
29
29
  "@cucumber/messages": "^34.2.1",
30
+ "@statelyai/graph": "^2.6.0",
30
31
  "@toon-format/toon": "^4.1.1",
31
32
  "nunjucks": "^3.2.4",
33
+ "xstate": "^5.33.2",
32
34
  "yaml": "^2.9.1",
33
35
  "zod": "^4.6.5"
34
36
  },
@@ -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 {
@@ -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
@@ -31,6 +31,7 @@ export type {
31
31
  ScenarioStep,
32
32
  SpecStructuralError,
33
33
  } from './spec/ir.ts';
34
+ export { assignSpecIds, featureRelPath, preferredSpecIdFromRel } from './spec/assignSpecIds.ts';
34
35
  export { ruleHasRunnableScenario, specIdOf } from './spec/ir.ts';
35
36
  export {
36
37
  SpecParseError,
@@ -63,12 +64,15 @@ export {
63
64
  export { stripLegacyHeaderLines } from './spec/migrateScope.ts';
64
65
  export {
65
66
  MIGRATIONS,
66
- findMigration,
67
- knownMigrationIds,
68
- isValidMigrationExpr,
69
- migrationPrompt,
67
+ compareVersions,
68
+ isValidVersion,
69
+ knownMigrationVersions,
70
70
  migrationOverviewLines,
71
- type MigrationEntry,
71
+ migrationPrompt,
72
+ parseVersionExpr,
73
+ resolveMigrations,
74
+ type MigrationDoc,
75
+ type MigrationItem,
72
76
  } from './project/migrations.ts';
73
77
  export {
74
78
  MIGRATE_KINDS,
@@ -96,6 +100,17 @@ export type {
96
100
  } from './validation/validate.ts';
97
101
  export { validateAllSpecs, validateCapability } from './validation/validate.ts';
98
102
  export { buildDuplicatesFor, formatTotals } from './validation/validate.ts';
103
+ export {
104
+ ESCAPE_TRANSITIONS_TAG,
105
+ FORCE_TRANSITIONS_TAG,
106
+ TRANSITIONS_INTROSPECTION,
107
+ isTransitionOutline,
108
+ parseTransitionExpr,
109
+ resolveTransitionDecision,
110
+ type TransitionDecision,
111
+ validateTransitionScenario,
112
+ type TransitionEdge,
113
+ } from './validation/xstateTransitions.ts';
99
114
  export { splitVerb } from './config/changeId.ts';
100
115
  export {
101
116
  checkChangeDoc,
@@ -205,6 +220,7 @@ export {
205
220
  export {
206
221
  TEMPLATES_ROOT,
207
222
  refreshSubRootBlocks,
223
+ resolveEffectiveLocale,
208
224
  runInit,
209
225
  updateFileWithMarkers,
210
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,70 +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.7.5->0.8.0',
22
- title: 'Governance metadata retirement (`# reviewed-through:` stamp & `# scope:` header)',
23
- steps: [
24
- 'Run `llman-sdd project migrate strip-legacy-headers --dry-run` to preview the affected spec files.',
25
- 'Run `llman-sdd project migrate strip-legacy-headers` to strip the legacy `# scope:` / `# reviewed-through:` header comment lines (idempotent).',
26
- 'Run `llman-sdd init --update` to refresh the managed AGENTS blocks and agent skills.',
27
- 'Run `llman-sdd validate --all --strict` — it must pass.',
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
+ },
28
43
  ],
29
- checks: [
30
- 'No `# scope:` / `# reviewed-through:` header lines remain under `llmanspec/specs/**`.',
31
- '`llman-sdd review` signal kinds are exactly unbound / locked / validate (no `stale`).',
32
- '`llman-sdd validate --specs --json` output carries no `staleness` key.',
33
- 'A subsequent `llman-sdd` invocation prints no version-drift NOTE.',
44
+ },
45
+ {
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
+ },
34
89
  ],
35
90
  },
36
91
  ];
37
92
 
93
+ const VERSION_RE = /^\d+\.\d+\.\d+$/u;
38
94
  const EXPR_RE = /^\d+\.\d+\.\d+->\d+\.\d+\.\d+$/u;
39
95
 
40
- /** Exact-match lookup; null when the expr is well-formed but unknown. */
41
- export function findMigration(expr: string): MigrationEntry | null {
42
- return MIGRATIONS.find((m) => m.id === expr) ?? null;
96
+ export function isValidVersion(version: string): boolean {
97
+ return VERSION_RE.test(version);
43
98
  }
44
99
 
45
- export function knownMigrationIds(): string[] {
46
- 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;
47
107
  }
48
108
 
49
- export function isValidMigrationExpr(expr: string): boolean {
50
- 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));
51
114
  }
52
115
 
53
- /** Agent-facing playbook for one migration — deterministic, English. */
54
- export function migrationPrompt(entry: MigrationEntry): string {
55
- const steps = entry.steps.map((s, i) => `${i + 1}. ${s}`).join('\n');
56
- const checks = entry.checks.map((c) => `- [ ] ${c}`).join('\n');
57
- return [
58
- `# Migration playbook: ${entry.id}`,
59
- '',
60
- `${entry.title}.`,
61
- '',
62
- '## Steps',
63
- '',
64
- steps,
65
- '',
66
- '## Verification checklist',
67
- '',
68
- checks,
69
- '',
70
- ].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');
71
153
  }
72
154
 
73
155
  /** Lines appended to the bare `project migrate` overview. */
74
156
  export function migrationOverviewLines(): string[] {
75
- const ids = knownMigrationIds()
76
- .map((id) => ` - ${id}`)
157
+ const versions = knownMigrationVersions()
158
+ .map((v) => ` - ${v}`)
77
159
  .join('\n');
78
160
  return [
79
161
  '',
80
162
  'Versioned migration playbooks (agent-readable, via `project migrate prompt`):',
81
- ids,
82
- "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>',
83
165
  'Mechanical spec-header strip: llman-sdd project migrate strip-legacy-headers [--dry-run]',
84
166
  ];
85
167
  }
@@ -1,3 +1,4 @@
1
+ import { assignSpecIds } from '../spec/assignSpecIds.ts';
1
2
  import { officialKeywords, officialKeywordsOrEn } from '../spec/keywords.ts';
2
3
  import { localeToGherkinLang, parseCapability } from '../spec/parser.ts';
3
4
  import { buildReqRegistry } from '../spec/reqRegistry.ts';
@@ -6,6 +7,7 @@ import { buildReqRegistry } from '../spec/reqRegistry.ts';
6
7
  * skeleton generation + global next req id. Pure, IO injected.
7
8
  */
8
9
  import { localeFallbacks } from '../templates/locale.ts';
10
+ import type { SpecEntry } from '../validation/validate.ts';
9
11
 
10
12
  export interface SpecHelperIo {
11
13
  exists(path: string): boolean;
@@ -16,13 +18,8 @@ export interface SpecHelperIo {
16
18
  listDir(path: string): string[];
17
19
  }
18
20
 
19
- interface ParsedEntry {
20
- fileName: string;
21
- doc: ReturnType<typeof parseCapability>;
22
- }
23
-
24
- function collectSpecEntries(io: SpecHelperIo, specsDir: string): ParsedEntry[] {
25
- const entries: ParsedEntry[] = [];
21
+ function collectSpecEntries(io: SpecHelperIo, specsDir: string): SpecEntry[] {
22
+ const entries: SpecEntry[] = [];
26
23
  const walk = (dir: string): void => {
27
24
  if (!io.exists(dir)) return;
28
25
  for (const name of io.listDir(dir)) {
@@ -35,6 +32,7 @@ function collectSpecEntries(io: SpecHelperIo, specsDir: string): ParsedEntry[] {
35
32
  }
36
33
  };
37
34
  walk(specsDir);
35
+ assignSpecIds(entries, specsDir);
38
36
  return entries;
39
37
  }
40
38
 
@@ -63,8 +61,8 @@ export function skeletonContent(capability: string, reqId: string, locale: strin
63
61
  const language = officialKeywords(mapped) !== null ? mapped : 'en';
64
62
  const kw = officialKeywordsOrEn(language);
65
63
  const header = zh
66
- ? `# language: ${language}\n# capability: ${capability}\n# purpose: TODO: 一句话描述该能力与其目的。`
67
- : `# language: ${language}\n# capability: ${capability}\n# purpose: TODO: Describe this capability and its purpose.`;
64
+ ? `# language: ${language}\n# purpose: TODO: 一句话描述该能力与其目的。`
65
+ : `# language: ${language}\n# purpose: TODO: Describe this capability and its purpose.`;
68
66
  const ruleDesc = zh ? 'TODO: 需求描述(自由文本)。' : 'TODO: requirement statement (free text).';
69
67
  // Skeleton placeholder prose is not vocabulary — the zh/en copy stays; keywords do not.
70
68
  const steps = zh
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Global spec-id assignment (spec-parsing r101): after discovering all
3
+ * `.feature` files under one `llmanspec/specs/` instance, each entry gets a
4
+ * unique `specId` from path preference + collision disambiguation.
5
+ */
6
+ /** Minimal entry shape for id assignment (avoids validation↔spec cycle). */
7
+ export interface SpecIdAssignable {
8
+ fileName: string;
9
+ specId?: string;
10
+ }
11
+
12
+ /** `rel` path relative to specs root (POSIX slashes, includes `.feature`). */
13
+ export function featureRelPath(fileName: string, specsDir: string): string {
14
+ const norm = (p: string): string => p.replace(/\\/g, '/').replace(/\/$/u, '');
15
+ const root = norm(specsDir);
16
+ let rel = norm(fileName);
17
+ const prefix = `${root}/`;
18
+ if (rel.startsWith(prefix)) rel = rel.slice(prefix.length);
19
+ return rel;
20
+ }
21
+
22
+ /** Preference id before instance-wide collision resolution (r101). */
23
+ export function preferredSpecIdFromRel(rel: string): string {
24
+ const withoutExt = rel.replace(/\.feature$/u, '');
25
+ const parts = withoutExt.split('/');
26
+ const stem = parts.at(-1) ?? '';
27
+ if (parts.length === 1) return stem;
28
+ if (parts.length === 2 && parts[0] === stem) return stem;
29
+ return withoutExt;
30
+ }
31
+
32
+ function finalSpecIdFromRel(rel: string, preferredCount: number): string {
33
+ const preferred = preferredSpecIdFromRel(rel);
34
+ if (preferredCount === 1) return preferred;
35
+ return rel.replace(/\.feature$/u, '');
36
+ }
37
+
38
+ /**
39
+ * Mutates `entries[].specId`. Returns spec ids that appear on more than one
40
+ * file after assignment (layout error).
41
+ */
42
+ export function assignSpecIds(entries: SpecIdAssignable[], specsDir: string): Set<string> {
43
+ const rels = entries.map((entry) => ({
44
+ entry,
45
+ rel: featureRelPath(entry.fileName, specsDir),
46
+ }));
47
+
48
+ const preferredCounts = new Map<string, number>();
49
+ for (const { rel } of rels) {
50
+ const preferred = preferredSpecIdFromRel(rel);
51
+ preferredCounts.set(preferred, (preferredCounts.get(preferred) ?? 0) + 1);
52
+ }
53
+
54
+ for (const { entry, rel } of rels) {
55
+ const preferred = preferredSpecIdFromRel(rel);
56
+ const count = preferredCounts.get(preferred) ?? 0;
57
+ entry.specId = finalSpecIdFromRel(rel, count);
58
+ }
59
+
60
+ const byId = new Map<string, number>();
61
+ for (const { entry } of rels) {
62
+ const id = entry.specId ?? '';
63
+ byId.set(id, (byId.get(id) ?? 0) + 1);
64
+ }
65
+ return new Set([...byId.entries()].filter(([, n]) => n > 1).map(([id]) => id));
66
+ }