@suifei/dsh-ai-team 0.4.144 → 0.4.145

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -0
  4. package/client.js +22 -14
  5. package/cordis.patch.yml +31 -31
  6. package/icon.svg +12 -12
  7. package/lib/domain/ids.js +26 -26
  8. package/lib/domain/inbox.js +93 -93
  9. package/lib/domain/member-config.js +168 -168
  10. package/lib/host/decision-report.js +72 -72
  11. package/lib/host/default-workspace.js +69 -69
  12. package/lib/host/fault-adapter.js +50 -50
  13. package/lib/host/people-view.js +120 -120
  14. package/lib/host/permission-guard.js +61 -61
  15. package/lib/host/pmo.js +13 -13
  16. package/lib/host/project-registry.js +104 -104
  17. package/lib/host/risk-view.js +99 -99
  18. package/lib/host/weekly-view.js +86 -86
  19. package/lib/host/workspace-path.js +94 -94
  20. package/lib/ledger/checkpoint.js +415 -415
  21. package/lib/ledger/events.js +398 -398
  22. package/lib/ledger/namespace.js +124 -124
  23. package/lib/ledger/tools.js +118 -118
  24. package/lib/ledger/writer.js +1266 -1266
  25. package/lib/runtime/error-chain.js +31 -31
  26. package/lib/runtime/shell-guard.js +102 -102
  27. package/lib/runtime/skill-catalog.js +41 -41
  28. package/lib/runtime/skill-policy.js +12 -12
  29. package/lib/skillopt/adopt-gate.js +108 -108
  30. package/lib/skillopt/gate-wiring.js +146 -146
  31. package/lib/skillopt/jobs.js +135 -135
  32. package/lib/skillopt/proposal-store.js +33 -33
  33. package/lib/skillopt/review-runner.js +107 -107
  34. package/lib/skillopt/rubric.js +189 -189
  35. package/lib/skillopt/subagent-text.js +101 -101
  36. package/lib/skillopt/tool-access.js +56 -56
  37. package/locale/en.json +6 -6
  38. package/locale/zh.json +6 -6
  39. package/package.json +1 -1
@@ -1,124 +1,124 @@
1
- /**
2
- * Profile 命名空间解析与一次性的旧命名空间迁移。
3
- *
4
- * 背景:桌面启动器不导出 `DSH_PROFILE`,而是把 profile 目录作为**位置参数**传给
5
- * 宿主(`… <dsh-root> C:\Users\…\.dsh\profiles\desktop …`)。旧解析只认
6
- * `--profile <name>`,于是 desktop profile 的账本全部落进 `ai-team/default/`,
7
- * 两个 profile 共用一个命名空间。
8
- *
9
- * 但只修解析会把已经落在 `default/` 的数据留在原地(界面上团队凭空消失),
10
- * 因此配一条**数据驱动、一次性、可回退**的迁移规则:只有当旧命名空间的数据
11
- * 明显多于目标命名空间时才搬迁,并把目标原有内容改名保留,不删除任何东西。
12
- */
13
-
14
- import { existsSync, readdirSync, renameSync, statSync } from 'node:fs';
15
- import { homedir } from 'node:os';
16
- import { join } from 'node:path';
17
-
18
- /** 从启动参数/env 解析 profile 名。 */
19
- export function resolveProfileName(argv = process.argv, env = process.env) {
20
- return resolveProfile(argv, env).name;
21
- }
22
-
23
- /**
24
- * 同 `resolveProfileName`,但同时给出**来源**:
25
- * - `flag`:`--profile x` / `--profile=x`(CLI 显式指定)
26
- * - `argv-path`:位置参数里的 `…/profiles/<name>`(桌面启动器)
27
- * - `env` / `default`
28
- *
29
- * 迁移只允许发生在 `argv-path`:旧命名空间那个坑正是桌面启动器造成的;
30
- * 若从 `--profile ai-team` 起一个 CLI 就顺手把 desktop 的数据搬过去,会把
31
- * GUI 的团队偷走。
32
- */
33
- export function resolveProfile(argv = process.argv, env = process.env) {
34
- const list = Array.isArray(argv) ? argv.map(String) : [];
35
- const flagAt = list.indexOf('--profile');
36
- if (flagAt >= 0 && typeof list[flagAt + 1] === 'string' && list[flagAt + 1] !== '') {
37
- return { name: list[flagAt + 1], source: 'flag' };
38
- }
39
- const inline = list.find((arg) => arg.startsWith('--profile='));
40
- if (inline !== undefined) {
41
- const value = inline.slice('--profile='.length);
42
- if (value !== '') return { name: value, source: 'flag' };
43
- }
44
- // 位置参数形态:…/profiles/<name>(Windows 反斜杠与 POSIX 斜杠都要认)。
45
- for (const arg of list) {
46
- const match = /[\\/]profiles[\\/]([^\\/]+)[\\/]?$/.exec(arg);
47
- if (match !== null) return { name: match[1], source: 'argv-path' };
48
- }
49
- if (env?.DSH_PROFILE) return { name: env.DSH_PROFILE, source: 'env' };
50
- // 兜底:某些启动器只传 dsh-root 而不传 profile 目录,于是上面两条都落空,
51
- // 账本被写进 `ai-team/default/`(实机复现)。此时若 `~/.dsh/profiles` 下
52
- // **只有一个** profile,它必然就是当前 profile。
53
- const only = singleProfileName(env);
54
- if (only !== null) return { name: only, source: 'profiles-single' };
55
- return { name: 'default', source: 'default' };
56
- }
57
-
58
- /** `~/.dsh/profiles` 下唯一的 profile 名;不存在或有多个时返回 null(不猜)。 */
59
- export function singleProfileName(env = process.env) {
60
- try {
61
- const home = typeof env?.DSH_HOME === 'string' && env.DSH_HOME.trim() !== ''
62
- ? env.DSH_HOME
63
- : join(homedir(), '.dsh');
64
- const entries = readdirSync(join(home, 'profiles'), { withFileTypes: true })
65
- .filter((entry) => entry.isDirectory())
66
- .map((entry) => entry.name);
67
- return entries.length === 1 ? entries[0] : null;
68
- } catch {
69
- return null;
70
- }
71
- }
72
-
73
- /** 目录下所有文件的总字节数;目录不存在按 0 计。 */
74
- export function dirBytes(dir) {
75
- if (!existsSync(dir)) return 0;
76
- let total = 0;
77
- const walk = (current) => {
78
- let entries = [];
79
- try { entries = readdirSync(current, { withFileTypes: true }); } catch { return; }
80
- for (const entry of entries) {
81
- const full = join(current, entry.name);
82
- if (entry.isDirectory()) { walk(full); continue; }
83
- try { total += statSync(full).size; } catch { /* vanished */ }
84
- }
85
- };
86
- walk(dir);
87
- return total;
88
- }
89
-
90
- /**
91
- * 旧命名空间有明显更多数据时搬迁到目标命名空间。
92
- * @returns {'migrated'|'kept'|'none'} migrated=已搬迁,kept=目标更新/一样大,none=没有旧数据
93
- */
94
- export function migrateLegacyNamespace({ fromDir, toDir, diag = null, now = Date.now, rename = renameSync }) {
95
- if (fromDir === toDir) return 'none';
96
- if (!existsSync(join(fromDir, 'projects.json'))) return 'none';
97
- const legacyBytes = dirBytes(fromDir);
98
- const targetBytes = dirBytes(toDir);
99
- if (legacyBytes <= targetBytes) return 'kept';
100
- let supersededDir = null;
101
- try {
102
- if (existsSync(toDir)) {
103
- // 目标原有内容改名保留(不删除),便于回退与人工核对。
104
- supersededDir = `${toDir}.superseded-${now()}`;
105
- rename(toDir, supersededDir);
106
- }
107
- rename(fromDir, toDir);
108
- diag?.append?.({ ev: 'ledger.namespace.migrated', from: fromDir, to: toDir, legacyBytes, targetBytes });
109
- return 'migrated';
110
- } catch (error) {
111
- // 第二步失败时目标已经被挪走:必须还原,否则下一次 boot 会用一个空目录
112
- // 重建 registry,用户看到的是「团队被清空」,而数据只躺在 superseded 里。
113
- if (supersededDir !== null && !existsSync(toDir)) {
114
- try {
115
- rename(supersededDir, toDir);
116
- diag?.append?.({ ev: 'ledger.namespace.migrate.rollback', to: toDir, superseded: supersededDir });
117
- } catch (rollbackError) {
118
- diag?.append?.({ ev: 'ledger.namespace.rollback.fail', to: toDir, superseded: supersededDir, message: rollbackError?.message ?? String(rollbackError) });
119
- }
120
- }
121
- diag?.append?.({ ev: 'ledger.namespace.migrate.fail', from: fromDir, to: toDir, message: error?.message ?? String(error) });
122
- return 'kept';
123
- }
124
- }
1
+ /**
2
+ * Profile 命名空间解析与一次性的旧命名空间迁移。
3
+ *
4
+ * 背景:桌面启动器不导出 `DSH_PROFILE`,而是把 profile 目录作为**位置参数**传给
5
+ * 宿主(`… <dsh-root> C:\Users\…\.dsh\profiles\desktop …`)。旧解析只认
6
+ * `--profile <name>`,于是 desktop profile 的账本全部落进 `ai-team/default/`,
7
+ * 两个 profile 共用一个命名空间。
8
+ *
9
+ * 但只修解析会把已经落在 `default/` 的数据留在原地(界面上团队凭空消失),
10
+ * 因此配一条**数据驱动、一次性、可回退**的迁移规则:只有当旧命名空间的数据
11
+ * 明显多于目标命名空间时才搬迁,并把目标原有内容改名保留,不删除任何东西。
12
+ */
13
+
14
+ import { existsSync, readdirSync, renameSync, statSync } from 'node:fs';
15
+ import { homedir } from 'node:os';
16
+ import { join } from 'node:path';
17
+
18
+ /** 从启动参数/env 解析 profile 名。 */
19
+ export function resolveProfileName(argv = process.argv, env = process.env) {
20
+ return resolveProfile(argv, env).name;
21
+ }
22
+
23
+ /**
24
+ * 同 `resolveProfileName`,但同时给出**来源**:
25
+ * - `flag`:`--profile x` / `--profile=x`(CLI 显式指定)
26
+ * - `argv-path`:位置参数里的 `…/profiles/<name>`(桌面启动器)
27
+ * - `env` / `default`
28
+ *
29
+ * 迁移只允许发生在 `argv-path`:旧命名空间那个坑正是桌面启动器造成的;
30
+ * 若从 `--profile ai-team` 起一个 CLI 就顺手把 desktop 的数据搬过去,会把
31
+ * GUI 的团队偷走。
32
+ */
33
+ export function resolveProfile(argv = process.argv, env = process.env) {
34
+ const list = Array.isArray(argv) ? argv.map(String) : [];
35
+ const flagAt = list.indexOf('--profile');
36
+ if (flagAt >= 0 && typeof list[flagAt + 1] === 'string' && list[flagAt + 1] !== '') {
37
+ return { name: list[flagAt + 1], source: 'flag' };
38
+ }
39
+ const inline = list.find((arg) => arg.startsWith('--profile='));
40
+ if (inline !== undefined) {
41
+ const value = inline.slice('--profile='.length);
42
+ if (value !== '') return { name: value, source: 'flag' };
43
+ }
44
+ // 位置参数形态:…/profiles/<name>(Windows 反斜杠与 POSIX 斜杠都要认)。
45
+ for (const arg of list) {
46
+ const match = /[\\/]profiles[\\/]([^\\/]+)[\\/]?$/.exec(arg);
47
+ if (match !== null) return { name: match[1], source: 'argv-path' };
48
+ }
49
+ if (env?.DSH_PROFILE) return { name: env.DSH_PROFILE, source: 'env' };
50
+ // 兜底:某些启动器只传 dsh-root 而不传 profile 目录,于是上面两条都落空,
51
+ // 账本被写进 `ai-team/default/`(实机复现)。此时若 `~/.dsh/profiles` 下
52
+ // **只有一个** profile,它必然就是当前 profile。
53
+ const only = singleProfileName(env);
54
+ if (only !== null) return { name: only, source: 'profiles-single' };
55
+ return { name: 'default', source: 'default' };
56
+ }
57
+
58
+ /** `~/.dsh/profiles` 下唯一的 profile 名;不存在或有多个时返回 null(不猜)。 */
59
+ export function singleProfileName(env = process.env) {
60
+ try {
61
+ const home = typeof env?.DSH_HOME === 'string' && env.DSH_HOME.trim() !== ''
62
+ ? env.DSH_HOME
63
+ : join(homedir(), '.dsh');
64
+ const entries = readdirSync(join(home, 'profiles'), { withFileTypes: true })
65
+ .filter((entry) => entry.isDirectory())
66
+ .map((entry) => entry.name);
67
+ return entries.length === 1 ? entries[0] : null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ /** 目录下所有文件的总字节数;目录不存在按 0 计。 */
74
+ export function dirBytes(dir) {
75
+ if (!existsSync(dir)) return 0;
76
+ let total = 0;
77
+ const walk = (current) => {
78
+ let entries = [];
79
+ try { entries = readdirSync(current, { withFileTypes: true }); } catch { return; }
80
+ for (const entry of entries) {
81
+ const full = join(current, entry.name);
82
+ if (entry.isDirectory()) { walk(full); continue; }
83
+ try { total += statSync(full).size; } catch { /* vanished */ }
84
+ }
85
+ };
86
+ walk(dir);
87
+ return total;
88
+ }
89
+
90
+ /**
91
+ * 旧命名空间有明显更多数据时搬迁到目标命名空间。
92
+ * @returns {'migrated'|'kept'|'none'} migrated=已搬迁,kept=目标更新/一样大,none=没有旧数据
93
+ */
94
+ export function migrateLegacyNamespace({ fromDir, toDir, diag = null, now = Date.now, rename = renameSync }) {
95
+ if (fromDir === toDir) return 'none';
96
+ if (!existsSync(join(fromDir, 'projects.json'))) return 'none';
97
+ const legacyBytes = dirBytes(fromDir);
98
+ const targetBytes = dirBytes(toDir);
99
+ if (legacyBytes <= targetBytes) return 'kept';
100
+ let supersededDir = null;
101
+ try {
102
+ if (existsSync(toDir)) {
103
+ // 目标原有内容改名保留(不删除),便于回退与人工核对。
104
+ supersededDir = `${toDir}.superseded-${now()}`;
105
+ rename(toDir, supersededDir);
106
+ }
107
+ rename(fromDir, toDir);
108
+ diag?.append?.({ ev: 'ledger.namespace.migrated', from: fromDir, to: toDir, legacyBytes, targetBytes });
109
+ return 'migrated';
110
+ } catch (error) {
111
+ // 第二步失败时目标已经被挪走:必须还原,否则下一次 boot 会用一个空目录
112
+ // 重建 registry,用户看到的是「团队被清空」,而数据只躺在 superseded 里。
113
+ if (supersededDir !== null && !existsSync(toDir)) {
114
+ try {
115
+ rename(supersededDir, toDir);
116
+ diag?.append?.({ ev: 'ledger.namespace.migrate.rollback', to: toDir, superseded: supersededDir });
117
+ } catch (rollbackError) {
118
+ diag?.append?.({ ev: 'ledger.namespace.rollback.fail', to: toDir, superseded: supersededDir, message: rollbackError?.message ?? String(rollbackError) });
119
+ }
120
+ }
121
+ diag?.append?.({ ev: 'ledger.namespace.migrate.fail', from: fromDir, to: toDir, message: error?.message ?? String(error) });
122
+ return 'kept';
123
+ }
124
+ }
@@ -1,118 +1,118 @@
1
- /**
2
- * 账本工具面(R-15 / "plumbing 的 porcelain"):把 writer 已有的读取与
3
- * 校验能力包装成不依赖宿主进程的人读操作——"一切有记录"的承诺必须可以
4
- * **独立兑现**才成立。
5
- *
6
- * 纪律:全部只读;**不做 gc/压缩/删除**(D1 裁定:append-only 即历史不可变)。
7
- *
8
- * exportLedger(dir, outDir) 自包含导出包:段文件副本 + manifest.json +
9
- * verify-report.md(人读校验结论)
10
- * auditLedger(dir) 独立校验 hash 链,返回结构化结论(人读报告
11
- * 由 CLI 层渲染)
12
- * statsLedger(dir) 段/事件/字节计数与首尾时间
13
- */
14
-
15
- import fsDefault from 'node:fs';
16
- import pathDefault from 'node:path';
17
- import { verifyChain } from './events.js';
18
-
19
- function listSegments(dir, fs = fsDefault) {
20
- return fs.readdirSync(dir)
21
- .filter((name) => /^ledger-\d+\.jsonl$/.test(name))
22
- .sort();
23
- }
24
-
25
- function readEvents(dir, fs = fsDefault) {
26
- const segments = listSegments(dir, fs);
27
- const events = [];
28
- for (const name of segments) {
29
- const text = fs.readFileSync(pathDefault.join(dir, name), 'utf8');
30
- for (const line of text.split('\n')) {
31
- if (line.trim() === '') continue;
32
- events.push(JSON.parse(line));
33
- }
34
- }
35
- return { segments, events };
36
- }
37
-
38
- function bytesOf(dir, segments, fs = fsDefault) {
39
- let total = 0;
40
- for (const name of segments) {
41
- total += fs.statSync(pathDefault.join(dir, name)).size;
42
- }
43
- return total;
44
- }
45
-
46
- /** 独立校验:读全部事件 → verifyChain(不加锁、不写盘、不 require 宿主)。 */
47
- export function auditLedger(dir, options = {}) {
48
- const fs = options.fs ?? fsDefault;
49
- const { segments, events } = readEvents(dir, fs);
50
- const projectId = events[0]?.projectId ?? null;
51
- const chain = verifyChain(events, { projectId });
52
- return {
53
- ok: chain.ok,
54
- dir,
55
- projectId,
56
- segments,
57
- eventCount: events.length,
58
- head: events.length > 0 ? { seq: events.at(-1).seq, hash: events.at(-1).hash, at: events.at(-1).at } : null,
59
- error: chain.ok ? null : { code: chain.code, message: chain.message, details: chain.details ?? {}, index: chain.index ?? null },
60
- };
61
- }
62
-
63
- /** 段/事件/字节/首尾时间统计。 */
64
- export function statsLedger(dir, options = {}) {
65
- const fs = options.fs ?? fsDefault;
66
- const { segments, events } = readEvents(dir, fs);
67
- const first = events[0] ?? null;
68
- const last = events.at(-1) ?? null;
69
- return {
70
- dir,
71
- segments: segments.length,
72
- segmentBytes: segments.length > 0 ? bytesOf(dir, segments, fs) : 0,
73
- eventCount: events.length,
74
- firstAt: first?.at ?? null,
75
- lastAt: last?.at ?? null,
76
- headSeq: last?.seq ?? 0,
77
- types: [...new Set(events.map((event) => event.type))].sort(),
78
- };
79
- }
80
-
81
- /**
82
- * 自包含导出:段文件副本(字节级复制,不重排不重写)+ manifest.json(head/
83
- * 事件计数/文件清单/导出时间)+ verify-report.md(人读校验结论)。导出包
84
- * 拷到任何机器都可以用 audit 独立复检。
85
- */
86
- export function exportLedger(dir, outDir, options = {}) {
87
- const fs = options.fs ?? fsDefault;
88
- const path = options.path ?? pathDefault;
89
- const audit = auditLedger(dir, { fs });
90
- fs.mkdirSync(outDir, { recursive: true });
91
- const copied = [];
92
- for (const name of audit.segments) {
93
- fs.copyFileSync(path.join(dir, name), path.join(outDir, name));
94
- copied.push({ name, bytes: fs.statSync(path.join(outDir, name)).size });
95
- }
96
- const manifest = {
97
- exportedAt: new Date().toISOString(),
98
- sourceDir: dir,
99
- projectId: audit.projectId,
100
- head: audit.head,
101
- eventCount: audit.eventCount,
102
- files: copied,
103
- verify: { ok: audit.ok, error: audit.error },
104
- };
105
- fs.writeFileSync(path.join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf8');
106
- const lines = [
107
- '# Ledger export verify report', '',
108
- '- source: `' + dir + '`',
109
- '- projectId: `' + String(audit.projectId) + '`',
110
- '- events: ' + String(audit.eventCount),
111
- '- head: seq ' + String(audit.head?.seq ?? 0),
112
- '- hash chain: ' + (audit.ok ? '**OK**' : '**BROKEN**'),
113
- audit.error ? '- error: ' + audit.error.code + ' ' + audit.error.message : '- error: none',
114
- '- exportedAt: ' + manifest.exportedAt,
115
- ];
116
- fs.writeFileSync(path.join(outDir, 'verify-report.md'), lines.join('\n') + '\n', 'utf8');
117
- return { ok: audit.ok, outDir, files: copied.map((file) => file.name).concat(['manifest.json', 'verify-report.md']) };
118
- }
1
+ /**
2
+ * 账本工具面(R-15 / "plumbing 的 porcelain"):把 writer 已有的读取与
3
+ * 校验能力包装成不依赖宿主进程的人读操作——"一切有记录"的承诺必须可以
4
+ * **独立兑现**才成立。
5
+ *
6
+ * 纪律:全部只读;**不做 gc/压缩/删除**(D1 裁定:append-only 即历史不可变)。
7
+ *
8
+ * exportLedger(dir, outDir) 自包含导出包:段文件副本 + manifest.json +
9
+ * verify-report.md(人读校验结论)
10
+ * auditLedger(dir) 独立校验 hash 链,返回结构化结论(人读报告
11
+ * 由 CLI 层渲染)
12
+ * statsLedger(dir) 段/事件/字节计数与首尾时间
13
+ */
14
+
15
+ import fsDefault from 'node:fs';
16
+ import pathDefault from 'node:path';
17
+ import { verifyChain } from './events.js';
18
+
19
+ function listSegments(dir, fs = fsDefault) {
20
+ return fs.readdirSync(dir)
21
+ .filter((name) => /^ledger-\d+\.jsonl$/.test(name))
22
+ .sort();
23
+ }
24
+
25
+ function readEvents(dir, fs = fsDefault) {
26
+ const segments = listSegments(dir, fs);
27
+ const events = [];
28
+ for (const name of segments) {
29
+ const text = fs.readFileSync(pathDefault.join(dir, name), 'utf8');
30
+ for (const line of text.split('\n')) {
31
+ if (line.trim() === '') continue;
32
+ events.push(JSON.parse(line));
33
+ }
34
+ }
35
+ return { segments, events };
36
+ }
37
+
38
+ function bytesOf(dir, segments, fs = fsDefault) {
39
+ let total = 0;
40
+ for (const name of segments) {
41
+ total += fs.statSync(pathDefault.join(dir, name)).size;
42
+ }
43
+ return total;
44
+ }
45
+
46
+ /** 独立校验:读全部事件 → verifyChain(不加锁、不写盘、不 require 宿主)。 */
47
+ export function auditLedger(dir, options = {}) {
48
+ const fs = options.fs ?? fsDefault;
49
+ const { segments, events } = readEvents(dir, fs);
50
+ const projectId = events[0]?.projectId ?? null;
51
+ const chain = verifyChain(events, { projectId });
52
+ return {
53
+ ok: chain.ok,
54
+ dir,
55
+ projectId,
56
+ segments,
57
+ eventCount: events.length,
58
+ head: events.length > 0 ? { seq: events.at(-1).seq, hash: events.at(-1).hash, at: events.at(-1).at } : null,
59
+ error: chain.ok ? null : { code: chain.code, message: chain.message, details: chain.details ?? {}, index: chain.index ?? null },
60
+ };
61
+ }
62
+
63
+ /** 段/事件/字节/首尾时间统计。 */
64
+ export function statsLedger(dir, options = {}) {
65
+ const fs = options.fs ?? fsDefault;
66
+ const { segments, events } = readEvents(dir, fs);
67
+ const first = events[0] ?? null;
68
+ const last = events.at(-1) ?? null;
69
+ return {
70
+ dir,
71
+ segments: segments.length,
72
+ segmentBytes: segments.length > 0 ? bytesOf(dir, segments, fs) : 0,
73
+ eventCount: events.length,
74
+ firstAt: first?.at ?? null,
75
+ lastAt: last?.at ?? null,
76
+ headSeq: last?.seq ?? 0,
77
+ types: [...new Set(events.map((event) => event.type))].sort(),
78
+ };
79
+ }
80
+
81
+ /**
82
+ * 自包含导出:段文件副本(字节级复制,不重排不重写)+ manifest.json(head/
83
+ * 事件计数/文件清单/导出时间)+ verify-report.md(人读校验结论)。导出包
84
+ * 拷到任何机器都可以用 audit 独立复检。
85
+ */
86
+ export function exportLedger(dir, outDir, options = {}) {
87
+ const fs = options.fs ?? fsDefault;
88
+ const path = options.path ?? pathDefault;
89
+ const audit = auditLedger(dir, { fs });
90
+ fs.mkdirSync(outDir, { recursive: true });
91
+ const copied = [];
92
+ for (const name of audit.segments) {
93
+ fs.copyFileSync(path.join(dir, name), path.join(outDir, name));
94
+ copied.push({ name, bytes: fs.statSync(path.join(outDir, name)).size });
95
+ }
96
+ const manifest = {
97
+ exportedAt: new Date().toISOString(),
98
+ sourceDir: dir,
99
+ projectId: audit.projectId,
100
+ head: audit.head,
101
+ eventCount: audit.eventCount,
102
+ files: copied,
103
+ verify: { ok: audit.ok, error: audit.error },
104
+ };
105
+ fs.writeFileSync(path.join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf8');
106
+ const lines = [
107
+ '# Ledger export verify report', '',
108
+ '- source: `' + dir + '`',
109
+ '- projectId: `' + String(audit.projectId) + '`',
110
+ '- events: ' + String(audit.eventCount),
111
+ '- head: seq ' + String(audit.head?.seq ?? 0),
112
+ '- hash chain: ' + (audit.ok ? '**OK**' : '**BROKEN**'),
113
+ audit.error ? '- error: ' + audit.error.code + ' ' + audit.error.message : '- error: none',
114
+ '- exportedAt: ' + manifest.exportedAt,
115
+ ];
116
+ fs.writeFileSync(path.join(outDir, 'verify-report.md'), lines.join('\n') + '\n', 'utf8');
117
+ return { ok: audit.ok, outDir, files: copied.map((file) => file.name).concat(['manifest.json', 'verify-report.md']) };
118
+ }