@akjamie/agentic-sdlc 1.11.1 → 1.13.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.
@@ -1,17 +1,49 @@
1
1
  import path from 'node:path';
2
- import { spawnSync } from 'node:child_process';
3
2
  import { Option } from 'commander';
4
3
  import { exists, readText, writeText } from '../lib/fs.js';
5
4
  import { changeDir } from '../lib/paths.js';
6
- import { requireRepo, toChangeSlug, requireAgentRuntime } from '../lib/cliutil.js';
7
- import { lastCommitTouching, git, resolveDefaultBranch } from '../lib/git.js';
5
+ import { requireRepo, toChangeSlug, requireAgentRuntime, jsonOut } from '../lib/cliutil.js';
6
+ import { lastCommitTouching, git, resolveDefaultBranch, headSha } from '../lib/git.js';
8
7
  import { fail } from '../lib/errors.js';
9
8
  import { log } from '../lib/log.js';
10
9
  import { isSinglePrLevel, readEffectiveLevel } from '../lib/level.js';
11
10
  import { resolveWorkflowMode } from '../lib/config.js';
12
11
  import { assess } from '../assess/index.js';
13
- import { triagePullRequest, PULL_REQUEST_THREADS_QUERY } from '../lib/triage.js';
12
+ import {
13
+ triagePullRequest,
14
+ checkAntiThrashingCircuitBreaker,
15
+ buildThreadResolutionPlan,
16
+ } from '../lib/triage.js';
14
17
  import { recordEvent } from '../lib/telemetry.js';
18
+ import { generateTasksFromSpecs } from '../lib/tasks-gen.js';
19
+ import { createForgeAdapter } from '../lib/forge/index.js';
20
+
21
+ function loadPrCommitMessages(repoRoot, branch, emitWarn) {
22
+ let raw = git(['log', `${branch}..HEAD`, '--format=%B'], repoRoot, { allowFail: true });
23
+ if (raw === null) {
24
+ emitWarn(`commit range '${branch}..HEAD' unavailable; falling back to last 20 commits`);
25
+ raw = git(['log', '-n', '20', '--format=%B'], repoRoot, { allowFail: true }) || '';
26
+ }
27
+ return raw.split(/\r?\n\r?\n/).filter(Boolean);
28
+ }
29
+
30
+ function printTriageThreads(triage, prRef) {
31
+ const sections = [
32
+ ['SUGGESTION_BLOCK', triage.suggestionThreads],
33
+ ['ACTION_REQUIRED', triage.actionableThreads],
34
+ ['INFORMATIONAL_QUESTION', triage.questionThreads],
35
+ ];
36
+ for (const [label, threads] of sections) {
37
+ for (const t of threads) {
38
+ const loc = t.path ? `${t.path}${t.line ? `:${t.line}` : ''}` : 'PR';
39
+ const snippet = String(t.latestBody || t.body || '').replace(/\s+/g, ' ').slice(0, 140);
40
+ log.info(` [${label}] ${t.id || 'n/a'} (${loc}) @${t.latestAuthor || 'reviewer'}: ${snippet}`);
41
+ }
42
+ }
43
+ if (triage.unaddressedCount > 0) {
44
+ log.info(` -> After fixing & committing with '(ref: #<threadId>)', resolve via: asdlc apply <ID> --from-pr ${prRef} --resolve-thread <threadId>`);
45
+ }
46
+ }
15
47
 
16
48
  // Guard before implementing: the spec must be APPROVED on the target branch
17
49
  // (i.e. the Spec PR has been merged into targetBranch, locking proposal.md & specs/**).
@@ -84,6 +116,7 @@ export function applyGuard(changeId, opts = {}) {
84
116
  }
85
117
  }
86
118
 
119
+ const emit = (fn, msg) => { if (!opts.json) fn(msg); };
87
120
  const isSinglePr = isSinglePrLevel(effectiveLevel) && resolvedMode !== 'spec-first' && meta.workflowMode !== 'spec-first';
88
121
  let approvedSha = null;
89
122
 
@@ -98,9 +131,9 @@ export function applyGuard(changeId, opts = {}) {
98
131
  };
99
132
  metaText = upsertKey(metaText, 'status', 'ready_for_impl');
100
133
  writeText(metaPath, metaText);
101
- log.ok(`${slug}: marked status=ready_for_impl (no separate Spec PR in Single-PR mode; human sign-off happens on the final PR)`);
134
+ emit(log.ok, `${slug}: marked status=ready_for_impl (no separate Spec PR in Single-PR mode; human sign-off happens on the final PR)`);
102
135
  }
103
- log.ok(`${slug}: governance level is ${effectiveLevel} (Single PR mode: direct local implementation permitted)`);
136
+ emit(log.ok, `${slug}: governance level is ${effectiveLevel} (Single PR mode: direct local implementation permitted)`);
104
137
  } else {
105
138
  // L2 / L3 Two-phase Spec-first flow
106
139
  // 2. Multi-tenant path-isolated approval detection
@@ -150,7 +183,7 @@ export function applyGuard(changeId, opts = {}) {
150
183
  }
151
184
  writeText(metaPath, metaText);
152
185
  }
153
- log.ok(`${slug}: recognized PR approval on ${branch} (synced state to ready_for_impl @ ${approvedSha.slice(0, 8)})`);
186
+ emit(log.ok, `${slug}: recognized PR approval on ${branch} (synced state to ready_for_impl @ ${approvedSha.slice(0, 8)})`);
154
187
  }
155
188
  }
156
189
 
@@ -175,74 +208,56 @@ export function applyGuard(changeId, opts = {}) {
175
208
  writeText(metaPath, metaText);
176
209
  }
177
210
 
178
- // 7. Tasks checklist presence
211
+ // 7. Tasks checklist presence (auto-compile from spec ACs if missing)
179
212
  const tasksPath = path.join(cdir, 'tasks.md');
180
213
  if (!exists(tasksPath)) {
181
- fail(`'${slug}' missing tasks.md`, {
182
- code: 'TASKS_MISSING',
183
- hint: 'author tasks.md with TDD verification tasks before running apply',
184
- });
214
+ const gen = generateTasksFromSpecs(repoRoot, slug);
215
+ if (gen.generated) {
216
+ emit(log.ok, `auto-generated tasks.md (${gen.taskCount} TDD tasks from ${gen.acCount} spec AC(s))`);
217
+ } else {
218
+ fail(`'${slug}' missing tasks.md`, {
219
+ code: 'TASKS_MISSING',
220
+ hint: 'author tasks.md with TDD verification tasks (or add AC<n>: ... (test: <path>) to specs) before running apply',
221
+ });
222
+ }
185
223
  }
186
224
 
187
225
  const isAutoPr = opts.autoPr === true || (opts.autoPr === undefined && meta.autoPr === 'true');
188
226
  const shaDisplay = approvedSha ? ` (specSha: ${approvedSha.slice(0, 8)}, state: ready_for_impl)` : ` (state: ready_for_impl)`;
189
- log.ok(`${slug} is READY FOR IMPLEMENTATION on ${branch}${shaDisplay}`);
227
+ emit(log.ok, `${slug} is READY FOR IMPLEMENTATION on ${branch}${shaDisplay}`);
190
228
 
191
229
  if (opts.fromPr) {
192
230
  const prRef = String(opts.fromPr).replace(/^#/, '');
193
231
  const prNum = Number(prRef);
232
+ const forge = opts.forge || createForgeAdapter({ repoRoot });
194
233
  let prCtx = opts.prContext || null;
195
234
  if (!prCtx) {
196
- let reviewThreads = [];
197
- let reviewDecision = null;
198
- const remoteUrl = git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true }) || '';
199
- const repoMatch = remoteUrl.match(/[:/]([^/:\s]+)\/([^/:\s]+?)(?:\.git)?$/);
200
- if (repoMatch && Number.isFinite(prNum) && prNum > 0) {
201
- const gql = spawnSync('gh', [
202
- 'api', 'graphql',
203
- '-F', `owner=${repoMatch[1]}`,
204
- '-F', `repo=${repoMatch[2]}`,
205
- '-F', `number=${prNum}`,
206
- '-f', `query=${PULL_REQUEST_THREADS_QUERY}`,
207
- ], { cwd: repoRoot, encoding: 'utf8', timeout: 8000 });
208
- if (gql.status === 0 && gql.stdout) {
209
- try {
210
- const parsedGql = JSON.parse(gql.stdout);
211
- const prNode = parsedGql?.data?.repository?.pullRequest;
212
- reviewThreads = prNode?.reviewThreads?.nodes || [];
213
- reviewDecision = prNode?.reviewDecision || null;
214
- } catch {
215
- // fallback to view
216
- }
217
- }
218
- }
219
- const gh = spawnSync('gh', ['pr', 'view', prRef, '--json', 'comments,reviews,reviewDecision'], {
220
- cwd: repoRoot,
221
- encoding: 'utf8',
222
- timeout: 8000,
223
- });
224
- if (gh.status === 0 && gh.stdout) {
225
- try {
226
- const parsed = JSON.parse(gh.stdout);
227
- prCtx = {
228
- reviewThreads,
229
- issueComments: parsed.comments || [],
230
- reviewDecision: reviewDecision || parsed.reviewDecision || null,
231
- };
232
- } catch {
233
- prCtx = { reviewThreads, reviewDecision };
234
- }
235
- } else if (reviewThreads.length > 0) {
236
- prCtx = { reviewThreads, issueComments: [], reviewDecision };
235
+ const fetched = forge.fetchThreads({ pr: prRef });
236
+ for (const w of fetched.warnings || []) {
237
+ emit(log.warn, w);
237
238
  }
239
+ prCtx = {
240
+ reviewThreads: fetched.reviewThreads || fetched.threads || [],
241
+ issueComments: fetched.issueComments || [],
242
+ reviews: fetched.reviews || [],
243
+ reviewDecision: fetched.reviewDecision || null,
244
+ };
238
245
  }
239
- let commitMessages = [];
240
- try {
241
- const recentLog = git(['log', '-n', '20', '--format=%B'], repoRoot, { allowFail: true }) || '';
242
- commitMessages = recentLog.split(/\r?\n\r?\n/).filter(Boolean);
243
- } catch {}
244
- const triage = triagePullRequest(prCtx || {}, { commitMessages });
245
- log.info(`[PR #${prRef}] Triaged review feedback (Round ${triage.round}/${triage.maxRounds}): ${triage.actionableThreads.length} actionable, ${triage.questionThreads.length} question(s), ${triage.suggestionThreads.length} suggestion(s).`);
246
+ const commitMessages = loadPrCommitMessages(repoRoot, branch, (msg) => emit(log.warn, msg));
247
+ const triage = triagePullRequest(prCtx, { commitMessages });
248
+ const unresolvedThreads = [
249
+ ...triage.actionableThreads,
250
+ ...triage.suggestionThreads,
251
+ ...triage.questionThreads,
252
+ ];
253
+ const breaker = checkAntiThrashingCircuitBreaker({
254
+ currentRound: triage.round,
255
+ maxRounds: triage.maxRounds,
256
+ unresolvedThreads,
257
+ changeId: slug,
258
+ prNumber: Number.isFinite(prNum) ? prNum : null,
259
+ });
260
+
246
261
  recordEvent('pr.triage', {
247
262
  stage: 'apply',
248
263
  change: slug,
@@ -257,7 +272,58 @@ export function applyGuard(changeId, opts = {}) {
257
272
  suggestionCount: triage.suggestionThreads.length,
258
273
  round: triage.round,
259
274
  maxRounds: triage.maxRounds,
275
+ circuitBreakerTripped: breaker.tripped,
260
276
  }, { repoRoot });
277
+
278
+ if (opts.resolveThread) {
279
+ const matchedThread = unresolvedThreads.find((t) => t.id === opts.resolveThread) || { id: opts.resolveThread };
280
+ const plan = buildThreadResolutionPlan(matchedThread, {
281
+ commitSha: opts.commit || headSha(repoRoot) || 'HEAD',
282
+ summary: opts.reply || '',
283
+ disputed: Boolean(opts.dispute),
284
+ specRef: typeof opts.dispute === 'string' ? opts.dispute : null,
285
+ });
286
+ if (!opts.dryRun && (!opts.prContext || opts.forge)) {
287
+ if (plan.replyBody) {
288
+ forge.replyThread({ pr: prRef, threadId: plan.threadId, body: plan.replyBody });
289
+ }
290
+ if (plan.shouldResolve) {
291
+ forge.resolveThread({ pr: prRef, threadId: plan.threadId });
292
+ } else if (plan.disputed && plan.escalationLabel) {
293
+ forge.addLabel({ pr: prRef, label: plan.escalationLabel });
294
+ }
295
+ }
296
+ if (opts.json) {
297
+ jsonOut({ changeId: slug, pr: prNum, resolutionPlan: plan });
298
+ } else {
299
+ log.ok(plan.shouldResolve
300
+ ? `[PR #${prRef}] Thread ${opts.resolveThread} replied & resolved (${plan.commitMessage}).`
301
+ : `[PR #${prRef}] Thread ${opts.resolveThread} marked DISPUTED — escalated for human arbitration (resolve blocked).`);
302
+ }
303
+ return 0;
304
+ }
305
+
306
+ if (breaker.tripped) {
307
+ if (!opts.dryRun && (!opts.prContext || opts.forge)) {
308
+ forge.postComment({ pr: prRef, body: breaker.synthesisReport });
309
+ forge.addLabel({ pr: prRef, label: breaker.label });
310
+ }
311
+ if (opts.json) {
312
+ jsonOut({ changeId: slug, pr: prNum, triage, circuitBreaker: breaker });
313
+ } else {
314
+ log.error(`[PR #${prRef}] Anti-Thrashing Circuit Breaker tripped (Round ${triage.round}/${triage.maxRounds}). Automated edits halted.`);
315
+ log.info(breaker.synthesisReport);
316
+ }
317
+ return breaker.exitCode;
318
+ }
319
+
320
+ if (opts.json) {
321
+ jsonOut({ changeId: slug, pr: prNum, triage, circuitBreaker: breaker });
322
+ return 0;
323
+ }
324
+
325
+ log.info(`[PR #${prRef}] Triaged review feedback (Round ${triage.round}/${triage.maxRounds}): ${triage.actionableThreads.length} actionable, ${triage.questionThreads.length} question(s), ${triage.suggestionThreads.length} suggestion(s).`);
326
+ printTriageThreads(triage, prRef);
261
327
  }
262
328
 
263
329
  if (isAutoPr) {
@@ -277,6 +343,12 @@ export function register(program) {
277
343
  .option('--target-branch <ref>', 'target branch to merge into')
278
344
  .option('--mode <mode>', 'workflow mode: supervised (default) | spec-first | auto')
279
345
  .option('--from-pr <pr>', 'triage review comments from a GitHub PR number or #N')
346
+ .option('--resolve-thread <threadId>', 'reply and resolve a PR review thread (or escalate via --dispute)')
347
+ .option('--commit <sha>', 'commit SHA to cite when resolving a review thread')
348
+ .option('--reply <text>', 'reply summary when resolving a review thread')
349
+ .option('--dispute <reason>', 'mark thread as spec-conflict (forbids auto-resolve and attaches human arbitration label)')
350
+ .option('--dry-run', 'compute triage or resolution plan without calling gh mutations')
351
+ .option('--json', 'output triage or resolution plan as structured JSON')
280
352
  .option('--auto-pr', 'explicitly delegate authority to automatically open Implementation PR after verification passes')
281
353
  .option('--no-auto-pr', 'disable automatic Implementation PR creation (default)')
282
354
  .option('--guard-only', 'only run pre-implementation guard checks in terminal without starting the AI TDD loop')
@@ -7,6 +7,7 @@ import { assess } from '../assess/index.js';
7
7
  import { resolveWorkflowMode } from '../lib/config.js';
8
8
  import { log, dim } from '../lib/log.js';
9
9
  import { recordEvent, getChangeIteration, writeGitHubStepSummary } from '../lib/telemetry.js';
10
+ import { generateTasksFromSpecs } from '../lib/tasks-gen.js';
10
11
 
11
12
  // THE spec check (v10: lint absorbed review). Deterministic:
12
13
  // - required artifacts (explore.md + proposal.md + >=1 spec delta)
@@ -189,7 +190,11 @@ export function runLint(changeId, opts = {}) {
189
190
  if (exists(clarPath)) {
190
191
  const clarText = readText(clarPath);
191
192
  const unresolved = hasUnresolvedClarifications(clarText);
192
- add('clarifications', unresolved ? 'fail' : 'pass', unresolved ? 'unresolved [OPEN] questions in clarifications.md' : 'all clarifications settled');
193
+ if (unresolved && opts.allowOpenClarifications) {
194
+ add('clarifications', 'pass', 'allowed in draft mode ([OPEN] questions pending on PR)');
195
+ } else {
196
+ add('clarifications', unresolved ? 'fail' : 'pass', unresolved ? 'unresolved [OPEN] questions in clarifications.md' : 'all clarifications settled');
197
+ }
193
198
  }
194
199
 
195
200
  // Spec-stage risk assessment: ground in artifacts and sync level/workflow mode
@@ -242,6 +247,13 @@ export function runLint(changeId, opts = {}) {
242
247
  }
243
248
  add('BDD + acceptance criteria', blockers === 0 ? 'pass' : 'fail', bddDetail);
244
249
 
250
+ if (opts.genTasks && blockers === 0) {
251
+ const gen = generateTasksFromSpecs(repoRoot, slug);
252
+ if (gen.generated && !opts.json) {
253
+ log.ok(`generated tasks.md (${gen.taskCount} TDD tasks from ${gen.acCount} spec AC(s))`);
254
+ }
255
+ }
256
+
245
257
  return finish(results, { json: opts.json, changeId: slug, repoRoot, startTime, iteration });
246
258
  }
247
259
 
@@ -251,6 +263,7 @@ export function register(program) {
251
263
  .description('check the spec: artifacts + review record + BDD/acceptance criteria')
252
264
  .option('--repo-root <path>')
253
265
  .option('--mode <mode>', 'workflow mode: supervised (default) | spec-first | auto')
266
+ .option('--gen-tasks', 'auto-generate tasks.md from spec ACs if missing and lint passes')
254
267
  .option('--json', 'stable JSON output for CI')
255
268
  .action((changeId, opts) => {
256
269
  process.exitCode = runLint(changeId, opts);
@@ -1,17 +1,21 @@
1
1
  import path from 'node:path';
2
2
  import { exists, readText, writeText, ensureDir } from '../lib/fs.js';
3
3
  import { changeDir, schemaAssetDir } from '../lib/paths.js';
4
- import { requireRepo, deriveChangeSlug, extractRequirementTerms, requireAgentRuntime } from '../lib/cliutil.js';
4
+ import { requireRepo, deriveChangeSlug, extractRequirementTerms, requireAgentRuntime, toChangeSlug, jsonOut } from '../lib/cliutil.js';
5
5
  import { ensureGraphify, ensureFreshGraph, graphifyQuery } from '../lib/graphify.js';
6
6
  import { runOpenspec } from '../lib/openspec.js';
7
7
  import { runShell } from '../lib/exec.js';
8
- import { fail } from '../lib/errors.js';
8
+ import { lastCommitTouching, resolveDefaultBranch } from '../lib/git.js';
9
+ import { fail, AsdlcError } from '../lib/errors.js';
9
10
  import { log } from '../lib/log.js';
10
11
  import { Option } from 'commander';
11
12
  import { inferInitialLevel } from '../lib/level.js';
12
13
  import { resolveWorkflowMode } from '../lib/config.js';
13
14
  import { ingestIntakeSources, extractIntakeContext } from '../lib/intake.js';
14
15
  import { recordEvent } from '../lib/telemetry.js';
16
+ import { createForgeAdapter } from '../lib/forge/index.js';
17
+ import { triagePullRequest, isBotOrSelfAuthor } from '../lib/triage.js';
18
+ import { runLint } from './lint.js';
15
19
 
16
20
  function collectOption(val, prev = []) {
17
21
  return [...prev, val];
@@ -321,6 +325,123 @@ ${intakeSectionMd}
321
325
  return slug;
322
326
  }
323
327
 
328
+ function extractOpenQuestions(clarText) {
329
+ return String(clarText ?? '')
330
+ .split(/\r?\n/)
331
+ .map((l) => l.trim())
332
+ .filter((l) => /\[OPEN\]/i.test(l));
333
+ }
334
+
335
+ /**
336
+ * Spec-phase counterpart to `asdlc apply --from-pr`:
337
+ * Pulls human answers to `[OPEN]` grill questions or Spec PR review comments without mutating
338
+ * the remote PR when no human reply exists (`NO_HUMAN_REPLY`, exitCode 3).
339
+ * Hard-blocks if the spec has already been approved (`SPEC_ALREADY_APPROVED`).
340
+ */
341
+ export async function syncSpecFromPr(changeId, opts = {}) {
342
+ const repoRoot = requireRepo(opts);
343
+ const slug = toChangeSlug(changeId);
344
+ const cdir = changeDir(repoRoot, slug);
345
+ if (!exists(cdir)) {
346
+ fail(`change '${slug}' not found`, { code: 'CHANGE_NOT_FOUND' });
347
+ }
348
+
349
+ const metaPath = path.join(cdir, '.openspec.yaml');
350
+ const metaText = exists(metaPath) ? readText(metaPath) : '';
351
+ const statusMatch = metaText.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
352
+ const shaMatch = metaText.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
353
+ const branch = opts.targetBranch ?? opts.protectedBranch ?? resolveDefaultBranch(repoRoot);
354
+ const locked = [`openspec/changes/${slug}/proposal.md`, `openspec/changes/${slug}/specs`];
355
+ const approvedSha = lastCommitTouching(repoRoot, branch, locked);
356
+
357
+ if ((statusMatch && statusMatch[1] === 'ready_for_impl') || (shaMatch && shaMatch[1]) || approvedSha) {
358
+ fail(`cannot sync '${slug}': spec is already approved (locked for implementation)`, {
359
+ code: 'SPEC_ALREADY_APPROVED',
360
+ exitCode: 1,
361
+ hint: 'Use `asdlc apply --from-pr` for implementation fixes or start a new change.',
362
+ });
363
+ }
364
+
365
+ const prRef = String(opts.fromPr || '').replace(/^#/, '');
366
+ const forge = opts.forge || createForgeAdapter({ repoRoot });
367
+
368
+ let fetched;
369
+ try {
370
+ fetched = await forge.fetchThreads({ pr: prRef });
371
+ } catch (err) {
372
+ if (err instanceof AsdlcError && err.code === 'PR_FETCH_FAILED') throw err;
373
+ throw new AsdlcError(`Failed to fetch PR #${prRef}: ${err?.message || err}`, {
374
+ code: 'PR_FETCH_FAILED',
375
+ exitCode: 1,
376
+ });
377
+ }
378
+
379
+ for (const w of fetched?.warnings || []) {
380
+ if (!opts.json) log.warn(w);
381
+ }
382
+
383
+ const threads = fetched?.threads || fetched?.reviewThreads || [];
384
+ const issueComments = fetched?.issueComments || [];
385
+ const reviews = fetched?.reviews || [];
386
+
387
+ const humanThreadReplies = threads.filter((t) => {
388
+ const comments = Array.isArray(t?.comments?.nodes) ? t.comments.nodes : (Array.isArray(t?.comments) ? t.comments : []);
389
+ const last = comments[comments.length - 1];
390
+ return Boolean(last && !isBotOrSelfAuthor(last?.author?.login));
391
+ });
392
+ const humanIssueComments = issueComments.filter((c) => !isBotOrSelfAuthor(c?.author?.login));
393
+ const humanReviews = reviews.filter((r) => !isBotOrSelfAuthor(r?.author?.login) && String(r?.body || '').trim().length > 0);
394
+
395
+ const clarPath = path.join(cdir, 'clarifications.md');
396
+ const clarText = exists(clarPath) ? readText(clarPath) : '';
397
+ const openQuestions = extractOpenQuestions(clarText);
398
+
399
+ const hasHumanReply = humanThreadReplies.length > 0 || humanIssueComments.length > 0 || humanReviews.length > 0;
400
+ if (!hasHumanReply) {
401
+ const pendingList = openQuestions.length > 0 ? `\n${openQuestions.map((q) => ` ${q}`).join('\n')}` : '';
402
+ if (!opts.json && pendingList) {
403
+ log.warn(`Pending [OPEN] questions awaiting human reply on PR #${prRef}:${pendingList}`);
404
+ }
405
+ throw new AsdlcError(`No human replies found on PR #${prRef}`, {
406
+ code: 'NO_HUMAN_REPLY',
407
+ exitCode: 3,
408
+ detail: pendingList || undefined,
409
+ hint: `Wait for a human reply on PR #${prRef}, then re-run \`asdlc new ${slug} --from-pr ${prRef}\`.`,
410
+ });
411
+ }
412
+
413
+ const triage = triagePullRequest({
414
+ reviewThreads: threads,
415
+ issueComments,
416
+ reviews,
417
+ reviewDecision: fetched?.reviewDecision || null,
418
+ });
419
+
420
+ if (!opts.dryRun && openQuestions.length === 0) {
421
+ const lintExit = runLint(slug, { repoRoot, json: true });
422
+ if (lintExit === 0) {
423
+ await forge.markReady({ pr: prRef });
424
+ await forge.addLabel({ pr: prRef, label: 'asdlc:spec-review' });
425
+ }
426
+ }
427
+
428
+ if (opts.json) {
429
+ jsonOut({
430
+ changeId: slug,
431
+ pr: prRef,
432
+ openQuestions,
433
+ humanReplyCount: humanThreadReplies.length + humanIssueComments.length + humanReviews.length,
434
+ triage,
435
+ });
436
+ } else {
437
+ log.ok(`[PR #${prRef}] Found ${humanThreadReplies.length + humanIssueComments.length + humanReviews.length} human reply/review item(s) for '${slug}'.`);
438
+ for (const c of humanIssueComments) {
439
+ log.info(` [PR Comment] @${c.author?.login}: ${String(c.body || '').replace(/\s+/g, ' ').slice(0, 140)}`);
440
+ }
441
+ }
442
+ return 0;
443
+ }
444
+
324
445
  export function register(program) {
325
446
  program
326
447
  .command('new [requirement]')
@@ -332,17 +453,29 @@ export function register(program) {
332
453
  .option('--from-issue <id>', 'external issue/ticket reference to intake (repeatable)', collectOption, [])
333
454
  .option('--ticket <id>', 'alias for --from-issue (repeatable)', collectOption, [])
334
455
  .option('--issue <id>', 'alias for --from-issue (repeatable)', collectOption, [])
456
+ .option('--from-pr <pr>', 'sync human grill answers / spec review comments from a PR (#N)')
335
457
  .option('--design', 'explicitly generate technical design (design.md)')
336
458
  .option('--no-design', 'skip generating technical design (design.md)')
337
459
  .option('--batch-grill', 'use batch-grill-me (present entire decision frontier in structured batches)')
338
460
  .option('--no-grill', 'skip interactive grilling interview (self-settle decisions in clarifications.md)')
339
461
  .option('--mode <mode>', 'workflow mode: supervised (default) | spec-first | auto')
462
+ .option('--json', 'output machine-readable JSON (for --from-pr)')
340
463
  .option('--scaffold-only', 'only scaffold change directory and explore.md in terminal without an AI agent')
341
464
  .addOption(new Option('--agent', 'internal agent runtime marker').hideHelp())
342
465
  .addOption(new Option('--level <level>', 'internal governance level override (hidden)').hideHelp())
343
466
  .option('--repo-root <path>')
344
- .action((requirement, opts) => {
467
+ .action(async (requirement, opts) => {
345
468
  requireAgentRuntime('new', opts);
469
+ if (opts.fromPr) {
470
+ if (!requirement) {
471
+ fail('changeId is required when using --from-pr', {
472
+ code: 'MISSING_CHANGE_ID',
473
+ hint: 'Run `asdlc new <changeId> --from-pr <pr>`',
474
+ });
475
+ }
476
+ process.exitCode = await syncSpecFromPr(requirement, opts);
477
+ return;
478
+ }
346
479
  newChange(requirement, opts);
347
480
  });
348
481
  }
@@ -106,8 +106,31 @@ export const ASDLC_LABELS = {
106
106
  color: '0e8a16',
107
107
  description: 'Agentic SDLC: Verified implementation',
108
108
  },
109
+ 'asdlc:needs-grill': {
110
+ color: 'fbca04',
111
+ description: 'Agentic SDLC: Draft Spec PR awaiting async grill answers',
112
+ },
109
113
  };
110
114
 
115
+ export function ensureGitLabLabels(repoRoot, remoteInfo, labelNames = Object.keys(ASDLC_LABELS)) {
116
+ if (!remoteInfo?.isGitLab || !remoteInfo.repoPath) return;
117
+ for (const name of labelNames) {
118
+ const meta = ASDLC_LABELS[name];
119
+ if (!meta) continue;
120
+ try {
121
+ execFileSync('glab', [
122
+ 'api', '-X', 'POST',
123
+ `projects/${encodeURIComponent(remoteInfo.repoPath)}/labels`,
124
+ '-f', `name=${name}`,
125
+ '-f', `color=#${meta.color}`,
126
+ '-f', `description=${meta.description}`,
127
+ ], { cwd: repoRoot, stdio: 'ignore' });
128
+ } catch {
129
+ // ignore if glab is unavailable or label already exists
130
+ }
131
+ }
132
+ }
133
+
111
134
  export function ensureRemoteLabels(repoRoot, labelNames = Object.keys(ASDLC_LABELS)) {
112
135
  for (const name of labelNames) {
113
136
  const meta = ASDLC_LABELS[name];
@@ -191,9 +214,13 @@ export async function createPR(changeId, targetBranch, opts = {}) {
191
214
  }
192
215
 
193
216
  const isSpec = prType === 'spec';
194
- const labelPrefix = isSpec ? 'asdlc:spec-review' : 'asdlc:impl-review';
217
+ const isDraftSpec = Boolean(opts.draft);
218
+ if (isDraftSpec && !isSpec) {
219
+ fail('--draft is only supported for Spec PRs (Stage 2/3)');
220
+ }
221
+ const labelPrefix = isSpec ? (isDraftSpec ? 'asdlc:needs-grill' : 'asdlc:spec-review') : 'asdlc:impl-review';
195
222
  const secondaryLabel = isSpec ? 'spec' : 'impl';
196
- const prTypeName = isSpec ? 'Spec PR' : 'Implementation PR';
223
+ const prTypeName = isSpec ? (isDraftSpec ? 'Draft Spec PR' : 'Spec PR') : 'Implementation PR';
197
224
 
198
225
  // 1. Stage & commit any unstaged changes BEFORE running pre-flight gates,
199
226
  // ensuring runVerify and runLint evaluate the true, complete state being pushed.
@@ -221,11 +248,11 @@ export async function createPR(changeId, targetBranch, opts = {}) {
221
248
  // 2. Pre-flight self-check (evaluates committed HEAD vs targetBranch)
222
249
  if (isSpec) {
223
250
  log.step(`running spec lint pre-flight for ${slug}...`);
224
- const lintExit = runLint(slug, { repoRoot, json: true });
251
+ const lintExit = runLint(slug, { repoRoot, json: true, allowOpenClarifications: isDraftSpec });
225
252
  if (lintExit !== 0) {
226
253
  fail(`spec lint failed; fix all blocking findings before opening the Spec PR (run \`asdlc lint ${slug}\`)`);
227
254
  }
228
- log.ok('spec lint passed (0 blockers)');
255
+ log.ok(isDraftSpec ? 'spec lint passed (draft mode: [OPEN] questions deferred to PR)' : 'spec lint passed (0 blockers)');
229
256
  } else {
230
257
  log.step(`running implementation verify pre-flight for ${slug}...`);
231
258
  const verifyExit = runVerify(slug, {
@@ -321,15 +348,19 @@ ${proposalText}
321
348
  const remoteUrl = git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true });
322
349
  const remoteInfo = parseRemoteUrl(remoteUrl);
323
350
 
324
- // Pre-provision governance labels on remote before PR creation (so gh pr create doesn't reject unknown labels)
351
+ // Pre-provision governance labels on remote before PR creation (so gh/glab doesn't reject unknown labels)
325
352
  if (remoteInfo?.isGitHub) {
326
353
  ensureRemoteLabels(repoRoot, labelsToApply);
354
+ } else if (remoteInfo?.isGitLab) {
355
+ ensureGitLabLabels(repoRoot, remoteInfo, labelsToApply);
327
356
  }
328
357
 
329
358
  // Attempt Tier 1: CLI (gh)
359
+ const draftArgs = isDraftSpec ? ['--draft'] : [];
330
360
  try {
331
361
  const out = execFileSync('gh', [
332
362
  'pr', 'create',
363
+ ...draftArgs,
333
364
  '--title', title,
334
365
  '--body', body,
335
366
  '--base', targetBranch,
@@ -342,6 +373,7 @@ ${proposalText}
342
373
  try {
343
374
  const out = execFileSync('gh', [
344
375
  'pr', 'create',
376
+ ...draftArgs,
345
377
  '--title', title,
346
378
  '--body', body,
347
379
  '--base', targetBranch,
@@ -354,6 +386,7 @@ ${proposalText}
354
386
  try {
355
387
  const out = execFileSync('gh', [
356
388
  'pr', 'create',
389
+ ...draftArgs,
357
390
  '--title', title,
358
391
  '--body', body,
359
392
  '--base', targetBranch,
@@ -402,6 +435,7 @@ ${proposalText}
402
435
  '--target-branch', targetBranch,
403
436
  '--source-branch', currentBranch,
404
437
  '--label', `${labelPrefix},${secondaryLabel}`,
438
+ ...draftArgs,
405
439
  ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
406
440
  prCreated = true;
407
441
  prUrl = out.trim();
@@ -494,7 +528,7 @@ ${proposalText}
494
528
  'Content-Type': 'application/json',
495
529
  },
496
530
  body: JSON.stringify({
497
- title,
531
+ title: isDraftSpec && !title.startsWith('Draft: ') ? `Draft: ${title}` : title,
498
532
  description: body,
499
533
  source_branch: currentBranch,
500
534
  target_branch: targetBranch,
@@ -554,50 +588,16 @@ export function createSpecPR(changeId, targetBranch, opts = {}) {
554
588
  return createPR(changeId, targetBranch, { type: 'spec', ...opts });
555
589
  }
556
590
 
557
- export function parseRemoteUrl(url, opts = {}) {
558
- if (!url) return null;
559
- const cleaned = url.trim().replace(/\.git$/, '');
560
- let host = '';
561
- let repoPath = '';
562
- let protocol = 'https:';
563
-
564
- const sshMatch = cleaned.match(/^git@([^:]+):(.+)$/);
565
- if (sshMatch) {
566
- host = sshMatch[1];
567
- repoPath = sshMatch[2];
568
- } else {
569
- try {
570
- const u = new URL(cleaned);
571
- host = u.host;
572
- protocol = u.protocol || 'https:';
573
- repoPath = u.pathname.replace(/^\//, '');
574
- } catch {
575
- return null;
576
- }
577
- }
591
+ import { parseRemoteUrl } from '../lib/remote.js';
578
592
 
579
- const explicitPlatform = (opts.platform || process.env.ASDLC_GIT_PLATFORM || process.env.GIT_PLATFORM || '').toLowerCase();
580
- const isGitLab = explicitPlatform === 'gitlab'
581
- || host.includes('gitlab')
582
- || (!host.includes('github') && Boolean(process.env.GITLAB_TOKEN || process.env.CI_JOB_TOKEN || process.env.GL_TOKEN));
583
- const isGitHub = explicitPlatform === 'github'
584
- || host.includes('github')
585
- || (!isGitLab);
586
-
587
- return {
588
- host,
589
- repoPath,
590
- protocol,
591
- isGitHub,
592
- isGitLab,
593
- };
594
- }
593
+ export { parseRemoteUrl };
595
594
 
596
595
  export function register(program) {
597
596
  program
598
597
  .command('pr <changeId> [targetBranch]')
599
598
  .description('automatically open a Spec or Implementation PR: auto-detects stage, pre-flight checks, pushes branch, and attaches labels for CI AI review')
600
599
  .option('--mode <mode>', 'workflow mode: supervised (default) | spec-first | auto')
600
+ .option('--draft', 'open a Draft Spec PR (asdlc:needs-grill) when clarifications.md still has [OPEN] items')
601
601
  .option('--repo-root <path>')
602
602
  .action(async (changeId, targetBranch, opts) => {
603
603
  await createPR(changeId, targetBranch, opts);