ai-engineering-loop 1.13.0 → 1.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 (117) hide show
  1. package/.agents/skills/ai-engineering-loop/SKILL.md +62 -0
  2. package/.agents/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  3. package/.agents/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  4. package/.agents/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  5. package/.agents/skills/ai-engineering-loop/references/loop-hosts.md +44 -0
  6. package/.agents/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  7. package/.agents/skills/ai-engineering-loop/references/loop-review.md +18 -0
  8. package/.agents/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  9. package/.agents/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  10. package/.claude/skills/ai-engineering-loop/SKILL.md +28 -47
  11. package/.claude/skills/ai-engineering-loop/references/loop-commands.md +20 -0
  12. package/.claude/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
  13. package/.claude/skills/ai-engineering-loop/references/loop-goal.md +10 -0
  14. package/.claude/skills/ai-engineering-loop/references/loop-hosts.md +44 -0
  15. package/.claude/skills/ai-engineering-loop/references/loop-maker.md +8 -0
  16. package/.claude/skills/ai-engineering-loop/references/loop-review.md +18 -0
  17. package/.claude/skills/ai-engineering-loop/references/loop-risky.md +9 -0
  18. package/.claude/skills/ai-engineering-loop/references/loop-verify.md +20 -0
  19. package/CHANGELOG.md +116 -0
  20. package/README.md +90 -5
  21. package/README.npm.md +6 -2
  22. package/THIRD_PARTY_NOTICES.md +29 -0
  23. package/adapters/dot/README.md +1 -1
  24. package/adapters/dot/skills/dot-dev-skill-router/SKILL.md +24 -16
  25. package/adapters/project-onboarding/SKILL.md +27 -0
  26. package/adapters/project-onboarding/references/output.md +29 -0
  27. package/adapters/quality/skills/ael-code-simplifier/SKILL.md +43 -0
  28. package/adapters/quality/skills/ael-receiving-code-review/SKILL.md +37 -0
  29. package/bin/ai-engineering-loop.js +1270 -75
  30. package/core/grill-policy.md +1 -1
  31. package/core/root-cause-analysis.md +6 -0
  32. package/core/runtime-safety.md +31 -3
  33. package/evals/cases/21-tier-t0-docs.json +34 -0
  34. package/evals/cases/22-tier-t1-small-pass.json +30 -0
  35. package/evals/cases/23-tier-t1-blocker.json +26 -0
  36. package/evals/cases/24-tier-t1-auth-escalates.json +30 -0
  37. package/lib/auto-update.js +488 -0
  38. package/lib/budget.js +31 -1
  39. package/lib/cli-args.js +95 -0
  40. package/lib/docs.js +91 -0
  41. package/lib/doctor.js +9 -14
  42. package/lib/gates.js +114 -1
  43. package/lib/host-skill-build.js +121 -0
  44. package/lib/hosts/agent-formats.js +135 -0
  45. package/lib/hosts/commands.js +126 -0
  46. package/lib/hosts/detect.js +56 -0
  47. package/lib/hosts/doctor.js +76 -0
  48. package/lib/hosts/redetect.js +60 -0
  49. package/lib/hosts/registry.js +271 -0
  50. package/lib/hosts/table.js +35 -0
  51. package/lib/migrations.js +84 -0
  52. package/lib/project-registry.js +148 -0
  53. package/lib/run-abandon.js +116 -0
  54. package/lib/run-state.js +6 -3
  55. package/lib/sync-hosts.js +456 -130
  56. package/lib/tier.js +134 -0
  57. package/lib/update-manager.js +17 -1
  58. package/lib/update-notice.js +192 -0
  59. package/lib/user-state.js +80 -0
  60. package/lib/verification-recorder.js +44 -0
  61. package/migrations/README.md +21 -0
  62. package/package.json +8 -4
  63. package/.agents/devil-advocate.md +0 -79
  64. package/.agents/judge.md +0 -58
  65. package/.agents/workflows/ai-engineering-loop.md +0 -24
  66. package/.claude/commands/ai-engineering-loop.md +0 -11
  67. package/.gemini/skills/ai-engineering-loop/SKILL.md +0 -74
  68. package/.gemini/skills/animate/RECIPES.md +0 -324
  69. package/.gemini/skills/animate/SKILL.md +0 -207
  70. package/.gemini/skills/animate-expo/RECIPES.md +0 -385
  71. package/.gemini/skills/animate-expo/SKILL.md +0 -263
  72. package/.gemini/skills/animation-vocabulary/SKILL.md +0 -181
  73. package/.gemini/skills/apple-design/SKILL.md +0 -290
  74. package/.gemini/skills/ask-sonner/API.md +0 -64
  75. package/.gemini/skills/ask-sonner/SKILL.md +0 -88
  76. package/.gemini/skills/backend-development/SKILL.md +0 -272
  77. package/.gemini/skills/backend-development/references/api-design-guidelines.md +0 -95
  78. package/.gemini/skills/backend-development/references/query-and-database-best-practices.md +0 -53
  79. package/.gemini/skills/backend-development/references/security-checklist.md +0 -60
  80. package/.gemini/skills/emil-design-eng/SKILL.md +0 -674
  81. package/.gemini/skills/find-animation-opportunities/SKILL.md +0 -140
  82. package/.gemini/skills/improve-animations/AUDIT.md +0 -115
  83. package/.gemini/skills/improve-animations/PLAN-TEMPLATE.md +0 -73
  84. package/.gemini/skills/improve-animations/SKILL.md +0 -109
  85. package/.gemini/skills/mobile-native/SKILL.md +0 -311
  86. package/.gemini/skills/pick-ui-library/SKILL.md +0 -85
  87. package/.gemini/skills/prototype/PICKER.md +0 -197
  88. package/.gemini/skills/prototype/SKILL.md +0 -98
  89. package/.gemini/skills/review-animations/SKILL.md +0 -120
  90. package/.gemini/skills/review-animations/STANDARDS.md +0 -187
  91. package/.gemini/skills/write-swift/SKILL.md +0 -396
  92. package/.grok/commands/ai-engineering-loop.md +0 -11
  93. package/.grok/skills/ai-engineering-loop/SKILL.md +0 -94
  94. package/.grok/skills/animate/RECIPES.md +0 -324
  95. package/.grok/skills/animate/SKILL.md +0 -207
  96. package/.grok/skills/animate-expo/RECIPES.md +0 -385
  97. package/.grok/skills/animate-expo/SKILL.md +0 -263
  98. package/.grok/skills/animation-vocabulary/SKILL.md +0 -181
  99. package/.grok/skills/apple-design/SKILL.md +0 -290
  100. package/.grok/skills/ask-sonner/API.md +0 -64
  101. package/.grok/skills/ask-sonner/SKILL.md +0 -88
  102. package/.grok/skills/backend-development/SKILL.md +0 -272
  103. package/.grok/skills/backend-development/references/api-design-guidelines.md +0 -95
  104. package/.grok/skills/backend-development/references/query-and-database-best-practices.md +0 -53
  105. package/.grok/skills/backend-development/references/security-checklist.md +0 -60
  106. package/.grok/skills/emil-design-eng/SKILL.md +0 -674
  107. package/.grok/skills/find-animation-opportunities/SKILL.md +0 -140
  108. package/.grok/skills/improve-animations/AUDIT.md +0 -115
  109. package/.grok/skills/improve-animations/PLAN-TEMPLATE.md +0 -73
  110. package/.grok/skills/improve-animations/SKILL.md +0 -109
  111. package/.grok/skills/mobile-native/SKILL.md +0 -311
  112. package/.grok/skills/pick-ui-library/SKILL.md +0 -85
  113. package/.grok/skills/prototype/PICKER.md +0 -197
  114. package/.grok/skills/prototype/SKILL.md +0 -98
  115. package/.grok/skills/review-animations/SKILL.md +0 -120
  116. package/.grok/skills/review-animations/STANDARDS.md +0 -187
  117. package/.grok/skills/write-swift/SKILL.md +0 -396
@@ -0,0 +1,488 @@
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
439
+ ? `, ${last.pending.length} pending (active run; if abandoned: ai-engineering-loop run --abandon --reason "<why>" --by <name> in that project)`
440
+ : '';
441
+ const failed = last.failed && last.failed.length ? `, ${last.failed.length} failed` : '';
442
+ return `ai-engineering-loop updated ${last.from} -> ${last.to}; hosts ${last.hosts}; ${last.refreshed}/${last.total} projects refreshed${pending}${failed}.`;
443
+ }
444
+
445
+ // Starts `update auto --background` detached; returns immediately.
446
+ function spawnBackgroundCheck({ cliPath, env = process.env }) {
447
+ try {
448
+ const child = spawn(process.execPath, [cliPath, 'update', 'auto', '--background'], {
449
+ detached: true,
450
+ stdio: 'ignore',
451
+ env,
452
+ windowsHide: true
453
+ });
454
+ child.unref();
455
+ return true;
456
+ } catch {
457
+ return false;
458
+ }
459
+ }
460
+
461
+ module.exports = {
462
+ restoreLegacySnapshots,
463
+ POLICIES,
464
+ DEFAULT_POLICY,
465
+ UNSET_POLICY,
466
+ CHANNELS,
467
+ CHECK_INTERVAL_MS,
468
+ CHECK_TIMEOUT_MS,
469
+ autoUpdateAllowedHere,
470
+ resolvePolicy,
471
+ setPolicy,
472
+ readCache,
473
+ cacheStale,
474
+ fetchDistTags,
475
+ refreshCache,
476
+ bumpType,
477
+ matchesPin,
478
+ decideUpdate,
479
+ noticeText,
480
+ acquireLock,
481
+ readState,
482
+ applyUpdate,
483
+ verifyRelease,
484
+ processPending,
485
+ rollback,
486
+ consumeSummary,
487
+ spawnBackgroundCheck
488
+ };
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
  };
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+
3
+ // Side-effect-free argument checks that run before any command handler.
4
+ // Contract: `--help`/`-h` never executes a command, and commands that write
5
+ // files reject unknown flags before touching the filesystem.
6
+
7
+ const HELP_FLAGS = new Set(['-h', '--help']);
8
+
9
+ // Commands whose handlers write files (repository, home, or package installs).
10
+ // `flags` take no value; `valued` consume the next token; `positionals` lists
11
+ // accepted bare words (null = free text allowed).
12
+ const WRITER_COMMANDS = Object.freeze({
13
+ init: { flags: [], valued: [], positionals: [] },
14
+ refresh: { flags: ['--non-destructive', '--json'], valued: [], positionals: [] },
15
+ 'sync-hosts': { flags: ['--dry-run', '--prune', '--json'], valued: ['--pack'], positionals: [] },
16
+ setup: { flags: ['--yes', '--json'], valued: ['--hosts', '--mode'], positionals: [] },
17
+ hosts: { flags: ['--json'], valued: [], positionals: null },
18
+ update: { flags: ['--json', '--yes', '--background', '--force', '--no-pin'], valued: ['--channel', '--pin'], positionals: ['check', 'plan', 'apply', 'auto', 'policy', 'rollback', ...['off', 'notify', 'patch', 'minor', 'all']] },
19
+ projects: { flags: ['--json'], valued: ['--root', '--depth'], positionals: null },
20
+ // `run --abandon` (issue #46) is a writer; plain `run` takes free text.
21
+ 'run:abandon': { flags: ['--abandon', '--yes', '--json'], valued: ['--run', '--reason', '--by'], positionals: [] },
22
+ migrate: { flags: ['--json', '--dry-run'], valued: ['--from'], positionals: [] },
23
+ verify: { flags: ['--json', '--serial', '--shell'], valued: ['--run', '--cmd', '--timeout-ms'], positionals: [] },
24
+ 'review-pack': { flags: ['--json'], valued: ['--run', '--base', '--profile'], positionals: [] },
25
+ deliver: { flags: ['--json', '--approve'], valued: ['--run', '--destination', '--summary', '--by'], positionals: [] },
26
+ 'generate-adapter': { flags: [], valued: ['--type'], positionals: [] },
27
+ 'generate-workflow': { flags: ['--write'], valued: [], positionals: [] }
28
+ });
29
+
30
+ function beforeSeparator(args) {
31
+ const index = args.indexOf('--');
32
+ return index === -1 ? args : args.slice(0, index);
33
+ }
34
+
35
+ // `run --abandon ...` is checked as its own writer command.
36
+ function effectiveCommand(command, rest) {
37
+ if (command === 'run' && beforeSeparator(rest).includes('--abandon')) return 'run:abandon';
38
+ return command;
39
+ }
40
+
41
+ function wantsCommandHelp(command, rest) {
42
+ const scoped = beforeSeparator(rest);
43
+ // `run` takes free-text task words; only a leading help flag counts.
44
+ if (command === 'run') return scoped.length > 0 && HELP_FLAGS.has(scoped[0]);
45
+ return scoped.some((arg) => HELP_FLAGS.has(arg));
46
+ }
47
+
48
+ function unknownWriterArgs(command, rest) {
49
+ const spec = WRITER_COMMANDS[command];
50
+ if (!spec) return [];
51
+ const scoped = beforeSeparator(rest);
52
+ const unknown = [];
53
+ for (let index = 0; index < scoped.length; index += 1) {
54
+ const arg = scoped[index];
55
+ if (arg.startsWith('-')) {
56
+ const [name] = arg.split('=');
57
+ if (spec.valued.includes(name)) {
58
+ if (!arg.includes('=')) index += 1;
59
+ continue;
60
+ }
61
+ if (spec.flags.includes(arg)) continue;
62
+ unknown.push(arg);
63
+ continue;
64
+ }
65
+ if (spec.positionals === null) continue;
66
+ if (!spec.positionals.includes(arg)) unknown.push(arg);
67
+ }
68
+ return unknown;
69
+ }
70
+
71
+ function commandHelp(helpText, command) {
72
+ const lines = String(helpText).split('\n');
73
+ const start = lines.findIndex((line) => {
74
+ const match = line.match(/^ (\S+)/);
75
+ return match && match[1] === command;
76
+ });
77
+ if (start === -1) return null;
78
+ const block = [lines[start]];
79
+ for (let index = start + 1; index < lines.length; index += 1) {
80
+ const line = lines[index];
81
+ if (/^ \S/.test(line) || /^\S/.test(line) || line.trim() === '') break;
82
+ block.push(line);
83
+ }
84
+ return block.join('\n');
85
+ }
86
+
87
+ module.exports = {
88
+ HELP_FLAGS,
89
+ WRITER_COMMANDS,
90
+ beforeSeparator,
91
+ effectiveCommand,
92
+ wantsCommandHelp,
93
+ unknownWriterArgs,
94
+ commandHelp
95
+ };