@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.
@@ -0,0 +1,123 @@
1
+ import path from 'node:path';
2
+ import { exists, readText, writeText, walkFiles } from './fs.js';
3
+ import { changeDir } from './paths.js';
4
+
5
+ /**
6
+ * Parse `- [ ] ACn: <description> (test: <path>)` acceptance criteria grouped by Requirement.
7
+ */
8
+ export function parseSpecAcceptanceCriteria(specText) {
9
+ const acs = [];
10
+ const lines = String(specText ?? '').split(/\r?\n/);
11
+ let currentReq = '';
12
+
13
+ for (const line of lines) {
14
+ const reqMatch = line.match(/^###\s+Requirement:\s*(.+?)\s*$/);
15
+ if (reqMatch) {
16
+ currentReq = reqMatch[1];
17
+ continue;
18
+ }
19
+ const acMatch = line.match(/^\s*-\s*\[[ xX]\]\s*(AC\d+)\s*:\s*(.+)$/);
20
+ if (!acMatch) continue;
21
+ const testMatch = line.match(/\(test:\s*([^)]+?)\s*\)/i);
22
+ acs.push({
23
+ id: acMatch[1],
24
+ requirement: currentReq,
25
+ text: acMatch[2].replace(/\(test:.*$/i, '').trim(),
26
+ testPath: testMatch ? testMatch[1].trim() : null,
27
+ });
28
+ }
29
+ return acs;
30
+ }
31
+
32
+ function hasUiSurface(designText, specEntries) {
33
+ if (designText && /(UI\/UX|Visual|Breakpoints|Loading\s+Skeleton|Empty\s+State|Component)/i.test(designText)) {
34
+ return true;
35
+ }
36
+ return specEntries.some(({ content }) => /(Playwright|responsive\s+breakpoint|Empty,\s*Loading,\s*Error)/i.test(content));
37
+ }
38
+
39
+ /**
40
+ * Compile `openspec/changes/<slug>/tasks.md` deterministically from spec ACs.
41
+ * Idempotent: never overwrites an existing non-empty `tasks.md`.
42
+ * Fails closed (`generated: false`) if no valid ACs exist in specs.
43
+ */
44
+ export function generateTasksFromSpecs(repoRoot, slug) {
45
+ const cdir = changeDir(repoRoot, slug);
46
+ const tasksPath = path.join(cdir, 'tasks.md');
47
+
48
+ if (exists(tasksPath) && readText(tasksPath).trim().length > 0) {
49
+ return { generated: false, reason: 'already_exists', path: tasksPath };
50
+ }
51
+
52
+ const specsDir = path.join(cdir, 'specs');
53
+ if (!exists(specsDir)) {
54
+ return { generated: false, reason: 'no_specs', path: tasksPath };
55
+ }
56
+
57
+ const specFiles = walkFiles(specsDir).filter((f) => f.endsWith('spec.md'));
58
+ const specEntries = specFiles.map((rel) => {
59
+ const content = readText(path.join(specsDir, rel));
60
+ return { rel: rel.replace(/\\/g, '/'), content, acs: parseSpecAcceptanceCriteria(content) };
61
+ });
62
+
63
+ const allAcs = specEntries.flatMap((e) => e.acs.map((ac) => ({ ...ac, specFile: e.rel })));
64
+ if (allAcs.length === 0) {
65
+ return { generated: false, reason: 'no_acs', path: tasksPath };
66
+ }
67
+
68
+ const designPath = path.join(cdir, 'design.md');
69
+ const designText = exists(designPath) ? readText(designPath) : '';
70
+ const uiTasksIncluded = hasUiSurface(designText, specEntries);
71
+
72
+ const lines = [
73
+ `# Tasks: ${slug}`,
74
+ '',
75
+ '> Auto-generated from capability specs (mutable during implementation: refine, split, or append TDD tasks as needed).',
76
+ '> Follow strict task-level TDD loop (RED -> GREEN -> REFACTOR -> EVIDENCE).',
77
+ '',
78
+ ];
79
+
80
+ let taskCount = 0;
81
+
82
+ if (uiTasksIncluded) {
83
+ lines.push('## 0. UI/UX Foundation & Component States (`design.md`)');
84
+ lines.push('- [ ] 0.1 [UI/DESIGN] Establish design tokens, responsive layout containers, and theme styles');
85
+ lines.push('- [ ] 0.2 [UI/COMPONENTS] Implement Empty, Loading, Error, and Success states with component render tests');
86
+ lines.push('');
87
+ taskCount += 2;
88
+ }
89
+
90
+ const groups = new Map();
91
+ for (const ac of allAcs) {
92
+ const key = `${ac.specFile}::${ac.requirement || 'General'}`;
93
+ if (!groups.has(key)) {
94
+ groups.set(key, { specFile: ac.specFile, requirement: ac.requirement || 'Capability Requirements', acs: [] });
95
+ }
96
+ groups.get(key).acs.push(ac);
97
+ }
98
+
99
+ let sectionNum = 1;
100
+ for (const group of groups.values()) {
101
+ lines.push(`## ${sectionNum}. ${group.requirement} (\`specs/${group.specFile}\`)`);
102
+ let subNum = 1;
103
+ for (const ac of group.acs) {
104
+ const testRef = ac.testPath ? ` (\`${ac.testPath}\`)` : '';
105
+ lines.push(`- [ ] ${sectionNum}.${subNum} [TEST] Write failing test for ${ac.id}: ${ac.text}${testRef}`);
106
+ subNum += 1;
107
+ lines.push(`- [ ] ${sectionNum}.${subNum} [IMPL] Implement minimal code to satisfy ${ac.id}${testRef}`);
108
+ subNum += 1;
109
+ taskCount += 2;
110
+ }
111
+ lines.push('');
112
+ sectionNum += 1;
113
+ }
114
+
115
+ writeText(tasksPath, `${lines.join('\n').trimEnd()}\n`);
116
+ return {
117
+ generated: true,
118
+ taskCount,
119
+ acCount: allAcs.length,
120
+ uiTasksIncluded,
121
+ path: tasksPath,
122
+ };
123
+ }
@@ -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
+ }
package/src/lib/tools.js CHANGED
@@ -285,8 +285,12 @@ export function installCommands(repoRoot, tools = []) {
285
285
  }
286
286
  }
287
287
 
288
+ function normalizeLf(text) {
289
+ return String(text ?? '').replace(/\r\n/g, '\n');
290
+ }
291
+
288
292
  /**
289
- * Audit tool health for asdlc doctor
293
+ * Audit tool health for asdlc doctor (checks presence and normalized skill/command drift)
290
294
  */
291
295
  export function checkToolHealth(repoRoot, toolId) {
292
296
  const def = TOOL_REGISTRY[toolId];
@@ -295,21 +299,63 @@ export function checkToolHealth(repoRoot, toolId) {
295
299
  const skillsPath = path.join(repoRoot, def.skillsDir);
296
300
  const commandsPath = path.join(repoRoot, def.commandsDir);
297
301
 
298
- const skillsOk = exists(skillsPath) && listDir(skillsPath).length > 0;
299
- const commandsOk = exists(commandsPath) && listDir(commandsPath).length > 0;
302
+ const missingCommands = [];
303
+ if (exists(commandsAssetDir)) {
304
+ const bundledCommands = listDir(commandsAssetDir).filter((f) => !f.isDirectory() && f.name.endsWith('.md'));
305
+ for (const cmd of bundledCommands) {
306
+ const baseName = cmd.name.replace(/\.md$/, '');
307
+ if (!exists(path.join(commandsPath, `${baseName}${def.commandExt}`))) {
308
+ missingCommands.push(`${baseName}${def.commandExt}`);
309
+ }
310
+ }
311
+ }
312
+
313
+ const missingSkills = [];
314
+ const staleSkills = [];
315
+ const deprecatedSkills = [];
316
+ if (exists(skillsAssetDir)) {
317
+ const bundledSkills = listDir(skillsAssetDir).filter((d) => d.isDirectory()).map((d) => d.name);
318
+ for (const skillName of bundledSkills) {
319
+ const bundledFile = path.join(skillsAssetDir, skillName, 'SKILL.md');
320
+ const installedFile = path.join(skillsPath, skillName, 'SKILL.md');
321
+ if (!exists(installedFile)) {
322
+ missingSkills.push(skillName);
323
+ } else if (exists(bundledFile) && normalizeLf(readText(installedFile)) !== normalizeLf(readText(bundledFile))) {
324
+ staleSkills.push(skillName);
325
+ }
326
+ }
327
+ for (const dep of DEPRECATED_SKILLS) {
328
+ if (exists(path.join(skillsPath, dep))) {
329
+ deprecatedSkills.push(dep);
330
+ }
331
+ }
332
+ }
333
+
334
+ const hasSkillsDir = exists(skillsPath) && listDir(skillsPath).length > 0;
335
+ const hasCommandsDir = exists(commandsPath) && listDir(commandsPath).length > 0;
336
+ const skillsOk = hasSkillsDir && missingSkills.length === 0 && staleSkills.length === 0 && deprecatedSkills.length === 0;
337
+ const commandsOk = hasCommandsDir && missingCommands.length === 0;
300
338
 
301
339
  let status = 'pass';
302
340
  let detail = `skills + commands installed (${def.commandsDir})`;
303
341
 
304
- if (!skillsOk && !commandsOk) {
342
+ if (!hasSkillsDir && !hasCommandsDir) {
305
343
  status = 'warn';
306
344
  detail = 'missing skills and commands (run `asdlc init`)';
307
- } else if (!skillsOk) {
345
+ } else if (!hasSkillsDir) {
308
346
  status = 'warn';
309
347
  detail = `missing skills in ${def.skillsDir} (run 'asdlc init')`;
310
- } else if (!commandsOk) {
348
+ } else if (!hasCommandsDir) {
311
349
  status = 'warn';
312
350
  detail = `missing commands in ${def.commandsDir} (run 'asdlc init')`;
351
+ } else if (!skillsOk || !commandsOk) {
352
+ status = 'warn';
353
+ const reasons = [];
354
+ if (missingCommands.length > 0) reasons.push(`${missingCommands.length} missing command(s)`);
355
+ if (missingSkills.length > 0) reasons.push(`${missingSkills.length} missing skill(s)`);
356
+ if (staleSkills.length > 0) reasons.push(`${staleSkills.length} stale skill(s)`);
357
+ if (deprecatedSkills.length > 0) reasons.push(`${deprecatedSkills.length} deprecated skill(s)`);
358
+ detail = `stale or missing skills/commands (${reasons.join(', ')}; run 'asdlc update' or 'asdlc doctor --fix')`;
313
359
  }
314
360
 
315
361
  return {
@@ -319,5 +365,6 @@ export function checkToolHealth(repoRoot, toolId) {
319
365
  detail,
320
366
  skillsOk,
321
367
  commandsOk,
368
+ drift: { missingCommands, missingSkills, staleSkills, deprecatedSkills },
322
369
  };
323
370
  }
package/src/lib/triage.js CHANGED
@@ -1,36 +1,6 @@
1
- /**
2
- * GraphQL query for fetching PR review threads, review decision, and commit anchor.
3
- */
4
- export const PULL_REQUEST_THREADS_QUERY = `
5
- query PullRequestReviewThreads($owner: String!, $repo: String!, $number: Int!) {
6
- repository(owner: $owner, name: $repo) {
7
- pullRequest(number: $number) {
8
- reviewDecision
9
- headRefOid
10
- commits(last: 1) { nodes { commit { committedDate, oid } } }
11
- reviewThreads(first: 100) {
12
- nodes {
13
- id
14
- isResolved
15
- isOutdated
16
- path
17
- line
18
- originalLine
19
- comments(first: 20) {
20
- nodes {
21
- id
22
- databaseId
23
- author { login }
24
- body
25
- createdAt
26
- }
27
- }
28
- }
29
- }
30
- }
31
- }
32
- }
33
- `.trim();
1
+ import { PULL_REQUEST_THREADS_QUERY } from './forge/github.js';
2
+
3
+ export { PULL_REQUEST_THREADS_QUERY };
34
4
 
35
5
  const DEFAULT_AGENT_LOGINS = [
36
6
  'asdlc-bot',
@@ -319,8 +289,8 @@ export function applySuggestionToLines(fileContent, { startLine = null, endLine
319
289
 
320
290
  /**
321
291
  * Tier 3 Resolution Plan:
322
- * Generates traceable commit trailer, GraphQL reply mutation, and optional thread resolution mutation.
323
- * Category C informational answers reply without committing or force-resolving the thread.
292
+ * Generates platform-agnostic resolution intent (commit trailer, reply body, resolve/dispute decision).
293
+ * Platform adapters (GitHubAdapter, GitLabAdapter, etc.) execute the actual API mutations.
324
294
  */
325
295
  export function buildThreadResolutionPlan(triagedThread, { commitSha = null, summary = '', answerBody = null, disputed = false, specRef = null } = {}) {
326
296
  const intent = triagedThread?.classification?.intent;
@@ -332,15 +302,12 @@ export function buildThreadResolutionPlan(triagedThread, { commitSha = null, sum
332
302
  const replyBody = answerBody || `Spec Conflict: ${specCitation}, requested change contradicts approved design. Escalated for human review.`;
333
303
  return {
334
304
  threadId,
305
+ action: 'dispute',
335
306
  commitMessage: null,
307
+ replyBody,
336
308
  shouldResolve: false,
337
309
  disputed: true,
338
310
  escalationLabel: 'asdlc:needs-human-arbitration',
339
- replyMutation: {
340
- query: 'mutation ReplyThread($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }',
341
- variables: { threadId, body: replyBody },
342
- },
343
- resolveMutation: null,
344
311
  };
345
312
  }
346
313
 
@@ -348,13 +315,12 @@ export function buildThreadResolutionPlan(triagedThread, { commitSha = null, sum
348
315
  const replyBody = answerBody || summary || 'Answered in technical explanation above.';
349
316
  return {
350
317
  threadId,
318
+ action: 'reply_only',
351
319
  commitMessage: null,
320
+ replyBody,
352
321
  shouldResolve: false,
353
- replyMutation: {
354
- query: 'mutation ReplyThread($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }',
355
- variables: { threadId, body: replyBody },
356
- },
357
- resolveMutation: null,
322
+ disputed: false,
323
+ escalationLabel: null,
358
324
  };
359
325
  }
360
326
 
@@ -365,16 +331,12 @@ export function buildThreadResolutionPlan(triagedThread, { commitSha = null, sum
365
331
 
366
332
  return {
367
333
  threadId,
334
+ action: 'reply_and_resolve',
368
335
  commitMessage,
336
+ replyBody,
369
337
  shouldResolve: true,
370
- replyMutation: {
371
- query: 'mutation ReplyThread($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }',
372
- variables: { threadId, body: replyBody },
373
- },
374
- resolveMutation: {
375
- query: 'mutation ResolveThread($threadId: ID!) { resolveReviewThread(input: { threadId: $threadId }) { thread { isResolved } } }',
376
- variables: { threadId },
377
- },
338
+ disputed: false,
339
+ escalationLabel: null,
378
340
  };
379
341
  }
380
342