@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
@@ -0,0 +1,912 @@
1
+ /**
2
+ * Three-way semantic sync items and pick-merge for Studio drafts (studio-core r164).
3
+ * Aligns by state name and transition signature — never line-merges .feature text.
4
+ * Pure: zero I/O, zero wall clock; worldline timestamps come from `nowIso`.
5
+ */
6
+ import { computeMachineDiff, type NodeMetaField } from './diff.ts';
7
+ import {
8
+ cloneMachineDraft,
9
+ cloneMachineIR,
10
+ nextPrefixedUid,
11
+ type MachineDraft,
12
+ type StudioDocDraft,
13
+ type StudioMachineIR,
14
+ type StudioStateDoc,
15
+ type StudioStateNode,
16
+ type StudioTransitionEdge,
17
+ } from './model.ts';
18
+ import { recordWorldlineCommit } from './store.ts';
19
+
20
+ export const SYNC_SNAPSHOT_BRANCH_REF = 'snapshot-before-sync';
21
+ export const SYNC_SNAPSHOT_LABEL = '刚才在画布上的版本';
22
+ export const SYNC_BOTH_BLOCKED_REASON = 'signature-clash';
23
+
24
+ export type SyncItemKind =
25
+ | 'state'
26
+ | 'transition'
27
+ | 'condition'
28
+ | 'doc-rule'
29
+ | 'nest'
30
+ | 'kind'
31
+ | 'node-meta';
32
+ export type SyncPick = 'ours' | 'theirs' | 'both';
33
+
34
+ export interface SyncTransitionPayload {
35
+ from: string;
36
+ event: string;
37
+ condition?: string;
38
+ to: string;
39
+ }
40
+
41
+ export interface SyncItem {
42
+ id: string;
43
+ kind: SyncItemKind;
44
+ machineKey?: string;
45
+ sourceFile: string;
46
+ oursPresent: boolean;
47
+ theirsPresent: boolean;
48
+ labelOurs: string | null;
49
+ labelTheirs: string | null;
50
+ defaultPick: SyncPick | null;
51
+ oursStateName?: string;
52
+ theirsStateName?: string;
53
+ oursTransition?: SyncTransitionPayload;
54
+ theirsTransition?: SyncTransitionPayload;
55
+ oursNest?: string | null;
56
+ theirsNest?: string | null;
57
+ oursNodeKind?: string | null;
58
+ theirsNodeKind?: string | null;
59
+ metaField?: NodeMetaField;
60
+ oursNodeMeta?: string | null;
61
+ theirsNodeMeta?: string | null;
62
+ oursText?: string;
63
+ theirsText?: string;
64
+ }
65
+
66
+ export interface ApplySyncPicksResult {
67
+ draft: MachineDraft;
68
+ applied: string[];
69
+ blocked: Array<{ itemId: string; reason: string }>;
70
+ }
71
+
72
+ export interface ApplyDocSyncPicksResult {
73
+ docDraft: StudioDocDraft;
74
+ applied: string[];
75
+ blocked: Array<{ itemId: string; reason: string }>;
76
+ }
77
+
78
+ function stateNameOf(ir: StudioMachineIR, uid: string): string {
79
+ return ir.states.find((s) => s.uid === uid)?.name ?? uid;
80
+ }
81
+
82
+ function transitionPayload(ir: StudioMachineIR, edge: StudioTransitionEdge): SyncTransitionPayload {
83
+ const payload: SyncTransitionPayload = {
84
+ from: stateNameOf(ir, edge.fromUid),
85
+ event: edge.event.trim(),
86
+ to: stateNameOf(ir, edge.toUid),
87
+ };
88
+ const condition = (edge.condition ?? '').trim();
89
+ if (condition !== '') payload.condition = condition;
90
+ return payload;
91
+ }
92
+
93
+ function transitionSig(p: SyncTransitionPayload): string {
94
+ return `${p.from}\0${p.event}\0${p.condition ?? ''}\0${p.to}`;
95
+ }
96
+
97
+ function pairKey(p: SyncTransitionPayload): string {
98
+ return `${p.from}\0${p.event}\0${p.to}`;
99
+ }
100
+
101
+ function payloadsByPair(
102
+ map: Map<string, SyncTransitionPayload>,
103
+ ): Map<string, SyncTransitionPayload[]> {
104
+ const out = new Map<string, SyncTransitionPayload[]>();
105
+ for (const payload of map.values()) {
106
+ const key = pairKey(payload);
107
+ const arr = out.get(key);
108
+ if (arr) arr.push(payload);
109
+ else out.set(key, [payload]);
110
+ }
111
+ return out;
112
+ }
113
+
114
+ function formatTransition(p: SyncTransitionPayload): string {
115
+ const conditionPart = p.condition ? ` [${p.condition}]` : '';
116
+ return `${p.from} --[${p.event}${conditionPart}]--> ${p.to}`;
117
+ }
118
+
119
+ function stateSet(ir: StudioMachineIR | null): Set<string> {
120
+ return new Set((ir?.states ?? []).map((s) => s.name));
121
+ }
122
+
123
+ function transitionMap(ir: StudioMachineIR | null): Map<string, SyncTransitionPayload> {
124
+ const map = new Map<string, SyncTransitionPayload>();
125
+ if (!ir) return map;
126
+ for (const edge of ir.transitions) {
127
+ const payload = transitionPayload(ir, edge);
128
+ map.set(transitionSig(payload), payload);
129
+ }
130
+ return map;
131
+ }
132
+
133
+ function itemId(machineKey: string, kind: SyncItemKind, key: string): string {
134
+ return `${machineKey}/${kind}/${key}`;
135
+ }
136
+
137
+ /**
138
+ * Build pick-list items from BASE (session baseline), OURS (canvas current), THEIRS (reparsed disk).
139
+ * Same-signature adds/removes on both sides are treated as already aligned and omitted.
140
+ */
141
+ export function buildSyncItems(draft: MachineDraft, theirs: StudioMachineIR | null): SyncItem[] {
142
+ const base = draft.baseline;
143
+ const ours = draft.current;
144
+ const machineKey = ours?.machineKey ?? base?.machineKey ?? theirs?.machineKey ?? draft.sourceFile;
145
+ const sourceFile = draft.sourceFile;
146
+ const items: SyncItem[] = [];
147
+
148
+ const baseStates = stateSet(base);
149
+ const oursStates = stateSet(ours);
150
+ const theirsStates = stateSet(theirs);
151
+ const allStates = new Set([...baseStates, ...oursStates, ...theirsStates]);
152
+
153
+ for (const name of allStates) {
154
+ const inBase = baseStates.has(name);
155
+ const inOurs = oursStates.has(name);
156
+ const inTheirs = theirsStates.has(name);
157
+ if (inOurs === inTheirs && inOurs === inBase) continue;
158
+ if (inOurs === inTheirs && inOurs !== inBase) continue;
159
+
160
+ const oursPresent = inOurs !== inBase ? inOurs : inOurs && !inTheirs;
161
+ const theirsPresent = inTheirs !== inBase ? inTheirs : inTheirs && !inOurs;
162
+ if (!oursPresent && !theirsPresent) continue;
163
+ if (oursPresent && theirsPresent && inOurs === inTheirs) continue;
164
+
165
+ let defaultPick: SyncPick | null = null;
166
+ if (oursPresent && !theirsPresent) defaultPick = 'ours';
167
+ else if (!oursPresent && theirsPresent) defaultPick = 'theirs';
168
+
169
+ const labelOurs = oursPresent ? (inOurs ? `状态「${name}」` : `去掉状态「${name}」`) : null;
170
+ const labelTheirs = theirsPresent
171
+ ? inTheirs
172
+ ? `状态「${name}」`
173
+ : `去掉状态「${name}」`
174
+ : null;
175
+
176
+ items.push({
177
+ id: itemId(machineKey, 'state', name),
178
+ kind: 'state',
179
+ machineKey,
180
+ sourceFile,
181
+ oursPresent,
182
+ theirsPresent,
183
+ labelOurs,
184
+ labelTheirs,
185
+ defaultPick,
186
+ ...(inOurs ? { oursStateName: name } : {}),
187
+ ...(inTheirs ? { theirsStateName: name } : {}),
188
+ });
189
+ }
190
+
191
+ const nestOf = (ir: StudioMachineIR | null, name: string): string | null =>
192
+ ir?.states.find((s) => s.name === name)?.nestKey ?? null;
193
+ const kindOf = (ir: StudioMachineIR | null, name: string): string | null =>
194
+ ir?.states.find((s) => s.name === name)?.nodeKind ?? null;
195
+ const metaOf = (ir: StudioMachineIR | null, name: string, field: NodeMetaField): string | null =>
196
+ ir?.states.find((s) => s.name === name)?.[field] ?? null;
197
+ const NODE_META_FIELDS: readonly NodeMetaField[] = ['summary', 'actor', 'done'];
198
+
199
+ for (const name of allStates) {
200
+ const inOurs = oursStates.has(name);
201
+ const inTheirs = theirsStates.has(name);
202
+ const inBase = baseStates.has(name);
203
+ if (!inOurs && !inTheirs && !inBase) continue;
204
+
205
+ const oursNest = nestOf(ours, name);
206
+ const theirsNest = nestOf(theirs, name);
207
+ const baseNest = nestOf(base, name);
208
+ if (oursNest !== theirsNest && (oursNest !== baseNest || theirsNest !== baseNest)) {
209
+ const oursPresent = oursNest !== baseNest;
210
+ const theirsPresent = theirsNest !== baseNest;
211
+ if (oursPresent || theirsPresent) {
212
+ let defaultPick: SyncPick | null = null;
213
+ if (oursPresent && !theirsPresent) defaultPick = 'ours';
214
+ else if (!oursPresent && theirsPresent) defaultPick = 'theirs';
215
+ items.push({
216
+ id: itemId(machineKey, 'nest', name),
217
+ kind: 'nest',
218
+ machineKey,
219
+ sourceFile,
220
+ oursPresent,
221
+ theirsPresent,
222
+ labelOurs: oursPresent ? `nest ${name} -> ${oursNest ?? '∅'}` : null,
223
+ labelTheirs: theirsPresent ? `nest ${name} -> ${theirsNest ?? '∅'}` : null,
224
+ defaultPick,
225
+ oursStateName: name,
226
+ theirsStateName: name,
227
+ oursNest,
228
+ theirsNest,
229
+ });
230
+ }
231
+ }
232
+
233
+ const oursKind = kindOf(ours, name);
234
+ const theirsKind = kindOf(theirs, name);
235
+ const baseKind = kindOf(base, name);
236
+ if (oursKind !== theirsKind && (oursKind !== baseKind || theirsKind !== baseKind)) {
237
+ const oursPresent = oursKind !== baseKind;
238
+ const theirsPresent = theirsKind !== baseKind;
239
+ if (oursPresent || theirsPresent) {
240
+ let defaultPick: SyncPick | null = null;
241
+ if (oursPresent && !theirsPresent) defaultPick = 'ours';
242
+ else if (!oursPresent && theirsPresent) defaultPick = 'theirs';
243
+ items.push({
244
+ id: itemId(machineKey, 'kind', name),
245
+ kind: 'kind',
246
+ machineKey,
247
+ sourceFile,
248
+ oursPresent,
249
+ theirsPresent,
250
+ labelOurs: oursPresent ? `类型 ${name}=${oursKind ?? '(未指定)'}` : null,
251
+ labelTheirs: theirsPresent ? `类型 ${name}=${theirsKind ?? '(未指定)'}` : null,
252
+ defaultPick,
253
+ oursStateName: name,
254
+ theirsStateName: name,
255
+ oursNodeKind: oursKind,
256
+ theirsNodeKind: theirsKind,
257
+ });
258
+ }
259
+ }
260
+
261
+ for (const field of NODE_META_FIELDS) {
262
+ const oursMeta = metaOf(ours, name, field);
263
+ const theirsMeta = metaOf(theirs, name, field);
264
+ const baseMeta = metaOf(base, name, field);
265
+ if (oursMeta === theirsMeta) continue;
266
+ if (oursMeta === baseMeta && theirsMeta === baseMeta) continue;
267
+ const oursPresent = oursMeta !== baseMeta;
268
+ const theirsPresent = theirsMeta !== baseMeta;
269
+ if (!oursPresent && !theirsPresent) continue;
270
+ let defaultPick: SyncPick | null = null;
271
+ if (oursPresent && !theirsPresent) defaultPick = 'ours';
272
+ else if (!oursPresent && theirsPresent) defaultPick = 'theirs';
273
+ items.push({
274
+ id: itemId(machineKey, 'node-meta', `${name}/${field}`),
275
+ kind: 'node-meta',
276
+ machineKey,
277
+ sourceFile,
278
+ oursPresent,
279
+ theirsPresent,
280
+ labelOurs: oursPresent ? `${field} ${name}=${oursMeta ?? '∅'}` : null,
281
+ labelTheirs: theirsPresent ? `${field} ${name}=${theirsMeta ?? '∅'}` : null,
282
+ defaultPick,
283
+ oursStateName: name,
284
+ theirsStateName: name,
285
+ metaField: field,
286
+ oursNodeMeta: oursMeta,
287
+ theirsNodeMeta: theirsMeta,
288
+ });
289
+ }
290
+ }
291
+
292
+ const baseTrans = transitionMap(base);
293
+ const oursTrans = transitionMap(ours);
294
+ const theirsTrans = transitionMap(theirs);
295
+ const oursByPair = payloadsByPair(oursTrans);
296
+ const theirsByPair = payloadsByPair(theirsTrans);
297
+ const allPairs = new Set([...oursByPair.keys(), ...theirsByPair.keys()]);
298
+
299
+ for (const pair of allPairs) {
300
+ const oursP = oursByPair.get(pair) ?? [];
301
+ const theirsP = theirsByPair.get(pair) ?? [];
302
+ const oursSigs = new Set(oursP.map((p) => transitionSig(p)));
303
+ const theirsSigs = new Set(theirsP.map((p) => transitionSig(p)));
304
+ const aligned =
305
+ oursSigs.size === theirsSigs.size && [...oursSigs].every((s) => theirsSigs.has(s));
306
+ if (aligned) continue;
307
+
308
+ if (oursP.length === 1 && theirsP.length === 1) {
309
+ const payload = oursP[0]!;
310
+ const tpayload = theirsP[0]!;
311
+ const onlyCondition =
312
+ payload.from === tpayload.from &&
313
+ payload.event === tpayload.event &&
314
+ payload.to === tpayload.to &&
315
+ (payload.condition ?? '') !== (tpayload.condition ?? '');
316
+ items.push({
317
+ id: itemId(machineKey, onlyCondition ? 'condition' : 'transition', pair),
318
+ kind: onlyCondition ? 'condition' : 'transition',
319
+ machineKey,
320
+ sourceFile,
321
+ oursPresent: true,
322
+ theirsPresent: true,
323
+ labelOurs: formatTransition(payload),
324
+ labelTheirs: formatTransition(tpayload),
325
+ defaultPick: null,
326
+ oursTransition: payload,
327
+ theirsTransition: tpayload,
328
+ });
329
+ continue;
330
+ }
331
+
332
+ for (const payload of oursP) {
333
+ if (theirsSigs.has(transitionSig(payload))) continue;
334
+ items.push({
335
+ id: itemId(machineKey, 'transition', `ours+${transitionSig(payload)}`),
336
+ kind: 'transition',
337
+ machineKey,
338
+ sourceFile,
339
+ oursPresent: true,
340
+ theirsPresent: false,
341
+ labelOurs: formatTransition(payload),
342
+ labelTheirs: null,
343
+ defaultPick: 'ours',
344
+ oursTransition: payload,
345
+ });
346
+ }
347
+
348
+ for (const payload of theirsP) {
349
+ if (oursSigs.has(transitionSig(payload))) continue;
350
+ const canvasDroppedPair = oursP.length === 0 && baseTrans.has(transitionSig(payload));
351
+ if (canvasDroppedPair) {
352
+ items.push({
353
+ id: itemId(machineKey, 'transition', `drop+${transitionSig(payload)}`),
354
+ kind: 'transition',
355
+ machineKey,
356
+ sourceFile,
357
+ oursPresent: true,
358
+ theirsPresent: true,
359
+ labelOurs: `去掉 ${formatTransition(payload)}`,
360
+ labelTheirs: formatTransition(payload),
361
+ defaultPick: 'ours',
362
+ oursTransition: payload,
363
+ theirsTransition: payload,
364
+ });
365
+ continue;
366
+ }
367
+ items.push({
368
+ id: itemId(machineKey, 'transition', `theirs+${transitionSig(payload)}`),
369
+ kind: 'transition',
370
+ machineKey,
371
+ sourceFile,
372
+ oursPresent: false,
373
+ theirsPresent: true,
374
+ labelOurs: null,
375
+ labelTheirs: formatTransition(payload),
376
+ defaultPick: 'theirs',
377
+ theirsTransition: payload,
378
+ });
379
+ }
380
+ }
381
+
382
+ return items;
383
+ }
384
+
385
+ export function buildDocSyncItems(
386
+ sourceFile: string,
387
+ oursText: string,
388
+ theirsText: string,
389
+ ): SyncItem[] {
390
+ if (oursText === theirsText) return [];
391
+ return [
392
+ {
393
+ id: `doc/${sourceFile}`,
394
+ kind: 'doc-rule',
395
+ sourceFile,
396
+ oursPresent: true,
397
+ theirsPresent: true,
398
+ labelOurs: '你在本画布改的正文',
399
+ labelTheirs: '文件里新来的正文',
400
+ defaultPick: null,
401
+ oursText,
402
+ theirsText,
403
+ },
404
+ ];
405
+ }
406
+
407
+ function ensureState(machine: StudioMachineIR, name: string): string {
408
+ const existing = machine.states.find((s) => s.name === name);
409
+ if (existing) return existing.uid;
410
+ const uid = nextPrefixedUid(
411
+ 's',
412
+ machine.states.map((s) => s.uid),
413
+ );
414
+ const created: StudioStateNode = { uid, name };
415
+ machine.states = [...machine.states, created];
416
+ if (machine.initialStateUid === null) machine.initialStateUid = uid;
417
+ return uid;
418
+ }
419
+
420
+ function addTransition(machine: StudioMachineIR, payload: SyncTransitionPayload): void {
421
+ const fromUid = ensureState(machine, payload.from);
422
+ const toUid = ensureState(machine, payload.to);
423
+ const already = machine.transitions.some((e) => {
424
+ const cur = transitionPayload(machine, e);
425
+ return transitionSig(cur) === transitionSig(payload);
426
+ });
427
+ if (already) return;
428
+ const uid = nextPrefixedUid(
429
+ 'e',
430
+ machine.transitions.map((t) => t.uid),
431
+ );
432
+ const edge: StudioTransitionEdge = {
433
+ uid,
434
+ fromUid,
435
+ event: payload.event,
436
+ toUid,
437
+ ...(payload.condition !== undefined && payload.condition !== ''
438
+ ? { condition: payload.condition }
439
+ : {}),
440
+ };
441
+ machine.transitions = [...machine.transitions, edge];
442
+ }
443
+
444
+ function replacePair(machine: StudioMachineIR, payload: SyncTransitionPayload): void {
445
+ machine.transitions = machine.transitions.filter(
446
+ (e) => pairKey(transitionPayload(machine, e)) !== pairKey(payload),
447
+ );
448
+ addTransition(machine, payload);
449
+ }
450
+
451
+ const NODE_ATTR_FIELDS = ['summary', 'actor', 'done'] as const;
452
+
453
+ function copyUncontestedAttrs(
454
+ target: StudioStateNode,
455
+ from: StudioStateNode,
456
+ contested: { nest: boolean; kind: boolean; meta: ReadonlySet<string> },
457
+ ): void {
458
+ if (!contested.kind) {
459
+ if (from.nodeKind) target.nodeKind = from.nodeKind;
460
+ else delete target.nodeKind;
461
+ }
462
+ if (!contested.nest) {
463
+ if (from.nestKey) target.nestKey = from.nestKey;
464
+ else delete target.nestKey;
465
+ }
466
+ for (const field of NODE_ATTR_FIELDS) {
467
+ if (contested.meta.has(field)) continue;
468
+ if (from[field]) target[field] = from[field];
469
+ else delete target[field];
470
+ }
471
+ }
472
+
473
+ /** Domain IR equality: states (name, type, summary, nest) and transition signatures. Layout ignored. */
474
+ export function machineDomainEquals(a: StudioMachineIR | null, b: StudioMachineIR | null): boolean {
475
+ if (a === null && b === null) return true;
476
+ if (a === null || b === null) return false;
477
+ if (a.states.length !== b.states.length) return false;
478
+ const bByName = new Map(b.states.map((s) => [s.name, s]));
479
+ for (const sa of a.states) {
480
+ const sb = bByName.get(sa.name);
481
+ if (!sb) return false;
482
+ if ((sa.nodeKind ?? '') !== (sb.nodeKind ?? '')) return false;
483
+ if ((sa.summary ?? '') !== (sb.summary ?? '')) return false;
484
+ if ((sa.nestKey ?? '') !== (sb.nestKey ?? '')) return false;
485
+ if ((sa.actor ?? '') !== (sb.actor ?? '')) return false;
486
+ if ((sa.done ?? '') !== (sb.done ?? '')) return false;
487
+ }
488
+ const sigs = (ir: StudioMachineIR): Set<string> => {
489
+ const set = new Set<string>();
490
+ for (const edge of ir.transitions) set.add(transitionSig(transitionPayload(ir, edge)));
491
+ return set;
492
+ };
493
+ const aSigs = sigs(a);
494
+ const bSigs = sigs(b);
495
+ if (aSigs.size !== bSigs.size) return false;
496
+ for (const s of aSigs) {
497
+ if (!bSigs.has(s)) return false;
498
+ }
499
+ return true;
500
+ }
501
+
502
+ function overlayAlignedFromOurs(
503
+ machine: StudioMachineIR,
504
+ ours: StudioMachineIR,
505
+ items: readonly SyncItem[],
506
+ ): void {
507
+ const contestedStates = new Set<string>();
508
+ const contestedNest = new Set<string>();
509
+ const contestedKind = new Set<string>();
510
+ const contestedMeta = new Map<string, Set<string>>();
511
+ const contestedPairs = new Set<string>();
512
+ const contestedSigs = new Set<string>();
513
+ for (const item of items) {
514
+ if (item.kind === 'state') {
515
+ const name = item.oursStateName ?? item.theirsStateName;
516
+ if (name) contestedStates.add(name);
517
+ }
518
+ const attrName = item.oursStateName ?? item.theirsStateName;
519
+ if (item.kind === 'nest' && attrName) contestedNest.add(attrName);
520
+ if (item.kind === 'kind' && attrName) contestedKind.add(attrName);
521
+ if (item.kind === 'node-meta' && attrName && item.metaField) {
522
+ const fields = contestedMeta.get(attrName) ?? new Set<string>();
523
+ fields.add(item.metaField);
524
+ contestedMeta.set(attrName, fields);
525
+ }
526
+ const payloads = [item.oursTransition, item.theirsTransition].filter(
527
+ (p): p is SyncTransitionPayload => p !== undefined,
528
+ );
529
+ for (const p of payloads) {
530
+ contestedPairs.add(pairKey(p));
531
+ contestedSigs.add(transitionSig(p));
532
+ }
533
+ }
534
+
535
+ const oursNames = new Set(ours.states.map((s) => s.name));
536
+ const machineNames = new Set(machine.states.map((s) => s.name));
537
+ for (const name of new Set([...oursNames, ...machineNames])) {
538
+ if (contestedStates.has(name)) continue;
539
+ const inOurs = oursNames.has(name);
540
+ const inMachine = machineNames.has(name);
541
+ if (inOurs && !inMachine) ensureState(machine, name);
542
+ if (!inOurs && inMachine) removeStateByName(machine, name);
543
+ }
544
+ for (const oursState of ours.states) {
545
+ if (contestedStates.has(oursState.name)) continue;
546
+ const target = machine.states.find((s) => s.name === oursState.name);
547
+ if (!target) continue;
548
+ copyUncontestedAttrs(target, oursState, {
549
+ nest: contestedNest.has(oursState.name),
550
+ kind: contestedKind.has(oursState.name),
551
+ meta: contestedMeta.get(oursState.name) ?? new Set(),
552
+ });
553
+ }
554
+
555
+ const oursMap = transitionMap(ours);
556
+ const machineMap = transitionMap(machine);
557
+ for (const [sig, payload] of oursMap) {
558
+ if (contestedSigs.has(sig) || contestedPairs.has(pairKey(payload))) continue;
559
+ if (!machineMap.has(sig)) addTransition(machine, payload);
560
+ }
561
+ for (const [sig, payload] of machineMap) {
562
+ if (contestedSigs.has(sig) || contestedPairs.has(pairKey(payload))) continue;
563
+ if (!oursMap.has(sig)) removeTransition(machine, payload);
564
+ }
565
+ }
566
+
567
+ function removeStateByName(machine: StudioMachineIR, name: string): void {
568
+ const target = machine.states.find((s) => s.name === name);
569
+ if (!target) return;
570
+ machine.states = machine.states.filter((s) => s.uid !== target.uid);
571
+ machine.transitions = machine.transitions.filter(
572
+ (t) => t.fromUid !== target.uid && t.toUid !== target.uid,
573
+ );
574
+ if (machine.initialStateUid === target.uid) {
575
+ machine.initialStateUid = machine.states[0]?.uid ?? null;
576
+ }
577
+ }
578
+
579
+ function removeTransition(machine: StudioMachineIR, payload: SyncTransitionPayload): void {
580
+ machine.transitions = machine.transitions.filter((e) => {
581
+ return transitionSig(transitionPayload(machine, e)) !== transitionSig(payload);
582
+ });
583
+ }
584
+
585
+ function isRemovalLabel(label: string | null): boolean {
586
+ return label !== null && label.startsWith('去掉');
587
+ }
588
+
589
+ function clashBoth(item: SyncItem): boolean {
590
+ if (item.kind === 'nest' || item.kind === 'kind' || item.kind === 'node-meta') {
591
+ return item.oursPresent && item.theirsPresent;
592
+ }
593
+ return (
594
+ item.oursPresent &&
595
+ item.theirsPresent &&
596
+ item.kind !== 'doc-rule' &&
597
+ item.oursTransition !== undefined &&
598
+ item.theirsTransition !== undefined &&
599
+ pairKey(item.oursTransition) === pairKey(item.theirsTransition)
600
+ );
601
+ }
602
+
603
+ function writePickedStateAttr(
604
+ machine: StudioMachineIR,
605
+ name: string,
606
+ pick: SyncPick,
607
+ oursValue: string | null | undefined,
608
+ theirsValue: string | null | undefined,
609
+ write: (state: StudioStateNode, next: string | null | undefined) => void,
610
+ ): boolean {
611
+ const state = machine.states.find((s) => s.name === name);
612
+ if (!state) return false;
613
+ if (pick === 'theirs') write(state, theirsValue);
614
+ else if (pick === 'ours') write(state, oursValue);
615
+ return true;
616
+ }
617
+
618
+ export function applySyncPicks(
619
+ draft: MachineDraft,
620
+ items: readonly SyncItem[],
621
+ picks: Readonly<Record<string, SyncPick>>,
622
+ _nowIso: string,
623
+ ): ApplySyncPicksResult {
624
+ const next = cloneMachineDraft(draft);
625
+ const seed = next.baseline ?? next.current;
626
+ if (seed === null) {
627
+ return { draft: next, applied: [], blocked: [] };
628
+ }
629
+ const machine = cloneMachineIR(seed);
630
+ if (next.current) overlayAlignedFromOurs(machine, next.current, items);
631
+ const applied: string[] = [];
632
+ const blocked: Array<{ itemId: string; reason: string }> = [];
633
+
634
+ for (const item of items) {
635
+ const pick = picks[item.id];
636
+ if (pick === undefined) continue;
637
+ if (pick === 'both' && clashBoth(item)) {
638
+ blocked.push({ itemId: item.id, reason: SYNC_BOTH_BLOCKED_REASON });
639
+ continue;
640
+ }
641
+
642
+ if (item.kind === 'nest') {
643
+ const name = item.oursStateName ?? item.theirsStateName;
644
+ if (name === undefined) continue;
645
+ writePickedStateAttr(machine, name, pick, item.oursNest, item.theirsNest, (state, value) => {
646
+ if (value) state.nestKey = value;
647
+ else delete state.nestKey;
648
+ });
649
+ applied.push(item.id);
650
+ continue;
651
+ }
652
+
653
+ if (item.kind === 'kind') {
654
+ const name = item.oursStateName ?? item.theirsStateName;
655
+ if (name === undefined) continue;
656
+ writePickedStateAttr(
657
+ machine,
658
+ name,
659
+ pick,
660
+ item.oursNodeKind,
661
+ item.theirsNodeKind,
662
+ (state, value) => {
663
+ if (value) state.nodeKind = value;
664
+ else delete state.nodeKind;
665
+ },
666
+ );
667
+ applied.push(item.id);
668
+ continue;
669
+ }
670
+
671
+ if (item.kind === 'node-meta') {
672
+ const name = item.oursStateName ?? item.theirsStateName;
673
+ const field = item.metaField;
674
+ if (name === undefined || field === undefined) continue;
675
+ writePickedStateAttr(
676
+ machine,
677
+ name,
678
+ pick,
679
+ item.oursNodeMeta,
680
+ item.theirsNodeMeta,
681
+ (state, value) => {
682
+ if (value) state[field] = value;
683
+ else delete state[field];
684
+ },
685
+ );
686
+ applied.push(item.id);
687
+ continue;
688
+ }
689
+
690
+ if (item.kind === 'state') {
691
+ const name = item.oursStateName ?? item.theirsStateName;
692
+ if (name === undefined) continue;
693
+ if (pick === 'ours') {
694
+ if (item.oursPresent && isRemovalLabel(item.labelOurs)) {
695
+ removeStateByName(machine, name);
696
+ } else if (item.oursPresent) {
697
+ ensureState(machine, item.oursStateName ?? name);
698
+ } else if (item.theirsPresent) {
699
+ removeStateByName(machine, name);
700
+ }
701
+ } else if (pick === 'theirs') {
702
+ if (item.theirsPresent && isRemovalLabel(item.labelTheirs)) {
703
+ removeStateByName(machine, name);
704
+ } else if (item.theirsPresent) {
705
+ ensureState(machine, item.theirsStateName ?? name);
706
+ } else if (item.oursPresent && !isRemovalLabel(item.labelOurs)) {
707
+ removeStateByName(machine, name);
708
+ }
709
+ } else if (pick === 'both') {
710
+ if (item.oursStateName) ensureState(machine, item.oursStateName);
711
+ if (item.theirsStateName) ensureState(machine, item.theirsStateName);
712
+ }
713
+ applied.push(item.id);
714
+ continue;
715
+ }
716
+
717
+ if (item.kind === 'transition' || item.kind === 'condition') {
718
+ const writePayload = (payload: SyncTransitionPayload): void => {
719
+ if (item.kind === 'condition' || clashBoth(item)) replacePair(machine, payload);
720
+ else addTransition(machine, payload);
721
+ };
722
+ if (pick === 'ours') {
723
+ if (item.oursTransition && isRemovalLabel(item.labelOurs)) {
724
+ removeTransition(machine, item.oursTransition);
725
+ } else if (item.oursTransition) {
726
+ writePayload(item.oursTransition);
727
+ } else if (item.theirsTransition && !isRemovalLabel(item.labelTheirs)) {
728
+ removeTransition(machine, item.theirsTransition);
729
+ }
730
+ } else if (pick === 'theirs') {
731
+ if (item.theirsTransition && isRemovalLabel(item.labelTheirs)) {
732
+ removeTransition(machine, item.theirsTransition);
733
+ } else if (item.theirsTransition) {
734
+ writePayload(item.theirsTransition);
735
+ } else if (item.oursTransition && !isRemovalLabel(item.labelOurs)) {
736
+ removeTransition(machine, item.oursTransition);
737
+ }
738
+ } else if (pick === 'both') {
739
+ if (item.oursTransition && !isRemovalLabel(item.labelOurs)) {
740
+ addTransition(machine, item.oursTransition);
741
+ }
742
+ if (item.theirsTransition && !isRemovalLabel(item.labelTheirs)) {
743
+ addTransition(machine, item.theirsTransition);
744
+ }
745
+ }
746
+ applied.push(item.id);
747
+ }
748
+ }
749
+
750
+ next.current = machine;
751
+ return { draft: next, applied, blocked };
752
+ }
753
+
754
+ export function applyDocSyncPicks(
755
+ docDraft: StudioDocDraft,
756
+ items: readonly SyncItem[],
757
+ picks: Readonly<Record<string, SyncPick>>,
758
+ ): ApplyDocSyncPicksResult {
759
+ let next: StudioDocDraft = { ...docDraft };
760
+ const applied: string[] = [];
761
+ const blocked: Array<{ itemId: string; reason: string }> = [];
762
+ for (const item of items) {
763
+ if (item.kind !== 'doc-rule') continue;
764
+ const pick = picks[item.id];
765
+ if (pick === undefined) continue;
766
+ if (pick === 'both') {
767
+ blocked.push({ itemId: item.id, reason: SYNC_BOTH_BLOCKED_REASON });
768
+ continue;
769
+ }
770
+ if (pick === 'theirs' && item.theirsText !== undefined) {
771
+ next = { ...next, currentText: item.theirsText };
772
+ }
773
+ applied.push(item.id);
774
+ }
775
+ return { docDraft: next, applied, blocked };
776
+ }
777
+
778
+ export function hasOpenSyncSnapshot(doc: StudioStateDoc, machineKey: string): boolean {
779
+ const openId = doc.syncOpen?.[machineKey];
780
+ if (openId === undefined) return false;
781
+ const tl = doc.timelines[machineKey];
782
+ return tl?.entries.some((e) => e.id === openId) === true;
783
+ }
784
+
785
+ function canonicalMachineIr(ir: StudioMachineIR | null): string {
786
+ if (ir === null) return 'null';
787
+ const states = [...ir.states]
788
+ .sort((a, b) => a.uid.localeCompare(b.uid))
789
+ .map((s) => ({
790
+ uid: s.uid,
791
+ name: s.name,
792
+ nodeKind: s.nodeKind,
793
+ nestKey: s.nestKey,
794
+ summary: s.summary,
795
+ done: s.done,
796
+ actor: s.actor,
797
+ }));
798
+ const transitions = [...ir.transitions]
799
+ .sort((a, b) => a.uid.localeCompare(b.uid))
800
+ .map((e) => ({
801
+ uid: e.uid,
802
+ fromUid: e.fromUid,
803
+ event: e.event,
804
+ condition: e.condition,
805
+ action: e.action,
806
+ actor: e.actor,
807
+ edgeKind: e.edgeKind,
808
+ meta: e.meta,
809
+ verify: e.verify,
810
+ toUid: e.toUid,
811
+ }));
812
+ return JSON.stringify({
813
+ machineKey: ir.machineKey,
814
+ capability: ir.capability,
815
+ reqId: ir.reqId,
816
+ ruleTitle: ir.ruleTitle,
817
+ scenarioName: ir.scenarioName,
818
+ graphKind: ir.graphKind ?? 'machine',
819
+ initialStateUid: ir.initialStateUid,
820
+ columns: ir.columns,
821
+ states,
822
+ transitions,
823
+ });
824
+ }
825
+
826
+ /** Canonical semantic equality for two Studio machine IR snapshots (ignores layout coordinates). */
827
+ export function machineIrSemanticallyEquivalent(
828
+ a: StudioMachineIR | null,
829
+ b: StudioMachineIR | null,
830
+ ): boolean {
831
+ return canonicalMachineIr(a) === canonicalMachineIr(b);
832
+ }
833
+
834
+ export function snapshotBeforeSync(
835
+ doc: StudioStateDoc,
836
+ machineKey: string,
837
+ nowIso: string,
838
+ ): StudioStateDoc {
839
+ if (hasOpenSyncSnapshot(doc, machineKey)) return doc;
840
+ const current = doc.machines[machineKey]?.current ?? null;
841
+ const timeline = doc.timelines[machineKey];
842
+ const head = timeline?.entries[timeline.headIdx];
843
+ const isSyncSnapshotHead =
844
+ head?.branchRef === SYNC_SNAPSHOT_BRANCH_REF || head?.label === SYNC_SNAPSHOT_LABEL;
845
+ if (
846
+ timeline !== undefined &&
847
+ head !== undefined &&
848
+ !head.isBase &&
849
+ isSyncSnapshotHead &&
850
+ machineIrSemanticallyEquivalent(current, head.snapshot)
851
+ ) {
852
+ return {
853
+ ...doc,
854
+ updatedAt: nowIso,
855
+ revision: (doc.revision ?? 0) + 1,
856
+ syncOpen: { ...doc.syncOpen, [machineKey]: head.id },
857
+ };
858
+ }
859
+ const snapped = recordWorldlineCommit(doc, machineKey, current, {
860
+ label: SYNC_SNAPSHOT_LABEL,
861
+ createdAt: nowIso,
862
+ actor: 'human',
863
+ branchRef: SYNC_SNAPSHOT_BRANCH_REF,
864
+ });
865
+ const tl = snapped.timelines[machineKey];
866
+ const snapshotId = tl?.entries.at(-1)?.id;
867
+ if (snapshotId === undefined) return snapped;
868
+ return {
869
+ ...snapped,
870
+ syncOpen: { ...snapped.syncOpen, [machineKey]: snapshotId },
871
+ };
872
+ }
873
+
874
+ export function closeSyncSnapshot(doc: StudioStateDoc, machineKey: string): StudioStateDoc {
875
+ if (doc.syncOpen === undefined || doc.syncOpen[machineKey] === undefined) return doc;
876
+ const next = { ...doc.syncOpen };
877
+ delete next[machineKey];
878
+ return { ...doc, syncOpen: Object.keys(next).length > 0 ? next : undefined };
879
+ }
880
+
881
+ /** Release every open sync snapshot in one pure pass (panel dismissal). */
882
+ export function closeAllSyncSnapshots(doc: StudioStateDoc): StudioStateDoc {
883
+ let next = doc;
884
+ for (const key of Object.keys(doc.syncOpen ?? {})) next = closeSyncSnapshot(next, key);
885
+ return next;
886
+ }
887
+
888
+ export function picksMatchDiff(
889
+ before: MachineDraft,
890
+ after: MachineDraft,
891
+ items: readonly SyncItem[],
892
+ picks: Readonly<Record<string, SyncPick>>,
893
+ ): boolean {
894
+ const afterDiff = computeMachineDiff(after);
895
+ const theirsNames = new Set(
896
+ items
897
+ .filter((i) => picks[i.id] === 'theirs' && i.theirsStateName)
898
+ .map((i) => i.theirsStateName!),
899
+ );
900
+ for (const name of theirsNames) {
901
+ if (!after.current?.states.some((s) => s.name === name)) return false;
902
+ }
903
+ const droppedOurs = items.filter(
904
+ (i) => picks[i.id] === 'theirs' && i.oursPresent && !i.theirsPresent && i.oursStateName,
905
+ );
906
+ for (const item of droppedOurs) {
907
+ if (after.current?.states.some((s) => s.name === item.oursStateName)) return false;
908
+ }
909
+ void before;
910
+ void afterDiff;
911
+ return true;
912
+ }