@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,1209 @@
1
+ /**
2
+ * Docker workspace management for Kandev tasks.
3
+ * Spins up task-dedicated containers, manages Git worktrees inside Docker,
4
+ * provisions project/toolchain dependencies inside the container, and configures
5
+ * container access to host Codex proxy & ADB services.
6
+ */
7
+ import crypto from "node:crypto";
8
+ import { spawnSync } from "node:child_process";
9
+ import fs from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+
13
+ export const DEFAULT_DOCKER_CONFIG = {
14
+ enabled: true,
15
+ image: "kandev-task-runtime:bookworm",
16
+ dockerfile: "docker/Dockerfile",
17
+ platform: "linux/amd64",
18
+ container_prefix: "kandev-task",
19
+ worktree_root: "~/.kandev/tasks",
20
+ provision_dependencies: true,
21
+ };
22
+
23
+ export function parseBoolean(value, defaultValue = true) {
24
+ if (typeof value === "boolean") return value;
25
+ if (value === undefined || value === null) return defaultValue;
26
+ const str = String(value).trim().toLowerCase();
27
+ if (["1", "true", "yes", "on"].includes(str)) return true;
28
+ if (["0", "false", "no", "off"].includes(str)) return false;
29
+ return defaultValue;
30
+ }
31
+
32
+ export function expandHome(value, home = os.homedir()) {
33
+ if (!value) return home;
34
+ if (value === "~") return home;
35
+ if (value.startsWith("~/") || value.startsWith("~\\")) {
36
+ return path.join(home, value.slice(2));
37
+ }
38
+ return value;
39
+ }
40
+
41
+ export function sanitizeSlug(raw) {
42
+ return String(raw || "task")
43
+ .toLowerCase()
44
+ .replace(/[^a-z0-9_.-]/g, "-")
45
+ .replace(/-+/g, "-")
46
+ .replace(/^[-_.]+|[-_.]+$/g, "")
47
+ .slice(0, 48) || "task";
48
+ }
49
+
50
+ export function isInsideDocker(env = process.env) {
51
+ return env?.KANDEV_IN_CONTAINER === "1" || fs.existsSync("/.dockerenv");
52
+ }
53
+
54
+ export const DEFAULT_CONTAINER_ENV = {
55
+ ANDROID_HOME: "/opt/android-sdk",
56
+ ANDROID_SDK_ROOT: "/opt/android-sdk",
57
+ ANDROID_ADB_SERVER_ADDRESS: "host.docker.internal",
58
+ JAVA_HOME: "/usr/lib/jvm/temurin-21-jdk-amd64",
59
+ GRADLE_OPTS: "-Dorg.gradle.vfs.watch=false",
60
+ NPM_CONFIG_CACHE: "/opt/npm-cache",
61
+ };
62
+
63
+ export const DEFAULT_CONTAINER_VOLUMES = [
64
+ "kandev-gradle-cache:/root/.gradle",
65
+ ];
66
+
67
+ function extractBasePipelineDocker(rootOrPipeline) {
68
+ let rootDir = null;
69
+ let pipelineDocker = null;
70
+ if (rootOrPipeline && typeof rootOrPipeline === "object") {
71
+ pipelineDocker = rootOrPipeline.docker || rootOrPipeline.pipeline?.docker || null;
72
+ } else if (typeof rootOrPipeline === "string") {
73
+ rootDir = rootOrPipeline;
74
+ const pipelinePath = path.join(rootOrPipeline, "config", "pipeline.json");
75
+ if (fs.existsSync(pipelinePath)) {
76
+ try {
77
+ const raw = JSON.parse(fs.readFileSync(pipelinePath, "utf8"));
78
+ pipelineDocker = raw.docker || null;
79
+ } catch {}
80
+ }
81
+ }
82
+ return { rootDir, pipelineDocker };
83
+ }
84
+
85
+ /** Load separated per-project Docker configurations declared in pipeline.docker.projects. */
86
+ export function loadProjectDockerConfigs(rootOrPipeline = process.cwd()) {
87
+ const { rootDir, pipelineDocker } = extractBasePipelineDocker(rootOrPipeline);
88
+ const rawProjects = pipelineDocker?.projects;
89
+ if (!rawProjects || typeof rawProjects !== "object" || Array.isArray(rawProjects)) {
90
+ return {};
91
+ }
92
+ const baseRoot = path.resolve(rootDir || process.cwd());
93
+ const out = {};
94
+ for (const [key, entry] of Object.entries(rawProjects)) {
95
+ if (typeof entry === "string") {
96
+ const abs = path.isAbsolute(entry) ? entry : path.resolve(baseRoot, entry);
97
+ const parsed = readJsonSafe(abs);
98
+ if (parsed && typeof parsed === "object") {
99
+ out[key] = { ...parsed, project: parsed.project || key, config_path: entry };
100
+ }
101
+ } else if (entry && typeof entry === "object") {
102
+ out[key] = { ...entry, project: entry.project || key };
103
+ }
104
+ }
105
+ return out;
106
+ }
107
+
108
+ function detectGitMainRepoRoot(worktree) {
109
+ if (!fs.existsSync(worktree)) return worktree;
110
+ const commonDirRes = spawnSync("git", ["-C", worktree, "rev-parse", "--git-common-dir"], {
111
+ encoding: "utf8",
112
+ timeout: 5000,
113
+ });
114
+ if (commonDirRes.status !== 0) return worktree;
115
+ const rawCommon = commonDirRes.stdout.trim();
116
+ if (!rawCommon) return worktree;
117
+ const commonDir = path.isAbsolute(rawCommon) ? rawCommon : path.resolve(worktree, rawCommon);
118
+ return path.dirname(commonDir);
119
+ }
120
+
121
+ function readGradleRootProjectName(worktree) {
122
+ for (const file of ["settings.gradle.kts", "settings.gradle"]) {
123
+ const full = path.join(worktree, file);
124
+ if (!fs.existsSync(full)) continue;
125
+ try {
126
+ const text = fs.readFileSync(full, "utf8");
127
+ const m = text.match(/rootProject\.name\s*=\s*["']([^"']+)["']/);
128
+ if (m) return m[1];
129
+ } catch {}
130
+ }
131
+ return null;
132
+ }
133
+
134
+ /** Match a repository worktree against the declared per-project Docker configurations. */
135
+ export function matchProjectDockerConfig(worktree, projects = {}) {
136
+ if (!worktree || !projects || typeof projects !== "object") return null;
137
+ const entries = Object.values(projects);
138
+ if (entries.length === 0) return null;
139
+
140
+ const absWorktree = path.resolve(worktree);
141
+ const mainRepoRoot = detectGitMainRepoRoot(absWorktree);
142
+ const repoNames = new Set([path.basename(absWorktree), path.basename(mainRepoRoot)].filter(Boolean));
143
+ const pkg = readJsonSafe(path.join(absWorktree, "package.json"));
144
+ const pkgName = typeof pkg?.name === "string" ? pkg.name : null;
145
+ const gradleRootName = readGradleRootProjectName(absWorktree);
146
+
147
+ for (const cfg of entries) {
148
+ const match = cfg?.match || {};
149
+ const hasIdentityCriteria = Boolean(
150
+ (Array.isArray(match.repo_names) && match.repo_names.length > 0)
151
+ || (Array.isArray(match.package_names) && match.package_names.length > 0)
152
+ || (Array.isArray(match.gradle_root_projects) && match.gradle_root_projects.length > 0),
153
+ );
154
+ const repoHit = Array.isArray(match.repo_names) && match.repo_names.some((name) => repoNames.has(name));
155
+ const pkgHit = Boolean(pkgName) && Array.isArray(match.package_names) && match.package_names.includes(pkgName);
156
+ const gradleHit = Boolean(gradleRootName)
157
+ && Array.isArray(match.gradle_root_projects)
158
+ && match.gradle_root_projects.includes(gradleRootName);
159
+ if (repoHit || pkgHit || gradleHit) {
160
+ return cfg;
161
+ }
162
+ if (!hasIdentityCriteria && Array.isArray(match.files) && match.files.length > 0) {
163
+ if (match.files.every((rel) => fs.existsSync(path.join(absWorktree, rel)))) {
164
+ return cfg;
165
+ }
166
+ }
167
+ }
168
+ return null;
169
+ }
170
+
171
+ export function resolveDockerConfig(rootOrPipeline = process.cwd(), env = process.env, overrides = {}) {
172
+ const { pipelineDocker } = extractBasePipelineDocker(rootOrPipeline);
173
+ const projects = loadProjectDockerConfigs(rootOrPipeline);
174
+ const targetCwd = overrides?.cwd || overrides?.worktree || null;
175
+ const projectConfig = overrides?.project && projects[overrides.project]
176
+ ? projects[overrides.project]
177
+ : (targetCwd ? matchProjectDockerConfig(targetCwd, projects) : null);
178
+
179
+ let enabled = DEFAULT_DOCKER_CONFIG.enabled;
180
+ if (typeof overrides?.docker === "boolean") {
181
+ enabled = overrides.docker;
182
+ } else if (env?.KANDEV_DOCKER_ENABLED !== undefined) {
183
+ enabled = parseBoolean(env.KANDEV_DOCKER_ENABLED, DEFAULT_DOCKER_CONFIG.enabled);
184
+ } else if (typeof pipelineDocker?.enabled === "boolean") {
185
+ enabled = pipelineDocker.enabled;
186
+ }
187
+
188
+ let provision_dependencies = DEFAULT_DOCKER_CONFIG.provision_dependencies;
189
+ if (typeof overrides?.provision_dependencies === "boolean") {
190
+ provision_dependencies = overrides.provision_dependencies;
191
+ } else if (env?.KANDEV_DOCKER_PROVISION_DEPS !== undefined) {
192
+ provision_dependencies = parseBoolean(env.KANDEV_DOCKER_PROVISION_DEPS, DEFAULT_DOCKER_CONFIG.provision_dependencies);
193
+ } else if (typeof pipelineDocker?.provision_dependencies === "boolean") {
194
+ provision_dependencies = pipelineDocker.provision_dependencies;
195
+ }
196
+
197
+ const baseImage = pipelineDocker?.image || DEFAULT_DOCKER_CONFIG.image;
198
+ const baseDockerfile = pipelineDocker?.dockerfile || DEFAULT_DOCKER_CONFIG.dockerfile;
199
+ const basePlatform = pipelineDocker?.platform ?? DEFAULT_DOCKER_CONFIG.platform;
200
+ const basePrefix = pipelineDocker?.container_prefix || DEFAULT_DOCKER_CONFIG.container_prefix;
201
+
202
+ // agent-tools env carries the generic pipeline.docker.image/platform defaults; let a matched
203
+ // project's dedicated image/platform take precedence unless env specifies a distinct custom value.
204
+ const envImage = env?.KANDEV_DOCKER_IMAGE && (!projectConfig || env.KANDEV_DOCKER_IMAGE !== baseImage)
205
+ ? env.KANDEV_DOCKER_IMAGE
206
+ : null;
207
+ const envPlatform = env?.KANDEV_DOCKER_PLATFORM && (!projectConfig || env.KANDEV_DOCKER_PLATFORM !== basePlatform)
208
+ ? env.KANDEV_DOCKER_PLATFORM
209
+ : null;
210
+
211
+ const image = overrides?.image || envImage || projectConfig?.image || baseImage;
212
+ const dockerfile = overrides?.dockerfile || env?.KANDEV_DOCKERFILE || projectConfig?.dockerfile || baseDockerfile;
213
+ const platform = overrides?.platform !== undefined
214
+ ? overrides.platform
215
+ : (envPlatform ?? projectConfig?.platform ?? basePlatform);
216
+ const container_prefix = overrides?.container_prefix || env?.KANDEV_DOCKER_CONTAINER_PREFIX || projectConfig?.container_prefix || basePrefix;
217
+ const worktree_root = overrides?.worktree_root || env?.KANDEV_DOCKER_WORKTREE_ROOT || pipelineDocker?.worktree_root || DEFAULT_DOCKER_CONFIG.worktree_root;
218
+
219
+ return {
220
+ enabled,
221
+ image,
222
+ dockerfile,
223
+ platform,
224
+ container_prefix,
225
+ worktree_root,
226
+ provision_dependencies,
227
+ project: projectConfig?.project || null,
228
+ projectConfig: projectConfig || null,
229
+ env: projectConfig?.env ? { ...projectConfig.env } : { ...DEFAULT_CONTAINER_ENV },
230
+ volumes: Array.isArray(projectConfig?.volumes) ? [...projectConfig.volumes] : [...DEFAULT_CONTAINER_VOLUMES],
231
+ projects,
232
+ };
233
+ }
234
+
235
+ export async function ensureDockerDaemon({ timeoutMs = 30000, env = process.env, log = () => {} } = {}) {
236
+ if (env.KANDEV_DOCKER_SKIP_DAEMON === "1") {
237
+ log("KANDEV_DOCKER_SKIP_DAEMON is set; skipping Docker daemon check");
238
+ return false;
239
+ }
240
+ const check = () => {
241
+ const res = spawnSync("docker", ["info"], { encoding: "utf8", timeout: 10000 });
242
+ return res.status === 0;
243
+ };
244
+ if (check()) return true;
245
+
246
+ if (process.platform === "darwin") {
247
+ log("Docker daemon not running; attempting to launch Docker Desktop via open -a Docker...");
248
+ spawnSync("open", ["-a", "Docker"], { encoding: "utf8", timeout: 5000 });
249
+ const started = Date.now();
250
+ while (Date.now() - started < timeoutMs) {
251
+ await new Promise((resolve) => setTimeout(resolve, 1000));
252
+ if (check()) {
253
+ log("Docker Desktop is ready");
254
+ return true;
255
+ }
256
+ }
257
+ }
258
+
259
+ throw new Error("Docker daemon is not running and could not be started");
260
+ }
261
+
262
+ export function ensureDockerImage({ image, dockerfile, platform, root, env = process.env, log = () => {} }) {
263
+ if (env.KANDEV_DOCKER_SKIP_BUILD === "1") return { built: false, skipped: true };
264
+ const inspect = spawnSync("docker", ["image", "inspect", image], { encoding: "utf8", timeout: 10000 });
265
+ if (inspect.status === 0) return { built: false, exists: true };
266
+
267
+ if (!dockerfile) {
268
+ throw new Error(`Docker image "${image}" is missing and no dockerfile is configured`);
269
+ }
270
+ const resolvedRoot = path.resolve(env.KANDEV_WORKFLOW_ROOT || root || process.cwd());
271
+ const dockerfilePath = path.isAbsolute(dockerfile) ? dockerfile : path.resolve(resolvedRoot, dockerfile);
272
+ if (!fs.existsSync(dockerfilePath)) {
273
+ throw new Error(`Docker image "${image}" is missing and Dockerfile not found: ${dockerfilePath}`);
274
+ }
275
+ const contextDir = path.dirname(dockerfilePath);
276
+ const buildArgs = ["build"];
277
+ if (platform) buildArgs.push("--platform", platform);
278
+ buildArgs.push("-t", image, "-f", dockerfilePath, contextDir);
279
+ log(`Building Docker runtime image ${image} from ${dockerfilePath}...`);
280
+ const buildRes = spawnSync("docker", buildArgs, {
281
+ encoding: "utf8",
282
+ timeout: 900_000,
283
+ maxBuffer: 32 * 1024 * 1024,
284
+ });
285
+ if (buildRes.status !== 0) {
286
+ throw new Error(`Failed to build Docker image ${image}: ${buildRes.stderr || buildRes.stdout}`);
287
+ }
288
+ return { built: true, exists: true };
289
+ }
290
+
291
+ export function inspectContainer(containerName) {
292
+ const res = spawnSync("docker", ["inspect", containerName], { encoding: "utf8", timeout: 10000 });
293
+ if (res.status !== 0) return { exists: false, running: false, id: null, image: null, mounts: [], mountDestinations: [], cmd: [] };
294
+ try {
295
+ const data = JSON.parse(res.stdout);
296
+ const item = Array.isArray(data) ? data[0] : data;
297
+ const mounts = (item?.Mounts || []).map((m) => m.Source || m.Destination).filter(Boolean);
298
+ const mountDestinations = (item?.Mounts || []).map((m) => m.Destination).filter(Boolean);
299
+ return {
300
+ exists: true,
301
+ running: Boolean(item?.State?.Running),
302
+ id: item?.Id || null,
303
+ image: item?.Config?.Image || null,
304
+ mounts,
305
+ mountDestinations,
306
+ cmd: Array.isArray(item?.Config?.Cmd) ? item.Config.Cmd : [],
307
+ };
308
+ } catch {
309
+ return { exists: false, running: false, id: null, image: null, mounts: [], mountDestinations: [], cmd: [] };
310
+ }
311
+ }
312
+
313
+ export function execInContainer(containerName, argv, { cwd = null, env = {}, input = undefined, timeout = 120_000 } = {}) {
314
+ const args = ["exec"];
315
+ if (input !== undefined) args.push("-i");
316
+ if (cwd) {
317
+ args.push("-w", cwd);
318
+ }
319
+ for (const [k, v] of Object.entries(env)) {
320
+ if (v !== undefined && v !== null) args.push("-e", `${k}=${v}`);
321
+ }
322
+ args.push(containerName, ...argv);
323
+ const res = spawnSync("docker", args, {
324
+ encoding: "utf8",
325
+ input,
326
+ timeout,
327
+ maxBuffer: 32 * 1024 * 1024,
328
+ });
329
+ return {
330
+ command: `docker ${args.join(" ")}`,
331
+ exit_code: Number.isInteger(res.status) ? res.status : 1,
332
+ stdout: String(res.stdout || "").trim(),
333
+ stderr: String(res.stderr || "").trim(),
334
+ };
335
+ }
336
+
337
+ export function stopTaskDockerWorkspace({ containerName, remove = false }) {
338
+ if (!containerName) return;
339
+ if (remove) {
340
+ spawnSync("docker", ["rm", "-f", containerName], { encoding: "utf8", timeout: 15000 });
341
+ } else {
342
+ spawnSync("docker", ["stop", containerName], { encoding: "utf8", timeout: 15000 });
343
+ }
344
+ }
345
+
346
+ function normalizeMountPath(p) {
347
+ if (!p) return null;
348
+ const abs = path.resolve(p);
349
+ if (abs === "/tmp" || abs === "/private/tmp") return null;
350
+ return abs;
351
+ }
352
+
353
+ /** Detect loopback ports referenced in host Codex config (e.g. 10100) for TCP forwarding inside Docker. */
354
+ export function detectLoopbackProxyPorts(rawToml = "") {
355
+ const ports = new Set();
356
+ for (const match of String(rawToml).matchAll(/(?:https?|wss?):\/\/(?:127\.0\.0\.1|localhost):(\d+)/g)) {
357
+ const port = Number(match[1]);
358
+ if (Number.isInteger(port) && port > 0 && port < 65536) ports.add(port);
359
+ }
360
+ if (ports.size === 0) ports.add(10100);
361
+ return [...ports];
362
+ }
363
+
364
+ export function buildContainerEntrypointScript(ports = [10100]) {
365
+ const list = JSON.stringify(ports.length ? ports : [10100]);
366
+ return `const net=require("net");for(const p of ${list}){net.createServer(c=>{const u=net.connect(p,"host.docker.internal");c.pipe(u);u.pipe(c);c.on("error",()=>u.destroy());u.on("error",()=>c.destroy());}).listen(p,"127.0.0.1");}setInterval(()=>{},1<<30);`;
367
+ }
368
+
369
+ /** Rewrite host Codex config for Linux container usage (loopback proxy forwarder, no macOS paths). */
370
+ export function buildContainerCodexConfig(rawToml, { hasCatalog = true } = {}) {
371
+ const lines = String(rawToml || "").split("\n");
372
+ const out = [];
373
+ let skipSection = false;
374
+ for (const line of lines) {
375
+ const trimmed = line.trim();
376
+ if (/^\[/.test(trimmed)) {
377
+ skipSection = /^\[(marketplaces|plugins|desktop)/.test(trimmed);
378
+ if (!skipSection) out.push(line);
379
+ continue;
380
+ }
381
+ if (skipSection) continue;
382
+ if (/^notify\s*=/.test(trimmed)) continue;
383
+ if (/^model_catalog_json\s*=/.test(trimmed)) {
384
+ if (hasCatalog) out.push('model_catalog_json = "/root/.codex/opencodex-catalog.json"');
385
+ continue;
386
+ }
387
+ if (/^sandbox_mode\s*=/.test(trimmed)) {
388
+ out.push('sandbox_mode = "danger-full-access"');
389
+ continue;
390
+ }
391
+ const rewritten = line.replace(/(https?:\/\/|wss?:\/\/)localhost(?=[:/]|$)/g, "$1127.0.0.1");
392
+ out.push(rewritten);
393
+ }
394
+ return out.join("\n").trimEnd() + "\n";
395
+ }
396
+
397
+ export function normalizeContainerCodexCatalog(rawCatalog) {
398
+ try {
399
+ const parsed = JSON.parse(rawCatalog);
400
+ if (!parsed || !Array.isArray(parsed.models)) return rawCatalog;
401
+ const xhighLevel = { effort: "xhigh", description: "Extra high reasoning depth for complex problems" };
402
+ const mediumLevel = { effort: "medium", description: "Balances speed and reasoning depth for everyday tasks" };
403
+ const order = ["low", "medium", "high", "xhigh", "max", "ultra"];
404
+ const targetSlugs = new Set([
405
+ "combo/deepseek-v4.1-flash-auto",
406
+ "opencode-go/deepseek-v4.1-flash",
407
+ "deepseek/deepseek-flash",
408
+ "deepseek/deepseek-v4-flash",
409
+ ]);
410
+ for (const model of parsed.models) {
411
+ if (!targetSlugs.has(model?.slug)) continue;
412
+ const levels = Array.isArray(model.supported_reasoning_levels) ? [...model.supported_reasoning_levels] : [];
413
+ if (!levels.some((lvl) => lvl?.effort === "medium")) levels.push(mediumLevel);
414
+ if (!levels.some((lvl) => lvl?.effort === "xhigh")) levels.push(xhighLevel);
415
+ levels.sort((a, b) => order.indexOf(a?.effort) - order.indexOf(b?.effort));
416
+ model.supported_reasoning_levels = levels;
417
+ if (model.slug === "combo/deepseek-v4.1-flash-auto") {
418
+ model.default_reasoning_level = "xhigh";
419
+ }
420
+ }
421
+ return JSON.stringify(parsed, null, 2) + "\n";
422
+ } catch {
423
+ return rawCatalog;
424
+ }
425
+ }
426
+
427
+ function prepareContainerCodexConfig({ containerName, homeDir = os.homedir(), log = () => {} }) {
428
+ const hostCodexDir = path.join(homeDir, ".codex");
429
+ const authPath = path.join(hostCodexDir, "auth.json");
430
+ const cfgPath = path.join(hostCodexDir, "config.toml");
431
+ const catalogPath = path.join(hostCodexDir, "opencodex-catalog.json");
432
+
433
+ const hostGeminiDir = path.join(homeDir, ".gemini");
434
+ const geminiSettingsPath = path.join(hostGeminiDir, "settings.json");
435
+ const geminiEnvPath = path.join(hostGeminiDir, ".env");
436
+ const geminiOauthPath = path.join(hostGeminiDir, "oauth_creds.json");
437
+
438
+ const hasCatalog = fs.existsSync(catalogPath);
439
+ const payload = {
440
+ auth: fs.existsSync(authPath) ? fs.readFileSync(authPath, "utf8") : null,
441
+ catalog: hasCatalog ? normalizeContainerCodexCatalog(fs.readFileSync(catalogPath, "utf8")) : null,
442
+ cfg: fs.existsSync(cfgPath) ? buildContainerCodexConfig(fs.readFileSync(cfgPath, "utf8"), { hasCatalog }) : null,
443
+ geminiSettings: fs.existsSync(geminiSettingsPath) ? fs.readFileSync(geminiSettingsPath, "utf8") : null,
444
+ geminiEnv: fs.existsSync(geminiEnvPath) ? fs.readFileSync(geminiEnvPath, "utf8") : null,
445
+ geminiOauth: fs.existsSync(geminiOauthPath) ? fs.readFileSync(geminiOauthPath, "utf8") : null,
446
+ };
447
+
448
+ const nodeScript = [
449
+ 'const fs = require("node:fs");',
450
+ 'const cp = require("node:child_process");',
451
+ 'const data = JSON.parse(fs.readFileSync(0, "utf8"));',
452
+ 'fs.mkdirSync("/root/.codex", { recursive: true });',
453
+ 'if (data.auth !== null) { fs.writeFileSync("/root/.codex/auth.json", data.auth); fs.chmodSync("/root/.codex/auth.json", 0o600); }',
454
+ 'if (data.catalog !== null) { fs.writeFileSync("/root/.codex/opencodex-catalog.json", data.catalog); }',
455
+ 'if (data.cfg !== null) { fs.writeFileSync("/root/.codex/config.toml", data.cfg); fs.chmodSync("/root/.codex/config.toml", 0o600); }',
456
+ 'if (data.geminiSettings !== null || data.geminiEnv !== null || data.geminiOauth !== null) {',
457
+ ' fs.mkdirSync("/root/.gemini", { recursive: true });',
458
+ ' if (data.geminiSettings !== null) { fs.writeFileSync("/root/.gemini/settings.json", data.geminiSettings); }',
459
+ ' if (data.geminiEnv !== null) { fs.writeFileSync("/root/.gemini/.env", data.geminiEnv); fs.chmodSync("/root/.gemini/.env", 0o600); }',
460
+ ' if (data.geminiOauth !== null) { fs.writeFileSync("/root/.gemini/oauth_creds.json", data.geminiOauth); fs.chmodSync("/root/.gemini/oauth_creds.json", 0o600); }',
461
+ '}',
462
+ 'cp.execFileSync("git", ["config", "--global", "--add", "safe.directory", "*"], { stdio: "ignore" });',
463
+ ].join(" ");
464
+
465
+ const res = execInContainer(containerName, ["node", "-e", nodeScript], {
466
+ input: JSON.stringify(payload),
467
+ });
468
+ if (res.exit_code !== 0) {
469
+ log(`failed to prepare /root/.codex inside container: ${res.stderr}`);
470
+ }
471
+ }
472
+
473
+ /** Detect Node, Bun, and Android project dependencies from repository manifests and project config. */
474
+ export function detectProjectDependencies(worktree, projectConfig = null) {
475
+ const root = path.resolve(worktree);
476
+ const deps = {
477
+ project: projectConfig?.project || null,
478
+ node: null,
479
+ bun: null,
480
+ android: null,
481
+ };
482
+
483
+ const pkgPath = path.join(root, "package.json");
484
+ let pkg = null;
485
+ if (fs.existsSync(pkgPath)) {
486
+ try {
487
+ pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
488
+ const hasDeclared = Boolean(
489
+ (pkg.dependencies && Object.keys(pkg.dependencies).length > 0)
490
+ || (pkg.devDependencies && Object.keys(pkg.devDependencies).length > 0),
491
+ );
492
+ deps.node = {
493
+ package_json: true,
494
+ has_lockfile: fs.existsSync(path.join(root, "package-lock.json")),
495
+ has_node_modules: fs.existsSync(path.join(root, "node_modules")),
496
+ has_dependencies: hasDeclared,
497
+ };
498
+ } catch {}
499
+ }
500
+
501
+ const hasBunLock = fs.existsSync(path.join(root, "bun.lock")) || fs.existsSync(path.join(root, "bun.lockb"));
502
+ const hasBunfig = fs.existsSync(path.join(root, "bunfig.toml"));
503
+ const pmIsBun = typeof pkg?.packageManager === "string" && pkg.packageManager.startsWith("bun@");
504
+ if (hasBunLock || hasBunfig || pmIsBun || projectConfig?.dependencies?.bun) {
505
+ deps.bun = {
506
+ detected: true,
507
+ has_lockfile: hasBunLock,
508
+ has_bunfig: hasBunfig,
509
+ has_node_modules: fs.existsSync(path.join(root, "node_modules")),
510
+ version: projectConfig?.dependencies?.bun?.version || null,
511
+ };
512
+ }
513
+
514
+ const gradlewPath = path.join(root, "gradlew");
515
+ if (fs.existsSync(gradlewPath)) {
516
+ const cfgAndroid = projectConfig?.dependencies?.android_sdk || null;
517
+ let compileSdk = cfgAndroid?.compile_sdk ? String(cfgAndroid.compile_sdk) : null;
518
+ let targetSdk = cfgAndroid?.target_sdk ? String(cfgAndroid.target_sdk) : null;
519
+ let buildToolsVersion = Array.isArray(cfgAndroid?.build_tools) && cfgAndroid.build_tools.length > 0
520
+ ? String(cfgAndroid.build_tools[0])
521
+ : "35.0.0";
522
+ for (const candidate of ["app/build.gradle.kts", "app/build.gradle", "build.gradle.kts", "build.gradle"]) {
523
+ const full = path.join(root, candidate);
524
+ if (!fs.existsSync(full)) continue;
525
+ const text = fs.readFileSync(full, "utf8");
526
+ const compileMatch = text.match(/\bcompileSdk\s*(?:=|\s)\s*(\d+)/);
527
+ if (compileMatch && !compileSdk) compileSdk = compileMatch[1];
528
+ const targetMatch = text.match(/\btargetSdk\s*(?:=|\s)\s*(\d+)/);
529
+ if (targetMatch && !targetSdk) targetSdk = targetMatch[1];
530
+ const btMatch = text.match(/\bbuildToolsVersion\s*(?:=|\s)\s*["']([^"']+)["']/);
531
+ if (btMatch) buildToolsVersion = btMatch[1];
532
+ }
533
+ const resolvedCompileSdk = compileSdk || "35";
534
+ const resolvedBuildTools = Array.isArray(cfgAndroid?.build_tools) && cfgAndroid.build_tools.length > 0
535
+ ? [...new Set([...cfgAndroid.build_tools, buildToolsVersion])]
536
+ : [buildToolsVersion];
537
+ const sdkPackages = [...new Set([
538
+ ...(Array.isArray(cfgAndroid?.packages) ? cfgAndroid.packages : []),
539
+ "platform-tools",
540
+ `platforms;android-${resolvedCompileSdk}`,
541
+ ...resolvedBuildTools.map((bt) => `build-tools;${bt}`),
542
+ ])];
543
+ deps.android = {
544
+ gradlew: true,
545
+ compile_sdk: resolvedCompileSdk,
546
+ target_sdk: targetSdk || resolvedCompileSdk,
547
+ build_tools: buildToolsVersion,
548
+ sdk_packages: sdkPackages,
549
+ };
550
+ }
551
+
552
+ return deps;
553
+ }
554
+
555
+ function dependencySignature(containerName, worktree, deps, projectConfig = null) {
556
+ const parts = [containerName, worktree, projectConfig?.project || "", JSON.stringify(deps)];
557
+ for (const rel of [
558
+ "package.json",
559
+ "package-lock.json",
560
+ "bun.lock",
561
+ "bun.lockb",
562
+ "bunfig.toml",
563
+ "gradle/wrapper/gradle-wrapper.properties",
564
+ "settings.gradle.kts",
565
+ "app/build.gradle.kts",
566
+ "app/build.gradle",
567
+ "build.gradle.kts",
568
+ "build.gradle",
569
+ ]) {
570
+ const file = path.join(worktree, rel);
571
+ if (fs.existsSync(file)) {
572
+ parts.push(crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"));
573
+ }
574
+ }
575
+ return crypto.createHash("sha256").update(parts.join("|")).digest("hex");
576
+ }
577
+
578
+ function readJsonSafe(file) {
579
+ try {
580
+ return JSON.parse(fs.readFileSync(file, "utf8"));
581
+ } catch {
582
+ return null;
583
+ }
584
+ }
585
+
586
+ export function provisionContainerDependencies({
587
+ containerName,
588
+ worktree,
589
+ projectConfig = null,
590
+ log = () => {},
591
+ env = process.env,
592
+ inContainer = false,
593
+ }) {
594
+ if (env.KANDEV_DOCKER_SKIP_PROVISION === "1") {
595
+ return { skipped: true, actions: [] };
596
+ }
597
+ const deps = detectProjectDependencies(worktree, projectConfig);
598
+ const sig = dependencySignature(containerName, worktree, deps, projectConfig);
599
+ const markerPath = path.join(worktree, ".agentic", ".docker-provisioned.json");
600
+ const existing = readJsonSafe(markerPath);
601
+ if (existing && existing.signature === sig && existing.ok === true) {
602
+ return {
603
+ skipped: false,
604
+ cached: true,
605
+ project: projectConfig?.project || null,
606
+ detected: deps,
607
+ actions: existing.actions || [],
608
+ };
609
+ }
610
+
611
+ const stepEnv = { ...(projectConfig?.env || {}) };
612
+ const runStep = (argv, opts = {}) => {
613
+ if (inContainer) {
614
+ const mergedEnv = { ...process.env, ...env, ...stepEnv, ...(opts.env || {}) };
615
+ const res = spawnSync(argv[0], argv.slice(1), {
616
+ cwd: opts.cwd || worktree,
617
+ env: mergedEnv,
618
+ encoding: "utf8",
619
+ timeout: opts.timeout || 120_000,
620
+ maxBuffer: 32 * 1024 * 1024,
621
+ });
622
+ return {
623
+ command: argv.join(" "),
624
+ exit_code: Number.isInteger(res.status) ? res.status : 1,
625
+ stdout: String(res.stdout || "").trim(),
626
+ stderr: String(res.stderr || "").trim(),
627
+ };
628
+ }
629
+ return execInContainer(containerName, argv, {
630
+ ...opts,
631
+ env: { ...stepEnv, ...(opts.env || {}) },
632
+ });
633
+ };
634
+
635
+ const actions = [];
636
+
637
+ // 0. Verify pre-installed CLI tools declared in per-project Docker config
638
+ const cliTools = projectConfig?.dependencies?.cli_tools || [];
639
+ if (cliTools.length > 0) {
640
+ const verifiedTools = [];
641
+ for (const tool of cliTools) {
642
+ const res = runStep(tool.verify, { cwd: worktree, timeout: 30_000 });
643
+ verifiedTools.push({ name: tool.name, command: res.command, exit_code: res.exit_code });
644
+ if (res.exit_code !== 0) {
645
+ throw new Error(`Required container CLI tool "${tool.name}" failed (${res.command}): ${res.stderr || res.stdout}`);
646
+ }
647
+ }
648
+ actions.push({ type: "cli-tools", tools: verifiedTools.map((t) => t.name), exit_code: 0 });
649
+ }
650
+
651
+ // 1. Bun (when declared by project config) or Node dependencies (install inside container if missing)
652
+ if (projectConfig?.dependencies?.bun && deps.node?.has_dependencies && !deps.node.has_node_modules) {
653
+ const commands = Array.isArray(projectConfig?.dependencies?.bun?.provision_commands) && projectConfig.dependencies.bun.provision_commands.length > 0
654
+ ? projectConfig.dependencies.bun.provision_commands
655
+ : [deps.bun.has_lockfile ? ["bun", "install", "--frozen-lockfile"] : ["bun", "install"]];
656
+ for (const bunCmd of commands) {
657
+ log(`Provisioning Bun dependencies inside ${containerName}: ${bunCmd.join(" ")}`);
658
+ const res = runStep(bunCmd, { cwd: worktree, timeout: 300_000 });
659
+ actions.push({ type: "bun", command: res.command, exit_code: res.exit_code });
660
+ if (res.exit_code !== 0) {
661
+ throw new Error(`Bun dependency install failed in container: ${res.stderr || res.stdout}`);
662
+ }
663
+ }
664
+ } else if (deps.node?.has_dependencies && !deps.node.has_node_modules) {
665
+ const npmCmd = deps.node.has_lockfile ? ["npm", "ci", "--no-audit", "--no-fund"] : ["npm", "install", "--no-package-lock", "--no-audit", "--no-fund"];
666
+ log(`Provisioning Node dependencies inside ${containerName}: ${npmCmd.join(" ")}`);
667
+ const res = runStep(npmCmd, { cwd: worktree, timeout: 300_000 });
668
+ actions.push({ type: "node", command: res.command, exit_code: res.exit_code });
669
+ if (res.exit_code !== 0) {
670
+ throw new Error(`Node dependency install failed in container: ${res.stderr || res.stdout}`);
671
+ }
672
+ }
673
+
674
+ // 2. Android SDK + Gradle dependencies + Stage 5 Android agent runtime (install inside container)
675
+ if (deps.android?.gradlew) {
676
+ const workflowRoot = path.resolve(env.KANDEV_WORKFLOW_ROOT || process.cwd());
677
+ const localAndroidPkg = path.join(workflowRoot, "agents", "android-testing-superpowers");
678
+ const localAndroidPkgJson = readJsonSafe(path.join(localAndroidPkg, "package.json"));
679
+ if (localAndroidPkgJson?.name && localAndroidPkgJson?.version) {
680
+ const targetSpec = `${localAndroidPkgJson.name}@${localAndroidPkgJson.version}`;
681
+ const checkPkg = runStep(
682
+ ["bash", "-lc", `npm list --prefix /usr/local -g --depth=0 ${targetSpec} >/dev/null 2>&1`],
683
+ );
684
+ if (checkPkg.exit_code !== 0) {
685
+ log(`Provisioning ${targetSpec} runtime inside ${containerName}...`);
686
+ const packInstall = runStep(
687
+ [
688
+ "bash",
689
+ "-lc",
690
+ `TAR=$(npm --prefix "${localAndroidPkg}" pack "${localAndroidPkg}" --pack-destination /tmp --quiet) && npm install --prefix /usr/local -g "/tmp/$TAR" >/dev/null && rm -f "/tmp/$TAR" && /usr/local/bin/android-cli-superpowers --help >/dev/null`,
691
+ ],
692
+ { timeout: 300_000 },
693
+ );
694
+ actions.push({ type: "android-agent", package: targetSpec, exit_code: packInstall.exit_code });
695
+ if (packInstall.exit_code !== 0) {
696
+ throw new Error(`Failed to provision ${targetSpec} inside container: ${packInstall.stderr || packInstall.stdout}`);
697
+ }
698
+ }
699
+ }
700
+
701
+ const sdkPackages = deps.android.sdk_packages || [
702
+ `platforms;android-${deps.android.compile_sdk}`,
703
+ `build-tools;${deps.android.build_tools}`,
704
+ ];
705
+ const requireSdk = Boolean(projectConfig?.dependencies?.android_sdk);
706
+ const missingFail = requireSdk
707
+ ? `echo "sdkmanager missing at /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager" >&2; exit 1`
708
+ : `exit 0`;
709
+ const checkScript = `if [ -x /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager ]; then missing=""; for pkg in ${sdkPackages.map((p) => `"${p}"`).join(" ")}; do dir="/opt/android-sdk/$(echo "$pkg" | tr ';' '/')"; if [ ! -d "$dir" ]; then missing="$missing $pkg"; fi; done; if [ -n "$missing" ]; then yes | /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager $missing >/dev/null; fi; else ${missingFail}; fi`;
710
+ log(`Ensuring Android SDK packages (${sdkPackages.join(", ")}) inside ${containerName}...`);
711
+ const sdkRes = runStep(["bash", "-lc", checkScript], { cwd: worktree, timeout: 600_000 });
712
+ actions.push({ type: "android-sdk", packages: sdkPackages, exit_code: sdkRes.exit_code });
713
+ if (sdkRes.exit_code !== 0) {
714
+ throw new Error(`Android SDK provisioning failed in container: ${sdkRes.stderr || sdkRes.stdout}`);
715
+ }
716
+
717
+ const gradleCmds = Array.isArray(projectConfig?.dependencies?.gradle?.provision_commands) && projectConfig.dependencies.gradle.provision_commands.length > 0
718
+ ? projectConfig.dependencies.gradle.provision_commands
719
+ : [["./gradlew", "--version"]];
720
+ for (const gCmd of gradleCmds) {
721
+ log(`Resolving Gradle wrapper inside ${containerName}: ${gCmd.join(" ")}`);
722
+ const gradleRes = runStep(
723
+ ["bash", "-lc", `sh ${gCmd.map((a) => `"${a}"`).join(" ")} >/dev/null`],
724
+ {
725
+ cwd: worktree,
726
+ env: {
727
+ ANDROID_HOME: "/opt/android-sdk",
728
+ ANDROID_SDK_ROOT: "/opt/android-sdk",
729
+ JAVA_HOME: "/usr/lib/jvm/temurin-21-jdk-amd64",
730
+ GRADLE_OPTS: "-Dorg.gradle.vfs.watch=false",
731
+ ...stepEnv,
732
+ },
733
+ timeout: 300_000,
734
+ },
735
+ );
736
+ actions.push({ type: "gradle-wrapper", command: gCmd.join(" "), exit_code: gradleRes.exit_code });
737
+ if (gradleRes.exit_code !== 0) {
738
+ throw new Error(`Gradle wrapper resolution failed in container: ${gradleRes.stderr || gradleRes.stdout}`);
739
+ }
740
+ }
741
+ }
742
+
743
+ const record = {
744
+ ok: true,
745
+ project: projectConfig?.project || null,
746
+ signature: sig,
747
+ container_name: containerName,
748
+ timestamp: new Date().toISOString(),
749
+ detected: deps,
750
+ actions,
751
+ };
752
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
753
+ fs.writeFileSync(markerPath, `${JSON.stringify(record, null, 2)}\n`);
754
+ return record;
755
+ }
756
+
757
+ function normalizeArtifactOwnership(worktree, containerName) {
758
+ if (!process.getuid || !process.getgid) return;
759
+ const uid = process.getuid();
760
+ const gid = process.getgid();
761
+ const agenticDir = path.join(worktree, ".agentic");
762
+ if (!fs.existsSync(agenticDir)) return;
763
+ try {
764
+ if (fs.statSync(agenticDir).uid !== uid) {
765
+ execInContainer(containerName, ["chown", "-R", `${uid}:${gid}`, agenticDir]);
766
+ }
767
+ } catch {}
768
+ }
769
+
770
+ export async function ensureTaskDockerWorkspace({
771
+ cwd,
772
+ task = "agent gateway",
773
+ root = process.cwd(),
774
+ env = process.env,
775
+ overrides = {},
776
+ deferProvisioning = false,
777
+ log = () => {},
778
+ } = {}) {
779
+ const worktree = path.resolve(cwd || process.cwd());
780
+ const dockerConfig = resolveDockerConfig(root, env, { ...overrides, cwd: worktree });
781
+
782
+ const writeDockerArtifact = (targetDir, artifact) => {
783
+ const dir = path.join(targetDir, ".agentic");
784
+ fs.mkdirSync(dir, { recursive: true });
785
+ fs.writeFileSync(path.join(dir, "docker.json"), `${JSON.stringify(artifact, null, 2)}\n`);
786
+ };
787
+
788
+ if (!dockerConfig.enabled) {
789
+ const disabledArtifact = {
790
+ enabled: false,
791
+ timestamp: new Date().toISOString(),
792
+ worktree_path: worktree,
793
+ };
794
+ writeDockerArtifact(worktree, disabledArtifact);
795
+ return disabledArtifact;
796
+ }
797
+
798
+ // Inside-container execution path (e.g. Stage 1 gateway running inside container via agent-tools)
799
+ if (isInsideDocker(env)) {
800
+ const existingArtifact = readJsonSafe(path.join(worktree, ".agentic", "docker.json")) || {};
801
+ const commands = [];
802
+ const runLocal = (argv, execCwd = null) => {
803
+ const res = spawnSync(argv[0], argv.slice(1), {
804
+ cwd: execCwd || worktree,
805
+ encoding: "utf8",
806
+ timeout: 60_000,
807
+ });
808
+ const rec = {
809
+ command: argv.join(" "),
810
+ exit_code: Number.isInteger(res.status) ? res.status : 1,
811
+ stdout: String(res.stdout || "").trim(),
812
+ stderr: String(res.stderr || "").trim(),
813
+ };
814
+ commands.push(rec);
815
+ return rec;
816
+ };
817
+
818
+ runLocal(["git", "config", "--global", "--add", "safe.directory", "*"]);
819
+ const commonDirRes = spawnSync("git", ["-C", worktree, "rev-parse", "--git-common-dir"], { encoding: "utf8" });
820
+ let mainRepoRoot = worktree;
821
+ if (commonDirRes.status === 0) {
822
+ const rawCommon = commonDirRes.stdout.trim();
823
+ const commonDir = path.isAbsolute(rawCommon) ? rawCommon : path.resolve(worktree, rawCommon);
824
+ mainRepoRoot = path.dirname(commonDir);
825
+ }
826
+ const commitCheck = spawnSync("git", ["-C", worktree, "rev-parse", "--verify", "HEAD"], { encoding: "utf8" });
827
+ const hasCommits = commitCheck.status === 0;
828
+ const branchCheck = spawnSync("git", ["-C", worktree, "rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8" });
829
+ const currentBranch = branchCheck.status === 0 ? branchCheck.stdout.trim() : "main";
830
+ const verifyRes = runLocal(["git", "-C", worktree, "rev-parse", "--is-inside-work-tree"]);
831
+ runLocal(["git", "-C", worktree, "status", "--porcelain"]);
832
+ runLocal(["git", "-C", mainRepoRoot, "worktree", "list", "--porcelain"]);
833
+
834
+ const containerName = env.KANDEV_CONTAINER_NAME || existingArtifact.container_name || os.hostname();
835
+ const containerId = existingArtifact.container_id || os.hostname();
836
+
837
+ let provisionedDependencies = existingArtifact.provisioned_dependencies || { skipped: true, actions: [] };
838
+ if (!deferProvisioning && dockerConfig.provision_dependencies && hasCommits) {
839
+ provisionedDependencies = provisionContainerDependencies({
840
+ containerName,
841
+ worktree,
842
+ projectConfig: dockerConfig.projectConfig,
843
+ log,
844
+ env,
845
+ inContainer: true,
846
+ });
847
+ }
848
+
849
+ const artifact = {
850
+ ...existingArtifact,
851
+ enabled: true,
852
+ project: dockerConfig.project || existingArtifact.project || null,
853
+ execution_mode: "container",
854
+ container_id: containerId,
855
+ container_name: containerName,
856
+ image: existingArtifact.image || dockerConfig.image,
857
+ platform: existingArtifact.platform || dockerConfig.platform,
858
+ worktree_path: worktree,
859
+ main_repo_path: mainRepoRoot,
860
+ branch: currentBranch,
861
+ verified_in_container: verifyRes.exit_code === 0 && verifyRes.stdout.includes("true"),
862
+ provisioned_dependencies: provisionedDependencies,
863
+ commands,
864
+ };
865
+ writeDockerArtifact(worktree, artifact);
866
+ return artifact;
867
+ }
868
+
869
+ const daemonReady = await ensureDockerDaemon({ env, log });
870
+ if (!daemonReady) {
871
+ const skippedArtifact = {
872
+ enabled: true,
873
+ skipped: true,
874
+ reason: "Docker daemon skipped via KANDEV_DOCKER_SKIP_DAEMON",
875
+ worktree_path: worktree,
876
+ verified_in_container: false,
877
+ commands: [],
878
+ };
879
+ writeDockerArtifact(worktree, skippedArtifact);
880
+ return skippedArtifact;
881
+ }
882
+
883
+ // Ensure runtime image exists (auto-build from docker/Dockerfile if missing)
884
+ ensureDockerImage({
885
+ image: dockerConfig.image,
886
+ dockerfile: dockerConfig.dockerfile,
887
+ platform: dockerConfig.platform,
888
+ root,
889
+ env,
890
+ log,
891
+ });
892
+
893
+ // Check git repository status
894
+ const gitCheck = spawnSync("git", ["-C", worktree, "rev-parse", "--is-inside-work-tree"], { encoding: "utf8" });
895
+ if (gitCheck.status !== 0) {
896
+ throw new Error(`cwd is not inside a git repository: ${worktree}`);
897
+ }
898
+
899
+ const commonDirRes = spawnSync("git", ["-C", worktree, "rev-parse", "--git-common-dir"], { encoding: "utf8" });
900
+ let mainRepoRoot = worktree;
901
+ if (commonDirRes.status === 0) {
902
+ const rawCommon = commonDirRes.stdout.trim();
903
+ const commonDir = path.isAbsolute(rawCommon) ? rawCommon : path.resolve(worktree, rawCommon);
904
+ mainRepoRoot = path.dirname(commonDir);
905
+ }
906
+
907
+ const commitCheck = spawnSync("git", ["-C", worktree, "rev-parse", "--verify", "HEAD"], { encoding: "utf8" });
908
+ const hasCommits = commitCheck.status === 0;
909
+
910
+ const branchCheck = spawnSync("git", ["-C", worktree, "rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8" });
911
+ const currentBranch = branchCheck.status === 0 ? branchCheck.stdout.trim() : "main";
912
+
913
+ const tasksRoot = path.resolve(expandHome(dockerConfig.worktree_root));
914
+ fs.mkdirSync(tasksRoot, { recursive: true });
915
+
916
+ const isUnderTasks = worktree.startsWith(tasksRoot + path.sep);
917
+ let taskSlug;
918
+ if (isUnderTasks) {
919
+ taskSlug = sanitizeSlug(path.basename(path.dirname(worktree)));
920
+ } else if (task && task !== "agent gateway") {
921
+ taskSlug = sanitizeSlug(task);
922
+ } else {
923
+ taskSlug = sanitizeSlug(path.basename(worktree));
924
+ }
925
+
926
+ const containerName = `${dockerConfig.container_prefix}-${taskSlug}`;
927
+ const workflowRoot = path.resolve(env.KANDEV_WORKFLOW_ROOT || root);
928
+
929
+ const candidateMounts = new Set([
930
+ normalizeMountPath(mainRepoRoot),
931
+ normalizeMountPath(tasksRoot),
932
+ normalizeMountPath(workflowRoot),
933
+ normalizeMountPath(worktree),
934
+ normalizeMountPath(os.tmpdir()),
935
+ ]);
936
+
937
+ for (const m of [...candidateMounts]) {
938
+ if (m && fs.existsSync(m)) {
939
+ try {
940
+ const real = fs.realpathSync(m);
941
+ const normReal = normalizeMountPath(real);
942
+ if (normReal) candidateMounts.add(normReal);
943
+ } catch {}
944
+ }
945
+ }
946
+
947
+ const mountPaths = [...candidateMounts].filter(Boolean);
948
+ const configuredVolumes = Array.isArray(dockerConfig.volumes) && dockerConfig.volumes.length > 0
949
+ ? dockerConfig.volumes
950
+ : DEFAULT_CONTAINER_VOLUMES;
951
+ const volumeDestinations = configuredVolumes
952
+ .map((vol) => {
953
+ const idx = String(vol).indexOf(":");
954
+ return idx >= 0 ? String(vol).slice(idx + 1).split(":")[0] : null;
955
+ })
956
+ .filter(Boolean);
957
+ const mountArgs = [
958
+ ...mountPaths.flatMap((p) => ["-v", `${p}:${p}`]),
959
+ ...configuredVolumes.flatMap((vol) => ["-v", vol]),
960
+ ];
961
+
962
+ let hostCodexCfg = "";
963
+ try {
964
+ hostCodexCfg = fs.readFileSync(path.join(os.homedir(), ".codex", "config.toml"), "utf8");
965
+ } catch {}
966
+ const proxyPorts = detectLoopbackProxyPorts(hostCodexCfg);
967
+ const entrypointScript = buildContainerEntrypointScript(proxyPorts);
968
+
969
+ let info = inspectContainer(containerName);
970
+ if (info.exists) {
971
+ const missingMount = mountPaths.some((p) => !info.mounts.includes(p));
972
+ const missingVolume = volumeDestinations.some((dest) => !info.mountDestinations.includes(dest));
973
+ const imageMismatch = info.image && info.image !== dockerConfig.image;
974
+ const entrypointMismatch = !Array.isArray(info.cmd) || info.cmd[0] !== "node";
975
+ if (missingMount || missingVolume || imageMismatch || entrypointMismatch) {
976
+ stopTaskDockerWorkspace({ containerName, remove: true });
977
+ info = { exists: false, running: false, id: null };
978
+ }
979
+ }
980
+
981
+ if (info.exists) {
982
+ if (!info.running) {
983
+ const startRes = spawnSync("docker", ["start", containerName], { encoding: "utf8", timeout: 15000 });
984
+ if (startRes.status !== 0) {
985
+ throw new Error(`Failed to start existing Docker container ${containerName}: ${startRes.stderr}`);
986
+ }
987
+ }
988
+ } else {
989
+ const runArgs = ["run", "-d"];
990
+ if (dockerConfig.platform) {
991
+ runArgs.push("--platform", dockerConfig.platform);
992
+ }
993
+ const containerEnv = {
994
+ KANDEV_IN_CONTAINER: "1",
995
+ KANDEV_CONTAINER_NAME: containerName,
996
+ ...(dockerConfig.env || DEFAULT_CONTAINER_ENV),
997
+ };
998
+ runArgs.push(
999
+ "--name", containerName,
1000
+ "--add-host", "host.docker.internal:host-gateway",
1001
+ ...Object.entries(containerEnv).flatMap(([k, v]) => ["-e", `${k}=${v}`]),
1002
+ ...mountArgs,
1003
+ dockerConfig.image,
1004
+ "node", "-e", entrypointScript,
1005
+ );
1006
+ const runRes = spawnSync("docker", runArgs, { encoding: "utf8", timeout: 30000 });
1007
+ if (runRes.status !== 0) {
1008
+ throw new Error(`Failed to run Docker container ${containerName}: ${runRes.stderr || runRes.stdout}`);
1009
+ }
1010
+ }
1011
+
1012
+ info = inspectContainer(containerName);
1013
+ if (!info.running) {
1014
+ throw new Error(`Docker container ${containerName} is not running`);
1015
+ }
1016
+
1017
+ const commands = [];
1018
+ const runInside = (argv, execCwd = null) => {
1019
+ const cmdRes = execInContainer(containerName, argv, { cwd: execCwd });
1020
+ commands.push(cmdRes);
1021
+ if (cmdRes.exit_code !== 0) {
1022
+ log(`docker exec warning (${cmdRes.command}): ${cmdRes.stderr || cmdRes.stdout}`);
1023
+ }
1024
+ return cmdRes;
1025
+ };
1026
+
1027
+ const existingArtifact = readJsonSafe(path.join(worktree, ".agentic", "docker.json"));
1028
+ if (
1029
+ deferProvisioning
1030
+ && existingArtifact?.container_name === containerName
1031
+ && existingArtifact?.verified_in_container === true
1032
+ && info.running
1033
+ ) {
1034
+ return existingArtifact;
1035
+ }
1036
+
1037
+ // Seed container ~/.codex config & auth + git safe.directory in a single fast call
1038
+ prepareContainerCodexConfig({ containerName, log });
1039
+
1040
+ let effectiveWorktree = worktree;
1041
+ let effectiveBranch = currentBranch;
1042
+ let createdWorktree = false;
1043
+
1044
+ if (hasCommits) {
1045
+ if (worktree === mainRepoRoot && task && task !== "agent gateway" && !isUnderTasks) {
1046
+ const targetWorktree = path.join(tasksRoot, taskSlug, path.basename(mainRepoRoot));
1047
+ const targetBranch = `kandev/${taskSlug}`;
1048
+ if (!fs.existsSync(targetWorktree)) {
1049
+ fs.mkdirSync(path.dirname(targetWorktree), { recursive: true });
1050
+ const addRes = runInside(["git", "-C", mainRepoRoot, "worktree", "add", "-b", targetBranch, targetWorktree, "HEAD"]);
1051
+ if (addRes.exit_code === 0) {
1052
+ effectiveWorktree = targetWorktree;
1053
+ effectiveBranch = targetBranch;
1054
+ createdWorktree = true;
1055
+ }
1056
+ } else {
1057
+ effectiveWorktree = targetWorktree;
1058
+ effectiveBranch = targetBranch;
1059
+ createdWorktree = false;
1060
+ }
1061
+ } else if (!deferProvisioning) {
1062
+ createdWorktree = false;
1063
+ runInside(["git", "-C", worktree, "status", "--porcelain"]);
1064
+ runInside(["git", "-C", mainRepoRoot, "worktree", "list", "--porcelain"]);
1065
+ }
1066
+ }
1067
+
1068
+ const verifyRes = runInside(["git", "-C", effectiveWorktree, "rev-parse", "--is-inside-work-tree"]);
1069
+ const verifiedInContainer = verifyRes.exit_code === 0 && verifyRes.stdout.includes("true");
1070
+
1071
+ // Provision project dependencies inside the container (skip during fast MCP startup)
1072
+ let provisionedDependencies = existingArtifact?.provisioned_dependencies || { skipped: true, actions: [] };
1073
+ if (!deferProvisioning && dockerConfig.provision_dependencies && hasCommits) {
1074
+ provisionedDependencies = provisionContainerDependencies({
1075
+ containerName,
1076
+ worktree: effectiveWorktree,
1077
+ projectConfig: dockerConfig.projectConfig,
1078
+ log,
1079
+ env,
1080
+ inContainer: false,
1081
+ });
1082
+ }
1083
+
1084
+ normalizeArtifactOwnership(effectiveWorktree, containerName);
1085
+ if (worktree !== effectiveWorktree) {
1086
+ normalizeArtifactOwnership(worktree, containerName);
1087
+ }
1088
+
1089
+ const artifact = {
1090
+ enabled: true,
1091
+ project: dockerConfig.project || null,
1092
+ execution_mode: "container",
1093
+ container_id: info.id,
1094
+ container_name: containerName,
1095
+ image: dockerConfig.image,
1096
+ platform: dockerConfig.platform,
1097
+ worktree_path: effectiveWorktree,
1098
+ main_repo_path: mainRepoRoot,
1099
+ branch: effectiveBranch,
1100
+ created_worktree: createdWorktree,
1101
+ verified_in_container: verifiedInContainer,
1102
+ provisioned_dependencies: provisionedDependencies,
1103
+ commands,
1104
+ };
1105
+
1106
+ writeDockerArtifact(effectiveWorktree, artifact);
1107
+ if (worktree !== effectiveWorktree) {
1108
+ writeDockerArtifact(worktree, artifact);
1109
+ }
1110
+
1111
+ return artifact;
1112
+ }
1113
+
1114
+ const REEXEC_FORWARD_ENV_KEYS = [
1115
+ "KANDEV_WORKFLOW_ROOT",
1116
+ "KANDEV_STAGE_MODEL",
1117
+ "KANDEV_MODEL",
1118
+ "KANDEV_DOCKER_ENABLED",
1119
+ "KANDEV_DOCKER_IMAGE",
1120
+ "KANDEV_DOCKER_PLATFORM",
1121
+ "KANDEV_DOCKER_SKIP_DAEMON",
1122
+ "KANDEV_DOCKER_SKIP_BUILD",
1123
+ "KANDEV_DOCKER_SKIP_PROVISION",
1124
+ "KANDEV_STAGE_ANDROID_DEVICE",
1125
+ "KANDEV_STAGE_ANDROID_AVD",
1126
+ "REVIEW_TIMEOUT_MS",
1127
+ "REVIEW_RUN_TIMEOUT_MS",
1128
+ "REVIEW_KILL_TIMEOUT_MS",
1129
+ "ANDROID_SERIAL",
1130
+ "ANDROID_AVD",
1131
+ "CI",
1132
+ ];
1133
+
1134
+ /**
1135
+ * Re-execute a stage wrapper script inside the task's Docker container when
1136
+ * called on the host for a worktree whose Stage 1 `.agentic/docker.json` enabled
1137
+ * container execution. Returns `null` when already inside Docker or when Docker
1138
+ * execution is not enabled for this worktree; otherwise returns `{ status }`.
1139
+ */
1140
+ export async function maybeReexecInTaskContainer({
1141
+ cwd,
1142
+ scriptPath,
1143
+ argv = process.argv.slice(2),
1144
+ root,
1145
+ env = process.env,
1146
+ }) {
1147
+ if (isInsideDocker(env) || env.KANDEV_IN_CONTAINER_REEXEC === "1") {
1148
+ return null;
1149
+ }
1150
+ const resolvedCwd = path.resolve(cwd || process.cwd());
1151
+ const dockerArtifact = readJsonSafe(path.join(resolvedCwd, ".agentic", "docker.json"));
1152
+ if (!dockerArtifact || dockerArtifact.enabled !== true || !dockerArtifact.container_name) {
1153
+ return null;
1154
+ }
1155
+ const dockerConfig = resolveDockerConfig(root, env, { cwd: resolvedCwd });
1156
+ if (!dockerConfig.enabled) {
1157
+ return null;
1158
+ }
1159
+
1160
+ const containerName = dockerArtifact.container_name;
1161
+ let info = inspectContainer(containerName);
1162
+ if (!info.running) {
1163
+ const ensured = await ensureTaskDockerWorkspace({
1164
+ cwd: resolvedCwd,
1165
+ root,
1166
+ env,
1167
+ deferProvisioning: true,
1168
+ });
1169
+ if (ensured?.skipped || !ensured?.container_name) {
1170
+ return null;
1171
+ }
1172
+ info = inspectContainer(ensured.container_name);
1173
+ if (!info.running) {
1174
+ throw new Error(`Docker container ${ensured.container_name} is not running`);
1175
+ }
1176
+ }
1177
+
1178
+ const containerEnv = {
1179
+ KANDEV_IN_CONTAINER: "1",
1180
+ KANDEV_IN_CONTAINER_REEXEC: "1",
1181
+ KANDEV_CONTAINER_NAME: containerName,
1182
+ KANDEV_WORKFLOW_ROOT: root,
1183
+ ...(dockerConfig.env || DEFAULT_CONTAINER_ENV),
1184
+ };
1185
+ for (const key of REEXEC_FORWARD_ENV_KEYS) {
1186
+ if (env[key] !== undefined && env[key] !== "") {
1187
+ containerEnv[key] = env[key];
1188
+ }
1189
+ }
1190
+ if (dockerConfig.project) {
1191
+ containerEnv.KANDEV_DOCKER_IMAGE = dockerConfig.image;
1192
+ containerEnv.KANDEV_DOCKER_PLATFORM = dockerConfig.platform;
1193
+ }
1194
+
1195
+ const execArgs = ["exec", "-i", "-w", resolvedCwd];
1196
+ for (const [k, v] of Object.entries(containerEnv)) {
1197
+ execArgs.push("-e", `${k}=${v}`);
1198
+ }
1199
+ execArgs.push(containerName, "node", path.resolve(scriptPath), ...argv);
1200
+
1201
+ const res = spawnSync("docker", execArgs, {
1202
+ cwd: resolvedCwd,
1203
+ stdio: "inherit",
1204
+ });
1205
+ if (res.error) {
1206
+ throw new Error(`Failed to execute inside Docker container ${containerName}: ${res.error.message}`);
1207
+ }
1208
+ return { status: res.status ?? 1, containerName };
1209
+ }