@akjamie/agentic-sdlc 1.12.0 → 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.
@@ -3,6 +3,8 @@ name: ASDLC Governance & AI Review
3
3
  on:
4
4
  pull_request:
5
5
  types: [opened, synchronize, labeled]
6
+ pull_request_review:
7
+ types: [submitted]
6
8
 
7
9
  permissions:
8
10
  contents: read
@@ -42,7 +44,13 @@ jobs:
42
44
  asdlc lint "$CHANGE_ID"
43
45
  fi
44
46
  if echo "$LABELS" | grep -q "asdlc:impl-review"; then
45
- asdlc verify "$CHANGE_ID" --protected-branch "origin/${{ github.base_ref }}"
47
+ APPROVED_FLAG=""
48
+ PR_NUM="${{ github.event.pull_request.number || github.event.review.pull_request.number }}"
49
+ REVIEW_DECISION=$(gh pr view "$PR_NUM" --json reviewDecision --jq '.reviewDecision' 2>/dev/null || echo "")
50
+ if [ "$REVIEW_DECISION" = "APPROVED" ]; then
51
+ APPROVED_FLAG="--approved"
52
+ fi
53
+ asdlc verify "$CHANGE_ID" --protected-branch "origin/${{ github.base_ref }}" $APPROVED_FLAG
46
54
  fi
47
55
 
48
56
  # Optional: configure repository variable ASDLC_AI_REVIEW_CMD + LLM secret to run a headless review agent
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akjamie/agentic-sdlc",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "description": "Enterprise Agentic SDLC governance CLI: a 7-stage spec-driven flow on top of OpenSpec + Graphify, enforced by CI.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,5 +1,4 @@
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';
@@ -12,32 +11,20 @@ import { resolveWorkflowMode } from '../lib/config.js';
12
11
  import { assess } from '../assess/index.js';
13
12
  import {
14
13
  triagePullRequest,
15
- PULL_REQUEST_THREADS_QUERY,
16
14
  checkAntiThrashingCircuitBreaker,
17
15
  buildThreadResolutionPlan,
18
16
  } from '../lib/triage.js';
19
17
  import { recordEvent } from '../lib/telemetry.js';
20
18
  import { generateTasksFromSpecs } from '../lib/tasks-gen.js';
19
+ import { createForgeAdapter } from '../lib/forge/index.js';
21
20
 
22
- function runGhGraphql(repoRoot, mutation) {
23
- return spawnSync('gh', [
24
- 'api', 'graphql',
25
- '-f', `query=${mutation.query}`,
26
- ...Object.entries(mutation.variables || {}).flatMap(([k, v]) => ['-F', `${k}=${v}`]),
27
- ], { cwd: repoRoot, encoding: 'utf8', timeout: 8000 });
28
- }
29
-
30
- function postBreakerEscalation(repoRoot, prRef, breaker) {
31
- spawnSync('gh', ['pr', 'comment', prRef, '--body', breaker.synthesisReport], {
32
- cwd: repoRoot,
33
- encoding: 'utf8',
34
- timeout: 8000,
35
- });
36
- spawnSync('gh', ['pr', 'edit', prRef, '--add-label', breaker.label], {
37
- cwd: repoRoot,
38
- encoding: 'utf8',
39
- timeout: 8000,
40
- });
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);
41
28
  }
42
29
 
43
30
  function printTriageThreads(triage, prRef) {
@@ -242,57 +229,22 @@ export function applyGuard(changeId, opts = {}) {
242
229
  if (opts.fromPr) {
243
230
  const prRef = String(opts.fromPr).replace(/^#/, '');
244
231
  const prNum = Number(prRef);
232
+ const forge = opts.forge || createForgeAdapter({ repoRoot });
245
233
  let prCtx = opts.prContext || null;
246
234
  if (!prCtx) {
247
- let reviewThreads = [];
248
- let reviewDecision = null;
249
- const remoteUrl = git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true }) || '';
250
- const repoMatch = remoteUrl.match(/[:/]([^/:\s]+)\/([^/:\s]+?)(?:\.git)?$/);
251
- if (repoMatch && Number.isFinite(prNum) && prNum > 0) {
252
- const gql = spawnSync('gh', [
253
- 'api', 'graphql',
254
- '-F', `owner=${repoMatch[1]}`,
255
- '-F', `repo=${repoMatch[2]}`,
256
- '-F', `number=${prNum}`,
257
- '-f', `query=${PULL_REQUEST_THREADS_QUERY}`,
258
- ], { cwd: repoRoot, encoding: 'utf8', timeout: 8000 });
259
- if (gql.status === 0 && gql.stdout) {
260
- try {
261
- const parsedGql = JSON.parse(gql.stdout);
262
- const prNode = parsedGql?.data?.repository?.pullRequest;
263
- reviewThreads = prNode?.reviewThreads?.nodes || [];
264
- reviewDecision = prNode?.reviewDecision || null;
265
- } catch {
266
- // fallback to view
267
- }
268
- }
269
- }
270
- const gh = spawnSync('gh', ['pr', 'view', prRef, '--json', 'comments,reviews,reviewDecision'], {
271
- cwd: repoRoot,
272
- encoding: 'utf8',
273
- timeout: 8000,
274
- });
275
- if (gh.status === 0 && gh.stdout) {
276
- try {
277
- const parsed = JSON.parse(gh.stdout);
278
- prCtx = {
279
- reviewThreads,
280
- issueComments: parsed.comments || [],
281
- reviewDecision: reviewDecision || parsed.reviewDecision || null,
282
- };
283
- } catch {
284
- prCtx = { reviewThreads, reviewDecision };
285
- }
286
- } else if (reviewThreads.length > 0) {
287
- prCtx = { reviewThreads, issueComments: [], reviewDecision };
235
+ const fetched = forge.fetchThreads({ pr: prRef });
236
+ for (const w of fetched.warnings || []) {
237
+ emit(log.warn, w);
288
238
  }
239
+ prCtx = {
240
+ reviewThreads: fetched.reviewThreads || fetched.threads || [],
241
+ issueComments: fetched.issueComments || [],
242
+ reviews: fetched.reviews || [],
243
+ reviewDecision: fetched.reviewDecision || null,
244
+ };
289
245
  }
290
- let commitMessages = [];
291
- try {
292
- const recentLog = git(['log', '-n', '20', '--format=%B'], repoRoot, { allowFail: true }) || '';
293
- commitMessages = recentLog.split(/\r?\n\r?\n/).filter(Boolean);
294
- } catch {}
295
- const triage = triagePullRequest(prCtx || {}, { commitMessages });
246
+ const commitMessages = loadPrCommitMessages(repoRoot, branch, (msg) => emit(log.warn, msg));
247
+ const triage = triagePullRequest(prCtx, { commitMessages });
296
248
  const unresolvedThreads = [
297
249
  ...triage.actionableThreads,
298
250
  ...triage.suggestionThreads,
@@ -331,16 +283,14 @@ export function applyGuard(changeId, opts = {}) {
331
283
  disputed: Boolean(opts.dispute),
332
284
  specRef: typeof opts.dispute === 'string' ? opts.dispute : null,
333
285
  });
334
- if (!opts.dryRun && !opts.prContext) {
335
- if (plan.replyMutation) runGhGraphql(repoRoot, plan.replyMutation);
336
- if (plan.shouldResolve && plan.resolveMutation) {
337
- runGhGraphql(repoRoot, plan.resolveMutation);
338
- } else if (plan.disputed) {
339
- spawnSync('gh', ['pr', 'edit', prRef, '--add-label', 'asdlc:needs-human-arbitration'], {
340
- cwd: repoRoot,
341
- encoding: 'utf8',
342
- timeout: 8000,
343
- });
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 });
344
294
  }
345
295
  }
346
296
  if (opts.json) {
@@ -354,8 +304,9 @@ export function applyGuard(changeId, opts = {}) {
354
304
  }
355
305
 
356
306
  if (breaker.tripped) {
357
- if (!opts.dryRun && !opts.prContext) {
358
- postBreakerEscalation(repoRoot, prRef, breaker);
307
+ if (!opts.dryRun && (!opts.prContext || opts.forge)) {
308
+ forge.postComment({ pr: prRef, body: breaker.synthesisReport });
309
+ forge.addLabel({ pr: prRef, label: breaker.label });
359
310
  }
360
311
  if (opts.json) {
361
312
  jsonOut({ changeId: slug, pr: prNum, triage, circuitBreaker: breaker });
@@ -190,7 +190,11 @@ export function runLint(changeId, opts = {}) {
190
190
  if (exists(clarPath)) {
191
191
  const clarText = readText(clarPath);
192
192
  const unresolved = hasUnresolvedClarifications(clarText);
193
- 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
+ }
194
198
  }
195
199
 
196
200
  // Spec-stage risk assessment: ground in artifacts and sync level/workflow mode
@@ -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);
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { exists, readText, walkFiles, listDir } from '../lib/fs.js';
2
+ import { exists, readText, writeText, walkFiles, listDir } from '../lib/fs.js';
3
3
  import { changeDir, openspecDir, CHANGES_DIR } from '../lib/paths.js';
4
4
  import { requireRepo, toChangeSlug, jsonOut } from '../lib/cliutil.js';
5
5
  import { lastCommitTouching, resolveDefaultBranch } from '../lib/git.js';
@@ -7,7 +7,7 @@ import { verdictOf } from './lint.js';
7
7
  import { countUncheckedTasks } from './verify.js';
8
8
  import { log } from '../lib/log.js';
9
9
  import { resolveTopology } from '../lib/level.js';
10
- import { computeTeamMetrics, renderMetricsDashboard } from '../lib/telemetry.js';
10
+ import { computeTeamMetrics, renderMetricsDashboard, renderMetricsReportMarkdown } from '../lib/telemetry.js';
11
11
 
12
12
  // "Where am I?" for a change - a read-only view of the 7 stages from the working
13
13
  // tree + git. Useful for humans and for an agent deciding the next command.
@@ -247,6 +247,11 @@ export function statusPortfolio(opts = {}) {
247
247
  export function statusMetrics(opts = {}) {
248
248
  const repoRoot = requireRepo(opts);
249
249
  const metrics = computeTeamMetrics(repoRoot, { days: opts.days ? Number(opts.days) : 30 });
250
+ if (opts.report) {
251
+ const reportPath = path.resolve(repoRoot, opts.report);
252
+ writeText(reportPath, renderMetricsReportMarkdown(metrics));
253
+ if (!opts.json) log.ok(`exported metrics report -> ${opts.report}`);
254
+ }
250
255
  if (opts.json) {
251
256
  jsonOut(metrics);
252
257
  } else {
@@ -263,6 +268,7 @@ export function register(program) {
263
268
  .option('--mode <mode>', 'workflow mode: supervised (default) | spec-first | auto')
264
269
  .option('--metrics', 'show team governance metrics & gate friction dashboard')
265
270
  .option('--days <count>', 'number of days to aggregate metrics for', '30')
271
+ .option('--report <path>', 'export metrics report to a Markdown file')
266
272
  .option('--repo-root <path>')
267
273
  .option('--json', 'output machine-readable JSON')
268
274
  .action((changeId, opts) => {
@@ -134,6 +134,26 @@ ${tableRows}
134
134
  // Fail-silent contract: Telemetry never throws or interferes with gate results
135
135
  }
136
136
 
137
+ if (opts.report && opts.repoRoot) {
138
+ const rows = processed.map((r) => `| \`${r.name}\` | ${r.status.toUpperCase()} | ${r.detail || ''} |`).join('\n');
139
+ const provenance = opts.approvalProvenance || (opts.approved ? 'ci-flag (--approved)' : 'local-review-md');
140
+ const reportMd = [
141
+ `# ASDLC Verification Audit Report — \`${opts.changeId || 'unknown'}\``,
142
+ '',
143
+ `- **Verdict**: ${failed === 0 ? 'PASS' : 'FAIL'} (${processed.length - failed}/${processed.length} passed)`,
144
+ `- **Spec SHA**: ${opts.specSha || 'N/A'}`,
145
+ `- **Approval Provenance**: ${provenance}`,
146
+ `- **Generated At**: ${new Date().toISOString()}`,
147
+ '',
148
+ '| Gate | Status | Detail |',
149
+ '| :--- | :--- | :--- |',
150
+ rows,
151
+ '',
152
+ ].join('\n');
153
+ writeText(path.resolve(opts.repoRoot, opts.report), reportMd);
154
+ if (!opts.json) log.ok(`exported verification audit report -> ${opts.report}`);
155
+ }
156
+
137
157
  if (opts.json) {
138
158
  jsonOut({
139
159
  verdict: failed === 0 ? 'PASS' : 'FAIL',
@@ -578,6 +598,8 @@ export function runVerify(changeId, opts = {}) {
578
598
  ...opts,
579
599
  repoRoot,
580
600
  changeId: slug,
601
+ specSha,
602
+ approvalProvenance: opts.approved ? 'ci-flag (--approved)' : (isCI ? 'unverified (CI)' : 'local-review-md'),
581
603
  iteration,
582
604
  startTime,
583
605
  addressedThreadIds,
@@ -599,6 +621,7 @@ export function register(program) {
599
621
  .option('--required', 'require AI verification gate to pass')
600
622
  .option('--skip-openspec', 'skip openspec validation')
601
623
  .option('--skip-external', 'skip external checks from config')
624
+ .option('--report <path>', 'export verification audit report to a Markdown file')
602
625
  .option('--json', 'print output in structured JSON')
603
626
  .action((changeId, opts) => {
604
627
  process.exitCode = runVerify(changeId, opts);