@glrs-dev/harness-plugin-opencode 0.3.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,204 @@
1
+ // src/pilot/paths.ts
2
+ import { promises as fs2 } from "fs";
3
+ import * as os2 from "os";
4
+ import * as path2 from "path";
5
+
6
+ // src/plan-paths.ts
7
+ import { execFile } from "child_process";
8
+ import * as fs from "fs/promises";
9
+ import * as os from "os";
10
+ import * as path from "path";
11
+ function execFileP(file, args, opts = {}) {
12
+ const { cwd, timeoutMs = 5e3 } = opts;
13
+ return new Promise((resolve2, reject) => {
14
+ const controller = new AbortController();
15
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
16
+ execFile(
17
+ file,
18
+ args,
19
+ { signal: controller.signal, cwd, encoding: "utf8" },
20
+ (err, stdout) => {
21
+ clearTimeout(timer);
22
+ if (err) {
23
+ reject(err);
24
+ return;
25
+ }
26
+ resolve2(stdout ?? "");
27
+ }
28
+ );
29
+ });
30
+ }
31
+ function expandTilde(p) {
32
+ if (p === "~") return os.homedir();
33
+ if (p.startsWith("~/")) return path.join(os.homedir(), p.slice(2));
34
+ return p;
35
+ }
36
+ async function getRepoFolder(worktreeDir) {
37
+ let stdout;
38
+ try {
39
+ stdout = await execFileP(
40
+ "git",
41
+ ["rev-parse", "--git-common-dir"],
42
+ { cwd: worktreeDir }
43
+ );
44
+ } catch (err) {
45
+ const msg = err instanceof Error ? err.message : "unknown error running `git rev-parse --git-common-dir`";
46
+ throw new Error(
47
+ `getRepoFolder: failed to resolve git-common-dir for ${worktreeDir}: ${msg}`
48
+ );
49
+ }
50
+ const gitCommonDir = stdout.trim();
51
+ if (!gitCommonDir) {
52
+ throw new Error(
53
+ `getRepoFolder: \`git rev-parse --git-common-dir\` returned empty for ${worktreeDir}`
54
+ );
55
+ }
56
+ const absCommonDir = path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(worktreeDir, gitCommonDir);
57
+ const repoRoot = path.dirname(absCommonDir);
58
+ return path.basename(repoRoot);
59
+ }
60
+ async function getPlanDir(worktreeDir) {
61
+ const override = process.env.GLORIOUS_PLAN_DIR;
62
+ const base = override ? expandTilde(override) : path.join(os.homedir(), ".glorious", "opencode");
63
+ const repoFolder = await getRepoFolder(worktreeDir);
64
+ const planDir = path.join(base, repoFolder, "plans");
65
+ await fs.mkdir(planDir, { recursive: true });
66
+ return planDir;
67
+ }
68
+ async function migratePlans(worktreeDir, planDir) {
69
+ const oldDir = path.join(worktreeDir, ".agent", "plans");
70
+ const marker = path.join(oldDir, ".migrated");
71
+ try {
72
+ await fs.stat(oldDir);
73
+ } catch {
74
+ return;
75
+ }
76
+ try {
77
+ await fs.stat(marker);
78
+ return;
79
+ } catch {
80
+ }
81
+ let entries;
82
+ try {
83
+ entries = await fs.readdir(oldDir);
84
+ } catch {
85
+ return;
86
+ }
87
+ const planFiles = entries.filter(
88
+ (name) => name.endsWith(".md") && !name.startsWith(".")
89
+ );
90
+ await fs.mkdir(planDir, { recursive: true });
91
+ for (const name of planFiles) {
92
+ const src = path.join(oldDir, name);
93
+ const dst = path.join(planDir, name);
94
+ let dstExists = false;
95
+ try {
96
+ await fs.stat(dst);
97
+ dstExists = true;
98
+ } catch {
99
+ dstExists = false;
100
+ }
101
+ if (!dstExists) {
102
+ await fs.rename(src, dst);
103
+ continue;
104
+ }
105
+ const [srcBuf, dstBuf] = await Promise.all([
106
+ fs.readFile(src),
107
+ fs.readFile(dst)
108
+ ]);
109
+ if (srcBuf.equals(dstBuf)) {
110
+ await fs.unlink(src);
111
+ continue;
112
+ }
113
+ process.stderr.write(
114
+ `[harness-opencode] migratePlans: conflict on ${name} \u2014 destination ${dst} exists with different content; leaving source ${src} in place. Resolve manually.
115
+ `
116
+ );
117
+ }
118
+ await fs.writeFile(marker, "");
119
+ }
120
+
121
+ // src/pilot/paths.ts
122
+ function expandTilde2(p) {
123
+ if (p === "~") return os2.homedir();
124
+ if (p.startsWith("~/")) return path2.join(os2.homedir(), p.slice(2));
125
+ return p;
126
+ }
127
+ function resolveBaseDir() {
128
+ const pilotEnv = process.env.GLORIOUS_PILOT_DIR;
129
+ if (pilotEnv) return expandTilde2(pilotEnv);
130
+ const planEnv = process.env.GLORIOUS_PLAN_DIR;
131
+ if (planEnv) {
132
+ return path2.dirname(expandTilde2(planEnv));
133
+ }
134
+ return path2.join(os2.homedir(), ".glorious", "opencode");
135
+ }
136
+ async function getPilotDir(cwd) {
137
+ const base = resolveBaseDir();
138
+ const repoFolder = await getRepoFolder(cwd);
139
+ const dir = path2.join(base, repoFolder, "pilot");
140
+ await fs2.mkdir(dir, { recursive: true });
141
+ return dir;
142
+ }
143
+ async function getPlansDir(cwd) {
144
+ const pilot = await getPilotDir(cwd);
145
+ const dir = path2.join(pilot, "plans");
146
+ await fs2.mkdir(dir, { recursive: true });
147
+ return dir;
148
+ }
149
+ async function getRunDir(cwd, runId) {
150
+ if (!isSafeRunId(runId)) {
151
+ throw new Error(
152
+ `getRunDir: runId ${JSON.stringify(runId)} is not a safe filesystem segment`
153
+ );
154
+ }
155
+ const pilot = await getPilotDir(cwd);
156
+ const dir = path2.join(pilot, "runs", runId);
157
+ await fs2.mkdir(dir, { recursive: true });
158
+ return dir;
159
+ }
160
+ async function getStateDbPath(cwd, runId) {
161
+ const runDir = await getRunDir(cwd, runId);
162
+ return path2.join(runDir, "state.db");
163
+ }
164
+ async function getWorkerJsonlPath(cwd, runId, n) {
165
+ const runDir = await getRunDir(cwd, runId);
166
+ const workersDir = path2.join(runDir, "workers");
167
+ await fs2.mkdir(workersDir, { recursive: true });
168
+ const padded = n.toString().padStart(2, "0");
169
+ return path2.join(workersDir, `${padded}.jsonl`);
170
+ }
171
+ async function getTaskJsonlPath(cwd, runId, taskId) {
172
+ if (!isSafeRunId(runId)) {
173
+ throw new Error(
174
+ `getTaskJsonlPath: runId ${JSON.stringify(runId)} is not a safe filesystem segment`
175
+ );
176
+ }
177
+ if (!isSafeTaskId(taskId)) {
178
+ throw new Error(
179
+ `getTaskJsonlPath: taskId ${JSON.stringify(taskId)} is not a safe filesystem segment`
180
+ );
181
+ }
182
+ const runDir = await getRunDir(cwd, runId);
183
+ const taskDir = path2.join(runDir, "tasks", taskId);
184
+ await fs2.mkdir(taskDir, { recursive: true });
185
+ return path2.join(taskDir, "session.jsonl");
186
+ }
187
+ function isSafeRunId(runId) {
188
+ return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(runId);
189
+ }
190
+ function isSafeTaskId(taskId) {
191
+ return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(taskId);
192
+ }
193
+
194
+ export {
195
+ getPlanDir,
196
+ migratePlans,
197
+ resolveBaseDir,
198
+ getPilotDir,
199
+ getPlansDir,
200
+ getRunDir,
201
+ getStateDbPath,
202
+ getWorkerJsonlPath,
203
+ getTaskJsonlPath
204
+ };
@@ -0,0 +1,145 @@
1
+ // src/pilot/worker/safety-gate.ts
2
+ import { execFile } from "child_process";
3
+ import { promisify } from "util";
4
+ import picomatch from "picomatch";
5
+ var execFileP = promisify(execFile);
6
+ var SAFETY_GATE_TOLERATE = [
7
+ // opencode plugin installer churn. opencode upgrades its own plugin
8
+ // dependency in the background, which bumps the pinned version in
9
+ // .opencode/package.json + .opencode/package-lock.json. Users don't
10
+ // author those edits; refusing to start pilot because of them is a
11
+ // consistent friction.
12
+ ".opencode/**",
13
+ // Next.js — `next build` regenerates this every run, often outside
14
+ // a pilot session.
15
+ "**/next-env.d.ts",
16
+ // Next.js app-router generated types.
17
+ "**/.next/types/**",
18
+ "**/.next/dev/types/**",
19
+ // TypeScript project-reference build info — tsc writes these.
20
+ "**/*.tsbuildinfo",
21
+ // Snapshot test files rewritten by `vitest -u` / `jest -u`.
22
+ "**/__snapshots__/**",
23
+ "**/*.snap"
24
+ ];
25
+ async function git(cwd, args) {
26
+ for (const a of args) {
27
+ if (a.includes("\0")) {
28
+ throw new Error(`git arg contains null byte: ${JSON.stringify(a)}`);
29
+ }
30
+ }
31
+ try {
32
+ const { stdout, stderr } = await execFileP("git", args, {
33
+ cwd,
34
+ timeout: 1e4,
35
+ maxBuffer: 1 << 20
36
+ });
37
+ return { stdout: stdout.toString(), stderr: stderr.toString(), ok: true };
38
+ } catch (err) {
39
+ const e = err;
40
+ return {
41
+ stdout: (e.stdout ?? "").toString(),
42
+ stderr: (e.stderr ?? "").toString(),
43
+ ok: false
44
+ };
45
+ }
46
+ }
47
+ async function headSha(cwd) {
48
+ const r = await git(cwd, ["rev-parse", "HEAD"]);
49
+ if (!r.ok) throw new Error(`git rev-parse HEAD failed: ${r.stderr.trim()}`);
50
+ return r.stdout.trim();
51
+ }
52
+ var FORBIDDEN_BRANCHES = /* @__PURE__ */ new Set(["main", "master"]);
53
+ function parsePorcelainPaths(stdout) {
54
+ const paths = [];
55
+ for (const line of stdout.split("\n")) {
56
+ if (line.length < 4) continue;
57
+ let rest = line.slice(3);
58
+ const arrow = rest.indexOf(" -> ");
59
+ if (arrow !== -1) rest = rest.slice(arrow + 4);
60
+ if (rest.startsWith('"') && rest.endsWith('"')) {
61
+ rest = rest.slice(1, -1);
62
+ }
63
+ paths.push(rest);
64
+ }
65
+ return paths;
66
+ }
67
+ async function checkCwdSafety(cwd) {
68
+ const inside = await git(cwd, ["rev-parse", "--is-inside-work-tree"]);
69
+ if (!inside.ok || inside.stdout.trim() !== "true") {
70
+ return {
71
+ ok: false,
72
+ reason: `not inside a git worktree: ${cwd}`
73
+ };
74
+ }
75
+ const branchRes = await git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
76
+ if (!branchRes.ok) {
77
+ return {
78
+ ok: false,
79
+ reason: `cannot determine current branch: ${branchRes.stderr.trim()}`
80
+ };
81
+ }
82
+ const branch = branchRes.stdout.trim();
83
+ if (FORBIDDEN_BRANCHES.has(branch)) {
84
+ return {
85
+ ok: false,
86
+ reason: `refuse to run on protected branch: ${branch}. Switch to a feature branch first.`
87
+ };
88
+ }
89
+ const defaultRes = await git(cwd, [
90
+ "symbolic-ref",
91
+ "--short",
92
+ "refs/remotes/origin/HEAD"
93
+ ]);
94
+ if (defaultRes.ok) {
95
+ const remoteDefault = defaultRes.stdout.trim().replace(/^origin\//, "");
96
+ if (remoteDefault && branch === remoteDefault) {
97
+ return {
98
+ ok: false,
99
+ reason: `refuse to run on the remote's default branch: ${branch}. Switch to a feature branch first.`
100
+ };
101
+ }
102
+ }
103
+ const statusRes = await git(cwd, ["status", "--porcelain"]);
104
+ if (!statusRes.ok) {
105
+ return {
106
+ ok: false,
107
+ reason: `git status failed: ${statusRes.stderr.trim()}`
108
+ };
109
+ }
110
+ const rawStdout = statusRes.stdout.replace(/\n$/, "");
111
+ if (rawStdout.length === 0) {
112
+ return { ok: true, warnings: [] };
113
+ }
114
+ const paths = parsePorcelainPaths(rawStdout);
115
+ const matchTolerate = picomatch([...SAFETY_GATE_TOLERATE], { dot: true });
116
+ const tolerated = [];
117
+ const genuine = [];
118
+ for (const p of paths) {
119
+ if (matchTolerate(p)) tolerated.push(p);
120
+ else genuine.push(p);
121
+ }
122
+ if (genuine.length > 0) {
123
+ const lines = rawStdout.split("\n").slice(0, 10).map((s) => " " + s).join("\n");
124
+ return {
125
+ ok: false,
126
+ reason: `working tree is dirty; pilot refuses to run on uncommitted changes.
127
+ Commit, stash, or discard them, then re-run.
128
+ First 10 lines of git status --porcelain:
129
+ ${lines}`
130
+ };
131
+ }
132
+ const preview = tolerated.slice(0, 5);
133
+ const suffix = tolerated.length > preview.length ? ` (+${tolerated.length - preview.length} more)` : "";
134
+ const warnings = [
135
+ `working tree has ${tolerated.length} modified file(s) in framework-owned paths; treating tree as clean:
136
+ ` + preview.map((p) => ` ${p}`).join("\n") + suffix
137
+ ];
138
+ return { ok: true, warnings };
139
+ }
140
+
141
+ export {
142
+ SAFETY_GATE_TOLERATE,
143
+ headSha,
144
+ checkCwdSafety
145
+ };
@@ -0,0 +1,56 @@
1
+ // src/pilot/mcp/session-registry.ts
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+ import { promisify } from "util";
5
+ var writeFile2 = promisify(fs.writeFile);
6
+ var rename2 = promisify(fs.rename);
7
+ var unlink2 = promisify(fs.unlink);
8
+ var mkdir2 = promisify(fs.mkdir);
9
+ function getSessionsPath(runDir) {
10
+ return path.join(runDir, "sessions.json");
11
+ }
12
+ function readSessions(runDir) {
13
+ const sessionsPath = getSessionsPath(runDir);
14
+ try {
15
+ const content = fs.readFileSync(sessionsPath, "utf8");
16
+ const parsed = JSON.parse(content);
17
+ if (typeof parsed !== "object" || parsed === null) {
18
+ return {};
19
+ }
20
+ return parsed;
21
+ } catch {
22
+ return {};
23
+ }
24
+ }
25
+ async function registerSession(args) {
26
+ const { runDir, sessionId, runId, taskId } = args;
27
+ const sessionsPath = getSessionsPath(runDir);
28
+ await mkdir2(runDir, { recursive: true });
29
+ const current = readSessions(runDir);
30
+ const updated = {
31
+ ...current,
32
+ [sessionId]: { runId, taskId }
33
+ };
34
+ const tempPath = `${sessionsPath}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 8)}`;
35
+ await writeFile2(tempPath, JSON.stringify(updated, null, 2), "utf8");
36
+ await rename2(tempPath, sessionsPath);
37
+ }
38
+ async function unregisterSession(args) {
39
+ const { runDir, sessionId } = args;
40
+ const sessionsPath = getSessionsPath(runDir);
41
+ const current = readSessions(runDir);
42
+ if (!(sessionId in current)) {
43
+ return;
44
+ }
45
+ const { [sessionId]: _, ...rest } = current;
46
+ const tempPath = `${sessionsPath}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 8)}`;
47
+ await writeFile2(tempPath, JSON.stringify(rest, null, 2), "utf8");
48
+ await rename2(tempPath, sessionsPath);
49
+ }
50
+
51
+ export {
52
+ getSessionsPath,
53
+ readSessions,
54
+ registerSession,
55
+ unregisterSession
56
+ };