Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

fix(storage): recover replacement backups before staging updates

CloudTianTian1f14bb953d43
diff --git a/src/main/features/builtin_marketplace.ts b/src/main/features/builtin_marketplace.ts
index 11f731c1..63c8c6fe 100644
--- a/src/main/features/builtin_marketplace.ts
+++ b/src/main/features/builtin_marketplace.ts
@@ -383,10 +383,11 @@ async function _writeAgentSeed(
opts: BuiltinMarketplaceSeedOptions = {},
): Promise<void> {
const target = userMarketplaceAgentDir(uid, installId);
- const existing = _readInstallMetaObject(target) || {};
- const previousFiles = _previousManagedFiles(target, existing, 'agent', installId);
const files = marketplaceContentTreeFiles(srcDir);
await _replaceBuiltinInstallDirectory(target, 'agent', installId, opts, async (staged) => {
+ // Recovery may restore the baseline immediately before staging.
+ const existing = _readInstallMetaObject(staged) || {};
+ const previousFiles = _previousManagedFiles(staged, existing, 'agent', installId);
await _removeStaleManagedFiles(staged, previousFiles, files);
await _copyManagedFiles(srcDir, staged, files);
await fsp.writeFile(
@@ -434,10 +435,11 @@ async function _writeAgentMarketplaceOverlay(
opts: BuiltinMarketplaceSeedOptions = {},
): Promise<void> {
const target = userMarketplaceAgentDir(uid, installId);
- const existing = _readInstallMetaObject(target) || {};
- const previousFiles = _previousManagedFiles(target, existing, 'agent', installId);
const files = marketplaceContentTreeFiles(srcDir);
await _replaceBuiltinInstallDirectory(target, 'agent', installId, opts, async (staged) => {
+ // Recovery may restore the baseline immediately before staging.
+ const existing = _readInstallMetaObject(staged) || {};
+ const previousFiles = _previousManagedFiles(staged, existing, 'agent', installId);
await _removeStaleManagedFiles(staged, previousFiles, files);
await _copyManagedFiles(srcDir, staged, files);
await fsp.writeFile(
@@ -588,10 +590,11 @@ async function _writeSkillSeed(
opts: BuiltinMarketplaceSeedOptions = {},
): Promise<void> {
const target = userMarketplaceSkillDir(uid, installId);
- const existing = _readInstallMetaObject(target) || {};
- const previousFiles = _previousManagedFiles(target, existing, 'skill', installId);
const files = marketplaceContentTreeFiles(srcDir);
await _replaceBuiltinInstallDirectory(target, 'skill', installId, opts, async (staged) => {
+ // Recovery may restore the baseline immediately before staging.
+ const existing = _readInstallMetaObject(staged) || {};
+ const previousFiles = _previousManagedFiles(staged, existing, 'skill', installId);
await _removeStaleManagedFiles(staged, previousFiles, files);
await _copyManagedFiles(srcDir, staged, files);
const contentSha = sha256OfFile(path.join(staged, 'SKILL.md'));
@@ -633,10 +636,11 @@ async function _writeSkillMarketplaceOverlay(
opts: BuiltinMarketplaceSeedOptions = {},
): Promise<void> {
const target = userMarketplaceSkillDir(uid, installId);
- const existing = _readInstallMetaObject(target) || {};
- const previousFiles = _previousManagedFiles(target, existing, 'skill', installId);
const files = marketplaceContentTreeFiles(srcDir);
await _replaceBuiltinInstallDirectory(target, 'skill', installId, opts, async (staged) => {
+ // Recovery may restore the baseline immediately before staging.
+ const existing = _readInstallMetaObject(staged) || {};
+ const previousFiles = _previousManagedFiles(staged, existing, 'skill', installId);
await _removeStaleManagedFiles(staged, previousFiles, files);
await _copyManagedFiles(srcDir, staged, files);
const contentSha = sha256OfFile(path.join(staged, 'SKILL.md'));
diff --git a/src/main/util/atomic-directory-replace.ts b/src/main/util/atomic-directory-replace.ts
index 60d0928c..8d90614c 100644
--- a/src/main/util/atomic-directory-replace.ts
+++ b/src/main/util/atomic-directory-replace.ts
@@ -62,6 +62,34 @@ export async function sweepStaleReplacementArtifacts(
return removed;
}
+/** A failed rollback can leave the only prior copy beside a missing target.
+ * Restore that unambiguous copy before a merge consumer reads its baseline.
+ * Existing targets take the constant-time path; cold recovery streams one
+ * parent directory without opening unrelated entries or retaining its listing.
+ */
+async function recoverPreviousDirectory(target: string, opts: AtomicDirectoryReplaceOptions): Promise<void> {
+ if (fs.existsSync(target)) return;
+ const parent = path.dirname(target), name = path.basename(target);
+ let backup: string | undefined;
+ const directory = await fsp.opendir(parent);
+ for await (const entry of directory) {
+ const match = REPLACEMENT_ARTIFACT_RE.exec(entry.name);
+ if (!match || match[1] !== name || !entry.name.endsWith('.previous')) continue;
+ const candidate = path.join(parent, entry.name);
+ if (activeReplacementArtifacts.has(candidate)) throw new Error('Previous directory replacement is still active');
+ if (!entry.isDirectory() || backup) throw new Error('Previous directory recovery is ambiguous');
+ backup = candidate;
+ }
+ if (!backup) return;
+ const recover = async () => {
+ opts.assertReady?.();
+ if (fs.existsSync(target)) throw new Error('Directory changed before recovery');
+ await fsp.rename(backup!, target);
+ };
+ if (opts.activationGuard) await opts.activationGuard(recover);
+ else await recover();
+}
+
export async function replaceDirectoryAtomically(
target: string,
prepare: (staged: string) => Promise<void>,
@@ -71,6 +99,7 @@ export async function replaceDirectoryAtomically(
const assertReady = opts.assertReady || (() => undefined);
const parent = path.dirname(target);
await fsp.mkdir(parent, { recursive: true });
+ await recoverPreviousDirectory(target, opts);
const staged = await fsp.mkdtemp(path.join(parent, `.${path.basename(target)}.install-`));
const backup = `${staged}.previous`;
let previousMoved = false;
diff --git a/test/main/features/auto_tasks.test.ts b/test/main/features/auto_tasks.test.ts
index 96f4019d..02974d09 100644
--- a/test/main/features/auto_tasks.test.ts
+++ b/test/main/features/auto_tasks.test.ts
@@ -2434,3 +2434,93 @@ describe('automation › daylight-saving calendar boundaries', () => {
expect(nextDueAfterRestoreForTest(task, repeated)?.toISOString()).toBe('2026-11-02T06:30:00.000Z');
});
});
+
+describe('automation › recovery discovery sequences', () => {
+ it.each(['success', 'failure'] as const)('preserves the claimed occurrence across restoration before a late %s', async outcome => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 4, 22, 8, 30));
+ const taskId = 'at_18181818';
+ expect((await createTask(TEST_UID, { id: taskId, content: 'Recovery discovery',
+ schedule: { type: 'daily', hour: 9, minute: 0 } })).ok).toBe(true);
+ stopScheduler();
+ let complete!: (value: {ok: boolean; error?: string}) => void;
+ autoRuntime.send.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));
+ const events: AutoFireEvent[] = [];
+ const unsubscribe = subscribeFiresForUser(TEST_UID, event => events.push(event));
+ try {
+ vi.setSystemTime(new Date(2026, 4, 22, 9, 0));
+ const firing = _onTimerFireForTest(TEST_UID, taskId);
+ await waitForSchedulerOutcome(() => !!complete, 'pending admitted send');
+ const persisted = fs.readFileSync(autoTaskConfigFile(TEST_UID, taskId));
+ expect((await getTask(TEST_UID, taskId))?.last_run_at).toBe(new Date(2026, 4, 22, 9, 0).toISOString());
+ expect(events).toEqual([]);
+ stopScheduler();
+ await rescheduleAllForTest(TEST_UID);
+ expect(armedDueAtForTest(taskId)).toBe(new Date(2026, 4, 23, 9, 0).getTime());
+ expect(autoRuntime.send).toHaveBeenCalledTimes(1);
+ complete(outcome === 'success' ? {ok:true} : {ok:false,error:'injected late refusal'});
+ await firing;
+ expect(events).toHaveLength(1);
+ expect(events[0].type).toBe(outcome === 'success' ? 'conv_created' : 'fire_failed');
+ expect(autoRuntime.deleteConversation).toHaveBeenCalledTimes(outcome === 'success' ? 0 : 1);
+ expect(fs.readFileSync(autoTaskConfigFile(TEST_UID, taskId))).toEqual(persisted);
+ stopScheduler();
+ await rescheduleAllForTest(TEST_UID);
+ await _onTimerFireForTest(TEST_UID, taskId);
+ expect(autoRuntime.send).toHaveBeenCalledTimes(1);
+ vi.setSystemTime(new Date(2026, 4, 23, 9, 0));
+ await _onTimerFireForTest(TEST_UID, taskId);
+ expect(autoRuntime.send).toHaveBeenCalledTimes(2);
+ expect(events).toHaveLength(2);
+ expect(events[1].type).toBe('conv_created');
+ expect((await getTask(TEST_UID, taskId))?.last_run_at).toBe(new Date(2026, 4, 23, 9, 0).toISOString());
+ } finally { unsubscribe(); }
+ });
+
+ it.each([false, true])('retries a failed migration from the latest source and rejects obsolete scoped mutations (rollback failure: %s)', async rollbackFails => {
+ const taskId='at_18181819', projectId='p_daily_recovery';
+ writeProject(TEST_UID, projectId);
+ expect((await createTask(TEST_UID, {id:taskId,project_id:projectId,content:'Original briefing',enabled:false,
+ schedule:{type:'daily',hour:18,minute:0},attachments:['source.txt']})).ok).toBe(true);
+ await uploadAttachment(TEST_UID,taskId,'source.txt',Buffer.from('revision one'));
+ const source=projectAutoTaskConfigFile(TEST_UID,projectId,taskId), target=autoTaskDir(TEST_UID,taskId);
+ const targetAttachments=autoTaskAttachmentsDir(TEST_UID,taskId);
+ fs.mkdirSync(targetAttachments,{recursive:true});
+ fs.writeFileSync(path.join(targetAttachments,'draft.txt'),'unrelated draft');
+ const initial=fs.readFileSync(source);
+ const rename=nativeFs.promises.rename.bind(nativeFs.promises);
+ const fault=Object.assign(new Error('injected activation failure'),{code:'ENOSPC'});
+ const spy=vi.spyOn(nativeFs.promises,'rename').mockImplementation(async(from,to)=>{
+ if(String(to)===target && (rollbackFails || !String(from).endsWith('.previous')))throw fault;
+ return rename(from,to);
+ });
+ syncBuiltinESMExports();
+ try {
+ await expect(updateTask(TEST_UID,taskId,{project_id:null})).rejects.toThrow(fault);
+ expect(fs.readFileSync(source)).toEqual(initial);
+ expect(fs.existsSync(autoTaskConfigFile(TEST_UID,taskId))).toBe(false);
+ if (rollbackFails) {
+ expect(fs.existsSync(target)).toBe(false);
+ const backups=fs.readdirSync(path.dirname(target)).filter(name=>name.startsWith(`.${taskId}.install-`)&&name.endsWith('.previous'));
+ expect(backups).toHaveLength(1);
+ expect(fs.readFileSync(path.join(path.dirname(target),backups[0],'attachments','draft.txt'),'utf8')).toBe('unrelated draft');
+ } else expect(fs.readdirSync(targetAttachments)).toEqual(['draft.txt']);
+ } finally {spy.mockRestore();syncBuiltinESMExports();}
+ expect((await updateTask(TEST_UID,taskId,{content:'Accepted revised briefing'},projectId)).ok).toBe(true);
+ await uploadAttachment(TEST_UID,taskId,'source.txt',Buffer.from('revision two'));
+ expect((await updateTask(TEST_UID,taskId,{project_id:null})).ok).toBe(true);
+ const durable=fs.readFileSync(autoTaskConfigFile(TEST_UID,taskId));
+ expect(await setTaskEnabled(TEST_UID,taskId,true,projectId)).toEqual({ok:false,error:'not_found'});
+ expect(await deleteTask(TEST_UID,taskId,projectId)).toEqual({ok:false});
+ expect(fs.readFileSync(autoTaskConfigFile(TEST_UID,taskId))).toEqual(durable);
+ stopScheduler();await rescheduleAllForTest(TEST_UID);
+ expect(await listTasks(TEST_UID)).toMatchObject([{id:taskId,content:'Accepted revised briefing',enabled:false}]);
+ expect(await listTasks(TEST_UID)).toHaveLength(1);
+ expect(fs.existsSync(source)).toBe(false);
+ expect(fs.readFileSync(path.join(targetAttachments,'source.txt'),'utf8')).toBe('revision two');
+ expect(fs.readFileSync(path.join(targetAttachments,'draft.txt'),'utf8')).toBe('unrelated draft');
+ expect(fs.readdirSync(path.dirname(target)).filter(name=>name.includes('.install-')||name.includes('.old-'))).toEqual([]);
+ expect(autoRuntime.send).not.toHaveBeenCalled();
+ expect(armedDueAtForTest(taskId)).toBeNull();
+ });
+});
diff --git a/test/main/features/builtin_marketplace.test.ts b/test/main/features/builtin_marketplace.test.ts
index b76284f3..ce6cad5f 100644
--- a/test/main/features/builtin_marketplace.test.ts
+++ b/test/main/features/builtin_marketplace.test.ts
@@ -1510,3 +1510,37 @@ describe('builtin marketplace seed', () => {
expect(commanderBlock).not.toContain('**evolved-helper**');
});
});
+
+describe('builtin recovery baseline', () => {
+ it.each(['agent', 'skill'] as const)('preserves recovered %s metadata and removes only retired managed files on retry', async kind => {
+ const id=kind==='agent'?TEST_AGENT_ID:'recovered-skill';
+ if(kind==='agent')writeBuiltinAgent(id,{name:'Recovery writer',workflow:'Write.',version:'1.0.0'});
+ else {writeBuiltinSkill(id);writeBuiltinSkillMeta(id,{version:'1.0.0'});}
+ const source=path.join(tmpDir,'builtin','marketplace',kind==='agent'?'agents':'skills',id);
+ fs.writeFileSync(path.join(source,'retired.txt'),'old managed file');
+ const seed=await import('../../../src/main/features/builtin_marketplace');
+ const paths=await import('../../../src/main/paths');
+ await seed.seedBuiltinMarketplaceForUser('u1');
+ const target=kind==='agent'?paths.userMarketplaceAgentDir('u1',id):paths.userMarketplaceSkillDir('u1',id);
+ fs.writeFileSync(path.join(target,'user-notes.txt'),'keep my notes');
+ const meta=JSON.parse(fs.readFileSync(path.join(target,'_install.json'),'utf8'));
+ meta.installed_at=123456;meta.default_install=false;meta.user_annotation='preserve';
+ fs.writeFileSync(path.join(target,'_install.json'),JSON.stringify(meta));
+ // The helper's persistent rollback-fault regression establishes this
+ // durable precondition. Seeding must read metadata after restoring it.
+ const backup=path.join(path.dirname(target),`.${id}.install-recovery.previous`);
+ fs.renameSync(target,backup);
+ fs.unlinkSync(path.join(source,'retired.txt'));
+ fs.writeFileSync(path.join(source,'current.txt'),'new managed file');
+ if(kind==='agent')writeBuiltinAgent(id,{name:'Recovery writer',workflow:'Write updated.',version:'2.0.0'});
+ else writeBuiltinSkillMeta(id,{version:'2.0.0'});
+ await seed.seedBuiltinMarketplaceForUser('u1');
+ expect(fs.readFileSync(path.join(target,'user-notes.txt'),'utf8')).toBe('keep my notes');
+ expect(fs.existsSync(path.join(target,'retired.txt'))).toBe(false);
+ expect(fs.readFileSync(path.join(target,'current.txt'),'utf8')).toBe('new managed file');
+ expect(JSON.parse(fs.readFileSync(path.join(target,'_install.json'),'utf8')))
+ .toMatchObject({version:'2.0.0',installed_at:123456,default_install:false,user_annotation:'preserve'});
+ expect(fs.existsSync(backup)).toBe(false);
+ expect(postJsonMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/main/util/atomic-directory-replace.test.ts b/test/main/util/atomic-directory-replace.test.ts
index 8146ca6b..3f40e52d 100644
--- a/test/main/util/atomic-directory-replace.test.ts
+++ b/test/main/util/atomic-directory-replace.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
+import nativeFs from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
import * as os from 'node:os';
import * as path from 'node:path';
@@ -118,6 +120,59 @@ describe('atomic directory replacement', () => {
expect(transactionArtifacts()).toEqual([]);
});
+ it('recovers the previous directory before retry preparation after activation and rollback both fail', async () => {
+ writeCurrent('user-maintained draft');
+ const rename = nativeFs.promises.rename.bind(nativeFs.promises);
+ const fault = Object.assign(new Error('injected persistent rename failure'), { code: 'ENOSPC' });
+ const spy = vi.spyOn(nativeFs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to) === target) throw fault;
+ return rename(from, to);
+ });
+ syncBuiltinESMExports();
+ try {
+ await expect(replaceDirectoryAtomically(target, async staged => {
+ fs.writeFileSync(path.join(staged, 'new.txt'), 'requested addition');
+ })).rejects.toThrow(fault);
+ } finally { spy.mockRestore(); syncBuiltinESMExports(); }
+ const backup = transactionArtifacts().find(name => name.endsWith('.previous'))!;
+ expect(fs.readFileSync(path.join(root, backup, 'content.txt'), 'utf8')).toBe('user-maintained draft');
+ expect(fs.existsSync(target)).toBe(false);
+ // The real consumer prepares a merge from the authoritative prior target.
+ // It cannot discover an unreported random backup name itself.
+ const commit = vi.fn(async () => undefined);
+ await replaceDirectoryAtomically(target, async staged => {
+ if (fs.existsSync(target)) fs.cpSync(target, staged, { recursive: true });
+ fs.writeFileSync(path.join(staged, 'new.txt'), 'requested addition');
+ }, commit);
+ await sweepStaleReplacementArtifacts(root);
+ expect(fs.existsSync(path.join(target, 'content.txt'))).toBe(true);
+ expect(fs.readFileSync(path.join(target, 'content.txt'), 'utf8')).toBe('user-maintained draft');
+ expect(fs.readFileSync(path.join(target, 'new.txt'), 'utf8')).toBe('requested addition');
+ expect(commit).toHaveBeenCalledOnce();
+ expect(transactionArtifacts()).toEqual([]);
+ });
+
+ it('keeps recovery behind the existing activation guard and preserves ambiguous backups', async () => {
+ const first = path.join(root, '.installed-item.install-one.previous');
+ fs.mkdirSync(first);
+ fs.writeFileSync(path.join(first, 'content.txt'), 'original');
+ const prepare = vi.fn(async () => undefined);
+ await expect(replaceDirectoryAtomically(target, prepare, undefined, {
+ activationGuard: async () => { throw new Error('account changed'); },
+ })).rejects.toThrow('account changed');
+ expect(fs.existsSync(target)).toBe(false);
+ expect(fs.readFileSync(path.join(first, 'content.txt'), 'utf8')).toBe('original');
+ expect(prepare).not.toHaveBeenCalled();
+ const second = path.join(root, '.installed-item.install-two.previous');
+ fs.mkdirSync(second);
+ fs.writeFileSync(path.join(second, 'content.txt'), 'different original');
+ await expect(replaceDirectoryAtomically(target, prepare)).rejects.toThrow('ambiguous');
+ expect(prepare).not.toHaveBeenCalled();
+ expect(fs.existsSync(target)).toBe(false);
+ expect(fs.readFileSync(path.join(second, 'content.txt'), 'utf8')).toBe('different original');
+ expect(fs.readFileSync(path.join(first, 'content.txt'), 'utf8')).toBe('original');
+ });
+
it('finishes staging before waiting for the activation guard', async () => {
writeCurrent();
let releaseActivation!: () => void;