@akjamie/agentic-sdlc 1.9.3 → 2.0.0-alpha.1

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,831 @@
1
+ import fs, { readFileSync } from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { scanDiffForSecrets } from '../assess/secrets.js';
6
+ import { AsdlcError } from './errors.js';
7
+ import { git } from './git.js';
8
+
9
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
10
+ export const DEFAULT_RUNNER_IMAGE = `ghcr.io/akjamie/asdlc-runner:${pkg.version}`;
11
+ export const SUPPORTED_CONTAINER_ENGINES = Object.freeze(['docker', 'podman']);
12
+
13
+ /**
14
+ * Container security baseline enforced internally on every sandbox launch.
15
+ * Never exposes CLI flags to run as root or grant Linux capabilities.
16
+ */
17
+ export const CONTAINER_SECURITY_BASELINE = Object.freeze({
18
+ user: '10001:10001',
19
+ capDrop: 'ALL',
20
+ securityOpt: 'no-new-privileges:true',
21
+ pidsLimit: '512',
22
+ rm: true,
23
+ safeDirectory: '/workspace',
24
+ caCertPath: '/etc/ssl/certs/corporate-ca.crt',
25
+ });
26
+
27
+ const PROXY_ENV_KEYS = ['HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'no_proxy'];
28
+ const MAX_SCAN_FILE_BYTES = 512 * 1024;
29
+
30
+ /**
31
+ * Checks whether an environment variable key is sensitive (tokens, keys, secrets, passwords).
32
+ * Secrets must never be passed via container CLI arguments (-e).
33
+ *
34
+ * @param {string} key
35
+ * @returns {boolean}
36
+ */
37
+ export function isSensitiveEnvKey(key) {
38
+ if (!key) return false;
39
+ const upper = String(key).toUpperCase();
40
+ if (upper.startsWith('GIT_CONFIG_') || upper === 'SSH_AUTH_SOCK' || upper.startsWith('SSL_') || upper.startsWith('NODE_EXTRA_CA_')) {
41
+ return false;
42
+ }
43
+ return /(API_KEY|AUTH_TOKEN|PRIVATE_KEY|BEARER|PASSWORD|SECRET_KEY|_TOKEN$|_SECRET$|_KEY$)/i.test(upper);
44
+ }
45
+
46
+ /**
47
+ * Extract corporate HTTP(S) proxy environment variables from host env.
48
+ *
49
+ * @param {Record<string, string|undefined>} [hostEnv]
50
+ * @returns {Record<string, string>}
51
+ */
52
+ export function collectCorporateProxyEnv(hostEnv = process.env) {
53
+ const out = {};
54
+ for (const key of PROXY_ENV_KEYS) {
55
+ if (hostEnv?.[key]) {
56
+ out[key] = String(hostEnv[key]);
57
+ }
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /**
63
+ * Probes whether a container engine CLI & daemon/machine is available.
64
+ * Probes with `<engine> info` to verify active daemon connectivity.
65
+ *
66
+ * @param {string} engine
67
+ * @param {Function} [execFn]
68
+ * @returns {boolean}
69
+ */
70
+ export function isEngineAvailable(engine, execFn = defaultExec) {
71
+ if (!engine) return false;
72
+ try {
73
+ const res = execFn(engine, ['info'], { stdio: 'ignore', timeout: 5000 });
74
+ return Boolean(res && res.status === 0);
75
+ } catch {
76
+ return false;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Locate executable binary on host PATH.
82
+ *
83
+ * @param {string} name
84
+ * @param {Function} [execFn]
85
+ * @returns {string|null}
86
+ */
87
+ export function whichCommand(name, execFn = defaultExec) {
88
+ if (!name) return null;
89
+ const finder = process.platform === 'win32' ? 'where' : 'which';
90
+ try {
91
+ const r = execFn(finder, [name], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
92
+ if (r && r.status === 0) {
93
+ return r.stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)[0] ?? null;
94
+ }
95
+ } catch {
96
+ // continue
97
+ }
98
+ return null;
99
+ }
100
+
101
+ /**
102
+ * Resolves the container engine according to precedence:
103
+ * 1. Explicit CLI option `opts.engine`
104
+ * 2. Environment variable `ASDLC_CONTAINER_ENGINE`
105
+ * 3. Global config `runner.engine`
106
+ * 4. Automatic probe order: `docker`, then `podman`
107
+ *
108
+ * @param {object} [opts]
109
+ * @param {Function} [execFn]
110
+ * @returns {'docker'|'podman'}
111
+ */
112
+ export function resolveContainerEngine(opts = {}, execFn = defaultExec) {
113
+ const explicit = opts.engine || opts.hostEnv?.ASDLC_CONTAINER_ENGINE || process.env?.ASDLC_CONTAINER_ENGINE || opts.config?.runner?.engine;
114
+ if (explicit && explicit !== 'auto') {
115
+ const norm = String(explicit).toLowerCase().trim();
116
+ if (!SUPPORTED_CONTAINER_ENGINES.includes(norm)) {
117
+ throw new AsdlcError(
118
+ `Unsupported container engine '${explicit}'. Supported engines: ${SUPPORTED_CONTAINER_ENGINES.join(', ')}.`,
119
+ {
120
+ code: 'ASDLC_ERR_INVALID_ENGINE',
121
+ hint: `Specify --engine docker or --engine podman, or unset to allow auto-detection.`,
122
+ }
123
+ );
124
+ }
125
+ if (!isEngineAvailable(norm, execFn)) {
126
+ throw new AsdlcError(
127
+ `Container engine '${norm}' is not available or its daemon is not running.`,
128
+ {
129
+ code: 'ASDLC_ERR_ENGINE_NOT_AVAILABLE',
130
+ hint: `Ensure '${norm}' is installed, in your PATH, and its service/machine is running.`,
131
+ }
132
+ );
133
+ }
134
+ return norm;
135
+ }
136
+
137
+ // Automatic probe order: docker first, then podman
138
+ for (const candidate of SUPPORTED_CONTAINER_ENGINES) {
139
+ if (isEngineAvailable(candidate, execFn)) {
140
+ return candidate;
141
+ }
142
+ }
143
+
144
+ throw new AsdlcError(
145
+ 'No supported container engine found (probed docker, podman). Please start Docker/Podman or run without --container.',
146
+ {
147
+ code: 'ASDLC_ERR_ENGINE_NOT_AVAILABLE',
148
+ hint: 'Install Docker or Podman, ensure the service/machine is running, or execute without the --container flag.',
149
+ }
150
+ );
151
+ }
152
+
153
+ /**
154
+ * Health check helper for `asdlc doctor`.
155
+ * Reports active engine, version, or warn if neither is available.
156
+ *
157
+ * @param {Function} [execFn]
158
+ * @returns {{ status: 'pass'|'warn', detail: string, engine?: string }}
159
+ */
160
+ export function checkContainerEngineHealth(execFn = defaultExec) {
161
+ for (const candidate of SUPPORTED_CONTAINER_ENGINES) {
162
+ try {
163
+ const verRes = execFn(candidate, ['--version'], { stdio: 'pipe', encoding: 'utf8', timeout: 5000 });
164
+ if (verRes && verRes.status === 0) {
165
+ const verText = String(verRes.stdout || '').trim().split('\n')[0];
166
+ const infoRes = execFn(candidate, ['info'], { stdio: 'ignore', timeout: 5000 });
167
+ if (infoRes && infoRes.status === 0) {
168
+ return { status: 'pass', detail: `${candidate} (${verText})`, engine: candidate };
169
+ }
170
+ return { status: 'warn', detail: `${candidate} installed (${verText}) but daemon/machine unreachable`, engine: candidate };
171
+ }
172
+ } catch {
173
+ // continue
174
+ }
175
+ }
176
+ return { status: 'warn', detail: 'neither docker nor podman detected (optional, required only for --container)' };
177
+ }
178
+
179
+ /**
180
+ * Build hardened OCI `create` argument vector enforcing non-root UID 10001:10001,
181
+ * dropped capabilities, PIDs cap, dubious-ownership immunity, and enterprise proxy/CA passthrough.
182
+ *
183
+ * @param {object} [opts]
184
+ * @returns {string[]}
185
+ */
186
+ export function buildContainerCreateArgs(opts = {}) {
187
+ const image = opts.image || DEFAULT_RUNNER_IMAGE;
188
+ const workdir = opts.workdir || CONTAINER_SECURITY_BASELINE.safeDirectory;
189
+ const hostEnv = opts.hostEnv || process.env;
190
+ const engine = opts.engine || 'docker';
191
+ const args = [
192
+ 'create',
193
+ '--user',
194
+ CONTAINER_SECURITY_BASELINE.user,
195
+ `--cap-drop=${CONTAINER_SECURITY_BASELINE.capDrop}`,
196
+ `--security-opt=${CONTAINER_SECURITY_BASELINE.securityOpt}`,
197
+ `--pids-limit=${CONTAINER_SECURITY_BASELINE.pidsLimit}`,
198
+ '-w',
199
+ workdir,
200
+ ];
201
+
202
+ if (opts.rm !== false) {
203
+ args.push('--rm');
204
+ }
205
+
206
+ if (opts.name) {
207
+ args.push('--name', String(opts.name));
208
+ }
209
+
210
+ const injectedEnv = {
211
+ ASDLC_CONTAINER: '1',
212
+ ASDLC_IN_CONTAINER: '1',
213
+ GIT_CONFIG_COUNT: '1',
214
+ GIT_CONFIG_KEY_0: 'safe.directory',
215
+ GIT_CONFIG_VALUE_0: workdir,
216
+ ...collectCorporateProxyEnv(hostEnv),
217
+ ...(opts.env || {}),
218
+ };
219
+
220
+ if (opts.caCertHostPath || hostEnv?.SSL_CERT_FILE || hostEnv?.NODE_EXTRA_CA_CERTS) {
221
+ injectedEnv.SSL_CERT_FILE = CONTAINER_SECURITY_BASELINE.caCertPath;
222
+ injectedEnv.NODE_EXTRA_CA_CERTS = CONTAINER_SECURITY_BASELINE.caCertPath;
223
+ }
224
+
225
+ // SSH Patterns A, B, and C (Agent forwarding, /dev/shm deploy key, Known Hosts handling)
226
+ const platform = opts.platform || process.platform;
227
+ if (opts.sshAuthSock || opts.sshAgent) {
228
+ const isDockerDesktop = engine === 'docker' && (platform === 'darwin' || platform === 'win32');
229
+ const hostSock = opts.sshAuthSock || (isDockerDesktop ? '/run/host-services/ssh-auth.sock' : hostEnv?.SSH_AUTH_SOCK);
230
+ const containerSock = hostSock === '/run/host-services/ssh-auth.sock'
231
+ ? '/run/host-services/ssh-auth.sock'
232
+ : '/run/ssh-agent.sock';
233
+ if (hostSock) {
234
+ const mountOpt = (engine === 'podman' && platform === 'linux') ? ':ro,z' : ':ro';
235
+ args.push('-v', `${hostSock}:${containerSock}${mountOpt}`);
236
+ injectedEnv.SSH_AUTH_SOCK = containerSock;
237
+ }
238
+ if (!injectedEnv.GIT_SSH_COMMAND) {
239
+ injectedEnv.GIT_SSH_COMMAND = 'ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/dev/shm/.ssh/known_hosts';
240
+ }
241
+ } else if (opts.sshKeyPath || hostEnv?.ASDLC_SSH_KEY) {
242
+ if (!injectedEnv.GIT_SSH_COMMAND) {
243
+ injectedEnv.GIT_SSH_COMMAND = 'ssh -i /dev/shm/.ssh/id_ed25519 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/dev/shm/.ssh/known_hosts';
244
+ }
245
+ }
246
+
247
+ for (const [k, v] of Object.entries(injectedEnv)) {
248
+ if (isSensitiveEnvKey(k)) continue; // §3.3: Never leak secrets via inspect / -e flags
249
+ if (v !== undefined && v !== null && String(v).length > 0) {
250
+ args.push('-e', `${k}=${v}`);
251
+ }
252
+ }
253
+
254
+ args.push(image);
255
+ if (Array.isArray(opts.cmd) && opts.cmd.length > 0) {
256
+ args.push(...opts.cmd);
257
+ }
258
+ return args;
259
+ }
260
+
261
+ export const buildDockerCreateArgs = buildContainerCreateArgs;
262
+
263
+ /**
264
+ * Detect Tri-State Repository Lifecycle (`greenfield`, `brownfield`, `established`).
265
+ *
266
+ * @param {string} repoDir
267
+ * @returns {{ lifecycle: 'greenfield'|'brownfield'|'established', isGitRepo: boolean, hasOpenspec: boolean }}
268
+ */
269
+ export function detectRepoLifecycle(repoDir) {
270
+ const target = path.resolve(repoDir || process.cwd());
271
+ if (!fs.existsSync(target)) {
272
+ return { lifecycle: 'greenfield', isGitRepo: false, hasOpenspec: false };
273
+ }
274
+ const inside = git(['rev-parse', '--is-inside-work-tree'], target, { allowFail: true });
275
+ const isGitRepo = Boolean(inside && inside.trim() === 'true');
276
+ if (!isGitRepo) {
277
+ return { lifecycle: 'greenfield', isGitRepo: false, hasOpenspec: false };
278
+ }
279
+ const hasOpenspec = fs.existsSync(path.join(target, 'openspec'));
280
+ return {
281
+ lifecycle: hasOpenspec ? 'established' : 'brownfield',
282
+ isGitRepo: true,
283
+ hasOpenspec,
284
+ };
285
+ }
286
+
287
+ /**
288
+ * Pre-Ingestion Secret Scanning Guard:
289
+ * Scans dirty working tree diffs and untracked non-ignored files before
290
+ * streaming workspace contents into an isolated container or AI session.
291
+ * Throws AsdlcError('ASDLC_ERR_UNCOMMITTED_SECRET') on detection.
292
+ *
293
+ * @param {string} repoDir
294
+ * @param {object} [opts]
295
+ * @returns {{ clean: boolean, findings: Array<object> }}
296
+ */
297
+ export function preScanWorkspaceForSecrets(repoDir, opts = {}) {
298
+ const findings = [];
299
+
300
+ if (typeof opts.diffText === 'string') {
301
+ for (const f of scanDiffForSecrets(opts.diffText)) {
302
+ findings.push({ source: 'working-diff', ...f });
303
+ }
304
+ } else if (repoDir && fs.existsSync(repoDir)) {
305
+ const lifecycle = detectRepoLifecycle(repoDir);
306
+ if (lifecycle.isGitRepo) {
307
+ const hasHead = Boolean(git(['rev-parse', '--verify', 'HEAD'], repoDir, { allowFail: true }));
308
+ const diffArgs = hasHead ? ['diff', '-p', 'HEAD'] : ['diff', '--cached', '-p'];
309
+ const diffText = git(diffArgs, repoDir, { allowFail: true }) || '';
310
+ for (const f of scanDiffForSecrets(diffText)) {
311
+ findings.push({ source: 'git-diff', ...f });
312
+ }
313
+ const untracked = (git(['ls-files', '--others', '--exclude-standard'], repoDir, { allowFail: true }) || '')
314
+ .split(/\r?\n/)
315
+ .filter(Boolean);
316
+ for (const rel of untracked) {
317
+ const abs = path.join(repoDir, rel);
318
+ try {
319
+ const stat = fs.statSync(abs);
320
+ if (!stat.isFile() || stat.size > MAX_SCAN_FILE_BYTES) continue;
321
+ const content = fs.readFileSync(abs, 'utf8');
322
+ if (content.includes('\u0000')) continue; // skip binaries
323
+ for (const f of scanDiffForSecrets(content)) {
324
+ findings.push({ source: rel, ...f });
325
+ }
326
+ } catch {
327
+ // ignore unreadable race
328
+ }
329
+ }
330
+ }
331
+ }
332
+
333
+ if (findings.length > 0) {
334
+ const summary = findings
335
+ .slice(0, 5)
336
+ .map((f) => `${f.source}:${f.line} [${f.rule}] ${f.redacted}`)
337
+ .join('; ');
338
+ throw new AsdlcError(
339
+ `Uncommitted or untracked plaintext secret detected before container ingestion: ${summary}`,
340
+ {
341
+ code: 'ASDLC_ERR_UNCOMMITTED_SECRET',
342
+ hint: 'Remove or encrypt the secret using environment variables / secret manager before running `asdlc run`.',
343
+ }
344
+ );
345
+ }
346
+
347
+ return { clean: true, findings: [] };
348
+ }
349
+
350
+ function walkSpecTargets(changeDirPath) {
351
+ const targets = [];
352
+ if (!changeDirPath || !fs.existsSync(changeDirPath)) return targets;
353
+ const proposal = path.join(changeDirPath, 'proposal.md');
354
+ if (fs.existsSync(proposal)) targets.push(proposal);
355
+
356
+ const specsRoot = path.join(changeDirPath, 'specs');
357
+ if (fs.existsSync(specsRoot)) {
358
+ const stack = [specsRoot];
359
+ while (stack.length > 0) {
360
+ const cur = stack.pop();
361
+ for (const entry of fs.readdirSync(cur, { withFileTypes: true })) {
362
+ const full = path.join(cur, entry.name);
363
+ if (entry.isDirectory()) {
364
+ stack.push(full);
365
+ } else if (entry.isFile()) {
366
+ targets.push(full);
367
+ }
368
+ }
369
+ }
370
+ }
371
+ return targets;
372
+ }
373
+
374
+ /**
375
+ * Set OS/kernel-level read-only permissions (0444) on approved specification
376
+ * files (`proposal.md` and `specs/**`) during implementation (`apply`).
377
+ *
378
+ * @param {string} changeDirPath
379
+ * @returns {string[]} locked file paths
380
+ */
381
+ export function lockSpecsReadOnly(changeDirPath) {
382
+ const locked = [];
383
+ for (const file of walkSpecTargets(changeDirPath)) {
384
+ fs.chmodSync(file, 0o444);
385
+ locked.push(file);
386
+ }
387
+ return locked;
388
+ }
389
+
390
+ /**
391
+ * Restore writable permissions (0644) on specification files (required for
392
+ * spec revisions or test cleanup on Windows/POSIX).
393
+ *
394
+ * @param {string} changeDirPath
395
+ * @returns {string[]} unlocked file paths
396
+ */
397
+ export function unlockSpecsWritable(changeDirPath) {
398
+ const unlocked = [];
399
+ for (const file of walkSpecTargets(changeDirPath)) {
400
+ fs.chmodSync(file, 0o644);
401
+ unlocked.push(file);
402
+ }
403
+ return unlocked;
404
+ }
405
+
406
+ function defaultExec(cmd, args, opts = {}) {
407
+ return spawnSync(cmd, args, { encoding: opts.encoding ?? 'utf8', ...opts });
408
+ }
409
+
410
+ /**
411
+ * Performs 3-layer workspace ingestion + external intake / custom skill / /dev/shm credential
412
+ * streaming into an isolated stopped/created container without mounting the host filesystem.
413
+ *
414
+ * @param {string} repoDir
415
+ * @param {string} containerId
416
+ * @param {object} [opts]
417
+ * @returns {object} staging summary
418
+ */
419
+ export function stageWorkspaceToContainer(repoDir, containerId, opts = {}) {
420
+ if (!containerId) {
421
+ throw new AsdlcError('containerId is required for workspace ingestion', { code: 'ASDLC_ERR_CONTAINER_ID' });
422
+ }
423
+ const execFn = opts.execFn || defaultExec;
424
+ const targetDir = path.resolve(repoDir || process.cwd());
425
+ const lifecycle = opts.lifecycle || detectRepoLifecycle(targetDir).lifecycle;
426
+ const homeDir = opts.homeDir || os.homedir();
427
+ const engine = opts.engine || 'docker';
428
+ const staged = {
429
+ lifecycle,
430
+ containerId,
431
+ layers: [],
432
+ externalFiles: 0,
433
+ customSkillsInjected: false,
434
+ shmCredentials: [],
435
+ };
436
+
437
+ if (lifecycle === 'greenfield') {
438
+ const res = execFn(engine, ['exec', containerId, 'sh', '-c', 'mkdir -p /workspace'], { cwd: targetDir });
439
+ if (res && res.status !== 0 && !opts.ignoreErrors) {
440
+ throw new AsdlcError(`Failed to initialize /workspace in greenfield container: ${res.stderr || res.status}`, {
441
+ code: 'ASDLC_ERR_CONTAINER_STAGE',
442
+ });
443
+ }
444
+ staged.layers.push('greenfield-init');
445
+ } else {
446
+ // Layer 1: Tracked commits via `git archive HEAD`
447
+ const hasHead = Boolean(git(['rev-parse', '--verify', 'HEAD'], targetDir, { allowFail: true }));
448
+ if (hasHead) {
449
+ const archive = execFn('git', ['archive', '--format=tar', 'HEAD'], { cwd: targetDir, encoding: null });
450
+ if (archive && archive.status === 0 && archive.stdout) {
451
+ const cp = execFn(engine, ['cp', '-', `${containerId}:/workspace`], { input: archive.stdout, encoding: null });
452
+ if (cp && cp.status !== 0 && !opts.ignoreErrors) {
453
+ throw new AsdlcError(`Failed to stream git archive into container: ${cp.stderr || cp.status}`, {
454
+ code: 'ASDLC_ERR_CONTAINER_STAGE',
455
+ });
456
+ }
457
+ staged.layers.push('git-archive-head');
458
+ }
459
+ }
460
+
461
+ // Layer 2: Uncommitted tracked changes (`git diff --binary HEAD`)
462
+ const diffRes = execFn('git', ['diff', '--binary', 'HEAD'], { cwd: targetDir, timeout: 60000 });
463
+ if (diffRes && diffRes.status === 0 && diffRes.stdout && String(diffRes.stdout).trim().length > 0) {
464
+ const applyRes = execFn(engine, ['exec', '-i', containerId, 'git', 'apply', '--allow-empty', '-'], {
465
+ input: String(diffRes.stdout),
466
+ timeout: 60000,
467
+ });
468
+ if (applyRes && applyRes.status !== 0 && !opts.ignoreErrors) {
469
+ throw new AsdlcError(`Failed to apply git diff in container: ${applyRes.stderr || applyRes.status}`, {
470
+ code: 'ASDLC_ERR_CONTAINER_STAGE',
471
+ });
472
+ }
473
+ staged.layers.push('git-diff-head');
474
+ }
475
+
476
+ // Layer 3: Untracked non-ignored files (`git ls-files --others --exclude-standard`)
477
+ const untrackedRes = execFn('git', ['ls-files', '--others', '--exclude-standard'], { cwd: targetDir, timeout: 60000 });
478
+ const untracked = String(untrackedRes?.stdout || '')
479
+ .split(/\r?\n/)
480
+ .map((s) => s.trim())
481
+ .filter(Boolean);
482
+ if (untracked.length > 0) {
483
+ for (const rel of untracked) {
484
+ const abs = path.join(targetDir, rel);
485
+ if (!fs.existsSync(abs)) continue;
486
+ const containerDestDir = path.posix.dirname(`/workspace/${rel.replace(/\\/g, '/')}`);
487
+ execFn(engine, ['exec', containerId, 'mkdir', '-p', containerDestDir], { timeout: 15000 });
488
+ const cpRes = execFn(engine, ['cp', abs, `${containerId}:/workspace/${rel.replace(/\\/g, '/')}`], { timeout: 30000 });
489
+ if (cpRes && cpRes.status !== 0 && !opts.ignoreErrors) {
490
+ throw new AsdlcError(`Failed to copy untracked file '${rel}' into container: ${cpRes.stderr || cpRes.status}`, {
491
+ code: 'ASDLC_ERR_CONTAINER_STAGE',
492
+ });
493
+ }
494
+ }
495
+ staged.layers.push(`untracked-files:${untracked.length}`);
496
+ }
497
+ }
498
+
499
+ // External --from-file attachments
500
+ const fromFiles = Array.isArray(opts.fromFiles) ? opts.fromFiles.filter(Boolean) : [];
501
+ if (fromFiles.length > 0) {
502
+ execFn(engine, ['exec', '-u', '0:0', containerId, 'mkdir', '-p', '/workspace/.asdlc-intake/files'], { timeout: 15000 });
503
+ for (const f of fromFiles) {
504
+ const abs = path.isAbsolute(f) ? f : path.resolve(targetDir, f);
505
+ if (fs.existsSync(abs)) {
506
+ const cpRes = execFn(engine, ['cp', abs, `${containerId}:/workspace/.asdlc-intake/files/${path.basename(abs)}`], { timeout: 30000 });
507
+ if (cpRes && cpRes.status !== 0 && !opts.ignoreErrors) {
508
+ throw new AsdlcError(`Failed to copy intake file '${f}' into container: ${cpRes.stderr || cpRes.status}`, {
509
+ code: 'ASDLC_ERR_CONTAINER_STAGE',
510
+ });
511
+ }
512
+ staged.externalFiles += 1;
513
+ }
514
+ }
515
+ }
516
+
517
+ // Tier 1 enterprise custom skills (~/.asdlc/skills/)
518
+ const customSkillsDir = path.join(homeDir, '.asdlc', 'skills');
519
+ if (fs.existsSync(customSkillsDir)) {
520
+ execFn(engine, ['exec', '-u', '0:0', containerId, 'mkdir', '-p', '/workspace/.asdlc'], { timeout: 15000 });
521
+ const cpRes = execFn(engine, ['cp', customSkillsDir, `${containerId}:/workspace/.asdlc/skills`], { timeout: 30000 });
522
+ if (cpRes && cpRes.status !== 0 && !opts.ignoreErrors) {
523
+ throw new AsdlcError(`Failed to copy custom skills into container: ${cpRes.stderr || cpRes.status}`, {
524
+ code: 'ASDLC_ERR_CONTAINER_STAGE',
525
+ });
526
+ }
527
+ staged.customSkillsInjected = true;
528
+ }
529
+
530
+ // Ensure non-root agent user (UID 10001:10001) owns the entire staged workspace including ingested files and skills
531
+ const chownRes = execFn(engine, ['exec', '-u', '0:0', containerId, 'chown', '-R', '10001:10001', '/workspace'], { timeout: 60000 });
532
+ if (chownRes && chownRes.status !== 0 && !opts.ignoreErrors) {
533
+ throw new AsdlcError(`Failed to set non-root ownership on /workspace: ${chownRes.stderr || chownRes.status}`, {
534
+ code: 'ASDLC_ERR_CONTAINER_STAGE',
535
+ });
536
+ }
537
+
538
+ // Stream volatile AI auth & SSH keys directly into container tmpfs (/dev/shm) with 0600 permissions
539
+ const streamShmFile = (containerDestPath, content) => {
540
+ const dir = path.posix.dirname(containerDestPath);
541
+ execFn(engine, ['exec', '-i', containerId, 'sh', '-c', `mkdir -p ${dir} && chmod 700 ${dir} && cat > ${containerDestPath} && chmod 600 ${containerDestPath}`], {
542
+ input: typeof content === 'string' ? content : JSON.stringify(content, null, 2),
543
+ timeout: 30000,
544
+ });
545
+ staged.shmCredentials.push(containerDestPath);
546
+ };
547
+
548
+ if (opts.harness?.baseConfigPath && fs.existsSync(opts.harness.baseConfigPath)) {
549
+ streamShmFile('/dev/shm/opencode/opencode.json', fs.readFileSync(opts.harness.baseConfigPath, 'utf8'));
550
+ } else if (opts.harness?.generatedConfig) {
551
+ streamShmFile('/dev/shm/opencode/opencode.json', opts.harness.generatedConfig);
552
+ }
553
+
554
+ if (opts.harness?.authPath && fs.existsSync(opts.harness.authPath)) {
555
+ streamShmFile('/dev/shm/opencode/auth.json', fs.readFileSync(opts.harness.authPath, 'utf8'));
556
+ } else if (opts.harness?.authPayload) {
557
+ streamShmFile('/dev/shm/opencode/auth.json', opts.harness.authPayload);
558
+ }
559
+
560
+ if (opts.sshKeyPath && fs.existsSync(opts.sshKeyPath)) {
561
+ streamShmFile('/dev/shm/.ssh/id_ed25519', fs.readFileSync(opts.sshKeyPath, 'utf8'));
562
+ } else if (opts.sshKeyContent) {
563
+ streamShmFile('/dev/shm/.ssh/id_ed25519', opts.sshKeyContent);
564
+ }
565
+
566
+ // Stream Git / tool credentials and API tokens into /dev/shm/.env with export syntax
567
+ const shmEnv = {};
568
+ if (opts.creds?.token) {
569
+ shmEnv.GH_TOKEN = opts.creds.token;
570
+ shmEnv.GITHUB_TOKEN = opts.creds.token;
571
+ }
572
+ for (const [k, v] of Object.entries(opts.env || {})) {
573
+ if (isSensitiveEnvKey(k) && v !== undefined && v !== null && String(v).length > 0) {
574
+ shmEnv[k] = String(v);
575
+ }
576
+ }
577
+ if (Object.keys(shmEnv).length > 0) {
578
+ const envLines = Object.entries(shmEnv)
579
+ .map(([k, v]) => `export ${k}=${JSON.stringify(v)}`)
580
+ .join('\n') + '\n';
581
+ streamShmFile('/dev/shm/.env', envLines);
582
+ }
583
+
584
+ // Ensure OpenCode agent finds configuration in /dev/shm
585
+ execFn(engine, [
586
+ 'exec', containerId, 'sh', '-c',
587
+ 'mkdir -p /home/agent/.config /home/agent/.local/share && ln -sfn /dev/shm/opencode /home/agent/.config/opencode && ln -sfn /dev/shm/opencode /home/agent/.local/share/opencode'
588
+ ], { timeout: 15000 });
589
+
590
+ return staged;
591
+ }
592
+
593
+ /**
594
+ * Enforces true root-owned read-only immutability (chown 0:0, chmod 0444) on approved spec files
595
+ * inside the container so the unprivileged agent (UID 10001) cannot mutate them.
596
+ *
597
+ * @param {string} containerId
598
+ * @param {string} changeSlug
599
+ * @param {object} [opts]
600
+ * @returns {string[]} locked paths
601
+ */
602
+ export function lockContainerSpecsRootReadOnly(containerId, changeSlug, opts = {}) {
603
+ const execFn = opts.execFn || defaultExec;
604
+ const engine = opts.engine || 'docker';
605
+ const lockedPaths = [
606
+ `/workspace/openspec/changes/${changeSlug}/proposal.md`,
607
+ `/workspace/openspec/changes/${changeSlug}/specs`,
608
+ ];
609
+ for (const p of lockedPaths) {
610
+ execFn(engine, ['exec', '-u', '0:0', containerId, 'sh', '-c', `if [ -e "${p}" ]; then chown -R 0:0 "${p}" && chmod -R 0444 "${p}"; fi`], { timeout: 15000 });
611
+ }
612
+ return lockedPaths;
613
+ }
614
+
615
+ /**
616
+ * Syncs verified container workspace artifacts back to host repository according to
617
+ * the Tri-State Repository Lifecycle (`greenfield`, `brownfield`, `established`).
618
+ *
619
+ * @param {string} repoDir
620
+ * @param {string} containerId
621
+ * @param {'greenfield'|'brownfield'|'established'} lifecycleState
622
+ * @param {object} [opts]
623
+ * @returns {object} egress sync summary
624
+ */
625
+ export function syncContainerEgressToHost(repoDir, containerId, lifecycleState = 'established', opts = {}) {
626
+ if (!containerId) {
627
+ throw new AsdlcError('containerId is required for egress sync', { code: 'ASDLC_ERR_CONTAINER_ID' });
628
+ }
629
+ const execFn = opts.execFn || defaultExec;
630
+ const engine = opts.engine || 'docker';
631
+ const targetDir = path.resolve(repoDir || process.cwd());
632
+ const branch = opts.branch || 'HEAD';
633
+
634
+ if (lifecycleState === 'greenfield') {
635
+ fs.mkdirSync(targetDir, { recursive: true });
636
+ execFn(engine, ['cp', `${containerId}:/workspace/.`, targetDir], { timeout: 60000 });
637
+ return { lifecycle: 'greenfield', strategy: 'full-copy', dest: targetDir };
638
+ }
639
+
640
+ if (lifecycleState === 'brownfield') {
641
+ const syncedPaths = [];
642
+ for (const rel of ['openspec', '.agents', 'AGENTS.md', '.gitignore']) {
643
+ const check = execFn(engine, ['exec', containerId, 'test', '-e', `/workspace/${rel}`], { timeout: 15000 });
644
+ if (!check || check.status === 0) {
645
+ const hostDest = path.join(targetDir, rel);
646
+ execFn(engine, ['cp', `${containerId}:/workspace/${rel}`, hostDest], { timeout: 30000 });
647
+ syncedPaths.push(rel);
648
+ }
649
+ }
650
+ return { lifecycle: 'brownfield', strategy: 'selective-governance-copy', syncedPaths };
651
+ }
652
+
653
+ // Established repositories: atomic git bundle fetch without touching host dirty tree
654
+ const bundleHostPath = opts.bundleHostPath || path.join(os.tmpdir(), `asdlc-egress-${containerId.slice(0, 12)}.bundle`);
655
+ const bundleRes = execFn(engine, ['exec', containerId, 'git', '-C', '/workspace', 'bundle', 'create', '/tmp/asdlc-out.bundle', branch], { timeout: 60000 });
656
+ if (bundleRes && bundleRes.status !== 0 && !opts.ignoreErrors) {
657
+ throw new AsdlcError(`Failed to create git egress bundle inside container: ${bundleRes.stderr || bundleRes.status}`, {
658
+ code: 'ASDLC_ERR_CONTAINER_EGRESS',
659
+ });
660
+ }
661
+
662
+ const cpRes = execFn(engine, ['cp', `${containerId}:/tmp/asdlc-out.bundle`, bundleHostPath], { timeout: 60000 });
663
+ if (cpRes && cpRes.status !== 0 && !opts.ignoreErrors) {
664
+ throw new AsdlcError(`Failed to copy git egress bundle from container: ${cpRes.stderr || cpRes.status}`, {
665
+ code: 'ASDLC_ERR_CONTAINER_EGRESS',
666
+ });
667
+ }
668
+
669
+ const targetRef = opts.targetRef || branch;
670
+ const egressTrackingRef = `refs/asdlc/egress/${branch.replace(/^refs\/(heads\/)?/, '')}`;
671
+ const fetchRes = execFn('git', ['fetch', bundleHostPath, `${branch}:${egressTrackingRef}`, '--force'], { cwd: targetDir, timeout: 60000 });
672
+ if (fetchRes && fetchRes.status !== 0 && !opts.ignoreErrors) {
673
+ throw new AsdlcError(`Failed to fetch git egress bundle into host repository: ${fetchRes.stderr || fetchRes.status}`, {
674
+ code: 'ASDLC_ERR_CONTAINER_EGRESS',
675
+ });
676
+ }
677
+
678
+ // If host workspace is currently on target branch, fast-forward; otherwise update ref
679
+ let headBranch = '';
680
+ try {
681
+ const headRes = execFn('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: targetDir, timeout: 5000 });
682
+ headBranch = headRes?.stdout?.trim() || '';
683
+ } catch {
684
+ // ignore
685
+ }
686
+
687
+ if (headBranch === branch || headBranch === targetRef) {
688
+ execFn('git', ['merge', '--ff-only', egressTrackingRef], { cwd: targetDir, timeout: 15000 });
689
+ } else {
690
+ execFn('git', ['update-ref', `refs/heads/${targetRef.replace(/^refs\/heads\//, '')}`, egressTrackingRef], { cwd: targetDir, timeout: 15000 });
691
+ }
692
+
693
+ try {
694
+ if (fs.existsSync(bundleHostPath)) fs.unlinkSync(bundleHostPath);
695
+ } catch {
696
+ // ignore cleanup error
697
+ }
698
+ return { lifecycle: 'established', strategy: 'git-bundle-fetch', branch: targetRef };
699
+ }
700
+
701
+ /**
702
+ * Build deterministic container CLI invocation command forwarding all orchestrator flags.
703
+ *
704
+ * @param {string|null} target
705
+ * @param {object} [opts]
706
+ * @returns {string}
707
+ */
708
+ export function buildContainerRunCommand(target, opts = {}) {
709
+ const parts = ['asdlc', 'run'];
710
+ if (target) parts.push(JSON.stringify(String(target)));
711
+ if (opts.stage) parts.push('--stage', opts.stage);
712
+ if (opts.repo) parts.push('--repo', JSON.stringify(opts.repo));
713
+ if (opts.mode) parts.push('--mode', opts.mode);
714
+ if (opts.model) parts.push('--model', JSON.stringify(opts.model));
715
+ if (opts.reviewModel) parts.push('--review-model', JSON.stringify(opts.reviewModel));
716
+ if (opts.targetBranch) parts.push('--target-branch', JSON.stringify(opts.targetBranch));
717
+ for (const f of (opts.fromFile || [])) {
718
+ const stagedPath = `/workspace/.asdlc-intake/files/${path.basename(f)}`;
719
+ parts.push('--from-file', JSON.stringify(stagedPath));
720
+ }
721
+ for (const i of (opts.fromIssue || [])) parts.push('--from-issue', JSON.stringify(i));
722
+ return parts.join(' ');
723
+ }
724
+
725
+ /**
726
+ * Executes a full end-to-end containerized pipeline lifecycle:
727
+ * 1. Verifies container engine (Docker / Podman) CLI & daemon/machine
728
+ * 2. Creates container with idle entrypoint (sleep infinity) without --rm
729
+ * 3. Starts container in background so tmpfs (/dev/shm) is mounted and exec is accepted
730
+ * 4. Ingests workspace via 3-layer staging + volatile credentials in /dev/shm
731
+ * 5. Locks specs root-owned (if apply stage)
732
+ * 6. Executes pipeline stage as unprivileged UID 10001 with sourced /dev/shm/.env
733
+ * 7. Syncs egress artifacts back to host repository while container is alive
734
+ * 8. Cleans up container safely
735
+ *
736
+ * @param {string|null} target
737
+ * @param {object} [opts]
738
+ * @returns {Promise<object>} execution summary
739
+ */
740
+ export async function runContainerPipeline(target, opts = {}) {
741
+ const execFn = opts.execFn || defaultExec;
742
+ const targetDir = path.resolve(opts.repoRoot || process.cwd());
743
+ const lifecycleInfo = detectRepoLifecycle(targetDir);
744
+
745
+ const engine = resolveContainerEngine(opts, execFn);
746
+
747
+ const containerName = `asdlc-run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
748
+ const containerSubcommand = buildContainerRunCommand(target, opts);
749
+
750
+ const createArgs = buildContainerCreateArgs({
751
+ name: containerName,
752
+ engine,
753
+ image: opts.image || DEFAULT_RUNNER_IMAGE,
754
+ hostEnv: opts.env || process.env,
755
+ sshAuthSock: opts.sshAuthSock,
756
+ sshAgent: opts.sshAgent,
757
+ sshKeyPath: opts.sshKeyPath,
758
+ caCertHostPath: opts.caCertHostPath,
759
+ rm: false, // Must not delete automatically on exit so egress artifacts can be synced
760
+ cmd: ['sleep', 'infinity'], // Keeps container alive as daemon for staging, execution, and egress
761
+ });
762
+
763
+ const createRes = execFn(engine, createArgs);
764
+ if (!createRes || createRes.status !== 0) {
765
+ throw new AsdlcError(`${engine} create failed: ${createRes?.stderr || createRes?.status}`, {
766
+ code: 'ASDLC_ERR_CONTAINER_CREATE',
767
+ });
768
+ }
769
+ const containerId = String(createRes.stdout || '').trim() || containerName;
770
+
771
+ try {
772
+ // 1. Start container in background so tmpfs (/dev/shm) is active and exec works
773
+ const startRes = execFn(engine, ['start', containerId]);
774
+ if (startRes && startRes.status !== 0) {
775
+ throw new AsdlcError(`Failed to start container daemon: ${startRes.stderr || startRes.status}`, {
776
+ code: 'ASDLC_ERR_CONTAINER_START',
777
+ });
778
+ }
779
+
780
+ // 2. Stage workspace and inject credentials into active /dev/shm
781
+ stageWorkspaceToContainer(targetDir, containerId, {
782
+ ...opts,
783
+ engine,
784
+ execFn,
785
+ lifecycle: lifecycleInfo.lifecycle,
786
+ });
787
+
788
+ // 3. Lock specs root-owned if apply stage
789
+ if (opts.stage === 'apply' && opts.slug) {
790
+ lockContainerSpecsRootReadOnly(containerId, opts.slug, { engine, execFn });
791
+ }
792
+
793
+ // 4. Run stage command inside the running container as unprivileged UID 10001
794
+ const execTimeout = opts.timeoutMs ?? (opts.stage === 'apply' ? 1800000 : 600000);
795
+ const runRes = execFn(engine, [
796
+ 'exec',
797
+ '-u', CONTAINER_SECURITY_BASELINE.user,
798
+ containerId,
799
+ 'sh', '-c',
800
+ `export ASDLC_IN_CONTAINER=1 ASDLC_CONTAINER=1; if [ -f /dev/shm/.env ]; then . /dev/shm/.env; fi; exec ${containerSubcommand}`,
801
+ ], {
802
+ stdio: opts.stdio || 'inherit',
803
+ timeout: execTimeout,
804
+ });
805
+ const exitCode = runRes?.status ?? 0;
806
+
807
+ // 5. Sync egress artifacts back to host while container is still alive
808
+ let egress = null;
809
+ if (exitCode === 0 && !opts.skipEgress) {
810
+ egress = syncContainerEgressToHost(targetDir, containerId, lifecycleInfo.lifecycle, {
811
+ ...opts,
812
+ engine,
813
+ execFn,
814
+ branch: opts.branch || 'HEAD',
815
+ });
816
+ }
817
+
818
+ return {
819
+ engine,
820
+ containerId,
821
+ exitCode,
822
+ egress,
823
+ stdout: runRes?.stdout || '',
824
+ stderr: runRes?.stderr || '',
825
+ };
826
+ } finally {
827
+ // 6. Guarantee container removal
828
+ execFn(engine, ['rm', '-f', containerId]);
829
+ }
830
+ }
831
+