@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.
- package/package.json +11 -8
- package/src/archive/freeze.ts +41 -15
- package/src/archive/frozenCard.ts +57 -9
- package/src/archive/ignoreChain.ts +2 -6
- package/src/archive/sevenzip.ts +0 -1
- package/src/change/closeOutHarness.ts +17 -0
- package/src/change/collect.ts +0 -5
- package/src/change/frontmatter.ts +15 -7
- package/src/change/id.ts +0 -2
- package/src/change/lifecycle.ts +53 -94
- package/src/config/changeId.ts +0 -2
- package/src/config/load.ts +0 -4
- package/src/config/schema.ts +24 -13
- package/src/config/surface.ts +2 -12
- package/src/context/sddState.ts +23 -18
- package/src/git/spawnGit.ts +0 -3
- package/src/hints/jitHints.ts +82 -0
- package/src/index.ts +462 -39
- package/src/init/defaultConfig.ts +4 -13
- package/src/init/init.ts +108 -36
- package/src/init/skillCheck.ts +60 -0
- package/src/init/uncommentConfig.ts +909 -0
- package/src/locale.ts +0 -2
- package/src/project/migrateNotes.ts +0 -9
- package/src/project/migrations.ts +151 -9
- package/src/report/graph/analysis.ts +0 -4
- package/src/report/graph/nodes.ts +0 -6
- package/src/report/show.ts +7 -23
- package/src/report/specHelpers.ts +10 -14
- package/src/review/review.ts +0 -12
- package/src/spec/assignSpecIds.ts +0 -3
- package/src/spec/authoring.ts +16 -24
- package/src/spec/ir.ts +14 -5
- package/src/spec/keywords.ts +0 -2
- package/src/spec/machineKey.ts +49 -0
- package/src/spec/migrateNative.ts +4 -18
- package/src/spec/parser.ts +10 -19
- package/src/spec/reqRef.ts +135 -0
- package/src/studio/changeScope.ts +50 -0
- package/src/studio/changeScopeDiff.ts +195 -0
- package/src/studio/contracts.ts +493 -0
- package/src/studio/decisionTree.ts +206 -0
- package/src/studio/deeplink.ts +116 -0
- package/src/studio/demos.ts +167 -0
- package/src/studio/diff.ts +494 -0
- package/src/studio/drift.ts +738 -0
- package/src/studio/extract.ts +360 -0
- package/src/studio/featureSync.ts +592 -0
- package/src/studio/forest.ts +570 -0
- package/src/studio/index.ts +32 -0
- package/src/studio/model.ts +254 -0
- package/src/studio/revisions.ts +476 -0
- package/src/studio/search.ts +337 -0
- package/src/studio/store.ts +811 -0
- package/src/studio/sync.ts +912 -0
- package/src/studio/textfold.ts +72 -0
- package/src/studio/time.ts +107 -0
- package/src/studio/validate.ts +363 -0
- package/src/templates/embedded.ts +4 -6
- package/src/templates/engine.ts +1 -1
- package/src/templates/skills.ts +76 -51
- package/src/theorems/guard.ts +52 -0
- package/src/theorems/index.ts +56 -0
- package/src/theorems/migrate.ts +133 -0
- package/src/theorems/schema.ts +67 -0
- package/src/theorems/scope.ts +68 -0
- package/src/theorems/serialize.ts +60 -0
- package/src/theorems/transactionMachine.ts +247 -0
- package/src/theorems/validate.ts +141 -0
- package/src/util/nextNumber.ts +0 -2
- package/src/validation/changeCheck.ts +0 -24
- package/src/validation/flowAndNesting.ts +434 -0
- package/src/validation/harness.ts +108 -65
- package/src/validation/validate.ts +26 -12
- package/src/validation/xstateTransitions.ts +483 -184
- package/templates/zh-Hans/llmanspec-agents-stub.md +17 -2
- package/templates/zh-Hans/skills/llman-sdd-autopilot/SKILL.md +34 -0
- package/templates/zh-Hans/skills/llman-sdd-change/SKILL.md +44 -0
- package/templates/zh-Hans/skills/llman-sdd-change/playbooks/archive.md +15 -0
- package/templates/zh-Hans/skills/llman-sdd-change/playbooks/draft.md +9 -0
- package/templates/zh-Hans/skills/llman-sdd-review/SKILL.md +71 -0
- package/templates/zh-Hans/skills/llman-sdd-specs/SKILL.md +70 -0
- package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/compact.md +12 -0
- package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/doctor.md +26 -0
- package/templates/zh-Hans/skills/llman-sdd-specs/references/graph-dsl.md +33 -0
- package/templates/zh-Hans/skills/llman-sdd-studio/SKILL.md +33 -0
- package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/collab.md +20 -0
- package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/drift.md +52 -0
- package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/onboard.md +33 -0
- package/templates/zh-Hans/units/skills/cli-footer.md +2 -2
- package/src/context/indexStore.ts +0 -171
- package/src/context/retrieve.ts +0 -332
- package/src/context/tree.ts +0 -112
- package/templates/zh-Hans/agents-root-stub.md +0 -9
- package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +0 -69
- package/templates/zh-Hans/skills/llman-sdd-apply.md +0 -117
- package/templates/zh-Hans/skills/llman-sdd-arch-review.md +0 -58
- package/templates/zh-Hans/skills/llman-sdd-archive.md +0 -79
- package/templates/zh-Hans/skills/llman-sdd-continue.md +0 -34
- package/templates/zh-Hans/skills/llman-sdd-draft.md +0 -53
- package/templates/zh-Hans/skills/llman-sdd-explore.md +0 -64
- package/templates/zh-Hans/skills/llman-sdd-ff.md +0 -33
- package/templates/zh-Hans/skills/llman-sdd-graph.md +0 -56
- package/templates/zh-Hans/skills/llman-sdd-propose.md +0 -107
- package/templates/zh-Hans/skills/llman-sdd-quick.md +0 -41
- package/templates/zh-Hans/skills/llman-sdd-research.md +0 -35
- package/templates/zh-Hans/skills/llman-sdd-specs-compact.md +0 -41
- package/templates/zh-Hans/skills/llman-sdd-validate.md +0 -28
- package/templates/zh-Hans/skills/llman-sdd-verify.md +0 -77
- package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +0 -83
- package/templates/zh-Hans/units/skills/ethics-governance.md +0 -6
- package/templates/zh-Hans/units/skills/git-native-flow.md +0 -56
- package/templates/zh-Hans/units/skills/human-readable-summary.md +0 -9
- package/templates/zh-Hans/units/skills/index-fallback.md +0 -1
- package/templates/zh-Hans/units/skills/stage-guard.md +0 -17
- package/templates/zh-Hans/units/skills/structured-protocol.md +0 -19
- package/templates/zh-Hans/units/skills/validation-hints.md +0 -20
- package/templates/zh-Hans/units/skills/version-drift.md +0 -3
- package/templates/zh-Hans/units/spec/feature-contract.md +0 -8
|
@@ -0,0 +1,811 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local Studio draft storage, Zod validation, and Git-like linear change timeline (studio-core r132).
|
|
3
|
+
* Pure domain module — filesystem and clock access only via injected StudioStateIo.
|
|
4
|
+
*/
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
|
|
7
|
+
import { REQ_ID_RE, allocateNextReqId } from '../spec/reqRef.ts';
|
|
8
|
+
import type { FsPort } from '../util/fsPort.ts';
|
|
9
|
+
import {
|
|
10
|
+
cloneMachineDraft,
|
|
11
|
+
cloneMachineIR,
|
|
12
|
+
makeMachineKey,
|
|
13
|
+
type MachineDraft,
|
|
14
|
+
type MachineTimeline,
|
|
15
|
+
type StudioMachineIR,
|
|
16
|
+
type StudioStateDoc,
|
|
17
|
+
type StudioStateNode,
|
|
18
|
+
type EdgeBendOffset,
|
|
19
|
+
type NodePosition,
|
|
20
|
+
} from './model.ts';
|
|
21
|
+
|
|
22
|
+
export const STUDIO_STATES_REL = '.llman-sdd/studio/states';
|
|
23
|
+
|
|
24
|
+
export type StudioStateIo = Pick<
|
|
25
|
+
FsPort,
|
|
26
|
+
| 'exists'
|
|
27
|
+
| 'readText'
|
|
28
|
+
| 'writeText'
|
|
29
|
+
| 'rename'
|
|
30
|
+
| 'listDir'
|
|
31
|
+
| 'mkdirp'
|
|
32
|
+
| 'remove'
|
|
33
|
+
| 'currentPid'
|
|
34
|
+
| 'now'
|
|
35
|
+
>;
|
|
36
|
+
|
|
37
|
+
export class StudioStateError extends Error {
|
|
38
|
+
constructor(message: string) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.name = 'StudioStateError';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const STATE_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/u;
|
|
45
|
+
|
|
46
|
+
export function validateStateId(stateId: string): string {
|
|
47
|
+
const id = stateId.trim();
|
|
48
|
+
if (!STATE_ID_RE.test(id)) {
|
|
49
|
+
throw new StudioStateError(
|
|
50
|
+
`invalid studio state id "${stateId}": must match ${STATE_ID_RE.source} (no path traversal)`,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
return id;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function studioStateRelPath(stateId: string): string {
|
|
57
|
+
return `${STUDIO_STATES_REL}/${validateStateId(stateId)}.json`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const stateNodeSchema = z.object({
|
|
61
|
+
uid: z.string().min(1),
|
|
62
|
+
name: z.string(),
|
|
63
|
+
nodeKind: z.string().optional(),
|
|
64
|
+
nestKey: z.string().min(1).optional(),
|
|
65
|
+
summary: z.string().optional(),
|
|
66
|
+
done: z.string().optional(),
|
|
67
|
+
actor: z.string().optional(),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const transitionEdgeSchema = z.object({
|
|
71
|
+
uid: z.string().min(1),
|
|
72
|
+
fromUid: z.string().min(1),
|
|
73
|
+
event: z.string(),
|
|
74
|
+
condition: z.string().optional(),
|
|
75
|
+
action: z.string().optional(),
|
|
76
|
+
actor: z.string().optional(),
|
|
77
|
+
edgeKind: z.string().optional(),
|
|
78
|
+
meta: z.string().optional(),
|
|
79
|
+
verify: z.string().optional(),
|
|
80
|
+
toUid: z.string().min(1),
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const columnsSchema = z.object({
|
|
84
|
+
source: z.string().min(1),
|
|
85
|
+
label: z.string().min(1),
|
|
86
|
+
target: z.string().min(1),
|
|
87
|
+
condition: z.string().optional(),
|
|
88
|
+
action: z.string().optional(),
|
|
89
|
+
actor: z.string().optional(),
|
|
90
|
+
edgeKind: z.string().optional(),
|
|
91
|
+
meta: z.string().optional(),
|
|
92
|
+
verify: z.string().optional(),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
export const machineIrSchema = z.object({
|
|
96
|
+
machineKey: z.string().min(1),
|
|
97
|
+
capability: z.string().min(1),
|
|
98
|
+
reqId: z.string().nullable(),
|
|
99
|
+
ruleTitle: z.string(),
|
|
100
|
+
scenarioName: z.string().min(1),
|
|
101
|
+
graphKind: z.enum(['machine', 'flow']).optional(),
|
|
102
|
+
initialStateUid: z.string().nullable(),
|
|
103
|
+
columns: columnsSchema,
|
|
104
|
+
states: z.array(stateNodeSchema),
|
|
105
|
+
transitions: z.array(transitionEdgeSchema),
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
const machineDraftSchema = z.object({
|
|
109
|
+
mode: z.enum(['modify', 'create', 'remove']),
|
|
110
|
+
baseline: machineIrSchema.nullable(),
|
|
111
|
+
current: machineIrSchema.nullable(),
|
|
112
|
+
sourceFile: z.string().min(1),
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const semanticAnchorSchema = z.discriminatedUnion('kind', [
|
|
116
|
+
z.object({ kind: z.literal('machine'), machineKey: z.string().min(1) }),
|
|
117
|
+
z.object({
|
|
118
|
+
kind: z.literal('state'),
|
|
119
|
+
machineKey: z.string().min(1),
|
|
120
|
+
stateUid: z.string().min(1),
|
|
121
|
+
}),
|
|
122
|
+
z.object({ kind: z.literal('edge'), machineKey: z.string().min(1), edgeUid: z.string().min(1) }),
|
|
123
|
+
z.object({ kind: z.literal('forest'), capability: z.string().min(1) }),
|
|
124
|
+
z.object({ kind: z.literal('macro-edge'), edgeId: z.string().min(1) }),
|
|
125
|
+
z.object({
|
|
126
|
+
kind: z.literal('doc'),
|
|
127
|
+
capability: z.string().min(1),
|
|
128
|
+
reqId: z.string().min(1).optional(),
|
|
129
|
+
}),
|
|
130
|
+
]);
|
|
131
|
+
|
|
132
|
+
const commentSchema = z.object({
|
|
133
|
+
id: z.string().min(1),
|
|
134
|
+
anchor: semanticAnchorSchema,
|
|
135
|
+
author: z.enum(['human', 'agent']),
|
|
136
|
+
body: z.string().min(1),
|
|
137
|
+
createdAt: z.string().min(1),
|
|
138
|
+
status: z.enum(['open', 'resolved']),
|
|
139
|
+
replyTo: z.string().optional(),
|
|
140
|
+
watchTag: z.string().min(1).optional(),
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
const revisionOpSchema = z.discriminatedUnion('op', [
|
|
144
|
+
z.object({ op: z.literal('add_state'), name: z.string() }).strict(),
|
|
145
|
+
z.object({ op: z.literal('remove_state'), stateName: z.string() }).strict(),
|
|
146
|
+
z.object({ op: z.literal('rename_state'), from: z.string(), to: z.string() }).strict(),
|
|
147
|
+
z
|
|
148
|
+
.object({
|
|
149
|
+
op: z.literal('add_transition'),
|
|
150
|
+
from: z.string(),
|
|
151
|
+
event: z.string(),
|
|
152
|
+
condition: z.string().optional(),
|
|
153
|
+
to: z.string(),
|
|
154
|
+
})
|
|
155
|
+
.strict(),
|
|
156
|
+
z
|
|
157
|
+
.object({
|
|
158
|
+
op: z.literal('remove_transition'),
|
|
159
|
+
from: z.string(),
|
|
160
|
+
event: z.string(),
|
|
161
|
+
condition: z.string().optional(),
|
|
162
|
+
to: z.string(),
|
|
163
|
+
})
|
|
164
|
+
.strict(),
|
|
165
|
+
z
|
|
166
|
+
.object({
|
|
167
|
+
op: z.literal('update_transition'),
|
|
168
|
+
match: z
|
|
169
|
+
.object({
|
|
170
|
+
from: z.string(),
|
|
171
|
+
event: z.string(),
|
|
172
|
+
condition: z.string().optional(),
|
|
173
|
+
to: z.string(),
|
|
174
|
+
})
|
|
175
|
+
.strict(),
|
|
176
|
+
next: z
|
|
177
|
+
.object({
|
|
178
|
+
from: z.string().optional(),
|
|
179
|
+
event: z.string().optional(),
|
|
180
|
+
condition: z.string().optional(),
|
|
181
|
+
to: z.string().optional(),
|
|
182
|
+
})
|
|
183
|
+
.strict(),
|
|
184
|
+
})
|
|
185
|
+
.strict(),
|
|
186
|
+
]);
|
|
187
|
+
|
|
188
|
+
const revisionProposalSchema = z.object({
|
|
189
|
+
id: z.string().min(1),
|
|
190
|
+
machineKey: z.string().min(1),
|
|
191
|
+
author: z.literal('agent'),
|
|
192
|
+
source: z.enum(['agent', 'drift-trace']).optional(),
|
|
193
|
+
rationale: z.string(),
|
|
194
|
+
ops: z.array(revisionOpSchema),
|
|
195
|
+
createdAt: z.string().min(1),
|
|
196
|
+
status: z.enum(['pending', 'accepted', 'rejected']),
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
const timelineEntrySchema = z.object({
|
|
200
|
+
seq: z.number().int().nonnegative(),
|
|
201
|
+
id: z.string().min(1),
|
|
202
|
+
label: z.string(),
|
|
203
|
+
createdAt: z.string().min(1),
|
|
204
|
+
isBase: z.boolean(),
|
|
205
|
+
mode: z.enum(['modify', 'create', 'remove']),
|
|
206
|
+
snapshot: machineIrSchema.nullable(),
|
|
207
|
+
parentId: z.string().min(1).nullable().optional(),
|
|
208
|
+
actor: z.enum(['human', 'agent']).optional(),
|
|
209
|
+
branchRef: z.string().min(1).optional(),
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const timelineSchema = z.object({
|
|
213
|
+
entries: z.array(timelineEntrySchema).min(1),
|
|
214
|
+
headIdx: z.number().int().nonnegative(),
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
const nodePositionSchema = z.object({
|
|
218
|
+
x: z.number().finite(),
|
|
219
|
+
y: z.number().finite(),
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
const edgeBendOffsetSchema = z.object({
|
|
223
|
+
dx: z.number().finite(),
|
|
224
|
+
dy: z.number().finite(),
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
const docDraftSchema = z.object({
|
|
228
|
+
sourceFile: z.string().min(1),
|
|
229
|
+
baseHash: z.string().min(1),
|
|
230
|
+
currentText: z.string(),
|
|
231
|
+
changeKind: z.enum(['wording', 'semantic']),
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
export const studioStateDocSchema = z.object({
|
|
235
|
+
version: z.literal(1),
|
|
236
|
+
id: z.string().regex(STATE_ID_RE),
|
|
237
|
+
title: z.string().min(1),
|
|
238
|
+
createdAt: z.string().min(1),
|
|
239
|
+
updatedAt: z.string().min(1),
|
|
240
|
+
revision: z.number().int().nonnegative().optional(),
|
|
241
|
+
baseHashes: z.record(z.string(), z.string()).optional(),
|
|
242
|
+
machines: z.record(z.string(), machineDraftSchema),
|
|
243
|
+
docDrafts: z.record(z.string(), docDraftSchema).optional(),
|
|
244
|
+
timelines: z.record(z.string(), timelineSchema),
|
|
245
|
+
layouts: z.record(z.string(), z.record(z.string(), nodePositionSchema)),
|
|
246
|
+
edgeBends: z.record(z.string(), z.record(z.string(), edgeBendOffsetSchema)).optional(),
|
|
247
|
+
comments: z.array(commentSchema),
|
|
248
|
+
revisions: z.array(revisionProposalSchema),
|
|
249
|
+
syncOpen: z.record(z.string(), z.string().min(1)).optional(),
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
export function buildInitialTimeline(draft: MachineDraft, createdAt: string): MachineTimeline {
|
|
253
|
+
const baseSnapshot = draft.baseline
|
|
254
|
+
? cloneMachineIR(draft.baseline)
|
|
255
|
+
: draft.current
|
|
256
|
+
? cloneMachineIR(draft.current)
|
|
257
|
+
: null;
|
|
258
|
+
return {
|
|
259
|
+
entries: [
|
|
260
|
+
{
|
|
261
|
+
seq: 0,
|
|
262
|
+
id: 'BASE',
|
|
263
|
+
label: draft.mode === 'create' ? 'initial create draft' : `${draft.sourceFile} baseline`,
|
|
264
|
+
createdAt,
|
|
265
|
+
isBase: true,
|
|
266
|
+
mode: draft.mode,
|
|
267
|
+
snapshot: baseSnapshot,
|
|
268
|
+
},
|
|
269
|
+
],
|
|
270
|
+
headIdx: 0,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export interface CreateStudioStateDocInput {
|
|
275
|
+
id: string;
|
|
276
|
+
title: string;
|
|
277
|
+
createdAt: string;
|
|
278
|
+
drafts: readonly MachineDraft[];
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export interface AllocatedReqId {
|
|
282
|
+
/** Draft machine key before allocation (`draft:<capability>#<场景名>`). */
|
|
283
|
+
machineKey: string;
|
|
284
|
+
/** Newly allocated global `rN` id. */
|
|
285
|
+
reqId: string;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Rename freshly allocated drafts from `draft:<cap>#<场景名>` to `rN#<场景名>`
|
|
290
|
+
* and carry the new identity through every keyed map (machines, timelines,
|
|
291
|
+
* layouts, edge bends, sync sessions, comment anchors, revisions), every
|
|
292
|
+
* `states[*].nestKey` link (including machines that keep their own key) and
|
|
293
|
+
* every worldline `entry.snapshot` (`machineKey` / `reqId` / `nestKey`).
|
|
294
|
+
* Pure — no I/O, no clock.
|
|
295
|
+
*/
|
|
296
|
+
export function applyAllocatedReqIds(
|
|
297
|
+
doc: StudioStateDoc,
|
|
298
|
+
allocations: readonly AllocatedReqId[],
|
|
299
|
+
): StudioStateDoc {
|
|
300
|
+
const keyMap = new Map<string, string>();
|
|
301
|
+
const reqIdByKey = new Map<string, string>();
|
|
302
|
+
for (const allocation of allocations) {
|
|
303
|
+
const draft = doc.machines[allocation.machineKey];
|
|
304
|
+
const machine = draft?.current ?? draft?.baseline ?? null;
|
|
305
|
+
if (machine === null) continue;
|
|
306
|
+
const nextKey = makeMachineKey(machine.capability, allocation.reqId, machine.scenarioName);
|
|
307
|
+
if (nextKey === allocation.machineKey) continue;
|
|
308
|
+
keyMap.set(allocation.machineKey, nextKey);
|
|
309
|
+
reqIdByKey.set(allocation.machineKey, allocation.reqId);
|
|
310
|
+
}
|
|
311
|
+
if (keyMap.size === 0) return doc;
|
|
312
|
+
|
|
313
|
+
const renameKey = (key: string): string => keyMap.get(key) ?? key;
|
|
314
|
+
const remapStates = (states: StudioStateNode[]): StudioStateNode[] =>
|
|
315
|
+
states.map((state) => ({
|
|
316
|
+
...state,
|
|
317
|
+
...(state.nestKey !== undefined ? { nestKey: renameKey(state.nestKey) } : {}),
|
|
318
|
+
}));
|
|
319
|
+
const remapMachine = (
|
|
320
|
+
machine: StudioMachineIR,
|
|
321
|
+
reqId: string | undefined,
|
|
322
|
+
nextKey: string,
|
|
323
|
+
): StudioMachineIR => ({
|
|
324
|
+
...machine,
|
|
325
|
+
...(reqId === undefined ? {} : { machineKey: nextKey, reqId }),
|
|
326
|
+
states: remapStates(machine.states),
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
const machines: Record<string, MachineDraft> = {};
|
|
330
|
+
for (const [key, draft] of Object.entries(doc.machines)) {
|
|
331
|
+
const nextKey = renameKey(key);
|
|
332
|
+
if (
|
|
333
|
+
nextKey !== key &&
|
|
334
|
+
(doc.machines[nextKey] !== undefined || machines[nextKey] !== undefined)
|
|
335
|
+
) {
|
|
336
|
+
throw new Error(
|
|
337
|
+
`applyAllocatedReqIds: renaming \`${key}\` to \`${nextKey}\` collides with an existing machine`,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
const reqId = reqIdByKey.get(key);
|
|
341
|
+
machines[nextKey] = {
|
|
342
|
+
...draft,
|
|
343
|
+
baseline: draft.baseline ? remapMachine(draft.baseline, reqId, nextKey) : null,
|
|
344
|
+
current: draft.current ? remapMachine(draft.current, reqId, nextKey) : null,
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const timelines: Record<string, MachineTimeline> = {};
|
|
349
|
+
for (const [key, timeline] of Object.entries(doc.timelines)) {
|
|
350
|
+
timelines[renameKey(key)] = {
|
|
351
|
+
...timeline,
|
|
352
|
+
entries: timeline.entries.map((entry) => {
|
|
353
|
+
const snapshot = entry.snapshot;
|
|
354
|
+
if (snapshot === null) return entry;
|
|
355
|
+
const snapshotReqId = reqIdByKey.get(snapshot.machineKey);
|
|
356
|
+
return {
|
|
357
|
+
...entry,
|
|
358
|
+
snapshot: {
|
|
359
|
+
...snapshot,
|
|
360
|
+
machineKey: renameKey(snapshot.machineKey),
|
|
361
|
+
...(snapshotReqId === undefined ? {} : { reqId: snapshotReqId }),
|
|
362
|
+
states: remapStates(snapshot.states),
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
}),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
const layouts: Record<string, Record<string, NodePosition>> = {};
|
|
369
|
+
for (const [key, layout] of Object.entries(doc.layouts)) {
|
|
370
|
+
layouts[renameKey(key)] = layout;
|
|
371
|
+
}
|
|
372
|
+
const edgeBends: Record<string, Record<string, EdgeBendOffset>> | undefined =
|
|
373
|
+
doc.edgeBends === undefined
|
|
374
|
+
? undefined
|
|
375
|
+
: Object.fromEntries(
|
|
376
|
+
Object.entries(doc.edgeBends).map(([key, bends]) => [renameKey(key), bends]),
|
|
377
|
+
);
|
|
378
|
+
const syncOpen: Record<string, string> | undefined =
|
|
379
|
+
doc.syncOpen === undefined
|
|
380
|
+
? undefined
|
|
381
|
+
: Object.fromEntries(
|
|
382
|
+
Object.entries(doc.syncOpen).map(([key, entryId]) => [renameKey(key), entryId]),
|
|
383
|
+
);
|
|
384
|
+
|
|
385
|
+
const comments = doc.comments.map((comment) => {
|
|
386
|
+
const anchor = comment.anchor;
|
|
387
|
+
if (!('machineKey' in anchor)) return comment;
|
|
388
|
+
return { ...comment, anchor: { ...anchor, machineKey: renameKey(anchor.machineKey) } };
|
|
389
|
+
});
|
|
390
|
+
const revisions = doc.revisions.map((revision) => ({
|
|
391
|
+
...revision,
|
|
392
|
+
machineKey: renameKey(revision.machineKey),
|
|
393
|
+
}));
|
|
394
|
+
|
|
395
|
+
return {
|
|
396
|
+
...doc,
|
|
397
|
+
machines,
|
|
398
|
+
timelines,
|
|
399
|
+
layouts,
|
|
400
|
+
...(edgeBends !== undefined ? { edgeBends } : {}),
|
|
401
|
+
...(syncOpen !== undefined ? { syncOpen } : {}),
|
|
402
|
+
comments,
|
|
403
|
+
revisions,
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export interface StudioApplyPlan {
|
|
408
|
+
/** Drafts that received a freshly allocated `rN` (draft key → id). */
|
|
409
|
+
allocations: AllocatedReqId[];
|
|
410
|
+
/** Final used id set: disk ids + same-batch explicit ids + allocated ids. */
|
|
411
|
+
usedReqIds: string[];
|
|
412
|
+
/** Original draft key → remapped machine key (identity when unchanged). */
|
|
413
|
+
keyMap: Record<string, string>;
|
|
414
|
+
/** Fully remapped state doc (keys, reqId, machineKey, nestKey, timelines). */
|
|
415
|
+
doc: StudioStateDoc;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Pre-plan one `studio apply`: collect disk ids and same-batch explicit ids,
|
|
420
|
+
* allocate `r<max+1>` for every create draft that still lacks one, then remap
|
|
421
|
+
* the whole doc so cross-draft `nestKey` links resolve before rendering.
|
|
422
|
+
* Pure — no I/O, no clock.
|
|
423
|
+
*/
|
|
424
|
+
export function planStudioApply(
|
|
425
|
+
doc: StudioStateDoc,
|
|
426
|
+
diskReqIds: Iterable<string>,
|
|
427
|
+
): StudioApplyPlan {
|
|
428
|
+
const used: string[] = [];
|
|
429
|
+
const seen = new Set<string>();
|
|
430
|
+
const push = (id: string): void => {
|
|
431
|
+
const trimmed = id.trim();
|
|
432
|
+
if (!REQ_ID_RE.test(trimmed) || seen.has(trimmed)) return;
|
|
433
|
+
seen.add(trimmed);
|
|
434
|
+
used.push(trimmed);
|
|
435
|
+
};
|
|
436
|
+
for (const id of diskReqIds) push(id);
|
|
437
|
+
|
|
438
|
+
const drafts = Object.entries(doc.machines);
|
|
439
|
+
for (const [, draft] of drafts) {
|
|
440
|
+
const machine = draft.current ?? draft.baseline;
|
|
441
|
+
if (draft.mode !== 'create' || machine === null) continue;
|
|
442
|
+
push(machine.reqId ?? '');
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const allocations: AllocatedReqId[] = [];
|
|
446
|
+
for (const [machineKey, draft] of drafts) {
|
|
447
|
+
const machine = draft.current ?? draft.baseline;
|
|
448
|
+
if (draft.mode !== 'create' || machine === null) continue;
|
|
449
|
+
if (REQ_ID_RE.test(machine.reqId?.trim() ?? '')) continue;
|
|
450
|
+
const reqId = allocateNextReqId(used);
|
|
451
|
+
push(reqId);
|
|
452
|
+
allocations.push({ machineKey, reqId });
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const keyMap: Record<string, string> = {};
|
|
456
|
+
for (const [key] of drafts) keyMap[key] = key;
|
|
457
|
+
for (const allocation of allocations) {
|
|
458
|
+
const draft = doc.machines[allocation.machineKey];
|
|
459
|
+
const machine = draft?.current ?? draft?.baseline ?? null;
|
|
460
|
+
if (machine === null) continue;
|
|
461
|
+
keyMap[allocation.machineKey] = makeMachineKey(
|
|
462
|
+
machine.capability,
|
|
463
|
+
allocation.reqId,
|
|
464
|
+
machine.scenarioName,
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
return {
|
|
469
|
+
allocations,
|
|
470
|
+
usedReqIds: used,
|
|
471
|
+
keyMap,
|
|
472
|
+
doc: allocations.length === 0 ? doc : applyAllocatedReqIds(doc, allocations),
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
export function createStudioStateDoc(input: CreateStudioStateDocInput): StudioStateDoc {
|
|
477
|
+
const id = validateStateId(input.id);
|
|
478
|
+
const machines: Record<string, MachineDraft> = {};
|
|
479
|
+
const timelines: Record<string, MachineTimeline> = {};
|
|
480
|
+
const layouts: Record<string, Record<string, { x: number; y: number }>> = {};
|
|
481
|
+
|
|
482
|
+
for (const draft of input.drafts) {
|
|
483
|
+
const key = draft.current?.machineKey ?? draft.baseline?.machineKey;
|
|
484
|
+
if (!key) continue;
|
|
485
|
+
machines[key] = cloneMachineDraft(draft);
|
|
486
|
+
timelines[key] = buildInitialTimeline(draft, input.createdAt);
|
|
487
|
+
layouts[key] = {};
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
return {
|
|
491
|
+
version: 1,
|
|
492
|
+
id,
|
|
493
|
+
title: input.title.trim() || id,
|
|
494
|
+
createdAt: input.createdAt,
|
|
495
|
+
updatedAt: input.createdAt,
|
|
496
|
+
machines,
|
|
497
|
+
timelines,
|
|
498
|
+
layouts,
|
|
499
|
+
comments: [],
|
|
500
|
+
revisions: [],
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Commit a semantic machine edit onto the Git-like linear timeline.
|
|
506
|
+
* Truncates any future redo entries beyond `headIdx` and advances `headIdx` to the new commit.
|
|
507
|
+
*/
|
|
508
|
+
export function recordTimelineCommit(
|
|
509
|
+
doc: StudioStateDoc,
|
|
510
|
+
machineKey: string,
|
|
511
|
+
nextMachine: StudioMachineIR | null,
|
|
512
|
+
input: { label: string; createdAt: string; mode?: MachineDraft['mode'] },
|
|
513
|
+
): StudioStateDoc {
|
|
514
|
+
const existingDraft = doc.machines[machineKey];
|
|
515
|
+
if (!existingDraft) {
|
|
516
|
+
throw new StudioStateError(`machine not found in state doc: ${machineKey}`);
|
|
517
|
+
}
|
|
518
|
+
const nextMode = input.mode ?? existingDraft.mode;
|
|
519
|
+
const nextDraft: MachineDraft = {
|
|
520
|
+
...cloneMachineDraft(existingDraft),
|
|
521
|
+
mode: nextMode,
|
|
522
|
+
current: nextMachine ? cloneMachineIR(nextMachine) : null,
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
const existingTl =
|
|
526
|
+
doc.timelines[machineKey] ?? buildInitialTimeline(existingDraft, doc.createdAt);
|
|
527
|
+
const entries = existingTl.entries.slice(0, existingTl.headIdx + 1);
|
|
528
|
+
const seq = entries.length;
|
|
529
|
+
entries.push({
|
|
530
|
+
seq,
|
|
531
|
+
id: `#${String(seq)}`,
|
|
532
|
+
label: input.label.trim() || `edit #${String(seq)}`,
|
|
533
|
+
createdAt: input.createdAt,
|
|
534
|
+
isBase: false,
|
|
535
|
+
mode: nextMode,
|
|
536
|
+
snapshot: nextMachine ? cloneMachineIR(nextMachine) : null,
|
|
537
|
+
});
|
|
538
|
+
|
|
539
|
+
return {
|
|
540
|
+
...doc,
|
|
541
|
+
updatedAt: input.createdAt,
|
|
542
|
+
revision: (doc.revision ?? 0) + 1,
|
|
543
|
+
machines: { ...doc.machines, [machineKey]: nextDraft },
|
|
544
|
+
timelines: { ...doc.timelines, [machineKey]: { entries, headIdx: entries.length - 1 } },
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Non-destructive multi-branch Worldline commit (studio-web r146).
|
|
550
|
+
* Appends a new snapshot linked to `parentId` (defaulting to current head) without truncating
|
|
551
|
+
* sibling human or agent branches.
|
|
552
|
+
*/
|
|
553
|
+
export function recordWorldlineCommit(
|
|
554
|
+
doc: StudioStateDoc,
|
|
555
|
+
machineKey: string,
|
|
556
|
+
nextMachine: StudioMachineIR | null,
|
|
557
|
+
input: {
|
|
558
|
+
label: string;
|
|
559
|
+
createdAt: string;
|
|
560
|
+
actor?: 'human' | 'agent';
|
|
561
|
+
parentId?: string | null;
|
|
562
|
+
branchRef?: string;
|
|
563
|
+
mode?: MachineDraft['mode'];
|
|
564
|
+
annotation?: boolean;
|
|
565
|
+
},
|
|
566
|
+
): StudioStateDoc {
|
|
567
|
+
const existingDraft = doc.machines[machineKey];
|
|
568
|
+
if (!existingDraft) {
|
|
569
|
+
throw new StudioStateError(`machine not found in state doc: ${machineKey}`);
|
|
570
|
+
}
|
|
571
|
+
const nextMode = input.mode ?? existingDraft.mode;
|
|
572
|
+
const nextDraft: MachineDraft = {
|
|
573
|
+
...cloneMachineDraft(existingDraft),
|
|
574
|
+
mode: nextMode,
|
|
575
|
+
current: nextMachine ? cloneMachineIR(nextMachine) : null,
|
|
576
|
+
};
|
|
577
|
+
const existingTl =
|
|
578
|
+
doc.timelines[machineKey] ?? buildInitialTimeline(existingDraft, doc.createdAt);
|
|
579
|
+
const currentHead = existingTl.entries[existingTl.headIdx];
|
|
580
|
+
const parentId = input.parentId !== undefined ? input.parentId : (currentHead?.id ?? 'BASE');
|
|
581
|
+
const seq = existingTl.entries.length;
|
|
582
|
+
const entries = [
|
|
583
|
+
...existingTl.entries,
|
|
584
|
+
{
|
|
585
|
+
seq,
|
|
586
|
+
id: `#${String(seq)}`,
|
|
587
|
+
label: input.label.trim() || `branch #${String(seq)}`,
|
|
588
|
+
createdAt: input.createdAt,
|
|
589
|
+
isBase: false,
|
|
590
|
+
mode: nextMode,
|
|
591
|
+
snapshot: nextMachine ? cloneMachineIR(nextMachine) : null,
|
|
592
|
+
parentId,
|
|
593
|
+
actor: input.actor ?? 'human',
|
|
594
|
+
...(input.branchRef !== undefined ? { branchRef: input.branchRef } : {}),
|
|
595
|
+
...(input.annotation === true ? { annotation: true } : {}),
|
|
596
|
+
},
|
|
597
|
+
];
|
|
598
|
+
return {
|
|
599
|
+
...doc,
|
|
600
|
+
updatedAt: input.createdAt,
|
|
601
|
+
revision: (doc.revision ?? 0) + 1,
|
|
602
|
+
machines: { ...doc.machines, [machineKey]: nextDraft },
|
|
603
|
+
timelines: { ...doc.timelines, [machineKey]: { entries, headIdx: entries.length - 1 } },
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** Non-destructively switch the active head pointer to any node in the Worldline tree. */
|
|
608
|
+
export function switchWorldlineHead(
|
|
609
|
+
doc: StudioStateDoc,
|
|
610
|
+
machineKey: string,
|
|
611
|
+
targetIdx: number,
|
|
612
|
+
updatedAt: string,
|
|
613
|
+
): StudioStateDoc {
|
|
614
|
+
const draft = doc.machines[machineKey];
|
|
615
|
+
const tl = doc.timelines[machineKey];
|
|
616
|
+
if (!draft || !tl) throw new StudioStateError(`timeline not found for machine: ${machineKey}`);
|
|
617
|
+
const target = tl.entries[targetIdx];
|
|
618
|
+
if (!target) throw new StudioStateError(`timeline index out of range: ${String(targetIdx)}`);
|
|
619
|
+
const nextDraft: MachineDraft = {
|
|
620
|
+
...cloneMachineDraft(draft),
|
|
621
|
+
mode: target.mode,
|
|
622
|
+
current: target.snapshot ? cloneMachineIR(target.snapshot) : null,
|
|
623
|
+
};
|
|
624
|
+
return {
|
|
625
|
+
...doc,
|
|
626
|
+
updatedAt,
|
|
627
|
+
revision: (doc.revision ?? 0) + 1,
|
|
628
|
+
machines: { ...doc.machines, [machineKey]: nextDraft },
|
|
629
|
+
timelines: { ...doc.timelines, [machineKey]: { ...tl, headIdx: targetIdx } },
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** Non-destructive read-only snapshot preview at any timeline index. */
|
|
634
|
+
export function previewTimelineEntry(
|
|
635
|
+
doc: StudioStateDoc,
|
|
636
|
+
machineKey: string,
|
|
637
|
+
index: number,
|
|
638
|
+
): MachineDraft {
|
|
639
|
+
const draft = doc.machines[machineKey];
|
|
640
|
+
const tl = doc.timelines[machineKey];
|
|
641
|
+
if (!draft || !tl) throw new StudioStateError(`timeline not found for machine: ${machineKey}`);
|
|
642
|
+
const entry = tl.entries[index];
|
|
643
|
+
if (!entry) throw new StudioStateError(`timeline index out of range: ${String(index)}`);
|
|
644
|
+
return {
|
|
645
|
+
mode: entry.mode,
|
|
646
|
+
baseline: draft.baseline ? cloneMachineIR(draft.baseline) : null,
|
|
647
|
+
current: entry.snapshot ? cloneMachineIR(entry.snapshot) : null,
|
|
648
|
+
sourceFile: draft.sourceFile,
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function stepTimeline(
|
|
653
|
+
doc: StudioStateDoc,
|
|
654
|
+
machineKey: string,
|
|
655
|
+
delta: -1 | 1,
|
|
656
|
+
updatedAt: string,
|
|
657
|
+
): StudioStateDoc {
|
|
658
|
+
const draft = doc.machines[machineKey];
|
|
659
|
+
const tl = doc.timelines[machineKey];
|
|
660
|
+
if (!draft || !tl) throw new StudioStateError(`timeline not found for machine: ${machineKey}`);
|
|
661
|
+
const nextIdx = tl.headIdx + delta;
|
|
662
|
+
const target = tl.entries[nextIdx];
|
|
663
|
+
if (!target) return doc;
|
|
664
|
+
const nextDraft: MachineDraft = {
|
|
665
|
+
...cloneMachineDraft(draft),
|
|
666
|
+
mode: target.mode,
|
|
667
|
+
current: target.snapshot ? cloneMachineIR(target.snapshot) : null,
|
|
668
|
+
};
|
|
669
|
+
return {
|
|
670
|
+
...doc,
|
|
671
|
+
updatedAt,
|
|
672
|
+
machines: { ...doc.machines, [machineKey]: nextDraft },
|
|
673
|
+
timelines: { ...doc.timelines, [machineKey]: { ...tl, headIdx: nextIdx } },
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
export function undoTimeline(
|
|
678
|
+
doc: StudioStateDoc,
|
|
679
|
+
machineKey: string,
|
|
680
|
+
updatedAt: string,
|
|
681
|
+
): StudioStateDoc {
|
|
682
|
+
return stepTimeline(doc, machineKey, -1, updatedAt);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
export function redoTimeline(
|
|
686
|
+
doc: StudioStateDoc,
|
|
687
|
+
machineKey: string,
|
|
688
|
+
updatedAt: string,
|
|
689
|
+
): StudioStateDoc {
|
|
690
|
+
return stepTimeline(doc, machineKey, 1, updatedAt);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* Roll back a machine draft to any historical checkpoint (or index 0 to restore BASE).
|
|
695
|
+
* Rolling back to index 0 resets `headIdx = 0`; rolling back to a non-base checkpoint appends a rollback commit.
|
|
696
|
+
*/
|
|
697
|
+
export function rollbackTimeline(
|
|
698
|
+
doc: StudioStateDoc,
|
|
699
|
+
machineKey: string,
|
|
700
|
+
targetIdx: number,
|
|
701
|
+
rolledBackAt: string,
|
|
702
|
+
): StudioStateDoc {
|
|
703
|
+
const draft = doc.machines[machineKey];
|
|
704
|
+
const tl = doc.timelines[machineKey];
|
|
705
|
+
if (!draft || !tl) throw new StudioStateError(`timeline not found for machine: ${machineKey}`);
|
|
706
|
+
const target = tl.entries[targetIdx];
|
|
707
|
+
if (!target) throw new StudioStateError(`timeline index out of range: ${String(targetIdx)}`);
|
|
708
|
+
|
|
709
|
+
if (targetIdx === 0) {
|
|
710
|
+
const baseDraft: MachineDraft = {
|
|
711
|
+
...cloneMachineDraft(draft),
|
|
712
|
+
mode: target.mode,
|
|
713
|
+
current: target.snapshot ? cloneMachineIR(target.snapshot) : null,
|
|
714
|
+
};
|
|
715
|
+
return {
|
|
716
|
+
...doc,
|
|
717
|
+
updatedAt: rolledBackAt,
|
|
718
|
+
machines: { ...doc.machines, [machineKey]: baseDraft },
|
|
719
|
+
timelines: { ...doc.timelines, [machineKey]: { ...tl, headIdx: 0 } },
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
return recordTimelineCommit(doc, machineKey, target.snapshot, {
|
|
724
|
+
label: `rollback to ${target.id} (${target.label})`,
|
|
725
|
+
createdAt: rolledBackAt,
|
|
726
|
+
mode: target.mode,
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
export function parseStudioStateDoc(rawJson: string): StudioStateDoc {
|
|
731
|
+
let parsed: unknown;
|
|
732
|
+
try {
|
|
733
|
+
parsed = JSON.parse(rawJson);
|
|
734
|
+
} catch (error) {
|
|
735
|
+
throw new StudioStateError(
|
|
736
|
+
`invalid studio state JSON: ${error instanceof Error ? error.message : String(error)}`,
|
|
737
|
+
);
|
|
738
|
+
}
|
|
739
|
+
const checked = studioStateDocSchema.safeParse(parsed);
|
|
740
|
+
if (!checked.success) {
|
|
741
|
+
const first = checked.error.issues[0];
|
|
742
|
+
throw new StudioStateError(
|
|
743
|
+
`invalid studio state schema at ${first?.path.join('.') || '<root>'}: ${first?.message ?? 'unknown error'}`,
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
return checked.data as StudioStateDoc;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
export function readStudioState(io: StudioStateIo, stateId: string): StudioStateDoc {
|
|
750
|
+
const rel = studioStateRelPath(stateId);
|
|
751
|
+
if (!io.exists(rel)) {
|
|
752
|
+
throw new StudioStateError(`studio state not found: ${stateId}`);
|
|
753
|
+
}
|
|
754
|
+
return parseStudioStateDoc(io.readText(rel));
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
let writeSeq = 0;
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* Atomically persist a StudioStateDoc via sibling `.tmp.<pid>.<seq>` + `rename`.
|
|
761
|
+
* Lazily creates `.llman-sdd/studio/states/` only on write.
|
|
762
|
+
*/
|
|
763
|
+
export function writeStudioState(io: StudioStateIo, doc: StudioStateDoc): string {
|
|
764
|
+
const checked = studioStateDocSchema.safeParse(doc);
|
|
765
|
+
if (!checked.success) {
|
|
766
|
+
const first = checked.error.issues[0];
|
|
767
|
+
throw new StudioStateError(
|
|
768
|
+
`refusing to write invalid studio state at ${first?.path.join('.') || '<root>'}: ${first?.message ?? 'unknown error'}`,
|
|
769
|
+
);
|
|
770
|
+
}
|
|
771
|
+
const targetRel = studioStateRelPath(doc.id);
|
|
772
|
+
io.mkdirp(STUDIO_STATES_REL);
|
|
773
|
+
writeSeq += 1;
|
|
774
|
+
const tmpRel = `${STUDIO_STATES_REL}/.${doc.id}.tmp.${String(io.currentPid())}.${String(writeSeq)}`;
|
|
775
|
+
io.writeText(tmpRel, `${JSON.stringify(doc, null, 2)}\n`);
|
|
776
|
+
io.rename(tmpRel, targetRel);
|
|
777
|
+
return targetRel;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
export interface StudioStateSummary {
|
|
781
|
+
id: string;
|
|
782
|
+
title: string;
|
|
783
|
+
machineCount: number;
|
|
784
|
+
updatedAt: string;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
export function listStudioStates(io: StudioStateIo): StudioStateSummary[] {
|
|
788
|
+
if (!io.exists(STUDIO_STATES_REL)) return [];
|
|
789
|
+
const names = io.listDir(STUDIO_STATES_REL);
|
|
790
|
+
const summaries: StudioStateSummary[] = [];
|
|
791
|
+
for (const name of names.toSorted()) {
|
|
792
|
+
if (!name.endsWith('.json') || name.startsWith('.')) continue;
|
|
793
|
+
const id = name.slice(0, -'.json'.length);
|
|
794
|
+
if (!STATE_ID_RE.test(id)) continue;
|
|
795
|
+
const doc = readStudioState(io, id);
|
|
796
|
+
summaries.push({
|
|
797
|
+
id: doc.id,
|
|
798
|
+
title: doc.title,
|
|
799
|
+
machineCount: Object.keys(doc.machines).length,
|
|
800
|
+
updatedAt: doc.updatedAt,
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
return summaries;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
export function deleteStudioState(io: StudioStateIo, stateId: string): boolean {
|
|
807
|
+
const rel = studioStateRelPath(stateId);
|
|
808
|
+
if (!io.exists(rel)) return false;
|
|
809
|
+
io.remove(rel);
|
|
810
|
+
return true;
|
|
811
|
+
}
|