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
package/lib/sync-hosts.js CHANGED
@@ -1,17 +1,26 @@
1
1
  'use strict';
2
2
 
3
3
  const fs = require('fs');
4
- const os = require('os');
5
4
  const path = require('path');
5
+ const {
6
+ homeDir,
7
+ sha256,
8
+ userStatePath,
9
+ readJsonFile,
10
+ writeJsonFile,
11
+ readUserConfig,
12
+ writeUserConfig
13
+ } = require('./user-state.js');
6
14
 
7
15
  function packageRoot() {
8
16
  return path.join(__dirname, '..');
9
17
  }
10
18
 
11
- function homeDir(env = process.env) {
12
- if (env.AEL_HOME) return env.AEL_HOME;
13
- return os.homedir();
14
- }
19
+ // Host packs. `core` is always installed; the others are opt-in so unrelated
20
+ // skills do not enter every session's skill index (issue #31).
21
+ const HOST_PACKS = Object.freeze(['core', 'backend', 'design', 'quality']);
22
+ const DEFAULT_HOST_PACKS = Object.freeze(['core']);
23
+ const MANIFEST_FILE = 'host-manifest.json';
15
24
 
16
25
  function applyGrokSkillOverlay(content) {
17
26
  const normalized = String(content).replace(/\r\n?/g, '\n');
@@ -67,6 +76,7 @@ function backendSkillFiles(srcRoot, destRoot, { grokSkillOverlay = false } = {})
67
76
  src: path.posix.join(srcRoot, file),
68
77
  dest: path.join(destRoot, file),
69
78
  mode: 'upsert',
79
+ pack: 'backend',
70
80
  ...(grokSkillOverlay && file === 'SKILL.md' ? { grokSkillOverlay: true } : {})
71
81
  }));
72
82
  }
@@ -77,11 +87,50 @@ function emilKowalskiSkillFiles(srcRoot, destRoot, { grokSkillOverlay = false }
77
87
  src: path.posix.join(srcRoot, skill, file),
78
88
  dest: path.join(destRoot, skill, file),
79
89
  mode: 'upsert',
90
+ pack: 'design',
80
91
  ...(grokSkillOverlay && file === 'SKILL.md' ? { grokSkillOverlay: true } : {})
81
92
  }))
82
93
  ));
83
94
  }
84
95
 
96
+ // Adopted skills (issue #36). project-onboarding ships with core; the quality
97
+ // pack (ael-code-simplifier, ael-receiving-code-review) is opt-in.
98
+ const QUALITY_SKILLS = Object.freeze(['ael-code-simplifier', 'ael-receiving-code-review']);
99
+
100
+ function adoptedSkillFiles(destRoot, { grokSkillOverlay = false } = {}) {
101
+ const overlay = grokSkillOverlay ? { grokSkillOverlay: true } : {};
102
+ return [
103
+ { src: 'adapters/project-onboarding/SKILL.md', dest: path.join(destRoot, 'project-onboarding/SKILL.md'), mode: 'upsert', ...overlay },
104
+ { src: 'adapters/project-onboarding/references/output.md', dest: path.join(destRoot, 'project-onboarding/references/output.md'), mode: 'upsert' },
105
+ ...QUALITY_SKILLS.map((skill) => ({
106
+ src: `adapters/quality/skills/${skill}/SKILL.md`,
107
+ dest: path.join(destRoot, skill, 'SKILL.md'),
108
+ mode: 'upsert',
109
+ pack: 'quality',
110
+ ...overlay
111
+ }))
112
+ ];
113
+ }
114
+
115
+ // Loop stage references sit beside each host's SKILL.md (issue #35).
116
+ const LOOP_REFERENCE_FILES = Object.freeze([
117
+ 'loop-commands.md',
118
+ 'loop-deliver.md',
119
+ 'loop-goal.md',
120
+ 'loop-maker.md',
121
+ 'loop-review.md',
122
+ 'loop-risky.md',
123
+ 'loop-verify.md'
124
+ ]);
125
+
126
+ function loopReferenceFiles(srcDir, destDir) {
127
+ return LOOP_REFERENCE_FILES.map((file) => ({
128
+ src: path.posix.join(srcDir, 'references', file),
129
+ dest: path.join(destDir, 'references', file),
130
+ mode: 'upsert'
131
+ }));
132
+ }
133
+
85
134
  function hostFileMap(home) {
86
135
  const claude = path.join(home, '.claude');
87
136
  const grok = path.join(home, '.grok');
@@ -93,11 +142,13 @@ function hostFileMap(home) {
93
142
  root: claude,
94
143
  files: [
95
144
  { src: '.claude/skills/ai-engineering-loop/SKILL.md', dest: path.join(claude, 'skills/ai-engineering-loop/SKILL.md'), mode: 'upsert' },
145
+ ...loopReferenceFiles('.claude/skills/ai-engineering-loop', path.join(claude, 'skills/ai-engineering-loop')),
96
146
  ...backendSkillFiles('.claude/skills/backend-development', path.join(claude, 'skills/backend-development')),
97
147
  ...emilKowalskiSkillFiles('.claude/skills', path.join(claude, 'skills')),
98
148
  { src: 'adapters/dot/skills/task-impact-inquiry/SKILL.md', dest: path.join(claude, 'skills/task-impact-inquiry/SKILL.md'), mode: 'upsert' },
99
149
  { src: 'adapters/generate-adapter/SKILL.md', dest: path.join(claude, 'skills/generate-adapter/SKILL.md'), mode: 'upsert' },
100
150
  { src: 'adapters/generate-workflow/SKILL.md', dest: path.join(claude, 'skills/generate-workflow/SKILL.md'), mode: 'upsert' },
151
+ ...adoptedSkillFiles(path.join(claude, 'skills')),
101
152
  { src: '.claude/agents/devil-advocate.md', dest: path.join(claude, 'agents/devil-advocate.md'), mode: 'upsert' },
102
153
  { src: '.claude/agents/judge.md', dest: path.join(claude, 'agents/judge.md'), mode: 'upsert' },
103
154
  { src: '.claude/commands/ai-engineering-loop.md', dest: path.join(claude, 'commands/ai-engineering-loop.md'), mode: 'upsert' }
@@ -108,11 +159,13 @@ function hostFileMap(home) {
108
159
  root: grok,
109
160
  files: [
110
161
  { src: '.grok/skills/ai-engineering-loop/SKILL.md', dest: path.join(grok, 'skills/ai-engineering-loop/SKILL.md'), mode: 'upsert', grokSkillOverlay: true },
162
+ ...loopReferenceFiles('.grok/skills/ai-engineering-loop', path.join(grok, 'skills/ai-engineering-loop')),
111
163
  ...backendSkillFiles('.grok/skills/backend-development', path.join(grok, 'skills/backend-development'), { grokSkillOverlay: true }),
112
164
  ...emilKowalskiSkillFiles('.grok/skills', path.join(grok, 'skills'), { grokSkillOverlay: true }),
113
165
  { src: 'adapters/dot/skills/task-impact-inquiry/SKILL.md', dest: path.join(grok, 'skills/task-impact-inquiry/SKILL.md'), mode: 'upsert', grokSkillOverlay: true },
114
166
  { src: 'adapters/generate-adapter/SKILL.md', dest: path.join(grok, 'skills/generate-adapter/SKILL.md'), mode: 'upsert', grokSkillOverlay: true },
115
167
  { src: 'adapters/generate-workflow/SKILL.md', dest: path.join(grok, 'skills/generate-workflow/SKILL.md'), mode: 'upsert', grokSkillOverlay: true },
168
+ ...adoptedSkillFiles(path.join(grok, 'skills'), { grokSkillOverlay: true }),
116
169
  { src: '.grok/agents/devil-advocate.md', dest: path.join(grok, 'agents/devil-advocate.md'), mode: 'upsert' },
117
170
  { src: '.grok/agents/judge.md', dest: path.join(grok, 'agents/judge.md'), mode: 'upsert' },
118
171
  { src: '.grok/commands/ai-engineering-loop.md', dest: path.join(grok, 'commands/ai-engineering-loop.md'), mode: 'upsert' }
@@ -123,11 +176,13 @@ function hostFileMap(home) {
123
176
  root: gemini,
124
177
  files: [
125
178
  { src: '.gemini/skills/ai-engineering-loop/SKILL.md', dest: path.join(gemini, 'config/skills/ai-engineering-loop/SKILL.md'), mode: 'upsert' },
179
+ ...loopReferenceFiles('.gemini/skills/ai-engineering-loop', path.join(gemini, 'config/skills/ai-engineering-loop')),
126
180
  ...backendSkillFiles('.gemini/skills/backend-development', path.join(gemini, 'config/skills/backend-development')),
127
181
  ...emilKowalskiSkillFiles('.gemini/skills', path.join(gemini, 'config/skills')),
128
182
  { src: 'adapters/dot/skills/task-impact-inquiry/SKILL.md', dest: path.join(gemini, 'config/skills/task-impact-inquiry/SKILL.md'), mode: 'upsert' },
129
183
  { src: 'adapters/generate-adapter/SKILL.md', dest: path.join(gemini, 'config/skills/generate-adapter/SKILL.md'), mode: 'upsert' },
130
- { src: 'adapters/generate-workflow/SKILL.md', dest: path.join(gemini, 'config/skills/generate-workflow/SKILL.md'), mode: 'upsert' }
184
+ { src: 'adapters/generate-workflow/SKILL.md', dest: path.join(gemini, 'config/skills/generate-workflow/SKILL.md'), mode: 'upsert' },
185
+ ...adoptedSkillFiles(path.join(gemini, 'config/skills'))
131
186
  ]
132
187
  },
133
188
  {
@@ -136,6 +191,7 @@ function hostFileMap(home) {
136
191
  files: [
137
192
  ...backendSkillFiles('.agents/skills/backend-development', path.join(agents, 'skills/backend-development')),
138
193
  ...emilKowalskiSkillFiles('.agents/skills', path.join(agents, 'skills')),
194
+ ...adoptedSkillFiles(path.join(agents, 'skills')),
139
195
  { src: '.agents/devil-advocate.md', dest: path.join(agents, 'devil-advocate.md'), mode: 'upsert' },
140
196
  { src: '.agents/judge.md', dest: path.join(agents, 'judge.md'), mode: 'upsert' },
141
197
  { src: '.agents/workflows/ai-engineering-loop.md', dest: path.join(agents, 'workflows/ai-engineering-loop.md'), mode: 'upsert' }
@@ -173,17 +229,104 @@ function isSymlink(dest) {
173
229
  }
174
230
  }
175
231
 
176
- function planHostSync({ packageRoot: root = packageRoot(), home = homeDir() } = {}) {
232
+ function findSymlinkAncestor(home, destination) {
233
+ const homePath = path.resolve(home);
234
+ const destinationPath = path.resolve(destination);
235
+ const relative = path.relative(homePath, destinationPath);
236
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return null;
237
+
238
+ let current = homePath;
239
+ const candidates = [];
240
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
241
+ current = path.join(current, segment);
242
+ candidates.push(current);
243
+ }
244
+ for (const candidate of candidates) {
245
+ try {
246
+ if (fs.lstatSync(candidate).isSymbolicLink()) return candidate;
247
+ } catch (error) {
248
+ if (error.code !== 'ENOENT') throw error;
249
+ }
250
+ }
251
+ return null;
252
+ }
253
+
254
+ function normalizePacks(value) {
255
+ const list = Array.isArray(value)
256
+ ? value
257
+ : String(value || '').split(',');
258
+ const packs = new Set(['core']);
259
+ for (const raw of list) {
260
+ const pack = String(raw).trim();
261
+ if (!pack) continue;
262
+ if (!HOST_PACKS.includes(pack)) {
263
+ const err = new Error(`Unknown host pack "${pack}". Use: ${HOST_PACKS.join(', ')}`);
264
+ err.code = 'UNKNOWN_HOST_PACK';
265
+ throw err;
266
+ }
267
+ packs.add(pack);
268
+ }
269
+ return HOST_PACKS.filter((pack) => packs.has(pack));
270
+ }
271
+
272
+ function manifestPath(home) {
273
+ return userStatePath(MANIFEST_FILE, home);
274
+ }
275
+
276
+ function readHostManifest(home = homeDir()) {
277
+ const value = readJsonFile(manifestPath(home), null);
278
+ if (!value || typeof value !== 'object' || typeof value.files !== 'object' || value.files === null) {
279
+ return { schemaVersion: 1, version: null, files: {} };
280
+ }
281
+ return { schemaVersion: 1, version: value.version || null, files: value.files };
282
+ }
283
+
284
+ function readFileText(dest) {
285
+ try {
286
+ return fs.readFileSync(dest, 'utf8');
287
+ } catch {
288
+ return null;
289
+ }
290
+ }
291
+
292
+ function packageContent(root, file) {
293
+ const srcAbs = path.join(root, file.src);
294
+ let content = fs.readFileSync(srcAbs, 'utf8').replace(/\r\n?/g, '\n');
295
+ if (file.grokSkillOverlay) content = applyGrokSkillOverlay(content);
296
+ return content;
297
+ }
298
+
299
+ // Pack selection precedence: explicit argument > saved user config > legacy
300
+ // auto-detect (a non-core pack stays selected while any of its files is already
301
+ // installed, so upgrading never silently freezes an existing install).
302
+ function resolvePacks({ packs, home }) {
303
+ if (packs != null) return { packs: normalizePacks(packs), source: 'argument' };
304
+ const config = readUserConfig(home);
305
+ if (Array.isArray(config.hostPacks)) return { packs: normalizePacks(config.hostPacks), source: 'config' };
306
+ const detected = new Set(DEFAULT_HOST_PACKS);
307
+ for (const group of hostFileMap(home)) {
308
+ for (const file of group.files) {
309
+ if (file.pack && file.pack !== 'core' && destExists(file.dest)) detected.add(file.pack);
310
+ }
311
+ }
312
+ return { packs: normalizePacks([...detected]), source: detected.size > 1 ? 'detected' : 'default' };
313
+ }
314
+
315
+ function planHostSync({ packageRoot: root = packageRoot(), home = homeDir(), packs = null, prune = false } = {}) {
177
316
  const results = [];
317
+ const selection = resolvePacks({ packs, home });
318
+ const manifest = readHostManifest(home);
178
319
  for (const group of hostFileMap(home)) {
179
320
  for (const file of group.files) {
180
321
  const srcAbs = path.join(root, file.src);
181
322
  const hostRoot = file.hostRoot || group.root;
323
+ const pack = file.pack || 'core';
182
324
  const item = {
183
325
  id: group.id,
184
326
  src: file.src,
185
327
  dest: file.dest,
186
- mode: file.mode
328
+ mode: file.mode,
329
+ pack
187
330
  };
188
331
  if (hostRoot && !fs.existsSync(hostRoot)) {
189
332
  results.push({ ...item, action: 'skip', reason: 'host-missing' });
@@ -193,67 +336,245 @@ function planHostSync({ packageRoot: root = packageRoot(), home = homeDir() } =
193
336
  results.push({ ...item, action: 'skip', reason: 'src-missing' });
194
337
  continue;
195
338
  }
196
- if (isSymlink(file.dest)) {
197
- results.push({ ...item, action: 'skip', reason: 'symlink' });
339
+ const symlinkPath = findSymlinkAncestor(home, file.dest);
340
+ if (symlinkPath) {
341
+ const isDestinationSymlink = path.resolve(symlinkPath) === path.resolve(file.dest);
342
+ results.push({
343
+ ...item,
344
+ action: 'skip',
345
+ reason: isDestinationSymlink ? 'symlink' : 'symlink-ancestor'
346
+ });
347
+ continue;
348
+ }
349
+ const content = packageContent(root, file);
350
+ const existing = destExists(file.dest) ? readFileText(file.dest) : null;
351
+ if (!selection.packs.includes(pack)) {
352
+ if (prune && existing !== null) {
353
+ const tracked = manifest.files[file.dest];
354
+ const currentHash = sha256(existing);
355
+ const ours = (tracked && tracked.sha256 === currentHash) || existing === content;
356
+ results.push(ours
357
+ ? { ...item, action: 'prune' }
358
+ : { ...item, action: 'skip', reason: 'modified' });
359
+ continue;
360
+ }
361
+ results.push({ ...item, action: 'skip', reason: 'pack-not-selected' });
198
362
  continue;
199
363
  }
200
- if (file.mode === 'update-if-exists' && !destExists(file.dest)) {
364
+ if (file.mode === 'update-if-exists' && existing === null) {
201
365
  results.push({ ...item, action: 'skip', reason: 'not-installed' });
202
366
  continue;
203
367
  }
204
- let content = fs.readFileSync(srcAbs, 'utf8').replace(/\r\n?/g, '\n');
205
- if (file.grokSkillOverlay) content = applyGrokSkillOverlay(content);
206
- if (destExists(file.dest) && fs.readFileSync(file.dest, 'utf8') === content) {
207
- results.push({ ...item, action: 'current' });
368
+ if (existing === content) {
369
+ results.push({ ...item, action: 'current', sha256: sha256(content) });
208
370
  continue;
209
371
  }
210
- results.push({ ...item, action: 'copy', content });
372
+ const tracked = existing === null ? null : manifest.files[file.dest];
373
+ // A file is "user-modified" when it exists and is not byte-identical to the
374
+ // content AEL last wrote. Legacy installs without a manifest count as
375
+ // modified, so the first managed sync keeps a backup instead of guessing.
376
+ const backup = existing !== null && !(tracked && tracked.sha256 === sha256(existing));
377
+ results.push({ ...item, action: 'copy', content, sha256: sha256(content), backup });
378
+ }
379
+ }
380
+ // Obsolete AEL files (decision 5 on #37): recorded in the manifest by an
381
+ // earlier sync but no longer shipped (for example a renamed skill). Removed
382
+ // when still byte-identical to what AEL wrote; edited ones are kept.
383
+ const known = new Set(results.map((item) => path.resolve(item.dest)));
384
+ const hostRoots = hostFileMap(home).map((group) => path.resolve(group.root || path.dirname(group.files[0] ? group.files[0].dest : home)));
385
+ for (const [dest, tracked] of Object.entries(manifest.files || {})) {
386
+ const abs = path.resolve(dest);
387
+ if (known.has(abs)) continue;
388
+ if (!hostRoots.some((root) => abs.startsWith(root + path.sep))) continue;
389
+ if (!destExists(abs)) {
390
+ results.push({ id: 'obsolete', src: null, dest: abs, pack: tracked.pack || null, action: 'forget' });
391
+ continue;
211
392
  }
393
+ if (findSymlinkAncestor(home, abs)) continue;
394
+ const current = readFileText(abs);
395
+ results.push(current !== null && tracked && sha256(current) === tracked.sha256
396
+ ? { id: 'obsolete', src: null, dest: abs, pack: tracked.pack || null, action: 'prune', reason: 'obsolete' }
397
+ : { id: 'obsolete', src: null, dest: abs, pack: tracked.pack || null, action: 'skip', reason: 'obsolete-modified' });
212
398
  }
399
+ results.packs = selection.packs;
400
+ results.packSource = selection.source;
213
401
  return results;
214
402
  }
215
403
 
216
- function applyHostSync({ packageRoot: root = packageRoot(), home = homeDir(), dryRun = false } = {}) {
217
- const plan = planHostSync({ packageRoot: root, home });
404
+ // Remove directories emptied by --prune, never above <home>/.<host>/skills.
405
+ function removeEmptyParents(dir, home) {
406
+ let current = path.resolve(dir);
407
+ const stop = path.resolve(home);
408
+ for (let depth = 0; depth < 3; depth += 1) {
409
+ if (path.basename(current) === 'skills' || path.dirname(current) === stop || current === stop) return;
410
+ try {
411
+ if (fs.readdirSync(current).length > 0) return;
412
+ fs.rmdirSync(current);
413
+ } catch {
414
+ return;
415
+ }
416
+ current = path.dirname(current);
417
+ }
418
+ }
419
+
420
+ function backupPathFor(dest) {
421
+ const base = `${dest}.ael-backup`;
422
+ if (!destExists(base)) return base;
423
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
424
+ return `${base}-${stamp}`;
425
+ }
426
+
427
+ function writeNoFollow(dest, content) {
428
+ const flags = fs.constants.O_WRONLY
429
+ | fs.constants.O_CREAT
430
+ | fs.constants.O_TRUNC
431
+ | (fs.constants.O_NOFOLLOW || 0);
432
+ const descriptor = fs.openSync(dest, flags, 0o600);
433
+ try {
434
+ fs.writeFileSync(descriptor, content);
435
+ } finally {
436
+ fs.closeSync(descriptor);
437
+ }
438
+ }
439
+
440
+ function applyHostSync({
441
+ packageRoot: root = packageRoot(),
442
+ home = homeDir(),
443
+ dryRun = false,
444
+ packs = null,
445
+ prune = false,
446
+ version = null
447
+ } = {}) {
448
+ const plan = planHostSync({ packageRoot: root, home, packs, prune });
218
449
  const applied = [];
450
+ const manifest = readHostManifest(home);
451
+ let manifestChanged = false;
219
452
  for (const item of plan) {
453
+ if (item.action === 'current') {
454
+ if (!dryRun && (!manifest.files[item.dest] || manifest.files[item.dest].sha256 !== item.sha256)) {
455
+ manifest.files[item.dest] = { sha256: item.sha256, pack: item.pack };
456
+ manifestChanged = true;
457
+ }
458
+ applied.push(item);
459
+ continue;
460
+ }
461
+ if (item.action === 'prune') {
462
+ if (!dryRun) {
463
+ fs.unlinkSync(item.dest);
464
+ removeEmptyParents(path.dirname(item.dest), home);
465
+ delete manifest.files[item.dest];
466
+ manifestChanged = true;
467
+ }
468
+ applied.push({ ...item, dryRun });
469
+ continue;
470
+ }
471
+ if (item.action === 'forget') {
472
+ if (!dryRun) {
473
+ delete manifest.files[item.dest];
474
+ manifestChanged = true;
475
+ }
476
+ continue;
477
+ }
220
478
  if (item.action !== 'copy') {
221
479
  applied.push(item);
222
480
  continue;
223
481
  }
224
- if (!dryRun) {
225
- fs.mkdirSync(path.dirname(item.dest), { recursive: true });
226
- fs.writeFileSync(item.dest, item.content);
482
+ if (dryRun) {
483
+ applied.push({ ...item, content: undefined, dryRun });
484
+ continue;
485
+ }
486
+ if (findSymlinkAncestor(home, item.dest)) {
487
+ applied.push({ ...item, action: 'skip', reason: 'symlink-ancestor', content: undefined });
488
+ continue;
489
+ }
490
+ fs.mkdirSync(path.dirname(item.dest), { recursive: true });
491
+ if (findSymlinkAncestor(home, item.dest)) {
492
+ applied.push({ ...item, action: 'skip', reason: 'symlink-ancestor', content: undefined });
493
+ continue;
494
+ }
495
+ let backupPath = null;
496
+ if (item.backup) {
497
+ backupPath = backupPathFor(item.dest);
498
+ writeNoFollow(backupPath, fs.readFileSync(item.dest));
227
499
  }
228
- applied.push({ ...item, content: undefined, dryRun });
500
+ writeNoFollow(item.dest, item.content);
501
+ manifest.files[item.dest] = { sha256: item.sha256, pack: item.pack };
502
+ manifestChanged = true;
503
+ applied.push({ ...item, content: undefined, dryRun, backupPath });
229
504
  }
505
+ if (!dryRun && manifestChanged) {
506
+ writeJsonFile(manifestPath(home), {
507
+ schemaVersion: 1,
508
+ version: version || manifest.version || null,
509
+ updatedAt: new Date().toISOString(),
510
+ files: manifest.files
511
+ });
512
+ } else if (!dryRun && version && manifest.version !== version && Object.keys(manifest.files).length > 0) {
513
+ writeJsonFile(manifestPath(home), { ...manifest, version, updatedAt: new Date().toISOString() });
514
+ }
515
+ if (!dryRun && packs != null) writeUserConfig({ hostPacks: plan.packs }, home);
516
+ applied.packs = plan.packs;
517
+ applied.packSource = plan.packSource;
230
518
  return applied;
231
519
  }
232
520
 
521
+ function hostSkillStatus({ packageRoot: root = packageRoot(), home = homeDir(), version = null } = {}) {
522
+ const plan = planHostSync({ packageRoot: root, home });
523
+ const staleFiles = plan.filter((item) => item.action === 'copy').length;
524
+ const managedFiles = plan.filter((item) => item.action === 'current').length;
525
+ const manifest = readHostManifest(home);
526
+ return {
527
+ installedVersion: manifest.version,
528
+ packageVersion: version,
529
+ stale: staleFiles > 0,
530
+ staleFiles,
531
+ managedFiles,
532
+ packs: plan.packs,
533
+ packSource: plan.packSource
534
+ };
535
+ }
536
+
233
537
  function summarizeHostSync(results) {
234
- const summary = { copy: 0, current: 0, skip: 0 };
538
+ const summary = { copy: 0, current: 0, skip: 0, backup: 0, prune: 0 };
235
539
  for (const item of results) {
236
- if (item.action === 'copy') summary.copy += 1;
237
- else if (item.action === 'current') summary.current += 1;
540
+ if (item.action === 'copy') {
541
+ summary.copy += 1;
542
+ if (item.backup) summary.backup += 1;
543
+ } else if (item.action === 'current') summary.current += 1;
544
+ else if (item.action === 'prune') summary.prune += 1;
238
545
  else summary.skip += 1;
239
546
  }
240
547
  return summary;
241
548
  }
242
549
 
550
+ const QUIET_SKIP_REASONS = new Set(['host-missing', 'not-installed', 'pack-not-selected']);
551
+
243
552
  function formatHostSyncReport(results, { version, dryRun = false } = {}) {
244
553
  const summary = summarizeHostSync(results);
245
554
  const lines = [
246
555
  `Host skills sync (v${version || 'unknown'})${dryRun ? ' [dry-run]' : ''}`,
247
556
  `- copy: ${summary.copy} current: ${summary.current} skip: ${summary.skip}`
557
+ + (summary.backup ? ` backup: ${summary.backup}` : '')
558
+ + (summary.prune ? ` prune: ${summary.prune}` : '')
248
559
  ];
560
+ if (results.packs) lines.push(`- packs: ${results.packs.join(', ')} (${results.packSource || 'default'})`);
249
561
  for (const item of results) {
250
- if (item.action === 'skip' && item.reason === 'host-missing') continue;
251
- if (item.action === 'skip' && item.reason === 'not-installed') continue;
562
+ if (item.action === 'skip' && QUIET_SKIP_REASONS.has(item.reason)) continue;
252
563
  const rel = item.dest;
253
- if (item.action === 'copy') lines.push(` ${item.id.padEnd(12)} ${dryRun ? 'would-copy' : 'copied'} ${rel}`);
564
+ if (item.action === 'copy') {
565
+ lines.push(` ${item.id.padEnd(12)} ${dryRun ? 'would-copy' : 'copied'} ${rel}`);
566
+ if (item.backup) {
567
+ lines.push(` ${''.padEnd(12)} ${dryRun ? 'would-backup' : 'backed-up'} ${item.backupPath || `${rel}.ael-backup`}`);
568
+ }
569
+ } else if (item.action === 'prune') lines.push(` ${item.id.padEnd(12)} ${dryRun ? 'would-prune' : 'pruned'} ${rel}`);
254
570
  else if (item.action === 'current') lines.push(` ${item.id.padEnd(12)} current ${rel}`);
255
571
  else lines.push(` ${item.id.padEnd(12)} skip(${item.reason}) ${rel}`);
256
572
  }
573
+ const notSelected = results.filter((item) => item.reason === 'pack-not-selected');
574
+ if (notSelected.length) {
575
+ const packs = [...new Set(notSelected.map((item) => item.pack))];
576
+ lines.push(`Optional packs not installed: ${packs.join(', ')} (add with --pack ${packs.join(',')})`);
577
+ }
257
578
  if (summary.copy > 0 && !dryRun) {
258
579
  lines.push('Skill text already loaded in this session stays stale until you start a new session.');
259
580
  }
@@ -261,6 +582,13 @@ function formatHostSyncReport(results, { version, dryRun = false } = {}) {
261
582
  }
262
583
 
263
584
  module.exports = {
585
+ QUALITY_SKILLS,
586
+ LOOP_REFERENCE_FILES,
587
+ HOST_PACKS,
588
+ DEFAULT_HOST_PACKS,
589
+ normalizePacks,
590
+ readHostManifest,
591
+ hostSkillStatus,
264
592
  packageRoot,
265
593
  homeDir,
266
594
  applyGrokSkillOverlay,
package/lib/tier.js ADDED
@@ -0,0 +1,134 @@
1
+ 'use strict';
2
+
3
+ // Task tiers (issue #33). Gates stay; only the number of stages that run
4
+ // depends on risk.
5
+ // T0 trivial: inline AC, Maker, verification, claimed-vs-reality, delivery. 0 subagents.
6
+ // T1 normal: failure-table Goal, TDD, verification, lean DA, deterministic review. 1 subagent.
7
+ // T2 risky: full flow (grill + blast radius, DA, Judge on STRONG_MODEL). 2 subagents.
8
+ // A tier can rise automatically (never fall) when the Maker diff shows more risk.
9
+
10
+ const { extractChangedPaths, isHighRiskPath } = require('./escalation.js');
11
+
12
+ const TIERS = Object.freeze({ T0: 'T0', T1: 'T1', T2: 'T2' });
13
+ const TIER_RANK = Object.freeze({ T0: 0, T1: 1, T2: 2 });
14
+
15
+ const T0_LIMITS = Object.freeze({ maxFiles: 3, maxChangedLines: 180 });
16
+ const T2_FILE_THRESHOLD = 10;
17
+
18
+ const TRIVIAL_TASK = /\b(typo|typos|spelling|docs?|documentation|readme|changelog|comment|comments|lint|linting|format|formatting|prettier|bump|version bump|wording|copy edit)\b/i;
19
+ const RISKY_TASK = /\b(auth|authentication|authorization|login|permission|permissions|rbac|payment|payments|billing|invoice|ledger|migration|migrations|schema|database|encrypt|encryption|crypto|secret|secrets|token|credential|credentials|security|vulnerability|deploy|deployment|infra|terraform|kubernetes|k8s)\b/i;
20
+ const DOC_PATH = /(^|\/)(docs?\/.*|[^/]+\.(md|mdx|txt|rst|adoc)|LICENSE[^/]*|CHANGELOG[^/]*|\.github\/ISSUE_TEMPLATE\/.*)$/i;
21
+
22
+ function normalizeTier(value) {
23
+ const tier = String(value || '').trim().toUpperCase();
24
+ if (!Object.hasOwn(TIERS, tier)) {
25
+ const err = new Error(`Invalid tier "${value}". Use T0, T1, or T2.`);
26
+ err.code = 'INVALID_TIER';
27
+ throw err;
28
+ }
29
+ return tier;
30
+ }
31
+
32
+ function maxTier(a, b) {
33
+ return TIER_RANK[a] >= TIER_RANK[b] ? a : b;
34
+ }
35
+
36
+ function changedLineCount(diff) {
37
+ let count = 0;
38
+ for (const line of String(diff || '').split('\n')) {
39
+ if ((line.startsWith('+') && !line.startsWith('+++')) || (line.startsWith('-') && !line.startsWith('---'))) count += 1;
40
+ }
41
+ return count;
42
+ }
43
+
44
+ // Classify from the task text and any paths already known (working tree at
45
+ // `run`, Maker diff later). Returns { tier, reasons: [{ code, detail }] }.
46
+ function classifyTier({ task = '', changedPaths = [], changedLines = null } = {}) {
47
+ const reasons = [];
48
+ const riskyPaths = changedPaths.filter(isHighRiskPath);
49
+ const riskyWord = String(task).match(RISKY_TASK);
50
+ if (riskyPaths.length) reasons.push({ code: 'HIGH_RISK_PATH', detail: riskyPaths.join(', '), tier: 'T2' });
51
+ if (riskyWord) reasons.push({ code: 'RISKY_TASK_TEXT', detail: riskyWord[0], tier: 'T2' });
52
+ if (changedPaths.length > T2_FILE_THRESHOLD) {
53
+ reasons.push({ code: 'MANY_FILES', detail: `${changedPaths.length} files > ${T2_FILE_THRESHOLD}`, tier: 'T2' });
54
+ }
55
+ if (reasons.length) return { tier: TIERS.T2, reasons };
56
+
57
+ const trivialWord = String(task).match(TRIVIAL_TASK);
58
+ const docsOnly = changedPaths.length > 0 && changedPaths.every((p) => DOC_PATH.test(p));
59
+ const small = changedPaths.length <= T0_LIMITS.maxFiles
60
+ && (changedLines == null || changedLines <= T0_LIMITS.maxChangedLines);
61
+ if (small && (trivialWord || docsOnly)) {
62
+ if (trivialWord) reasons.push({ code: 'TRIVIAL_TASK_TEXT', detail: trivialWord[0], tier: 'T0' });
63
+ if (docsOnly) reasons.push({ code: 'DOCS_ONLY_PATHS', detail: changedPaths.join(', '), tier: 'T0' });
64
+ return { tier: TIERS.T0, reasons };
65
+ }
66
+ reasons.push({ code: 'DEFAULT', detail: 'normal change', tier: 'T1' });
67
+ return { tier: TIERS.T1, reasons };
68
+ }
69
+
70
+ function initialTierState({ task, changedPaths = [], override = null, overrideReason = '', now = new Date() } = {}) {
71
+ const auto = classifyTier({ task, changedPaths });
72
+ if (override) {
73
+ const tier = normalizeTier(override);
74
+ const reason = String(overrideReason || '').trim();
75
+ if (!reason) {
76
+ const err = new Error('--tier requires --tier-reason "<why>" so the override is recorded.');
77
+ err.code = 'TIER_REASON_REQUIRED';
78
+ throw err;
79
+ }
80
+ return {
81
+ current: tier,
82
+ auto: auto.tier,
83
+ source: 'override',
84
+ reasons: [{ code: 'MANUAL_OVERRIDE', detail: reason.slice(0, 500), tier }, ...auto.reasons],
85
+ history: [{ from: null, to: tier, by: 'override', reason: reason.slice(0, 500), at: now.toISOString() }]
86
+ };
87
+ }
88
+ return {
89
+ current: auto.tier,
90
+ auto: auto.tier,
91
+ source: 'auto',
92
+ reasons: auto.reasons,
93
+ history: [{ from: null, to: auto.tier, by: 'run', at: now.toISOString() }]
94
+ };
95
+ }
96
+
97
+ // Re-assess from the gated Maker diff. Only raises the tier.
98
+ function raiseTierFromDiff(tierState, { task = '', diff = '', now = new Date() } = {}) {
99
+ if (!tierState || !tierState.current) return null;
100
+ const changedPaths = extractChangedPaths(diff);
101
+ const changedLines = changedLineCount(diff);
102
+ const assessed = classifyTier({ task: '', changedPaths, changedLines });
103
+ let next = assessed.tier;
104
+ // T0 must also stay inside T0 limits: a code diff that is not trivial by
105
+ // text or docs-only paths becomes T1.
106
+ if (tierState.current === TIERS.T0 && next === TIERS.T1) {
107
+ const stillTrivial = classifyTier({ task, changedPaths, changedLines }).tier === TIERS.T0;
108
+ if (stillTrivial) next = TIERS.T0;
109
+ }
110
+ const raised = maxTier(tierState.current, next);
111
+ if (raised === tierState.current) return null;
112
+ return {
113
+ ...tierState,
114
+ current: raised,
115
+ reasons: [...assessed.reasons.filter((r) => r.tier === raised), ...tierState.reasons],
116
+ history: [
117
+ ...(tierState.history || []),
118
+ { from: tierState.current, to: raised, by: 'maker-diff', reason: assessed.reasons.map((r) => r.code).join(',') || 'T0 limits exceeded', at: now.toISOString() }
119
+ ]
120
+ };
121
+ }
122
+
123
+ module.exports = {
124
+ TIERS,
125
+ TIER_RANK,
126
+ T0_LIMITS,
127
+ T2_FILE_THRESHOLD,
128
+ normalizeTier,
129
+ maxTier,
130
+ changedLineCount,
131
+ classifyTier,
132
+ initialTierState,
133
+ raiseTierFromDiff
134
+ };