@llman-sdd/core 0.10.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/package.json +11 -8
  2. package/src/archive/freeze.ts +41 -15
  3. package/src/archive/frozenCard.ts +57 -9
  4. package/src/archive/ignoreChain.ts +2 -6
  5. package/src/archive/sevenzip.ts +0 -1
  6. package/src/change/closeOutHarness.ts +17 -0
  7. package/src/change/collect.ts +0 -5
  8. package/src/change/frontmatter.ts +15 -7
  9. package/src/change/id.ts +0 -2
  10. package/src/change/lifecycle.ts +53 -94
  11. package/src/config/changeId.ts +0 -2
  12. package/src/config/load.ts +0 -4
  13. package/src/config/schema.ts +24 -13
  14. package/src/config/surface.ts +2 -12
  15. package/src/context/sddState.ts +23 -18
  16. package/src/git/spawnGit.ts +0 -3
  17. package/src/hints/jitHints.ts +82 -0
  18. package/src/index.ts +462 -39
  19. package/src/init/defaultConfig.ts +4 -13
  20. package/src/init/init.ts +108 -36
  21. package/src/init/skillCheck.ts +60 -0
  22. package/src/init/uncommentConfig.ts +909 -0
  23. package/src/locale.ts +0 -2
  24. package/src/project/migrateNotes.ts +0 -9
  25. package/src/project/migrations.ts +151 -9
  26. package/src/report/graph/analysis.ts +0 -4
  27. package/src/report/graph/nodes.ts +0 -6
  28. package/src/report/show.ts +7 -23
  29. package/src/report/specHelpers.ts +10 -14
  30. package/src/review/review.ts +0 -12
  31. package/src/spec/assignSpecIds.ts +0 -3
  32. package/src/spec/authoring.ts +16 -24
  33. package/src/spec/ir.ts +14 -5
  34. package/src/spec/keywords.ts +0 -2
  35. package/src/spec/machineKey.ts +49 -0
  36. package/src/spec/migrateNative.ts +4 -18
  37. package/src/spec/parser.ts +10 -19
  38. package/src/spec/reqRef.ts +135 -0
  39. package/src/studio/changeScope.ts +50 -0
  40. package/src/studio/changeScopeDiff.ts +195 -0
  41. package/src/studio/contracts.ts +493 -0
  42. package/src/studio/decisionTree.ts +206 -0
  43. package/src/studio/deeplink.ts +116 -0
  44. package/src/studio/demos.ts +167 -0
  45. package/src/studio/diff.ts +494 -0
  46. package/src/studio/drift.ts +738 -0
  47. package/src/studio/extract.ts +360 -0
  48. package/src/studio/featureSync.ts +592 -0
  49. package/src/studio/forest.ts +570 -0
  50. package/src/studio/index.ts +32 -0
  51. package/src/studio/model.ts +254 -0
  52. package/src/studio/revisions.ts +476 -0
  53. package/src/studio/search.ts +337 -0
  54. package/src/studio/store.ts +811 -0
  55. package/src/studio/sync.ts +912 -0
  56. package/src/studio/textfold.ts +72 -0
  57. package/src/studio/time.ts +107 -0
  58. package/src/studio/validate.ts +363 -0
  59. package/src/templates/embedded.ts +4 -6
  60. package/src/templates/engine.ts +1 -1
  61. package/src/templates/skills.ts +76 -51
  62. package/src/theorems/guard.ts +52 -0
  63. package/src/theorems/index.ts +56 -0
  64. package/src/theorems/migrate.ts +133 -0
  65. package/src/theorems/schema.ts +67 -0
  66. package/src/theorems/scope.ts +68 -0
  67. package/src/theorems/serialize.ts +60 -0
  68. package/src/theorems/transactionMachine.ts +247 -0
  69. package/src/theorems/validate.ts +141 -0
  70. package/src/util/nextNumber.ts +0 -2
  71. package/src/validation/changeCheck.ts +0 -24
  72. package/src/validation/flowAndNesting.ts +434 -0
  73. package/src/validation/harness.ts +108 -65
  74. package/src/validation/validate.ts +26 -12
  75. package/src/validation/xstateTransitions.ts +483 -184
  76. package/templates/zh-Hans/llmanspec-agents-stub.md +17 -2
  77. package/templates/zh-Hans/skills/llman-sdd-autopilot/SKILL.md +34 -0
  78. package/templates/zh-Hans/skills/llman-sdd-change/SKILL.md +44 -0
  79. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/archive.md +15 -0
  80. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/draft.md +9 -0
  81. package/templates/zh-Hans/skills/llman-sdd-review/SKILL.md +71 -0
  82. package/templates/zh-Hans/skills/llman-sdd-specs/SKILL.md +70 -0
  83. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/compact.md +12 -0
  84. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/doctor.md +26 -0
  85. package/templates/zh-Hans/skills/llman-sdd-specs/references/graph-dsl.md +33 -0
  86. package/templates/zh-Hans/skills/llman-sdd-studio/SKILL.md +33 -0
  87. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/collab.md +20 -0
  88. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/drift.md +52 -0
  89. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/onboard.md +33 -0
  90. package/templates/zh-Hans/units/skills/cli-footer.md +2 -2
  91. package/src/context/indexStore.ts +0 -171
  92. package/src/context/retrieve.ts +0 -332
  93. package/src/context/tree.ts +0 -112
  94. package/templates/zh-Hans/agents-root-stub.md +0 -9
  95. package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +0 -69
  96. package/templates/zh-Hans/skills/llman-sdd-apply.md +0 -117
  97. package/templates/zh-Hans/skills/llman-sdd-arch-review.md +0 -58
  98. package/templates/zh-Hans/skills/llman-sdd-archive.md +0 -79
  99. package/templates/zh-Hans/skills/llman-sdd-continue.md +0 -34
  100. package/templates/zh-Hans/skills/llman-sdd-draft.md +0 -53
  101. package/templates/zh-Hans/skills/llman-sdd-explore.md +0 -64
  102. package/templates/zh-Hans/skills/llman-sdd-ff.md +0 -33
  103. package/templates/zh-Hans/skills/llman-sdd-graph.md +0 -56
  104. package/templates/zh-Hans/skills/llman-sdd-propose.md +0 -107
  105. package/templates/zh-Hans/skills/llman-sdd-quick.md +0 -41
  106. package/templates/zh-Hans/skills/llman-sdd-research.md +0 -35
  107. package/templates/zh-Hans/skills/llman-sdd-specs-compact.md +0 -41
  108. package/templates/zh-Hans/skills/llman-sdd-validate.md +0 -28
  109. package/templates/zh-Hans/skills/llman-sdd-verify.md +0 -77
  110. package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +0 -83
  111. package/templates/zh-Hans/units/skills/ethics-governance.md +0 -6
  112. package/templates/zh-Hans/units/skills/git-native-flow.md +0 -56
  113. package/templates/zh-Hans/units/skills/human-readable-summary.md +0 -9
  114. package/templates/zh-Hans/units/skills/index-fallback.md +0 -1
  115. package/templates/zh-Hans/units/skills/stage-guard.md +0 -17
  116. package/templates/zh-Hans/units/skills/structured-protocol.md +0 -19
  117. package/templates/zh-Hans/units/skills/validation-hints.md +0 -20
  118. package/templates/zh-Hans/units/skills/version-drift.md +0 -3
  119. package/templates/zh-Hans/units/spec/feature-contract.md +0 -8
@@ -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
  }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Single requirement-reference coordinate system (unify-req-ref-and-clean-graph-dsl).
3
+ *
4
+ * One `REQ_ID_RE`, one `parseReqRef`, one tokenizer and one allocator serve every
5
+ * surface that names a requirement: `.feature` `@req:` handles, `@nodes` 引用 cells,
6
+ * `@flow` 验证 cells and source-code `@llmanspec:req:` anchors.
7
+ *
8
+ * Pure — zero I/O, zero `node:*`, zero wall-clock calls (core-zero-io).
9
+ */
10
+ import { nextNumber } from '../util/nextNumber.ts';
11
+
12
+ /** The only legal requirement id shape: `r` followed by digits. */
13
+ export const REQ_ID_RE = /^r\d+$/u;
14
+
15
+ export interface ReqRef {
16
+ /** Parsed requirement id; empty string marks a syntactically invalid cell. */
17
+ reqId: string;
18
+ /** Scenario name when the reference pins one, `null` for a rule-level reference. */
19
+ scenarioName: string | null;
20
+ /** Original cell text, trimmed. */
21
+ raw: string;
22
+ }
23
+
24
+ const REF_PREFIX_RE = /^@?(?:llmanspec:)?req:/u;
25
+ const REQ_TAG_RE = /^@?req:(.+)$/u;
26
+
27
+ /**
28
+ * Which prefix a reference cell must carry.
29
+ * - `spec`: `.feature` cells (`引用` / `验证`) must be exactly `@req:...`.
30
+ * - `anchor`: source-code anchors must be exactly `@llmanspec:req:...`.
31
+ * - `payload`: bare `rN[#场景名]` payload (already prefix-stripped).
32
+ */
33
+ export type ReqRefMode = 'spec' | 'anchor' | 'payload';
34
+
35
+ /** Extract the requirement id from a Gherkin tag name (`@req:r12` / `req:r12`). */
36
+ export function reqIdFromTag(tagName: string): string | null {
37
+ const m = REQ_TAG_RE.exec(tagName.trim());
38
+ if (!m?.[1]) return null;
39
+ return REQ_ID_RE.test(m[1]) ? m[1] : null;
40
+ }
41
+
42
+ function parseScenarioName(raw: string): string | null {
43
+ if (/^\s/u.test(raw)) return null;
44
+ const text = raw.trim();
45
+ if (text === '') return null;
46
+ if (text.startsWith('"')) {
47
+ if (text.length < 3 || !text.endsWith('"')) return null;
48
+ const inner = text.slice(1, -1);
49
+ if (inner.trim() === '' || inner.includes('"') || /[\r\n]/u.test(inner)) return null;
50
+ return inner;
51
+ }
52
+ if (text.includes('"')) return null;
53
+ if (/\s/u.test(text)) return null;
54
+ return text;
55
+ }
56
+
57
+ /**
58
+ * Parse a requirement reference payload — with or without the `@req:` /
59
+ * `@llmanspec:req:` prefix: `r12`, `r12#待办生命周期`, `r12#"Studio Web 主态流转"`.
60
+ * Empty cell → `null`; syntactically invalid cell → `{ reqId: '', ... }`.
61
+ */
62
+ export function parseReqRef(cell: string, mode: ReqRefMode = 'payload'): ReqRef | null {
63
+ const raw = cell.trim();
64
+ if (raw === '') return null;
65
+ let payload: string;
66
+ if (mode === 'spec') {
67
+ if (!raw.startsWith('@req:')) return { reqId: '', scenarioName: null, raw };
68
+ payload = raw.slice('@req:'.length);
69
+ } else if (mode === 'anchor') {
70
+ if (!raw.startsWith('@llmanspec:req:')) return { reqId: '', scenarioName: null, raw };
71
+ payload = raw.slice('@llmanspec:req:'.length);
72
+ } else {
73
+ payload = raw.replace(REF_PREFIX_RE, '');
74
+ }
75
+ const hashAt = payload.indexOf('#');
76
+ const idPart = hashAt === -1 ? payload : payload.slice(0, hashAt);
77
+ if (!REQ_ID_RE.test(idPart)) return { reqId: '', scenarioName: null, raw };
78
+ if (hashAt === -1) return { reqId: idPart, scenarioName: null, raw };
79
+ const scenarioName = parseScenarioName(payload.slice(hashAt + 1));
80
+ if (scenarioName === null) return { reqId: '', scenarioName: null, raw };
81
+ return { reqId: idPart, scenarioName, raw };
82
+ }
83
+
84
+ /**
85
+ * Split a whitespace-separated `验证` cell into reference tokens.
86
+ * Whitespace inside double quotes never splits:
87
+ * `@req:r1#"主态 流转" @req:r2` → 2 tokens.
88
+ */
89
+ export function tokenizeReqRefs(cell: string): string[] {
90
+ const tokens: string[] = [];
91
+ let current = '';
92
+ let quoted = false;
93
+ for (const ch of cell.trim()) {
94
+ if (ch === '"') {
95
+ quoted = !quoted;
96
+ current += ch;
97
+ continue;
98
+ }
99
+ if (!quoted && /\s/u.test(ch)) {
100
+ if (current !== '') {
101
+ tokens.push(current);
102
+ current = '';
103
+ }
104
+ continue;
105
+ }
106
+ current += ch;
107
+ }
108
+ if (current !== '') tokens.push(current);
109
+ return tokens;
110
+ }
111
+
112
+ /** Wrap a scenario name in double quotes when it carries whitespace. */
113
+ export function quoteScenarioName(scenarioName: string): string {
114
+ return /\s/u.test(scenarioName) ? `"${scenarioName}"` : scenarioName;
115
+ }
116
+
117
+ /** Render `@req:rN` / `@req:rN#场景名` / `@req:rN#"带空格 场景"`. */
118
+ export function formatReqRef(reqId: string, scenarioName?: string | null): string {
119
+ const name = scenarioName?.trim() ?? '';
120
+ if (name === '') return `@req:${reqId}`;
121
+ return `@req:${reqId}#${quoteScenarioName(name)}`;
122
+ }
123
+
124
+ /**
125
+ * Allocate the repo-wide next requirement id (`r<max+1>`).
126
+ * Retired ranges are never reused (align-next-req-id-max-plus-one).
127
+ */
128
+ export function allocateNextReqId(existingReqIds: Iterable<string>): string {
129
+ const used: number[] = [];
130
+ for (const id of existingReqIds) {
131
+ const trimmed = id.trim();
132
+ if (REQ_ID_RE.test(trimmed)) used.push(Math.trunc(Number(trimmed.slice(1))));
133
+ }
134
+ return `r${String(nextNumber(used))}`;
135
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Browser-safe pure helpers for Studio change-scoped spec view (studio-web r199, r200).
3
+ * Strictly zero I/O and zero wall-clock calls.
4
+ */
5
+ import type { StudioChangeScope } from './contracts.ts';
6
+
7
+ export type StudioScopeViewMode = 'changed' | 'all';
8
+
9
+ export interface ChangeScopeActivationInput {
10
+ isDefaultBranch: boolean;
11
+ hasCommittedSpecDiff: boolean;
12
+ hasUncommittedSpecDiff: boolean;
13
+ }
14
+
15
+ export interface ChangeScopeActivationDecision {
16
+ active: boolean;
17
+ defaultViewMode: StudioScopeViewMode;
18
+ }
19
+
20
+ export const EMPTY_CHANGE_SCOPE: StudioChangeScope = {
21
+ active: false,
22
+ branch: null,
23
+ baseBranch: null,
24
+ mergeBaseSha: null,
25
+ boundChangeId: null,
26
+ boundChangeTitle: null,
27
+ touchedSpecs: [],
28
+ };
29
+
30
+ /**
31
+ * Pure decision table for `studio-web` r199 ("变更视图激活判定"):
32
+ * - Default branch + no uncommitted diff -> inactive, all specs
33
+ * - Default branch + uncommitted diff -> active, changed view
34
+ * - Feature branch + no diffs -> active, all specs (with gentle empty-diff notice)
35
+ * - Feature branch + any committed/uncommitted diff -> active, changed view
36
+ */
37
+ export function resolveChangeScopeActivation(
38
+ input: ChangeScopeActivationInput,
39
+ ): ChangeScopeActivationDecision {
40
+ const hasAnyDiff = input.hasCommittedSpecDiff || input.hasUncommittedSpecDiff;
41
+ if (input.isDefaultBranch) {
42
+ return input.hasUncommittedSpecDiff
43
+ ? { active: true, defaultViewMode: 'changed' }
44
+ : { active: false, defaultViewMode: 'all' };
45
+ }
46
+ return {
47
+ active: true,
48
+ defaultViewMode: hasAnyDiff ? 'changed' : 'all',
49
+ };
50
+ }
@@ -0,0 +1,195 @@
1
+ import type { CapabilityDoc, RuleIR } from '../spec/ir.ts';
2
+ /**
3
+ * Pure-domain `.feature` fine-grained diff extractor for Studio change scope (studio-web r199).
4
+ * Extracts touched `@req` IDs and graph anchors (`@state` / `@flow` / `@decision_table`)
5
+ * with strictly zero I/O or wall-clock dependencies.
6
+ */
7
+ import { parseCapability } from '../spec/parser.ts';
8
+ import type { SpecEntry } from '../validation/validate.ts';
9
+ import type { StudioChangeItemStatus } from './contracts.ts';
10
+ import { extractDecisionTables } from './decisionTree.ts';
11
+ import { extractStudioMachines } from './extract.ts';
12
+ import type { StudioMachineIR } from './model.ts';
13
+
14
+ export interface FeatureChangeDiffResult {
15
+ touchedReqIds: string[];
16
+ reqStatuses: Record<string, StudioChangeItemStatus>;
17
+ touchedGraphIds: string[];
18
+ graphStatuses: Record<string, StudioChangeItemStatus>;
19
+ baseMachines: Record<string, StudioMachineIR>;
20
+ }
21
+
22
+ function serializeRule(rule: RuleIR): string {
23
+ return JSON.stringify({
24
+ reqId: rule.reqId,
25
+ title: rule.title.trim(),
26
+ description: rule.description.trim(),
27
+ tags: [...rule.tags].sort(),
28
+ scenarios: rule.scenarios.map((sc) => ({
29
+ name: sc.name.trim(),
30
+ tags: [...sc.tags].sort(),
31
+ steps: sc.steps.map((s) => `${s.kind} ${s.text.trim()}`),
32
+ examples: (sc.examples ?? []).map((ex) => ({
33
+ headers: ex.headers.map((h) => h.trim()),
34
+ rows: ex.rows.map((r) => r.map((c) => c.trim())),
35
+ })),
36
+ })),
37
+ });
38
+ }
39
+
40
+ function parseDocSafe(raw: string | null): CapabilityDoc | null {
41
+ if (!raw || raw.trim() === '') return null;
42
+ try {
43
+ return parseCapability(raw);
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ function extractGraphFingerprints(
50
+ doc: CapabilityDoc | null,
51
+ capId: string,
52
+ ): { fingerprints: Map<string, string>; machines: Map<string, StudioMachineIR> } {
53
+ const fingerprints = new Map<string, string>();
54
+ const machines = new Map<string, StudioMachineIR>();
55
+ if (!doc) return { fingerprints, machines };
56
+
57
+ const entry: SpecEntry = {
58
+ fileName: `${capId}.feature`,
59
+ specId: capId,
60
+ doc,
61
+ };
62
+
63
+ for (const extracted of extractStudioMachines([entry])) {
64
+ const m = extracted.machine;
65
+ machines.set(m.machineKey, m);
66
+ fingerprints.set(
67
+ m.machineKey,
68
+ JSON.stringify({
69
+ graphKind: m.graphKind ?? 'machine',
70
+ reqId: m.reqId,
71
+ ruleTitle: m.ruleTitle,
72
+ scenarioName: m.scenarioName,
73
+ states: m.states.map((s) => ({
74
+ name: s.name,
75
+ nodeKind: s.nodeKind ?? null,
76
+ actor: s.actor ?? null,
77
+ nestKey: s.nestKey ?? null,
78
+ summary: s.summary ?? null,
79
+ })),
80
+ transitions: m.transitions.map((t) => ({
81
+ from: m.states.find((s) => s.uid === t.fromUid)?.name ?? t.fromUid,
82
+ to: m.states.find((s) => s.uid === t.toUid)?.name ?? t.toUid,
83
+ event: t.event,
84
+ condition: t.condition ?? null,
85
+ action: t.action ?? null,
86
+ actor: t.actor ?? null,
87
+ edgeKind: t.edgeKind ?? null,
88
+ verify: t.verify ?? null,
89
+ })),
90
+ }),
91
+ );
92
+ }
93
+
94
+ for (const dt of extractDecisionTables(doc)) {
95
+ fingerprints.set(
96
+ `decision:${dt.id}`,
97
+ JSON.stringify({
98
+ reqId: dt.reqId,
99
+ title: dt.title,
100
+ headers: dt.headers,
101
+ rows: dt.rows,
102
+ }),
103
+ );
104
+ }
105
+
106
+ return { fingerprints, machines };
107
+ }
108
+
109
+ /**
110
+ * Pure domain diff between `baseRaw` (merge-base version or null when newly added)
111
+ * and `currentRaw` (working-tree version or null when deleted).
112
+ */
113
+ export function computeFeatureChangeDiff(
114
+ baseRaw: string | null,
115
+ currentRaw: string | null,
116
+ capId = 'spec',
117
+ ): FeatureChangeDiffResult {
118
+ const baseDoc = parseDocSafe(baseRaw);
119
+ const currentDoc = parseDocSafe(currentRaw);
120
+
121
+ const effectiveCapId = currentDoc?.featureName?.trim() || baseDoc?.featureName?.trim() || capId;
122
+
123
+ const baseRules = new Map<string, string>();
124
+ for (const r of baseDoc?.rules ?? []) {
125
+ if (r.reqId) baseRules.set(r.reqId, serializeRule(r));
126
+ }
127
+
128
+ const currentRules = new Map<string, string>();
129
+ const currentRuleOrder: string[] = [];
130
+ for (const r of currentDoc?.rules ?? []) {
131
+ if (r.reqId) {
132
+ currentRules.set(r.reqId, serializeRule(r));
133
+ currentRuleOrder.push(r.reqId);
134
+ }
135
+ }
136
+
137
+ const touchedReqIds: string[] = [];
138
+ const reqStatuses: Record<string, StudioChangeItemStatus> = {};
139
+
140
+ for (const reqId of currentRuleOrder) {
141
+ const prev = baseRules.get(reqId);
142
+ const next = currentRules.get(reqId)!;
143
+ if (prev === undefined) {
144
+ touchedReqIds.push(reqId);
145
+ reqStatuses[reqId] = 'added';
146
+ } else if (prev !== next) {
147
+ touchedReqIds.push(reqId);
148
+ reqStatuses[reqId] = 'modified';
149
+ }
150
+ }
151
+
152
+ for (const [reqId] of baseRules) {
153
+ if (!currentRules.has(reqId)) {
154
+ touchedReqIds.push(reqId);
155
+ reqStatuses[reqId] = 'deleted';
156
+ }
157
+ }
158
+
159
+ const baseExtracted = extractGraphFingerprints(baseDoc, effectiveCapId);
160
+ const currentExtracted = extractGraphFingerprints(currentDoc, effectiveCapId);
161
+ const baseGraphs = baseExtracted.fingerprints;
162
+ const currentGraphs = currentExtracted.fingerprints;
163
+
164
+ const touchedGraphIds: string[] = [];
165
+ const graphStatuses: Record<string, StudioChangeItemStatus> = {};
166
+ const baseMachines: Record<string, StudioMachineIR> = {};
167
+
168
+ for (const [graphId, fp] of currentGraphs) {
169
+ const prev = baseGraphs.get(graphId);
170
+ if (prev === undefined) {
171
+ touchedGraphIds.push(graphId);
172
+ graphStatuses[graphId] = 'added';
173
+ } else if (prev !== fp) {
174
+ touchedGraphIds.push(graphId);
175
+ graphStatuses[graphId] = 'modified';
176
+ const baseIr = baseExtracted.machines.get(graphId);
177
+ if (baseIr) baseMachines[graphId] = baseIr;
178
+ }
179
+ }
180
+
181
+ for (const [graphId] of baseGraphs) {
182
+ if (!currentGraphs.has(graphId)) {
183
+ touchedGraphIds.push(graphId);
184
+ graphStatuses[graphId] = 'deleted';
185
+ }
186
+ }
187
+
188
+ return {
189
+ touchedReqIds,
190
+ reqStatuses,
191
+ touchedGraphIds,
192
+ graphStatuses,
193
+ baseMachines,
194
+ };
195
+ }