ai-engineering-loop 1.9.4 → 1.11.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/devil-advocate.md +13 -1
- package/.agents/judge.md +10 -0
- package/.agents/workflows/ai-engineering-loop.md +4 -4
- package/.claude/agents/devil-advocate.md +13 -1
- package/.claude/agents/judge.md +10 -0
- package/.claude/skills/ai-engineering-loop/SKILL.md +4 -4
- package/.gemini/skills/ai-engineering-loop/SKILL.md +4 -4
- package/.grok/agents/devil-advocate.md +13 -1
- package/.grok/agents/judge.md +10 -0
- package/.grok/skills/ai-engineering-loop/SKILL.md +4 -4
- package/README.md +22 -0
- package/README.npm.md +4 -1
- package/agents/shared/devil-advocate.body.md +13 -1
- package/agents/shared/judge.body.md +10 -0
- package/bin/ai-engineering-loop.js +97 -6
- package/core/runtime-safety.md +26 -0
- package/lib/budget.js +35 -0
- package/lib/run-checkout.js +70 -10
- package/lib/run-journey.js +75 -0
- package/lib/run-lifecycle.js +40 -1
- package/lib/runtime-policy.js +24 -1
- package/lib/safe-context.js +43 -7
- package/lib/smart-context.js +384 -0
- package/lib/studio-runtime.js +1 -1
- package/lib/studio-server.js +20 -3
- package/lib/verification-summary.js +130 -0
- package/package.json +1 -1
- package/policies/review-budget.md +12 -0
- package/studio/app.js +149 -23
- package/studio/index.html +30 -5
- package/studio/styles.css +7 -0
package/lib/runtime-policy.js
CHANGED
|
@@ -10,6 +10,7 @@ const {
|
|
|
10
10
|
const DEFAULT_POLICY = Object.freeze({
|
|
11
11
|
schemaVersion: 1,
|
|
12
12
|
defaultMode: RUN_MODES.ASSISTED,
|
|
13
|
+
reviewProfile: 'lean',
|
|
13
14
|
allowUnattended: false,
|
|
14
15
|
requireSandboxForUnattended: true,
|
|
15
16
|
perRunTokenLimit: 50_000,
|
|
@@ -17,6 +18,8 @@ const DEFAULT_POLICY = Object.freeze({
|
|
|
17
18
|
killSwitch: false
|
|
18
19
|
});
|
|
19
20
|
|
|
21
|
+
const REVIEW_PROFILES = Object.freeze(['lean', 'standard', 'thorough']);
|
|
22
|
+
|
|
20
23
|
function policyPath(rootDir) {
|
|
21
24
|
return path.join(rootDir, '.ai-engineering-loop', 'runtime-policy.json');
|
|
22
25
|
}
|
|
@@ -32,6 +35,17 @@ function normalizeMode(value, fallback = null) {
|
|
|
32
35
|
return RUN_MODES[normalized];
|
|
33
36
|
}
|
|
34
37
|
|
|
38
|
+
function normalizeReviewProfile(value, fallback = DEFAULT_POLICY.reviewProfile) {
|
|
39
|
+
if (value == null || value === '') return fallback;
|
|
40
|
+
const normalized = String(value).trim().replace(/_/g, '-').toLowerCase();
|
|
41
|
+
if (!REVIEW_PROFILES.includes(normalized)) {
|
|
42
|
+
const err = new Error(`Unknown reviewProfile: ${value}. Use ${REVIEW_PROFILES.join('|')}`);
|
|
43
|
+
err.code = 'INVALID_REVIEW_PROFILE';
|
|
44
|
+
throw err;
|
|
45
|
+
}
|
|
46
|
+
return normalized;
|
|
47
|
+
}
|
|
48
|
+
|
|
35
49
|
function validatePolicy(value) {
|
|
36
50
|
const errors = [];
|
|
37
51
|
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
@@ -43,6 +57,11 @@ function validatePolicy(value) {
|
|
|
43
57
|
} catch (cause) {
|
|
44
58
|
errors.push(cause.message);
|
|
45
59
|
}
|
|
60
|
+
try {
|
|
61
|
+
normalizeReviewProfile(value.reviewProfile);
|
|
62
|
+
} catch (cause) {
|
|
63
|
+
errors.push(cause.message);
|
|
64
|
+
}
|
|
46
65
|
for (const key of ['allowUnattended', 'requireSandboxForUnattended', 'killSwitch']) {
|
|
47
66
|
if (typeof value[key] !== 'boolean') errors.push(`${key} must be boolean`);
|
|
48
67
|
}
|
|
@@ -74,12 +93,12 @@ function loadPolicy(rootDir) {
|
|
|
74
93
|
throw err;
|
|
75
94
|
}
|
|
76
95
|
policy.defaultMode = normalizeMode(policy.defaultMode);
|
|
96
|
+
policy.reviewProfile = normalizeReviewProfile(policy.reviewProfile);
|
|
77
97
|
return policy;
|
|
78
98
|
}
|
|
79
99
|
|
|
80
100
|
function writePolicy(rootDir, policy) {
|
|
81
101
|
const next = { ...DEFAULT_POLICY, ...policy, schemaVersion: 1 };
|
|
82
|
-
next.defaultMode = normalizeMode(next.defaultMode);
|
|
83
102
|
const errors = validatePolicy(next);
|
|
84
103
|
if (errors.length) {
|
|
85
104
|
const err = new Error(`Invalid runtime policy: ${errors.join('; ')}`);
|
|
@@ -87,6 +106,8 @@ function writePolicy(rootDir, policy) {
|
|
|
87
106
|
err.details = errors;
|
|
88
107
|
throw err;
|
|
89
108
|
}
|
|
109
|
+
next.defaultMode = normalizeMode(next.defaultMode);
|
|
110
|
+
next.reviewProfile = normalizeReviewProfile(next.reviewProfile);
|
|
90
111
|
atomicWriteJson(policyPath(rootDir), next);
|
|
91
112
|
return next;
|
|
92
113
|
}
|
|
@@ -108,8 +129,10 @@ function assertModeAllowed(rootDir, mode) {
|
|
|
108
129
|
|
|
109
130
|
module.exports = {
|
|
110
131
|
DEFAULT_POLICY,
|
|
132
|
+
REVIEW_PROFILES,
|
|
111
133
|
policyPath,
|
|
112
134
|
normalizeMode,
|
|
135
|
+
normalizeReviewProfile,
|
|
113
136
|
validatePolicy,
|
|
114
137
|
loadPolicy,
|
|
115
138
|
writePolicy,
|
package/lib/safe-context.js
CHANGED
|
@@ -5,12 +5,26 @@ const fs = require('fs');
|
|
|
5
5
|
const path = require('path');
|
|
6
6
|
const { atomicWriteJson, getCurrentRun, loadRun, runsDir } = require('./run-state.js');
|
|
7
7
|
const { assertBudgetAvailable } = require('./budget.js');
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
const { loadPolicy, normalizeReviewProfile } = require('./runtime-policy.js');
|
|
9
|
+
|
|
10
|
+
const CONTEXT_PROFILE_LIMITS = Object.freeze({
|
|
11
|
+
lean: Object.freeze({
|
|
12
|
+
maker: Object.freeze({ maxFiles: 8, maxFileBytes: 16_000, maxTotalBytes: 48_000, maxEstimatedTokens: 12_000 }),
|
|
13
|
+
'devil-advocate': Object.freeze({ maxFiles: 6, maxFileBytes: 8_000, maxTotalBytes: 24_000, maxEstimatedTokens: 6_000 }),
|
|
14
|
+
judge: Object.freeze({ maxFiles: 3, maxFileBytes: 4_000, maxTotalBytes: 12_000, maxEstimatedTokens: 3_000 })
|
|
15
|
+
}),
|
|
16
|
+
standard: Object.freeze({
|
|
17
|
+
maker: Object.freeze({ maxFiles: 10, maxFileBytes: 24_000, maxTotalBytes: 72_000, maxEstimatedTokens: 18_000 }),
|
|
18
|
+
'devil-advocate': Object.freeze({ maxFiles: 8, maxFileBytes: 12_000, maxTotalBytes: 48_000, maxEstimatedTokens: 12_000 }),
|
|
19
|
+
judge: Object.freeze({ maxFiles: 3, maxFileBytes: 8_000, maxTotalBytes: 24_000, maxEstimatedTokens: 6_000 })
|
|
20
|
+
}),
|
|
21
|
+
thorough: Object.freeze({
|
|
22
|
+
maker: Object.freeze({ maxFiles: 12, maxFileBytes: 32_000, maxTotalBytes: 96_000, maxEstimatedTokens: 24_000 }),
|
|
23
|
+
'devil-advocate': Object.freeze({ maxFiles: 8, maxFileBytes: 16_000, maxTotalBytes: 64_000, maxEstimatedTokens: 16_000 }),
|
|
24
|
+
judge: Object.freeze({ maxFiles: 3, maxFileBytes: 12_000, maxTotalBytes: 32_000, maxEstimatedTokens: 8_000 })
|
|
25
|
+
})
|
|
13
26
|
});
|
|
27
|
+
const STAGE_LIMITS = CONTEXT_PROFILE_LIMITS.lean;
|
|
14
28
|
|
|
15
29
|
const SENSITIVE_NAMES = [
|
|
16
30
|
/^\.env(?:\.|$)/i,
|
|
@@ -89,6 +103,16 @@ function redactSecrets(input) {
|
|
|
89
103
|
return { text, categories: [...categories].sort() };
|
|
90
104
|
}
|
|
91
105
|
|
|
106
|
+
function redactHomePaths(input) {
|
|
107
|
+
return String(input ?? '')
|
|
108
|
+
.replace(/(?:file:\/\/)?\/Users\/[A-Za-z0-9._-]+/g, '[REDACTED HOME]')
|
|
109
|
+
.replace(/(?:file:\/\/)?\/home\/[A-Za-z0-9._-]+/g, '[REDACTED HOME]')
|
|
110
|
+
.replace(/(?:file:\/\/)?\/root(?=\/|\\|$)/g, '[REDACTED HOME]')
|
|
111
|
+
.replace(/(?:file:\/\/)?(?:\/private)?\/var\/folders\/[A-Za-z0-9._/-]+/g, '[REDACTED TMP]')
|
|
112
|
+
.replace(/\b[A-Za-z]:\\Users\\[A-Za-z0-9._-]+/g, '[REDACTED HOME]')
|
|
113
|
+
.replace(/\\\\[A-Za-z0-9._-]+\\[A-Za-z0-9._$-]+/g, '[REDACTED HOME]');
|
|
114
|
+
}
|
|
115
|
+
|
|
92
116
|
function sha256(content) {
|
|
93
117
|
return crypto.createHash('sha256').update(content).digest('hex');
|
|
94
118
|
}
|
|
@@ -104,11 +128,18 @@ function resolveRun(rootDir, runId) {
|
|
|
104
128
|
return current;
|
|
105
129
|
}
|
|
106
130
|
|
|
107
|
-
function
|
|
108
|
-
const
|
|
131
|
+
function contextLimitsForProfile(profile, stage) {
|
|
132
|
+
const reviewProfile = normalizeReviewProfile(profile);
|
|
133
|
+
const limits = CONTEXT_PROFILE_LIMITS[reviewProfile]?.[stage];
|
|
109
134
|
if (!limits) {
|
|
110
135
|
throw contextError(`Unknown context stage: ${stage}. Use ${Object.keys(STAGE_LIMITS).join('|')}`, 'UNKNOWN_CONTEXT_STAGE');
|
|
111
136
|
}
|
|
137
|
+
return { reviewProfile, limits };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function createContextPack(rootDir, { runId, stage, files, profile } = {}) {
|
|
141
|
+
const policy = loadPolicy(rootDir);
|
|
142
|
+
const { reviewProfile, limits } = contextLimitsForProfile(profile || policy.reviewProfile, stage);
|
|
112
143
|
const run = resolveRun(rootDir, runId);
|
|
113
144
|
assertBudgetAvailable(rootDir, { runId: run.runId });
|
|
114
145
|
const uniqueFiles = [...new Set((files || []).map((file) => String(file).trim()).filter(Boolean))];
|
|
@@ -154,6 +185,7 @@ function createContextPack(rootDir, { runId, stage, files } = {}) {
|
|
|
154
185
|
schemaVersion: 1,
|
|
155
186
|
runId: run.runId,
|
|
156
187
|
stage,
|
|
188
|
+
reviewProfile,
|
|
157
189
|
createdAt: new Date().toISOString(),
|
|
158
190
|
transcriptInherited: false,
|
|
159
191
|
limits,
|
|
@@ -174,6 +206,7 @@ function contextPackSummary(result) {
|
|
|
174
206
|
schemaVersion: result.pack.schemaVersion,
|
|
175
207
|
runId: result.pack.runId,
|
|
176
208
|
stage: result.pack.stage,
|
|
209
|
+
reviewProfile: result.pack.reviewProfile,
|
|
177
210
|
path: result.path,
|
|
178
211
|
files: result.pack.entries.length,
|
|
179
212
|
totalBytes: result.pack.totalBytes,
|
|
@@ -184,10 +217,13 @@ function contextPackSummary(result) {
|
|
|
184
217
|
}
|
|
185
218
|
|
|
186
219
|
module.exports = {
|
|
220
|
+
CONTEXT_PROFILE_LIMITS,
|
|
187
221
|
STAGE_LIMITS,
|
|
222
|
+
contextLimitsForProfile,
|
|
188
223
|
isSensitivePath,
|
|
189
224
|
resolveSafeRepoFile,
|
|
190
225
|
redactSecrets,
|
|
226
|
+
redactHomePaths,
|
|
191
227
|
estimateTokens,
|
|
192
228
|
createContextPack,
|
|
193
229
|
contextPackSummary
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { execFileSync } = require('child_process');
|
|
7
|
+
const { atomicWriteJson, getCurrentRun, loadRun, runsDir } = require('./run-state.js');
|
|
8
|
+
const { assertBudgetAvailable } = require('./budget.js');
|
|
9
|
+
const { ensurePrivateRuntimeIgnores } = require('./runtime-files.js');
|
|
10
|
+
const {
|
|
11
|
+
CONTEXT_PROFILE_LIMITS,
|
|
12
|
+
estimateTokens,
|
|
13
|
+
isSensitivePath,
|
|
14
|
+
redactSecrets,
|
|
15
|
+
resolveSafeRepoFile
|
|
16
|
+
} = require('./safe-context.js');
|
|
17
|
+
const { loadPolicy, normalizeReviewProfile } = require('./runtime-policy.js');
|
|
18
|
+
|
|
19
|
+
const DIFF_PACK_LIMITS = Object.freeze({
|
|
20
|
+
lean: Object.freeze({ maxFiles: 20, maxHunksPerFile: 8, maxHunkBytes: 4_000, maxTotalBytes: 32_000 }),
|
|
21
|
+
standard: Object.freeze({ maxFiles: 35, maxHunksPerFile: 12, maxHunkBytes: 8_000, maxTotalBytes: 64_000 }),
|
|
22
|
+
thorough: Object.freeze({ maxFiles: 60, maxHunksPerFile: 20, maxHunkBytes: 12_000, maxTotalBytes: 128_000 })
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
function smartContextError(message, code = 'SMART_CONTEXT_ERROR') {
|
|
26
|
+
const err = new Error(message);
|
|
27
|
+
err.code = code;
|
|
28
|
+
return err;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function sha256(content) {
|
|
32
|
+
return crypto.createHash('sha256').update(content).digest('hex');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function contextRoot(rootDir) {
|
|
36
|
+
return path.join(rootDir, '.ai-engineering-loop', 'context');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function summaryCacheDir(rootDir) {
|
|
40
|
+
return path.join(contextRoot(rootDir), 'files');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function git(rootDir, args) {
|
|
44
|
+
return execFileSync('git', args, {
|
|
45
|
+
cwd: rootDir,
|
|
46
|
+
encoding: 'utf8',
|
|
47
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function listTrackedFiles(rootDir) {
|
|
52
|
+
return git(rootDir, ['ls-files'])
|
|
53
|
+
.split('\n')
|
|
54
|
+
.map((line) => line.trim())
|
|
55
|
+
.filter(Boolean)
|
|
56
|
+
.filter((relativePath) => !isSensitivePath(relativePath));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function languageFor(relativePath) {
|
|
60
|
+
const extension = path.extname(relativePath).replace(/^\./, '').toLowerCase();
|
|
61
|
+
return extension || 'text';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function extractSymbols(relativePath, text) {
|
|
65
|
+
const symbols = [];
|
|
66
|
+
const patterns = [
|
|
67
|
+
/\bfunction\s+([A-Za-z_$][\w$]*)\s*\(/g,
|
|
68
|
+
/\bclass\s+([A-Za-z_$][\w$]*)\b/g,
|
|
69
|
+
/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g,
|
|
70
|
+
/\bexports\.([A-Za-z_$][\w$]*)\s*=/g,
|
|
71
|
+
/\bmodule\.exports\.([A-Za-z_$][\w$]*)\s*=/g,
|
|
72
|
+
/^#{1,6}\s+(.+)$/gm
|
|
73
|
+
];
|
|
74
|
+
for (const pattern of patterns) {
|
|
75
|
+
for (const match of text.matchAll(pattern)) {
|
|
76
|
+
const symbol = String(match[1] || '').trim();
|
|
77
|
+
if (symbol && !symbols.includes(symbol)) symbols.push(symbol);
|
|
78
|
+
if (symbols.length >= 20) return symbols;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (symbols.length === 0 && ['json', 'md', 'txt'].includes(languageFor(relativePath))) {
|
|
82
|
+
const firstLine = text.split('\n').find((line) => line.trim());
|
|
83
|
+
if (firstLine) symbols.push(firstLine.trim().slice(0, 80));
|
|
84
|
+
}
|
|
85
|
+
return symbols;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function summarizeFile(rootDir, relativePath) {
|
|
89
|
+
const safe = resolveSafeRepoFile(rootDir, relativePath);
|
|
90
|
+
const raw = fs.readFileSync(safe.absolute);
|
|
91
|
+
const sourceSha = sha256(raw);
|
|
92
|
+
const cached = readCachedSummary(rootDir, sourceSha);
|
|
93
|
+
if (cached) return { ...cached, path: safe.relative, cacheHit: true };
|
|
94
|
+
if (raw.includes(0)) {
|
|
95
|
+
const summary = {
|
|
96
|
+
path: safe.relative,
|
|
97
|
+
binary: true,
|
|
98
|
+
sourceSha256: sourceSha,
|
|
99
|
+
sourceBytes: raw.length,
|
|
100
|
+
language: languageFor(safe.relative),
|
|
101
|
+
lines: null,
|
|
102
|
+
symbols: []
|
|
103
|
+
};
|
|
104
|
+
writeCachedSummary(rootDir, summary);
|
|
105
|
+
return { ...summary, cacheHit: false };
|
|
106
|
+
}
|
|
107
|
+
const text = raw.toString('utf8');
|
|
108
|
+
const summary = {
|
|
109
|
+
path: safe.relative,
|
|
110
|
+
binary: false,
|
|
111
|
+
sourceSha256: sourceSha,
|
|
112
|
+
sourceBytes: raw.length,
|
|
113
|
+
language: languageFor(safe.relative),
|
|
114
|
+
lines: text.length === 0 ? 0 : text.split('\n').length,
|
|
115
|
+
symbols: extractSymbols(safe.relative, text)
|
|
116
|
+
};
|
|
117
|
+
writeCachedSummary(rootDir, summary);
|
|
118
|
+
return { ...summary, cacheHit: false };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function readCachedSummary(rootDir, sourceSha) {
|
|
122
|
+
const filePath = path.join(summaryCacheDir(rootDir), `${sourceSha}.json`);
|
|
123
|
+
if (!fs.existsSync(filePath)) return null;
|
|
124
|
+
try {
|
|
125
|
+
const cached = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
126
|
+
if (cached.sourceSha256 !== sourceSha) return null;
|
|
127
|
+
return cached;
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function writeCachedSummary(rootDir, summary) {
|
|
134
|
+
const filePath = path.join(summaryCacheDir(rootDir), `${summary.sourceSha256}.json`);
|
|
135
|
+
atomicWriteJson(filePath, {
|
|
136
|
+
path: summary.path,
|
|
137
|
+
binary: summary.binary,
|
|
138
|
+
sourceSha256: summary.sourceSha256,
|
|
139
|
+
sourceBytes: summary.sourceBytes,
|
|
140
|
+
language: summary.language,
|
|
141
|
+
lines: summary.lines,
|
|
142
|
+
symbols: summary.symbols
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function buildContextIndex(rootDir, { files } = {}) {
|
|
147
|
+
ensurePrivateRuntimeIgnores(rootDir);
|
|
148
|
+
const candidates = (files && files.length ? files : listTrackedFiles(rootDir))
|
|
149
|
+
.map((file) => String(file).trim())
|
|
150
|
+
.filter(Boolean);
|
|
151
|
+
const summaries = [];
|
|
152
|
+
const cache = { hits: 0, misses: 0 };
|
|
153
|
+
for (const candidate of [...new Set(candidates)]) {
|
|
154
|
+
try {
|
|
155
|
+
const summary = summarizeFile(rootDir, candidate);
|
|
156
|
+
if (summary.cacheHit) cache.hits += 1;
|
|
157
|
+
else cache.misses += 1;
|
|
158
|
+
const { cacheHit: _cacheHit, ...publicSummary } = summary;
|
|
159
|
+
summaries.push(publicSummary);
|
|
160
|
+
} catch (cause) {
|
|
161
|
+
if (cause.code === 'CONTEXT_FILE_MISSING') continue;
|
|
162
|
+
throw cause;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const index = {
|
|
166
|
+
schemaVersion: 1,
|
|
167
|
+
createdAt: new Date().toISOString(),
|
|
168
|
+
cache,
|
|
169
|
+
files: summaries.sort((left, right) => left.path.localeCompare(right.path))
|
|
170
|
+
};
|
|
171
|
+
const indexPath = path.join(contextRoot(rootDir), 'index.json');
|
|
172
|
+
atomicWriteJson(indexPath, index);
|
|
173
|
+
return {
|
|
174
|
+
index,
|
|
175
|
+
path: path.relative(rootDir, indexPath).split(path.sep).join('/')
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function parseDiff(diff) {
|
|
180
|
+
const files = [];
|
|
181
|
+
let currentFile = null;
|
|
182
|
+
let currentHunk = null;
|
|
183
|
+
for (const line of String(diff || '').split('\n')) {
|
|
184
|
+
const fileMatch = line.match(/^diff --git a\/(.+) b\/(.+)$/);
|
|
185
|
+
if (fileMatch) {
|
|
186
|
+
currentFile = {
|
|
187
|
+
path: fileMatch[2],
|
|
188
|
+
oldPath: fileMatch[1],
|
|
189
|
+
hunks: []
|
|
190
|
+
};
|
|
191
|
+
files.push(currentFile);
|
|
192
|
+
currentHunk = null;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (!currentFile) continue;
|
|
196
|
+
if (line.startsWith('@@ ')) {
|
|
197
|
+
currentHunk = { header: line, lines: [line] };
|
|
198
|
+
currentFile.hunks.push(currentHunk);
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (currentHunk) currentHunk.lines.push(line);
|
|
202
|
+
}
|
|
203
|
+
return files.filter((file) => file.hunks.length > 0);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function compactFinding(finding) {
|
|
207
|
+
return {
|
|
208
|
+
id: finding.id,
|
|
209
|
+
axis: finding.axis,
|
|
210
|
+
severity: finding.severity,
|
|
211
|
+
validity: finding.validity,
|
|
212
|
+
disposition: finding.disposition,
|
|
213
|
+
location: finding.location,
|
|
214
|
+
acceptanceCriteria: finding.acceptanceCriteria
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function pathFromFindingLocation(location) {
|
|
219
|
+
const value = String(location || '').split('#')[0].trim();
|
|
220
|
+
return value || null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function unresolvedFindings(rootDir, runId) {
|
|
224
|
+
const filePath = path.join(runsDir(rootDir), runId, 'findings.json');
|
|
225
|
+
if (!fs.existsSync(filePath)) return [];
|
|
226
|
+
let parsed;
|
|
227
|
+
try {
|
|
228
|
+
parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
229
|
+
} catch (cause) {
|
|
230
|
+
throw smartContextError(`Unable to read findings.json: ${cause.message}`, 'INVALID_FINDINGS');
|
|
231
|
+
}
|
|
232
|
+
return (parsed.findings || [])
|
|
233
|
+
.filter((finding) => finding.validity === 'VALID')
|
|
234
|
+
.filter((finding) => ['BLOCKER', 'HIGH'].includes(finding.severity) || finding.disposition === 'STRONG')
|
|
235
|
+
.map(compactFinding)
|
|
236
|
+
.slice(0, 20);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function resolveRun(rootDir, runId) {
|
|
240
|
+
if (runId) return loadRun(rootDir, runId);
|
|
241
|
+
const current = getCurrentRun(rootDir);
|
|
242
|
+
if (!current) throw smartContextError('No current run. Pass --run <id>.', 'NO_CURRENT_RUN');
|
|
243
|
+
return current;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function summarizeChangedFile(rootDir, relativePath) {
|
|
247
|
+
try {
|
|
248
|
+
return summarizeFile(rootDir, relativePath);
|
|
249
|
+
} catch (cause) {
|
|
250
|
+
if (cause.code === 'CONTEXT_FILE_MISSING') {
|
|
251
|
+
return {
|
|
252
|
+
path: relativePath,
|
|
253
|
+
deleted: true,
|
|
254
|
+
binary: false,
|
|
255
|
+
sourceSha256: null,
|
|
256
|
+
sourceBytes: 0,
|
|
257
|
+
language: languageFor(relativePath),
|
|
258
|
+
lines: null,
|
|
259
|
+
symbols: []
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
throw cause;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function boundedHunks(file, limits, remainingBytes) {
|
|
267
|
+
const hunks = [];
|
|
268
|
+
let includedBytes = 0;
|
|
269
|
+
let truncated = file.hunks.length > limits.maxHunksPerFile;
|
|
270
|
+
for (const hunk of file.hunks.slice(0, limits.maxHunksPerFile)) {
|
|
271
|
+
if (remainingBytes - includedBytes <= 0) {
|
|
272
|
+
truncated = true;
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
const rawContent = hunk.lines.join('\n');
|
|
276
|
+
const redacted = redactSecrets(rawContent);
|
|
277
|
+
const allowed = Math.min(Buffer.byteLength(redacted.text), limits.maxHunkBytes, remainingBytes - includedBytes);
|
|
278
|
+
const content = Buffer.from(redacted.text).subarray(0, allowed).toString('utf8');
|
|
279
|
+
if (allowed < Buffer.byteLength(redacted.text)) truncated = true;
|
|
280
|
+
includedBytes += allowed;
|
|
281
|
+
hunks.push({
|
|
282
|
+
header: hunk.header,
|
|
283
|
+
content,
|
|
284
|
+
redactions: redacted.categories,
|
|
285
|
+
truncated: allowed < Buffer.byteLength(redacted.text)
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
return { hunks, includedBytes, truncated };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function createDiffHunkPack(rootDir, { runId, base = 'HEAD', profile } = {}) {
|
|
292
|
+
const run = resolveRun(rootDir, runId);
|
|
293
|
+
const policy = loadPolicy(rootDir);
|
|
294
|
+
const reviewProfile = normalizeReviewProfile(profile || policy.reviewProfile);
|
|
295
|
+
const limits = DIFF_PACK_LIMITS[reviewProfile];
|
|
296
|
+
const contextLimits = CONTEXT_PROFILE_LIMITS[reviewProfile]['devil-advocate'];
|
|
297
|
+
const diff = git(rootDir, ['diff', '--no-ext-diff', '--unified=3', base, '--']);
|
|
298
|
+
const allParsedFiles = parseDiff(diff).filter((file) => !isSensitivePath(file.path));
|
|
299
|
+
const parsedFiles = allParsedFiles.slice(0, limits.maxFiles);
|
|
300
|
+
const totalFilesTruncated = allParsedFiles.length > parsedFiles.length;
|
|
301
|
+
const unresolved = unresolvedFindings(rootDir, run.runId);
|
|
302
|
+
const changedPaths = allParsedFiles.map((file) => file.path);
|
|
303
|
+
const focusPaths = [...new Set(unresolved
|
|
304
|
+
.map((finding) => pathFromFindingLocation(finding.location))
|
|
305
|
+
.filter((location) => location && changedPaths.includes(location)))];
|
|
306
|
+
const files = [];
|
|
307
|
+
let totalBytes = 0;
|
|
308
|
+
let estimatedTokens = 0;
|
|
309
|
+
for (const file of parsedFiles) {
|
|
310
|
+
const remaining = limits.maxTotalBytes - totalBytes;
|
|
311
|
+
if (remaining <= 0) break;
|
|
312
|
+
const bounded = boundedHunks(file, limits, remaining);
|
|
313
|
+
totalBytes += bounded.includedBytes;
|
|
314
|
+
estimatedTokens += estimateTokens(bounded.hunks.map((hunk) => hunk.content).join('\n'));
|
|
315
|
+
files.push({
|
|
316
|
+
path: file.path,
|
|
317
|
+
oldPath: file.oldPath === file.path ? null : file.oldPath,
|
|
318
|
+
summary: summarizeChangedFile(rootDir, file.path),
|
|
319
|
+
includedBytes: bounded.includedBytes,
|
|
320
|
+
truncated: bounded.truncated,
|
|
321
|
+
hunks: bounded.hunks
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
if (estimatedTokens > contextLimits.maxEstimatedTokens) {
|
|
325
|
+
throw smartContextError(`${reviewProfile} diff hunk pack exceeds devil-advocate token budget`, 'DIFF_PACK_TOKEN_LIMIT');
|
|
326
|
+
}
|
|
327
|
+
assertBudgetAvailable(rootDir, { runId: run.runId, estimatedTokens });
|
|
328
|
+
const pack = {
|
|
329
|
+
schemaVersion: 1,
|
|
330
|
+
runId: run.runId,
|
|
331
|
+
reviewProfile,
|
|
332
|
+
base,
|
|
333
|
+
createdAt: new Date().toISOString(),
|
|
334
|
+
mode: 'diff-hunks',
|
|
335
|
+
limits,
|
|
336
|
+
totalBytes,
|
|
337
|
+
estimatedTokens,
|
|
338
|
+
truncated: totalFilesTruncated || files.some((file) => file.truncated),
|
|
339
|
+
reviewDelta: {
|
|
340
|
+
previousDiffHash: run.artifacts?.diff?.sha256 || null,
|
|
341
|
+
currentDiffHash: sha256(diff),
|
|
342
|
+
changedPaths,
|
|
343
|
+
unresolvedFindingIds: unresolved.map((finding) => finding.id),
|
|
344
|
+
focusPaths
|
|
345
|
+
},
|
|
346
|
+
unresolvedFindings: unresolved,
|
|
347
|
+
files
|
|
348
|
+
};
|
|
349
|
+
const packPath = path.join(runsDir(rootDir), run.runId, 'context', 'diff-hunks.json');
|
|
350
|
+
atomicWriteJson(packPath, pack);
|
|
351
|
+
return {
|
|
352
|
+
pack,
|
|
353
|
+
path: path.relative(rootDir, packPath).split(path.sep).join('/')
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function smartContextSummary(result) {
|
|
358
|
+
if (result.pack) {
|
|
359
|
+
return {
|
|
360
|
+
schemaVersion: result.pack.schemaVersion,
|
|
361
|
+
runId: result.pack.runId,
|
|
362
|
+
reviewProfile: result.pack.reviewProfile,
|
|
363
|
+
path: result.path,
|
|
364
|
+
files: result.pack.files.length,
|
|
365
|
+
totalBytes: result.pack.totalBytes,
|
|
366
|
+
estimatedTokens: result.pack.estimatedTokens,
|
|
367
|
+
truncated: result.pack.truncated,
|
|
368
|
+
unresolvedFindings: result.pack.unresolvedFindings.length
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
return {
|
|
372
|
+
schemaVersion: result.index.schemaVersion,
|
|
373
|
+
path: result.path,
|
|
374
|
+
files: result.index.files.length
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
module.exports = {
|
|
379
|
+
DIFF_PACK_LIMITS,
|
|
380
|
+
buildContextIndex,
|
|
381
|
+
createDiffHunkPack,
|
|
382
|
+
parseDiff,
|
|
383
|
+
smartContextSummary
|
|
384
|
+
};
|
package/lib/studio-runtime.js
CHANGED
|
@@ -56,7 +56,7 @@ function createStudioRun(
|
|
|
56
56
|
};
|
|
57
57
|
throw error;
|
|
58
58
|
}
|
|
59
|
-
const loaded = loadRecipe(rootDir, recipeId);
|
|
59
|
+
const loaded = loadRecipe(rootDir, recipeId || 'default');
|
|
60
60
|
const plan = compileRecipe(loaded.recipe, { mode: normalizedMode });
|
|
61
61
|
const runId = newRunId(now);
|
|
62
62
|
const workflow = createWorkflowBundle(plan, runId, {
|
package/lib/studio-server.js
CHANGED
|
@@ -29,6 +29,8 @@ const {
|
|
|
29
29
|
const { listRunHistory, runHistoryDetail, inspectRunArtifact } = require('./run-history.js');
|
|
30
30
|
const {
|
|
31
31
|
duplicateRunAsRecipe,
|
|
32
|
+
edgesFromPlan,
|
|
33
|
+
redactedValue,
|
|
32
34
|
runCheckout,
|
|
33
35
|
runNodeIo,
|
|
34
36
|
studioAgentHandoff
|
|
@@ -40,6 +42,7 @@ const {
|
|
|
40
42
|
} = require('./run-interactions.js');
|
|
41
43
|
const { saveGoalDraft, loadGoalDraft, freezeGoal, unfreezeGoal } = require('./goal-runtime.js');
|
|
42
44
|
const { appendRunLifecycle, listRunLifecycle, runAgentPresence } = require('./run-lifecycle.js');
|
|
45
|
+
const { runJourney } = require('./run-journey.js');
|
|
43
46
|
const { cancelStudioRun, createStudioRun, executeStudioRun } = require('./studio-runtime.js');
|
|
44
47
|
const { createHandoff, handoffBrief, recordDecision } = require('./handoff.js');
|
|
45
48
|
const { loadStudioLayout, saveStudioLayout } = require('./studio-layout.js');
|
|
@@ -105,17 +108,31 @@ function liveSnapshot(rootDir) {
|
|
|
105
108
|
const run = getCurrentRun(rootDir);
|
|
106
109
|
if (!run?.workflow) return null;
|
|
107
110
|
const workflow = workflowStatus(rootDir, { runId: run.runId });
|
|
108
|
-
return {
|
|
111
|
+
return redactedValue({
|
|
109
112
|
run,
|
|
110
113
|
plan: workflow.plan,
|
|
111
114
|
nodes: workflow.state.nodes,
|
|
115
|
+
edges: edgesFromPlan(workflow.plan, workflow.state),
|
|
112
116
|
loopGroups: workflow.state.loopGroups,
|
|
117
|
+
journey: (() => {
|
|
118
|
+
try {
|
|
119
|
+
return runJourney(rootDir, run.runId, { workflowState: workflow.state });
|
|
120
|
+
} catch {
|
|
121
|
+
return {
|
|
122
|
+
runId: run.runId,
|
|
123
|
+
current: 'UNKNOWN',
|
|
124
|
+
pendingQuestions: 0,
|
|
125
|
+
sources: { available: false },
|
|
126
|
+
steps: []
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
})(),
|
|
113
130
|
budget: budgetStatus(rootDir, { runId: run.runId }),
|
|
114
131
|
events: workflow.events.slice(-50).map(({ initialNodes, changes, ...event }) => ({
|
|
115
132
|
...event,
|
|
116
133
|
changedNodes: (changes || []).map((change) => change.nodeId)
|
|
117
134
|
}))
|
|
118
|
-
};
|
|
135
|
+
});
|
|
119
136
|
}
|
|
120
137
|
|
|
121
138
|
function bootstrap(rootDir) {
|
|
@@ -366,7 +383,7 @@ function createStudioServer(rootDir, { token = crypto.randomBytes(24).toString('
|
|
|
366
383
|
expectedHash: body.expectedHash
|
|
367
384
|
});
|
|
368
385
|
appendRunLifecycle(rootDir, runId, {
|
|
369
|
-
type: '
|
|
386
|
+
type: 'GOAL_FROZEN',
|
|
370
387
|
phase: 'goal',
|
|
371
388
|
actor: body.actor || 'studio-user',
|
|
372
389
|
message: 'Goal Contract frozen in Studio'
|