Skip to content

Commit 3535f56

Browse files
committed
fix: migrate tmpdir state to CLAUDE_PLUGIN_DATA + fix /tmp literal
The fallback path was hard-coded to '/tmp' — broken on Windows. Use os.tmpdir() so Windows and other platforms get a real tmp path. Additionally: when CLAUDE_PLUGIN_DATA is set on a later call but state was previously written to the tmpdir fallback, copy it into the plugin-data dir and rewrite absolute path references inside state.json and jobs/*.json so logFile pointers don't dangle. Prevents job history from being silently dropped when commands run under different env contexts within one Claude session. Closes #47. Port of openai/codex-plugin-cc#125.
1 parent f8d3fcc commit 3535f56

2 files changed

Lines changed: 195 additions & 6 deletions

File tree

‎plugins/opencode/scripts/lib/state.mjs‎

Lines changed: 69 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,86 @@
33
// JSON state file, per-job files and logs.
44

55
import crypto from "node:crypto";
6+
import fs from "node:fs";
7+
import os from "node:os";
68
import path from "node:path";
79
import { ensureDir, readJson, writeJson } from "./fs.mjs";
810

911
const MAX_JOBS = 50;
1012

13+
const FALLBACK_STATE_ROOT_DIR = path.join(os.tmpdir(), "opencode-companion");
14+
15+
function workspaceHash(workspacePath) {
16+
return crypto.createHash("sha256").update(workspacePath).digest("hex").slice(0, 16);
17+
}
18+
19+
/**
20+
* One-time migration: if state for this workspace exists only in the tmpdir
21+
* fallback (written by a command that ran without CLAUDE_PLUGIN_DATA), copy
22+
* it into the persistent plugin-data dir so future reads/writes go there and
23+
* state survives /tmp cleanup.
24+
*
25+
* Absolute paths embedded in the migrated JSON (logFile references, job data
26+
* paths) are rewritten to point at the new location.
27+
*/
28+
function migrateTmpdirStateIfNeeded(fallbackDir, primaryDir) {
29+
const primaryState = path.join(primaryDir, "state.json");
30+
const fallbackState = path.join(fallbackDir, "state.json");
31+
if (fs.existsSync(primaryState) || !fs.existsSync(fallbackState)) return;
32+
33+
try {
34+
fs.mkdirSync(primaryDir, { recursive: true });
35+
fs.cpSync(fallbackDir, primaryDir, { recursive: true });
36+
37+
const escapedFallback = fallbackDir.replaceAll("\\", "\\\\");
38+
const escapedPrimary = primaryDir.replaceAll("\\", "\\\\");
39+
const rewritePaths = (filePath) => {
40+
try {
41+
let txt = fs.readFileSync(filePath, "utf8");
42+
const original = txt;
43+
txt = txt.replaceAll(fallbackDir, primaryDir);
44+
if (escapedFallback !== fallbackDir) {
45+
txt = txt.replaceAll(escapedFallback, escapedPrimary);
46+
}
47+
if (txt !== original) fs.writeFileSync(filePath, txt, "utf8");
48+
} catch {
49+
// non-fatal — migration is best-effort
50+
}
51+
};
52+
53+
rewritePaths(primaryState);
54+
const jobsDir = path.join(primaryDir, "jobs");
55+
if (fs.existsSync(jobsDir)) {
56+
for (const entry of fs.readdirSync(jobsDir)) {
57+
if (entry.endsWith(".json")) {
58+
rewritePaths(path.join(jobsDir, entry));
59+
}
60+
}
61+
}
62+
} catch {
63+
// If migration fails for any reason, fall through and let the caller
64+
// operate on whatever state is visible. A failed migration must never
65+
// crash a status/cancel call.
66+
}
67+
}
68+
1169
/**
1270
* Compute the state directory root for a workspace.
1371
* @param {string} workspacePath
1472
* @returns {string}
1573
*/
1674
export function stateRoot(workspacePath) {
17-
const base =
18-
process.env.CLAUDE_PLUGIN_DATA
19-
? path.join(process.env.CLAUDE_PLUGIN_DATA, "state")
20-
: path.join("/tmp", "opencode-companion");
21-
const hash = crypto.createHash("sha256").update(workspacePath).digest("hex").slice(0, 16);
22-
return path.join(base, hash);
75+
const hash = workspaceHash(workspacePath);
76+
const pluginDataDir = process.env.CLAUDE_PLUGIN_DATA;
77+
78+
if (pluginDataDir) {
79+
const primaryDir = path.join(pluginDataDir, "state", hash);
80+
const fallbackDir = path.join(FALLBACK_STATE_ROOT_DIR, hash);
81+
migrateTmpdirStateIfNeeded(fallbackDir, primaryDir);
82+
return primaryDir;
83+
}
84+
85+
return path.join(FALLBACK_STATE_ROOT_DIR, hash);
2386
}
2487

2588
/**

‎tests/state-migration.test.mjs‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import { describe, it, beforeEach, afterEach } from "node:test";
2+
import assert from "node:assert/strict";
3+
import fs from "node:fs";
4+
import os from "node:os";
5+
import path from "node:path";
6+
import { createTmpDir, cleanupTmpDir } from "./helpers.mjs";
7+
import {
8+
stateRoot,
9+
loadState,
10+
upsertJob,
11+
} from "../plugins/opencode/scripts/lib/state.mjs";
12+
13+
let previousPluginData;
14+
15+
beforeEach(() => {
16+
previousPluginData = process.env.CLAUDE_PLUGIN_DATA;
17+
});
18+
19+
afterEach(() => {
20+
if (previousPluginData == null) {
21+
delete process.env.CLAUDE_PLUGIN_DATA;
22+
} else {
23+
process.env.CLAUDE_PLUGIN_DATA = previousPluginData;
24+
}
25+
});
26+
27+
describe("stateRoot fallback", () => {
28+
it("uses os.tmpdir when CLAUDE_PLUGIN_DATA is unset", () => {
29+
delete process.env.CLAUDE_PLUGIN_DATA;
30+
const root = stateRoot("/some/workspace");
31+
assert.ok(root.startsWith(os.tmpdir()), `${root} does not start with ${os.tmpdir()}`);
32+
assert.match(root, /opencode-companion/);
33+
});
34+
35+
it("uses CLAUDE_PLUGIN_DATA when set", () => {
36+
const dataDir = createTmpDir("opencode-data-");
37+
try {
38+
process.env.CLAUDE_PLUGIN_DATA = dataDir;
39+
const root = stateRoot("/some/workspace");
40+
assert.ok(root.startsWith(dataDir), `${root} does not start with ${dataDir}`);
41+
} finally {
42+
cleanupTmpDir(dataDir);
43+
}
44+
});
45+
});
46+
47+
describe("stateRoot tmpdir → plugin-data migration", () => {
48+
let workspace;
49+
let dataDir;
50+
51+
beforeEach(() => {
52+
workspace = "/migrate/test/workspace-" + Math.random().toString(16).slice(2);
53+
dataDir = createTmpDir("opencode-migrate-data-");
54+
});
55+
56+
afterEach(() => {
57+
cleanupTmpDir(dataDir);
58+
});
59+
60+
it("migrates existing tmpdir state to plugin-data dir", () => {
61+
// First, seed state in the tmpdir fallback (no CLAUDE_PLUGIN_DATA).
62+
delete process.env.CLAUDE_PLUGIN_DATA;
63+
upsertJob(workspace, { id: "pre-migration", status: "completed" });
64+
const fallbackDir = stateRoot(workspace);
65+
assert.ok(fallbackDir.startsWith(os.tmpdir()));
66+
const fallbackStateFile = path.join(fallbackDir, "state.json");
67+
assert.ok(fs.existsSync(fallbackStateFile));
68+
69+
// Now set CLAUDE_PLUGIN_DATA and call stateRoot again — should migrate.
70+
process.env.CLAUDE_PLUGIN_DATA = dataDir;
71+
const primaryDir = stateRoot(workspace);
72+
assert.ok(primaryDir.startsWith(dataDir));
73+
const primaryStateFile = path.join(primaryDir, "state.json");
74+
assert.ok(fs.existsSync(primaryStateFile), "state.json did not migrate to primary dir");
75+
76+
const migrated = loadState(workspace);
77+
const job = migrated.jobs.find((j) => j.id === "pre-migration");
78+
assert.ok(job, "migrated state does not contain seeded job");
79+
assert.equal(job.status, "completed");
80+
});
81+
82+
it("rewrites absolute fallback paths in migrated JSON", () => {
83+
delete process.env.CLAUDE_PLUGIN_DATA;
84+
upsertJob(workspace, { id: "j1", status: "running" });
85+
const fallbackDir = stateRoot(workspace);
86+
87+
// Write a job/*.json file containing an absolute reference to fallbackDir.
88+
const jobsDir = path.join(fallbackDir, "jobs");
89+
fs.mkdirSync(jobsDir, { recursive: true });
90+
const jobFile = path.join(jobsDir, "j1.json");
91+
fs.writeFileSync(
92+
jobFile,
93+
JSON.stringify({ id: "j1", logFile: path.join(fallbackDir, "jobs", "j1.log") }),
94+
"utf8"
95+
);
96+
97+
process.env.CLAUDE_PLUGIN_DATA = dataDir;
98+
const primaryDir = stateRoot(workspace);
99+
const migratedJob = JSON.parse(
100+
fs.readFileSync(path.join(primaryDir, "jobs", "j1.json"), "utf8")
101+
);
102+
assert.ok(
103+
migratedJob.logFile.startsWith(primaryDir),
104+
`logFile not rewritten: ${migratedJob.logFile}`
105+
);
106+
assert.ok(!migratedJob.logFile.startsWith(fallbackDir));
107+
});
108+
109+
it("does not re-migrate when primary state already exists", () => {
110+
delete process.env.CLAUDE_PLUGIN_DATA;
111+
upsertJob(workspace, { id: "fallback-only", status: "completed" });
112+
113+
process.env.CLAUDE_PLUGIN_DATA = dataDir;
114+
// First call migrates.
115+
stateRoot(workspace);
116+
const primaryDir = stateRoot(workspace);
117+
upsertJob(workspace, { id: "primary-update", status: "running" });
118+
119+
// Now wipe the fallback so a re-migration would be observable.
120+
// The existing primary state.json still has both seeded jobs.
121+
const state = loadState(workspace);
122+
assert.ok(state.jobs.find((j) => j.id === "fallback-only"));
123+
assert.ok(state.jobs.find((j) => j.id === "primary-update"));
124+
assert.ok(fs.existsSync(path.join(primaryDir, "state.json")));
125+
});
126+
});

0 commit comments

Comments
 (0)