Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 装入/更新崩溃窗口的事务标记,消除迁移收编与旧 receipt 错位(2 P0)

Yuewei-LL08aaf50d6cb7
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 4276a3f50d..69f4131d3f 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -34,6 +34,7 @@ import {
hashGhostContentBuffers,
hashGhostContentFiles,
resolveGhostContentPathSync,
+ type GhostDirEntryKind,
} from './ghostContentTree.js';
import { checkSkillMdConsistency } from './skillSlot.js';
import {
@@ -172,31 +173,83 @@ export class GhostManager {
) {
throw new Error('ghost install content and approval state roots must be disjoint');
}
- this.recoverInterruptedUpdatesSync();
+ this.recoverInterruptedMutationsSync();
}
/**
- * 启动一次性:恢复更新的"两次 rename 之间"崩溃现场(§5:插件不得凭空消失)。
+ * 启动一次性:恢复装入/更新的"目录已 rename、receipt 还没写"崩溃现场。构造期同步跑
+ * (目录极小,与 resolveGhostRepoRoot 的启动期迁移同一先例)。
*
- * update 的目录交换是 final→backup(.cindy-updating-*)、staging→final 两步;断电/
- * 进程被杀落在两步之间时,final 缺位、旧版完整字节还在 backup 里 —— 而 list()
- * 跳过点目录,插件就从 UI 与运行时**消失**了。这里在构造期同步扫一遍(目录极小,
- * 与 resolveGhostRepoRoot 的启动期迁移同一先例):
- * - final 缺位且该 id 只有唯一 backup → 原子搬回(receipt 未更新过,恢复后
- * receipt/内容完全一致,等价于更新从未发生);
- * - final 在位(崩溃发生在收尾清理前)→ backup 是已被替换的旧字节,回收;
- * - 同 id 多个 backup(多次崩溃)→ 不猜,原样保留并记 error 供人工处理;
- * - `.cindy-installing-*` staging 残留一律回收(从未发布过,不构成任何事实)。
+ * **事务标记(状态根内)是权威判据**:装入/更新在 rename 动盘前落标记、写完 receipt
+ * 清标记,标记带本次 `packageSha256`。恢复时同步读 receipt,`receipt.packageSha256 ===
+ * marker.packageSha256` 即"已提交":
+ * - install 未提交 → finalDir 是不完整安装,删掉(否则迁移会把它当 legacy 收编,而
+ * 崩溃窗口内 manifest 可能已被同权限进程改写 = 用户确认 A 却授权 B);已提交 → 保留;
+ * - update 未提交 → 回滚到 backup(旧字节+旧 receipt 自洽);已提交 → 回收陈旧 backup。
+ * 这修掉了"final 在位就删 backup"把"新字节+旧 receipt"固化成"按旧批准跑新代码"的洞。
+ *
+ * 无标记的孤儿 `.cindy-updating-*`(journal 之前的崩溃残留)沿用原启发式兜底:final
+ * 缺位且唯一 backup → 搬回(§5 插件不得凭空消失);final 在位 → 陈旧 backup 回收。
+ * `.cindy-installing-*` staging 残留一律回收(从未发布)。
*/
- private recoverInterruptedUpdatesSync(): void {
+ private recoverInterruptedMutationsSync(): void {
const root = this.options.getRootDir();
+
+ // 1) 标记驱动恢复(权威)。
+ const handledBackupNames = new Set<string>();
+ for (const id of this.receiptStore.listPendingMutationIdsSync()) {
+ const marker = this.receiptStore.readPendingMutationSync(id);
+ const finalDir = path.join(root, id);
+ try {
+ if (!marker) {
+ // 标记读不出:它只驱动恢复,读不出就无从据它动盘,清掉(下次启动靠内容判定)。
+ this.receiptStore.clearPendingMutationSync(id);
+ continue;
+ }
+ const approval = this.receiptStore.read(id);
+ if (marker.kind === 'install') {
+ // 未提交装入(无已批准 receipt)= 不完整安装,删 finalDir;有已批准 receipt = 完整
+ // 安装,保留(绝不删有有效批准的插件)。只删真目录,junction/链接跳过(避免穿透)。
+ if (approval.state !== 'approved' && this.isRealDirChild(root, id)) {
+ fs.rmSync(finalDir, { recursive: true, force: true });
+ }
+ } else {
+ handledBackupNames.add(marker.backupDirName);
+ const backupPath = path.join(root, marker.backupDirName);
+ const committed =
+ approval.state === 'approved' &&
+ approval.receipt.packageSha256 === marker.packageSha256;
+ if (committed) {
+ fs.rmSync(backupPath, { recursive: true, force: true }); // 陈旧旧字节
+ } else {
+ // 回滚:finalDir 可能是未提交新字节,删;backup 若在则搬回(旧字节+旧 receipt)。
+ if (this.isRealDirChild(root, id)) {
+ fs.rmSync(finalDir, { recursive: true, force: true });
+ }
+ if (this.isBackupDir(backupPath)) fs.renameSync(backupPath, finalDir);
+ }
+ }
+ this.receiptStore.clearPendingMutationSync(id);
+ } catch (err) {
+ // 动盘失败:留着标记,下次启动幂等重试。
+ (this.options.log?.error ?? this.options.log?.warn)?.call(this.options.log,
+ 'interrupted ghost mutation recovery failed; left for next launch', {
+ id, kind: marker?.kind, error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
+ // 2) 无标记的孤儿 backup + staging 残留。
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(root, { withFileTypes: true });
} catch {
return; // 根目录还不存在 = 没装过任何插件
}
- const backups = entries.filter((entry) => entry.name.startsWith('.cindy-updating-'));
+ const backups = entries.filter(
+ (entry) =>
+ entry.name.startsWith('.cindy-updating-') && !handledBackupNames.has(entry.name),
+ );
for (const entry of backups) {
const match = /^\.cindy-updating-(.+)-[0-9a-f]{8}$/.exec(entry.name);
if (!match || !isValidGhostId(match[1])) continue;
@@ -250,6 +303,24 @@ export class GhostManager {
}
}
+ /** `<root>/<id>` 是否真目录(非链接/junction;判据同 ghostContentTree,避免穿透删除)。 */
+ private isRealDirChild(root: string, id: string): boolean {
+ try {
+ return classifyGhostDirEntrySync(path.join(root, id)) === 'directory';
+ } catch {
+ return false;
+ }
+ }
+
+ /** backup 路径是否真目录(搬回前确认,不跟随链接)。 */
+ private isBackupDir(backupPath: string): boolean {
+ try {
+ return classifyGhostDirEntrySync(backupPath) === 'directory';
+ } catch {
+ return false;
+ }
+ }
+
/**
* 从 `.cindy` 包的内存投影算技能字节指纹(P0-8)。
*
@@ -485,6 +556,13 @@ export class GhostManager {
(resumePending ? preMigrated : result.skipped).push(id);
continue;
}
+ // 有未清的事务标记 = 一次装入/更新崩在半途、启动恢复还没收干净(通常恢复已在
+ // 构造期把它清掉,这里兜住"恢复删 finalDir 失败"的残留)。绝不迁移这种目录 ——
+ // 它的字节来源不是"用户确认过的旧安装",而是一次未完成事务的中间态。
+ if (this.receiptStore.readPendingMutationSync(id) !== null) {
+ result.skipped.push(id);
+ continue;
+ }
candidates.push(id);
}
@@ -1033,7 +1111,17 @@ export class GhostManager {
return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };
}
const dir = path.join(this.options.getRootDir(), id);
- if (!(await pathExists(dir))) {
+ // pathExists(fs.access)跟随链接:`<root>/<id>` 被换成 junction 时,下面对
+ // `<dir>/.disabled` 的写/删会穿透到安装根之外的目标。判据改用 ghostContentTree 的
+ // lstat 分类(与 list()「只有真目录才算安装」同源):不存在(ENOENT→抛错)或非真目录
+ // (链接/文件)一律按未装入拒,标记读写不越过安装根边界。
+ let dirKind: GhostDirEntryKind | null;
+ try {
+ dirKind = classifyGhostDirEntrySync(dir);
+ } catch {
+ dirKind = null;
+ }
+ if (dirKind !== 'directory') {
return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };
}
const receiptResult = this.readApproval(id);
@@ -1536,6 +1624,14 @@ export class GhostManager {
: MAX_BASIC_UNCOMPRESSED_BYTES,
trust,
});
+ // 事务标记必须在 rename 动盘**之前**落:否则 rename→写 receipt 之间崩溃会留下
+ // "有 finalDir、无 receipt、无 ledger"的目录,与 legacy 安装无法区分,被迁移当
+ // 存量批准掉(而崩溃窗口内同权限进程可改写 finalDir 的 manifest)。带 packageSha256
+ // 让启动恢复能判定 receipt 是否已提交。
+ await this.receiptStore.writePendingMutation(manifest.id, {
+ kind: 'install',
+ packageSha256,
+ });
await fs.promises.rename(stagingDir, finalDir);
try {
receipt = createGhostInstallReceipt({
@@ -1554,9 +1650,13 @@ export class GhostManager {
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
});
await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
+ // receipt 已就位 = 事务提交,清标记。清失败只多留一份标记,下轮恢复见
+ // receipt.packageSha256 与标记相符即判已提交、幂等清理。
+ await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
this.untrustedApprovals.delete(this.isolationKey(manifest.id));
} catch (error) {
await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
+ await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
throw error;
}
} catch (err) {
@@ -1691,11 +1791,26 @@ export class GhostManager {
return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
}
+ // 事务标记在两次 rename 动盘**之前**落:staging→final 之后、写 receipt 之前崩溃会
+ // 留下"新字节 + 旧 receipt";恢复器旧逻辑(final 在位就删 backup)会把它固化成"按旧
+ // 批准跑新代码"。标记带本次 packageSha256 + backup 目录名,让恢复能判定 receipt 是否
+ // 已提交:未提交则回滚到 backup。
+ try {
+ await this.receiptStore.writePendingMutation(manifest.id, {
+ kind: 'update',
+ packageSha256,
+ backupDirName: path.basename(backupDir),
+ });
+ } catch (err) {
+ await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
+ return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ }
// 换目录:旧版先挪去备份位,新版 rename 失败即滚回,保证任何时刻都有一份完整版本在位。
try {
await fs.promises.rename(finalDir, backupDir);
} catch (err) {
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
+ await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
}
try {
@@ -1711,6 +1826,10 @@ export class GhostManager {
});
});
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
+ // 已回滚到 backup(或回滚也失败):无论如何这次 update 未提交,清标记 —— 回滚成功时
+ // finalDir=旧字节+旧 receipt 已自洽;回滚失败时 rollbackFailed 已上报,标记留着也
+ // 只会让恢复器再尝试同样已失败的回滚。
+ await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
return {
rejection: {
code: 'io',
@@ -1749,6 +1868,7 @@ export class GhostManager {
error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
});
});
+ await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
return {
rejection: {
code: 'io',
@@ -1757,6 +1877,8 @@ export class GhostManager {
},
};
}
+ // receipt 已就位 = 事务提交,清标记后再回收 backup;顺序保证"标记在 ⟺ 可能未提交"。
+ await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => {});
const ghost: InstalledGhost = {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index 789c4af58c..d708b27a2b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -856,6 +856,121 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
});
});
+describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () => {
+ const pendingMarkerPath = (id = 'hello') =>
+ path.join(workDir, 'ghosts-install-state', `.pending-${id}.json`);
+ const receiptPath = (id = 'hello') =>
+ path.join(workDir, 'ghosts-install-state', `${id}.json`);
+ /** 在同一组根上新建 manager —— 构造期跑一次崩溃恢复扫描。 */
+ const freshManager = () =>
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
+
+ it('崩溃的装入(有 finalDir、无 receipt、有 install 标记)被恢复删除,不被迁移收编', async () => {
+ // install 在 rename(staging→final) 之后、写 receipt 之前崩溃:finalDir 完整、无
+ // receipt、无 ledger。若不处理,迁移会把它(崩溃窗口内可能被改过 manifest)当 legacy
+ // 批准掉。事务标记让恢复识别它是"未完成安装"并删除。
+ await writeLegacyInstall('hello', goodManifest());
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256: 'a'.repeat(64) }),
+ );
+
+ const recovered = freshManager(); // 构造期恢复:删掉未完成安装
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ const outcome = await recovered.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual([]); // 目录已被删,迁移无对象
+ });
+
+ it('未提交的更新(新字节+旧 receipt+update 标记)回滚到 backup,不固化成按旧批准跑新代码', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');
+ const finalDir = path.join(rootDir, 'hello');
+ const backupName = '.cindy-updating-hello-abcdef12';
+
+ // 模拟 staging→final 之后、写 receipt 之前崩溃:旧字节挪到 backup,新字节在 final,
+ // receipt 仍是旧的。标记的 packageSha256 与旧 receipt 不同 = 未提交。
+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));
+ await fs.promises.mkdir(finalDir);
+ await fs.promises.writeFile(
+ path.join(finalDir, 'ghost.json'),
+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),
+ );
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: backupName,
+ }),
+ );
+
+ freshManager(); // 构造期恢复:未提交 → 回滚到 backup
+ const restored = JSON.parse(await fs.promises.readFile(path.join(finalDir, 'ghost.json'), 'utf8'));
+ expect(restored.version).toBe('1.0.0'); // 旧字节搬回
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ // receipt 一字未动,与回滚后的旧字节自洽(不是"新字节 + 旧 receipt"的错位)。
+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);
+ });
+
+ it('已提交的更新(标记 packageSha256 == receipt)保留新字节,只回收陈旧 backup', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const committedPkg = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ }).packageSha256;
+ const backupName = '.cindy-updating-hello-abcdef34';
+ await fs.promises.mkdir(path.join(rootDir, backupName));
+ await fs.promises.writeFile(path.join(rootDir, backupName, 'stale.txt'), 'old');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: committedPkg, // 与 receipt 相符 = 已提交
+ backupDirName: backupName,
+ }),
+ );
+
+ freshManager();
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false); // 陈旧 backup 回收
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true); // 新版保留
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(manager.list()[0].approval.state).toBe('approved');
+ });
+
+ it('setEnabled 不跟随非真目录:<id> 是普通文件时按未装入拒,不越安装根写标记', async () => {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ await fs.promises.writeFile(path.join(rootDir, 'foo'), 'not a dir');
+ const result = await manager.setEnabled('foo', false);
+ await expectRejection(result, 'not-installed');
+ });
+
+ it('setEnabled 不跟随 junction:<id> 是指向外部的链接时拒,不在外部目标写/删 .disabled', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const dir = path.join(rootDir, 'hello');
+ const outside = path.join(workDir, 'outside-target');
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.rm(dir, { recursive: true, force: true });
+ try {
+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return; // 无 symlink 权限(Windows 未开发者模式):生产守卫仍由 classify 钉死。
+ }
+ const result = await manager.setEnabled('hello', false);
+ await expectRejection(result, 'not-installed');
+ // 关键:没有往 junction 目标(安装根之外)写 .disabled。
+ expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);
+ });
+});
+
describe('GhostManager · install', () => {
it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
const manifest = {
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 9f76ca4d18..fa8f69302b 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -109,6 +109,25 @@ export interface GhostLegacyMigrationLedger {
pendingIds?: string[];
}
+/**
+ * 装入/更新事务的提交日志(状态根内,崩溃后仍在)。用来消除「目录已 rename、receipt
+ * 还没写」这段崩溃窗口:
+ * - install:崩溃留下"有 finalDir、无 receipt、无 ledger"的目录,与 legacy 安装无法
+ * 区分 —— 全新 owner 首个安装崩在这里,下轮迁移会把它(含崩溃窗口内被同权限进程
+ * 改写的 manifest)当存量批准掉,用户确认的是 A、被授权的是 B。
+ * - update:`final→backup`、`staging→final`、写 receipt 三步;第二三步之间崩溃留下
+ * "新字节 + 旧 receipt",恢复器旧逻辑(final 在位就删 backup)会把它固化成"按旧批准
+ * 跑新代码"。
+ *
+ * `packageSha256` 是判定「提交是否完成」的唯一信号:装入/更新写出的 receipt 一定带上
+ * 这次 `.cindy` 的哈希,所以启动恢复只需**同步**读 receipt、比对
+ * `receipt.packageSha256 === marker.packageSha256` —— 相等 = receipt 已写(提交完成),
+ * 不等/缺失 = 未提交。两者都是已落盘事实,判定不引入额外写窗口。
+ */
+export type GhostPendingMutation =
+ | { kind: 'install'; packageSha256: string }
+ | { kind: 'update'; packageSha256: string; backupDirName: string };
+
/** Host-owned receipt store:严格读取、同目录临时文件 + rename 原子提交。 */
export class GhostInstallReceiptStore {
/** receipt 首写后的自动落账写失败(进程内关门标志,见 migrationDoorClosed)。 */
@@ -391,6 +410,76 @@ export class GhostInstallReceiptStore {
}
}
+ /** 事务标记路径。点开头,不与 `<id>.json` receipt 或 `.legacy-migration.json` 撞名。 */
+ private pendingMutationPath(id: string): string {
+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for pending mutation path');
+ return path.join(this.rootDir(), `.pending-${id}.json`);
+ }
+
+ /** 事务开始:装入/更新 rename 动盘**之前**落标记(原子 temp+rename;re-begin 覆盖)。 */
+ async writePendingMutation(id: string, entry: GhostPendingMutation): Promise<void> {
+ const root = this.rootDir();
+ await fs.promises.mkdir(root, { recursive: true });
+ const target = this.pendingMutationPath(id);
+ const temp = path.join(
+ root,
+ `.pending-${id}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,
+ );
+ try {
+ await fs.promises.writeFile(temp, `${JSON.stringify({ version: 1, id, ...entry })}\n`, {
+ encoding: 'utf8',
+ flag: 'wx',
+ mode: 0o600,
+ });
+ await fs.promises.rename(temp, target);
+ } finally {
+ await fs.promises.rm(temp, { force: true }).catch(() => undefined);
+ }
+ }
+
+ /** 事务提交:receipt 写成功后清标记。删不动只多留一份标记,下轮恢复幂等重判。 */
+ async clearPendingMutation(id: string): Promise<void> {
+ await fs.promises.rm(this.pendingMutationPath(id), { force: true });
+ }
+
+ /** 同步清标记(启动恢复在构造期同步跑,不能留 fire-and-forget 的异步删除)。 */
+ clearPendingMutationSync(id: string): void {
+ fs.rmSync(this.pendingMutationPath(id), { force: true });
+ }
+
+ readPendingMutationSync(id: string): GhostPendingMutation | null {
+ let raw: Record<string, unknown>;
+ try {
+ raw = JSON.parse(fs.readFileSync(this.pendingMutationPath(id), 'utf8')) as Record<string, unknown>;
+ } catch {
+ return null;
+ }
+ if (typeof raw.packageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(raw.packageSha256)) {
+ return null;
+ }
+ if (raw.kind === 'install') return { kind: 'install', packageSha256: raw.packageSha256 };
+ if (raw.kind === 'update' && typeof raw.backupDirName === 'string') {
+ return { kind: 'update', packageSha256: raw.packageSha256, backupDirName: raw.backupDirName };
+ }
+ return null;
+ }
+
+ /** 状态根里所有未清的事务标记 id(启动恢复用)。 */
+ listPendingMutationIdsSync(): string[] {
+ let names: string[];
+ try {
+ names = fs.readdirSync(this.rootDir());
+ } catch {
+ return [];
+ }
+ const ids: string[] = [];
+ for (const name of names) {
+ const match = /^\.pending-(.+)\.json$/.exec(name);
+ if (match && isValidGhostId(match[1])) ids.push(match[1]);
+ }
+ return ids;
+ }
+
private receiptPath(id: string): string {
if (!isValidGhostId(id)) throw new Error('invalid ghost id for receipt path');
return path.join(this.rootDir(), `${id}.json`);