ai-engineering-loop 1.1.0 → 1.5.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/workflows/ai-engineering-loop.md +5 -5
- package/.claude/skills/ai-engineering-loop/SKILL.md +7 -5
- package/.gemini/skills/ai-engineering-loop/SKILL.md +7 -5
- package/.grok/skills/ai-engineering-loop/SKILL.md +7 -5
- package/README.md +56 -6
- package/README.npm.md +9 -1
- package/SECURITY.md +8 -2
- package/agents/judge.md +5 -5
- package/agents/maker.md +6 -6
- package/agents/recipe-builder.md +28 -0
- package/bin/ai-engineering-loop.js +521 -16
- package/core/configuration-precedence.md +4 -4
- package/core/context-impact-assessment.md +1 -1
- package/core/controlled-workflow-runtime.md +77 -0
- package/core/definition-of-done.md +3 -3
- package/core/escalation-policy.md +2 -2
- package/core/goal-contract.md +2 -2
- package/core/iteration-policy.md +4 -4
- package/core/project-initialization.md +2 -2
- package/core/runtime-safety.md +75 -0
- package/core/verification-loop.md +1 -1
- package/core/workflow-recipes.md +140 -0
- package/lib/budget.js +258 -0
- package/lib/doctor.js +38 -2
- package/lib/gates.js +55 -1
- package/lib/node-registry.js +155 -0
- package/lib/package-audit.js +78 -0
- package/lib/recipe-builder.js +200 -0
- package/lib/recipe.js +495 -0
- package/lib/run-state.js +94 -8
- package/lib/runtime-files.js +54 -0
- package/lib/runtime-policy.js +118 -0
- package/lib/safe-context.js +3 -0
- package/lib/sandbox.js +305 -0
- package/lib/workflow-runtime.js +692 -0
- package/package.json +7 -3
- package/policies/finding-policy.md +2 -2
- package/policies/no-progress-policy.md +2 -2
- package/profiles/README.md +5 -5
- package/profiles/backend-api.md +1 -1
- package/profiles/library.md +1 -1
- package/profiles/mobile-app.md +1 -1
- package/profiles/monorepo.md +1 -1
- package/profiles/web-app.md +1 -1
- package/recipes/audit.json +32 -0
- package/recipes/bugfix.json +63 -0
- package/recipes/default.json +49 -0
- package/recipes/docs-light.json +63 -0
- package/recipes/high-risk.json +69 -0
- package/recipes/refactor.json +63 -0
- package/schemas/compiled-plan.schema.json +19 -0
- package/schemas/delivery.schema.json +2 -1
- package/schemas/node-definition.schema.json +33 -0
- package/schemas/recipe.schema.json +26 -0
- package/schemas/report.schema.json +17 -0
- package/schemas/workflow-event.schema.json +28 -0
- package/schemas/workflow-state.schema.json +29 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
|
|
6
|
+
const PRIVATE_RUNTIME_PATTERNS = Object.freeze([
|
|
7
|
+
'runs/',
|
|
8
|
+
'usage/',
|
|
9
|
+
'worktrees/',
|
|
10
|
+
'locks/',
|
|
11
|
+
'recipes/.history/',
|
|
12
|
+
'tasks/current.diff',
|
|
13
|
+
'tasks/*.log'
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
const PRIVATE_RUNTIME_GITIGNORE =
|
|
17
|
+
`# Runtime artifacts may contain source excerpts and verification logs.\n${PRIVATE_RUNTIME_PATTERNS.join('\n')}\n`;
|
|
18
|
+
|
|
19
|
+
function assertNotSymlink(filePath, label) {
|
|
20
|
+
let stat;
|
|
21
|
+
try {
|
|
22
|
+
stat = fs.lstatSync(filePath);
|
|
23
|
+
} catch (cause) {
|
|
24
|
+
if (cause.code !== 'ENOENT') throw cause;
|
|
25
|
+
}
|
|
26
|
+
if (stat?.isSymbolicLink()) {
|
|
27
|
+
const err = new Error(`${label} must not be a symbolic link`);
|
|
28
|
+
err.code = 'UNSAFE_RUNTIME_PATH';
|
|
29
|
+
throw err;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function ensurePrivateRuntimeIgnores(rootDir) {
|
|
34
|
+
const contextDir = path.join(rootDir, '.ai-engineering-loop');
|
|
35
|
+
assertNotSymlink(contextDir, '.ai-engineering-loop');
|
|
36
|
+
fs.mkdirSync(contextDir, { recursive: true });
|
|
37
|
+
const filePath = path.join(contextDir, '.gitignore');
|
|
38
|
+
assertNotSymlink(filePath, '.ai-engineering-loop/.gitignore');
|
|
39
|
+
const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
|
|
40
|
+
const missing = PRIVATE_RUNTIME_PATTERNS.filter((pattern) => (
|
|
41
|
+
!existing.split(/\r?\n/).includes(pattern)
|
|
42
|
+
));
|
|
43
|
+
if (missing.length === 0) return false;
|
|
44
|
+
const separator = existing && !existing.endsWith('\n') ? '\n' : '';
|
|
45
|
+
const header = existing ? '' : '# Runtime artifacts may contain source excerpts and verification logs.\n';
|
|
46
|
+
fs.writeFileSync(filePath, `${existing}${separator}${header}${missing.join('\n')}\n`);
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
module.exports = {
|
|
51
|
+
PRIVATE_RUNTIME_PATTERNS,
|
|
52
|
+
PRIVATE_RUNTIME_GITIGNORE,
|
|
53
|
+
ensurePrivateRuntimeIgnores
|
|
54
|
+
};
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const {
|
|
6
|
+
RUN_MODES,
|
|
7
|
+
atomicWriteJson
|
|
8
|
+
} = require('./run-state.js');
|
|
9
|
+
|
|
10
|
+
const DEFAULT_POLICY = Object.freeze({
|
|
11
|
+
schemaVersion: 1,
|
|
12
|
+
defaultMode: RUN_MODES.ASSISTED,
|
|
13
|
+
allowUnattended: false,
|
|
14
|
+
requireSandboxForUnattended: true,
|
|
15
|
+
perRunTokenLimit: 50_000,
|
|
16
|
+
dailyTokenLimit: 200_000,
|
|
17
|
+
killSwitch: false
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
function policyPath(rootDir) {
|
|
21
|
+
return path.join(rootDir, '.ai-engineering-loop', 'runtime-policy.json');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function normalizeMode(value, fallback = null) {
|
|
25
|
+
if (value == null || value === '') return fallback;
|
|
26
|
+
const normalized = String(value).trim().replace(/-/g, '_').toUpperCase();
|
|
27
|
+
if (!Object.hasOwn(RUN_MODES, normalized)) {
|
|
28
|
+
const err = new Error(`Unknown run mode: ${value}. Use report-only|assisted|unattended`);
|
|
29
|
+
err.code = 'INVALID_RUN_MODE';
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
return RUN_MODES[normalized];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function validatePolicy(value) {
|
|
36
|
+
const errors = [];
|
|
37
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
38
|
+
return ['runtime policy must be a JSON object'];
|
|
39
|
+
}
|
|
40
|
+
if (value.schemaVersion !== 1) errors.push('schemaVersion must be 1');
|
|
41
|
+
try {
|
|
42
|
+
normalizeMode(value.defaultMode);
|
|
43
|
+
} catch (cause) {
|
|
44
|
+
errors.push(cause.message);
|
|
45
|
+
}
|
|
46
|
+
for (const key of ['allowUnattended', 'requireSandboxForUnattended', 'killSwitch']) {
|
|
47
|
+
if (typeof value[key] !== 'boolean') errors.push(`${key} must be boolean`);
|
|
48
|
+
}
|
|
49
|
+
for (const key of ['perRunTokenLimit', 'dailyTokenLimit']) {
|
|
50
|
+
if (!Number.isSafeInteger(value[key]) || value[key] <= 0) {
|
|
51
|
+
errors.push(`${key} must be a positive integer`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return errors;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function loadPolicy(rootDir) {
|
|
58
|
+
const filePath = policyPath(rootDir);
|
|
59
|
+
if (!fs.existsSync(filePath)) return { ...DEFAULT_POLICY };
|
|
60
|
+
let parsed;
|
|
61
|
+
try {
|
|
62
|
+
parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
63
|
+
} catch (cause) {
|
|
64
|
+
const err = new Error(`Unable to read runtime policy: ${cause.message}`);
|
|
65
|
+
err.code = 'INVALID_RUNTIME_POLICY';
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
const policy = { ...DEFAULT_POLICY, ...parsed };
|
|
69
|
+
const errors = validatePolicy(policy);
|
|
70
|
+
if (errors.length) {
|
|
71
|
+
const err = new Error(`Invalid runtime policy: ${errors.join('; ')}`);
|
|
72
|
+
err.code = 'INVALID_RUNTIME_POLICY';
|
|
73
|
+
err.details = errors;
|
|
74
|
+
throw err;
|
|
75
|
+
}
|
|
76
|
+
policy.defaultMode = normalizeMode(policy.defaultMode);
|
|
77
|
+
return policy;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function writePolicy(rootDir, policy) {
|
|
81
|
+
const next = { ...DEFAULT_POLICY, ...policy, schemaVersion: 1 };
|
|
82
|
+
next.defaultMode = normalizeMode(next.defaultMode);
|
|
83
|
+
const errors = validatePolicy(next);
|
|
84
|
+
if (errors.length) {
|
|
85
|
+
const err = new Error(`Invalid runtime policy: ${errors.join('; ')}`);
|
|
86
|
+
err.code = 'INVALID_RUNTIME_POLICY';
|
|
87
|
+
err.details = errors;
|
|
88
|
+
throw err;
|
|
89
|
+
}
|
|
90
|
+
atomicWriteJson(policyPath(rootDir), next);
|
|
91
|
+
return next;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function updatePolicy(rootDir, changes) {
|
|
95
|
+
return writePolicy(rootDir, { ...loadPolicy(rootDir), ...changes });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function assertModeAllowed(rootDir, mode) {
|
|
99
|
+
const normalized = normalizeMode(mode);
|
|
100
|
+
const policy = loadPolicy(rootDir);
|
|
101
|
+
if (normalized === RUN_MODES.UNATTENDED && !policy.allowUnattended) {
|
|
102
|
+
const err = new Error('UNATTENDED mode is disabled by runtime policy; a human must explicitly enable allowUnattended');
|
|
103
|
+
err.code = 'UNATTENDED_DISABLED';
|
|
104
|
+
throw err;
|
|
105
|
+
}
|
|
106
|
+
return policy;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
module.exports = {
|
|
110
|
+
DEFAULT_POLICY,
|
|
111
|
+
policyPath,
|
|
112
|
+
normalizeMode,
|
|
113
|
+
validatePolicy,
|
|
114
|
+
loadPolicy,
|
|
115
|
+
writePolicy,
|
|
116
|
+
updatePolicy,
|
|
117
|
+
assertModeAllowed
|
|
118
|
+
};
|
package/lib/safe-context.js
CHANGED
|
@@ -4,6 +4,7 @@ const crypto = require('crypto');
|
|
|
4
4
|
const fs = require('fs');
|
|
5
5
|
const path = require('path');
|
|
6
6
|
const { atomicWriteJson, getCurrentRun, loadRun, runsDir } = require('./run-state.js');
|
|
7
|
+
const { assertBudgetAvailable } = require('./budget.js');
|
|
7
8
|
|
|
8
9
|
const STAGE_LIMITS = Object.freeze({
|
|
9
10
|
maker: Object.freeze({ maxFiles: 12, maxFileBytes: 32_000, maxTotalBytes: 96_000, maxEstimatedTokens: 24_000 }),
|
|
@@ -109,6 +110,7 @@ function createContextPack(rootDir, { runId, stage, files } = {}) {
|
|
|
109
110
|
throw contextError(`Unknown context stage: ${stage}. Use ${Object.keys(STAGE_LIMITS).join('|')}`, 'UNKNOWN_CONTEXT_STAGE');
|
|
110
111
|
}
|
|
111
112
|
const run = resolveRun(rootDir, runId);
|
|
113
|
+
assertBudgetAvailable(rootDir, { runId: run.runId });
|
|
112
114
|
const uniqueFiles = [...new Set((files || []).map((file) => String(file).trim()).filter(Boolean))];
|
|
113
115
|
if (uniqueFiles.length === 0) throw contextError('At least one context file is required', 'EMPTY_CONTEXT');
|
|
114
116
|
if (uniqueFiles.length > limits.maxFiles) {
|
|
@@ -146,6 +148,7 @@ function createContextPack(rootDir, { runId, stage, files } = {}) {
|
|
|
146
148
|
content: redacted.text
|
|
147
149
|
});
|
|
148
150
|
}
|
|
151
|
+
assertBudgetAvailable(rootDir, { runId: run.runId, estimatedTokens });
|
|
149
152
|
|
|
150
153
|
const pack = {
|
|
151
154
|
schemaVersion: 1,
|
package/lib/sandbox.js
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const os = require('os');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { execFileSync } = require('child_process');
|
|
8
|
+
const {
|
|
9
|
+
RUN_MODES,
|
|
10
|
+
RUN_STATES,
|
|
11
|
+
assertRunId,
|
|
12
|
+
atomicWritePrivateFile,
|
|
13
|
+
atomicWriteJson,
|
|
14
|
+
getCurrentRun,
|
|
15
|
+
loadRun,
|
|
16
|
+
runsDir
|
|
17
|
+
} = require('./run-state.js');
|
|
18
|
+
const { assertBudgetAvailable } = require('./budget.js');
|
|
19
|
+
const { assertModeAllowed } = require('./runtime-policy.js');
|
|
20
|
+
const { ensurePrivateRuntimeIgnores } = require('./runtime-files.js');
|
|
21
|
+
|
|
22
|
+
const LOCK_MAX_AGE_MS = 2 * 60 * 60 * 1000;
|
|
23
|
+
|
|
24
|
+
function sandboxError(message, code = 'SANDBOX_ERROR') {
|
|
25
|
+
const err = new Error(message);
|
|
26
|
+
err.code = code;
|
|
27
|
+
return err;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function sandboxRoot(rootDir) {
|
|
31
|
+
return path.join(path.resolve(rootDir), '.ai-engineering-loop', 'worktrees');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function sandboxPath(rootDir, runId) {
|
|
35
|
+
return path.join(sandboxRoot(rootDir), assertRunId(runId));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function lockPath(rootDir) {
|
|
39
|
+
return path.join(rootDir, '.ai-engineering-loop', 'locks', 'maker.json');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function metadataPath(rootDir, runId) {
|
|
43
|
+
return path.join(runsDir(rootDir), assertRunId(runId), 'sandbox.json');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function evidencePath(rootDir, runId) {
|
|
47
|
+
return path.join(runsDir(rootDir), assertRunId(runId), 'sandbox-evidence.json');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function pathEntryExists(filePath) {
|
|
51
|
+
try {
|
|
52
|
+
fs.lstatSync(filePath);
|
|
53
|
+
return true;
|
|
54
|
+
} catch (cause) {
|
|
55
|
+
if (cause.code === 'ENOENT') return false;
|
|
56
|
+
throw cause;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function resolveRun(rootDir, runId) {
|
|
61
|
+
if (runId) return loadRun(rootDir, assertRunId(runId));
|
|
62
|
+
const current = getCurrentRun(rootDir);
|
|
63
|
+
if (!current) throw sandboxError('No current run. Start one first.', 'NO_CURRENT_RUN');
|
|
64
|
+
return current;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function git(rootDir, args, options = {}) {
|
|
68
|
+
const { trim = true, ...execOptions } = options;
|
|
69
|
+
try {
|
|
70
|
+
const output = execFileSync('git', args, {
|
|
71
|
+
cwd: rootDir,
|
|
72
|
+
encoding: 'utf8',
|
|
73
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
74
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
75
|
+
...execOptions
|
|
76
|
+
});
|
|
77
|
+
return trim ? output.trim() : output;
|
|
78
|
+
} catch (cause) {
|
|
79
|
+
const detail = String(cause.stderr || cause.message || '').trim();
|
|
80
|
+
throw sandboxError(`Git worktree operation failed${detail ? `: ${detail}` : ''}`, 'GIT_WORKTREE_FAILED');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function assertGitRoot(rootDir) {
|
|
85
|
+
const prefix = git(rootDir, ['rev-parse', '--show-prefix']);
|
|
86
|
+
if (prefix !== '') {
|
|
87
|
+
throw sandboxError('Sandbox commands must run from the Git repository root', 'NOT_REPOSITORY_ROOT');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function processIsAlive(pid) {
|
|
92
|
+
try {
|
|
93
|
+
process.kill(pid, 0);
|
|
94
|
+
return true;
|
|
95
|
+
} catch (cause) {
|
|
96
|
+
return cause.code === 'EPERM';
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function readLock(rootDir) {
|
|
101
|
+
const filePath = lockPath(rootDir);
|
|
102
|
+
if (!fs.existsSync(filePath)) return null;
|
|
103
|
+
if (fs.lstatSync(filePath).isSymbolicLink()) {
|
|
104
|
+
throw sandboxError('Maker lock must not be a symbolic link', 'UNSAFE_RUNTIME_PATH');
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
108
|
+
} catch (cause) {
|
|
109
|
+
throw sandboxError(`Maker lock is unreadable: ${cause.message}`, 'SANDBOX_LOCKED');
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function staleLocalLock(lock, now) {
|
|
114
|
+
const created = Date.parse(lock.createdAt);
|
|
115
|
+
return (
|
|
116
|
+
lock.hostname === os.hostname() &&
|
|
117
|
+
Number.isSafeInteger(lock.pid) &&
|
|
118
|
+
Number.isFinite(created) &&
|
|
119
|
+
now.getTime() - created > LOCK_MAX_AGE_MS &&
|
|
120
|
+
!processIsAlive(lock.pid)
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function acquireMakerLock(rootDir, runId, now = new Date()) {
|
|
125
|
+
ensurePrivateRuntimeIgnores(rootDir);
|
|
126
|
+
const filePath = lockPath(rootDir);
|
|
127
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
128
|
+
const lock = {
|
|
129
|
+
schemaVersion: 1,
|
|
130
|
+
runId: assertRunId(runId),
|
|
131
|
+
nonce: crypto.randomBytes(16).toString('hex'),
|
|
132
|
+
pid: process.pid,
|
|
133
|
+
hostname: os.hostname(),
|
|
134
|
+
createdAt: now.toISOString()
|
|
135
|
+
};
|
|
136
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
137
|
+
let descriptor;
|
|
138
|
+
try {
|
|
139
|
+
descriptor = fs.openSync(filePath, 'wx', 0o600);
|
|
140
|
+
fs.writeFileSync(descriptor, `${JSON.stringify(lock, null, 2)}\n`);
|
|
141
|
+
fs.fchmodSync(descriptor, 0o600);
|
|
142
|
+
return lock;
|
|
143
|
+
} catch (cause) {
|
|
144
|
+
if (cause.code !== 'EEXIST') throw cause;
|
|
145
|
+
const existing = readLock(rootDir);
|
|
146
|
+
if (attempt === 0 && staleLocalLock(existing, now)) {
|
|
147
|
+
fs.unlinkSync(filePath);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
throw sandboxError(
|
|
151
|
+
`Maker is locked by run ${existing?.runId || 'unknown'} on ${existing?.hostname || 'unknown host'}`,
|
|
152
|
+
'SANDBOX_LOCKED'
|
|
153
|
+
);
|
|
154
|
+
} finally {
|
|
155
|
+
if (descriptor != null) fs.closeSync(descriptor);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
throw sandboxError('Unable to acquire Maker lock', 'SANDBOX_LOCKED');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function releaseMakerLock(rootDir, ownedLock) {
|
|
162
|
+
const existing = readLock(rootDir);
|
|
163
|
+
if (!existing) return false;
|
|
164
|
+
if (existing.runId !== ownedLock.runId || existing.nonce !== ownedLock.nonce) {
|
|
165
|
+
throw sandboxError('Refusing to release a Maker lock owned by another process', 'LOCK_OWNERSHIP_MISMATCH');
|
|
166
|
+
}
|
|
167
|
+
fs.unlinkSync(lockPath(rootDir));
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function createSandbox(rootDir, { runId, now = new Date() } = {}) {
|
|
172
|
+
const run = resolveRun(rootDir, runId);
|
|
173
|
+
const mode = run.mode || RUN_MODES.ASSISTED;
|
|
174
|
+
assertModeAllowed(rootDir, mode);
|
|
175
|
+
assertBudgetAvailable(rootDir, { runId: run.runId });
|
|
176
|
+
if (mode === RUN_MODES.REPORT_ONLY) {
|
|
177
|
+
throw sandboxError('REPORT_ONLY mode cannot create a Maker sandbox', 'MODE_FORBIDS_MAKER');
|
|
178
|
+
}
|
|
179
|
+
if (run.state !== RUN_STATES.GOAL_FROZEN) {
|
|
180
|
+
throw sandboxError(`Maker sandbox requires GOAL_FROZEN; run is ${run.state}`, 'INVALID_SANDBOX_STATE');
|
|
181
|
+
}
|
|
182
|
+
assertGitRoot(rootDir);
|
|
183
|
+
ensurePrivateRuntimeIgnores(rootDir);
|
|
184
|
+
const worktree = sandboxPath(rootDir, run.runId);
|
|
185
|
+
if (pathEntryExists(worktree)) {
|
|
186
|
+
throw sandboxError(`Sandbox already exists for run ${run.runId}`, 'SANDBOX_EXISTS');
|
|
187
|
+
}
|
|
188
|
+
const ownedLock = acquireMakerLock(rootDir, run.runId, now);
|
|
189
|
+
try {
|
|
190
|
+
const baseRevision = run.startedRevision;
|
|
191
|
+
if (!/^[a-f0-9]{40,64}$/.test(String(baseRevision || ''))) {
|
|
192
|
+
throw sandboxError('Run did not start from a reproducible Git revision', 'INVALID_BASE_REVISION');
|
|
193
|
+
}
|
|
194
|
+
fs.mkdirSync(path.dirname(worktree), { recursive: true, mode: 0o700 });
|
|
195
|
+
git(rootDir, ['worktree', 'add', '--detach', worktree, baseRevision]);
|
|
196
|
+
const metadata = {
|
|
197
|
+
schemaVersion: 1,
|
|
198
|
+
runId: run.runId,
|
|
199
|
+
baseRevision,
|
|
200
|
+
worktreePath: worktree,
|
|
201
|
+
lockNonce: ownedLock.nonce,
|
|
202
|
+
createdAt: now.toISOString()
|
|
203
|
+
};
|
|
204
|
+
atomicWriteJson(metadataPath(rootDir, run.runId), metadata);
|
|
205
|
+
return metadata;
|
|
206
|
+
} catch (cause) {
|
|
207
|
+
try {
|
|
208
|
+
if (pathEntryExists(worktree)) git(rootDir, ['worktree', 'remove', '--force', worktree]);
|
|
209
|
+
} catch {
|
|
210
|
+
// Preserve the original failure; `git worktree prune` can recover a partial registration.
|
|
211
|
+
}
|
|
212
|
+
releaseMakerLock(rootDir, ownedLock);
|
|
213
|
+
throw cause;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function loadOwnedSandbox(rootDir, runId) {
|
|
218
|
+
const run = resolveRun(rootDir, runId);
|
|
219
|
+
const expectedPath = sandboxPath(rootDir, run.runId);
|
|
220
|
+
let metadata;
|
|
221
|
+
try {
|
|
222
|
+
metadata = JSON.parse(fs.readFileSync(metadataPath(rootDir, run.runId), 'utf8'));
|
|
223
|
+
} catch (cause) {
|
|
224
|
+
throw sandboxError(`Sandbox metadata is unavailable: ${cause.message}`, 'SANDBOX_MISSING');
|
|
225
|
+
}
|
|
226
|
+
if (
|
|
227
|
+
metadata.runId !== run.runId ||
|
|
228
|
+
metadata.worktreePath !== expectedPath ||
|
|
229
|
+
!/^[a-f0-9]{40,64}$/.test(String(metadata.baseRevision || ''))
|
|
230
|
+
) {
|
|
231
|
+
throw sandboxError('Sandbox metadata is invalid', 'INVALID_SANDBOX_METADATA');
|
|
232
|
+
}
|
|
233
|
+
const lock = readLock(rootDir);
|
|
234
|
+
if (!lock || lock.runId !== run.runId || lock.nonce !== metadata.lockNonce) {
|
|
235
|
+
throw sandboxError('Maker lock does not match sandbox metadata', 'LOCK_OWNERSHIP_MISMATCH');
|
|
236
|
+
}
|
|
237
|
+
if (!fs.existsSync(expectedPath)) throw sandboxError('Sandbox worktree is missing', 'SANDBOX_MISSING');
|
|
238
|
+
return { run, metadata, lock, worktree: expectedPath };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function captureSandbox(rootDir, { runId, now = new Date() } = {}) {
|
|
242
|
+
const owned = loadOwnedSandbox(rootDir, runId);
|
|
243
|
+
try {
|
|
244
|
+
fs.unlinkSync(evidencePath(rootDir, owned.run.runId));
|
|
245
|
+
} catch (cause) {
|
|
246
|
+
if (cause.code !== 'ENOENT') throw cause;
|
|
247
|
+
}
|
|
248
|
+
git(owned.worktree, ['add', '--intent-to-add', '--all']);
|
|
249
|
+
const diff = git(
|
|
250
|
+
owned.worktree,
|
|
251
|
+
['diff', '--binary', '--no-ext-diff', 'HEAD', '--'],
|
|
252
|
+
{ trim: false }
|
|
253
|
+
);
|
|
254
|
+
if (!diff.trim()) throw sandboxError('Maker sandbox has no changes to capture', 'EMPTY_SANDBOX_DIFF');
|
|
255
|
+
const diffFile = path.join(runsDir(rootDir), owned.run.runId, 'diff.patch');
|
|
256
|
+
atomicWritePrivateFile(diffFile, diff);
|
|
257
|
+
const evidence = {
|
|
258
|
+
schemaVersion: 1,
|
|
259
|
+
runId: owned.run.runId,
|
|
260
|
+
sandboxed: true,
|
|
261
|
+
baseRevision: owned.metadata.baseRevision,
|
|
262
|
+
diffSha256: crypto.createHash('sha256').update(diff).digest('hex'),
|
|
263
|
+
capturedAt: now.toISOString()
|
|
264
|
+
};
|
|
265
|
+
git(rootDir, ['worktree', 'remove', '--force', owned.worktree]);
|
|
266
|
+
releaseMakerLock(rootDir, owned.lock);
|
|
267
|
+
atomicWriteJson(evidencePath(rootDir, owned.run.runId), evidence);
|
|
268
|
+
return { diffPath: diffFile, evidence };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function abortSandbox(rootDir, { runId } = {}) {
|
|
272
|
+
const owned = loadOwnedSandbox(rootDir, runId);
|
|
273
|
+
git(rootDir, ['worktree', 'remove', '--force', owned.worktree]);
|
|
274
|
+
releaseMakerLock(rootDir, owned.lock);
|
|
275
|
+
return { runId: owned.run.runId, aborted: true };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function sandboxStatus(rootDir, { runId } = {}) {
|
|
279
|
+
const run = resolveRun(rootDir, runId);
|
|
280
|
+
const filePath = metadataPath(rootDir, run.runId);
|
|
281
|
+
if (!fs.existsSync(filePath)) return { runId: run.runId, exists: false, locked: false };
|
|
282
|
+
const metadata = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
283
|
+
const lock = readLock(rootDir);
|
|
284
|
+
return {
|
|
285
|
+
runId: run.runId,
|
|
286
|
+
exists: fs.existsSync(sandboxPath(rootDir, run.runId)),
|
|
287
|
+
locked: lock?.runId === run.runId && lock?.nonce === metadata.lockNonce,
|
|
288
|
+
baseRevision: metadata.baseRevision
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
module.exports = {
|
|
293
|
+
LOCK_MAX_AGE_MS,
|
|
294
|
+
sandboxRoot,
|
|
295
|
+
sandboxPath,
|
|
296
|
+
lockPath,
|
|
297
|
+
metadataPath,
|
|
298
|
+
evidencePath,
|
|
299
|
+
acquireMakerLock,
|
|
300
|
+
releaseMakerLock,
|
|
301
|
+
createSandbox,
|
|
302
|
+
captureSandbox,
|
|
303
|
+
abortSandbox,
|
|
304
|
+
sandboxStatus
|
|
305
|
+
};
|