@akjamie/agentic-sdlc 1.6.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,369 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { isTestOrDocFile } from './rules/builtin.js';
4
+ import { getBatchGitFiles } from '../lib/git.js';
5
+
6
+ /**
7
+ * Checks whether a file is an auto-generated asset by inspecting standard path conventions
8
+ * and header comments. Requires matching standard generated file paths or historical presence in baseRef
9
+ * to prevent gaming/bypass on arbitrary source files.
10
+ */
11
+ export function isGeneratedFile(filePath, content, oldContent = null) {
12
+ if (content === undefined && typeof filePath === 'string') {
13
+ content = filePath;
14
+ filePath = '';
15
+ }
16
+ if (!content && !oldContent) return false;
17
+ const norm = String(filePath || '').replace(/\\/g, '/');
18
+
19
+ const checkMarker = (text) => {
20
+ if (!text || typeof text !== 'string') return false;
21
+ const lines = text.slice(0, 2048).split('\n', 15);
22
+ const pattern = /(?:\/\/|#|\/\*)\s*(?:code generated|generated by|autogenerated|auto-generated).*?(?:do not edit|never edit)/i;
23
+ return lines.some((l) => pattern.test(l));
24
+ };
25
+
26
+ const hasMarker = checkMarker(content);
27
+ const hadMarkerInBase = checkMarker(oldContent);
28
+
29
+ // Path convention check: prevent gaming where developer puts marker in arbitrary source file
30
+ const matchesGeneratedPath = /(?:\.pb\.go$|_gen\.go$|\.generated\.[a-z0-9]+$|\/(?:generated|autogen|gen|dist|build)\/)/i.test(norm);
31
+
32
+ // Only allow exclusion if it matches generated path conventions OR was already generated in base
33
+ return (matchesGeneratedPath && hasMarker) || hadMarkerInBase;
34
+ }
35
+
36
+ /**
37
+ * Scans third-party framework imports / using directives (Layer 1).
38
+ */
39
+ export function scanImports(filePath, content) {
40
+ if (!content || typeof content !== 'string') return null;
41
+ const norm = filePath.replace(/\\/g, '/');
42
+ const ext = path.extname(norm).toLowerCase();
43
+
44
+ // 1. Java / Kotlin
45
+ if (['.java', '.kt'].includes(ext)) {
46
+ // Security (L3)
47
+ const javaSecRegex = /\bimport\s+(?:org\.springframework\.security|cn\.dev33\.satoken|org\.apache\.shiro|io\.jsonwebtoken|com\.auth0\.jwt|io\.quarkus\.security|io\.quarkus\.vertx\.http\.runtime\.security|io\.smallrye\.jwt|io\.ktor\.server\.auth)\b/;
48
+ const javaFilterRegex = /\b(?:extends\s+OncePerRequestFilter|implements\s+(?:HandlerInterceptor|GlobalFilter|HttpAuthenticationMechanism))\b/;
49
+ if (javaSecRegex.test(content) || javaFilterRegex.test(content)) {
50
+ return { level: 'L3', id: 'SEM_JAVA_SECURITY', summary: `Java/Kotlin security framework import/filter in ${norm}`, mandatoryHumanReview: true };
51
+ }
52
+
53
+ // Server Contract / RPC / Messaging (L2)
54
+ const javaContractRegex = /\bimport\s+(?:org\.apache\.dubbo|com\.alibaba\.dubbo|org\.apache\.rocketmq|com\.aliyun\.openservices\.ons|org\.springframework\.cloud\.openfeign|org\.springframework\.kafka|org\.springframework\.amqp|jakarta\.jms|jakarta\.ws\.rs|javax\.ws\.rs|io\.quarkus\.vertx\.web|io\.ktor\.server\.routing|com\.alibaba\.csp\.sentinel|io\.seata)\b/;
55
+ const javaAnnotationRegex = /@(?:DubboService|DubboReference|FeignClient|RestController|RequestMapping|GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|Path)\b/;
56
+ if (javaContractRegex.test(content) || javaAnnotationRegex.test(content)) {
57
+ return { level: 'L2', id: 'SEM_JAVA_CONTRACT', summary: `Java/Kotlin server RPC/endpoint contract in ${norm}` };
58
+ }
59
+
60
+ // Persistence / Entity (L2)
61
+ const javaDbRegex = /\bimport\s+(?:jakarta\.persistence|javax\.persistence|org\.jetbrains\.exposed\.sql|io\.quarkus\.hibernate\.orm\.panache)\b/;
62
+ if (javaDbRegex.test(content) || /@(?:Entity|Table|TableName)\b/.test(content)) {
63
+ return { level: 'L2', id: 'SEM_JAVA_PERSISTENCE', summary: `Java/Kotlin DB persistence entity in ${norm}` };
64
+ }
65
+ }
66
+
67
+ // 2. Go
68
+ if (ext === '.go') {
69
+ // Security (L3)
70
+ const goSecRegex = /"(?:github\.com\/golang-jwt\/jwt(?:\/v\d+)?|github\.com\/casbin\/casbin(?:\/v\d+)?|golang\.org\/x\/oauth2|github\.com\/coreos\/go-oidc|golang\.org\/x\/crypto)\b/;
71
+ if (goSecRegex.test(content)) {
72
+ return { level: 'L3', id: 'SEM_GO_SECURITY', summary: `Go security/auth package import in ${norm}`, mandatoryHumanReview: true };
73
+ }
74
+
75
+ // Server Contract (L2)
76
+ const goContractRegex = /"(?:github\.com\/gin-gonic\/gin|github\.com\/labstack\/echo(?:\/v\d+)?|github\.com\/go-chi\/chi(?:\/v\d+)?|github\.com\/gofiber\/fiber(?:\/v\d+)?|github\.com\/cloudwego\/hertz|github\.com\/go-kratos\/kratos(?:\/v\d+)?|google\.golang\.org\/grpc|github\.com\/cloudwego\/kitex)\b/;
77
+ if (goContractRegex.test(content) || /\b(?:http\.HandleFunc|http\.NewServeMux)\b/.test(content)) {
78
+ return { level: 'L2', id: 'SEM_GO_CONTRACT', summary: `Go server HTTP/gRPC routing in ${norm}` };
79
+ }
80
+
81
+ // DB Migration (L2)
82
+ const goDbRegex = /"(?:github\.com\/golang-migrate\/migrate(?:\/v\d+)?|github\.com\/pressly\/goose(?:\/v\d+)?|entgo\.io\/ent)\b/;
83
+ if (goDbRegex.test(content) || /\bAutoMigrate\s*\(/.test(content)) {
84
+ return { level: 'L2', id: 'SEM_GO_MIGRATION', summary: `Go database migration/schema in ${norm}` };
85
+ }
86
+ }
87
+
88
+ // 3. Python
89
+ if (ext === '.py') {
90
+ // Security (L3)
91
+ const pySecRegex = /\b(?:from\s+fastapi\.security\b|import\s+fastapi\.security\b|from\s+jose\b|import\s+jose\b|from\s+passlib\b|import\s+passlib\b|from\s+authlib\b|import\s+authlib\b|from\s+django\.contrib\.auth\b|from\s+rest_framework\.permissions\b|from\s+flask_login\b|import\s+bcrypt\b|import\s+jwt\b)/;
92
+ if (pySecRegex.test(content)) {
93
+ return { level: 'L3', id: 'SEM_PY_SECURITY', summary: `Python security framework import in ${norm}`, mandatoryHumanReview: true };
94
+ }
95
+
96
+ // Alembic / Django migrations
97
+ const pyMigrateRegex = /\b(?:from\s+alembic\s+import\s+op|from\s+django\.db\s+import\s+migrations)\b/;
98
+ if (pyMigrateRegex.test(content)) {
99
+ const isDestructive = /(?:op\.drop_|DeleteModel|RemoveField)/.test(content);
100
+ if (isDestructive) {
101
+ return { level: 'L3', id: 'SEM_PY_DESTRUCTIVE_MIGRATION', summary: `Python destructive database migration in ${norm}`, mandatoryHumanReview: true };
102
+ }
103
+ return { level: 'L2', id: 'SEM_PY_MIGRATION', summary: `Python database migration in ${norm}` };
104
+ }
105
+
106
+ // Server Contract (L2)
107
+ const pyContractRegex = /\b(?:from\s+django\.urls\b|from\s+rest_framework\b.*import\s+(?:APIView|ViewSet|Serializer)|from\s+airflow\b|from\s+celery\b)/;
108
+ const hasFastApiFlask = /\b(?:import\s+(?:fastapi|flask)|from\s+(?:fastapi|flask)\b)/.test(content) &&
109
+ /@\w+\.(?:route|get|post|put|delete|patch)\s*\(/.test(content);
110
+ if (pyContractRegex.test(content) || hasFastApiFlask) {
111
+ return { level: 'L2', id: 'SEM_PY_CONTRACT', summary: `Python server routing/contract in ${norm}` };
112
+ }
113
+ }
114
+
115
+ // 4. Node.js / TypeScript
116
+ if (['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs'].includes(ext)) {
117
+ // Security (L3) - Next.js root or src/ middleware
118
+ if (/^(?:src\/)?middleware\.(?:ts|js)$/i.test(norm)) {
119
+ return { level: 'L3', id: 'SEM_NODE_MIDDLEWARE', summary: `Next.js root middleware in ${norm}`, mandatoryHumanReview: true };
120
+ }
121
+ const nodeSecRegex = /\b(?:from\s+['"](?:passport|@nestjs\/passport|@nestjs\/jwt|jose|jsonwebtoken|next-auth|@auth\/core|better-auth|bcrypt|argon2)['"]|require\(['"](?:passport|@nestjs\/passport|@nestjs\/jwt|jose|jsonwebtoken|next-auth|@auth\/core|better-auth|bcrypt|argon2)['"]\))/;
122
+ if (nodeSecRegex.test(content)) {
123
+ return { level: 'L3', id: 'SEM_NODE_SECURITY', summary: `Node.js security package import in ${norm}`, mandatoryHumanReview: true };
124
+ }
125
+
126
+ // Server Contract (L2)
127
+ const nodeContractRegex = /\b(?:from\s+['"](?:express|fastify|koa|hono|@trpc\/server|@apollo\/server|@nestjs\/graphql|graphql-yoga)['"]|require\(['"](?:express|fastify|koa|hono|@trpc\/server|@apollo\/server|@nestjs\/graphql|graphql-yoga)['"]\))/;
128
+ const isNestController = /@(?:Controller|Resolver)\b/.test(content) && /@nestjs\/common/.test(content);
129
+ const isServerAction = /^\s*['"]use server['"]/m.test(content);
130
+ if (nodeContractRegex.test(content) || isNestController || isServerAction) {
131
+ return { level: 'L2', id: 'SEM_NODE_CONTRACT', summary: `Node.js server routing/actions in ${norm}` };
132
+ }
133
+
134
+ // DB Schema / Client (L2)
135
+ const nodeDbRegex = /\b(?:from\s+['"](?:drizzle-orm\/(?:pg-core|mysql-core|sqlite-core)|@prisma\/client)['"]|require\(['"]@prisma\/client['"]\))/;
136
+ if (nodeDbRegex.test(content)) {
137
+ return { level: 'L2', id: 'SEM_NODE_PERSISTENCE', summary: `Node.js DB schema/client in ${norm}` };
138
+ }
139
+ }
140
+
141
+ return null;
142
+ }
143
+
144
+ /**
145
+ * Scans file content schema headers, config keys, and SQL DDL syntax (Layer 2).
146
+ */
147
+ export function scanSchemaHeaders(filePath, content, { allChangedFiles = [] } = {}) {
148
+ if (!content || typeof content !== 'string') return null;
149
+ const norm = filePath.replace(/\\/g, '/');
150
+ const base = path.basename(norm);
151
+ const ext = path.extname(norm).toLowerCase();
152
+
153
+ // 1. SQL DDL and Migration scripts
154
+ if (ext === '.sql') {
155
+ const hasDdl = /\b(?:CREATE\s+(?:TABLE|INDEX|VIEW)|ALTER\s+TABLE)\b/i.test(content);
156
+ const hasDestructive = /\b(?:DROP\s+(?:TABLE|DATABASE)|TRUNCATE)\b/i.test(content);
157
+
158
+ if (hasDestructive) {
159
+ // Check paired down.sql with up.sql in the same PR
160
+ const isDownSql = /\.down\.sql$/i.test(base);
161
+ const counterpartUp = base.replace(/\.down\.sql$/i, '.up.sql');
162
+ const hasPairedUp = isDownSql && allChangedFiles.some((f) => f.endsWith(counterpartUp));
163
+
164
+ if (hasPairedUp) {
165
+ return { level: 'L2', id: 'SEM_SQL_PAIRED_DOWN', summary: `Paired migration rollback script ${base}` };
166
+ }
167
+ return { level: 'L3', id: 'SEM_SQL_DESTRUCTIVE_DDL', summary: `Destructive SQL statement (DROP/TRUNCATE) in ${norm}`, mandatoryHumanReview: true };
168
+ }
169
+
170
+ if (hasDdl) {
171
+ return { level: 'L2', id: 'SEM_SQL_DDL', summary: `SQL DDL migration statement in ${norm}` };
172
+ }
173
+ }
174
+
175
+ // 2. Liquibase
176
+ if (ext === '.xml' || ['.yml', '.yaml'].includes(ext)) {
177
+ if (/databaseChangeLog/i.test(content)) {
178
+ return { level: 'L2', id: 'SEM_LIQUIBASE', summary: `Liquibase database change log in ${norm}` };
179
+ }
180
+ }
181
+
182
+ // 3. MyBatis XML
183
+ if (ext === '.xml' && (/<mapper\s+namespace=/i.test(content) || /<!DOCTYPE\s+mapper/i.test(content))) {
184
+ const hasWriteOrDdl = /<(?:insert|update|delete)\b/i.test(content) || /\b(?:CREATE|ALTER|DROP|TRUNCATE)\b/i.test(content);
185
+ if (hasWriteOrDdl) {
186
+ return { level: 'L2', id: 'SEM_MYBATIS_WRITE', summary: `MyBatis XML write/DDL mapping in ${norm}` };
187
+ }
188
+ // Pure select queries stay L1 routine
189
+ return { level: 'L1', id: 'SEM_MYBATIS_SELECT', summary: `MyBatis XML pure select query in ${norm}` };
190
+ }
191
+
192
+ // 4. Cloud / K8s / Serverless / IaC
193
+ if (base.toLowerCase() === 'chart.yaml' || base.toLowerCase() === 'chart.yml') {
194
+ return { level: 'L2', id: 'SEM_HELM_CHART', summary: `Helm chart definition in ${norm}` };
195
+ }
196
+ if (ext === '.tf') {
197
+ return { level: 'L2', id: 'SEM_TERRAFORM', summary: `Terraform infrastructure definition in ${norm}` };
198
+ }
199
+ if (['.yaml', '.yml'].includes(ext)) {
200
+ if (/\bapiVersion:\s*[^\r\n]+/i.test(content) && /^[ \t]*kind:\s*(?:Deployment|StatefulSet|DaemonSet|Ingress|Role|ClusterRole|RoleBinding|Secret|Service)\b/m.test(content)) {
201
+ return { level: 'L2', id: 'SEM_K8S_MANIFEST', summary: `Kubernetes workload/service manifest in ${norm}` };
202
+ }
203
+ if (/^[ \t]*edition:\s*[^\r\n]+/m.test(content) && /^[ \t]*services:\s*$/m.test(content)) {
204
+ return { level: 'L2', id: 'SEM_SERVERLESS_DEVS', summary: `Serverless Devs application manifest in ${norm}` };
205
+ }
206
+ if (/openapi:\s*['"]?3\.|swagger:\s*['"]?2\./i.test(content)) {
207
+ return { level: 'L2', id: 'SEM_OPENAPI_SPEC', summary: `OpenAPI specification document in ${norm}` };
208
+ }
209
+ }
210
+
211
+ // 5. Prisma Database Schema
212
+ if (ext === '.prisma') {
213
+ return { level: 'L2', id: 'SEM_PRISMA_SCHEMA', summary: `Prisma database schema definition in ${norm}` };
214
+ }
215
+
216
+ // 6. Core Configuration Keys
217
+ if (['.properties', '.yaml', '.yml', '.json', '.toml'].includes(ext)) {
218
+ // High-risk security config (L3)
219
+ if (/(?:quarkus\.oidc\.|server\.ssl\.|spring\.security\.)/i.test(content)) {
220
+ return { level: 'L3', id: 'SEM_CONFIG_SECURITY', summary: `Core security configuration keys in ${norm}`, mandatoryHumanReview: true };
221
+ }
222
+ // Architecture / Datasource config (L2)
223
+ if (/(?:spring\.datasource\.|spring\.cloud\.nacos\.|dubbo\.|seata\.|quarkus\.datasource\.)/i.test(content)) {
224
+ return { level: 'L2', id: 'SEM_CONFIG_ARCH', summary: `Core architectural datasource/registry config in ${norm}` };
225
+ }
226
+ }
227
+
228
+ return null;
229
+ }
230
+
231
+ /**
232
+ * Scans standard build manifests and supply chain configuration (Layer 3).
233
+ */
234
+ export function scanToolchainManifests(filePath, content) {
235
+ const norm = filePath.replace(/\\/g, '/');
236
+ const base = path.basename(norm).toLowerCase();
237
+
238
+ // Cloud pipeline
239
+ if (/\.workflow\/.*\.ya?ml$/i.test(norm)) {
240
+ return { level: 'L3', id: 'SEM_WORKFLOW_CI', summary: `CI workflow pipeline in ${norm}`, mandatoryHumanReview: true };
241
+ }
242
+
243
+ // Standard build tools
244
+ const buildManifests = [
245
+ 'pom.xml', 'build.gradle', 'build.gradle.kts', 'settings.gradle', 'settings.gradle.kts',
246
+ 'libs.versions.toml', 'go.mod', 'go.work', 'pyproject.toml', 'cmakelists.txt'
247
+ ];
248
+ if (buildManifests.includes(base) || base.startsWith('requirements') && base.endsWith('.txt') || base.endsWith('.csproj') || base.endsWith('.proto')) {
249
+ return { level: 'L2', id: 'SEM_BUILD_MANIFEST', summary: `Standard build toolchain manifest ${base}` };
250
+ }
251
+
252
+ // package.json supply chain vs metadata
253
+ if (base === 'package.json' && content) {
254
+ try {
255
+ const parsed = JSON.parse(content);
256
+ // If substantive keys are present (dependencies or scripts)
257
+ if (parsed.dependencies || parsed.devDependencies || parsed.scripts || parsed.exports || parsed.main) {
258
+ return { level: 'L2', id: 'SEM_PACKAGE_JSON', summary: `Node.js package.json dependency or script manifest` };
259
+ }
260
+ } catch {
261
+ return { level: 'L2', id: 'SEM_PACKAGE_JSON', summary: `Node.js package.json manifest` };
262
+ }
263
+ }
264
+
265
+ return null;
266
+ }
267
+
268
+ /**
269
+ * Analyzes a changed file across all 3 static semantics layers.
270
+ */
271
+ export function analyzeFileSemantics({ filePath, content, oldContent, allChangedFiles = [] } = {}) {
272
+ // If file is generated code, exclude from risk escalation
273
+ if (isGeneratedFile(filePath, content, oldContent)) {
274
+ return { isGenerated: true, level: 'L1', mandatoryHumanReview: false, signals: [] };
275
+ }
276
+
277
+ const signals = [];
278
+ let maxLevel = 'L1';
279
+ let mandatoryReview = false;
280
+
281
+ const checkSignal = (sig) => {
282
+ if (!sig) return;
283
+ signals.push(sig);
284
+ if (sig.level === 'L3') {
285
+ maxLevel = 'L3';
286
+ if (sig.mandatoryHumanReview) mandatoryReview = true;
287
+ } else if (sig.level === 'L2' && maxLevel !== 'L3') {
288
+ maxLevel = 'L2';
289
+ }
290
+ };
291
+
292
+ // Inspect current (head) content
293
+ if (content) {
294
+ checkSignal(scanImports(filePath, content));
295
+ checkSignal(scanSchemaHeaders(filePath, content, { allChangedFiles }));
296
+ checkSignal(scanToolchainManifests(filePath, content));
297
+ }
298
+
299
+ // Inspect old (baseRef) content (detects deletions of contracts, manifests, or security rules)
300
+ if (oldContent && oldContent !== content) {
301
+ checkSignal(scanImports(filePath, oldContent));
302
+ checkSignal(scanSchemaHeaders(filePath, oldContent, { allChangedFiles }));
303
+ checkSignal(scanToolchainManifests(filePath, oldContent));
304
+ }
305
+
306
+ return {
307
+ isGenerated: false,
308
+ level: maxLevel,
309
+ mandatoryHumanReview: mandatoryReview,
310
+ signals
311
+ };
312
+ }
313
+
314
+ /**
315
+ * Batches file reading and static semantics analysis for a set of changed files,
316
+ * eliminating redundant disk I/O and git subprocess spawns across vectors.
317
+ */
318
+ export function batchAnalyzeFileSemantics(changedFiles = [], { repoRoot = null, baseRef = null } = {}) {
319
+ const cache = new Map();
320
+ if (!Array.isArray(changedFiles) || changedFiles.length === 0) return cache;
321
+
322
+ const substantive = changedFiles.filter((f) => !isTestOrDocFile(f));
323
+ let baseFilesMap = new Map();
324
+ if (repoRoot && baseRef && substantive.length > 0) {
325
+ baseFilesMap = getBatchGitFiles(repoRoot, baseRef, substantive);
326
+ }
327
+
328
+ for (const f of changedFiles) {
329
+ if (isTestOrDocFile(f)) {
330
+ cache.set(f, {
331
+ filePath: f,
332
+ headContent: null,
333
+ oldContent: null,
334
+ isGenerated: false,
335
+ level: 'L1',
336
+ mandatoryHumanReview: false,
337
+ signals: []
338
+ });
339
+ continue;
340
+ }
341
+
342
+ const fullPath = path.isAbsolute(f) ? f : (repoRoot ? path.join(repoRoot, f) : f);
343
+ let headContent = null;
344
+ if (fs.existsSync(fullPath)) {
345
+ try {
346
+ headContent = fs.readFileSync(fullPath, 'utf8');
347
+ } catch { /* binary or unreadable */ }
348
+ }
349
+
350
+ const oldContent = baseFilesMap.get(f) || null;
351
+
352
+ const sem = analyzeFileSemantics({
353
+ filePath: f,
354
+ content: headContent,
355
+ oldContent,
356
+ allChangedFiles: changedFiles
357
+ });
358
+
359
+ cache.set(f, {
360
+ filePath: f,
361
+ headContent,
362
+ oldContent,
363
+ ...sem
364
+ });
365
+ }
366
+
367
+ return cache;
368
+ }
369
+
@@ -41,20 +41,9 @@ export function evaluateV1Intent({ requirement = '', specDelta = '', changedFile
41
41
  const evalMode = aiJudgment.evaluator_mode || 'heuristic_seed';
42
42
  const isAiMode = evalMode !== 'heuristic_seed';
43
43
 
44
- // 2a. Agent / LLM Semantic Escalation (Bidirectional — never triggered by offline regex heuristic_seed):
44
+ // 2a. Agent / LLM Semantic Escalation (Bidirectional — reserved for agent_native or llm_classifier):
45
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) {
46
+ if (aiJudgment.classification === 'destructive' || aiJudgment.contains_destructive_ops) {
58
47
  level = 'L3';
59
48
  mandatory_human_review = true;
60
49
  evidence.push({
@@ -72,6 +61,17 @@ export function evaluateV1Intent({ requirement = '', specDelta = '', changedFile
72
61
  signal: 'hard',
73
62
  summary: aiJudgment.rationale || 'Agent Semantic Evaluation: Task modifies core repository governance'
74
63
  });
64
+ } else if (aiJudgment.classification === 'api_contract' || aiJudgment.contains_api_changes) {
65
+ if (level === 'L1') {
66
+ level = 'L2';
67
+ inferredType = inferredType === 'chore' ? 'change' : inferredType;
68
+ evidence.push({
69
+ id: 'V1_AI_API_CONTRACT_INTENT',
70
+ kind: 'semantic_intent',
71
+ signal: 'hard',
72
+ summary: aiJudgment.rationale || 'Agent Semantic Evaluation: Change modifies cross-boundary API contracts'
73
+ });
74
+ }
75
75
  }
76
76
  }
77
77
 
@@ -1,9 +1,11 @@
1
1
  import path from 'node:path';
2
2
  import { exists, readText } from '../../lib/fs.js';
3
+ import { git } from '../../lib/git.js';
3
4
  import { HARD_RULES, isTestOrDocFile, CANONICAL_DESTRUCTIVE_PATTERN } from '../rules/builtin.js';
4
- import { judgeChangeSemantics } from '../ai_judge.js';
5
+ import { scanDiffForSecrets } from '../secrets.js';
6
+ import { analyzeFileSemantics, batchAnalyzeFileSemantics } from '../semantics.js';
5
7
 
6
- export function evaluateV2Security({ requirement = '', changedFiles = [], repoRoot = null } = {}) {
8
+ export function evaluateV2Security({ requirement = '', changedFiles = [], repoRoot = null, baseRef = null, diffText = null, fileSemantics = null } = {}) {
7
9
  const req = String(requirement || '').toLowerCase();
8
10
  const evidence = [];
9
11
  const unresolved = [];
@@ -12,7 +14,71 @@ export function evaluateV2Security({ requirement = '', changedFiles = [], repoRo
12
14
  let mandatory_human_review = false;
13
15
  let no_signal = true;
14
16
 
15
- // 1. Check Hard Rules against physical files
17
+ const semanticsMap = fileSemantics || batchAnalyzeFileSemantics(changedFiles, { repoRoot, baseRef });
18
+
19
+ // 1a. Scan diff or changed files for plaintext secrets
20
+ let secretFindings = [];
21
+ if (diffText) {
22
+ secretFindings = scanDiffForSecrets(diffText);
23
+ } else if (repoRoot) {
24
+ for (const f of changedFiles) {
25
+ const fullPath = path.isAbsolute(f) ? f : path.join(repoRoot, f);
26
+ if (exists(fullPath)) {
27
+ try {
28
+ const content = readText(fullPath);
29
+ const sf = scanDiffForSecrets(content);
30
+ if (sf.length > 0) secretFindings.push(...sf.map((s) => ({ ...s, file: f })));
31
+ } catch { /* ignore binary / unreadable */ }
32
+ }
33
+ }
34
+ }
35
+
36
+ if (secretFindings.length > 0) {
37
+ level = 'L3';
38
+ no_signal = false;
39
+ mandatory_human_review = true;
40
+ evidence.push({
41
+ id: 'V2_HARD_SECRET_LEAK',
42
+ kind: 'secret_leak',
43
+ rule_id: 'HARD_SECURITY_CREDENTIALS',
44
+ signal: 'hard',
45
+ summary: `Plaintext credential detected in changed code (${secretFindings.map((s) => `${s.rule}:${s.redacted}`).slice(0, 3).join(', ')})`,
46
+ source: secretFindings[0].file || 'diff'
47
+ });
48
+ }
49
+
50
+ // 1b. Check for deleted sensitive files (fallback to baseRef)
51
+ if (repoRoot && baseRef) {
52
+ for (const f of changedFiles) {
53
+ const fullPath = path.isAbsolute(f) ? f : path.join(repoRoot, f);
54
+ const norm = f.replace(/\\/g, '/');
55
+ if (!exists(fullPath)) {
56
+ try {
57
+ const cached = semanticsMap.get(f);
58
+ const oldContent = cached ? cached.oldContent : git(['show', `${baseRef}:${norm}`], repoRoot, { allowFail: true });
59
+ if (oldContent) {
60
+ const isSecurity = /@EnableWebSecurity|SecurityConfig|JwtAuthenticationFilter|jwt\.sign|passport|fastapi\.security/i.test(oldContent);
61
+ const isDestructive = CANONICAL_DESTRUCTIVE_PATTERN.test(oldContent);
62
+ if (isSecurity || isDestructive || /(auth|security|session|mfa|kms)/i.test(norm)) {
63
+ level = 'L3';
64
+ no_signal = false;
65
+ mandatory_human_review = true;
66
+ evidence.push({
67
+ id: 'V2_DELETED_SECURITY',
68
+ kind: 'deleted_security',
69
+ rule_id: 'HARD_SECURITY_CREDENTIALS',
70
+ signal: 'hard',
71
+ summary: `Deleted high-risk security configuration or destructive migration from base: ${norm}`,
72
+ source: norm
73
+ });
74
+ }
75
+ }
76
+ } catch { /* ignore */ }
77
+ }
78
+ }
79
+ }
80
+
81
+ // 1c. Check Hard Rules against physical files
16
82
  const securityRules = HARD_RULES.filter((r) =>
17
83
  ['HARD_GOV_PLANE', 'HARD_SECURITY_CREDENTIALS', 'HARD_FINANCIAL_ASSETS', 'HARD_DESTRUCTIVE_DDL'].includes(r.id)
18
84
  );
@@ -52,94 +118,23 @@ export function evaluateV2Security({ requirement = '', changedFiles = [], repoRo
52
118
  }
53
119
  }
54
120
 
55
- // 2. Check Requirement Semantics for Security/Financial/Regulatory (English + Chinese)
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 cjkHighRiskCompounds = [
64
- '清结算', '资金清算', '账务清算', '资金账本', '核心账务', '对账', '打款', '提现',
65
- '私钥', '密钥轮换', '密码哈希', '密码加密', '鉴权绕过', '越权', '隐私合规', '实名认证', '数据脱敏'
66
- ];
67
-
68
- const genericSecWords = [
69
- 'auth', 'authentication', 'password', 'credential', 'crypto',
70
- 'payment', 'payout', 'refund', 'billing', 'ledger', 'wallet', 'clearing'
71
- ];
72
-
73
- const cjkGenericSecWords = [
74
- '支付', '结算', '账务', '账本', '钱包', '计费', '账单', '退款',
75
- '鉴权', '认证', '权限', '密钥', '令牌', '加密', '登录态'
76
- ];
77
-
78
- let compoundHit = null;
79
- for (const compound of highRiskCompounds) {
80
- const re = new RegExp(`\\b${compound.replace(/-/g, '[-\\s]')}\\b`, 'i');
81
- if (re.test(req)) {
82
- compoundHit = compound;
83
- break;
84
- }
85
- }
86
- if (!compoundHit) {
87
- for (const cjkCompound of cjkHighRiskCompounds) {
88
- if (req.includes(cjkCompound)) {
89
- compoundHit = cjkCompound;
90
- break;
91
- }
92
- }
93
- }
94
-
95
- const matchedGenerics = [];
96
- for (const word of genericSecWords) {
97
- const re = new RegExp(`\\b${word}\\b`, 'i');
98
- if (re.test(req)) {
99
- matchedGenerics.push(word);
100
- }
101
- }
102
- for (const cjkWord of cjkGenericSecWords) {
103
- if (req.includes(cjkWord)) {
104
- matchedGenerics.push(cjkWord);
105
- }
106
- }
107
-
108
- const aiJudgment = judgeChangeSemantics({ requirement: req, changedFiles });
109
- const isDocOrTest = aiJudgment.is_pure_test || aiJudgment.is_pure_doc;
110
-
111
- if (!isDocOrTest) {
112
- if (compoundHit) {
113
- no_signal = false;
121
+ // 2. Static Semantics Engine: Check L3 security / credentials / middleware / auth
122
+ for (const f of changedFiles) {
123
+ if (isTestOrDocFile(f)) continue;
124
+ const sem = semanticsMap.get(f) || analyzeFileSemantics({ filePath: f, allChangedFiles: changedFiles });
125
+ if (sem && sem.level === 'L3') {
114
126
  level = 'L3';
115
- mandatory_human_review = true;
116
- evidence.push({
117
- id: 'V2_SECURITY_COMPOUND_KEYWORD',
118
- kind: 'task_statement',
119
- signal: 'hard',
120
- summary: `Task requirement touches critical security/regulatory compound phrase: '${compoundHit}'`
121
- });
122
- } else if (matchedGenerics.length >= 2) {
123
127
  no_signal = false;
124
- level = 'L3';
125
128
  mandatory_human_review = true;
126
- evidence.push({
127
- id: 'V2_SECURITY_MULTI_KEYWORD',
128
- kind: 'task_statement',
129
- signal: 'soft',
130
- summary: `Task requirement touches multiple security/financial domains: '${matchedGenerics.join(', ')}'`
131
- });
132
- } else if (matchedGenerics.length === 1) {
133
- no_signal = false;
134
- if (level === 'L1') {
135
- level = 'L2'; // Capped at L2 for single soft generic keyword
129
+ for (const sig of sem.signals.filter((s) => s.level === 'L3')) {
130
+ evidence.push({
131
+ id: `V2_${sig.id}`,
132
+ kind: 'static_semantics',
133
+ signal: 'hard',
134
+ summary: sig.summary,
135
+ source: f
136
+ });
136
137
  }
137
- evidence.push({
138
- id: 'V2_SECURITY_SINGLE_KEYWORD',
139
- kind: 'task_statement',
140
- signal: 'soft',
141
- summary: `Task requirement touches security/financial domain keyword: '${matchedGenerics[0]}'`
142
- });
143
138
  }
144
139
  }
145
140