@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.
@@ -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
+ }
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { git } from './git.js';
4
4
  import { readYaml } from './yaml.js';
5
- import { readText, exists } from './fs.js';
5
+ import { readText, exists, listDir } from './fs.js';
6
6
  import { openspecDir } from './paths.js';
7
7
 
8
8
  const GITIGNORE_CONTENT = `# Autogenerated by asdlc telemetry: ignore local friction logs; keep policy.yaml
@@ -292,6 +292,43 @@ export function computeTeamMetrics(repoRoot, { days = 30 } = {}) {
292
292
  const r3Pct = total > 0 ? Math.round((convergenceRounds.r3 / total) * 100) : 0;
293
293
  const escPct = total > 0 ? Math.round((convergenceRounds.escalated / total) * 100) : 0;
294
294
 
295
+ let repoBaseline = null;
296
+ if (total === 0) {
297
+ const changesDir = path.join(repoRoot, 'openspec', 'changes');
298
+ const activeInFlightChanges = exists(changesDir)
299
+ ? listDir(changesDir).filter((e) => e.isDirectory() && e.name !== 'archive').length
300
+ : 0;
301
+
302
+ const verifiedRuns = [...localEvents, ...lintEvents].filter((e) => e.type === 'gate.verified');
303
+ const localGateRuns = verifiedRuns.length;
304
+ const localGatePassRatePct = localGateRuns > 0
305
+ ? Math.round((verifiedRuns.filter((e) => e.status === 'pass' || e.verdict === 'pass').length / localGateRuns) * 100)
306
+ : null;
307
+
308
+ let testFileTouchRatioPct = 0;
309
+ let recentCommitCount = 0;
310
+ try {
311
+ const logRaw = git(['log', `--since=${days} days ago`, '--name-only', '--pretty=format:__COMMIT__'], repoRoot, { allowFail: true }) || '';
312
+ const commitBlocks = logRaw.split('__COMMIT__').map((b) => b.trim()).filter(Boolean);
313
+ recentCommitCount = commitBlocks.length;
314
+ if (recentCommitCount > 0) {
315
+ const testCommits = commitBlocks.filter((b) =>
316
+ b.split(/\r?\n/).some((f) => /(?:^|\/)(?:test|tests|__tests__|spec|specs)\/|\.(?:test|spec)\.[jt]sx?$|\.test\.py$|_test\.go$/i.test(f))
317
+ ).length;
318
+ testFileTouchRatioPct = Math.round((testCommits / recentCommitCount) * 100);
319
+ }
320
+ } catch { /* ignore */ }
321
+
322
+ repoBaseline = {
323
+ activeInFlightChanges,
324
+ localGateRuns,
325
+ localGatePassRatePct,
326
+ recentCommitCount,
327
+ testFileTouchRatioPct,
328
+ disclaimer: 'Informational repo-level baseline only — not for individual or team performance evaluation.',
329
+ };
330
+ }
331
+
295
332
  return {
296
333
  days,
297
334
  totalTrackedChanges: total,
@@ -310,6 +347,7 @@ export function computeTeamMetrics(repoRoot, { days = 30 } = {}) {
310
347
  counts: convergenceRounds,
311
348
  },
312
349
  frictionLeaderboard,
350
+ repoBaseline,
313
351
  };
314
352
  }
315
353
 
@@ -357,7 +395,52 @@ export function renderMetricsDashboard(metrics) {
357
395
  const l3 = metrics.riskLevels.L3 || 0;
358
396
  lines.push('4. 🛡️ Risk Tier Breakdown');
359
397
  lines.push(` • L0 (Docs/Internal): ${l0} | L1 (Normal): ${l1} | L2 (High): ${l2} | L3 (Critical): ${l3}`);
398
+
399
+ if (metrics.repoBaseline) {
400
+ const b = metrics.repoBaseline;
401
+ const passText = b.localGatePassRatePct === null ? 'N/A (0 local runs)' : `${b.localGatePassRatePct}% (${b.localGateRuns} runs)`;
402
+ lines.push('');
403
+ lines.push('5. 📊 Day-1 Repository Baseline (No Archived Changes Yet)');
404
+ lines.push(` • Active In-Flight Changes : ${b.activeInFlightChanges}`);
405
+ lines.push(` • Local Gate Pass Rate : ${passText}`);
406
+ lines.push(` • Repo Test-File Touch Ratio : ${b.testFileTouchRatioPct}% (${b.recentCommitCount} commits in last ${metrics.days}d)`);
407
+ lines.push(` • Note: ${b.disclaimer}`);
408
+ }
360
409
  lines.push('=============================================================================');
361
410
 
362
411
  return lines.join('\n');
363
412
  }
413
+
414
+ export function renderMetricsReportMarkdown(metrics) {
415
+ const lines = [
416
+ '# ASDLC Harness Observability Report',
417
+ '',
418
+ `- **Window**: Last ${metrics.days} Days`,
419
+ `- **Tracked Archived Changes**: ${metrics.totalTrackedChanges}`,
420
+ `- **Generated At**: ${new Date().toISOString()}`,
421
+ '',
422
+ '## Autonomous PR Convergence',
423
+ `- Round 1 Pass: ${metrics.convergence.r1Pct}% (${metrics.convergence.counts.r1} PRs)`,
424
+ `- Round 2 Pass: ${metrics.convergence.r2Pct}% (${metrics.convergence.counts.r2} PRs)`,
425
+ `- Round 3 Pass: ${metrics.convergence.r3Pct}% (${metrics.convergence.counts.r3} PRs)`,
426
+ `- Human Escalated: ${metrics.convergence.escPct}% (${metrics.convergence.counts.escalated} PRs)`,
427
+ '',
428
+ '## Stage Lead Time (P50 / P90)',
429
+ `- Spec Phase (new -> approve): ${metrics.leadTime.specP50Min}m / ${metrics.leadTime.specP90Min}m`,
430
+ `- TDD Phase (apply -> verify): ${metrics.leadTime.implP50Min}m / ${metrics.leadTime.implP90Min}m`,
431
+ '',
432
+ '## Risk Tier Breakdown',
433
+ `- L0: ${metrics.riskLevels.L0 || 0} | L1: ${metrics.riskLevels.L1 || 0} | L2: ${metrics.riskLevels.L2 || 0} | L3: ${metrics.riskLevels.L3 || 0}`,
434
+ ];
435
+ if (metrics.repoBaseline) {
436
+ const b = metrics.repoBaseline;
437
+ const passText = b.localGatePassRatePct === null ? 'N/A' : `${b.localGatePassRatePct}% (${b.localGateRuns} runs)`;
438
+ lines.push('');
439
+ lines.push('## Day-1 Repository Baseline');
440
+ lines.push(`- Active In-Flight Changes: ${b.activeInFlightChanges}`);
441
+ lines.push(`- Local Gate Pass Rate: ${passText}`);
442
+ lines.push(`- Repo Test-File Touch Ratio: ${b.testFileTouchRatioPct}% (${b.recentCommitCount} commits)`);
443
+ lines.push(`- > ${b.disclaimer}`);
444
+ }
445
+ return `${lines.join('\n')}\n`;
446
+ }