@akjamie/agentic-sdlc 1.7.0 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akjamie/agentic-sdlc",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "Enterprise Agentic SDLC governance CLI: a 7-stage spec-driven flow on top of OpenSpec + Graphify, enforced by CI.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import { execSync } from 'node:child_process';
11
- import { CANONICAL_DESTRUCTIVE_PATTERN, isTestOrDocFile, isChangeMetadataFile } from './rules/builtin.js';
11
+ import { CANONICAL_DESTRUCTIVE_PATTERN, isTestOrDocFile, isChangeMetadataFile, isPureTestFile, isPureL0File } from './rules/builtin.js';
12
12
 
13
13
  export const AI_CLASSIFICATION_SCHEMA = {
14
14
  type: 'object',
@@ -163,50 +163,51 @@ export function judgeChangeSemantics({ requirement = '', changedFiles = [], repo
163
163
  }
164
164
 
165
165
  // 3. Validated baseline heuristic seed (deterministic fallback for standalone CLI execution)
166
+ // Per Hardening Spec C3/C4 & R2 Review: CLI maintains ZERO human natural language dictionaries for risk escalation.
167
+ // Pre-code risk escalation relies strictly on CANONICAL_DESTRUCTIVE_PATTERN, target files (explore.md), or host agentContext.
168
+ // Explicit documented exception: Safe L0-only doc/test intent tokens are retained exclusively for pre-code routine
169
+ // classification (guarded by Invariant 4 against refactoring/code masking), and can NEVER escalate risk or bypass gates.
166
170
  if (!rawAiOutput) {
167
- const hasProductionTarget = /\b(create|add|implement|build)\b.*\b(api|endpoint|service|table|database|schema|handler|router)\b/i.test(req) ||
168
- /(?:创建|新增|实现|开发)\b.*(?:接口|服务|路由|数据表|表结构|控制器)/i.test(req);
169
171
  const hasDestructiveAction = CANONICAL_DESTRUCTIVE_PATTERN.test(req);
170
172
 
171
- const isDocIntent = /(?:\b(?:typo|typos|readme|docs?|documentation|comments?|whitespace|markdown|license|changelog)\b|错别字|文档|注释|说明文档)/i.test(req) &&
172
- !hasProductionTarget && !hasDestructiveAction;
173
-
174
- const isTestIntent = /(?:\b(?:tests?|testing|mocks?|fixtures?|suites?|unittests?|integrationtests?)\b|单元测试|集成测试|测试用例)/i.test(req) &&
175
- !hasProductionTarget && !hasDestructiveAction;
173
+ const substantiveFiles = normFiles.filter((f) => !isChangeMetadataFile(f));
174
+ const allTestFiles = substantiveFiles.length > 0 && substantiveFiles.every((f) => isPureTestFile(f));
175
+ const allDocFiles = substantiveFiles.length > 0 && substantiveFiles.every((f) => isPureL0File(f));
176
176
 
177
- // Few-shot file pattern seeds (illustrative samples)
178
- const testPatternSamples = [
179
- /(^|\/)(tests?|__tests__|testing|fixtures?|mocks?)\//i,
180
- /\.(test|spec)\.[a-z0-9]+$/i,
181
- /_test\.go$/i,
182
- /test_[^/]+\.py$/i,
183
- /[^/]+_test\.py$/i
184
- ];
177
+ let isPureTest = allTestFiles;
178
+ let isPureDoc = allDocFiles;
185
179
 
186
- const docPatternSamples = [
187
- /(^|\/)docs?\//i,
188
- /\.(md|txt)$/i,
189
- /^license$/i
190
- ];
180
+ if (substantiveFiles.length === 0 && !hasDestructiveAction) {
181
+ const hasDocSignal = /(?:\b(?:docs?|documentation|readme|typo|typos|comments?|whitespace|changelog|markdown|license)\b|文档|注释|错别字|说明文档)/i.test(req);
182
+ const hasTestSignal = /(?:\b(?:unit\s+tests?|integration\s+tests?|e2e\s+tests?|test\s+suites?|test\s+cases?|tests?|testing|mocks?|fixtures?)\b|单元测试|集成测试|测试用例)/i.test(req);
183
+ const hasCodeRefactorOrMutation = /(?:\b(?:refactor|rewrite|redesign|state\s+machine)\b|重构|重写|状态机)/i.test(req) ||
184
+ /\b(?:implement|build|create)\b.*\b(?:api|endpoint|service|controller|router|table|database|schema|handler)\b/i.test(req) ||
185
+ /(?:实现|开发|创建|新增)\b.*(?:接口|服务|路由|数据表|表结构|控制器)/i.test(req);
191
186
 
192
- const substantiveFiles = normFiles.filter((f) => !isChangeMetadataFile(f));
193
- const allTestFiles = substantiveFiles.length > 0 && substantiveFiles.every((f) => testPatternSamples.some((p) => p.test(f)));
194
- const allDocFiles = substantiveFiles.length > 0 && substantiveFiles.every((f) => docPatternSamples.some((p) => p.test(f)));
187
+ if (hasDocSignal && !hasCodeRefactorOrMutation) {
188
+ isPureDoc = true;
189
+ }
190
+ if (hasTestSignal && !hasCodeRefactorOrMutation) {
191
+ isPureTest = true;
192
+ }
193
+ }
195
194
 
196
- const isPureTest = allTestFiles || (substantiveFiles.length === 0 && isTestIntent);
197
- const isPureDoc = allDocFiles || (substantiveFiles.length === 0 && isDocIntent);
195
+ let heuristicClass = 'internal_code';
196
+ if (isPureTest) heuristicClass = 'test_only';
197
+ else if (isPureDoc) heuristicClass = 'doc_only';
198
+ else if (hasDestructiveAction) heuristicClass = 'destructive';
198
199
 
199
200
  rawAiOutput = {
200
201
  is_pure_test: isPureTest,
201
202
  is_pure_doc: isPureDoc,
202
- contains_destructive_ops: CANONICAL_DESTRUCTIVE_PATTERN.test(req),
203
+ contains_destructive_ops: hasDestructiveAction,
203
204
  contains_api_changes: false,
204
- classification: isPureTest ? 'test_only' : (isPureDoc ? 'doc_only' : 'internal_code'),
205
+ classification: heuristicClass,
205
206
  confidence: 'high',
206
207
  evaluator_mode: 'heuristic_seed',
207
208
  rationale: isPureTest
208
209
  ? 'Deterministic Heuristic Baseline: Change is strictly confined to test suites, mocks, and test assertions.'
209
- : (isPureDoc ? 'Deterministic Heuristic Baseline: Change is purely documentation, typo fix, comments, or non-executable text.' : 'Deterministic Heuristic Baseline: General code change')
210
+ : (isPureDoc ? 'Deterministic Heuristic Baseline: Change is purely documentation, typo fix, comments, or non-executable text.' : (hasDestructiveAction ? 'Deterministic Heuristic Baseline: Irreversible destructive data operations detected in task statement.' : 'Deterministic Heuristic Baseline: General code change (evaluated via static code semantics)'))
210
211
  };
211
212
  } else {
212
213
  rawAiOutput.evaluator_mode = rawAiOutput.evaluator_mode || 'llm_classifier';
@@ -73,6 +73,24 @@ export function decideAssessment({
73
73
  }
74
74
  }
75
75
 
76
+ // 3b. Bounded L1 Positive Safety Envelope (§10.2 7b):
77
+ // When calculatedLevel is L1, verify it remains within bounded local code envelope:
78
+ // - Substantive production source files <= 5
79
+ // - Did not modify root export entrypoints (index.ts/js, lib.rs)
80
+ // If unbounded (> 5 source files or touching root entrypoints), escalate to L2
81
+ if (calculatedLevel === 'L1' && !hasMandatoryHumanReview) {
82
+ const substantiveFiles = changedFiles
83
+ .map((f) => f.replace(/\\/g, '/'))
84
+ .filter((f) => !isChangeMetadataFile(f));
85
+ const productionFiles = substantiveFiles.filter((f) => !isPureL0File(f) && !isPureTestFile(f));
86
+
87
+ if (productionFiles.length > 5) {
88
+ calculatedLevel = 'L2';
89
+ } else if (productionFiles.some((f) => /^(?:(?:packages\/[^/]+\/)?(?:src\/|lib\/)?)?(?:index\.(?:ts|js|mjs)|lib\.rs)$/i.test(f))) {
90
+ calculatedLevel = 'L2';
91
+ }
92
+ }
93
+
76
94
  // 4. Determine Confidence & Unresolved
77
95
  const allUnresolved = [
78
96
  ...(v1.unresolved || []),
@@ -5,6 +5,7 @@ import { HARNESS_RULES_VERSION, ENGINE_VERSION } from './rules/builtin.js';
5
5
  import { evaluateV1Intent } from './vectors/v1_intent.js';
6
6
  import { evaluateV2Security } from './vectors/v2_security.js';
7
7
  import { evaluateV3Topology } from './vectors/v3_topology.js';
8
+ import { batchAnalyzeFileSemantics } from './semantics.js';
8
9
  import { decideAssessment } from './decide.js';
9
10
  import { deriveGovernance } from './governance.js';
10
11
  import { appendAssessmentRecord, loadLatestAssessment, loadInitialAssessment } from './store.js';
@@ -31,7 +32,8 @@ export function assess({
31
32
  baseline = null,
32
33
  actor = { type: 'system', id: 'asdlc' },
33
34
  repoRoot = null,
34
- persist = true
35
+ persist = true,
36
+ agentContext = null
35
37
  } = {}) {
36
38
  try {
37
39
  const prev = previous || (repoRoot && changeId ? loadLatestAssessment(repoRoot, changeId) : null);
@@ -39,7 +41,7 @@ export function assess({
39
41
 
40
42
  // If requirement is empty or for spec stage, load proposal.md and design.md from change dir
41
43
  let effectiveReq = requirement || '';
42
- let agentContext = null;
44
+ let effectiveAgentContext = agentContext;
43
45
  if (repoRoot && changeId) {
44
46
  try {
45
47
  const cdir = changeDir(repoRoot, changeId);
@@ -50,19 +52,24 @@ export function assess({
50
52
  }
51
53
 
52
54
  // Check if change contains agent assessment context (.agent-assess.json or .openspec.yaml assessment)
53
- const agentCtxPath = path.join(cdir, '.agent-assess.json');
54
- if (fs.existsSync(agentCtxPath)) {
55
- try {
56
- agentContext = JSON.parse(fs.readFileSync(agentCtxPath, 'utf8'));
57
- } catch { /* ignore parse error */ }
55
+ if (!effectiveAgentContext) {
56
+ const agentCtxPath = path.join(cdir, '.agent-assess.json');
57
+ if (fs.existsSync(agentCtxPath)) {
58
+ try {
59
+ effectiveAgentContext = JSON.parse(fs.readFileSync(agentCtxPath, 'utf8'));
60
+ } catch { /* ignore parse error */ }
61
+ }
58
62
  }
59
63
  } catch { /* ignore read failure */ }
60
64
  }
61
65
 
66
+ const effectiveBase = baseRef || baseSha;
67
+ const fileSemantics = batchAnalyzeFileSemantics(changedFiles, { repoRoot, baseRef: effectiveBase });
68
+
62
69
  // 1. Evaluate Three Risk Vectors
63
- const v1 = evaluateV1Intent({ requirement: effectiveReq, changedFiles, changeType, agentContext });
64
- const v2 = evaluateV2Security({ requirement: effectiveReq, changedFiles, repoRoot, baseRef: baseRef || baseSha });
65
- const v3 = evaluateV3Topology({ requirement: effectiveReq, changedFiles, repoRoot, changeId });
70
+ const v1 = evaluateV1Intent({ requirement: effectiveReq, changedFiles, changeType, agentContext: effectiveAgentContext });
71
+ const v2 = evaluateV2Security({ requirement: effectiveReq, changedFiles, repoRoot, baseRef: effectiveBase, fileSemantics });
72
+ const v3 = evaluateV3Topology({ requirement: effectiveReq, changedFiles, repoRoot, changeId, baseRef: effectiveBase, fileSemantics });
66
73
 
67
74
  // Inferred or provided Change Type
68
75
  const effectiveType = changeType || v1.inferredType || 'change';
@@ -1,5 +1,5 @@
1
1
  export const HARNESS_RULES_VERSION = '2026.10.0';
2
- export const ENGINE_VERSION = '1.7.0';
2
+ export const ENGINE_VERSION = '1.8.0';
3
3
 
4
4
  export const RISK_LEVELS = {
5
5
  L0: 'L0',
@@ -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,
@@ -9,6 +9,7 @@ import { readYaml } from '../lib/yaml.js';
9
9
  import { git } from '../lib/git.js';
10
10
  import { log, dim } from '../lib/log.js';
11
11
  import { detectTools, checkToolHealth, installSkills, installCommands } from '../lib/tools.js';
12
+ import { jsonOut } from '../lib/cliutil.js';
12
13
 
13
14
  // Environment + setup health. Exit non-zero only on a critical failure
14
15
  // (no OpenSpec project, or the managed schema is not installed / is overridden).
@@ -94,10 +95,22 @@ export function doctor(opts = {}) {
94
95
  }
95
96
 
96
97
  let failed = 0;
98
+ for (const r of rows) {
99
+ if (r.status === 'fail') failed += 1;
100
+ }
101
+
102
+ if (opts.json) {
103
+ jsonOut({
104
+ ok: failed === 0,
105
+ failed,
106
+ checks: rows,
107
+ });
108
+ return failed ? 1 : 0;
109
+ }
110
+
97
111
  log.info('');
98
112
  for (const r of rows) {
99
113
  const badge = { pass: 'PASS', warn: 'WARN', fail: 'FAIL' }[r.status];
100
- if (r.status === 'fail') failed += 1;
101
114
  log.plain(` [${badge}] ${r.name}`);
102
115
  if (r.detail) log.plain(` ${dim(r.detail)}`);
103
116
  }
@@ -174,6 +187,7 @@ export function register(program) {
174
187
  .description('check the environment + repo setup health (with optional --fix)')
175
188
  .option('-g, --global', 'check global toolchain and agent skills only (for CI/headless environments)')
176
189
  .option('--fix', 'automatically remediate fixable environment and configuration drift')
190
+ .option('--json', 'output machine-readable JSON')
177
191
  .option('--repo-root <path>')
178
192
  .action((opts) => {
179
193
  process.exitCode = doctor(opts);
@@ -100,6 +100,7 @@ _(unavailable - graph query error)_
100
100
  const { level, changeType, workflowMode, reason: levelReason } = inferInitialLevel({
101
101
  requirement,
102
102
  explicitLevel: opts.level,
103
+ agentContext: opts.agentContext,
103
104
  repoRoot,
104
105
  changeId: slug
105
106
  });
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { exists, readText, walkFiles, listDir } from '../lib/fs.js';
3
3
  import { changeDir, openspecDir, CHANGES_DIR } from '../lib/paths.js';
4
- import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
4
+ import { requireRepo, toChangeSlug, jsonOut } from '../lib/cliutil.js';
5
5
  import { lastCommitTouching } from '../lib/git.js';
6
6
  import { verdictOf } from './lint.js';
7
7
  import { countUncheckedTasks } from './verify.js';
@@ -18,11 +18,11 @@ export function statusChange(changeId, opts = {}) {
18
18
 
19
19
  if (!exists(cdir)) {
20
20
  if (opts.json) {
21
- log.plain(JSON.stringify({
21
+ jsonOut({
22
22
  change: slug,
23
23
  exists: false,
24
24
  next: `asdlc new ${changeId}`
25
- }, null, 2));
25
+ });
26
26
  return 0;
27
27
  }
28
28
  log.plain(`change: ${slug}`);
@@ -61,13 +61,20 @@ export function statusChange(changeId, opts = {}) {
61
61
  else next = `asdlc verify ${changeId}`;
62
62
 
63
63
  if (opts.json) {
64
- log.plain(JSON.stringify({
64
+ jsonOut({
65
65
  change: slug,
66
66
  exists: true,
67
67
  level,
68
68
  stage: stage.map(([name, ok]) => ({ name, ok })),
69
- next
70
- }, null, 2));
69
+ next,
70
+ checks: {
71
+ explore: has('explore.md'),
72
+ proposal: has('proposal.md'),
73
+ specs: specFiles.length,
74
+ approvedSha,
75
+ tasksComplete: unchecked === 0,
76
+ }
77
+ });
71
78
  return 0;
72
79
  }
73
80
 
@@ -186,10 +193,10 @@ export function statusPortfolio(opts = {}) {
186
193
  }
187
194
 
188
195
  if (opts.json) {
189
- log.plain(JSON.stringify({
196
+ jsonOut({
190
197
  total: active.length,
191
198
  active
192
- }, null, 2));
199
+ });
193
200
  return 0;
194
201
  }
195
202
 
@@ -11,51 +11,6 @@ export function toChangeSlug(changeId) {
11
11
  .replace(/^-+|-+$/g, '');
12
12
  }
13
13
 
14
- // Bilingual domain lexicon bridging Chinese engineering requirements to canonical English
15
- // codebase symbols and readable change slugs (enabling Graphify AST queries on CJK inputs).
16
- const CJK_DOMAIN_LEXICON = [
17
- [/重构/, 'refactor'],
18
- [/修复|排障|缺陷/, 'fix'],
19
- [/清结算|清算/, 'clearing-settlement'],
20
- [/支付|打款|收单/, 'payment'],
21
- [/结算/, 'settlement'],
22
- [/退款/, 'refund'],
23
- [/账务|账本|记账|对账/, 'ledger'],
24
- [/计费|账单/, 'billing'],
25
- [/钱包|资金/, 'wallet'],
26
- [/删表|删除.*表|清空.*表|清理历史|物理删除/, 'purge-table'],
27
- [/鉴权|认证|登录态|单点登录/, 'auth'],
28
- [/权限|越权|角色/, 'rbac'],
29
- [/密钥|私钥|令牌|加密|脱敏/, 'secret-crypto'],
30
- [/接口|出入参|协议/, 'api'],
31
- [/路由|网关|控制器/, 'router'],
32
- [/数据库|数据表|表结构|迁移|索引/, 'schema-db'],
33
- [/订单/, 'order'],
34
- [/缓存/, 'cache'],
35
- [/队列|消息/, 'queue'],
36
- [/配置/, 'config'],
37
- [/单元测试|集成测试|测试用例/, 'test'],
38
- [/文档|注释/, 'docs'],
39
- [/微信/, 'wechat'],
40
- [/回调|通知/, 'callback'],
41
- [/状态机/, 'state-machine'],
42
- [/错别字/, 'typo'],
43
- ];
44
-
45
- function extractCjkMappedTokens(text) {
46
- const raw = String(text ?? '');
47
- if (!/[\u4e00-\u9fff]/.test(raw)) return [];
48
- const tokens = [];
49
- for (const [pattern, mapped] of CJK_DOMAIN_LEXICON) {
50
- if (pattern.test(raw)) {
51
- for (const part of mapped.split('-')) {
52
- if (!tokens.includes(part)) tokens.push(part);
53
- }
54
- }
55
- }
56
- return tokens;
57
- }
58
-
59
14
  export function extractRequirementTerms(text) {
60
15
  const raw = String(text ?? '');
61
16
  const s = raw
@@ -66,9 +21,7 @@ export function extractRequirementTerms(text) {
66
21
  .replace(/[^a-z0-9\s]/g, ' ')
67
22
  .trim();
68
23
  const asciiWords = s.split(/\s+/).filter(Boolean);
69
- const cjkWords = extractCjkMappedTokens(raw).filter((w) => !['refactor', 'fix'].includes(w));
70
- const merged = [...new Set([...asciiWords, ...cjkWords])];
71
- return merged.slice(0, 6).join(' ');
24
+ return [...new Set(asciiWords)].slice(0, 6).join(' ');
72
25
  }
73
26
 
74
27
  export function deriveChangeSlug(input, opts = {}) {
@@ -100,8 +53,7 @@ export function deriveChangeSlug(input, opts = {}) {
100
53
  .split(/\s+/)
101
54
  .filter(Boolean);
102
55
 
103
- const cjkTokens = extractCjkMappedTokens(text);
104
- const words = [...new Set([...cjkTokens, ...asciiWords])].slice(0, 5);
56
+ const words = [...new Set(asciiWords)].slice(0, 5);
105
57
 
106
58
  const keywords = words.join('-');
107
59
  if (ticket && keywords) return `${ticket}-${keywords}`.slice(0, 40).replace(/-+$/, '');
@@ -110,7 +62,7 @@ export function deriveChangeSlug(input, opts = {}) {
110
62
  const fallback = toChangeSlug(text).slice(0, 40);
111
63
  if (fallback) return fallback;
112
64
 
113
- // Non-ASCII fallback when no domain terms matched: generate deterministic slug from content hash
65
+ // Non-ASCII fallback when no ASCII terms matched: generate deterministic slug from content hash
114
66
  const hash = Math.abs(text.split('').reduce((acc, c) => ((acc << 5) - acc) + c.charCodeAt(0), 0)).toString(36);
115
67
  return `change-${hash || Date.now().toString(36)}`;
116
68
  }
package/src/lib/git.js CHANGED
@@ -81,3 +81,45 @@ export function lastCommitTouching(cwd, ref, paths = []) {
81
81
  export function changeOnRef(cwd, ref, slug) {
82
82
  return Boolean(git(['log', '-1', '--format=%H', ref, '--', `openspec/changes/${slug}/proposal.md`], cwd, { allowFail: true }));
83
83
  }
84
+
85
+ /**
86
+ * Batch-reads file contents from a git ref in a single subprocess using `git cat-file --batch`.
87
+ * Returns a Map of filePath -> content string (or null if file does not exist on ref).
88
+ */
89
+ export function getBatchGitFiles(cwd = process.cwd(), ref = 'HEAD', filePaths = []) {
90
+ const result = new Map();
91
+ if (!ref || !Array.isArray(filePaths) || filePaths.length === 0 || !isGitRepo(cwd)) return result;
92
+ try {
93
+ const input = filePaths.map((f) => `${ref}:${f.replace(/\\/g, '/')}\n`).join('');
94
+ const raw = execFileSync('git', ['-c', 'core.quotepath=off', 'cat-file', '--batch'], {
95
+ cwd,
96
+ input: Buffer.from(input, 'utf8'),
97
+ maxBuffer: 50 * 1024 * 1024,
98
+ stdio: ['pipe', 'pipe', 'ignore']
99
+ });
100
+
101
+ let offset = 0;
102
+ for (const f of filePaths) {
103
+ const headerEnd = raw.indexOf(0x0a, offset);
104
+ if (headerEnd === -1) break;
105
+ const header = raw.subarray(offset, headerEnd).toString('utf8');
106
+ offset = headerEnd + 1;
107
+
108
+ if (header.endsWith('missing')) {
109
+ result.set(f, null);
110
+ continue;
111
+ }
112
+
113
+ const parts = header.split(' ');
114
+ if (parts.length >= 3 && parts[1] === 'blob') {
115
+ const size = parseInt(parts[2], 10);
116
+ const contentBuf = raw.subarray(offset, offset + size);
117
+ result.set(f, contentBuf.toString('utf8'));
118
+ offset += size + 1;
119
+ }
120
+ }
121
+ } catch {
122
+ // If batch cat-file fails, return empty map
123
+ }
124
+ return result;
125
+ }
package/src/lib/level.js CHANGED
@@ -9,12 +9,13 @@ import { fail } from './errors.js';
9
9
 
10
10
  export const LEVELS = RISK_LEVELS;
11
11
 
12
- export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, changeId } = {}) {
12
+ export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, changeId, agentContext = null } = {}) {
13
13
  // Always run assessment to establish immutable baseline in history
14
14
  const result = assess({
15
15
  stage: 'new',
16
16
  changeId: changeId || 'provisional',
17
17
  requirement,
18
+ agentContext,
18
19
  repoRoot,
19
20
  persist: Boolean(repoRoot && changeId)
20
21
  });
package/src/lib/risk.js CHANGED
@@ -6,7 +6,7 @@ export { RISK_LEVELS, LEVEL_RANK };
6
6
  /**
7
7
  * Backward-compatible adapter for legacy callers/tests, delegating to unified assess engine.
8
8
  */
9
- export function assessRisk({ requirement = '', changedFiles = [], currentLevel = null, repoRoot = null } = {}) {
9
+ export function assessRisk({ requirement = '', changedFiles = [], currentLevel = null, repoRoot = null, agentContext = null } = {}) {
10
10
  const result = assess({
11
11
  stage: changedFiles.length > 0 ? 'impl' : 'new',
12
12
  requirement,
@@ -14,6 +14,7 @@ export function assessRisk({ requirement = '', changedFiles = [], currentLevel =
14
14
  previous: currentLevel ? { risk: { level: currentLevel } } : null,
15
15
  baseline: currentLevel ? { risk: { level: currentLevel } } : null,
16
16
  repoRoot,
17
+ agentContext,
17
18
  persist: false
18
19
  });
19
20