@akjamie/agentic-sdlc 1.7.0 → 1.9.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
 
@@ -3,9 +3,9 @@ import { exists, readText } from '../../lib/fs.js';
3
3
  import { git } from '../../lib/git.js';
4
4
  import { HARD_RULES, isTestOrDocFile, CANONICAL_DESTRUCTIVE_PATTERN } from '../rules/builtin.js';
5
5
  import { scanDiffForSecrets } from '../secrets.js';
6
- import { judgeChangeSemantics } from '../ai_judge.js';
6
+ import { analyzeFileSemantics, batchAnalyzeFileSemantics } from '../semantics.js';
7
7
 
8
- export function evaluateV2Security({ requirement = '', changedFiles = [], repoRoot = null, baseRef = null, diffText = null } = {}) {
8
+ export function evaluateV2Security({ requirement = '', changedFiles = [], repoRoot = null, baseRef = null, diffText = null, fileSemantics = null } = {}) {
9
9
  const req = String(requirement || '').toLowerCase();
10
10
  const evidence = [];
11
11
  const unresolved = [];
@@ -14,6 +14,8 @@ export function evaluateV2Security({ requirement = '', changedFiles = [], repoRo
14
14
  let mandatory_human_review = false;
15
15
  let no_signal = true;
16
16
 
17
+ const semanticsMap = fileSemantics || batchAnalyzeFileSemantics(changedFiles, { repoRoot, baseRef });
18
+
17
19
  // 1a. Scan diff or changed files for plaintext secrets
18
20
  let secretFindings = [];
19
21
  if (diffText) {
@@ -52,7 +54,8 @@ export function evaluateV2Security({ requirement = '', changedFiles = [], repoRo
52
54
  const norm = f.replace(/\\/g, '/');
53
55
  if (!exists(fullPath)) {
54
56
  try {
55
- const oldContent = git(['show', `${baseRef}:${norm}`], repoRoot, { allowFail: true });
57
+ const cached = semanticsMap.get(f);
58
+ const oldContent = cached ? cached.oldContent : git(['show', `${baseRef}:${norm}`], repoRoot, { allowFail: true });
56
59
  if (oldContent) {
57
60
  const isSecurity = /@EnableWebSecurity|SecurityConfig|JwtAuthenticationFilter|jwt\.sign|passport|fastapi\.security/i.test(oldContent);
58
61
  const isDestructive = CANONICAL_DESTRUCTIVE_PATTERN.test(oldContent);
@@ -115,94 +118,23 @@ export function evaluateV2Security({ requirement = '', changedFiles = [], repoRo
115
118
  }
116
119
  }
117
120
 
118
- // 2. Check Requirement Semantics for Security/Financial/Regulatory (English + Chinese)
119
- const highRiskCompounds = [
120
- 'access token', 'refresh token', 'bearer token', 'session token', 'auth token', 'security token',
121
- 'jwt', 'oauth', 'private key', 'secret key', 'password hash', 'password encryption',
122
- 'mfa', 'rbac', 'kms', 'pii', 'gdpr', 'tax id', 'ssn', 'payment refund', 'payment ledger',
123
- 'refund ledger', 'clearing settlement', 'credit card'
124
- ];
125
-
126
- const cjkHighRiskCompounds = [
127
- '清结算', '资金清算', '账务清算', '资金账本', '核心账务', '对账', '打款', '提现',
128
- '私钥', '密钥轮换', '密码哈希', '密码加密', '鉴权绕过', '越权', '隐私合规', '实名认证', '数据脱敏'
129
- ];
130
-
131
- const genericSecWords = [
132
- 'auth', 'authentication', 'password', 'credential', 'crypto',
133
- 'payment', 'payout', 'refund', 'billing', 'ledger', 'wallet', 'clearing'
134
- ];
135
-
136
- const cjkGenericSecWords = [
137
- '支付', '结算', '账务', '账本', '钱包', '计费', '账单', '退款',
138
- '鉴权', '认证', '权限', '密钥', '令牌', '加密', '登录态'
139
- ];
140
-
141
- let compoundHit = null;
142
- for (const compound of highRiskCompounds) {
143
- const re = new RegExp(`\\b${compound.replace(/-/g, '[-\\s]')}\\b`, 'i');
144
- if (re.test(req)) {
145
- compoundHit = compound;
146
- break;
147
- }
148
- }
149
- if (!compoundHit) {
150
- for (const cjkCompound of cjkHighRiskCompounds) {
151
- if (req.includes(cjkCompound)) {
152
- compoundHit = cjkCompound;
153
- break;
154
- }
155
- }
156
- }
157
-
158
- const matchedGenerics = [];
159
- for (const word of genericSecWords) {
160
- const re = new RegExp(`\\b${word}\\b`, 'i');
161
- if (re.test(req)) {
162
- matchedGenerics.push(word);
163
- }
164
- }
165
- for (const cjkWord of cjkGenericSecWords) {
166
- if (req.includes(cjkWord)) {
167
- matchedGenerics.push(cjkWord);
168
- }
169
- }
170
-
171
- const aiJudgment = judgeChangeSemantics({ requirement: req, changedFiles });
172
- const isDocOrTest = aiJudgment.is_pure_test || aiJudgment.is_pure_doc;
173
-
174
- if (!isDocOrTest) {
175
- if (compoundHit) {
176
- 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') {
177
126
  level = 'L3';
178
- mandatory_human_review = true;
179
- evidence.push({
180
- id: 'V2_SECURITY_COMPOUND_KEYWORD',
181
- kind: 'task_statement',
182
- signal: 'hard',
183
- summary: `Task requirement touches critical security/regulatory compound phrase: '${compoundHit}'`
184
- });
185
- } else if (matchedGenerics.length >= 2) {
186
127
  no_signal = false;
187
- level = 'L3';
188
128
  mandatory_human_review = true;
189
- evidence.push({
190
- id: 'V2_SECURITY_MULTI_KEYWORD',
191
- kind: 'task_statement',
192
- signal: 'soft',
193
- summary: `Task requirement touches multiple security/financial domains: '${matchedGenerics.join(', ')}'`
194
- });
195
- } else if (matchedGenerics.length === 1) {
196
- no_signal = false;
197
- if (level === 'L1') {
198
- 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
+ });
199
137
  }
200
- evidence.push({
201
- id: 'V2_SECURITY_SINGLE_KEYWORD',
202
- kind: 'task_statement',
203
- signal: 'soft',
204
- summary: `Task requirement touches security/financial domain keyword: '${matchedGenerics[0]}'`
205
- });
206
138
  }
207
139
  }
208
140
 
@@ -2,8 +2,9 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { HARD_RULES, isTestOrDocFile, isChangeMetadataFile } from '../rules/builtin.js';
4
4
  import { getGraphTopologyMetrics } from '../../lib/graphify.js';
5
+ import { analyzeFileSemantics, batchAnalyzeFileSemantics } from '../semantics.js';
5
6
 
6
- export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRoot = null, changeId = null } = {}) {
7
+ export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRoot = null, changeId = null, baseRef = null, fileSemantics = null } = {}) {
7
8
  const req = String(requirement || '').toLowerCase();
8
9
  const evidence = [];
9
10
  const unresolved = [];
@@ -12,6 +13,8 @@ export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRo
12
13
  let mandatory_human_review = false;
13
14
  let no_signal = true;
14
15
 
16
+ const semanticsMap = fileSemantics || batchAnalyzeFileSemantics(changedFiles, { repoRoot, baseRef });
17
+
15
18
  // 1. Check Hard Rules for Topology / Contracts / Infra
16
19
  const topoRules = HARD_RULES.filter((r) =>
17
20
  ['HARD_API_CONTRACT', 'HARD_DB_MIGRATION', 'HARD_SUPPLY_CHAIN'].includes(r.id)
@@ -29,13 +32,18 @@ export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRo
29
32
  const norm = f.replace(/\\/g, '/');
30
33
  if (rule.patterns.some((p) => p.test(norm))) return true;
31
34
 
32
- // Content-based heuristic for API handlers in source files
35
+ // Content-based heuristic for API handlers in source files (symmetric head/baseRef inspection)
33
36
  if (rule.id === 'HARD_API_CONTRACT' && repoRoot && /\.(java|kt|py|go|ts|js)$/i.test(norm)) {
34
37
  try {
35
- const fullPath = path.isAbsolute(f) ? f : path.join(repoRoot, f);
36
- if (fs.existsSync(fullPath)) {
37
- const content = fs.readFileSync(fullPath, 'utf8');
38
- if (API_CONTENT_PATTERNS.some((p) => p.test(content))) return true;
38
+ const cached = semanticsMap.get(f);
39
+ const contentToCheck = cached ? (cached.headContent || cached.oldContent) : null;
40
+ if (contentToCheck && API_CONTENT_PATTERNS.some((p) => p.test(contentToCheck))) return true;
41
+ if (!cached) {
42
+ const fullPath = path.isAbsolute(f) ? f : path.join(repoRoot, f);
43
+ if (fs.existsSync(fullPath)) {
44
+ const content = fs.readFileSync(fullPath, 'utf8');
45
+ if (API_CONTENT_PATTERNS.some((p) => p.test(content))) return true;
46
+ }
39
47
  }
40
48
  } catch { /* ignore read failure */ }
41
49
  }
@@ -166,48 +174,25 @@ export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRo
166
174
  }
167
175
  }
168
176
 
169
- // 3. Check Requirement Semantics for Architecture / Schema / Infra (English + Chinese)
170
- const topoKeywords = [
171
- 'api', 'endpoint', 'openapi', 'swagger', 'grpc', 'protobuf', 'graphql', 'webhook',
172
- 'fastapi', 'springboot', 'spring boot', 'controller', 'rest api', 'router',
173
- 'database', 'migration', 'schema', 'db table', 'database table', 'sql table', 'ddl', 'model', 'docker', 'k8s', 'helm'
174
- ];
175
-
176
- const cjkTopoKeywords = [
177
- '接口', '路由', '协议', '网关', '控制器', '出入参', '字段变更',
178
- '数据库', '数据表', '表结构', '数据库迁移', '索引变更', '容器编排'
179
- ];
180
-
181
- let matchedTopoKw = null;
182
- for (const kw of topoKeywords) {
183
- const re = new RegExp(`\\b${kw.replace(/-/g, '[-\\s]')}\\b`, 'i');
184
- if (re.test(req)) {
185
- matchedTopoKw = kw;
186
- break;
187
- }
188
- }
189
- if (!matchedTopoKw) {
190
- for (const cjkKw of cjkTopoKeywords) {
191
- if (req.includes(cjkKw)) {
192
- matchedTopoKw = cjkKw;
193
- break;
177
+ // 3. Static Semantics Engine: Check L2 server contracts, migrations, schemas, manifests (symmetric head/baseRef)
178
+ for (const f of changedFiles) {
179
+ if (isTestOrDocFile(f)) continue;
180
+ const sem = semanticsMap.get(f) || analyzeFileSemantics({ filePath: f, allChangedFiles: changedFiles });
181
+ if (sem && sem.level === 'L2') {
182
+ if (level === 'L1') level = 'L2';
183
+ no_signal = false;
184
+ for (const sig of sem.signals.filter((s) => s.level === 'L2')) {
185
+ evidence.push({
186
+ id: `V3_${sig.id}`,
187
+ kind: 'static_semantics',
188
+ signal: 'hard',
189
+ summary: sig.summary,
190
+ source: f
191
+ });
194
192
  }
195
193
  }
196
194
  }
197
195
 
198
- if (matchedTopoKw) {
199
- no_signal = false;
200
- if (level === 'L1') {
201
- level = 'L2';
202
- }
203
- evidence.push({
204
- id: 'V3_TOPOLOGY_KEYWORD',
205
- kind: 'task_statement',
206
- signal: 'soft',
207
- summary: `Requirement touches cross-boundary architectural keyword: '${matchedTopoKw}'`
208
- });
209
- }
210
-
211
196
  return {
212
197
  level,
213
198
  confidence,