@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,1089 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {
5
+ resolveAgentHarnessConfig,
6
+ resolveGitCredentials,
7
+ resolvePassthroughEnv,
8
+ redactSecrets,
9
+ } from '../lib/auth.js';
10
+ import { loadGlobalConfig } from '../lib/config.js';
11
+ import { toChangeSlug, jsonOut } from '../lib/cliutil.js';
12
+ import {
13
+ buildContainerCreateArgs,
14
+ buildDockerCreateArgs,
15
+ detectRepoLifecycle,
16
+ lockSpecsReadOnly,
17
+ preScanWorkspaceForSecrets,
18
+ resolveContainerEngine,
19
+ runContainerPipeline,
20
+ whichCommand,
21
+ DEFAULT_RUNNER_IMAGE,
22
+ } from '../lib/container.js';
23
+ import { AsdlcError, fail } from '../lib/errors.js';
24
+ import {
25
+ changeOnRef,
26
+ git,
27
+ headSha,
28
+ lastCommitTouching,
29
+ resolveDefaultBranch,
30
+ } from '../lib/git.js';
31
+ import { assertGitRepositoryInitialized, resolveGitHostAndRepo } from '../lib/githost.js';
32
+ import { findChangeByIssueId } from '../lib/intake.js';
33
+ import { resolveTopology } from '../lib/level.js';
34
+ import { log, dim } from '../lib/log.js';
35
+ import { exists, readText, walkFiles } from '../lib/fs.js';
36
+ import { changeDir, openspecDir } from '../lib/paths.js';
37
+ import {
38
+ buildThreadResolutionPlan,
39
+ checkAntiThrashingCircuitBreaker,
40
+ triagePullRequest,
41
+ fetchGitHubPrReviewContext,
42
+ replyAndResolveGitHubThread,
43
+ } from '../lib/triage.js';
44
+ import { applyGuard } from './apply.js';
45
+ import { hasUnresolvedClarifications, runLint } from './lint.js';
46
+ import { newChange } from './new.js';
47
+ import { createPR } from './pr.js';
48
+ import { runVerify } from './verify.js';
49
+
50
+ export const CANONICAL_STAGES = Object.freeze(['spec', 'apply', 'verify', 'fix']);
51
+
52
+ export const STAGE_ALIASES = Object.freeze({
53
+ 'spec-review': 'spec',
54
+ 'impl-review': 'verify',
55
+ 'fix-comments': 'fix',
56
+ });
57
+
58
+ const DEFAULT_MUTEX_STALE_MS = 30 * 60 * 1000;
59
+
60
+ /**
61
+ * Normalize explicit `--stage` values onto the canonical 3+1 stage verbs (`spec`, `apply`, `verify`, `fix`).
62
+ * Rejects unrecognized stage names with `ASDLC_ERR_INVALID_STAGE`.
63
+ *
64
+ * @param {string|null|undefined} stage
65
+ * @returns {string|null}
66
+ */
67
+ export function normalizeStage(stage) {
68
+ if (stage === undefined || stage === null || String(stage).trim() === '') {
69
+ return null;
70
+ }
71
+ const normalized = String(stage).trim().toLowerCase();
72
+ if (CANONICAL_STAGES.includes(normalized)) {
73
+ return normalized;
74
+ }
75
+ if (Object.hasOwn(STAGE_ALIASES, normalized)) {
76
+ return STAGE_ALIASES[normalized];
77
+ }
78
+ throw new AsdlcError(
79
+ `Invalid pipeline stage '${stage}'. Expected one of: ${CANONICAL_STAGES.join(', ')} (aliases: ${Object.keys(STAGE_ALIASES).join(', ')}).`,
80
+ {
81
+ code: 'ASDLC_ERR_INVALID_STAGE',
82
+ hint: 'Pass `--stage spec`, `--stage apply`, `--stage verify`, or `--stage fix`.',
83
+ }
84
+ );
85
+ }
86
+
87
+ /**
88
+ * Acquire an exclusive per-change mutex lock file (`.run.lock`) to prevent concurrent orchestrators
89
+ * from racing on the same change directory.
90
+ *
91
+ * @param {string} changeDirPath
92
+ * @param {object} [opts]
93
+ * @returns {string} lock file path
94
+ */
95
+ export function acquireChangeMutex(changeDirPath, opts = {}) {
96
+ const baseDir = opts.lockDir || changeDirPath;
97
+ fs.mkdirSync(baseDir, { recursive: true });
98
+ const lockPath = path.join(baseDir, '.run.lock');
99
+ const staleMs = opts.staleMs ?? DEFAULT_MUTEX_STALE_MS;
100
+ const payload = JSON.stringify({
101
+ pid: process.pid,
102
+ startedAt: Date.now(),
103
+ stage: opts.stage || 'auto',
104
+ });
105
+
106
+ const tryCreate = () => {
107
+ const fd = fs.openSync(lockPath, 'wx');
108
+ try {
109
+ fs.writeSync(fd, payload);
110
+ } finally {
111
+ fs.closeSync(fd);
112
+ }
113
+ return lockPath;
114
+ };
115
+
116
+ try {
117
+ return tryCreate();
118
+ } catch (err) {
119
+ if (err.code !== 'EEXIST') throw err;
120
+ let existing = null;
121
+ try {
122
+ existing = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
123
+ } catch {
124
+ existing = null;
125
+ }
126
+ const ageMs = existing?.startedAt ? Date.now() - Number(existing.startedAt) : 0;
127
+ if (!existing || ageMs > staleMs) {
128
+ try {
129
+ fs.unlinkSync(lockPath);
130
+ } catch {
131
+ // ignore race
132
+ }
133
+ return tryCreate();
134
+ }
135
+ throw new AsdlcError(
136
+ `Change lock already held at ${lockPath} (pid=${existing.pid}, stage=${existing.stage || 'unknown'}).`,
137
+ {
138
+ code: 'ASDLC_ERR_CHANGE_LOCKED',
139
+ hint: 'Wait for the active `asdlc run` process to finish or remove stale `.run.lock`.',
140
+ }
141
+ );
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Release a per-change mutex lock file created by `acquireChangeMutex`.
147
+ *
148
+ * @param {string|null|undefined} lockPath
149
+ */
150
+ export function releaseChangeMutex(lockPath) {
151
+ if (!lockPath) return;
152
+ try {
153
+ fs.unlinkSync(lockPath);
154
+ } catch (err) {
155
+ if (err.code !== 'ENOENT') throw err;
156
+ }
157
+ }
158
+
159
+ function readMetaFields(cdir) {
160
+ const metaPath = path.join(cdir, '.openspec.yaml');
161
+ if (!exists(metaPath)) return {};
162
+ const text = readText(metaPath);
163
+ const pick = (key) => {
164
+ const m = text.match(new RegExp(`^\\s*${key}:\\s*['"]?([^\\s'"]+)['"]?\\s*$`, 'm'));
165
+ return m ? m[1] : null;
166
+ };
167
+ return {
168
+ status: pick('status'),
169
+ specSha: pick('specSha'),
170
+ targetBranch: pick('targetBranch'),
171
+ level: pick('level'),
172
+ workflowMode: pick('workflowMode'),
173
+ };
174
+ }
175
+
176
+ function sanitizeResult(value, explicitSecrets = []) {
177
+ if (typeof value === 'string') return redactSecrets(value, explicitSecrets);
178
+ if (Array.isArray(value)) return value.map((item) => sanitizeResult(item, explicitSecrets));
179
+ if (value && typeof value === 'object') {
180
+ const out = {};
181
+ for (const [k, v] of Object.entries(value)) {
182
+ out[k] = sanitizeResult(v, explicitSecrets);
183
+ }
184
+ return out;
185
+ }
186
+ return value;
187
+ }
188
+
189
+ function resolvePrLabel(labels = []) {
190
+ const normalized = (labels || []).map((l) => (typeof l === 'string' ? l : l?.name || '')).filter(Boolean);
191
+ if (normalized.includes('asdlc:needs-clarification')) return 'needs-clarification';
192
+ if (normalized.includes('asdlc:spec-review')) return 'spec-review';
193
+ if (normalized.includes('asdlc:impl-review')) return 'impl-review';
194
+ return 'none';
195
+ }
196
+
197
+ function readChangeStateInputs(repoRoot, slug, opts = {}) {
198
+ const cdir = changeDir(repoRoot, slug);
199
+ const cdirExists = exists(cdir);
200
+ const meta = cdirExists ? readMetaFields(cdir) : {};
201
+ const targetBranch = (opts.targetBranch || meta.targetBranch || resolveDefaultBranch(repoRoot)).replace(/^origin\//, '');
202
+ const topology = opts.topology || (cdirExists
203
+ ? resolveTopology({ repoRoot, slug, baseRef: targetBranch, cliMode: opts.mode })
204
+ : { mode: opts.mode || 'supervised', isSinglePr: false });
205
+
206
+ const proposalExists = cdirExists && exists(path.join(cdir, 'proposal.md'));
207
+ const specsPath = path.join(cdir, 'specs');
208
+ const specFiles = exists(specsPath)
209
+ ? walkFiles(specsPath).filter((f) => f.endsWith('.md'))
210
+ : [];
211
+ const pSpec = proposalExists && specFiles.length > 0 ? 1 : 0;
212
+
213
+ const clarPath = path.join(cdir, 'clarifications.md');
214
+ let nOpen = 0;
215
+ if (exists(clarPath)) {
216
+ const clarText = readText(clarPath);
217
+ nOpen = (clarText.match(/\[OPEN\]/gi) ?? []).length;
218
+ }
219
+
220
+ const tasksPath = path.join(cdir, 'tasks.md');
221
+ let nTasks = 0;
222
+ let uTasks = 0;
223
+ if (exists(tasksPath)) {
224
+ const tasksText = readText(tasksPath);
225
+ const checked = (tasksText.match(/^\s*-\s+\[[xX]\]/gm) ?? []).length;
226
+ uTasks = (tasksText.match(/^\s*-\s+\[\s\]/gm) ?? []).length;
227
+ nTasks = checked + uTasks;
228
+ }
229
+
230
+ let rStage = null;
231
+ let rVerdict = null;
232
+ const reviewPath = path.join(cdir, 'review.md');
233
+ if (exists(reviewPath)) {
234
+ const revText = readText(reviewPath);
235
+ const st = revText.match(/\bstage\s*[:=]\s*['"]?(spec|impl)['"]?/i);
236
+ const vd = revText.match(/\bverdict\s*[:=]\s*['"]?(APPROVE|REQUEST_CHANGES)['"]?/i);
237
+ rStage = st ? st[1].toLowerCase() : null;
238
+ rVerdict = vd ? vd[1].toUpperCase() : null;
239
+ }
240
+
241
+ const pr = opts.prContext || {};
242
+ const prLabel = pr.label || resolvePrLabel(pr.labels);
243
+ const prState = pr.state ? String(pr.state).toUpperCase() : 'none';
244
+
245
+ const approvedOnBranch = changeOnRef(repoRoot, targetBranch, slug)
246
+ || changeOnRef(repoRoot, `origin/${targetBranch}`, slug)
247
+ || Boolean(lastCommitTouching(repoRoot, targetBranch, [`openspec/changes/${slug}/proposal.md`, `openspec/changes/${slug}/specs`]));
248
+ const isApproved = approvedOnBranch
249
+ || String(meta.status || '').toLowerCase() === 'ready_for_impl'
250
+ || (prLabel === 'spec-review' && prState === 'MERGED');
251
+
252
+ const lTarget = topology.isSinglePr
253
+ ? (pSpec === 1 ? 1 : 0)
254
+ : (isApproved ? 1 : 0);
255
+
256
+ const diffFiles = (git(['diff', '--name-only', `${targetBranch}...HEAD`], repoRoot, { allowFail: true }) ?? '')
257
+ .split(/\r?\n/)
258
+ .filter(Boolean);
259
+ const sCode = diffFiles.filter(
260
+ (f) => !f.startsWith(`openspec/changes/${slug}/`) && !f.startsWith('graphify-out/')
261
+ ).length;
262
+
263
+ return {
264
+ artifacts: { pSpec, nOpen, nTasks, uTasks, rStage, rVerdict },
265
+ gitLocks: { mode: topology.mode, isSinglePr: topology.isSinglePr, lTarget },
266
+ treeDiff: { sCode, targetBranch },
267
+ prMetadata: {
268
+ prLabel,
269
+ prState,
270
+ cReplied: pr.cReplied ? 1 : (Number(pr.humanReplyCount || 0) > 0 ? 1 : 0),
271
+ hFeedback: pr.hFeedback ? 1 : (pr.reviewDecision === 'CHANGES_REQUESTED' || Number(pr.unresolvedActionableCount || 0) > 0 ? 1 : 0),
272
+ roundsUsed: Number(pr.roundsUsed || 0),
273
+ },
274
+ verifyPassed: Boolean(opts.verifyPassed),
275
+ };
276
+ }
277
+
278
+ /**
279
+ * Evaluate the 4-Dimension Objective State Vector <Artifacts, GitLocks, TreeDiff, PRMetadata>
280
+ * against the 10-Phase State Matrix to derive the deterministic next pipeline phase & stage.
281
+ *
282
+ * @param {object} ctx
283
+ * @returns {{ phase: string, stage: string, reason: string, exitCleanly?: boolean, circuitBroken?: boolean, vector: object }}
284
+ */
285
+ export function evaluateStateVector(ctx = {}) {
286
+ const artifacts = {
287
+ pSpec: ctx.artifacts?.pSpec ?? 0,
288
+ nOpen: ctx.artifacts?.nOpen ?? 0,
289
+ nTasks: ctx.artifacts?.nTasks ?? 0,
290
+ uTasks: ctx.artifacts?.uTasks ?? 0,
291
+ rStage: ctx.artifacts?.rStage ?? null,
292
+ rVerdict: ctx.artifacts?.rVerdict ?? null,
293
+ };
294
+ const gitLocks = {
295
+ mode: ctx.gitLocks?.mode || 'supervised',
296
+ isSinglePr: Boolean(ctx.gitLocks?.isSinglePr),
297
+ lTarget: ctx.gitLocks?.lTarget ?? 0,
298
+ };
299
+ const treeDiff = {
300
+ sCode: ctx.treeDiff?.sCode ?? 0,
301
+ targetBranch: ctx.treeDiff?.targetBranch || 'main',
302
+ };
303
+ const prMetadata = {
304
+ prLabel: ctx.prMetadata?.prLabel || 'none',
305
+ prState: ctx.prMetadata?.prState || 'none',
306
+ cReplied: ctx.prMetadata?.cReplied ?? 0,
307
+ hFeedback: ctx.prMetadata?.hFeedback ?? 0,
308
+ roundsUsed: ctx.prMetadata?.roundsUsed ?? 0,
309
+ };
310
+ const verifyPassed = Boolean(ctx.verifyPassed);
311
+ const vector = { artifacts, gitLocks, treeDiff, prMetadata };
312
+
313
+ const out = (phase, stage, reason, extra = {}) => ({ phase, stage, reason, vector, ...extra });
314
+
315
+ // 1. PR-driven high-priority routes
316
+ if (prMetadata.prLabel === 'needs-clarification') {
317
+ if (prMetadata.cReplied === 1) {
318
+ return out('SPEC_GRILL_RESUME', 'spec', 'Draft PR has human replies resolving open clarifications');
319
+ }
320
+ return out('SPEC_GRILL_PAUSE', 'spec', 'Draft PR awaits human clarification replies', { exitCleanly: true });
321
+ }
322
+
323
+ if (prMetadata.hFeedback === 1 && (prMetadata.prState === 'OPEN' || prMetadata.prState === 'DRAFT')) {
324
+ if (prMetadata.roundsUsed >= 3) {
325
+ return out(
326
+ 'HUMAN_ARBITRATION_REQUIRED',
327
+ 'fix',
328
+ 'Anti-thrashing circuit breaker tripped after 3 unresolved review rounds',
329
+ { exitCleanly: true, circuitBroken: true }
330
+ );
331
+ }
332
+ if (prMetadata.prLabel === 'spec-review') {
333
+ return out('SPEC_HUMAN_REVIEW_FIX', 'fix', 'Open Spec PR has unresolved human review feedback');
334
+ }
335
+ return out('IMPL_HUMAN_REVIEW_FIX', 'fix', 'Open PR has unresolved human review feedback');
336
+ }
337
+
338
+ if (prMetadata.prLabel === 'spec-review' && prMetadata.prState === 'MERGED' && (artifacts.nTasks === 0 || artifacts.uTasks > 0)) {
339
+ return out('APPLY_TDD', 'apply', 'Spec PR merged on target branch; ready for TDD implementation');
340
+ }
341
+
342
+ if (prMetadata.prLabel === 'impl-review' && prMetadata.prState === 'MERGED') {
343
+ return out('READY_TO_ARCHIVE', 'verify', 'Implementation PR merged; ready to run `asdlc archive`', { exitCleanly: true });
344
+ }
345
+
346
+ // 2. Artifact + Git Lock deterministic vector progression
347
+ if (artifacts.pSpec === 0) {
348
+ return out('SPEC_DRAFT', 'spec', 'Specification artifacts (proposal.md / specs/**) not yet drafted');
349
+ }
350
+
351
+ if (artifacts.nOpen > 0) {
352
+ if (prMetadata.cReplied === 1) {
353
+ return out('SPEC_GRILL_RESUME', 'spec', 'Human clarification answers received; ready to settle [OPEN] items');
354
+ }
355
+ return out('SPEC_GRILL_PAUSE', 'spec', `${artifacts.nOpen} open clarification(s) remain`, { exitCleanly: true });
356
+ }
357
+
358
+ if (!gitLocks.isSinglePr && gitLocks.lTarget === 0) {
359
+ if (
360
+ prMetadata.prLabel === 'spec-review'
361
+ && prMetadata.prState === 'OPEN'
362
+ && artifacts.rStage === 'spec'
363
+ && artifacts.rVerdict === 'APPROVE'
364
+ && prMetadata.hFeedback === 0
365
+ ) {
366
+ return out('AWAITING_SPEC_MERGE', 'spec', 'Spec PR reviewed and awaiting human merge into target branch', { exitCleanly: true });
367
+ }
368
+ return out('SPEC_REVIEW', 'spec', 'Spec drafted with 0 [OPEN] markers; awaiting lint & Spec PR review');
369
+ }
370
+
371
+ if (gitLocks.lTarget === 1 && (artifacts.nTasks === 0 || artifacts.uTasks > 0)) {
372
+ return out('APPLY_TDD', 'apply', 'Spec locked on target branch with unchecked/missing tasks');
373
+ }
374
+
375
+ if (gitLocks.lTarget === 1 && artifacts.nTasks > 0 && artifacts.uTasks === 0) {
376
+ if (verifyPassed && artifacts.rStage === 'impl' && prMetadata.hFeedback === 0) {
377
+ if (prMetadata.prLabel !== 'impl-review') {
378
+ return out('OPEN_IMPL_PR', 'verify', 'All tasks and verification gates passed; ready to open Implementation PR');
379
+ }
380
+ return out('AWAITING_IMPL_MERGE', 'verify', 'Implementation PR verified and awaiting human merge', { exitCleanly: true });
381
+ }
382
+ return out('IMPL_REVIEW_AND_VERIFY', 'verify', 'All tasks checked; running independent impl review and verification gates');
383
+ }
384
+
385
+ return out('SPEC_DRAFT', 'spec', 'Default initial spec phase');
386
+ }
387
+
388
+ function parsePrReference(target) {
389
+ if (!target) return null;
390
+ const s = String(target).trim();
391
+ const hashMatch = s.match(/^#(\d+)$/);
392
+ if (hashMatch) return Number(hashMatch[1]);
393
+ const urlMatch = s.match(/\/(?:pull|merge_requests)\/(\d+)(?:[/?#]|$)/);
394
+ if (urlMatch) return Number(urlMatch[1]);
395
+ return null;
396
+ }
397
+
398
+ function extractSlugFromBranchName(branchName) {
399
+ const b = String(branchName || '').trim();
400
+ const m = b.match(/^(?:change|spec|impl|feat|fix)\/([a-z0-9._-]+)$/i);
401
+ return m ? toChangeSlug(m[1]) : null;
402
+ }
403
+
404
+ function listActiveChangeSlugs(repoRoot) {
405
+ const changesRoot = path.join(openspecDir(repoRoot), 'changes');
406
+ if (!exists(changesRoot)) return [];
407
+ return fs.readdirSync(changesRoot, { withFileTypes: true })
408
+ .filter((d) => d.isDirectory() && d.name !== 'archive')
409
+ .map((d) => d.name);
410
+ }
411
+
412
+ function extractSlugFromPrMetadata(prMeta, activeSlugs = []) {
413
+ if (!prMeta) return null;
414
+ const labels = (prMeta.labels || []).map((l) => (typeof l === 'string' ? l : l?.name || '')).filter(Boolean);
415
+ for (const label of labels) {
416
+ const m = label.match(/^asdlc:change-id:\s*(.+)$/i);
417
+ if (m) return toChangeSlug(m[1].trim());
418
+ }
419
+ const fromBranch = extractSlugFromBranchName(prMeta.headRefName || prMeta.head?.ref || '');
420
+ if (fromBranch) return fromBranch;
421
+ for (const s of activeSlugs) {
422
+ if (String(prMeta.title || '').toLowerCase().includes(s.toLowerCase())) {
423
+ return s;
424
+ }
425
+ }
426
+ return null;
427
+ }
428
+
429
+ function inferActiveSlug(repoRoot, opts = {}) {
430
+ const active = listActiveChangeSlugs(repoRoot);
431
+ if (active.length === 0) return null;
432
+
433
+ // Priority 1: Current git branch name (`change/<slug>`, `spec/<slug>`, `impl/<slug>`, etc.)
434
+ const headBranch = git(['rev-parse', '--abbrev-ref', 'HEAD'], repoRoot, { allowFail: true });
435
+ const branchSlug = extractSlugFromBranchName(headBranch);
436
+ if (branchSlug && active.includes(branchSlug)) {
437
+ return branchSlug;
438
+ }
439
+
440
+ // Priority 2: Single active change in workspace
441
+ if (active.length === 1) return active[0];
442
+
443
+ // Priority 3: Disambiguate multiple active changes via callback or fail explicitly
444
+ if (typeof opts.changeSelector === 'function') {
445
+ const picked = opts.changeSelector(active);
446
+ if (picked && active.includes(picked)) return picked;
447
+ }
448
+
449
+ fail(`Multiple active changes found (${active.join(', ')}). Specify a change ID, e.g. \`asdlc run ${active[0]}\`.`, {
450
+ code: 'MULTIPLE_ACTIVE_CHANGES',
451
+ hint: `Active changes: ${active.join(', ')}`,
452
+ });
453
+ }
454
+
455
+ function formatPauseBanner(reason, resumeCmd) {
456
+ return `⏸️ Paused: ${reason}\n 👉 Resume command: ${resumeCmd}`;
457
+ }
458
+
459
+ function collectRepeatable(val, prev = []) {
460
+ return [...prev, val];
461
+ }
462
+
463
+ function mergeOptsList(...lists) {
464
+ const out = [];
465
+ for (const list of lists) {
466
+ if (Array.isArray(list)) out.push(...list.filter(Boolean));
467
+ else if (list) out.push(list);
468
+ }
469
+ return out;
470
+ }
471
+
472
+ /**
473
+ * Orchestrate autonomous or local-symmetrical SDLC stage execution (`spec`, `apply`, `verify`, `fix`).
474
+ *
475
+ * @param {string|null|undefined} target - Change ID, natural language requirement, `#N` PR number, or PR URL.
476
+ * @param {object} [opts]
477
+ * @returns {Promise<object>}
478
+ */
479
+ export async function runPipeline(target, opts = {}) {
480
+ const explicitStage = normalizeStage(opts.stage);
481
+ const env = opts.env || process.env;
482
+
483
+ // Resolve remote host/repo if `--repo` is provided (enforces intranet zero-guessing policy)
484
+ let hostRepo = null;
485
+ if (opts.repo) {
486
+ hostRepo = resolveGitHostAndRepo({ repo: opts.repo, host: opts.host });
487
+ }
488
+
489
+ const workDir = path.resolve(opts.repoRoot || opts.cwd || process.cwd());
490
+ const lifecycleInfo = opts.repo
491
+ ? { lifecycle: 'remote', isGitRepo: false, hasOpenspec: false }
492
+ : detectRepoLifecycle(workDir);
493
+
494
+ if (lifecycleInfo.lifecycle === 'greenfield' && !opts.createRepo && !opts.repo) {
495
+ assertGitRepositoryInitialized(workDir, { repo: opts.repo, createRepo: opts.createRepo });
496
+ }
497
+
498
+ // Pre-Ingestion Secret Scan Guard (runs on local workspace before container/AI execution)
499
+ if (!opts.skipSecretScan && lifecycleInfo.isGitRepo) {
500
+ preScanWorkspaceForSecrets(workDir, { diffText: opts.diffText });
501
+ }
502
+
503
+ const fromFiles = mergeOptsList(opts.fromFile, opts.file);
504
+ const fromIssues = mergeOptsList(opts.fromIssue, opts.ticket, opts.issue);
505
+ const globalConfig = opts.globalConfig || loadGlobalConfig();
506
+ const passthroughEnv = resolvePassthroughEnv(globalConfig, env);
507
+ const mergedEnv = { ...passthroughEnv, ...env };
508
+
509
+ const prNumber = parsePrReference(target);
510
+ const repoRoot = lifecycleInfo.isGitRepo && lifecycleInfo.hasOpenspec ? workDir : (opts.repoRoot ? path.resolve(opts.repoRoot) : workDir);
511
+
512
+ // Resolve credentials & agent harness config when container or dry-run planning is requested
513
+ const creds = await resolveGitCredentials({ env: mergedEnv, globalConfig, host: hostRepo?.host, fetchFn: opts.fetchFn });
514
+ const authSource = creds?.type || 'none';
515
+ const explicitSecrets = creds?.token ? [creds.token] : [];
516
+ if (globalConfig?.agent?.api_key) explicitSecrets.push(globalConfig.agent.api_key);
517
+ if (mergedEnv?.JIRA_API_TOKEN) explicitSecrets.push(mergedEnv.JIRA_API_TOKEN);
518
+
519
+ const harness = resolveAgentHarnessConfig({
520
+ globalConfig,
521
+ cliModel: opts.model,
522
+ cliReviewModel: opts.reviewModel,
523
+ env: mergedEnv,
524
+ });
525
+
526
+ // Determine target change slug if possible (active branch, single change, selector, PR metadata, issue ID)
527
+ let slug = null;
528
+ if (!prNumber && target) {
529
+ const candidate = toChangeSlug(target);
530
+ if (exists(changeDir(repoRoot, candidate))) {
531
+ slug = candidate;
532
+ } else if (fromIssues.length && lifecycleInfo.hasOpenspec) {
533
+ slug = findChangeByIssueId(repoRoot, fromIssues[0]) || null;
534
+ }
535
+ } else if (prNumber) {
536
+ const activeSlugs = lifecycleInfo.hasOpenspec ? listActiveChangeSlugs(repoRoot) : [];
537
+ let prMeta = opts.prContext || null;
538
+ if (!prMeta && typeof opts.prMetadataResolver === 'function') {
539
+ prMeta = await opts.prMetadataResolver(prNumber, { repo: opts.repo, host: opts.host, env: mergedEnv });
540
+ } else if (!prMeta && lifecycleInfo.isGitRepo) {
541
+ try {
542
+ const ghRes = spawnSync('gh', ['pr', 'view', String(prNumber), '--json', 'number,title,headRefName,labels,state'], {
543
+ cwd: repoRoot,
544
+ encoding: 'utf8',
545
+ env: mergedEnv,
546
+ timeout: 8000,
547
+ });
548
+ if (ghRes.status === 0 && ghRes.stdout) {
549
+ prMeta = JSON.parse(ghRes.stdout);
550
+ }
551
+ } catch {
552
+ // offline fallback
553
+ }
554
+ }
555
+ slug = (prMeta?.changeId ? toChangeSlug(prMeta.changeId) : null)
556
+ || extractSlugFromPrMetadata(prMeta, activeSlugs);
557
+ if (!slug && !opts.dryRun && explicitStage !== 'spec') {
558
+ fail(`Could not resolve active change associated with PR #${prNumber}.`, {
559
+ code: 'ASDLC_ERR_PR_NOT_FOUND',
560
+ hint: `Ensure PR #${prNumber} has label 'asdlc:change-id: <slug>' or branch 'spec/<slug>' / 'impl/<slug>'.`,
561
+ });
562
+ }
563
+ } else if (opts.prContext?.changeId) {
564
+ slug = toChangeSlug(opts.prContext.changeId);
565
+ } else if (fromIssues.length && lifecycleInfo.hasOpenspec) {
566
+ slug = findChangeByIssueId(repoRoot, fromIssues[0]) || null;
567
+ } else if (!target && lifecycleInfo.hasOpenspec) {
568
+ slug = inferActiveSlug(repoRoot, { changeSelector: opts.changeSelector });
569
+ }
570
+
571
+ let vectorResult = null;
572
+ if (slug && lifecycleInfo.isGitRepo && lifecycleInfo.hasOpenspec) {
573
+ const inputs = readChangeStateInputs(repoRoot, slug, opts);
574
+ vectorResult = evaluateStateVector(inputs);
575
+ } else if (opts.prContext) {
576
+ vectorResult = evaluateStateVector({
577
+ artifacts: opts.prContext.artifacts,
578
+ gitLocks: opts.prContext.gitLocks,
579
+ treeDiff: opts.prContext.treeDiff,
580
+ prMetadata: {
581
+ prLabel: resolvePrLabel(opts.prContext.labels),
582
+ prState: opts.prContext.state || 'OPEN',
583
+ cReplied: opts.prContext.cReplied ? 1 : 0,
584
+ hFeedback: opts.prContext.hFeedback ? 1 : 0,
585
+ roundsUsed: Number(opts.prContext.roundsUsed || 0),
586
+ },
587
+ verifyPassed: opts.verifyPassed,
588
+ });
589
+ } else {
590
+ vectorResult = evaluateStateVector({});
591
+ }
592
+
593
+ const selectedStage = explicitStage || vectorResult.stage;
594
+
595
+ if (!explicitStage && !opts.json) {
596
+ log.info(`No --stage specified. Auto-selected stage: '${selectedStage}' (${vectorResult.phase}).`);
597
+ log.info(dim(`You can run this stage explicitly: asdlc run ${target || slug || '<target>'} --stage ${selectedStage}`));
598
+ }
599
+
600
+ const isContainerRun = Boolean(opts.container || opts.engine);
601
+
602
+ // Container dry-run mode returns the hardened execution plan without running Docker / Podman
603
+ if (isContainerRun && opts.dryRun) {
604
+ let resolvedEngine = 'docker';
605
+ try {
606
+ resolvedEngine = resolveContainerEngine(opts, spawnSync);
607
+ } catch {
608
+ resolvedEngine = opts.engine || 'docker';
609
+ }
610
+ const containerArgs = buildContainerCreateArgs({
611
+ engine: resolvedEngine,
612
+ image: opts.image,
613
+ hostEnv: mergedEnv,
614
+ caCertHostPath: opts.caCertHostPath,
615
+ sshAuthSock: opts.sshAuthSock,
616
+ sshAgent: Boolean(globalConfig?.git?.ssh_agent || opts.sshAgent),
617
+ sshKeyPath: opts.sshKeyPath || globalConfig?.git?.ssh_key_path,
618
+ env: {
619
+ ...passthroughEnv,
620
+ ASDLC_LIFECYCLE: lifecycleInfo.lifecycle,
621
+ ASDLC_STAGE: selectedStage,
622
+ ASDLC_AUTH_SOURCE: authSource,
623
+ ...(harness.model ? { ASDLC_MODEL: harness.model } : {}),
624
+ ...(harness.reviewModel ? { ASDLC_REVIEW_MODEL: harness.reviewModel } : {}),
625
+ },
626
+ cmd: ['asdlc', 'run', ...(target ? [String(target)] : []), '--stage', selectedStage],
627
+ });
628
+ const plan = sanitizeResult({
629
+ dryRun: true,
630
+ container: true,
631
+ engine: resolvedEngine,
632
+ lifecycle: lifecycleInfo.lifecycle,
633
+ hostRepo,
634
+ slug,
635
+ prNumber,
636
+ selectedStage,
637
+ phase: vectorResult.phase,
638
+ stateVector: vectorResult.vector,
639
+ authSource,
640
+ passthroughKeys: Object.keys(passthroughEnv),
641
+ harnessConfig: {
642
+ configSource: harness.configSource,
643
+ model: harness.model,
644
+ reviewModel: harness.reviewModel,
645
+ },
646
+ containerArgs,
647
+ dockerArgs: containerArgs, // Backwards-compatible alias
648
+ }, explicitSecrets);
649
+ if (opts.json) jsonOut(plan);
650
+ return plan;
651
+ }
652
+
653
+ // Full Container Execution Mode
654
+ if (isContainerRun && !opts.dryRun) {
655
+ log.step(`Launching container pipeline (${opts.image || DEFAULT_RUNNER_IMAGE})...`);
656
+ const containerResult = await runContainerPipeline(target, {
657
+ ...opts,
658
+ engine: opts.engine,
659
+ slug,
660
+ prNumber,
661
+ stage: selectedStage,
662
+ repoRoot,
663
+ env: mergedEnv,
664
+ harness,
665
+ creds,
666
+ sshAuthSock: opts.sshAuthSock,
667
+ sshAgent: Boolean(globalConfig?.git?.ssh_agent || opts.sshAgent),
668
+ sshKeyPath: opts.sshKeyPath || globalConfig?.git?.ssh_key_path,
669
+ });
670
+ const safeContainerResult = sanitizeResult({
671
+ container: true,
672
+ slug,
673
+ prNumber,
674
+ stage: selectedStage,
675
+ ...containerResult,
676
+ }, explicitSecrets);
677
+ if (opts.json) jsonOut(safeContainerResult);
678
+ return safeContainerResult;
679
+ }
680
+
681
+ // Zero-flag context inference: determine if AI agent execution is mandatory
682
+ // When opts.ci is explicitly false, it suppresses CI autodetection (e.g. running in local test harnesses under CI runners)
683
+ const isCiExplicitFalse = opts.ci === false;
684
+ const isCiEnv = !isCiExplicitFalse && Boolean(opts.ci || mergedEnv?.CI === 'true' || mergedEnv?.GITHUB_ACTIONS === 'true');
685
+ const isContainerEnv = Boolean(isContainerRun || mergedEnv?.ASDLC_CONTAINER === '1' || mergedEnv?.ASDLC_IN_CONTAINER === '1');
686
+ const hasExplicitModelOverride = Boolean(opts.model || opts.reviewModel || opts.agentConfig);
687
+ const isMandatoryAgentEnv = Boolean(isContainerEnv || isCiEnv || hasExplicitModelOverride || opts.autonomous);
688
+
689
+ const harnessBin = harness.harness;
690
+ const whichFn = typeof opts.whichCommand === 'function' ? opts.whichCommand : whichCommand;
691
+ const resolvedHarnessBin = whichFn(harnessBin);
692
+ const hasHarnessCli = Boolean(resolvedHarnessBin);
693
+
694
+ const runDefaultAgent = async ({ prompt, model, type = 'author' }) => {
695
+ if (!hasHarnessCli) return null;
696
+ if (typeof opts.agentRunner === 'function') {
697
+ return opts.agentRunner({ harness: harnessBin, prompt, model, type, repoRoot, env: mergedEnv });
698
+ }
699
+ const buildArgs = type === 'reviewer' ? harness.buildReviewerArgs : harness.buildAuthorArgs;
700
+ const args = buildArgs(prompt, model);
701
+ try {
702
+ const isWin = process.platform === 'win32';
703
+ const cmdToRun = isWin && (resolvedHarnessBin.endsWith('.cmd') || resolvedHarnessBin.endsWith('.bat'))
704
+ ? resolvedHarnessBin
705
+ : harnessBin;
706
+ const res = spawnSync(cmdToRun, args, { cwd: repoRoot, stdio: opts.stdio || 'inherit', env: mergedEnv, shell: isWin });
707
+ return { ok: res && res.status === 0, status: res && res.status === 0 ? 'completed' : 'failed', exitCode: res?.status };
708
+ } catch (err) {
709
+ return { ok: false, status: 'error', error: err.message };
710
+ }
711
+ };
712
+
713
+ // Ensure slug exists or can be scaffolded for `--stage spec`
714
+ if (!slug && selectedStage === 'spec') {
715
+ if (!target && !fromFiles.length && !fromIssues.length) {
716
+ fail('Cannot start `spec` stage without a requirement, change ID, `--from-file`, or `--from-issue`/`--ticket`.');
717
+ }
718
+ slug = newChange(target || null, {
719
+ repoRoot,
720
+ fromFile: fromFiles,
721
+ fromIssue: fromIssues,
722
+ grill: false,
723
+ openspec: opts.openspec ?? false,
724
+ mode: opts.mode,
725
+ targetBranch: opts.targetBranch,
726
+ issueFetcher: opts.issueFetcher,
727
+ ghRunner: opts.ghRunner,
728
+ httpFetcher: opts.httpFetcher,
729
+ env: mergedEnv,
730
+ globalConfig,
731
+ });
732
+ }
733
+
734
+ const cdir = slug ? changeDir(repoRoot, slug) : null;
735
+ let lockPath = null;
736
+ if (cdir && exists(cdir)) {
737
+ lockPath = acquireChangeMutex(cdir, { stage: selectedStage, staleMs: opts.staleMs });
738
+ }
739
+
740
+ try {
741
+ let result;
742
+ const targetBranch = (opts.targetBranch || vectorResult.vector.treeDiff.targetBranch || 'main').replace(/^origin\//, '');
743
+
744
+ if (selectedStage === 'spec') {
745
+ const clarPath = cdir ? path.join(cdir, 'clarifications.md') : null;
746
+ const openFound = clarPath && exists(clarPath) && hasUnresolvedClarifications(readText(clarPath));
747
+
748
+ if (openFound) {
749
+ const hasReplies = Boolean(opts.prContext?.cReplied || opts.prContext?.comments?.length);
750
+ if (hasReplies && typeof opts.onResumeClarifications === 'function') {
751
+ await opts.onResumeClarifications({ slug, cdir, prContext: opts.prContext });
752
+ } else {
753
+ let prInfo = null;
754
+ if (!opts.skipPr) {
755
+ if (typeof opts.createDraftPr === 'function') {
756
+ prInfo = await opts.createDraftPr({ slug, targetBranch, label: 'asdlc:needs-clarification' });
757
+ } else if (lifecycleInfo.isGitRepo) {
758
+ prInfo = await createPR(slug, targetBranch, {
759
+ repoRoot,
760
+ mode: opts.mode,
761
+ env: mergedEnv,
762
+ fetchFn: opts.fetchFn,
763
+ draft: true,
764
+ skipPush: opts.skipPush,
765
+ skipCliPr: opts.skipCliPr,
766
+ skipOpenspec: opts.skipOpenspec,
767
+ skipExternal: opts.skipExternal,
768
+ });
769
+ }
770
+ }
771
+ const prNumLabel = prInfo?.number ? `#${prInfo.number}` : slug;
772
+ const resumeCmd = `asdlc run ${prNumLabel}${opts.container ? ' --container' : ''}`;
773
+ const pauseBanner = formatPauseBanner(
774
+ `Awaiting human replies on Draft Spec PR ${prNumLabel} for '${slug}' ([OPEN] clarifications remain).`,
775
+ resumeCmd
776
+ );
777
+ if (!opts.json) log.info(pauseBanner);
778
+ result = {
779
+ slug,
780
+ stage: 'spec',
781
+ phase: hasReplies ? 'SPEC_GRILL_RESUME' : 'SPEC_GRILL_PAUSE',
782
+ paused: !hasReplies,
783
+ prLabel: 'asdlc:needs-clarification',
784
+ pauseBanner,
785
+ exitCode: 0,
786
+ pr: prInfo,
787
+ };
788
+ if (opts.json) jsonOut(sanitizeResult(result, explicitSecrets));
789
+ return result;
790
+ }
791
+ }
792
+
793
+ const lintExitCode = runLint(slug, { repoRoot });
794
+ const lintResult = { pass: lintExitCode === 0, exitCode: lintExitCode };
795
+ if (!lintResult.pass) {
796
+ fail(`Spec lint failed for '${slug}'. Fix blocking findings before opening Spec PR.`);
797
+ }
798
+ let reviewResult = null;
799
+ if (typeof opts.specReviewer === 'function') {
800
+ reviewResult = await opts.specReviewer({ slug, cdir, repoRoot, reviewModel: harness.reviewModel });
801
+ } else if (hasHarnessCli) {
802
+ log.step(`Running spec review via ${harnessBin}...`);
803
+ const prompt = `Review specification for change ${slug} in ${cdir}. Validate BDD acceptance criteria.`;
804
+ const res = await runDefaultAgent({ prompt, model: harness.reviewModel, type: 'reviewer' });
805
+ reviewResult = { status: res?.ok ? 'passed' : 'failed', summary: `Spec review via ${harnessBin}` };
806
+ } else if (isMandatoryAgentEnv) {
807
+ fail('Autonomous/CI spec stage requires an AI review agent harness.', {
808
+ code: 'ASDLC_ERR_AGENT_UNAVAILABLE',
809
+ hint: `Ensure '${harnessBin}' is installed and accessible in PATH.`,
810
+ });
811
+ } else {
812
+ if (!opts.json) log.info(`[INFO] Local AI CLI (${harnessBin}) not found in PATH; executed deterministic gates only.`);
813
+ reviewResult = { status: 'skipped', summary: `Local AI CLI (${harnessBin}) not found in PATH; executed deterministic gates only (human review on PR)` };
814
+ }
815
+ let prResult = null;
816
+ if (!opts.skipPr) {
817
+ prResult = await createPR(slug, targetBranch, {
818
+ repoRoot,
819
+ mode: opts.mode,
820
+ env,
821
+ fetchFn: opts.fetchFn,
822
+ skipPush: opts.skipPush,
823
+ skipCliPr: opts.skipCliPr,
824
+ skipOpenspec: opts.skipOpenspec,
825
+ skipExternal: opts.skipExternal,
826
+ draft: opts.draft,
827
+ });
828
+ }
829
+ result = {
830
+ slug,
831
+ stage: 'spec',
832
+ phase: 'SPEC_REVIEW',
833
+ lint: lintResult,
834
+ review: reviewResult,
835
+ pr: prResult,
836
+ exitCode: 0,
837
+ };
838
+ } else if (selectedStage === 'apply') {
839
+ if (!slug || !cdir || !exists(cdir)) {
840
+ fail(`Change '${slug || target}' not found for 'apply' stage.`);
841
+ }
842
+ const guard = applyGuard(slug, { repoRoot, targetBranch, mode: opts.mode });
843
+ const lockedSpecPaths = lockSpecsReadOnly(cdir);
844
+ let implOutput = null;
845
+ if (typeof opts.implExecutor === 'function') {
846
+ implOutput = await opts.implExecutor({ slug, cdir, repoRoot, lockedSpecPaths, model: harness.model });
847
+ } else if (hasHarnessCli) {
848
+ log.step(`Running implementation via ${harnessBin}...`);
849
+ const prompt = `Implement change ${slug} following TDD workflow in ${cdir}/tasks.md without modifying locked spec files.`;
850
+ const res = await runDefaultAgent({ prompt, model: harness.model, type: 'author' });
851
+ implOutput = { status: res?.ok ? 'implemented' : 'failed', summary: `Implementation via ${harnessBin}` };
852
+ } else if (isMandatoryAgentEnv) {
853
+ fail('Autonomous/CI apply stage requires an AI implementation agent.', {
854
+ code: 'ASDLC_ERR_AGENT_UNAVAILABLE',
855
+ hint: `Ensure '${harnessBin}' is installed and accessible in PATH to run TDD implementation.`,
856
+ });
857
+ } else {
858
+ if (!opts.json) log.info(`[INFO] Local AI CLI (${harnessBin}) not found in PATH; executed deterministic gates only.`);
859
+ implOutput = { status: 'waiting_for_implementation', message: 'Spec locked 0444 read-only. Implement tasks in tasks.md, then run asdlc verify.' };
860
+ }
861
+ result = {
862
+ slug,
863
+ stage: 'apply',
864
+ phase: 'APPLY_TDD',
865
+ guard,
866
+ lockedSpecPaths,
867
+ implOutput,
868
+ exitCode: 0,
869
+ };
870
+ } else if (selectedStage === 'verify') {
871
+ if (!slug || !cdir || !exists(cdir)) {
872
+ fail(`Change '${slug || target}' not found for 'verify' stage.`);
873
+ }
874
+ let implReview = null;
875
+ if (typeof opts.implReviewer === 'function') {
876
+ implReview = await opts.implReviewer({ slug, cdir, repoRoot, reviewModel: harness.reviewModel });
877
+ } else if (hasHarnessCli) {
878
+ log.step(`Running implementation review via ${harnessBin}...`);
879
+ const prompt = `Review implementation for change ${slug} in ${repoRoot}. Verify against approved spec in ${cdir}.`;
880
+ const res = await runDefaultAgent({ prompt, model: harness.reviewModel, type: 'reviewer' });
881
+ implReview = { status: res?.ok ? 'passed' : 'failed', summary: `Implementation review via ${harnessBin}` };
882
+ } else if (isMandatoryAgentEnv) {
883
+ fail('Autonomous/CI verify stage requires an independent AI reviewer.', {
884
+ code: 'ASDLC_ERR_AGENT_UNAVAILABLE',
885
+ hint: `Ensure '${harnessBin}' is installed and accessible in PATH.`,
886
+ });
887
+ } else {
888
+ if (!opts.json) log.info(`[INFO] Local AI CLI (${harnessBin}) not found in PATH; executed deterministic gates only.`);
889
+ implReview = { status: 'skipped', summary: `Local AI CLI (${harnessBin}) not found in PATH; independent AI reviewer not configured` };
890
+ }
891
+ const verifyExitCode = runVerify(slug, {
892
+ repoRoot,
893
+ protectedBranch: targetBranch,
894
+ base: targetBranch,
895
+ mode: opts.mode,
896
+ ci: opts.ci,
897
+ approved: opts.approved,
898
+ skipOpenspec: opts.skipOpenspec,
899
+ skipExternal: opts.skipExternal,
900
+ });
901
+ const verifyResult = { pass: verifyExitCode === 0, exitCode: verifyExitCode };
902
+ let prResult = null;
903
+ if (!opts.skipPr && verifyResult.pass) {
904
+ prResult = await createPR(slug, targetBranch, {
905
+ repoRoot,
906
+ mode: opts.mode,
907
+ env,
908
+ fetchFn: opts.fetchFn,
909
+ skipPush: opts.skipPush,
910
+ skipCliPr: opts.skipCliPr,
911
+ skipOpenspec: opts.skipOpenspec,
912
+ skipExternal: opts.skipExternal,
913
+ });
914
+ }
915
+ result = {
916
+ slug,
917
+ stage: 'verify',
918
+ phase: verifyResult.pass ? 'OPEN_IMPL_PR' : 'IMPL_REVIEW_AND_VERIFY',
919
+ review: implReview,
920
+ verify: verifyResult,
921
+ pr: prResult,
922
+ exitCode: verifyResult.pass ? 0 : 1,
923
+ };
924
+ } else if (selectedStage === 'fix') {
925
+ const prCtx = typeof opts.fetchPrContext === 'function'
926
+ ? await opts.fetchPrContext({ prNumber, slug, target })
927
+ : (opts.prContext || (prNumber ? await fetchGitHubPrReviewContext(prNumber, { repoRoot, repo: opts.repo, host: opts.host, env: mergedEnv, fetchFn: opts.fetchFn }) : {}));
928
+ const rawThreads = prCtx.reviewThreads || prCtx.threads || [];
929
+ const currentRound = Number(
930
+ prCtx.currentRound
931
+ ?? (prCtx.roundsUsed !== undefined
932
+ ? Number(prCtx.roundsUsed) + 1
933
+ : (opts.roundsUsed !== undefined ? Number(opts.roundsUsed) + 1 : 1))
934
+ );
935
+ const cb = checkAntiThrashingCircuitBreaker({
936
+ currentRound,
937
+ maxRounds: 3,
938
+ unresolvedThreads: rawThreads,
939
+ changeId: slug || 'unknown',
940
+ prNumber,
941
+ });
942
+
943
+ if (cb.tripped) {
944
+ result = {
945
+ slug,
946
+ prNumber,
947
+ stage: 'fix',
948
+ phase: 'HUMAN_ARBITRATION_REQUIRED',
949
+ circuitBroken: true,
950
+ escalationLabel: cb.label || 'asdlc:needs-human-arbitration',
951
+ synthesisReport: cb.synthesisReport,
952
+ exitCode: cb.exitCode ?? 2,
953
+ };
954
+ if (opts.json) jsonOut(sanitizeResult(result, explicitSecrets));
955
+ return result;
956
+ }
957
+
958
+ const triage = triagePullRequest({
959
+ reviewThreads: rawThreads,
960
+ issueComments: prCtx.issueComments || prCtx.topLevelComments || [],
961
+ reviewDecision: prCtx.reviewDecision || null,
962
+ commitMessages: prCtx.commitMessages || [],
963
+ agentLogins: prCtx.agentLogins || prCtx.botLogins || [],
964
+ });
965
+ // §6.3.4: Category C questions must NEVER be resolved automatically
966
+ const actionablePlan = [
967
+ ...triage.actionableThreads,
968
+ ...triage.suggestionThreads,
969
+ ].map((t) => buildThreadResolutionPlan(t, { commitSha: opts.commitSha }));
970
+
971
+ let fixOutput = null;
972
+ if (typeof opts.fixExecutor === 'function') {
973
+ fixOutput = await opts.fixExecutor({ slug, prNumber, triage, plan: actionablePlan, repoRoot });
974
+ } else if (hasHarnessCli && actionablePlan.length > 0) {
975
+ log.step(`Running review comment fixes via ${harnessBin}...`);
976
+ const preHeadSha = headSha(repoRoot);
977
+ const prompt = `Address review feedback on PR #${prNumber}: ${actionablePlan.map((p) => p.commentBody).filter(Boolean).join('; ')}`;
978
+ const agentRes = await runDefaultAgent({ prompt, model: harness.model, type: 'author' });
979
+ const postHeadSha = headSha(repoRoot);
980
+ const autoCommitSha = (postHeadSha && postHeadSha !== preHeadSha) ? postHeadSha : null;
981
+ fixOutput = {
982
+ status: agentRes?.ok ? 'completed' : 'failed',
983
+ ok: agentRes?.ok,
984
+ commitSha: autoCommitSha,
985
+ };
986
+ } else if (isMandatoryAgentEnv && actionablePlan.length > 0) {
987
+ fail('Autonomous/CI fix stage requires an AI implementation agent.', {
988
+ code: 'ASDLC_ERR_AGENT_UNAVAILABLE',
989
+ hint: `Ensure '${harnessBin}' is installed and accessible in PATH to address review comments.`,
990
+ });
991
+ } else if (actionablePlan.length > 0) {
992
+ if (!opts.json) log.info(`[INFO] Local AI CLI (${harnessBin}) not found in PATH; review comments left for manual resolution.`);
993
+ }
994
+
995
+ // Threads may ONLY be resolved after a verified fix commit exists
996
+ const effectiveCommitSha = fixOutput?.commitSha || opts.commitSha;
997
+ const resolvedThreads = [];
998
+ if (effectiveCommitSha && fixOutput?.ok !== false && !opts.skipThreadResolution) {
999
+ for (const item of actionablePlan) {
1000
+ if (item.threadId) {
1001
+ const replyMsg = item.commitMessage
1002
+ ? `Applied suggestion in commit ${effectiveCommitSha.slice(0, 8)}:\n${item.commitMessage}`
1003
+ : `Resolved in commit ${effectiveCommitSha.slice(0, 8)}.`;
1004
+ const res = await replyAndResolveGitHubThread(item.threadId, replyMsg, {
1005
+ repoRoot,
1006
+ repo: opts.repo,
1007
+ host: opts.host,
1008
+ env: mergedEnv,
1009
+ fetchFn: opts.fetchFn,
1010
+ });
1011
+ resolvedThreads.push(res);
1012
+ }
1013
+ }
1014
+ }
1015
+
1016
+ result = {
1017
+ slug,
1018
+ prNumber,
1019
+ stage: 'fix',
1020
+ phase: vectorResult.phase === 'SPEC_HUMAN_REVIEW_FIX' ? 'SPEC_HUMAN_REVIEW_FIX' : 'IMPL_HUMAN_REVIEW_FIX',
1021
+ triage,
1022
+ resolutionPlan: actionablePlan,
1023
+ unresolvedQuestions: triage.questionThreads.length,
1024
+ fixOutput: fixOutput || {
1025
+ status: 'plan_generated',
1026
+ resolvedCount: resolvedThreads.length,
1027
+ reason: effectiveCommitSha ? 'Fix processed' : 'No fix commit executed; review threads remain open for agent/author',
1028
+ },
1029
+ resolvedThreads,
1030
+ exitCode: 0,
1031
+ };
1032
+ }
1033
+
1034
+ const safeResult = sanitizeResult(result, explicitSecrets);
1035
+ if (opts.json) jsonOut(safeResult);
1036
+ return safeResult;
1037
+ } finally {
1038
+ releaseChangeMutex(lockPath);
1039
+ }
1040
+ }
1041
+
1042
+ export function register(program) {
1043
+ program
1044
+ .command('run [target]')
1045
+ .description('orchestrate autonomous or stage-driven SDLC pipeline (spec | apply | verify | fix)')
1046
+ .option('--stage <stage>', 'explicit canonical stage: spec, apply, verify, or fix')
1047
+ .option('--repo <repo>', 'target repository (owner/repo or canonical full git URL for intranet/zero-checkout)')
1048
+ .option('--create-repo <repo>', 'provision a new remote repository in greenfield mode')
1049
+ .option('--host <host>', 'explicit git host when disambiguating enterprise hosts')
1050
+ .option('--from-file <path>', 'attach local requirement/PRD file snapshot (repeatable)', collectRepeatable, [])
1051
+ .option('--file <path>', 'alias for --from-file (repeatable)', collectRepeatable, [])
1052
+ .option('--from-issue <id>', 'attach external issue reference snapshot (repeatable)', collectRepeatable, [])
1053
+ .option('--ticket <id>', 'alias for --from-issue (repeatable)', collectRepeatable, [])
1054
+ .option('--issue <id>', 'alias for --from-issue (repeatable)', collectRepeatable, [])
1055
+ .option('--container', 'run in isolated hardened UID 10001:10001 container runtime')
1056
+ .option('--engine <engine>', 'container engine to use: docker | podman (default: auto)')
1057
+ .option('--dry-run', 'print deterministic execution & security plan without executing')
1058
+ .option('--mode <mode>', 'override workflow mode: spec-first | supervised | auto')
1059
+ .option('--target-branch <branch>', 'target protected branch (defaults to repo default)')
1060
+ .option('--agent-config <path>', 'enterprise opencode.json template path')
1061
+ .option('-m, --model <model>', 'override author AI model')
1062
+ .option('--review-model <model>', 'override independent reviewer AI model (Player != Referee)')
1063
+ .option('--json', 'emit redacted structured JSON output')
1064
+ .action(async (target, opts) => {
1065
+ const res = await runPipeline(target, opts);
1066
+ if (res && typeof res.exitCode === 'number' && res.exitCode !== 0) {
1067
+ process.exitCode = res.exitCode;
1068
+ }
1069
+ });
1070
+
1071
+ // First-class local CLI symmetry for addressing PR review feedback (Tier 1-3 triage)
1072
+ program
1073
+ .command('fix [target]')
1074
+ .alias('review-comments')
1075
+ .description('address PR review comments with Tier 1-3 triage & anti-thrashing circuit breaker')
1076
+ .option('--repo <repo>', 'target repository (owner/repo or canonical git URL)')
1077
+ .option('--host <host>', 'explicit git host when disambiguating enterprise hosts')
1078
+ .option('--mode <mode>', 'override workflow mode: spec-first | supervised | auto')
1079
+ .option('--target-branch <branch>', 'target protected branch (defaults to repo default)')
1080
+ .option('-m, --model <model>', 'override author AI model')
1081
+ .option('--json', 'emit redacted structured JSON output')
1082
+ .option('--repo-root <path>')
1083
+ .action(async (target, opts) => {
1084
+ const res = await runPipeline(target, { ...opts, stage: 'fix' });
1085
+ if (res && typeof res.exitCode === 'number' && res.exitCode !== 0) {
1086
+ process.exitCode = res.exitCode;
1087
+ }
1088
+ });
1089
+ }