@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.
@@ -0,0 +1,307 @@
1
+ import { isGitRepo, headSha, git } from './git.js';
2
+ import { fail, AsdlcError } from './errors.js';
3
+ import { exists } from './fs.js';
4
+ import { openspecDir } from './paths.js';
5
+
6
+ const CANONICAL_URL_RE = /^(?:(https?|ssh):\/\/(?:([^@]+)@)?([^/:]+)(?::(\d+))?\/|git@([^:]+):)(.+?)(?:\.git)?(?:\/(?:pull|-\/merge_requests)\/(\d+))?\/?$/i;
7
+ const SHORTHAND_SLUG_RE = /^[a-zA-Z0-9._-]+(?:\/[a-zA-Z0-9._-]+)+$/;
8
+ const PR_REF_RE = /^#?(\d+)$/;
9
+
10
+ /**
11
+ * Renders a boxed diagnostic error card with root causes and actionable remedies.
12
+ */
13
+ export function formatDiagnosticCard({ code, title, rootCauses = [], remedies = [] }) {
14
+ const lines = [
15
+ `┌──────────────────────────────────────────────────────────────────────────────┐`,
16
+ `│ [ERROR] ${code}: ${title}`,
17
+ `├──────────────────────────────────────────────────────────────────────────────┤`,
18
+ ];
19
+ if (rootCauses.length > 0) {
20
+ lines.push('│ Root Cause:');
21
+ for (const rc of rootCauses) {
22
+ lines.push(`│ - ${rc}`);
23
+ }
24
+ }
25
+ if (remedies.length > 0) {
26
+ lines.push('│');
27
+ lines.push('│ Actionable Remedies (Choose one):');
28
+ remedies.forEach((rem, i) => {
29
+ lines.push(`│ ${i + 1}. ${rem}`);
30
+ });
31
+ }
32
+ lines.push(`└──────────────────────────────────────────────────────────────────────────────┘`);
33
+ return lines.join('\n');
34
+ }
35
+
36
+ function throwDiagnosticError({ code, title, message, rootCauses = [], remedies = [], env = process.env }) {
37
+ const card = formatDiagnosticCard({ code, title, rootCauses, remedies });
38
+ if (env?.GITHUB_ACTIONS === 'true') {
39
+ process.stderr.write(`::error title=${code}::${message}\n`);
40
+ }
41
+ const err = new AsdlcError(message, {
42
+ code,
43
+ exitCode: 1,
44
+ hint: remedies[0] || '',
45
+ detail: card,
46
+ });
47
+ err.remedies = remedies;
48
+ err.card = card;
49
+ throw err;
50
+ }
51
+
52
+ /**
53
+ * Verifies that the target workspace or container options provide an initialized Git repository
54
+ * with at least one commit, or explicit remote/create-repo targets for greenfield runs.
55
+ */
56
+ export function assertGitRepositoryInitialized(repoRoot, {
57
+ container = false,
58
+ repo = null,
59
+ createRepo = null,
60
+ env = process.env,
61
+ requireCommit = true,
62
+ } = {}) {
63
+ const hasGit = Boolean(repoRoot && isGitRepo(repoRoot));
64
+ const hasOpenspec = Boolean(repoRoot && exists(openspecDir(repoRoot)));
65
+
66
+ // Container zero-checkout or greenfield flow with explicit remote/creation target
67
+ if (container && (repo || createRepo)) {
68
+ return { initialized: hasGit, greenfield: !hasGit };
69
+ }
70
+
71
+ // Case 1: Empty/non-Git folder (container mode always requires remote or repo; local requires repo/openspec)
72
+ if (!hasGit && (container || !hasOpenspec)) {
73
+ throwDiagnosticError({
74
+ code: 'ASDLC_ERR_NO_REPOSITORY',
75
+ title: 'Target Git repository not specified',
76
+ message: `No initialized Git repository found at ${repoRoot}. Container and governance workflows require an explicit repository.`,
77
+ rootCauses: [
78
+ 'Current directory is not a Git repository or has no remote origin.',
79
+ container ? 'Container execution requires an explicit target repository (--repo or --create-repo).' : 'OpenSpec project is not initialized in a Git repository.',
80
+ ],
81
+ remedies: [
82
+ 'Create a new GitHub repository: asdlc run "<requirement>" --create-repo <org/repo-name> --container',
83
+ 'Target an existing remote repository: asdlc run "<requirement>" --repo <org/repo-name> --container',
84
+ 'Initialize Git locally first: git init && git commit --allow-empty -m "chore: init" && asdlc init',
85
+ ],
86
+ env,
87
+ });
88
+ }
89
+
90
+ // Case 2: `git init` exists, but 0 commits (unborn HEAD) breaks SHA anchoring & spec locks
91
+ if (hasGit && requireCommit && !headSha(repoRoot)) {
92
+ throwDiagnosticError({
93
+ code: 'ASDLC_ERR_NO_REPOSITORY',
94
+ title: 'Git repository has no initial commit (unborn HEAD)',
95
+ message: `Git repository at ${repoRoot} has no commits yet. At least one initial commit is required for branch anchoring.`,
96
+ rootCauses: [
97
+ 'git init was run, but no initial commit exists on HEAD yet.',
98
+ ],
99
+ remedies: [
100
+ 'Create an initial commit: git add -A && git commit --allow-empty -m "chore: initial commit"',
101
+ ],
102
+ env,
103
+ });
104
+ }
105
+
106
+ // Case 3: Container mode inside a git repo without remote origin and without --repo/--create-repo
107
+ if (container && hasGit && !repo && !createRepo) {
108
+ const originUrl = git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true });
109
+ if (!originUrl) {
110
+ throwDiagnosticError({
111
+ code: 'ASDLC_ERR_NO_REPOSITORY',
112
+ title: 'Git repository has no remote origin configured',
113
+ message: `Git repository at ${repoRoot} has no remote 'origin'. Container autonomous PR lifecycle requires a remote target.`,
114
+ rootCauses: [
115
+ 'Local Git repository has no remote named "origin".',
116
+ 'Neither --repo nor --create-repo was specified.',
117
+ ],
118
+ remedies: [
119
+ 'Create remote repository: asdlc run "<requirement>" --create-repo <org/repo-name> --container',
120
+ 'Or link an existing remote: git remote add origin <url>',
121
+ ],
122
+ env,
123
+ });
124
+ }
125
+ }
126
+
127
+ return { initialized: true, greenfield: false };
128
+ }
129
+
130
+ /**
131
+ * Parses a canonical Git or PR/MR URL into structured components.
132
+ * Supports https://, http://, ssh://, git@host:path, multi-level GitLab subgroups, and /pull/N or /-/merge_requests/N.
133
+ */
134
+ export function parseCanonicalGitUrl(input) {
135
+ if (!input || typeof input !== 'string') return null;
136
+ const trimmed = input.trim();
137
+ const m = trimmed.match(CANONICAL_URL_RE);
138
+ if (!m) return null;
139
+
140
+ const [, protoRaw, , httpsHost, port, sshHost, pathPart, prNumRaw] = m;
141
+ const host = (httpsHost || sshHost || '').toLowerCase();
142
+ if (!host || !pathPart) return null;
143
+
144
+ const cleanPath = pathPart.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '');
145
+ const segments = cleanPath.split('/').filter(Boolean);
146
+ if (segments.length < 2) return null;
147
+
148
+ const repo = segments[segments.length - 1];
149
+ const namespace = segments.slice(0, -1).join('/');
150
+ const protocol = protoRaw ? protoRaw.toLowerCase() : 'ssh';
151
+ const hostWithPort = port ? `${host}:${port}` : host;
152
+ const remoteUrl = protocol === 'ssh' && !protoRaw
153
+ ? `git@${host}:${cleanPath}.git`
154
+ : `${protocol}://${hostWithPort}/${cleanPath}.git`;
155
+
156
+ return {
157
+ format: 'canonical-url',
158
+ protocol: protocol === 'ssh' ? 'ssh' : 'https',
159
+ host,
160
+ port: port ? Number(port) : null,
161
+ namespace,
162
+ repo,
163
+ fullSlug: cleanPath,
164
+ remoteUrl,
165
+ prNumber: prNumRaw ? Number(prNumRaw) : null,
166
+ };
167
+ }
168
+
169
+ function detectIntranetIndicators({ env = process.env, policy = null, originUrl = null, strictIntranet = false } = {}) {
170
+ if (strictIntranet || env?.ASDLC_STRICT_HOST === '1' || policy?.git?.strict_host === true) return true;
171
+ if (env?.HTTPS_PROXY || env?.HTTP_PROXY || env?.https_proxy || env?.http_proxy || env?.SSL_CERT_FILE || env?.NODE_EXTRA_CA_CERTS) {
172
+ return true;
173
+ }
174
+ if (originUrl) {
175
+ const parsed = parseCanonicalGitUrl(originUrl);
176
+ if (parsed && parsed.host !== 'github.com' && parsed.host !== 'gitlab.com') {
177
+ return true;
178
+ }
179
+ }
180
+ return false;
181
+ }
182
+
183
+ /**
184
+ * Resolves target Git repository & host deterministically across 3 tiers:
185
+ * A. Canonical full URL (zero ambiguity, supports multi-level subgroups & ports)
186
+ * B. Configured shorthand slug (requires configured default_host; never guesses github.com in intranet/multi-subgroup contexts)
187
+ * C. Ambient context (local git origin remote or CI env vars)
188
+ */
189
+ export function resolveGitHostAndRepo(targetInput = '', options = {}) {
190
+ let opts = options;
191
+ let raw = '';
192
+ if (typeof targetInput === 'string') {
193
+ raw = targetInput.trim();
194
+ } else if (targetInput && typeof targetInput === 'object') {
195
+ raw = String(targetInput.repo || targetInput.target || targetInput.url || '').trim();
196
+ opts = { ...targetInput, ...options };
197
+ }
198
+ const {
199
+ repoRoot = null,
200
+ globalConfig = null,
201
+ policy = null,
202
+ env = process.env,
203
+ strictIntranet = false,
204
+ } = opts;
205
+
206
+ // Tier A: Canonical full URL (GitHub, GitLab, GHES, multi-subgroup, PR/MR URL)
207
+ if (raw) {
208
+ const canonical = parseCanonicalGitUrl(raw);
209
+ if (canonical) return canonical;
210
+ }
211
+
212
+ // Tier B: Shorthand slug (e.g. "owner/repo" or "fintech/settlement/refund")
213
+ const prMatch = raw.match(PR_REF_RE);
214
+ if (raw && !prMatch && SHORTHAND_SLUG_RE.test(raw)) {
215
+ const cleanSlug = raw.replace(/\.git$/i, '');
216
+ const segments = cleanSlug.split('/').filter(Boolean);
217
+ const repo = segments[segments.length - 1];
218
+ const namespace = segments.slice(0, -1).join('/');
219
+
220
+ const configuredHost = env?.ASDLC_GIT_HOST
221
+ || policy?.git?.default_host
222
+ || globalConfig?.git?.default_host
223
+ || null;
224
+
225
+ const configuredProtocol = (
226
+ env?.ASDLC_GIT_PROTOCOL
227
+ || policy?.git?.protocol
228
+ || globalConfig?.git?.protocol
229
+ || 'https'
230
+ ).toLowerCase();
231
+
232
+ const originUrl = repoRoot && isGitRepo(repoRoot)
233
+ ? git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true })
234
+ : null;
235
+
236
+ const isDeepGroup = segments.length >= 3;
237
+ const intranetDetected = detectIntranetIndicators({ env, policy, originUrl, strictIntranet });
238
+
239
+ if (!configuredHost && (isDeepGroup || intranetDetected)) {
240
+ throwDiagnosticError({
241
+ code: 'ASDLC_ERR_AMBIGUOUS_HOST',
242
+ title: 'Cannot resolve Git host for shorthand slug',
243
+ message: `Ambiguous shorthand repository '${raw}' without configured git.default_host. Refusing to fall back to github.com.`,
244
+ rootCauses: [
245
+ `Input provided: "${raw}" without protocol or domain.`,
246
+ 'In enterprise/intranet environments or nested GitLab groups, fallback guessing to github.com is prohibited to prevent metadata and token exfiltration.',
247
+ ],
248
+ remedies: [
249
+ `Provide a canonical full URL: asdlc run --repo https://gitlab.corp.com/${cleanSlug}.git --container`,
250
+ 'Configure your enterprise default host: asdlc config set git.default_host gitlab.corp.company.com',
251
+ ],
252
+ env,
253
+ });
254
+ }
255
+
256
+ const host = configuredHost ? configuredHost.toLowerCase() : 'github.com';
257
+ const remoteUrl = configuredProtocol === 'ssh'
258
+ ? `git@${host}:${cleanSlug}.git`
259
+ : `https://${host}/${cleanSlug}.git`;
260
+
261
+ return {
262
+ format: configuredHost ? 'configured-shorthand' : 'public-shorthand',
263
+ protocol: configuredProtocol === 'ssh' ? 'ssh' : 'https',
264
+ host,
265
+ port: null,
266
+ namespace,
267
+ repo,
268
+ fullSlug: cleanSlug,
269
+ remoteUrl,
270
+ prNumber: null,
271
+ };
272
+ }
273
+
274
+ // Tier C: Ambient context (#N, bare change slug, or empty)
275
+ const prNumber = prMatch ? Number(prMatch[1]) : null;
276
+ if (repoRoot && isGitRepo(repoRoot)) {
277
+ const originUrl = git(['remote', 'get-url', 'origin'], repoRoot, { allowFail: true });
278
+ if (originUrl) {
279
+ const parsed = parseCanonicalGitUrl(originUrl);
280
+ if (parsed) {
281
+ return {
282
+ ...parsed,
283
+ format: 'ambient-origin',
284
+ prNumber,
285
+ };
286
+ }
287
+ }
288
+ }
289
+
290
+ // Ambient CI environment (GitHub Actions / GitLab CI)
291
+ if (env?.GITHUB_REPOSITORY) {
292
+ const serverUrl = (env.GITHUB_SERVER_URL || 'https://github.com').replace(/\/+$/, '');
293
+ const parsed = parseCanonicalGitUrl(`${serverUrl}/${env.GITHUB_REPOSITORY}`);
294
+ if (parsed) return { ...parsed, format: 'ambient-ci', prNumber };
295
+ }
296
+ if (env?.CI_PROJECT_PATH) {
297
+ const serverUrl = (env.CI_SERVER_URL || 'https://gitlab.com').replace(/\/+$/, '');
298
+ const parsed = parseCanonicalGitUrl(`${serverUrl}/${env.CI_PROJECT_PATH}`);
299
+ if (parsed) return { ...parsed, format: 'ambient-ci', prNumber };
300
+ }
301
+
302
+ fail(`Cannot resolve target Git repository or remote host from '${raw || '(cwd)'}'.`, {
303
+ code: 'ASDLC_ERR_NO_REPOSITORY',
304
+ hint: 'Pass --repo <url-or-owner/repo>, run inside a cloned repo with remote origin, or set git.default_host.',
305
+ });
306
+ }
307
+