@akjamie/agentic-sdlc 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { LEVEL_RANK, CANONICAL_DESTRUCTIVE_PATTERN } from '../rules/builtin.js';
2
2
  import { judgeChangeSemantics } from '../ai_judge.js';
3
3
 
4
- export function evaluateV1Intent({ requirement = '', specDelta = '', changedFiles = [], changeType = null } = {}) {
4
+ export function evaluateV1Intent({ requirement = '', specDelta = '', changedFiles = [], changeType = null, agentContext = null } = {}) {
5
5
  const req = String(requirement || '').toLowerCase();
6
6
  const evidence = [];
7
7
  const unresolved = [];
@@ -36,10 +36,48 @@ export function evaluateV1Intent({ requirement = '', specDelta = '', changedFile
36
36
  });
37
37
  }
38
38
 
39
- // 2. AI Semantic Classification: Pure Test or Pure Doc Evaluation (L0)
40
- // CRITICAL: A soft classifier must NEVER downgrade an already-triggered hard security signal! (P0-1)
41
- if (!mandatory_human_review) {
42
- const aiJudgment = judgeChangeSemantics({ requirement: req, changedFiles });
39
+ // 2. Semantic Evaluation: Agent Native Evaluation, External LLM Classifier, or Heuristic Baseline
40
+ const aiJudgment = judgeChangeSemantics({ requirement: req, changedFiles, agentContext });
41
+ const evalMode = aiJudgment.evaluator_mode || 'heuristic_seed';
42
+ const isAiMode = evalMode !== 'heuristic_seed';
43
+
44
+ // 2a. Agent / LLM Semantic Escalation (Bidirectional — never triggered by offline regex heuristic_seed):
45
+ if (isAiMode) {
46
+ if (aiJudgment.classification === 'api_contract' || aiJudgment.contains_api_changes) {
47
+ if (level === 'L1') {
48
+ level = 'L2';
49
+ inferredType = inferredType === 'chore' ? 'change' : inferredType;
50
+ evidence.push({
51
+ id: 'V1_AI_API_CONTRACT_INTENT',
52
+ kind: 'semantic_intent',
53
+ signal: 'hard',
54
+ summary: aiJudgment.rationale || 'Agent Semantic Evaluation: Change modifies cross-boundary API contracts'
55
+ });
56
+ }
57
+ } else if (aiJudgment.classification === 'destructive' || aiJudgment.contains_destructive_ops) {
58
+ level = 'L3';
59
+ mandatory_human_review = true;
60
+ evidence.push({
61
+ id: 'V1_AI_DESTRUCTIVE_INTENT',
62
+ kind: 'semantic_intent',
63
+ signal: 'hard',
64
+ summary: aiJudgment.rationale || 'Agent Semantic Evaluation: Task involves destructive data purge or drop'
65
+ });
66
+ } else if (aiJudgment.classification === 'governance_plane') {
67
+ level = 'L3';
68
+ mandatory_human_review = true;
69
+ evidence.push({
70
+ id: 'V1_AI_GOVERNANCE_INTENT',
71
+ kind: 'semantic_intent',
72
+ signal: 'hard',
73
+ summary: aiJudgment.rationale || 'Agent Semantic Evaluation: Task modifies core repository governance'
74
+ });
75
+ }
76
+ }
77
+
78
+ // 2b. L0 Trivial Evaluation (only if no hard signals triggered)
79
+ if (!mandatory_human_review && level === 'L1') {
80
+ const modePrefix = isAiMode ? 'Agent Semantic Evaluation' : 'Deterministic Heuristic Baseline';
43
81
  if (aiJudgment.is_pure_test) {
44
82
  level = 'L0';
45
83
  inferredType = 'chore';
@@ -47,7 +85,7 @@ export function evaluateV1Intent({ requirement = '', specDelta = '', changedFile
47
85
  id: 'V1_AI_TEST_EVALUATION',
48
86
  kind: 'scanner_result',
49
87
  signal: 'soft',
50
- summary: aiJudgment.rationale || 'AI Semantic Evaluation: Change is strictly test suites/mocks (evaluated as L0 trivial/routine)'
88
+ summary: aiJudgment.rationale || `${modePrefix}: Change is strictly test suites/mocks (evaluated as L0 trivial/routine)`
51
89
  });
52
90
  } else if (aiJudgment.is_pure_doc) {
53
91
  level = 'L0';
@@ -56,7 +94,7 @@ export function evaluateV1Intent({ requirement = '', specDelta = '', changedFile
56
94
  id: 'V1_AI_DOC_EVALUATION',
57
95
  kind: 'scanner_result',
58
96
  signal: 'soft',
59
- summary: aiJudgment.rationale || 'AI Semantic Evaluation: Intent is purely documentation, typo, or comment editing'
97
+ summary: aiJudgment.rationale || `${modePrefix}: Intent is purely documentation, typo, or comment editing`
60
98
  });
61
99
  }
62
100
  }
@@ -71,10 +109,17 @@ export function evaluateV1Intent({ requirement = '', specDelta = '', changedFile
71
109
  return {
72
110
  level,
73
111
  confidence,
112
+ evaluator_mode: evalMode,
74
113
  inferredType,
75
114
  evidence,
76
115
  unresolved,
77
116
  mandatory_human_review,
78
- no_signal
117
+ no_signal,
118
+ requirement: effectiveReqSafe(req),
119
+ aiJudgment
79
120
  };
80
121
  }
122
+
123
+ function effectiveReqSafe(req) {
124
+ return req || '';
125
+ }
@@ -1,8 +1,9 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { HARD_RULES, isTestOrDocFile } from '../rules/builtin.js';
3
+ import { HARD_RULES, isTestOrDocFile, isChangeMetadataFile } from '../rules/builtin.js';
4
+ import { getGraphTopologyMetrics } from '../../lib/graphify.js';
4
5
 
5
- export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRoot = null } = {}) {
6
+ export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRoot = null, changeId = null } = {}) {
6
7
  const req = String(requirement || '').toLowerCase();
7
8
  const evidence = [];
8
9
  const unresolved = [];
@@ -72,7 +73,100 @@ export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRo
72
73
  }
73
74
  }
74
75
 
75
- // 2. Check Requirement Semantics for Architecture / Schema / Infra
76
+ // 2. Graphify AST Knowledge Graph Centrality & God Nodes Check
77
+ // Escalates to L2 if changed files touch architectural hubs with high cross-file fan-in
78
+ if (repoRoot) {
79
+ try {
80
+ const topoMetrics = getGraphTopologyMetrics(repoRoot);
81
+ if (topoMetrics.available && topoMetrics.fileInDegree) {
82
+ // High centrality threshold: >= 20 cross-file inbound dependencies
83
+ // Exclude purely peripheral utility loggers or formats
84
+ const GOD_NODE_THRESHOLD = 20;
85
+ const hitHubs = [];
86
+
87
+ const substantiveFiles = changedFiles.filter((f) => !isChangeMetadataFile(f));
88
+
89
+ // Check 1: Physical changed files
90
+ for (const f of substantiveFiles) {
91
+ if (isTestOrDocFile(f)) continue;
92
+ const norm = f.replace(/\\/g, '/');
93
+ if (/(^|\/)(log|logger|logging|cliutil)\.[a-z0-9]+$/i.test(norm)) continue; // ignore pure logger / cli wrappers
94
+ const inDegree = topoMetrics.fileInDegree[norm] || 0;
95
+ if (inDegree >= GOD_NODE_THRESHOLD) {
96
+ hitHubs.push({ file: norm, inDegree });
97
+ }
98
+ }
99
+
100
+ // Check 2: Pre-implementation stages (no substantive changedFiles yet) — ground in explore.md query
101
+ // IMPORTANT:
102
+ // a) Only inspect the ## Query: section (never the global ## Architectural hubs header).
103
+ // b) When Graphify outputs a BFS depth=2 traversal with `Start: [...]`, restrict matches to
104
+ // 0-hop Start nodes so 2-hop neighbor hubs (e.g. leaf -> caller -> fs.js) do not trigger false positives.
105
+ if (substantiveFiles.length === 0 && hitHubs.length === 0 && changeId) {
106
+ try {
107
+ const expPath = path.join(repoRoot, 'openspec', 'changes', changeId, 'explore.md');
108
+ if (fs.existsSync(expPath)) {
109
+ const expContent = fs.readFileSync(expPath, 'utf8');
110
+ const queryMatch = expContent.match(/##\s*Query:[^\n]*\n([\s\S]*?)(?:\n##\s|$)/i);
111
+ const queryContent = queryMatch ? queryMatch[1] : '';
112
+ if (queryContent && !queryContent.includes('_(no matches)_') && !queryContent.includes('_(unavailable')) {
113
+ const startHeaderMatch = queryContent.match(/\bStart:\s*\[([^\]]*)\]/);
114
+ let directHitFiles = null;
115
+ let startLabels = null;
116
+
117
+ if (startHeaderMatch) {
118
+ startLabels = new Set();
119
+ const rawList = startHeaderMatch[1];
120
+ for (const m of rawList.matchAll(/['"]([^'"]+)['"]/g)) {
121
+ startLabels.add(m[1].trim());
122
+ }
123
+ directHitFiles = new Set();
124
+ for (const m of queryContent.matchAll(/^NODE\s+(.+?)\s+\[src=([^\s\]]+)/gm)) {
125
+ const nodeLabel = m[1].trim();
126
+ const nodeSrc = m[2].replace(/\\/g, '/');
127
+ if (startLabels.has(nodeLabel) && !isTestOrDocFile(nodeSrc)) {
128
+ directHitFiles.add(nodeSrc);
129
+ }
130
+ }
131
+ }
132
+
133
+ for (const [hubFile, inDeg] of (topoMetrics.topHubs || [])) {
134
+ if (inDeg >= GOD_NODE_THRESHOLD && !/(^|\/)(log|logger|logging|cliutil)\.[a-z0-9]+$/i.test(hubFile)) {
135
+ const baseName = path.basename(hubFile);
136
+ const matched = directHitFiles !== null
137
+ ? (directHitFiles.has(hubFile) || startLabels.has(hubFile) || startLabels.has(baseName))
138
+ : (queryContent.includes(hubFile) || queryContent.includes(baseName));
139
+ if (matched) {
140
+ hitHubs.push({ file: hubFile, inDegree: inDeg });
141
+ }
142
+ }
143
+ }
144
+ }
145
+ }
146
+ } catch { /* ignore explore read */ }
147
+ }
148
+
149
+ if (hitHubs.length > 0) {
150
+ no_signal = false;
151
+ if (level === 'L1') {
152
+ level = 'L2';
153
+ }
154
+ const hubDesc = hitHubs.slice(0, 3).map((h) => `${h.file} (${h.inDegree} inbound refs)`).join(', ');
155
+ evidence.push({
156
+ id: 'V3_GRAPHIFY_GOD_NODE',
157
+ kind: 'topology_centrality',
158
+ signal: 'hard',
159
+ summary: `Touches Graphify AST architectural hub: ${hubDesc}`,
160
+ source: hitHubs[0].file
161
+ });
162
+ }
163
+ }
164
+ } catch {
165
+ /* ignore graph metrics reading failure */
166
+ }
167
+ }
168
+
169
+ // 3. Check Requirement Semantics for Architecture / Schema / Infra
76
170
  const topoKeywords = [
77
171
  'api', 'endpoint', 'openapi', 'swagger', 'grpc', 'protobuf', 'graphql', 'webhook',
78
172
  'fastapi', 'springboot', 'spring boot', 'controller', 'rest api', 'router',
@@ -6,6 +6,7 @@ import { lastCommitTouching, git } from '../lib/git.js';
6
6
  import { fail } from '../lib/errors.js';
7
7
  import { log } from '../lib/log.js';
8
8
  import { isSinglePrLevel, readEffectiveLevel } from '../lib/level.js';
9
+ import { assess } from '../assess/index.js';
9
10
 
10
11
  // Guard before implementing: the spec must be APPROVED on the target branch
11
12
  // (i.e. the Spec PR has been merged into targetBranch, locking proposal.md & specs/**).
@@ -15,7 +16,6 @@ export function applyGuard(changeId, opts = {}) {
15
16
  const cdir = changeDir(repoRoot, slug);
16
17
  if (!exists(cdir)) fail(`change '${slug}' not found`);
17
18
 
18
- // 1. Resolve target branch dynamically: CLI option -> .openspec.yaml -> git tracking -> main/master
19
19
  const metaPath = path.join(cdir, '.openspec.yaml');
20
20
  let meta = {};
21
21
  if (exists(metaPath)) {
@@ -49,7 +49,32 @@ export function applyGuard(changeId, opts = {}) {
49
49
  });
50
50
  }
51
51
 
52
- const effectiveLevel = levelInfo?.effectiveLevel || meta.level || null;
52
+ let effectiveLevel = levelInfo?.effectiveLevel || meta.level || null;
53
+ const agentAssessPath = path.join(cdir, '.agent-assess.json');
54
+ if (meta.level && (exists(agentAssessPath) || levelInfo?.maxHistoryLevel)) {
55
+ const assessment = assess({
56
+ stage: 'spec',
57
+ changeId: slug,
58
+ repoRoot,
59
+ persist: true
60
+ });
61
+ const assessedLevel = assessment.risk.level;
62
+ const rank = { L0: 0, L1: 1, L2: 2, L3: 3 };
63
+ if ((rank[assessedLevel] ?? 0) > (rank[effectiveLevel] ?? 0)) {
64
+ effectiveLevel = assessedLevel;
65
+ if (exists(metaPath)) {
66
+ let metaText = readText(metaPath);
67
+ const upsertKey = (text, key, val) => {
68
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
69
+ return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
70
+ };
71
+ metaText = upsertKey(metaText, 'level', effectiveLevel);
72
+ metaText = upsertKey(metaText, 'workflowMode', assessment.governance.workflow_mode);
73
+ writeText(metaPath, metaText);
74
+ }
75
+ }
76
+ }
77
+
53
78
  const isSinglePr = isSinglePrLevel(effectiveLevel);
54
79
  let approvedSha = null;
55
80
 
@@ -88,7 +113,7 @@ export function applyGuard(changeId, opts = {}) {
88
113
  });
89
114
  }
90
115
 
91
- // 4. Content-level cryptographic zero-diff invariant:
116
+ // 4. Content-level Git-anchored zero-diff invariant:
92
117
  // The local spec content MUST match the approved version on the target branch
93
118
  const diff = (git(['diff', approvedSha, '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
94
119
  if (diff) {
@@ -109,6 +134,10 @@ export function applyGuard(changeId, opts = {}) {
109
134
  };
110
135
  metaText = upsertKey(metaText, 'specSha', approvedSha);
111
136
  metaText = upsertKey(metaText, 'status', 'ready_for_impl');
137
+ if (effectiveLevel && effectiveLevel !== meta.level) {
138
+ metaText = upsertKey(metaText, 'level', effectiveLevel);
139
+ metaText = upsertKey(metaText, 'workflowMode', 'spec-first');
140
+ }
112
141
  writeText(metaPath, metaText);
113
142
  }
114
143
  log.ok(`${slug}: recognized PR approval on ${branch} (synced state to ready_for_impl @ ${approvedSha.slice(0, 8)})`);
@@ -1,8 +1,9 @@
1
1
  import path from 'node:path';
2
- import { exists, readText, walkFiles } from '../lib/fs.js';
2
+ import { exists, readText, writeText, walkFiles } from '../lib/fs.js';
3
3
  import { changeDir } from '../lib/paths.js';
4
4
  import { requireRepo, toChangeSlug, readLintConfig, jsonOut } from '../lib/cliutil.js';
5
5
  import { lintSpecText, countBlockers } from '../lib/speclint.js';
6
+ import { assess } from '../assess/index.js';
6
7
  import { log, dim } from '../lib/log.js';
7
8
 
8
9
  // THE spec check (v10: lint absorbed review). Deterministic:
@@ -90,7 +91,7 @@ export function runLint(changeId, opts = {}) {
90
91
 
91
92
  const reviewPath = path.join(cdir, 'review.md');
92
93
  if (!exists(reviewPath)) {
93
- add('review.md', 'pass', 'delegated to CI bot (review comments & summary posted on PR)');
94
+ add('review.md', 'pass', 'delegated to independent review agent (review comments & summary posted on PR)');
94
95
  add('review verdict', 'pass', 'pending human PR review on GitHub/GitLab');
95
96
  } else {
96
97
  const text = readText(reviewPath);
@@ -100,6 +101,35 @@ export function runLint(changeId, opts = {}) {
100
101
  add('blocking findings', hasBlockingFindings(text) ? 'fail' : 'pass', hasBlockingFindings(text) ? 'blocking findings present' : '');
101
102
  }
102
103
 
104
+ // Spec-stage risk assessment: ground in artifacts and sync level/workflow mode
105
+ const metaPath = path.join(cdir, '.openspec.yaml');
106
+ let currLvl = null;
107
+ if (exists(metaPath)) {
108
+ const lvlMatch = readText(metaPath).match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
109
+ currLvl = lvlMatch ? lvlMatch[1].toUpperCase() : null;
110
+ }
111
+ const agentAssessPath = path.join(cdir, '.agent-assess.json');
112
+ if (currLvl || exists(agentAssessPath) || exists(path.join(cdir, 'risk-history.jsonl'))) {
113
+ const assessment = assess({
114
+ stage: 'spec',
115
+ changeId: slug,
116
+ repoRoot,
117
+ persist: true
118
+ });
119
+ const effectiveLevel = assessment.risk.level;
120
+ if (exists(metaPath) && currLvl !== effectiveLevel) {
121
+ let metaText = readText(metaPath);
122
+ const upsertKey = (text, key, val) => {
123
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
124
+ return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
125
+ };
126
+ metaText = upsertKey(metaText, 'level', effectiveLevel);
127
+ metaText = upsertKey(metaText, 'workflowMode', assessment.governance.workflow_mode);
128
+ writeText(metaPath, metaText);
129
+ }
130
+ add('governance level', 'pass', `${effectiveLevel} (${assessment.governance.workflow_mode})`);
131
+ }
132
+
103
133
  const { rules } = readLintConfig(repoRoot);
104
134
  const findings = [];
105
135
  for (const file of specFiles) {
@@ -34,28 +34,8 @@ export function newChange(requirement, opts = {}) {
34
34
  // Determine grill mode: 'none' (--no-grill), 'batch' (--batch-grill), or 'interactive' (default grill-me)
35
35
  const grillMode = opts.grill === false ? 'none' : (opts.batchGrill ? 'batch' : 'interactive');
36
36
 
37
- // Infer governance level (L0, L1, L2, L3) via unified assessment engine
38
- const { level, changeType, workflowMode, reason: levelReason } = inferInitialLevel({
39
- requirement,
40
- explicitLevel: opts.level,
41
- repoRoot,
42
- changeId: slug
43
- });
44
-
45
- // Record requirement, grill mode, and governance level in change metadata (.openspec.yaml)
46
- const metaPath = path.join(cdir, '.openspec.yaml');
47
- if (exists(metaPath)) {
48
- const existing = readText(metaPath).trimEnd();
49
- writeText(metaPath, `${existing}\nrequirement: ${JSON.stringify(requirement)}\ngrillMode: "${grillMode}"\nchangeType: "${changeType}"\nworkflowMode: "${workflowMode}"\nlevel: "${level}"\nlevelReason: ${JSON.stringify(levelReason)}\n`);
50
- }
51
-
52
- if (workflowMode === 'single-pr') {
53
- log.ok(`assigned governance level: ${level} [Type: ${changeType}] (${levelReason}) - [Single PR mode: code & specs in one PR]`);
54
- } else {
55
- log.ok(`assigned governance level: ${level} [Type: ${changeType}] (${levelReason}) - [Spec-first mode: Spec PR required before implementation]`);
56
- }
57
-
58
- const g = ensureGraphify();
37
+ // Grounding in knowledge graph (explore.md) before assessing initial risk level
38
+ const g = ensureGraphify({ autoInstall: false });
59
39
  if (!g.installed) {
60
40
  log.warn('[WARN] explore.md generated without graph context (Graphify not installed). Run `asdlc init --graph` to enable architectural AST index.');
61
41
  const fallbackMd = `# Explore: ${slug}
@@ -116,6 +96,27 @@ _(unavailable - graph query error)_
116
96
  }
117
97
  }
118
98
 
99
+ // Infer governance level (L0, L1, L2, L3) via unified assessment engine (grounded in explore.md)
100
+ const { level, changeType, workflowMode, reason: levelReason } = inferInitialLevel({
101
+ requirement,
102
+ explicitLevel: opts.level,
103
+ repoRoot,
104
+ changeId: slug
105
+ });
106
+
107
+ // Record requirement, grill mode, and governance level in change metadata (.openspec.yaml)
108
+ const metaPath = path.join(cdir, '.openspec.yaml');
109
+ if (exists(metaPath)) {
110
+ const existing = readText(metaPath).trimEnd();
111
+ writeText(metaPath, `${existing}\nrequirement: ${JSON.stringify(requirement)}\ngrillMode: "${grillMode}"\nchangeType: "${changeType}"\nworkflowMode: "${workflowMode}"\nlevel: "${level}"\nlevelReason: ${JSON.stringify(levelReason)}\n`);
112
+ }
113
+
114
+ if (workflowMode === 'single-pr') {
115
+ log.ok(`assigned governance level: ${level} [Type: ${changeType}] (${levelReason}) - [Single PR mode: code & specs in one PR]`);
116
+ } else {
117
+ log.ok(`assigned governance level: ${level} [Type: ${changeType}] (${levelReason}) - [Spec-first mode: Spec PR required before implementation]`);
118
+ }
119
+
119
120
  // Seed the grilling interview / clarification record.
120
121
  const clar = path.join(cdir, 'clarifications.md');
121
122
  if (!exists(clar)) {
@@ -56,7 +56,7 @@ export function statusChange(changeId, opts = {}) {
56
56
  let next;
57
57
  if (!has('explore.md') && !has('proposal.md')) next = `asdlc new ${changeId}`;
58
58
  else if (!has('proposal.md') || specFiles.length === 0) next = 'author proposal.md + specs/**';
59
- else if (!approvedSha) next = `run: asdlc lint ${changeId} && asdlc pr ${changeId} (CI handles AI review on PR; once merged run: asdlc approve ${changeId})`;
59
+ else if (!approvedSha) next = `run: asdlc lint ${changeId} && asdlc pr ${changeId} (after independent spec review & merge, run: asdlc approve ${changeId})`;
60
60
  else if (unchecked !== 0) next = `asdlc apply ${changeId}, then complete tasks in tasks.md`;
61
61
  else next = `asdlc verify ${changeId}`;
62
62
 
@@ -1,10 +1,11 @@
1
1
  import path from 'node:path';
2
2
  import { exists, readText, walkFiles } from '../lib/fs.js';
3
- import { changeDir } from '../lib/paths.js';
3
+ import { changeDir, openspecDir } from '../lib/paths.js';
4
4
  import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
5
5
  import { runShell } from '../lib/exec.js';
6
6
  import { fail } from '../lib/errors.js';
7
7
  import { log } from '../lib/log.js';
8
+ import { readYaml } from '../lib/yaml.js';
8
9
 
9
10
  export function parseSpecAcceptanceCriteria(specText) {
10
11
  const acs = [];
@@ -88,9 +89,35 @@ export function runTests(changeId, opts = {}) {
88
89
  log.info('');
89
90
  }
90
91
 
91
- const runnerCmd = opts.runner ?? (process.platform === 'win32'
92
- ? `node --test ${uniqueTestPaths.map((p) => `"${p}"`).join(' ')}`
93
- : `node --test ${uniqueTestPaths.join(' ')}`);
92
+ const testCfg = path.join(openspecDir(repoRoot), 'config.yaml');
93
+ let configuredRunner = null;
94
+ if (exists(testCfg)) {
95
+ try {
96
+ const parsed = readYaml(testCfg);
97
+ configuredRunner = parsed?.test?.runner || parsed?.testing?.runner || null;
98
+ } catch { /* ignore config parse error */ }
99
+ }
100
+
101
+ const defaultRunner = () => {
102
+ const allGo = uniqueTestPaths.every((p) => p.endsWith('.go'));
103
+ const allPy = uniqueTestPaths.every((p) => p.endsWith('.py'));
104
+ const allJava = uniqueTestPaths.every((p) => /\.(java|kt)$/i.test(p));
105
+ if (allGo) {
106
+ // In Go, package directory syntax './path/to/pkg' is required so intra-package symbols resolve
107
+ const goPkgs = [...new Set(uniqueTestPaths.map((p) => {
108
+ const dir = path.dirname(p).replace(/\\/g, '/');
109
+ return dir === '.' ? '.' : `./${dir}`;
110
+ }))];
111
+ return `go test ${goPkgs.join(' ')}`;
112
+ }
113
+ if (allPy) return `pytest ${uniqueTestPaths.join(' ')}`;
114
+ if (allJava) return 'mvn test';
115
+ return process.platform === 'win32'
116
+ ? `node --test ${uniqueTestPaths.map((p) => `"${p}"`).join(' ')}`
117
+ : `node --test ${uniqueTestPaths.join(' ')}`;
118
+ };
119
+
120
+ const runnerCmd = opts.runner ?? configuredRunner ?? defaultRunner();
94
121
 
95
122
  const res = runShell(runnerCmd, repoRoot, {
96
123
  env: { NODE_TEST_CONTEXT: undefined },
@@ -11,7 +11,7 @@ import { checkSchema } from '../lib/schema.js';
11
11
  import { loadPolicy, isAdvisory, DEFAULT_POLICY, matchesAny } from '../lib/policy.js';
12
12
  import { classifyPR } from '../lib/prtype.js';
13
13
  import { isSinglePrLevel, requiresHumanReview, readChangeLevel, readEffectiveLevel } from '../lib/level.js';
14
- import { assess, renderCheckSummary, loadInitialAssessment } from '../assess/index.js';
14
+ import { assess, renderCheckSummary, loadRiskHistory } from '../assess/index.js';
15
15
  import { checkTestPresence, checkTaskEvidence } from '../lib/tdd.js';
16
16
  import { log, dim } from '../lib/log.js';
17
17
 
@@ -22,15 +22,27 @@ import { log, dim } from '../lib/log.js';
22
22
  function meta(repoRoot, changeId) {
23
23
  const p = path.join(changeDir(repoRoot, toChangeSlug(changeId)), '.openspec.yaml');
24
24
  if (!exists(p)) return {};
25
- const text = readText(p);
26
- const sha = text.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
27
- const status = text.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
28
- const lvl = text.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
29
- return {
30
- specSha: sha ? sha[1] : null,
31
- status: status ? status[1] : null,
32
- level: lvl ? lvl[1].toUpperCase() : null,
33
- };
25
+ try {
26
+ const data = readYaml(p) ?? {};
27
+ return {
28
+ specSha: data.specSha ? String(data.specSha) : null,
29
+ status: data.status ? String(data.status) : null,
30
+ level: data.level ? String(data.level).toUpperCase() : null,
31
+ escalatedInImpl: data.escalatedInImpl === true || String(data.escalatedInImpl).toLowerCase() === 'true',
32
+ };
33
+ } catch {
34
+ const text = readText(p);
35
+ const sha = text.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
36
+ const status = text.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
37
+ const lvl = text.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
38
+ const esc = text.match(/^\s*escalatedInImpl:\s*['"]?([^\s'"]+)['"]?\s*$/m);
39
+ return {
40
+ specSha: sha ? sha[1] : null,
41
+ status: status ? status[1] : null,
42
+ level: lvl ? lvl[1].toUpperCase() : null,
43
+ escalatedInImpl: esc ? esc[1].toLowerCase() === 'true' : false,
44
+ };
45
+ }
34
46
  }
35
47
 
36
48
  function readYamlConfig(repoRoot) {
@@ -133,15 +145,27 @@ export function runVerify(changeId, opts = {}) {
133
145
  } else {
134
146
  add('level-integrity', 'pass', `conforms to recorded history (${effLevel?.effectiveLevel || 'L1'})`);
135
147
  }
136
- const { specSha, status } = meta(repoRoot, changeId);
137
- const changeLevel = effLevel?.effectiveLevel || meta(repoRoot, changeId).level || null;
148
+ const metaInfo = meta(repoRoot, changeId);
149
+ const { specSha, status } = metaInfo;
150
+ const changeLevel = effLevel?.effectiveLevel || metaInfo.level || null;
138
151
 
139
152
  const changedFiles = (git(['diff', '--name-only', `${base}...${head}`], repoRoot, { allowFail: true }) ?? '')
140
153
  .split(/\r?\n/).filter(Boolean);
141
154
  const changeOnMain = changeOnRef(repoRoot, branch, slug);
142
- const initialAss = loadInitialAssessment(repoRoot, slug);
143
- const wasInitialSinglePr = initialAss && isSinglePrLevel(initialAss.risk?.level);
144
- const isSinglePr = Boolean(wasInitialSinglePr || isSinglePrLevel(changeLevel));
155
+
156
+ // Single-PR privilege applies ONLY if the change is currently L0/L1 OR legitimately entered
157
+ // implementation as L0/L1 and escalated strictly during `impl` (NOT during `new`/`spec`).
158
+ let history = [];
159
+ try { history = loadRiskHistory(repoRoot, slug); } catch { /* handled by readEffectiveLevel */ }
160
+ const preImplRecords = history.filter((r) => r.stage === 'new' || r.stage === 'spec');
161
+ const escalatedOnlyInImpl = Boolean(
162
+ metaInfo.escalatedInImpl ||
163
+ (history.length > 0 &&
164
+ preImplRecords.length > 0 &&
165
+ preImplRecords.every((r) => isSinglePrLevel(r.risk?.level)) &&
166
+ history.some((r) => r.stage === 'impl' && !isSinglePrLevel(r.risk?.level)))
167
+ );
168
+ const isSinglePr = Boolean(isSinglePrLevel(changeLevel) || escalatedOnlyInImpl);
145
169
 
146
170
  const pr = classifyPR({ changedFiles, changeOnMain, policy, emergency: opts.emergency, level: changeLevel, repoRoot, singlePr: isSinglePr });
147
171
  add('pr-type', pr.type === 'invalid' ? 'fail' : 'pass', `type=${pr.type} (${pr.reason})`);
@@ -157,7 +181,7 @@ export function runVerify(changeId, opts = {}) {
157
181
  const approvedSha = lastCommitTouching(repoRoot, branch, lockedPaths);
158
182
  if (effLevel?.tampered) {
159
183
  add('approved-spec', 'fail', 'governance level tampered: declared level is lower than history');
160
- } else if (isSinglePrLevel(changeLevel) || wasInitialSinglePr) {
184
+ } else if (isSinglePr) {
161
185
  add('approved-spec', 'pass', `${changeLevel || 'single-pr'} single-PR mode (spec approval co-located in implementation PR)`);
162
186
  } else if (!approvedSha) {
163
187
  add('approved-spec', 'fail', `no commit on locked paths is merged into ${branch} (not approved)`);
@@ -169,13 +193,13 @@ export function runVerify(changeId, opts = {}) {
169
193
 
170
194
  // Lightweight tamper guard: in a two-phase implementation PR, locked spec files MUST NOT be modified
171
195
  const lockedModified = changedFiles.filter((f) => matchesAny(f, policy?.locked_paths ?? DEFAULT_POLICY.locked_paths));
172
- if (!isSinglePrLevel(changeLevel) && !wasInitialSinglePr && pr.type === 'impl' && lockedModified.length > 0) {
196
+ if (!isSinglePr && pr.type === 'impl' && lockedModified.length > 0) {
173
197
  add('spec-tamper', 'fail', `${lockedModified.length} locked spec file(s) modified in implementation PR (${lockedModified.join(', ')})`);
174
198
  } else {
175
199
  add('spec-tamper', 'pass', 'locked spec paths unmodified');
176
200
  }
177
201
 
178
- if (isSinglePrLevel(changeLevel) || wasInitialSinglePr) {
202
+ if (isSinglePr) {
179
203
  add('flow-state', 'pass', `${changeLevel || 'single-pr'} single-PR mode (direct implementation)`);
180
204
  } else {
181
205
  add('flow-state', status === 'ready_for_impl' ? 'pass' : 'fail',
@@ -197,9 +221,12 @@ export function runVerify(changeId, opts = {}) {
197
221
  });
198
222
 
199
223
  const effectiveLevel = assessment.risk.level;
200
- const isEscalated = assessment.verdict === 'escalated' || (effLevel?.declaredLevel && effLevel.declaredLevel !== effectiveLevel && effectiveLevel !== 'L1');
224
+ const isEscalatedInImpl = Boolean(
225
+ (assessment.reason_codes || []).includes('ESCALATED_IN_IMPL') ||
226
+ (isSinglePr && !isSinglePrLevel(effectiveLevel))
227
+ );
201
228
 
202
- if (isEscalated) {
229
+ if (isEscalatedInImpl) {
203
230
  // Synchronize .openspec.yaml on in-place escalation (local runs only, avoid dirtying tree in CI)
204
231
  const metaPath = path.join(cdir, '.openspec.yaml');
205
232
  if (!isCI && !opts.openingPr && exists(metaPath)) {