@llman-sdd/core 0.11.0 → 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 (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,72 @@
1
+ /**
2
+ * Tier 0 deterministic offline AST 5-level semantic folding for `.feature` specs (studio-web r145).
3
+ * Produces 5 compact levels [0: full, 1: brief, 2: key-clauses, 3: bullets, 4: headline]
4
+ * with zero external dependencies and zero LLM tokens. Pure — zero I/O.
5
+ */
6
+ import type { CapabilityDoc } from '../spec/ir.ts';
7
+
8
+ export type TextfoldLevels = [string, string, string, string, string];
9
+
10
+ function truncateText(text: string, maxLen: number): string {
11
+ const clean = text.replaceAll(/\s+/gu, ' ').trim();
12
+ if (clean.length <= maxLen) return clean;
13
+ return `${clean.slice(0, Math.max(0, maxLen - 1)).trimEnd()}…`;
14
+ }
15
+
16
+ /** Fold a parsed CapabilityDoc deterministically into 5 progressive semantic summary levels. */
17
+ export function foldFeatureAst(doc: CapabilityDoc, rawText = ''): TextfoldLevels {
18
+ const purpose = (doc.header.purpose ?? '').trim() || doc.featureName;
19
+ const ruleCount = doc.rules.length;
20
+ const scenarioCount =
21
+ doc.rules.reduce((sum, r) => sum + r.scenarios.length, 0) + doc.orphans.length;
22
+ const reqIds = doc.rules.map((r) => `@req:${r.reqId}`).filter((id) => id !== '@req:');
23
+ const reqPreview =
24
+ reqIds.length <= 3
25
+ ? reqIds.join(' / ')
26
+ : `${reqIds.slice(0, 3).join(' / ')} 等共 ${String(reqIds.length)} 条`;
27
+
28
+ const level4 = truncateText(`${doc.featureName}:${purpose}`, 72);
29
+ const level3 =
30
+ ruleCount > 0
31
+ ? `共 ${String(ruleCount)} 条规格规则、${String(scenarioCount)} 个场景${reqPreview ? `(${reqPreview})` : ''}。`
32
+ : truncateText(purpose, 110);
33
+ const level2 =
34
+ ruleCount > 0
35
+ ? doc.rules
36
+ .slice(0, 3)
37
+ .map((r) => `@req:${r.reqId} ${r.title}`)
38
+ .join(';') + (ruleCount > 3 ? ` 等共 ${String(ruleCount)} 条规则` : '')
39
+ : truncateText(purpose, 160);
40
+ const level1 =
41
+ ruleCount > 0
42
+ ? `${purpose}\n` +
43
+ doc.rules
44
+ .slice(0, 6)
45
+ .map(
46
+ (r) => `- [@req:${r.reqId}] ${r.title}:${truncateText(r.description || r.title, 70)}`,
47
+ )
48
+ .join('\n')
49
+ : truncateText(rawText || purpose, 400);
50
+ const level0 =
51
+ rawText.trim() !== ''
52
+ ? rawText
53
+ : `${purpose}\n\n` +
54
+ doc.rules.map((r) => `[@req:${r.reqId}] ${r.title}\n${r.description}`).join('\n\n');
55
+
56
+ return [level0, level1, level2, level3, level4];
57
+ }
58
+
59
+ /** Fallback deterministic 5-level folding for arbitrary plain text when no CapabilityDoc is parsed. */
60
+ export function foldPlainText(content: string): TextfoldLevels {
61
+ const trimmed = content.trim();
62
+ const lines = trimmed
63
+ .split('\n')
64
+ .map((l) => l.trim())
65
+ .filter((l) => l !== '');
66
+ const firstLine = lines[0] ?? '';
67
+ const level4 = truncateText(firstLine, 72);
68
+ const level3 = truncateText(lines.slice(0, 2).join(' '), 120);
69
+ const level2 = truncateText(lines.slice(0, 4).join(';'), 220);
70
+ const level1 = truncateText(lines.slice(0, 10).join('\n'), 500);
71
+ return [trimmed, level1, level2, level3, level4];
72
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Studio worldline clock formatting and retention (studio-core r187).
3
+ * Pure: zero I/O, zero wall clock; nowIso and timeZone are injected.
4
+ */
5
+ import type { MachineTimeline, StudioStateDoc, TimelineEntry } from './model.ts';
6
+
7
+ function localYmd(iso: string, timeZone: string): string {
8
+ return new Intl.DateTimeFormat('en-CA', {
9
+ timeZone,
10
+ year: 'numeric',
11
+ month: '2-digit',
12
+ day: '2-digit',
13
+ }).format(new Date(iso));
14
+ }
15
+
16
+ function addCalendarDays(ymd: string, delta: number): string {
17
+ const [year, month, day] = ymd.split('-').map(Number);
18
+ const utc = Date.UTC(year ?? 0, (month ?? 1) - 1, (day ?? 1) + delta);
19
+ return new Date(utc).toISOString().slice(0, 10);
20
+ }
21
+
22
+ function windowCutoffYmd(nowIso: string, timeZone: string, windowDays: number): string {
23
+ const today = localYmd(nowIso, timeZone);
24
+ return addCalendarDays(today, -(windowDays - 1));
25
+ }
26
+
27
+ /** Format an injected ISO timestamp in the given IANA time zone, with local date and offset. */
28
+ export function formatStudioDateTime(iso: string, timeZone: string): string {
29
+ return new Intl.DateTimeFormat('zh-CN', {
30
+ timeZone,
31
+ year: 'numeric',
32
+ month: '2-digit',
33
+ day: '2-digit',
34
+ hour: '2-digit',
35
+ minute: '2-digit',
36
+ second: '2-digit',
37
+ hourCycle: 'h23',
38
+ timeZoneName: 'shortOffset',
39
+ }).format(new Date(iso));
40
+ }
41
+
42
+ export function partitionTimelineEntries(
43
+ entries: readonly TimelineEntry[],
44
+ nowIso: string,
45
+ timeZone: string,
46
+ windowDays = 7,
47
+ ): { recent: TimelineEntry[]; older: TimelineEntry[] } {
48
+ const cutoff = windowCutoffYmd(nowIso, timeZone, windowDays);
49
+ const recent: TimelineEntry[] = [];
50
+ const older: TimelineEntry[] = [];
51
+ for (const entry of entries) {
52
+ if (localYmd(entry.createdAt, timeZone) >= cutoff) recent.push(entry);
53
+ else older.push(entry);
54
+ }
55
+ return { recent, older };
56
+ }
57
+
58
+ function ancestorIds(timeline: MachineTimeline): Set<string> {
59
+ const byId = new Map(timeline.entries.map((e) => [e.id, e]));
60
+ const keep = new Set<string>();
61
+ let cur: TimelineEntry | undefined = timeline.entries[timeline.headIdx];
62
+ const seen = new Set<string>();
63
+ while (cur && !seen.has(cur.id)) {
64
+ seen.add(cur.id);
65
+ keep.add(cur.id);
66
+ if (!cur.parentId) break;
67
+ cur = byId.get(cur.parentId);
68
+ }
69
+ return keep;
70
+ }
71
+
72
+ /** Drop fork cells older than retainDays unless they sit on the current head ancestor chain. */
73
+ export function pruneTimelineEntries(
74
+ timeline: MachineTimeline,
75
+ nowIso: string,
76
+ timeZone: string,
77
+ retainDays = 30,
78
+ ): MachineTimeline {
79
+ const ancestors = ancestorIds(timeline);
80
+ const cutoff = windowCutoffYmd(nowIso, timeZone, retainDays);
81
+ const entries = timeline.entries.filter((entry) => {
82
+ if (entry.isBase || ancestors.has(entry.id)) return true;
83
+ return localYmd(entry.createdAt, timeZone) >= cutoff;
84
+ });
85
+ const headId = timeline.entries[timeline.headIdx]?.id;
86
+ const found = headId === undefined ? -1 : entries.findIndex((e) => e.id === headId);
87
+ return { entries, headIdx: found < 0 ? Math.max(0, entries.length - 1) : found };
88
+ }
89
+
90
+ /** Prune every machine timeline in a Studio state doc without touching specs or non-timeline data. */
91
+ export function pruneStudioTimelines(
92
+ doc: StudioStateDoc,
93
+ nowIso: string,
94
+ timeZone: string,
95
+ retainDays = 30,
96
+ ): StudioStateDoc {
97
+ let changed = false;
98
+ const timelines = { ...doc.timelines };
99
+ for (const [machineKey, timeline] of Object.entries(doc.timelines)) {
100
+ const next = pruneTimelineEntries(timeline, nowIso, timeZone, retainDays);
101
+ if (next.entries.length !== timeline.entries.length || next.headIdx !== timeline.headIdx) {
102
+ timelines[machineKey] = next;
103
+ changed = true;
104
+ }
105
+ }
106
+ return changed ? { ...doc, timelines } : doc;
107
+ }
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Extensible full-graph Linter for StudioMachineIR (studio-core r129).
3
+ * Collects ALL diagnostics (blocking E1-E4 errors + non-blocking W1-W2 warnings)
4
+ * with exact stateUid / edgeUid anchors using @statelyai/graph. Pure — zero I/O.
5
+ */
6
+ import { addEdge, addNode, createGraph, genBFS, hasPath } from '@statelyai/graph';
7
+
8
+ import type { StudioMachineIR } from './model.ts';
9
+
10
+ export type DiagnosticSeverity = 'error' | 'warning';
11
+ export type DiagnosticTargetKind = 'machine' | 'state' | 'edge';
12
+ export type DiagnosticFixKind = 'delete-edge';
13
+
14
+ export interface StudioLinterRuleMeta {
15
+ code: string;
16
+ severity: DiagnosticSeverity;
17
+ name: string;
18
+ description: string;
19
+ }
20
+
21
+ export interface MachineDiagnostic {
22
+ code: string;
23
+ severity: DiagnosticSeverity;
24
+ targetKind: DiagnosticTargetKind;
25
+ targetId: string | null;
26
+ /** Additional related edge uids (e.g. both conflicting edges on E2). */
27
+ relatedIds?: string[];
28
+ fixable?: DiagnosticFixKind;
29
+ message: string;
30
+ }
31
+
32
+ export const STUDIO_LINTER_RULES: readonly StudioLinterRuleMeta[] = [
33
+ {
34
+ code: 'E1',
35
+ severity: 'error',
36
+ name: 'Structure completeness',
37
+ description: 'At least 2 distinct non-empty states and 1 valid non-empty transition',
38
+ },
39
+ {
40
+ code: 'E2',
41
+ severity: 'error',
42
+ name: 'Determinism conflict',
43
+ description: 'Duplicate (fromUid, event, condition) transition on the same source state',
44
+ },
45
+ {
46
+ code: 'E3',
47
+ severity: 'error',
48
+ name: 'Unreachable state',
49
+ description: 'Every state must be reachable from initialStateUid',
50
+ },
51
+ {
52
+ code: 'E4',
53
+ severity: 'error',
54
+ name: 'Deadlock or trap',
55
+ description: 'Non-terminal states must reach a terminal state (or return to initial state)',
56
+ },
57
+ {
58
+ code: 'W1',
59
+ severity: 'warning',
60
+ name: 'Condition fallback missing',
61
+ description: 'State with a single conditioned outgoing edge has no fallback branch',
62
+ },
63
+ {
64
+ code: 'W2',
65
+ severity: 'warning',
66
+ name: 'Placeholder state name',
67
+ description: 'Draft placeholder name should be replaced with a domain state name',
68
+ },
69
+ ] as const;
70
+
71
+ const PLACEHOLDER_NAME_RE = /^(新状态|中间态|终态|新步骤|条件判断|state|step)\d+$/iu;
72
+
73
+ export const FLOWCHART_LINTER_RULES: readonly StudioLinterRuleMeta[] = [
74
+ {
75
+ code: 'F1',
76
+ severity: 'error',
77
+ name: 'Flow start/end completeness',
78
+ description: 'Flowchart requires at least 2 distinct steps, 1 transition, and a start step',
79
+ },
80
+ {
81
+ code: 'F2',
82
+ severity: 'error',
83
+ name: 'Unreachable flow step',
84
+ description: 'Every step must be reachable from the start step',
85
+ },
86
+ {
87
+ code: 'F3',
88
+ severity: 'warning',
89
+ name: 'Judgment branch completeness',
90
+ description: 'Judgment step should have at least 2 outgoing branches',
91
+ },
92
+ {
93
+ code: 'F4',
94
+ severity: 'warning',
95
+ name: 'Placeholder step name',
96
+ description: 'Draft placeholder step name should be replaced with a domain action',
97
+ },
98
+ ] as const;
99
+
100
+ function validateFlowchartGraph(machine: StudioMachineIR): MachineDiagnostic[] {
101
+ const diagnostics: MachineDiagnostic[] = [];
102
+ const stateByUid = new Map(machine.states.map((s) => [s.uid, s]));
103
+ const nameOf = (uid: string): string => stateByUid.get(uid)?.name || uid;
104
+ const validEdges = machine.transitions.filter(
105
+ (e) => stateByUid.has(e.fromUid) && stateByUid.has(e.toUid),
106
+ );
107
+
108
+ const distinctNames = new Set(machine.states.map((s) => s.name.trim()).filter((n) => n !== ''));
109
+ if (distinctNames.size < 2 || validEdges.length < 1) {
110
+ diagnostics.push({
111
+ code: 'F1',
112
+ severity: 'error',
113
+ targetKind: 'machine',
114
+ targetId: null,
115
+ message: 'F1 structure: flowchart requires at least 2 steps and 1 valid connection',
116
+ });
117
+ }
118
+ const initialUid =
119
+ machine.initialStateUid && stateByUid.has(machine.initialStateUid)
120
+ ? machine.initialStateUid
121
+ : (validEdges[0]?.fromUid ?? machine.states[0]?.uid ?? null);
122
+
123
+ if (initialUid !== null && machine.states.length > 0) {
124
+ const graph = createGraph();
125
+ for (const s of machine.states) addNode(graph, { id: s.uid });
126
+ for (const e of validEdges) {
127
+ addEdge(graph, { id: e.uid, sourceId: e.fromUid, targetId: e.toUid });
128
+ }
129
+ const reachable = new Set(
130
+ [...genBFS(graph, initialUid)]
131
+ .map((n) => (typeof n === 'object' && n !== null && 'id' in n ? String(n.id) : String(n)))
132
+ .filter((id) => id !== ''),
133
+ );
134
+ for (const s of machine.states) {
135
+ if (!reachable.has(s.uid)) {
136
+ diagnostics.push({
137
+ code: 'F2',
138
+ severity: 'error',
139
+ targetKind: 'state',
140
+ targetId: s.uid,
141
+ message: `F2 unreachable: step \`${s.name}\` cannot be reached from \`${nameOf(initialUid)}\``,
142
+ });
143
+ }
144
+ }
145
+ }
146
+
147
+ for (const s of machine.states) {
148
+ if (s.nodeKind === '判断') {
149
+ const outs = validEdges.filter((e) => e.fromUid === s.uid);
150
+ if (outs.length < 2) {
151
+ diagnostics.push({
152
+ code: 'F3',
153
+ severity: 'warning',
154
+ targetKind: 'state',
155
+ targetId: s.uid,
156
+ message: `F3 judgment: step \`${s.name}\` has ${String(outs.length)} outgoing branch(es); expected >= 2`,
157
+ });
158
+ }
159
+ }
160
+ if (PLACEHOLDER_NAME_RE.test(s.name.trim())) {
161
+ diagnostics.push({
162
+ code: 'F4',
163
+ severity: 'warning',
164
+ targetKind: 'state',
165
+ targetId: s.uid,
166
+ message: `F4 placeholder name: step \`${s.name}\` should be renamed to a concrete action`,
167
+ });
168
+ }
169
+ }
170
+
171
+ return diagnostics;
172
+ }
173
+
174
+ /**
175
+ * Validate a StudioMachineIR against dialect-isolated rules:
176
+ * - graphKind === 'flow': Flowchart Linter (F1-F4)
177
+ * - default ('machine'): State Machine Linter (E1-E4 blocking errors + W1-W2 warnings)
178
+ * Never short-circuits on the first error so interactive UI can highlight every issue at once.
179
+ */
180
+ export function validateMachineGraph(machine: StudioMachineIR): MachineDiagnostic[] {
181
+ if (machine.graphKind === 'flow') {
182
+ return validateFlowchartGraph(machine);
183
+ }
184
+ const diagnostics: MachineDiagnostic[] = [];
185
+ const stateByUid = new Map(machine.states.map((s) => [s.uid, s]));
186
+ const nameOf = (uid: string): string => stateByUid.get(uid)?.name || uid;
187
+
188
+ const distinctNonEmptyNames = new Set(
189
+ machine.states.map((s) => s.name.trim()).filter((n) => n !== ''),
190
+ );
191
+ if (distinctNonEmptyNames.size < 2 || machine.transitions.length < 1) {
192
+ diagnostics.push({
193
+ code: 'E1',
194
+ severity: 'error',
195
+ targetKind: 'machine',
196
+ targetId: null,
197
+ message: 'E1 structure: machine requires at least 2 distinct states and 1 transition',
198
+ });
199
+ }
200
+
201
+ for (const s of machine.states) {
202
+ if (s.name.trim() === '') {
203
+ diagnostics.push({
204
+ code: 'E1',
205
+ severity: 'error',
206
+ targetKind: 'state',
207
+ targetId: s.uid,
208
+ message: `E1 structure: state \`${s.uid}\` has an empty name`,
209
+ });
210
+ }
211
+ }
212
+
213
+ for (const e of machine.transitions) {
214
+ if (e.event.trim() === '') {
215
+ diagnostics.push({
216
+ code: 'E1',
217
+ severity: 'error',
218
+ targetKind: 'edge',
219
+ targetId: e.uid,
220
+ message: `E1 structure: transition \`${e.uid}\` has an empty event`,
221
+ });
222
+ }
223
+ if (!stateByUid.has(e.fromUid) || !stateByUid.has(e.toUid)) {
224
+ diagnostics.push({
225
+ code: 'E1',
226
+ severity: 'error',
227
+ targetKind: 'edge',
228
+ targetId: e.uid,
229
+ message: `E1 structure: transition \`${e.uid}\` references missing state endpoint`,
230
+ });
231
+ }
232
+ }
233
+
234
+ const seenEdges = new Map<string, string>();
235
+ for (const e of machine.transitions) {
236
+ const key = `${e.fromUid}\0${e.event.trim()}\0${(e.condition ?? '').trim()}`;
237
+ const firstUid = seenEdges.get(key);
238
+ if (firstUid !== undefined) {
239
+ const conditionPart = e.condition ? ` [${e.condition}]` : '';
240
+ diagnostics.push({
241
+ code: 'E2',
242
+ severity: 'error',
243
+ targetKind: 'edge',
244
+ targetId: e.uid,
245
+ relatedIds: [firstUid, e.uid],
246
+ fixable: 'delete-edge',
247
+ message: `E2 determinism: state \`${nameOf(e.fromUid)}\` has duplicate transition on \`${e.event}\`${conditionPart}`,
248
+ });
249
+ } else {
250
+ seenEdges.set(key, e.uid);
251
+ }
252
+ }
253
+
254
+ const validEdges = machine.transitions.filter(
255
+ (e) => stateByUid.has(e.fromUid) && stateByUid.has(e.toUid),
256
+ );
257
+ const initialUid =
258
+ machine.initialStateUid && stateByUid.has(machine.initialStateUid)
259
+ ? machine.initialStateUid
260
+ : (validEdges[0]?.fromUid ?? machine.states[0]?.uid ?? null);
261
+
262
+ if (initialUid !== null && machine.states.length > 0) {
263
+ const graph = createGraph();
264
+ for (const s of machine.states) addNode(graph, { id: s.uid });
265
+ for (const e of validEdges) {
266
+ addEdge(graph, { id: e.uid, sourceId: e.fromUid, targetId: e.toUid });
267
+ }
268
+
269
+ const reachable = new Set(
270
+ [...genBFS(graph, initialUid)]
271
+ .map((n) => (typeof n === 'object' && n !== null && 'id' in n ? String(n.id) : String(n)))
272
+ .filter((id) => id !== ''),
273
+ );
274
+
275
+ for (const s of machine.states) {
276
+ if (!reachable.has(s.uid)) {
277
+ diagnostics.push({
278
+ code: 'E3',
279
+ severity: 'error',
280
+ targetKind: 'state',
281
+ targetId: s.uid,
282
+ message: `E3 unreachable: state \`${s.name}\` cannot be reached from \`${nameOf(initialUid)}\``,
283
+ });
284
+ }
285
+ }
286
+
287
+ if (validEdges.length > 0) {
288
+ const outDegree = new Map<string, number>();
289
+ for (const s of machine.states) outDegree.set(s.uid, 0);
290
+ for (const e of validEdges) {
291
+ outDegree.set(e.fromUid, (outDegree.get(e.fromUid) ?? 0) + 1);
292
+ }
293
+ const terminals = machine.states
294
+ .filter((s) => (outDegree.get(s.uid) ?? 0) === 0)
295
+ .map((s) => s.uid);
296
+
297
+ if (terminals.length > 0) {
298
+ const terminalSet = new Set(terminals);
299
+ for (const s of machine.states) {
300
+ if (terminalSet.has(s.uid)) continue;
301
+ const canExit = terminals.some((term) => hasPath(graph, s.uid, term));
302
+ if (!canExit) {
303
+ diagnostics.push({
304
+ code: 'E4',
305
+ severity: 'error',
306
+ targetKind: 'state',
307
+ targetId: s.uid,
308
+ message: `E4 deadlock: state \`${s.name}\` cannot reach any terminal state`,
309
+ });
310
+ }
311
+ }
312
+ } else {
313
+ for (const s of machine.states) {
314
+ if (s.uid === initialUid) continue;
315
+ if (!hasPath(graph, s.uid, initialUid)) {
316
+ diagnostics.push({
317
+ code: 'E4',
318
+ severity: 'error',
319
+ targetKind: 'state',
320
+ targetId: s.uid,
321
+ message: `E4 trap: state \`${s.name}\` cannot return to initial state \`${nameOf(initialUid)}\``,
322
+ });
323
+ }
324
+ }
325
+ }
326
+ }
327
+ }
328
+
329
+ for (const s of machine.states) {
330
+ const outs = validEdges.filter((e) => e.fromUid === s.uid);
331
+ const conditioned = outs.filter((e) => e.condition !== undefined && e.condition.trim() !== '');
332
+ const unconditioned = outs.filter(
333
+ (e) => e.condition === undefined || e.condition.trim() === '',
334
+ );
335
+ if (conditioned.length === 1 && unconditioned.length === 0) {
336
+ const onlyEdge = conditioned[0];
337
+ if (onlyEdge) {
338
+ diagnostics.push({
339
+ code: 'W1',
340
+ severity: 'warning',
341
+ targetKind: 'edge',
342
+ targetId: onlyEdge.uid,
343
+ message: `W1 condition coverage: state \`${s.name}\` only has conditioned branch [${onlyEdge.condition ?? ''}] without a fallback`,
344
+ });
345
+ }
346
+ }
347
+ if (PLACEHOLDER_NAME_RE.test(s.name.trim())) {
348
+ diagnostics.push({
349
+ code: 'W2',
350
+ severity: 'warning',
351
+ targetKind: 'state',
352
+ targetId: s.uid,
353
+ message: `W2 placeholder name: state \`${s.name}\` should be renamed to a domain term`,
354
+ });
355
+ }
356
+ }
357
+
358
+ return diagnostics;
359
+ }
360
+
361
+ export function hasBlockingDiagnostics(diagnostics: readonly MachineDiagnostic[]): boolean {
362
+ return diagnostics.some((d) => d.severity === 'error');
363
+ }
@@ -23,10 +23,7 @@ export function resolveEmbeddedTable(value: unknown): Record<string, string> | u
23
23
  try {
24
24
  const table: unknown = JSON.parse(value);
25
25
  if (isTable(table)) return table;
26
- } catch {
27
- // A malformed define must not silently yield a half-broken binary; treat
28
- // as absent so the missing file surfaces loudly on first read.
29
- }
26
+ } catch {}
30
27
  }
31
28
  return undefined;
32
29
  }
@@ -43,9 +40,10 @@ export function embeddedTemplates(raw?: unknown): Record<string, string> | undef
43
40
  * path) and $bunfs-mode (`/$bunfs/root/...` → `/templates/...`) roots.
44
41
  */
45
42
  export function templateKeyFor(path: string): string {
43
+ const normalized = path.replaceAll('\\', '/');
46
44
  const marker = '/templates/';
47
- const idx = path.lastIndexOf(marker);
48
- return idx === -1 ? path : path.slice(idx + marker.length);
45
+ const idx = normalized.lastIndexOf(marker);
46
+ return idx === -1 ? normalized : normalized.slice(idx + marker.length);
49
47
  }
50
48
 
51
49
  /** TemplateIo over the embedded table (no filesystem access). */
@@ -27,7 +27,7 @@ export function renderWithUnits(
27
27
  if (depth > MAX_UNIT_NESTING_DEPTH) {
28
28
  throw new Error(`unit nesting exceeded ${MAX_UNIT_NESTING_DEPTH}`);
29
29
  }
30
- // minijinja keep_trailing_newline=false: a single trailing newline of the
30
+ // minijinja keep_trailing_newline=false: a single trailing newline of the ~keep
31
31
  // template SOURCE is stripped before rendering (predecessor parity). \r? first —
32
32
  // stripping \n alone would strand a trailing \r for CRLF sources.
33
33
  const source = raw.replace(/\r?\n$/u, '');