Skip to content

An open-source, faster Devin alternative

TypeScript

cli: keep the edited draft on every failed memory save

Igor Zalutskie234b74f9630
diff --git a/cli/README.md b/cli/README.md
index e99da500..16c52161 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -77,9 +77,11 @@ opencomputer memory export --out ./memory # <out>/<resource>/<id>.
opencomputer memory remove requirements workshop
```
-`edit` replaces the text with the revision it read; if the document changed
-meanwhile the command exits non-zero with the conflict and keeps your edited
-text in a temporary file. Pass `--text-file` or `--text-stdin` to `create` and
+`edit` replaces the text with the revision it read. Any save that does not
+succeed, whether the document changed meanwhile, the text is over the limit
+or the API was unreachable, exits non-zero and keeps your edited text in a
+temporary file whose path the error prints; save it again with
+`--text-file <path>`. Pass `--text-file` or `--text-stdin` to `create` and
`edit` to supply text without an editor.
## Secrets and managed egress
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index dc15bb69..16652716 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -1,5 +1,4 @@
import {
- APIError,
OpenComputerClient,
type ManagedAgentEvent,
type ManagedAgentLog,
@@ -49,7 +48,12 @@ import { join, resolve as resolvePath } from "node:path";
import { createInterface } from "node:readline/promises";
import { doctorProject, type DoctorResult } from "./doctor.js";
import { CLIError } from "./errors.js";
-import { memoryResources, type MemoryResourceSummary } from "./memory.js";
+import {
+ memoryResources,
+ saveMemoryEdit,
+ type MemoryEditDraft,
+ type MemoryResourceSummary,
+} from "./memory.js";
export interface GlobalOptions {
apiUrl?: string;
@@ -342,7 +346,7 @@ async function editMemoryTextInEditor(
resource: string,
id: string,
text: string,
-): Promise<{ text: string; path: string; discard: () => Promise<void> }> {
+): Promise<MemoryEditDraft & { text: string }> {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new CLIError(
"editor_required",
@@ -1773,41 +1777,18 @@ export async function runCommand(
else process.stdout.write(`No changes to ${resource}/${id}.\n`);
return;
}
- try {
- const { document } = await client.replaceMemoryDocument({
- ...target,
- etag: current.etag,
- text,
- ...(summary !== undefined ? { summary } : {}),
- });
- await edited?.discard();
- if (globals.json) printJSON(document);
- else {
- process.stdout.write(
- `Saved ${resource}/${document.id} (${memorySizeLabel(document)}, revision ${document.revision}).\n`,
- );
- }
- } catch (error) {
- if (error instanceof APIError && error.status === 412) {
- const latest = await client.memoryDocument(target).catch(() => null);
- throw new CLIError(
- "memory_conflict",
- `${resource}/${id} changed since you opened it` +
- (latest
- ? ` (now revision ${latest.document.revision}, updated ${latest.document.updatedAt} by ${memoryWriterLabel(latest.document)})`
- : "") +
- `; your edit was not saved.`,
- (edited ? `Your edited text is kept at ${edited.path}. ` : "") +
- "Run `opencomputer memory show` to read the current text, reconcile, and edit again.",
- {
- status: 412,
- ...(latest ? { current: latest.document } : {}),
- ...(edited ? { editedTextPath: edited.path } : {}),
- },
- );
- }
- await edited?.discard();
- throw error;
+ const document = await saveMemoryEdit(client, {
+ ...target,
+ etag: current.etag,
+ text,
+ ...(summary !== undefined ? { summary } : {}),
+ ...(edited ? { draft: { path: edited.path, discard: edited.discard } } : {}),
+ });
+ if (globals.json) printJSON(document);
+ else {
+ process.stdout.write(
+ `Saved ${resource}/${document.id} (${memorySizeLabel(document)}, revision ${document.revision}).\n`,
+ );
}
return;
}
diff --git a/cli/src/memory.test.ts b/cli/src/memory.test.ts
index aedcf248..c82454cb 100644
--- a/cli/src/memory.test.ts
+++ b/cli/src/memory.test.ts
@@ -1,8 +1,12 @@
import assert from "node:assert/strict";
+import { access, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import test from "node:test";
import { OpenComputerClient } from "./api.js";
-import { memoryResources } from "./memory.js";
+import { CLIError } from "./errors.js";
+import { memoryResources, saveMemoryEdit } from "./memory.js";
const config = { apiUrl: "https://app.opencomputer.dev", apiKey: "test" };
@@ -160,3 +164,123 @@ test("without the inventory route, memory resources merge every project member's
assert.ok(paths.includes("/api/managed-agents/deployments/muse--worker%3Adev"));
assert.ok(!paths.some((path) => path.includes("muse%3Aprod")));
});
+
+async function draftFile(): Promise<{
+ path: string;
+ discarded: () => boolean;
+ discard: () => Promise<void>;
+ cleanup: () => Promise<void>;
+}> {
+ const directory = await mkdtemp(join(tmpdir(), "opencomputer-memory-test-"));
+ const path = join(directory, "requirements--workshop.md");
+ await writeFile(path, "Exercises must run on Node.js 22.\n", "utf8");
+ let discarded = false;
+ return {
+ path,
+ discarded: () => discarded,
+ discard: async () => {
+ discarded = true;
+ await rm(directory, { recursive: true, force: true });
+ },
+ cleanup: () => rm(directory, { recursive: true, force: true }),
+ };
+}
+
+const target = {
+ projectId: "prj_1",
+ resource: "requirements",
+ id: "workshop",
+ environment: "development" as const,
+ etag: '"rev-1"',
+ text: "Exercises must run on Node.js 22.\n",
+};
+
+test("an over-limit save keeps the edited draft and says where it is", async (context) => {
+ context.mock.method(globalThis, "fetch", async () =>
+ Response.json(
+ {
+ error: {
+ code: "memory_limit_exceeded",
+ message: "Text is 9000 bytes; the limit is 8192.",
+ },
+ },
+ { status: 413 },
+ ),
+ );
+ const draft = await draftFile();
+ try {
+ const error = await saveMemoryEdit(new OpenComputerClient(config), {
+ ...target,
+ draft,
+ }).catch((error: unknown) => error);
+
+ assert.ok(error instanceof CLIError);
+ assert.equal(error.code, "memory_too_large");
+ assert.match(error.message, /requirements\/workshop was not saved: Text is 9000 bytes/);
+ assert.match(error.hint, new RegExp(`kept at ${draft.path}`));
+ assert.match(error.hint, /--text-file/);
+ assert.deepEqual(error.details, {
+ status: 413,
+ apiCode: "memory_limit_exceeded",
+ editedTextPath: draft.path,
+ });
+ assert.equal(draft.discarded(), false);
+ await access(draft.path);
+ } finally {
+ await draft.cleanup();
+ }
+});
+
+test("a save that never reaches the API keeps the edited draft", async (context) => {
+ context.mock.method(globalThis, "fetch", async () => {
+ throw new TypeError("fetch failed");
+ });
+ const draft = await draftFile();
+ try {
+ const error = await saveMemoryEdit(new OpenComputerClient(config), {
+ ...target,
+ draft,
+ }).catch((error: unknown) => error);
+
+ assert.ok(error instanceof CLIError);
+ assert.equal(error.code, "command_failed");
+ assert.match(error.message, /was not saved: fetch failed/);
+ assert.match(error.hint, new RegExp(`kept at ${draft.path}`));
+ assert.deepEqual(error.details, { editedTextPath: draft.path });
+ await access(draft.path);
+ } finally {
+ await draft.cleanup();
+ }
+});
+
+test("a saved edit discards its draft", async (context) => {
+ context.mock.method(globalThis, "fetch", async () =>
+ Response.json(
+ {
+ id: "workshop",
+ title: "Workshop requirements",
+ text: target.text,
+ summary: "",
+ agentWrites: "enabled",
+ revision: "rev-2",
+ bytes: 34,
+ maxBytes: 8192,
+ updatedAt: "2026-09-10T12:00:00.000Z",
+ writer: { kind: "owner" },
+ },
+ { headers: { etag: '"rev-2"' } },
+ ),
+ );
+ const draft = await draftFile();
+ try {
+ const document = await saveMemoryEdit(new OpenComputerClient(config), {
+ ...target,
+ draft,
+ });
+ assert.equal(document.revision, "rev-2");
+ assert.equal(draft.discarded(), true);
+ await assert.rejects(access(draft.path));
+ } finally {
+ await draft.cleanup();
+ }
+});
diff --git a/cli/src/memory.ts b/cli/src/memory.ts
index 6e548597..ef6f9d70 100644
--- a/cli/src/memory.ts
+++ b/cli/src/memory.ts
@@ -1,9 +1,11 @@
import {
APIError,
+ type MemoryDocument,
type MemoryEnvironment,
type MemoryResource,
type OpenComputerClient,
} from "./api.js";
+import { CLIError, structuredError } from "./errors.js";
// Project memory (docs/agents/document-memory.mdx, "Owner access"): the parts
// of the `memory` command group that talk to the API and have to be right
@@ -95,3 +97,80 @@ export async function memoryResources(
function byId(left: { id: string }, right: { id: string }): number {
return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
}
+
+export interface MemoryEditDraft {
+ /** The file holding the user's edited text. */
+ path: string;
+ discard: () => Promise<void>;
+}
+
+/**
+ * Replaces a document's text at the revision that was read. On success the
+ * draft file goes; on any failure it stays and the error names it, so an
+ * over-limit, unreachable or failing save costs no work.
+ */
+export async function saveMemoryEdit(
+ client: OpenComputerClient,
+ input: {
+ projectId: string;
+ resource: string;
+ id: string;
+ environment: MemoryEnvironment;
+ etag: string;
+ text: string;
+ summary?: string;
+ draft?: MemoryEditDraft;
+ },
+): Promise<MemoryDocument> {
+ const { draft, ...replacement } = input;
+ try {
+ const { document } = await client.replaceMemoryDocument(replacement);
+ await draft?.discard();
+ return document;
+ } catch (error) {
+ const kept = draft
+ ? { editedTextPath: draft.path }
+ : {};
+ const resume = draft
+ ? ` Your edited text is kept at ${draft.path}; save it with ` +
+ `\`opencomputer memory edit ${input.resource} ${input.id} --text-file ${draft.path}\`.`
+ : "";
+ if (error instanceof APIError && error.status === 412) {
+ const latest = await client
+ .memoryDocument(input)
+ .catch(() => null);
+ throw new CLIError(
+ "memory_conflict",
+ `${input.resource}/${input.id} changed since you opened it` +
+ (latest
+ ? ` (now revision ${latest.document.revision}, updated ${latest.document.updatedAt} by ${writerLabel(latest.document)})`
+ : "") +
+ `; your edit was not saved.`,
+ "Run `opencomputer memory show` to read the current text, reconcile, and edit again." +
+ resume,
+ {
+ status: 412,
+ ...(latest ? { current: latest.document } : {}),
+ ...kept,
+ },
+ );
+ }
+ const failure = structuredError(error);
+ const details =
+ failure.details && typeof failure.details === "object"
+ ? (failure.details as Record<string, unknown>)
+ : {};
+ throw new CLIError(
+ failure.code === "payload_too_large" ? "memory_too_large" : failure.code,
+ `${input.resource}/${input.id} was not saved: ${failure.message}`,
+ failure.hint + resume,
+ { ...details, ...kept },
+ );
+ }
+}
+
+function writerLabel(document: MemoryDocument): string {
+ return document.writer.kind === "agent"
+ ? `agent ${document.writer.sessionId}`
+ : "owner";
+}