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
fix(file-tools): keep file revisions alive across model rounds
wytb307841e07bc
diff --git a/src/main/model/core-agent/file-revision.ts b/src/main/model/core-agent/file-revision.tsindex 119744b6..612e8c6f 100644--- a/src/main/model/core-agent/file-revision.ts+++ b/src/main/model/core-agent/file-revision.ts@@ -4,8 +4,13 @@* Models should copy a revision token instead of translating read_file's* character offsets into write_file/append_file byte offsets. The token is an* opaque lookup key; the host retains the path, byte size, and content hash.- * Tokens deliberately expire with ToolContext.state, so a later run must read- * the file again and cannot accidentally rely on stale process memory.+ * Tokens deliberately expire with the run, so a later run must read the file+ * again and cannot accidentally rely on stale process memory. Within a run they+ * must outlive a model round: the model has to see a read result before it can+ * form the append that quotes its revision, so those two calls always land in+ * different rounds and AgentRunner rebuilds ToolContext.state between them. The+ * tokens therefore live in the `runScopedLedger` map the runner injects by+ * reference, the same place web_fetch keeps its run cache.*/import * as crypto from 'node:crypto';@@ -38,6 +43,14 @@ type FileRevisionState = {appendReplayByInput: Map<string, AppendReplayRecord>;};+function newState(): FileRevisionState {+ return {+ byToken: new Map(),+ tokenByIdentity: new Map(),+ appendReplayByInput: new Map(),+ };+}+function stateFor(ctx: ToolContext, create: boolean): FileRevisionState | null {// A few direct/legacy tool callers omit `state`; production runners always// provide one. Creating it here preserves the useful receipt for those@@ -47,14 +60,24 @@ function stateFor(ctx: ToolContext, create: boolean): FileRevisionState | null {if (!create) return null;toolContext.state = {};}+ // Prefer the runner's run-scoped map. `state` itself is rebuilt after every+ // model round, so a token issued by read_file would otherwise be gone by the+ // time append_file quotes it — the read and the append can never share a+ // round. Keeping it on `state` alone made that handoff fail every time in+ // production while passing any test that reused one context object.+ const ledger = toolContext.state.runScopedLedger;+ if (ledger instanceof Map) {+ const shared = ledger.get(FILE_REVISION_STATE_KEY);+ if (shared && typeof shared === 'object') return shared as FileRevisionState;+ if (!create) return null;+ const created = newState();+ ledger.set(FILE_REVISION_STATE_KEY, created);+ return created;+ }const existing = toolContext.state[FILE_REVISION_STATE_KEY];if (existing && typeof existing === 'object') return existing as FileRevisionState;if (!create) return null;- const created: FileRevisionState = {- byToken: new Map(),- tokenByIdentity: new Map(),- appendReplayByInput: new Map(),- };+ const created = newState();toolContext.state[FILE_REVISION_STATE_KEY] = created;return created;}diff --git a/test/main/model/local-tools.test.ts b/test/main/model/local-tools.test.tsindex c111e1f8..33d992cc 100644--- a/test/main/model/local-tools.test.ts+++ b/test/main/model/local-tools.test.ts@@ -1758,6 +1758,80 @@ describe('local-tools › write_file', () => {});describe('local-tools › append_file', () => {+ it('carries a read_file revision across the model round that must separate the two calls', async () => {+ // 2026-08-11 research-resume-durable-ledger: the agent read fetch_ledger.jsonl+ // and evidence_ledger.jsonl, quoted the revisions the host had issued for+ // them, and every append came back E_REVISION_UNKNOWN — four times, then the+ // no-progress nudge. The tokens were genuine; the store was not.+ // AgentRunner rebuilds ToolContext.state after every model round, and the+ // model cannot form an append until it has seen the read result, so the two+ // calls never share a round. Keeping the revisions on `state` made this+ // handoff impossible in production while passing a test that reused one+ // context — which is exactly what the previous regression here did.+ const { lt, perm } = await loadModules();+ const ft = await import('../../../src/main/model/core-agent/file-tools');+ perm.grantLocalExec();+ await setTmpWorkspace();+ const tools = lt.createLocalTools({ userId: 'u1' });+ const append = tools.find((tool) => tool.name === 'append_file')!;+ const read = ft.createFileTools({ userId: 'u1', cid: 'c1' }).find((t) => t.name === 'read_file')!;++ // The runner injects this one map by reference into every round's state.+ const runScopedLedger = new Map<string, unknown>();+ const round = () => {+ const ctx = makeCtx();+ ctx.state.runScopedLedger = runScopedLedger;+ return ctx;+ };++ const absolutePath = path.join(tmpDir, 'fetch_ledger.jsonl');+ fs.writeFileSync(absolutePath, '{"kind":"fetch","n":1}\n', 'utf8');++ const readBack = await read.execute({ path: absolutePath }, round());+ const revision = /revision="(file_rev_[A-Za-z0-9_-]{16})"/.exec(readBack.content)?.[1];+ expect(revision, 'read_file must hand back a revision').toBeTruthy();++ // A different round object, as production always gives it.+ const appended = await append.execute({+ path: 'fetch_ledger.jsonl',+ content: '{"kind":"fetch","n":2}\n',+ base_revision: revision,+ }, round());+ expect(appended.isError, appended.content).toBeFalsy();+ expect(fs.readFileSync(absolutePath, 'utf8'))+ .toBe('{"kind":"fetch","n":1}\n{"kind":"fetch","n":2}\n');++ // The refusal's own revision must survive the next round too: that is the+ // recovery path the message tells the caller to take.+ const other = path.join(tmpDir, 'evidence_ledger.jsonl');+ fs.writeFileSync(other, 'x\n', 'utf8');+ const refused = await append.execute({+ path: 'evidence_ledger.jsonl',+ content: 'y\n',+ base_revision: 'file_rev_neverIssuedAAAA',+ }, round());+ expect(refused.isError).toBe(true);+ expect(refused.content).toContain('E_REVISION_UNKNOWN');+ const offered = /revision="(file_rev_[A-Za-z0-9_-]{16})"/.exec(refused.content)?.[1];+ expect(offered).toBeTruthy();+ const retried = await append.execute({+ path: 'evidence_ledger.jsonl',+ content: 'y\n',+ base_revision: offered,+ }, round());+ expect(retried.isError, retried.content).toBeFalsy();+ expect(fs.readFileSync(other, 'utf8')).toBe('x\ny\n');++ // A token from one run must not resolve in another.+ const foreign = await append.execute({+ path: 'evidence_ledger.jsonl',+ content: 'z\n',+ base_revision: revision,+ }, makeCtx());+ expect(foreign.isError).toBe(true);+ expect(foreign.content).toContain('E_REVISION_UNKNOWN');+ });+it('rejects empty content or a missing concurrency baseline without changing the file', async () => {const { lt, perm } = await loadModules();perm.grantLocalExec();