@jjh32456/longlive 2.1.0 → 2.3.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/CHANGELOG.md +108 -1
- package/QUICKSTART.md +7 -7
- package/README.en.md +13 -1
- package/README.md +26 -8
- package/SPEC.md +6 -5
- package/build-info.json +143 -73
- package/cordis.patch.yml +2 -0
- package/docs/ARCHITECTURE.md +6 -3
- package/docs/CONFIG.md +25 -1
- package/docs/FAQ.md +2 -2
- package/docs/FEATURES.md +125 -2
- package/docs/INDEX-FRESHNESS.md +8 -1
- package/docs/OPERATIONS.md +63 -2
- package/docs/QUICKSTART.md +2 -2
- package/docs/README.en.md +1 -1
- package/docs/TROUBLESHOOTING.md +1 -1
- package/package.json +10 -2
- package/scripts/assert-install.mjs +124 -0
- package/scripts/backlog-report.mjs +98 -0
- package/scripts/install-230.mjs +787 -0
- package/scripts/lib/eng-common.mjs +428 -0
- package/scripts/rebuild-index.mjs +148 -0
- package/scripts/restore-drill.mjs +351 -0
- package/scripts/run-autoresolve.mjs +123 -0
- package/scripts/watchdog-230.mjs +379 -0
- package/src/config.js +7 -0
- package/src/features.js +35 -0
- package/src/gate/action-gate.js +545 -0
- package/src/memory/backup-retention.mjs +823 -0
- package/src/memory/cards.js +73 -12
- package/src/memory/conflict-scan.mjs +356 -0
- package/src/memory/conflicts.js +202 -9
- package/src/memory/consolidate.js +537 -35
- package/src/memory/decay.js +133 -19
- package/src/memory/event-index.js +62 -4
- package/src/memory/forget-scheduler.mjs +303 -0
- package/src/memory/forget-v2.js +94 -8
- package/src/memory/index-cache.mjs +216 -0
- package/src/memory/index.js +179 -16
- package/src/memory/lock.js +53 -12
- package/src/memory/maintenance.js +295 -19
- package/src/memory/recall-feedback.mjs +159 -17
- package/src/memory/recall-v2.js +5 -3
- package/src/memory/recall.js +10 -4
- package/src/memory/state.js +446 -38
- package/src/memory/task-state.mjs +569 -0
- package/src/recall/brain.mjs +55 -6
- package/src/recall/continuity-volatile.mjs +195 -1
- package/src/recall/index.js +8 -0
- package/src/tools.js +141 -21
- package/src/ui/routes-readonly.js +63 -5
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
// scripts/lib/eng-common.mjs — 2.3.0 / W6 工程化公共件(安装链、看门狗、演练共用)。
|
|
2
|
+
//
|
|
3
|
+
// 只依赖 Node 内置;不引入第三方包。四条硬约束:
|
|
4
|
+
// 1. 无本机绝对路径:本文件与调用方不得出现盘符/家目录/用户名常量(普适性);
|
|
5
|
+
// 2. 日志脱敏:maskText() 默认把绝对路径/家目录/邮箱/凭据换成占位符(隐私性);
|
|
6
|
+
// 3. tgz 读写自持:ustar 写 + pax/gnu 读,供夹具(测试合成包)与安装校验共用;
|
|
7
|
+
// 4. 失败不吞:所有异常带 code(E_*),调用方 fail-closed。
|
|
8
|
+
//
|
|
9
|
+
// 被 scripts/install-230.mjs、scripts/watchdog-230.mjs、scripts/install-drill-230.mjs
|
|
10
|
+
// 以相对 import 引用;随包文件见 package.json files 白名单。
|
|
11
|
+
|
|
12
|
+
import { spawnSync } from 'node:child_process';
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import zlib from 'node:zlib';
|
|
17
|
+
|
|
18
|
+
export const ENGINE = { name: 'longlive-eng', version: '2.3.0-w6' };
|
|
19
|
+
|
|
20
|
+
const TAR_BLOCK = 512;
|
|
21
|
+
const ZERO_BLOCK = Buffer.alloc(TAR_BLOCK, 0);
|
|
22
|
+
const PAX_PATH = 'path';
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
// 基础工具
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
export function sha256(data) {
|
|
29
|
+
return createHash('sha256').update(data).digest('hex');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function sha256File(file) {
|
|
33
|
+
return sha256(fs.readFileSync(file));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function ensureDir(dir) {
|
|
37
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
38
|
+
return dir;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function exists(file) {
|
|
42
|
+
try {
|
|
43
|
+
fs.statSync(file);
|
|
44
|
+
return true;
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function codedError(code, message) {
|
|
51
|
+
const error = new Error(message);
|
|
52
|
+
error.code = code;
|
|
53
|
+
return error;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function readJsonFile(file) {
|
|
57
|
+
let text;
|
|
58
|
+
try {
|
|
59
|
+
text = fs.readFileSync(file, 'utf8');
|
|
60
|
+
} catch (error) {
|
|
61
|
+
throw codedError('E_JSON_READ', `cannot read ${path.basename(file)}: ${error.code ?? error.message}`);
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
return JSON.parse(text);
|
|
65
|
+
} catch {
|
|
66
|
+
throw codedError('E_JSON_PARSE', `invalid JSON: ${path.basename(file)}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function writeJsonAtomic(file, value) {
|
|
71
|
+
ensureDir(path.dirname(file));
|
|
72
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now().toString(36)}`;
|
|
73
|
+
fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
74
|
+
fs.renameSync(tmp, file);
|
|
75
|
+
return file;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function writeTextAtomic(file, text) {
|
|
79
|
+
ensureDir(path.dirname(file));
|
|
80
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now().toString(36)}`;
|
|
81
|
+
fs.writeFileSync(tmp, text, 'utf8');
|
|
82
|
+
fs.renameSync(tmp, file);
|
|
83
|
+
return file;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function stampNow(now = new Date()) {
|
|
87
|
+
const pad = (value, width = 2) => String(value).padStart(width, '0');
|
|
88
|
+
return (
|
|
89
|
+
`${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}-` +
|
|
90
|
+
`${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}-` +
|
|
91
|
+
`${pad(now.getUTCMilliseconds(), 3)}`
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function escapeRegExp(text) {
|
|
96
|
+
return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function sumBytes(entries) {
|
|
100
|
+
return entries.reduce((total, entry) => total + entry.bytes.length, 0);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// 脱敏(隐私门):绝对路径 / 家目录 / 邮箱 / 凭据一律占位
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
const MASK_RULES = [
|
|
108
|
+
{ name: 'private-key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, to: '<private-key>' },
|
|
109
|
+
{ name: 'token', re: /\b(?:sk|ghp|gho|github_pat|xoxb|xoxp)-[A-Za-z0-9_]{16,}\b/g, to: '<token>' },
|
|
110
|
+
{ name: 'email', re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, to: '<email>' },
|
|
111
|
+
{ name: 'password-assignment', re: /\bpassword\s*[:=]\s*\S+/gi, to: 'password=<masked>' },
|
|
112
|
+
// Windows 绝对路径(含盘符);UNC 与 file:/// 形式先于裸盘符处理
|
|
113
|
+
{ name: 'file-url', re: /file:\/\/\/[^\s"'`<>|,;]*/gi, to: 'file:///<abs-path>' },
|
|
114
|
+
{ name: 'unc-path', re: /\\\\[A-Za-z0-9_.$-]+\\[^\s"'`<>|,;]*/g, to: '<abs-path>' },
|
|
115
|
+
// 盘符必须出现在词边界(不能吞掉 http:// 里的 "p:/"),否则会把 URL 误脱敏成 "htt<abs-path>"
|
|
116
|
+
{ name: 'drive-letter', re: /(?<![A-Za-z0-9])[A-Za-z]:[\\/][^\s"'`<>|,;]*/g, to: '<abs-path>' },
|
|
117
|
+
// POSIX 绝对路径(/home /Users /tmp /var /opt /usr /etc /private)
|
|
118
|
+
{ name: 'posix-home', re: /\/(?:Users|home)\/[A-Za-z0-9._-]+(?:\/[^\s"'`<>|,;]*)?/gi, to: '<abs-path>' },
|
|
119
|
+
{ name: 'posix-tmp', re: /\/(?:tmp|var|opt|usr|etc|private)\/[^\s"'`<>|,;]*/g, to: '<abs-path>' },
|
|
120
|
+
];
|
|
121
|
+
|
|
122
|
+
export const PRIVACY_PATTERN_NAMES = MASK_RULES.map((rule) => rule.name);
|
|
123
|
+
|
|
124
|
+
// maskText(text, { roots }) —— roots 是调用方已知的绝对路径根(如 profile、tgz 所在目录、
|
|
125
|
+
// 演练临时树),先按根替换成 `placeholder`,再走通用规则;保证不泄漏本机目录结构。
|
|
126
|
+
export function maskText(text, options = {}) {
|
|
127
|
+
let out = String(text ?? '');
|
|
128
|
+
const roots = Array.isArray(options.roots) ? options.roots.filter(Boolean) : [];
|
|
129
|
+
const sorted = [...roots].sort((a, b) => {
|
|
130
|
+
const left = typeof a === 'string' ? a.length : a?.path?.length ?? 0;
|
|
131
|
+
const right = typeof b === 'string' ? b.length : b?.path?.length ?? 0;
|
|
132
|
+
return right - left;
|
|
133
|
+
});
|
|
134
|
+
for (const item of sorted) {
|
|
135
|
+
const root = typeof item === 'string' ? { path: item, placeholder: '<abs-path>' } : item;
|
|
136
|
+
if (!root?.path) continue;
|
|
137
|
+
const placeholder = root.placeholder || '<abs-path>';
|
|
138
|
+
const variants = new Set([
|
|
139
|
+
root.path,
|
|
140
|
+
root.path.replace(/\\/g, '/'),
|
|
141
|
+
root.path.replace(/\//g, '\\'),
|
|
142
|
+
]);
|
|
143
|
+
for (const variant of variants) {
|
|
144
|
+
if (!variant) continue;
|
|
145
|
+
out = out.replace(new RegExp(escapeRegExp(variant), 'gi'), placeholder);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
for (const rule of MASK_RULES) {
|
|
149
|
+
rule.re.lastIndex = 0;
|
|
150
|
+
out = out.replace(rule.re, rule.to);
|
|
151
|
+
rule.re.lastIndex = 0;
|
|
152
|
+
}
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// privacyScan(text) —— 交付前隐私自检:只回报命中的规则名(不回传样本,避免二次泄漏)。
|
|
157
|
+
export function privacyScan(text) {
|
|
158
|
+
const src = String(text ?? '');
|
|
159
|
+
const hits = [];
|
|
160
|
+
for (const rule of MASK_RULES) {
|
|
161
|
+
rule.re.lastIndex = 0;
|
|
162
|
+
if (rule.re.test(src)) hits.push(rule.name);
|
|
163
|
+
rule.re.lastIndex = 0;
|
|
164
|
+
}
|
|
165
|
+
return { clean: hits.length === 0, hits };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function assertNoPrivacyLeak(text, label = 'output') {
|
|
169
|
+
const scan = privacyScan(text);
|
|
170
|
+
if (!scan.clean) throw codedError('E_PRIVACY', `${label} leaks machine paths: ${scan.hits.join(',')}`);
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
// 进程调用
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
export function runProcess(command, args, options = {}) {
|
|
179
|
+
const started = Date.now();
|
|
180
|
+
const result = spawnSync(command, args, {
|
|
181
|
+
cwd: options.cwd,
|
|
182
|
+
env: { ...process.env, ...(options.env || {}) },
|
|
183
|
+
encoding: 'utf8',
|
|
184
|
+
windowsHide: true,
|
|
185
|
+
timeout: options.timeoutMs ?? 600_000,
|
|
186
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
187
|
+
shell: false,
|
|
188
|
+
});
|
|
189
|
+
const ms = Date.now() - started;
|
|
190
|
+
const stdout = result.stdout ?? '';
|
|
191
|
+
const stderr = result.stderr ?? '';
|
|
192
|
+
const code = typeof result.status === 'number' ? result.status : result.error ? 1 : 0;
|
|
193
|
+
return {
|
|
194
|
+
ok: code === 0,
|
|
195
|
+
code,
|
|
196
|
+
signal: result.signal ?? null,
|
|
197
|
+
stdout,
|
|
198
|
+
stderr,
|
|
199
|
+
ms,
|
|
200
|
+
error: result.error ? String(result.error.code ?? result.error.message) : null,
|
|
201
|
+
timedOut: Boolean(result.error && result.error.code === 'ETIMEDOUT'),
|
|
202
|
+
command,
|
|
203
|
+
args,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ---------------------------------------------------------------------------
|
|
208
|
+
// pnpm 发现(不硬编码本机路径)
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
|
|
211
|
+
// 返回 { kind: 'node-cli', node, cli } | { kind: 'bin', command } | null
|
|
212
|
+
export function discoverPnpm(options = {}) {
|
|
213
|
+
const explicit = options.explicit ?? process.env.DSH_LONGLIVE_PNPM ?? null;
|
|
214
|
+
const resolved = explicit ? resolvePnpmCandidate(explicit) : null;
|
|
215
|
+
if (resolved) return resolved;
|
|
216
|
+
|
|
217
|
+
const start = path.dirname(options.nodePath ?? process.execPath);
|
|
218
|
+
let dir = start;
|
|
219
|
+
for (let depth = 0; depth < 6; depth += 1) {
|
|
220
|
+
for (const relative of [
|
|
221
|
+
path.join('pnpm', 'bin', 'pnpm.cjs'),
|
|
222
|
+
path.join('pnpm', 'bin', 'pnpm.js'),
|
|
223
|
+
path.join('node_modules', 'pnpm', 'bin', 'pnpm.cjs'),
|
|
224
|
+
]) {
|
|
225
|
+
const candidate = path.join(dir, relative);
|
|
226
|
+
if (exists(candidate)) return { kind: 'node-cli', node: process.execPath, cli: candidate };
|
|
227
|
+
}
|
|
228
|
+
const parent = path.dirname(dir);
|
|
229
|
+
if (parent === dir) break;
|
|
230
|
+
dir = parent;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const pathEntries = String(process.env.PATH ?? '').split(path.delimiter).filter(Boolean);
|
|
234
|
+
for (const entry of pathEntries) {
|
|
235
|
+
for (const name of ['pnpm.cmd', 'pnpm.exe', 'pnpm']) {
|
|
236
|
+
const candidate = path.join(entry, name);
|
|
237
|
+
if (exists(candidate)) return { kind: 'bin', command: candidate };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function resolvePnpmCandidate(file) {
|
|
244
|
+
if (!file) return null;
|
|
245
|
+
const abs = path.resolve(file);
|
|
246
|
+
if (!exists(abs)) return null;
|
|
247
|
+
if (/\.(?:cjs|mjs|js)$/i.test(abs)) return { kind: 'node-cli', node: process.execPath, cli: abs };
|
|
248
|
+
return { kind: 'bin', command: abs };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export function pnpmInvocation(pnpm, args) {
|
|
252
|
+
if (!pnpm) throw codedError('E_PNPM', 'pnpm not found (pass --pnpm or set DSH_LONGLIVE_PNPM)');
|
|
253
|
+
if (pnpm.kind === 'node-cli') return { command: pnpm.node, args: [pnpm.cli, ...args] };
|
|
254
|
+
return { command: pnpm.command, args };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function describePnpm(pnpm) {
|
|
258
|
+
if (!pnpm) return null;
|
|
259
|
+
return pnpm.kind === 'node-cli' ? '<node>/pnpm/bin/pnpm.cjs' : '<pnpm>';
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ---------------------------------------------------------------------------
|
|
263
|
+
// tgz 读写(ustar 写 + pax/gnu 读)
|
|
264
|
+
// ---------------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
function octal(value, width) {
|
|
267
|
+
const text = Number(value).toString(8);
|
|
268
|
+
return `${text.padStart(width - 1, '0')}\0`;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function splitUstarName(rel) {
|
|
272
|
+
const bytes = Buffer.byteLength(rel);
|
|
273
|
+
if (bytes <= 100) return { name: rel, prefix: '' };
|
|
274
|
+
for (let index = rel.length - 1; index > 0; index -= 1) {
|
|
275
|
+
if (rel[index] !== '/') continue;
|
|
276
|
+
const prefix = rel.slice(0, index);
|
|
277
|
+
const name = rel.slice(index + 1);
|
|
278
|
+
if (Buffer.byteLength(name) > 100) continue;
|
|
279
|
+
if (Buffer.byteLength(prefix) > 155) break;
|
|
280
|
+
return { name, prefix };
|
|
281
|
+
}
|
|
282
|
+
throw codedError('E_TAR_NAME', `path too long for ustar: ${rel.slice(0, 64)}...`);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function tarHeader(rel, size, mtimeMs, mode) {
|
|
286
|
+
const { name, prefix } = splitUstarName(rel);
|
|
287
|
+
const header = Buffer.alloc(TAR_BLOCK, 0);
|
|
288
|
+
header.write(name, 0, 100, 'utf8');
|
|
289
|
+
header.write(octal(mode ?? 0o644, 8), 100, 8, 'ascii');
|
|
290
|
+
header.write(octal(0, 8), 108, 8, 'ascii'); // uid
|
|
291
|
+
header.write(octal(0, 8), 116, 8, 'ascii'); // gid
|
|
292
|
+
header.write(octal(size, 12), 124, 12, 'ascii');
|
|
293
|
+
header.write(octal(Math.floor((mtimeMs ?? Date.now()) / 1000), 12), 136, 12, 'ascii');
|
|
294
|
+
header.write(' ', 148, 8, 'ascii'); // checksum placeholder
|
|
295
|
+
header.write('0', 156, 1, 'ascii'); // typeflag = regular file
|
|
296
|
+
header.write('ustar\0', 257, 6, 'ascii');
|
|
297
|
+
header.write('00', 263, 2, 'ascii');
|
|
298
|
+
header.write('root', 265, 32, 'ascii');
|
|
299
|
+
header.write('root', 297, 32, 'ascii');
|
|
300
|
+
if (prefix) header.write(prefix, 345, 155, 'utf8');
|
|
301
|
+
let checksum = 0;
|
|
302
|
+
for (const byte of header) checksum += byte;
|
|
303
|
+
header.write(`${checksum.toString(8).padStart(6, '0')}\0 `, 148, 8, 'ascii');
|
|
304
|
+
return header;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// tarFromEntries([{ path, bytes, mode?, mtimeMs? }]) -> Buffer(未压缩 tar)
|
|
308
|
+
export function tarFromEntries(entries) {
|
|
309
|
+
const chunks = [];
|
|
310
|
+
for (const entry of entries) {
|
|
311
|
+
const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(String(entry.bytes ?? ''), 'utf8');
|
|
312
|
+
const rel = String(entry.path ?? '').replace(/\\/g, '/').replace(/^\/+/, '');
|
|
313
|
+
if (!rel) throw codedError('E_TAR_PATH', 'empty tar entry path');
|
|
314
|
+
chunks.push(tarHeader(rel, bytes.length, entry.mtimeMs, entry.mode));
|
|
315
|
+
chunks.push(bytes);
|
|
316
|
+
const pad = (TAR_BLOCK - (bytes.length % TAR_BLOCK)) % TAR_BLOCK;
|
|
317
|
+
if (pad > 0) chunks.push(Buffer.alloc(pad, 0));
|
|
318
|
+
}
|
|
319
|
+
chunks.push(ZERO_BLOCK, ZERO_BLOCK);
|
|
320
|
+
return Buffer.concat(chunks);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export function makeTgz(entries, options = {}) {
|
|
324
|
+
return zlib.gzipSync(tarFromEntries(entries), { level: options.level ?? 9 });
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function parseOctal(buffer) {
|
|
328
|
+
const text = buffer.toString('ascii').replace(/\0.*$/, '').trim();
|
|
329
|
+
if (!text) return 0;
|
|
330
|
+
const value = Number.parseInt(text, 8);
|
|
331
|
+
return Number.isFinite(value) ? value : 0;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function parsePaxRecords(body) {
|
|
335
|
+
const records = {};
|
|
336
|
+
let offset = 0;
|
|
337
|
+
while (offset < body.length) {
|
|
338
|
+
const space = body.indexOf(0x20, offset);
|
|
339
|
+
if (space < 0) break;
|
|
340
|
+
const length = Number.parseInt(body.subarray(offset, space).toString('ascii'), 10);
|
|
341
|
+
if (!Number.isFinite(length) || length <= 0 || offset + length > body.length) break;
|
|
342
|
+
const record = body.subarray(space + 1, offset + length - 1).toString('utf8');
|
|
343
|
+
const eq = record.indexOf('=');
|
|
344
|
+
if (eq > 0) records[record.slice(0, eq)] = record.slice(eq + 1);
|
|
345
|
+
offset += length;
|
|
346
|
+
}
|
|
347
|
+
return records;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// parseTgz(buffer) -> [{ path, bytes }](仅普通文件;pax/gnu 长名已展开)
|
|
351
|
+
export function parseTgz(buffer) {
|
|
352
|
+
let tar;
|
|
353
|
+
try {
|
|
354
|
+
tar = zlib.gunzipSync(buffer);
|
|
355
|
+
} catch (error) {
|
|
356
|
+
throw codedError('E_TGZ', `not a gzip stream: ${error.code ?? error.message}`);
|
|
357
|
+
}
|
|
358
|
+
const files = [];
|
|
359
|
+
let offset = 0;
|
|
360
|
+
let pax = null;
|
|
361
|
+
let pendingName = null;
|
|
362
|
+
while (offset + TAR_BLOCK <= tar.length) {
|
|
363
|
+
const header = tar.subarray(offset, offset + TAR_BLOCK);
|
|
364
|
+
if (header.equals(ZERO_BLOCK)) break;
|
|
365
|
+
const name = header.toString('utf8', 0, 100).replace(/\0.*$/, '');
|
|
366
|
+
const size = parseOctal(header.subarray(124, 136));
|
|
367
|
+
const type = header.toString('ascii', 156, 157);
|
|
368
|
+
const prefix = header.toString('utf8', 345, 500).replace(/\0.*$/, '');
|
|
369
|
+
const fullName = pendingName || (prefix ? `${prefix}/${name}` : name);
|
|
370
|
+
const bodyStart = offset + TAR_BLOCK;
|
|
371
|
+
const body = tar.subarray(bodyStart, bodyStart + size);
|
|
372
|
+
if (body.length !== size) throw codedError('E_TGZ', `truncated tar entry: ${fullName.slice(0, 80)}`);
|
|
373
|
+
const next = bodyStart + size + ((TAR_BLOCK - (size % TAR_BLOCK)) % TAR_BLOCK);
|
|
374
|
+
if (type === 'x') {
|
|
375
|
+
pax = { ...parsePaxRecords(body) };
|
|
376
|
+
offset = next;
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
if (type === 'g') {
|
|
380
|
+
offset = next;
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
if (type === 'L') {
|
|
384
|
+
pendingName = body.toString('utf8').replace(/\0.*$/, '');
|
|
385
|
+
offset = next;
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
const entryPath = (pax && pax[PAX_PATH]) || pendingName || fullName;
|
|
389
|
+
pax = null;
|
|
390
|
+
pendingName = null;
|
|
391
|
+
offset = next;
|
|
392
|
+
if (type === '0' || type === '\0' || type === '') {
|
|
393
|
+
files.push({ path: entryPath, bytes: Buffer.from(body) });
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return files;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export function readTgzFile(file) {
|
|
400
|
+
let buffer;
|
|
401
|
+
try {
|
|
402
|
+
buffer = fs.readFileSync(file);
|
|
403
|
+
} catch (error) {
|
|
404
|
+
throw codedError('E_TGZ_READ', `cannot read tgz: ${error.code ?? error.message}`);
|
|
405
|
+
}
|
|
406
|
+
const entries = parseTgz(buffer);
|
|
407
|
+
return {
|
|
408
|
+
bytes: buffer.length,
|
|
409
|
+
sha256: sha256(buffer),
|
|
410
|
+
entries,
|
|
411
|
+
byPath: new Map(entries.map((entry) => [entry.path, entry.bytes])),
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ---------------------------------------------------------------------------
|
|
416
|
+
// 小工具
|
|
417
|
+
// ---------------------------------------------------------------------------
|
|
418
|
+
|
|
419
|
+
export function isMainModule(importMetaUrl, argv = process.argv) {
|
|
420
|
+
if (!argv[1]) return false;
|
|
421
|
+
try {
|
|
422
|
+
const selfPath = new URL(importMetaUrl).pathname;
|
|
423
|
+
const normalized = process.platform === 'win32' ? selfPath.replace(/^\/([A-Za-z]:)/, '$1') : selfPath;
|
|
424
|
+
return path.resolve(argv[1]) === path.resolve(decodeURIComponent(normalized));
|
|
425
|
+
} catch {
|
|
426
|
+
return false;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// scripts/rebuild-index.mjs — 手动全量重建索引(INDEX.md + 会话事件索引 events.db)。
|
|
3
|
+
//
|
|
4
|
+
// node scripts/rebuild-index.mjs --memory-root <dir> [--apply] [--json]
|
|
5
|
+
// [--skip-events] [--events-only]
|
|
6
|
+
// [--force] [--session-root <dir> ...]
|
|
7
|
+
//
|
|
8
|
+
// 重建时机(2.3.0 W3 ⑥):
|
|
9
|
+
// - 启动 / 手动全量:本脚本。INDEX 用 `full:true` 绕过 mtime 缓存整份重扫;
|
|
10
|
+
// 事件索引用 `rebuild:true` 从 L0 会话日志全量重建。
|
|
11
|
+
// - 日常刷新:capture 后走 `refreshIndexAfterCapture`(ifChanged,只读变化文件),
|
|
12
|
+
// 不碰本脚本,也不再每次启动扫全库。
|
|
13
|
+
//
|
|
14
|
+
// 默认 dry-run:只报告“会重建什么”,`--apply` 才落盘。`--force` 让 INDEX 即使
|
|
15
|
+
// 生成段内容没变也重写(刷新生成时间戳;平时不需要——F5 幂等口径)。
|
|
16
|
+
|
|
17
|
+
import { memoryIndex } from '../src/memory/index.js';
|
|
18
|
+
import { buildIndexFromSessions, discoverSessionLogs } from '../src/memory/event-index.js';
|
|
19
|
+
import { getIndexFreshness } from '../src/memory/index-freshness.js';
|
|
20
|
+
|
|
21
|
+
function flagValues(argv, name) {
|
|
22
|
+
const out = [];
|
|
23
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
24
|
+
if (argv[i] === name && argv[i + 1] && !argv[i + 1].startsWith('--')) out.push(argv[i + 1]);
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function arg(argv, name) {
|
|
30
|
+
const values = flagValues(argv, name);
|
|
31
|
+
return values.length > 0 ? values[0] : '';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const argv = process.argv.slice(2);
|
|
35
|
+
const memoryRoot = arg(argv, '--memory-root');
|
|
36
|
+
if (memoryRoot === '') {
|
|
37
|
+
console.error('[rebuild-index] --memory-root is required');
|
|
38
|
+
process.exit(2);
|
|
39
|
+
}
|
|
40
|
+
const apply = argv.includes('--apply');
|
|
41
|
+
const force = argv.includes('--force');
|
|
42
|
+
const skipEvents = argv.includes('--skip-events');
|
|
43
|
+
const eventsOnly = argv.includes('--events-only');
|
|
44
|
+
const sessionRoots = flagValues(argv, '--session-root');
|
|
45
|
+
const json = argv.includes('--json');
|
|
46
|
+
|
|
47
|
+
const startedAt = Date.now();
|
|
48
|
+
const report = {
|
|
49
|
+
ok: true,
|
|
50
|
+
memoryRoot,
|
|
51
|
+
apply,
|
|
52
|
+
mode: apply ? 'apply' : 'dry-run',
|
|
53
|
+
startedAt: new Date(startedAt).toISOString(),
|
|
54
|
+
steps: [],
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
if (!eventsOnly) {
|
|
59
|
+
const indexArgs = { full: true, ...(apply ? { apply: true } : {}), ...(force ? { ifChanged: false } : {}) };
|
|
60
|
+
const indexResult = memoryIndex(indexArgs, { memoryRoot });
|
|
61
|
+
report.steps.push({
|
|
62
|
+
name: 'index',
|
|
63
|
+
ok: indexResult.ok !== false,
|
|
64
|
+
status: indexResult.status,
|
|
65
|
+
cards: indexResult.cards,
|
|
66
|
+
procedures: indexResult.procedures,
|
|
67
|
+
changed: indexResult.changed,
|
|
68
|
+
contentChanged: indexResult.contentChanged,
|
|
69
|
+
applied: indexResult.applied === true,
|
|
70
|
+
read: indexResult.scan?.filesRead ?? null,
|
|
71
|
+
reused: indexResult.scan?.filesReused ?? null,
|
|
72
|
+
removed: indexResult.scan?.filesRemoved ?? null,
|
|
73
|
+
dataThroughAt: indexResult.scan?.dataThroughAt ?? null,
|
|
74
|
+
indexHash: indexResult.indexHash ?? null,
|
|
75
|
+
});
|
|
76
|
+
if (indexResult.ok === false) report.ok = false;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (!skipEvents) {
|
|
80
|
+
const roots = sessionRoots.length > 0 ? sessionRoots : undefined;
|
|
81
|
+
if (!apply) {
|
|
82
|
+
const planned = discoverSessionLogs(roots ?? defaultRootsHint());
|
|
83
|
+
report.steps.push({ name: 'events', ok: true, status: 'dry-run', sessionsPlanned: planned.length });
|
|
84
|
+
} else {
|
|
85
|
+
const events = buildIndexFromSessions({
|
|
86
|
+
memoryRoot,
|
|
87
|
+
...(roots ? { sessionRoots: roots } : {}),
|
|
88
|
+
rebuild: true,
|
|
89
|
+
});
|
|
90
|
+
report.steps.push({
|
|
91
|
+
name: 'events',
|
|
92
|
+
ok: events.ok !== false,
|
|
93
|
+
status: 'applied',
|
|
94
|
+
sessionsScanned: events.sessionsScanned ?? null,
|
|
95
|
+
sessionsBuilt: events.sessionsBuilt ?? null,
|
|
96
|
+
turns: events.turns ?? null,
|
|
97
|
+
inserted: events.inserted ?? null,
|
|
98
|
+
errors: events.errors ?? null,
|
|
99
|
+
dbBytes: events.dbBytes ?? null,
|
|
100
|
+
});
|
|
101
|
+
if (events.ok === false) report.ok = false;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (eventsOnly && apply) {
|
|
106
|
+
// --events-only 也要把 INDEX 的 freshness 账对齐,否则健康度会显示 stale。
|
|
107
|
+
report.freshness = getIndexFreshness({ memoryRoot });
|
|
108
|
+
} else {
|
|
109
|
+
report.freshness = getIndexFreshness({ memoryRoot });
|
|
110
|
+
}
|
|
111
|
+
} catch (error) {
|
|
112
|
+
report.ok = false;
|
|
113
|
+
report.error = { code: error?.code ?? 'E_REBUILD', message: String(error?.message ?? error) };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
report.durationMs = Date.now() - startedAt;
|
|
117
|
+
|
|
118
|
+
if (json) {
|
|
119
|
+
console.log(JSON.stringify(report, null, 2));
|
|
120
|
+
} else {
|
|
121
|
+
console.log(`[rebuild-index] mode=${report.mode} ok=${report.ok} durationMs=${report.durationMs}`);
|
|
122
|
+
for (const step of report.steps) {
|
|
123
|
+
const detail = step.name === 'index'
|
|
124
|
+
? `cards=${step.cards} status=${step.status} changed=${step.changed} read=${step.read} reused=${step.reused}`
|
|
125
|
+
: `status=${step.status} sessions=${step.sessionsBuilt ?? step.sessionsPlanned} turns=${step.turns ?? '-'}`;
|
|
126
|
+
console.log(`[rebuild-index] ${step.name}: ${detail}`);
|
|
127
|
+
}
|
|
128
|
+
if (report.freshness) {
|
|
129
|
+
console.log(`[rebuild-index] freshness=${report.freshness.status} lagMs=${report.freshness.indexLagMs} generatedAt=${report.freshness.generatedAt}`);
|
|
130
|
+
}
|
|
131
|
+
if (report.error) console.log(`[rebuild-index] error=${report.error.code} ${report.error.message}`);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
process.exitCode = report.ok === false ? 1 : 0;
|
|
135
|
+
|
|
136
|
+
/** dry-run 下没给 --session-root 时,用事件索引模块自己的默认会话根做估算。 */
|
|
137
|
+
function defaultRootsHint() {
|
|
138
|
+
try {
|
|
139
|
+
// ESM 无法同步读 env 之外的东西;这里只做“能不能数到日志”的估算。
|
|
140
|
+
// buildIndexFromSessions 的默认根来自环境变量(DSH_HOME 等),dry-run 直接
|
|
141
|
+
// 传 undefined 会让 discoverSessionLogs 拿到空数组,故显式构造。
|
|
142
|
+
const hint = [];
|
|
143
|
+
if (process.env.DSH_HOME) hint.push(process.env.DSH_HOME);
|
|
144
|
+
return hint;
|
|
145
|
+
} catch {
|
|
146
|
+
return [];
|
|
147
|
+
}
|
|
148
|
+
}
|