@akjamie/agentic-sdlc 1.2.0 → 1.4.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.
Files changed (48) hide show
  1. package/LICENSE +201 -21
  2. package/README.md +239 -302
  3. package/assets/commands/asdlc-apply.md +24 -0
  4. package/assets/commands/asdlc-approve.md +21 -0
  5. package/assets/commands/asdlc-archive.md +21 -0
  6. package/assets/commands/asdlc-doctor.md +24 -0
  7. package/assets/commands/asdlc-lint.md +30 -0
  8. package/assets/commands/asdlc-new.md +29 -0
  9. package/assets/commands/asdlc-pr.md +25 -0
  10. package/assets/commands/asdlc-status.md +23 -0
  11. package/assets/commands/asdlc-test.md +20 -0
  12. package/assets/commands/asdlc-verify.md +29 -0
  13. package/assets/schema/risk-assessment.schema.json +225 -0
  14. package/assets/skills/asdlc-apply/SKILL.md +43 -18
  15. package/assets/skills/asdlc-new/SKILL.md +15 -1
  16. package/assets/skills/asdlc-verify/SKILL.md +16 -6
  17. package/package.json +2 -2
  18. package/src/assess/ai_judge.js +163 -0
  19. package/src/assess/decide.js +164 -0
  20. package/src/assess/governance.js +53 -0
  21. package/src/assess/index.js +183 -0
  22. package/src/assess/render.js +71 -0
  23. package/src/assess/rules/builtin.js +195 -0
  24. package/src/assess/schema.js +148 -0
  25. package/src/assess/store.js +138 -0
  26. package/src/assess/vectors/v1_intent.js +80 -0
  27. package/src/assess/vectors/v2_security.js +131 -0
  28. package/src/assess/vectors/v3_topology.js +107 -0
  29. package/src/cli.js +91 -89
  30. package/src/commands/apply.js +103 -36
  31. package/src/commands/assess.js +57 -0
  32. package/src/commands/doctor.js +33 -18
  33. package/src/commands/init.js +5 -64
  34. package/src/commands/lint.js +9 -2
  35. package/src/commands/new.js +19 -2
  36. package/src/commands/pr.js +27 -3
  37. package/src/commands/skills.js +7 -19
  38. package/src/commands/status.js +169 -8
  39. package/src/commands/update.js +4 -3
  40. package/src/commands/upgrade.js +1 -1
  41. package/src/commands/verify.js +109 -15
  42. package/src/lib/fs.js +26 -3
  43. package/src/lib/level.js +118 -0
  44. package/src/lib/paths.js +3 -1
  45. package/src/lib/prtype.js +17 -4
  46. package/src/lib/risk.js +50 -0
  47. package/src/lib/schema.js +4 -0
  48. package/src/lib/tools.js +313 -0
@@ -0,0 +1,195 @@
1
+ export const HARNESS_RULES_VERSION = '2026.10.0';
2
+ export const ENGINE_VERSION = '1.4.0';
3
+
4
+ export const RISK_LEVELS = {
5
+ L0: 'L0',
6
+ L1: 'L1',
7
+ L2: 'L2',
8
+ L3: 'L3',
9
+ };
10
+
11
+ export const LEVEL_RANK = {
12
+ L0: 0,
13
+ L1: 1,
14
+ L2: 2,
15
+ L3: 3,
16
+ };
17
+
18
+ /**
19
+ * Global default fallback governance (Specification §5.5)
20
+ * Applied when assessment crashes, times out, or baseline is corrupted.
21
+ * Fixed at L2 (not L3) to avoid total tool paralysis while closing all automation.
22
+ */
23
+ export const DEFAULT_GOVERNANCE = {
24
+ level: 'L2',
25
+ workflow_mode: 'spec-first',
26
+ spec_approval: 'human',
27
+ implementation_review: 'ai+human',
28
+ auto_approval: 'disabled'
29
+ };
30
+
31
+ export const CANONICAL_DESTRUCTIVE_PATTERN = /\b(drop\s+(table|column|database|index|schema)|truncate\s+(table|database)?|purge\s+(data|table|database)|hard\s+delete|clean\s+database|destroy\s+database)\b/i;
32
+
33
+ /**
34
+ * Hard Signal Rules (§5.2):
35
+ * Deterministic path patterns, migration types, CI/CD, agent governance files.
36
+ * Can trigger single-veto up to L3.
37
+ */
38
+ export const HARD_RULES = [
39
+ // 1. Critical Governance Plane (L3)
40
+ {
41
+ id: 'HARD_GOV_PLANE',
42
+ level: 'L3',
43
+ signal: 'hard',
44
+ mandatory_human_review: true,
45
+ patterns: [
46
+ /(^|\/)AGENTS\.md$/i,
47
+ /(^|\/)openspec\/config\.yaml$/i,
48
+ /(^|\/)(assets|\.agents)\/skills\/.*SKILL\.md$/i
49
+ ],
50
+ summary: 'Modifies core Agent governance constitution (AGENTS.md, openspec/config.yaml, or agent skills)'
51
+ },
52
+ // 2. High-Risk Security, Credentials & Cryptography (L3)
53
+ {
54
+ id: 'HARD_SECURITY_CREDENTIALS',
55
+ level: 'L3',
56
+ signal: 'hard',
57
+ mandatory_human_review: true,
58
+ patterns: [
59
+ /(^|\/)(auth|security|session|mfa|kms)\//i,
60
+ /\.(pem|key|cert|p12|jks)$/i,
61
+ /(^|\/)secrets?\.[a-z0-9]+$/i
62
+ ],
63
+ summary: 'Touches security, cryptographic keys, authentication, or secrets'
64
+ },
65
+ // 3. Financial, Billing & Ledgers (L3)
66
+ {
67
+ id: 'HARD_FINANCIAL_ASSETS',
68
+ level: 'L3',
69
+ signal: 'hard',
70
+ mandatory_human_review: true,
71
+ patterns: [
72
+ /(^|\/)(payment|billing|ledger|clearing|settlement|wallet)\//i
73
+ ],
74
+ summary: 'Touches core financial accounting, settlement, or payment ledger paths'
75
+ },
76
+ // 4. Destructive Database Operations (L3)
77
+ {
78
+ id: 'HARD_DESTRUCTIVE_DDL',
79
+ level: 'L3',
80
+ signal: 'hard',
81
+ mandatory_human_review: true,
82
+ patterns: [
83
+ /(^|\/)(db\/)?migrations?\/.*(drop|truncate|purge|destructive)/i,
84
+ /(^|\/)db\/migration\/.*(drop|truncate|purge|destructive)/i
85
+ ],
86
+ summary: 'Executes destructive, irreversible schema or data deletion operations'
87
+ },
88
+ // 5. Public API Contracts & Framework Handlers (L2 - Spec-First)
89
+ {
90
+ id: 'HARD_API_CONTRACT',
91
+ level: 'L2',
92
+ signal: 'hard',
93
+ mandatory_human_review: false,
94
+ patterns: [
95
+ // Schema & IDL definitions (excluding docs and tooling schemas)
96
+ /(^|\/)(protos?)\//i,
97
+ /(^|\/)(openapi|swagger)\.[a-z0-9]+$/i,
98
+ /\.(proto|graphql|gql|thrift|prisma)$/i,
99
+ // Spring Boot (Java / Kotlin)
100
+ /(^|\/).*(Controller|Resource|Endpoint|Api)\.(java|kt)$/i,
101
+ /(^|\/)(controllers?|endpoints?|resources?)\/.*\.(java|kt)$/i,
102
+ // FastAPI / Python web frameworks
103
+ /(^|\/)(routers?|endpoints?)\/.*\.py$/i,
104
+ /(^|\/).*(router|controller|endpoint).*\.py$/i,
105
+ /(^|\/)(app|api)\/(main|app)\.py$/i,
106
+ // Node.js / NestJS / Express / Next.js
107
+ /(^|\/).*\.controller\.(ts|js)$/i,
108
+ /(^|\/)(pages|app|server|src)\/api\/.*\.(ts|js|tsx|jsx)$/i,
109
+ /(^|\/)(routes?\/|.*routes?\.)(ts|js)$/i,
110
+ // Go web handlers (excluding utilities and non-API handlers)
111
+ /(^|\/)(handlers?|routers?|controllers?|api)\/(?!.*error_handler).*\.go$/i,
112
+ /^(?!.*[/\\](utils?|helpers?)[/\\]).*(?<!error)_(handler|router|controller)\.go$/i
113
+ ],
114
+ summary: 'Modifies public API contracts, controllers, routers, or schemas (Spring Boot, FastAPI, NestJS, Go, Proto, OpenAPI)'
115
+ },
116
+ // 6. CI/CD Workflows & Git Hooks (L1 Tooling / Routine Dev)
117
+ {
118
+ id: 'HARD_CI_TOOLING',
119
+ level: 'L1',
120
+ signal: 'hard',
121
+ mandatory_human_review: false,
122
+ patterns: [
123
+ /^\.github\/workflows\//i,
124
+ /(^|\/)Jenkinsfile$/i,
125
+ /(^|\/)\.githooks\//i,
126
+ /(^|\/)\.husky\//i,
127
+ /(^|\/)\.gitlab-ci\.ya?ml$/i
128
+ ],
129
+ summary: 'Modifies CI/CD pipeline workflows, Git hooks, or developer tooling'
130
+ },
131
+ // 7. Database Migrations & Data Models (L2)
132
+ {
133
+ id: 'HARD_DB_MIGRATION',
134
+ level: 'L2',
135
+ signal: 'hard',
136
+ mandatory_human_review: false,
137
+ patterns: [
138
+ /(^|\/)(db\/)?migrations?\//i,
139
+ /(^|\/)db\/(schema|models?)\//i,
140
+ /(^|\/)prisma\/schema\.prisma$/i
141
+ ],
142
+ summary: 'Modifies database migrations, tables, or persistence schemas'
143
+ },
144
+ // 7. Supply Chain & Build Manifests (L2)
145
+ {
146
+ id: 'HARD_SUPPLY_CHAIN',
147
+ level: 'L2',
148
+ signal: 'hard',
149
+ mandatory_human_review: false,
150
+ patterns: [
151
+ /(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock)$/i,
152
+ /(^|\/)(go\.mod|go\.sum|Cargo\.toml|Cargo\.lock|pom\.xml|build\.gradle)$/i,
153
+ /(^|\/)(Dockerfile.*|Containerfile.*|docker-compose.*)$/i,
154
+ /(^|\/)(helm|k8s|terraform)\//i
155
+ ],
156
+ summary: 'Touches dependency manifests, lockfiles, containers, or infra code'
157
+ }
158
+ ];
159
+
160
+ /**
161
+ * Deterministic Proof of L0 Trivial Change (§2.2):
162
+ * All files must match documentation or non-executable patterns.
163
+ * Never touches code, CI, configs, or agent files.
164
+ */
165
+ export const L0_DETERMINISTIC_PATTERNS = [
166
+ /^docs\//i,
167
+ /\.md$/i,
168
+ /\.txt$/i,
169
+ /^LICENSE$/i,
170
+ /^NOTICE$/i
171
+ ];
172
+
173
+ export const TEST_AND_DOC_PATTERNS = [
174
+ /(^|\/)(tests?|__tests__|testing)\//i,
175
+ /\.(test|spec)\.[a-z0-9]+$/i,
176
+ /_test\.go$/i,
177
+ /test_[^/]+\.py$/i,
178
+ /[^/]+_test\.py$/i,
179
+ /(^|\/)docs?\//i,
180
+ /\.(md|txt)$/i,
181
+ /(^|\/)assets\/(?:images|media|icons|fonts)\//i
182
+ ];
183
+
184
+ export function isTestOrDocFile(filePath = '') {
185
+ const norm = String(filePath).replace(/\\/g, '/');
186
+ if (
187
+ /(^|\/)AGENTS\.md$/i.test(norm) ||
188
+ /(^|\/)openspec\/config\.yaml$/i.test(norm) ||
189
+ /(^|\/)(assets|\.agents)\/skills\//i.test(norm)
190
+ ) {
191
+ return false;
192
+ }
193
+ return TEST_AND_DOC_PATTERNS.some((p) => p.test(norm));
194
+ }
195
+
@@ -0,0 +1,148 @@
1
+ import crypto from 'node:crypto';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { exists, readText } from '../lib/fs.js';
5
+
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+ const SCHEMA_PATH = path.resolve(__dirname, '../../assets/schema/risk-assessment.schema.json');
9
+
10
+ /**
11
+ * Canonicalize JSON according to RFC 8785 (JCS principles):
12
+ * Deterministic key sorting, compact representation, no extra whitespace.
13
+ */
14
+ export function canonicalJson(obj) {
15
+ if (obj === null || typeof obj !== 'object') {
16
+ return JSON.stringify(obj);
17
+ }
18
+ if (Array.isArray(obj)) {
19
+ return '[' + obj.map(canonicalJson).join(',') + ']';
20
+ }
21
+ const keys = Object.keys(obj).sort();
22
+ const pairs = keys.map((k) => JSON.stringify(k) + ':' + canonicalJson(obj[k]));
23
+ return '{' + pairs.join(',') + '}';
24
+ }
25
+
26
+ /**
27
+ * Computes sha256 hash of a record excluding the 'hash' field itself.
28
+ */
29
+ export function computeRecordHash(record) {
30
+ const clone = { ...record };
31
+ delete clone.hash;
32
+ const canonical = canonicalJson(clone);
33
+ return crypto.createHash('sha256').update(canonical, 'utf8').digest('hex');
34
+ }
35
+
36
+ /**
37
+ * Validates a single record against the JSON Schema principles.
38
+ * Returns { valid: boolean, errors: string[] }
39
+ */
40
+ export function validateRecordSchema(record) {
41
+ const errors = [];
42
+ if (!record || typeof record !== 'object') {
43
+ return { valid: false, errors: ['Record must be an object'] };
44
+ }
45
+
46
+ const requiredFields = [
47
+ 'schema_version', 'change_id', 'seq', 'prev_hash', 'hash',
48
+ 'timestamp', 'actor', 'stage', 'role', 'status', 'verdict',
49
+ 'change_type', 'source', 'risk', 'vectors', 'governance',
50
+ 'reason_codes', 'transition'
51
+ ];
52
+
53
+ for (const f of requiredFields) {
54
+ if (record[f] === undefined) {
55
+ errors.push(`Missing required field: ${f}`);
56
+ }
57
+ }
58
+
59
+ if (record.schema_version !== 1) {
60
+ errors.push(`schema_version must be 1, got ${record.schema_version}`);
61
+ }
62
+
63
+ const validLevels = ['L0', 'L1', 'L2', 'L3'];
64
+ if (record.risk && !validLevels.includes(record.risk.level)) {
65
+ errors.push(`Invalid risk level: ${record.risk.level}`);
66
+ }
67
+
68
+ const validTypes = ['chore', 'fix', 'change', 'feature'];
69
+ if (!validTypes.includes(record.change_type)) {
70
+ errors.push(`Invalid change_type: ${record.change_type}`);
71
+ }
72
+
73
+ const validStages = ['new', 'spec', 'impl'];
74
+ if (!validStages.includes(record.stage)) {
75
+ errors.push(`Invalid stage: ${record.stage}`);
76
+ }
77
+
78
+ const validStatuses = ['provisional', 'needs_input', 'ready', 'defaulted'];
79
+ if (!validStatuses.includes(record.status)) {
80
+ errors.push(`Invalid status: ${record.status}`);
81
+ }
82
+
83
+ if (record.status === 'defaulted' && !record.defaulted_cause) {
84
+ errors.push('status defaulted requires non-null defaulted_cause');
85
+ }
86
+
87
+ if (record.hash && computeRecordHash(record) !== record.hash) {
88
+ errors.push(`Hash mismatch: computed ${computeRecordHash(record)} vs declared ${record.hash}`);
89
+ }
90
+
91
+ return {
92
+ valid: errors.length === 0,
93
+ errors
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Validates a sequence of historical records (Cross-Record Invariants §8.3):
99
+ * 1. seq is continuous starting from 1
100
+ * 2. prev_hash equals previous record's hash (first record is null)
101
+ * 3. Level only increases (monotonic) unless waiver or recovered_from_default
102
+ */
103
+ export function validateChainInvariants(records = []) {
104
+ const errors = [];
105
+ if (!Array.isArray(records) || records.length === 0) {
106
+ return { valid: false, errors: ['History is empty'] };
107
+ }
108
+
109
+ const rank = { L0: 0, L1: 1, L2: 2, L3: 3 };
110
+
111
+ for (let i = 0; i < records.length; i++) {
112
+ const rec = records[i];
113
+ const expectedSeq = i + 1;
114
+ if (rec.seq !== expectedSeq) {
115
+ errors.push(`Record at index ${i} has seq ${rec.seq}, expected ${expectedSeq}`);
116
+ }
117
+
118
+ // Cryptographic content hash integrity (P1-3)
119
+ const computed = computeRecordHash(rec);
120
+ if (rec.hash && computed !== rec.hash) {
121
+ errors.push(`Record ${rec.seq} hash mismatch: computed ${computed} vs declared ${rec.hash}`);
122
+ }
123
+
124
+ if (i === 0) {
125
+ if (rec.prev_hash !== null) {
126
+ errors.push(`Initial record must have prev_hash: null, got ${rec.prev_hash}`);
127
+ }
128
+ } else {
129
+ const prev = records[i - 1];
130
+ if (rec.prev_hash !== prev.hash) {
131
+ errors.push(`Record ${rec.seq} prev_hash (${rec.prev_hash}) does not match previous hash (${prev.hash})`);
132
+ }
133
+
134
+ const prevRank = rank[prev.risk.level] ?? 1;
135
+ const curRank = rank[rec.risk.level] ?? 1;
136
+ const allowedDemote = Boolean(rec.transition?.waiver || rec.transition?.recovered_from_default);
137
+
138
+ if (curRank < prevRank && !allowedDemote) {
139
+ errors.push(`Illegal demotion from ${prev.risk.level} to ${rec.risk.level} without waiver or default recovery`);
140
+ }
141
+ }
142
+ }
143
+
144
+ return {
145
+ valid: errors.length === 0,
146
+ errors
147
+ };
148
+ }
@@ -0,0 +1,138 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import YAML from 'yaml';
4
+ import { exists, readText, writeText, ensureDir } from '../lib/fs.js';
5
+ import { changeDir } from '../lib/paths.js';
6
+ import { computeRecordHash, validateRecordSchema, validateChainInvariants } from './schema.js';
7
+
8
+ export const HISTORY_FILE = 'risk-history.jsonl';
9
+ export const SNAPSHOT_FILE = 'risk-assessment.yaml';
10
+
11
+ /**
12
+ * Loads all historical assessment records for a change.
13
+ * Enforces fail-closed chain validation on read (P1-3).
14
+ */
15
+ export function loadRiskHistory(repoRoot, changeId) {
16
+ if (!repoRoot || !changeId) return [];
17
+ const cdir = changeDir(repoRoot, changeId);
18
+ const p = path.join(cdir, HISTORY_FILE);
19
+ if (!exists(p)) return [];
20
+
21
+ const lines = readText(p).split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
22
+ const records = [];
23
+ for (const line of lines) {
24
+ try {
25
+ records.push(JSON.parse(line));
26
+ } catch {
27
+ const err = new Error(`Corrupted JSON in risk history line for ${changeId}`);
28
+ err.code = 'TAMPER_DETECTED';
29
+ throw err;
30
+ }
31
+ }
32
+
33
+ if (records.length > 0) {
34
+ const chainCheck = validateChainInvariants(records);
35
+ if (!chainCheck.valid) {
36
+ const err = new Error(`Risk history tamper detected for ${changeId}: ${chainCheck.errors.join('; ')}`);
37
+ err.code = 'TAMPER_DETECTED';
38
+ throw err;
39
+ }
40
+ }
41
+
42
+ return records;
43
+ }
44
+
45
+ /**
46
+ * Loads the latest assessment record for a change.
47
+ */
48
+ export function loadLatestAssessment(repoRoot, changeId) {
49
+ const history = loadRiskHistory(repoRoot, changeId);
50
+ return history.length > 0 ? history[history.length - 1] : null;
51
+ }
52
+
53
+ /**
54
+ * Loads the initial baseline assessment record for a change (seq: 1).
55
+ */
56
+ export function loadInitialAssessment(repoRoot, changeId) {
57
+ const history = loadRiskHistory(repoRoot, changeId);
58
+ return history.length > 0 ? history[0] : null;
59
+ }
60
+
61
+ /**
62
+ * Loads the maximum risk level recorded in history.
63
+ */
64
+ export function loadMaxHistoryLevel(repoRoot, changeId) {
65
+ const history = loadRiskHistory(repoRoot, changeId);
66
+ if (history.length === 0) return null;
67
+ const rank = { L0: 0, L1: 1, L2: 2, L3: 3 };
68
+ let maxLvl = history[0].risk?.level || 'L1';
69
+ for (const h of history) {
70
+ const lvl = h.risk?.level;
71
+ if (lvl && (rank[lvl] ?? 1) > (rank[maxLvl] ?? 1)) {
72
+ maxLvl = lvl;
73
+ }
74
+ }
75
+ return maxLvl;
76
+ }
77
+
78
+ /**
79
+ * Appends an assessment record to risk-history.jsonl and overwrites risk-assessment.yaml snapshot.
80
+ */
81
+ export function appendAssessmentRecord(repoRoot, changeId, recordData) {
82
+ const cdir = changeDir(repoRoot, changeId);
83
+ ensureDir(cdir);
84
+
85
+ const history = loadRiskHistory(repoRoot, changeId);
86
+
87
+ // Deduplicate consecutive identical stage evaluations to prevent log bloat
88
+ if (history.length > 0) {
89
+ const prev = history[history.length - 1];
90
+ if (
91
+ prev.stage === recordData.stage &&
92
+ prev.risk?.level === recordData.risk?.level &&
93
+ prev.verdict === recordData.verdict &&
94
+ JSON.stringify(prev.reason_codes || []) === JSON.stringify(recordData.reason_codes || [])
95
+ ) {
96
+ return prev;
97
+ }
98
+ }
99
+
100
+ const seq = history.length + 1;
101
+ const prev_hash = history.length > 0 ? history[history.length - 1].hash : null;
102
+
103
+ const record = {
104
+ schema_version: 1,
105
+ change_id: changeId,
106
+ seq,
107
+ prev_hash,
108
+ ...recordData
109
+ };
110
+
111
+ // Compute immutable sha256 hash
112
+ record.hash = computeRecordHash(record);
113
+
114
+ // Validate single record schema
115
+ const schemaCheck = validateRecordSchema(record);
116
+ if (!schemaCheck.valid) {
117
+ throw new Error(`Schema validation failed: ${schemaCheck.errors.join('; ')}`);
118
+ }
119
+
120
+ // Validate chain invariant
121
+ const newChain = [...history, record];
122
+ const chainCheck = validateChainInvariants(newChain);
123
+ if (!chainCheck.valid) {
124
+ throw new Error(`Chain invariant validation failed: ${chainCheck.errors.join('; ')}`);
125
+ }
126
+
127
+ // 1. Append to JSONL history atomically (P2-3)
128
+ const histPath = path.join(cdir, HISTORY_FILE);
129
+ const line = JSON.stringify(record) + '\n';
130
+ fs.appendFileSync(histPath, line, 'utf8');
131
+
132
+ // 2. Overwrite human-readable YAML snapshot
133
+ const snapPath = path.join(cdir, SNAPSHOT_FILE);
134
+ const yamlText = `# ASdlc Latest Risk Assessment Snapshot\n# Generated at: ${record.timestamp}\n# Change: ${changeId} (seq: ${record.seq})\n\n` + YAML.stringify(record);
135
+ writeText(snapPath, yamlText);
136
+
137
+ return record;
138
+ }
@@ -0,0 +1,80 @@
1
+ import { LEVEL_RANK, CANONICAL_DESTRUCTIVE_PATTERN } from '../rules/builtin.js';
2
+ import { judgeChangeSemantics } from '../ai_judge.js';
3
+
4
+ export function evaluateV1Intent({ requirement = '', specDelta = '', changedFiles = [], changeType = null } = {}) {
5
+ const req = String(requirement || '').toLowerCase();
6
+ const evidence = [];
7
+ const unresolved = [];
8
+ let level = 'L1';
9
+ let confidence = 'high';
10
+ let mandatory_human_review = false;
11
+ let no_signal = false;
12
+
13
+ // Infer Change Type if not provided
14
+ let inferredType = changeType;
15
+ if (!inferredType) {
16
+ if (/\b(doc|docs|readme|typo|format|clean|ci|workflow|action|hook|dependency|upgrade|refactor)\b/i.test(req)) {
17
+ inferredType = 'chore';
18
+ } else if (/\b(fix|bug|defect|issue|error|patch|resolve)\b/i.test(req)) {
19
+ inferredType = 'fix';
20
+ } else if (/\b(add|new|feature|capability|create)\b/i.test(req)) {
21
+ inferredType = 'feature';
22
+ } else {
23
+ inferredType = 'change';
24
+ }
25
+ }
26
+
27
+ // 1. Destructive Operations & Irreversibility (P0-1)
28
+ if (CANONICAL_DESTRUCTIVE_PATTERN.test(req)) {
29
+ level = 'L3';
30
+ mandatory_human_review = true;
31
+ evidence.push({
32
+ id: 'V1_DESTRUCTIVE_INTENT',
33
+ kind: 'task_statement',
34
+ signal: 'hard',
35
+ summary: 'Task intent indicates irreversible data destruction or purge'
36
+ });
37
+ }
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 });
43
+ if (aiJudgment.is_pure_test) {
44
+ level = 'L0';
45
+ inferredType = 'chore';
46
+ evidence.push({
47
+ id: 'V1_AI_TEST_EVALUATION',
48
+ kind: 'scanner_result',
49
+ signal: 'soft',
50
+ summary: aiJudgment.rationale || 'AI Semantic Evaluation: Change is strictly test suites/mocks (evaluated as L0 trivial/routine)'
51
+ });
52
+ } else if (aiJudgment.is_pure_doc) {
53
+ level = 'L0';
54
+ inferredType = 'chore';
55
+ evidence.push({
56
+ id: 'V1_AI_DOC_EVALUATION',
57
+ kind: 'scanner_result',
58
+ signal: 'soft',
59
+ summary: aiJudgment.rationale || 'AI Semantic Evaluation: Intent is purely documentation, typo, or comment editing'
60
+ });
61
+ }
62
+ }
63
+
64
+ // If empty input
65
+ if (!req.trim() && changedFiles.length === 0) {
66
+ no_signal = true;
67
+ confidence = 'low';
68
+ unresolved.push('Requirement text is empty or missing');
69
+ }
70
+
71
+ return {
72
+ level,
73
+ confidence,
74
+ inferredType,
75
+ evidence,
76
+ unresolved,
77
+ mandatory_human_review,
78
+ no_signal
79
+ };
80
+ }
@@ -0,0 +1,131 @@
1
+ import path from 'node:path';
2
+ import { exists, readText } from '../../lib/fs.js';
3
+ import { HARD_RULES, isTestOrDocFile, CANONICAL_DESTRUCTIVE_PATTERN } from '../rules/builtin.js';
4
+ import { judgeChangeSemantics } from '../ai_judge.js';
5
+
6
+ export function evaluateV2Security({ requirement = '', changedFiles = [], repoRoot = null } = {}) {
7
+ const req = String(requirement || '').toLowerCase();
8
+ const evidence = [];
9
+ const unresolved = [];
10
+ let level = 'L1';
11
+ let confidence = 'high';
12
+ let mandatory_human_review = false;
13
+ let no_signal = true;
14
+
15
+ // 1. Check Hard Rules against physical files
16
+ const securityRules = HARD_RULES.filter((r) =>
17
+ ['HARD_GOV_PLANE', 'HARD_SECURITY_CREDENTIALS', 'HARD_FINANCIAL_ASSETS', 'HARD_DESTRUCTIVE_DDL'].includes(r.id)
18
+ );
19
+
20
+ for (const rule of securityRules) {
21
+ const hits = changedFiles.filter((f) => {
22
+ // Exclude test and documentation files from security/credentials (never exclude governance plane or destructive DDL) (P1-4)
23
+ if (rule.id !== 'HARD_GOV_PLANE' && rule.id !== 'HARD_DESTRUCTIVE_DDL' && isTestOrDocFile(f)) return false;
24
+ const norm = f.replace(/\\/g, '/');
25
+ if (rule.patterns.some((p) => p.test(norm))) return true;
26
+ // Content-level or name-level DDL check for SQL files (P1-2)
27
+ if (rule.id === 'HARD_DESTRUCTIVE_DDL' && /\.(sql)$/i.test(norm)) {
28
+ if (/drop|truncate|purge|destructive/i.test(norm)) return true;
29
+ if (repoRoot) {
30
+ const fullPath = path.isAbsolute(f) ? f : path.join(repoRoot, f);
31
+ if (exists(fullPath)) {
32
+ const sqlContent = readText(fullPath);
33
+ if (CANONICAL_DESTRUCTIVE_PATTERN.test(sqlContent)) return true;
34
+ }
35
+ }
36
+ }
37
+ return false;
38
+ });
39
+
40
+ if (hits.length > 0) {
41
+ level = 'L3';
42
+ no_signal = false;
43
+ mandatory_human_review = rule.mandatory_human_review;
44
+ evidence.push({
45
+ id: `V2_${rule.id}`,
46
+ kind: 'rule_hit',
47
+ rule_id: rule.id,
48
+ signal: 'hard',
49
+ summary: `${rule.summary} (${hits.slice(0, 3).join(', ')})`,
50
+ source: hits[0]
51
+ });
52
+ }
53
+ }
54
+
55
+ // 2. Check Requirement Semantics for Security/Financial/Regulatory
56
+ const highRiskCompounds = [
57
+ 'access token', 'refresh token', 'bearer token', 'session token', 'auth token', 'security token',
58
+ 'jwt', 'oauth', 'private key', 'secret key', 'password hash', 'password encryption',
59
+ 'mfa', 'rbac', 'kms', 'pii', 'gdpr', 'tax id', 'ssn', 'payment refund', 'payment ledger',
60
+ 'refund ledger', 'clearing settlement', 'credit card'
61
+ ];
62
+
63
+ const genericSecWords = [
64
+ 'auth', 'authentication', 'password', 'credential', 'crypto',
65
+ 'payment', 'payout', 'refund', 'billing', 'ledger', 'wallet', 'clearing'
66
+ ];
67
+
68
+ let compoundHit = null;
69
+ for (const compound of highRiskCompounds) {
70
+ const re = new RegExp(`\\b${compound.replace(/-/g, '[-\\s]')}\\b`, 'i');
71
+ if (re.test(req)) {
72
+ compoundHit = compound;
73
+ break;
74
+ }
75
+ }
76
+
77
+ const matchedGenerics = [];
78
+ for (const word of genericSecWords) {
79
+ const re = new RegExp(`\\b${word}\\b`, 'i');
80
+ if (re.test(req)) {
81
+ matchedGenerics.push(word);
82
+ }
83
+ }
84
+
85
+ const aiJudgment = judgeChangeSemantics({ requirement: req, changedFiles });
86
+ const isDocOrTest = aiJudgment.is_pure_test || aiJudgment.is_pure_doc;
87
+
88
+ if (!isDocOrTest) {
89
+ if (compoundHit) {
90
+ no_signal = false;
91
+ level = 'L3';
92
+ mandatory_human_review = true;
93
+ evidence.push({
94
+ id: 'V2_SECURITY_COMPOUND_KEYWORD',
95
+ kind: 'task_statement',
96
+ signal: 'hard',
97
+ summary: `Task requirement touches critical security/regulatory compound phrase: '${compoundHit}'`
98
+ });
99
+ } else if (matchedGenerics.length >= 2) {
100
+ no_signal = false;
101
+ level = 'L3';
102
+ mandatory_human_review = true;
103
+ evidence.push({
104
+ id: 'V2_SECURITY_MULTI_KEYWORD',
105
+ kind: 'task_statement',
106
+ signal: 'soft',
107
+ summary: `Task requirement touches multiple security/financial domains: '${matchedGenerics.join(', ')}'`
108
+ });
109
+ } else if (matchedGenerics.length === 1) {
110
+ no_signal = false;
111
+ if (level === 'L1') {
112
+ level = 'L2'; // Capped at L2 for single soft generic keyword
113
+ }
114
+ evidence.push({
115
+ id: 'V2_SECURITY_SINGLE_KEYWORD',
116
+ kind: 'task_statement',
117
+ signal: 'soft',
118
+ summary: `Task requirement touches security/financial domain keyword: '${matchedGenerics[0]}'`
119
+ });
120
+ }
121
+ }
122
+
123
+ return {
124
+ level,
125
+ confidence,
126
+ evidence,
127
+ unresolved,
128
+ mandatory_human_review,
129
+ no_signal
130
+ };
131
+ }