ai-engineering-loop 1.15.0 → 1.17.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/.agents/skills/ai-engineering-loop/SKILL.md +1 -1
- package/.agents/skills/ai-engineering-loop/references/loop-deliver.md +3 -1
- package/.agents/skills/ai-engineering-loop/references/loop-goal.md +1 -0
- package/.agents/skills/ai-engineering-loop/references/loop-hosts.md +5 -1
- package/.agents/skills/ai-engineering-loop/references/loop-maker.md +7 -1
- package/.agents/skills/ai-engineering-loop/references/loop-review.md +2 -0
- package/.claude/skills/ai-engineering-loop/SKILL.md +1 -1
- package/.claude/skills/ai-engineering-loop/references/loop-deliver.md +3 -1
- package/.claude/skills/ai-engineering-loop/references/loop-goal.md +1 -0
- package/.claude/skills/ai-engineering-loop/references/loop-hosts.md +5 -1
- package/.claude/skills/ai-engineering-loop/references/loop-maker.md +7 -1
- package/.claude/skills/ai-engineering-loop/references/loop-review.md +2 -0
- package/CHANGELOG.md +68 -0
- package/README.md +26 -22
- package/adapters/README.md +22 -0
- package/adapters/dot/README.md +19 -9
- package/adapters/dot/gitlab.md +55 -0
- package/adapters/dot/mattermost.md +10 -0
- package/adapters/dot/skills/dot-dev-workflow/SKILL.md +27 -5
- package/adapters/dot/sonar.md +90 -0
- package/adapters/generate-adapter/SKILL.md +6 -5
- package/adapters/github/pull-request.md +5 -0
- package/adapters/gitlab/merge-request.md +5 -0
- package/adapters/{dot → quality}/skills/task-impact-inquiry/SKILL.md +12 -7
- package/agents/instruction-only/AGENTS.md +24 -0
- package/bin/ai-engineering-loop.js +318 -27
- package/core/blast-radius-map.md +37 -0
- package/core/grill-policy.md +1 -1
- package/core/learnings.md +24 -0
- package/core/orchestration-model.md +11 -0
- package/core/pr-receipt.md +35 -0
- package/core/runtime-safety.md +24 -0
- package/lib/adapter-check.js +102 -0
- package/lib/adapter-detect.js +125 -0
- package/lib/cli-args.js +5 -1
- package/lib/doctor.js +14 -4
- package/lib/gates.js +67 -1
- package/lib/generate-adapter.js +6 -30
- package/lib/guard-hooks.js +115 -0
- package/lib/guard.js +336 -0
- package/lib/host-skill-build.js +10 -0
- package/lib/hosts/commands.js +5 -4
- package/lib/hosts/doctor.js +4 -3
- package/lib/hosts/registry.js +69 -23
- package/lib/hosts/table.js +15 -5
- package/lib/impact-map.js +501 -0
- package/lib/learn.js +303 -0
- package/lib/orchestration.js +39 -6
- package/lib/receipt.js +362 -0
- package/lib/safe-context.js +14 -0
- package/lib/smart-context.js +21 -0
- package/lib/studio-server.js +1 -0
- package/lib/sync-hosts.js +2 -1
- package/package.json +1 -1
- package/schemas/delivery.schema.json +11 -1
- package/schemas/finding-ledger.schema.json +2 -1
- package/schemas/goal-contract.schema.json +9 -0
- package/schemas/impact-map.schema.json +78 -0
- package/schemas/learnings.schema.json +47 -0
- package/schemas/receipt.schema.json +102 -0
- package/schemas/report.schema.json +52 -5
package/lib/hosts/table.js
CHANGED
|
@@ -2,24 +2,34 @@
|
|
|
2
2
|
|
|
3
3
|
// README host table generated from the registry (#52); `npm test` fails on drift.
|
|
4
4
|
|
|
5
|
-
const { HOSTS, OUT_OF_SCOPE, SHARED_SKILLS_DIR, usesSharedSkills } = require('./registry.js');
|
|
5
|
+
const { HOSTS, OUT_OF_SCOPE, SHARED_SKILLS_DIR, guardrailSupport, usesSharedSkills } = require('./registry.js');
|
|
6
6
|
|
|
7
7
|
const START = '<!-- hosts-table:start (generated from lib/hosts/registry.js; run npm run build:hosts-table) -->';
|
|
8
8
|
const END = '<!-- hosts-table:end -->';
|
|
9
9
|
|
|
10
|
+
// `full (default, v1.16.0, 2026-10-20)` when certified, else the bare tier.
|
|
11
|
+
function certificationLabel(host) {
|
|
12
|
+
const by = host.certifiedBy;
|
|
13
|
+
return by ? `${host.certification} (${by.recipe}, v${by.aelVersion}, ${by.date})` : host.certification;
|
|
14
|
+
}
|
|
15
|
+
|
|
10
16
|
function renderHostTable() {
|
|
11
17
|
const rows = HOSTS.map((host) => {
|
|
12
18
|
const skills = usesSharedSkills(host) ? `\`~/${SHARED_SKILLS_DIR}\` (shared)` : `\`~/${host.skills.dir}\``;
|
|
13
19
|
const agents = host.agents ? `\`~/${host.agents.dir}\`` : 'none (in-session review)';
|
|
14
20
|
const detect = [...host.detect.dirs.map((d) => `\`~/${d}\``), ...(host.detect.bins || []).map((b) => `\`${b}\``)].join(', ');
|
|
15
|
-
return `| ${host.name} | \`${host.id}\` | ${skills} | ${agents} | ${detect} |`;
|
|
21
|
+
return `| ${host.name} | \`${host.id}\` | ${certificationLabel(host)} | ${guardrailSupport(host)} | ${skills} | ${agents} | ${detect} |`;
|
|
16
22
|
});
|
|
17
23
|
return [
|
|
18
24
|
START,
|
|
19
|
-
'| Host | id | Skill folder | Reviewer agents | Detected by |',
|
|
20
|
-
'
|
|
25
|
+
'| Host | id | Certification | Guardrails | Skill folder | Reviewer agents | Detected by |',
|
|
26
|
+
'|---|---|---|---|---|---|---|',
|
|
21
27
|
...rows,
|
|
22
28
|
'',
|
|
29
|
+
'Certification: **full** = a real `default` recipe run with reviewer subagents and every gate is recorded for this host; **experimental** = reviewer subagents install, no recorded run; **instruction-only** = no subagents, review runs in-session (`CONTEXT_ISOLATION_ONLY`; compact digest: `npx ai-engineering-loop docs AGENTS`).',
|
|
30
|
+
'',
|
|
31
|
+
'Guardrails: **enforced** = `npx ai-engineering-loop hooks install` adds native pre-tool hooks that check scope and destructive commands; **advisory** = the host has no hook API, so the guardrail is the loop instructions only.',
|
|
32
|
+
'',
|
|
23
33
|
`Not supported (no native skills): ${OUT_OF_SCOPE.map((h) => h.name).join(', ')}.`,
|
|
24
34
|
END
|
|
25
35
|
].join('\n');
|
|
@@ -32,4 +42,4 @@ function replaceHostTable(text) {
|
|
|
32
42
|
return text.slice(0, start) + renderHostTable() + text.slice(end + END.length);
|
|
33
43
|
}
|
|
34
44
|
|
|
35
|
-
module.exports = { START, END, renderHostTable, replaceHostTable };
|
|
45
|
+
module.exports = { START, END, certificationLabel, renderHostTable, replaceHostTable };
|
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Blast-radius impact map (#71). A deterministic, heuristic scan of the
|
|
4
|
+
// frozen Goal against the repository index, written to the Run before
|
|
5
|
+
// Stage 3 (Maker). A human confirms or edits it; the confirmed paths become
|
|
6
|
+
// the Run's allowed scope (#59), and verify reports drift outside it.
|
|
7
|
+
|
|
8
|
+
const crypto = require('crypto');
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const { atomicWriteJson, getCurrentRun, loadRun, runsDir } = require('./run-state.js');
|
|
12
|
+
const { sha256 } = require('./recipe.js');
|
|
13
|
+
|
|
14
|
+
const IMPACT_MAP_FILE = 'impact-map.json';
|
|
15
|
+
const IMPACT_DRIFT_FILE = 'impact-drift.json';
|
|
16
|
+
const MAP_STATUSES = Object.freeze(['DRAFT', 'CONFIRMED', 'SKIPPED']);
|
|
17
|
+
const DEFAULT_FILE_LIMIT = 20;
|
|
18
|
+
const MAX_SCAN_BYTES = 256 * 1024;
|
|
19
|
+
const MAX_ENTRIES = 50;
|
|
20
|
+
|
|
21
|
+
// English + Indonesian filler words; never used as match keywords.
|
|
22
|
+
const STOPWORDS = new Set([
|
|
23
|
+
'the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'when', 'then', 'than', 'must', 'should',
|
|
24
|
+
'will', 'shall', 'have', 'has', 'are', 'was', 'were', 'not', 'only', 'each', 'every', 'any', 'all',
|
|
25
|
+
'returns', 'return', 'show', 'shows', 'make', 'makes', 'add', 'adds', 'new', 'use', 'uses', 'used',
|
|
26
|
+
'can', 'cannot', 'does', 'still', 'also', 'more', 'less', 'after', 'before', 'without', 'within',
|
|
27
|
+
'yang', 'dan', 'untuk', 'dengan', 'dari', 'pada', 'harus', 'tidak', 'akan', 'bisa', 'atau', 'ini', 'itu',
|
|
28
|
+
'saat', 'jika', 'kalau', 'agar', 'supaya', 'sudah', 'belum', 'tambah', 'buat', 'ubah'
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
const TEST_PATH = /(^|\/)(tests?|__tests__|spec|specs)\/|\.(test|spec)\.[a-z0-9]+$/i;
|
|
32
|
+
const MIGRATION_PATH = /(^|\/)(migrations?|migrate|db\/migrate)\/|\.sql$/i;
|
|
33
|
+
const ROUTE_PATTERNS = [
|
|
34
|
+
/\b(?:app|router|server|route|api)\.(get|post|put|patch|delete)\(\s*['"`]([^'"`]+)['"`]/gi,
|
|
35
|
+
/@(Get|Post|Put|Patch|Delete)\(\s*['"`]([^'"`]*)['"`]/g
|
|
36
|
+
];
|
|
37
|
+
const TABLE_PATTERN = /\b(?:create|alter|drop)\s+table\s+(?:if\s+(?:not\s+)?exists\s+)?[`"']?([A-Za-z_][\w.]*)/gi;
|
|
38
|
+
|
|
39
|
+
function impactError(message, code = 'IMPACT_MAP_ERROR', details = []) {
|
|
40
|
+
const error = new Error(message);
|
|
41
|
+
error.code = code;
|
|
42
|
+
error.details = details;
|
|
43
|
+
return error;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function resolveRun(rootDir, runId) {
|
|
47
|
+
if (runId) return loadRun(rootDir, runId);
|
|
48
|
+
const current = getCurrentRun(rootDir);
|
|
49
|
+
if (!current) throw impactError('No current Run. Pass --run <id>.', 'NO_CURRENT_RUN');
|
|
50
|
+
return current;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function mapPath(rootDir, runId) {
|
|
54
|
+
return path.join(runsDir(rootDir), runId, IMPACT_MAP_FILE);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function driftPath(rootDir, runId) {
|
|
58
|
+
return path.join(runsDir(rootDir), runId, IMPACT_DRIFT_FILE);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function relative(rootDir, filePath) {
|
|
62
|
+
return path.relative(rootDir, filePath).split(path.sep).join('/');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function normalizeRepoPath(value) {
|
|
66
|
+
return String(value || '').trim().replace(/\\/g, '/').replace(/^\.\/+/, '');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// `**` crosses directories, `*` and `?` stay inside one segment, a trailing
|
|
70
|
+
// `/` means "this directory and everything below it".
|
|
71
|
+
function globToRegExp(pattern) {
|
|
72
|
+
const glob = normalizeRepoPath(pattern);
|
|
73
|
+
if (glob.endsWith('/')) return globToRegExp(`${glob}**`);
|
|
74
|
+
let source = '';
|
|
75
|
+
for (let index = 0; index < glob.length; index += 1) {
|
|
76
|
+
const char = glob[index];
|
|
77
|
+
if (char === '*' && glob[index + 1] === '*') {
|
|
78
|
+
const slash = glob[index + 2] === '/';
|
|
79
|
+
source += slash ? '(?:.*/)?' : '.*';
|
|
80
|
+
index += slash ? 2 : 1;
|
|
81
|
+
} else if (char === '*') {
|
|
82
|
+
source += '[^/]*';
|
|
83
|
+
} else if (char === '?') {
|
|
84
|
+
source += '[^/]';
|
|
85
|
+
} else {
|
|
86
|
+
source += char.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return new RegExp(`^${source}$`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function matchesGlob(filePath, pattern) {
|
|
93
|
+
return globToRegExp(pattern).test(normalizeRepoPath(filePath));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function matchesAnyGlob(filePath, patterns) {
|
|
97
|
+
return (patterns || []).some((pattern) => matchesGlob(filePath, pattern));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function readGoal(rootDir, run) {
|
|
101
|
+
const filePath = path.join(runsDir(rootDir), run.runId, 'goal-contract.json');
|
|
102
|
+
if (!run.goal?.frozen && !run.artifacts?.goalContract) {
|
|
103
|
+
throw impactError('The impact map needs a frozen Goal. Freeze the Goal first.', 'GOAL_NOT_FROZEN');
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
107
|
+
} catch (cause) {
|
|
108
|
+
throw impactError(`Unable to read the frozen Goal: ${cause.message}`, 'GOAL_NOT_FROZEN');
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function goalKeywords(goal) {
|
|
113
|
+
const text = [
|
|
114
|
+
goal.objective,
|
|
115
|
+
...(goal.acceptanceCriteria || []).flatMap((criterion) => [criterion.statement, ...(criterion.failureCases || [])])
|
|
116
|
+
].join(' ');
|
|
117
|
+
const words = text
|
|
118
|
+
.replace(/([a-z])([A-Z])/g, '$1 $2')
|
|
119
|
+
.toLowerCase()
|
|
120
|
+
.split(/[^a-z0-9]+/)
|
|
121
|
+
.filter((word) => word.length >= 3 && !STOPWORDS.has(word) && !/^\d+$/.test(word));
|
|
122
|
+
return [...new Set(words)].sort();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function tokensOf(value) {
|
|
126
|
+
return String(value || '')
|
|
127
|
+
.replace(/([a-z])([A-Z])/g, '$1 $2')
|
|
128
|
+
.toLowerCase()
|
|
129
|
+
.split(/[^a-z0-9]+/)
|
|
130
|
+
.filter((token) => token.length >= 3);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Keyword vs token match; a 4+ letter keyword also matches a plural/suffixed
|
|
134
|
+
// token ("page" ~ "pages", "pagination" ~ "paginate" share a 6-letter stem).
|
|
135
|
+
function keywordHits(keywords, tokens) {
|
|
136
|
+
const set = new Set(tokens);
|
|
137
|
+
return keywords.filter((keyword) => set.has(keyword) || tokens.some((token) => (
|
|
138
|
+
(keyword.length >= 4 && token.startsWith(keyword)) ||
|
|
139
|
+
(token.length >= 4 && keyword.startsWith(token)) ||
|
|
140
|
+
(keyword.length >= 6 && token.length >= 6 && keyword.slice(0, 6) === token.slice(0, 6))
|
|
141
|
+
)));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function loadIndex(rootDir) {
|
|
145
|
+
try {
|
|
146
|
+
const { buildContextIndex } = require('./smart-context.js');
|
|
147
|
+
return { files: buildContextIndex(rootDir).index.files, warning: null };
|
|
148
|
+
} catch (cause) {
|
|
149
|
+
return { files: [], warning: `Repository index unavailable: ${cause.message}` };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function readBounded(rootDir, relativePath) {
|
|
154
|
+
try {
|
|
155
|
+
const absolute = path.join(rootDir, relativePath);
|
|
156
|
+
const stat = fs.lstatSync(absolute);
|
|
157
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_SCAN_BYTES) return '';
|
|
158
|
+
const raw = fs.readFileSync(absolute);
|
|
159
|
+
return raw.includes(0) ? '' : raw.toString('utf8');
|
|
160
|
+
} catch {
|
|
161
|
+
return '';
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function confidence(score, top) {
|
|
166
|
+
if (!top) return 0;
|
|
167
|
+
return Math.round(Math.min(0.95, Math.max(0.1, score / top)) * 100) / 100;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function stem(relativePath) {
|
|
171
|
+
return path.posix.basename(relativePath).replace(/\.(test|spec)(?=\.)/i, '').replace(/\.[^.]+$/, '').toLowerCase();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function scoreFiles(index, keywords) {
|
|
175
|
+
return index
|
|
176
|
+
.map((file) => {
|
|
177
|
+
const pathHits = keywordHits(keywords, tokensOf(file.path));
|
|
178
|
+
const symbolHits = keywordHits(keywords, (file.symbols || []).flatMap(tokensOf))
|
|
179
|
+
.filter((keyword) => !pathHits.includes(keyword));
|
|
180
|
+
return { file, pathHits, symbolHits, score: pathHits.length * 3 + symbolHits.length * 2 };
|
|
181
|
+
})
|
|
182
|
+
.filter((entry) => entry.score > 0)
|
|
183
|
+
.sort((left, right) => right.score - left.score || left.file.path.localeCompare(right.file.path));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function reasonFor({ pathHits, symbolHits }) {
|
|
187
|
+
const parts = [];
|
|
188
|
+
if (pathHits.length) parts.push(`path matches ${pathHits.join(', ')}`);
|
|
189
|
+
if (symbolHits.length) parts.push(`symbols match ${symbolHits.join(', ')}`);
|
|
190
|
+
return parts.join('; ');
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function buildImpactMap(rootDir, { run, goal, limit = DEFAULT_FILE_LIMIT, now = new Date() }) {
|
|
194
|
+
const keywords = goalKeywords(goal);
|
|
195
|
+
const { files: index, warning } = loadIndex(rootDir);
|
|
196
|
+
const scored = scoreFiles(index, keywords);
|
|
197
|
+
const top = scored[0]?.score || 0;
|
|
198
|
+
const sourceHits = scored.filter((entry) => !TEST_PATH.test(entry.file.path) && !MIGRATION_PATH.test(entry.file.path)).slice(0, limit);
|
|
199
|
+
const files = sourceHits.map((entry) => ({
|
|
200
|
+
path: entry.file.path,
|
|
201
|
+
confidence: confidence(entry.score, top),
|
|
202
|
+
reason: reasonFor(entry)
|
|
203
|
+
}));
|
|
204
|
+
|
|
205
|
+
const tests = new Map();
|
|
206
|
+
for (const entry of scored.filter((item) => TEST_PATH.test(item.file.path)).slice(0, limit)) {
|
|
207
|
+
tests.set(entry.file.path, { path: entry.file.path, confidence: confidence(entry.score, top), reason: reasonFor(entry) });
|
|
208
|
+
}
|
|
209
|
+
const sourceStems = new Map(files.map((file) => [stem(file.path), file.path]));
|
|
210
|
+
for (const file of index.filter((item) => TEST_PATH.test(item.path))) {
|
|
211
|
+
const target = sourceStems.get(stem(file.path));
|
|
212
|
+
if (target && !tests.has(file.path)) {
|
|
213
|
+
tests.set(file.path, { path: file.path, confidence: 0.6, reason: `test file named after ${target}` });
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const modules = new Map();
|
|
218
|
+
for (const file of files) {
|
|
219
|
+
const directory = path.posix.dirname(file.path);
|
|
220
|
+
const name = directory === '.' ? '.' : directory.split('/').slice(0, 2).join('/');
|
|
221
|
+
const current = modules.get(name);
|
|
222
|
+
if (!current) modules.set(name, { name, confidence: file.confidence, reason: `contains ${file.path}` });
|
|
223
|
+
else if (file.confidence > current.confidence) current.confidence = file.confidence;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const endpoints = [];
|
|
227
|
+
const dbTables = new Map();
|
|
228
|
+
for (const entry of scored.filter((item) => MIGRATION_PATH.test(item.file.path)).slice(0, limit)) {
|
|
229
|
+
dbTables.set(`migration:${entry.file.path}`, {
|
|
230
|
+
name: path.posix.basename(entry.file.path),
|
|
231
|
+
kind: 'migration',
|
|
232
|
+
path: entry.file.path,
|
|
233
|
+
confidence: confidence(entry.score, top),
|
|
234
|
+
reason: reasonFor(entry)
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
for (const entry of [...sourceHits, ...scored.filter((item) => MIGRATION_PATH.test(item.file.path)).slice(0, limit)]) {
|
|
238
|
+
const text = readBounded(rootDir, entry.file.path);
|
|
239
|
+
if (!text) continue;
|
|
240
|
+
for (const pattern of ROUTE_PATTERNS) {
|
|
241
|
+
for (const match of text.matchAll(pattern)) {
|
|
242
|
+
endpoints.push({
|
|
243
|
+
method: match[1].toUpperCase(),
|
|
244
|
+
route: match[2] || '/',
|
|
245
|
+
path: entry.file.path,
|
|
246
|
+
confidence: confidence(entry.score, top),
|
|
247
|
+
reason: `route declared in ${entry.file.path}`
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
for (const match of text.matchAll(TABLE_PATTERN)) {
|
|
252
|
+
const key = `table:${match[1].toLowerCase()}`;
|
|
253
|
+
if (!dbTables.has(key)) {
|
|
254
|
+
dbTables.set(key, {
|
|
255
|
+
name: match[1],
|
|
256
|
+
kind: 'table',
|
|
257
|
+
path: entry.file.path,
|
|
258
|
+
confidence: confidence(entry.score, top),
|
|
259
|
+
reason: `table statement in ${entry.file.path}`
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const byConfidence = (left, right) => right.confidence - left.confidence ||
|
|
266
|
+
String(left.path || left.name).localeCompare(String(right.path || right.name));
|
|
267
|
+
return {
|
|
268
|
+
schemaVersion: 1,
|
|
269
|
+
runId: run.runId,
|
|
270
|
+
goalHash: sha256(goal),
|
|
271
|
+
status: 'DRAFT',
|
|
272
|
+
generator: 'heuristic-v1',
|
|
273
|
+
generatedAt: now.toISOString(),
|
|
274
|
+
keywords,
|
|
275
|
+
...(warning ? { warnings: [warning] } : {}),
|
|
276
|
+
files,
|
|
277
|
+
modules: [...modules.values()].sort(byConfidence).slice(0, MAX_ENTRIES),
|
|
278
|
+
endpoints: endpoints.sort(byConfidence).slice(0, MAX_ENTRIES),
|
|
279
|
+
dbTables: [...dbTables.values()].sort(byConfidence).slice(0, MAX_ENTRIES),
|
|
280
|
+
tests: [...tests.values()].sort(byConfidence).slice(0, MAX_ENTRIES),
|
|
281
|
+
scope: null
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function loadImpactMap(rootDir, runId) {
|
|
286
|
+
const filePath = mapPath(rootDir, runId);
|
|
287
|
+
if (!fs.existsSync(filePath)) return null;
|
|
288
|
+
try {
|
|
289
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
290
|
+
} catch (cause) {
|
|
291
|
+
throw impactError(`impact-map.json is invalid: ${cause.message}`, 'INVALID_IMPACT_MAP');
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function validateImpactMap(map, run) {
|
|
296
|
+
const errors = [];
|
|
297
|
+
if (!map || typeof map !== 'object' || Array.isArray(map)) return ['impact map must be an object'];
|
|
298
|
+
if (map.schemaVersion !== 1) errors.push('schemaVersion must be 1');
|
|
299
|
+
if (run && map.runId !== run.runId) errors.push(`runId must be ${run.runId}`);
|
|
300
|
+
if (!MAP_STATUSES.includes(map.status)) errors.push(`status must be one of ${MAP_STATUSES.join(', ')}`);
|
|
301
|
+
for (const key of ['files', 'modules', 'endpoints', 'dbTables', 'tests']) {
|
|
302
|
+
if (!Array.isArray(map[key])) {
|
|
303
|
+
errors.push(`${key} must be an array`);
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
map[key].forEach((entry, index) => {
|
|
307
|
+
if (!String(entry?.reason || '').trim()) errors.push(`${key}[${index}].reason is required`);
|
|
308
|
+
if (typeof entry?.confidence !== 'number' || entry.confidence < 0 || entry.confidence > 1) {
|
|
309
|
+
errors.push(`${key}[${index}].confidence must be between 0 and 1`);
|
|
310
|
+
}
|
|
311
|
+
if (!String(entry?.path || entry?.name || '').trim()) errors.push(`${key}[${index}] needs a path or name`);
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
if (map.status === 'SKIPPED' && !String(map.skipReason || '').trim()) errors.push('skipReason is required when SKIPPED');
|
|
315
|
+
if (map.status === 'CONFIRMED') {
|
|
316
|
+
if (!Array.isArray(map.scope?.allowedPaths)) errors.push('scope.allowedPaths is required when CONFIRMED');
|
|
317
|
+
if (!String(map.confirmedBy || '').trim()) errors.push('confirmedBy is required when CONFIRMED');
|
|
318
|
+
}
|
|
319
|
+
return errors;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function writeMap(rootDir, run, map) {
|
|
323
|
+
const errors = validateImpactMap(map, run);
|
|
324
|
+
if (errors.length) throw impactError('Impact map is invalid', 'INVALID_IMPACT_MAP', errors);
|
|
325
|
+
const filePath = mapPath(rootDir, run.runId);
|
|
326
|
+
atomicWriteJson(filePath, map);
|
|
327
|
+
return { map, path: relative(rootDir, filePath) };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function actorId(actor) {
|
|
331
|
+
const value = String(actor || '').trim();
|
|
332
|
+
if (!/^[A-Za-z0-9@._-]{1,64}$/.test(value)) {
|
|
333
|
+
throw impactError('--by <name> must be a short account identifier', 'INVALID_USAGE');
|
|
334
|
+
}
|
|
335
|
+
return value;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function generateImpactMap(rootDir, { runId, force = false, limit, now = new Date() } = {}) {
|
|
339
|
+
const run = resolveRun(rootDir, runId);
|
|
340
|
+
const existing = loadImpactMap(rootDir, run.runId);
|
|
341
|
+
if (existing && existing.status !== 'DRAFT' && !force) {
|
|
342
|
+
throw impactError(`Impact map is already ${existing.status}; pass --force to regenerate it`, 'IMPACT_MAP_LOCKED');
|
|
343
|
+
}
|
|
344
|
+
const goal = readGoal(rootDir, run);
|
|
345
|
+
return writeMap(rootDir, run, buildImpactMap(rootDir, { run, goal, limit, now }));
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function mappedPaths(map) {
|
|
349
|
+
return [...new Set([
|
|
350
|
+
...(map.files || []).map((entry) => entry.path),
|
|
351
|
+
...(map.tests || []).map((entry) => entry.path),
|
|
352
|
+
...(map.dbTables || []).filter((entry) => entry.kind === 'migration').map((entry) => entry.path)
|
|
353
|
+
].filter(Boolean).map(normalizeRepoPath))].sort();
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function confirmImpactMap(rootDir, { runId, by, allow = [], remove = [], now = new Date() } = {}) {
|
|
357
|
+
const run = resolveRun(rootDir, runId);
|
|
358
|
+
const map = loadImpactMap(rootDir, run.runId);
|
|
359
|
+
if (!map) throw impactError('No impact map yet. Run `impact map` first.', 'IMPACT_MAP_MISSING');
|
|
360
|
+
const goal = readGoal(rootDir, run);
|
|
361
|
+
if (map.goalHash !== sha256(goal)) {
|
|
362
|
+
throw impactError('Impact map was built for another Goal version; regenerate it with `impact map --force`', 'IMPACT_MAP_STALE');
|
|
363
|
+
}
|
|
364
|
+
const removed = new Set(remove.map(normalizeRepoPath));
|
|
365
|
+
const allowedPaths = [...new Set([...mappedPaths(map), ...allow.map(normalizeRepoPath)])]
|
|
366
|
+
.filter((entry) => entry && !removed.has(entry))
|
|
367
|
+
.sort();
|
|
368
|
+
const { skipReason: _skip, skippedBy: _by, skippedAt: _at, ...rest } = map;
|
|
369
|
+
return writeMap(rootDir, run, {
|
|
370
|
+
...rest,
|
|
371
|
+
status: 'CONFIRMED',
|
|
372
|
+
confirmedBy: actorId(by),
|
|
373
|
+
confirmedAt: now.toISOString(),
|
|
374
|
+
scope: { allowedPaths }
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function skipImpactMap(rootDir, { runId, by, reason, now = new Date() } = {}) {
|
|
379
|
+
const run = resolveRun(rootDir, runId);
|
|
380
|
+
const why = String(reason || '').trim();
|
|
381
|
+
if (!why || why.length > 500) throw impactError('--reason must be 1-500 characters', 'INVALID_USAGE');
|
|
382
|
+
const goal = readGoal(rootDir, run);
|
|
383
|
+
const existing = loadImpactMap(rootDir, run.runId);
|
|
384
|
+
return writeMap(rootDir, run, {
|
|
385
|
+
schemaVersion: 1,
|
|
386
|
+
runId: run.runId,
|
|
387
|
+
goalHash: sha256(goal),
|
|
388
|
+
status: 'SKIPPED',
|
|
389
|
+
generator: existing?.generator || 'heuristic-v1',
|
|
390
|
+
generatedAt: existing?.generatedAt || now.toISOString(),
|
|
391
|
+
keywords: existing?.keywords || goalKeywords(goal),
|
|
392
|
+
files: [],
|
|
393
|
+
modules: [],
|
|
394
|
+
endpoints: [],
|
|
395
|
+
dbTables: [],
|
|
396
|
+
tests: [],
|
|
397
|
+
scope: null,
|
|
398
|
+
skipReason: why,
|
|
399
|
+
skippedBy: actorId(by),
|
|
400
|
+
skippedAt: now.toISOString()
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Allowed scope for the guardrail (#59): only a CONFIRMED map defines one.
|
|
405
|
+
function impactScope(map) {
|
|
406
|
+
if (!map || map.status !== 'CONFIRMED' || !Array.isArray(map.scope?.allowedPaths)) return null;
|
|
407
|
+
return { allowedPaths: [...map.scope.allowedPaths] };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function changedFilesFromDiff(diff) {
|
|
411
|
+
const files = new Set();
|
|
412
|
+
for (const line of String(diff || '').split('\n')) {
|
|
413
|
+
const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
|
|
414
|
+
if (match) files.add(normalizeRepoPath(match[2]));
|
|
415
|
+
}
|
|
416
|
+
return [...files].filter((file) => !file.startsWith('.ai-engineering-loop/')).sort();
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// Diff the gated Maker diff against the map. DRAFT maps compare against the
|
|
420
|
+
// mapped paths but say so; SKIPPED or missing maps record no drift.
|
|
421
|
+
function detectImpactDrift(rootDir, { runId, now = new Date() } = {}) {
|
|
422
|
+
const run = resolveRun(rootDir, runId);
|
|
423
|
+
const diffFile = path.join(runsDir(rootDir), run.runId, 'diff.patch');
|
|
424
|
+
if (!fs.existsSync(diffFile)) throw impactError('No Maker diff to compare. Pass the Maker gate first.', 'MAKER_NOT_GATED');
|
|
425
|
+
const raw = fs.readFileSync(diffFile);
|
|
426
|
+
const diff = raw.toString('utf8');
|
|
427
|
+
const map = loadImpactMap(rootDir, run.runId);
|
|
428
|
+
const changedFiles = changedFilesFromDiff(diff);
|
|
429
|
+
let allowed = [];
|
|
430
|
+
if (map?.status === 'CONFIRMED') allowed = map.scope?.allowedPaths || [];
|
|
431
|
+
else if (map?.status === 'DRAFT') allowed = mappedPaths(map);
|
|
432
|
+
const compared = map && map.status !== 'SKIPPED';
|
|
433
|
+
const outOfMap = compared ? changedFiles.filter((file) => !matchesAnyGlob(file, allowed)) : [];
|
|
434
|
+
const drift = {
|
|
435
|
+
schemaVersion: 1,
|
|
436
|
+
runId: run.runId,
|
|
437
|
+
diffHash: crypto.createHash('sha256').update(raw).digest('hex'),
|
|
438
|
+
mapStatus: map ? map.status : 'MISSING',
|
|
439
|
+
...(map?.status === 'SKIPPED' ? { skipReason: map.skipReason } : {}),
|
|
440
|
+
checkedAt: now.toISOString(),
|
|
441
|
+
changedFiles,
|
|
442
|
+
outOfMap
|
|
443
|
+
};
|
|
444
|
+
const filePath = driftPath(rootDir, run.runId);
|
|
445
|
+
atomicWriteJson(filePath, drift);
|
|
446
|
+
return { drift, path: relative(rootDir, filePath) };
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function loadImpactDrift(rootDir, runId) {
|
|
450
|
+
const filePath = driftPath(rootDir, runId);
|
|
451
|
+
if (!fs.existsSync(filePath)) return null;
|
|
452
|
+
try {
|
|
453
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
454
|
+
} catch {
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function driftFindings(drift) {
|
|
460
|
+
return (drift?.outOfMap || []).map((file, index) => ({
|
|
461
|
+
id: `IMPACT-DRIFT-${index + 1}`,
|
|
462
|
+
axis: 'spec',
|
|
463
|
+
location: file,
|
|
464
|
+
failureScenario: `${file} changed outside the ${drift.mapStatus === 'CONFIRMED' ? 'confirmed' : 'unconfirmed'} blast-radius map; reviewers did not plan for its side effects`,
|
|
465
|
+
evidence: `${IMPACT_DRIFT_FILE} lists ${file} in outOfMap (map status ${drift.mapStatus})`,
|
|
466
|
+
severity: 'LOW',
|
|
467
|
+
validity: 'VALID',
|
|
468
|
+
disposition: 'ACCEPTABLE',
|
|
469
|
+
source: 'impact-map'
|
|
470
|
+
}));
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// Called by the review gate: drift becomes LOW ledger warnings, added once.
|
|
474
|
+
function mergeDriftIntoLedger(ledger, drift) {
|
|
475
|
+
if (!drift || drift.diffHash !== ledger.diffHash || !Array.isArray(ledger.findings)) return { ledger, added: 0 };
|
|
476
|
+
const present = new Set(ledger.findings.filter((item) => item.source === 'impact-map').map((item) => item.location));
|
|
477
|
+
const additions = driftFindings(drift).filter((item) => !present.has(item.location));
|
|
478
|
+
return { ledger: { ...ledger, findings: [...ledger.findings, ...additions] }, added: additions.length };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
module.exports = {
|
|
482
|
+
IMPACT_MAP_FILE,
|
|
483
|
+
IMPACT_DRIFT_FILE,
|
|
484
|
+
MAP_STATUSES,
|
|
485
|
+
globToRegExp,
|
|
486
|
+
matchesGlob,
|
|
487
|
+
matchesAnyGlob,
|
|
488
|
+
goalKeywords,
|
|
489
|
+
buildImpactMap,
|
|
490
|
+
generateImpactMap,
|
|
491
|
+
confirmImpactMap,
|
|
492
|
+
skipImpactMap,
|
|
493
|
+
loadImpactMap,
|
|
494
|
+
validateImpactMap,
|
|
495
|
+
impactScope,
|
|
496
|
+
changedFilesFromDiff,
|
|
497
|
+
detectImpactDrift,
|
|
498
|
+
loadImpactDrift,
|
|
499
|
+
driftFindings,
|
|
500
|
+
mergeDriftIntoLedger
|
|
501
|
+
};
|