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.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Retain strict storage reads and atomic binary publication
wytbd950e53c441
diff --git a/src/main/storage.ts b/src/main/storage.tsindex b93a349a..c1e0e826 100644--- a/src/main/storage.ts+++ b/src/main/storage.ts@@ -54,12 +54,17 @@ export function safeId(value: unknown): boolean {// ── JSON / JSONL IO ──────────────────────────────────────────────────────-/** Read a JSON file. Returns {} on any error (missing, invalid, etc.). */-export async function readJson<T = Record<string, any>>(filePath: string): Promise<T> {+/** Tolerant by default. Authoritative lookups opt into strict reads so an+ * unavailable source cannot be mistaken for an empty collection. */+export async function readJson<T = Record<string, any>>(+ filePath: string,+ opts?: { strict?: boolean },+): Promise<T> {try {const text = await fsp.readFile(filePath, 'utf8');return JSON.parse(text) as T;- } catch {+ } catch (error) {+ if (opts?.strict) throw error;return {} as T;}}@@ -126,6 +131,12 @@ export function renameWithRetry(tmp: string, filePath: string, shouldCommit?: ()return renameWithRetryUsing(tmp, filePath, shouldCommit ? fs.renameSync : fsp.rename, shouldCommit);}+/** Publish a completed same-filesystem inode without replacing an existing+ * destination, retaining the bounded asynchronous Windows lock retries. */+export async function linkWithRetry(source: string, target: string): Promise<void> {+ await renameWithRetryUsing(source, target, fsp.link);+}+function renameWithRetrySyncUsing(tmp: string,filePath: string,@@ -202,8 +213,8 @@ export async function writeBytesAtomic(filePath: string, data: Uint8Array, opts?export function writeJsonSync(filePath: string, data: unknown): void {fs.mkdirSync(path.dirname(filePath), { recursive: true });const tmp = atomicTmpPath(filePath);- fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');try {+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');renameWithRetrySync(tmp, filePath);} catch (err) {try { fs.rmSync(tmp, { force: true }); } catch {}@@ -222,6 +233,20 @@ export function writeTextAtomicSync(text: string,encoding: BufferEncoding = 'utf8',opts?: { mode?: number },+): void {+ writeFileAtomicSync(filePath, text, encoding, opts);+}++/** Publish binary bytes with the same bounded rename and cleanup as text. */+export function writeBytesAtomicSync(filePath: string, bytes: Uint8Array, opts?: { mode?: number }): void {+ writeFileAtomicSync(filePath, bytes, 'utf8', opts);+}++function writeFileAtomicSync(+ filePath: string,+ data: string | Uint8Array,+ encoding: BufferEncoding,+ opts?: { mode?: number },): void {fs.mkdirSync(path.dirname(filePath), { recursive: true });const tmp = atomicTmpPath(filePath);@@ -229,7 +254,7 @@ export function writeTextAtomicSync(// by secret-bearing writers (connectors.json, auth profiles) that need 0600.try {// A failed (e.g. disk-full) write must not leave a partial sibling behind.- fs.writeFileSync(tmp, text, { encoding, ...(opts && opts.mode !== undefined ? { mode: opts.mode } : {}) });+ fs.writeFileSync(tmp, data, { encoding, ...(opts && opts.mode !== undefined ? { mode: opts.mode } : {}) });renameWithRetrySync(tmp, filePath);} catch (err) {try { fs.rmSync(tmp, { force: true }); } catch {}@@ -397,14 +422,17 @@ function _concatJsonlSegments(segments: Buffer[]): Buffer {return Buffer.concat(segments);}-function _parseJsonlRecord<T>(line: string): T | undefined {+function _parseJsonlRecord<T>(line: string, strict = false): T | undefined {const trimmed = line.trim();if (!trimmed) return undefined;- try { return JSON.parse(trimmed) as T; } catch { return undefined; }+ try { return JSON.parse(trimmed) as T; } catch {+ if (strict) throw new Error('JSONL record is invalid');+ return undefined;+ }}-function _appendJsonlRecord<T>(out: T[], line: string): void {- const record = _parseJsonlRecord<T>(line);+function _appendJsonlRecord<T>(out: T[], line: string, strict = false): void {+ const record = _parseJsonlRecord<T>(line, strict);if (record !== undefined) out.push(record);}@@ -445,8 +473,9 @@ export async function readJsonlPage<T = Record<string, any>>(filePath: string,limit = 200,before?: number | null,+ opts?: { strict?: boolean },): Promise<JsonlPage<T>> {- const page = await readJsonlPageWithOffsets<T>(filePath, limit, before);+ const page = await readJsonlPageWithOffsets<T>(filePath, limit, before, opts);return {records: page.entries.map(({ record }) => record),nextCursor: page.nextCursor,@@ -458,12 +487,14 @@ export async function readJsonlPageWithOffsets<T = Record<string, any>>(filePath: string,limit = 200,before?: number | null,+ opts?: { strict?: boolean },): Promise<JsonlPageWithOffsets<T>> {const wanted = Math.max(1, Math.floor(Number(limit) || 1));let handle: fs.promises.FileHandle;try {handle = await fsp.open(filePath, 'r');- } catch {+ } catch (error) {+ if (opts?.strict) throw error;return { entries: [], nextCursor: null };}@@ -485,6 +516,7 @@ export async function readJsonlPageWithOffsets<T = Record<string, any>>(position -= bytes;const block = Buffer.allocUnsafe(bytes);const { bytesRead } = await handle.read(block, 0, bytes, position);+ if (opts?.strict && bytesRead !== bytes) throw new Error('JSONL read is incomplete');if (bytesRead <= 0) break;let end = bytesRead;@@ -494,7 +526,7 @@ export async function readJsonlPageWithOffsets<T = Record<string, any>>(const line = suffixSegments.length? _concatJsonlSegments([current, ...suffixSegments.reverse()]): current;- const record = _parseJsonlRecord<T>(line.toString('utf8'));+ const record = _parseJsonlRecord<T>(line.toString('utf8'), opts?.strict);if (record !== undefined) {const start = position + i + 1;newestFirst.push({ record, start });@@ -513,6 +545,7 @@ export async function readJsonlPageWithOffsets<T = Record<string, any>>(if (newestFirst.length < wanted && suffixSegments.length) {const record = _parseJsonlRecord<T>(_concatJsonlSegments(suffixSegments.reverse()).toString('utf8'),+ opts?.strict,);if (record !== undefined) {newestFirst.push({ record, start: 0 });@@ -685,22 +718,24 @@ export async function readJsonlWindowAtMatch<T = Record<string, any>>(* characters that straddle a disk-read boundary remain intact.** Non-positive limits retain the historical full-file behavior. Malformed- * lines are silently skipped, matching the previous Python-compatible read.+ * lines are silently skipped by default, matching the previous Python-compatible read.+ * Durable projections can opt into strict reads to distinguish missing, corrupt or incomplete IO.*/-export async function readJsonl<T = Record<string, any>>(filePath: string, limit = 200): Promise<T[]> {+export async function readJsonl<T = Record<string, any>>(filePath: string, limit = 200, opts?: { strict?: boolean }): Promise<T[]> {if (!Number.isFinite(limit) || limit < 1) {let text: string;try {text = await fsp.readFile(filePath, 'utf8');- } catch {+ } catch (error) {+ if (opts?.strict) throw error;return [];}const out: T[] = [];- for (const line of text.split('\n')) _appendJsonlRecord(out, line);+ for (const line of text.split('\n')) _appendJsonlRecord(out, line, opts?.strict);return out.slice(-limit);}- return (await readJsonlPage<T>(filePath, limit)).records;+ return (await readJsonlPage<T>(filePath, limit, undefined, opts)).records;}/** Read one immutable append receipt without scanning the conversation. */diff --git a/test/main/storage.test.ts b/test/main/storage.test.tsindex 86f0e034..d2057604 100644--- a/test/main/storage.test.ts+++ b/test/main/storage.test.ts@@ -6,7 +6,7 @@ import * as os from 'node:os';import * as path from 'node:path';import {nowIso, genUserId, genId12, safeId,- readJson, readJsonSync, writeJson, writeJsonSync,+ readJson, readJsonSync, writeJson, writeJsonSync, linkWithRetry,writeTextAtomicSync, writeTextAtomicGuardedSync, appendJsonl, appendJsonlAtomic,invalidateLineCount, readJsonl, readJsonlPage, readJsonlPageWithOffsets,readJsonlWindow, readJsonlWindowAtMatch, __storageTestHooks,@@ -81,7 +81,52 @@ describe('storage › safeId guard', () => {});});+describe('storage › exclusive file publication', () => {+ it('retains both byte sequences when a destination already exists', async () => {+ const source = path.join(tmpDir, 'complete.tmp');+ const target = path.join(tmpDir, 'winner.txt');+ fs.writeFileSync(source, 'new complete bytes');+ fs.writeFileSync(target, 'existing winner');+ await expect(linkWithRetry(source, target)).rejects.toMatchObject({ code: 'EEXIST' });+ expect(fs.readFileSync(source, 'utf8')).toBe('new complete bytes');+ expect(fs.readFileSync(target, 'utf8')).toBe('existing winner');+ });++ it('recovers from a transient Windows publication lock without blocking the event loop', async () => {+ const source = path.join(tmpDir, 'complete.tmp');+ const target = path.join(tmpDir, 'published.txt');+ fs.writeFileSync(source, 'complete bytes');+ const originalLink = fs.promises.link;+ let first = true;+ let timerRan = false;+ const timer = setTimeout(() => { timerRan = true; }, 0);+ vi.spyOn(fs.promises, 'link').mockImplementation(async (from, to) => {+ if (first) { first = false; throw eperm(); }+ await originalLink(from, to);+ });+ syncBuiltinESMExports();+ try {+ await linkWithRetry(source, target);+ expect(timerRan).toBe(true);+ expect(fs.readFileSync(target, 'utf8')).toBe('complete bytes');+ expect(fs.readFileSync(source, 'utf8')).toBe('complete bytes');+ } finally { clearTimeout(timer); vi.restoreAllMocks(); syncBuiltinESMExports(); }+ });+});+describe('storage › JSON IO', () => {+ it('strict reads preserve read failures and parse failures while tolerant callers retain compatibility', async () => {+ const missing = path.join(tmpDir, 'missing-strict.json');+ await expect(readJson(missing, { strict: true })).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await readJson(missing)).toEqual({});+ const file = path.join(tmpDir, 'recoverable.json');+ fs.writeFileSync(file, '{broken');+ await expect(readJson(file, { strict: true })).rejects.toBeInstanceOf(SyntaxError);+ expect(await readJson(file)).toEqual({});+ fs.writeFileSync(file, JSON.stringify({ agents: ['kept'] }));+ expect(await readJson(file, { strict: true })).toEqual({ agents: ['kept'] });+ });+it('writeJson + readJson roundtrip preserves UTF-8 and structure', async () => {const p = path.join(tmpDir, 'nested', 'a.json');const data = { x: 1, 中: '文', arr: [1, 2, 3], nested: { a: true } };@@ -89,6 +134,24 @@ describe('storage › JSON IO', () => {expect(await readJson(p)).toEqual(data);});+ it('preserves committed JSON and removes a partial sibling when a synchronous write runs out of space', () => {+ const target = path.join(tmpDir, 'state.json');+ fs.writeFileSync(target, JSON.stringify({ retained: true }));+ const originalWrite = fs.writeFileSync;+ vi.spyOn(nativeFs, 'writeFileSync').mockImplementation(((file: fs.PathOrFileDescriptor, data: any, ...args: any[]) => {+ if (typeof file === 'string' && file.startsWith(target + '.') && file.endsWith('.tmp')) {+ originalWrite(file, '{'); throw Object.assign(new Error('Controlled partial JSON write'), { code: 'ENOSPC' });+ }+ return (originalWrite as any)(file, data, ...args);+ }) as any);+ syncBuiltinESMExports();+ try {+ expect(() => writeJsonSync(target, { next: true })).toThrow('Controlled partial JSON write');+ expect(readJsonSync(target)).toEqual({ retained: true });+ expect(fs.readdirSync(tmpDir)).toEqual(['state.json']);+ } finally { vi.restoreAllMocks(); syncBuiltinESMExports(); }+ });+it('writeJson is atomic — no .tmp file left behind', async () => {const p = path.join(tmpDir, 'a.json');await writeJson(p, { ok: true });