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
Keep file edits and tool output tied to current inputs
wytbc5138ad4a6b
diff --git a/src/main/model/core-agent/file-tools.ts b/src/main/model/core-agent/file-tools.tsindex 1ecdd907..9651605e 100644--- a/src/main/model/core-agent/file-tools.ts+++ b/src/main/model/core-agent/file-tools.ts@@ -1554,7 +1554,7 @@ function createSearchFilesTool(opts: FileToolsOpts): AgentTool {const header = total > hits.length? `${total} match(es), showing ${maxResults}; backend=${[...backends].join('+') || 'walk'}:`: `${total} match(es); backend=${[...backends].join('+') || 'walk'}:`;- return { content: `${header}\n${completion}\n${formatSearchFileResults(hits)}` };+ return { content: `${header}\n${completion}\n${formatSearchFileResults(hits, path, ctx.workingDir)}` };} finally { budget.dispose(); }},};@@ -1974,7 +1974,7 @@ function createListFilesTool(opts: FileToolsOpts): AgentTool {inputSchema: {type: 'object',properties: {- path: { type: 'string', description: 'Directory relative to the working directory, a visible absolute directory, or @skill/<read-ref>[/relative-path] for a Skill advertised in this run.' },+ path: { type: 'string', minLength: 1, description: 'Directory relative to the working directory (use "." for that directory), a visible absolute directory, or @skill/<read-ref>[/relative-path] for a Skill advertised in this run.' },},required: ['path'],},diff --git a/src/main/model/core-agent/read-tracker.ts b/src/main/model/core-agent/read-tracker.tsindex 1f0cf760..3d2fe923 100644--- a/src/main/model/core-agent/read-tracker.ts+++ b/src/main/model/core-agent/read-tracker.ts@@ -56,6 +56,15 @@ function stampFromStats(st: fs.Stats, hash?: string): ReadStamp {return { mtimeMs: st.mtimeMs, size: st.size, ...(hash ? { hash } : {}) };}+/** The stamp a host seeds for a file whose complete decoded text it put in+ * front of the model itself (see `AgentRunParams.initialReadFileState`).+ * `hash` must be the same `sha256:` digest of the UTF-8 re-encoded text+ * that `edit_file` computes, so a later edit compares content, not only+ * metadata. */+export function readStampFromStats(st: fs.Stats, hash: string): ReadStamp {+ return stampFromStats(st, hash);+}+/** Record that `abs` was read (or written) at its current on-disk state, so a* later `edit_file` accepts an edit built on these bytes. Best-effort: a stat* failure is swallowed (the edit path re-stats and will reject if needed).diff --git a/src/main/util/atomic-directory-replace.ts b/src/main/util/atomic-directory-replace.tsindex 7d1efb0f..5a13f80b 100644--- a/src/main/util/atomic-directory-replace.ts+++ b/src/main/util/atomic-directory-replace.ts@@ -23,12 +23,11 @@ const activeReplacementArtifacts = new Set<string>();const REPLACEMENT_ARTIFACT_RE = /^\.(.+)\.install-[^.]+(?:\.previous)?$/;-/** Remove staging (`.<name>.install-*`) and backup (`*.previous`) directories a- * crashed or killed replacement left under `parent`. They start with a dot,- * so the install listings never showed them and nothing ever reclaimed- * their space. Live artifacts are skipped. A previous-directory backup is- * retained if activation never installed a real target directory: it may- * contain the only recoverable copy of the user's prior content. */+/** Remove abandoned staging (`.<name>.install-*`) directories under `parent`.+ * Live artifacts and previous-directory backups are retained: an existing+ * target may be a rejected candidate whose rollback also failed, not proof of+ * a successful metadata commit. Successful replacements clean their own+ * backups; maintenance cannot decide that an orphan prior copy is disposable. */export async function sweepStaleReplacementArtifacts(parent: string,onCleanupError?: (err: unknown, artifactPath: string) => void,@@ -36,7 +35,11 @@ export async function sweepStaleReplacementArtifacts(let entries: fs.Dirent[];try {entries = await fsp.readdir(parent, { withFileTypes: true });- } catch {+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ if (!onCleanupError) throw err;+ onCleanupError(err, parent);+ }return [];}const removed: string[] = [];@@ -45,18 +48,13 @@ export async function sweepStaleReplacementArtifacts(if (!entry.isDirectory() || !match) continue;const artifact = path.join(parent, entry.name);if (activeReplacementArtifacts.has(artifact)) continue;- if (entry.name.endsWith('.previous')) {- try {- if (!fs.lstatSync(path.join(parent, match[1])).isDirectory()) continue;- } catch {- continue;- }- }+ if (entry.name.endsWith('.previous')) continue;try {await fsp.rm(artifact, { recursive: true, force: true });removed.push(artifact);} catch (err) {- onCleanupError?.(err, artifact);+ if (!onCleanupError) throw err;+ onCleanupError(err, artifact);}}return removed;diff --git a/src/main/util/path-sandbox.ts b/src/main/util/path-sandbox.tsindex 28d87c3d..d73b5787 100644--- a/src/main/util/path-sandbox.ts+++ b/src/main/util/path-sandbox.ts@@ -13,27 +13,43 @@** Symlink handling: uses `fs.realpathSync` on both sides so a symlink* planted inside an allowed root cannot exfiltrate to /etc/passwd. If the- * candidate doesn't exist yet (write path — not our case today), falls- * back to lexical resolve so the check still works.+ * candidate does not exist yet, resolves known links and its nearest existing+ * ancestor. Truly unresolvable entries fail closed at authorization.*/import * as fs from 'node:fs';import * as path from 'node:path';-function realOrResolve(p: string): string {+function realOrResolve(p: string, identityOnly = false, seenLinks?: Set<string>): string | null {try { return fs.realpathSync(p); }catch {- // Path doesn't exist — walk up until we hit an existing ancestor, realpath- // that, then rejoin the missing tail. Needed because macOS tmpdir- // (/var/folders/...) is itself a symlink to /private/var/..., so plain- // path.resolve on a nonexistent candidate wouldn't match a realpath-ed- // existing root.+ // Missing descendants inherit the real existing ancestor. Existing links+ // retain their actual target even when that target has not been created.const resolved = path.resolve(p);let existing = resolved;const missing: string[] = [];while (existing && existing !== path.dirname(existing)) {try { existing = fs.realpathSync(existing); break; }catch {+ if (!identityOnly) {+ let entry: fs.Stats | undefined;+ try { entry = fs.lstatSync(existing); }+ catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT' && code !== 'ENOTDIR') return null;+ }+ if (entry) {+ // Only a known symlink target can resolve an existing entry here.+ // Cycles, inaccessible entries and non-directory ancestors deny.+ const links = seenLinks ?? new Set<string>();+ if (!entry.isSymbolicLink() || links.has(existing) || links.size >= 40) return null;+ links.add(existing);+ try {+ const target = path.resolve(path.dirname(existing), fs.readlinkSync(existing), ...missing);+ return realOrResolve(target, false, links);+ } catch { return null; }+ }+ }missing.unshift(path.basename(existing));existing = path.dirname(existing);}@@ -52,12 +68,15 @@ function comparisonKey(p: string): string {* realpath walk once and pass `{ rootsResolved: true }` afterwards.*/export function resolveSandboxRoot(root: string): string {- return realOrResolve(root);+ // Keep best-effort identity compatibility for an unresolvable root; the+ // authorization check still resolves each candidate and rejects unknowns.+ return realOrResolve(root) ?? realOrResolve(root, true) ?? path.resolve(root);}/** Resolve an unlink operand without following its final directory entry. */export function resolveSandboxEntry(candidate: string): string {- return path.join(realOrResolve(path.dirname(candidate)), path.basename(candidate));+ const parent = path.dirname(candidate);+ return path.join(realOrResolve(parent) ?? realOrResolve(parent, true) ?? path.resolve(parent), path.basename(candidate));}export interface PathAllowedOptions {@@ -94,16 +113,21 @@ export function isPathAllowed(const parts = candidate.split(path.sep);if (!parts.at(-1) || parts.at(-1) === '.' || parts.includes('..')) return false;}+ const realParent = options.followFinalSymlink === false+ ? realOrResolve(path.dirname(candidate)) : null;const realCand = options.followFinalSymlink === false- ? resolveSandboxEntry(candidate)+ ? (realParent ? path.join(realParent, path.basename(candidate)) : null): realOrResolve(candidate);+ if (!realCand) return false;const candidateKey = comparisonKey(realCand);for (const root of allowedRoots) {if (!root || !path.isAbsolute(root)) continue;const realRoot = options.rootsResolved ? root : realOrResolve(root);+ if (!realRoot) continue;const rootKey = comparisonKey(realRoot);if (candidateKey === rootKey) return true;- if (candidateKey.startsWith(rootKey + path.sep)) return true;+ const prefix = rootKey.endsWith(path.sep) ? rootKey : rootKey + path.sep;+ if (candidateKey.startsWith(prefix)) return true;}return false;}diff --git a/src/main/util/public-material.ts b/src/main/util/public-material.tsindex 3aa9556d..8535bc83 100644--- a/src/main/util/public-material.ts+++ b/src/main/util/public-material.ts@@ -2,6 +2,40 @@ import * as fs from 'node:fs';import * as path from 'node:path';import { createPublicKey, X509Certificate } from 'node:crypto';+/** Check the complete BER/DER envelope, independently of native crypto's+ * semantic validation (which may accept a prefix). Reads stay bounded by the+ * existing 64 KiB file limit; indefinite constructed values have a depth cap. */+function publicObjectEnd(bytes: Buffer, offset = 0, depth = 0): number {+ if (depth > 64 || offset + 2 > bytes.length) return -1;+ const tag = bytes[offset++];+ if ((tag & 0x1f) === 0x1f) {+ do { if (offset >= bytes.length) return -1; } while (bytes[offset++] & 0x80);+ }+ if (offset >= bytes.length) return -1;+ const first = bytes[offset++];+ if (first === 0x80) {+ if (!(tag & 0x20)) return -1;+ while (offset + 2 <= bytes.length) {+ if (bytes[offset] === 0 && bytes[offset + 1] === 0) return offset + 2;+ const end = publicObjectEnd(bytes, offset, depth + 1);+ if (end <= offset) return -1;+ offset = end;+ }+ return -1;+ }+ let size = first;+ if (first & 0x80) {+ const count = first & 0x7f;+ if (offset + count > bytes.length) return -1;+ size = 0;+ for (let i = 0; i < count; i++) {+ size = size * 256 + bytes[offset++];+ if (size > bytes.length) return -1;+ }+ }+ return offset + size <= bytes.length ? offset + size : -1;+}+/** Content proof for the shipped credential-path policy, never a general path* grant. Bounded reads, no cache (a template may acquire secrets after a write).* Comments and trailing data are deliberately not accepted as public proof. */@@ -28,6 +62,8 @@ export function isVerifiedPublicMaterial(file: string): boolean {}const pem = /^-----BEGIN (CERTIFICATE|PUBLIC KEY|RSA PUBLIC KEY)-----\r?\n[A-Za-z0-9+/=\r\n]+\r?\n-----END \1-----$/.exec(text);if (pem) {+ const bytes = Buffer.from(text.split(/\r?\n/).slice(1, -1).join(''), 'base64');+ if (bytes[0] !== 0x30 || publicObjectEnd(bytes) !== bytes.length) return false;if (pem[1] === 'CERTIFICATE') new X509Certificate(text);else createPublicKey(text);return true;diff --git a/src/main/util/tool-result-cap.ts b/src/main/util/tool-result-cap.tsindex 247286aa..7fbb881a 100644--- a/src/main/util/tool-result-cap.ts+++ b/src/main/util/tool-result-cap.ts@@ -18,7 +18,7 @@import { appendInputReceipt } from '../../../bin/tool-input-compat.cjs';import * as fs from 'fs';import * as path from 'path';-import { createHash } from 'crypto';+import { createHash, randomUUID } from 'crypto';import { StringDecoder } from 'node:string_decoder';import type { AgentTool, ToolResult, ToolContext } from '#core-agent';import { createLogger } from '../logger';@@ -433,7 +433,7 @@ export function persistToolResult(.slice(0, TOOL_RESULT_REF_HASH_HEX);const abs = path.join(toolResultsDir, `${safeTool}.${id}.txt`);if (fs.existsSync(abs)) return abs;- const tmp = `${abs}.${process.pid}.tmp`;+ const tmp = `${abs}.${process.pid}.${randomUUID()}.tmp`;try {fs.writeFileSync(tmp, content, { encoding: 'utf8', mode: 0o600 });fs.renameSync(tmp, abs);diff --git a/test/main/features/local_access_policy.test.ts b/test/main/features/local_access_policy.test.tsindex 8816f3cc..32bacd8b 100644--- a/test/main/features/local_access_policy.test.ts+++ b/test/main/features/local_access_policy.test.ts@@ -2,7 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';-import { generateKeyPairSync } from 'node:crypto';+import { syncBuiltinESMExports } from 'node:module';+import { generateKeyPairSync, ECDH, X509Certificate } from 'node:crypto';const UID = 'localaccesspolicy001';@@ -262,3 +263,161 @@ describe('local_access_policy', () => {.toEqual(['external_mutation']);});});+++// A successful native parse may consume only an ASN.1 prefix. The entire+// encoded file must be public. Preserve the desktop runtime's existing+// decisions for legacy/BER variants as well as its supported encodings.+describe('complete public material proof', () => {+ function sample(shape: string): { label: string; bytes: Buffer } {+ if (shape.startsWith('certificate')) {+ const text = fs.readFileSync(path.join(__dirname, '../../fixtures/public-proof-certificate.pem'), 'utf8');+ const bytes = new X509Certificate(text).raw;+ if (shape === 'certificate-ber') {+ const header = 2 + ((bytes[1] & 0x80) ? bytes[1] & 0x7f : 0);+ return { label: 'CERTIFICATE', bytes: Buffer.concat([Buffer.from([0x30, 0x80]), bytes.subarray(header), Buffer.from([0, 0])]) };+ }+ return { label: 'CERTIFICATE', bytes };+ }+ if (shape.startsWith('rsa')) {+ const key = generateKeyPairSync('rsa', { modulusLength: 2048 }).publicKey;+ if (shape === 'rsa-pkcs1') return { label: 'RSA PUBLIC KEY', bytes: key.export({ type: 'pkcs1', format: 'der' }) };+ const bytes = key.export({ type: 'spki', format: 'der' });+ if (shape === 'rsa-absent-null') {+ expect([...bytes.subarray(4, 6)]).toEqual([0x30, 13]);+ expect([...bytes.subarray(17, 19)]).toEqual([5, 0]);+ const legacy = Buffer.concat([bytes.subarray(0, 4), Buffer.from([0x30, 11]), bytes.subarray(6, 17), bytes.subarray(19)]);+ legacy.writeUInt16BE(legacy.length - 4, 2);+ return { label: 'PUBLIC KEY', bytes: legacy };+ }+ return { label: 'PUBLIC KEY', bytes };+ }+ if (shape.startsWith('ec')) {+ const bytes = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).publicKey.export({ type: 'spki', format: 'der' });+ if (shape === 'ec-compressed') {+ const point = ECDH.convertKey(bytes.subarray(-65), 'prime256v1', undefined, undefined, 'compressed') as Buffer;+ return { label: 'PUBLIC KEY', bytes: Buffer.concat([Buffer.from([0x30, 57]), bytes.subarray(2, 23), Buffer.from([3, 34, 0]), point]) };+ }+ return { label: 'PUBLIC KEY', bytes };+ }+ const bytes = generateKeyPairSync('ed25519').publicKey.export({ type: 'spki', format: 'der' });+ if (shape === 'ed25519-ber') return { label: 'PUBLIC KEY', bytes: Buffer.concat([Buffer.from([0x30, 0x80]), bytes.subarray(2), Buffer.from([0, 0])]) };+ if (shape === 'ed25519-nested-ber') return { label: 'PUBLIC KEY', bytes: Buffer.concat([Buffer.from([0x30, 0x80, 0x30, 0x80]), bytes.subarray(4, 9), Buffer.from([0, 0]), bytes.subarray(9), Buffer.from([0, 0])]) };+ return { label: 'PUBLIC KEY', bytes };+ }+ const pem = (label: string, bytes: Buffer) => `-----BEGIN ${label}-----\n${bytes.toString('base64')}\n-----END ${label}-----\n`;++ it.each(['ed25519', 'rsa-spki', 'rsa-pkcs1', 'rsa-absent-null', 'ec', 'ec-compressed', 'ed25519-ber', 'ed25519-nested-ber', 'certificate', 'certificate-ber'])(+ 'preserves the native %s decision and rejects additional encoded data at both policy consumers', async shape => {+ const { isVerifiedPublicMaterial } = await import('../../../src/main/util/public-material');+ const policy = await import('../../../src/main/features/local_access_policy');+ const { ordinaryBashReasons } = await import('../../../src/main/model/core-agent/ordinary-shell-operations');+ const { label, bytes } = sample(shape);+ const file = path.join(tmpDir, 'record.pem');+ const valid = pem(label, bytes);+ const ctx = { cwd: tmpDir, platform: 'linux' as const, canWrite: () => true, isProduced: () => false, ownsTree: () => false };+ const supported = !['rsa-absent-null', 'ed25519-ber', 'ed25519-nested-ber', 'certificate-ber'].includes(shape);+ fs.writeFileSync(file, valid);+ expect(isVerifiedPublicMaterial(file)).toBe(supported);+ expect(policy.sensitivePathReasons(file)).toEqual(supported ? [] : ['sensitive_path']);+ expect(policy.sensitivePathReasons(file, 'write')).toEqual(['sensitive_path']);+ expect(ordinaryBashReasons('cat record.pem', ctx).has('sensitive_path')).toBe(supported);+ fs.writeFileSync(file, pem(label, Buffer.concat([bytes, Buffer.from('synthetic-private-marker')])));+ expect({ proof: isVerifiedPublicMaterial(file), pathReasons: policy.sensitivePathReasons(file),+ shellExemption: ordinaryBashReasons('cat record.pem', ctx).has('sensitive_path'),+ powershellExemption: ordinaryBashReasons('Get-Content -Raw -LiteralPath record.pem', { ...ctx, platform: 'win32' }).has('sensitive_path'),+ }).toEqual({ proof: false, pathReasons: ['sensitive_path'], shellExemption: false, powershellExemption: false });+ fs.writeFileSync(file, valid);+ expect(isVerifiedPublicMaterial(file)).toBe(supported);+ },+ );++ it.each([+ [], [0x30], [0x30, 0x82, 1], [0x30, 0x84, 255, 255, 255, 255],+ [0x30, 0x80], [0x30, 0x80, 3, 0x80, 0, 0, 0, 0],+ [0x30, 0x80, 0x1f, 0x81], [0x30, 0x80, 0x1f],+ [0x30, 1, 0], [0x30, 0, 0, 0],+ ].map(bytes => [bytes]))('does not grant public proof for truncated or malformed ASN.1 %j', async bytes => {+ const { isVerifiedPublicMaterial } = await import('../../../src/main/util/public-material');+ const file = path.join(tmpDir, 'malformed.pem');+ fs.writeFileSync(file, pem('PUBLIC KEY', Buffer.from(bytes)));+ expect(isVerifiedPublicMaterial(file)).toBe(false);+ });++ it('keeps public proof bounded to a single regular file and the 64 KiB limit', async () => {+ const { isVerifiedPublicMaterial } = await import('../../../src/main/util/public-material');+ const text = pem('PUBLIC KEY', sample('ed25519').bytes);+ const file = path.join(tmpDir, 'bounded.pem');+ const alias = path.join(tmpDir, 'alias.pem');+ fs.mkdirSync(path.join(tmpDir, 'directory.pem'));+ expect(isVerifiedPublicMaterial(path.join(tmpDir, 'directory.pem'))).toBe(false);+ expect(isVerifiedPublicMaterial(file)).toBe(false);+ fs.writeFileSync(file, text);+ fs.symlinkSync(file, alias);+ expect(isVerifiedPublicMaterial(alias)).toBe(false);+ fs.unlinkSync(alias);+ fs.linkSync(file, alias);+ expect(isVerifiedPublicMaterial(file)).toBe(false);+ fs.unlinkSync(alias);+ expect(isVerifiedPublicMaterial(file)).toBe(true);+ fs.writeFileSync(file, text.padEnd(64 * 1024, ' '));+ expect(isVerifiedPublicMaterial(file)).toBe(true);+ fs.appendFileSync(file, ' ');+ expect(isVerifiedPublicMaterial(file)).toBe(false);+ fs.writeFileSync(file, '');+ expect(isVerifiedPublicMaterial(file)).toBe(false);+ fs.writeFileSync(file, text);+ expect(isVerifiedPublicMaterial(file)).toBe(true);+ });++ it.each(['open', 'fstat', 'read', 'short-read', 'changed-inode', 'changed-device', 'changed-size'])(+ 'denies unknown public content on %s, closes opened descriptors and recovers', async fault => {+ const { isVerifiedPublicMaterial } = await import('../../../src/main/util/public-material');+ const file = path.join(tmpDir, 'fault.pem');+ fs.writeFileSync(file, pem('PUBLIC KEY', sample('ed25519').bytes));+ const fail = () => { throw Object.assign(new Error('controlled unreadable fixture'), { code: 'EIO' }); };+ const nodeFs = (await import('node:fs')).default;+ const close = vi.spyOn(nodeFs, 'closeSync');+ const originalStat = nodeFs.fstatSync;+ let injected: { mockRestore(): void };+ if (fault === 'open') injected = vi.spyOn(nodeFs, 'openSync').mockImplementation(fail);+ else if (fault === 'read') injected = vi.spyOn(nodeFs, 'readSync').mockImplementation(fail);+ else if (fault === 'short-read') injected = vi.spyOn(nodeFs, 'readSync').mockReturnValue(0);+ else injected = vi.spyOn(nodeFs, 'fstatSync').mockImplementation(((fd: number) => {+ if (fault === 'fstat') return fail();+ const original = originalStat(fd);+ const field = fault === 'changed-inode' ? 'ino' : fault === 'changed-device' ? 'dev' : 'size';+ return { ...original, [field]: Number(original[field]) + 1 };+ }) as typeof fs.fstatSync);+ syncBuiltinESMExports();+ try {+ expect(isVerifiedPublicMaterial(file)).toBe(false);+ expect(close).toHaveBeenCalledTimes(fault === 'open' ? 0 : 1);+ } finally { injected.mockRestore(); close.mockRestore(); syncBuiltinESMExports(); }+ expect(isVerifiedPublicMaterial(file)).toBe(true);+ },+ );++ it.each(['ed25519', 'rsa-spki', 'rsa-pkcs1', 'ec', 'ec-compressed', 'certificate'])(+ 'rejects extra material around and inside the %s encoding', async shape => {+ const { isVerifiedPublicMaterial } = await import('../../../src/main/util/public-material');+ const { label, bytes } = sample(shape);+ const file = path.join(tmpDir, 'encoding.pem');+ const encoded = bytes.toString('base64');+ const header = 2 + ((bytes[1] & 0x80) ? bytes[1] & 0x7f : 0);+ const content = Buffer.concat([bytes.subarray(header), Buffer.from([4, 3, 65, 66, 67])]);+ const length = content.length < 128 ? Buffer.from([content.length]) : Buffer.from([0x82, content.length >> 8, content.length & 255]);+ for (const text of [+ `-----BEGIN ${label}-----\n${encoded}QUJD\n-----END ${label}-----\n`,+ `-----BEGIN ${label}-----\n${encoded}==\n-----END ${label}-----\n`,+ pem(label, bytes) + pem(label, bytes),+ pem(label, Buffer.concat([Buffer.from([0x30]), length, content])),+ ]) {+ fs.writeFileSync(file, text);+ expect(isVerifiedPublicMaterial(file)).toBe(false);+ }+ fs.writeFileSync(file, pem(label, bytes));+ expect(isVerifiedPublicMaterial(file)).toBe(true);+ },+ );+});diff --git a/test/main/model/core-agent/file-edit-handoff.test.ts b/test/main/model/core-agent/file-edit-handoff.test.tsnew file mode 100644index 00000000..8c09c499--- /dev/null+++ b/test/main/model/core-agent/file-edit-handoff.test.ts@@ -0,0 +1,98 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++vi.mock('../../../../src/main/logger', () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));++const uid = 'file-edit-handoff';+let root: string;+let previousRoot: string | undefined;++beforeEach(async () => {+ previousRoot = process.env.ORKAS_WORKSPACE_ROOT;+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-file-handoff-'));+ process.env.ORKAS_WORKSPACE_ROOT = root;+ vi.resetModules();+ const users = await import('../../../../src/main/features/users');+ users.activateUser(uid);+ const permissions = await import('../../../../src/main/features/permissions');+ permissions.setLocalExecMode('all_files_auto');+});++afterEach(() => {+ if (previousRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;+ else process.env.ORKAS_WORKSPACE_ROOT = previousRoot;+ fs.rmSync(root, { recursive: true, force: true });+});++async function setup() {+ const workingDir = path.join(root, 'workspace');+ fs.mkdirSync(workingDir);+ const workspace = await import('../../../../src/main/features/user_workspace');+ expect(workspace.setWorkspacePath(uid, workingDir).ok).toBe(true);+ const { createLocalTools } = await import('../../../../src/main/model/core-agent/local-tools');+ const { createFileTools } = await import('../../../../src/main/model/core-agent/file-tools');+ const opts = { userId: uid, cid: 'handoff' };+ const tools = [...createLocalTools(opts), ...createFileTools(opts)];+ const ctx = { workingDir, state: { readFileState: new Map() } } as any;+ const call = (name: string, input: Record<string, unknown>) => tools.find(t => t.name === name)!.execute(input, ctx);+ const patch = (from: string, to: string) => ({ patch: `*** Begin Patch\n*** Update File: target.py\n@@\n-${from}\n+${to}\n*** End Patch` });+ return { workingDir, ctx, call, patch, target: path.join(workingDir, 'target.py') };+}++// Replay the two observed handoffs with real file executors and shell commands.+// File bytes are the independent oracle; a rejected edit must not write anything.+it.skipIf(process.platform === 'win32')('reproduces N02: shell read cannot establish a patch baseline; explicit file read recovers', async () => {+ const { target, ctx, call, patch } = await setup();+ fs.writeFileSync(target, 'value = 1\n');+ const shell = await call('bash', { command: "sed -n '1,10p' target.py" });+ expect(shell.isError).toBeFalsy();+ expect(shell.content).toContain('value = 1');+ expect(ctx.state.readFileState.has(target)).toBe(false);+ const rejected = await call('apply_patch', patch('value = 1', 'value = 2'));+ expect(rejected.content).toContain('E_NOT_READ');+ expect(fs.readFileSync(target, 'utf8')).toBe('value = 1\n');+ expect((await call('read_files', { paths: [{ path: 'target.py' }] })).isError).toBeFalsy();+ expect((await call('apply_patch', patch('value = 1', 'value = 2'))).isError).toBeFalsy();+ expect(fs.readFileSync(target, 'utf8')).toBe('value = 2\n');+});++it.skipIf(process.platform === 'win32')('reproduces N09: shell-created source needs a file read before targeted editing', async () => {+ const { target, ctx, call } = await setup();+ expect((await call('bash', { command: "cat > target.py <<'PY'\nvalue = 1\nPY" })).isError).toBeFalsy();+ expect(fs.readFileSync(target, 'utf8')).toBe('value = 1\n');+ expect(ctx.state.readFileState.has(target)).toBe(false);+ const edit = { path: 'target.py', old_string: 'value = 1', new_string: 'value = 2' };+ const rejected = await call('edit_file', edit);+ expect(rejected.content).toContain('E_NOT_READ');+ expect(fs.readFileSync(target, 'utf8')).toBe('value = 1\n');+ expect((await call('read_files', { paths: [{ path: 'target.py' }] })).isError).toBeFalsy();+ expect((await call('edit_file', edit)).isError).toBeFalsy();+ expect(fs.readFileSync(target, 'utf8')).toBe('value = 2\n');+});++it.skipIf(process.platform === 'win32')('preserves a dedicated read across unrelated shell work and rejects a later shell mutation', async () => {+ const { target, call, patch } = await setup();+ fs.writeFileSync(target, 'value = 1\n');+ expect((await call('read_files', { paths: [{ path: 'target.py' }] })).isError).toBeFalsy();+ expect((await call('bash', { command: "cat > other.py <<'PY'\nother = 1\nPY" })).isError).toBeFalsy();+ expect((await call('apply_patch', patch('value = 1', 'value = 2'))).isError).toBeFalsy();+ expect((await call('bash', { command: "cat > target.py <<'PY'\nvalue = 9\nPY" })).isError).toBeFalsy();+ const stale = await call('apply_patch', patch('value = 9', 'value = 3'));+ expect(stale.content).toContain('E_STALE');+ expect(fs.readFileSync(target, 'utf8')).toBe('value = 9\n');+});++it.each(['write_file', 'apply_patch'])('continues editing after a dedicated %s creates the file without another read', async creator => {+ const { target, call, patch } = await setup();+ const input = creator === 'write_file'+ ? { path: 'target.py', content: 'value = 1\n' }+ : { patch: '*** Begin Patch\n*** Add File: target.py\n+value = 1\n*** End Patch' };+ expect((await call(creator, input)).isError).toBeFalsy();+ expect((await call('edit_file', { path: 'target.py', old_string: 'value = 1', new_string: 'value = 2' })).isError).toBeFalsy();+ expect((await call('apply_patch', patch('value = 2', 'value = 3'))).isError).toBeFalsy();+ expect(fs.readFileSync(target, 'utf8')).toBe('value = 3\n');+});diff --git a/test/main/model/core-agent/file-tools.test.ts b/test/main/model/core-agent/file-tools.test.tsindex 9e07709a..8cd8ed57 100644--- a/test/main/model/core-agent/file-tools.test.ts+++ b/test/main/model/core-agent/file-tools.test.ts@@ -109,7 +109,7 @@ function attachmentDir(): string {function searchResults(content: string): {roots: string[];- files: Array<{ root: number; path: string; name: string; size: number; mtime: string; source: string; total_chars?: number }>;+ files: Array<{ root: number; path: string; read_path: string; name: string; size: number; mtime: string; source: string; total_chars?: number }>;} {return JSON.parse(content.slice(content.indexOf('{')));}@@ -348,6 +348,24 @@ describe('file-tools › working-directory-relative paths', () => {});describe('file-tools › list_files', () => {+ it('advertises the existing nonempty path requirement while dot lists the current directory', async () => {+ const { tools, wsDir } = await buildTools();+ fs.writeFileSync(path.join(wsDir, 'accounts.csv'), 'customer,value\nAster,1500\n');+ const tool = getTool(tools, 'list_files');+ const ctx = { workingDir: wsDir, state: {} } as any;+ const invalid = await tool.execute({ path: '' }, ctx);+ expect(invalid.isError).toBe(true);+ expect(invalid.content).toContain('E_BAD_INPUT');+ const listed = await tool.execute({ path: '.' }, ctx);+ expect(listed.isError).toBeFalsy();+ expect(listed.content).toContain('f accounts.csv');+ const { toToolDefinition } = await import('../../../../src/core-agent/src/tools');+ const schema = toToolDefinition(tool).inputSchema as any;+ expect(schema.required).toContain('path');+ expect(schema.properties.path).toMatchObject({ type: 'string', minLength: 1 });+ expect(schema.properties.path.description).toContain('use "." for that directory');+ });+it('treats a lazy, not-yet-created conversation cwd as an empty directory', async () => {const { tools, wsDir } = await buildTools();const lazyCwd = path.join(wsDir, 'new-conversation');@@ -1171,7 +1189,8 @@ describe('file-tools › read_file scope guards', () => {const { roots, files } = searchResults(result.content);const address = path.posix.join(roots[files[0].root], files[0].path);expect(address).toBe('@skill/bundle/references/facts.md');- const read = await run(getTool(tools, 'read_files'), { paths: [{ path: address }] });+ expect(files[0].read_path).toBe(address);+ const read = await run(getTool(tools, 'read_files'), { paths: [{ path: files[0].read_path }] });expect(read.isError, read.content).toBeFalsy();expect(read.content).toContain('needle fact');}@@ -2564,6 +2583,63 @@ describe('file-tools › read_files metadata_only', () => {});describe('file-tools › search_files', () => {+ it.each(['account', 'project'])('reads discovered files directly from a nested %s conversation cwd', async (scope) => {+ const { tools, wsDir, attDir } = scope === 'project' ? await buildProjectTools() : await buildTools();+ const cwd = path.join(wsDir, 'conversation');+ const sources = [+ [path.join(cwd, 'accounts.csv'), 'current conversation'],+ [path.join(cwd, 'conversation', 'accounts.csv'), 'real nested directory'],+ [path.join(attDir, 'accounts.csv'), 'current attachment'],+ ];+ for (const [file, body] of sources) {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, body);+ }+ const ctx = { workingDir: cwd, state: {} } as any;+ const result = await getTool(tools, 'search_files').execute({ query: 'accounts.csv' }, ctx);+ expect(result.isError, result.content).toBeFalsy();+ const { roots, files } = searchResults(result.content);+ expect(files).toHaveLength(sources.length);+ for (const [file, body] of sources) {+ const found = files.find(f => path.join(roots[f.root], f.path) === file)!;+ expect(found, file).toBeDefined();+ expect(found.read_path).toBe(file.startsWith(`${cwd}${path.sep}`) ? path.relative(cwd, file) : file);+ const read = await getTool(tools, 'read_files').execute({ paths: [{ path: found.read_path }] }, ctx);+ expect(read.isError, read.content).toBeFalsy();+ expect(read.content).toContain(body);+ expect(fs.readFileSync(file, 'utf8')).toBe(body);+ }+ // The old scan-relative path stays available, but is never silently repaired.+ const current = files.find(f => f.read_path === 'accounts.csv')!;+ expect(current.path).toBe(path.join('conversation', 'accounts.csv'));+ fs.unlinkSync(path.join(cwd, 'conversation', 'accounts.csv'));+ const wrong = await getTool(tools, 'read_files').execute({ paths: [{ path: current.path }] }, ctx);+ expect(wrong.isError).toBe(true);+ expect(wrong.content).toContain('E_NOT_FOUND');+ });++ it('keeps discovered read paths subject to the existing scope check', async () => {+ const permissions = await import('../../../../src/main/features/permissions');+ permissions.setLocalExecMode('workspace_approval');+ const { tools, wsDir } = await buildTools();+ const root = path.join(tmpDir, 'references');+ const file = path.join(root, 'report.txt');+ fs.mkdirSync(root);+ fs.writeFileSync(file, 'visible report');+ const { createFileTools } = await import('../../../../src/main/model/core-agent/file-tools');+ const referenceTools = createFileTools({ userId: UID, cid: CID, readOnlyExtraRoots: [root] });+ const ctx = { workingDir: wsDir, state: {} } as any;+ const result = await getTool(referenceTools, 'search_files').execute({ query: 'report.txt' }, ctx);+ const found = searchResults(result.content).files[0];+ expect(found.read_path).toBe(file);+ const allowed = await getTool(referenceTools, 'read_files').execute({ paths: [{ path: found.read_path }] }, ctx);+ expect(allowed.isError, allowed.content).toBeFalsy();+ expect(allowed.content).toContain('visible report');+ const read = await getTool(tools, 'read_files').execute({ paths: [{ path: found.read_path }] }, ctx);+ expect(read.isError).toBe(true);+ expect(read.content).not.toContain('visible report');+ });+it.each(['native', 'fallback'])('finds a selective filename beyond the old enumeration cap (%s)', async (backend) => {const { tools, wsDir } = await buildTools();for (let i = 0; i < 2100; i++) fs.writeFileSync(path.join(wsDir, `source-${i}.ts`), 'needle\n');diff --git a/test/main/util/atomic-directory-replace.test.ts b/test/main/util/atomic-directory-replace.test.tsindex 548dfed2..6895ca08 100644--- a/test/main/util/atomic-directory-replace.test.ts+++ b/test/main/util/atomic-directory-replace.test.ts@@ -29,10 +29,9 @@ describe('atomic directory replacement', () => {return fs.readdirSync(root).filter((name) => name.startsWith('.installed-item.install-'));}- it('sweeps staging and backup leftovers of a dead replacement but never a live one', async () => {- // A crash between staging and activation leaves `.item.install-XXXX` and- // `.item.install-XXXX.previous` behind; they are dot-prefixed, so the- // install listings ignore them and their space was never reclaimed.+ it('sweeps abandoned staging while preserving prior copies and live work', async () => {+ // Directory presence cannot establish that a crashed replacement committed.+ // Keep its prior copy even when an installed-looking target also exists.writeCurrent();for (const name of ['.installed-item.install-dead01', '.installed-item.install-dead01.previous', '.other.install-x9']) {fs.mkdirSync(path.join(root, name), { recursive: true });@@ -58,10 +57,10 @@ describe('atomic directory replacement', () => {expect(errors).toEqual([]);expect(removed.map((item) => path.basename(item)).sort()).toEqual(['.installed-item.install-dead01',- '.installed-item.install-dead01.previous','.other.install-x9',]);expect(fs.existsSync(liveStaged)).toBe(true);+ expect(fs.readFileSync(path.join(root, '.installed-item.install-dead01.previous', 'content.txt'), 'utf8')).toBe('stale');expect(fs.existsSync(path.join(root, '.hidden-but-not-ours'))).toBe(true);expect(fs.existsSync(path.join(root, '.installed-item.install-file'))).toBe(true);expect(fs.readFileSync(path.join(target, 'content.txt'), 'utf8')).toBe('working');@@ -70,7 +69,7 @@ describe('atomic directory replacement', () => {await inFlight;expect(fs.readFileSync(path.join(target, 'content.txt'), 'utf8')).toBe('fresh');fs.rmSync(path.join(root, '.installed-item.install-file'));- expect(transactionArtifacts()).toEqual([]);+ expect(transactionArtifacts()).toEqual(['.installed-item.install-dead01.previous']);// Missing parent: nothing to do, no throw.expect(await sweepStaleReplacementArtifacts(path.join(root, 'nope'))).toEqual([]);});@@ -285,4 +284,64 @@ describe('atomic directory replacement', () => {expect(fs.readFileSync(path.join(target, 'content.txt'), 'utf8')).toBe('working');expect(transactionArtifacts()).toEqual([]);});++ it('keeps the prior copy through maintenance when both rollback removal and quarantine fail', async () => {+ writeCurrent('only durable draft');+ const rm = nativeFs.promises.rm.bind(nativeFs.promises);+ const rename = nativeFs.promises.rename.bind(nativeFs.promises);+ let metadataRejected = false;+ const denied = Object.assign(new Error('injected rollback denial'), { code: 'EACCES' });+ const removeSpy = vi.spyOn(nativeFs.promises, 'rm').mockImplementation(async (file, options) => {+ if (metadataRejected && String(file) === target) throw denied;+ return rm(file, options);+ });+ const renameSpy = vi.spyOn(nativeFs.promises, 'rename').mockImplementation(async (from, to) => {+ if (metadataRejected && String(from) === target) throw denied;+ return rename(from, to);+ });+ syncBuiltinESMExports();+ try {+ await expect(replaceDirectoryAtomically(target, async staged => {+ fs.writeFileSync(path.join(staged, 'uncommitted.txt'), 'rejected candidate');+ }, async () => {+ metadataRejected = true;+ throw new Error('metadata rejected');+ })).rejects.toThrow();+ } finally {+ removeSpy.mockRestore();renameSpy.mockRestore();syncBuiltinESMExports();+ }+ const backup = transactionArtifacts().find(name => name.endsWith('.previous'))!;+ expect(fs.readFileSync(path.join(root, backup, 'content.txt'), 'utf8')).toBe('only durable draft');+ expect(fs.existsSync(path.join(target, 'uncommitted.txt'))).toBe(true);+ await sweepStaleReplacementArtifacts(root);+ await sweepStaleReplacementArtifacts(root);+ expect(fs.readFileSync(path.join(root, backup, 'content.txt'), 'utf8')).toBe('only durable draft');+ });++ it('distinguishes failed directory discovery from a missing parent', async () => {+ const denied = Object.assign(new Error('injected directory read denial'), { code: 'EACCES' });+ const spy = vi.spyOn(nativeFs.promises, 'readdir').mockRejectedValue(denied);+ syncBuiltinESMExports();+ try {+ const onError = vi.fn();+ expect(await sweepStaleReplacementArtifacts(root, onError)).toEqual([]);+ expect(onError).toHaveBeenCalledWith(denied, root);+ await expect(sweepStaleReplacementArtifacts(root)).rejects.toThrow(denied);+ } finally {spy.mockRestore();syncBuiltinESMExports();}+ });++ it('reports an undeletable staging directory instead of silently swallowing its failure', async () => {+ const artifact=path.join(root,'.installed-item.install-denied');+ fs.mkdirSync(artifact);+ const denied=Object.assign(new Error('injected staging cleanup denial'),{code:'EACCES'});+ const spy=vi.spyOn(nativeFs.promises,'rm').mockRejectedValue(denied);+ syncBuiltinESMExports();+ try {+ const onError=vi.fn();+ expect(await sweepStaleReplacementArtifacts(root,onError)).toEqual([]);+ expect(onError).toHaveBeenCalledWith(denied,artifact);+ expect(fs.existsSync(artifact)).toBe(true);+ await expect(sweepStaleReplacementArtifacts(root)).rejects.toThrow(denied);+ } finally {spy.mockRestore();syncBuiltinESMExports();}+ });});diff --git a/test/main/util/path-sandbox.test.ts b/test/main/util/path-sandbox.test.tsindex 79278bbd..6bf06af5 100644--- a/test/main/util/path-sandbox.test.ts+++ b/test/main/util/path-sandbox.test.ts@@ -1,4 +1,5 @@-import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';+import { syncBuiltinESMExports } from 'node:module';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';@@ -218,3 +219,132 @@ describe('path-sandbox › isPathAllowed', () => {}});});+++describe('path-sandbox › unresolved existing entries', () => {+ it('refuses a missing descendant behind a dangling directory link while allowing unlink of the link itself', () => {+ const target = path.join(tmpRoot, 'outside', 'not-created');+ const link = path.join(workspace, 'dangling-directory');+ fs.symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir');+ try {+ expect(isPathAllowed(path.join(link, 'future.md'), [workspace])).toBe(false);+ expect(isPathAllowed(link, [workspace])).toBe(false);+ expect(isPathAllowed(link, [workspace], { followFinalSymlink: false })).toBe(true);+ expect(isPathAllowed(path.join(link, 'future.md'), [workspace], { followFinalSymlink: false })).toBe(false);+ const resolved = resolveSandboxRoot(workspace);+ expect(isPathAllowed(path.join(link, 'future.md'), [resolved], { rootsResolved: true })).toBe(false);+ expect(isPathAllowed(path.join(workspace, 'ordinary-new', 'future.md'), [resolved], { rootsResolved: true })).toBe(true);+ } finally { fs.unlinkSync(link); }+ });++ it('preserves a known root alias when its ordinary target directory has not been created yet', () => {+ const link = path.join(tmpRoot, 'future-root-alias');+ const target = path.join(tmpRoot, 'future-workspace');+ fs.symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir');+ try {+ for (const candidate of [path.join(link, 'future.md'), path.join(target, 'future.md')]) {+ expect(isPathAllowed(candidate, [link])).toBe(true);+ expect(isPathAllowed(candidate, [resolveSandboxRoot(link)], { rootsResolved: true })).toBe(true);+ }+ expect(fs.existsSync(target)).toBe(false);+ } finally { fs.unlinkSync(link); }+ });++ it.runIf(process.platform !== 'win32')('preserves a known internal file alias whose target has not been created yet', () => {+ const link = path.join(workspace, 'future-file-alias.md');+ const target = path.join(workspace, 'future-file.md');+ fs.symlinkSync(target, link, 'file');+ try {+ expect(isPathAllowed(link, [workspace])).toBe(true);+ expect(isPathAllowed(link, [resolveSandboxRoot(workspace)], { rootsResolved: true })).toBe(true);+ expect(fs.existsSync(target)).toBe(false);+ } finally { fs.unlinkSync(link); }+ });++ it.runIf(process.platform !== 'win32')('refuses dangling file links and symlink cycles without changing their targets', () => {+ const dangling = path.join(workspace, 'dangling-file.md');+ const first = path.join(workspace, 'cycle-a');+ const second = path.join(workspace, 'cycle-b');+ const target = path.join(tmpRoot, 'outside', 'not-created.md');+ fs.symlinkSync(target, dangling, 'file');+ fs.symlinkSync(second, first, 'dir'); fs.symlinkSync(first, second, 'dir');+ try {+ expect(isPathAllowed(dangling, [workspace])).toBe(false);+ expect(isPathAllowed(path.join(first, 'future.md'), [workspace])).toBe(false);+ expect(isPathAllowed(path.join(first, 'future.md'), [first])).toBe(false);+ expect(isPathAllowed(path.join(first, 'future.md'), [resolveSandboxRoot(first)], { rootsResolved: true })).toBe(false);+ expect(isPathAllowed(dangling, [workspace], { followFinalSymlink: false })).toBe(true);+ expect(fs.existsSync(target)).toBe(false);+ } finally { fs.unlinkSync(dangling); fs.unlinkSync(first); fs.unlinkSync(second); }+ });+});+++describe('path-sandbox › resolution budget and metadata recovery', () => {+ it.runIf(process.platform !== 'win32').each([39, 40, 41])('bounds unresolved symlink resolution for a chain of %i links', count => {+ const directory = path.join(workspace, `chain-${count}`);+ fs.mkdirSync(directory);+ let target = path.join(directory, 'future-target.md');+ for (let index = count - 1; index >= 0; index--) {+ const link = path.join(directory, `link-${index}.md`);+ fs.symlinkSync(target, link, 'file'); target = link;+ }+ expect(isPathAllowed(target, [workspace])).toBe(count <= 40);+ expect(isPathAllowed(target, [resolveSandboxRoot(workspace)], { rootsResolved: true })).toBe(count <= 40);+ expect(fs.existsSync(path.join(directory, 'future-target.md'))).toBe(false);+ });++ it.each(['EACCES', 'EIO'])('denies unknown metadata after %s and recovers after the filesystem is readable', async code => {+ const nodeFs = (await import('node:fs')).default;+ const realpath = nodeFs.realpathSync, lstat = nodeFs.lstatSync;+ const failure = Object.assign(new Error('Private metadata failure'), { code });+ const realpathSpy = vi.spyOn(nodeFs, 'realpathSync').mockImplementation(((filename: any, ...args: any[]) => {+ if (String(filename) === workspaceFile) throw failure;+ return (realpath as any)(filename, ...args);+ }) as any);+ const lstatSpy = vi.spyOn(nodeFs, 'lstatSync').mockImplementation(((filename: any, ...args: any[]) => {+ if (String(filename) === workspaceFile) throw failure;+ return (lstat as any)(filename, ...args);+ }) as any);+ syncBuiltinESMExports();+ try { expect(isPathAllowed(workspaceFile, [workspace])).toBe(false); }+ finally { realpathSpy.mockRestore(); lstatSpy.mockRestore(); syncBuiltinESMExports(); }+ expect(isPathAllowed(workspaceFile, [workspace])).toBe(true);+ expect(fs.readFileSync(workspaceFile, 'utf8')).toBe('hello');+ });+});+++describe('path-sandbox › explicitly allowed volume roots', () => {+ it.each([false, true])('contains native temporary fixtures under the filesystem root, resolved=%s', rootsResolved => {+ const root = path.parse(fs.realpathSync(workspaceFile)).root;+ const allowed = rootsResolved ? resolveSandboxRoot(root) : root;+ expect(isPathAllowed(root, [allowed], { rootsResolved })).toBe(true);+ expect(isPathAllowed(workspaceFile, [allowed], { rootsResolved })).toBe(true);+ expect(isPathAllowed(workspaceFile, [allowed], { rootsResolved, followFinalSymlink: false })).toBe(true);+ // An unrelated narrow root still cannot grant the same file.+ expect(isPathAllowed(workspaceFile, [attachments], { rootsResolved })).toBe(false);+ });++ it.each([+ ['C:\\', 'C:\\allowed\\note.txt', 'D:\\outside.txt'],+ ['\\\\fixture-host\\share\\', '\\\\fixture-host\\share\\allowed\\note.txt', '\\\\fixture-host\\share-other\\outside.txt'],+ ])('keeps Windows path-engine root containment without a sibling grant: %s', async (root, candidate, outside) => {+ vi.resetModules();+ // Pure path-engine simulation, not native Windows/filesystem acceptance.+ vi.doMock('node:path', () => ({ ...path.win32, default: path.win32 }));+ vi.doMock('node:fs', () => ({ realpathSync: (value: string) => path.win32.resolve(value) }));+ try {+ const module = await import('../../../src/main/util/path-sandbox');+ for (const rootsResolved of [false, true]) {+ const allowed = rootsResolved ? module.resolveSandboxRoot(root) : root;+ expect(module.isPathAllowed(root, [allowed], { rootsResolved })).toBe(true);+ expect(module.isPathAllowed(candidate, [allowed], { rootsResolved })).toBe(true);+ expect(module.isPathAllowed(candidate, [allowed], { rootsResolved, followFinalSymlink: false })).toBe(true);+ expect(module.isPathAllowed(outside, [allowed], { rootsResolved })).toBe(false);+ }+ } finally {+ vi.doUnmock('node:path'); vi.doUnmock('node:fs'); vi.resetModules();+ }+ });+});diff --git a/test/main/util/tool-result-cap.test.ts b/test/main/util/tool-result-cap.test.tsindex 34a5a20b..4afc5784 100644--- a/test/main/util/tool-result-cap.test.ts+++ b/test/main/util/tool-result-cap.test.ts@@ -1,4 +1,6 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import nativeFs from 'node:fs';+import { syncBuiltinESMExports } from 'node:module';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';@@ -598,6 +600,33 @@ describe('persisted result helpers', () => {beforeEach(() => { dir = makeTmpDir(); });afterEach(() => cleanup(dir));+ it('keeps a successful publication intact when an overlapping writer fails after opening its temporary file', () => {+ const write = nativeFs.writeFileSync;+ const rename = nativeFs.renameSync;+ let writes = 0, overlapped = false;+ const writer = vi.spyOn(nativeFs, 'writeFileSync').mockImplementation(((file: any, ...args: any[]) => {+ if (String(file).startsWith(dir) && ++writes === 2) {+ write(file, '');+ throw new Error('injected writer failure');+ }+ return (write as any)(file, ...args);+ }) as any);+ const publisher = vi.spyOn(nativeFs, 'renameSync').mockImplementation(((from: any, to: any) => {+ if (!overlapped) {+ overlapped = true;+ expect(() => persistToolResult(dir, 'bash', 'complete receipt')).toThrow('injected writer failure');+ }+ return rename(from, to);+ }) as any);+ syncBuiltinESMExports();+ try {+ const result = persistToolResult(dir, 'bash', 'complete receipt');+ expect(overlapped).toBe(true);+ expect(fs.readFileSync(result, 'utf8')).toBe('complete receipt');+ expect(fs.readdirSync(dir)).toEqual([path.basename(result)]);+ } finally { writer.mockRestore(); publisher.mockRestore(); syncBuiltinESMExports(); }+ });+it('uses a content-addressed name and deduplicates identical output', () => {const first = persistToolResult(dir, 'bash', 'same content');const second = persistToolResult(dir, 'bash', 'same content');