ai-engineering-loop 2.14.0 → 2.15.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.
Files changed (48) hide show
  1. package/.agents/skills/ael/SKILL.md +4 -4
  2. package/.agents/skills/ael/references/loop-commands.md +6 -3
  3. package/.agents/skills/ael/references/loop-deliver.md +1 -0
  4. package/.agents/skills/ael/references/loop-goal.md +7 -4
  5. package/.agents/skills/ael/references/loop-hosts.md +1 -0
  6. package/.agents/skills/ael/references/loop-modes.md +1 -0
  7. package/CHANGELOG.md +31 -1
  8. package/README.md +1 -0
  9. package/adapters/project-onboarding/SKILL.md +2 -0
  10. package/agents/instruction-only/AGENTS.md +1 -1
  11. package/bin/ai-engineering-loop.js +447 -40
  12. package/core/coordinator.md +33 -0
  13. package/core/garden.md +18 -0
  14. package/core/goal-contract.md +23 -1
  15. package/core/overnight-contract.md +62 -0
  16. package/core/prototype-spike.md +28 -0
  17. package/core/root-cause-analysis.md +27 -0
  18. package/core/run-isolation.md +19 -0
  19. package/core/verification-loop.md +2 -0
  20. package/core/verification-one-pager.md +34 -0
  21. package/core/weekly-process-sampling.md +32 -0
  22. package/lib/agent-artifacts.js +6 -0
  23. package/lib/cli-args.js +5 -3
  24. package/lib/design-ref.js +15 -0
  25. package/lib/driver-scaffold.js +1 -1
  26. package/lib/feature-map.js +427 -1
  27. package/lib/features.js +20 -1
  28. package/lib/garden.js +171 -0
  29. package/lib/gates.js +18 -0
  30. package/lib/git-readiness.js +6 -1
  31. package/lib/goal-runtime.js +31 -1
  32. package/lib/harness-audit.js +1 -1
  33. package/lib/issue-repro.js +460 -0
  34. package/lib/learn.js +34 -0
  35. package/lib/overnight.js +179 -0
  36. package/lib/pr-babysit.js +277 -0
  37. package/lib/run-isolation.js +25 -4
  38. package/lib/spike.js +104 -0
  39. package/lib/ste.js +15 -0
  40. package/lib/verification-lanes.js +1 -2
  41. package/package.json +1 -1
  42. package/schemas/goal-contract.schema.json +13 -0
  43. package/README.npm.md +0 -104
  44. package/docs/images/ael-hero.svg +0 -19
  45. package/docs/images/engineering-loop-overview.svg +0 -114
  46. package/docs/images/social-preview.png +0 -0
  47. package/docs/images/studio-hero-orange.svg +0 -136
  48. package/docs/images/studio-hero.svg +0 -136
@@ -0,0 +1,179 @@
1
+ 'use strict';
2
+
3
+ // Overnight contract for an UNATTENDED Run the human left. The check
4
+ // recomputes the morning packet from Run files. It does not read a note
5
+ // the agent wrote about itself.
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { getCurrentRun, loadRun, runsDir } = require('./run-state.js');
10
+ const { loadPolicy } = require('./runtime-policy.js');
11
+ const { runMaxIterations } = require('./no-progress.js');
12
+
13
+ const CONTRACT = Object.freeze({
14
+ schemaVersion: 1,
15
+ id: 'overnight-v1',
16
+ mayDo: Object.freeze([
17
+ 'continue a Goal the human already froze',
18
+ 'edit only inside that frozen scope, in the sandbox worktree',
19
+ 'run verify, Devil\'s Advocate, and Judge inside the recipe cap and token budget',
20
+ 'record evidence under runs/<id>/'
21
+ ]),
22
+ mustNot: Object.freeze([
23
+ 'freeze, unfreeze, or edit the Goal',
24
+ 'deliver, approve, or merge',
25
+ 'force-push, reset --hard, or clean -fd',
26
+ 'widen scope, change verification config, or add a dependency',
27
+ 'guess a product decision, or pick an option the human has not answered'
28
+ ]),
29
+ stopWhen: Object.freeze([
30
+ 'GOAL_NOT_FROZEN',
31
+ 'NEEDS_HUMAN',
32
+ 'GUARD_BLOCK',
33
+ 'BUDGET',
34
+ 'VERIFY_STILL_RED',
35
+ 'JUDGE_ESCALATE',
36
+ 'JUDGED_PASS'
37
+ ]),
38
+ leaveForMorning: Object.freeze([
39
+ 'frozen Goal',
40
+ 'diff.patch',
41
+ 'verification.json',
42
+ 'findings.json when a review ran',
43
+ 'verdict.json or the stop reason',
44
+ 'unanswered questions'
45
+ ])
46
+ });
47
+
48
+ const AGENT_APPROVERS = new Set([
49
+ 'agent', 'agents', 'ael', 'ael-agent', 'assistant', 'bot', 'ai', 'llm', 'model', 'system', 'auto'
50
+ ]);
51
+
52
+ const PACKET_FILES = Object.freeze({
53
+ diff: 'diff.patch',
54
+ verification: 'verification.json',
55
+ verdict: 'verdict.json'
56
+ });
57
+
58
+ function readJson(file) {
59
+ try {
60
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ function fileExists(file) {
67
+ try {
68
+ const stat = fs.statSync(file);
69
+ return stat.isFile() && stat.size > 0;
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ function pendingQuestions(rootDir, runId) {
76
+ try {
77
+ return require('./run-interactions.js').listRunInteractions(rootDir, runId).pending
78
+ .map((question) => ({ id: question.questionId, message: String(question.message || '').slice(0, 240) }));
79
+ } catch {
80
+ return [];
81
+ }
82
+ }
83
+
84
+ function guardBlocked(runDir) {
85
+ const parsed = readJson(path.join(runDir, 'guard-events.json'));
86
+ const events = Array.isArray(parsed?.events) ? parsed.events : [];
87
+ return events.some((event) => event && event.decision === 'block');
88
+ }
89
+
90
+ function verificationRed(runDir) {
91
+ const commands = readJson(path.join(runDir, 'verification.json'))?.commands;
92
+ if (!Array.isArray(commands) || !commands.length) return false;
93
+ return commands.some((record) => !record || record.exitCode !== 0 || record.timeoutStatus !== 'COMPLETED');
94
+ }
95
+
96
+ function deliveryViolation(delivery) {
97
+ const by = String(delivery?.approvedBy || delivery?.by || '').trim().toLowerCase();
98
+ if (delivery?.humanApproved !== true || !by || AGENT_APPROVERS.has(by)) {
99
+ return {
100
+ id: 'DELIVERED_WITHOUT_HUMAN',
101
+ why: 'An overnight run must not ship. Delivery waits for a person in the morning.',
102
+ fix: 'Leave the Run at JUDGED_PASS. In the morning the human runs `deliver --approve --by <name>`.'
103
+ };
104
+ }
105
+ return null;
106
+ }
107
+
108
+ function classify(run, ctx) {
109
+ if (run.state === 'DELIVERED') {
110
+ return {
111
+ mayContinue: false,
112
+ stopReason: ctx.deliveryViolation ? 'DELIVERED_WITHOUT_HUMAN' : 'MORNING_APPROVED',
113
+ required: ctx.deliveryViolation ? [] : ['diff', 'verification', 'verdict']
114
+ };
115
+ }
116
+ if (run.state === 'ESCALATED') return { mayContinue: false, stopReason: 'JUDGE_ESCALATE', required: ['verdict'] };
117
+ if (run.state === 'CANCELLED') return { mayContinue: false, stopReason: 'CANCELLED', required: [] };
118
+ if (run.state === 'JUDGED_PASS') return { mayContinue: false, stopReason: 'JUDGED_PASS', required: ['diff', 'verification', 'verdict'] };
119
+ if (run.goal?.frozen !== true) return { mayContinue: false, stopReason: 'GOAL_NOT_FROZEN', required: [] };
120
+ if (ctx.questions.length) return { mayContinue: false, stopReason: 'NEEDS_HUMAN', required: [] };
121
+ if (ctx.killSwitch) return { mayContinue: false, stopReason: 'BUDGET', required: [] };
122
+ if (ctx.guardBlocked) return { mayContinue: false, stopReason: 'GUARD_BLOCK', required: [] };
123
+ if (ctx.atCap && ctx.verificationRed) return { mayContinue: false, stopReason: 'VERIFY_STILL_RED', required: [] };
124
+ return { mayContinue: true, stopReason: null, required: [] };
125
+ }
126
+
127
+ function resolveRun(rootDir, runId) {
128
+ if (runId) return loadRun(rootDir, runId);
129
+ return getCurrentRun(rootDir);
130
+ }
131
+
132
+ // `applies` is true only for UNATTENDED. Other modes return the contract and ok.
133
+ function morningReview(rootDir, { runId = null } = {}) {
134
+ const run = resolveRun(rootDir, runId);
135
+ if (!run) {
136
+ return { ok: true, applies: false, contract: CONTRACT, runId: null, reason: 'NO_RUN' };
137
+ }
138
+ const applies = run.mode === 'UNATTENDED';
139
+ const runDir = path.join(runsDir(rootDir), run.runId);
140
+ const present = {
141
+ goal: run.goal?.frozen === true,
142
+ diff: fileExists(path.join(runDir, 'diff.patch')),
143
+ verification: fileExists(path.join(runDir, 'verification.json')),
144
+ findings: fileExists(path.join(runDir, 'findings.json')),
145
+ verdict: fileExists(path.join(runDir, 'verdict.json'))
146
+ };
147
+ const questions = pendingQuestions(rootDir, run.runId);
148
+ const violation = applies && run.state === 'DELIVERED' ? deliveryViolation(readJson(path.join(runDir, 'delivery.json'))) : null;
149
+ const policy = loadPolicy(rootDir);
150
+ const result = applies
151
+ ? classify(run, {
152
+ questions,
153
+ killSwitch: policy.killSwitch === true,
154
+ guardBlocked: guardBlocked(runDir),
155
+ atCap: Number(run.iteration) >= runMaxIterations(rootDir, run),
156
+ verificationRed: verificationRed(runDir),
157
+ deliveryViolation: violation
158
+ })
159
+ : { mayContinue: false, stopReason: null, required: [] };
160
+ const missing = result.required.filter((key) => !present[key]).map((key) => PACKET_FILES[key]);
161
+ const violations = violation ? [violation] : [];
162
+ return {
163
+ ok: violations.length === 0 && missing.length === 0,
164
+ applies,
165
+ contract: CONTRACT,
166
+ runId: run.runId,
167
+ mode: run.mode,
168
+ state: run.state,
169
+ mayContinue: applies ? result.mayContinue : false,
170
+ stopReason: result.stopReason,
171
+ morning: { present, missing, questions },
172
+ violations
173
+ };
174
+ }
175
+
176
+ module.exports = {
177
+ CONTRACT,
178
+ morningReview
179
+ };
@@ -0,0 +1,277 @@
1
+ 'use strict';
2
+
3
+ // `pr babysit` keeps an open PR moving after delivery. It reuses `pr status`
4
+ // (including GH_UNAVAILABLE) and the same T0/T1/T2 classifier as `run`.
5
+ // The only git write is `git push origin <branch>`. Merge stays with the human.
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { spawnSync } = require('child_process');
10
+ const { classifyTier } = require('./tier.js');
11
+ const { sleepSync, writePrivateJson } = require('./fsutil.js');
12
+
13
+ const BACKOFF_MS = Object.freeze([2000, 4000, 8000, 16000, 30000]);
14
+ const MAX_POLLS = 8;
15
+
16
+ const fail = (message, code, fix, why) => Object.assign(new Error(message), { code, fix, ...(why ? { why } : {}) });
17
+
18
+ function backoffMs(waitIndex) {
19
+ return BACKOFF_MS[Math.min(Math.max(0, waitIndex), BACKOFF_MS.length - 1)];
20
+ }
21
+
22
+ function pushArgs(branch) {
23
+ const name = String(branch || '');
24
+ if (!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,200}$/.test(name) || name.includes('..') || name.endsWith('/') || name.endsWith('.lock')) {
25
+ throw fail(`Refusing to push "${branch || ''}"`, 'INVALID_BRANCH', 'Pass a plain branch name. pr babysit only runs `git push origin <branch>`.');
26
+ }
27
+ return ['push', 'origin', name];
28
+ }
29
+
30
+ function pushSameBranch(rootDir, branch) {
31
+ const args = pushArgs(branch);
32
+ const result = spawnSync('git', args, { cwd: rootDir, encoding: 'utf8' });
33
+ if (result.status !== 0) {
34
+ const detail = `${result.stderr || ''}${result.stdout || ''}`.trim().split('\n').pop() || `git exited ${result.status}`;
35
+ throw fail(`Could not push ${branch}: ${detail}`, 'PUSH_FAILED', `git ${args.join(' ')}`);
36
+ }
37
+ return { pushed: true };
38
+ }
39
+
40
+ function failingCheckNames(status) {
41
+ const line = (status?.blockers || []).find((item) => String(item).startsWith('failing-checks:'));
42
+ if (!line) return [];
43
+ return [...new Set(line.slice('failing-checks:'.length).split(',').map((part) => part.trim()).filter(Boolean))];
44
+ }
45
+
46
+ function fixTask(checks) {
47
+ return `Fix failing checks: ${checks.join(', ')}`;
48
+ }
49
+
50
+ function classifyFix(checks, changedPaths = []) {
51
+ return classifyTier({ task: fixTask(checks), changedPaths });
52
+ }
53
+
54
+ function porcelainPaths(rootDir) {
55
+ const result = spawnSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: rootDir, encoding: 'utf8' });
56
+ if (result.status !== 0) return [];
57
+ return String(result.stdout || '').split('\n')
58
+ .map((line) => line.slice(3).trim())
59
+ .filter((line) => line && !line.startsWith('.ai-engineering-loop/'))
60
+ .map((line) => (line.includes(' -> ') ? line.split(' -> ').pop() : line));
61
+ }
62
+
63
+ function currentBranch(rootDir) {
64
+ const result = spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: rootDir, encoding: 'utf8' });
65
+ if (result.status !== 0) return null;
66
+ const name = String(result.stdout || '').trim();
67
+ return name || null;
68
+ }
69
+
70
+ function decide(status, tier = null) {
71
+ const pr = status?.pr ?? '?';
72
+ if (status?.verdict === 'ready') {
73
+ return { action: 'stop', reason: 'ready', message: `PR #${pr} is ready to merge. You merge it. This command stops here.` };
74
+ }
75
+ if ((status?.blockers || []).includes('changes-requested')) {
76
+ return { action: 'stop', reason: 'changes-requested', message: `PR #${pr} has changes requested. Ask the human. This command stops here.` };
77
+ }
78
+ const checks = failingCheckNames(status);
79
+ if (checks.length) {
80
+ if (tier !== 'T0' && tier !== 'T1') {
81
+ return { action: 'stop', reason: 'tier-t2', checks, message: `Failing checks (${checks.join(', ')}) classify as T2. This command only starts a T0 or T1 fix. A human takes this one.` };
82
+ }
83
+ return { action: 'fix', reason: 'failing-checks', checks, tier, message: '' };
84
+ }
85
+ if (status?.verdict === 'waiting') return { action: 'poll', reason: 'waiting', message: '' };
86
+ if (status?.verdict === 'merged') return { action: 'stop', reason: 'merged', message: `PR #${pr} is merged.` };
87
+ if (status?.verdict === 'closed') return { action: 'stop', reason: 'closed', message: `PR #${pr} is closed.` };
88
+ const named = (status?.blockers || []).join(', ') || status?.verdict || 'blocked';
89
+ return { action: 'stop', reason: 'blocker', message: `PR #${pr} is blocked (${named}). This command only starts a fix for failing checks. A human takes the rest.` };
90
+ }
91
+
92
+ function present(status, extra) {
93
+ return {
94
+ pr: status?.pr ?? null,
95
+ url: status?.url ?? null,
96
+ branch: status?.branch ?? null,
97
+ verdict: status?.verdict ?? null,
98
+ blockers: status?.blockers || [],
99
+ ...(status?.waitingOn ? { waitingOn: status.waitingOn } : {}),
100
+ ...extra
101
+ };
102
+ }
103
+
104
+ function runDir(rootDir, runId) {
105
+ return path.join(rootDir, '.ai-engineering-loop', 'runs', runId);
106
+ }
107
+
108
+ function readFixPass(rootDir, runId) {
109
+ try {
110
+ return JSON.parse(fs.readFileSync(path.join(runDir(rootDir, runId), 'fix-pass.json'), 'utf8'));
111
+ } catch {
112
+ return null;
113
+ }
114
+ }
115
+
116
+ function sameChecks(left, right) {
117
+ return [...left].sort().join('\0') === [...right].sort().join('\0');
118
+ }
119
+
120
+ function nextStep(tier, runId, branch, parentRunId, startedNext) {
121
+ const stay = `Stay on ${branch}.`;
122
+ const again = `Then: ai-engineering-loop pr babysit --run ${parentRunId}`;
123
+ if (startedNext) return `${stay} ${startedNext} ${again}`;
124
+ if (tier === 'T0') return `${stay} Make the fix, then: npx ai-engineering-loop quick finish --run ${runId}. ${again}`;
125
+ return `${stay} Continue the T1 loop for Run ${runId} (Goal Contract, Maker, verify, review). ${again}`;
126
+ }
127
+
128
+ function startFixPass(rootDir, { task, checks, branch, parentRunId }) {
129
+ const { getCurrentRun, TERMINAL_STATES } = require('./run-state.js');
130
+ const current = getCurrentRun(rootDir);
131
+ if (current && !TERMINAL_STATES.has(current.state)) {
132
+ const recorded = readFixPass(rootDir, current.runId);
133
+ if (recorded && recorded.parentRunId === parentRunId && sameChecks(recorded.checks || [], checks)) {
134
+ const tier = current.tier?.current || recorded.tier;
135
+ return { runId: current.runId, tier, resumed: true, next: nextStep(tier, current.runId, branch, parentRunId) };
136
+ }
137
+ throw fail(
138
+ `Run ${current.runId} is still ${current.state}, so pr babysit will not start another fix pass.`,
139
+ 'ACTIVE_RUN',
140
+ `Finish Run ${current.runId}, or abandon it, then retry \`ai-engineering-loop pr babysit --run ${parentRunId}\``,
141
+ 'One checkout keeps one unfinished Run. A fix pass waits until that Run is finished.'
142
+ );
143
+ }
144
+ const started = require('./quick.js').startQuick(rootDir, { task });
145
+ if (started.tier !== 'T0' && started.tier !== 'T1') {
146
+ return { runId: started.runId, tier: started.tier, refused: true, next: started.next };
147
+ }
148
+ writePrivateJson(path.join(runDir(rootDir, started.runId), 'fix-pass.json'), {
149
+ schemaVersion: 1,
150
+ parentRunId,
151
+ branch,
152
+ tier: started.tier,
153
+ checks
154
+ });
155
+ return {
156
+ runId: started.runId,
157
+ tier: started.tier,
158
+ resumed: false,
159
+ next: nextStep(started.tier, started.runId, branch, parentRunId, started.next)
160
+ };
161
+ }
162
+
163
+ function babysit(rootDir, {
164
+ runId = null,
165
+ maxPolls = MAX_POLLS,
166
+ sleep = sleepSync,
167
+ readStatus = null,
168
+ startFix = null,
169
+ push = null
170
+ } = {}) {
171
+ if (!runId) {
172
+ throw fail('Use: pr babysit --run <id> [--json]', 'INVALID_USAGE', 'ai-engineering-loop pr babysit --run <id>');
173
+ }
174
+ const read = readStatus || (() => require('./pr-status.js').prStatus(rootDir, { runId }));
175
+ const start = startFix || ((spec) => startFixPass(rootDir, spec));
176
+ const pushFn = push || ((branch) => pushSameBranch(rootDir, branch));
177
+ const limit = Math.max(1, Number(maxPolls) || MAX_POLLS);
178
+ let waits = 0;
179
+ for (let poll = 1; poll <= limit; poll += 1) {
180
+ const status = read();
181
+ const checks = failingCheckNames(status);
182
+ const blockedByReview = (status.blockers || []).includes('changes-requested');
183
+ const assessed = checks.length && !blockedByReview && status.verdict !== 'ready'
184
+ ? classifyFix(checks, porcelainPaths(rootDir))
185
+ : null;
186
+ const decision = decide(status, assessed?.tier || null);
187
+ if (decision.action === 'poll') {
188
+ if (poll === limit) {
189
+ return present(status, {
190
+ action: 'waiting',
191
+ reason: 'pending',
192
+ message: `PR #${status.pr} is still waiting after ${poll} polls. Run pr babysit again.`,
193
+ polls: poll,
194
+ runId
195
+ });
196
+ }
197
+ sleep(backoffMs(waits));
198
+ waits += 1;
199
+ continue;
200
+ }
201
+ if (decision.action === 'stop') {
202
+ return present(status, {
203
+ action: 'stop',
204
+ reason: decision.reason,
205
+ message: decision.message,
206
+ polls: poll,
207
+ runId,
208
+ ...(assessed ? { tier: assessed.tier } : {}),
209
+ ...(decision.checks ? { checks: decision.checks } : {})
210
+ });
211
+ }
212
+ const branch = status.branch;
213
+ pushArgs(branch);
214
+ const here = currentBranch(rootDir);
215
+ if (here && here !== branch) {
216
+ return present(status, {
217
+ action: 'stop',
218
+ reason: 'wrong-branch',
219
+ message: `The PR branch is ${branch} and this checkout is on ${here}. Continue on ${branch}, then run pr babysit again.`,
220
+ next: `git checkout ${branch}`,
221
+ polls: poll,
222
+ runId,
223
+ tier: decision.tier,
224
+ checks: decision.checks
225
+ });
226
+ }
227
+ const fix = start({
228
+ task: fixTask(decision.checks),
229
+ checks: decision.checks,
230
+ tier: decision.tier,
231
+ branch,
232
+ parentRunId: runId
233
+ });
234
+ if (fix.refused || (fix.tier !== 'T0' && fix.tier !== 'T1')) {
235
+ return present(status, {
236
+ action: 'stop',
237
+ reason: 'tier-t2',
238
+ message: `The fix pass classified as ${fix.tier || 'T2'}. This command only continues a T0 or T1 fix. A human takes this one.`,
239
+ polls: poll,
240
+ runId,
241
+ tier: fix.tier || 'T2',
242
+ checks: decision.checks,
243
+ ...(fix.runId ? { fixRunId: fix.runId } : {})
244
+ });
245
+ }
246
+ const pushed = pushFn(branch);
247
+ const verb = fix.resumed ? 'Continuing' : 'Started';
248
+ return present(status, {
249
+ action: 'fix',
250
+ reason: 'failing-checks',
251
+ message: `${verb} a ${fix.tier} fix pass (${fix.runId}) for ${decision.checks.join(', ')} on ${branch}. Pushed ${branch}. You merge when the PR is ready.`,
252
+ next: fix.next,
253
+ tier: fix.tier,
254
+ checks: decision.checks,
255
+ fixRunId: fix.runId,
256
+ resumed: Boolean(fix.resumed),
257
+ pushed: pushed?.pushed !== false,
258
+ polls: poll,
259
+ runId
260
+ });
261
+ }
262
+ throw fail('pr babysit stopped without a decision', 'PR_BABYSIT_FAILED', 'ai-engineering-loop pr babysit --run <id>');
263
+ }
264
+
265
+ module.exports = {
266
+ BACKOFF_MS,
267
+ MAX_POLLS,
268
+ backoffMs,
269
+ babysit,
270
+ classifyFix,
271
+ decide,
272
+ failingCheckNames,
273
+ fixTask,
274
+ pushArgs,
275
+ pushSameBranch,
276
+ startFixPass
277
+ };
@@ -111,19 +111,40 @@ function copyContext(fromRoot, toRoot) {
111
111
  }
112
112
  }
113
113
 
114
- function createWorktree(rootDir, { task, now = new Date() }) {
114
+ function resolveBase(mainRoot, baseRef) {
115
+ if (baseRef == null || baseRef === '') {
116
+ return { base: git(mainRoot, ['rev-parse', 'HEAD']), baseRef: 'HEAD' };
117
+ }
118
+ const name = String(baseRef).trim();
119
+ if (!/^[A-Za-z0-9._/-]+$/.test(name) || name.includes('..') || name.startsWith('-') || name.endsWith('/')) {
120
+ throw fail('--base needs a branch or commit that is already in this repository.', 'INVALID_USAGE', {
121
+ why: 'A stacked Run starts from a local commit. AEL does not fetch.',
122
+ fix: 'ael run --worktree --base <branch> "<task>"'
123
+ });
124
+ }
125
+ const resolved = git(mainRoot, ['rev-parse', '--verify', '--quiet', `${name}^{commit}`], { allowFail: true });
126
+ if (!resolved) {
127
+ throw fail(`--base ${name} is not a commit in this repository.`, 'INVALID_USAGE', {
128
+ why: 'A stacked Run starts from a commit that already exists here. AEL does not fetch.',
129
+ fix: 'git rev-parse --verify <branch>'
130
+ });
131
+ }
132
+ return { base: resolved, baseRef: name };
133
+ }
134
+
135
+ function createWorktree(rootDir, { task, now = new Date(), baseRef = null } = {}) {
115
136
  if (!String(task || '').trim()) throw fail('run --worktree needs a task: run --worktree "<task>"');
116
137
  const mainRoot = mainCheckout(rootDir);
117
138
  if (!mainRoot) throw fail('run --worktree needs a git repository');
139
+ const resolved = resolveBase(mainRoot, baseRef);
118
140
  const id = now.toISOString().replace(/\D/g, '').slice(2, 12);
119
141
  const slug = `${slugOf(task)}-${id}`;
120
142
  const branch = `ael/${slug}`;
121
143
  const worktreePath = path.join(path.dirname(mainRoot), `${path.basename(mainRoot)}.ael-worktrees`, slug);
122
- const base = git(mainRoot, ['rev-parse', 'HEAD']);
123
144
  fs.mkdirSync(path.dirname(worktreePath), { recursive: true });
124
- git(mainRoot, ['worktree', 'add', '--quiet', '-b', branch, worktreePath, base]);
145
+ git(mainRoot, ['worktree', 'add', '--quiet', '-b', branch, worktreePath, resolved.base]);
125
146
  copyContext(mainRoot, worktreePath);
126
- return { mainRoot, path: worktreePath, branch, base };
147
+ return { mainRoot, path: worktreePath, branch, base: resolved.base, baseRef: resolved.baseRef };
127
148
  }
128
149
 
129
150
  function registerWorktree(mainRoot, entry) {
package/lib/spike.js ADDED
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+
3
+ // A throwaway prototype before the Goal is frozen. The command records the
4
+ // question and what the contract should say. It does not keep the spike code.
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { atomicWriteJson, getCurrentRun, loadRun, runsDir } = require('./run-state.js');
9
+
10
+ const MIN_TEXT = 8;
11
+ const MAX_QUESTION = 500;
12
+ const MAX_LEARNED = 2000;
13
+
14
+ function spikeError(message, code, extra = {}) {
15
+ return Object.assign(new Error(message), { code, ...extra });
16
+ }
17
+
18
+ function resolveRun(rootDir, runId) {
19
+ if (runId) return loadRun(rootDir, runId);
20
+ const current = getCurrentRun(rootDir);
21
+ if (!current) {
22
+ throw spikeError('spike needs a Run. Start one, then record the spike before the Goal is frozen.', 'NO_RUN', {
23
+ why: 'The note is stored on the Run that the contract will freeze.',
24
+ fix: 'ael run "<task>"'
25
+ });
26
+ }
27
+ return current;
28
+ }
29
+
30
+ function bounded(value, label, max, fix) {
31
+ const text = String(value || '').trim().replace(/\s+/g, ' ');
32
+ if (text.length < MIN_TEXT || text.length > max) {
33
+ throw spikeError(`${label} must be ${MIN_TEXT}-${max} characters.`, 'INVALID_USAGE', {
34
+ why: 'The spike note is one question and what the contract should say.',
35
+ fix
36
+ });
37
+ }
38
+ return text;
39
+ }
40
+
41
+ function spikePath(rootDir, runId) {
42
+ return path.join(runsDir(rootDir), runId, 'spike.json');
43
+ }
44
+
45
+ function recordSpike(rootDir, { runId = null, question, learned, discarded = false, now = new Date() } = {}) {
46
+ if (discarded !== true) {
47
+ throw spikeError('A spike is throwaway. Delete the prototype, then pass --discarded.', 'SPIKE_NOT_DISCARDED', {
48
+ why: 'Spike code must not become the implementation or the contract.',
49
+ fix: 'ael spike record --discarded --question "<one question>" --learned "<what the contract should say>"'
50
+ });
51
+ }
52
+ const run = resolveRun(rootDir, runId);
53
+ if (run.goal?.frozen === true || run.state !== 'STARTED') {
54
+ throw spikeError('Record the spike before the Goal is frozen.', 'GOAL_ALREADY_FROZEN', {
55
+ why: 'The spike informs the contract. After freeze the contract does not move.',
56
+ fix: 'Write the Goal from what you learned, then ask the human to freeze.'
57
+ });
58
+ }
59
+ const doc = {
60
+ schemaVersion: 1,
61
+ runId: run.runId,
62
+ question: bounded(question, '--question', MAX_QUESTION, 'ael spike record --discarded --question "<one question>" --learned "<what you learned>"'),
63
+ learned: bounded(learned, '--learned', MAX_LEARNED, 'ael spike record --discarded --question "<one question>" --learned "<what the contract should say>"'),
64
+ discarded: true,
65
+ recordedAt: now.toISOString()
66
+ };
67
+ atomicWriteJson(spikePath(rootDir, run.runId), doc);
68
+ return { ...doc, path: `.ai-engineering-loop/runs/${run.runId}/spike.json` };
69
+ }
70
+
71
+ function showSpike(rootDir, { runId = null } = {}) {
72
+ let run = null;
73
+ try {
74
+ run = runId ? loadRun(rootDir, runId) : getCurrentRun(rootDir);
75
+ } catch (err) {
76
+ if (err.code === 'NO_CURRENT_RUN') return { ok: true, recorded: false, runId: null };
77
+ throw err;
78
+ }
79
+ if (!run) return { ok: true, recorded: false, runId: null };
80
+ const file = spikePath(rootDir, run.runId);
81
+ if (!fs.existsSync(file)) return { ok: true, recorded: false, runId: run.runId };
82
+ let doc;
83
+ try {
84
+ doc = JSON.parse(fs.readFileSync(file, 'utf8'));
85
+ } catch (cause) {
86
+ return { ok: false, recorded: true, runId: run.runId, code: 'INVALID_SPIKE', error: `spike.json is not valid JSON: ${cause.message}` };
87
+ }
88
+ if (doc?.discarded !== true || !String(doc.question || '').trim() || !String(doc.learned || '').trim()) {
89
+ return {
90
+ ok: false,
91
+ recorded: true,
92
+ runId: run.runId,
93
+ code: 'SPIKE_NOT_DISCARDED',
94
+ error: 'spike.json must say the prototype was discarded, with a question and what was learned.',
95
+ fix: 'ael spike record --discarded --question "<one question>" --learned "<what the contract should say>"'
96
+ };
97
+ }
98
+ return { ok: true, recorded: true, runId: run.runId, spike: doc };
99
+ }
100
+
101
+ module.exports = {
102
+ recordSpike,
103
+ showSpike
104
+ };
package/lib/ste.js CHANGED
@@ -49,6 +49,21 @@ const line = (text) => String(text || '').replace(/\s+/g, ' ').trim();
49
49
 
50
50
  function renderHumanGoal(goal, { runId = goal?.runId, revision = null } = {}) {
51
51
  const parts = [`# Goal${runId ? ` for Run ${runId}` : ''}${revision != null ? ` (revision ${revision})` : ''}`, ''];
52
+ const restate = goal?.restatement;
53
+ if (restate && typeof restate === 'object' && !Array.isArray(restate)) {
54
+ parts.push(
55
+ '## Restate',
56
+ '',
57
+ `Problem: ${line(restate.problem)}`,
58
+ '',
59
+ `Done when: ${line(restate.doneWhen)}`,
60
+ '',
61
+ `Fail if: ${line(restate.failIf)}`,
62
+ '',
63
+ `Unknowns: ${line(restate.unknowns)}`,
64
+ ''
65
+ );
66
+ }
52
67
  parts.push('## What changes', '', line(goal?.plainSummary || goal?.objective), '');
53
68
  parts.push('## Done when', '');
54
69
  for (const criterion of goal?.acceptanceCriteria || []) {
@@ -99,8 +99,7 @@ const VERIFICATION_CATALOG = Object.freeze({
99
99
  formal: { layer: 'LF', plan: false, what: 'formal verification (TLA+, Lean, model checking)' }
100
100
  });
101
101
  const LAYER_OF_KEY = Object.freeze(Object.fromEntries(Object.entries(VERIFICATION_CATALOG).map(([key, entry]) => [key, entry.layer])));
102
- // Cheapest-first default plan (templates/repo-config/verification.md
103
- // "Default order"): L1 static checks, then L2 unit and property tests.
102
+ // Cheapest-first default plan: L1 static checks, then L2 unit and property tests.
104
103
  const DEFAULT_PLAN_KEYS = Object.freeze(Object.keys(VERIFICATION_CATALOG).filter((key) => VERIFICATION_CATALOG[key].plan));
105
104
 
106
105
  function layerOfKey(key) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-engineering-loop",
3
- "version": "2.14.0",
3
+ "version": "2.15.0",
4
4
  "description": "A visual workspace that helps AI coding agents plan, build, review, and ship reliable software.",
5
5
  "main": "bin/ai-engineering-loop.js",
6
6
  "bin": {
@@ -7,6 +7,7 @@
7
7
  "schemaVersion",
8
8
  "runId",
9
9
  "objective",
10
+ "restatement",
10
11
  "acceptanceCriteria"
11
12
  ],
12
13
  "properties": {
@@ -21,6 +22,18 @@
21
22
  "type": "string",
22
23
  "minLength": 1
23
24
  },
25
+ "restatement": {
26
+ "description": "Required by goal draft. The problem in the agent's own words, written before acceptance criteria, so a freeze cannot lock the human's method. The four fields name the outcome. They do not name steps, files or libraries.",
27
+ "type": "object",
28
+ "additionalProperties": false,
29
+ "required": ["problem", "doneWhen", "failIf", "unknowns"],
30
+ "properties": {
31
+ "problem": { "type": "string", "minLength": 1 },
32
+ "doneWhen": { "type": "string", "minLength": 1 },
33
+ "failIf": { "type": "string", "minLength": 1 },
34
+ "unknowns": { "type": "string", "minLength": 1 }
35
+ }
36
+ },
24
37
  "acceptanceCriteria": {
25
38
  "type": "array",
26
39
  "minItems": 1,