@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
@@ -0,0 +1,592 @@
1
+ /**
2
+ * Lossless .feature transition-table rendering, proposal.md assembly, and in-memory Unified Diff
3
+ * preview via jsdiff (studio-core r133). Pure — zero filesystem I/O.
4
+ */
5
+ import { createTwoFilesPatch } from 'diff';
6
+
7
+ import { REQ_ID_RE, allocateNextReqId, formatReqRef } from '../spec/reqRef.ts';
8
+ import { computeMachineDiff, formatSemanticDiff } from './diff.ts';
9
+ import {
10
+ splitMachineKey,
11
+ type MachineDraft,
12
+ type StudioComment,
13
+ type StudioMachineIR,
14
+ } from './model.ts';
15
+
16
+ export class StudioSyncError extends Error {
17
+ constructor(message: string) {
18
+ super(message);
19
+ this.name = 'StudioSyncError';
20
+ }
21
+ }
22
+
23
+ const RULE_HEADER_RE = /^(\s*)(?:规则|Rule)\s*:\s*(.+?)\s*$/u;
24
+ const SCENARIO_HEADER_RE =
25
+ /^(\s*)(?:场景大纲|场景模板|场景|Scenario Outline|Scenario Template|Scenario)\s*:\s*(.+?)\s*$/u;
26
+ const EXAMPLES_HEADER_RE = /^(\s*)(?:例子|Examples|Scenarios)\s*:\s*.*$/u;
27
+
28
+ const OPTIONAL_NODE_COLS = ['类型', '引用', '执行方', '人类说明', '完成标准'] as const;
29
+
30
+ function formatTableLines(machine: StudioMachineIR, indent: string): string[] {
31
+ const stateNameByUid = new Map(machine.states.map((s) => [s.uid, s.name]));
32
+ const nameOf = (uid: string): string => stateNameByUid.get(uid) ?? uid;
33
+
34
+ const headers = [machine.columns.source, machine.columns.label, machine.columns.target];
35
+ const optionalKeys = [
36
+ ['condition', '条件'],
37
+ ['action', '动作'],
38
+ ['actor', '执行方'],
39
+ ['edgeKind', '边类型'],
40
+ ['meta', '元信息'],
41
+ ['verify', '验证'],
42
+ ] as const;
43
+ const activeOptional: Array<{ key: (typeof optionalKeys)[number][0]; header: string }> = [];
44
+ for (const [key, zh] of optionalKeys) {
45
+ const col = machine.columns[key];
46
+ const used = col !== undefined || machine.transitions.some((t) => (t[key] ?? '').trim() !== '');
47
+ if (used) activeOptional.push({ key, header: col ?? zh });
48
+ }
49
+ headers.push(...activeOptional.map((o) => o.header));
50
+
51
+ const orderedTransitions =
52
+ machine.initialStateUid !== null &&
53
+ machine.transitions.length > 1 &&
54
+ machine.transitions[0]?.fromUid !== machine.initialStateUid
55
+ ? (() => {
56
+ const idx = machine.transitions.findIndex((t) => t.fromUid === machine.initialStateUid);
57
+ if (idx <= 0) return machine.transitions;
58
+ const first = machine.transitions[idx];
59
+ if (!first) return machine.transitions;
60
+ return [
61
+ first,
62
+ ...machine.transitions.slice(0, idx),
63
+ ...machine.transitions.slice(idx + 1),
64
+ ];
65
+ })()
66
+ : machine.transitions;
67
+
68
+ const rows: string[][] = orderedTransitions.map((t) => [
69
+ nameOf(t.fromUid),
70
+ t.event,
71
+ nameOf(t.toUid),
72
+ ...activeOptional.map(({ key }) => (t[key] ?? '').trim()),
73
+ ]);
74
+
75
+ const allRows = [headers, ...rows];
76
+ const widths = headers.map((_, colIdx) =>
77
+ Math.max(...allRows.map((row) => (row[colIdx] ?? '').length), 1),
78
+ );
79
+
80
+ return allRows.map((row) => {
81
+ const cells = row.map((cell, idx) => cell.padEnd(widths[idx] ?? 0, ' '));
82
+ return `${indent}| ${cells.join(' | ')} |`;
83
+ });
84
+ }
85
+
86
+ function attributedStates(machine: StudioMachineIR) {
87
+ return machine.states.filter(
88
+ (s) =>
89
+ (s.nodeKind ?? '') !== '' ||
90
+ (s.nestKey ?? '') !== '' ||
91
+ (s.summary ?? '') !== '' ||
92
+ (s.done ?? '') !== '' ||
93
+ (s.actor ?? '') !== '',
94
+ );
95
+ }
96
+
97
+ function formatNestCell(machineKey: string): string {
98
+ const parts = splitMachineKey(machineKey);
99
+ if (parts === null || parts.reqId === null) {
100
+ throw new StudioSyncError(
101
+ `cannot write a 引用 cell for a draft machine without @req: ${machineKey}`,
102
+ );
103
+ }
104
+ return formatReqRef(parts.reqId, parts.scenarioName);
105
+ }
106
+
107
+ function formatNodesTableLines(machine: StudioMachineIR, indent: string): string[] {
108
+ const headers = ['节点', ...OPTIONAL_NODE_COLS];
109
+ const rows = attributedStates(machine).map((s) => [
110
+ s.name,
111
+ s.nodeKind ?? '',
112
+ s.nestKey ? formatNestCell(s.nestKey) : '',
113
+ s.actor ?? '',
114
+ s.summary ?? '',
115
+ s.done ?? '',
116
+ ]);
117
+ const allRows = [headers, ...rows];
118
+ const widths = headers.map((_, colIdx) =>
119
+ Math.max(...allRows.map((row) => (row[colIdx] ?? '').length), 1),
120
+ );
121
+ return allRows.map((row) => {
122
+ const cells = row.map((cell, idx) => cell.padEnd(widths[idx] ?? 0, ' '));
123
+ return `${indent}| ${cells.join(' | ')} |`;
124
+ });
125
+ }
126
+
127
+ function buildNodesOutlineBlock(machine: StudioMachineIR, indent = ' '): string[] {
128
+ if (attributedStates(machine).length === 0) return [];
129
+ const tableIndent = `${indent} `;
130
+ return [
131
+ `${indent}@nodes`,
132
+ `${indent}场景大纲: 节点属性`,
133
+ `${indent} 例子:`,
134
+ ...formatNodesTableLines(machine, tableIndent),
135
+ ];
136
+ }
137
+
138
+ function buildScenarioOutlineBlock(machine: StudioMachineIR, indent = ' '): string[] {
139
+ const tableIndent = `${indent} `;
140
+ const edgeTag = machine.graphKind === 'flow' ? '@flow' : '@state';
141
+
142
+ const lines = [
143
+ `${indent}${edgeTag}`,
144
+ `${indent}场景大纲: ${machine.scenarioName}`,
145
+ `${indent} 例子:`,
146
+ ...formatTableLines(machine, tableIndent),
147
+ ];
148
+ const nodesBlock = buildNodesOutlineBlock(machine, indent);
149
+ if (nodesBlock.length > 0) {
150
+ lines.push('', ...nodesBlock);
151
+ }
152
+ return lines;
153
+ }
154
+
155
+ function lineHasTag(line: string, tag: string): boolean {
156
+ return new RegExp(`(?:^|\\s)@${tag}(?:\\s|$)`, 'u').test(line.trim());
157
+ }
158
+
159
+ /**
160
+ * Resolve the `@req:` id a create draft will land with: an already-valid `rN`
161
+ * is kept, otherwise the repo-wide next `r<max+1>` is allocated. There is no
162
+ * placeholder fallback — a draft without ids and without `existingReqIds` fails.
163
+ */
164
+ function resolveDraftReqId(
165
+ machine: StudioMachineIR,
166
+ existingReqIds: Iterable<string> | undefined,
167
+ ): string {
168
+ const current = machine.reqId?.trim() ?? '';
169
+ if (REQ_ID_RE.test(current)) return current;
170
+ if (existingReqIds === undefined) {
171
+ throw new StudioSyncError(
172
+ `create draft \`${machine.machineKey}\` has no @req id — pass existingReqIds to allocate r<max+1>`,
173
+ );
174
+ }
175
+ return allocateNextReqId(existingReqIds);
176
+ }
177
+
178
+ function buildRuleBlock(machine: StudioMachineIR, existingReqIds?: Iterable<string>): string[] {
179
+ const reqTag = resolveDraftReqId(machine, existingReqIds);
180
+ return [
181
+ ` @req:${reqTag}`,
182
+ ` 规则: ${machine.ruleTitle}`,
183
+ ` ${machine.ruleTitle} MUST 遵循状态流转表约束并通过 E1–E4 图校验。`,
184
+ '',
185
+ ...buildScenarioOutlineBlock(machine, ' '),
186
+ ];
187
+ }
188
+
189
+ interface ScenarioSpan {
190
+ ruleStartIdx: number;
191
+ ruleEndIdx: number;
192
+ scenarioStartIdx: number;
193
+ scenarioEndIdx: number;
194
+ examplesHeaderIdx: number;
195
+ tableStartIdx: number;
196
+ tableEndIdx: number;
197
+ tableIndent: string;
198
+ otherScenariosInRule: number;
199
+ }
200
+
201
+ function locateScenarioSpan(
202
+ lines: readonly string[],
203
+ target: Pick<StudioMachineIR, 'reqId' | 'ruleTitle' | 'scenarioName'>,
204
+ ): ScenarioSpan | null {
205
+ interface RuleRange {
206
+ startIdx: number;
207
+ endIdx: number;
208
+ reqId: string | null;
209
+ title: string;
210
+ }
211
+
212
+ const ruleRanges: RuleRange[] = [];
213
+ for (let i = 0; i < lines.length; i += 1) {
214
+ const m = RULE_HEADER_RE.exec(lines[i] ?? '');
215
+ if (!m) continue;
216
+ let startIdx = i;
217
+ let reqId: string | null = null;
218
+ for (let j = i - 1; j >= 0; j -= 1) {
219
+ const trimmed = (lines[j] ?? '').trim();
220
+ if (trimmed.startsWith('@')) {
221
+ startIdx = j;
222
+ const rm = /@req:([^\s]+)/u.exec(trimmed);
223
+ if (rm?.[1]) reqId = rm[1];
224
+ } else {
225
+ break;
226
+ }
227
+ }
228
+ const prev = ruleRanges.at(-1);
229
+ if (prev) prev.endIdx = startIdx;
230
+ ruleRanges.push({ startIdx, endIdx: lines.length, reqId, title: (m[2] ?? '').trim() });
231
+ }
232
+
233
+ for (const rr of ruleRanges) {
234
+ const ruleMatches =
235
+ (target.reqId !== null && target.reqId !== '' && rr.reqId === target.reqId) ||
236
+ rr.title === target.ruleTitle.trim();
237
+ if (!ruleMatches) continue;
238
+
239
+ const scStarts: Array<{ startIdx: number; headerIdx: number; name: string }> = [];
240
+ for (let i = rr.startIdx; i < rr.endIdx; i += 1) {
241
+ const sm = SCENARIO_HEADER_RE.exec(lines[i] ?? '');
242
+ if (!sm) continue;
243
+ let startIdx = i;
244
+ for (let j = i - 1; j >= rr.startIdx; j -= 1) {
245
+ if ((lines[j] ?? '').trim().startsWith('@')) startIdx = j;
246
+ else break;
247
+ }
248
+ scStarts.push({ startIdx, headerIdx: i, name: (sm[2] ?? '').trim() });
249
+ }
250
+
251
+ const matchIdx = scStarts.findIndex((s) => s.name === target.scenarioName.trim());
252
+ if (matchIdx === -1) continue;
253
+
254
+ const hit = scStarts[matchIdx];
255
+ if (!hit) continue;
256
+ const scenarioEndIdx = scStarts[matchIdx + 1]?.startIdx ?? rr.endIdx;
257
+
258
+ let examplesHeaderIdx = -1;
259
+ for (let i = hit.headerIdx + 1; i < scenarioEndIdx; i += 1) {
260
+ if (EXAMPLES_HEADER_RE.test(lines[i] ?? '')) {
261
+ examplesHeaderIdx = i;
262
+ break;
263
+ }
264
+ }
265
+ if (examplesHeaderIdx === -1) return null;
266
+
267
+ let tableStartIdx = -1;
268
+ let tableEndIdx = -1;
269
+ let tableIndent = ' ';
270
+ for (let i = examplesHeaderIdx + 1; i < scenarioEndIdx; i += 1) {
271
+ const line = lines[i] ?? '';
272
+ const trimmed = line.trim();
273
+ if (trimmed.startsWith('|')) {
274
+ if (tableStartIdx === -1) {
275
+ tableStartIdx = i;
276
+ tableIndent = /^(\s*)/u.exec(line)?.[1] ?? ' ';
277
+ }
278
+ tableEndIdx = i + 1;
279
+ } else if (tableStartIdx !== -1) {
280
+ break;
281
+ }
282
+ }
283
+ if (tableStartIdx === -1 || tableEndIdx === -1) return null;
284
+
285
+ return {
286
+ ruleStartIdx: rr.startIdx,
287
+ ruleEndIdx: rr.endIdx,
288
+ scenarioStartIdx: hit.startIdx,
289
+ scenarioEndIdx,
290
+ examplesHeaderIdx,
291
+ tableStartIdx,
292
+ tableEndIdx,
293
+ tableIndent,
294
+ otherScenariosInRule: scStarts.length - 1,
295
+ };
296
+ }
297
+
298
+ return null;
299
+ }
300
+
301
+ function locateStatesSpan(
302
+ lines: readonly string[],
303
+ ruleStartIdx: number,
304
+ ruleEndIdx: number,
305
+ ): Pick<
306
+ ScenarioSpan,
307
+ 'scenarioStartIdx' | 'scenarioEndIdx' | 'tableStartIdx' | 'tableEndIdx' | 'tableIndent'
308
+ > | null {
309
+ const scStarts: Array<{ startIdx: number; headerIdx: number }> = [];
310
+ for (let i = ruleStartIdx; i < ruleEndIdx; i += 1) {
311
+ const sm = SCENARIO_HEADER_RE.exec(lines[i] ?? '');
312
+ if (!sm) continue;
313
+ let startIdx = i;
314
+ let hasStates = false;
315
+ for (let j = i - 1; j >= ruleStartIdx; j -= 1) {
316
+ const trimmed = (lines[j] ?? '').trim();
317
+ if (trimmed.startsWith('@')) {
318
+ startIdx = j;
319
+ if (lineHasTag(trimmed, 'nodes')) hasStates = true;
320
+ } else {
321
+ break;
322
+ }
323
+ }
324
+ if (hasStates) scStarts.push({ startIdx, headerIdx: i });
325
+ }
326
+ const hit = scStarts[0];
327
+ if (!hit) return null;
328
+ const scenarioEndIdx = scStarts[1]?.startIdx ?? ruleEndIdx;
329
+ let examplesHeaderIdx = -1;
330
+ for (let i = hit.headerIdx + 1; i < scenarioEndIdx; i += 1) {
331
+ if (EXAMPLES_HEADER_RE.test(lines[i] ?? '')) {
332
+ examplesHeaderIdx = i;
333
+ break;
334
+ }
335
+ }
336
+ if (examplesHeaderIdx === -1) return null;
337
+ let tableStartIdx = -1;
338
+ let tableEndIdx = -1;
339
+ let tableIndent = ' ';
340
+ for (let i = examplesHeaderIdx + 1; i < scenarioEndIdx; i += 1) {
341
+ const line = lines[i] ?? '';
342
+ const trimmed = line.trim();
343
+ if (trimmed.startsWith('|')) {
344
+ if (tableStartIdx === -1) {
345
+ tableStartIdx = i;
346
+ tableIndent = /^(\s*)/u.exec(line)?.[1] ?? ' ';
347
+ }
348
+ tableEndIdx = i + 1;
349
+ } else if (tableStartIdx !== -1) {
350
+ break;
351
+ }
352
+ }
353
+ if (tableStartIdx === -1 || tableEndIdx === -1) return null;
354
+ return {
355
+ scenarioStartIdx: hit.startIdx,
356
+ scenarioEndIdx,
357
+ tableStartIdx,
358
+ tableEndIdx,
359
+ tableIndent,
360
+ };
361
+ }
362
+
363
+ function syncEdgeDialectTag(lines: string[], span: ScenarioSpan, wantFlow: boolean): void {
364
+ for (let i = span.scenarioStartIdx; i < span.examplesHeaderIdx && i < lines.length; i += 1) {
365
+ const line = lines[i] ?? '';
366
+ const trimmed = line.trim();
367
+ if (!trimmed.startsWith('@')) continue;
368
+ const indent = /^(\s*)/u.exec(line)?.[1] ?? '';
369
+ const hasFlow = lineHasTag(trimmed, 'flow');
370
+ const hasState = lineHasTag(trimmed, 'state');
371
+ if (!hasFlow && !hasState) continue;
372
+ const wantTag = wantFlow ? '@flow' : '@state';
373
+ lines[i] = `${indent}${wantTag}`;
374
+ return;
375
+ }
376
+ const indent = /^(\s*)/u.exec(lines[span.scenarioStartIdx] ?? '')?.[1] ?? ' ';
377
+ lines.splice(span.scenarioStartIdx, 0, `${indent}${wantFlow ? '@flow' : '@state'}`);
378
+ }
379
+
380
+ /**
381
+ * Losslessly render updated `.feature` source for `modify`, `create`, or `remove` drafts.
382
+ * Semantically locates the target `例子:` block — immune to line-number drift above or below.
383
+ */
384
+ export interface RenderFeatureOptions {
385
+ /**
386
+ * Repo-wide used `@req:` ids. Create drafts without a valid `reqId` allocate
387
+ * `r<max+1>` from this set; omitting it makes such a render fail loudly.
388
+ */
389
+ existingReqIds?: Iterable<string>;
390
+ }
391
+
392
+ export function renderUpdatedFeatureSource(
393
+ originalText: string | null,
394
+ draft: MachineDraft,
395
+ options: RenderFeatureOptions = {},
396
+ ): string {
397
+ if (draft.mode === 'create') {
398
+ const machine = draft.current;
399
+ if (!machine) throw new StudioSyncError('create draft has no current machine IR');
400
+ if (originalText === null || originalText.trim() === '') {
401
+ const out = [
402
+ '# language: zh-CN',
403
+ `# purpose: 定义 ${machine.capability} 能力的状态流转与行为合约。`,
404
+ '',
405
+ `功能: ${machine.capability}`,
406
+ '',
407
+ ...buildRuleBlock(machine, options.existingReqIds),
408
+ ];
409
+ return `${out.join('\n')}\n`;
410
+ }
411
+ const baseTrimmed = originalText.replace(/\s+$/u, '');
412
+ return `${baseTrimmed}\n\n${buildRuleBlock(machine, options.existingReqIds).join('\n')}\n`;
413
+ }
414
+
415
+ if (originalText === null) {
416
+ throw new StudioSyncError(`source file does not exist for ${draft.mode}: ${draft.sourceFile}`);
417
+ }
418
+
419
+ const trailingNewline = originalText.endsWith('\n');
420
+ const rawLines = (trailingNewline ? originalText.slice(0, -1) : originalText).split('\n');
421
+
422
+ if (draft.mode === 'remove') {
423
+ const target = draft.baseline;
424
+ if (!target) throw new StudioSyncError('remove draft has no baseline machine IR');
425
+ const span = locateScenarioSpan(rawLines, target);
426
+ if (!span) {
427
+ throw new StudioSyncError(
428
+ `target transition scenario not found for removal: ${target.scenarioName} in ${draft.sourceFile}`,
429
+ );
430
+ }
431
+ const removeFrom = span.otherScenariosInRule === 0 ? span.ruleStartIdx : span.scenarioStartIdx;
432
+ const removeTo = span.otherScenariosInRule === 0 ? span.ruleEndIdx : span.scenarioEndIdx;
433
+ const nextLines = [...rawLines.slice(0, removeFrom), ...rawLines.slice(removeTo)];
434
+ const cleaned = nextLines
435
+ .join('\n')
436
+ .replaceAll(/\n{3,}/gu, '\n\n')
437
+ .trimEnd();
438
+ return `${cleaned}\n`;
439
+ }
440
+
441
+ const machine = draft.current;
442
+ if (!machine) throw new StudioSyncError('modify draft has no current machine IR');
443
+ const locatorTarget = draft.baseline ?? machine;
444
+ const span = locateScenarioSpan(rawLines, locatorTarget);
445
+ if (!span) {
446
+ throw new StudioSyncError(
447
+ `target transition scenario not found: ${locatorTarget.scenarioName} in ${draft.sourceFile}`,
448
+ );
449
+ }
450
+ const diff = computeMachineDiff(draft);
451
+ if (!diff.hasChanges) {
452
+ return originalText;
453
+ }
454
+
455
+ const transitionDirty =
456
+ diff.statesAdded.length +
457
+ diff.statesRemoved.length +
458
+ diff.statesRenamed.length +
459
+ diff.transitionsAdded.length +
460
+ diff.transitionsRemoved.length +
461
+ diff.transitionsModified.length >
462
+ 0;
463
+ const attrDirty =
464
+ diff.nestLinksChanged.length > 0 ||
465
+ diff.nodeKindsChanged.length > 0 ||
466
+ diff.nodeMetaChanged.length > 0;
467
+ const flowDirty = diff.graphKindChanged;
468
+ const attrs = attributedStates(machine);
469
+
470
+ let nextLines = [...rawLines];
471
+ if (transitionDirty) {
472
+ const newTable = formatTableLines(machine, span.tableIndent);
473
+ nextLines = [
474
+ ...nextLines.slice(0, span.tableStartIdx),
475
+ ...newTable,
476
+ ...nextLines.slice(span.tableEndIdx),
477
+ ];
478
+ }
479
+
480
+ if (flowDirty) {
481
+ const spanNow = locateScenarioSpan(nextLines, locatorTarget);
482
+ if (spanNow) syncEdgeDialectTag(nextLines, spanNow, machine.graphKind === 'flow');
483
+ }
484
+
485
+ if (attrDirty || diff.statesRenamed.length > 0) {
486
+ const spanNow = locateScenarioSpan(nextLines, locatorTarget);
487
+ const statesSpan = spanNow
488
+ ? locateStatesSpan(nextLines, spanNow.ruleStartIdx, spanNow.ruleEndIdx)
489
+ : null;
490
+ if (attrs.length === 0 && statesSpan) {
491
+ nextLines = [
492
+ ...nextLines.slice(0, statesSpan.scenarioStartIdx),
493
+ ...nextLines.slice(statesSpan.scenarioEndIdx),
494
+ ];
495
+ } else if (attrs.length > 0 && statesSpan) {
496
+ const newTable = formatNodesTableLines(machine, statesSpan.tableIndent);
497
+ nextLines = [
498
+ ...nextLines.slice(0, statesSpan.tableStartIdx),
499
+ ...newTable,
500
+ ...nextLines.slice(statesSpan.tableEndIdx),
501
+ ];
502
+ } else if (attrs.length > 0 && spanNow && !statesSpan) {
503
+ const insertAt = spanNow.scenarioEndIdx;
504
+ const indent = /^(\s*)/u.exec(nextLines[spanNow.scenarioStartIdx] ?? '')?.[1] ?? ' ';
505
+ const block = ['', ...buildNodesOutlineBlock(machine, indent)];
506
+ nextLines = [...nextLines.slice(0, insertAt), ...block, ...nextLines.slice(insertAt)];
507
+ }
508
+ }
509
+
510
+ const joined = nextLines.join('\n').replaceAll(/\n{3,}/gu, '\n\n');
511
+ return `${joined}${trailingNewline ? '\n' : ''}`;
512
+ }
513
+
514
+ /** Generate in-memory standard Unified Diff preview via jsdiff (zero patch files written). */
515
+ export function previewFeatureUnifiedDiff(
516
+ filePath: string,
517
+ beforeText: string | null,
518
+ afterText: string,
519
+ ): string {
520
+ const oldLabel = beforeText === null ? '/dev/null' : `a/${filePath}`;
521
+ const newLabel = `b/${filePath}`;
522
+ return createTwoFilesPatch(oldLabel, newLabel, beforeText ?? '', afterText, '', '', {
523
+ context: 3,
524
+ });
525
+ }
526
+
527
+ export interface BuildProposalDraftInput {
528
+ title: string;
529
+ why: string;
530
+ drafts: readonly MachineDraft[];
531
+ comments?: readonly StudioComment[];
532
+ dependsOn?: readonly string[];
533
+ }
534
+
535
+ /** Assemble a compliant `llmanspec/changes/<id>/proposal.md` document from Studio drafts. */
536
+ export function buildProposalDraft(input: BuildProposalDraftInput): string {
537
+ const title = input.title.trim();
538
+ if (title === '') throw new StudioSyncError('proposal title must not be empty');
539
+ const deps = input.dependsOn ?? [];
540
+ const depsYaml =
541
+ deps.length === 0 ? 'depends_on: []' : `depends_on:\n${deps.map((d) => ` - ${d}`).join('\n')}`;
542
+
543
+ const capabilities = new Set<string>();
544
+ const diffSections: string[] = [];
545
+
546
+ for (const draft of input.drafts) {
547
+ const cap = draft.current?.capability ?? draft.baseline?.capability;
548
+ if (cap) capabilities.add(cap);
549
+ const diff = computeMachineDiff(draft);
550
+ const key = draft.current?.machineKey ?? draft.baseline?.machineKey ?? draft.sourceFile;
551
+ diffSections.push(
552
+ `- **\`${key}\`** (${draft.mode}):\n\n\`\`\`diff\n${formatSemanticDiff(diff, draft)}\n\`\`\``,
553
+ );
554
+ }
555
+
556
+ const commentLines = (input.comments ?? []).map((c) => `- [${c.author}/${c.status}] ${c.body}`);
557
+
558
+ const sections = [
559
+ '---',
560
+ depsYaml,
561
+ `title: ${title}`,
562
+ '---',
563
+ '',
564
+ `# ${title}`,
565
+ '',
566
+ '## Why',
567
+ '',
568
+ input.why.trim(),
569
+ '',
570
+ '## What Changes',
571
+ '',
572
+ ...(diffSections.length > 0 ? diffSections : ['- (no semantic state machine diffs)']),
573
+ ];
574
+
575
+ if (commentLines.length > 0) {
576
+ sections.push('', '### Key Discussion Notes', '', ...commentLines);
577
+ }
578
+
579
+ sections.push(
580
+ '',
581
+ '## Capabilities',
582
+ '',
583
+ ...[...capabilities].toSorted().map((c) => `- \`${c}\``),
584
+ '',
585
+ '## Impact',
586
+ '',
587
+ '- Generated from Studio local draft; bind a change branch via `llman-sdd change start <id>` and run `llman-sdd studio apply` to land specs safely.',
588
+ '',
589
+ );
590
+
591
+ return sections.join('\n');
592
+ }