@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,570 @@
1
+ /**
2
+ * Pure Macro Business Forest Projection, Cross-Forest Bridge Analysis, W3 Isolation Linter,
3
+ * and Atomic `.llman-sdd/studio/views.json` Contract (studio-core r153).
4
+ * 100% browser-pure, 0-Token, zero direct filesystem I/O (injected StudioViewsIo only).
5
+ */
6
+ import { z } from 'zod';
7
+
8
+ import { ruleHasRunnableScenario, specIdOf } from '../spec/ir.ts';
9
+ import { buildReqRegistry } from '../spec/reqRegistry.ts';
10
+ import type { FsPort } from '../util/fsPort.ts';
11
+ import type { SpecEntry } from '../validation/validate.ts';
12
+ import { extractDecisionTables } from './decisionTree.ts';
13
+ import { extractStudioMachines } from './extract.ts';
14
+ import { foldFeatureAst } from './textfold.ts';
15
+
16
+ export const STUDIO_VIEWS_REL = '.llman-sdd/studio/views.json';
17
+
18
+ export type StudioViewsIo = Pick<
19
+ FsPort,
20
+ 'exists' | 'readText' | 'writeText' | 'rename' | 'mkdirp' | 'currentPid' | 'now'
21
+ >;
22
+
23
+ export class StudioViewsError extends Error {
24
+ constructor(message: string) {
25
+ super(message);
26
+ this.name = 'StudioViewsError';
27
+ }
28
+ }
29
+
30
+ export const forestEdgeEvidenceSchema = z.object({
31
+ sourceReqId: z.string().optional(),
32
+ targetReqId: z.string().optional(),
33
+ summary: z.string(),
34
+ });
35
+ export type ForestEdgeEvidence = z.infer<typeof forestEdgeEvidenceSchema>;
36
+
37
+ export const studioManualLinkSchema = z.object({
38
+ id: z.string().min(1),
39
+ fromCap: z.string().min(1),
40
+ toCap: z.string().min(1),
41
+ label: z.string().optional(),
42
+ });
43
+ export type StudioManualLink = z.infer<typeof studioManualLinkSchema>;
44
+
45
+ export const studioManualGroupSchema = z.object({
46
+ id: z.string().min(1),
47
+ title: z.string().min(1),
48
+ tone: z.string().optional(),
49
+ capabilities: z.array(z.string().min(1)),
50
+ collapsed: z.boolean().optional(),
51
+ });
52
+ export type StudioManualGroup = z.infer<typeof studioManualGroupSchema>;
53
+
54
+ export const studioTabViewSchema = z.object({
55
+ id: z.string().min(1),
56
+ title: z.string().min(1),
57
+ pinned: z.boolean().optional(),
58
+ includedCapabilities: z.array(z.string()),
59
+ tagFilter: z.string().nullable().optional(),
60
+ showExternalHops: z.boolean().optional(),
61
+ bridgeOnly: z.boolean(),
62
+ manualLinks: z.array(studioManualLinkSchema),
63
+ manualGroups: z.array(studioManualGroupSchema),
64
+ macroPositions: z.record(
65
+ z.string(),
66
+ z.object({ x: z.number().finite(), y: z.number().finite() }),
67
+ ),
68
+ });
69
+ export type StudioTabView = z.infer<typeof studioTabViewSchema>;
70
+
71
+ export const studioViewsDocSchema = z.object({
72
+ version: z.literal(1),
73
+ updatedAt: z.string().min(1),
74
+ views: z.array(studioTabViewSchema),
75
+ });
76
+ export type StudioViewsDoc = z.infer<typeof studioViewsDocSchema>;
77
+
78
+ export function defaultStudioViewsDoc(now = '1970-01-01T00:00:00.000Z'): StudioViewsDoc {
79
+ return {
80
+ version: 1,
81
+ updatedAt: now,
82
+ views: [
83
+ {
84
+ id: 'main',
85
+ title: '主视图',
86
+ pinned: true,
87
+ includedCapabilities: [],
88
+ tagFilter: null,
89
+ showExternalHops: false,
90
+ bridgeOnly: false,
91
+ manualLinks: [],
92
+ manualGroups: [],
93
+ macroPositions: {},
94
+ },
95
+ ],
96
+ };
97
+ }
98
+
99
+ export function parseStudioViewsDoc(rawJson: string): StudioViewsDoc {
100
+ let parsed: unknown;
101
+ try {
102
+ parsed = JSON.parse(rawJson);
103
+ } catch (error) {
104
+ throw new StudioViewsError(
105
+ `invalid studio views JSON: ${error instanceof Error ? error.message : String(error)}`,
106
+ );
107
+ }
108
+ const checked = studioViewsDocSchema.safeParse(parsed);
109
+ if (!checked.success) {
110
+ const first = checked.error.issues[0];
111
+ throw new StudioViewsError(
112
+ `invalid studio views schema at ${first?.path.join('.') || '<root>'}: ${first?.message ?? 'unknown error'}`,
113
+ );
114
+ }
115
+ return checked.data;
116
+ }
117
+
118
+ export function readStudioViews(io: StudioViewsIo): StudioViewsDoc {
119
+ if (!io.exists(STUDIO_VIEWS_REL)) {
120
+ return defaultStudioViewsDoc(io.now().toISOString());
121
+ }
122
+ return parseStudioViewsDoc(io.readText(STUDIO_VIEWS_REL));
123
+ }
124
+
125
+ let viewsWriteSeq = 0;
126
+
127
+ /**
128
+ * Atomically persist `.llman-sdd/studio/views.json` via sibling `.tmp.<pid>.<seq>` + `rename`.
129
+ * Strictly pure local view state — never modifies `llmanspec/specs/`.
130
+ */
131
+ export function writeStudioViews(io: StudioViewsIo, doc: StudioViewsDoc): string {
132
+ const checked = studioViewsDocSchema.safeParse(doc);
133
+ if (!checked.success) {
134
+ const first = checked.error.issues[0];
135
+ throw new StudioViewsError(
136
+ `refusing to write invalid studio views at ${first?.path.join('.') || '<root>'}: ${first?.message ?? 'unknown error'}`,
137
+ );
138
+ }
139
+ io.mkdirp('.llman-sdd/studio');
140
+ viewsWriteSeq += 1;
141
+ const tmpRel = `.llman-sdd/studio/.views.tmp.${String(io.currentPid())}.${String(viewsWriteSeq)}`;
142
+ io.writeText(tmpRel, `${JSON.stringify(checked.data, null, 2)}\n`);
143
+ io.rename(tmpRel, STUDIO_VIEWS_REL);
144
+ return STUDIO_VIEWS_REL;
145
+ }
146
+
147
+ export type ForestGraphItemKind = 'machine' | 'flow' | 'decision' | 'doc';
148
+ export type ForestNodeKind = ForestGraphItemKind | 'composite';
149
+
150
+ export interface ForestGraphItem {
151
+ id: string;
152
+ kind: ForestGraphItemKind;
153
+ title: string;
154
+ reqId: string | null;
155
+ machineKey?: string;
156
+ decisionTableId?: string;
157
+ ruleCount?: number;
158
+ stateCount?: number;
159
+ rowCount?: number;
160
+ nests?: string[];
161
+ nestedBy?: string[];
162
+ }
163
+
164
+ export interface ForestKindCounts {
165
+ flow: number;
166
+ machine: number;
167
+ decision: number;
168
+ doc: number;
169
+ }
170
+
171
+ export interface ForestNode {
172
+ id: string;
173
+ title: string;
174
+ file: string;
175
+ kind: ForestNodeKind;
176
+ hardness: 'doc' | 'tested' | 'drift-guarded' | 'formal';
177
+ ruleCount: number;
178
+ scenarioCount: number;
179
+ decisionTableCount: number;
180
+ /** Longest nestKey chain among this capability's machines (0 if none). Optional so P4 UI can omit until P5. */
181
+ maxNestingDepth?: number;
182
+ /** Distinct nested machines referenced from this capability's states. Optional so P4 UI can omit until P5. */
183
+ nestedMachineCount?: number;
184
+ machineKeys: string[];
185
+ /** Per-capability breakdown of @flow, @state, @decision_table, and aggregated plain GWT rules. */
186
+ graphItems?: ForestGraphItem[];
187
+ /** Per-kind counts inside this capability (doc = non-graph plain rules). */
188
+ kindCounts?: ForestKindCounts;
189
+ weight: number;
190
+ tags: string[];
191
+ reqPreview: string[];
192
+ summary: string;
193
+ }
194
+
195
+ export interface ForestEdge {
196
+ id: string;
197
+ from: string;
198
+ to: string;
199
+ label: string;
200
+ kind: 'spec-ref';
201
+ evidence: ForestEdgeEvidence[];
202
+ }
203
+
204
+ export interface ForestGraph {
205
+ nodes: ForestNode[];
206
+ edges: ForestEdge[];
207
+ }
208
+
209
+ export interface ForestGroupSpec {
210
+ id: string;
211
+ capabilities: readonly string[];
212
+ }
213
+
214
+ export interface CrossForestBridgeItem {
215
+ edgeId: string;
216
+ from: string;
217
+ to: string;
218
+ fromGroupId: string;
219
+ toGroupId: string;
220
+ label: string;
221
+ evidence: ForestEdgeEvidence[];
222
+ }
223
+
224
+ export interface CrossForestBridgeResult {
225
+ bridgeEdgeIds: string[];
226
+ bridgeNodeIds: string[];
227
+ bridges: CrossForestBridgeItem[];
228
+ }
229
+
230
+ export interface ForestDiagnostic {
231
+ code: 'W3';
232
+ severity: 'warning';
233
+ capability: string;
234
+ message: string;
235
+ }
236
+
237
+ /**
238
+ * 0-Token pure domain projection of `SpecEntry[]` into a 4-kind Macro Business Forest
239
+ * (`machine` / `flow` / `decision` / `doc`) with weighted nodes and cross-capability evidence edges.
240
+ */
241
+ export function buildForestGraph(entries: readonly SpecEntry[]): ForestGraph {
242
+ const extracted = extractStudioMachines(entries);
243
+ const machinesByCap = new Map<string, typeof extracted>();
244
+ for (const m of extracted) {
245
+ const cap = m.machine.capability;
246
+ const list = machinesByCap.get(cap) ?? [];
247
+ list.push(m);
248
+ machinesByCap.set(cap, list);
249
+ }
250
+
251
+ const registry = buildReqRegistry(entries);
252
+ const reqToCap = new Map<string, string>();
253
+ for (const [reqId, occs] of registry.byId.entries()) {
254
+ const first = occs[0];
255
+ if (!first) continue;
256
+ const owner = entries.find((e) => e.fileName === first.fileName);
257
+ if (owner) reqToCap.set(reqId, specIdOf(owner));
258
+ }
259
+
260
+ const nodes: ForestNode[] = [];
261
+ const edgeByPair = new Map<
262
+ string,
263
+ { from: string; to: string; labels: Set<string>; evidence: ForestEdgeEvidence[] }
264
+ >();
265
+
266
+ const addEvidenceEdge = (
267
+ from: string,
268
+ to: string,
269
+ label: string,
270
+ ev: ForestEdgeEvidence,
271
+ ): void => {
272
+ if (from === to) return;
273
+ const pairKey = `${from}->${to}`;
274
+ let bucket = edgeByPair.get(pairKey);
275
+ if (!bucket) {
276
+ bucket = { from, to, labels: new Set<string>(), evidence: [] };
277
+ edgeByPair.set(pairKey, bucket);
278
+ }
279
+ bucket.labels.add(label);
280
+ const dup = bucket.evidence.some(
281
+ (e) =>
282
+ e.sourceReqId === ev.sourceReqId &&
283
+ e.targetReqId === ev.targetReqId &&
284
+ e.summary === ev.summary,
285
+ );
286
+ if (!dup) bucket.evidence.push(ev);
287
+ };
288
+
289
+ for (const entry of entries) {
290
+ const id = specIdOf(entry);
291
+ const capMachines = machinesByCap.get(id) ?? [];
292
+ const machineKeys = capMachines.map((m) => m.machine.machineKey);
293
+ const decisionTables = extractDecisionTables(entry.doc);
294
+ const allTags = Array.from(
295
+ new Set(entry.doc.rules.flatMap((r) => r.tags.map((t) => (t.startsWith('#') ? t : `#${t}`)))),
296
+ ).slice(0, 6);
297
+
298
+ const hasFlowTag =
299
+ capMachines.some((m) => m.machine.graphKind === 'flow') ||
300
+ allTags.some((t) => /^#(flow|flowchart|workflow)$/iu.test(t));
301
+
302
+ const kind: ForestNodeKind =
303
+ capMachines.length > 0
304
+ ? hasFlowTag
305
+ ? 'flow'
306
+ : 'machine'
307
+ : decisionTables.length > 0
308
+ ? 'decision'
309
+ : 'doc';
310
+
311
+ const ruleCount = entry.doc.rules.length;
312
+ const scenarioCount =
313
+ entry.doc.rules.reduce((sum, r) => sum + r.scenarios.length, 0) + entry.doc.orphans.length;
314
+ const runnableRules = entry.doc.rules.filter((r) => ruleHasRunnableScenario(r)).length;
315
+ const hardness: ForestNode['hardness'] =
316
+ machineKeys.length > 0 ? 'drift-guarded' : runnableRules > 0 ? 'tested' : 'doc';
317
+
318
+ const capMachineList = capMachines.map((m) => m.machine);
319
+ const byKey = new Map(extracted.map((m) => [m.machine.machineKey, m.machine]));
320
+ const depthMemo = new Map<string, number>();
321
+ const nestDepth = (key: string, stack: Set<string>): number => {
322
+ if (stack.has(key)) return 0;
323
+ const cached = depthMemo.get(key);
324
+ if (cached !== undefined) return cached;
325
+ const node = byKey.get(key);
326
+ const children = (node?.states ?? [])
327
+ .map((s) => s.nestKey)
328
+ .filter((k): k is string => k !== undefined && k !== '');
329
+ if (children.length === 0) {
330
+ depthMemo.set(key, 0);
331
+ return 0;
332
+ }
333
+ stack.add(key);
334
+ const depth = 1 + Math.max(...children.map((c) => nestDepth(c, stack)));
335
+ stack.delete(key);
336
+ depthMemo.set(key, depth);
337
+ return depth;
338
+ };
339
+ const nestedKeys = new Set<string>();
340
+ let maxNestingDepth = 0;
341
+ for (const m of capMachineList) {
342
+ maxNestingDepth = Math.max(maxNestingDepth, nestDepth(m.machineKey, new Set()));
343
+ for (const s of m.states) {
344
+ if (s.nestKey) nestedKeys.add(s.nestKey);
345
+ }
346
+ }
347
+ const nestedMachineCount = nestedKeys.size;
348
+
349
+ const capMachineKeySet = new Set(machineKeys);
350
+ const nestsByKey = new Map<string, string[]>();
351
+ const nestedByKey = new Map<string, string[]>();
352
+ for (const m of capMachineList) {
353
+ const localNests = Array.from(
354
+ new Set(
355
+ m.states
356
+ .map((s) => s.nestKey)
357
+ .filter(
358
+ (k): k is string =>
359
+ k !== undefined && k !== '' && capMachineKeySet.has(k) && k !== m.machineKey,
360
+ ),
361
+ ),
362
+ );
363
+ if (localNests.length > 0) {
364
+ nestsByKey.set(m.machineKey, localNests);
365
+ for (const targetKey of localNests) {
366
+ const parents = nestedByKey.get(targetKey) ?? [];
367
+ if (!parents.includes(m.machineKey)) parents.push(m.machineKey);
368
+ nestedByKey.set(targetKey, parents);
369
+ }
370
+ }
371
+ }
372
+
373
+ const graphItems: ForestGraphItem[] = [];
374
+ let flowCount = 0;
375
+ let machineCount = 0;
376
+ for (const m of capMachineList) {
377
+ const itemKind: ForestGraphItemKind = m.graphKind === 'flow' ? 'flow' : 'machine';
378
+ if (itemKind === 'flow') flowCount += 1;
379
+ else machineCount += 1;
380
+ const nests = nestsByKey.get(m.machineKey);
381
+ const nestedBy = nestedByKey.get(m.machineKey);
382
+ graphItems.push({
383
+ id: m.machineKey,
384
+ kind: itemKind,
385
+ title: m.ruleTitle || m.scenarioName || m.machineKey,
386
+ reqId: m.reqId,
387
+ machineKey: m.machineKey,
388
+ stateCount: m.states.length,
389
+ ...(nests && nests.length > 0 ? { nests } : {}),
390
+ ...(nestedBy && nestedBy.length > 0 ? { nestedBy } : {}),
391
+ });
392
+ }
393
+
394
+ for (const dt of decisionTables) {
395
+ graphItems.push({
396
+ id: `decision:${dt.id}`,
397
+ kind: 'decision',
398
+ title: dt.title || dt.id,
399
+ reqId: dt.reqId,
400
+ decisionTableId: dt.id,
401
+ rowCount: dt.rows.length,
402
+ });
403
+ }
404
+
405
+ const isGraphRule = (rule: (typeof entry.doc.rules)[number]): boolean =>
406
+ rule.scenarios.some((sc) => sc.tags.some((t) => /^@?(flow|state|decision_table)$/iu.test(t)));
407
+ const plainRuleCount = entry.doc.rules.filter((r) => !isGraphRule(r)).length;
408
+ if (plainRuleCount > 0 || graphItems.length === 0) {
409
+ graphItems.push({
410
+ id: `doc:${id}`,
411
+ kind: 'doc',
412
+ title: '文档规则',
413
+ reqId: null,
414
+ ruleCount: plainRuleCount,
415
+ });
416
+ }
417
+
418
+ const kindCounts: ForestKindCounts = {
419
+ flow: flowCount,
420
+ machine: machineCount,
421
+ decision: decisionTables.length,
422
+ doc: plainRuleCount,
423
+ };
424
+
425
+ const distinctKindCount =
426
+ (flowCount > 0 ? 1 : 0) +
427
+ (machineCount > 0 ? 1 : 0) +
428
+ (decisionTables.length > 0 ? 1 : 0) +
429
+ (plainRuleCount > 0 ? 1 : 0);
430
+ const totalGraphs = flowCount + machineCount + decisionTables.length;
431
+ const resolvedKind: ForestNodeKind =
432
+ distinctKindCount > 1 || totalGraphs > 1 ? 'composite' : kind;
433
+
434
+ const weight = Number((ruleCount + scenarioCount * 0.5 + machineKeys.length * 3).toFixed(2));
435
+ const levels = foldFeatureAst(entry.doc);
436
+ const reqPreview = entry.doc.rules
437
+ .map((r) => `@req:${r.reqId}`)
438
+ .filter((x) => x !== '@req:')
439
+ .slice(0, 3);
440
+
441
+ nodes.push({
442
+ id,
443
+ title: id,
444
+ file: entry.fileName,
445
+ kind: resolvedKind,
446
+ hardness,
447
+ ruleCount,
448
+ scenarioCount,
449
+ decisionTableCount: decisionTables.length,
450
+ maxNestingDepth,
451
+ nestedMachineCount,
452
+ machineKeys,
453
+ graphItems,
454
+ kindCounts,
455
+ weight,
456
+ tags: allTags,
457
+ reqPreview,
458
+ summary: levels[3],
459
+ });
460
+
461
+ for (const rule of entry.doc.rules) {
462
+ const bodyText = `${rule.title}\n${rule.description}`;
463
+ for (const rawClause of bodyText.split(/[。;;\n]/u)) {
464
+ const clause = rawClause.trim();
465
+ if (clause === '') continue;
466
+ const isUpstreamClause = /(前置|依赖|上游|based on|depends on|upstream)/iu.test(clause);
467
+ for (const match of clause.matchAll(/@req:([a-zA-Z0-9_-]+)/gu)) {
468
+ const targetReq = match[1];
469
+ if (!targetReq) continue;
470
+ const targetCap = reqToCap.get(targetReq);
471
+ if (!targetCap || targetCap === id) continue;
472
+ const fromCap = isUpstreamClause ? targetCap : id;
473
+ const toCap = isUpstreamClause ? id : targetCap;
474
+ addEvidenceEdge(fromCap, toCap, `@req:${targetReq}`, {
475
+ ...(rule.reqId ? { sourceReqId: rule.reqId } : {}),
476
+ targetReqId: targetReq,
477
+ summary: clause.slice(0, 120),
478
+ });
479
+ }
480
+ }
481
+ }
482
+ }
483
+
484
+ let seq = 0;
485
+ const edges: ForestEdge[] = [];
486
+ for (const bucket of edgeByPair.values()) {
487
+ seq += 1;
488
+ const labels = Array.from(bucket.labels);
489
+ const label =
490
+ labels.length <= 2 ? labels.join(' · ') : `${labels[0]!} +${String(labels.length - 1)}`;
491
+ edges.push({
492
+ id: `ref_${String(seq)}`,
493
+ from: bucket.from,
494
+ to: bucket.to,
495
+ label,
496
+ kind: 'spec-ref',
497
+ evidence: bucket.evidence,
498
+ });
499
+ }
500
+
501
+ return { nodes, edges };
502
+ }
503
+
504
+ /**
505
+ * Identify automatic solid contract edges bridging two distinct domain groups (Cross-Forest Bridge).
506
+ */
507
+ export function computeCrossForestBridges(
508
+ graph: ForestGraph,
509
+ groups: readonly ForestGroupSpec[],
510
+ ): CrossForestBridgeResult {
511
+ const capToGroup = new Map<string, string>();
512
+ for (const g of groups) {
513
+ for (const cap of g.capabilities) {
514
+ if (!capToGroup.has(cap)) capToGroup.set(cap, g.id);
515
+ }
516
+ }
517
+
518
+ const bridges: CrossForestBridgeItem[] = [];
519
+ const bridgeEdgeIds: string[] = [];
520
+ const bridgeNodeSet = new Set<string>();
521
+
522
+ for (const edge of graph.edges) {
523
+ const gFrom = capToGroup.get(edge.from);
524
+ const gTo = capToGroup.get(edge.to);
525
+ if (!gFrom || !gTo || gFrom === gTo) continue;
526
+ bridges.push({
527
+ edgeId: edge.id,
528
+ from: edge.from,
529
+ to: edge.to,
530
+ fromGroupId: gFrom,
531
+ toGroupId: gTo,
532
+ label: edge.label,
533
+ evidence: edge.evidence,
534
+ });
535
+ bridgeEdgeIds.push(edge.id);
536
+ bridgeNodeSet.add(edge.from);
537
+ bridgeNodeSet.add(edge.to);
538
+ }
539
+
540
+ return {
541
+ bridgeEdgeIds,
542
+ bridgeNodeIds: Array.from(bridgeNodeSet),
543
+ bridges,
544
+ };
545
+ }
546
+
547
+ /**
548
+ * W3 Macro Topology Linter: flag isolated capabilities with zero cross-capability spec references.
549
+ */
550
+ export function validateForestIsolation(graph: ForestGraph): ForestDiagnostic[] {
551
+ if (graph.nodes.length <= 1) return [];
552
+ const degree = new Map<string, number>();
553
+ for (const e of graph.edges) {
554
+ degree.set(e.from, (degree.get(e.from) ?? 0) + 1);
555
+ degree.set(e.to, (degree.get(e.to) ?? 0) + 1);
556
+ }
557
+
558
+ const diags: ForestDiagnostic[] = [];
559
+ for (const n of graph.nodes) {
560
+ if ((degree.get(n.id) ?? 0) === 0) {
561
+ diags.push({
562
+ code: 'W3',
563
+ severity: 'warning',
564
+ capability: n.id,
565
+ message: `W3 孤立规格:能力「${n.id}」未与其他规格存在跨能力 @req 契约连线`,
566
+ });
567
+ }
568
+ }
569
+ return diags;
570
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Browser-safe Studio pure domain barrel (`@llman-sdd/core/studio`).
3
+ * Contains strictly zero `node:*` imports so Web bundlers (rsbuild) can consume
4
+ * Zod contracts, IR models, semantic Diff, Worldline, and Linter directly.
5
+ */
6
+ export * from './model.ts';
7
+ export * from './diff.ts';
8
+ export * from './validate.ts';
9
+ export * from './revisions.ts';
10
+ export * from './store.ts';
11
+ export * from './contracts.ts';
12
+ export * from './deeplink.ts';
13
+ export * from './decisionTree.ts';
14
+ export * from './textfold.ts';
15
+ export * from './demos.ts';
16
+ export * from './drift.ts';
17
+ export * from './forest.ts';
18
+ export * from './search.ts';
19
+ export * from './sync.ts';
20
+ export * from './time.ts';
21
+ export * from './changeScope.ts';
22
+ export { isJudgmentKind, parseNestRef, type NestRef } from '../validation/xstateTransitions.ts';
23
+ export {
24
+ REQ_ID_RE,
25
+ allocateNextReqId,
26
+ formatReqRef,
27
+ parseReqRef,
28
+ quoteScenarioName,
29
+ reqIdFromTag,
30
+ tokenizeReqRefs,
31
+ type ReqRef,
32
+ } from '../spec/reqRef.ts';