ai-engineering-loop 2.14.1 → 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 (41) 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 +23 -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 +446 -39
  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/package.json +1 -1
  41. package/schemas/goal-contract.schema.json +13 -0
@@ -30,6 +30,36 @@ function actorId(actor) {
30
30
  return value;
31
31
  }
32
32
 
33
+ // Names an agent uses for itself. A real person (`pengguna`, `alice`, `human`,
34
+ // `studio-user`, the bench `scripted-approver`) is not in this set.
35
+ const SELF_FREEZE_EXACT = new Set([
36
+ 'agent', 'agents', 'ael', 'ael-agent', 'assistant', 'bot', 'ai', 'llm',
37
+ 'model', 'system', 'auto', 'opencode'
38
+ ]);
39
+ const SELF_FREEZE_TOKEN = new Set(['agent', 'assistant', 'bot', 'llm']);
40
+ const MODEL_PREFIX = /^(?:gpt|claude|gemini|deepseek|llama|qwen|grok|codex|chatgpt|openai|anthropic)(?:$|[-_.])/i;
41
+ const MODEL_TAIL = new Set(['sonnet', 'opus', 'haiku', 'flash']);
42
+
43
+ function freezeActorError(message, runId) {
44
+ const error = goalError(message, 'GOAL_FREEZE_NOT_HUMAN');
45
+ error.why = 'Only the human can freeze the Goal. An agent name, a model id, or an empty --by records the agent as the approver.';
46
+ error.fix = `Wait until the human agrees. Then rerun \`goal freeze --latest --run ${runId} --by <their name>\`. If the question was cancelled or unanswered, stop and wait.`;
47
+ return error;
48
+ }
49
+
50
+ function humanFreezeActor(actor, runId) {
51
+ const raw = String(actor ?? '').trim();
52
+ if (!raw) throw freezeActorError('goal freeze requires --by <human name>', runId);
53
+ const value = actorId(raw);
54
+ const lower = value.toLowerCase();
55
+ const tokens = lower.split(/[-_.]+/).filter(Boolean);
56
+ const model = MODEL_PREFIX.test(lower) || (tokens.length > 1 && tokens.some((token) => MODEL_TAIL.has(token)));
57
+ if (SELF_FREEZE_EXACT.has(lower) || tokens.some((token) => SELF_FREEZE_TOKEN.has(token)) || model) {
58
+ throw freezeActorError(`goal freeze refuses --by ${value}`, runId);
59
+ }
60
+ return value;
61
+ }
62
+
33
63
  function goalPaths(rootDir, runId, version) {
34
64
  const directory = path.join(runsDir(rootDir), runId);
35
65
  return {
@@ -187,7 +217,7 @@ function freezeGoal(
187
217
  if (unfilled.length) {
188
218
  throw goalError(`Fill the <fill: ...> placeholders before freezing: ${unfilled.join(', ')}`, 'GOAL_PLACEHOLDERS', unfilled);
189
219
  }
190
- const human = actorId(actor);
220
+ const human = humanFreezeActor(actor, runId);
191
221
  if (fs.existsSync(paths.version)) {
192
222
  throw goalError(`Goal version ${version} already exists`, 'GOAL_VERSION_EXISTS');
193
223
  }
@@ -125,7 +125,7 @@ function auditFeatureMap(rootDir) {
125
125
  const commands = lanes.verificationCommands(rootDir);
126
126
  if (!commands.e2e && !commands.smoke) return [];
127
127
  if (require('./feature-map.js').loadFeatureMap(rootDir).length) return [];
128
- return [{ id: 'feature-map', level: 'warn', detail: 'e2e/smoke is configured but .ai-engineering-loop/feature-map.md is missing or empty. FIX: list user-facing features (Feature | Where | Paths | How to reach | Driver) so agents and reviewers share one vocabulary for runtime checks.' }];
128
+ return [{ id: 'feature-map', level: 'warn', detail: 'e2e/smoke is configured but .ai-engineering-loop/feature-map.md is missing or empty. FIX: `feature-map scaffold`, or list user-facing features (Feature | Where | Paths | How to reach | Driver) so agents and reviewers share one vocabulary for runtime checks.' }];
129
129
  }
130
130
 
131
131
  function auditFeatureMapDrift(rootDir) {
@@ -0,0 +1,460 @@
1
+ 'use strict';
2
+
3
+ // Turn a bug report into one red-repro Goal, then the normal loop.
4
+ // Connectors are read-only: `gh issue view` / `glab issue view` only.
5
+ // A pasted report uses the same draft (`outcome repro --file`).
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { spawnSync } = require('child_process');
10
+ const { DOT_GITLAB_HOST, detectAdapter } = require('./adapter-detect.js');
11
+
12
+ const MAX_REPORT_BYTES = 256 * 1024;
13
+ const VIEW_FLAGS = new Set(['--json', '--output', '--repo']);
14
+ const WRITE_WORDS = new Set(['comment', 'create', 'close', 'update', 'edit', 'note', 'reopen', 'delete', 'lock', 'unlock', 'merge', 'pin', 'unpin']);
15
+ const RUNNERS = /^(?:npm|npx|pnpm|yarn|bun|node|deno|python3?|pytest|go|cargo|make|mvn|gradle|dotnet|rspec|bundle|php|composer|rails|mix|just|tox|jest|vitest|mocha)(?:\s|$)/;
16
+ const FILE_FIX = 'Paste the report into `.ai-engineering-loop/drafts/bug-report.md` (a title, `Actual: <what fails>`, and `Verify: <command>`), then run `ael outcome repro --file .ai-engineering-loop/drafts/bug-report.md`.';
17
+
18
+ function fail(message, code, fix, why = null) {
19
+ return Object.assign(new Error(message), { code, fix, why: why || message });
20
+ }
21
+
22
+ function sentence(text, max = 240) {
23
+ const flat = String(text || '').replace(/\s+/g, ' ').trim();
24
+ if (!flat) return '';
25
+ const first = flat.split(/(?<=[.!?])\s/)[0].trim();
26
+ return first.length > max ? first.slice(0, max).trim() : first;
27
+ }
28
+
29
+ function looksLikeCommand(value) {
30
+ const text = String(value || '').trim();
31
+ if (!text || /[\r\n]/.test(text) || text.length > 300) return false;
32
+ if (/^(?:\.\/|\/|bin\/)/.test(text)) return true;
33
+ return RUNNERS.test(text);
34
+ }
35
+
36
+ function commandText(line) {
37
+ let text = String(line || '').trim().replace(/^\$\s*/, '').replace(/^(?:[-*]|\d+[.)])\s+/, '');
38
+ if (text.startsWith('`') && text.endsWith('`') && text.length > 2) text = text.slice(1, -1).trim();
39
+ if (text.endsWith('.') && looksLikeCommand(text.slice(0, -1))) text = text.slice(0, -1);
40
+ return text;
41
+ }
42
+
43
+ function asCommand(line) {
44
+ const text = commandText(line);
45
+ return looksLikeCommand(text) ? text : null;
46
+ }
47
+
48
+ function assertVerifyCommand(command) {
49
+ const value = String(command || '').trim();
50
+ if (!looksLikeCommand(value)) {
51
+ throw fail('The red repro needs one local verify command.', 'REPRO_COMMAND_INVALID', 'Example: `Verify: npm test -- export.test.js`, or one ```bash fence with that command.');
52
+ }
53
+ if (/\b(?:gh|glab)\b/i.test(value)) {
54
+ throw fail('The verify command must be a local test or driver, not gh or glab.', 'REPRO_COMMAND_INVALID', 'Use the command that fails today, for example `npm test -- export.test.js`.');
55
+ }
56
+ return value;
57
+ }
58
+
59
+ function labeled(text, name) {
60
+ const match = String(text || '').match(new RegExp(`^${name}\\s*:\\s*(.+)$`, 'im'));
61
+ return match ? match[1].trim() : null;
62
+ }
63
+
64
+ function sections(text) {
65
+ const blocks = [];
66
+ let current = { heading: '', body: [] };
67
+ for (const line of String(text || '').split(/\r?\n/)) {
68
+ const heading = line.match(/^#{1,3}\s+(.+?)\s*$/);
69
+ if (heading) {
70
+ blocks.push(current);
71
+ current = { heading: heading[1].trim(), body: [] };
72
+ } else {
73
+ current.body.push(line);
74
+ }
75
+ }
76
+ blocks.push(current);
77
+ return blocks;
78
+ }
79
+
80
+ function paragraphOf(lines) {
81
+ const buf = [];
82
+ for (const line of lines) {
83
+ const trimmed = line.trim();
84
+ if (!trimmed || trimmed.startsWith('```')) {
85
+ if (buf.length) break;
86
+ continue;
87
+ }
88
+ if (asCommand(trimmed)) continue;
89
+ buf.push(trimmed.replace(/^(?:[-*]|\d+[.)])\s+/, ''));
90
+ }
91
+ return buf.join(' ');
92
+ }
93
+
94
+ function fencedCommand(text) {
95
+ const re = /```([^\n`]*)\n([\s\S]*?)```/g;
96
+ let match;
97
+ while ((match = re.exec(String(text || '')))) {
98
+ const lang = match[1].trim().toLowerCase().split(/\s+/)[0];
99
+ if (!['bash', 'sh', 'shell', 'console', 'zsh'].includes(lang)) continue;
100
+ for (const line of match[2].split(/\r?\n/)) {
101
+ if (!line.trim() || line.trim().startsWith('#')) continue;
102
+ const command = asCommand(line);
103
+ if (command) return command;
104
+ }
105
+ }
106
+ return null;
107
+ }
108
+
109
+ function commandUnderHeading(text) {
110
+ for (const block of sections(text)) {
111
+ if (!/repro|steps|verify|command|driver/i.test(block.heading)) continue;
112
+ for (const line of block.body) {
113
+ const command = asCommand(line);
114
+ if (command) return command;
115
+ }
116
+ }
117
+ return null;
118
+ }
119
+
120
+ function extractCommand(text) {
121
+ for (const name of ['verify', 'driver', 'command']) {
122
+ const value = labeled(text, name);
123
+ if (!value) continue;
124
+ const command = asCommand(value);
125
+ if (!command) {
126
+ throw fail(`\`${name}:\` must be the local command that fails today.`, 'REPRO_COMMAND_INVALID', 'Example: `Verify: npm test -- export.test.js`.');
127
+ }
128
+ return assertVerifyCommand(command);
129
+ }
130
+ const found = fencedCommand(text) || commandUnderHeading(text);
131
+ return found ? assertVerifyCommand(found) : '';
132
+ }
133
+
134
+ function firstProse(text) {
135
+ const stripped = String(text || '').replace(/```[\s\S]*?```/g, '');
136
+ const buf = [];
137
+ for (const line of stripped.split(/\r?\n/)) {
138
+ if (/^#{1,6}\s/.test(line)) {
139
+ if (buf.length) break;
140
+ continue;
141
+ }
142
+ if (/^(?:verify|driver|command|repro|actual|current|failure|fails|bug|observed|symptom|title|expected)\s*:/i.test(line)) continue;
143
+ if (!line.trim()) {
144
+ if (buf.length) break;
145
+ continue;
146
+ }
147
+ if (asCommand(line)) continue;
148
+ buf.push(line.trim().replace(/^(?:[-*]|\d+[.)])\s+/, ''));
149
+ }
150
+ return buf.join(' ');
151
+ }
152
+
153
+ function extractFailure(text) {
154
+ for (const name of ['actual', 'current', 'failure', 'fails', 'bug', 'observed', 'symptom']) {
155
+ const value = labeled(text, name);
156
+ if (value && !asCommand(value)) return value;
157
+ }
158
+ for (const block of sections(text)) {
159
+ if (!/actual|current|what happens|symptom|observed|failure|^bug\b/i.test(block.heading)) continue;
160
+ const paragraph = paragraphOf(block.body);
161
+ if (paragraph) return paragraph;
162
+ }
163
+ return firstProse(text);
164
+ }
165
+
166
+ function headingTitle(text) {
167
+ for (const block of sections(text)) {
168
+ if (!block.heading || /actual|expected|current|repro|steps|verify|command|driver|what happens|description|symptom|observed|failure|^bug\b/i.test(block.heading)) continue;
169
+ return block.heading;
170
+ }
171
+ return '';
172
+ }
173
+
174
+ function parseReport(text, { title = '', source = 'file', ref = null } = {}) {
175
+ const body = String(text || '').replace(/^\uFEFF/, '');
176
+ const command = extractCommand(body);
177
+ if (!command) {
178
+ throw fail('The report has no verify command that fails today.', 'REPRO_COMMAND_MISSING', `Add \`Verify: <command>\` or one \`\`\`bash fence. ${FILE_FIX}`, 'A red-repro Goal names the command that is red now. AEL does not invent one.');
179
+ }
180
+ const resolvedTitle = sentence(title || labeled(body, 'title') || headingTitle(body), 120);
181
+ const failing = sentence(extractFailure(body) || resolvedTitle);
182
+ if (!resolvedTitle && !failing) {
183
+ throw fail('The report has no title.', 'REPRO_TITLE_MISSING', 'Add a first line `# <bug title>`.', 'The Run task is the bug title.');
184
+ }
185
+ if (!failing) {
186
+ throw fail('The report has no failing behavior.', 'REPRO_BEHAVIOR_MISSING', 'Add `Actual: <what fails today>`.', 'The Goal needs one concrete failure, not a sunny-path statement.');
187
+ }
188
+ return { title: (resolvedTitle || failing).replace(/[.]+$/, ''), failingBehavior: failing, command, source, ref };
189
+ }
190
+
191
+ function reproContract(runId, report) {
192
+ const failing = sentence(report.failingBehavior);
193
+ const command = assertVerifyCommand(report.command);
194
+ const title = sentence(report.title, 120).replace(/[.]+$/, '');
195
+ return {
196
+ schemaVersion: 1,
197
+ runId,
198
+ objective: `Fix the reported failure: ${title}.`,
199
+ restatement: {
200
+ problem: failing,
201
+ doneWhen: 'The reported failure no longer happens.',
202
+ failIf: failing,
203
+ unknowns: 'None.'
204
+ },
205
+ acceptanceCriteria: [{
206
+ id: 'AC-1',
207
+ statement: 'The verify command exits 0.',
208
+ evidenceRequired: `red repro turns green: ${command}`,
209
+ failureCases: [failing],
210
+ verify: { command, layer: 'L2' }
211
+ }],
212
+ outOfScope: ['A change that leaves this red repro failing'],
213
+ repro: {
214
+ source: report.source,
215
+ ref: report.ref,
216
+ readOnly: true,
217
+ command,
218
+ failingBehavior: failing,
219
+ title
220
+ }
221
+ };
222
+ }
223
+
224
+ function hostnameOf(url) {
225
+ return url.hostname.toLowerCase().replace(/^www\./, '');
226
+ }
227
+
228
+ function safeProject(project) {
229
+ const parts = String(project || '').split('/');
230
+ if (!parts.length || parts.some((part) => !part || part === '.' || part === '..' || part.startsWith('-'))) return null;
231
+ return parts.join('/');
232
+ }
233
+
234
+ function parseIssueRef(input) {
235
+ const text = String(input || '').trim();
236
+ const hash = text.match(/^#(\d+)$/);
237
+ if (hash) return { number: Number(hash[1]), url: null, host: null, project: null };
238
+ let url;
239
+ try {
240
+ url = new URL(text);
241
+ } catch {
242
+ url = null;
243
+ }
244
+ if (!url || !['http:', 'https:'].includes(url.protocol)) {
245
+ throw fail('Pass an issue URL or #number.', 'INVALID_ISSUE_REF', 'ael run --from-issue https://github.com/owner/repo/issues/12', 'A #number uses the origin host. A URL names the host.');
246
+ }
247
+ const host = hostnameOf(url);
248
+ if (host === 'github.com') {
249
+ const match = url.pathname.match(/^\/([^/]+)\/([^/]+)\/issues\/(\d+)\/?$/);
250
+ if (!match) {
251
+ throw fail('That GitHub URL is not an issue.', 'INVALID_ISSUE_REF', 'Use https://github.com/<owner>/<repo>/issues/<n>, or paste the report with `ael outcome repro --file <path>`.');
252
+ }
253
+ const project = safeProject(`${match[1]}/${match[2]}`);
254
+ if (!project) throw fail('That GitHub URL is not an issue.', 'INVALID_ISSUE_REF', FILE_FIX);
255
+ return { host: 'github', number: Number(match[3]), url: url.href, project };
256
+ }
257
+ if (host === DOT_GITLAB_HOST || host.includes('gitlab')) {
258
+ const match = url.pathname.match(/^(.*)\/-\/issues\/(\d+)\/?$/);
259
+ const project = match ? safeProject(match[1].replace(/^\//, '')) : null;
260
+ if (!match || !project) {
261
+ throw fail('That GitLab URL is not an issue.', 'INVALID_ISSUE_REF', 'Use https://gitlab.com/<group>/<repo>/-/issues/<n>, or paste the report with `ael outcome repro --file <path>`.');
262
+ }
263
+ return { host: 'gitlab', number: Number(match[2]), url: url.href, project };
264
+ }
265
+ throw fail(`No read-only issue reader for ${host}.`, 'UNSUPPORTED_ISSUE_HOST', FILE_FIX, 'GitHub uses gh. GitLab uses glab. Anything else is a pasted report.');
266
+ }
267
+
268
+ function issueViewPlan(ref, host) {
269
+ if (host === 'github') {
270
+ return { bin: 'gh', args: ['issue', 'view', ref.url || String(ref.number), '--json', 'number,title,body,url,state'] };
271
+ }
272
+ if (host === 'gitlab') {
273
+ const args = ['issue', 'view', String(ref.number), '--output', 'json'];
274
+ if (ref.project) args.push('--repo', ref.project);
275
+ return { bin: 'glab', args };
276
+ }
277
+ throw fail(`No read-only issue reader for ${host}.`, 'UNSUPPORTED_ISSUE_HOST', FILE_FIX);
278
+ }
279
+
280
+ function assertReadOnlyIssueView(plan) {
281
+ const bin = plan && plan.bin;
282
+ const args = plan && Array.isArray(plan.args) ? plan.args : [];
283
+ if (!['gh', 'glab'].includes(bin) || args[0] !== 'issue' || args[1] !== 'view') {
284
+ throw fail('Issue connectors are read-only: only `issue view` is allowed.', 'ISSUE_WRITE_REFUSED', 'AEL never comments on or edits the issue. Paste a report with `ael outcome repro --file <path>`.');
285
+ }
286
+ for (const arg of args) {
287
+ const token = String(arg).toLowerCase();
288
+ if (WRITE_WORDS.has(token) || (token.startsWith('-') && !VIEW_FLAGS.has(token))) {
289
+ throw fail(`Refusing \`${arg}\` on an issue connector.`, 'ISSUE_WRITE_REFUSED', 'AEL never comments on or edits the issue.');
290
+ }
291
+ }
292
+ return plan;
293
+ }
294
+
295
+ function hostForRef(rootDir, ref) {
296
+ if (ref.host) return ref.host;
297
+ const type = detectAdapter(rootDir).type;
298
+ if (type === 'github') return 'github';
299
+ if (type === 'gitlab' || type === 'dot') return 'gitlab';
300
+ throw fail('This checkout has no GitHub or GitLab remote, so #n cannot be read.', 'ISSUE_HOST_UNKNOWN', 'Pass a full issue URL, or paste the report: `ael outcome repro --file <path>`.', 'A bare #number uses the origin host.');
301
+ }
302
+
303
+ function toolFailure(host, result) {
304
+ const name = host === 'github' ? 'gh' : 'glab';
305
+ if (result.reason === 'missing') {
306
+ throw fail(`${name} is not installed, so the issue was not read.`, 'ISSUE_TOOL_MISSING', FILE_FIX, `${name} is the read-only connector for this host.`);
307
+ }
308
+ if (result.reason === 'auth') {
309
+ throw fail(`${name} is not signed in, so the issue was not read.`, 'ISSUE_TOOL_AUTH', `${FILE_FIX} Or run \`${name} auth login\` and retry.`, 'The connector only reads. It does not log in for you.');
310
+ }
311
+ if (result.reason === 'not-found') {
312
+ throw fail('No issue found for that reference.', 'ISSUE_NOT_FOUND', 'Check the URL or number, or paste the report and use `ael outcome repro --file <path>`.');
313
+ }
314
+ throw fail(`${name} could not read the issue: ${result.message || 'unknown error'}`, 'ISSUE_READ_FAILED', FILE_FIX);
315
+ }
316
+
317
+ function glabJson(args, cwd) {
318
+ const custom = process.env.AEL_GLAB_BIN;
319
+ const js = custom && /\.(c|m)?js$/.test(custom);
320
+ const bin = js ? process.execPath : (custom || 'glab');
321
+ const argv = js ? [custom, ...args] : args;
322
+ const result = spawnSync(bin, argv, { cwd, encoding: 'utf8', timeout: 20000, stdio: ['ignore', 'pipe', 'pipe'] });
323
+ if (result.error?.code === 'ENOENT') return { ok: false, reason: 'missing', message: 'GitLab CLI (glab) is not installed' };
324
+ if (result.status !== 0) {
325
+ const text = `${result.stderr || ''}${result.stdout || ''}`.trim();
326
+ const reason = /auth|not logged|401|403/i.test(text) ? 'auth' : /not found|404/i.test(text) ? 'not-found' : 'failed';
327
+ return { ok: false, reason, message: text.split('\n')[0] || `glab exited ${result.status}` };
328
+ }
329
+ try {
330
+ return { ok: true, value: JSON.parse(String(result.stdout || '').trim()) };
331
+ } catch {
332
+ return { ok: false, reason: 'failed', message: 'glab returned output that is not JSON' };
333
+ }
334
+ }
335
+
336
+ function defaultRun(plan, rootDir) {
337
+ assertReadOnlyIssueView(plan);
338
+ if (plan.bin === 'gh') {
339
+ const { ghJson } = require('./gh.js');
340
+ return ghJson(plan.args, { cwd: rootDir });
341
+ }
342
+ return glabJson(plan.args, rootDir);
343
+ }
344
+
345
+ function normalizeIssue(host, value, ref) {
346
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
347
+ throw fail('The issue tool returned no issue.', 'ISSUE_READ_FAILED', FILE_FIX);
348
+ }
349
+ const title = String(value.title || '').trim();
350
+ const body = String(host === 'github' ? (value.body || '') : (value.description || value.body || ''));
351
+ const url = value.url || value.web_url || ref.url || null;
352
+ const number = value.number || value.iid || ref.number || null;
353
+ return parseReport(body, {
354
+ title,
355
+ source: host === 'github' ? 'github' : 'gitlab',
356
+ ref: url || (number ? `#${number}` : null)
357
+ });
358
+ }
359
+
360
+ function readIssue(rootDir, input, { run = defaultRun } = {}) {
361
+ const ref = parseIssueRef(input);
362
+ const host = hostForRef(rootDir, ref);
363
+ const plan = assertReadOnlyIssueView(issueViewPlan(ref, host));
364
+ const result = run(plan, rootDir);
365
+ if (!result || !result.ok) toolFailure(host, result || { reason: 'failed', message: 'no result' });
366
+ return normalizeIssue(host, result.value, ref);
367
+ }
368
+
369
+ function readReportFile(rootDir, fileName) {
370
+ const file = path.resolve(rootDir, String(fileName || ''));
371
+ const relative = path.relative(rootDir, file);
372
+ if (!fileName || relative.startsWith('..') || path.isAbsolute(relative)) {
373
+ throw fail('The report file must stay inside the repository.', 'UNSAFE_REPORT_PATH', 'Copy it to `.ai-engineering-loop/drafts/bug-report.md` and pass that path.', 'Run files stay in the project. A path outside it is not read.');
374
+ }
375
+ let stat;
376
+ try {
377
+ stat = fs.lstatSync(file);
378
+ } catch {
379
+ throw fail(`Report file not found: ${relative}`, 'REPORT_NOT_FOUND', `Create the file, then \`ael outcome repro --file ${relative.split(path.sep).join('/')}\`.`);
380
+ }
381
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1 || stat.size > MAX_REPORT_BYTES) {
382
+ throw fail('The report must be one regular file of at most 256KB.', 'INVALID_REPORT', FILE_FIX);
383
+ }
384
+ const ref = relative.split(path.sep).join('/');
385
+ return parseReport(fs.readFileSync(file, 'utf8'), { source: 'file', ref });
386
+ }
387
+
388
+ function parseCliJson(stdout) {
389
+ const text = String(stdout || '');
390
+ const start = text.indexOf('{');
391
+ if (start === -1) return null;
392
+ try {
393
+ return JSON.parse(text.slice(start));
394
+ } catch {
395
+ return null;
396
+ }
397
+ }
398
+
399
+ function reproSummary(report, extra) {
400
+ return {
401
+ drafted: false,
402
+ revision: null,
403
+ source: report.source,
404
+ ref: report.ref,
405
+ readOnly: true,
406
+ command: report.command,
407
+ failingBehavior: report.failingBehavior,
408
+ ...extra
409
+ };
410
+ }
411
+
412
+ // Writes the contract through `goal draft` (revision, goal.md, freeze question).
413
+ // Does not freeze. The Run stays on the normal loop.
414
+ function attachReproGoal(rootDir, runId, report) {
415
+ const { loadRun } = require('./run-state.js');
416
+ const { loadGoalDraft } = require('./goal-runtime.js');
417
+ const run = loadRun(rootDir, runId);
418
+ if (run.goal?.frozen) return reproSummary(report, { reason: 'frozen', revision: run.goal.version || null });
419
+ const existing = loadGoalDraft(rootDir, runId);
420
+ if (existing) return reproSummary(report, { reason: 'draft-exists', revision: existing.metadata.revision });
421
+ const contract = reproContract(runId, report);
422
+ const validation = require('./gates.js').validateGoalContract(contract);
423
+ if (!validation.valid) {
424
+ throw fail(`Red-repro Goal is invalid: ${validation.errors[0]}`, 'GATE_FAILED', FILE_FIX);
425
+ }
426
+ const relative = '.ai-engineering-loop/drafts/repro-goal.json';
427
+ const absolute = path.join(rootDir, '.ai-engineering-loop', 'drafts', 'repro-goal.json');
428
+ fs.mkdirSync(path.dirname(absolute), { recursive: true, mode: 0o700 });
429
+ fs.writeFileSync(absolute, `${JSON.stringify(contract, null, 2)}\n`, { mode: 0o600 });
430
+ const cli = path.join(__dirname, '..', 'bin', 'ai-engineering-loop.js');
431
+ const result = spawnSync(process.execPath, [
432
+ cli, 'goal', 'draft', '--json', '--run', runId, '--file', relative, '--revision', '0', '--by', 'agent'
433
+ ], {
434
+ cwd: rootDir,
435
+ encoding: 'utf8',
436
+ env: { ...process.env, AEL_NO_AUTO_UPDATE: '1' },
437
+ maxBuffer: 8 * 1024 * 1024
438
+ });
439
+ const parsed = parseCliJson(result.stdout);
440
+ if (result.status !== 0 || !parsed || parsed.ok === false) {
441
+ const message = parsed?.error || String(result.stderr || result.stdout || 'goal draft failed').trim().split('\n').pop();
442
+ throw fail(`goal draft failed: ${message}`, parsed?.code || 'GOAL_DRAFT_FAILED', parsed?.fix || `ael goal draft --run ${runId} --file ${relative} --revision 0`, parsed?.why || null);
443
+ }
444
+ return reproSummary(report, {
445
+ drafted: true,
446
+ revision: parsed.result?.metadata?.revision || 1,
447
+ show: `goal show --run ${runId} --human`
448
+ });
449
+ }
450
+
451
+ module.exports = {
452
+ assertReadOnlyIssueView,
453
+ attachReproGoal,
454
+ issueViewPlan,
455
+ parseIssueRef,
456
+ parseReport,
457
+ readIssue,
458
+ readReportFile,
459
+ reproContract
460
+ };
package/lib/learn.js CHANGED
@@ -246,6 +246,39 @@ function loadLearnings(rootDir) {
246
246
  return readExisting(rootDir)?.entries || [];
247
247
  }
248
248
 
249
+ // Drop stored lessons whose files are gone or that have not been seen in the
250
+ // last `maxAgeRuns` Runs. Does not re-mine ledgers, so a hand-kept lesson
251
+ // stays until one of those reasons applies. Dry-run writes nothing.
252
+ function pruneStored(rootDir, { dryRun = true, maxAgeRuns = DEFAULT_MAX_AGE_RUNS } = {}) {
253
+ if (!Number.isSafeInteger(maxAgeRuns) || maxAgeRuns < 1) throw learnError('--max-age-runs must be a positive integer', 'INVALID_USAGE');
254
+ const existing = readExisting(rootDir);
255
+ if (!existing) return { pruned: [], written: false, path: '.ai-engineering-loop/learnings.json' };
256
+ const { runs } = collectOccurrences(rootDir);
257
+ const runIndex = new Map([...runs].reverse().map((run, index) => [run.runId, index]));
258
+ const pruned = [];
259
+ const kept = [];
260
+ for (const entry of existing.entries || []) {
261
+ const reason = pruneReason(rootDir, entry, runIndex, maxAgeRuns);
262
+ if (reason) pruned.push({ id: entry.id, reason });
263
+ else kept.push(entry);
264
+ }
265
+ if (dryRun || !pruned.length) return { pruned, written: false, path: '.ai-engineering-loop/learnings.json' };
266
+ const suppressed = [...(existing.suppressed || [])];
267
+ const previous = new Map((existing.entries || []).map((entry) => [entry.id, entry]));
268
+ for (const item of pruned) {
269
+ if (suppressed.some((row) => row.id === item.id)) continue;
270
+ suppressed.push({ id: item.id, reason: item.reason, lastRunId: previous.get(item.id)?.lastRunId || null });
271
+ }
272
+ const document = {
273
+ ...existing,
274
+ entries: kept,
275
+ suppressed: suppressed.sort((left, right) => String(left.id).localeCompare(String(right.id)))
276
+ };
277
+ atomicWriteJson(learningsPath(rootDir), document);
278
+ atomicWritePrivateFile(learningsPath(rootDir, LEARNINGS_MD), renderMarkdown(document));
279
+ return { pruned, written: true, path: '.ai-engineering-loop/learnings.json' };
280
+ }
281
+
249
282
  function relevance(entry, files) {
250
283
  let score = 0;
251
284
  for (const file of files) {
@@ -316,6 +349,7 @@ module.exports = {
316
349
  guidanceFor,
317
350
  learn,
318
351
  loadLearnings,
352
+ pruneStored,
319
353
  selectLearnings,
320
354
  renderMarkdown
321
355
  };