ai-engineering-loop 1.12.0 → 1.14.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 (68) hide show
  1. package/.agents/workflows/ai-engineering-loop.md +47 -11
  2. package/.claude/commands/ai-engineering-loop.md +1 -1
  3. package/.claude/skills/ai-engineering-loop/SKILL.md +26 -44
  4. package/.claude/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  5. package/.claude/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  6. package/.claude/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  7. package/.claude/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  8. package/.claude/skills/ai-engineering-loop/references/loop-review.md +18 -0
  9. package/.claude/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  10. package/.claude/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  11. package/.gemini/skills/ai-engineering-loop/SKILL.md +24 -37
  12. package/.gemini/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  13. package/.gemini/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  14. package/.gemini/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  15. package/.gemini/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  16. package/.gemini/skills/ai-engineering-loop/references/loop-review.md +18 -0
  17. package/.gemini/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  18. package/.gemini/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  19. package/.grok/skills/ai-engineering-loop/SKILL.md +29 -61
  20. package/.grok/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  21. package/.grok/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  22. package/.grok/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  23. package/.grok/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  24. package/.grok/skills/ai-engineering-loop/references/loop-review.md +18 -0
  25. package/.grok/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  26. package/.grok/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  27. package/CHANGELOG.md +69 -0
  28. package/README.md +52 -1
  29. package/README.npm.md +6 -2
  30. package/THIRD_PARTY_NOTICES.md +29 -0
  31. package/adapters/dot/skills/dot-dev-skill-router/SKILL.md +24 -16
  32. package/adapters/project-onboarding/SKILL.md +27 -0
  33. package/adapters/project-onboarding/references/output.md +29 -0
  34. package/adapters/quality/skills/ael-code-simplifier/SKILL.md +43 -0
  35. package/adapters/quality/skills/ael-receiving-code-review/SKILL.md +37 -0
  36. package/bin/ai-engineering-loop.js +1137 -78
  37. package/core/artifact-gates.md +32 -1
  38. package/core/root-cause-analysis.md +6 -0
  39. package/core/runtime-safety.md +32 -4
  40. package/core/verification-loop.md +6 -0
  41. package/evals/cases/21-tier-t0-docs.json +34 -0
  42. package/evals/cases/22-tier-t1-small-pass.json +30 -0
  43. package/evals/cases/23-tier-t1-blocker.json +26 -0
  44. package/evals/cases/24-tier-t1-auth-escalates.json +30 -0
  45. package/lib/agent-artifacts.js +250 -0
  46. package/lib/auto-update.js +486 -0
  47. package/lib/budget.js +31 -1
  48. package/lib/claimed-vs-reality.js +134 -0
  49. package/lib/cli-args.js +84 -0
  50. package/lib/docs.js +91 -0
  51. package/lib/doctor.js +7 -1
  52. package/lib/gates.js +114 -1
  53. package/lib/host-skill-build.js +121 -0
  54. package/lib/migrations.js +84 -0
  55. package/lib/project-registry.js +148 -0
  56. package/lib/run-state.js +6 -3
  57. package/lib/safe-context.js +62 -4
  58. package/lib/sync-hosts.js +356 -28
  59. package/lib/tier.js +134 -0
  60. package/lib/update-manager.js +17 -1
  61. package/lib/update-notice.js +192 -0
  62. package/lib/user-state.js +80 -0
  63. package/lib/verification-recorder.js +268 -0
  64. package/lib/workflow-runtime.js +26 -1
  65. package/migrations/README.md +21 -0
  66. package/package.json +7 -2
  67. package/policies/review-budget.md +1 -1
  68. package/schemas/verification.schema.json +2 -2
@@ -0,0 +1,486 @@
1
+ 'use strict';
2
+
3
+ // Auto-update (issue #37). The CLI, never an agent, checks the npm registry at
4
+ // most once per 24 hours in a detached background process and applies
5
+ // patch/minor releases only under the policy the user chose. Majors are always
6
+ // notice-only. Offline or slow registries never block a command.
7
+ //
8
+ // Conservative choices (see the PR):
9
+ // - Project-scoped installs (devDependency/npx) are notify-only: package.json
10
+ // and lockfiles are never edited automatically.
11
+ // - Agents never initiate updates; only this CLI under a user-set policy does.
12
+ // - With no policy configured and no interactive answer, the policy is
13
+ // `notify` (the first-run prompt offers `minor` as the default answer).
14
+
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const { execFileSync, spawn } = require('child_process');
18
+ const { homeDir, userStatePath, readJsonFile, writeJsonFile, readUserConfig, writeUserConfig } = require('./user-state.js');
19
+ const { compareVersions, parseVersion } = require('./update-manager.js');
20
+
21
+ const POLICIES = Object.freeze(['off', 'notify', 'patch', 'minor', 'all']);
22
+ const DEFAULT_POLICY = 'minor';
23
+ const UNSET_POLICY = 'notify';
24
+ const CHANNELS = Object.freeze(['latest', 'next']);
25
+ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
26
+ const CHECK_TIMEOUT_MS = 3000;
27
+ const LOCK_STALE_MS = 15 * 60 * 1000;
28
+
29
+ const truthy = (value) => ['1', 'true', 'yes'].includes(String(value || '').trim().toLowerCase());
30
+
31
+ // Background checks are disabled inside the Node test runner (no network,
32
+ // no orphan processes) unless a test opts in with AEL_ALLOW_AUTO_UPDATE_IN_TESTS.
33
+ function autoUpdateAllowedHere(env = process.env) {
34
+ if (env.NODE_TEST_CONTEXT && !truthy(env.AEL_ALLOW_AUTO_UPDATE_IN_TESTS)) return false;
35
+ return true;
36
+ }
37
+
38
+ function resolvePolicy({ config = readUserConfig(), env = process.env } = {}) {
39
+ const channel = CHANNELS.includes(config.updateChannel) ? config.updateChannel : 'latest';
40
+ const pin = typeof config.updatePin === 'string' && config.updatePin.trim() ? config.updatePin.trim() : null;
41
+ if (truthy(env.AEL_NO_AUTO_UPDATE)) return { policy: 'off', source: 'AEL_NO_AUTO_UPDATE', channel, pin };
42
+ if (truthy(env.CI)) return { policy: 'off', source: 'CI', channel, pin };
43
+ if (POLICIES.includes(config.autoUpdate)) return { policy: config.autoUpdate, source: 'config', channel, pin };
44
+ return { policy: UNSET_POLICY, source: 'unset', channel, pin };
45
+ }
46
+
47
+ function setPolicy({ policy, channel, pin, home = homeDir() } = {}) {
48
+ const patch = {};
49
+ if (policy !== undefined) {
50
+ if (!POLICIES.includes(policy)) {
51
+ const err = new Error(`Invalid auto-update policy "${policy}". Use: ${POLICIES.join(', ')}`);
52
+ err.code = 'INVALID_POLICY';
53
+ throw err;
54
+ }
55
+ patch.autoUpdate = policy;
56
+ }
57
+ if (channel !== undefined) {
58
+ if (!CHANNELS.includes(channel)) {
59
+ const err = new Error(`Invalid update channel "${channel}". Use: ${CHANNELS.join(', ')}`);
60
+ err.code = 'INVALID_CHANNEL';
61
+ throw err;
62
+ }
63
+ patch.updateChannel = channel;
64
+ }
65
+ if (pin !== undefined) {
66
+ if (pin !== null && !/^\d+(\.(\d+|x))?(\.(\d+|x))?$/.test(pin)) {
67
+ const err = new Error(`Invalid pin "${pin}". Use forms like 1, 1.13, or 1.13.x`);
68
+ err.code = 'INVALID_PIN';
69
+ throw err;
70
+ }
71
+ patch.updatePin = pin;
72
+ }
73
+ return writeUserConfig(patch, home);
74
+ }
75
+
76
+ // ---- cache ---------------------------------------------------------------
77
+
78
+ const cachePath = (home) => userStatePath('update-check.json', home);
79
+ const statePath = (home) => userStatePath('update-state.json', home);
80
+ const lockPath = (home) => userStatePath('update.lock', home);
81
+
82
+ function readCache(home = homeDir()) {
83
+ return readJsonFile(cachePath(home), null);
84
+ }
85
+
86
+ function cacheStale(cache, now = new Date()) {
87
+ if (!cache || !cache.checkedAt) return true;
88
+ const age = now.getTime() - Date.parse(cache.checkedAt);
89
+ return !(age >= 0 && age < CHECK_INTERVAL_MS);
90
+ }
91
+
92
+ function fetchDistTags(packageName, { env = process.env, timeoutMs = CHECK_TIMEOUT_MS } = {}) {
93
+ if (truthy(env.AEL_UPDATE_OFFLINE)) {
94
+ const err = new Error('offline (AEL_UPDATE_OFFLINE)');
95
+ err.code = 'OFFLINE';
96
+ throw err;
97
+ }
98
+ if (env.AEL_UPDATE_DIST_TAGS) return JSON.parse(env.AEL_UPDATE_DIST_TAGS);
99
+ const output = execFileSync('npm', ['view', packageName, 'dist-tags', '--json'], {
100
+ encoding: 'utf8',
101
+ stdio: ['ignore', 'pipe', 'ignore'],
102
+ timeout: timeoutMs,
103
+ windowsHide: true
104
+ });
105
+ return JSON.parse(output);
106
+ }
107
+
108
+ // Never throws. A failed check keeps the previous dist-tags.
109
+ function refreshCache({ packageName, home = homeDir(), env = process.env, now = new Date() } = {}) {
110
+ const previous = readCache(home) || {};
111
+ let next;
112
+ try {
113
+ const distTags = fetchDistTags(packageName, { env });
114
+ if (!distTags || typeof distTags !== 'object' || Array.isArray(distTags)) throw new Error('unexpected npm response');
115
+ next = { schemaVersion: 1, packageName, checkedAt: now.toISOString(), distTags, error: null, notified: previous.notified || null, notices: previous.notices || {}, highlights: previous.highlights || null };
116
+ } catch (error) {
117
+ next = { schemaVersion: 1, packageName, checkedAt: now.toISOString(), distTags: previous.distTags || null, error: error.code || 'CHECK_FAILED', notified: previous.notified || null, notices: previous.notices || {}, highlights: previous.highlights || null };
118
+ }
119
+ try {
120
+ writeJsonFile(cachePath(home), next);
121
+ } catch {
122
+ // Unwritable home: still return the result.
123
+ }
124
+ return next;
125
+ }
126
+
127
+ // ---- decision ------------------------------------------------------------
128
+
129
+ function bumpType(current, target) {
130
+ if (compareVersions(target, current) <= 0) return 'none';
131
+ const [cMajor, cMinor] = parseVersion(current);
132
+ const [tMajor, tMinor] = parseVersion(target);
133
+ if (tMajor !== cMajor) return 'major';
134
+ if (tMinor !== cMinor) return 'minor';
135
+ return 'patch';
136
+ }
137
+
138
+ function matchesPin(version, pin) {
139
+ if (!pin) return true;
140
+ const parts = parseVersion(version);
141
+ return pin.split('.').every((part, index) => part === 'x' || Number(part) === parts[index]);
142
+ }
143
+
144
+ function decideUpdate({ current, distTags, policy, channel = 'latest', pin = null }) {
145
+ const target = distTags && (distTags[channel] || distTags.latest);
146
+ if (!target) return { action: 'none', reason: 'NO_DATA', target: null, bump: 'none' };
147
+ let bump;
148
+ try {
149
+ bump = bumpType(current, target);
150
+ } catch {
151
+ return { action: 'none', reason: 'INVALID_VERSION', target, bump: 'none' };
152
+ }
153
+ if (bump === 'none') return { action: 'none', reason: 'UP_TO_DATE', target, bump };
154
+ if (policy === 'off') return { action: 'none', reason: 'POLICY_OFF', target, bump };
155
+ const notify = (reason) => ({ action: 'notify', reason, target, bump });
156
+ if (bump === 'major') return notify('MAJOR_NOTICE_ONLY');
157
+ if (!matchesPin(target, pin)) return notify('PINNED');
158
+ if (/-/.test(target) && policy !== 'all') return notify('PRERELEASE');
159
+ if (policy === 'notify') return notify('POLICY_NOTIFY');
160
+ if (policy === 'patch' && bump !== 'patch') return notify('POLICY_PATCH_ONLY');
161
+ return { action: 'apply', reason: `POLICY_${policy.toUpperCase()}`, target, bump };
162
+ }
163
+
164
+ function noticeText(current, decision) {
165
+ const why = {
166
+ MAJOR_NOTICE_ONLY: 'major release: read the changelog/migration notes, then run `ai-engineering-loop update apply --yes`',
167
+ PINNED: 'outside your pin (`update policy --pin`)',
168
+ PRERELEASE: 'prerelease; policy `all` is needed to apply it',
169
+ POLICY_NOTIFY: 'run `ai-engineering-loop update apply --yes`, or choose `update policy minor`',
170
+ POLICY_PATCH_ONLY: 'policy `patch` applies patch releases only',
171
+ PROJECT_SCOPE_NOTIFY_ONLY: 'project install: update package.json yourself (`npm install ai-engineering-loop@latest --save-dev`)'
172
+ }[decision.reason] || decision.reason;
173
+ return `ai-engineering-loop ${decision.target} is available (current ${current}, ${decision.bump}): ${why}.`;
174
+ }
175
+
176
+ // ---- lock ----------------------------------------------------------------
177
+
178
+ function acquireLock(home = homeDir(), { now = Date.now() } = {}) {
179
+ const file = lockPath(home);
180
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
181
+ for (let attempt = 0; attempt < 2; attempt += 1) {
182
+ try {
183
+ const fd = fs.openSync(file, 'wx', 0o600);
184
+ fs.writeSync(fd, JSON.stringify({ pid: process.pid, at: new Date(now).toISOString() }));
185
+ fs.closeSync(fd);
186
+ return () => {
187
+ try {
188
+ fs.unlinkSync(file);
189
+ } catch {
190
+ // Already gone.
191
+ }
192
+ };
193
+ } catch (error) {
194
+ if (error.code !== 'EEXIST') throw error;
195
+ let stale = false;
196
+ try {
197
+ stale = now - fs.statSync(file).mtimeMs > LOCK_STALE_MS;
198
+ } catch {
199
+ stale = true;
200
+ }
201
+ if (!stale) return null;
202
+ try {
203
+ fs.unlinkSync(file);
204
+ } catch {
205
+ // Raced with another process.
206
+ }
207
+ }
208
+ }
209
+ return null;
210
+ }
211
+
212
+ // ---- state, apply, rollback ----------------------------------------------
213
+
214
+ function readState(home = homeDir()) {
215
+ return readJsonFile(statePath(home), null) || { schemaVersion: 1 };
216
+ }
217
+
218
+ function writeState(state, home = homeDir()) {
219
+ writeJsonFile(statePath(home), { schemaVersion: 1, ...state });
220
+ }
221
+
222
+ function defaultExec(cmd, args, options = {}) {
223
+ return execFileSync(cmd, args, { stdio: 'ignore', windowsHide: true, timeout: 10 * 60 * 1000, ...options });
224
+ }
225
+
226
+ // Projects whose current run is not terminal are skipped and retried later.
227
+ function activeRun(projectDir, { readCurrentRun }) {
228
+ try {
229
+ const run = readCurrentRun(projectDir);
230
+ return run && !run.terminal ? run : null;
231
+ } catch {
232
+ return null;
233
+ }
234
+ }
235
+
236
+ function refreshProjects({ projects, exec, readCurrentRun, bin }) {
237
+ const refreshed = [];
238
+ const pending = [];
239
+ const failed = [];
240
+ for (const project of projects) {
241
+ if (activeRun(project.path, { readCurrentRun })) {
242
+ pending.push(project.path);
243
+ continue;
244
+ }
245
+ try {
246
+ exec(bin.cmd, [...bin.args, 'refresh', '--non-destructive'], { cwd: project.path });
247
+ refreshed.push(project.path);
248
+ } catch {
249
+ failed.push(project.path);
250
+ }
251
+ }
252
+ return { refreshed, pending, failed };
253
+ }
254
+
255
+ const GLOBAL_BIN = Object.freeze({ cmd: 'ai-engineering-loop', args: [] });
256
+
257
+ // Refuses a release whose registry metadata names a different repository than
258
+ // this package, or has no integrity hash. npm itself verifies the tarball
259
+ // against dist.integrity during install.
260
+ function defaultViewRelease(packageName, version) {
261
+ const out = execFileSync('npm', ['view', `${packageName}@${version}`, 'repository.url', 'dist.integrity', '--json'], {
262
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000, windowsHide: true
263
+ });
264
+ const parsed = JSON.parse(out);
265
+ return { repository: parsed['repository.url'] || '', integrity: parsed['dist.integrity'] || '' };
266
+ }
267
+
268
+ function repoSlug(url) {
269
+ const match = String(url || '').match(/github\.com[/:]([^/]+\/[^/.#]+)/i);
270
+ return match ? match[1].toLowerCase() : null;
271
+ }
272
+
273
+ function verifyRelease({ packageName, version, expectedRepository, viewRelease = defaultViewRelease }) {
274
+ let info;
275
+ try {
276
+ info = viewRelease(packageName, version);
277
+ } catch {
278
+ return { ok: false, reason: 'RELEASE_LOOKUP_FAILED' };
279
+ }
280
+ if (!info.integrity) return { ok: false, reason: 'NO_INTEGRITY' };
281
+ const expected = repoSlug(expectedRepository);
282
+ if (expected && repoSlug(info.repository) !== expected) return { ok: false, reason: 'REPOSITORY_MISMATCH' };
283
+ return { ok: true };
284
+ }
285
+
286
+ // Applies `target` for a global install: npm install -g, sync-hosts, then a
287
+ // non-destructive refresh of every registered project.
288
+ function applyUpdate({
289
+ packageName,
290
+ current,
291
+ target,
292
+ scope,
293
+ projects = [],
294
+ home = homeDir(),
295
+ exec = defaultExec,
296
+ readCurrentRun,
297
+ bin = GLOBAL_BIN,
298
+ expectedRepository = null,
299
+ viewRelease = defaultViewRelease,
300
+ now = new Date()
301
+ }) {
302
+ if (scope !== 'global') return { applied: false, reason: 'PROJECT_SCOPE_NOTIFY_ONLY' };
303
+ const verified = verifyRelease({ packageName, version: target, expectedRepository, viewRelease });
304
+ if (!verified.ok) return { applied: false, reason: verified.reason };
305
+ if (projects.some((p) => {
306
+ const run = activeRun(p.path, { readCurrentRun });
307
+ return run && run.mode === 'UNATTENDED';
308
+ })) {
309
+ return { applied: false, reason: 'UNATTENDED_RUN_ACTIVE' };
310
+ }
311
+ const release = acquireLock(home);
312
+ if (!release) return { applied: false, reason: 'LOCKED' };
313
+ const state = readState(home);
314
+ try {
315
+ writeState({ ...state, inProgress: { from: current, to: target, at: now.toISOString() } }, home);
316
+ try {
317
+ exec('npm', ['install', '--global', `${packageName}@${target}`]);
318
+ } catch (error) {
319
+ writeState({ ...state, inProgress: null, lastError: { to: target, step: 'install', at: now.toISOString(), message: String(error.message).slice(0, 300) } }, home);
320
+ return { applied: false, reason: 'INSTALL_FAILED' };
321
+ }
322
+ let hosts = 'synced';
323
+ try {
324
+ exec(bin.cmd, [...bin.args, 'sync-hosts']);
325
+ } catch {
326
+ hosts = 'failed';
327
+ }
328
+ const result = refreshProjects({ projects, exec, readCurrentRun, bin });
329
+ const summary = {
330
+ from: current,
331
+ to: target,
332
+ at: now.toISOString(),
333
+ hosts,
334
+ refreshed: result.refreshed.length,
335
+ total: projects.length,
336
+ pending: result.pending,
337
+ failed: result.failed,
338
+ shown: false
339
+ };
340
+ writeState({ ...state, inProgress: null, previousVersion: current, currentVersion: target, lastApplied: summary, pendingProjects: result.pending }, home);
341
+ return { applied: true, ...summary };
342
+ } finally {
343
+ release();
344
+ }
345
+ }
346
+
347
+ function processPending({ projects, home = homeDir(), exec = defaultExec, readCurrentRun, bin = GLOBAL_BIN }) {
348
+ const state = readState(home);
349
+ const wanted = new Set(state.pendingProjects || []);
350
+ if (!wanted.size) return { refreshed: [], pending: [] };
351
+ const release = acquireLock(home);
352
+ if (!release) return { refreshed: [], pending: [...wanted], reason: 'LOCKED' };
353
+ try {
354
+ const result = refreshProjects({ projects: projects.filter((p) => wanted.has(p.path)), exec, readCurrentRun, bin });
355
+ writeState({ ...readState(home), pendingProjects: result.pending }, home);
356
+ return result;
357
+ } finally {
358
+ release();
359
+ }
360
+ }
361
+
362
+ // Undo the legacy first-update overwrite (decision 5 on #37): copy snapshot
363
+ // files back and drop the hash files so the project is exactly as before.
364
+ function restoreLegacySnapshots({ projects = [], since }) {
365
+ const restored = [];
366
+ if (!since) return restored;
367
+ for (const project of projects) {
368
+ const contextDir = path.join(project.path, '.ai-engineering-loop');
369
+ const backupRoot = path.join(contextDir, '.ael-backup');
370
+ let entries = [];
371
+ try {
372
+ entries = fs.readdirSync(backupRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
373
+ } catch {
374
+ continue;
375
+ }
376
+ for (const name of entries) {
377
+ const dir = path.join(backupRoot, name);
378
+ const metaPath = path.join(dir, 'snapshot.json');
379
+ const meta = readJsonFile(metaPath, null);
380
+ if (!meta || meta.reason !== 'LEGACY_FIRST_UPDATE' || meta.restoredAt) continue;
381
+ if (Date.parse(meta.at) < Date.parse(since)) continue;
382
+ for (const rel of meta.files || []) {
383
+ const from = path.resolve(dir, rel);
384
+ const to = path.resolve(contextDir, rel);
385
+ if (!from.startsWith(path.resolve(dir) + path.sep) || !to.startsWith(path.resolve(contextDir) + path.sep)) continue;
386
+ try {
387
+ fs.mkdirSync(path.dirname(to), { recursive: true });
388
+ fs.copyFileSync(from, to);
389
+ } catch {
390
+ // Keep going; the snapshot stays for manual recovery.
391
+ }
392
+ }
393
+ for (const hashFile of [path.join(contextDir, '.ael-generated.json'), path.join(contextDir, 'adrs', '.ael-generated.json')]) {
394
+ try {
395
+ fs.unlinkSync(hashFile);
396
+ } catch {
397
+ // Not present.
398
+ }
399
+ }
400
+ writeJsonFile(metaPath, { ...meta, restoredAt: new Date().toISOString() });
401
+ restored.push({ project: project.path, snapshot: path.relative(project.path, dir).split(path.sep).join('/'), files: (meta.files || []).length });
402
+ }
403
+ }
404
+ return restored;
405
+ }
406
+
407
+ function rollback({ packageName, home = homeDir(), exec = defaultExec, bin = GLOBAL_BIN, now = new Date(), projects = [] }) {
408
+ const state = readState(home);
409
+ if (!state.previousVersion) {
410
+ const err = new Error('No previous version recorded; nothing to roll back.');
411
+ err.code = 'NO_ROLLBACK';
412
+ throw err;
413
+ }
414
+ const release = acquireLock(home);
415
+ if (!release) {
416
+ const err = new Error('Another update is running (update.lock).');
417
+ err.code = 'LOCKED';
418
+ throw err;
419
+ }
420
+ try {
421
+ exec('npm', ['install', '--global', `${packageName}@${state.previousVersion}`]);
422
+ exec(bin.cmd, [...bin.args, 'sync-hosts']);
423
+ const restored = restoreLegacySnapshots({ projects, since: state.lastApplied && state.lastApplied.at });
424
+ const record = { from: state.currentVersion || null, to: state.previousVersion, at: now.toISOString(), restored };
425
+ writeState({ ...state, currentVersion: state.previousVersion, previousVersion: null, lastRollback: record }, home);
426
+ return record;
427
+ } finally {
428
+ release();
429
+ }
430
+ }
431
+
432
+ // One-line summary of the last automatic update, returned once.
433
+ function consumeSummary(home = homeDir()) {
434
+ const state = readState(home);
435
+ const last = state.lastApplied;
436
+ if (!last || last.shown) return null;
437
+ writeState({ ...state, lastApplied: { ...last, shown: true } }, home);
438
+ const pending = last.pending && last.pending.length ? `, ${last.pending.length} pending` : '';
439
+ const failed = last.failed && last.failed.length ? `, ${last.failed.length} failed` : '';
440
+ return `ai-engineering-loop updated ${last.from} -> ${last.to}; hosts ${last.hosts}; ${last.refreshed}/${last.total} projects refreshed${pending}${failed}.`;
441
+ }
442
+
443
+ // Starts `update auto --background` detached; returns immediately.
444
+ function spawnBackgroundCheck({ cliPath, env = process.env }) {
445
+ try {
446
+ const child = spawn(process.execPath, [cliPath, 'update', 'auto', '--background'], {
447
+ detached: true,
448
+ stdio: 'ignore',
449
+ env,
450
+ windowsHide: true
451
+ });
452
+ child.unref();
453
+ return true;
454
+ } catch {
455
+ return false;
456
+ }
457
+ }
458
+
459
+ module.exports = {
460
+ restoreLegacySnapshots,
461
+ POLICIES,
462
+ DEFAULT_POLICY,
463
+ UNSET_POLICY,
464
+ CHANNELS,
465
+ CHECK_INTERVAL_MS,
466
+ CHECK_TIMEOUT_MS,
467
+ autoUpdateAllowedHere,
468
+ resolvePolicy,
469
+ setPolicy,
470
+ readCache,
471
+ cacheStale,
472
+ fetchDistTags,
473
+ refreshCache,
474
+ bumpType,
475
+ matchesPin,
476
+ decideUpdate,
477
+ noticeText,
478
+ acquireLock,
479
+ readState,
480
+ applyUpdate,
481
+ verifyRelease,
482
+ processPending,
483
+ rollback,
484
+ consumeSummary,
485
+ spawnBackgroundCheck
486
+ };
package/lib/budget.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
- const { assertRunId, getCurrentRun, loadRun } = require('./run-state.js');
5
+ const { RUN_MODES, assertRunId, getCurrentRun, loadRun } = require('./run-state.js');
6
6
  const { loadPolicy, updatePolicy } = require('./runtime-policy.js');
7
7
  const { ensurePrivateRuntimeIgnores } = require('./runtime-files.js');
8
8
 
@@ -276,6 +276,35 @@ function recordTokenUsage(
276
276
  };
277
277
  }
278
278
 
279
+ function unavailableUsagePath(rootDir, now = new Date()) {
280
+ return path.join(usageDir(rootDir), `unavailable-${utcDay(now)}.jsonl`);
281
+ }
282
+
283
+ // Issue #29: when the host does not expose provider usage, ASSISTED notes the gap
284
+ // once and continues (a human is already present at freeze and delivery);
285
+ // UNATTENDED still fails closed so the run stops and escalates.
286
+ function recordUsageUnavailable(rootDir, { runId, nodeId, now = new Date() } = {}) {
287
+ const run = resolveRun(rootDir, runId);
288
+ const mode = run.mode || RUN_MODES.ASSISTED;
289
+ if (mode === RUN_MODES.UNATTENDED) {
290
+ throw usageError(
291
+ 'UNATTENDED runs require provider-reported usage. Stop and escalate to a human.',
292
+ 'USAGE_UNAVAILABLE_UNATTENDED'
293
+ );
294
+ }
295
+ if (nodeId != null && !/^[a-z][a-z0-9-]{0,63}$/.test(nodeId)) throw usageError('nodeId is invalid');
296
+ const entry = {
297
+ schemaVersion: 1,
298
+ runId: run.runId,
299
+ usage: 'unavailable',
300
+ mode,
301
+ ...(nodeId ? { nodeId } : {}),
302
+ recordedAt: now.toISOString()
303
+ };
304
+ appendPrivateLine(rootDir, unavailableUsagePath(rootDir, now), `${JSON.stringify(entry)}\n`);
305
+ return { entry, continue: true, disclose: 'Provider usage was unavailable; report it once in the delivery summary.' };
306
+ }
307
+
279
308
  function setKillSwitch(rootDir, active) {
280
309
  return updatePolicy(rootDir, { killSwitch: Boolean(active) });
281
310
  }
@@ -289,5 +318,6 @@ module.exports = {
289
318
  budgetStatus,
290
319
  assertBudgetAvailable,
291
320
  recordTokenUsage,
321
+ recordUsageUnavailable,
292
322
  setKillSwitch
293
323
  };
@@ -1,5 +1,138 @@
1
1
  'use strict';
2
2
 
3
+ const crypto = require('crypto');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { getCurrentRun, loadRun } = require('./run-state.js');
7
+
8
+ function claimedVsRealityError(message, code = 'CLAIMED_VS_REALITY_FAILED') {
9
+ const error = new Error(message);
10
+ error.code = code;
11
+ return error;
12
+ }
13
+
14
+ function markdownCell(value) {
15
+ return String(value ?? '')
16
+ .replace(/\|/g, '/')
17
+ .replace(/\s+/g, ' ')
18
+ .trim();
19
+ }
20
+
21
+ function frozenGoal(rootDir, run) {
22
+ const artifact = run.artifacts?.goalContract;
23
+ if (!artifact?.path || !artifact.sha256) {
24
+ throw claimedVsRealityError('The Goal Contract has not passed the Goal gate.', 'GOAL_NOT_FROZEN');
25
+ }
26
+ const root = fs.realpathSync(rootDir);
27
+ const goalPath = path.resolve(root, artifact.path);
28
+ const relative = path.relative(root, goalPath);
29
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
30
+ throw claimedVsRealityError('Frozen Goal Contract path escapes the repository.', 'UNSAFE_GOAL_PATH');
31
+ }
32
+ assertNoSymlinkPath(root, goalPath);
33
+ const stat = fs.lstatSync(goalPath);
34
+ if (!stat.isFile() || stat.isSymbolicLink()) {
35
+ throw claimedVsRealityError('Frozen Goal Contract must be a regular file.', 'UNSAFE_GOAL_PATH');
36
+ }
37
+ const content = fs.readFileSync(goalPath);
38
+ const hash = crypto.createHash('sha256').update(content).digest('hex');
39
+ if (hash !== artifact.sha256) {
40
+ throw claimedVsRealityError('Frozen Goal Contract changed after its gate.', 'STALE_GOAL');
41
+ }
42
+ let goal;
43
+ try {
44
+ goal = JSON.parse(content.toString('utf8'));
45
+ } catch (cause) {
46
+ throw claimedVsRealityError(`Frozen Goal Contract is invalid JSON: ${cause.message}`, 'INVALID_GOAL');
47
+ }
48
+ if (goal.runId !== run.runId || !Array.isArray(goal.acceptanceCriteria) || goal.acceptanceCriteria.length === 0) {
49
+ throw claimedVsRealityError('Frozen Goal Contract has no criteria for this Run.', 'INVALID_GOAL');
50
+ }
51
+ return goal;
52
+ }
53
+
54
+ function assertNoSymlinkPath(root, targetPath) {
55
+ const relative = path.relative(root, targetPath);
56
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
57
+ throw claimedVsRealityError('Output path must stay inside the repository.', 'UNSAFE_OUTPUT_PATH');
58
+ }
59
+ let current = root;
60
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
61
+ current = path.join(current, segment);
62
+ try {
63
+ if (fs.lstatSync(current).isSymbolicLink()) {
64
+ throw claimedVsRealityError(`Repository path crosses a symlink: ${path.relative(root, current)}`, 'UNSAFE_PATH');
65
+ }
66
+ } catch (cause) {
67
+ if (cause.code === 'ENOENT') return;
68
+ throw cause;
69
+ }
70
+ }
71
+ }
72
+
73
+ function renderClaimedVsRealityTemplate(goal) {
74
+ const lines = [
75
+ '# Claimed vs Reality',
76
+ '',
77
+ '> Generated from the frozen Goal Contract. Fill Claimed and Reality only after implementation and verification. Reality must cite observed command output; this template is not verification evidence.',
78
+ '',
79
+ '| AC | Claimed | Reality from command log |',
80
+ '|---|---|---|'
81
+ ];
82
+ for (const criterion of goal.acceptanceCriteria) {
83
+ const evidence = markdownCell(criterion.evidenceRequired);
84
+ const failures = (criterion.failureCases || []).map(markdownCell).filter(Boolean).join('; ');
85
+ const description = [
86
+ `${criterion.id}: ${markdownCell(criterion.statement)}`,
87
+ evidence ? `Evidence: ${evidence}` : '',
88
+ failures ? `Failure cases: ${failures}` : ''
89
+ ].filter(Boolean).join(' — ');
90
+ lines.push(`| ${markdownCell(description)} | | |`);
91
+ }
92
+ return `${lines.join('\n')}\n`;
93
+ }
94
+
95
+ function createClaimedVsRealityTemplate(rootDir, { runId, outputPath } = {}) {
96
+ const run = runId ? loadRun(rootDir, runId) : getCurrentRun(rootDir);
97
+ if (!run) throw claimedVsRealityError('No current Run. Pass --run <id>.', 'NO_CURRENT_RUN');
98
+ const goal = frozenGoal(rootDir, run);
99
+ const root = fs.realpathSync(rootDir);
100
+ const requestedPath = outputPath || '.ai-engineering-loop/tasks/claimed-vs-reality.md';
101
+ if (path.isAbsolute(requestedPath)) {
102
+ throw claimedVsRealityError('Output path must be repository-relative.', 'UNSAFE_OUTPUT_PATH');
103
+ }
104
+ const filePath = path.resolve(root, requestedPath);
105
+ const relative = path.relative(root, filePath);
106
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
107
+ throw claimedVsRealityError('Output path must stay inside the repository.', 'UNSAFE_OUTPUT_PATH');
108
+ }
109
+ assertNoSymlinkPath(root, path.dirname(filePath));
110
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
111
+ const realParent = fs.realpathSync(path.dirname(filePath));
112
+ if (realParent !== root && !realParent.startsWith(`${root}${path.sep}`)) {
113
+ throw claimedVsRealityError('Output path escapes the repository through a symlink.', 'UNSAFE_OUTPUT_PATH');
114
+ }
115
+ let descriptor;
116
+ try {
117
+ descriptor = fs.openSync(filePath, 'wx', 0o600);
118
+ } catch (cause) {
119
+ if (cause.code === 'EEXIST') {
120
+ throw claimedVsRealityError(
121
+ `Refusing to overwrite ${relative}. Choose --output <new-file> to preserve existing evidence.`,
122
+ 'OUTPUT_EXISTS'
123
+ );
124
+ }
125
+ throw cause;
126
+ }
127
+ try {
128
+ fs.writeFileSync(descriptor, renderClaimedVsRealityTemplate(goal));
129
+ fs.fsyncSync(descriptor);
130
+ } finally {
131
+ fs.closeSync(descriptor);
132
+ }
133
+ return { runId: run.runId, path: relative.split(path.sep).join('/') };
134
+ }
135
+
3
136
  function parseClaimedVsReality(markdown) {
4
137
  const rows = [];
5
138
  if (!markdown || !String(markdown).trim()) return { rows };
@@ -32,6 +165,7 @@ function readyForDa(markdown) {
32
165
  }
33
166
 
34
167
  module.exports = {
168
+ createClaimedVsRealityTemplate,
35
169
  parseClaimedVsReality,
36
170
  readyForDa
37
171
  };