@lumesync/studio 0.0.0-stage → 1.0.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/README.md +229 -2
- package/bin/lumesync-studio.js +7 -0
- package/package.json +33 -4
- package/skills/courseware-authoring/SKILL.md +226 -0
- package/skills/courseware-authoring/references/tools.md +133 -0
- package/src/chat/mailbox.js +307 -0
- package/src/cli/main.js +669 -0
- package/src/core/document.js +349 -0
- package/src/core/errors.js +44 -0
- package/src/core/exporter.js +272 -0
- package/src/core/model.js +305 -0
- package/src/core/rules.js +288 -0
- package/src/core/storage.js +616 -0
- package/src/core/transaction.js +250 -0
- package/src/core/validate.js +503 -0
- package/src/core/zip.js +251 -0
- package/src/editing/operations.js +671 -0
- package/src/editing/session.js +838 -0
- package/src/server/http.js +944 -0
- package/src/server/ws.js +128 -0
- package/src/templates/courseware.js +48 -0
- package/src/templates/init.js +374 -0
- package/src/tools/registry.js +487 -0
- package/ui/app.js +2671 -0
- package/ui/home.html +32 -0
- package/ui/home.js +148 -0
- package/ui/index.html +210 -0
- package/ui/shared/edit-model.js +105 -0
- package/ui/shared/quiz-view.js +455 -0
- package/ui/style.css +1161 -0
|
@@ -0,0 +1,838 @@
|
|
|
1
|
+
// 编辑事务:校验 baseRevision、应用 Patch、暂存、校验、目录级原子提交、广播。
|
|
2
|
+
// 单一串行队列保证同一文档不被两个提交交错;所有落盘都经过 journal 事务。
|
|
3
|
+
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import fsp from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { ERROR_CODES, StudioError } from '../core/errors.js';
|
|
8
|
+
import {
|
|
9
|
+
createSnapshot, jsonText, listPackageFiles, readOperationLog, readSnapshot,
|
|
10
|
+
resolveRealFile, sanitizeOperationsForLog, sha256Hex,
|
|
11
|
+
} from '../core/storage.js';
|
|
12
|
+
import { commitFileSet } from '../core/transaction.js';
|
|
13
|
+
import { applyAnswerMaterial } from '../core/document.js';
|
|
14
|
+
import { inspectCoursewareArchive } from '../core/exporter.js';
|
|
15
|
+
import { lintCourseware, summarize, validateManifest } from '../core/validate.js';
|
|
16
|
+
import { applyOperation, DraftWorkspace, OPERATION_TYPES } from './operations.js';
|
|
17
|
+
import { interactionIssues, normalizePolicy } from '../core/model.js';
|
|
18
|
+
|
|
19
|
+
const HISTORY_LIMIT = 30;
|
|
20
|
+
const CONFIRMATION_TTL_MS = 5 * 60 * 1000;
|
|
21
|
+
|
|
22
|
+
export class EditSession {
|
|
23
|
+
constructor({ root, document, broadcast }) {
|
|
24
|
+
this.root = path.resolve(root);
|
|
25
|
+
this.document = document;
|
|
26
|
+
this.broadcast = broadcast ?? (() => 0);
|
|
27
|
+
this.queue = Promise.resolve();
|
|
28
|
+
this.pendingChanges = new Map();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// 串行化所有写事务与读取。
|
|
32
|
+
enqueue(task) {
|
|
33
|
+
const run = this.queue.then(task, task);
|
|
34
|
+
this.queue = run.catch(() => {});
|
|
35
|
+
return run;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// 读取也必须排队:直接 reload 会与进行中的提交竞争,
|
|
39
|
+
// 可能把内存中的 revision 回退成提交前的旧值。
|
|
40
|
+
async readDocument() {
|
|
41
|
+
return this.enqueue(async () => {
|
|
42
|
+
await this.document.reload();
|
|
43
|
+
return {
|
|
44
|
+
revision: this.document.revision,
|
|
45
|
+
exists: this.document.exists,
|
|
46
|
+
report: this.document.report,
|
|
47
|
+
document: this.document.toAuthorView(),
|
|
48
|
+
history: await this.history(10),
|
|
49
|
+
};
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async readWorkspace(operations) {
|
|
54
|
+
return this.enqueue(async () => {
|
|
55
|
+
const workspace = new DraftWorkspace(this.document);
|
|
56
|
+
const changes = [];
|
|
57
|
+
for (const operation of operations) {
|
|
58
|
+
changes.push(applyOperation(workspace, operation, { root: this.root }));
|
|
59
|
+
}
|
|
60
|
+
const validation = await this.validateDraft(workspace);
|
|
61
|
+
const diff = buildDiff(this.document, workspace);
|
|
62
|
+
const impact = analyzeImpact(this.document, workspace, diff);
|
|
63
|
+
return { workspace, changes, validation, diff, impact };
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async validateDraft(workspace) {
|
|
68
|
+
const items = [...validateManifest(workspace.manifest)];
|
|
69
|
+
for (const record of workspace.interactions.values()) {
|
|
70
|
+
for (const issue of interactionIssues(record)) {
|
|
71
|
+
items.push({ code: 'P009', level: 'error', path: `interactions/${record.id}.json`, message: issue });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const sceneTexts = Object.fromEntries(Object.entries(workspace.sceneTexts).filter(([, text]) => typeof text === 'string'));
|
|
75
|
+
const script = workspace.manifest.script
|
|
76
|
+
? await this.readScriptSafe(workspace.manifest.script)
|
|
77
|
+
: null;
|
|
78
|
+
items.push(...lintCourseware(workspace.manifest, sceneTexts, script));
|
|
79
|
+
return summarize(items);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async readScriptSafe(name) {
|
|
83
|
+
try {
|
|
84
|
+
const { value } = await readJsonFile(resolveRealFile(this.root, name));
|
|
85
|
+
return value;
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// 提交一个编辑计划。成功返回 { revision, diff, validation, ... }。
|
|
92
|
+
async commit(request) {
|
|
93
|
+
return this.enqueue(async () => {
|
|
94
|
+
const operations = request?.operations;
|
|
95
|
+
if (!Array.isArray(operations) || operations.length === 0) {
|
|
96
|
+
throw new StudioError(ERROR_CODES.OPERATION_INVALID, '编辑计划必须包含至少一个操作', undefined, 400);
|
|
97
|
+
}
|
|
98
|
+
if (operations.length > 200) {
|
|
99
|
+
throw new StudioError(ERROR_CODES.PAYLOAD_TOO_LARGE, '单个事务最多 200 个操作', { count: operations.length }, 413);
|
|
100
|
+
}
|
|
101
|
+
const operationId = request.operationId;
|
|
102
|
+
if (typeof operationId !== 'string' || operationId.length < 8 || operationId.length > 80) {
|
|
103
|
+
throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'operationId 必须是 8-80 位字符串', undefined, 400);
|
|
104
|
+
}
|
|
105
|
+
const baseRevision = request.baseRevision;
|
|
106
|
+
if (!Number.isInteger(baseRevision) || baseRevision < 0) {
|
|
107
|
+
throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'baseRevision 必须是非负整数', undefined, 400);
|
|
108
|
+
}
|
|
109
|
+
if (!this.document.exists) {
|
|
110
|
+
throw new StudioError(ERROR_CODES.COURSEWARE_INVALID, '当前目录没有可编辑课件,请先初始化', undefined, 422);
|
|
111
|
+
}
|
|
112
|
+
// 幂等优先于版本检查:客户端重试同一 operationId 应拿到首次结果,
|
|
113
|
+
// 而不是因为 revision 已推进被误判为冲突。
|
|
114
|
+
if (this.document.operationIds.includes(operationId)) {
|
|
115
|
+
const previous = await this.findOperation(operationId);
|
|
116
|
+
return { ...previous, duplicated: true };
|
|
117
|
+
}
|
|
118
|
+
if (baseRevision !== this.document.revision) {
|
|
119
|
+
throw new StudioError(
|
|
120
|
+
ERROR_CODES.REVISION_CONFLICT,
|
|
121
|
+
`文档已更新到 revision ${this.document.revision},请重新读取后再提交`,
|
|
122
|
+
{ baseRevision, currentRevision: this.document.revision },
|
|
123
|
+
409,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const workspace = new DraftWorkspace(this.document);
|
|
128
|
+
const changes = [];
|
|
129
|
+
for (const operation of operations) {
|
|
130
|
+
changes.push(applyOperation(workspace, operation, { root: this.root }));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const validation = await this.validateDraft(workspace);
|
|
134
|
+
if (!validation.valid) {
|
|
135
|
+
throw new StudioError(
|
|
136
|
+
ERROR_CODES.VALIDATION_FAILED,
|
|
137
|
+
'编辑计划未通过校验,未写入任何文件',
|
|
138
|
+
{ diagnostics: validation.items, errors: validation.errors },
|
|
139
|
+
422,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const diff = buildDiff(this.document, workspace);
|
|
144
|
+
const impact = analyzeImpact(this.document, workspace, diff);
|
|
145
|
+
|
|
146
|
+
if (impact.high) {
|
|
147
|
+
const confirmation = this.verifyConfirmation(request, {
|
|
148
|
+
baseRevision,
|
|
149
|
+
diff,
|
|
150
|
+
operations,
|
|
151
|
+
});
|
|
152
|
+
if (!confirmation.ok) {
|
|
153
|
+
if (confirmation.reason === 'MISSING') {
|
|
154
|
+
const pending = this.registerPendingChange({ baseRevision, diff, operations, reasons: impact.reasons });
|
|
155
|
+
return {
|
|
156
|
+
pending: true,
|
|
157
|
+
confirmationRequired: true,
|
|
158
|
+
highImpact: true,
|
|
159
|
+
reasons: impact.reasons,
|
|
160
|
+
change: pending.change,
|
|
161
|
+
preview: { diff, validation },
|
|
162
|
+
baseRevision,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
throw new StudioError(
|
|
166
|
+
ERROR_CODES.OPERATION_CONFLICT,
|
|
167
|
+
confirmation.message,
|
|
168
|
+
{ changeId: confirmation.changeId ?? null, baseRevision, currentRevision: this.document.revision },
|
|
169
|
+
409,
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const nextRevision = this.document.revision + 1;
|
|
175
|
+
const stamp = new Date().toISOString();
|
|
176
|
+
const createdAt = this.document.createdAt ?? stamp;
|
|
177
|
+
const operationIds = [...this.document.operationIds, operationId].slice(-200);
|
|
178
|
+
|
|
179
|
+
// 快照必须成功;失败直接终止,不允许在没有回滚点的情况下写正式文件。
|
|
180
|
+
await createSnapshot(this.root, this.document.revision);
|
|
181
|
+
|
|
182
|
+
const writes = this.workspaceWrites(workspace);
|
|
183
|
+
writes.push({
|
|
184
|
+
path: '.studio/document.json',
|
|
185
|
+
content: jsonText({ revision: nextRevision, operationIds, createdAt, updatedAt: stamp }),
|
|
186
|
+
});
|
|
187
|
+
const logRecord = {
|
|
188
|
+
revision: nextRevision,
|
|
189
|
+
operationId,
|
|
190
|
+
timestamp: stamp,
|
|
191
|
+
actor: request.actor ?? 'agent',
|
|
192
|
+
summary: request.summary ?? '',
|
|
193
|
+
operations: sanitizeOperationsForLog(operations),
|
|
194
|
+
changes: sanitizeOperationsForLog(changes),
|
|
195
|
+
effect: {
|
|
196
|
+
answerChanged: changes.some((change) => change.kind === 'interaction' && change.answerChanged),
|
|
197
|
+
impact: impact.reasons,
|
|
198
|
+
},
|
|
199
|
+
changedFiles: diff.files.map((file) => ({ path: file.path, kind: file.kind })),
|
|
200
|
+
diffSummary: diff.summary,
|
|
201
|
+
validation: { errors: validation.errors, warnings: validation.warnings },
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
try {
|
|
205
|
+
await commitFileSet(this.root, {
|
|
206
|
+
writes,
|
|
207
|
+
deletes: [...new Set(workspace.filesToDelete)],
|
|
208
|
+
checksum: workspace.manifest.checksums === 'checksums.json',
|
|
209
|
+
logRecord,
|
|
210
|
+
});
|
|
211
|
+
} catch (error) {
|
|
212
|
+
await this.document.reload().catch(() => {});
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
await this.document.reload();
|
|
217
|
+
const { pruneSnapshots } = await import('../core/storage.js');
|
|
218
|
+
await pruneSnapshots(this.root, { keep: HISTORY_LIMIT });
|
|
219
|
+
|
|
220
|
+
const result = {
|
|
221
|
+
revision: nextRevision,
|
|
222
|
+
operationId,
|
|
223
|
+
committed: true,
|
|
224
|
+
validated: true,
|
|
225
|
+
broadcast: false,
|
|
226
|
+
previewClients: 0,
|
|
227
|
+
summary: request.summary ?? '',
|
|
228
|
+
diff,
|
|
229
|
+
validation: { errors: validation.errors, warnings: validation.warnings },
|
|
230
|
+
changes: changes.map(toChangeEvent),
|
|
231
|
+
impact: impact.reasons,
|
|
232
|
+
};
|
|
233
|
+
const event = this.broadcast({
|
|
234
|
+
type: 'courseware.changed',
|
|
235
|
+
coursewareId: this.document.manifest?.id ?? null,
|
|
236
|
+
previewKey: this.document.previewKey,
|
|
237
|
+
revision: nextRevision,
|
|
238
|
+
baseRevision,
|
|
239
|
+
operationId,
|
|
240
|
+
summary: request.summary ?? '',
|
|
241
|
+
changes: result.changes,
|
|
242
|
+
validation: result.validation,
|
|
243
|
+
});
|
|
244
|
+
const receivers = typeof event === 'number' ? event : Number(event?.receivers ?? 0);
|
|
245
|
+
result.previewClients = Number.isFinite(receivers) ? receivers : 0;
|
|
246
|
+
result.broadcast = result.previewClients > 0;
|
|
247
|
+
return result;
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// 把 .lume 内容作为一次普通事务提交:替换课件文件但保留 .studio 历史、
|
|
252
|
+
// session.json 与内存中的服务凭证,因此导入后可以继续编辑或撤销。
|
|
253
|
+
async importCourseware(buffer, { actor = 'user', summary = '导入课件包' } = {}) {
|
|
254
|
+
return this.enqueue(async () => {
|
|
255
|
+
const archive = await inspectCoursewareArchive(buffer);
|
|
256
|
+
const baseRevision = this.document.revision;
|
|
257
|
+
const nextRevision = baseRevision + 1;
|
|
258
|
+
const stamp = new Date().toISOString();
|
|
259
|
+
const createdAt = this.document.createdAt ?? stamp;
|
|
260
|
+
|
|
261
|
+
// 导入前先留一份快照,让「历史」里可以撤回到导入前的状态。
|
|
262
|
+
if (this.document.exists) await createSnapshot(this.root, baseRevision);
|
|
263
|
+
|
|
264
|
+
const current = listPackageFiles(this.root, { includeChecksums: true });
|
|
265
|
+
const writes = [...archive.files.entries()].map(([relative, content]) => ({ path: relative, content }));
|
|
266
|
+
const deletes = current.filter((relative) => !archive.files.has(relative));
|
|
267
|
+
writes.push({
|
|
268
|
+
path: '.studio/document.json',
|
|
269
|
+
content: jsonText({
|
|
270
|
+
revision: nextRevision,
|
|
271
|
+
operationIds: this.document.operationIds,
|
|
272
|
+
createdAt,
|
|
273
|
+
updatedAt: stamp,
|
|
274
|
+
}),
|
|
275
|
+
});
|
|
276
|
+
const changes = [{ kind: 'import', parts: ['manifest', 'scenes', 'assets'] }];
|
|
277
|
+
const logRecord = {
|
|
278
|
+
revision: nextRevision,
|
|
279
|
+
operationId: `import-${Date.now()}-${randomBytes(4).toString('hex')}`,
|
|
280
|
+
timestamp: stamp,
|
|
281
|
+
actor,
|
|
282
|
+
summary,
|
|
283
|
+
operations: [{ op: 'courseware.import', coursewareId: archive.coursewareId }],
|
|
284
|
+
changes,
|
|
285
|
+
effect: { impact: [{ code: 'IMPORT_REPLACED', message: '整份课件被导入包替换' }] },
|
|
286
|
+
changedFiles: [...archive.files.keys()].map((relative) => ({ path: relative, kind: 'imported' })),
|
|
287
|
+
diffSummary: `导入 ${archive.title ?? archive.coursewareId}`,
|
|
288
|
+
validation: archive.validation,
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
await commitFileSet(this.root, {
|
|
292
|
+
writes,
|
|
293
|
+
deletes,
|
|
294
|
+
checksum: archive.manifest?.checksums === 'checksums.json',
|
|
295
|
+
logRecord,
|
|
296
|
+
});
|
|
297
|
+
await this.document.reload();
|
|
298
|
+
const validation = this.document.report;
|
|
299
|
+
const result = {
|
|
300
|
+
revision: nextRevision,
|
|
301
|
+
committed: true,
|
|
302
|
+
validated: validation.valid,
|
|
303
|
+
coursewareId: archive.coursewareId,
|
|
304
|
+
title: archive.title,
|
|
305
|
+
scenes: archive.scenes,
|
|
306
|
+
files: archive.files.size,
|
|
307
|
+
removed: deletes.length,
|
|
308
|
+
previewClients: 0,
|
|
309
|
+
broadcast: false,
|
|
310
|
+
changes,
|
|
311
|
+
validation: { errors: validation.errors, warnings: validation.warnings },
|
|
312
|
+
};
|
|
313
|
+
const event = this.broadcast({
|
|
314
|
+
type: 'courseware.changed',
|
|
315
|
+
coursewareId: this.document.manifest?.id ?? null,
|
|
316
|
+
previewKey: this.document.previewKey,
|
|
317
|
+
revision: nextRevision,
|
|
318
|
+
baseRevision,
|
|
319
|
+
summary,
|
|
320
|
+
changes,
|
|
321
|
+
validation: result.validation,
|
|
322
|
+
});
|
|
323
|
+
const receivers = typeof event === 'number' ? event : Number(event?.receivers ?? 0);
|
|
324
|
+
result.previewClients = Number.isFinite(receivers) ? receivers : 0;
|
|
325
|
+
result.broadcast = result.previewClients > 0;
|
|
326
|
+
return result;
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// 只生成预览,不落盘:用于高影响操作的确认与 Diff 展示。
|
|
331
|
+
async preview(operations) {
|
|
332
|
+
const { workspace, changes, validation, diff, impact } = await this.readWorkspace(operations);
|
|
333
|
+
return { diff, validation, changes, impact, workspace: undefined };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
workspaceWrites(workspace) {
|
|
337
|
+
const writes = [{ path: 'manifest.json', content: jsonText(workspace.manifest) }];
|
|
338
|
+
for (const [file, text] of Object.entries(workspace.sceneTexts)) {
|
|
339
|
+
if (typeof text !== 'string') continue;
|
|
340
|
+
writes.push({ path: file, content: text });
|
|
341
|
+
}
|
|
342
|
+
for (const [id, body] of workspace.interactions.entries()) {
|
|
343
|
+
const entry = (workspace.manifest.interactions ?? []).find((item) => item.id === id);
|
|
344
|
+
if (!entry) continue;
|
|
345
|
+
writes.push({ path: entry.file, content: jsonText(body) });
|
|
346
|
+
}
|
|
347
|
+
for (const [file, asset] of workspace.assets.entries()) {
|
|
348
|
+
const content = asset.encoding === 'base64' ? Buffer.from(asset.content, 'base64') : asset.content;
|
|
349
|
+
writes.push({ path: file, content });
|
|
350
|
+
}
|
|
351
|
+
return writes;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async findOperation(operationId) {
|
|
355
|
+
const log = await readOperationLog(this.root, 500);
|
|
356
|
+
const found = log.find((entry) => entry?.operationId === operationId);
|
|
357
|
+
if (!found) {
|
|
358
|
+
return {
|
|
359
|
+
revision: this.document.revision,
|
|
360
|
+
operationId,
|
|
361
|
+
committed: true,
|
|
362
|
+
validated: true,
|
|
363
|
+
broadcast: false,
|
|
364
|
+
replayed: true,
|
|
365
|
+
diff: { files: [], summary: '重复提交,返回当前修订', changedFiles: 0 },
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
return {
|
|
369
|
+
revision: found.revision,
|
|
370
|
+
operationId,
|
|
371
|
+
committed: true,
|
|
372
|
+
validated: true,
|
|
373
|
+
broadcast: false,
|
|
374
|
+
replayed: true,
|
|
375
|
+
summary: found.summary ?? '',
|
|
376
|
+
changes: found.changes ?? [],
|
|
377
|
+
diff: { files: [], summary: '重复提交,返回首次执行结果', changedFiles: 0 },
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
registerPendingChange({ baseRevision, diff, operations, reasons }) {
|
|
382
|
+
for (const [id, pending] of this.pendingChanges) {
|
|
383
|
+
if (Date.now() > pending.expiresAt + 60000) this.pendingChanges.delete(id);
|
|
384
|
+
}
|
|
385
|
+
const changeId = `chg_${randomBytes(12).toString('base64url')}`;
|
|
386
|
+
const record = {
|
|
387
|
+
changeId,
|
|
388
|
+
baseRevision,
|
|
389
|
+
diffDigest: diffDigest(diff),
|
|
390
|
+
operationsDigest: sha256Hex(JSON.stringify(operations)),
|
|
391
|
+
reasons,
|
|
392
|
+
expiresAt: Date.now() + CONFIRMATION_TTL_MS,
|
|
393
|
+
used: false,
|
|
394
|
+
};
|
|
395
|
+
this.pendingChanges.set(changeId, record);
|
|
396
|
+
return {
|
|
397
|
+
change: {
|
|
398
|
+
changeId,
|
|
399
|
+
baseRevision,
|
|
400
|
+
diffDigest: record.diffDigest,
|
|
401
|
+
expiresAt: new Date(record.expiresAt).toISOString(),
|
|
402
|
+
},
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
verifyConfirmation(request, { baseRevision, diff, operations }) {
|
|
407
|
+
const supplied = request.confirmation ?? (typeof request.confirm === 'object' ? request.confirm : null);
|
|
408
|
+
if (!supplied) return { ok: false, reason: 'MISSING' };
|
|
409
|
+
const changeId = supplied.changeId;
|
|
410
|
+
const record = this.pendingChanges.get(changeId);
|
|
411
|
+
if (!record) return { ok: false, reason: 'INVALID', changeId, message: '确认已失效,请重新预览 Diff 后确认' };
|
|
412
|
+
if (record.used) return { ok: false, reason: 'USED', changeId, message: '该确认已提交过一次,请重新预览' };
|
|
413
|
+
if (Date.now() > record.expiresAt) return { ok: false, reason: 'EXPIRED', changeId, message: '确认已过期,请重新预览 Diff' };
|
|
414
|
+
if (record.baseRevision !== baseRevision) {
|
|
415
|
+
return { ok: false, reason: 'BASE_REVISION', changeId, message: '确认对应的 baseRevision 已过期' };
|
|
416
|
+
}
|
|
417
|
+
if (supplied.diffDigest !== record.diffDigest || record.diffDigest !== diffDigest(diff)) {
|
|
418
|
+
return { ok: false, reason: 'DIGEST', changeId, message: 'Diff 摘要不匹配,课件可能已被修改,请重新预览' };
|
|
419
|
+
}
|
|
420
|
+
if (record.operationsDigest !== sha256Hex(JSON.stringify(operations))) {
|
|
421
|
+
return { ok: false, reason: 'OPERATIONS', changeId, message: '确认对应的操作集合不一致,请重新预览' };
|
|
422
|
+
}
|
|
423
|
+
record.used = true;
|
|
424
|
+
return { ok: true };
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// 撤销:把快照恢复成一次普通事务(Diff、确认、日志与新 revision)。
|
|
428
|
+
async undo(targetRevision, { confirm = false, baseRevision } = {}) {
|
|
429
|
+
return this.enqueue(async () => {
|
|
430
|
+
const revision = targetRevision ?? this.document.revision - 1;
|
|
431
|
+
if (!Number.isInteger(revision) || revision < 0) {
|
|
432
|
+
throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'revision 必须是非负整数', undefined, 400);
|
|
433
|
+
}
|
|
434
|
+
if (revision >= this.document.revision) {
|
|
435
|
+
throw new StudioError(ERROR_CODES.OPERATION_INVALID, '撤销目标必须早于当前修订', { revision, currentRevision: this.document.revision }, 400);
|
|
436
|
+
}
|
|
437
|
+
if (baseRevision !== undefined && baseRevision !== this.document.revision) {
|
|
438
|
+
throw new StudioError(
|
|
439
|
+
ERROR_CODES.REVISION_CONFLICT,
|
|
440
|
+
`文档已更新到 revision ${this.document.revision},请重新读取后再撤销`,
|
|
441
|
+
{ baseRevision, currentRevision: this.document.revision },
|
|
442
|
+
409,
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
const snapshot = await readSnapshot(this.root, revision);
|
|
446
|
+
const currentFiles = new Map();
|
|
447
|
+
for (const relative of listPackageFiles(this.root, { includeChecksums: true })) {
|
|
448
|
+
currentFiles.set(relative, await fsp.readFile(resolveRealFile(this.root, relative)));
|
|
449
|
+
}
|
|
450
|
+
const diff = buildFileMapDiff(currentFiles, snapshot.files, {
|
|
451
|
+
fromRevision: this.document.revision,
|
|
452
|
+
toRevision: revision,
|
|
453
|
+
});
|
|
454
|
+
const reasons = [{ code: 'HISTORY_RESTORE', message: `恢复到 revision ${revision}` }];
|
|
455
|
+
if (revision < this.document.revision - 1) {
|
|
456
|
+
reasons.push({ code: 'REVERTS_MULTIPLE_REVISIONS', message: `将回退 revision ${revision + 1}-${this.document.revision} 的修改` });
|
|
457
|
+
}
|
|
458
|
+
if (!confirm) {
|
|
459
|
+
return {
|
|
460
|
+
pending: true,
|
|
461
|
+
confirmationRequired: true,
|
|
462
|
+
highImpact: true,
|
|
463
|
+
reasons,
|
|
464
|
+
conflict: revision < this.document.revision - 1
|
|
465
|
+
? { code: 'REVERTS_MULTIPLE_REVISIONS', fromRevision: revision + 1, toRevision: this.document.revision }
|
|
466
|
+
: null,
|
|
467
|
+
restoredFrom: revision,
|
|
468
|
+
preview: { diff },
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const nextRevision = this.document.revision + 1;
|
|
473
|
+
const stamp = new Date().toISOString();
|
|
474
|
+
const createdAt = this.document.createdAt ?? stamp;
|
|
475
|
+
const operationId = `undo-${Date.now()}-${randomBytes(4).toString('hex')}`;
|
|
476
|
+
await createSnapshot(this.root, this.document.revision);
|
|
477
|
+
const writes = [...snapshot.files.entries()].map(([relative, content]) => ({ path: relative, content }));
|
|
478
|
+
writes.push({
|
|
479
|
+
path: '.studio/document.json',
|
|
480
|
+
content: jsonText({ revision: nextRevision, operationIds: this.document.operationIds, createdAt, updatedAt: stamp }),
|
|
481
|
+
});
|
|
482
|
+
const deletes = [...currentFiles.keys()].filter((relative) => !snapshot.files.has(relative));
|
|
483
|
+
const logRecord = {
|
|
484
|
+
revision: nextRevision,
|
|
485
|
+
operationId,
|
|
486
|
+
timestamp: stamp,
|
|
487
|
+
actor: 'user',
|
|
488
|
+
summary: `撤销到 revision ${revision}`,
|
|
489
|
+
operations: [{ op: 'history.restore', revision }],
|
|
490
|
+
changes: [{ kind: 'history', parts: ['restored'], revision }],
|
|
491
|
+
effect: { impact: reasons },
|
|
492
|
+
changedFiles: diff.files.map((file) => ({ path: file.path, kind: file.kind })),
|
|
493
|
+
diffSummary: diff.summary,
|
|
494
|
+
validation: { errors: 0, warnings: 0 },
|
|
495
|
+
};
|
|
496
|
+
await commitFileSet(this.root, {
|
|
497
|
+
writes,
|
|
498
|
+
deletes,
|
|
499
|
+
checksum: Boolean(snapshot.files.has('checksums.json')),
|
|
500
|
+
logRecord,
|
|
501
|
+
});
|
|
502
|
+
await this.document.reload();
|
|
503
|
+
const validation = this.document.report;
|
|
504
|
+
logRecord.validation = { errors: validation.errors, warnings: validation.warnings };
|
|
505
|
+
const result = {
|
|
506
|
+
revision: nextRevision,
|
|
507
|
+
restoredFrom: revision,
|
|
508
|
+
committed: true,
|
|
509
|
+
validated: true,
|
|
510
|
+
broadcast: false,
|
|
511
|
+
previewClients: 0,
|
|
512
|
+
diff,
|
|
513
|
+
};
|
|
514
|
+
const event = this.broadcast({
|
|
515
|
+
type: 'courseware.changed',
|
|
516
|
+
coursewareId: this.document.manifest?.id ?? null,
|
|
517
|
+
previewKey: this.document.previewKey,
|
|
518
|
+
revision: nextRevision,
|
|
519
|
+
baseRevision: nextRevision - 1,
|
|
520
|
+
summary: `撤销到 revision ${revision}`,
|
|
521
|
+
changes: [{ kind: 'history', parts: ['restored'] }],
|
|
522
|
+
validation: { errors: validation.errors, warnings: validation.warnings },
|
|
523
|
+
});
|
|
524
|
+
const receivers = typeof event === 'number' ? event : Number(event?.receivers ?? 0);
|
|
525
|
+
result.previewClients = Number.isFinite(receivers) ? receivers : 0;
|
|
526
|
+
result.broadcast = result.previewClients > 0;
|
|
527
|
+
return result;
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async history(limit = 20) {
|
|
532
|
+
const records = await readOperationLog(this.root, limit);
|
|
533
|
+
return records.map((record) => ({
|
|
534
|
+
revision: record.revision,
|
|
535
|
+
operationId: record.operationId,
|
|
536
|
+
timestamp: record.timestamp,
|
|
537
|
+
actor: record.actor,
|
|
538
|
+
summary: record.summary,
|
|
539
|
+
validation: record.validation,
|
|
540
|
+
impact: record.effect?.impact ?? [],
|
|
541
|
+
changedFiles: record.changedFiles ?? [],
|
|
542
|
+
diffSummary: record.diffSummary ?? '',
|
|
543
|
+
operations: record.operations ?? [],
|
|
544
|
+
}));
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// revision-to-revision Diff:目标为当前修订时直接读磁盘,其余读快照。
|
|
548
|
+
async diffRevisions(fromRevision, toRevision) {
|
|
549
|
+
return this.enqueue(async () => {
|
|
550
|
+
const target = toRevision ?? this.document.revision;
|
|
551
|
+
if (!Number.isInteger(target) || target < 0 || target > this.document.revision) {
|
|
552
|
+
throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'toRevision 超出可用范围', { toRevision: target, currentRevision: this.document.revision }, 400);
|
|
553
|
+
}
|
|
554
|
+
const from = fromRevision ?? Math.max(0, target - 1);
|
|
555
|
+
if (!Number.isInteger(from) || from < 0 || from > target) {
|
|
556
|
+
throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'fromRevision 超出可用范围', { fromRevision: from }, 400);
|
|
557
|
+
}
|
|
558
|
+
if (from === target) {
|
|
559
|
+
return { fromRevision: from, toRevision: target, files: [], summary: '', changedFiles: 0 };
|
|
560
|
+
}
|
|
561
|
+
const fromFiles = (await readSnapshot(this.root, from)).files;
|
|
562
|
+
let toFiles;
|
|
563
|
+
if (target === this.document.revision) {
|
|
564
|
+
toFiles = new Map();
|
|
565
|
+
for (const relative of listPackageFiles(this.root, { includeChecksums: true })) {
|
|
566
|
+
toFiles.set(relative, await fsp.readFile(resolveRealFile(this.root, relative)));
|
|
567
|
+
}
|
|
568
|
+
} else {
|
|
569
|
+
toFiles = (await readSnapshot(this.root, target)).files;
|
|
570
|
+
}
|
|
571
|
+
return buildFileMapDiff(fromFiles, toFiles, { fromRevision: from, toRevision: target });
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
async function readJsonFile(absolutePath) {
|
|
577
|
+
const text = await fsp.readFile(absolutePath, 'utf8');
|
|
578
|
+
return { text, value: JSON.parse(text) };
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function toChangeEvent(change) {
|
|
582
|
+
return {
|
|
583
|
+
kind: change.kind,
|
|
584
|
+
parts: change.parts,
|
|
585
|
+
...(change.sceneId ? { sceneId: change.sceneId } : {}),
|
|
586
|
+
...(change.interactionId ? { interactionId: change.interactionId } : {}),
|
|
587
|
+
...(change.cid ? { cid: change.cid } : {}),
|
|
588
|
+
...(change.path ? { path: change.path } : {}),
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function diffDigest(diff) {
|
|
593
|
+
return sha256Hex(JSON.stringify({
|
|
594
|
+
files: diff.files.map((file) => ({
|
|
595
|
+
path: file.path,
|
|
596
|
+
kind: file.kind,
|
|
597
|
+
before: file.before,
|
|
598
|
+
after: file.after,
|
|
599
|
+
answerChanged: file.answerChanged ?? false,
|
|
600
|
+
})),
|
|
601
|
+
}));
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// 受保护 Diff 视图:答案与参考材料只保留是否变化及配置状态。
|
|
605
|
+
function protectedInteractionView(body) {
|
|
606
|
+
if (!body || typeof body !== 'object') return body;
|
|
607
|
+
const copy = structuredClone(body);
|
|
608
|
+
copy.policy = normalizePolicy(copy.policy ?? {});
|
|
609
|
+
if (Array.isArray(copy.answerKeys)) {
|
|
610
|
+
copy.answerKeysCount = copy.answerKeys.length;
|
|
611
|
+
delete copy.answerKeys;
|
|
612
|
+
}
|
|
613
|
+
delete copy.answerHash;
|
|
614
|
+
delete copy.answerSalt;
|
|
615
|
+
if (copy.explain !== undefined) {
|
|
616
|
+
copy.explainConfigured = Boolean(copy.explain);
|
|
617
|
+
delete copy.explain;
|
|
618
|
+
}
|
|
619
|
+
if (copy.grading && typeof copy.grading === 'object') {
|
|
620
|
+
if (copy.grading.referenceAnswer !== undefined) {
|
|
621
|
+
copy.grading.referenceConfigured = Boolean(copy.grading.referenceAnswer);
|
|
622
|
+
delete copy.grading.referenceAnswer;
|
|
623
|
+
}
|
|
624
|
+
if (Array.isArray(copy.grading.rubric)) {
|
|
625
|
+
copy.grading.rubricCount = copy.grading.rubric.length;
|
|
626
|
+
delete copy.grading.rubric;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
if (body.answerHash !== undefined) copy.answerConfigured = true;
|
|
630
|
+
return copy;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// 生成可审阅的文件级 Diff。答案材料经过脱敏;大文件标记截断而不是静默丢弃。
|
|
634
|
+
export function buildDiff(document, workspace) {
|
|
635
|
+
const files = [];
|
|
636
|
+
const beforeManifest = document.manifest ? stableJson(document.manifest) : null;
|
|
637
|
+
const afterManifest = stableJson(workspace.manifest);
|
|
638
|
+
if (beforeManifest !== afterManifest) {
|
|
639
|
+
files.push(textEntry('manifest.json', beforeManifest, afterManifest, beforeManifest === null ? 'added' : 'modified'));
|
|
640
|
+
}
|
|
641
|
+
for (const [file, text] of Object.entries(workspace.sceneTexts)) {
|
|
642
|
+
const before = document.sceneTexts[file];
|
|
643
|
+
if (before === undefined) {
|
|
644
|
+
files.push(textEntry(file, null, text, 'added'));
|
|
645
|
+
} else if (before !== text) {
|
|
646
|
+
files.push(textEntry(file, before, text, 'modified'));
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
const removedSceneFiles = new Set(workspace.filesToDelete.filter((file) => file.startsWith('scenes/')));
|
|
650
|
+
for (const file of removedSceneFiles) {
|
|
651
|
+
if (document.sceneTexts[file] !== undefined) files.push(textEntry(file, document.sceneTexts[file], null, 'deleted'));
|
|
652
|
+
}
|
|
653
|
+
for (const [id, body] of workspace.interactions.entries()) {
|
|
654
|
+
const record = document.interactions.find((item) => item.entry.id === id);
|
|
655
|
+
const before = record?.body ? stableJson(protectedInteractionView(record.body)) : null;
|
|
656
|
+
const after = stableJson(protectedInteractionView(body));
|
|
657
|
+
const answerChanged = record?.body
|
|
658
|
+
? (record.body.answerHash ?? null) !== (body.answerHash ?? null)
|
|
659
|
+
: body.answerHash !== undefined;
|
|
660
|
+
if (before !== after || answerChanged) {
|
|
661
|
+
files.push({
|
|
662
|
+
...textEntry(record?.entry.file ?? `interactions/${id}.json`, before, after, before === null ? 'added' : 'modified'),
|
|
663
|
+
answerChanged,
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
const removed = document.interactions.filter((record) => !workspace.interactions.has(record.entry.id));
|
|
668
|
+
for (const record of removed) {
|
|
669
|
+
files.push(textEntry(record.entry.file, stableJson(protectedInteractionView(record.body)), null, 'deleted'));
|
|
670
|
+
}
|
|
671
|
+
// 资源:正文不进 Diff,只记录是否存在、大小和摘要。
|
|
672
|
+
for (const [file, asset] of workspace.assets.entries()) {
|
|
673
|
+
const beforeRecord = (document.manifest?.assets ?? []).find((item) => item.path === file);
|
|
674
|
+
const content = asset.encoding === 'base64' ? Buffer.from(asset.content, 'base64') : Buffer.from(asset.content, 'utf8');
|
|
675
|
+
files.push({
|
|
676
|
+
path: file,
|
|
677
|
+
kind: beforeRecord ? 'modified' : 'added',
|
|
678
|
+
binary: true,
|
|
679
|
+
before: beforeRecord ? { bytes: beforeRecord.bytes ?? null, sha256: beforeRecord.sha256 ?? null } : null,
|
|
680
|
+
after: { bytes: content.length, sha256: sha256Hex(content) },
|
|
681
|
+
summary: beforeRecord ? '资源更新' : '资源新增',
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
for (const file of workspace.filesToDelete) {
|
|
685
|
+
if (!file.startsWith('assets/')) continue;
|
|
686
|
+
const beforeRecord = (document.manifest?.assets ?? []).find((item) => item.path === file);
|
|
687
|
+
files.push({
|
|
688
|
+
path: file,
|
|
689
|
+
kind: 'deleted',
|
|
690
|
+
binary: true,
|
|
691
|
+
before: beforeRecord ?? null,
|
|
692
|
+
after: null,
|
|
693
|
+
summary: '资源删除',
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
return {
|
|
697
|
+
files,
|
|
698
|
+
summary: files.map((file) => `${file.kind} ${file.path}`).join('; '),
|
|
699
|
+
changedFiles: files.length,
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
function textEntry(pathName, before, after, kind) {
|
|
704
|
+
const beforeText = before === null || before === undefined ? null : String(before);
|
|
705
|
+
const afterText = after === null || after === undefined ? null : String(after);
|
|
706
|
+
const entry = {
|
|
707
|
+
path: pathName,
|
|
708
|
+
kind,
|
|
709
|
+
binary: false,
|
|
710
|
+
before: truncate(beforeText),
|
|
711
|
+
after: truncate(afterText),
|
|
712
|
+
};
|
|
713
|
+
if (beforeText && beforeText.length > 4000) entry.beforeTruncated = true;
|
|
714
|
+
if (afterText && afterText.length > 4000) entry.afterTruncated = true;
|
|
715
|
+
entry.beforeBytes = beforeText === null ? 0 : Buffer.byteLength(beforeText);
|
|
716
|
+
entry.afterBytes = afterText === null ? 0 : Buffer.byteLength(afterText);
|
|
717
|
+
return entry;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function truncate(text) {
|
|
721
|
+
if (text === null || text === undefined) return text;
|
|
722
|
+
return text.length > 4000 ? `${text.slice(0, 4000)}\n…(截断)` : text;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
export function buildFileMapDiff(fromFiles, toFiles, { fromRevision, toRevision }) {
|
|
726
|
+
const files = [];
|
|
727
|
+
const paths = new Set([...fromFiles.keys(), ...toFiles.keys()]);
|
|
728
|
+
for (const relative of [...paths].sort()) {
|
|
729
|
+
if (relative === 'checksums.json' || relative.startsWith('.')) continue;
|
|
730
|
+
const before = fromFiles.get(relative);
|
|
731
|
+
const after = toFiles.get(relative);
|
|
732
|
+
if (before === undefined && after === undefined) continue;
|
|
733
|
+
if (before !== undefined && after !== undefined && Buffer.compare(before, after) === 0) continue;
|
|
734
|
+
const kind = before === undefined ? 'added' : after === undefined ? 'deleted' : 'modified';
|
|
735
|
+
if (isTextFile(relative)) {
|
|
736
|
+
const beforeText = before === undefined ? null : before.toString('utf8');
|
|
737
|
+
const afterText = after === undefined ? null : after.toString('utf8');
|
|
738
|
+
if (relative.startsWith('interactions/') && relative.endsWith('.json')) {
|
|
739
|
+
files.push({
|
|
740
|
+
...textEntry(relative, stableJson(protectedInteractionView(parseJson(beforeText))), stableJson(protectedInteractionView(parseJson(afterText))), kind),
|
|
741
|
+
answerChanged: answerDigestOf(parseJson(beforeText)) !== answerDigestOf(parseJson(afterText)),
|
|
742
|
+
});
|
|
743
|
+
} else {
|
|
744
|
+
files.push(textEntry(relative, beforeText, afterText, kind));
|
|
745
|
+
}
|
|
746
|
+
} else {
|
|
747
|
+
files.push({
|
|
748
|
+
path: relative,
|
|
749
|
+
kind,
|
|
750
|
+
binary: true,
|
|
751
|
+
before: before === undefined ? null : { bytes: before.length, sha256: sha256Hex(before) },
|
|
752
|
+
after: after === undefined ? null : { bytes: after.length, sha256: sha256Hex(after) },
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
return {
|
|
757
|
+
fromRevision,
|
|
758
|
+
toRevision,
|
|
759
|
+
files,
|
|
760
|
+
summary: files.map((file) => `${file.kind} ${file.path}`).join('; '),
|
|
761
|
+
changedFiles: files.length,
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
function parseJson(text) {
|
|
766
|
+
if (text === null || text === undefined) return null;
|
|
767
|
+
try {
|
|
768
|
+
return JSON.parse(text);
|
|
769
|
+
} catch {
|
|
770
|
+
return null;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function answerDigestOf(body) {
|
|
775
|
+
if (!body?.answerHash || !body?.answerSalt) return null;
|
|
776
|
+
return sha256Hex(`${body.answerSalt}:${body.answerHash}`).slice(0, 16);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function isTextFile(relative) {
|
|
780
|
+
return /\.(html|md|json|css|js|mjs|svg|txt)$/i.test(relative);
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function stableJson(value) {
|
|
784
|
+
return JSON.stringify(sortValue(value));
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
function sortValue(value) {
|
|
788
|
+
if (Array.isArray(value)) return value.map(sortValue);
|
|
789
|
+
if (!value || typeof value !== 'object') return value;
|
|
790
|
+
const result = {};
|
|
791
|
+
for (const key of Object.keys(value).sort()) result[key] = sortValue(value[key]);
|
|
792
|
+
return result;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// 基于实际变更判定高影响操作,而不是依赖操作名或 Agent 自觉。
|
|
796
|
+
export function analyzeImpact(document, workspace, diff) {
|
|
797
|
+
const reasons = [];
|
|
798
|
+
for (const file of diff.files) {
|
|
799
|
+
if (file.kind === 'deleted') reasons.push({ code: 'DELETE', message: `删除 ${file.path}` });
|
|
800
|
+
}
|
|
801
|
+
for (const [id, body] of workspace.interactions.entries()) {
|
|
802
|
+
const record = document.interactions.find((item) => item.entry.id === id);
|
|
803
|
+
if (!record?.body) continue;
|
|
804
|
+
const before = record.body;
|
|
805
|
+
if ((before.answerHash ?? null) !== (body.answerHash ?? null)) reasons.push({ code: 'ANSWER_CHANGED', interactionId: id });
|
|
806
|
+
if (normalizeText(before.explain) !== normalizeText(body.explain)) reasons.push({ code: 'EXPLAIN_CHANGED', interactionId: id });
|
|
807
|
+
if (stableJson(normalizePolicy(before.policy ?? {})) !== stableJson(normalizePolicy(body.policy ?? {}))) {
|
|
808
|
+
reasons.push({ code: 'POLICY_CHANGED', interactionId: id });
|
|
809
|
+
}
|
|
810
|
+
if (stableJson(before.grading ?? {}) !== stableJson(body.grading ?? {})) reasons.push({ code: 'GRADING_CHANGED', interactionId: id });
|
|
811
|
+
const beforeEntry = document.interactionEntry(id);
|
|
812
|
+
const afterEntry = (workspace.manifest.interactions ?? []).find((entry) => entry.id === id);
|
|
813
|
+
if (beforeEntry && afterEntry && (beforeEntry.points !== afterEntry.points || beforeEntry.graded !== afterEntry.graded)) {
|
|
814
|
+
reasons.push({ code: 'SCORE_CHANGED', interactionId: id });
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
const htmlChanges = Object.entries(workspace.sceneTexts)
|
|
818
|
+
.filter(([file, text]) => typeof text === 'string' && document.sceneTexts[file] !== text && file.endsWith('.html'));
|
|
819
|
+
if (htmlChanges.length >= 2) {
|
|
820
|
+
reasons.push({ code: 'MULTI_FILE_HTML_REWRITE', files: htmlChanges.map(([file]) => file) });
|
|
821
|
+
} else if (htmlChanges.length === 1) {
|
|
822
|
+
const [file, text] = htmlChanges[0];
|
|
823
|
+
const before = document.sceneTexts[file];
|
|
824
|
+
if (typeof before === 'string') {
|
|
825
|
+
const shorter = Math.min(before.length, text.length);
|
|
826
|
+
const longer = Math.max(before.length, text.length);
|
|
827
|
+
if (longer > 0 && shorter / longer < 0.5) reasons.push({ code: 'LARGE_HTML_REWRITE', path: file });
|
|
828
|
+
else if (Math.abs(before.length - text.length) > 4000) reasons.push({ code: 'LARGE_HTML_REWRITE', path: file });
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
return { high: reasons.length > 0, reasons };
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function normalizeText(value) {
|
|
835
|
+
return value === undefined || value === null ? '' : String(value);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
export { OPERATION_TYPES, DraftWorkspace, applyOperation, applyAnswerMaterial, sha256Hex };
|