@akjamie/agentic-sdlc 0.0.0-stage → 1.0.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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -2
  3. package/assets/ci/Jenkinsfile +80 -0
  4. package/assets/ci/asdlc-ai-review.yml +65 -0
  5. package/assets/config/config.yaml +76 -0
  6. package/assets/githooks/post-merge +22 -0
  7. package/assets/githooks/pre-push +17 -0
  8. package/assets/policy/policy.yaml +46 -0
  9. package/assets/schema/schema.yaml +162 -0
  10. package/assets/schema/templates/design.md +16 -0
  11. package/assets/schema/templates/proposal.md +25 -0
  12. package/assets/schema/templates/review.md +24 -0
  13. package/assets/schema/templates/spec.md +37 -0
  14. package/assets/schema/templates/tasks.md +10 -0
  15. package/assets/skills/asdlc-apply/SKILL.md +128 -0
  16. package/assets/skills/asdlc-approve/SKILL.md +107 -0
  17. package/assets/skills/asdlc-archive/SKILL.md +48 -0
  18. package/assets/skills/asdlc-doctor/SKILL.md +82 -0
  19. package/assets/skills/asdlc-impl-review/SKILL.md +214 -0
  20. package/assets/skills/asdlc-init/SKILL.md +68 -0
  21. package/assets/skills/asdlc-lint/SKILL.md +56 -0
  22. package/assets/skills/asdlc-new/SKILL.md +74 -0
  23. package/assets/skills/asdlc-pr/SKILL.md +59 -0
  24. package/assets/skills/asdlc-review/SKILL.md +80 -0
  25. package/assets/skills/asdlc-spec-review/SKILL.md +194 -0
  26. package/assets/skills/asdlc-status/SKILL.md +49 -0
  27. package/assets/skills/asdlc-upgrade/SKILL.md +34 -0
  28. package/assets/skills/asdlc-verify/SKILL.md +55 -0
  29. package/assets/skills/batch-grill-me/SKILL.md +136 -0
  30. package/assets/skills/grilling/SKILL.md +136 -0
  31. package/bin/asdlc.js +6 -0
  32. package/package.json +43 -4
  33. package/src/cli.js +86 -0
  34. package/src/commands/apply.js +114 -0
  35. package/src/commands/approve.js +166 -0
  36. package/src/commands/archive.js +115 -0
  37. package/src/commands/doctor.js +163 -0
  38. package/src/commands/init.js +201 -0
  39. package/src/commands/lint.js +103 -0
  40. package/src/commands/new.js +142 -0
  41. package/src/commands/pr.js +495 -0
  42. package/src/commands/skills.js +184 -0
  43. package/src/commands/status.js +65 -0
  44. package/src/commands/update.js +103 -0
  45. package/src/commands/upgrade.js +175 -0
  46. package/src/commands/verify.js +229 -0
  47. package/src/index.js +3 -0
  48. package/src/lib/agents.js +73 -0
  49. package/src/lib/cliutil.js +99 -0
  50. package/src/lib/errors.js +18 -0
  51. package/src/lib/exec.js +19 -0
  52. package/src/lib/fs.js +83 -0
  53. package/src/lib/git.js +76 -0
  54. package/src/lib/graphify.js +106 -0
  55. package/src/lib/log.js +15 -0
  56. package/src/lib/openspec.js +91 -0
  57. package/src/lib/paths.js +43 -0
  58. package/src/lib/policy.js +54 -0
  59. package/src/lib/prtype.js +41 -0
  60. package/src/lib/schema.js +86 -0
  61. package/src/lib/speclint.js +168 -0
  62. package/src/lib/tdd.js +71 -0
  63. package/src/lib/yaml.js +18 -0
@@ -0,0 +1,495 @@
1
+ import path from 'node:path';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { exists, readText, writeText } from '../lib/fs.js';
4
+ import { changeDir } from '../lib/paths.js';
5
+ import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
6
+ import { git, isGitRepo, changeOnRef, lastCommitTouching } from '../lib/git.js';
7
+ import { runLint } from './lint.js';
8
+ import { runVerify } from './verify.js';
9
+ import { fail } from '../lib/errors.js';
10
+ import { log } from '../lib/log.js';
11
+
12
+ export const ASDLC_LABELS = {
13
+ 'asdlc:spec-review': {
14
+ color: '1d76db',
15
+ description: 'Agentic SDLC: Spec PR undergoing AI and domain review',
16
+ },
17
+ 'asdlc:impl-review': {
18
+ color: '5319e7',
19
+ description: 'Agentic SDLC: Implementation PR undergoing AI and verification review',
20
+ },
21
+ 'spec': {
22
+ color: 'bfdadc',
23
+ description: 'Agentic SDLC: Specification draft or delta',
24
+ },
25
+ 'impl': {
26
+ color: '0e8a16',
27
+ description: 'Agentic SDLC: Verified implementation',
28
+ },
29
+ };
30
+
31
+ export function ensureRemoteLabels(repoRoot, labelNames = Object.keys(ASDLC_LABELS)) {
32
+ for (const name of labelNames) {
33
+ const meta = ASDLC_LABELS[name];
34
+ if (!meta) continue;
35
+ try {
36
+ execFileSync('gh', [
37
+ 'label', 'create', name,
38
+ '--description', meta.description,
39
+ '--color', meta.color,
40
+ '--force',
41
+ ], { cwd: repoRoot, stdio: 'ignore' });
42
+ } catch {
43
+ // ignore if gh is not installed, not authenticated, or not a GitHub repo
44
+ }
45
+ }
46
+ }
47
+
48
+ export async function createPR(changeId, targetBranch, opts = {}) {
49
+ const repoRoot = requireRepo(opts);
50
+ if (!isGitRepo(repoRoot)) fail('not a git repository');
51
+
52
+ if (!targetBranch) {
53
+ fail('target branch is required (e.g. `asdlc pr <changeId> main` or `asdlc pr <changeId> develop`)', {
54
+ code: 'MISSING_TARGET_BRANCH',
55
+ hint: 'specify the base branch to merge into: asdlc pr <changeId> <targetBranch>',
56
+ });
57
+ }
58
+
59
+ const slug = toChangeSlug(changeId);
60
+ const cdir = changeDir(repoRoot, slug);
61
+ if (!exists(cdir)) fail(`change '${slug}' not found`);
62
+
63
+ // Detect PR type 100% automatically (Spec PR vs Impl PR)
64
+ const metaPath = path.join(cdir, '.openspec.yaml');
65
+ const metaText = exists(metaPath) ? readText(metaPath) : '';
66
+ const statusMatch = metaText.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
67
+ const changeStatus = statusMatch ? statusMatch[1].toLowerCase() : '';
68
+ const shaMatch = metaText.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
69
+ const specSha = shaMatch ? shaMatch[1] : null;
70
+
71
+ const tasksPath = path.join(cdir, 'tasks.md');
72
+ const tasksText = exists(tasksPath) ? readText(tasksPath) : '';
73
+ const uncheckedCount = (tasksText.match(/^\s*-\s+\[\s\]/gm) ?? []).length;
74
+ const checkedCount = (tasksText.match(/^\s*-\s+\[[xX]\]/gm) ?? []).length;
75
+
76
+ const currentBranch = (git(['rev-parse', '--abbrev-ref', 'HEAD'], repoRoot) ?? '').trim();
77
+ if (currentBranch === targetBranch) {
78
+ fail(`cannot create a PR from '${currentBranch}' into itself. Please switch to a feature branch first (e.g. \`git checkout -b spec/${slug}\` or \`git checkout -b impl/${slug}\`)`);
79
+ }
80
+
81
+ // Check if the spec is already approved/merged into targetBranch
82
+ const isApprovedOnTarget = changeOnRef(repoRoot, targetBranch, slug)
83
+ || changeOnRef(repoRoot, `origin/${targetBranch}`, slug)
84
+ || Boolean(lastCommitTouching(repoRoot, targetBranch, [`openspec/changes/${slug}/proposal.md`]));
85
+
86
+ // Check git diff or status for source code changes outside openspec/changes/<slug>
87
+ const diffFiles = (git(['diff', '--name-only', `${targetBranch}...HEAD`], repoRoot, { allowFail: true }) ?? '')
88
+ .split(/\r?\n/).filter(Boolean);
89
+ const hasSourceChanges = diffFiles.some((f) => !f.startsWith(`openspec/changes/${slug}/`));
90
+
91
+ let prType;
92
+ if (opts.type) {
93
+ prType = opts.type.toLowerCase();
94
+ } else if (
95
+ isApprovedOnTarget ||
96
+ changeStatus === 'ready_for_impl' ||
97
+ Boolean(specSha) ||
98
+ currentBranch.startsWith('impl/') ||
99
+ (hasSourceChanges && (checkedCount > 0 || uncheckedCount === 0))
100
+ ) {
101
+ prType = 'impl';
102
+ } else {
103
+ prType = 'spec';
104
+ }
105
+
106
+ const isSpec = prType === 'spec';
107
+ const labelPrefix = isSpec ? 'asdlc:spec-review' : 'asdlc:impl-review';
108
+ const secondaryLabel = isSpec ? 'spec' : 'impl';
109
+ const prTypeName = isSpec ? 'Spec PR' : 'Implementation PR';
110
+
111
+ // 1. Pre-flight self-check
112
+ if (isSpec) {
113
+ log.step(`running spec lint pre-flight for ${slug}...`);
114
+ const lintExit = runLint(slug, { repoRoot, json: true });
115
+ if (lintExit !== 0) {
116
+ fail(`spec lint failed; fix all blocking findings before opening the Spec PR (run \`asdlc lint ${slug}\`)`);
117
+ }
118
+ log.ok('spec lint passed (0 blockers)');
119
+ } else {
120
+ log.step(`running implementation verify pre-flight for ${slug}...`);
121
+ const verifyExit = runVerify(slug, {
122
+ repoRoot,
123
+ base: targetBranch,
124
+ protectedBranch: targetBranch,
125
+ ...opts,
126
+ });
127
+ if (verifyExit !== 0) {
128
+ fail(`implementation verification failed; all 12 gates must pass before opening the Implementation PR (run \`asdlc verify ${slug}\`)`);
129
+ }
130
+ log.ok('implementation verify passed (all 12 gates passed)');
131
+ }
132
+
133
+ // 2. Extract Title and Description from proposal.md
134
+ const proposalPath = path.join(cdir, 'proposal.md');
135
+ if (!exists(proposalPath)) fail(`proposal.md missing for ${slug}`);
136
+ const proposalText = readText(proposalPath);
137
+
138
+ let title = `${isSpec ? 'spec' : 'impl'}(${slug})`;
139
+ const titleMatch = proposalText.match(/^#\s*(?:Proposal:\s*)?([^\n\r]+)/im);
140
+ if (titleMatch && titleMatch[1]) {
141
+ const raw = titleMatch[1].replace(/<!--[\s\S]*?-->/g, '').trim();
142
+ if (raw) title = `${isSpec ? 'spec' : 'impl'}(${slug}): ${raw}`;
143
+ }
144
+
145
+ // 3. Stage & commit any unstaged changes
146
+ try {
147
+ if (isSpec) {
148
+ git(['add', `openspec/changes/${slug}`], repoRoot);
149
+ const status = git(['status', '--porcelain', `openspec/changes/${slug}`], repoRoot);
150
+ if (status) {
151
+ execFileSync('git', ['commit', '-m', `spec(${slug}): specify feature intent`], { cwd: repoRoot, stdio: 'ignore' });
152
+ log.ok('committed latest spec changes');
153
+ }
154
+ } else {
155
+ git(['add', '-A'], repoRoot);
156
+ const status = git(['status', '--porcelain'], repoRoot);
157
+ if (status) {
158
+ execFileSync('git', ['commit', '-m', `impl(${slug}): implement verified changes`], { cwd: repoRoot, stdio: 'ignore' });
159
+ log.ok('committed latest implementation changes');
160
+ }
161
+ }
162
+ } catch { /* ignore */ }
163
+
164
+ // 4. Push to remote
165
+ log.step(`pushing branch '${currentBranch}' to origin...`);
166
+ try {
167
+ execFileSync('git', ['push', '-u', 'origin', currentBranch], { cwd: repoRoot, stdio: 'inherit' });
168
+ log.ok(`pushed branch '${currentBranch}' to origin`);
169
+ } catch (err) {
170
+ log.warn(`git push skipped or failed: ${err.message}`);
171
+ }
172
+
173
+ // 5. Build PR body
174
+ let body = '';
175
+ if (isSpec) {
176
+ body = `## 🤖 Agentic SDLC — Spec Review
177
+
178
+ **Change ID**: \`${slug}\`
179
+ **Target Branch**: \`${targetBranch}\`
180
+ **Spec Branch**: \`${currentBranch}\`
181
+
182
+ ---
183
+
184
+ ${proposalText}
185
+ `;
186
+ } else {
187
+ body = `## 🤖 Agentic SDLC — Implementation Review
188
+
189
+ **Change ID**: \`${slug}\`
190
+ **Target Branch**: \`${targetBranch}\`
191
+ **Implementation Branch**: \`${currentBranch}\`
192
+
193
+ ### 📋 Completed Tasks & TDD Evidence
194
+ ${tasksText || '(no tasks recorded)'}
195
+
196
+ ---
197
+
198
+ ### 🎯 Approved Intent
199
+ ${proposalText}
200
+ `;
201
+ }
202
+
203
+ // 6. Multi-tier PR creation strategy:
204
+ // Tier 1: Platform CLI (gh / glab)
205
+ // Tier 2: Direct REST API (GITHUB_TOKEN / GITLAB_TOKEN)
206
+ // Tier 3: 1-click Web compare URL fallback
207
+ let prCreated = false;
208
+ let prUrl = null;
209
+
210
+ // Detect remote repository information
211
+ const remoteUrl = git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true });
212
+ const remoteInfo = parseRemoteUrl(remoteUrl);
213
+
214
+ // Pre-provision governance labels on remote before PR creation (so gh pr create doesn't reject unknown labels)
215
+ if (remoteInfo?.isGitHub) {
216
+ ensureRemoteLabels(repoRoot, [labelPrefix, secondaryLabel]);
217
+ }
218
+
219
+ // Attempt Tier 1: CLI (gh)
220
+ try {
221
+ const out = execFileSync('gh', [
222
+ 'pr', 'create',
223
+ '--title', title,
224
+ '--body', body,
225
+ '--base', targetBranch,
226
+ '--head', currentBranch,
227
+ '--label', `${labelPrefix},${secondaryLabel}`,
228
+ ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
229
+ prCreated = true;
230
+ prUrl = out.trim();
231
+ } catch {
232
+ try {
233
+ const out = execFileSync('gh', [
234
+ 'pr', 'create',
235
+ '--title', title,
236
+ '--body', body,
237
+ '--base', targetBranch,
238
+ '--head', currentBranch,
239
+ '--label', labelPrefix,
240
+ ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
241
+ prCreated = true;
242
+ prUrl = out.trim();
243
+ } catch {
244
+ try {
245
+ const out = execFileSync('gh', [
246
+ 'pr', 'create',
247
+ '--title', title,
248
+ '--body', body,
249
+ '--base', targetBranch,
250
+ '--head', currentBranch,
251
+ ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
252
+ prCreated = true;
253
+ prUrl = out.trim();
254
+ } catch {
255
+ // Check if PR for current branch already exists on GitHub
256
+ try {
257
+ const existingOut = execFileSync('gh', [
258
+ 'pr', 'view', currentBranch,
259
+ '--json', 'url',
260
+ '-q', '.url',
261
+ ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
262
+ if (existingOut && existingOut.trim()) {
263
+ prCreated = true;
264
+ prUrl = existingOut.trim();
265
+ }
266
+ } catch {
267
+ // gh not available or failed
268
+ }
269
+ }
270
+ }
271
+ }
272
+
273
+ // If created or found via gh, guarantee labels are attached even if initial create omitted them
274
+ if (prCreated && remoteInfo?.isGitHub) {
275
+ try {
276
+ execFileSync('gh', [
277
+ 'pr', 'edit', currentBranch,
278
+ '--add-label', `${labelPrefix},${secondaryLabel}`,
279
+ ], { cwd: repoRoot, stdio: 'ignore' });
280
+ } catch {
281
+ // ignore
282
+ }
283
+ }
284
+
285
+ // Attempt Tier 1: CLI (glab for GitLab)
286
+ if (!prCreated) {
287
+ try {
288
+ const out = execFileSync('glab', [
289
+ 'mr', 'create',
290
+ '--title', title,
291
+ '--description', body,
292
+ '--target-branch', targetBranch,
293
+ '--source-branch', currentBranch,
294
+ '--label', `${labelPrefix},${secondaryLabel}`,
295
+ ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
296
+ prCreated = true;
297
+ prUrl = out.trim();
298
+ } catch {
299
+ // glab not available
300
+ }
301
+ }
302
+
303
+ // Attempt Tier 2: Direct REST API via fetch (Node 20+)
304
+ if (!prCreated && remoteInfo) {
305
+ const ghToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
306
+ const glToken = process.env.GITLAB_TOKEN || process.env.CI_JOB_TOKEN || process.env.GL_TOKEN;
307
+
308
+ if (remoteInfo.isGitHub && ghToken) {
309
+ try {
310
+ const apiBase = remoteInfo.host === 'github.com'
311
+ ? 'https://api.github.com'
312
+ : `${remoteInfo.protocol}//${remoteInfo.host}/api/v3`;
313
+ const apiUrl = `${apiBase}/repos/${remoteInfo.repoPath}/pulls`;
314
+ const res = await fetch(apiUrl, {
315
+ method: 'POST',
316
+ headers: {
317
+ 'Authorization': `Bearer ${ghToken}`,
318
+ 'Accept': 'application/vnd.github+json',
319
+ 'User-Agent': 'asdlc-cli',
320
+ 'Content-Type': 'application/json',
321
+ },
322
+ body: JSON.stringify({
323
+ title,
324
+ body,
325
+ head: currentBranch,
326
+ base: targetBranch,
327
+ }),
328
+ });
329
+ if (res.ok) {
330
+ const data = await res.json();
331
+ prCreated = true;
332
+ prUrl = data.html_url;
333
+
334
+ // Attach labels via GitHub Issues API (pull requests are issues in GitHub)
335
+ if (data.number) {
336
+ // Pre-create labels if missing
337
+ for (const lbl of [labelPrefix, secondaryLabel]) {
338
+ const meta = ASDLC_LABELS[lbl];
339
+ try {
340
+ await fetch(`${apiBase}/repos/${remoteInfo.repoPath}/labels`, {
341
+ method: 'POST',
342
+ headers: {
343
+ 'Authorization': `Bearer ${ghToken}`,
344
+ 'Accept': 'application/vnd.github+json',
345
+ 'User-Agent': 'asdlc-cli',
346
+ 'Content-Type': 'application/json',
347
+ },
348
+ body: JSON.stringify({
349
+ name: lbl,
350
+ color: meta?.color || '1d76db',
351
+ description: meta?.description || '',
352
+ }),
353
+ });
354
+ } catch { /* already exists or ignored */ }
355
+ }
356
+
357
+ try {
358
+ const labelUrl = `${apiBase}/repos/${remoteInfo.repoPath}/issues/${data.number}/labels`;
359
+ await fetch(labelUrl, {
360
+ method: 'POST',
361
+ headers: {
362
+ 'Authorization': `Bearer ${ghToken}`,
363
+ 'Accept': 'application/vnd.github+json',
364
+ 'User-Agent': 'asdlc-cli',
365
+ 'Content-Type': 'application/json',
366
+ },
367
+ body: JSON.stringify({ labels: [labelPrefix, secondaryLabel] }),
368
+ });
369
+ } catch { /* ignore label add error */ }
370
+ }
371
+ }
372
+ } catch {
373
+ // API attempt failed
374
+ }
375
+ } else if (remoteInfo.isGitLab && glToken) {
376
+ try {
377
+ const projectId = encodeURIComponent(remoteInfo.repoPath);
378
+ const apiUrl = `${remoteInfo.protocol}//${remoteInfo.host}/api/v4/projects/${projectId}/merge_requests`;
379
+ const res = await fetch(apiUrl, {
380
+ method: 'POST',
381
+ headers: {
382
+ 'PRIVATE-TOKEN': glToken,
383
+ 'User-Agent': 'asdlc-cli',
384
+ 'Content-Type': 'application/json',
385
+ },
386
+ body: JSON.stringify({
387
+ title,
388
+ description: body,
389
+ source_branch: currentBranch,
390
+ target_branch: targetBranch,
391
+ labels: `${labelPrefix},${secondaryLabel}`,
392
+ }),
393
+ });
394
+ if (res.ok) {
395
+ const data = await res.json();
396
+ prCreated = true;
397
+ prUrl = data.web_url;
398
+ }
399
+ } catch {
400
+ // GitLab API attempt failed
401
+ }
402
+ }
403
+ }
404
+
405
+ if (prCreated && prUrl) {
406
+ log.ok(`${prTypeName} automatically created: ${prUrl}`);
407
+ } else {
408
+ log.info('');
409
+ log.ok(`Branch '${currentBranch}' pushed and ready for ${prTypeName}.`);
410
+ log.info(`Target: ${targetBranch} | Title: "${title}" | Labels: ${labelPrefix}, ${secondaryLabel}`);
411
+
412
+ // Tier 3: Browser 1-click fallback link
413
+ if (remoteInfo) {
414
+ if (remoteInfo.isGitHub) {
415
+ const webUrl = `${remoteInfo.protocol}//${remoteInfo.host}/${remoteInfo.repoPath}/compare/${targetBranch}...${currentBranch}?expand=1&labels=${secondaryLabel},${labelPrefix}`;
416
+ log.info(`👉 Click to open and create PR in browser: ${webUrl}`);
417
+ } else if (remoteInfo.isGitLab) {
418
+ const webUrl = `${remoteInfo.protocol}//${remoteInfo.host}/${remoteInfo.repoPath}/-/merge_requests/new?merge_request[source_branch]=${currentBranch}&merge_request[target_branch]=${targetBranch}&merge_request[labels]=${labelPrefix},${secondaryLabel}`;
419
+ log.info(`👉 Click to open and create MR in browser: ${webUrl}`);
420
+ }
421
+ } else {
422
+ log.info(`(Install 'gh' / 'glab' CLI or set GITHUB_TOKEN for 1-click automatic PR creation)`);
423
+ }
424
+ }
425
+
426
+ // Persist targetBranch and prUrl to .openspec.yaml for full traceability
427
+ if (exists(metaPath)) {
428
+ let metaTextUpdated = readText(metaPath);
429
+ const upsertKey = (text, key, val) => {
430
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
431
+ return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
432
+ };
433
+ metaTextUpdated = upsertKey(metaTextUpdated, 'targetBranch', targetBranch);
434
+ metaTextUpdated = upsertKey(metaTextUpdated, 'lastPrType', prType);
435
+ if (prUrl) metaTextUpdated = upsertKey(metaTextUpdated, 'prUrl', prUrl);
436
+ writeText(metaPath, metaTextUpdated);
437
+ }
438
+
439
+ return { slug, type: prType, title, targetBranch, prUrl, labels: [labelPrefix, secondaryLabel] };
440
+ }
441
+
442
+ // Backwards-compatible export
443
+ export function createSpecPR(changeId, targetBranch, opts = {}) {
444
+ return createPR(changeId, targetBranch, { type: 'spec', ...opts });
445
+ }
446
+
447
+ export function parseRemoteUrl(url, opts = {}) {
448
+ if (!url) return null;
449
+ const cleaned = url.trim().replace(/\.git$/, '');
450
+ let host = '';
451
+ let repoPath = '';
452
+ let protocol = 'https:';
453
+
454
+ const sshMatch = cleaned.match(/^git@([^:]+):(.+)$/);
455
+ if (sshMatch) {
456
+ host = sshMatch[1];
457
+ repoPath = sshMatch[2];
458
+ } else {
459
+ try {
460
+ const u = new URL(cleaned);
461
+ host = u.host;
462
+ protocol = u.protocol || 'https:';
463
+ repoPath = u.pathname.replace(/^\//, '');
464
+ } catch {
465
+ return null;
466
+ }
467
+ }
468
+
469
+ const explicitPlatform = (opts.platform || process.env.ASDLC_GIT_PLATFORM || process.env.GIT_PLATFORM || '').toLowerCase();
470
+ const isGitLab = explicitPlatform === 'gitlab'
471
+ || host.includes('gitlab')
472
+ || (!host.includes('github') && Boolean(process.env.GITLAB_TOKEN || process.env.CI_JOB_TOKEN || process.env.GL_TOKEN));
473
+ const isGitHub = explicitPlatform === 'github'
474
+ || host.includes('github')
475
+ || (!isGitLab);
476
+
477
+ return {
478
+ host,
479
+ repoPath,
480
+ protocol,
481
+ isGitHub,
482
+ isGitLab,
483
+ };
484
+ }
485
+
486
+ export function register(program) {
487
+ program
488
+ .command('pr <changeId> <targetBranch>')
489
+ .description('automatically open a Spec or Implementation PR: auto-detects stage, pre-flight checks, pushes branch, and attaches labels for CI AI review')
490
+ .option('--repo-root <path>')
491
+ .action(async (changeId, targetBranch, opts) => {
492
+ await createPR(changeId, targetBranch, opts);
493
+ });
494
+ }
495
+
@@ -0,0 +1,184 @@
1
+ import path from 'node:path';
2
+ import os from 'node:os';
3
+ import fs from 'node:fs';
4
+ import { exists, listDir, readText, copyTree, ensureDir } from '../lib/fs.js';
5
+ import { skillsAssetDir, resolveRepoRoot, openspecDir } from '../lib/paths.js';
6
+ import { detectTools, installSkills } from './init.js';
7
+ import { fail } from '../lib/errors.js';
8
+ import { log } from '../lib/log.js';
9
+
10
+ // Standard agent tools and their home/global directories
11
+ const GLOBAL_TOOL_DIRS = {
12
+ agents: '.agents',
13
+ opencode: '.opencode',
14
+ pi: '.pi',
15
+ dsh: '.dsh',
16
+ claude: '.claude',
17
+ cursor: '.cursor',
18
+ codex: '.codex',
19
+ trae: '.trae',
20
+ zed: '.zed',
21
+ gemini: '.gemini',
22
+ };
23
+
24
+ /**
25
+ * Parse YAML frontmatter from a SKILL.md file
26
+ */
27
+ function parseSkillMetadata(skillDir) {
28
+ const skillFile = path.join(skillDir, 'SKILL.md');
29
+ if (!exists(skillFile)) return null;
30
+ const content = readText(skillFile);
31
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
32
+ if (!match) return { name: path.basename(skillDir), description: '' };
33
+
34
+ const frontmatter = match[1];
35
+ const nameMatch = frontmatter.match(/^name:\s*(.+)$/m);
36
+ const descMatch = frontmatter.match(/^description:\s*["']?([\s\S]*?)["']?$/m);
37
+
38
+ return {
39
+ name: nameMatch ? nameMatch[1].trim() : path.basename(skillDir),
40
+ description: descMatch ? descMatch[1].trim().replace(/\r?\n/g, ' ') : '',
41
+ };
42
+ }
43
+
44
+ /**
45
+ * List all available bundled skills
46
+ */
47
+ export function listSkills() {
48
+ if (!exists(skillsAssetDir)) {
49
+ log.warn('No bundled skills asset directory found.');
50
+ return;
51
+ }
52
+
53
+ const dirs = listDir(skillsAssetDir).filter((d) => d.isDirectory());
54
+ log.info(`Bundled Agent Skills (${dirs.length} available):`);
55
+ log.info('');
56
+
57
+ for (const d of dirs) {
58
+ const meta = parseSkillMetadata(path.join(skillsAssetDir, d.name));
59
+ if (meta) {
60
+ log.info(` • ${meta.name.padEnd(20)} ${meta.description}`);
61
+ } else {
62
+ log.info(` • ${d.name}`);
63
+ }
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Install or link skills globally (for CI Linux VM or headless agent runners)
69
+ */
70
+ export function installGlobalSkills(opts = {}) {
71
+ const home = os.homedir();
72
+ if (!exists(skillsAssetDir)) {
73
+ log.error(`Skills assets not found at: ${skillsAssetDir}`);
74
+ return 1;
75
+ }
76
+
77
+ const skillsCount = listDir(skillsAssetDir).filter((d) => d.isDirectory()).length;
78
+ const useLink = Boolean(opts.link);
79
+
80
+ // Determine target tool directories in user home
81
+ let targets = new Set(['.agents']);
82
+
83
+ if (opts.tools) {
84
+ const requested = opts.tools.split(',').map((t) => t.trim().toLowerCase());
85
+ for (const tool of requested) {
86
+ if (tool === 'all') {
87
+ Object.values(GLOBAL_TOOL_DIRS).forEach((dir) => targets.add(dir));
88
+ } else {
89
+ const clean = tool.replace(/^\./, '');
90
+ targets.add(GLOBAL_TOOL_DIRS[clean] || `.${clean}`);
91
+ }
92
+ }
93
+ } else {
94
+ // If no explicit tools given, always install to .agents (universal)
95
+ // plus any detected tool directories present in home
96
+ for (const [tool, dir] of Object.entries(GLOBAL_TOOL_DIRS)) {
97
+ if (exists(path.join(home, dir))) {
98
+ targets.add(dir);
99
+ }
100
+ }
101
+ }
102
+
103
+ log.step(`Installing bundled skills globally (${skillsCount} skills) into user home...`);
104
+
105
+ let installedCount = 0;
106
+ for (const dir of targets) {
107
+ const dest = path.join(home, dir, 'skills');
108
+ ensureDir(dest);
109
+
110
+ if (useLink) {
111
+ // Symlink individual skills or the entire tree
112
+ let symlinkOk = true;
113
+ try {
114
+ const subdirs = listDir(skillsAssetDir).filter((d) => d.isDirectory());
115
+ for (const sub of subdirs) {
116
+ const srcSkill = path.join(skillsAssetDir, sub.name);
117
+ const destSkill = path.join(dest, sub.name);
118
+ if (exists(destSkill)) {
119
+ try { fs.rmSync(destSkill, { recursive: true, force: true }); } catch { /* ignore */ }
120
+ }
121
+ fs.symlinkSync(srcSkill, destSkill, 'junction');
122
+ }
123
+ log.ok(`symlinked skills -> ~/${dir}/skills/ (live link)`);
124
+ installedCount++;
125
+ } catch (err) {
126
+ log.warn(`symlink failed for ~/${dir}/skills/: ${err.message}. Falling back to copy...`);
127
+ symlinkOk = false;
128
+ }
129
+ if (!symlinkOk) {
130
+ copyTree(skillsAssetDir, dest);
131
+ log.ok(`copied skills -> ~/${dir}/skills/`);
132
+ installedCount++;
133
+ }
134
+ } else {
135
+ copyTree(skillsAssetDir, dest);
136
+ log.ok(`installed skills -> ~/${dir}/skills/`);
137
+ installedCount++;
138
+ }
139
+ }
140
+
141
+ log.info('');
142
+ log.ok(`Global skills setup complete (${installedCount} target agent directories).`);
143
+ return 0;
144
+ }
145
+
146
+ /**
147
+ * CLI command registration
148
+ */
149
+ export function register(program) {
150
+ const skillsCmd = program
151
+ .command('skills')
152
+ .description('manage and install bundled agent skills for workspace or global CI agents');
153
+
154
+ skillsCmd
155
+ .command('list')
156
+ .description('list all bundled agent skills available in agentic-sdlc')
157
+ .action(() => {
158
+ listSkills();
159
+ });
160
+
161
+ skillsCmd
162
+ .command('install')
163
+ .description('install skills to repository workspace, or globally for CI/headless agents')
164
+ .option('-g, --global', 'install globally to user home (~/.agents, ~/.opencode, etc.) for CI runners')
165
+ .option('--tools <tools>', 'comma-separated list of target agent tools (e.g. opencode,pi,dsh,claude or "all")')
166
+ .option('--link', 'create symbolic links instead of copying (auto-updates when package is updated)')
167
+ .option('--repo-root <path>', 'repository root path (default: current workspace)')
168
+ .action((opts) => {
169
+ if (opts.global) {
170
+ process.exitCode = installGlobalSkills(opts);
171
+ } else {
172
+ const repoRoot = resolveRepoRoot(opts);
173
+ if (!exists(openspecDir(repoRoot))) {
174
+ fail('no OpenSpec repository found in current directory', {
175
+ hint: 'To install skills globally on a CI VM or headless environment, pass --global: asdlc skills install --global',
176
+ });
177
+ }
178
+ const explicit = opts.tools ? opts.tools.split(',').map((s) => s.trim().toLowerCase()) : [];
179
+ const tools = [...new Set([...detectTools(repoRoot), ...explicit])];
180
+ installSkills(repoRoot, tools);
181
+ log.ok('Repository skills refreshed successfully.');
182
+ }
183
+ });
184
+ }