@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,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) => {
@@ -6,30 +6,9 @@ import { runShell } from '../lib/exec.js';
6
6
  import { fail } from '../lib/errors.js';
7
7
  import { log } from '../lib/log.js';
8
8
  import { readYaml } from '../lib/yaml.js';
9
+ import { parseSpecAcceptanceCriteria } from '../lib/tasks-gen.js';
9
10
 
10
- export function parseSpecAcceptanceCriteria(specText) {
11
- const acs = [];
12
- const lines = specText.split('\n');
13
- let currentReq = '';
14
-
15
- for (const line of lines) {
16
- const reqMatch = line.match(/^###\s+Requirement:\s*(.+?)\s*$/);
17
- if (reqMatch) {
18
- currentReq = reqMatch[1];
19
- continue;
20
- }
21
- const acMatch = line.match(/^\s*-\s*\[[ xX]\]\s*(AC\d+)\s*:\s*(.+)$/);
22
- if (!acMatch) continue;
23
- const testMatch = line.match(/\(test:\s*([^)]+?)\s*\)/i);
24
- acs.push({
25
- id: acMatch[1],
26
- requirement: currentReq,
27
- text: acMatch[2].replace(/\(test:.*$/i, '').trim(),
28
- testPath: testMatch ? testMatch[1].trim() : null,
29
- });
30
- }
31
- return acs;
32
- }
11
+ export { parseSpecAcceptanceCriteria };
33
12
 
34
13
  export function runTests(changeId, opts = {}) {
35
14
  const repoRoot = requireRepo(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);
@@ -0,0 +1,248 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { AsdlcError } from '../errors.js';
3
+ import { git } from '../git.js';
4
+ import { parseRemoteUrl } from '../remote.js';
5
+
6
+ export const PULL_REQUEST_THREADS_QUERY = `
7
+ query PullRequestReviewThreads($owner: String!, $repo: String!, $number: Int!) {
8
+ repository(owner: $owner, name: $repo) {
9
+ pullRequest(number: $number) {
10
+ reviewDecision
11
+ headRefOid
12
+ commits(last: 1) { nodes { commit { committedDate, oid } } }
13
+ reviewThreads(first: 100) {
14
+ pageInfo { hasNextPage endCursor }
15
+ nodes {
16
+ id
17
+ isResolved
18
+ isOutdated
19
+ path
20
+ line
21
+ originalLine
22
+ comments(last: 20) {
23
+ pageInfo { hasPreviousPage }
24
+ nodes {
25
+ id
26
+ databaseId
27
+ author { login }
28
+ body
29
+ createdAt
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }`.trim();
37
+
38
+ const REPLY_THREAD_MUTATION =
39
+ 'mutation ReplyThread($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }';
40
+
41
+ const RESOLVE_THREAD_MUTATION =
42
+ 'mutation ResolveThread($threadId: ID!) { resolveReviewThread(input: { threadId: $threadId }) { thread { isResolved } } }';
43
+
44
+ function defaultExec(repoRoot) {
45
+ return (cmd, args) => spawnSync(cmd, args, {
46
+ cwd: repoRoot || process.cwd(),
47
+ encoding: 'utf8',
48
+ timeout: 10000,
49
+ });
50
+ }
51
+
52
+ function normalizeThread(t) {
53
+ const comments = Array.isArray(t?.comments?.nodes)
54
+ ? t.comments.nodes
55
+ : (Array.isArray(t?.comments) ? t.comments : []);
56
+ return {
57
+ id: t?.id ?? null,
58
+ isResolved: Boolean(t?.isResolved),
59
+ isOutdated: Boolean(t?.isOutdated),
60
+ path: t?.path ?? null,
61
+ line: t?.line ?? null,
62
+ originalLine: t?.originalLine ?? null,
63
+ comments,
64
+ };
65
+ }
66
+
67
+ function resolveOwnerRepo(repoRoot, remoteUrl) {
68
+ const url = remoteUrl || (repoRoot ? git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true }) : '');
69
+ const parsed = parseRemoteUrl(url);
70
+ if (!parsed?.repoPath) return { owner: '', repo: '' };
71
+ const parts = parsed.repoPath.split('/').filter(Boolean);
72
+ if (parts.length < 2) return { owner: '', repo: '' };
73
+ return {
74
+ owner: parts.slice(0, -1).join('/'),
75
+ repo: parts[parts.length - 1],
76
+ };
77
+ }
78
+
79
+ export function createGitHubAdapter({ repoRoot = null, remoteUrl = null, exec = null } = {}) {
80
+ const run = exec || defaultExec(repoRoot);
81
+
82
+ function ensureOk(res, code, context) {
83
+ if (!res || res.status !== 0) {
84
+ const detail = (res?.stderr || res?.stdout || res?.error?.message || '').trim();
85
+ throw new AsdlcError(`${context} failed${detail ? `: ${detail}` : ''}`, {
86
+ code,
87
+ exitCode: 1,
88
+ detail,
89
+ });
90
+ }
91
+ }
92
+
93
+ return {
94
+ platform: 'github',
95
+
96
+ fetchThreads({ pr, owner: explicitOwner, repo: explicitRepo }) {
97
+ const prRef = String(pr ?? '').replace(/^#/, '');
98
+ const prNum = Number(prRef);
99
+ if (!prRef || !Number.isFinite(prNum) || prNum <= 0) {
100
+ throw new AsdlcError(`Invalid PR number: ${pr}`, { code: 'PR_FETCH_FAILED', exitCode: 1 });
101
+ }
102
+
103
+ const resolved = resolveOwnerRepo(repoRoot, remoteUrl);
104
+ const owner = explicitOwner ?? resolved.owner;
105
+ const repo = explicitRepo ?? resolved.repo;
106
+
107
+ const gqlRes = run('gh', [
108
+ 'api', 'graphql',
109
+ '-f', `owner=${owner}`,
110
+ '-f', `repo=${repo}`,
111
+ '-F', `number=${prNum}`,
112
+ '-f', `query=${PULL_REQUEST_THREADS_QUERY}`,
113
+ ]);
114
+ ensureOk(gqlRes, 'PR_FETCH_FAILED', `gh api graphql for PR #${prNum}`);
115
+
116
+ let gqlJson;
117
+ try {
118
+ gqlJson = JSON.parse(gqlRes.stdout || '{}');
119
+ } catch (err) {
120
+ throw new AsdlcError(`Failed to parse GitHub GraphQL response: ${err.message}`, {
121
+ code: 'PR_FETCH_FAILED',
122
+ exitCode: 1,
123
+ });
124
+ }
125
+ if (Array.isArray(gqlJson.errors) && gqlJson.errors.length > 0) {
126
+ throw new AsdlcError(`GitHub GraphQL error: ${gqlJson.errors[0]?.message || 'unknown error'}`, {
127
+ code: 'PR_FETCH_FAILED',
128
+ exitCode: 1,
129
+ });
130
+ }
131
+
132
+ const prNode = gqlJson?.data?.repository?.pullRequest;
133
+ if (!prNode) {
134
+ throw new AsdlcError(`PR #${prNum} not found or inaccessible on GitHub`, {
135
+ code: 'PR_FETCH_FAILED',
136
+ exitCode: 1,
137
+ });
138
+ }
139
+
140
+ const viewRes = run('gh', ['pr', 'view', prRef, '--json', 'comments,reviews,reviewDecision']);
141
+ ensureOk(viewRes, 'PR_FETCH_FAILED', `gh pr view for PR #${prRef}`);
142
+
143
+ let viewJson;
144
+ try {
145
+ viewJson = JSON.parse(viewRes.stdout || '{}');
146
+ } catch (err) {
147
+ throw new AsdlcError(`Failed to parse gh pr view response: ${err.message}`, {
148
+ code: 'PR_FETCH_FAILED',
149
+ exitCode: 1,
150
+ });
151
+ }
152
+
153
+ const rawThreads = prNode.reviewThreads?.nodes || [];
154
+ const hasNextPage = Boolean(prNode.reviewThreads?.pageInfo?.hasNextPage);
155
+ const issueComments = Array.isArray(viewJson?.comments) ? viewJson.comments : [];
156
+ const reviews = Array.isArray(viewJson?.reviews) ? viewJson.reviews : [];
157
+ const reviewDecision = prNode.reviewDecision || viewJson?.reviewDecision || null;
158
+
159
+ const warnings = [];
160
+ if (hasNextPage || rawThreads.length >= 100) {
161
+ warnings.push('[WARN] GitHub reviewThreads reached the 100-thread cap; results may be truncated.');
162
+ }
163
+ for (const t of rawThreads) {
164
+ const count = Array.isArray(t?.comments?.nodes) ? t.comments.nodes.length : (Array.isArray(t?.comments) ? t.comments.length : 0);
165
+ if (t?.comments?.pageInfo?.hasPreviousPage || count >= 20) {
166
+ warnings.push(`[WARN] GitHub review thread ${t?.id || 'unknown'} reached the 20-comment cap; earlier comments may be truncated.`);
167
+ }
168
+ }
169
+
170
+ return {
171
+ reviewDecision,
172
+ reviewThreads: rawThreads,
173
+ threads: rawThreads.map(normalizeThread),
174
+ issueComments,
175
+ reviews,
176
+ warnings,
177
+ };
178
+ },
179
+
180
+ replyThread({ threadId, body }) {
181
+ const res = run('gh', [
182
+ 'api', 'graphql',
183
+ '-f', `query=${REPLY_THREAD_MUTATION}`,
184
+ '-f', `threadId=${threadId}`,
185
+ '-f', `body=${body}`,
186
+ ]);
187
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `replyThread (${threadId})`);
188
+ if (res.stdout) {
189
+ try {
190
+ const parsed = JSON.parse(res.stdout);
191
+ if (Array.isArray(parsed?.errors) && parsed.errors.length > 0) {
192
+ throw new AsdlcError(`replyThread (${threadId}) GraphQL error: ${parsed.errors[0]?.message || 'unknown error'}`, {
193
+ code: 'FORGE_MUTATION_FAILED',
194
+ exitCode: 1,
195
+ });
196
+ }
197
+ } catch (err) {
198
+ if (err instanceof AsdlcError) throw err;
199
+ }
200
+ }
201
+ return { threadId, replied: true };
202
+ },
203
+
204
+ resolveThread({ threadId }) {
205
+ const res = run('gh', [
206
+ 'api', 'graphql',
207
+ '-f', `query=${RESOLVE_THREAD_MUTATION}`,
208
+ '-f', `threadId=${threadId}`,
209
+ ]);
210
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `resolveThread (${threadId})`);
211
+ if (res.stdout) {
212
+ try {
213
+ const parsed = JSON.parse(res.stdout);
214
+ if (Array.isArray(parsed?.errors) && parsed.errors.length > 0) {
215
+ throw new AsdlcError(`resolveThread (${threadId}) GraphQL error: ${parsed.errors[0]?.message || 'unknown error'}`, {
216
+ code: 'FORGE_MUTATION_FAILED',
217
+ exitCode: 1,
218
+ });
219
+ }
220
+ } catch (err) {
221
+ if (err instanceof AsdlcError) throw err;
222
+ }
223
+ }
224
+ return { threadId, resolved: true };
225
+ },
226
+
227
+ addLabel({ pr, label }) {
228
+ const prRef = String(pr ?? '').replace(/^#/, '');
229
+ const res = run('gh', ['pr', 'edit', prRef, '--add-label', label]);
230
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `addLabel (${label})`);
231
+ return { pr: prRef, label };
232
+ },
233
+
234
+ postComment({ pr, body }) {
235
+ const prRef = String(pr ?? '').replace(/^#/, '');
236
+ const res = run('gh', ['pr', 'comment', prRef, '--body', body]);
237
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `postComment (PR #${prRef})`);
238
+ return { pr: prRef, commented: true };
239
+ },
240
+
241
+ markReady({ pr }) {
242
+ const prRef = String(pr ?? '').replace(/^#/, '');
243
+ const res = run('gh', ['pr', 'ready', prRef]);
244
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `markReady (PR #${prRef})`);
245
+ return { pr: prRef, ready: true };
246
+ },
247
+ };
248
+ }
@@ -0,0 +1,185 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { AsdlcError } from '../errors.js';
3
+ import { git } from '../git.js';
4
+ import { parseRemoteUrl } from '../remote.js';
5
+
6
+ function defaultExec(repoRoot) {
7
+ return (cmd, args) => spawnSync(cmd, args, {
8
+ cwd: repoRoot || process.cwd(),
9
+ encoding: 'utf8',
10
+ timeout: 10000,
11
+ });
12
+ }
13
+
14
+ function resolveGitLabContext(repoRoot, remoteUrl) {
15
+ const url = remoteUrl || (repoRoot ? git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true }) : '');
16
+ const parsed = parseRemoteUrl(url, { platform: 'gitlab' });
17
+ if (!parsed?.repoPath) {
18
+ return { apiBase: 'https://gitlab.com/api/v4', projectPath: '', encodedProject: '' };
19
+ }
20
+ return {
21
+ apiBase: `${parsed.protocol}//${parsed.host}/api/v4`,
22
+ projectPath: parsed.repoPath,
23
+ encodedProject: encodeURIComponent(parsed.repoPath),
24
+ };
25
+ }
26
+
27
+ function normalizeGitLabDiscussion(d) {
28
+ const rawNotes = Array.isArray(d?.notes) ? d.notes : [];
29
+ const userNotes = rawNotes.filter((n) => !n?.system);
30
+ const first = userNotes[0] || rawNotes[0] || {};
31
+ const resolvable = userNotes.filter((n) => n?.resolvable);
32
+ const isResolved = resolvable.length > 0 && resolvable.every((n) => Boolean(n.resolved));
33
+
34
+ return {
35
+ id: d?.id != null ? String(d.id) : null,
36
+ isResolved,
37
+ path: first?.position?.new_path ?? first?.position?.old_path ?? null,
38
+ line: first?.position?.new_line ?? first?.position?.old_line ?? null,
39
+ comments: userNotes.map((n) => ({
40
+ author: { login: n?.author?.username || n?.author?.login || 'unknown' },
41
+ body: n?.body || '',
42
+ })),
43
+ };
44
+ }
45
+
46
+ export function createGitLabAdapter({ repoRoot = null, remoteUrl = null, exec = null } = {}) {
47
+ const run = exec || defaultExec(repoRoot);
48
+
49
+ function ensureOk(res, code, context) {
50
+ if (!res || res.status !== 0) {
51
+ const detail = (res?.stderr || res?.stdout || res?.error?.message || '').trim();
52
+ throw new AsdlcError(`${context} failed${detail ? `: ${detail}` : ''}`, {
53
+ code,
54
+ exitCode: 1,
55
+ detail,
56
+ });
57
+ }
58
+ }
59
+
60
+ return {
61
+ platform: 'gitlab',
62
+ resolveProject: () => resolveGitLabContext(repoRoot, remoteUrl),
63
+
64
+ fetchThreads({ pr, projectPath: explicitProject } = {}) {
65
+ const mrRef = String(pr ?? '').replace(/^!/, '').replace(/^#/, '');
66
+ const mrNum = Number(mrRef);
67
+ if (!mrRef || !Number.isFinite(mrNum) || mrNum <= 0) {
68
+ throw new AsdlcError(`Invalid MR IID: ${pr}`, { code: 'PR_FETCH_FAILED', exitCode: 1 });
69
+ }
70
+
71
+ const ctx = resolveGitLabContext(repoRoot, remoteUrl);
72
+ const encoded = explicitProject ? encodeURIComponent(explicitProject) : (ctx.encodedProject || 'unknown');
73
+
74
+ const discRes = run('glab', [
75
+ 'api',
76
+ `projects/${encoded}/merge_requests/${mrNum}/discussions?per_page=100`,
77
+ ]);
78
+ ensureOk(discRes, 'PR_FETCH_FAILED', `glab api discussions for MR !${mrNum}`);
79
+
80
+ let discussions;
81
+ try {
82
+ discussions = JSON.parse(discRes.stdout || '[]');
83
+ } catch (err) {
84
+ throw new AsdlcError(`Failed to parse GitLab discussions response: ${err.message}`, {
85
+ code: 'PR_FETCH_FAILED',
86
+ exitCode: 1,
87
+ });
88
+ }
89
+ if (!Array.isArray(discussions)) {
90
+ discussions = Array.isArray(discussions?.discussions) ? discussions.discussions : [];
91
+ }
92
+
93
+ const mrRes = run('glab', ['api', `projects/${encoded}/merge_requests/${mrNum}`]);
94
+ ensureOk(mrRes, 'PR_FETCH_FAILED', `glab api MR !${mrNum}`);
95
+
96
+ let mrJson;
97
+ try {
98
+ mrJson = JSON.parse(mrRes.stdout || '{}');
99
+ } catch (err) {
100
+ throw new AsdlcError(`Failed to parse GitLab MR response: ${err.message}`, {
101
+ code: 'PR_FETCH_FAILED',
102
+ exitCode: 1,
103
+ });
104
+ }
105
+
106
+ const threads = [];
107
+ const issueComments = [];
108
+ for (const d of discussions) {
109
+ const normalized = normalizeGitLabDiscussion(d);
110
+ const notes = Array.isArray(d?.notes) ? d.notes.filter((n) => !n?.system) : [];
111
+ if (notes.length === 0) continue;
112
+ const hasPositionOrResolvable = notes.some((n) => Boolean(n?.position) || Boolean(n?.resolvable));
113
+ if (hasPositionOrResolvable) {
114
+ threads.push(normalized);
115
+ } else {
116
+ for (const c of normalized.comments) {
117
+ issueComments.push(c);
118
+ }
119
+ }
120
+ }
121
+
122
+ const warnings = [];
123
+ if (discussions.length >= 100) {
124
+ warnings.push('[WARN] GitLab MR discussions reached the 100-thread cap; results may be truncated.');
125
+ }
126
+
127
+ const reviewDecision = mrJson?.approved === true ? 'APPROVED' : null;
128
+ return {
129
+ reviewDecision,
130
+ reviewThreads: threads,
131
+ threads,
132
+ issueComments,
133
+ reviews: [],
134
+ warnings,
135
+ };
136
+ },
137
+
138
+ replyThread({ pr, threadId, body, projectPath: explicitProject } = {}) {
139
+ const mrRef = String(pr ?? '').replace(/^!/, '').replace(/^#/, '');
140
+ const ctx = resolveGitLabContext(repoRoot, remoteUrl);
141
+ const encoded = explicitProject ? encodeURIComponent(explicitProject) : (ctx.encodedProject || 'unknown');
142
+ const res = run('glab', [
143
+ 'api', '-X', 'POST',
144
+ `projects/${encoded}/merge_requests/${mrRef}/discussions/${threadId}/notes`,
145
+ '-f', `body=${body}`,
146
+ ]);
147
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `replyThread (${threadId})`);
148
+ return { threadId, replied: true };
149
+ },
150
+
151
+ resolveThread({ pr, threadId, projectPath: explicitProject } = {}) {
152
+ const mrRef = String(pr ?? '').replace(/^!/, '').replace(/^#/, '');
153
+ const ctx = resolveGitLabContext(repoRoot, remoteUrl);
154
+ const encoded = explicitProject ? encodeURIComponent(explicitProject) : (ctx.encodedProject || 'unknown');
155
+ const res = run('glab', [
156
+ 'api', '-X', 'PUT',
157
+ `projects/${encoded}/merge_requests/${mrRef}/discussions/${threadId}`,
158
+ '-f', 'resolved=true',
159
+ ]);
160
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `resolveThread (${threadId})`);
161
+ return { threadId, resolved: true };
162
+ },
163
+
164
+ addLabel({ pr, label } = {}) {
165
+ const mrRef = String(pr ?? '').replace(/^!/, '').replace(/^#/, '');
166
+ const res = run('glab', ['mr', 'update', mrRef, '--label', label]);
167
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `addLabel (${label})`);
168
+ return { pr: mrRef, label };
169
+ },
170
+
171
+ postComment({ pr, body } = {}) {
172
+ const mrRef = String(pr ?? '').replace(/^!/, '').replace(/^#/, '');
173
+ const res = run('glab', ['mr', 'note', mrRef, '--message', body]);
174
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `postComment (MR !${mrRef})`);
175
+ return { pr: mrRef, commented: true };
176
+ },
177
+
178
+ markReady({ pr } = {}) {
179
+ const mrRef = String(pr ?? '').replace(/^!/, '').replace(/^#/, '');
180
+ const res = run('glab', ['mr', 'update', mrRef, '--ready']);
181
+ ensureOk(res, 'FORGE_MUTATION_FAILED', `markReady (MR !${mrRef})`);
182
+ return { pr: mrRef, ready: true };
183
+ },
184
+ };
185
+ }
@@ -0,0 +1,33 @@
1
+ import { AsdlcError } from '../errors.js';
2
+ import { git } from '../git.js';
3
+ import { parseRemoteUrl } from '../remote.js';
4
+ import { createGitHubAdapter, PULL_REQUEST_THREADS_QUERY } from './github.js';
5
+ import { createGitLabAdapter } from './gitlab.js';
6
+
7
+ export { PULL_REQUEST_THREADS_QUERY };
8
+
9
+ /**
10
+ * Create a platform-specific ForgeAdapter (`github` | `gitlab`).
11
+ */
12
+ export function createForgeAdapter({ platform = null, repoRoot = null, remoteUrl = null, exec = null } = {}) {
13
+ let resolvedPlatform = platform ? String(platform).toLowerCase() : null;
14
+
15
+ if (!resolvedPlatform) {
16
+ const url = remoteUrl || (repoRoot ? git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true }) : '');
17
+ const parsed = parseRemoteUrl(url);
18
+ resolvedPlatform = parsed?.isGitLab ? 'gitlab' : 'github';
19
+ }
20
+
21
+ if (resolvedPlatform === 'github') {
22
+ return createGitHubAdapter({ repoRoot, remoteUrl, exec });
23
+ }
24
+ if (resolvedPlatform === 'gitlab') {
25
+ return createGitLabAdapter({ repoRoot, remoteUrl, exec });
26
+ }
27
+
28
+ throw new AsdlcError(`Forge platform '${resolvedPlatform}' is not yet supported.`, {
29
+ code: 'UNSUPPORTED_FORGE',
30
+ exitCode: 1,
31
+ hint: 'Currently supported forge platforms: github, gitlab.',
32
+ });
33
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Parse a git remote URL (HTTPS or SSH) into host, repoPath, protocol, and forge flags.
3
+ */
4
+ export function parseRemoteUrl(url, opts = {}) {
5
+ if (!url) return null;
6
+ const cleaned = url.trim().replace(/\.git$/, '');
7
+ let host = '';
8
+ let repoPath = '';
9
+ let protocol = 'https:';
10
+
11
+ const sshMatch = cleaned.match(/^git@([^:]+):(.+)$/);
12
+ if (sshMatch) {
13
+ host = sshMatch[1];
14
+ repoPath = sshMatch[2];
15
+ } else {
16
+ try {
17
+ const u = new URL(cleaned);
18
+ host = u.host;
19
+ protocol = u.protocol || 'https:';
20
+ repoPath = u.pathname.replace(/^\//, '');
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+
26
+ const explicitPlatform = (opts.platform || process.env.ASDLC_GIT_PLATFORM || process.env.GIT_PLATFORM || '').toLowerCase();
27
+ const isGitLab = explicitPlatform === 'gitlab'
28
+ || host.includes('gitlab')
29
+ || (!host.includes('github') && Boolean(process.env.GITLAB_TOKEN || process.env.CI_JOB_TOKEN || process.env.GL_TOKEN));
30
+ const isGitHub = explicitPlatform === 'github'
31
+ || host.includes('github')
32
+ || (!isGitLab);
33
+
34
+ return {
35
+ host,
36
+ repoPath,
37
+ protocol,
38
+ isGitHub,
39
+ isGitLab,
40
+ };
41
+ }