@akjamie/agentic-sdlc 1.10.0 โ†’ 1.11.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.
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # agentic-sdlc
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/@akjamie/agentic-sdlc?color=6366f1&label=npm)](https://www.npmjs.com/package/@akjamie/agentic-sdlc)
4
- [![version: v1.10.0](https://img.shields.io/badge/version-v1.10.0-6366f1.svg)](package.json)
4
+ [![version: v1.11.0](https://img.shields.io/badge/version-v1.11.0-6366f1.svg)](package.json)
5
5
  [![license: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-10b981.svg)](LICENSE)
6
6
  [![Node.js](https://img.shields.io/badge/node-%3E%3D20.19.0-38bdf8.svg)](https://nodejs.org/)
7
- [![tests](https://img.shields.io/badge/tests-225%20passing-10b981.svg)](#development--verification)
7
+ [![tests](https://img.shields.io/badge/tests-237%20passing-10b981.svg)](#development--verification)
8
8
  [![architecture](https://img.shields.io/badge/governance-L0--L3%20Adaptive%20Dual--Track-f59e0b.svg)](#adaptive-risk-tiered-governance-l0l3)
9
9
 
10
10
  > **The Intelligent Governance Engine for Autonomous AI Coding.**
@@ -285,8 +285,7 @@ CLI (--mode) > Env (ASDLC_WORKFLOW_MODE) > Repo (.sdlc/policy.yaml) > Global (~/
285
285
  | Skill | Role in Agentic SDLC |
286
286
  | :--- | :--- |
287
287
  | [`asdlc-init`](assets/skills/asdlc-init/SKILL.md) | One-command bootstrapping of OpenSpec, Graphify AST, policies, and automatic tech stack / test runner discovery. |
288
- | [`asdlc-intake`](assets/skills/asdlc-intake/SKILL.md) | Multi-source PRD/file (`--from-file`) and ticket (`--from-issue` for GitHub/Jira/Confluence) intake with prompt-injection fencing. |
289
- | [`asdlc-new`](assets/skills/asdlc-new/SKILL.md) | Scaffolds change, ingests files/tickets, queries AST hubs, runs conversational anti-fatigue `grill-me`. |
288
+ | [`asdlc-new`](assets/skills/asdlc-new/SKILL.md) | Stage 1 & 2: Multi-source intake (`--from-file`, `--from-issue`), AST explore, and conversational `grill-me`. |
290
289
  | [`asdlc-lint`](assets/skills/asdlc-lint/SKILL.md) | Enforces deterministic BDD GIVEN/WHEN/THEN, R5 scenario-to-AC coverage, and `[OPEN]` clarification gates. |
291
290
  | [`asdlc-pr`](assets/skills/asdlc-pr/SKILL.md) | Smart PR dispatcher: automatically handles Spec PR vs. Implementation PR. |
292
291
  | [`asdlc-approve`](assets/skills/asdlc-approve/SKILL.md) | Stamps Git `specSha` lock and truthful merge provenance upon Spec PR merge (Track A Dual-PR; waived for Track B Single-PR). |
@@ -298,11 +297,13 @@ CLI (--mode) > Env (ASDLC_WORKFLOW_MODE) > Repo (.sdlc/policy.yaml) > Global (~/
298
297
  | [`asdlc-doctor`](assets/skills/asdlc-doctor/SKILL.md) | 12-invariant diagnostic engine with 1-click automated remediation (`--fix`). |
299
298
  | [`asdlc-status`](assets/skills/asdlc-status/SKILL.md) | Real-time change lifecycle dashboard and next actionable command guidance. |
300
299
 
300
+ > *Note: Specialized sub-skills (such as [`asdlc-intake`](assets/skills/asdlc-intake/SKILL.md) for enterprise issue tracker SSO/MCP customization) are internal helpers invoked by primary stage skills like `asdlc-new` and do not require standalone user execution.*
301
+
301
302
  ---
302
303
 
303
- ## ๐Ÿ” What `asdlc verify` Checks (12 Local & CI Gates)
304
+ ## ๐Ÿ” What `asdlc verify` Checks (13 Local & CI Gates)
304
305
 
305
- Every implementation diff must pass the 12 deterministic gates in `asdlc verify`:
306
+ Every implementation diff must pass the 13 deterministic gates in `asdlc verify`:
306
307
 
307
308
  ```mermaid
308
309
  flowchart TD
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akjamie/agentic-sdlc",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "Enterprise Agentic SDLC governance CLI: a 7-stage spec-driven flow on top of OpenSpec + Graphify, enforced by CI.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,6 +10,7 @@ import { isSinglePrLevel, readEffectiveLevel } from '../lib/level.js';
10
10
  import { resolveWorkflowMode } from '../lib/config.js';
11
11
  import { assess } from '../assess/index.js';
12
12
  import { triagePullRequest, PULL_REQUEST_THREADS_QUERY } from '../lib/triage.js';
13
+ import { recordEvent } from '../lib/telemetry.js';
13
14
 
14
15
  // Guard before implementing: the spec must be APPROVED on the target branch
15
16
  // (i.e. the Spec PR has been merged into targetBranch, locking proposal.md & specs/**).
@@ -234,8 +235,28 @@ export function applyGuard(changeId, opts = {}) {
234
235
  prCtx = { reviewThreads, issueComments: [], reviewDecision };
235
236
  }
236
237
  }
237
- const triage = triagePullRequest(prCtx || {});
238
- log.info(`[PR #${prRef}] Triaged review feedback: ${triage.actionableThreads.length} actionable, ${triage.questionThreads.length} question(s), ${triage.suggestionThreads.length} suggestion(s).`);
238
+ let commitMessages = [];
239
+ try {
240
+ const recentLog = git(['log', '-n', '20', '--format=%B'], repoRoot, { allowFail: true }) || '';
241
+ commitMessages = recentLog.split(/\r?\n\r?\n/).filter(Boolean);
242
+ } catch {}
243
+ const triage = triagePullRequest(prCtx || {}, { commitMessages });
244
+ log.info(`[PR #${prRef}] Triaged review feedback (Round ${triage.round}/${triage.maxRounds}): ${triage.actionableThreads.length} actionable, ${triage.questionThreads.length} question(s), ${triage.suggestionThreads.length} suggestion(s).`);
245
+ recordEvent('pr.triage', {
246
+ stage: 'apply',
247
+ change: slug,
248
+ pr: prNum,
249
+ reviewDecision: triage.reviewDecision || null,
250
+ unaddressedThreads: triage.unaddressedCount,
251
+ actionableThreads: triage.actionableThreads.length,
252
+ suggestionThreads: triage.suggestionThreads.length,
253
+ questionThreads: triage.questionThreads.length,
254
+ actionableCount: triage.actionableThreads.length,
255
+ questionCount: triage.questionThreads.length,
256
+ suggestionCount: triage.suggestionThreads.length,
257
+ round: triage.round,
258
+ maxRounds: triage.maxRounds,
259
+ }, { repoRoot });
239
260
  }
240
261
 
241
262
  if (isAutoPr) {
@@ -9,6 +9,7 @@ import { classifyPR } from '../lib/prtype.js';
9
9
  import { fail } from '../lib/errors.js';
10
10
  import { log } from '../lib/log.js';
11
11
  import { resolveTopology } from '../lib/level.js';
12
+ import { recordEvent } from '../lib/telemetry.js';
12
13
 
13
14
  function upsertKey(text, key, value) {
14
15
  const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
@@ -109,6 +110,14 @@ export function mergeChange(changeId, opts = {}) {
109
110
  log.info(`${slug}: status=${topology.declaredStatus} preserved (no status regression).`);
110
111
  }
111
112
 
113
+ recordEvent('lifecycle.transition', {
114
+ stage: 'approve',
115
+ change: slug,
116
+ toState: 'READY_FOR_IMPL',
117
+ mode: 'single-pr',
118
+ level: topology.effectiveLevel,
119
+ }, { repoRoot });
120
+
112
121
  log.ok(`${slug}: Single-PR mode (${topology.effectiveLevel}) - spec approval is co-located with implementation PR.`);
113
122
  log.info('final approval = human Approve on the single PR (NOT waived).');
114
123
  log.info('note: final governance level is re-assessed by `asdlc apply` when implementation context is available.');
@@ -177,6 +186,13 @@ export function mergeChange(changeId, opts = {}) {
177
186
  }
178
187
  }
179
188
 
189
+ recordEvent('lifecycle.transition', {
190
+ stage: 'approve',
191
+ change: slug,
192
+ toState: 'READY_FOR_IMPL',
193
+ approvedSha,
194
+ }, { repoRoot });
195
+
180
196
  log.info('');
181
197
  log.info('Next (automatic chain):');
182
198
  log.info(' - generate tasks: /opsx-continue (its own step, after approval)');
@@ -9,6 +9,7 @@ import { ensureFreshGraph } from '../lib/graphify.js';
9
9
  import { git } from '../lib/git.js';
10
10
  import { fail } from '../lib/errors.js';
11
11
  import { log } from '../lib/log.js';
12
+ import { recordEvent } from '../lib/telemetry.js';
12
13
 
13
14
  export const CONSTITUTIONAL_PATHS = [
14
15
  'AGENTS.md',
@@ -110,6 +111,12 @@ export function archiveChange(changeId, opts = {}) {
110
111
  log.ok('updated AGENTS.md (explicit --agents or constitutional governance change)');
111
112
  }
112
113
 
114
+ recordEvent('lifecycle.transition', {
115
+ stage: 'archive',
116
+ change: slug,
117
+ toState: 'ARCHIVED',
118
+ }, { repoRoot });
119
+
113
120
  log.ok(`archive complete for ${slug}`);
114
121
  return 0;
115
122
  }
@@ -6,6 +6,7 @@ import { lintSpecText, countBlockers } from '../lib/speclint.js';
6
6
  import { assess } from '../assess/index.js';
7
7
  import { resolveWorkflowMode } from '../lib/config.js';
8
8
  import { log, dim } from '../lib/log.js';
9
+ import { recordEvent, getChangeIteration, writeGitHubStepSummary } from '../lib/telemetry.js';
9
10
 
10
11
  // THE spec check (v10: lint absorbed review). Deterministic:
11
12
  // - required artifacts (explore.md + proposal.md + >=1 spec delta)
@@ -58,8 +59,53 @@ export function hasUnresolvedClarifications(text) {
58
59
  return Boolean(body) && !/^\(?\s*none\s*\)?\.?$/i.test(body);
59
60
  }
60
61
 
61
- function finish(results, { json, changeId }) {
62
+ function finish(results, { json, changeId, repoRoot, startTime, iteration }) {
62
63
  const blockers = results.filter((r) => r.status === 'fail');
64
+
65
+ // Telemetry Fail-Silent Logging (Harness Observability)
66
+ try {
67
+ for (const r of blockers) {
68
+ recordEvent('gate.evaluated', {
69
+ stage: 'lint',
70
+ gate: r.name,
71
+ status: 'fail',
72
+ detail: r.detail,
73
+ change: changeId || null,
74
+ iteration: iteration || 1,
75
+ }, { repoRoot });
76
+ }
77
+ recordEvent('gate.verified', {
78
+ stage: 'lint',
79
+ change: changeId || null,
80
+ status: blockers.length === 0 ? 'pass' : 'fail',
81
+ verdict: blockers.length === 0 ? 'pass' : 'fail',
82
+ totalGates: results.length,
83
+ passedGates: results.length - blockers.length,
84
+ passed: results.length - blockers.length,
85
+ failed: blockers.length,
86
+ iteration: iteration || 1,
87
+ durationMs: startTime ? (Date.now() - startTime) : null,
88
+ }, { repoRoot });
89
+
90
+ if (process.env.GITHUB_STEP_SUMMARY) {
91
+ const tableRows = results.map((r) => {
92
+ const icon = { pass: 'โœ… PASS', fail: 'โŒ FAIL', skip: 'โญ๏ธ SKIP' }[r.status] || r.status;
93
+ return `| \`${r.name}\` | ${icon} | ${r.detail || ''} |`;
94
+ }).join('\n');
95
+ const verdictBadge = blockers.length === 0 ? 'โœ… PASS' : 'โŒ FAIL';
96
+ const md = `### ๐Ÿ›๏ธ ASDLC Lint Results: \`${changeId || 'unknown'}\`
97
+ | Gate | Status | Detail |
98
+ | :--- | :--- | :--- |
99
+ ${tableRows}
100
+
101
+ **Verdict: ${verdictBadge} (${results.length - blockers.length}/${results.length} Passed)**
102
+ `;
103
+ writeGitHubStepSummary(md);
104
+ }
105
+ } catch {
106
+ // Fail-silent contract: Telemetry never throws or interferes with lint results
107
+ }
108
+
63
109
  if (json) {
64
110
  jsonOut({ changeId, pass: blockers.length === 0, results });
65
111
  return blockers.length ? 1 : 0;
@@ -80,15 +126,17 @@ function finish(results, { json, changeId }) {
80
126
  }
81
127
 
82
128
  export function runLint(changeId, opts = {}) {
129
+ const startTime = Date.now();
83
130
  const repoRoot = requireRepo(opts);
84
131
  const slug = toChangeSlug(changeId);
132
+ const iteration = getChangeIteration(repoRoot, slug, 'lint');
85
133
  const cdir = changeDir(repoRoot, slug);
86
134
  const results = [];
87
135
  const add = (name, status, detail) => results.push({ name, status, detail });
88
136
 
89
137
  if (!exists(cdir)) {
90
138
  add('change', 'fail', `change '${slug}' not found`);
91
- return finish(results, { json: opts.json, changeId });
139
+ return finish(results, { json: opts.json, changeId: slug, repoRoot, startTime, iteration });
92
140
  }
93
141
  add('change', 'pass', slug);
94
142
  add('explore.md (stage 1)', exists(path.join(cdir, 'explore.md')) ? 'pass' : 'fail',
@@ -194,7 +242,7 @@ export function runLint(changeId, opts = {}) {
194
242
  }
195
243
  add('BDD + acceptance criteria', blockers === 0 ? 'pass' : 'fail', bddDetail);
196
244
 
197
- return finish(results, { json: opts.json, changeId });
245
+ return finish(results, { json: opts.json, changeId: slug, repoRoot, startTime, iteration });
198
246
  }
199
247
 
200
248
  export function register(program) {
@@ -11,6 +11,7 @@ import { Option } from 'commander';
11
11
  import { inferInitialLevel } from '../lib/level.js';
12
12
  import { resolveWorkflowMode } from '../lib/config.js';
13
13
  import { ingestIntakeSources, extractIntakeContext } from '../lib/intake.js';
14
+ import { recordEvent } from '../lib/telemetry.js';
14
15
 
15
16
  function collectOption(val, prev = []) {
16
17
  return [...prev, val];
@@ -305,6 +306,12 @@ ${intakeSectionMd}
305
306
  log.info(' โ–ถ [API DESIGN] Follow `api-design` skill (RESTful nouns, Stripe-style / RFC 7807 errors, idempotency, cursor pagination).');
306
307
  log.info(' โ–ถ [UI/UX DESIGN] Ground visual specs in `frontend-design` (Anthropic) & Vercel Web Interface Guidelines.');
307
308
  }
309
+ recordEvent('change.created', {
310
+ stage: 'new',
311
+ change: slug,
312
+ level: level || null,
313
+ }, { repoRoot });
314
+
308
315
  log.info(` โ–ถ Run \`asdlc lint ${slug}\`.`);
309
316
  return slug;
310
317
  }
@@ -23,6 +23,7 @@ const SENSITIVE_OR_DUMP_PATTERNS = [
23
23
  { re: /\.(hprof|dmp|core|heapdump)$/i, reason: 'crash/memory dump' },
24
24
  { re: /(^|\/)core\.\d+$/i, reason: 'core dump' },
25
25
  { re: /\.log(\.\d+)?$/i, reason: 'log artifact' },
26
+ { re: /(^|\/)\.sdlc\/events\.jsonl$/i, reason: 'local friction telemetry log' },
26
27
  ];
27
28
 
28
29
  /**
@@ -7,6 +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
11
 
11
12
  // "Where am I?" for a change - a read-only view of the 7 stages from the working
12
13
  // tree + git. Useful for humans and for an agent deciding the next command.
@@ -243,16 +244,33 @@ export function statusPortfolio(opts = {}) {
243
244
  return 0;
244
245
  }
245
246
 
247
+ export function statusMetrics(opts = {}) {
248
+ const repoRoot = requireRepo(opts);
249
+ const metrics = computeTeamMetrics(repoRoot, { days: opts.days ? Number(opts.days) : 30 });
250
+ if (opts.json) {
251
+ jsonOut(metrics);
252
+ } else {
253
+ log.plain(renderMetricsDashboard(metrics));
254
+ }
255
+ return 0;
256
+ }
257
+
246
258
  export function register(program) {
247
259
  program
248
260
  .command('status [changeId]')
249
261
  .description('show where a change is in the 7 stages + the next command (or portfolio overview if omitted)')
250
262
  .option('--protected-branch <ref>', 'branch the approved spec must be merged into', 'origin/main')
251
263
  .option('--mode <mode>', 'workflow mode: supervised (default) | spec-first | auto')
264
+ .option('--metrics', 'show team governance metrics & gate friction dashboard')
265
+ .option('--days <count>', 'number of days to aggregate metrics for', '30')
252
266
  .option('--repo-root <path>')
253
267
  .option('--json', 'output machine-readable JSON')
254
268
  .action((changeId, opts) => {
255
- process.exitCode = changeId ? statusChange(changeId, opts) : statusPortfolio(opts);
269
+ if (opts.metrics) {
270
+ process.exitCode = statusMetrics(opts);
271
+ } else {
272
+ process.exitCode = changeId ? statusChange(changeId, opts) : statusPortfolio(opts);
273
+ }
256
274
  });
257
275
  }
258
276
 
@@ -18,6 +18,8 @@ import { checkTestPresence, checkTaskEvidence } from '../lib/tdd.js';
18
18
  import { runTests, parseSpecAcceptanceCriteria } from './test.js';
19
19
  import { verdictOf, reviewedShaOf, hasBlockingFindings } from './lint.js';
20
20
  import { log, dim } from '../lib/log.js';
21
+ import { recordEvent, getChangeIteration, writeGitHubStepSummary } from '../lib/telemetry.js';
22
+ import { extractAddressedThreadIds } from '../lib/triage.js';
21
23
 
22
24
  // THE implementation check (v10: gate absorbed verify). Deterministic checks
23
25
  // first, then - if a verifier is configured - independent AI verification
@@ -82,6 +84,56 @@ function finish(results, policy, opts = {}) {
82
84
  return { ...r, status };
83
85
  });
84
86
 
87
+ // Telemetry Fail-Silent Logging (Harness Observability)
88
+ try {
89
+ for (const r of processed) {
90
+ if (r.status === 'fail') {
91
+ recordEvent('gate.evaluated', {
92
+ stage: 'verify',
93
+ gate: r.name,
94
+ status: 'fail',
95
+ detail: r.detail,
96
+ change: opts.changeId || null,
97
+ iteration: opts.iteration || 1,
98
+ }, { repoRoot: opts.repoRoot });
99
+ }
100
+ }
101
+ recordEvent('gate.verified', {
102
+ stage: 'verify',
103
+ change: opts.changeId || null,
104
+ status: failed === 0 ? 'pass' : 'fail',
105
+ verdict: failed === 0 ? 'pass' : 'fail',
106
+ totalGates: processed.length,
107
+ passedGates: processed.length - failed,
108
+ passed: processed.length - failed,
109
+ failed,
110
+ iteration: opts.iteration || 1,
111
+ durationMs: opts.startTime ? (Date.now() - opts.startTime) : null,
112
+ addressedThreadIds: opts.addressedThreadIds || [],
113
+ }, { repoRoot: opts.repoRoot });
114
+
115
+ if (process.env.GITHUB_STEP_SUMMARY) {
116
+ const tableRows = processed.map((r) => {
117
+ const icon = { pass: 'โœ… PASS', fail: 'โŒ FAIL', warn: 'โš ๏ธ WARN', skip: 'โญ๏ธ SKIP' }[r.status] || r.status;
118
+ return `| \`${r.name}\` | ${icon} | ${r.detail || ''} |`;
119
+ }).join('\n');
120
+ const verdictBadge = failed === 0 ? 'โœ… PASS' : 'โŒ FAIL';
121
+ const addressedRow = (opts.addressedThreadIds && opts.addressedThreadIds.length > 0)
122
+ ? `\n- **Addressed Review Threads**: ${opts.addressedThreadIds.map((id) => `\`#${id}\``).join(', ')}`
123
+ : '';
124
+ const md = `### ๐Ÿ›๏ธ ASDLC Gate Results: \`${opts.changeId || 'unknown'}\`
125
+ - **Verdict**: ${verdictBadge} (${processed.length - failed}/${processed.length} Passed, Iteration ${opts.iteration || 1})${addressedRow}
126
+
127
+ | Gate | Status | Detail |
128
+ | :--- | :--- | :--- |
129
+ ${tableRows}
130
+ `;
131
+ writeGitHubStepSummary(md);
132
+ }
133
+ } catch {
134
+ // Fail-silent contract: Telemetry never throws or interferes with gate results
135
+ }
136
+
85
137
  if (opts.json) {
86
138
  jsonOut({
87
139
  verdict: failed === 0 ? 'PASS' : 'FAIL',
@@ -243,6 +295,7 @@ export function checkTestWeakening(repoRoot, base, head, changedFiles = [], opts
243
295
  }
244
296
 
245
297
  export function runVerify(changeId, opts = {}) {
298
+ const startTime = Date.now();
246
299
  const results = [];
247
300
  const add = (name, status, detail) => results.push({ name, status, detail });
248
301
 
@@ -258,6 +311,12 @@ export function runVerify(changeId, opts = {}) {
258
311
  const branch = opts.protectedBranch ?? resolveDefaultBranch(repoRoot);
259
312
 
260
313
  const slug = toChangeSlug(changeId);
314
+ const iteration = getChangeIteration(repoRoot, slug);
315
+ let addressedThreadIds = [];
316
+ try {
317
+ const recentLog = git(['log', '-n', '20', '--format=%B'], repoRoot, { allowFail: true }) || '';
318
+ addressedThreadIds = Array.from(extractAddressedThreadIds(recentLog.split(/\r?\n\r?\n/)));
319
+ } catch { /* fail-silent */ }
261
320
  const base = opts.base ?? branch;
262
321
  const head = opts.head ?? 'HEAD';
263
322
  const policy = loadPolicy(repoRoot, { baseRef: base });
@@ -265,7 +324,14 @@ export function runVerify(changeId, opts = {}) {
265
324
  const cdir = changeDir(repoRoot, slug);
266
325
  if (!exists(cdir)) {
267
326
  add('change', 'fail', `change '${slug}' not found`);
268
- return finish(results, policy, opts);
327
+ return finish(results, policy, {
328
+ ...opts,
329
+ repoRoot,
330
+ changeId: slug,
331
+ iteration,
332
+ startTime,
333
+ addressedThreadIds,
334
+ });
269
335
  }
270
336
  add('change', 'pass', slug);
271
337
  const effLevel = readEffectiveLevel(repoRoot, changeId, { baseRef: base });
@@ -508,7 +574,14 @@ export function runVerify(changeId, opts = {}) {
508
574
  add('AI verification', ok ? 'pass' : 'fail', String(report.summary ?? '').slice(0, 300));
509
575
  }
510
576
 
511
- return finish(results, policy, opts);
577
+ return finish(results, policy, {
578
+ ...opts,
579
+ repoRoot,
580
+ changeId: slug,
581
+ iteration,
582
+ startTime,
583
+ addressedThreadIds,
584
+ });
512
585
  }
513
586
 
514
587
  export function register(program) {
@@ -0,0 +1,363 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { git } from './git.js';
4
+ import { readYaml } from './yaml.js';
5
+ import { readText, exists } from './fs.js';
6
+ import { openspecDir } from './paths.js';
7
+
8
+ const GITIGNORE_CONTENT = `# Autogenerated by asdlc telemetry: ignore local friction logs; keep policy.yaml
9
+ events.jsonl
10
+ *.log
11
+ `;
12
+
13
+ const MAX_EVENTS_FILE_BYTES = 5 * 1024 * 1024; // 5 MB
14
+ const RETAIN_EVENT_LINES = 2000;
15
+
16
+ function trimEventsFileIfNeeded(targetFile) {
17
+ try {
18
+ const st = fs.statSync(targetFile);
19
+ if (st.size > MAX_EVENTS_FILE_BYTES) {
20
+ const content = fs.readFileSync(targetFile, 'utf8');
21
+ const lines = content.split(/\r?\n/).filter(Boolean);
22
+ if (lines.length > RETAIN_EVENT_LINES) {
23
+ const retained = lines.slice(-RETAIN_EVENT_LINES);
24
+ fs.writeFileSync(targetFile, retained.join('\n') + '\n', 'utf8');
25
+ }
26
+ }
27
+ } catch {
28
+ // fail-silent
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Records an immutable lifecycle/gate telemetry event into .sdlc/events.jsonl.
34
+ * Fail-silent contract: Any I/O error is swallowed; never throws and never affects command execution.
35
+ */
36
+ export function recordEvent(type, payload = {}, { repoRoot = process.cwd() } = {}) {
37
+ try {
38
+ if (!repoRoot || typeof repoRoot !== 'string') return;
39
+ const sdlcDir = path.join(repoRoot, '.sdlc');
40
+ if (!fs.existsSync(sdlcDir)) {
41
+ fs.mkdirSync(sdlcDir, { recursive: true });
42
+ }
43
+
44
+ // Physical anti-leak defense: automatically ensure .sdlc/.gitignore exists
45
+ const gitignorePath = path.join(sdlcDir, '.gitignore');
46
+ if (!fs.existsSync(gitignorePath)) {
47
+ try {
48
+ fs.writeFileSync(gitignorePath, GITIGNORE_CONTENT, 'utf8');
49
+ } catch { /* fail-silent */ }
50
+ } else {
51
+ try {
52
+ const existing = fs.readFileSync(gitignorePath, 'utf8');
53
+ if (!existing.includes('events.jsonl')) {
54
+ fs.appendFileSync(gitignorePath, '\nevents.jsonl\n*.log\n', 'utf8');
55
+ }
56
+ } catch { /* fail-silent */ }
57
+ }
58
+
59
+ const event = {
60
+ v: 1,
61
+ ts: new Date().toISOString(),
62
+ stage: payload.stage || 'unknown',
63
+ type,
64
+ change: payload.change || null,
65
+ ...payload,
66
+ };
67
+
68
+ const targetFile = path.join(sdlcDir, 'events.jsonl');
69
+ fs.appendFileSync(targetFile, JSON.stringify(event) + '\n', 'utf8');
70
+ trimEventsFileIfNeeded(targetFile);
71
+ } catch {
72
+ // Fail-silent contract: Telemetry failures must never break core workflow
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Safely reads local telemetry events from .sdlc/events.jsonl with optional filters.
78
+ */
79
+ export function readLocalEvents(repoRoot, { change = null, stage = null, type = null } = {}) {
80
+ try {
81
+ const targetFile = path.join(repoRoot, '.sdlc', 'events.jsonl');
82
+ if (!fs.existsSync(targetFile)) return [];
83
+ const content = fs.readFileSync(targetFile, 'utf8');
84
+ const lines = content.split(/\r?\n/).filter(Boolean);
85
+ const events = [];
86
+ for (const line of lines) {
87
+ try {
88
+ const ev = JSON.parse(line);
89
+ if (change && ev.change !== change) continue;
90
+ if (stage && ev.stage !== stage) continue;
91
+ if (type && ev.type !== type) continue;
92
+ events.push(ev);
93
+ } catch {
94
+ // skip corrupt lines
95
+ }
96
+ }
97
+ return events;
98
+ } catch {
99
+ return [];
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Derives current verification or lint iteration for a change by scanning local events.
105
+ */
106
+ export function getChangeIteration(repoRoot, changeId, stage = 'verify') {
107
+ try {
108
+ const events = readLocalEvents(repoRoot, { change: changeId, stage });
109
+ const verifySummaries = events.filter((e) => e.type === 'gate.verified');
110
+ return verifySummaries.length + 1;
111
+ } catch {
112
+ return 1;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Appends Markdown summary to GitHub Actions step summary if running in CI.
118
+ */
119
+ export function writeGitHubStepSummary(markdownText) {
120
+ try {
121
+ const summaryFile = process.env.GITHUB_STEP_SUMMARY;
122
+ if (summaryFile && typeof summaryFile === 'string') {
123
+ fs.appendFileSync(summaryFile, `\n${markdownText.trim()}\n`, 'utf8');
124
+ }
125
+ } catch {
126
+ // fail-silent
127
+ }
128
+ }
129
+
130
+ function parseChangeDirTimestamp(dirName) {
131
+ const m = String(dirName).match(/^(\d{4})-?(\d{2})-?(\d{2})/);
132
+ if (m) {
133
+ return new Date(`${m[1]}-${m[2]}-${m[3]}T00:00:00Z`).getTime();
134
+ }
135
+ return null;
136
+ }
137
+
138
+ function getChangeGitTimestamps(repoRoot, cdirRel) {
139
+ try {
140
+ const out = git(['log', '--follow', '--format=%aI', '--', cdirRel], repoRoot, { allowFail: true });
141
+ if (!out) return null;
142
+ const lines = out.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
143
+ if (lines.length === 0) return null;
144
+ const latestMs = new Date(lines[0]).getTime();
145
+ const earliestMs = new Date(lines[lines.length - 1]).getTime();
146
+ return { earliestMs, latestMs };
147
+ } catch {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ function calculatePercentile(numbers, p) {
153
+ if (!numbers || numbers.length === 0) return 0;
154
+ const sorted = [...numbers].sort((a, b) => a - b);
155
+ const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));
156
+ return sorted[idx];
157
+ }
158
+
159
+ /**
160
+ * Aggregates 30-day team metrics from permanent Git archives and local friction logs.
161
+ * Zero-extra-server: Works immediately on any clone or CI runner.
162
+ */
163
+ export function computeTeamMetrics(repoRoot, { days = 30 } = {}) {
164
+ const cutoffMs = Date.now() - (Number(days) * 24 * 60 * 60 * 1000);
165
+ const archiveBase = path.join(openspecDir(repoRoot), 'changes', 'archive');
166
+
167
+ const trackedChanges = [];
168
+ const riskLevels = { L0: 0, L1: 0, L2: 0, L3: 0, unlevelled: 0 };
169
+ const specLeadTimesMin = [];
170
+ const implLeadTimesMin = [];
171
+ const convergenceRounds = { r1: 0, r2: 0, r3: 0, escalated: 0 };
172
+
173
+ if (fs.existsSync(archiveBase)) {
174
+ let entries = [];
175
+ try {
176
+ entries = fs.readdirSync(archiveBase, { withFileTypes: true });
177
+ } catch { entries = []; }
178
+
179
+ for (const ent of entries) {
180
+ if (!ent.isDirectory()) continue;
181
+ const cdir = path.join(archiveBase, ent.name);
182
+ const cdirRel = path.relative(repoRoot, cdir).replace(/\\/g, '/');
183
+ const gitTimes = getChangeGitTimestamps(repoRoot, cdirRel);
184
+ const stampMs = parseChangeDirTimestamp(ent.name);
185
+
186
+ let dirTime = stampMs || gitTimes?.latestMs;
187
+ if (!dirTime) {
188
+ try {
189
+ const st = fs.statSync(cdir);
190
+ dirTime = Math.max(st.mtimeMs, st.birthtimeMs);
191
+ } catch { dirTime = 0; }
192
+ }
193
+
194
+ if (dirTime && dirTime < cutoffMs) continue;
195
+
196
+ trackedChanges.push(ent.name);
197
+
198
+ // 1. Risk Tier breakdown
199
+ const metaPath = path.join(cdir, '.openspec.yaml');
200
+ let lvl = 'unlevelled';
201
+ if (exists(metaPath)) {
202
+ try {
203
+ const meta = readYaml(metaPath) ?? {};
204
+ if (meta.level) {
205
+ lvl = String(meta.level).toUpperCase();
206
+ }
207
+ } catch {}
208
+ }
209
+ if (riskLevels[lvl] !== undefined) riskLevels[lvl] += 1;
210
+ else riskLevels.unlevelled += 1;
211
+
212
+ // 2. Lead Time Calculation
213
+ let tStart = null;
214
+ let tApprove = null;
215
+ let tArchive = gitTimes?.latestMs || dirTime;
216
+
217
+ // Check intake index for start timestamp
218
+ const intakePath = path.join(cdir, 'intake', 'index.yaml');
219
+ if (exists(intakePath)) {
220
+ try {
221
+ const intake = readYaml(intakePath);
222
+ if (intake?.capturedAt) tStart = new Date(intake.capturedAt).getTime();
223
+ } catch {}
224
+ }
225
+
226
+ // Check review.md for approval timestamp
227
+ const reviewPath = path.join(cdir, 'review.md');
228
+ let reviewText = '';
229
+ if (exists(reviewPath)) {
230
+ try {
231
+ reviewText = readText(reviewPath);
232
+ const m = reviewText.match(/-\s*approvedAt\s*:\s*['"]?([^\s'"]+)['"]?/i);
233
+ if (m) tApprove = new Date(m[1]).getTime();
234
+ } catch {}
235
+ }
236
+
237
+ if (!tStart) {
238
+ if (gitTimes?.earliestMs) {
239
+ tStart = gitTimes.earliestMs;
240
+ } else if (exists(path.join(cdir, 'proposal.md'))) {
241
+ try {
242
+ const st = fs.statSync(path.join(cdir, 'proposal.md'));
243
+ tStart = st.birthtimeMs || st.mtimeMs;
244
+ } catch {}
245
+ }
246
+ }
247
+
248
+ if (tStart && tApprove && tApprove >= tStart) {
249
+ specLeadTimesMin.push(Math.round((tApprove - tStart) / 60000));
250
+ }
251
+ if (tApprove && tArchive && tArchive >= tApprove) {
252
+ implLeadTimesMin.push(Math.round((tArchive - tApprove) / 60000));
253
+ }
254
+
255
+ // 3. Autonomous PR convergence estimation
256
+ if (/asdlc:needs-human-arbitration/i.test(reviewText)) {
257
+ convergenceRounds.escalated += 1;
258
+ } else {
259
+ let trailerCount = (reviewText.match(/\(ref:\s*#PRRT_[^)]+\)/g) || []).length;
260
+ try {
261
+ const logOut = git(['log', '--grep=ref: #PRRT_', '--format=%B', '--', cdirRel], repoRoot, { allowFail: true }) || '';
262
+ const commitMatches = (logOut.match(/\(ref:\s*#PRRT_[^)]+\)/g) || []).length;
263
+ trailerCount = Math.max(trailerCount, commitMatches);
264
+ } catch {}
265
+
266
+ if (trailerCount === 0) convergenceRounds.r1 += 1;
267
+ else if (trailerCount === 1) convergenceRounds.r2 += 1;
268
+ else convergenceRounds.r3 += 1;
269
+ }
270
+ }
271
+ }
272
+
273
+ // 4. Local Friction Ranking from .sdlc/events.jsonl
274
+ const localEvents = readLocalEvents(repoRoot, { stage: 'verify' });
275
+ const lintEvents = readLocalEvents(repoRoot, { stage: 'lint' });
276
+ const allFails = [...localEvents, ...lintEvents].filter((e) => e.type === 'gate.evaluated' && e.status === 'fail');
277
+
278
+ const gateFailMap = new Map();
279
+ for (const ev of allFails) {
280
+ const key = `${ev.gate || 'unknown'}|${ev.stage || 'verify'}`;
281
+ const curr = gateFailMap.get(key) || { gate: ev.gate || 'unknown', stage: ev.stage || 'verify', count: 0, sampleDetail: ev.detail || '' };
282
+ curr.count += 1;
283
+ if (ev.detail && ev.detail.length > 5) curr.sampleDetail = ev.detail;
284
+ gateFailMap.set(key, curr);
285
+ }
286
+
287
+ const frictionLeaderboard = [...gateFailMap.values()].sort((a, b) => b.count - a.count).slice(0, 5);
288
+
289
+ const total = trackedChanges.length;
290
+ const r1Pct = total > 0 ? Math.round((convergenceRounds.r1 / total) * 100) : 0;
291
+ const r2Pct = total > 0 ? Math.round((convergenceRounds.r2 / total) * 100) : 0;
292
+ const r3Pct = total > 0 ? Math.round((convergenceRounds.r3 / total) * 100) : 0;
293
+ const escPct = total > 0 ? Math.round((convergenceRounds.escalated / total) * 100) : 0;
294
+
295
+ return {
296
+ days,
297
+ totalTrackedChanges: total,
298
+ riskLevels,
299
+ leadTime: {
300
+ specP50Min: calculatePercentile(specLeadTimesMin, 50),
301
+ specP90Min: calculatePercentile(specLeadTimesMin, 90),
302
+ implP50Min: calculatePercentile(implLeadTimesMin, 50),
303
+ implP90Min: calculatePercentile(implLeadTimesMin, 90),
304
+ },
305
+ convergence: {
306
+ r1Pct,
307
+ r2Pct,
308
+ r3Pct,
309
+ escPct,
310
+ counts: convergenceRounds,
311
+ },
312
+ frictionLeaderboard,
313
+ };
314
+ }
315
+
316
+ /**
317
+ * Formats team metrics into clean ANSI ASCII tables matching Section 7.1.
318
+ */
319
+ export function renderMetricsDashboard(metrics) {
320
+ const lines = [];
321
+ lines.push('======================= ๐Ÿ›๏ธ ASDLC HARNESS OBSERVABILITY =======================');
322
+ lines.push(`๐Ÿ“… Data Source: Git Archive History (Last ${metrics.days} Days, ${metrics.totalTrackedChanges} changes tracked)`);
323
+ lines.push('');
324
+
325
+ lines.push('1. ๐Ÿšฆ Gate Friction Leaderboard (Local .sdlc/ Retries)');
326
+ lines.push(' Rank | Gate | Stage | Fails | Top Failure Pattern');
327
+ lines.push(' --------------------------------------------------------------------------');
328
+ if (metrics.frictionLeaderboard.length === 0) {
329
+ lines.push(' (No local gate failures recorded)');
330
+ } else {
331
+ metrics.frictionLeaderboard.forEach((item, idx) => {
332
+ const rank = `#${idx + 1}`.padEnd(4, ' ');
333
+ const gate = item.gate.padEnd(21, ' ').slice(0, 21);
334
+ const stage = item.stage.padEnd(6, ' ');
335
+ const fails = String(item.count).padEnd(5, ' ');
336
+ const sample = String(item.sampleDetail || 'check failed').slice(0, 32);
337
+ lines.push(` ${rank} | ${gate} | ${stage} | ${fails} | ${sample}`);
338
+ });
339
+ }
340
+ lines.push('');
341
+
342
+ lines.push('2. ๐Ÿ”„ Autonomous PR Convergence (3-Round Cap)');
343
+ lines.push(` โ€ข Round 1 Pass (Zero rework) : ${metrics.convergence.r1Pct}% (${metrics.convergence.counts.r1} PRs)`);
344
+ lines.push(` โ€ข Round 2 Pass (Converged Rd 2) : ${metrics.convergence.r2Pct}% (${metrics.convergence.counts.r2} PRs)`);
345
+ lines.push(` โ€ข Round 3 Pass (Converged Rd 3) : ${metrics.convergence.r3Pct}% (${metrics.convergence.counts.r3} PRs)`);
346
+ lines.push(` โ€ข Human Escalated (>3 rounds) : ${metrics.convergence.escPct}% (${metrics.convergence.counts.escalated} PRs)`);
347
+ lines.push('');
348
+
349
+ lines.push('3. โฑ๏ธ Stage Lead Time (P50 / P90 via Git Provenance)');
350
+ lines.push(` โ€ข Stage new -> approve (Spec Phase): ${metrics.leadTime.specP50Min}m / ${metrics.leadTime.specP90Min}m`);
351
+ lines.push(` โ€ข Stage apply -> verify (TDD Phase): ${metrics.leadTime.implP50Min}m / ${metrics.leadTime.implP90Min}m`);
352
+ lines.push('');
353
+
354
+ const l0 = metrics.riskLevels.L0 || 0;
355
+ const l1 = metrics.riskLevels.L1 || 0;
356
+ const l2 = metrics.riskLevels.L2 || 0;
357
+ const l3 = metrics.riskLevels.L3 || 0;
358
+ lines.push('4. ๐Ÿ›ก๏ธ Risk Tier Breakdown');
359
+ lines.push(` โ€ข L0 (Docs/Internal): ${l0} | L1 (Normal): ${l1} | L2 (High): ${l2} | L3 (Critical): ${l3}`);
360
+ lines.push('=============================================================================');
361
+
362
+ return lines.join('\n');
363
+ }
package/src/lib/triage.js CHANGED
@@ -41,6 +41,7 @@ const DEFAULT_AGENT_LOGINS = [
41
41
  ];
42
42
 
43
43
  const THREAD_TRAILER_RE = /\bref:\s*#([A-Za-z0-9_=-]+)/g;
44
+ export const REVIEW_ROUND_ANCHOR_RE = /<!--\s*asdlc:review-round:(\d+)\s*-->/i;
44
45
  const SUGGESTION_BLOCK_RE = /```suggestion\r?\n([\s\S]*?)```/;
45
46
 
46
47
  const ACTION_IMPERATIVE_RE = /\b(please|fix|add|remove|delete|rename|change|update|handle|refactor|avoid|should|must|need to|needs to|missing|bug|error|broken|fail|invalid|nullable|null check|throw|catch|test)\b/i;
@@ -48,6 +49,43 @@ const MIXED_SIGNAL_RE = /\b(lgtm|looks good|nice|great|good)\b.*\b(but|however|e
48
49
  const QUESTION_RE = /(\?|\b(why|how|what if|could you explain|can you explain|what does|is this|are we|should this)\b)/i;
49
50
  const PRAISE_ONLY_RE = /^(?:lgtm|looks good(?: to me)?|nice(?: work| approach| job)?|good(?: job| catch| work)?|great|awesome|ship it|\+1|๐Ÿ‘|๐ŸŽ‰|๐Ÿš€|โœ…)[!.\s]*$/i;
50
51
 
52
+ /**
53
+ * Computes the current PR review round (1..maxRounds) according to ยง6.3.
54
+ * Counts formal hidden review anchors <!-- asdlc:review-round:N -->,
55
+ * or derives round from past commit batches containing `(ref: #PRRT_...)` trailers.
56
+ */
57
+ export function computeReviewRound({ issueComments = [], commitMessages = [], reviews = [] } = {}) {
58
+ let maxAnchorRound = 1;
59
+ let foundAnchor = false;
60
+
61
+ const allTexts = [
62
+ ...issueComments.map((c) => (typeof c === 'string' ? c : c?.body || '')),
63
+ ...reviews.map((r) => (typeof r === 'string' ? r : r?.body || '')),
64
+ ];
65
+
66
+ for (const text of allTexts) {
67
+ const m = String(text).match(REVIEW_ROUND_ANCHOR_RE);
68
+ if (m) {
69
+ foundAnchor = true;
70
+ const num = parseInt(m[1], 10);
71
+ if (num > maxAnchorRound) maxAnchorRound = num;
72
+ }
73
+ }
74
+
75
+ if (foundAnchor) {
76
+ return maxAnchorRound;
77
+ }
78
+
79
+ let fixCommits = 0;
80
+ for (const msg of commitMessages) {
81
+ if (/\bref:\s*#([A-Za-z0-9_=-]+)/.test(String(msg))) {
82
+ fixCommits += 1;
83
+ }
84
+ }
85
+
86
+ return fixCommits + 1;
87
+ }
88
+
51
89
  /**
52
90
  * Extracts review thread IDs already resolved via commit trailers (`ref: #<threadId>`).
53
91
  */
@@ -187,7 +225,7 @@ export function classifyReviewComment(body, { path = null, line = null } = {}) {
187
225
  * Evaluates a full Pull Request payload through Tier 1 filtering + Tier 2 classification.
188
226
  * Captures actionable feedback regardless of whether reviewDecision is COMMENTED or CHANGES_REQUESTED.
189
227
  */
190
- export function triagePullRequest(prPayload = {}, { commitMessages = [], agentLogins = DEFAULT_AGENT_LOGINS } = {}) {
228
+ export function triagePullRequest(prPayload = {}, { commitMessages = [], agentLogins = DEFAULT_AGENT_LOGINS, maxRounds = 3 } = {}) {
191
229
  const threads = prPayload.reviewThreads?.nodes || prPayload.reviewThreads || [];
192
230
  const unaddressed = filterUnaddressedThreads(threads, { commitMessages, agentLogins });
193
231
 
@@ -225,6 +263,12 @@ export function triagePullRequest(prPayload = {}, { commitMessages = [], agentLo
225
263
  }
226
264
 
227
265
  const reviewDecision = prPayload.reviewDecision || null;
266
+ const round = computeReviewRound({
267
+ issueComments: prPayload.issueComments || [],
268
+ commitMessages,
269
+ reviews: prPayload.reviews || [],
270
+ });
271
+
228
272
  const hasHumanFeedback = reviewDecision === 'CHANGES_REQUESTED'
229
273
  || actionableThreads.length > 0
230
274
  || suggestionThreads.length > 0
@@ -233,6 +277,8 @@ export function triagePullRequest(prPayload = {}, { commitMessages = [], agentLo
233
277
 
234
278
  return {
235
279
  reviewDecision,
280
+ round,
281
+ maxRounds,
236
282
  unaddressedCount: unaddressed.length,
237
283
  actionableThreads,
238
284
  suggestionThreads,
@@ -276,10 +322,28 @@ export function applySuggestionToLines(fileContent, { startLine = null, endLine
276
322
  * Generates traceable commit trailer, GraphQL reply mutation, and optional thread resolution mutation.
277
323
  * Category C informational answers reply without committing or force-resolving the thread.
278
324
  */
279
- export function buildThreadResolutionPlan(triagedThread, { commitSha = null, summary = '', answerBody = null } = {}) {
325
+ export function buildThreadResolutionPlan(triagedThread, { commitSha = null, summary = '', answerBody = null, disputed = false, specRef = null } = {}) {
280
326
  const intent = triagedThread?.classification?.intent;
281
327
  const threadId = triagedThread.id;
282
328
 
329
+ // ยง6.2 Player != Referee: An Author Agent is strictly forbidden from auto-resolving disputed feedback
330
+ if (disputed) {
331
+ const specCitation = specRef ? `Per approved specification \`${specRef}\`` : 'Per approved specification';
332
+ const replyBody = answerBody || `Spec Conflict: ${specCitation}, requested change contradicts approved design. Escalated for human review.`;
333
+ return {
334
+ threadId,
335
+ commitMessage: null,
336
+ shouldResolve: false,
337
+ disputed: true,
338
+ 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
+ };
345
+ }
346
+
283
347
  if (intent === 'INFORMATIONAL_QUESTION') {
284
348
  const replyBody = answerBody || summary || 'Answered in technical explanation above.';
285
349
  return {