@akjamie/agentic-sdlc 1.9.2 → 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.
@@ -12,6 +12,8 @@ import { fail } from '../lib/errors.js';
12
12
  import { log } from '../lib/log.js';
13
13
  import { assess, renderLabels, renderPRComment } from '../assess/index.js';
14
14
  import { readEffectiveLevel, resolveTopology } from '../lib/level.js';
15
+ import { loadGlobalConfig } from '../lib/config.js';
16
+ import { resolveGitCredentials, buildEphemeralGitEnv, redactSecrets } from '../lib/auth.js';
15
17
 
16
18
  const SAFE_ENV_TEMPLATE_RE = /(^|\/)\.env\.(example|sample|template|defaults|schema)$/i;
17
19
  const SENSITIVE_OR_DUMP_PATTERNS = [
@@ -107,7 +109,7 @@ export const ASDLC_LABELS = {
107
109
  },
108
110
  };
109
111
 
110
- export function ensureRemoteLabels(repoRoot, labelNames = Object.keys(ASDLC_LABELS)) {
112
+ export function ensureRemoteLabels(repoRoot, labelNames = Object.keys(ASDLC_LABELS), env = process.env) {
111
113
  for (const name of labelNames) {
112
114
  const meta = ASDLC_LABELS[name];
113
115
  if (!meta) continue;
@@ -117,13 +119,33 @@ export function ensureRemoteLabels(repoRoot, labelNames = Object.keys(ASDLC_LABE
117
119
  '--description', meta.description,
118
120
  '--color', meta.color,
119
121
  '--force',
120
- ], { cwd: repoRoot, stdio: 'ignore' });
122
+ ], { cwd: repoRoot, env, stdio: 'ignore' });
121
123
  } catch {
122
124
  // ignore if gh is not installed, not authenticated, or not a GitHub repo
123
125
  }
124
126
  }
125
127
  }
126
128
 
129
+ /**
130
+ * Resolves ephemeral Git & PR credentials for Auto-PR execution without writing tokens to disk.
131
+ */
132
+ export async function resolvePrAuthEnv(repoRoot, opts = {}) {
133
+ const remoteUrl = git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true });
134
+ const remoteInfo = parseRemoteUrl(remoteUrl, opts);
135
+ const globalConfig = opts.globalConfig || loadGlobalConfig(opts.customGlobalPath);
136
+ const env = opts.env || process.env;
137
+ const cred = await resolveGitCredentials({
138
+ env,
139
+ globalConfig,
140
+ host: remoteInfo?.host || globalConfig?.git?.default_host || 'github.com',
141
+ provider: remoteInfo?.isGitLab ? 'gitlab' : 'github',
142
+ execFn: opts.execFn,
143
+ fetchFn: opts.fetchFn,
144
+ });
145
+ const authEnv = buildEphemeralGitEnv(cred, env);
146
+ return { cred, authEnv, remoteInfo };
147
+ }
148
+
127
149
  export async function createPR(changeId, targetBranch, opts = {}) {
128
150
  const repoRoot = requireRepo(opts);
129
151
  if (!isGitRepo(repoRoot)) fail('not a git repository');
@@ -167,7 +189,7 @@ export async function createPR(changeId, targetBranch, opts = {}) {
167
189
  .split(/\r?\n/).filter(Boolean);
168
190
  const uncommittedFiles = statusLines.map((l) => l.replace(/^\s*\S+\s+/, '').trim()).filter(Boolean);
169
191
  const allPotentialFiles = [...diffFilesPre, ...uncommittedFiles];
170
- const hasSourceChanges = allPotentialFiles.some((f) => !f.startsWith(`openspec/changes/${slug}/`));
192
+ const hasSourceChanges = allPotentialFiles.some((f) => !f.startsWith(`openspec/changes/${slug}/`) && !f.startsWith('graphify-out/'));
171
193
 
172
194
  const topology = resolveTopology({ repoRoot, slug, baseRef: targetBranch, cliMode: opts.mode });
173
195
  const resolvedMode = topology.mode;
@@ -253,13 +275,18 @@ export async function createPR(changeId, targetBranch, opts = {}) {
253
275
  if (raw) title = `${isSpec ? 'spec' : 'impl'}(${slug}): ${raw}`;
254
276
  }
255
277
 
256
- // 4. Push to remote
278
+ // 4. Resolve ephemeral auth environment & push to remote
279
+ const { cred, authEnv, remoteInfo } = await resolvePrAuthEnv(repoRoot, opts);
280
+ const doFetch = opts.fetchFn || globalThis.fetch;
281
+
257
282
  log.step(`pushing branch '${currentBranch}' to origin...`);
258
- try {
259
- execFileSync('git', ['push', '-u', 'origin', currentBranch], { cwd: repoRoot, stdio: 'inherit' });
260
- log.ok(`pushed branch '${currentBranch}' to origin`);
261
- } catch (err) {
262
- log.warn(`git push skipped or failed: ${err.message}`);
283
+ if (!opts.skipPush) {
284
+ try {
285
+ execFileSync('git', ['push', '-u', 'origin', currentBranch], { cwd: repoRoot, env: authEnv, stdio: 'inherit' });
286
+ log.ok(`pushed branch '${currentBranch}' to origin`);
287
+ } catch (err) {
288
+ log.warn(`git push skipped or failed: ${redactSecrets(err.message, cred?.token ? [cred.token] : [])}`);
289
+ }
263
290
  }
264
291
 
265
292
  // 5. Build PR body
@@ -305,7 +332,8 @@ ${proposalText}
305
332
  });
306
333
  const assessLabels = renderLabels(assessment);
307
334
  const assessComment = renderPRComment(assessment);
308
- const labelsToApply = Array.from(new Set([labelPrefix, secondaryLabel, ...assessLabels]));
335
+ const extraLabels = opts.label ? (Array.isArray(opts.label) ? opts.label : [opts.label]) : [];
336
+ const labelsToApply = Array.from(new Set([labelPrefix, secondaryLabel, ...extraLabels, ...assessLabels]));
309
337
 
310
338
  body = `${body}\n\n---\n\n${assessComment}\n`;
311
339
 
@@ -315,29 +343,15 @@ ${proposalText}
315
343
  // Tier 3: 1-click Web compare URL fallback
316
344
  let prCreated = false;
317
345
  let prUrl = null;
318
-
319
- // Detect remote repository information
320
- const remoteUrl = git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true });
321
- const remoteInfo = parseRemoteUrl(remoteUrl);
346
+ const draftArgs = opts.draft ? ['--draft'] : [];
322
347
 
323
348
  // Pre-provision governance labels on remote before PR creation (so gh pr create doesn't reject unknown labels)
324
- if (remoteInfo?.isGitHub) {
325
- ensureRemoteLabels(repoRoot, labelsToApply);
349
+ if (remoteInfo?.isGitHub && !opts.skipCliPr) {
350
+ ensureRemoteLabels(repoRoot, labelsToApply, authEnv);
326
351
  }
327
352
 
328
353
  // Attempt Tier 1: CLI (gh)
329
- try {
330
- const out = execFileSync('gh', [
331
- 'pr', 'create',
332
- '--title', title,
333
- '--body', body,
334
- '--base', targetBranch,
335
- '--head', currentBranch,
336
- '--label', labelsToApply.join(','),
337
- ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
338
- prCreated = true;
339
- prUrl = out.trim();
340
- } catch {
354
+ if (!opts.skipCliPr) {
341
355
  try {
342
356
  const out = execFileSync('gh', [
343
357
  'pr', 'create',
@@ -345,8 +359,9 @@ ${proposalText}
345
359
  '--body', body,
346
360
  '--base', targetBranch,
347
361
  '--head', currentBranch,
348
- '--label', labelPrefix,
349
- ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
362
+ '--label', labelsToApply.join(','),
363
+ ...draftArgs,
364
+ ], { cwd: repoRoot, env: authEnv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
350
365
  prCreated = true;
351
366
  prUrl = out.trim();
352
367
  } catch {
@@ -357,62 +372,77 @@ ${proposalText}
357
372
  '--body', body,
358
373
  '--base', targetBranch,
359
374
  '--head', currentBranch,
360
- ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
375
+ '--label', labelPrefix,
376
+ ...draftArgs,
377
+ ], { cwd: repoRoot, env: authEnv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
361
378
  prCreated = true;
362
379
  prUrl = out.trim();
363
380
  } catch {
364
- // Check if PR for current branch already exists on GitHub
365
381
  try {
366
- const existingOut = execFileSync('gh', [
367
- 'pr', 'view', currentBranch,
368
- '--json', 'url',
369
- '-q', '.url',
370
- ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
371
- if (existingOut && existingOut.trim()) {
372
- prCreated = true;
373
- prUrl = existingOut.trim();
374
- }
382
+ const out = execFileSync('gh', [
383
+ 'pr', 'create',
384
+ '--title', title,
385
+ '--body', body,
386
+ '--base', targetBranch,
387
+ '--head', currentBranch,
388
+ ...draftArgs,
389
+ ], { cwd: repoRoot, env: authEnv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
390
+ prCreated = true;
391
+ prUrl = out.trim();
375
392
  } catch {
376
- // gh not available or failed
393
+ // Check if PR for current branch already exists on GitHub
394
+ try {
395
+ const existingOut = execFileSync('gh', [
396
+ 'pr', 'view', currentBranch,
397
+ '--json', 'url',
398
+ '-q', '.url',
399
+ ], { cwd: repoRoot, env: authEnv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
400
+ if (existingOut && existingOut.trim()) {
401
+ prCreated = true;
402
+ prUrl = existingOut.trim();
403
+ }
404
+ } catch {
405
+ // gh not available or failed
406
+ }
377
407
  }
378
408
  }
379
409
  }
380
- }
381
410
 
382
- // If created or found via gh, guarantee labels are attached even if initial create omitted them
383
- if (prCreated && remoteInfo?.isGitHub) {
384
- try {
385
- execFileSync('gh', [
386
- 'pr', 'edit', currentBranch,
387
- '--add-label', `${labelPrefix},${secondaryLabel}`,
388
- ], { cwd: repoRoot, stdio: 'ignore' });
389
- } catch {
390
- // ignore
411
+ // If created or found via gh, guarantee labels are attached even if initial create omitted them
412
+ if (prCreated && remoteInfo?.isGitHub) {
413
+ try {
414
+ execFileSync('gh', [
415
+ 'pr', 'edit', currentBranch,
416
+ '--add-label', `${labelPrefix},${secondaryLabel}`,
417
+ ], { cwd: repoRoot, env: authEnv, stdio: 'ignore' });
418
+ } catch {
419
+ // ignore
420
+ }
391
421
  }
392
- }
393
422
 
394
- // Attempt Tier 1: CLI (glab for GitLab)
395
- if (!prCreated) {
396
- try {
397
- const out = execFileSync('glab', [
398
- 'mr', 'create',
399
- '--title', title,
400
- '--description', body,
401
- '--target-branch', targetBranch,
402
- '--source-branch', currentBranch,
403
- '--label', `${labelPrefix},${secondaryLabel}`,
404
- ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
405
- prCreated = true;
406
- prUrl = out.trim();
407
- } catch {
408
- // glab not available
423
+ // Attempt Tier 1: CLI (glab for GitLab)
424
+ if (!prCreated) {
425
+ try {
426
+ const out = execFileSync('glab', [
427
+ 'mr', 'create',
428
+ '--title', title,
429
+ '--description', body,
430
+ '--target-branch', targetBranch,
431
+ '--source-branch', currentBranch,
432
+ '--label', `${labelPrefix},${secondaryLabel}`,
433
+ ], { cwd: repoRoot, env: authEnv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
434
+ prCreated = true;
435
+ prUrl = out.trim();
436
+ } catch {
437
+ // glab not available
438
+ }
409
439
  }
410
440
  }
411
441
 
412
442
  // Attempt Tier 2: Direct REST API via fetch (Node 20+)
413
443
  if (!prCreated && remoteInfo) {
414
- const ghToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
415
- const glToken = process.env.GITLAB_TOKEN || process.env.CI_JOB_TOKEN || process.env.GL_TOKEN;
444
+ const ghToken = authEnv.GITHUB_TOKEN || authEnv.GH_TOKEN;
445
+ const glToken = authEnv.GITLAB_TOKEN || authEnv.CI_JOB_TOKEN || authEnv.GL_TOKEN;
416
446
 
417
447
  if (remoteInfo.isGitHub && ghToken) {
418
448
  try {
@@ -420,7 +450,7 @@ ${proposalText}
420
450
  ? 'https://api.github.com'
421
451
  : `${remoteInfo.protocol}//${remoteInfo.host}/api/v3`;
422
452
  const apiUrl = `${apiBase}/repos/${remoteInfo.repoPath}/pulls`;
423
- const res = await fetch(apiUrl, {
453
+ const res = await doFetch(apiUrl, {
424
454
  method: 'POST',
425
455
  headers: {
426
456
  'Authorization': `Bearer ${ghToken}`,
@@ -433,6 +463,7 @@ ${proposalText}
433
463
  body,
434
464
  head: currentBranch,
435
465
  base: targetBranch,
466
+ draft: Boolean(opts.draft),
436
467
  }),
437
468
  });
438
469
  if (res.ok) {
@@ -443,10 +474,10 @@ ${proposalText}
443
474
  // Attach labels via GitHub Issues API (pull requests are issues in GitHub)
444
475
  if (data.number) {
445
476
  // Pre-create labels if missing
446
- for (const lbl of [labelPrefix, secondaryLabel]) {
477
+ for (const lbl of labelsToApply) {
447
478
  const meta = ASDLC_LABELS[lbl];
448
479
  try {
449
- await fetch(`${apiBase}/repos/${remoteInfo.repoPath}/labels`, {
480
+ await doFetch(`${apiBase}/repos/${remoteInfo.repoPath}/labels`, {
450
481
  method: 'POST',
451
482
  headers: {
452
483
  'Authorization': `Bearer ${ghToken}`,
@@ -465,7 +496,7 @@ ${proposalText}
465
496
 
466
497
  try {
467
498
  const labelUrl = `${apiBase}/repos/${remoteInfo.repoPath}/issues/${data.number}/labels`;
468
- await fetch(labelUrl, {
499
+ await doFetch(labelUrl, {
469
500
  method: 'POST',
470
501
  headers: {
471
502
  'Authorization': `Bearer ${ghToken}`,
@@ -473,7 +504,7 @@ ${proposalText}
473
504
  'User-Agent': 'asdlc-cli',
474
505
  'Content-Type': 'application/json',
475
506
  },
476
- body: JSON.stringify({ labels: [labelPrefix, secondaryLabel] }),
507
+ body: JSON.stringify({ labels: labelsToApply }),
477
508
  });
478
509
  } catch { /* ignore label add error */ }
479
510
  }
@@ -485,7 +516,7 @@ ${proposalText}
485
516
  try {
486
517
  const projectId = encodeURIComponent(remoteInfo.repoPath);
487
518
  const apiUrl = `${remoteInfo.protocol}//${remoteInfo.host}/api/v4/projects/${projectId}/merge_requests`;
488
- const res = await fetch(apiUrl, {
519
+ const res = await doFetch(apiUrl, {
489
520
  method: 'POST',
490
521
  headers: {
491
522
  'PRIVATE-TOKEN': glToken,
@@ -545,7 +576,10 @@ ${proposalText}
545
576
  writeText(metaPath, metaTextUpdated);
546
577
  }
547
578
 
548
- return { slug, type: prType, title, targetBranch, prUrl, labels: [labelPrefix, secondaryLabel] };
579
+ const numMatch = prUrl ? String(prUrl).match(/(?:pull|merge_requests)\/(\d+)/) : null;
580
+ const number = numMatch ? parseInt(numMatch[1], 10) : null;
581
+
582
+ return { slug, type: prType, title, targetBranch, prUrl, number, labels: Array.from(new Set([labelPrefix, secondaryLabel, ...extraLabels])) };
549
583
  }
550
584
 
551
585
  // Backwards-compatible export