@koreanhole/kandev 0.0.0-stage → 0.1.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.
Files changed (51) hide show
  1. package/README.md +367 -2
  2. package/bin/codex-acp.js +16 -0
  3. package/bin/kandev-auto-sync.mjs +101 -0
  4. package/bin/kandev-config.js +53 -0
  5. package/bin/kandev.js +35 -0
  6. package/config/config.yaml +6 -0
  7. package/config/docker/projects/opencodex-cli.json +79 -0
  8. package/config/docker/projects/samsung-bus-tracker.json +91 -0
  9. package/config/gateways.json +14 -0
  10. package/config/pipeline.json +150 -0
  11. package/config/workflows/sdlc.yaml +1019 -0
  12. package/docker/Dockerfile +68 -0
  13. package/docker/Dockerfile.opencodex-cli +44 -0
  14. package/docker/Dockerfile.samsung-bus-tracker +75 -0
  15. package/package.json +61 -4
  16. package/scripts/agent-tools-docker.mjs +223 -0
  17. package/scripts/baseline.mjs +20 -0
  18. package/scripts/codex-medium +2 -0
  19. package/scripts/codex-stage +22 -0
  20. package/scripts/gate.mjs +909 -0
  21. package/scripts/gateways/docker.mjs +64 -0
  22. package/scripts/gateways/speckit.mjs +78 -0
  23. package/scripts/install-prerequisites.mjs +48 -0
  24. package/scripts/lib/artifacts.mjs +990 -0
  25. package/scripts/lib/bugfix.mjs +325 -0
  26. package/scripts/lib/checksum.mjs +166 -0
  27. package/scripts/lib/docker-workspace.mjs +1209 -0
  28. package/scripts/lib/gateways.mjs +79 -0
  29. package/scripts/lib/kandev.mjs +273 -0
  30. package/scripts/lib/mcp.mjs +111 -0
  31. package/scripts/lib/pipeline.mjs +548 -0
  32. package/scripts/lib/planning-replan.mjs +103 -0
  33. package/scripts/lib/resume.mjs +207 -0
  34. package/scripts/lib/review-history.mjs +260 -0
  35. package/scripts/lib/stage-boundary.mjs +146 -0
  36. package/scripts/lib/stage-model.mjs +23 -0
  37. package/scripts/lib/task-worktree.mjs +40 -0
  38. package/scripts/measure-tokens.mjs +121 -0
  39. package/scripts/planning-tools.mjs +166 -0
  40. package/scripts/replan-planning.mjs +82 -0
  41. package/scripts/review-digest.mjs +240 -0
  42. package/scripts/run-android-e2e.mjs +116 -0
  43. package/scripts/run-code-review.mjs +281 -0
  44. package/scripts/run-detached.mjs +163 -0
  45. package/scripts/run-doc-review.mjs +155 -0
  46. package/scripts/run-gateways.mjs +138 -0
  47. package/scripts/sync.mjs +588 -0
  48. package/scripts/verify-change.mjs +252 -0
  49. package/scripts/verify-node.mjs +288 -0
  50. package/scripts/verify.mjs +442 -0
  51. package/scripts/wait-status.mjs +88 -0
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ /** Run the pinned Android E2E agent with the Kandev stage model. */
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { requireStageModel, resolveStageAgent } from "./lib/stage-model.mjs";
8
+ import { maybeReexecInTaskContainer } from "./lib/docker-workspace.mjs";
9
+
10
+ const SELF = fileURLToPath(import.meta.url);
11
+ const ROOT = path.resolve(path.dirname(SELF), "..");
12
+ const PACKAGE = "@koreanhole/android-testing-superpowers@0.1.5";
13
+ const NPX = path.join(path.dirname(process.execPath), process.platform === "win32" ? "npx.cmd" : "npx");
14
+ const SHIM = path.join(ROOT, "scripts", "codex-stage");
15
+
16
+ function fail(message) {
17
+ process.stderr.write(`${message}\n`);
18
+ process.exit(2);
19
+ }
20
+
21
+ function options(input) {
22
+ const value = typeof input === "string" ? { cwd: input } : input || {};
23
+ if (!value.cwd) throw new Error("cwd is required");
24
+ return { ...value, cwd: path.resolve(value.cwd) };
25
+ }
26
+
27
+ export function buildAndroidDoctorCommand(input) {
28
+ const value = options(input);
29
+ return [NPX, "-y", PACKAGE, "doctor", value.cwd];
30
+ }
31
+
32
+ export function buildAndroidE2ECommand(input) {
33
+ const value = options(input);
34
+ if (value.device && value.avd) throw new Error("use either --device or --avd");
35
+ const reportsDir = value.reportsDir || ".agentic/android-reports";
36
+ const argv = [
37
+ NPX, "-y", PACKAGE, "test", value.cwd,
38
+ "--provider", "cli",
39
+ "--reports-dir", reportsDir,
40
+ "--output-map", `${reportsDir}/app_ui_map.json`,
41
+ "--output-scenarios", `${reportsDir}/test_scenarios.json`,
42
+ "--non-interactive",
43
+ ];
44
+ if (value.device) argv.push("--device", value.device);
45
+ else if (value.avd) argv.push("--avd", value.avd);
46
+ return argv;
47
+ }
48
+
49
+ export function buildAndroidE2EEnvironment(env = process.env) {
50
+ const model = requireStageModel(env);
51
+ return {
52
+ ...env,
53
+ SUPERPOWER_LLM_PROVIDER: "cli",
54
+ SUPERPOWER_LLM_MODEL: model,
55
+ SUPERPOWER_LLM_CLI_COMMAND: SHIM,
56
+ };
57
+ }
58
+
59
+ function parse(argv) {
60
+ if (argv[0] === "--help") return { help: true };
61
+ const result = { command: argv[0] || "test" };
62
+ if (!["doctor", "test"].includes(result.command)) fail(`unknown command ${result.command}`);
63
+ for (let i = 1; i < argv.length; i += 1) {
64
+ const key = argv[i];
65
+ if (key === "--help") return { help: true };
66
+ if (!["--cwd", "--reports-dir", "--device", "--avd"].includes(key)) fail(`unknown option ${key}`);
67
+ const value = argv[i + 1];
68
+ if (value === undefined) fail(`missing value for ${key}`);
69
+ result[key.slice(2)] = value;
70
+ i += 1;
71
+ }
72
+ if (!result.cwd) fail("missing --cwd");
73
+ return result;
74
+ }
75
+
76
+ function run(command, env, cwd) {
77
+ return new Promise((resolve, reject) => {
78
+ const child = spawn(command[0], command.slice(1), { stdio: "inherit", env, cwd });
79
+ child.on("error", reject);
80
+ child.on("exit", (code) => resolve(code ?? 1));
81
+ });
82
+ }
83
+
84
+ async function main() {
85
+ const input = parse(process.argv.slice(2));
86
+ if (input.help) {
87
+ console.log("Usage: node scripts/run-android-e2e.mjs <doctor|test> --cwd <abs> [--reports-dir <path>] [--device <serial> | --avd <name>]");
88
+ return;
89
+ }
90
+ const cwd = path.resolve(input.cwd);
91
+ if (!fs.existsSync(cwd)) fail(`cwd does not exist: ${input.cwd}`);
92
+ const reexec = await maybeReexecInTaskContainer({
93
+ cwd,
94
+ scriptPath: SELF,
95
+ root: ROOT,
96
+ });
97
+ if (reexec) {
98
+ process.exitCode = reexec.status;
99
+ return;
100
+ }
101
+ const env = buildAndroidE2EEnvironment();
102
+ try {
103
+ fs.accessSync(SHIM, fs.constants.X_OK);
104
+ } catch {
105
+ fail(`stage model shim is missing or not executable: ${SHIM}`);
106
+ }
107
+ const cliBin = resolveStageAgent(env) === "gemini" ? "gemini" : "codex";
108
+ const probe = spawnSync(cliBin, ["--version"], { encoding: "utf8" });
109
+ if (probe.status !== 0) fail(`${cliBin} CLI is required for the Android stage model`);
110
+ const command = input.command === "doctor" ? buildAndroidDoctorCommand(input) : buildAndroidE2ECommand(input);
111
+ process.exitCode = await run(command, env, cwd);
112
+ }
113
+
114
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
115
+ main().catch((err) => fail(err.message));
116
+ }
@@ -0,0 +1,281 @@
1
+ #!/usr/bin/env node
2
+ /** Detect the reviewable diff and start the pinned code review. */
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { requireStageModel, resolveStageAgent } from "./lib/stage-model.mjs";
8
+ import { maybeReexecInTaskContainer } from "./lib/docker-workspace.mjs";
9
+
10
+ const SELF = fileURLToPath(import.meta.url);
11
+ const ROOT = path.resolve(path.dirname(SELF), "..");
12
+ const DETACHED = path.join(ROOT, "scripts", "run-detached.mjs");
13
+ const PACKAGE = "@koreanhole/code-review-agent@0.5.0";
14
+ const NPX = path.join(path.dirname(process.execPath), process.platform === "win32" ? "npx.cmd" : "npx");
15
+ const BASE_REFS = ["main", "master", "origin/main", "origin/master"];
16
+ const BRIEF = "Review the detected application diff against .agentic/spec.json and the reviewed documents listed in its documents array. specs/ is planning evidence and is intentionally excluded from the review snapshot. Report only application-code defects: requirement coverage, correctness, security, and test gaps. Reserve CRITICAL and HIGH only for concrete, reproducible defects introduced by the diff that directly break an explicit requirement or cause a crash or security flaw; classify secondary edge cases, pre-existing behavior outside the diff, concurrency/polling micro-optimizations, or test-style preferences as LOW or INFO. Do not report process, tooling, or Spec-Kit findings; a missing .specify/ directory or gateway artifact is not a finding. Return at most 8 findings, one line each, with severity, path:line when known, and a bounded message. Omit process commentary and repeated checks.";
17
+ const REVIEW_TIMEOUT_MS = "1200000";
18
+ const REVIEW_RUN_TIMEOUT_MS = "1800000";
19
+ const REVIEW_REASONING_EFFORT = "medium";
20
+ const DEFAULT_ROLES = Object.freeze({
21
+ bugfix: ["adversarial", "regression"],
22
+ feature: ["spec-compliance", "adversarial", "regression"],
23
+ });
24
+ export const REVIEW_EXCLUDES = [
25
+ ".agentic/*.log",
26
+ ".agentic/*.status.json",
27
+ ".agentic/.detached-*",
28
+ ".agentic/code-review.mode.json",
29
+ ".agentic/gateway.json",
30
+ ".agentic/speckit-analyze.md",
31
+ ".agentic/doc-review.log",
32
+ ".agentic/doc-review.status.json",
33
+ ".agentic/doc-review-runs/",
34
+ ".agentic/spec-review.json",
35
+ ".agentic/review.json",
36
+ ".agentic/e2e.json",
37
+ ".agentic/bugfix.json",
38
+ ".agentic/bugfix-repro.mjs",
39
+ ".agentic/bugfix-result.json",
40
+ ".agentic/bugfix-runs/",
41
+ ".agentic/implementation.json",
42
+ ".agentic/rework/",
43
+ ".agentic/logs/",
44
+ ".agentic/review-excludes.txt",
45
+ "specs/",
46
+ ".agents/",
47
+ ".specify/",
48
+ ".review-*",
49
+ ".review-runs/",
50
+ ".review-worktrees/",
51
+ ".review-clones/",
52
+ ];
53
+
54
+ export function writeReviewExcludes(cwd) {
55
+ const dir = path.join(path.resolve(cwd), ".agentic");
56
+ fs.mkdirSync(dir, { recursive: true });
57
+ const file = path.join(dir, "review-excludes.txt");
58
+ fs.writeFileSync(file, REVIEW_EXCLUDES.join("\n") + "\n");
59
+ return file;
60
+ }
61
+
62
+ export function buildReviewGitEnvironment(env = process.env, excludesFile) {
63
+ if (!excludesFile) throw new Error("excludesFile is required");
64
+ const next = { ...env };
65
+ const count = Number.parseInt(next.GIT_CONFIG_COUNT || "0", 10);
66
+ const index = Number.isInteger(count) && count >= 0 ? count : 0;
67
+ next["GIT_CONFIG_KEY_" + index] = "core.excludesFile";
68
+ next["GIT_CONFIG_VALUE_" + index] = path.resolve(excludesFile);
69
+ next.GIT_CONFIG_COUNT = String(index + 1);
70
+ next.npm_config_prefer_offline = "false";
71
+ return next;
72
+ }
73
+
74
+ export function selectReviewRoles({ changeType = "feature", platform = "web" } = {}) {
75
+ const roles = [...(DEFAULT_ROLES[changeType] || DEFAULT_ROLES.feature)];
76
+ if (platform === "android") roles.push("anr-fc-risk");
77
+ return roles;
78
+ }
79
+
80
+ function readSpec(cwd) {
81
+ try {
82
+ return JSON.parse(fs.readFileSync(path.join(path.resolve(cwd), ".agentic", "spec.json"), "utf8"));
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ function git(cwd, args) {
89
+ const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", shell: false });
90
+ return {
91
+ ok: result.status === 0,
92
+ stdout: result.stdout || "",
93
+ stderr: result.stderr || "",
94
+ };
95
+ }
96
+
97
+ export function detectReviewMode(cwd, { baseRef = null } = {}) {
98
+ const repo = path.resolve(cwd);
99
+ const status = git(repo, ["status", "--porcelain", "--untracked-files=all"]);
100
+ if (!status.ok) throw new Error(`git status failed: ${status.stderr.trim() || "unknown error"}`);
101
+ if (status.stdout.trim()) return { mode: "working-tree", base: null, dirty: true };
102
+
103
+ const refs = baseRef ? [baseRef] : BASE_REFS;
104
+ const head = git(repo, ["rev-parse", "HEAD"]);
105
+ if (!head.ok) throw new Error(`git rev-parse HEAD failed: ${head.stderr.trim() || "unknown error"}`);
106
+ const headSha = head.stdout.trim();
107
+ for (const ref of refs) {
108
+ const resolved = git(repo, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
109
+ if (!resolved.ok) continue;
110
+ const mergeBase = git(repo, ["merge-base", "HEAD", ref]);
111
+ if (!mergeBase.ok) continue;
112
+ const base = mergeBase.stdout.trim();
113
+ if (!base || base === headSha) continue;
114
+ const count = git(repo, ["rev-list", "--count", `${base}..HEAD`]);
115
+ if (count.ok && Number(count.stdout.trim()) > 0) return { mode: "base", base, dirty: false };
116
+ }
117
+ return { mode: "no-diff", base: null, dirty: false };
118
+ }
119
+
120
+ export function buildCodeReviewAgentCommand(input, env = process.env) {
121
+ const options = typeof input === "string" ? { cwd: input } : input || {};
122
+ if (!options.cwd) throw new Error("cwd is required");
123
+ const model = requireStageModel(env);
124
+ const agent = resolveStageAgent(env);
125
+ const cwd = path.resolve(options.cwd);
126
+ const argv = [NPX, "-y", PACKAGE, "run", "--repo", cwd];
127
+ if (options.base) argv.push("--base", options.base);
128
+ argv.push(
129
+ "--brief", BRIEF,
130
+ "--json",
131
+ );
132
+ const roles = options.roles || selectReviewRoles(options);
133
+ for (const role of roles) argv.push("--role", `${role}=${agent}:${model}`);
134
+ return argv;
135
+ }
136
+
137
+ export function buildCodeReviewCommand(input, env = process.env) {
138
+ const options = typeof input === "string" ? { cwd: input } : input || {};
139
+ if (!options.cwd) throw new Error("cwd is required");
140
+ const cwd = path.resolve(options.cwd);
141
+ return [
142
+ process.execPath,
143
+ DETACHED,
144
+ "--cwd", cwd,
145
+ "--log", options.log || ".agentic/code-review.log",
146
+ "--status", options.status || ".agentic/code-review.status.json",
147
+ "--",
148
+ ...buildCodeReviewAgentCommand({
149
+ cwd,
150
+ base: options.base,
151
+ changeType: options.changeType,
152
+ platform: options.platform,
153
+ roles: options.roles,
154
+ }, env),
155
+ ];
156
+ }
157
+
158
+ export function buildCodeReviewEnvironment(env = process.env, moduleRoot = ROOT) {
159
+ const root = path.resolve(env.KANDEV_WORKFLOW_ROOT || moduleRoot);
160
+ const agent = resolveStageAgent(env);
161
+ if (agent === "gemini") {
162
+ return {
163
+ ...env,
164
+ GEMINI_CLI_TRUST_WORKSPACE: env.GEMINI_CLI_TRUST_WORKSPACE || "true",
165
+ npm_config_prefer_offline: "false",
166
+ };
167
+ }
168
+ return {
169
+ ...env,
170
+ REVIEW_AGENT_CODEX: path.join(root, "scripts", "codex-medium"),
171
+ REVIEW_AGENT_CODEX_ACP: "none",
172
+ npm_config_prefer_offline: "false",
173
+ };
174
+ }
175
+
176
+ export function formatReviewSpawn(env, roles = []) {
177
+ const model = requireStageModel(env);
178
+ const agent = resolveStageAgent(env);
179
+ if (agent === "gemini") {
180
+ return `[run-code-review] reviewer=gemini model=${model} roles=${roles.join(",")} transport=acp\n`;
181
+ }
182
+ return `[run-code-review] reviewer=codex model=${model} reasoning_effort=${REVIEW_REASONING_EFFORT} roles=${roles.join(",")} transport=cli shim=${env.REVIEW_AGENT_CODEX}\n`;
183
+ }
184
+
185
+ function writeJson(file, value) {
186
+ fs.mkdirSync(path.dirname(file), { recursive: true });
187
+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);
188
+ }
189
+
190
+ function writeMode(cwd, mode) {
191
+ writeJson(path.join(cwd, ".agentic", "code-review.mode.json"), mode);
192
+ }
193
+
194
+ function fail(message) {
195
+ process.stderr.write(`${message}\n`);
196
+ process.exit(2);
197
+ }
198
+
199
+ function parse(argv) {
200
+ const options = {};
201
+ for (let i = 0; i < argv.length; i += 1) {
202
+ const key = argv[i];
203
+ if (key === "--help") return { help: true };
204
+ if (!["--cwd", "--log", "--status", "--base-ref"].includes(key)) fail(`unknown option ${key}`);
205
+ const value = argv[i + 1];
206
+ if (value === undefined) fail(`missing value for ${key}`);
207
+ if (key === "--base-ref") options.baseRef = value;
208
+ else options[key.slice(2)] = value;
209
+ i += 1;
210
+ }
211
+ if (!options.cwd) fail("missing --cwd");
212
+ return options;
213
+ }
214
+
215
+ function run(command, env) {
216
+ return new Promise((resolve, reject) => {
217
+ const child = spawn(command[0], command.slice(1), { stdio: "inherit", env });
218
+ child.on("error", reject);
219
+ child.on("exit", (code) => resolve(code ?? 1));
220
+ });
221
+ }
222
+
223
+ async function main() {
224
+ const options = parse(process.argv.slice(2));
225
+ if (options.help) {
226
+ console.log("Usage: node scripts/run-code-review.mjs --cwd <abs> [--log <rel>] [--status <rel>] [--base-ref <ref>]");
227
+ return;
228
+ }
229
+ const cwd = path.resolve(options.cwd);
230
+ if (!fs.existsSync(cwd)) fail(`cwd does not exist: ${options.cwd}`);
231
+ const reexec = await maybeReexecInTaskContainer({
232
+ cwd,
233
+ scriptPath: SELF,
234
+ root: ROOT,
235
+ });
236
+ if (reexec) {
237
+ process.exitCode = reexec.status;
238
+ return;
239
+ }
240
+ process.env.REVIEW_TIMEOUT_MS ||= REVIEW_TIMEOUT_MS;
241
+ process.env.REVIEW_RUN_TIMEOUT_MS ||= REVIEW_RUN_TIMEOUT_MS;
242
+ let mode;
243
+ try {
244
+ mode = detectReviewMode(cwd, { baseRef: options.baseRef || null });
245
+ } catch (err) {
246
+ fail(err.message);
247
+ }
248
+ writeMode(cwd, mode);
249
+ if (mode.mode === "no-diff") {
250
+ writeJson(path.resolve(cwd, options.status || ".agentic/code-review.status.json"), {
251
+ status: "failed",
252
+ exitCode: 3,
253
+ reason: "no changes to review",
254
+ });
255
+ process.exit(3);
256
+ }
257
+ const reviewerEnv = buildCodeReviewEnvironment();
258
+ Object.assign(reviewerEnv, buildReviewGitEnvironment(reviewerEnv, writeReviewExcludes(cwd)));
259
+ const spec = readSpec(cwd);
260
+ const changeType = spec?.change_type === "bugfix" ? "bugfix" : "feature";
261
+ const platform = spec?.platform || "web";
262
+ const roles = selectReviewRoles({ changeType, platform });
263
+ try {
264
+ fs.accessSync(reviewerEnv.REVIEW_AGENT_CODEX, fs.constants.X_OK);
265
+ } catch {
266
+ fail(`reviewer shim is missing or not executable: ${reviewerEnv.REVIEW_AGENT_CODEX}`);
267
+ }
268
+ try {
269
+ process.stderr.write(formatReviewSpawn(reviewerEnv, roles));
270
+ process.exitCode = await run(
271
+ buildCodeReviewCommand({ ...options, cwd, base: mode.base, changeType, platform, roles }, reviewerEnv),
272
+ reviewerEnv,
273
+ );
274
+ } catch (err) {
275
+ fail(err.message);
276
+ }
277
+ }
278
+
279
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
280
+ main();
281
+ }
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Start a long-running CLI agent without blocking the MCP run_process call.
4
+ *
5
+ * Usage:
6
+ * node scripts/run-detached.mjs --cwd <dir> --log <file> --status <file> -- <argv...>
7
+ *
8
+ * The parent writes a "running" status and exits immediately. A detached monitor
9
+ * process owns the child, waits for it, and rewrites the status to completed/failed.
10
+ * Stage prompts poll the status file instead of holding a single MCP call open.
11
+ */
12
+ import { spawn } from "node:child_process";
13
+ import fs from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ const SELF = fileURLToPath(import.meta.url);
19
+
20
+ function containerInfo() {
21
+ const inContainer = process.env.KANDEV_IN_CONTAINER === "1" || fs.existsSync("/.dockerenv");
22
+ return inContainer
23
+ ? { inContainer: true, containerName: process.env.KANDEV_CONTAINER_NAME || os.hostname() }
24
+ : { inContainer: false };
25
+ }
26
+
27
+ function fail(message) {
28
+ process.stderr.write(`${message}\n`);
29
+ process.exit(2);
30
+ }
31
+
32
+ function parse(argv) {
33
+ const sep = argv.indexOf("--");
34
+ if (sep < 0) fail("missing -- before the command");
35
+ const options = {};
36
+ for (let i = 0; i < sep; i += 1) {
37
+ const key = argv[i];
38
+ if (!key.startsWith("--")) fail(`unexpected option ${key}`);
39
+ const value = argv[i + 1];
40
+ if (value === undefined) fail(`missing value for ${key}`);
41
+ options[key.slice(2)] = value;
42
+ i += 1;
43
+ }
44
+ const command = argv.slice(sep + 1);
45
+ if (command.length === 0) fail("missing command after --");
46
+ return { options, command };
47
+ }
48
+
49
+ function writeStatus(file, payload) {
50
+ fs.mkdirSync(path.dirname(file), { recursive: true });
51
+ fs.writeFileSync(file, `${JSON.stringify(payload, null, 2)}\n`);
52
+ }
53
+
54
+ function monitor(specPath) {
55
+ const spec = JSON.parse(fs.readFileSync(specPath, "utf8"));
56
+ const fd = fs.openSync(spec.log, "a");
57
+ const startedAt = new Date().toISOString();
58
+ const child = spawn(spec.command[0], spec.command.slice(1), {
59
+ cwd: spec.cwd,
60
+ env: process.env,
61
+ stdio: ["ignore", fd, fd],
62
+ detached: true,
63
+ });
64
+ let finished = false;
65
+ let hardTimedOut = false;
66
+ let hardTimer = null;
67
+ let hardGrace = null;
68
+ const base = {
69
+ pid: child.pid,
70
+ monitorPid: process.pid,
71
+ startedAt,
72
+ cwd: spec.cwd,
73
+ command: spec.command,
74
+ log: spec.log,
75
+ ...containerInfo(),
76
+ };
77
+ const cleanup = () => {
78
+ fs.rmSync(specPath, { force: true });
79
+ try { fs.closeSync(fd); } catch { /* already closed */ }
80
+ };
81
+ const finish = (code, signal) => {
82
+ if (finished) return;
83
+ finished = true;
84
+ if (hardTimer) clearTimeout(hardTimer);
85
+ if (hardGrace) clearTimeout(hardGrace);
86
+ writeStatus(spec.status, {
87
+ status: code === 0 && !hardTimedOut ? "completed" : "failed",
88
+ ...base,
89
+ finishedAt: new Date().toISOString(),
90
+ exitCode: code,
91
+ signal,
92
+ ...(hardTimedOut ? { timedOut: true, error: `hard timeout after ${spec.killTimeoutMs}ms` } : {}),
93
+ });
94
+ cleanup();
95
+ };
96
+ writeStatus(spec.status, {
97
+ status: "running",
98
+ ...base,
99
+ });
100
+ const killAfter = Number(spec.killTimeoutMs || 0);
101
+ if (Number.isInteger(killAfter) && killAfter > 0) {
102
+ hardTimer = setTimeout(() => {
103
+ if (finished) return;
104
+ hardTimedOut = true;
105
+ try { process.kill(-child.pid, "SIGKILL"); } catch { try { child.kill("SIGKILL"); } catch { /* gone */ } }
106
+ hardGrace = setTimeout(() => finish(null, "SIGKILL"), 1000);
107
+ }, killAfter);
108
+ }
109
+ child.on("exit", finish);
110
+ child.on("error", (error) => {
111
+ if (finished) return;
112
+ finished = true;
113
+ if (hardTimer) clearTimeout(hardTimer);
114
+ if (hardGrace) clearTimeout(hardGrace);
115
+ writeStatus(spec.status, {
116
+ status: "failed",
117
+ ...base,
118
+ pid: null,
119
+ finishedAt: new Date().toISOString(),
120
+ exitCode: null,
121
+ error: error.message,
122
+ });
123
+ cleanup();
124
+ });
125
+ }
126
+
127
+ const rawArgs = process.argv.slice(2);
128
+ const monitorIndex = rawArgs.indexOf("--monitor");
129
+ if (monitorIndex >= 0) {
130
+ const specPath = rawArgs[monitorIndex + 1];
131
+ if (!specPath) fail("missing monitor spec path");
132
+ monitor(specPath);
133
+ } else {
134
+ const { options, command } = parse(rawArgs);
135
+ const cwd = path.resolve(options.cwd || process.cwd());
136
+ const log = path.resolve(cwd, options.log || ".agentic/agent.log");
137
+ const status = path.resolve(cwd, options.status || ".agentic/agent.status.json");
138
+ const killTimeoutMs = Number(options["kill-timeout-ms"] || 0);
139
+ if (!Number.isInteger(killTimeoutMs) || killTimeoutMs < 0) fail("--kill-timeout-ms must be a non-negative integer");
140
+ fs.mkdirSync(path.dirname(log), { recursive: true });
141
+ fs.mkdirSync(path.dirname(status), { recursive: true });
142
+ const specPath = path.resolve(cwd, ".agentic", `.detached-${process.pid}.json`);
143
+ fs.mkdirSync(path.dirname(specPath), { recursive: true });
144
+ fs.writeFileSync(specPath, JSON.stringify({ cwd, log, status, command, killTimeoutMs }, null, 2));
145
+ const child = spawn(process.execPath, [SELF, "--monitor", specPath], {
146
+ detached: true,
147
+ stdio: "ignore",
148
+ });
149
+ child.unref();
150
+ writeStatus(status, {
151
+ status: "running",
152
+ pid: null,
153
+ monitorPid: child.pid,
154
+ startedAt: new Date().toISOString(),
155
+ cwd,
156
+ command,
157
+ log,
158
+ ...containerInfo(),
159
+ });
160
+ process.stdout.write(
161
+ `${JSON.stringify({ status: "running", monitorPid: child.pid, statusFile: status, log })}\n`,
162
+ );
163
+ }