ronds_ai 0.13.0 → 0.14.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/LICENSE +21 -21
- package/PRIVACY.md +56 -56
- package/README.md +59 -59
- package/bin/ronds_ai.js +10 -1
- package/contracts/component-protocol.json +85 -74
- package/lib/component-store.js +245 -245
- package/lib/consent.js +238 -221
- package/lib/default-org.js +27 -27
- package/lib/gateway.js +195 -185
- package/lib/legacy.js +760 -760
- package/lib/manager-store.js +703 -703
- package/lib/paths.js +24 -24
- package/lib/uninstall.js +239 -239
- package/lib/update-manager.js +247 -247
- package/package.json +1 -1
package/lib/legacy.js
CHANGED
|
@@ -1,760 +1,760 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
/**
|
|
3
|
-
* 存量 .35 的只读盘点与数据迁移(docs/design/legacy-migration-and-retention.md §1/§5/§6,主设计 §6.2/§13)。
|
|
4
|
-
*
|
|
5
|
-
* - inspectLegacy():只读盘点旧目录布局。不读文件正文、不上传、不创建或修改任何对象;
|
|
6
|
-
* 时间取文件名时间戳,取不到用 mtime 并标注来源。
|
|
7
|
-
* - planDataMigration():按 §5 迁移表生成源→目标计划(move/keep),scan-state 损坏标 blocked 原位保留。
|
|
8
|
-
* - applyDataMigration(plan):显式事务。先整体备份元数据(源清单 + 每文件 sha256,不复制正文),
|
|
9
|
-
* 再按 state/migration.json 逐步「记录意图→执行→回读确认」,中断后按记录幂等续跑;
|
|
10
|
-
* data/legacy-pending 受 §6 的 128 MiB 初始预算约束,超额步骤递延并报告,不强行迁移。
|
|
11
|
-
* 跨文件系统 rename 失败时用复制 + 摘要校验 + 日志后再删源(§5)。
|
|
12
|
-
*
|
|
13
|
-
* 迁移全程不写 config/consent.json(§6.2:九项权限不因迁移产生);move 逐字节保持事件 ID 与水位。
|
|
14
|
-
*/
|
|
15
|
-
const fs = require('fs');
|
|
16
|
-
const path = require('path');
|
|
17
|
-
const crypto = require('crypto');
|
|
18
|
-
const paths = require('./paths');
|
|
19
|
-
const consent = require('./consent');
|
|
20
|
-
|
|
21
|
-
const MIGRATION_SCHEMA_VERSION = 1;
|
|
22
|
-
const DEFAULT_LEGACY_PENDING_BUDGET_BYTES = 128 * 1024 * 1024; // §6:隔离 legacy-pending 初始预算
|
|
23
|
-
|
|
24
|
-
// §5 表中 analyze/ 下已识别的历史日志(其余文件不猜测、原样保留)
|
|
25
|
-
const ANALYZE_LOG_FILES = ['session_hook.log', 'langfuse_hook.log'];
|
|
26
|
-
const DIAGNOSTICS_PREFIXES = ['diagnostics-active-', 'diagnostics-spool-'];
|
|
27
|
-
const ROOT_KNOWN_FILES = new Set([
|
|
28
|
-
'scan-state.json', 'hooks_state.json', 'hooks_auto_sync_sentinel',
|
|
29
|
-
'hooks_auto_sync_error.log', 'install_id', 'scan.lock', 'hooks_auto_sync.lock',
|
|
30
|
-
]);
|
|
31
|
-
const ROOT_KNOWN_DIRS = new Set([
|
|
32
|
-
'failed-events', 'ai-usage-events', 'ai-usage-sessions', 'analyze', 'runtime',
|
|
33
|
-
'manager', 'component', 'config', 'state', 'data', 'logs', 'leases',
|
|
34
|
-
]);
|
|
35
|
-
const TARGET_DIRS = ['data/legacy-pending', 'data/sessions', 'data/scan', 'logs/component/legacy'];
|
|
36
|
-
const FILENAME_TIME_PATTERNS = [
|
|
37
|
-
/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/,
|
|
38
|
-
/^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})/,
|
|
39
|
-
/^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})/,
|
|
40
|
-
];
|
|
41
|
-
|
|
42
|
-
// ---- 基础工具 ----
|
|
43
|
-
|
|
44
|
-
function toAbs(home, rel) { return path.join(home, ...String(rel).split('/')); }
|
|
45
|
-
|
|
46
|
-
function statOrNull(file) {
|
|
47
|
-
try { return fs.statSync(file); } catch { return null; }
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function isDirectory(dir) {
|
|
51
|
-
const st = statOrNull(dir);
|
|
52
|
-
return !!st && st.isDirectory();
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function iso(ms) { return new Date(ms).toISOString(); }
|
|
56
|
-
|
|
57
|
-
function stamp() { return iso(Date.now()); }
|
|
58
|
-
|
|
59
|
-
function sha256File(file) {
|
|
60
|
-
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// 递归收集常规文件(相对路径用 '/')。符号链接等不跟随、不盘点(§5:不跟随重解析点越界)。
|
|
64
|
-
function walkFiles(dirAbs) {
|
|
65
|
-
const out = [];
|
|
66
|
-
const visit = (rel) => {
|
|
67
|
-
let entries;
|
|
68
|
-
try { entries = fs.readdirSync(toAbs(dirAbs, rel), { withFileTypes: true }); }
|
|
69
|
-
catch { return; }
|
|
70
|
-
for (const entry of entries) {
|
|
71
|
-
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
72
|
-
if (entry.isDirectory()) visit(childRel);
|
|
73
|
-
else if (entry.isFile()) {
|
|
74
|
-
const st = statOrNull(toAbs(dirAbs, childRel));
|
|
75
|
-
if (st) out.push({ rel: childRel, bytes: st.size, mtimeMs: st.mtimeMs });
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
};
|
|
79
|
-
visit('');
|
|
80
|
-
return out;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function timestampFromName(name) {
|
|
84
|
-
for (const pattern of FILENAME_TIME_PATTERNS) {
|
|
85
|
-
const m = pattern.exec(name);
|
|
86
|
-
if (!m) continue;
|
|
87
|
-
const t = Date.parse(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`);
|
|
88
|
-
if (!Number.isNaN(t) && t > Date.UTC(2000, 0, 1) && t < Date.UTC(2100, 0, 1)) return t;
|
|
89
|
-
}
|
|
90
|
-
return null;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// oldest/newest:优先文件名时间戳,取不到退回 mtime;来源逐文件记录
|
|
94
|
-
function timeRange(files) {
|
|
95
|
-
let oldest = null;
|
|
96
|
-
let newest = null;
|
|
97
|
-
for (const f of files) {
|
|
98
|
-
const named = timestampFromName(path.posix.basename(f.rel));
|
|
99
|
-
const t = named === null ? f.mtimeMs : named;
|
|
100
|
-
const source = named === null ? 'mtime' : 'filename';
|
|
101
|
-
if (!oldest || t < oldest.t) oldest = { t, source };
|
|
102
|
-
if (!newest || t > newest.t) newest = { t, source };
|
|
103
|
-
}
|
|
104
|
-
return {
|
|
105
|
-
oldest: oldest ? iso(oldest.t) : null, oldestSource: oldest ? oldest.source : null,
|
|
106
|
-
newest: newest ? iso(newest.t) : null, newestSource: newest ? newest.source : null,
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function dirSummary(dirAbs, { excludeTop = [] } = {}) {
|
|
111
|
-
const exists = isDirectory(dirAbs);
|
|
112
|
-
if (!exists) return { path: dirAbs, exists };
|
|
113
|
-
const skip = new Set(excludeTop);
|
|
114
|
-
const files = walkFiles(dirAbs).filter((f) => !skip.has(f.rel.split('/')[0]));
|
|
115
|
-
return {
|
|
116
|
-
path: dirAbs, exists, files: files.length,
|
|
117
|
-
bytes: files.reduce((n, f) => n + f.bytes, 0),
|
|
118
|
-
...timeRange(files),
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function fileSummary(fileAbs) {
|
|
123
|
-
const st = statOrNull(fileAbs);
|
|
124
|
-
const isFile = !!st && st.isFile();
|
|
125
|
-
return { path: fileAbs, exists: isFile, bytes: isFile ? st.size : null, modified: st ? iso(st.mtimeMs) : null };
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function dirBytes(dirAbs) {
|
|
129
|
-
if (!isDirectory(dirAbs)) return 0;
|
|
130
|
-
return walkFiles(dirAbs).reduce((n, f) => n + f.bytes, 0);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// 只删空目录(自底向上),绝不删除任何文件;占用/非空时保留
|
|
134
|
-
function pruneEmptyDirs(dirAbs) {
|
|
135
|
-
if (!isDirectory(dirAbs)) return;
|
|
136
|
-
let entries;
|
|
137
|
-
try { entries = fs.readdirSync(dirAbs, { withFileTypes: true }); }
|
|
138
|
-
catch { return; }
|
|
139
|
-
for (const entry of entries) if (entry.isDirectory()) pruneEmptyDirs(path.join(dirAbs, entry.name));
|
|
140
|
-
try { fs.rmdirSync(dirAbs); } catch { /* 非空或被占用:保留原目录 */ }
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// ---- inspect(§1:只读盘点)----
|
|
144
|
-
|
|
145
|
-
function analyzeSummary(dirAbs) {
|
|
146
|
-
const summary = dirSummary(dirAbs);
|
|
147
|
-
if (!summary.exists) return summary;
|
|
148
|
-
const logs = [];
|
|
149
|
-
const diagnostics = [];
|
|
150
|
-
const unrecognized = [];
|
|
151
|
-
let langfuseState = false;
|
|
152
|
-
for (const f of walkFiles(dirAbs)) {
|
|
153
|
-
const name = path.posix.basename(f.rel);
|
|
154
|
-
if (ANALYZE_LOG_FILES.includes(f.rel)) logs.push(f.rel);
|
|
155
|
-
else if (DIAGNOSTICS_PREFIXES.some((p) => name.startsWith(p))) diagnostics.push(f.rel);
|
|
156
|
-
else if (f.rel === 'langfuse_state.json') langfuseState = true;
|
|
157
|
-
else unrecognized.push(f.rel);
|
|
158
|
-
}
|
|
159
|
-
return { ...summary, recognizedLogs: logs, diagnostics, langfuseState, unrecognized };
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
function runtimeSummary(dirAbs) {
|
|
163
|
-
const exists = isDirectory(dirAbs);
|
|
164
|
-
if (!exists) return { path: dirAbs, exists };
|
|
165
|
-
let entries;
|
|
166
|
-
try { entries = fs.readdirSync(dirAbs, { withFileTypes: true }); }
|
|
167
|
-
catch { return { path: dirAbs, exists }; }
|
|
168
|
-
const versionDirs = entries
|
|
169
|
-
.filter((e) => e.isDirectory() && /^\d+\.\d+\.\d+-[0-9a-f]+$/.test(e.name))
|
|
170
|
-
.map((e) => e.name);
|
|
171
|
-
const files = walkFiles(dirAbs);
|
|
172
|
-
return {
|
|
173
|
-
path: dirAbs, exists, files: files.length,
|
|
174
|
-
bytes: files.reduce((n, f) => n + f.bytes, 0),
|
|
175
|
-
...timeRange(files),
|
|
176
|
-
currentJson: fs.existsSync(path.join(dirAbs, 'current.json')),
|
|
177
|
-
launchCjs: fs.existsSync(path.join(dirAbs, 'launch.cjs')),
|
|
178
|
-
versionDirs, versionDirCount: versionDirs.length,
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
function targetConflictEntries(home) {
|
|
183
|
-
const conflicts = [];
|
|
184
|
-
for (const rel of TARGET_DIRS) {
|
|
185
|
-
const abs = toAbs(home, rel);
|
|
186
|
-
if (!isDirectory(abs)) continue;
|
|
187
|
-
const entries = fs.readdirSync(abs);
|
|
188
|
-
if (entries.length) conflicts.push({ path: abs, entries });
|
|
189
|
-
}
|
|
190
|
-
return conflicts;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
function inspectLegacy() {
|
|
194
|
-
const home = paths.home();
|
|
195
|
-
const items = {
|
|
196
|
-
failedEvents: dirSummary(toAbs(home, 'failed-events')),
|
|
197
|
-
aiUsageEvents: dirSummary(toAbs(home, 'ai-usage-events'), { excludeTop: ['dead-letter'] }),
|
|
198
|
-
deadLetter: dirSummary(toAbs(home, 'ai-usage-events/dead-letter')),
|
|
199
|
-
aiUsageSessions: dirSummary(toAbs(home, 'ai-usage-sessions')),
|
|
200
|
-
analyze: analyzeSummary(toAbs(home, 'analyze')),
|
|
201
|
-
scanState: fileSummary(toAbs(home, 'scan-state.json')),
|
|
202
|
-
hooksState: fileSummary(toAbs(home, 'hooks_state.json')),
|
|
203
|
-
sentinel: fileSummary(toAbs(home, 'hooks_auto_sync_sentinel')),
|
|
204
|
-
watchdogErrorLog: fileSummary(toAbs(home, 'hooks_auto_sync_error.log')),
|
|
205
|
-
installId: fileSummary(toAbs(home, 'install_id')),
|
|
206
|
-
locks: [
|
|
207
|
-
fileSummary(toAbs(home, 'scan.lock')),
|
|
208
|
-
fileSummary(toAbs(home, 'hooks_auto_sync.lock')),
|
|
209
|
-
],
|
|
210
|
-
runtime: runtimeSummary(toAbs(home, 'runtime')),
|
|
211
|
-
};
|
|
212
|
-
// 新布局冲突:目标目录已有内容,或 data/ 下存在预期外的目录
|
|
213
|
-
const newLayoutConflicts = targetConflictEntries(home);
|
|
214
|
-
const dataDir = toAbs(home, 'data');
|
|
215
|
-
if (isDirectory(dataDir)) {
|
|
216
|
-
const unexpected = fs.readdirSync(dataDir)
|
|
217
|
-
.filter((name) => !['legacy-pending', 'sessions', 'scan'].includes(name));
|
|
218
|
-
if (unexpected.length) newLayoutConflicts.push({ path: dataDir, entries: unexpected });
|
|
219
|
-
}
|
|
220
|
-
const managerBootstrapInstalled = fs.existsSync(path.join(paths.managerDir(), 'launch.cjs'));
|
|
221
|
-
return {
|
|
222
|
-
schemaVersion: MIGRATION_SCHEMA_VERSION, home, generatedAt: stamp(), items,
|
|
223
|
-
newLayoutConflicts, managerBootstrapInstalled,
|
|
224
|
-
notes: [
|
|
225
|
-
'只读盘点:不读文件正文、不上传、不修改或创建任何对象(规范 §1)',
|
|
226
|
-
'系统定时任务不在盘点范围:新架构已安装(manager/launch.cjs)时任务详情由 schedule status 查询(跨包边界)',
|
|
227
|
-
],
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
// ---- plan(§5:旧目录 → 类型 → 迁移表)----
|
|
232
|
-
|
|
233
|
-
function makeMigrationId(now) {
|
|
234
|
-
const id = iso(now).replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z');
|
|
235
|
-
return `${id}-${crypto.randomBytes(4).toString('hex')}`;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
function existsFileSync(abs) {
|
|
239
|
-
const st = statOrNull(abs);
|
|
240
|
-
return !!st && st.isFile();
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
function unrecognizedRootFiles(home) {
|
|
244
|
-
let entries;
|
|
245
|
-
try { entries = fs.readdirSync(home, { withFileTypes: true }); }
|
|
246
|
-
catch { return []; }
|
|
247
|
-
const out = [];
|
|
248
|
-
for (const entry of entries) {
|
|
249
|
-
if (entry.isFile() && !ROOT_KNOWN_FILES.has(entry.name)) out.push(entry.name);
|
|
250
|
-
else if (entry.isDirectory() && !ROOT_KNOWN_DIRS.has(entry.name)) out.push(`${entry.name}/`);
|
|
251
|
-
}
|
|
252
|
-
return out;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
function planDataMigration(options = {}) {
|
|
256
|
-
const home = paths.home();
|
|
257
|
-
const now = options.now === undefined ? Date.now() : options.now;
|
|
258
|
-
const migrationId = options.migrationId || makeMigrationId(now);
|
|
259
|
-
const backupDirRel = `state/migration-backup/${migrationId}`;
|
|
260
|
-
const steps = [];
|
|
261
|
-
|
|
262
|
-
const addDirStep = (id, fromRel, toRel, { excludeTop } = {}) => {
|
|
263
|
-
const fromAbs = toAbs(home, fromRel);
|
|
264
|
-
if (!isDirectory(fromAbs)) return;
|
|
265
|
-
const skip = new Set(excludeTop || []);
|
|
266
|
-
const files = walkFiles(fromAbs).filter((f) => !skip.has(f.rel.split('/')[0]));
|
|
267
|
-
if (!files.length) return;
|
|
268
|
-
steps.push({
|
|
269
|
-
id, from: fromRel, to: toRel, mode: 'move', sourceDir: fromRel,
|
|
270
|
-
files: files.map((f) => f.rel), fileCount: files.length,
|
|
271
|
-
bytes: files.reduce((n, f) => n + f.bytes, 0),
|
|
272
|
-
entries: files.map((f) => ({ from: `${fromRel}/${f.rel}`, to: `${toRel}/${f.rel}` })),
|
|
273
|
-
});
|
|
274
|
-
};
|
|
275
|
-
|
|
276
|
-
// analyze/ 下按已识别类别拆步:诊断数据、历史日志;其余原样保留
|
|
277
|
-
const addAnalyzeStep = (id, toRel, filter) => {
|
|
278
|
-
const analyzeAbs = toAbs(home, 'analyze');
|
|
279
|
-
if (!isDirectory(analyzeAbs)) return;
|
|
280
|
-
const files = walkFiles(analyzeAbs).filter(filter);
|
|
281
|
-
if (!files.length) return;
|
|
282
|
-
steps.push({
|
|
283
|
-
id, from: 'analyze', to: toRel, mode: 'move', sourceDir: 'analyze',
|
|
284
|
-
files: files.map((f) => f.rel), fileCount: files.length,
|
|
285
|
-
bytes: files.reduce((n, f) => n + f.bytes, 0),
|
|
286
|
-
entries: files.map((f) => ({ from: `analyze/${f.rel}`, to: `${toRel}/${f.rel}` })),
|
|
287
|
-
});
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
const addKeepStep = (id, files, note, extra = {}) => {
|
|
291
|
-
if (!files.length) return;
|
|
292
|
-
steps.push({ id, from: extra.from || null, to: null, mode: 'keep', files, fileCount: files.length, bytes: null, note, ...extra });
|
|
293
|
-
};
|
|
294
|
-
|
|
295
|
-
// §5 表逐行
|
|
296
|
-
addDirStep('failed-events', 'failed-events', 'data/legacy-pending/code');
|
|
297
|
-
addDirStep('ai-usage-events', 'ai-usage-events', 'data/legacy-pending/events', { excludeTop: ['dead-letter'] });
|
|
298
|
-
addDirStep('ai-usage-dead-letter', 'ai-usage-events/dead-letter', 'data/legacy-pending/dead-letter');
|
|
299
|
-
addDirStep('ai-usage-sessions', 'ai-usage-sessions', 'data/sessions');
|
|
300
|
-
|
|
301
|
-
const scanStateAbs = toAbs(home, 'scan-state.json');
|
|
302
|
-
if (existsFileSync(scanStateAbs)) {
|
|
303
|
-
const parsed = consent.readJson(scanStateAbs);
|
|
304
|
-
const valid = !!parsed && typeof parsed === 'object' && !Array.isArray(parsed);
|
|
305
|
-
if (valid) {
|
|
306
|
-
steps.push({
|
|
307
|
-
id: 'scan-state', from: 'scan-state.json', to: 'data/scan/state.json', mode: 'move',
|
|
308
|
-
files: ['scan-state.json'], fileCount: 1, bytes: statOrNull(scanStateAbs).size,
|
|
309
|
-
entries: [{ from: 'scan-state.json', to: 'data/scan/state.json' }],
|
|
310
|
-
});
|
|
311
|
-
} else {
|
|
312
|
-
addKeepStep('scan-state', ['scan-state.json'],
|
|
313
|
-
'scan-state.json 无法解析:损坏水位原位保留并暂停迁移(§5:不从空状态自动重扫历史)',
|
|
314
|
-
{ blocked: true, from: 'scan-state.json' });
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
addAnalyzeStep('analyze-diagnostics', 'data/legacy-pending/diagnostics',
|
|
319
|
-
(f) => DIAGNOSTICS_PREFIXES.some((p) => path.posix.basename(f.rel).startsWith(p)));
|
|
320
|
-
addAnalyzeStep('analyze-logs', 'logs/component/legacy', (f) => ANALYZE_LOG_FILES.includes(f.rel));
|
|
321
|
-
addKeepStep('langfuse-state', isDirectory(toAbs(home, 'analyze')) && existsFileSync(toAbs(home, 'analyze/langfuse_state.json'))
|
|
322
|
-
? ['analyze/langfuse_state.json'] : [],
|
|
323
|
-
'langfuse_state.json 语义未确认:原位保留并记录,待旧版本核实后才增状态迁移器(§5)', { from: 'analyze' });
|
|
324
|
-
|
|
325
|
-
const backupFiles = ['hooks_state.json', 'hooks_auto_sync_sentinel'].filter((n) => existsFileSync(toAbs(home, n)));
|
|
326
|
-
if (backupFiles.length) {
|
|
327
|
-
steps.push({
|
|
328
|
-
id: 'hooks-state-backup', from: null, to: backupDirRel, mode: 'move',
|
|
329
|
-
files: backupFiles, fileCount: backupFiles.length,
|
|
330
|
-
bytes: backupFiles.reduce((n, name) => n + statOrNull(toAbs(home, name)).size, 0),
|
|
331
|
-
entries: backupFiles.map((n) => ({ from: n, to: `${backupDirRel}/${n}` })),
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
const errorLog = 'hooks_auto_sync_error.log';
|
|
336
|
-
if (existsFileSync(toAbs(home, errorLog))) {
|
|
337
|
-
steps.push({
|
|
338
|
-
id: 'hooks-auto-sync-error-log', from: errorLog, to: `logs/component/legacy/${errorLog}`, mode: 'move',
|
|
339
|
-
files: [errorLog], fileCount: 1, bytes: statOrNull(toAbs(home, errorLog)).size,
|
|
340
|
-
entries: [{ from: errorLog, to: `logs/component/legacy/${errorLog}` }],
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
addKeepStep('install-id', existsFileSync(toAbs(home, 'install_id')) ? ['install_id'] : [],
|
|
345
|
-
'install_id 是否保留到组件状态依组织/接收方/identity 权限确认:原位保留,不自动继承为授权(§5)');
|
|
346
|
-
addKeepStep('sync-locks',
|
|
347
|
-
['scan.lock', 'hooks_auto_sync.lock', 'runtime/install.lock', 'runtime/update.lock']
|
|
348
|
-
.filter((n) => existsFileSync(toAbs(home, n))),
|
|
349
|
-
'进程同步对象不复制为新锁:核实旧持有者结束后按新协议重建(§5)');
|
|
350
|
-
|
|
351
|
-
const runtimeFiles = [];
|
|
352
|
-
if (isDirectory(toAbs(home, 'runtime'))) {
|
|
353
|
-
if (existsFileSync(toAbs(home, 'runtime/current.json'))) runtimeFiles.push('runtime/current.json');
|
|
354
|
-
if (existsFileSync(toAbs(home, 'runtime/launch.cjs'))) runtimeFiles.push('runtime/launch.cjs 兼容入口');
|
|
355
|
-
for (const dir of runtimeSummary(toAbs(home, 'runtime')).versionDirs) runtimeFiles.push(`runtime/${dir}/`);
|
|
356
|
-
}
|
|
357
|
-
addKeepStep('runtime', runtimeFiles,
|
|
358
|
-
'旧执行基线只作迁移报告/备份引用,排空后按受控清理规则回收;runtime/launch.cjs 单独保留兼容(§5)');
|
|
359
|
-
|
|
360
|
-
const unrecognized = [...unrecognizedRootFiles(home)];
|
|
361
|
-
if (isDirectory(toAbs(home, 'analyze'))) {
|
|
362
|
-
for (const rel of analyzeSummary(toAbs(home, 'analyze')).unrecognized) unrecognized.push(`analyze/${rel}`);
|
|
363
|
-
}
|
|
364
|
-
addKeepStep('unrecognized', unrecognized,
|
|
365
|
-
'未分类遗留数据:原样保留、计入空间盘点;无匹配规则不移动、不删除、不发送,待组织处理(§5)');
|
|
366
|
-
|
|
367
|
-
const moveSteps = steps.filter((s) => s.mode === 'move');
|
|
368
|
-
const totals = {
|
|
369
|
-
steps: steps.length,
|
|
370
|
-
files: steps.reduce((n, s) => n + s.fileCount, 0),
|
|
371
|
-
bytes: steps.reduce((n, s) => n + (s.bytes || 0), 0),
|
|
372
|
-
moveFiles: moveSteps.reduce((n, s) => n + s.fileCount, 0),
|
|
373
|
-
moveBytes: moveSteps.reduce((n, s) => n + (s.bytes || 0), 0),
|
|
374
|
-
keepFiles: steps.reduce((n, s) => (s.mode === 'keep' ? n + s.fileCount : n), 0),
|
|
375
|
-
};
|
|
376
|
-
return {
|
|
377
|
-
schemaVersion: MIGRATION_SCHEMA_VERSION, migrationId, home, backupDir: backupDirRel,
|
|
378
|
-
createdAt: iso(now), legacyPendingBudgetBytes: DEFAULT_LEGACY_PENDING_BUDGET_BYTES,
|
|
379
|
-
warnings: targetConflictEntries(home).map((c) => `目标目录已存在内容:${c.path}(${c.entries.length} 项,迁移将合并写入)`),
|
|
380
|
-
steps, totals,
|
|
381
|
-
};
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
// ---- apply(§4 事务思想 + §5/§6 约束,仅数据迁移子集)----
|
|
385
|
-
|
|
386
|
-
function migrationRecordFile() { return path.join(paths.stateDir(), 'migration.json'); }
|
|
387
|
-
|
|
388
|
-
function loadMigrationRecord() { return consent.readJson(migrationRecordFile()); }
|
|
389
|
-
|
|
390
|
-
function persistRecord(record) { consent.atomicWrite(migrationRecordFile(), record); }
|
|
391
|
-
|
|
392
|
-
// 备份元数据:源清单 + 每文件 sha256,写入备份目录;不复制文件内容(正文靠 move 原样保留)
|
|
393
|
-
function writeBackupManifest(home, backupDir, plan) {
|
|
394
|
-
const files = {};
|
|
395
|
-
for (const step of plan.steps) {
|
|
396
|
-
if (step.mode !== 'move') continue;
|
|
397
|
-
for (const entry of step.entries) {
|
|
398
|
-
if (files[entry.from]) continue;
|
|
399
|
-
const abs = toAbs(home, entry.from);
|
|
400
|
-
if (!existsFileSync(abs)) continue; // 已迁移或缺席:执行阶段按「目标在 + 摘要一致」确认
|
|
401
|
-
const st = statOrNull(abs);
|
|
402
|
-
files[entry.from] = { bytes: st.size, sha256: sha256File(abs), modified: iso(st.mtimeMs) };
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
consent.atomicWrite(path.join(backupDir, 'manifest.json'), {
|
|
406
|
-
schemaVersion: MIGRATION_SCHEMA_VERSION, migrationId: plan.migrationId, home,
|
|
407
|
-
createdAt: stamp(),
|
|
408
|
-
sources: plan.steps.filter((s) => s.mode === 'move')
|
|
409
|
-
.map((s) => ({ id: s.id, from: s.from, to: s.to, files: s.fileCount, bytes: s.bytes || 0 })),
|
|
410
|
-
files,
|
|
411
|
-
});
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
function appendOperation(backupDir, line) {
|
|
415
|
-
try {
|
|
416
|
-
fs.mkdirSync(backupDir, { recursive: true });
|
|
417
|
-
fs.appendFileSync(path.join(backupDir, 'operations.log'), `${new Date().toISOString()} ${line}\n`, 'utf8');
|
|
418
|
-
} catch { /* 操作日志失败不阻断:migration.json 仍逐步记录确认 */ }
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
function verifyFile(fileAbs, expected) {
|
|
422
|
-
const st = statOrNull(fileAbs);
|
|
423
|
-
return !!st && st.isFile() && st.size === expected.bytes && sha256File(fileAbs) === expected.sha256;
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
// 跨文件系统/不支持 rename:复制 + 摘要校验 + 日志之后才删源(§5)
|
|
427
|
-
function copyVerified(srcAbs, dstAbs, expected, entry, backupDir) {
|
|
428
|
-
fs.copyFileSync(srcAbs, dstAbs);
|
|
429
|
-
if (!verifyFile(dstAbs, expected)) {
|
|
430
|
-
try { fs.rmSync(dstAbs, { force: true }); } catch { /* 保留现场供诊断 */ }
|
|
431
|
-
throw new Error(`复制后校验失败:${entry.to}`);
|
|
432
|
-
}
|
|
433
|
-
appendOperation(backupDir, `copy-verified ${entry.from} -> ${entry.to} sha256=${expected.sha256}`);
|
|
434
|
-
fs.rmSync(srcAbs, { force: true });
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
function moveFile(srcAbs, dstAbs, expected, entry, backupDir, forceCopy) {
|
|
438
|
-
if (forceCopy) return copyVerified(srcAbs, dstAbs, expected, entry, backupDir);
|
|
439
|
-
try {
|
|
440
|
-
fs.renameSync(srcAbs, dstAbs);
|
|
441
|
-
} catch (error) {
|
|
442
|
-
if (error && (error.code === 'EXDEV' || error.code === 'ENOTSUP')) {
|
|
443
|
-
return copyVerified(srcAbs, dstAbs, expected, entry, backupDir);
|
|
444
|
-
}
|
|
445
|
-
throw error; // 占用/权限等其他失败:保持原文件,按 interrupted 记录后续跑
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
// 单步执行:每文件「目标在→校验一致则清源;否则搬运→回读确认」
|
|
450
|
-
function executeStep(home, step, manifest, backupDir, { forceCopy }) {
|
|
451
|
-
const results = [];
|
|
452
|
-
for (const entry of step.entries) {
|
|
453
|
-
const expected = manifest.files[entry.from];
|
|
454
|
-
if (!expected) throw new Error(`备份清单缺失 ${entry.from}(备份后源目录出现新文件,需重新 plan)`);
|
|
455
|
-
const srcAbs = toAbs(home, entry.from);
|
|
456
|
-
const dstAbs = toAbs(home, entry.to);
|
|
457
|
-
if (statOrNull(dstAbs)) {
|
|
458
|
-
if (!verifyFile(dstAbs, expected)) throw new Error(`目标已存在且内容不符:${entry.to}`);
|
|
459
|
-
if (existsFileSync(srcAbs)) fs.rmSync(srcAbs, { force: true }); // 补完被中断的迁移
|
|
460
|
-
results.push({ from: entry.from, to: entry.to, bytes: expected.bytes, sha256: expected.sha256, resumed: true });
|
|
461
|
-
continue;
|
|
462
|
-
}
|
|
463
|
-
if (!existsFileSync(srcAbs)) throw new Error(`源与目标均缺失:${entry.from}`);
|
|
464
|
-
fs.mkdirSync(path.dirname(dstAbs), { recursive: true });
|
|
465
|
-
moveFile(srcAbs, dstAbs, expected, entry, backupDir, forceCopy);
|
|
466
|
-
if (!verifyFile(dstAbs, expected)) throw new Error(`回读确认失败:${entry.to}`);
|
|
467
|
-
results.push({ from: entry.from, to: entry.to, bytes: expected.bytes, sha256: expected.sha256 });
|
|
468
|
-
}
|
|
469
|
-
return results;
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
function isLegacyPendingStep(step) {
|
|
473
|
-
return !!step.to && step.to.startsWith('data/legacy-pending');
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
function assertPlan(plan) {
|
|
477
|
-
if (!plan || plan.schemaVersion !== MIGRATION_SCHEMA_VERSION || !Array.isArray(plan.steps) || typeof plan.migrationId !== 'string') {
|
|
478
|
-
throw new Error('迁移计划无效(schema/migrationId/steps),拒绝执行');
|
|
479
|
-
}
|
|
480
|
-
// 只接受 home 内相对路径,拒绝绝对路径/.. 越界(§5:不递归移动不明外部目录、不越界)
|
|
481
|
-
for (const step of plan.steps) {
|
|
482
|
-
for (const entry of step.entries || []) {
|
|
483
|
-
for (const p of [entry.from, entry.to]) {
|
|
484
|
-
if (typeof p !== 'string' || !p || path.isAbsolute(p) || p.split('/').includes('..')) {
|
|
485
|
-
throw new Error(`迁移计划包含非法/越界路径:${p}`);
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
function applyDataMigration(plan, options = {}) {
|
|
493
|
-
assertPlan(plan);
|
|
494
|
-
const home = paths.home();
|
|
495
|
-
if (path.resolve(String(plan.home)) !== path.resolve(home)) {
|
|
496
|
-
throw new Error('迁移计划与当前 home 不一致,拒绝执行');
|
|
497
|
-
}
|
|
498
|
-
const budget = options.legacyPendingBudgetBytes === undefined
|
|
499
|
-
? DEFAULT_LEGACY_PENDING_BUDGET_BYTES : options.legacyPendingBudgetBytes;
|
|
500
|
-
|
|
501
|
-
let record = loadMigrationRecord();
|
|
502
|
-
if (record && record.migrationId !== plan.migrationId) {
|
|
503
|
-
if (record.status !== 'done') {
|
|
504
|
-
throw new Error(`存在未完成的迁移 ${record.migrationId}(state/migration.json),先续跑或处理后再发起新迁移`);
|
|
505
|
-
}
|
|
506
|
-
record = null; // 已完成的旧迁移记录由本次覆盖
|
|
507
|
-
}
|
|
508
|
-
if (!record) {
|
|
509
|
-
record = {
|
|
510
|
-
schemaVersion: MIGRATION_SCHEMA_VERSION, migrationId: plan.migrationId, home,
|
|
511
|
-
status: 'running', phase: 'backup', startedAt: stamp(), steps: {}, backup: null,
|
|
512
|
-
};
|
|
513
|
-
persistRecord(record);
|
|
514
|
-
}
|
|
515
|
-
const backupDir = options.backupDir ? path.resolve(options.backupDir) : toAbs(home, plan.backupDir);
|
|
516
|
-
|
|
517
|
-
// 1) 整体备份元数据(幂等:已确认则复用既有 manifest)
|
|
518
|
-
if (!record.backup || record.backup.status !== 'confirmed') {
|
|
519
|
-
writeBackupManifest(home, backupDir, plan);
|
|
520
|
-
record.backup = { dir: backupDir, status: 'confirmed', at: stamp() };
|
|
521
|
-
persistRecord(record);
|
|
522
|
-
}
|
|
523
|
-
const manifest = consent.readJson(path.join(backupDir, 'manifest.json'));
|
|
524
|
-
if (!manifest || !manifest.files) throw new Error('备份元数据缺失(manifest.json),拒绝执行');
|
|
525
|
-
|
|
526
|
-
// 2) 逐步「记录意图 → 执行 → 回读确认」
|
|
527
|
-
record.phase = 'migrate';
|
|
528
|
-
persistRecord(record);
|
|
529
|
-
const report = { migrationId: plan.migrationId, status: 'done', quota: null, steps: [], consentUnchanged: true };
|
|
530
|
-
const deferred = [];
|
|
531
|
-
let legacyUsed = dirBytes(toAbs(home, 'data/legacy-pending'));
|
|
532
|
-
for (const step of plan.steps) {
|
|
533
|
-
const prev = record.steps[step.id];
|
|
534
|
-
if (prev && prev.status === 'confirmed') {
|
|
535
|
-
if (isLegacyPendingStep(step)) legacyUsed += prev.bytes || 0;
|
|
536
|
-
report.steps.push({ id: step.id, status: 'confirmed', resumed: true });
|
|
537
|
-
continue;
|
|
538
|
-
}
|
|
539
|
-
if (step.mode === 'keep') {
|
|
540
|
-
record.steps[step.id] = { status: 'kept', note: step.note || null, blocked: !!step.blocked, at: stamp() };
|
|
541
|
-
persistRecord(record);
|
|
542
|
-
report.steps.push({ id: step.id, status: 'kept', blocked: !!step.blocked });
|
|
543
|
-
continue;
|
|
544
|
-
}
|
|
545
|
-
if (isLegacyPendingStep(step) && legacyUsed + (step.bytes || 0) > budget) {
|
|
546
|
-
deferred.push(step.id);
|
|
547
|
-
record.steps[step.id] = { status: 'deferred-quota', bytes: step.bytes || 0, at: stamp() };
|
|
548
|
-
persistRecord(record);
|
|
549
|
-
report.quota = { budgetBytes: budget, usedBytes: legacyUsed, deferredSteps: [...deferred] };
|
|
550
|
-
report.steps.push({ id: step.id, status: 'deferred-quota' });
|
|
551
|
-
continue;
|
|
552
|
-
}
|
|
553
|
-
record.steps[step.id] = {
|
|
554
|
-
status: 'intended', from: step.from, to: step.to,
|
|
555
|
-
fileCount: step.fileCount, bytes: step.bytes || 0, at: stamp(),
|
|
556
|
-
};
|
|
557
|
-
persistRecord(record); // 先落意图
|
|
558
|
-
let results;
|
|
559
|
-
try {
|
|
560
|
-
results = executeStep(home, step, manifest, backupDir, { forceCopy: !!options.forceCopy });
|
|
561
|
-
} catch (error) {
|
|
562
|
-
const message = String(error && error.message ? error.message : error);
|
|
563
|
-
record.steps[step.id] = { ...record.steps[step.id], status: 'pending', error: message };
|
|
564
|
-
record.status = 'interrupted';
|
|
565
|
-
persistRecord(record);
|
|
566
|
-
report.status = 'interrupted';
|
|
567
|
-
report.error = message;
|
|
568
|
-
return report;
|
|
569
|
-
}
|
|
570
|
-
record.steps[step.id] = {
|
|
571
|
-
status: 'confirmed', from: step.from, to: step.to, bytes: step.bytes || 0,
|
|
572
|
-
files: results, confirmedAt: stamp(),
|
|
573
|
-
};
|
|
574
|
-
persistRecord(record); // 回读确认后落账
|
|
575
|
-
if (isLegacyPendingStep(step)) legacyUsed += step.bytes || 0;
|
|
576
|
-
report.steps.push({ id: step.id, status: 'confirmed', files: results.length });
|
|
577
|
-
}
|
|
578
|
-
if (deferred.length) {
|
|
579
|
-
report.quota = { ...report.quota, note: 'legacy-pending 预算不足:超额步骤已递延并保留原位,未强行迁移(§6)' };
|
|
580
|
-
}
|
|
581
|
-
// 收尾:清理已搬空的源目录(只删空目录);记录终态
|
|
582
|
-
for (const dir of [...new Set(plan.steps.filter((s) => s.mode === 'move' && s.sourceDir).map((s) => s.sourceDir))]) {
|
|
583
|
-
pruneEmptyDirs(toAbs(home, dir));
|
|
584
|
-
}
|
|
585
|
-
record.status = 'done';
|
|
586
|
-
record.phase = 'done';
|
|
587
|
-
record.finishedAt = stamp();
|
|
588
|
-
persistRecord(record);
|
|
589
|
-
return report;
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
// CLI 入口:存在未完成迁移时复用其 migrationId 续跑(幂等),否则生成新计划
|
|
593
|
-
function runLegacyApply(options = {}) {
|
|
594
|
-
const existing = loadMigrationRecord();
|
|
595
|
-
const migrationId = existing && existing.status !== 'done' ? existing.migrationId : null;
|
|
596
|
-
const plan = planDataMigration({ ...options, migrationId });
|
|
597
|
-
return applyDataMigration(plan, options);
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
// ---- 存量补发(legacy release:隔离队列移回活动队列,由常规 flush 走分端点外发)----
|
|
601
|
-
|
|
602
|
-
const RELEASE_SCHEMA_VERSION = 1;
|
|
603
|
-
|
|
604
|
-
/**
|
|
605
|
-
* data/legacy-pending 各子目录 → 活动队列映射。ext 为目标队列的消费命名约定:
|
|
606
|
-
* code 队列只读顶层 *.jsonl、events 队列只读顶层 *.json(diagnostics/dead-letter
|
|
607
|
-
* 本就沿用诊断/死信命名,不换名)。grant 为移回前复核的事件类型授权。
|
|
608
|
-
*/
|
|
609
|
-
const RELEASE_DIRS = [
|
|
610
|
-
{ id: 'code', from: 'data/legacy-pending/code', to: 'data/code', grant: 'codeMetrics', ext: '.jsonl' },
|
|
611
|
-
{ id: 'events', from: 'data/legacy-pending/events', to: 'data/events', grant: 'promptContent', ext: '.json' },
|
|
612
|
-
{ id: 'diagnostics', from: 'data/legacy-pending/diagnostics', to: 'data/diagnostics', grant: 'promptContent', ext: null },
|
|
613
|
-
{ id: 'dead-letter', from: 'data/legacy-pending/dead-letter', to: 'data/events/dead-letter', grant: 'promptContent', ext: null },
|
|
614
|
-
];
|
|
615
|
-
|
|
616
|
-
function legacyReleaseLedgerFile() { return path.join(paths.stateDir(), 'legacy-release.json'); }
|
|
617
|
-
|
|
618
|
-
/** 按目标队列消费命名放行:.json → .jsonl 换尾、其余补尾;已是目标尾或无约定保持原名。 */
|
|
619
|
-
function releaseFileName(name, ext) {
|
|
620
|
-
if (!ext || name.endsWith(ext)) return name;
|
|
621
|
-
if (ext === '.jsonl' && name.endsWith('.json')) return name.slice(0, -'.json'.length) + ext;
|
|
622
|
-
return name + ext;
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
/** 目标名冲突避让:目标已存在或本轮已被占用时加 -rN 后缀(N 从 1 递增)。 */
|
|
626
|
-
function claimTargetName(targetDirAbs, relDir, wanted, claimed) {
|
|
627
|
-
const taken = (name) => claimed.has(relDir ? `${relDir}/${name}` : name)
|
|
628
|
-
|| existsFileSync(path.join(targetDirAbs, relDir, name));
|
|
629
|
-
if (!taken(wanted)) {
|
|
630
|
-
claimed.add(relDir ? `${relDir}/${wanted}` : wanted);
|
|
631
|
-
return wanted;
|
|
632
|
-
}
|
|
633
|
-
const dot = wanted.lastIndexOf('.');
|
|
634
|
-
const base = dot > 0 ? wanted.slice(0, dot) : wanted;
|
|
635
|
-
const suffix = dot > 0 ? wanted.slice(dot) : '';
|
|
636
|
-
for (let n = 1; ; n += 1) {
|
|
637
|
-
const candidate = `${base}-r${n}${suffix}`;
|
|
638
|
-
if (!taken(candidate)) {
|
|
639
|
-
claimed.add(relDir ? `${relDir}/${candidate}` : candidate);
|
|
640
|
-
return candidate;
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
/** 移动单文件(跨文件系统退化为复制),移后按 sha256 回读确认;瞬时占用退避重试一次。 */
|
|
646
|
-
function releaseMoveFile(home, fromRel, toRel) {
|
|
647
|
-
const srcAbs = toAbs(home, fromRel);
|
|
648
|
-
const dstAbs = toAbs(home, toRel);
|
|
649
|
-
const sha = sha256File(srcAbs);
|
|
650
|
-
fs.mkdirSync(path.dirname(dstAbs), { recursive: true }); // Windows:目标父目录缺失时 rename 报 ENOENT
|
|
651
|
-
const attempt = () => {
|
|
652
|
-
try {
|
|
653
|
-
fs.renameSync(srcAbs, dstAbs);
|
|
654
|
-
} catch (error) {
|
|
655
|
-
if (!error || (error.code !== 'EXDEV' && error.code !== 'ENOTSUP')) throw error;
|
|
656
|
-
fs.copyFileSync(srcAbs, dstAbs); // 跨文件系统:复制 + 摘要校验后再删源(§5 手法)
|
|
657
|
-
fs.rmSync(srcAbs, { force: true });
|
|
658
|
-
}
|
|
659
|
-
};
|
|
660
|
-
try {
|
|
661
|
-
attempt();
|
|
662
|
-
} catch (first) {
|
|
663
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 250); // E-SafeNet 瞬时占用
|
|
664
|
-
attempt();
|
|
665
|
-
}
|
|
666
|
-
const st = statOrNull(dstAbs);
|
|
667
|
-
if (!st || !st.isFile() || sha256File(dstAbs) !== sha) throw new Error(`移回后校验失败:${toRel}`);
|
|
668
|
-
return { sha256: sha, bytes: st.size };
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
/**
|
|
672
|
-
* 存量补发(§6 隔离数据的授权放行):把 data/legacy-pending 下 code/events/
|
|
673
|
-
* diagnostics/dead-letter 的文件移回活动队列,随后由常规 flush 走分端点外发。
|
|
674
|
-
*
|
|
675
|
-
* - 授权复核:各子目录按事件类型(code→codeMetrics,其余→promptContent)检查
|
|
676
|
-
* 当前授权,未覆盖类型的文件保留隔离并计数(不因补发越权放行);
|
|
677
|
-
* - 命名放行:目标按队列消费约定换尾(.json→.jsonl 等),冲突加 -rN 后缀;
|
|
678
|
-
* - 账本:state/legacy-release.json 逐文件记 from→to→sha256(复用 migration.json 风格);
|
|
679
|
-
* - options.confirm !== true 时只读盘点(dry-run),不动任何文件。
|
|
680
|
-
*/
|
|
681
|
-
function runLegacyRelease(options = {}) {
|
|
682
|
-
const confirm = options.confirm === true;
|
|
683
|
-
const home = paths.home();
|
|
684
|
-
if (consent.isDisabled()) {
|
|
685
|
-
return { schemaVersion: RELEASE_SCHEMA_VERSION, home, status: 'blocked', error: '已停用(disable),存量补发被阻断' };
|
|
686
|
-
}
|
|
687
|
-
const grants = consent.loadConsent().grants;
|
|
688
|
-
const report = {
|
|
689
|
-
schemaVersion: RELEASE_SCHEMA_VERSION, home, confirm,
|
|
690
|
-
status: confirm ? 'released' : 'dry-run',
|
|
691
|
-
...(confirm ? {} : { confirmRequired: '需要 --confirm 显式确认(会把隔离队列移回活动队列)' }),
|
|
692
|
-
grants: { codeMetrics: grants.codeMetrics === true, promptContent: grants.promptContent === true },
|
|
693
|
-
dirs: [], released: [], retained: [], failed: [],
|
|
694
|
-
};
|
|
695
|
-
const ledgerEntries = [];
|
|
696
|
-
for (const dir of RELEASE_DIRS) {
|
|
697
|
-
const fromAbs = toAbs(home, dir.from);
|
|
698
|
-
const entry = {
|
|
699
|
-
id: dir.id, from: dir.from, to: dir.to, requiredGrant: dir.grant,
|
|
700
|
-
granted: grants[dir.grant] === true, files: 0, moved: 0, retained: 0, failed: 0,
|
|
701
|
-
};
|
|
702
|
-
if (isDirectory(fromAbs)) {
|
|
703
|
-
const files = walkFiles(fromAbs);
|
|
704
|
-
entry.files = files.length;
|
|
705
|
-
const claimed = new Set();
|
|
706
|
-
for (const file of files) {
|
|
707
|
-
const fromRel = `${dir.from}/${file.rel}`;
|
|
708
|
-
if (!entry.granted) {
|
|
709
|
-
entry.retained += 1;
|
|
710
|
-
report.retained.push({ from: fromRel, reason: `consent:${dir.grant}` });
|
|
711
|
-
continue;
|
|
712
|
-
}
|
|
713
|
-
if (!confirm) continue; // dry-run 只盘点不动文件
|
|
714
|
-
const relDir = path.posix.dirname(file.rel);
|
|
715
|
-
const parentRel = relDir === '.' ? '' : relDir;
|
|
716
|
-
const wanted = releaseFileName(path.posix.basename(file.rel), dir.ext);
|
|
717
|
-
const finalName = claimTargetName(toAbs(home, dir.to), parentRel, wanted, claimed);
|
|
718
|
-
const toRel = parentRel ? `${dir.to}/${parentRel}/${finalName}` : `${dir.to}/${finalName}`;
|
|
719
|
-
try {
|
|
720
|
-
const moved = releaseMoveFile(home, fromRel, toRel);
|
|
721
|
-
entry.moved += 1;
|
|
722
|
-
report.released.push({ from: fromRel, to: toRel, ...moved });
|
|
723
|
-
ledgerEntries.push({ from: fromRel, to: toRel, ...moved });
|
|
724
|
-
} catch (error) {
|
|
725
|
-
entry.failed += 1;
|
|
726
|
-
report.failed.push({ from: fromRel, error: String(error && error.message ? error.message : error) });
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
if (confirm && files.length > 0 && entry.moved === files.length) pruneEmptyDirs(fromAbs);
|
|
730
|
-
}
|
|
731
|
-
report.dirs.push(entry);
|
|
732
|
-
}
|
|
733
|
-
if (confirm) {
|
|
734
|
-
pruneEmptyDirs(toAbs(home, 'data/legacy-pending'));
|
|
735
|
-
if (ledgerEntries.length || report.failed.length) {
|
|
736
|
-
const ledgerFile = legacyReleaseLedgerFile();
|
|
737
|
-
const existing = consent.readJson(ledgerFile);
|
|
738
|
-
const runs = Array.isArray(existing && existing.runs) ? existing.runs : [];
|
|
739
|
-
runs.push({
|
|
740
|
-
runId: makeMigrationId(options.now === undefined ? Date.now() : options.now),
|
|
741
|
-
ranAt: stamp(),
|
|
742
|
-
released: ledgerEntries,
|
|
743
|
-
failed: report.failed,
|
|
744
|
-
});
|
|
745
|
-
consent.atomicWrite(ledgerFile, { schemaVersion: RELEASE_SCHEMA_VERSION, home, runs });
|
|
746
|
-
report.ledger = 'state/legacy-release.json';
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
if (!confirm) report.status = 'dry-run';
|
|
750
|
-
else if (report.released.length === 0 && report.failed.length === 0) report.status = 'nothing-to-release';
|
|
751
|
-
else if (report.failed.length > 0) report.status = 'partial';
|
|
752
|
-
else report.status = 'released';
|
|
753
|
-
return report;
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
module.exports = {
|
|
757
|
-
MIGRATION_SCHEMA_VERSION, DEFAULT_LEGACY_PENDING_BUDGET_BYTES,
|
|
758
|
-
inspectLegacy, planDataMigration, applyDataMigration, runLegacyApply, loadMigrationRecord,
|
|
759
|
-
runLegacyRelease,
|
|
760
|
-
};
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* 存量 .35 的只读盘点与数据迁移(docs/design/legacy-migration-and-retention.md §1/§5/§6,主设计 §6.2/§13)。
|
|
4
|
+
*
|
|
5
|
+
* - inspectLegacy():只读盘点旧目录布局。不读文件正文、不上传、不创建或修改任何对象;
|
|
6
|
+
* 时间取文件名时间戳,取不到用 mtime 并标注来源。
|
|
7
|
+
* - planDataMigration():按 §5 迁移表生成源→目标计划(move/keep),scan-state 损坏标 blocked 原位保留。
|
|
8
|
+
* - applyDataMigration(plan):显式事务。先整体备份元数据(源清单 + 每文件 sha256,不复制正文),
|
|
9
|
+
* 再按 state/migration.json 逐步「记录意图→执行→回读确认」,中断后按记录幂等续跑;
|
|
10
|
+
* data/legacy-pending 受 §6 的 128 MiB 初始预算约束,超额步骤递延并报告,不强行迁移。
|
|
11
|
+
* 跨文件系统 rename 失败时用复制 + 摘要校验 + 日志后再删源(§5)。
|
|
12
|
+
*
|
|
13
|
+
* 迁移全程不写 config/consent.json(§6.2:九项权限不因迁移产生);move 逐字节保持事件 ID 与水位。
|
|
14
|
+
*/
|
|
15
|
+
const fs = require('fs');
|
|
16
|
+
const path = require('path');
|
|
17
|
+
const crypto = require('crypto');
|
|
18
|
+
const paths = require('./paths');
|
|
19
|
+
const consent = require('./consent');
|
|
20
|
+
|
|
21
|
+
const MIGRATION_SCHEMA_VERSION = 1;
|
|
22
|
+
const DEFAULT_LEGACY_PENDING_BUDGET_BYTES = 128 * 1024 * 1024; // §6:隔离 legacy-pending 初始预算
|
|
23
|
+
|
|
24
|
+
// §5 表中 analyze/ 下已识别的历史日志(其余文件不猜测、原样保留)
|
|
25
|
+
const ANALYZE_LOG_FILES = ['session_hook.log', 'langfuse_hook.log'];
|
|
26
|
+
const DIAGNOSTICS_PREFIXES = ['diagnostics-active-', 'diagnostics-spool-'];
|
|
27
|
+
const ROOT_KNOWN_FILES = new Set([
|
|
28
|
+
'scan-state.json', 'hooks_state.json', 'hooks_auto_sync_sentinel',
|
|
29
|
+
'hooks_auto_sync_error.log', 'install_id', 'scan.lock', 'hooks_auto_sync.lock',
|
|
30
|
+
]);
|
|
31
|
+
const ROOT_KNOWN_DIRS = new Set([
|
|
32
|
+
'failed-events', 'ai-usage-events', 'ai-usage-sessions', 'analyze', 'runtime',
|
|
33
|
+
'manager', 'component', 'config', 'state', 'data', 'logs', 'leases',
|
|
34
|
+
]);
|
|
35
|
+
const TARGET_DIRS = ['data/legacy-pending', 'data/sessions', 'data/scan', 'logs/component/legacy'];
|
|
36
|
+
const FILENAME_TIME_PATTERNS = [
|
|
37
|
+
/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/,
|
|
38
|
+
/^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})/,
|
|
39
|
+
/^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})/,
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
// ---- 基础工具 ----
|
|
43
|
+
|
|
44
|
+
function toAbs(home, rel) { return path.join(home, ...String(rel).split('/')); }
|
|
45
|
+
|
|
46
|
+
function statOrNull(file) {
|
|
47
|
+
try { return fs.statSync(file); } catch { return null; }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isDirectory(dir) {
|
|
51
|
+
const st = statOrNull(dir);
|
|
52
|
+
return !!st && st.isDirectory();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function iso(ms) { return new Date(ms).toISOString(); }
|
|
56
|
+
|
|
57
|
+
function stamp() { return iso(Date.now()); }
|
|
58
|
+
|
|
59
|
+
function sha256File(file) {
|
|
60
|
+
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// 递归收集常规文件(相对路径用 '/')。符号链接等不跟随、不盘点(§5:不跟随重解析点越界)。
|
|
64
|
+
function walkFiles(dirAbs) {
|
|
65
|
+
const out = [];
|
|
66
|
+
const visit = (rel) => {
|
|
67
|
+
let entries;
|
|
68
|
+
try { entries = fs.readdirSync(toAbs(dirAbs, rel), { withFileTypes: true }); }
|
|
69
|
+
catch { return; }
|
|
70
|
+
for (const entry of entries) {
|
|
71
|
+
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
72
|
+
if (entry.isDirectory()) visit(childRel);
|
|
73
|
+
else if (entry.isFile()) {
|
|
74
|
+
const st = statOrNull(toAbs(dirAbs, childRel));
|
|
75
|
+
if (st) out.push({ rel: childRel, bytes: st.size, mtimeMs: st.mtimeMs });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
visit('');
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function timestampFromName(name) {
|
|
84
|
+
for (const pattern of FILENAME_TIME_PATTERNS) {
|
|
85
|
+
const m = pattern.exec(name);
|
|
86
|
+
if (!m) continue;
|
|
87
|
+
const t = Date.parse(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`);
|
|
88
|
+
if (!Number.isNaN(t) && t > Date.UTC(2000, 0, 1) && t < Date.UTC(2100, 0, 1)) return t;
|
|
89
|
+
}
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// oldest/newest:优先文件名时间戳,取不到退回 mtime;来源逐文件记录
|
|
94
|
+
function timeRange(files) {
|
|
95
|
+
let oldest = null;
|
|
96
|
+
let newest = null;
|
|
97
|
+
for (const f of files) {
|
|
98
|
+
const named = timestampFromName(path.posix.basename(f.rel));
|
|
99
|
+
const t = named === null ? f.mtimeMs : named;
|
|
100
|
+
const source = named === null ? 'mtime' : 'filename';
|
|
101
|
+
if (!oldest || t < oldest.t) oldest = { t, source };
|
|
102
|
+
if (!newest || t > newest.t) newest = { t, source };
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
oldest: oldest ? iso(oldest.t) : null, oldestSource: oldest ? oldest.source : null,
|
|
106
|
+
newest: newest ? iso(newest.t) : null, newestSource: newest ? newest.source : null,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function dirSummary(dirAbs, { excludeTop = [] } = {}) {
|
|
111
|
+
const exists = isDirectory(dirAbs);
|
|
112
|
+
if (!exists) return { path: dirAbs, exists };
|
|
113
|
+
const skip = new Set(excludeTop);
|
|
114
|
+
const files = walkFiles(dirAbs).filter((f) => !skip.has(f.rel.split('/')[0]));
|
|
115
|
+
return {
|
|
116
|
+
path: dirAbs, exists, files: files.length,
|
|
117
|
+
bytes: files.reduce((n, f) => n + f.bytes, 0),
|
|
118
|
+
...timeRange(files),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function fileSummary(fileAbs) {
|
|
123
|
+
const st = statOrNull(fileAbs);
|
|
124
|
+
const isFile = !!st && st.isFile();
|
|
125
|
+
return { path: fileAbs, exists: isFile, bytes: isFile ? st.size : null, modified: st ? iso(st.mtimeMs) : null };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function dirBytes(dirAbs) {
|
|
129
|
+
if (!isDirectory(dirAbs)) return 0;
|
|
130
|
+
return walkFiles(dirAbs).reduce((n, f) => n + f.bytes, 0);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// 只删空目录(自底向上),绝不删除任何文件;占用/非空时保留
|
|
134
|
+
function pruneEmptyDirs(dirAbs) {
|
|
135
|
+
if (!isDirectory(dirAbs)) return;
|
|
136
|
+
let entries;
|
|
137
|
+
try { entries = fs.readdirSync(dirAbs, { withFileTypes: true }); }
|
|
138
|
+
catch { return; }
|
|
139
|
+
for (const entry of entries) if (entry.isDirectory()) pruneEmptyDirs(path.join(dirAbs, entry.name));
|
|
140
|
+
try { fs.rmdirSync(dirAbs); } catch { /* 非空或被占用:保留原目录 */ }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ---- inspect(§1:只读盘点)----
|
|
144
|
+
|
|
145
|
+
function analyzeSummary(dirAbs) {
|
|
146
|
+
const summary = dirSummary(dirAbs);
|
|
147
|
+
if (!summary.exists) return summary;
|
|
148
|
+
const logs = [];
|
|
149
|
+
const diagnostics = [];
|
|
150
|
+
const unrecognized = [];
|
|
151
|
+
let langfuseState = false;
|
|
152
|
+
for (const f of walkFiles(dirAbs)) {
|
|
153
|
+
const name = path.posix.basename(f.rel);
|
|
154
|
+
if (ANALYZE_LOG_FILES.includes(f.rel)) logs.push(f.rel);
|
|
155
|
+
else if (DIAGNOSTICS_PREFIXES.some((p) => name.startsWith(p))) diagnostics.push(f.rel);
|
|
156
|
+
else if (f.rel === 'langfuse_state.json') langfuseState = true;
|
|
157
|
+
else unrecognized.push(f.rel);
|
|
158
|
+
}
|
|
159
|
+
return { ...summary, recognizedLogs: logs, diagnostics, langfuseState, unrecognized };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function runtimeSummary(dirAbs) {
|
|
163
|
+
const exists = isDirectory(dirAbs);
|
|
164
|
+
if (!exists) return { path: dirAbs, exists };
|
|
165
|
+
let entries;
|
|
166
|
+
try { entries = fs.readdirSync(dirAbs, { withFileTypes: true }); }
|
|
167
|
+
catch { return { path: dirAbs, exists }; }
|
|
168
|
+
const versionDirs = entries
|
|
169
|
+
.filter((e) => e.isDirectory() && /^\d+\.\d+\.\d+-[0-9a-f]+$/.test(e.name))
|
|
170
|
+
.map((e) => e.name);
|
|
171
|
+
const files = walkFiles(dirAbs);
|
|
172
|
+
return {
|
|
173
|
+
path: dirAbs, exists, files: files.length,
|
|
174
|
+
bytes: files.reduce((n, f) => n + f.bytes, 0),
|
|
175
|
+
...timeRange(files),
|
|
176
|
+
currentJson: fs.existsSync(path.join(dirAbs, 'current.json')),
|
|
177
|
+
launchCjs: fs.existsSync(path.join(dirAbs, 'launch.cjs')),
|
|
178
|
+
versionDirs, versionDirCount: versionDirs.length,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function targetConflictEntries(home) {
|
|
183
|
+
const conflicts = [];
|
|
184
|
+
for (const rel of TARGET_DIRS) {
|
|
185
|
+
const abs = toAbs(home, rel);
|
|
186
|
+
if (!isDirectory(abs)) continue;
|
|
187
|
+
const entries = fs.readdirSync(abs);
|
|
188
|
+
if (entries.length) conflicts.push({ path: abs, entries });
|
|
189
|
+
}
|
|
190
|
+
return conflicts;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function inspectLegacy() {
|
|
194
|
+
const home = paths.home();
|
|
195
|
+
const items = {
|
|
196
|
+
failedEvents: dirSummary(toAbs(home, 'failed-events')),
|
|
197
|
+
aiUsageEvents: dirSummary(toAbs(home, 'ai-usage-events'), { excludeTop: ['dead-letter'] }),
|
|
198
|
+
deadLetter: dirSummary(toAbs(home, 'ai-usage-events/dead-letter')),
|
|
199
|
+
aiUsageSessions: dirSummary(toAbs(home, 'ai-usage-sessions')),
|
|
200
|
+
analyze: analyzeSummary(toAbs(home, 'analyze')),
|
|
201
|
+
scanState: fileSummary(toAbs(home, 'scan-state.json')),
|
|
202
|
+
hooksState: fileSummary(toAbs(home, 'hooks_state.json')),
|
|
203
|
+
sentinel: fileSummary(toAbs(home, 'hooks_auto_sync_sentinel')),
|
|
204
|
+
watchdogErrorLog: fileSummary(toAbs(home, 'hooks_auto_sync_error.log')),
|
|
205
|
+
installId: fileSummary(toAbs(home, 'install_id')),
|
|
206
|
+
locks: [
|
|
207
|
+
fileSummary(toAbs(home, 'scan.lock')),
|
|
208
|
+
fileSummary(toAbs(home, 'hooks_auto_sync.lock')),
|
|
209
|
+
],
|
|
210
|
+
runtime: runtimeSummary(toAbs(home, 'runtime')),
|
|
211
|
+
};
|
|
212
|
+
// 新布局冲突:目标目录已有内容,或 data/ 下存在预期外的目录
|
|
213
|
+
const newLayoutConflicts = targetConflictEntries(home);
|
|
214
|
+
const dataDir = toAbs(home, 'data');
|
|
215
|
+
if (isDirectory(dataDir)) {
|
|
216
|
+
const unexpected = fs.readdirSync(dataDir)
|
|
217
|
+
.filter((name) => !['legacy-pending', 'sessions', 'scan'].includes(name));
|
|
218
|
+
if (unexpected.length) newLayoutConflicts.push({ path: dataDir, entries: unexpected });
|
|
219
|
+
}
|
|
220
|
+
const managerBootstrapInstalled = fs.existsSync(path.join(paths.managerDir(), 'launch.cjs'));
|
|
221
|
+
return {
|
|
222
|
+
schemaVersion: MIGRATION_SCHEMA_VERSION, home, generatedAt: stamp(), items,
|
|
223
|
+
newLayoutConflicts, managerBootstrapInstalled,
|
|
224
|
+
notes: [
|
|
225
|
+
'只读盘点:不读文件正文、不上传、不修改或创建任何对象(规范 §1)',
|
|
226
|
+
'系统定时任务不在盘点范围:新架构已安装(manager/launch.cjs)时任务详情由 schedule status 查询(跨包边界)',
|
|
227
|
+
],
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ---- plan(§5:旧目录 → 类型 → 迁移表)----
|
|
232
|
+
|
|
233
|
+
function makeMigrationId(now) {
|
|
234
|
+
const id = iso(now).replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z');
|
|
235
|
+
return `${id}-${crypto.randomBytes(4).toString('hex')}`;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function existsFileSync(abs) {
|
|
239
|
+
const st = statOrNull(abs);
|
|
240
|
+
return !!st && st.isFile();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function unrecognizedRootFiles(home) {
|
|
244
|
+
let entries;
|
|
245
|
+
try { entries = fs.readdirSync(home, { withFileTypes: true }); }
|
|
246
|
+
catch { return []; }
|
|
247
|
+
const out = [];
|
|
248
|
+
for (const entry of entries) {
|
|
249
|
+
if (entry.isFile() && !ROOT_KNOWN_FILES.has(entry.name)) out.push(entry.name);
|
|
250
|
+
else if (entry.isDirectory() && !ROOT_KNOWN_DIRS.has(entry.name)) out.push(`${entry.name}/`);
|
|
251
|
+
}
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function planDataMigration(options = {}) {
|
|
256
|
+
const home = paths.home();
|
|
257
|
+
const now = options.now === undefined ? Date.now() : options.now;
|
|
258
|
+
const migrationId = options.migrationId || makeMigrationId(now);
|
|
259
|
+
const backupDirRel = `state/migration-backup/${migrationId}`;
|
|
260
|
+
const steps = [];
|
|
261
|
+
|
|
262
|
+
const addDirStep = (id, fromRel, toRel, { excludeTop } = {}) => {
|
|
263
|
+
const fromAbs = toAbs(home, fromRel);
|
|
264
|
+
if (!isDirectory(fromAbs)) return;
|
|
265
|
+
const skip = new Set(excludeTop || []);
|
|
266
|
+
const files = walkFiles(fromAbs).filter((f) => !skip.has(f.rel.split('/')[0]));
|
|
267
|
+
if (!files.length) return;
|
|
268
|
+
steps.push({
|
|
269
|
+
id, from: fromRel, to: toRel, mode: 'move', sourceDir: fromRel,
|
|
270
|
+
files: files.map((f) => f.rel), fileCount: files.length,
|
|
271
|
+
bytes: files.reduce((n, f) => n + f.bytes, 0),
|
|
272
|
+
entries: files.map((f) => ({ from: `${fromRel}/${f.rel}`, to: `${toRel}/${f.rel}` })),
|
|
273
|
+
});
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
// analyze/ 下按已识别类别拆步:诊断数据、历史日志;其余原样保留
|
|
277
|
+
const addAnalyzeStep = (id, toRel, filter) => {
|
|
278
|
+
const analyzeAbs = toAbs(home, 'analyze');
|
|
279
|
+
if (!isDirectory(analyzeAbs)) return;
|
|
280
|
+
const files = walkFiles(analyzeAbs).filter(filter);
|
|
281
|
+
if (!files.length) return;
|
|
282
|
+
steps.push({
|
|
283
|
+
id, from: 'analyze', to: toRel, mode: 'move', sourceDir: 'analyze',
|
|
284
|
+
files: files.map((f) => f.rel), fileCount: files.length,
|
|
285
|
+
bytes: files.reduce((n, f) => n + f.bytes, 0),
|
|
286
|
+
entries: files.map((f) => ({ from: `analyze/${f.rel}`, to: `${toRel}/${f.rel}` })),
|
|
287
|
+
});
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
const addKeepStep = (id, files, note, extra = {}) => {
|
|
291
|
+
if (!files.length) return;
|
|
292
|
+
steps.push({ id, from: extra.from || null, to: null, mode: 'keep', files, fileCount: files.length, bytes: null, note, ...extra });
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
// §5 表逐行
|
|
296
|
+
addDirStep('failed-events', 'failed-events', 'data/legacy-pending/code');
|
|
297
|
+
addDirStep('ai-usage-events', 'ai-usage-events', 'data/legacy-pending/events', { excludeTop: ['dead-letter'] });
|
|
298
|
+
addDirStep('ai-usage-dead-letter', 'ai-usage-events/dead-letter', 'data/legacy-pending/dead-letter');
|
|
299
|
+
addDirStep('ai-usage-sessions', 'ai-usage-sessions', 'data/sessions');
|
|
300
|
+
|
|
301
|
+
const scanStateAbs = toAbs(home, 'scan-state.json');
|
|
302
|
+
if (existsFileSync(scanStateAbs)) {
|
|
303
|
+
const parsed = consent.readJson(scanStateAbs);
|
|
304
|
+
const valid = !!parsed && typeof parsed === 'object' && !Array.isArray(parsed);
|
|
305
|
+
if (valid) {
|
|
306
|
+
steps.push({
|
|
307
|
+
id: 'scan-state', from: 'scan-state.json', to: 'data/scan/state.json', mode: 'move',
|
|
308
|
+
files: ['scan-state.json'], fileCount: 1, bytes: statOrNull(scanStateAbs).size,
|
|
309
|
+
entries: [{ from: 'scan-state.json', to: 'data/scan/state.json' }],
|
|
310
|
+
});
|
|
311
|
+
} else {
|
|
312
|
+
addKeepStep('scan-state', ['scan-state.json'],
|
|
313
|
+
'scan-state.json 无法解析:损坏水位原位保留并暂停迁移(§5:不从空状态自动重扫历史)',
|
|
314
|
+
{ blocked: true, from: 'scan-state.json' });
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
addAnalyzeStep('analyze-diagnostics', 'data/legacy-pending/diagnostics',
|
|
319
|
+
(f) => DIAGNOSTICS_PREFIXES.some((p) => path.posix.basename(f.rel).startsWith(p)));
|
|
320
|
+
addAnalyzeStep('analyze-logs', 'logs/component/legacy', (f) => ANALYZE_LOG_FILES.includes(f.rel));
|
|
321
|
+
addKeepStep('langfuse-state', isDirectory(toAbs(home, 'analyze')) && existsFileSync(toAbs(home, 'analyze/langfuse_state.json'))
|
|
322
|
+
? ['analyze/langfuse_state.json'] : [],
|
|
323
|
+
'langfuse_state.json 语义未确认:原位保留并记录,待旧版本核实后才增状态迁移器(§5)', { from: 'analyze' });
|
|
324
|
+
|
|
325
|
+
const backupFiles = ['hooks_state.json', 'hooks_auto_sync_sentinel'].filter((n) => existsFileSync(toAbs(home, n)));
|
|
326
|
+
if (backupFiles.length) {
|
|
327
|
+
steps.push({
|
|
328
|
+
id: 'hooks-state-backup', from: null, to: backupDirRel, mode: 'move',
|
|
329
|
+
files: backupFiles, fileCount: backupFiles.length,
|
|
330
|
+
bytes: backupFiles.reduce((n, name) => n + statOrNull(toAbs(home, name)).size, 0),
|
|
331
|
+
entries: backupFiles.map((n) => ({ from: n, to: `${backupDirRel}/${n}` })),
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const errorLog = 'hooks_auto_sync_error.log';
|
|
336
|
+
if (existsFileSync(toAbs(home, errorLog))) {
|
|
337
|
+
steps.push({
|
|
338
|
+
id: 'hooks-auto-sync-error-log', from: errorLog, to: `logs/component/legacy/${errorLog}`, mode: 'move',
|
|
339
|
+
files: [errorLog], fileCount: 1, bytes: statOrNull(toAbs(home, errorLog)).size,
|
|
340
|
+
entries: [{ from: errorLog, to: `logs/component/legacy/${errorLog}` }],
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
addKeepStep('install-id', existsFileSync(toAbs(home, 'install_id')) ? ['install_id'] : [],
|
|
345
|
+
'install_id 是否保留到组件状态依组织/接收方/identity 权限确认:原位保留,不自动继承为授权(§5)');
|
|
346
|
+
addKeepStep('sync-locks',
|
|
347
|
+
['scan.lock', 'hooks_auto_sync.lock', 'runtime/install.lock', 'runtime/update.lock']
|
|
348
|
+
.filter((n) => existsFileSync(toAbs(home, n))),
|
|
349
|
+
'进程同步对象不复制为新锁:核实旧持有者结束后按新协议重建(§5)');
|
|
350
|
+
|
|
351
|
+
const runtimeFiles = [];
|
|
352
|
+
if (isDirectory(toAbs(home, 'runtime'))) {
|
|
353
|
+
if (existsFileSync(toAbs(home, 'runtime/current.json'))) runtimeFiles.push('runtime/current.json');
|
|
354
|
+
if (existsFileSync(toAbs(home, 'runtime/launch.cjs'))) runtimeFiles.push('runtime/launch.cjs 兼容入口');
|
|
355
|
+
for (const dir of runtimeSummary(toAbs(home, 'runtime')).versionDirs) runtimeFiles.push(`runtime/${dir}/`);
|
|
356
|
+
}
|
|
357
|
+
addKeepStep('runtime', runtimeFiles,
|
|
358
|
+
'旧执行基线只作迁移报告/备份引用,排空后按受控清理规则回收;runtime/launch.cjs 单独保留兼容(§5)');
|
|
359
|
+
|
|
360
|
+
const unrecognized = [...unrecognizedRootFiles(home)];
|
|
361
|
+
if (isDirectory(toAbs(home, 'analyze'))) {
|
|
362
|
+
for (const rel of analyzeSummary(toAbs(home, 'analyze')).unrecognized) unrecognized.push(`analyze/${rel}`);
|
|
363
|
+
}
|
|
364
|
+
addKeepStep('unrecognized', unrecognized,
|
|
365
|
+
'未分类遗留数据:原样保留、计入空间盘点;无匹配规则不移动、不删除、不发送,待组织处理(§5)');
|
|
366
|
+
|
|
367
|
+
const moveSteps = steps.filter((s) => s.mode === 'move');
|
|
368
|
+
const totals = {
|
|
369
|
+
steps: steps.length,
|
|
370
|
+
files: steps.reduce((n, s) => n + s.fileCount, 0),
|
|
371
|
+
bytes: steps.reduce((n, s) => n + (s.bytes || 0), 0),
|
|
372
|
+
moveFiles: moveSteps.reduce((n, s) => n + s.fileCount, 0),
|
|
373
|
+
moveBytes: moveSteps.reduce((n, s) => n + (s.bytes || 0), 0),
|
|
374
|
+
keepFiles: steps.reduce((n, s) => (s.mode === 'keep' ? n + s.fileCount : n), 0),
|
|
375
|
+
};
|
|
376
|
+
return {
|
|
377
|
+
schemaVersion: MIGRATION_SCHEMA_VERSION, migrationId, home, backupDir: backupDirRel,
|
|
378
|
+
createdAt: iso(now), legacyPendingBudgetBytes: DEFAULT_LEGACY_PENDING_BUDGET_BYTES,
|
|
379
|
+
warnings: targetConflictEntries(home).map((c) => `目标目录已存在内容:${c.path}(${c.entries.length} 项,迁移将合并写入)`),
|
|
380
|
+
steps, totals,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ---- apply(§4 事务思想 + §5/§6 约束,仅数据迁移子集)----
|
|
385
|
+
|
|
386
|
+
function migrationRecordFile() { return path.join(paths.stateDir(), 'migration.json'); }
|
|
387
|
+
|
|
388
|
+
function loadMigrationRecord() { return consent.readJson(migrationRecordFile()); }
|
|
389
|
+
|
|
390
|
+
function persistRecord(record) { consent.atomicWrite(migrationRecordFile(), record); }
|
|
391
|
+
|
|
392
|
+
// 备份元数据:源清单 + 每文件 sha256,写入备份目录;不复制文件内容(正文靠 move 原样保留)
|
|
393
|
+
function writeBackupManifest(home, backupDir, plan) {
|
|
394
|
+
const files = {};
|
|
395
|
+
for (const step of plan.steps) {
|
|
396
|
+
if (step.mode !== 'move') continue;
|
|
397
|
+
for (const entry of step.entries) {
|
|
398
|
+
if (files[entry.from]) continue;
|
|
399
|
+
const abs = toAbs(home, entry.from);
|
|
400
|
+
if (!existsFileSync(abs)) continue; // 已迁移或缺席:执行阶段按「目标在 + 摘要一致」确认
|
|
401
|
+
const st = statOrNull(abs);
|
|
402
|
+
files[entry.from] = { bytes: st.size, sha256: sha256File(abs), modified: iso(st.mtimeMs) };
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
consent.atomicWrite(path.join(backupDir, 'manifest.json'), {
|
|
406
|
+
schemaVersion: MIGRATION_SCHEMA_VERSION, migrationId: plan.migrationId, home,
|
|
407
|
+
createdAt: stamp(),
|
|
408
|
+
sources: plan.steps.filter((s) => s.mode === 'move')
|
|
409
|
+
.map((s) => ({ id: s.id, from: s.from, to: s.to, files: s.fileCount, bytes: s.bytes || 0 })),
|
|
410
|
+
files,
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function appendOperation(backupDir, line) {
|
|
415
|
+
try {
|
|
416
|
+
fs.mkdirSync(backupDir, { recursive: true });
|
|
417
|
+
fs.appendFileSync(path.join(backupDir, 'operations.log'), `${new Date().toISOString()} ${line}\n`, 'utf8');
|
|
418
|
+
} catch { /* 操作日志失败不阻断:migration.json 仍逐步记录确认 */ }
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function verifyFile(fileAbs, expected) {
|
|
422
|
+
const st = statOrNull(fileAbs);
|
|
423
|
+
return !!st && st.isFile() && st.size === expected.bytes && sha256File(fileAbs) === expected.sha256;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// 跨文件系统/不支持 rename:复制 + 摘要校验 + 日志之后才删源(§5)
|
|
427
|
+
function copyVerified(srcAbs, dstAbs, expected, entry, backupDir) {
|
|
428
|
+
fs.copyFileSync(srcAbs, dstAbs);
|
|
429
|
+
if (!verifyFile(dstAbs, expected)) {
|
|
430
|
+
try { fs.rmSync(dstAbs, { force: true }); } catch { /* 保留现场供诊断 */ }
|
|
431
|
+
throw new Error(`复制后校验失败:${entry.to}`);
|
|
432
|
+
}
|
|
433
|
+
appendOperation(backupDir, `copy-verified ${entry.from} -> ${entry.to} sha256=${expected.sha256}`);
|
|
434
|
+
fs.rmSync(srcAbs, { force: true });
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function moveFile(srcAbs, dstAbs, expected, entry, backupDir, forceCopy) {
|
|
438
|
+
if (forceCopy) return copyVerified(srcAbs, dstAbs, expected, entry, backupDir);
|
|
439
|
+
try {
|
|
440
|
+
fs.renameSync(srcAbs, dstAbs);
|
|
441
|
+
} catch (error) {
|
|
442
|
+
if (error && (error.code === 'EXDEV' || error.code === 'ENOTSUP')) {
|
|
443
|
+
return copyVerified(srcAbs, dstAbs, expected, entry, backupDir);
|
|
444
|
+
}
|
|
445
|
+
throw error; // 占用/权限等其他失败:保持原文件,按 interrupted 记录后续跑
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// 单步执行:每文件「目标在→校验一致则清源;否则搬运→回读确认」
|
|
450
|
+
function executeStep(home, step, manifest, backupDir, { forceCopy }) {
|
|
451
|
+
const results = [];
|
|
452
|
+
for (const entry of step.entries) {
|
|
453
|
+
const expected = manifest.files[entry.from];
|
|
454
|
+
if (!expected) throw new Error(`备份清单缺失 ${entry.from}(备份后源目录出现新文件,需重新 plan)`);
|
|
455
|
+
const srcAbs = toAbs(home, entry.from);
|
|
456
|
+
const dstAbs = toAbs(home, entry.to);
|
|
457
|
+
if (statOrNull(dstAbs)) {
|
|
458
|
+
if (!verifyFile(dstAbs, expected)) throw new Error(`目标已存在且内容不符:${entry.to}`);
|
|
459
|
+
if (existsFileSync(srcAbs)) fs.rmSync(srcAbs, { force: true }); // 补完被中断的迁移
|
|
460
|
+
results.push({ from: entry.from, to: entry.to, bytes: expected.bytes, sha256: expected.sha256, resumed: true });
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
if (!existsFileSync(srcAbs)) throw new Error(`源与目标均缺失:${entry.from}`);
|
|
464
|
+
fs.mkdirSync(path.dirname(dstAbs), { recursive: true });
|
|
465
|
+
moveFile(srcAbs, dstAbs, expected, entry, backupDir, forceCopy);
|
|
466
|
+
if (!verifyFile(dstAbs, expected)) throw new Error(`回读确认失败:${entry.to}`);
|
|
467
|
+
results.push({ from: entry.from, to: entry.to, bytes: expected.bytes, sha256: expected.sha256 });
|
|
468
|
+
}
|
|
469
|
+
return results;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function isLegacyPendingStep(step) {
|
|
473
|
+
return !!step.to && step.to.startsWith('data/legacy-pending');
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function assertPlan(plan) {
|
|
477
|
+
if (!plan || plan.schemaVersion !== MIGRATION_SCHEMA_VERSION || !Array.isArray(plan.steps) || typeof plan.migrationId !== 'string') {
|
|
478
|
+
throw new Error('迁移计划无效(schema/migrationId/steps),拒绝执行');
|
|
479
|
+
}
|
|
480
|
+
// 只接受 home 内相对路径,拒绝绝对路径/.. 越界(§5:不递归移动不明外部目录、不越界)
|
|
481
|
+
for (const step of plan.steps) {
|
|
482
|
+
for (const entry of step.entries || []) {
|
|
483
|
+
for (const p of [entry.from, entry.to]) {
|
|
484
|
+
if (typeof p !== 'string' || !p || path.isAbsolute(p) || p.split('/').includes('..')) {
|
|
485
|
+
throw new Error(`迁移计划包含非法/越界路径:${p}`);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function applyDataMigration(plan, options = {}) {
|
|
493
|
+
assertPlan(plan);
|
|
494
|
+
const home = paths.home();
|
|
495
|
+
if (path.resolve(String(plan.home)) !== path.resolve(home)) {
|
|
496
|
+
throw new Error('迁移计划与当前 home 不一致,拒绝执行');
|
|
497
|
+
}
|
|
498
|
+
const budget = options.legacyPendingBudgetBytes === undefined
|
|
499
|
+
? DEFAULT_LEGACY_PENDING_BUDGET_BYTES : options.legacyPendingBudgetBytes;
|
|
500
|
+
|
|
501
|
+
let record = loadMigrationRecord();
|
|
502
|
+
if (record && record.migrationId !== plan.migrationId) {
|
|
503
|
+
if (record.status !== 'done') {
|
|
504
|
+
throw new Error(`存在未完成的迁移 ${record.migrationId}(state/migration.json),先续跑或处理后再发起新迁移`);
|
|
505
|
+
}
|
|
506
|
+
record = null; // 已完成的旧迁移记录由本次覆盖
|
|
507
|
+
}
|
|
508
|
+
if (!record) {
|
|
509
|
+
record = {
|
|
510
|
+
schemaVersion: MIGRATION_SCHEMA_VERSION, migrationId: plan.migrationId, home,
|
|
511
|
+
status: 'running', phase: 'backup', startedAt: stamp(), steps: {}, backup: null,
|
|
512
|
+
};
|
|
513
|
+
persistRecord(record);
|
|
514
|
+
}
|
|
515
|
+
const backupDir = options.backupDir ? path.resolve(options.backupDir) : toAbs(home, plan.backupDir);
|
|
516
|
+
|
|
517
|
+
// 1) 整体备份元数据(幂等:已确认则复用既有 manifest)
|
|
518
|
+
if (!record.backup || record.backup.status !== 'confirmed') {
|
|
519
|
+
writeBackupManifest(home, backupDir, plan);
|
|
520
|
+
record.backup = { dir: backupDir, status: 'confirmed', at: stamp() };
|
|
521
|
+
persistRecord(record);
|
|
522
|
+
}
|
|
523
|
+
const manifest = consent.readJson(path.join(backupDir, 'manifest.json'));
|
|
524
|
+
if (!manifest || !manifest.files) throw new Error('备份元数据缺失(manifest.json),拒绝执行');
|
|
525
|
+
|
|
526
|
+
// 2) 逐步「记录意图 → 执行 → 回读确认」
|
|
527
|
+
record.phase = 'migrate';
|
|
528
|
+
persistRecord(record);
|
|
529
|
+
const report = { migrationId: plan.migrationId, status: 'done', quota: null, steps: [], consentUnchanged: true };
|
|
530
|
+
const deferred = [];
|
|
531
|
+
let legacyUsed = dirBytes(toAbs(home, 'data/legacy-pending'));
|
|
532
|
+
for (const step of plan.steps) {
|
|
533
|
+
const prev = record.steps[step.id];
|
|
534
|
+
if (prev && prev.status === 'confirmed') {
|
|
535
|
+
if (isLegacyPendingStep(step)) legacyUsed += prev.bytes || 0;
|
|
536
|
+
report.steps.push({ id: step.id, status: 'confirmed', resumed: true });
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
if (step.mode === 'keep') {
|
|
540
|
+
record.steps[step.id] = { status: 'kept', note: step.note || null, blocked: !!step.blocked, at: stamp() };
|
|
541
|
+
persistRecord(record);
|
|
542
|
+
report.steps.push({ id: step.id, status: 'kept', blocked: !!step.blocked });
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (isLegacyPendingStep(step) && legacyUsed + (step.bytes || 0) > budget) {
|
|
546
|
+
deferred.push(step.id);
|
|
547
|
+
record.steps[step.id] = { status: 'deferred-quota', bytes: step.bytes || 0, at: stamp() };
|
|
548
|
+
persistRecord(record);
|
|
549
|
+
report.quota = { budgetBytes: budget, usedBytes: legacyUsed, deferredSteps: [...deferred] };
|
|
550
|
+
report.steps.push({ id: step.id, status: 'deferred-quota' });
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
record.steps[step.id] = {
|
|
554
|
+
status: 'intended', from: step.from, to: step.to,
|
|
555
|
+
fileCount: step.fileCount, bytes: step.bytes || 0, at: stamp(),
|
|
556
|
+
};
|
|
557
|
+
persistRecord(record); // 先落意图
|
|
558
|
+
let results;
|
|
559
|
+
try {
|
|
560
|
+
results = executeStep(home, step, manifest, backupDir, { forceCopy: !!options.forceCopy });
|
|
561
|
+
} catch (error) {
|
|
562
|
+
const message = String(error && error.message ? error.message : error);
|
|
563
|
+
record.steps[step.id] = { ...record.steps[step.id], status: 'pending', error: message };
|
|
564
|
+
record.status = 'interrupted';
|
|
565
|
+
persistRecord(record);
|
|
566
|
+
report.status = 'interrupted';
|
|
567
|
+
report.error = message;
|
|
568
|
+
return report;
|
|
569
|
+
}
|
|
570
|
+
record.steps[step.id] = {
|
|
571
|
+
status: 'confirmed', from: step.from, to: step.to, bytes: step.bytes || 0,
|
|
572
|
+
files: results, confirmedAt: stamp(),
|
|
573
|
+
};
|
|
574
|
+
persistRecord(record); // 回读确认后落账
|
|
575
|
+
if (isLegacyPendingStep(step)) legacyUsed += step.bytes || 0;
|
|
576
|
+
report.steps.push({ id: step.id, status: 'confirmed', files: results.length });
|
|
577
|
+
}
|
|
578
|
+
if (deferred.length) {
|
|
579
|
+
report.quota = { ...report.quota, note: 'legacy-pending 预算不足:超额步骤已递延并保留原位,未强行迁移(§6)' };
|
|
580
|
+
}
|
|
581
|
+
// 收尾:清理已搬空的源目录(只删空目录);记录终态
|
|
582
|
+
for (const dir of [...new Set(plan.steps.filter((s) => s.mode === 'move' && s.sourceDir).map((s) => s.sourceDir))]) {
|
|
583
|
+
pruneEmptyDirs(toAbs(home, dir));
|
|
584
|
+
}
|
|
585
|
+
record.status = 'done';
|
|
586
|
+
record.phase = 'done';
|
|
587
|
+
record.finishedAt = stamp();
|
|
588
|
+
persistRecord(record);
|
|
589
|
+
return report;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// CLI 入口:存在未完成迁移时复用其 migrationId 续跑(幂等),否则生成新计划
|
|
593
|
+
function runLegacyApply(options = {}) {
|
|
594
|
+
const existing = loadMigrationRecord();
|
|
595
|
+
const migrationId = existing && existing.status !== 'done' ? existing.migrationId : null;
|
|
596
|
+
const plan = planDataMigration({ ...options, migrationId });
|
|
597
|
+
return applyDataMigration(plan, options);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// ---- 存量补发(legacy release:隔离队列移回活动队列,由常规 flush 走分端点外发)----
|
|
601
|
+
|
|
602
|
+
const RELEASE_SCHEMA_VERSION = 1;
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* data/legacy-pending 各子目录 → 活动队列映射。ext 为目标队列的消费命名约定:
|
|
606
|
+
* code 队列只读顶层 *.jsonl、events 队列只读顶层 *.json(diagnostics/dead-letter
|
|
607
|
+
* 本就沿用诊断/死信命名,不换名)。grant 为移回前复核的事件类型授权。
|
|
608
|
+
*/
|
|
609
|
+
const RELEASE_DIRS = [
|
|
610
|
+
{ id: 'code', from: 'data/legacy-pending/code', to: 'data/code', grant: 'codeMetrics', ext: '.jsonl' },
|
|
611
|
+
{ id: 'events', from: 'data/legacy-pending/events', to: 'data/events', grant: 'promptContent', ext: '.json' },
|
|
612
|
+
{ id: 'diagnostics', from: 'data/legacy-pending/diagnostics', to: 'data/diagnostics', grant: 'promptContent', ext: null },
|
|
613
|
+
{ id: 'dead-letter', from: 'data/legacy-pending/dead-letter', to: 'data/events/dead-letter', grant: 'promptContent', ext: null },
|
|
614
|
+
];
|
|
615
|
+
|
|
616
|
+
function legacyReleaseLedgerFile() { return path.join(paths.stateDir(), 'legacy-release.json'); }
|
|
617
|
+
|
|
618
|
+
/** 按目标队列消费命名放行:.json → .jsonl 换尾、其余补尾;已是目标尾或无约定保持原名。 */
|
|
619
|
+
function releaseFileName(name, ext) {
|
|
620
|
+
if (!ext || name.endsWith(ext)) return name;
|
|
621
|
+
if (ext === '.jsonl' && name.endsWith('.json')) return name.slice(0, -'.json'.length) + ext;
|
|
622
|
+
return name + ext;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** 目标名冲突避让:目标已存在或本轮已被占用时加 -rN 后缀(N 从 1 递增)。 */
|
|
626
|
+
function claimTargetName(targetDirAbs, relDir, wanted, claimed) {
|
|
627
|
+
const taken = (name) => claimed.has(relDir ? `${relDir}/${name}` : name)
|
|
628
|
+
|| existsFileSync(path.join(targetDirAbs, relDir, name));
|
|
629
|
+
if (!taken(wanted)) {
|
|
630
|
+
claimed.add(relDir ? `${relDir}/${wanted}` : wanted);
|
|
631
|
+
return wanted;
|
|
632
|
+
}
|
|
633
|
+
const dot = wanted.lastIndexOf('.');
|
|
634
|
+
const base = dot > 0 ? wanted.slice(0, dot) : wanted;
|
|
635
|
+
const suffix = dot > 0 ? wanted.slice(dot) : '';
|
|
636
|
+
for (let n = 1; ; n += 1) {
|
|
637
|
+
const candidate = `${base}-r${n}${suffix}`;
|
|
638
|
+
if (!taken(candidate)) {
|
|
639
|
+
claimed.add(relDir ? `${relDir}/${candidate}` : candidate);
|
|
640
|
+
return candidate;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** 移动单文件(跨文件系统退化为复制),移后按 sha256 回读确认;瞬时占用退避重试一次。 */
|
|
646
|
+
function releaseMoveFile(home, fromRel, toRel) {
|
|
647
|
+
const srcAbs = toAbs(home, fromRel);
|
|
648
|
+
const dstAbs = toAbs(home, toRel);
|
|
649
|
+
const sha = sha256File(srcAbs);
|
|
650
|
+
fs.mkdirSync(path.dirname(dstAbs), { recursive: true }); // Windows:目标父目录缺失时 rename 报 ENOENT
|
|
651
|
+
const attempt = () => {
|
|
652
|
+
try {
|
|
653
|
+
fs.renameSync(srcAbs, dstAbs);
|
|
654
|
+
} catch (error) {
|
|
655
|
+
if (!error || (error.code !== 'EXDEV' && error.code !== 'ENOTSUP')) throw error;
|
|
656
|
+
fs.copyFileSync(srcAbs, dstAbs); // 跨文件系统:复制 + 摘要校验后再删源(§5 手法)
|
|
657
|
+
fs.rmSync(srcAbs, { force: true });
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
try {
|
|
661
|
+
attempt();
|
|
662
|
+
} catch (first) {
|
|
663
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 250); // E-SafeNet 瞬时占用
|
|
664
|
+
attempt();
|
|
665
|
+
}
|
|
666
|
+
const st = statOrNull(dstAbs);
|
|
667
|
+
if (!st || !st.isFile() || sha256File(dstAbs) !== sha) throw new Error(`移回后校验失败:${toRel}`);
|
|
668
|
+
return { sha256: sha, bytes: st.size };
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* 存量补发(§6 隔离数据的授权放行):把 data/legacy-pending 下 code/events/
|
|
673
|
+
* diagnostics/dead-letter 的文件移回活动队列,随后由常规 flush 走分端点外发。
|
|
674
|
+
*
|
|
675
|
+
* - 授权复核:各子目录按事件类型(code→codeMetrics,其余→promptContent)检查
|
|
676
|
+
* 当前授权,未覆盖类型的文件保留隔离并计数(不因补发越权放行);
|
|
677
|
+
* - 命名放行:目标按队列消费约定换尾(.json→.jsonl 等),冲突加 -rN 后缀;
|
|
678
|
+
* - 账本:state/legacy-release.json 逐文件记 from→to→sha256(复用 migration.json 风格);
|
|
679
|
+
* - options.confirm !== true 时只读盘点(dry-run),不动任何文件。
|
|
680
|
+
*/
|
|
681
|
+
function runLegacyRelease(options = {}) {
|
|
682
|
+
const confirm = options.confirm === true;
|
|
683
|
+
const home = paths.home();
|
|
684
|
+
if (consent.isDisabled()) {
|
|
685
|
+
return { schemaVersion: RELEASE_SCHEMA_VERSION, home, status: 'blocked', error: '已停用(disable),存量补发被阻断' };
|
|
686
|
+
}
|
|
687
|
+
const grants = consent.loadConsent().grants;
|
|
688
|
+
const report = {
|
|
689
|
+
schemaVersion: RELEASE_SCHEMA_VERSION, home, confirm,
|
|
690
|
+
status: confirm ? 'released' : 'dry-run',
|
|
691
|
+
...(confirm ? {} : { confirmRequired: '需要 --confirm 显式确认(会把隔离队列移回活动队列)' }),
|
|
692
|
+
grants: { codeMetrics: grants.codeMetrics === true, promptContent: grants.promptContent === true },
|
|
693
|
+
dirs: [], released: [], retained: [], failed: [],
|
|
694
|
+
};
|
|
695
|
+
const ledgerEntries = [];
|
|
696
|
+
for (const dir of RELEASE_DIRS) {
|
|
697
|
+
const fromAbs = toAbs(home, dir.from);
|
|
698
|
+
const entry = {
|
|
699
|
+
id: dir.id, from: dir.from, to: dir.to, requiredGrant: dir.grant,
|
|
700
|
+
granted: grants[dir.grant] === true, files: 0, moved: 0, retained: 0, failed: 0,
|
|
701
|
+
};
|
|
702
|
+
if (isDirectory(fromAbs)) {
|
|
703
|
+
const files = walkFiles(fromAbs);
|
|
704
|
+
entry.files = files.length;
|
|
705
|
+
const claimed = new Set();
|
|
706
|
+
for (const file of files) {
|
|
707
|
+
const fromRel = `${dir.from}/${file.rel}`;
|
|
708
|
+
if (!entry.granted) {
|
|
709
|
+
entry.retained += 1;
|
|
710
|
+
report.retained.push({ from: fromRel, reason: `consent:${dir.grant}` });
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
if (!confirm) continue; // dry-run 只盘点不动文件
|
|
714
|
+
const relDir = path.posix.dirname(file.rel);
|
|
715
|
+
const parentRel = relDir === '.' ? '' : relDir;
|
|
716
|
+
const wanted = releaseFileName(path.posix.basename(file.rel), dir.ext);
|
|
717
|
+
const finalName = claimTargetName(toAbs(home, dir.to), parentRel, wanted, claimed);
|
|
718
|
+
const toRel = parentRel ? `${dir.to}/${parentRel}/${finalName}` : `${dir.to}/${finalName}`;
|
|
719
|
+
try {
|
|
720
|
+
const moved = releaseMoveFile(home, fromRel, toRel);
|
|
721
|
+
entry.moved += 1;
|
|
722
|
+
report.released.push({ from: fromRel, to: toRel, ...moved });
|
|
723
|
+
ledgerEntries.push({ from: fromRel, to: toRel, ...moved });
|
|
724
|
+
} catch (error) {
|
|
725
|
+
entry.failed += 1;
|
|
726
|
+
report.failed.push({ from: fromRel, error: String(error && error.message ? error.message : error) });
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
if (confirm && files.length > 0 && entry.moved === files.length) pruneEmptyDirs(fromAbs);
|
|
730
|
+
}
|
|
731
|
+
report.dirs.push(entry);
|
|
732
|
+
}
|
|
733
|
+
if (confirm) {
|
|
734
|
+
pruneEmptyDirs(toAbs(home, 'data/legacy-pending'));
|
|
735
|
+
if (ledgerEntries.length || report.failed.length) {
|
|
736
|
+
const ledgerFile = legacyReleaseLedgerFile();
|
|
737
|
+
const existing = consent.readJson(ledgerFile);
|
|
738
|
+
const runs = Array.isArray(existing && existing.runs) ? existing.runs : [];
|
|
739
|
+
runs.push({
|
|
740
|
+
runId: makeMigrationId(options.now === undefined ? Date.now() : options.now),
|
|
741
|
+
ranAt: stamp(),
|
|
742
|
+
released: ledgerEntries,
|
|
743
|
+
failed: report.failed,
|
|
744
|
+
});
|
|
745
|
+
consent.atomicWrite(ledgerFile, { schemaVersion: RELEASE_SCHEMA_VERSION, home, runs });
|
|
746
|
+
report.ledger = 'state/legacy-release.json';
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
if (!confirm) report.status = 'dry-run';
|
|
750
|
+
else if (report.released.length === 0 && report.failed.length === 0) report.status = 'nothing-to-release';
|
|
751
|
+
else if (report.failed.length > 0) report.status = 'partial';
|
|
752
|
+
else report.status = 'released';
|
|
753
|
+
return report;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
module.exports = {
|
|
757
|
+
MIGRATION_SCHEMA_VERSION, DEFAULT_LEGACY_PENDING_BUDGET_BYTES,
|
|
758
|
+
inspectLegacy, planDataMigration, applyDataMigration, runLegacyApply, loadMigrationRecord,
|
|
759
|
+
runLegacyRelease,
|
|
760
|
+
};
|