@llman-sdd/core 0.11.0 → 0.12.1

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 (112) hide show
  1. package/package.json +6 -3
  2. package/src/archive/freeze.ts +0 -13
  3. package/src/archive/frozenCard.ts +1 -10
  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 +1 -38
  11. package/src/config/changeId.ts +0 -2
  12. package/src/config/load.ts +0 -4
  13. package/src/config/schema.ts +24 -0
  14. package/src/git/spawnGit.ts +0 -3
  15. package/src/hints/jitHints.ts +82 -0
  16. package/src/index.ts +455 -3
  17. package/src/init/defaultConfig.ts +2 -0
  18. package/src/init/init.ts +61 -20
  19. package/src/init/uncommentConfig.ts +909 -0
  20. package/src/locale.ts +0 -2
  21. package/src/project/migrateNotes.ts +0 -9
  22. package/src/project/migrations.ts +70 -0
  23. package/src/report/graph/analysis.ts +0 -4
  24. package/src/report/graph/nodes.ts +0 -6
  25. package/src/report/show.ts +7 -23
  26. package/src/report/specHelpers.ts +10 -14
  27. package/src/review/review.ts +0 -12
  28. package/src/spec/assignSpecIds.ts +0 -3
  29. package/src/spec/authoring.ts +14 -26
  30. package/src/spec/ir.ts +14 -5
  31. package/src/spec/keywords.ts +0 -2
  32. package/src/spec/machineKey.ts +49 -0
  33. package/src/spec/migrateNative.ts +4 -18
  34. package/src/spec/parser.ts +10 -19
  35. package/src/spec/reqRef.ts +135 -0
  36. package/src/studio/changeScope.ts +50 -0
  37. package/src/studio/changeScopeDiff.ts +195 -0
  38. package/src/studio/contracts.ts +493 -0
  39. package/src/studio/decisionTree.ts +206 -0
  40. package/src/studio/deeplink.ts +116 -0
  41. package/src/studio/demos.ts +167 -0
  42. package/src/studio/diff.ts +494 -0
  43. package/src/studio/drift.ts +738 -0
  44. package/src/studio/extract.ts +360 -0
  45. package/src/studio/featureSync.ts +592 -0
  46. package/src/studio/forest.ts +570 -0
  47. package/src/studio/index.ts +32 -0
  48. package/src/studio/model.ts +254 -0
  49. package/src/studio/revisions.ts +476 -0
  50. package/src/studio/search.ts +337 -0
  51. package/src/studio/store.ts +811 -0
  52. package/src/studio/sync.ts +912 -0
  53. package/src/studio/textfold.ts +72 -0
  54. package/src/studio/time.ts +107 -0
  55. package/src/studio/validate.ts +363 -0
  56. package/src/templates/embedded.ts +4 -6
  57. package/src/templates/engine.ts +1 -1
  58. package/src/templates/skills.ts +71 -49
  59. package/src/theorems/guard.ts +52 -0
  60. package/src/theorems/index.ts +56 -0
  61. package/src/theorems/migrate.ts +133 -0
  62. package/src/theorems/schema.ts +67 -0
  63. package/src/theorems/scope.ts +68 -0
  64. package/src/theorems/serialize.ts +60 -0
  65. package/src/theorems/transactionMachine.ts +247 -0
  66. package/src/theorems/validate.ts +141 -0
  67. package/src/util/nextNumber.ts +0 -2
  68. package/src/validation/changeCheck.ts +0 -24
  69. package/src/validation/flowAndNesting.ts +434 -0
  70. package/src/validation/harness.ts +108 -65
  71. package/src/validation/validate.ts +26 -12
  72. package/src/validation/xstateTransitions.ts +483 -184
  73. package/templates/zh-Hans/llmanspec-agents-stub.md +17 -2
  74. package/templates/zh-Hans/skills/llman-sdd-autopilot/SKILL.md +34 -0
  75. package/templates/zh-Hans/skills/llman-sdd-change/SKILL.md +44 -0
  76. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/archive.md +15 -0
  77. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/draft.md +9 -0
  78. package/templates/zh-Hans/skills/llman-sdd-review/SKILL.md +71 -0
  79. package/templates/zh-Hans/skills/llman-sdd-specs/SKILL.md +70 -0
  80. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/compact.md +12 -0
  81. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/doctor.md +26 -0
  82. package/templates/zh-Hans/skills/llman-sdd-specs/references/graph-dsl.md +33 -0
  83. package/templates/zh-Hans/skills/llman-sdd-studio/SKILL.md +33 -0
  84. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/collab.md +20 -0
  85. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/drift.md +52 -0
  86. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/onboard.md +33 -0
  87. package/templates/zh-Hans/units/skills/cli-footer.md +2 -2
  88. package/templates/zh-Hans/agents-root-stub.md +0 -9
  89. package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +0 -69
  90. package/templates/zh-Hans/skills/llman-sdd-apply.md +0 -116
  91. package/templates/zh-Hans/skills/llman-sdd-arch-review.md +0 -58
  92. package/templates/zh-Hans/skills/llman-sdd-archive.md +0 -78
  93. package/templates/zh-Hans/skills/llman-sdd-continue.md +0 -34
  94. package/templates/zh-Hans/skills/llman-sdd-draft.md +0 -53
  95. package/templates/zh-Hans/skills/llman-sdd-explore.md +0 -63
  96. package/templates/zh-Hans/skills/llman-sdd-ff.md +0 -34
  97. package/templates/zh-Hans/skills/llman-sdd-graph.md +0 -56
  98. package/templates/zh-Hans/skills/llman-sdd-propose.md +0 -106
  99. package/templates/zh-Hans/skills/llman-sdd-quick.md +0 -40
  100. package/templates/zh-Hans/skills/llman-sdd-research.md +0 -35
  101. package/templates/zh-Hans/skills/llman-sdd-specs-compact.md +0 -42
  102. package/templates/zh-Hans/skills/llman-sdd-validate.md +0 -28
  103. package/templates/zh-Hans/skills/llman-sdd-verify.md +0 -77
  104. package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +0 -83
  105. package/templates/zh-Hans/units/skills/ethics-governance.md +0 -6
  106. package/templates/zh-Hans/units/skills/git-native-flow.md +0 -56
  107. package/templates/zh-Hans/units/skills/human-readable-summary.md +0 -9
  108. package/templates/zh-Hans/units/skills/stage-guard.md +0 -17
  109. package/templates/zh-Hans/units/skills/structured-protocol.md +0 -19
  110. package/templates/zh-Hans/units/skills/validation-hints.md +0 -20
  111. package/templates/zh-Hans/units/skills/version-drift.md +0 -3
  112. package/templates/zh-Hans/units/spec/feature-contract.md +0 -8
package/src/locale.ts CHANGED
@@ -15,8 +15,6 @@ export function normalizeLocale(value: string): string {
15
15
  const lower = trimmed.toLowerCase();
16
16
  if (lower === 'zh' || lower.startsWith('zh-hans') || lower === 'zh-cn') return DEFAULT_LOCALE;
17
17
  if (lower.startsWith('en')) return DEFAULT_LOCALE;
18
- // Unknown values normalize instead of passing through: with no English pack,
19
- // an unlisted locale would render nothing at all.
20
18
  return DEFAULT_LOCALE;
21
19
  }
22
20
 
@@ -1,12 +1,3 @@
1
- // Collaboration notes for `project migrate` — the predecessor (Rust ≤0.0.78) shipped two
2
- // one-shot migrations (toon2features / specs-flatten); this tool deliberately ships
3
- // none (peripheral-commands r35: the command outputs an explanation and never
4
- // migrates). Porting the implementations was surveyed on 2026-09-23 and
5
- // declined: specs-flatten fights this repo's directory-style coexistence direction,
6
- // and toon2features has no confirmed audience. Instead, `--kind <x>` prints
7
- // the equivalent manual-migration guidance so old command forms get useful
8
- // stdout instead of an unknown-option error.
9
-
10
1
  export const MIGRATE_KINDS = ['toon2features', 'specs-flatten'] as const;
11
2
 
12
3
  export type MigrateKind = (typeof MIGRATE_KINDS)[number];
@@ -239,6 +239,76 @@ export const MIGRATIONS: readonly MigrationDoc[] = [
239
239
  },
240
240
  ],
241
241
  },
242
+ {
243
+ version: '0.12.0',
244
+ items: [
245
+ {
246
+ title: 'Graph DSL: whitelist English tags, zh-Hans-only columns, and 0-step outlines',
247
+ steps: [
248
+ 'Rewrite every graph Examples table under `llmanspec/specs/**`. Put exactly one whitelist tag on the scenario: `@state` (state machine), `@flow` (flowchart), `@nodes` (node attributes), or `@decision_table` (decision table). Untagged tables are no longer extracted.',
249
+ 'Use zh-Hans headers only: `@state` → `当前 | 触发 | 目标` (optional `条件 | 动作 | 执行方 | 边类型 | 元信息`); `@flow` → `当前步骤 | 分支 | 下一步` (optional `条件 | 动作 | 执行方 | 边类型 | 元信息 | 验证`); `@nodes` → `节点` plus optional `类型 | 引用 | 执行方 | 人类说明 | 完成标准`. Delete Given/When/Then placeholder steps on dialect outlines.',
250
+ 'Remove `@transitions` / `@states` / `@no-transitions` / `@ignore` / `@decision`. Replace `from/event/to/guard`, `初始状态/事件/目标状态/守卫`, `状态/子机/网关`, and remove the legacy `落地锚点` (`bind`) column on `@nodes`. Nest pointer column is `引用` with `@req:rN` or `@req:rN#<scene>`.',
251
+ 'Run `llman-sdd spec transitions`, `llman-sdd validate --specs --strict`, and `llman-sdd studio validate --specs`.',
252
+ ],
253
+ checks: [
254
+ 'No `@transitions`, `@states`, `@no-transitions`, `@ignore`, or `落地锚点` remain under `llmanspec/specs/**`.',
255
+ '`llman-sdd spec transitions` prints `@flow @state @nodes @decision_table` and `当前` / `触发` / `目标`, and does not list `from` as a legal alias.',
256
+ '`llman-sdd validate --specs --strict` and `llman-sdd studio validate --specs` exit 0.',
257
+ ],
258
+ },
259
+ {
260
+ title: '5 orthogonal domain skills and managed `llmanspec/AGENTS.md` block',
261
+ steps: [
262
+ 'Run `llman-sdd init --update`. It atomically replaces legacy `llman-sdd-*` skills with the 5 orthogonal hubs (`llman-sdd-specs`, `llman-sdd-studio`, `llman-sdd-change`, `llman-sdd-review`, `llman-sdd-autopilot`), preserves custom non-`llman-sdd-` skills, and refreshes `llmanspec/AGENTS.md`.',
263
+ 'Optionally configure `review.handoff_mode` (`ask` default | `inline` | `file`) and `review.handoff_file` in `llmanspec/config.yaml` for single-session independent-reviewer handoffs.',
264
+ 'Run `llman-sdd init --check` to confirm skill and CLI minor-version parity.',
265
+ ],
266
+ checks: [
267
+ '`.agents/skills/` contains the 5 `llman-sdd-*` hubs (with `playbooks/` and `references/`) and zero obsolete `llman-sdd-explore`/`propose`/`apply`/`verify`/`archive` directories.',
268
+ 'All non-`llman-sdd-` custom skills remain untouched.',
269
+ '`llman-sdd init --check` exits 0.',
270
+ ],
271
+ },
272
+ {
273
+ title: 'Unified requirement coordinates (`@llmanspec:req:rN[#<scene>]` and `machineKey`)',
274
+ steps: [
275
+ 'Replace any legacy `@llmanspec:machine:<key>` or bare `@llmanspec:rN` source comments with `@llmanspec:req:rN`, `@llmanspec:req:rN#<scene>`, or `@llmanspec:req:rN#"<scene with spaces>"`.',
276
+ 'Note `machineKey` in Studio now uses `rN#<scene>` (or `draft:<capability>#<scene>`). If stale local `.llman-sdd/studio/states/*.json` drafts use old 3-segment keys and have no pending edits, prune them with `llman-sdd studio state prune --all`.',
277
+ 'Run `llman-sdd studio validate --specs` and `llman-sdd validate --specs --strict`.',
278
+ ],
279
+ checks: [
280
+ 'No `@llmanspec:machine:` or bare `@llmanspec:rN` source comments remain.',
281
+ '`llman-sdd studio validate --specs` exits 0.',
282
+ ],
283
+ },
284
+ {
285
+ title: 'Verification gates and `.uncomment.toml` idempotent protection',
286
+ steps: [
287
+ 'Note `llman-sdd validate --check` now automatically runs `llman-sdd theorem check` alongside `specs.check_command` (and optional `specs.check_dangling_bdd_command`).',
288
+ 'Optionally set `specs.check_dangling_bdd_command` in `llmanspec/config.yaml` to enforce unused-step checks during `validate --check` and `change archive`.',
289
+ 'If the repository already has `.uncomment.toml` (or `.uncommentrc.toml` / `uncomment.toml`), `llman-sdd init --update` idempotently adds `@llmanspec:` and `LLMANSPEC:` to `[global].preserve_patterns` and excludes `llmanspec/**`, `.llman-sdd/**`, and `.agents/skills/llman-sdd-*/**`.',
290
+ ],
291
+ checks: [
292
+ '`llman-sdd validate --check` exits 0.',
293
+ 'If `.uncomment.toml` is present, running `uncomment --check .` preserves `@llmanspec:` anchors and `LLMANSPEC:` markers.',
294
+ ],
295
+ },
296
+ {
297
+ title:
298
+ 'Human Theorems: single-file YAML replaces Markdown + lock manifest (0.12-dev early adopters only; v0.11.0 repos without `llmanspec/theorems/*.md` skip this)',
299
+ steps: [
300
+ 'Check whether `llmanspec/theorems/*.md` or `.theorems.lock.json` exists. If absent (standard v0.11.0 repositories), skip this item completely.',
301
+ 'If `llmanspec/theorems/*.md` exists, a human MUST run `llman-sdd theorem migrate` and `llman-sdd theorem lock` interactively in a TTY (agents must never modify or migrate theorems non-interactively).',
302
+ 'Run `llman-sdd theorem check --strict` — it must exit 0 with `S2_LOCKED_STRONG`.',
303
+ ],
304
+ checks: [
305
+ '`llmanspec/theorems/**` contains only `.yaml` files; no `*.md` and no `.theorems.lock.json` remain.',
306
+ '`llman-sdd theorem list --json` lists every migrated theorem with `severity`, `status`, `scope`, and `verify`.',
307
+ '`llman-sdd theorem check --strict` exits 0.',
308
+ ],
309
+ },
310
+ ],
311
+ },
242
312
  ];
243
313
 
244
314
  const VERSION_RE = /^\d+\.\d+\.\d+$/u;
@@ -37,16 +37,12 @@ export function buildDefaultNodes(
37
37
  maxScanDepth?: number,
38
38
  ): GraphNode[] {
39
39
  const nodes = collectNodes(io, root, kinds, maxScanDepth);
40
- // depth 0 = 仅 scope 内节点(human-readable graph):不拉取任何依赖 target。
41
40
  if (depth <= 0) return nodes;
42
41
 
43
42
  const nodeIds = new Set(nodes.map((n) => n.id));
44
43
  const all = collectNodes(io, root, ['active', 'archived'], maxScanDepth);
45
44
  const allMap = new Map(all.map((n) => [n.id, n]));
46
45
 
47
- // BFS 沿 depends_on 从 scope 根展开 depth 层(depth 1 即现状的一层依赖拉取;
48
- // N >= 2 递归展开)。拉入的依赖 target 若不在 scope 作为节点保留
49
- // (present/archived 标记由 allMap 已知节点提供,未知 id 记为 phantom)。
50
46
  let frontier = nodes.filter((n) => n.present).map((n) => n.id);
51
47
  for (let level = 0; level < depth && frontier.length > 0; level++) {
52
48
  const next: string[] = [];
@@ -14,8 +14,6 @@ export function collectActiveNodes(
14
14
  root: string,
15
15
  maxScanDepth?: number,
16
16
  ): GraphNode[] {
17
- // T23: the active-change traversal is the shared walk (change/collect) —
18
- // graph nodes are just its (dir, name) pairs mapped to the node shape.
19
17
  const out: GraphNode[] = [];
20
18
  walkActiveChangeDirs(
21
19
  io,
@@ -83,7 +81,6 @@ export function collectNodes(
83
81
  export function proposalFor(io: GraphFsIo, root: string, node: GraphNode): string {
84
82
  if (node.archived) {
85
83
  const archiveDir = `${root}/${CHANGES_DIR}/archive`;
86
- // latest matching strategy: pick the newest date-prefixed dir
87
84
  let best = '';
88
85
  let bestDate = '';
89
86
  for (const name of io.listDir(archiveDir)) {
@@ -97,8 +94,6 @@ export function proposalFor(io: GraphFsIo, root: string, node: GraphNode): strin
97
94
  }
98
95
  const p = `${archiveDir}/${best}/proposal.md`;
99
96
  if (io.exists(p)) return io.readText(p);
100
- // Frozen card fallback (r54): dir gone, body in cold backup — read the
101
- // card (frontmatter incl. depends_on) so dependency edges survive freeze.
102
97
  const card = isFrozenCard(best) ? `${archiveDir}/${best}` : `${archiveDir}/${best}.yaml`;
103
98
  if (io.exists(card)) return io.readText(card);
104
99
  return '';
@@ -111,7 +106,6 @@ export function proposalFor(io: GraphFsIo, root: string, node: GraphNode): strin
111
106
  const child = `${dir}/${name}`;
112
107
  if (!io.isDirectory(child)) continue;
113
108
  if (io.exists(`${child}/proposal.md`)) {
114
- // leaf change dir — do not descend further
115
109
  if (name === node.id) found.push(`${child}/proposal.md`);
116
110
  continue;
117
111
  }
@@ -53,7 +53,6 @@ export function showChangeJson(
53
53
  ? countTasks(io.readText(`${dir}/tasks.md`))
54
54
  : { completed: 0, total: 0 };
55
55
 
56
- // predecessor parity: show works (gracefully degraded gates) outside a git repo.
57
56
  let cleanTree = false;
58
57
  let current = null;
59
58
  try {
@@ -64,8 +63,6 @@ export function showChangeJson(
64
63
  }
65
64
  const onBoundBranch = binding !== null && current === binding.branch;
66
65
 
67
- // specs landing: bound changes must have touched llmanspec/specs/ since base
68
- // (r119: judged under THIS instance's prefix, not the repo-root literal)
69
66
  const specsPrefix = deps.specsPrefix ?? DEFAULT_SPECS_PREFIX;
70
67
  let landedOnBranch = false;
71
68
  if (binding !== null) {
@@ -73,24 +70,11 @@ export function showChangeJson(
73
70
  }
74
71
  const needsSpecsChange = readNeedsSpecsChange(extractFrontmatter(proposal));
75
72
 
76
- const tasksDone = total > 0 && completed >= total;
73
+ const tasksDone = !hasTasks || total === 0 || completed >= total;
77
74
  const specReport = validateAllSpecs(discoverSpecs(deps.specsDir, io));
78
- const validateOk = !specReport.failed && (total === 0 || tasksDone);
75
+ const validateOk = !specReport.failed && tasksDone;
79
76
 
80
- const stageHint = !hasDesign
81
- ? 'add design.md (current: draft → designed)'
82
- : !hasTasks
83
- ? 'add tasks.md (current: designed → planned)'
84
- : stage === 'planned'
85
- ? 'bind via `llman-sdd change start <id>` (planned → full)'
86
- : '';
87
- // T34: a missing tasks.md has nothing to check off — the hint says so
88
- // instead of the legacy "complete or check off remaining tasks".
89
- const tasksHint = hasTasks
90
- ? total > 0 && completed < total
91
- ? `${total - completed} unchecked tasks`
92
- : 'complete or check off remaining tasks'
93
- : 'no tasks.md — seal-off needs no checked tasks';
77
+ const tasksHint = tasksDone ? '' : `${total - completed} unchecked tasks`;
94
78
 
95
79
  const gateChecks = [
96
80
  {
@@ -105,8 +89,8 @@ export function showChangeJson(
105
89
  },
106
90
  {
107
91
  name: 'stage-complete',
108
- pass: hasDesign && hasTasks,
109
- hint: hasDesign && hasTasks ? '' : (stageHint as string),
92
+ pass: true,
93
+ hint: '',
110
94
  },
111
95
  {
112
96
  name: 'specs-landed',
@@ -118,8 +102,8 @@ export function showChangeJson(
118
102
  },
119
103
  {
120
104
  name: 'tasks-done',
121
- pass: tasksDone && total > 0,
122
- hint: tasksDone && total > 0 ? '' : tasksHint,
105
+ pass: tasksDone,
106
+ hint: tasksHint,
123
107
  },
124
108
  {
125
109
  name: 'validate',
@@ -6,9 +6,9 @@ import { localeFallbacks } from '../locale.ts';
6
6
  import { assignSpecIds } from '../spec/assignSpecIds.ts';
7
7
  import { officialKeywords, officialKeywordsOrEn } from '../spec/keywords.ts';
8
8
  import { localeToGherkinLang, parseCapability } from '../spec/parser.ts';
9
+ import { allocateNextReqId } from '../spec/reqRef.ts';
9
10
  import { buildReqRegistry } from '../spec/reqRegistry.ts';
10
11
  import { type FsPort } from '../util/fsPort.ts';
11
- import { nextNumber } from '../util/nextNumber.ts';
12
12
  import { discoverFeatureFiles } from '../validation/discover.ts';
13
13
  import type { SpecEntry } from '../validation/validate.ts';
14
14
 
@@ -18,7 +18,6 @@ export type SpecHelperIo = Pick<
18
18
  >;
19
19
 
20
20
  function collectSpecEntries(io: SpecHelperIo, specsDir: string): SpecEntry[] {
21
- // T24: shared discovery — identical ordering/norm as the hash walk.
22
21
  const normDir = specsDir.replace(/\\/g, '/').replace(/\/$/u, '');
23
22
  const entries = discoverFeatureFiles(normDir, io).map((path) => ({
24
23
  fileName: path,
@@ -28,6 +27,14 @@ function collectSpecEntries(io: SpecHelperIo, specsDir: string): SpecEntry[] {
28
27
  return entries;
29
28
  }
30
29
 
30
+ /**
31
+ * Every `@req:` id occupied in the global registry (scan order) — the input
32
+ * for `allocateNextReqId` at every write-back surface.
33
+ */
34
+ export function usedReqIds(io: SpecHelperIo, specsDir: string): string[] {
35
+ return [...buildReqRegistry(collectSpecEntries(io, specsDir)).byId.keys()];
36
+ }
37
+
31
38
  /**
32
39
  * Max+1 over the requirement handles (`@req` on `规则:` headers) only — the id
33
40
  * set comes from the global req registry fed with the parsed specs. Deliberately
@@ -37,20 +44,11 @@ function collectSpecEntries(io: SpecHelperIo, specsDir: string): SpecEntry[] {
37
44
  * reused. See change `align-next-req-id-max-plus-one` design for the trade-off.
38
45
  */
39
46
  export function nextReqId(io: SpecHelperIo, specsDir: string): string {
40
- const entries = collectSpecEntries(io, specsDir);
41
- const used = [...buildReqRegistry(entries).byId.keys()].map((reqId) =>
42
- Math.trunc(Number(reqId.replace(/^r/u, ''))),
43
- );
44
- // SSOT: the numeric-id allocator primitive (unify-numeric-id-allocation) —
45
- // never a second max+1 fold. Same source as change sequence numbers.
46
- return `r${nextNumber(used)}`;
47
+ return allocateNextReqId(usedReqIds(io, specsDir));
47
48
  }
48
49
 
49
50
  export function skeletonContent(capability: string, reqId: string, locale: string): string {
50
51
  const zh = localeFallbacks(locale)[0] === 'zh-Hans';
51
- // r7: the `# language:` header derives from the locale mapping — never a
52
- // second hardcoded caliber. Table-less locales fall back to en wholesale
53
- // (header + keywords same-source) so the skeleton stays parseable.
54
52
  const mapped = localeToGherkinLang(locale);
55
53
  const language = officialKeywords(mapped) !== null ? mapped : 'en';
56
54
  const kw = officialKeywordsOrEn(language);
@@ -58,11 +56,9 @@ export function skeletonContent(capability: string, reqId: string, locale: strin
58
56
  ? `# language: ${language}\n# purpose: TODO: 一句话描述该能力与其目的。`
59
57
  : `# language: ${language}\n# purpose: TODO: Describe this capability and its purpose.`;
60
58
  const ruleDesc = zh ? 'TODO: 需求描述(自由文本)。' : 'TODO: requirement statement (free text).';
61
- // Skeleton placeholder prose is not vocabulary — the zh/en copy stays; keywords do not.
62
59
  const steps = zh
63
60
  ? ` ${kw.given} TODO 前置\n ${kw.when} TODO 动作\n ${kw.thenText} TODO 断言`
64
61
  : ` ${kw.given} TODO precondition\n ${kw.when} TODO action\n ${kw.thenText} TODO assertion`;
65
- // native v2 skeleton: a rule block (with @req handle) + one nested example
66
62
  return (
67
63
  `${header}\n\n${kw.feature}: ${capability}\n\n @req:${reqId}\n ${kw.rule}: TODO-rule\n` +
68
64
  ` ${ruleDesc}\n\n ${kw.scenario}: TODO-acceptance\n${steps}\n`
@@ -45,37 +45,25 @@ export function buildReview(input: ReviewInput): ReviewResult {
45
45
  const sweep = validateAllSpecs(entries);
46
46
  const sorted = [...entries].toSorted((a, b) => a.fileName.localeCompare(b.fileName));
47
47
 
48
- // T29: unbound counting is the shared collector (report/unbound) keyed by
49
- // capability — one definition of "rule without runnable scenario".
50
48
  const unboundByCap = new Map<string, number>();
51
49
  for (const u of collectUnboundRequirements(entries)) {
52
50
  unboundByCap.set(u.capability, (unboundByCap.get(u.capability) ?? 0) + 1);
53
51
  }
54
52
  for (const entry of sorted) {
55
53
  const cap = specIdOf(entry);
56
- // r33: per-capability signals honor the --capability filter; locked and
57
- // validate stay global regardless.
58
54
  if (input.capability !== undefined && cap !== input.capability) continue;
59
55
  push('unbound', cap, unboundByCap.get(cap) ?? 0);
60
56
  }
61
57
 
62
58
  const failed = sweep.verdicts.filter((v) => !v.ok);
63
59
  const sweepFailedCount = failed.length;
64
- // T35: unchecked tasks are work-in-progress noise, not contract breakage —
65
- // they degrade to a warningCount contribution instead of the critical count
66
- // (locked/unbound signals stay untouched).
67
60
  const taskWarnings = strictChangeFails.length;
68
- // predecessor parity: `count` is the removed locked-rule-confirmation concept (always
69
- // 0 now); the detail text carries the bound-change count separately.
70
61
  push(
71
62
  'locked',
72
63
  '-',
73
64
  0,
74
65
  `${boundChangeCount} bound change(s); inspect with \`llman-sdd change diff <id>\``,
75
66
  );
76
- // detail names the failing source: sweep failures point at `validate --all`;
77
- // strict-only failures name the offending changes instead of a command that
78
- // would report green.
79
67
  const sweepDetail =
80
68
  sweepFailedCount > 0 ? 'validate --all failed; run `llman-sdd validate --all` for details' : '';
81
69
  const strictDetail =
@@ -18,9 +18,6 @@ export function featureRelPath(fileName: string, specsDir: string): string {
18
18
  if (rel.startsWith(prefix)) return rel.slice(prefix.length);
19
19
  // Path-form independence (fix-review-sweep-path): callers may load entries
20
20
  // with absolute file names while specsDir stays root-relative (the review
21
- // sweep did exactly that). Locate the LAST whole-segment occurrence of the
22
- // specs root inside the file name and keep the tail — the id must depend on
23
- // the position inside the specs tree, never on the caller's path shape.
24
21
  const needle = `/${root}/`;
25
22
  const at = rel.lastIndexOf(needle);
26
23
  if (at >= 0) return rel.slice(at + needle.length);
@@ -124,6 +124,19 @@ export interface AddScenarioOpts {
124
124
  thenText: string;
125
125
  }
126
126
 
127
+ /**
128
+ * End of the rule block that owns the @req tag: the first 2-space top-level tag
129
+ * or official block keyword line after the rule header. The scan starts below the
130
+ * header so the header itself cannot be mistaken for the boundary.
131
+ */
132
+ function findRuleBlockEnd(lines: readonly string[], tagIdx: number): number {
133
+ for (let i = tagIdx + 2; i < lines.length; i++) {
134
+ const l = lines[i] ?? '';
135
+ if (l.startsWith(' @') || BLOCK_KEYWORD_LINE_RE.test(l)) return i;
136
+ }
137
+ return lines.length;
138
+ }
139
+
127
140
  /**
128
141
  * Insert a nested `场景:` under the target rule's block (r42). Finds the
129
142
  * rule block boundary in the raw text (next 2-space top-level element) and
@@ -143,32 +156,15 @@ export function addScenario(
143
156
  const lines = content.split('\n');
144
157
  const tagIdx = lines.findIndex((l) => l.trim() === `@req:${opts.reqId}`);
145
158
  if (tagIdx === -1) throw new AuthoringError(`req id not found in file: ${opts.reqId}`);
146
- // block end = first line after the tag's own rule header at 2-space top-level
147
- // indent that is a tag line or an official block keyword line (2-space +
148
- // keyword immediately, any official dialect). The rule header directly
149
- // following the tag opens the block, so the scan starts after it — otherwise
150
- // the header itself is mistaken for the boundary and the scenario is
151
- // inserted before the rule line (broken output).
152
- let end = lines.length;
153
- for (let i = tagIdx + 2; i < lines.length; i++) {
154
- const l = lines[i] ?? '';
155
- if (l.startsWith(' @') || BLOCK_KEYWORD_LINE_RE.test(l)) {
156
- end = i;
157
- break;
158
- }
159
- }
159
+ const end = findRuleBlockEnd(lines, tagIdx);
160
160
  const kw = keywordsOf(content);
161
161
  const givenLine =
162
162
  opts.given !== undefined && opts.given !== '' ? ` ${kw.given} ${opts.given}\n` : '';
163
163
  const scenarioBlock =
164
164
  ` ${kw.scenario}: ${opts.scenarioId}\n` +
165
165
  `${givenLine} ${kw.when} ${opts.when}\n ${kw.thenText} ${opts.thenText}\n`;
166
- // insert with a leading blank separator so the file stays readable
167
166
  lines.splice(end, 0, '', scenarioBlock.trimEnd());
168
167
  const joined = lines.join('\n');
169
- // 末尾换行保真:插入落在文件尾时,split 产生的结尾空串不再是最后一项,
170
- // join 会把原文件的尾换行吃掉;中段插入无此问题。缺行尾换行会让
171
- // end-of-file-fixer 之类的钩子反复改写文件。
172
168
  io.writeText(path, content.endsWith('\n') && !joined.endsWith('\n') ? `${joined}\n` : joined);
173
169
  return path;
174
170
  }
@@ -239,19 +235,12 @@ export function planDedupe(
239
235
  opts: { apply?: boolean } = {},
240
236
  ): DedupePlanItem[] {
241
237
  const used = ruleReqIds(entries);
242
- // Allocator primitive (unify-numeric-id-allocation): the remap sequence
243
- // starts at max(used)+1 over the in-memory registry set (no second
244
- // filesystem pass) and advances by one per allocation — never a
245
- // smallest-free probing loop. Zero persisted state.
246
238
  let next = nextNumber(
247
239
  [...used].map((id) => Number(id.slice(1))).filter((n) => Number.isFinite(n)),
248
240
  );
249
241
  const fresh = (): string => `r${String(next++)}`;
250
242
  const plan: DedupePlanItem[] = [];
251
243
  for (const dup of duplicates) {
252
- // occurrences are in scan order (sorted files, in-file rule order); the
253
- // per-file ordinal counts every occurrence so kept ones hold their slot
254
- // in the text and remapped ones target the exact `@req:` tag to rewrite.
255
244
  const perFileOrdinal = new Map<string, number>();
256
245
  let keepFile: string | null = null;
257
246
  for (const occ of dup.occurrences) {
@@ -272,7 +261,6 @@ export function planDedupe(
272
261
  }
273
262
  if (opts.apply === false) return plan;
274
263
  for (const item of plan) {
275
- // registry duplicates carry bare file names; accept already-rooted paths too
276
264
  const path = item.remapFile.startsWith(`${specsRoot}/`)
277
265
  ? item.remapFile
278
266
  : `${specsRoot}/${item.remapFile}`;
package/src/spec/ir.ts CHANGED
@@ -77,13 +77,22 @@ export interface CapabilityDoc {
77
77
  }
78
78
 
79
79
  /**
80
- * Whether a requirement is bound to real logic — it has at least one runnable
81
- * nested scenario (not `@skip`/`@experimental` and carrying steps). Single
82
- * authority for the `bound`/`unbound` definition shared by review's `unbound`
83
- * signal, validate's aggregate INFO, list/show morphology and `spec unbound`.
80
+ * Whether a requirement is bound in spec shape — it has at least one runnable
81
+ * nested scenario (not `@skip`/`@experimental`, and either carrying steps or a
82
+ * dialect-tagged examples table with a data row). That is not "tests executed
83
+ * the rows". Single authority for bound/unbound shared by review, validate INFO,
84
+ * list/show morphology and `spec unbound`.
84
85
  */
86
+ const DIALECT_BIND_TAGS = new Set(['flow', 'state', 'nodes', 'decision_table']);
87
+
85
88
  export function ruleHasRunnableScenario(rule: RuleIR): boolean {
86
- return rule.scenarios.some((s) => s.runnable && s.stepCount > 0);
89
+ return rule.scenarios.some((s) => {
90
+ if (!s.runnable) return false;
91
+ if (s.stepCount > 0) return true;
92
+ const hasDialect = s.tags.some((t) => DIALECT_BIND_TAGS.has(t));
93
+ if (!hasDialect) return false;
94
+ return (s.examples ?? []).some((ex) => ex.rows.length >= 1);
95
+ });
87
96
  }
88
97
 
89
98
  /**
@@ -87,8 +87,6 @@ export function officialKeywords(language: string): GherkinKeywords | null {
87
87
  if (!table) return null;
88
88
  const locked = LOCKED_KEYWORDS[language];
89
89
  if (locked === undefined) return keywordsFromTable(table);
90
- // A locked byte that left the official table would silently drift the
91
- // dialect — fall through to the table instead of emitting it.
92
90
  const fromTable = keywordsFromTable(table);
93
91
  if (fromTable === null) return null;
94
92
  return TABLE_KEY_PAIRS.every(([tableKey, kwKey]) =>
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Single Studio machine-key coordinate system (unify-req-ref-and-clean-graph-dsl).
3
+ *
4
+ * Formal graphs key as `rN#<场景名>`; drafts without a `reqId` key as
5
+ * `draft:<capability>#<场景名>`. `capability` stays a structured IR field —
6
+ * consumers MUST NOT reverse-split it out of the key.
7
+ *
8
+ * Authority lives in `spec/` so `validation/` never imports `studio/` (r72).
9
+ * Pure — zero I/O, zero `node:*`, zero wall-clock calls (core-zero-io).
10
+ */
11
+ import { REQ_ID_RE } from './reqRef.ts';
12
+
13
+ const DRAFT_PREFIX = 'draft:';
14
+
15
+ export interface ParsedMachineKey {
16
+ /** `r1` for a formal graph; `null` for a draft. */
17
+ reqId: string | null;
18
+ /** Capability carried by a draft key only. */
19
+ draftCapability?: string;
20
+ /** Full scenario name (may contain `/`, `#` and spaces). */
21
+ scenarioName: string;
22
+ }
23
+
24
+ export function makeMachineKey(
25
+ capability: string,
26
+ reqId: string | null | undefined,
27
+ scenarioName: string,
28
+ ): string {
29
+ const id = reqId?.trim();
30
+ if (id !== undefined && id !== '' && REQ_ID_RE.test(id)) return `${id}#${scenarioName}`;
31
+ return `${DRAFT_PREFIX}${capability}#${scenarioName}`;
32
+ }
33
+
34
+ /** Split on the first `#`: `rN` head → formal graph, `draft:<cap>` head → draft. */
35
+ export function splitMachineKey(machineKey: string): ParsedMachineKey | null {
36
+ const key = machineKey.trim();
37
+ const hashAt = key.indexOf('#');
38
+ if (hashAt <= 0) return null;
39
+ const head = key.slice(0, hashAt);
40
+ const scenarioName = key.slice(hashAt + 1);
41
+ if (scenarioName === '') return null;
42
+ if (REQ_ID_RE.test(head)) return { reqId: head, scenarioName };
43
+ if (head.startsWith(DRAFT_PREFIX)) {
44
+ const draftCapability = head.slice(DRAFT_PREFIX.length);
45
+ if (draftCapability === '') return null;
46
+ return { reqId: null, draftCapability, scenarioName };
47
+ }
48
+ return null;
49
+ }
@@ -71,7 +71,6 @@ export function analyzeLegacy(source: string): MigrateAnalysis | { ok: false; me
71
71
  const blocks: MigrateBlock[] = [];
72
72
  for (const child of doc.feature?.children ?? []) {
73
73
  if (child.rule) {
74
- // native source — nothing to migrate here; caller should skip
75
74
  continue;
76
75
  }
77
76
  const sc = child.scenario;
@@ -104,6 +103,10 @@ function stripBullet(line: string): string {
104
103
  * orphans. Non-scenario lines (headers/feature/comments) are NOT touched —
105
104
  * the native output only emits tag/rule/scenario lines, so the preamble is
106
105
  * reconstructed by the caller from the original file.
106
+ *
107
+ * Emitted keywords come from the official dialect table, so the result re-parses
108
+ * in one language; unbound acceptance examples are emitted last at top level,
109
+ * where official Gherkin absorbs them into the preceding rule.
107
110
  */
108
111
  export function migrateNativeSource(source: string): MigrateResult {
109
112
  const analysis = analyzeLegacy(source);
@@ -114,17 +117,9 @@ export function migrateNativeSource(source: string): MigrateResult {
114
117
  return { ok: false, message: 'no legacy scenarios found (already native?)' };
115
118
  }
116
119
 
117
- // Keywords come from the official gherkin dialect table so the output
118
- // stays parseable in one language — the preamble (`# language:` header,
119
- // `Feature:`/`功能:` line) is kept verbatim and already matches it. The
120
- // trailing parse self-check guards the rest.
121
120
  const kw = officialKeywordsOrEn(language);
122
- // The auto-nested acceptance title is a synthesized name, not a keyword —
123
- // no official source exists, so it keeps its localized map.
124
121
  const autoAcceptance = language === 'zh-CN' ? '验收示例' : 'Acceptance example';
125
122
 
126
- // preamble: everything before the first top-level tag line (headers,
127
- // feature line, comments) — cut textually, preserved verbatim.
128
123
  const lines = source.split('\n');
129
124
  let preEnd = 0;
130
125
  for (let i = 0; i < lines.length; i++) {
@@ -146,9 +141,6 @@ export function migrateNativeSource(source: string): MigrateResult {
146
141
  const text = stripBullet(line);
147
142
  if (text !== '') out.push(` ${text}`);
148
143
  }
149
- // A legacy rule scenario may carry its own acceptance steps inline
150
- // (description + steps in one block). They become the rule's first
151
- // nested scenario — file-order semantics, never dropped.
152
144
  if (b.steps.length > 0) {
153
145
  out.push('');
154
146
  if (b.skip) out.push(' @skip');
@@ -167,10 +159,6 @@ export function migrateNativeSource(source: string): MigrateResult {
167
159
  for (const s of a.steps) out.push(` ${s.keyword} ${s.text}`);
168
160
  }
169
161
  }
170
- // Unbound acceptance scenarios (no matching rule) are emitted last at
171
- // top level — native feature-level examples with no requirement handle.
172
- // Under official Gherkin parsing they are absorbed into the preceding rule,
173
- // which is their natural functional home; no special signal exists for them.
174
162
  for (const [ai, a] of blocks.entries()) {
175
163
  if (a.isRule || consumed.has(ai)) continue;
176
164
  consumed.add(ai);
@@ -186,8 +174,6 @@ export function migrateNativeSource(source: string): MigrateResult {
186
174
  }
187
175
 
188
176
  const content = `${out.join('\n')}\n`;
189
- // Fail closed: never hand back content the official parser rejects — a
190
- // dialect mismatch would otherwise land on disk as silent corruption.
191
177
  try {
192
178
  parseFeatureSource(content);
193
179
  } catch (error) {
@@ -3,10 +3,12 @@
3
3
  *
4
4
  * Native v2 model: `功能:` → `规则:` blocks (requirement: title + free-form
5
5
  * description + `@req:<id>` handle) → nested `场景:` (executable examples).
6
- * Top-level `场景:` outside any rule become orphans. Legacy role tags
7
- * (@human/@rule/@executable/@manual) are inert — the parser only reads
8
- * `@req` (handle) and `@skip`/`@experimental` (runner opt-out). Files in the
9
- * legacy flat layout must be migrated with `spec migrate-native`.
6
+ * Top-level `场景:` outside any rule become orphans. Tags are attached verbatim:
7
+ * only `@req:` is interpreted (as the rule handle, validated by the shared
8
+ * `REQ_ID_RE`) and `@skip`/`@experimental` are runner opt-outs. Every other tag —
9
+ * including legacy role tags (@human/@rule/@executable/@manual) — passes through
10
+ * as an ordinary unknown tag. Files in the legacy flat layout must be migrated
11
+ * with `spec migrate-native`.
10
12
  */
11
13
  import { AstBuilder, GherkinClassicTokenMatcher, Parser } from '@cucumber/gherkin';
12
14
  import type { GherkinDocument } from '@cucumber/messages';
@@ -22,6 +24,7 @@ import {
22
24
  type SpecStructuralError,
23
25
  } from './ir.ts';
24
26
  import { stepKeywordToOfficialKind } from './keywords.ts';
27
+ import { reqIdFromTag } from './reqRef.ts';
25
28
 
26
29
  export class SpecParseError extends Error {}
27
30
 
@@ -75,8 +78,6 @@ export function sourceDialect(source: string): string {
75
78
  }
76
79
  }
77
80
 
78
- const REQ_TAG_RE = /^@?req:(r\d+)$/u;
79
-
80
81
  /** Gherkin keyword → step kind, from the official dialect tables; And/But/* inherit via fallback. */
81
82
  function stepKeywordToKind(keyword: string): ScenarioStepKind {
82
83
  return stepKeywordToOfficialKind(keyword) ?? 'given';
@@ -96,14 +97,13 @@ function extractHeader(source: string): CapabilityHeader {
96
97
  }
97
98
 
98
99
  interface RawTags {
99
- // Tag names are stored here without the leading '@'.
100
100
  names: string[];
101
101
  reqId: string;
102
102
  }
103
103
 
104
104
  function parseTags(tags: readonly { name: string }[]): RawTags {
105
105
  const names = tags.map((t) => t.name.replace(/^@/u, ''));
106
- const req = tags.map((t) => t.name.match(REQ_TAG_RE)?.[1]).find((v): v is string => !!v);
106
+ const req = tags.map((t) => reqIdFromTag(t.name)).find((v): v is string => !!v);
107
107
  return { names, reqId: req ?? '' };
108
108
  }
109
109
 
@@ -148,14 +148,7 @@ function collectScenario(sc: {
148
148
  }
149
149
  return {
150
150
  name: sc.name,
151
- tags: names.filter(
152
- (n) =>
153
- !n.startsWith('req') &&
154
- !skipTokens.has(n) &&
155
- !n.startsWith('rule') &&
156
- !n.startsWith('human') &&
157
- !n.startsWith('executable'),
158
- ),
151
+ tags: names.filter((n) => reqIdFromTag(`@${n}`) === null && !skipTokens.has(n)),
159
152
  runnable,
160
153
  stepCount: steps.length,
161
154
  steps,
@@ -200,9 +193,7 @@ export function parseCapability(source: string, fileName = '<inline>'): Capabili
200
193
  title: rule.name,
201
194
  description,
202
195
  scenarios,
203
- tags: names.filter(
204
- (n) => !n.startsWith('req') && !n.startsWith('rule') && !n.startsWith('human'),
205
- ),
196
+ tags: names.filter((n) => reqIdFromTag(`@${n}`) === null),
206
197
  });
207
198
  continue;
208
199
  }