ai-engineering-loop 1.13.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.
- package/.agents/workflows/ai-engineering-loop.md +47 -11
- package/.claude/commands/ai-engineering-loop.md +1 -1
- package/.claude/skills/ai-engineering-loop/SKILL.md +26 -44
- package/.claude/skills/ai-engineering-loop/references/loop-commands.md +20 -0
- package/.claude/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
- package/.claude/skills/ai-engineering-loop/references/loop-goal.md +10 -0
- package/.claude/skills/ai-engineering-loop/references/loop-maker.md +8 -0
- package/.claude/skills/ai-engineering-loop/references/loop-review.md +18 -0
- package/.claude/skills/ai-engineering-loop/references/loop-risky.md +9 -0
- package/.claude/skills/ai-engineering-loop/references/loop-verify.md +20 -0
- package/.gemini/skills/ai-engineering-loop/SKILL.md +24 -37
- package/.gemini/skills/ai-engineering-loop/references/loop-commands.md +20 -0
- package/.gemini/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
- package/.gemini/skills/ai-engineering-loop/references/loop-goal.md +10 -0
- package/.gemini/skills/ai-engineering-loop/references/loop-maker.md +8 -0
- package/.gemini/skills/ai-engineering-loop/references/loop-review.md +18 -0
- package/.gemini/skills/ai-engineering-loop/references/loop-risky.md +9 -0
- package/.gemini/skills/ai-engineering-loop/references/loop-verify.md +20 -0
- package/.grok/skills/ai-engineering-loop/SKILL.md +29 -61
- package/.grok/skills/ai-engineering-loop/references/loop-commands.md +20 -0
- package/.grok/skills/ai-engineering-loop/references/loop-deliver.md +8 -0
- package/.grok/skills/ai-engineering-loop/references/loop-goal.md +10 -0
- package/.grok/skills/ai-engineering-loop/references/loop-maker.md +8 -0
- package/.grok/skills/ai-engineering-loop/references/loop-review.md +18 -0
- package/.grok/skills/ai-engineering-loop/references/loop-risky.md +9 -0
- package/.grok/skills/ai-engineering-loop/references/loop-verify.md +20 -0
- package/CHANGELOG.md +69 -0
- package/README.md +40 -1
- package/README.npm.md +6 -2
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/adapters/dot/skills/dot-dev-skill-router/SKILL.md +24 -16
- package/adapters/project-onboarding/SKILL.md +27 -0
- package/adapters/project-onboarding/references/output.md +29 -0
- package/adapters/quality/skills/ael-code-simplifier/SKILL.md +43 -0
- package/adapters/quality/skills/ael-receiving-code-review/SKILL.md +37 -0
- package/bin/ai-engineering-loop.js +979 -69
- package/core/root-cause-analysis.md +6 -0
- package/core/runtime-safety.md +30 -3
- package/evals/cases/21-tier-t0-docs.json +34 -0
- package/evals/cases/22-tier-t1-small-pass.json +30 -0
- package/evals/cases/23-tier-t1-blocker.json +26 -0
- package/evals/cases/24-tier-t1-auth-escalates.json +30 -0
- package/lib/auto-update.js +486 -0
- package/lib/budget.js +31 -1
- package/lib/cli-args.js +84 -0
- package/lib/docs.js +91 -0
- package/lib/doctor.js +7 -1
- package/lib/gates.js +114 -1
- package/lib/host-skill-build.js +121 -0
- package/lib/migrations.js +84 -0
- package/lib/project-registry.js +148 -0
- package/lib/run-state.js +6 -3
- package/lib/sync-hosts.js +325 -42
- package/lib/tier.js +134 -0
- package/lib/update-manager.js +17 -1
- package/lib/update-notice.js +192 -0
- package/lib/user-state.js +80 -0
- package/lib/verification-recorder.js +44 -0
- package/migrations/README.md +21 -0
- package/package.json +7 -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
|
};
|
package/lib/cli-args.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
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
|
+
update: { flags: ['--json', '--yes', '--background', '--force', '--no-pin'], valued: ['--channel', '--pin'], positionals: ['check', 'plan', 'apply', 'auto', 'policy', 'rollback', ...['off', 'notify', 'patch', 'minor', 'all']] },
|
|
17
|
+
projects: { flags: ['--json'], valued: ['--root', '--depth'], positionals: null },
|
|
18
|
+
migrate: { flags: ['--json', '--dry-run'], valued: ['--from'], positionals: [] },
|
|
19
|
+
verify: { flags: ['--json', '--serial', '--shell'], valued: ['--run', '--cmd', '--timeout-ms'], positionals: [] },
|
|
20
|
+
'review-pack': { flags: ['--json'], valued: ['--run', '--base', '--profile'], positionals: [] },
|
|
21
|
+
deliver: { flags: ['--json', '--approve'], valued: ['--run', '--destination', '--summary', '--by'], positionals: [] },
|
|
22
|
+
'generate-adapter': { flags: [], valued: ['--type'], positionals: [] },
|
|
23
|
+
'generate-workflow': { flags: ['--write'], valued: [], positionals: [] }
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
function beforeSeparator(args) {
|
|
27
|
+
const index = args.indexOf('--');
|
|
28
|
+
return index === -1 ? args : args.slice(0, index);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function wantsCommandHelp(command, rest) {
|
|
32
|
+
const scoped = beforeSeparator(rest);
|
|
33
|
+
// `run` takes free-text task words; only a leading help flag counts.
|
|
34
|
+
if (command === 'run') return scoped.length > 0 && HELP_FLAGS.has(scoped[0]);
|
|
35
|
+
return scoped.some((arg) => HELP_FLAGS.has(arg));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function unknownWriterArgs(command, rest) {
|
|
39
|
+
const spec = WRITER_COMMANDS[command];
|
|
40
|
+
if (!spec) return [];
|
|
41
|
+
const scoped = beforeSeparator(rest);
|
|
42
|
+
const unknown = [];
|
|
43
|
+
for (let index = 0; index < scoped.length; index += 1) {
|
|
44
|
+
const arg = scoped[index];
|
|
45
|
+
if (arg.startsWith('-')) {
|
|
46
|
+
const [name] = arg.split('=');
|
|
47
|
+
if (spec.valued.includes(name)) {
|
|
48
|
+
if (!arg.includes('=')) index += 1;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (spec.flags.includes(arg)) continue;
|
|
52
|
+
unknown.push(arg);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (spec.positionals === null) continue;
|
|
56
|
+
if (!spec.positionals.includes(arg)) unknown.push(arg);
|
|
57
|
+
}
|
|
58
|
+
return unknown;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function commandHelp(helpText, command) {
|
|
62
|
+
const lines = String(helpText).split('\n');
|
|
63
|
+
const start = lines.findIndex((line) => {
|
|
64
|
+
const match = line.match(/^ (\S+)/);
|
|
65
|
+
return match && match[1] === command;
|
|
66
|
+
});
|
|
67
|
+
if (start === -1) return null;
|
|
68
|
+
const block = [lines[start]];
|
|
69
|
+
for (let index = start + 1; index < lines.length; index += 1) {
|
|
70
|
+
const line = lines[index];
|
|
71
|
+
if (/^ \S/.test(line) || /^\S/.test(line) || line.trim() === '') break;
|
|
72
|
+
block.push(line);
|
|
73
|
+
}
|
|
74
|
+
return block.join('\n');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
module.exports = {
|
|
78
|
+
HELP_FLAGS,
|
|
79
|
+
WRITER_COMMANDS,
|
|
80
|
+
beforeSeparator,
|
|
81
|
+
wantsCommandHelp,
|
|
82
|
+
unknownWriterArgs,
|
|
83
|
+
commandHelp
|
|
84
|
+
};
|