joycraft 1.1.2 → 1.2.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 (28) hide show
  1. package/dist/joycraft-release.json +1 -1
  2. package/package.json +3 -3
  3. package/payload/.agents/skills/joycraft-decompose/SKILL.md +5 -1
  4. package/payload/.agents/skills/joycraft-entry/SKILL.md +16 -0
  5. package/payload/.agents/skills/joycraft-implement/SKILL.md +16 -0
  6. package/payload/.agents/skills/joycraft-session-end/SKILL.md +1 -1
  7. package/payload/.agents/skills/joycraft-testing/SKILL.md +7 -5
  8. package/payload/.agents/skills/joycraft-ui-slice/SKILL.md +4 -3
  9. package/payload/.agents/skills/joycraft-verify/SKILL.md +1 -1
  10. package/payload/.claude/agents/joycraft-reviewer.md +7 -2
  11. package/payload/.joycraft/contracts/types.d.ts +22 -0
  12. package/payload/.joycraft/references/archive.md +4 -2
  13. package/payload/.joycraft/references/completion.md +55 -2
  14. package/payload/.joycraft/references/dispatch.md +12 -0
  15. package/payload/.joycraft/references/setup.md +36 -12
  16. package/payload/.joycraft/references/testing.md +14 -7
  17. package/payload/.joycraft/references/update.md +8 -0
  18. package/payload/.joycraft/references/workflow.md +3 -2
  19. package/payload/.joycraft/runtime/archive.mjs +19 -4
  20. package/payload/.joycraft/runtime/completion.mjs +210 -10
  21. package/payload/.joycraft/runtime/dispatch-preflight.mjs +16 -3
  22. package/payload/.joycraft/runtime/evidence.mjs +4 -0
  23. package/payload/.joycraft/runtime/identity.mjs +11 -0
  24. package/payload/.joycraft/runtime/review-tools.json +110 -30
  25. package/payload/.joycraft/runtime/review-tools.mjs +650 -126
  26. package/payload/.joycraft/runtime/status.mjs +1 -1
  27. package/payload/.joycraft/runtime/worktrees.mjs +1 -1
  28. package/payload/PIN +27 -27
@@ -1,5 +1,5 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { existsSync, lstatSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
@@ -7,7 +7,9 @@ import { pathToFileURL } from 'node:url';
7
7
  // One catalog for detection, the setup plan and the public docs.
8
8
  export const catalog = JSON.parse(readFileSync(new URL('./review-tools.json', import.meta.url), 'utf8'));
9
9
  const sectionHeading = '## Review loop';
10
- const marker = /<!-- joycraft:review-loop v1 (\{.*\}) -->/;
10
+ const marker = /<!-- joycraft:review-loop v(\d+) (\{.*\}) -->/;
11
+ // The host's own tools (its browser, simulator, computer use) are per machine, never in the shared AGENTS.md.
12
+ const localFile = '.joycraft/local/review-loop.json';
11
13
  const webDeps = ['next', 'vite', 'react-dom', 'vue', 'svelte', '@sveltejs/kit', 'astro', 'nuxt', '@remix-run/react', 'solid-js', '@angular/core', 'gatsby'];
12
14
  const apiDeps = ['express', 'fastify', 'koa', 'hono', '@nestjs/core', '@hapi/hapi'];
13
15
  const devServer = /\b(vite|next dev|nuxt dev|astro dev|webpack serve|react-scripts start|ng serve)\b/;
@@ -125,6 +127,17 @@ export function packageManager(dir, root = dir) {
125
127
  return { name: 'npm', add: ['npm', 'install', '-D'], exec: ['npx'] };
126
128
  }
127
129
 
130
+ function startCommand(dir, root, categories) {
131
+ const scripts = json(read(path.join(dir, 'package.json')))?.scripts ?? {};
132
+ const pm = packageManager(dir, root).name;
133
+ const script = ['dev', 'start', 'ios', 'android'].find(name => scripts[name]);
134
+ if (script) return `${pm} run ${script} (package.json, unrun)`;
135
+ if (categories.includes('android')) return './gradlew installDebug (unrun)';
136
+ if (categories.includes('ios')) return 'xcodebuild build (scheme not established)';
137
+ if (categories.includes('flutter')) return 'flutter run (unrun)';
138
+ return 'not established';
139
+ }
140
+
128
141
  /** Read-only probe: run a version or list command with no shell. Never installs. */
129
142
  export function defaultRun(command, args) {
130
143
  try { return { ok: true, stdout: execFileSync(command, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10000 }) }; }
@@ -132,104 +145,410 @@ export function defaultRun(command, args) {
132
145
  }
133
146
 
134
147
  const firstVersion = text => /\d+(?:\.\d+)+/.exec(text)?.[0] ?? null;
148
+ const hints = new Map(catalog.hints.map(hint => [hint.id, hint]));
149
+ const hintLabel = id => hints.get(id)?.label ?? id;
150
+ const scriptPattern = hint => (hint.detect.scripts ? new RegExp(hint.detect.scripts) : null);
151
+ const roleOf = id => hints.get(id)?.role ?? null;
152
+ // A picked hint covers the detected tools of its role; a picked tool outside the hint list covers the package's missing tools.
153
+ const covers = (pick, tool) => (roleOf(pick.id) ? roleOf(pick.id) === roleOf(tool.id) : tool.status !== 'present');
135
154
 
136
- function playwrightBrowsers(env, home) {
155
+ /** Is a downloaded Playwright Chromium in the browser cache? A directory listing only. */
156
+ export function playwrightBrowsers(env, home) {
137
157
  const roots = env.PLAYWRIGHT_BROWSERS_PATH ? [env.PLAYWRIGHT_BROWSERS_PATH]
138
158
  : [path.join(home, 'Library/Caches/ms-playwright'), path.join(home, '.cache/ms-playwright')];
139
159
  return roots.some(dir => listDir(dir).some(name => name.startsWith('chromium')));
140
160
  }
141
161
 
142
- function probe(id, { dir, root, run, env, home }) {
143
- const manifest = json(read(path.join(dir, 'package.json')));
144
- const deps = { ...manifest?.dependencies, ...manifest?.devDependencies };
145
- switch (id) {
146
- case 'playwright': {
147
- if (deps.cypress) return { status: 'present', version: String(deps.cypress), via: 'Cypress (already in the project)' };
148
- const names = ['@playwright/test', 'playwright'];
149
- const installed = names.flatMap(name => [dir, root].map(base => json(read(path.join(base, 'node_modules', name, 'package.json'))))).find(Boolean);
150
- const declared = names.map(name => deps[name]).find(Boolean);
151
- if (!declared && !installed) return { status: 'missing' };
152
- if (!playwrightBrowsers(env, home)) return { status: 'missing', version: installed?.version ?? null, note: 'browser not downloaded' };
153
- return { status: 'present', version: installed?.version ?? String(declared) };
154
- }
155
- case 'xcode': { const out = run('xcodebuild', ['-version']); return out.ok ? { status: 'present', version: firstVersion(out.stdout) } : { status: 'missing' }; }
156
- case 'ios-simulator': {
157
- const out = run('xcrun', ['simctl', 'list', 'runtimes']);
158
- const line = out.ok ? out.stdout.split('\n').find(row => /^iOS \d/.test(row.trim())) : null;
159
- return line ? { status: 'present', version: firstVersion(line) } : { status: 'missing' };
160
- }
161
- case 'android-sdk': { const out = run('adb', ['version']); return out.ok ? { status: 'present', version: firstVersion(out.stdout) } : { status: 'missing' }; }
162
- case 'android-emulator': {
163
- const out = run('emulator', ['-list-avds']);
164
- return out.ok && out.stdout.trim() ? { status: 'present', version: null, note: out.stdout.trim().split('\n')[0] } : { status: 'missing' };
165
- }
166
- case 'flutter': { const out = run('flutter', ['--version']); return out.ok ? { status: 'present', version: firstVersion(out.stdout) } : { status: 'missing' }; }
167
- case 'react-native-cli': case 'expo-cli': {
168
- const name = catalog.tools[id].package;
169
- return deps[name] ? { status: 'present', version: String(deps[name]) } : { status: 'missing' };
170
- }
171
- case 'curl': { const out = run('curl', ['--version']); return out.ok ? { status: 'present', version: firstVersion(out.stdout) } : { status: 'missing' }; }
172
- case 'test-runner': {
173
- const declared = manifest?.scripts?.test ? `${packageManager(dir, root).name} test`
174
- : existsSync(path.join(dir, 'Cargo.toml')) ? 'cargo test'
175
- : existsSync(path.join(dir, 'go.mod')) ? 'go test ./...'
176
- : ['pyproject.toml', 'requirements.txt', 'setup.py'].some(file => existsSync(path.join(dir, file))) ? 'python3 -m pytest' : null;
177
- return declared ? { status: 'present', version: null, note: `${declared} (declared, unrun)` } : { status: 'missing', note: 'no test command declared' };
162
+ const brandedBrowsers = {
163
+ chrome: { label: 'Chrome', apps: ['Google Chrome.app'], commands: ['google-chrome', 'google-chrome-stable'] },
164
+ msedge: { label: 'Microsoft Edge', apps: ['Microsoft Edge.app'], commands: ['microsoft-edge', 'microsoft-edge-stable'] },
165
+ };
166
+
167
+ /** Read-only: a branded browser is installed when its macOS app bundle exists or its command answers `--version`. */
168
+ export function browserInstalled(browser, { run = defaultRun, exists = existsSync, home = homedir() } = {}) {
169
+ const spec = brandedBrowsers[browser];
170
+ if (spec.apps.some(app => exists(path.join('/Applications', app)) || exists(path.join(home, 'Applications', app)))) return true;
171
+ return spec.commands.some(command => run(command, ['--version']).ok);
172
+ }
173
+
174
+ /** The bracketed or braced block that opens at `start`, by depth; strings are not parsed (a text read, not a run). */
175
+ function block(code, start) {
176
+ const open = code[start]; const close = open === '[' ? ']' : '}';
177
+ let depth = 0;
178
+ for (let index = start; index < code.length; index += 1) {
179
+ if (code[index] === open) depth += 1;
180
+ else if (code[index] === close && --depth === 0) return code.slice(start, index + 1);
181
+ }
182
+ return code.slice(start);
183
+ }
184
+
185
+ const channelOf = text => /\bchannel\s*:\s*['"`]([\w.-]+)['"`]/.exec(text)?.[1] ?? null;
186
+
187
+ /**
188
+ * The browser channel each Playwright project uses, read as text from `playwright.config.*`; null is the
189
+ * bundled Chromium. `projects[].use.channel` overrides the top-level `use.channel`. The config is never run.
190
+ */
191
+ export function playwrightChannels(dir) {
192
+ const channels = [];
193
+ for (const ext of ['ts', 'js', 'mjs', 'cjs']) {
194
+ const text = read(path.join(dir, `playwright.config.${ext}`));
195
+ if (!text) continue;
196
+ const code = text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1');
197
+ const at = /\bprojects\s*:\s*\[/.exec(code);
198
+ if (!at) { channels.push(channelOf(code)); continue; }
199
+ const list = block(code, at.index + at[0].length - 1);
200
+ const top = channelOf(code.replace(list, '[]'));
201
+ const projects = [];
202
+ for (let index = 1; index < list.length; index += 1) {
203
+ if (list[index] !== '{') continue;
204
+ const item = block(list, index);
205
+ projects.push(channelOf(item) ?? top);
206
+ index += item.length - 1;
178
207
  }
179
- default: return { status: 'not-needed' };
208
+ channels.push(...(projects.length ? projects : [top]));
209
+ }
210
+ return channels.length ? [...new Set(channels)] : [null];
211
+ }
212
+
213
+ /** Playwright is present only when every project's browser is here: the downloaded Chromium, or the branded browser a channel names. */
214
+ function playwrightBrowser(found, ctx) {
215
+ const needs = new Set(playwrightChannels(ctx.dir).map(channel => (!channel ? 'bundled'
216
+ : /^chrome(-|$)/.test(channel) ? 'chrome' : /^msedge(-|$)/.test(channel) ? 'msedge' : 'bundled')));
217
+ const absent = [...needs].filter(need => !(need === 'bundled' ? playwrightBrowsers(ctx.env, ctx.home) : browserInstalled(need, ctx)));
218
+ if (!absent.length) {
219
+ const branded = [...needs].filter(need => need !== 'bundled');
220
+ return branded.length ? { ...found, note: `${branded.map(need => brandedBrowsers[need].label).join(' and ')} channel` } : found;
221
+ }
222
+ const branded = absent.filter(need => need !== 'bundled').map(need => brandedBrowsers[need].label);
223
+ const note = [...(absent.includes('bundled') ? ['browser not downloaded'] : []), ...(branded.length ? [`${branded.join(' and ')} not installed`] : [])].join('; ');
224
+ if (absent.includes('bundled')) {
225
+ return { ...found, status: 'missing', note,
226
+ install: { scope: 'project', commands: [[...ctx.pm.exec, 'playwright', 'install', 'chromium']], size: 'about 150 MB', sudo: false } };
227
+ }
228
+ return { ...found, status: 'missing', note,
229
+ install: { scope: 'user', steps: [`Install ${branded.join(' and ')}, or point use.channel at a browser on this machine`], size: 'about 500 MB', sudo: false } };
230
+ }
231
+
232
+ function installedVersion(name, { dir, root }) {
233
+ return [dir, root].map(base => json(read(path.join(base, 'node_modules', name, 'package.json')))?.version).find(Boolean) ?? null;
234
+ }
235
+
236
+ function commandVersion(hint, run) {
237
+ for (const [command, ...args] of hint.detect.commands ?? []) {
238
+ const out = run(command, args);
239
+ if (out.ok) return firstVersion(out.stdout);
180
240
  }
241
+ return null;
181
242
  }
182
243
 
183
- function toolsFor(categories, dir) {
184
- const ids = new Set();
244
+ function declaredTestCommand({ dir, root, manifest }) {
245
+ return manifest?.scripts?.test ? `${packageManager(dir, root).name} test`
246
+ : existsSync(path.join(dir, 'Cargo.toml')) ? 'cargo test'
247
+ : existsSync(path.join(dir, 'go.mod')) ? 'go test ./...'
248
+ : ['pyproject.toml', 'requirements.txt', 'setup.py'].some(file => existsSync(path.join(dir, file))) ? 'python3 -m pytest' : null;
249
+ }
250
+
251
+ /** A project hint is in use when the package declares its dependency, holds its config file, or has a script that runs it. File reads only. */
252
+ function inPackage(hint, ctx) {
253
+ const { detect } = hint;
254
+ if (detect.testCommand) {
255
+ const declared = declaredTestCommand(ctx);
256
+ return declared ? { status: 'present', version: null, note: `${declared} (declared, unrun)` } : null;
257
+ }
258
+ const dependency = (detect.dependencies ?? []).find(name => Object.hasOwn(ctx.deps, name));
259
+ const config = (detect.configFiles ?? []).find(file => (file.startsWith('*')
260
+ ? ctx.names.some(name => name.endsWith(file.slice(1))) : existsSync(path.join(ctx.dir, file))));
261
+ const pattern = scriptPattern(hint);
262
+ const script = pattern && Object.entries(ctx.scripts).find(([, command]) => pattern.test(String(command)));
263
+ const job = !script ? ctx.ci.find(item => runsHint(hint, item)) : null;
264
+ if (!dependency && !config && !script && !job) return null;
265
+ const version = dependency ? installedVersion(dependency, ctx) ?? String(ctx.deps[dependency]) : commandVersion(hint, ctx.run);
266
+ const found = { status: 'present', version, via: `${hint.label} (already in the project)`,
267
+ signal: dependency ? `dependency ${dependency}` : config ? `file ${config}` : script ? `script ${script[0]}` : `CI ${job.source}` };
268
+ return hint.id === 'playwright' ? playwrightBrowser(found, ctx) : found;
269
+ }
270
+
271
+ /** A machine hint is present when one of its version or list commands answers (and matches, when it names a line). */
272
+ function onMachine(hint, run) {
273
+ for (const [command, ...args] of hint.detect.commands ?? []) {
274
+ const out = run(command, args);
275
+ if (!out.ok) continue;
276
+ if (!hint.detect.match) return { status: 'present', version: firstVersion(out.stdout) };
277
+ const line = out.stdout.split('\n').map(row => row.trim()).find(row => new RegExp(hint.detect.match).test(row));
278
+ if (!line) continue;
279
+ const version = firstVersion(line);
280
+ return { status: 'present', version, ...(version ? {} : { note: line }) };
281
+ }
282
+ return null;
283
+ }
284
+
285
+ function plannedInstall(hint, pm) {
286
+ const spec = hint.install;
287
+ if (spec.scope === 'project' && spec.packages) {
288
+ const then = (spec.then ?? []).map(command => command.flatMap(part => (part === '{exec}' ? pm.exec : [part])));
289
+ return { scope: 'project', commands: [[...pm.add, ...spec.packages], ...then], size: spec.size, sudo: false };
290
+ }
291
+ return { scope: 'user', steps: spec.steps, size: spec.size, sudo: spec.sudo,
292
+ ...(spec.commands ? { commands: spec.commands } : {}), ...(spec.licence ? { licence: true } : {}), ...(spec.signIn ? { signIn: true } : {}) };
293
+ }
294
+
295
+ /** A user-scope install Joycraft may run after a yes: commands, no sudo, no licence, no sign-in. Anything else is the user's steps. */
296
+ const runnable = install => install?.scope === 'user' && Boolean(install.commands?.length) && install.sudo === false && !install.licence && !install.signIn;
297
+ const runsHere = install => install?.scope === 'project' || runnable(install);
298
+ const commandText = install => install.commands.map(command => command.join(' ')).join(' && ');
299
+
300
+ function row(hint, result, ctx, label = hint.label) {
301
+ const install = result.install ?? (result.status === 'missing' ? plannedInstall(hint, ctx.pm) : null);
302
+ const { install: _ignored, ...rest } = result;
303
+ return { id: hint.id, label, ...rest, canShow: hint.canShow, ...(install ? { install } : {}),
304
+ evidence: hint.evidence ? hint.evidence.replace('{exec}', ctx.pm.exec.join(' ')) : null };
305
+ }
306
+
307
+ /**
308
+ * Fill one role of one kind: tools the package already uses win; then tools on this machine; then the
309
+ * host's own tools; only then a gap, which names the recommended hint.
310
+ */
311
+ function fillRole(kind, role, ctx) {
312
+ const candidates = catalog.hints.filter(hint => hint.role === role && hint.kinds.includes(kind));
313
+ const used = candidates.filter(hint => hint.foundBy !== 'host').map(hint => [hint, inPackage(hint, ctx)]).filter(([, result]) => result);
314
+ // A working tool fills the role: another declared tool of that role plans no install, only a note.
315
+ const working = used.filter(([, result]) => result.status === 'present');
316
+ if (working.length) {
317
+ const others = used.filter(([, result]) => result.status !== 'present')
318
+ .map(([hint, result]) => ({ id: hint.id, label: hint.label, status: result.status, ...(result.note ? { note: result.note } : {}) }));
319
+ return working.map(([hint, result], index) => row(hint, { ...result, ...(index === 0 && others.length ? { alsoDeclared: others } : {}) }, ctx));
320
+ }
321
+ if (used.length) return used.map(([hint, result]) => row(hint, result, ctx));
322
+ for (const hint of candidates.filter(item => item.foundBy === 'machine')) {
323
+ const result = onMachine(hint, ctx.run);
324
+ if (result) return [row(hint, result, ctx)];
325
+ }
326
+ for (const hint of candidates) {
327
+ const host = (hint.detect.hostTools ?? []).find(tool => ctx.hostTools.includes(tool));
328
+ if (host) return [row(hint, { status: 'present', version: null, via: `the host's built-in ${host}`, host }, ctx)];
329
+ }
330
+ const hint = hints.get(catalog.categories[kind].recommend[role]);
331
+ return [{ ...row(hint, { status: 'missing', ...(hint.missingNote ? { note: hint.missingNote } : {}) }, ctx, hint.install.label ?? hint.label), gap: `${kind}:${role}` }];
332
+ }
333
+
334
+ /** Each kind of app with each role its review needs; a mobile framework adds the platforms it targets. */
335
+ function slotsFor(categories, dir) {
336
+ const kinds = [];
185
337
  for (const category of categories) {
186
- for (const id of catalog.categories[category].tools) ids.add(id);
338
+ kinds.push(category);
187
339
  if (catalog.categories[category].mobile) {
188
340
  const ios = isDir(path.join(dir, 'ios')); const android = isDir(path.join(dir, 'android'));
189
- if (ios || !android) for (const id of catalog.categories.ios.tools) ids.add(id);
190
- if (android || !ios) for (const id of catalog.categories.android.tools) ids.add(id);
341
+ if (ios || !android) kinds.push('ios');
342
+ if (android || !ios) kinds.push('android');
191
343
  }
192
344
  }
193
- return [...ids];
345
+ return [...new Set(kinds)].flatMap(kind => catalog.categories[kind].needs.map(role => [kind, role]));
194
346
  }
195
347
 
196
- function startCommand(dir, root, categories) {
197
- const scripts = json(read(path.join(dir, 'package.json')))?.scripts ?? {};
198
- const pm = packageManager(dir, root).name;
199
- const script = ['dev', 'start', 'ios', 'android'].find(name => scripts[name]);
200
- if (script) return `${pm} run ${script} (package.json, unrun)`;
201
- if (categories.includes('android')) return './gradlew installDebug (unrun)';
202
- if (categories.includes('ios')) return 'xcodebuild build (scheme not established)';
203
- if (categories.includes('flutter')) return 'flutter run (unrun)';
204
- return 'not established';
348
+ // Open-input rule (`check-detection`: `name-or-command`): a script or CI job that matches no hint is proposed
349
+ // when its name OR its command looks like a check. Missing a real check costs more than one extra line.
350
+ const checkName = name => /(^|[:_.\-\s/])(e2e|smoke|checks?|integration|visual|acceptance|ui|browser|screenshots?|a11y|lighthouse|regression)([:_.\-\s/]|$)/i.test(name)
351
+ || /^tests?[:_.-]\w/i.test(name) || /\b(e2e|smoke|integration|acceptance|end[- ]to[- ]end)\b/i.test(name);
352
+ const checkCommand = command => /\b(tests?|checks?|e2e|smoke|curl|jest|vitest|mocha|ava|pytest)\b/i.test(command) || /\bnode\s+--test\b/.test(command);
353
+ // A CI step that only runs a package script (`npm run e2e`) is judged as that script.
354
+ const runsPackageScript = /^(npm|pnpm|yarn|bun)\s+(run\s+)?([\w:.-]+)\s*$/;
355
+ const setupCommand = /^(npm\s+(ci|install|i)|pnpm\s+(i|install)|yarn(\s+install)?|bun\s+install|(npm|pnpm|yarn|bun)\s+(run\s+)?build|pip\s+install|apt-get|sudo\s+apt-get|brew)\b/;
356
+ const isSetup = command => command.split('\n').filter(line => line.trim()).every(line => setupCommand.test(line.trim()));
357
+ const runsHint = (hint, item) => Boolean((item.command && scriptPattern(hint)?.test(item.command))
358
+ || (item.uses && (hint.detect.actions ?? []).some(action => item.uses.startsWith(action))));
359
+ // Known for this package: a hint of a kind the package is; with no kinds (a step tied to no package), any hint.
360
+ const knownHint = (item, kinds = null) => catalog.hints.find(hint => (!kinds || hint.kinds.some(kind => kinds.includes(kind))) && runsHint(hint, item)) ?? null;
361
+ // Lint, format and type checks are static checks, not a way to look at the work.
362
+ const staticCheck = /^\s*((npx|pnpm\s+exec|yarn|bunx)\s+)?(tsc|eslint|prettier|biome|stylelint|markdownlint|oxlint)\b/;
363
+ const proposal = (source, command) => ({ status: 'found, not in the hint list', source, command });
364
+
365
+ const yamlValue = raw => raw.replace(/\s+#.*$/, '').trim().replace(/^(['"])(.*)\1$/, '$2');
366
+
367
+ /** A block scalar (`|` literal, `>` folded) after `index` is one command: literal lines joined by newlines, folded by spaces. */
368
+ function blockScalar(lines, index, keyIndent, indicator) {
369
+ const body = [];
370
+ let next = index + 1;
371
+ for (; next < lines.length; next += 1) {
372
+ const line = lines[next];
373
+ if (line.trim() && /^\s*/.exec(line)[0].length <= keyIndent) break;
374
+ body.push(line.trim());
375
+ }
376
+ while (body.length && !body.at(-1)) body.pop();
377
+ return { command: indicator.startsWith('>') ? body.filter(Boolean).join(' ') : body.join('\n'), end: next - 1 };
205
378
  }
206
379
 
207
- /** The Review loop plan: each package, each tool it needs, and that tool's status. Probes only. */
208
- export function reviewLoopPlan(root, { run = defaultRun, hostTools = [], env = process.env, home = homedir(), packages: named = null } = {}) {
209
- const packages = detectProjects(root, { packages: named }).map(entry => {
210
- const dir = path.join(root, entry.path);
211
- const tools = toolsFor(entry.categories, dir).map(id => {
212
- const spec = catalog.tools[id];
213
- let result = probe(id, { dir, root, run, env, home });
214
- if (result.status === 'missing' && spec.hostAlternative && hostTools.includes(spec.hostAlternative)) {
215
- result = { status: 'present', version: null, via: `the host's built-in ${spec.hostAlternative}` };
380
+ /** GitHub Actions: each job (id, name, working-directory) and each step (name, run, uses, working-directory). Text read only. */
381
+ function githubJobs(text, source) {
382
+ const lines = text.split('\n');
383
+ const jobs = [];
384
+ let jobsIndent = null; let jobIndent = null; let job = null; let step = null; let stepIndent = null; let inSteps = false; let stepsIndent = null;
385
+ for (let index = 0; index < lines.length; index += 1) {
386
+ const line = lines[index];
387
+ if (!line.trim() || line.trim().startsWith('#')) continue;
388
+ const indent = /^\s*/.exec(line)[0].length;
389
+ if (jobsIndent === null) { if (/^jobs\s*:\s*$/.test(line.trim())) jobsIndent = indent; continue; }
390
+ if (indent <= jobsIndent) break;
391
+ jobIndent ??= indent;
392
+ if (indent === jobIndent) {
393
+ job = { source, id: /^([^:\s]+)\s*:/.exec(line.trim())?.[1] ?? '', name: null, where: null, steps: [] };
394
+ jobs.push(job); step = null; inSteps = false;
395
+ continue;
396
+ }
397
+ let body = line.trim();
398
+ let keyIndent = indent;
399
+ if (inSteps && /^-\s+/.test(body) && (stepIndent === null || indent === stepIndent)) {
400
+ stepIndent = indent; step = { name: null, run: null, uses: null, where: null }; job.steps.push(step);
401
+ body = body.replace(/^-\s+/, ''); keyIndent = indent + 2;
402
+ } else if (step && indent <= stepIndent) step = null;
403
+ if (inSteps && !step && indent <= stepsIndent) inSteps = false;
404
+ const pair = /^([\w-]+)\s*:\s*(.*)$/.exec(body);
405
+ if (!pair) continue;
406
+ const [, key, raw] = pair;
407
+ const value = yamlValue(raw);
408
+ if (key === 'steps' && !step) { inSteps = true; stepsIndent = indent; stepIndent = null; continue; }
409
+ const target = step ?? (indent === jobIndent + 2 || keyIndent === jobIndent + 2 ? job : null);
410
+ if (key === 'working-directory') (step ?? job).where = value;
411
+ if (!target) continue;
412
+ if (key === 'name') target.name = value;
413
+ if (step && key === 'uses') step.uses = value;
414
+ if (step && key === 'run') {
415
+ if (/^[|>][-+]?$/.test(value)) { const block = blockScalar(lines, index, keyIndent, value); step.run = block.command; index = block.end; }
416
+ else step.run = value;
417
+ }
418
+ }
419
+ return jobs;
420
+ }
421
+
422
+ const gitlabReserved = new Set(['stages', 'variables', 'default', 'include', 'image', 'workflow', 'cache', 'services', 'before_script', 'after_script', 'pages_root']);
423
+
424
+ /** GitLab CI: each top-level job and the commands in its `script:` list (a `- |` item is one command). Text read only. */
425
+ function gitlabJobs(text, source) {
426
+ const lines = text.split('\n');
427
+ const jobs = [];
428
+ let job = null;
429
+ for (let index = 0; index < lines.length; index += 1) {
430
+ const line = lines[index];
431
+ if (!line.trim() || line.trim().startsWith('#')) continue;
432
+ const indent = /^\s*/.exec(line)[0].length;
433
+ if (indent === 0) {
434
+ const id = /^([^:\s][^:]*)\s*:/.exec(line)?.[1]?.trim();
435
+ job = id && !id.startsWith('.') && !gitlabReserved.has(id) ? { source, id, name: id, where: null, steps: [] } : null;
436
+ if (job) jobs.push(job);
437
+ continue;
438
+ }
439
+ const pair = job && /^(\s*)script\s*:\s*(.*)$/.exec(line);
440
+ if (!pair) continue;
441
+ const keyIndent = pair[1].length; const inline = yamlValue(pair[2]);
442
+ if (inline && !inline.startsWith('[')) { job.steps.push({ name: null, run: inline, uses: null, where: null }); continue; }
443
+ for (let next = index + 1; next < lines.length; next += 1) {
444
+ const item = lines[next];
445
+ if (!item.trim()) continue;
446
+ const depth = /^\s*/.exec(item)[0].length;
447
+ if (depth < keyIndent || (depth === keyIndent && !/^\s*-\s+/.test(item))) { index = next - 1; break; }
448
+ const dash = /^(\s*)-\s+(.*)$/.exec(item);
449
+ if (dash) {
450
+ const value = yamlValue(dash[2]);
451
+ if (/^[|>][-+]?$/.test(value)) { const block = blockScalar(lines, next, dash[1].length, value); job.steps.push({ name: null, run: block.command, uses: null, where: null }); next = block.end; }
452
+ else job.steps.push({ name: null, run: value, uses: null, where: null });
216
453
  }
217
- const pm = packageManager(dir, root);
218
- const install = result.status !== 'missing' ? null : spec.scope === 'project' && id === 'playwright'
219
- ? { scope: 'project', commands: [[...pm.add, '@playwright/test'], [...pm.exec, 'playwright', 'install', 'chromium']], size: spec.size, sudo: false }
220
- : spec.scope === 'project' && spec.package ? { scope: 'project', commands: [[...pm.add, spec.package]], size: spec.size, sudo: false }
221
- : spec.scope === 'project' ? { scope: 'user', steps: ['Declare a test command for this package'], size: spec.size, sudo: false }
222
- : { scope: 'user', steps: spec.steps, size: spec.size, sudo: spec.sudo };
223
- return { id, label: spec.label, ...result, ...(install ? { install } : {}),
224
- evidence: spec.evidence ? spec.evidence.replace('{exec}', pm.exec.join(' ')) : null };
225
- });
226
- return { path: entry.path, categories: entry.categories, start: startCommand(dir, root, entry.categories), tools };
454
+ index = next;
455
+ }
456
+ }
457
+ return jobs;
458
+ }
459
+
460
+ /** CI steps at the project root, each with its job: GitHub Actions workflows and `.gitlab-ci.yml`. Read-only. */
461
+ function ciSteps(root) {
462
+ const files = listDir(path.join(root, '.github/workflows')).filter(name => /\.ya?ml$/.test(name)).sort().map(name => `.github/workflows/${name}`);
463
+ const jobs = files.flatMap(file => githubJobs(read(path.join(root, file)) ?? '', file));
464
+ const gitlab = read(path.join(root, '.gitlab-ci.yml'));
465
+ if (gitlab) jobs.push(...gitlabJobs(gitlab, '.gitlab-ci.yml'));
466
+ return jobs.flatMap(job => job.steps.map(step => ({ source: job.source, job: job.id, jobName: job.name, name: step.name,
467
+ command: step.run, uses: step.uses, where: [job.where, step.where].filter(Boolean).join(' ') })));
468
+ }
469
+
470
+ /** Scripts and CI jobs that look like a check by name or command but run no tool in the hint list: proposals, never counted present. */
471
+ function unknownChecks(ctx) {
472
+ const scripts = Object.entries(ctx.scripts)
473
+ .filter(([name, command]) => name !== 'test' && !staticCheck.test(String(command)) && (checkName(name) || checkCommand(String(command)))
474
+ && !knownHint({ command: String(command) }, ctx.kinds))
475
+ .map(([name, command]) => proposal(`package.json script "${name}"`, String(command)));
476
+ return [...scripts, ...ciProposals(ctx.ci, ctx.kinds, ctx.scripts)];
477
+ }
478
+
479
+ /**
480
+ * A CI step that runs no known tool is proposed when its job name, its step name or its command looks like a check.
481
+ * A step that only runs a package script of this package is judged as that script, so it is not listed twice.
482
+ */
483
+ function ciProposals(steps, kinds = null, scripts = {}) {
484
+ const out = [];
485
+ for (const item of steps) {
486
+ if (!item.command || knownHint(item, kinds) || isSetup(item.command) || staticCheck.test(item.command)) continue;
487
+ const script = runsPackageScript.exec(item.command)?.[3];
488
+ if (script && Object.hasOwn(scripts, script)) continue;
489
+ const named = [item.job, item.jobName, item.name].some(name => name && checkName(name));
490
+ if (named || checkCommand(item.command)) out.push(proposal(`CI ${item.source} job "${item.job}"`, item.command));
491
+ }
492
+ return out;
493
+ }
494
+
495
+ const mentions = (command, dir) => command.split(/[\s=;&|"'`()]+/).map(token => token.replace(/^\.\//, ''))
496
+ .some(token => token === dir || token.startsWith(`${dir}/`));
497
+
498
+ /**
499
+ * The Review loop plan: each package, the tools it already uses, and one gap line per kind of package with none. Probes only.
500
+ * `chosen` holds the tools the user picked at record time, per package: a tool they cover plans no install and no gap.
501
+ */
502
+ export function reviewLoopPlan(root, { run = defaultRun, hostTools = [], env = process.env, home = homedir(), exists = existsSync, packages: named = null, chosen = {} } = {}) {
503
+ const detected = detectProjects(root, { packages: named });
504
+ // A CI command belongs to the package whose folder it names, else to the root package.
505
+ const ci = new Map(detected.map(entry => [entry.path, []]));
506
+ const unplaced = [];
507
+ for (const item of ciSteps(root)) {
508
+ const owner = detected.filter(entry => entry.path !== '.' && mentions(`${item.command ?? ''} ${item.where}`, entry.path))
509
+ .sort((a, b) => b.path.length - a.path.length)[0]?.path ?? (ci.has('.') ? '.' : null);
510
+ if (owner) ci.get(owner).push(item); else unplaced.push(item);
511
+ }
512
+ const packages = detected.map(entry => {
513
+ const dir = path.join(root, entry.path);
514
+ const manifest = json(read(path.join(dir, 'package.json')));
515
+ const ctx = { dir, root, run, env, home, exists, hostTools, manifest, pm: packageManager(dir, root),
516
+ deps: { ...manifest?.dependencies, ...manifest?.devDependencies }, scripts: manifest?.scripts ?? {}, names: listDir(dir), ci: ci.get(entry.path),
517
+ kinds: [...new Set(slotsFor(entry.categories, dir).map(([kind]) => kind))] };
518
+ const tools = [];
519
+ for (const [kind, role] of slotsFor(entry.categories, dir)) {
520
+ for (const tool of fillRole(kind, role, ctx)) if (!tools.some(other => other.id === tool.id)) tools.push(tool);
521
+ }
522
+ for (const tool of tools) {
523
+ const pick = (chosen[entry.path] ?? []).find(item => covers(item, tool));
524
+ if (pick) { delete tool.install; delete tool.gap; tool.covered = { label: pick.label ?? hintLabel(pick.id), canShow: pick.canShow ?? [] }; }
525
+ }
526
+ const proposals = unknownChecks(ctx);
527
+ return { path: entry.path, categories: entry.categories, start: startCommand(dir, root, entry.categories), tools, ...(proposals.length ? { proposals } : {}) };
227
528
  });
228
- return { schemaVersion: 1, packages };
529
+ // Packages of the same kind with no tool share one gap line and one question, never one install each.
530
+ const groups = new Map();
531
+ for (const entry of packages) for (const tool of entry.tools) if (tool.gap) groups.set(tool.gap, [...(groups.get(tool.gap) ?? []), { path: entry.path, tool }]);
532
+ const gaps = [];
533
+ for (const [key, items] of groups) {
534
+ if (items.length < 2) continue;
535
+ const [kind, role] = key.split(':');
536
+ const { tool } = items[0];
537
+ for (const item of items) { delete item.tool.install; item.tool.shared = true; }
538
+ const hint = hints.get(tool.id);
539
+ gaps.push({ kind, role, packages: items.map(item => item.path),
540
+ recommend: { id: tool.id, label: tool.label, canShow: tool.canShow, ...plannedInstall(hint, packageManager(root)) } });
541
+ }
542
+ // CI steps that name no package in a workspace with no root package are reported, never dropped.
543
+ const proposals = ciProposals(unplaced);
544
+ const ciTools = unplaced.filter(item => knownHint(item)).map(item => ({ id: knownHint(item).id, label: knownHint(item).label,
545
+ source: `CI ${item.source} job "${item.job}"`, command: item.command ?? `uses: ${item.uses}` }));
546
+ return { schemaVersion: 2, packages, gaps, ...(proposals.length ? { proposals } : {}), ...(ciTools.length ? { ciTools } : {}) };
229
547
  }
230
548
 
231
- const statusText = tool => tool.status === 'present' ? `present${tool.version ? ` ${tool.version}` : ''}${tool.via ? ` (${tool.via})` : ''}`
549
+ const statusText = tool => tool.status === 'recorded' ? 'recorded choice' : tool.status === 'present' ? `present${tool.version ? ` ${tool.version}` : ''}${tool.via ? ` (${tool.via})` : ''}`
232
550
  : tool.status === 'skipped' ? 'skipped' : `missing${tool.note ? ` (${tool.note})` : ''}`;
551
+ const roleText = { ui: 'tool that can show the UI', request: 'HTTP check', tests: 'test command', toolchain: 'build toolchain' };
233
552
 
234
553
  /** One table and at most one question, decision first. */
235
554
  export function renderPlan(plan, changes = null) {
@@ -237,59 +556,125 @@ export function renderPlan(plan, changes = null) {
237
556
  return ['Review loop plan', '', 'No packages found: no workspaces are declared and no project manifest was found below the root.',
238
557
  '', 'Which folders hold the apps? Name them with `--packages <dir,dir>` on plan, install and record.'].join('\n');
239
558
  }
240
- const lines = ['Review loop plan', '', '| Package | Kind | Tool | Status | To install |', '|---|---|---|---|---|'];
241
- for (const entry of plan.packages) for (const tool of entry.tools) {
242
- const install = tool.install?.commands ? `\`${tool.install.commands.map(command => command.join(' ')).join(' && ')}\` (${tool.install.size})`
559
+ const lines = ['Review loop plan', '', '| Package | Kind | Tool | Status | To install | Can show |', '|---|---|---|---|---|---|'];
560
+ for (const entry of plan.packages) for (const item of entry.tools.filter(tool => !tool.shared)) {
561
+ // A tool the recorded choice covers shows that choice instead.
562
+ const tool = item.covered ? { label: item.covered.label, status: 'recorded', canShow: item.covered.canShow } : item;
563
+ if (item.covered && entry.tools.some(other => other !== item && other.covered?.label === item.covered.label && entry.tools.indexOf(other) < entry.tools.indexOf(item))) continue;
564
+ const install = runsHere(tool.install) ? `\`${commandText(tool.install)}\` (${tool.install.size}${tool.install.scope === 'user' ? ', for this machine' : ''})`
243
565
  : tool.install ? `you: ${tool.install.steps.join('; ')} (${tool.install.size}${tool.install.sudo ? ', needs sudo' : ''})` : '';
244
- lines.push(`| ${entry.path} | ${entry.categories.map(category => catalog.categories[category].label).join(', ')} | ${tool.label} | ${statusText(tool)} | ${install} |`);
566
+ lines.push(`| ${entry.path} | ${entry.categories.map(category => catalog.categories[category].label).join(', ')} | ${tool.label} | ${statusText(tool)}${tool.alsoDeclared ? `; also declared: ${tool.alsoDeclared.map(other => `${other.label} (${other.note ?? other.status}), no install planned`).join(', ')}` : ''} | ${install} | ${(tool.canShow ?? []).join(', ')} |`);
567
+ }
568
+ const gaps = plan.gaps ?? [];
569
+ for (const gap of gaps) {
570
+ const how = gap.recommend.scope === 'project' ? `one install, ${gap.recommend.size}`
571
+ : runnable(gap.recommend) ? `one install for this machine, \`${commandText(gap.recommend)}\`, ${gap.recommend.size}` : `you: ${gap.recommend.steps.join('; ')} (${gap.recommend.size})`;
572
+ lines.push('', `${catalog.categories[gap.kind].label}: no ${roleText[gap.role]} found in ${gap.packages.length} packages (${gap.packages.join(', ')}). Recommended: ${gap.recommend.label} (${how}; shows ${gap.recommend.canShow.join(', ')}).`);
573
+ }
574
+ for (const [where, item] of [...plan.packages.flatMap(entry => (entry.proposals ?? []).map(item => [`${entry.path} `, item])), ...(plan.proposals ?? []).map(item => ['', item])]) {
575
+ lines.push('', `Found, not in the hint list: ${where}${item.source} runs \`${item.command.replace(/\n+/g, '; ')}\`. It does not count as a review tool until it is recorded.`);
576
+ }
577
+ for (const item of plan.ciTools ?? []) {
578
+ lines.push('', `Found in CI, not tied to one package: ${item.label} (${item.source} runs \`${item.command.replace(/\n+/g, '; ')}\`). Say which packages it reviews.`);
245
579
  }
246
580
  if (changes) lines.push('', `Changed since the recorded Review loop: ${changes.join('; ')}.`);
247
- const local = missingProjectTools(plan);
248
- if (local.length) lines.push('', `Install the missing project-local tools (${local.map(item => `${item.tool.label} in ${item.path}`).join(', ')}), skip them, or choose per tool?`);
249
- if (plan.packages.some(entry => entry.tools.some(tool => tool.install?.scope === 'user'))) lines.push('', 'The tools marked "you" need your own install; Joycraft will not run them.');
581
+ const local = [...missingProjectTools(plan), ...machineInstalls(plan).filter(item => item.path).map(item => ({ path: item.path, tool: item }))];
582
+ const shared = gaps.filter(gap => runsHere(gap.recommend));
583
+ const asked = shared.length || local.length;
584
+ if (shared.length) {
585
+ const items = [...local.map(item => `${item.tool.label} in ${item.path}`), ...shared.map(gap => `${gap.recommend.label} once for the ${gap.packages.length} ${catalog.categories[gap.kind].label} packages`)];
586
+ lines.push('', `Install ${items.join(', ')}, name a tool these packages already use, skip them, or choose per tool?`);
587
+ } else if (local.length) lines.push('', `Install the missing tools (${local.map(item => `${item.tool.label} in ${item.path}`).join(', ')}), skip them, or choose per tool?`);
588
+ if (!asked && changes?.length) lines.push('', 'Record the Review loop again with these tools?');
589
+ if (plan.packages.some(entry => entry.tools.some(tool => tool.install && !runsHere(tool.install))) || gaps.some(gap => !runsHere(gap.recommend))) {
590
+ lines.push('', 'The tools marked "you" need your own install; Joycraft will not run them.');
591
+ }
250
592
  return lines.join('\n');
251
593
  }
252
594
 
595
+ /** Per-package project installs. A shared gap is one question, so it adds no per-package install here. */
253
596
  export function missingProjectTools(plan) {
254
597
  return plan.packages.flatMap(entry => entry.tools.filter(tool => tool.install?.scope === 'project').map(tool => ({ path: entry.path, tool })));
255
598
  }
256
599
 
257
- /** Run project-local installs the user approved. System tools are never installed here. */
600
+ /**
601
+ * User-scope installs, once per machine: the plan's missing tools and gaps, plus any hint `tools` names (the user's pick
602
+ * from the hint list). `runs` says whether Joycraft may run it; otherwise its steps are the user's.
603
+ */
604
+ function userInstalls(plan, tools = null) {
605
+ const out = new Map();
606
+ const add = (id, label, install, where = null) => {
607
+ if (install?.scope !== 'user' || out.has(id) || (tools && !tools.includes(id))) return;
608
+ out.set(id, { id, label, install, runs: runnable(install), ...(where ? { path: where } : {}) });
609
+ };
610
+ for (const entry of plan.packages) for (const tool of entry.tools) add(tool.id, tool.label, tool.install, entry.path);
611
+ for (const gap of plan.gaps ?? []) add(gap.recommend.id, gap.recommend.label, gap.recommend);
612
+ for (const hint of (tools ?? []).map(id => hints.get(id)).filter(Boolean)) if (hint.install.scope === 'user') add(hint.id, hint.label, plannedInstall(hint, null));
613
+ return [...out.values()];
614
+ }
615
+
616
+ /** The user-scope installs Joycraft may run after a yes. */
617
+ export function machineInstalls(plan, tools = null) {
618
+ return userInstalls(plan, tools).filter(item => item.runs);
619
+ }
620
+
621
+ /** What the user installs themselves: sudo, a licence, a sign-in, or no command. Joycraft prints these, never runs them. */
622
+ export function installSteps(plan, tools = null) {
623
+ return userInstalls(plan, tools).filter(item => !item.runs)
624
+ .map(({ id, label, install }) => ({ id, label, steps: install.steps, size: install.size,
625
+ ...(install.sudo ? { sudo: true } : {}), ...(install.licence ? { licence: true } : {}), ...(install.signIn ? { signIn: true } : {}) }));
626
+ }
627
+
628
+ /**
629
+ * Run the installs the user approved: project-local tools with the project's package manager, and user-scope CLIs
630
+ * (`npm install -g`, `brew install`) whose hint marks no sudo, licence or sign-in. Never sudo, a licence or a sign-in.
631
+ */
258
632
  export function installProjectTools(root, plan, { approved, tools = null, run = (command, args, cwd) => execFileSync(command, args, { cwd, stdio: 'inherit' }) }) {
259
633
  if (approved !== true) throw new Error('Install needs the user\'s yes in this conversation');
260
634
  const ran = [];
261
- for (const { path: dir, tool } of missingProjectTools(plan)) {
262
- if (tools && !tools.includes(tool.id)) continue;
263
- for (const [command, ...args] of tool.install.commands) { run(command, args, path.join(root, dir)); ran.push([command, ...args].join(' ')); }
264
- }
635
+ const exec = (commands, cwd) => { for (const [command, ...args] of commands) { run(command, args, cwd); ran.push([command, ...args].join(' ')); } };
636
+ for (const { path: dir, tool } of missingProjectTools(plan)) if (!tools || tools.includes(tool.id)) exec(tool.install.commands, path.join(root, dir));
637
+ for (const item of machineInstalls(plan, tools)) exec(item.install.commands, root);
265
638
  return ran;
266
639
  }
267
640
 
641
+
642
+ /** The recorded marker with its version, or null. A v1 marker still reads, so its statuses are kept. */
268
643
  function recorded(root) {
269
644
  const text = read(path.join(root, 'AGENTS.md'));
270
645
  const match = text && marker.exec(text);
271
- return match ? json(match[1]) : null;
646
+ const data = match && json(match[2]);
647
+ return data ? { ...data, version: Number(match[1]) } : null;
272
648
  }
273
649
 
274
- const summary = (plan, skipped = []) => Object.fromEntries(plan.packages.map(entry => [entry.path, {
650
+ /** What detection found per package. The host's own tools are not shared, so they are not compared. */
651
+ const summary = plan => Object.fromEntries(plan.packages.map(entry => [entry.path, {
275
652
  categories: entry.categories,
276
- tools: Object.fromEntries(entry.tools.map(tool => [tool.id, skipped.includes(tool.id) && tool.status === 'missing' ? 'skipped' : tool.status])),
653
+ tools: Object.fromEntries(entry.tools.filter(tool => !tool.host).map(tool => [tool.id, tool.status])),
277
654
  }]));
278
655
 
656
+ /** The tools the user picked per package in the recorded v2 marker, for the next plan. */
657
+ export function recordedChoices(root) {
658
+ const before = recorded(root);
659
+ if (!before || before.version < 2) return {};
660
+ return Object.fromEntries(Object.entries(before.packages ?? {})
661
+ .map(([pkg, entry]) => [pkg, (entry.chosen ?? []).filter(item => item.picked)]).filter(([, picks]) => picks.length));
662
+ }
663
+
279
664
  /** Differences between this detection and the recorded Review loop; null when nothing is recorded. */
280
665
  export function reviewLoopChanges(root, plan) {
281
666
  const before = recorded(root);
282
667
  if (!before) return null;
283
668
  const now = summary(plan);
284
- const changes = [];
669
+ const changes = before.version < 2 ? ['recorded with v1; re-record to keep it'] : [];
285
670
  for (const [pkg, entry] of Object.entries(now)) {
286
671
  const old = before.packages?.[pkg];
287
672
  if (!old) { changes.push(`new ${entry.categories.join(', ')} package ${pkg}`); continue; }
288
- for (const category of entry.categories) if (!old.categories.includes(category)) changes.push(`${pkg} is now also ${category}`);
673
+ for (const category of entry.categories) if (!(old.categories ?? []).includes(category)) changes.push(`${pkg} is now also ${category}`);
289
674
  for (const [id, status] of Object.entries(entry.tools)) {
290
- const was = old.tools[id];
291
- if (was === undefined) changes.push(`${pkg} needs ${catalog.tools[id].label}`);
292
- else if (was !== status && !(was === 'skipped' && status === 'missing')) changes.push(`${catalog.tools[id].label} in ${pkg}: ${was} -> ${status}`);
675
+ const was = old.tools?.[id];
676
+ if (was === undefined) changes.push(`${pkg} needs ${hintLabel(id)}`);
677
+ else if (was !== status && !(was === 'skipped' && status === 'missing')) changes.push(`${hintLabel(id)} in ${pkg}: ${was} -> ${status}`);
293
678
  }
294
679
  }
295
680
  for (const pkg of Object.keys(before.packages ?? {})) if (!now[pkg]) changes.push(`package ${pkg} is gone`);
@@ -298,45 +683,164 @@ export function reviewLoopChanges(root, plan) {
298
683
 
299
684
  /** Plan only what changed: an unchanged recorded loop asks nothing. */
300
685
  export function planForSetup(root, options) {
301
- const plan = reviewLoopPlan(root, options);
686
+ const plan = reviewLoopPlan(root, { chosen: recordedChoices(root), ...options });
302
687
  const changes = reviewLoopChanges(root, plan);
303
688
  return { plan, changes, ask: changes === null || changes.length > 0, text: changes && !changes.length ? 'Review loop unchanged.' : renderPlan(plan, changes) };
304
689
  }
305
690
 
306
- /** Write the chosen setup to AGENTS.md under `## Review loop`, replacing only that section. */
307
- export function recordReviewLoop(root, plan, { skipped = [] } = {}) {
691
+ const pair = (value, flag) => {
692
+ const at = value.indexOf('=');
693
+ if (at <= 0) throw new Error(`${flag} takes <package>=<value>; got ${value}`);
694
+ return [value.slice(0, at), value.slice(at + 1)];
695
+ };
696
+ const globPattern = spec => new RegExp(`^${spec.split('*').map(part => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')}$`);
697
+ /** The packages a `<package>` spec names: the exact folder, or every folder a `*` glob matches. */
698
+ function named(spec, paths, flag) {
699
+ const found = paths.includes(spec) ? [spec] : spec.includes('*') ? paths.filter(dir => globPattern(spec).test(dir)) : [];
700
+ if (!found.length) throw new Error(`${flag} ${spec} names no package; the packages are ${paths.join(', ')}`);
701
+ return found;
702
+ }
703
+
704
+ /** `--choose`, `--command` and `--can-show` per package. An exact package spec wins over a glob. */
705
+ function picksFor(root, plan, { choose, commands, canShow }) {
706
+ const paths = plan.packages.map(entry => entry.path);
707
+ const spread = (values, flag) => {
708
+ const out = new Map();
709
+ for (const value of values) {
710
+ const [spec, rest] = pair(value, flag);
711
+ for (const pkg of named(spec, paths, flag)) out.set(pkg, [...(out.get(pkg) ?? []), { spec, exact: spec === pkg, value: rest }]);
712
+ }
713
+ for (const [pkg, items] of out) if (items.some(item => item.exact)) out.set(pkg, items.filter(item => item.exact));
714
+ return out;
715
+ };
716
+ const picks = spread(choose, '--choose'); const extra = { command: spread(commands, '--command'), canShow: spread(canShow, '--can-show') };
717
+ for (const [key, flag] of [['command', '--command'], ['canShow', '--can-show']]) {
718
+ for (const [pkg, items] of extra[key]) if (!picks.has(pkg)) throw new Error(`${flag} ${items[0].spec} needs a --choose for ${pkg}`);
719
+ }
720
+ const out = new Map();
721
+ for (const [pkg, items] of picks) {
722
+ const entry = plan.packages.find(item => item.path === pkg);
723
+ const pm = packageManager(path.join(root, pkg), root);
724
+ out.set(pkg, items.map(({ spec, value: id }) => {
725
+ // A per-pick value: the same spec, else the package's only value when it has one pick.
726
+ const take = key => {
727
+ const values = extra[key].get(pkg) ?? [];
728
+ return (values.find(item => item.spec === spec) ?? (items.length === 1 && values.length === 1 ? values[0] : null))?.value ?? null;
729
+ };
730
+ const hint = hints.get(id);
731
+ const proposal = !hint && [...(entry.proposals ?? []), ...(plan.proposals ?? [])].find(item => item.source.endsWith(`"${id}"`));
732
+ const command = take('command') ?? (proposal ? proposal.command : null);
733
+ if (!hint && !command) throw new Error(`--choose ${spec}=${id} is not in the hint list; give its command with --command ${spec}=<command>`);
734
+ const shows = take('canShow')?.split(',').filter(Boolean) ?? hint?.canShow ?? ['run'];
735
+ const unknown = shows.find(item => !catalog.canShow.includes(item));
736
+ if (unknown) throw new Error(`--can-show ${unknown} is not one of ${catalog.canShow.join(', ')}`);
737
+ return { id, label: hint?.label ?? id, canShow: shows, picked: true, ...(command ? { command } : {}),
738
+ ...(proposal ? { source: proposal.source } : {}), ...(spec.includes('*') ? { shared: spec } : {}),
739
+ evidence: command ?? (hint.evidence ? hint.evidence.replace('{exec}', pm.exec.join(' ')) : 'not established') };
740
+ }));
741
+ }
742
+ return out;
743
+ }
744
+
745
+ /** `--skip <tool>` skips that tool where it is missing (all packages); `--skip <package>:<tool>` skips it in that package; `--skip <package>` skips the package. */
746
+ function skipsFor(plan, skipped) {
747
+ const paths = plan.packages.map(entry => entry.path);
748
+ const all = []; const perPackage = new Map();
749
+ for (const value of skipped) {
750
+ const at = value.lastIndexOf(':');
751
+ const [spec, id] = at > 0 ? [value.slice(0, at), value.slice(at + 1)] : paths.includes(value) ? [value, '*'] : [null, value];
752
+ if (!spec) { all.push(id); continue; }
753
+ for (const pkg of named(spec, paths, '--skip')) {
754
+ const entry = plan.packages.find(item => item.path === pkg);
755
+ if (id !== '*' && !entry.tools.some(tool => tool.id === id)) throw new Error(`--skip ${value}: ${pkg} has no ${id}; its tools are ${entry.tools.map(tool => tool.id).join(', ')}`);
756
+ perPackage.set(pkg, new Set([...(perPackage.get(pkg) ?? []), id]));
757
+ }
758
+ }
759
+ return { all, perPackage };
760
+ }
761
+
762
+ /** Write the host's own tools to the git-ignored `.joycraft/local/review-loop.json`, under its name. Other hosts' records stay. */
763
+ export function recordHostTools(root, { host, tools = [] }) {
764
+ if (!host) throw new Error('--host-tools needs --host <name>, the host these tools belong to');
765
+ const dir = path.join(root, path.dirname(localFile));
766
+ mkdirSync(dir, { recursive: true });
767
+ if (!existsSync(path.join(dir, '.gitignore'))) writeFileSync(path.join(dir, '.gitignore'), '*\n');
768
+ const file = path.join(root, localFile);
769
+ const current = json(read(file));
770
+ const entry = { tools: tools.map(name => {
771
+ const hint = catalog.hints.find(item => (item.detect.hostTools ?? []).includes(name));
772
+ return { name, ...(hint ? { canShow: hint.canShow, evidence: `the host's ${name} tool` } : {}) };
773
+ }) };
774
+ writeFileSync(file, `${JSON.stringify({ schemaVersion: 1, hosts: { ...(current?.hosts ?? {}), [host]: entry } }, null, 2)}\n`);
775
+ return localFile;
776
+ }
777
+
778
+ const cellSafe = text => String(text).replace(/\|/g, '\\|').replace(/\n+/g, '; ');
779
+
780
+ /**
781
+ * Write the chosen setup to AGENTS.md under `## Review loop`, replacing only that section: one row per package.
782
+ * Earlier picks and skips stay for the packages this call does not name. Host tools go to the local record only.
783
+ */
784
+ export function recordReviewLoop(root, plan, { skipped = [], choose = [], commands = [], canShow = [], host = null, hostTools = [] } = {}) {
308
785
  if (!plan.packages.length) throw new Error('No packages found, so there is nothing to record; name them with --packages <dir,dir>');
309
- const rows = ['| Package | Tool | Start the app | Take the evidence |', '|---|---|---|---|'];
310
- const unverified = [];
786
+ if (hostTools.length && !host) throw new Error('--host-tools needs --host <name>, the host these tools belong to');
787
+ const picks = picksFor(root, plan, { choose, commands, canShow });
788
+ const skips = skipsFor(plan, skipped);
789
+ const before = recorded(root);
790
+ const prior = before?.version >= 2 ? before.packages ?? {} : {};
791
+ const rows = ['| Package | Tool | Can show | Start the app | Take the evidence |', '|---|---|---|---|---|'];
792
+ const packages = {};
311
793
  for (const entry of plan.packages) {
312
- for (const tool of entry.tools) {
313
- const skip = skipped.includes(tool.id) && tool.status === 'missing';
314
- if ((skip || tool.status === 'missing') && entry.categories.some(category => catalog.categories[category].ui)) unverified.push(entry.path);
315
- rows.push(`| ${entry.path} | ${tool.label}: ${skip ? 'skipped' : statusText(tool)} | ${entry.start} | ${tool.evidence ?? (tool.note ?? 'not applicable')} |`);
316
- }
794
+ const detected = entry.tools.filter(tool => !tool.host);
795
+ const fresh = picks.has(entry.path) || skips.perPackage.has(entry.path);
796
+ const old = fresh ? null : prior[entry.path];
797
+ const chosen = picks.get(entry.path) ?? (old?.chosen ?? []).filter(item => item.picked);
798
+ const own = skips.perPackage.get(entry.path) ?? new Set();
799
+ // A carried skip holds while detection still sees that tool as it was when the user skipped it.
800
+ const skip = tool => own.has('*') || own.has(tool.id) || (skips.all.includes(tool.id) && tool.status === 'missing')
801
+ || Boolean(old?.skipped?.includes(tool.id) && old.tools?.[tool.id] === tool.status);
802
+ const items = [
803
+ ...detected.filter(tool => !chosen.some(pick => covers(pick, tool))).map(tool => ({ tool, skipped: skip(tool) })),
804
+ ...chosen.map(pick => ({ pick, skipped: own.has('*') })),
805
+ ];
806
+ const cell = ({ tool, pick, skipped: off }) => {
807
+ if (tool) return `${tool.label}: ${off ? 'not reviewed (user skipped)' : statusText(tool)}`;
808
+ const same = detected.find(item => item.id === pick.id && item.status === 'present');
809
+ return `${pick.label}: ${off ? 'not reviewed (user skipped)' : same ? statusText(same) : 'chosen by the user'}${pick.shared ? `, shared harness for ${pick.shared}` : ''}${pick.source ? ` (${pick.source})` : ''}`;
810
+ };
811
+ const used = items.filter(item => !item.skipped);
812
+ const shows = [...new Set(used.flatMap(item => (item.tool ?? item.pick).canShow ?? []))];
813
+ const evidence = used.map(({ tool, pick }) => (tool ? tool.evidence ?? tool.note ?? 'not applicable' : pick.evidence));
814
+ rows.push(`| ${entry.path} | ${cellSafe(items.map(cell).join('; '))} | ${shows.join(', ') || 'none'} | ${entry.start} | ${cellSafe(evidence.join('; ') || 'not reviewed (user skipped)')} |`);
815
+ const off = items.filter(item => item.skipped && item.tool).map(item => item.tool.id);
816
+ packages[entry.path] = { ...summary({ packages: [entry] })[entry.path],
817
+ chosen: used.map(({ tool, pick }) => (tool ? { id: tool.id, canShow: tool.canShow ?? [] }
818
+ : { id: pick.id, label: pick.label, canShow: pick.canShow, picked: true, evidence: pick.evidence,
819
+ ...(pick.command ? { command: pick.command } : {}), ...(pick.source ? { source: pick.source } : {}), ...(pick.shared ? { shared: pick.shared } : {}) })),
820
+ ...(off.length ? { skipped: off } : {}) };
317
821
  }
318
822
  const section = [sectionHeading, '',
319
- 'Recorded by Joycraft setup. The implementer, reviewer and UI checks use these tools and commands.', '',
823
+ 'Recorded by Joycraft setup. The implementer, reviewer and UI checks use these tools and commands.',
824
+ `Tools a host brings itself are recorded per machine in \`${localFile}\`, not here.`, '',
320
825
  ...rows,
321
- ...([...new Set(unverified)].length ? ['', `UI claims in ${[...new Set(unverified)].join(', ')} stay UNVERIFIED in review reports until the missing tools are set up.`] : []),
322
- '', `<!-- joycraft:review-loop v1 ${JSON.stringify({ packages: summary(plan, skipped) })} -->`, ''].join('\n');
826
+ '', `<!-- joycraft:review-loop v2 ${JSON.stringify({ packages })} -->`, ''].join('\n');
323
827
  const file = path.join(root, 'AGENTS.md');
324
828
  const text = read(file);
325
- if (text === null) { writeFileSync(file, `${section}`); return { created: true }; }
326
- const start = text.indexOf(`\n${sectionHeading}\n`);
327
- if (start < 0 && !text.startsWith(`${sectionHeading}\n`)) {
328
- writeFileSync(file, `${text}${text.endsWith('\n') ? '' : '\n'}\n${section}`);
329
- return { created: false };
829
+ let created = false;
830
+ if (text === null) { writeFileSync(file, `${section}`); created = true; } else {
831
+ const start = text.indexOf(`\n${sectionHeading}\n`);
832
+ if (start < 0 && !text.startsWith(`${sectionHeading}\n`)) writeFileSync(file, `${text}${text.endsWith('\n') ? '' : '\n'}\n${section}`);
833
+ else {
834
+ const from = text.startsWith(`${sectionHeading}\n`) ? 0 : start + 1;
835
+ const next = text.slice(from + sectionHeading.length).search(/\n## /);
836
+ const end = next < 0 ? text.length : from + sectionHeading.length + next + 1;
837
+ writeFileSync(file, `${text.slice(0, from)}${section}${end < text.length ? `\n${text.slice(end)}` : ''}`);
838
+ }
330
839
  }
331
- const from = text.startsWith(`${sectionHeading}\n`) ? 0 : start + 1;
332
- const next = text.slice(from + sectionHeading.length).search(/\n## /);
333
- const end = next < 0 ? text.length : from + sectionHeading.length + next + 1;
334
- writeFileSync(file, `${text.slice(0, from)}${section}${end < text.length ? `\n${text.slice(end)}` : ''}`);
335
- return { created: false };
840
+ return { created, ...(host ? { local: recordHostTools(root, { host, tools: hostTools }) } : {}) };
336
841
  }
337
842
 
338
- /** The recorded section text, for worker and reviewer packets. */
339
- export function reviewLoopSection(root) {
843
+ function sharedSection(root) {
340
844
  const text = read(path.join(root, 'AGENTS.md'));
341
845
  if (!text) return null;
342
846
  const start = text.startsWith(`${sectionHeading}\n`) ? 0 : text.indexOf(`\n${sectionHeading}\n`) + 1;
@@ -345,15 +849,28 @@ export function reviewLoopSection(root) {
345
849
  return text.slice(start, next < 0 ? undefined : start + sectionHeading.length + next).trim();
346
850
  }
347
851
 
852
+ /** For worker and reviewer packets: the shared section and, when this machine has one, the local host record. Null when neither exists. */
853
+ export function reviewLoopSection(root) {
854
+ const section = sharedSection(root);
855
+ const local = json(read(path.join(root, localFile)));
856
+ if (!section && !local) return null;
857
+ return { ...(section ? { path: 'AGENTS.md', section } : {}), ...(local ? { local: { path: localFile, record: local } } : {}) };
858
+ }
859
+
348
860
  export async function main(argv = process.argv.slice(2)) {
349
861
  const [command, ...rest] = argv;
350
862
  const flags = {};
863
+ const repeated = new Set(['--choose', '--command', '--can-show', '--skip']);
351
864
  for (let index = 0; index < rest.length; index += 1) {
352
865
  if (rest[index] === '--yes') { flags['--yes'] = true; continue; }
353
- flags[rest[index]] = rest[index + 1]; index += 1;
866
+ if (repeated.has(rest[index])) (flags[rest[index]] ??= []).push(rest[index + 1]);
867
+ else flags[rest[index]] = rest[index + 1];
868
+ index += 1;
354
869
  }
355
870
  const root = path.resolve(flags['--root'] ?? '.');
356
871
  const list = value => (value ? value.split(',').filter(Boolean) : []);
872
+ // `--choose` and `--skip` take comma lists; a `--command` or `--can-show` value is one item, so repeat the flag.
873
+ const many = (name, split = true) => (flags[name] ?? []).flatMap(value => (split ? list(value) : value ? [value] : []));
357
874
  const options = { hostTools: list(flags['--host-tools']), packages: flags['--packages'] ? list(flags['--packages']) : null };
358
875
  if (command === 'plan') {
359
876
  const { text, ask } = planForSetup(root, options);
@@ -361,16 +878,23 @@ export async function main(argv = process.argv.slice(2)) {
361
878
  return { ask };
362
879
  }
363
880
  if (command === 'install') {
364
- const ran = installProjectTools(root, reviewLoopPlan(root, options), { approved: flags['--yes'] === true, tools: flags['--tools'] ? list(flags['--tools']) : null });
365
- process.stdout.write(`${JSON.stringify({ ran }, null, 2)}\n`);
881
+ const plan = reviewLoopPlan(root, { ...options, chosen: recordedChoices(root) });
882
+ const tools = flags['--tools'] ? list(flags['--tools']) : null;
883
+ const ran = installProjectTools(root, plan, { approved: flags['--yes'] === true, tools });
884
+ const steps = installSteps(plan, tools);
885
+ process.stdout.write(`${JSON.stringify({ ran, ...(steps.length ? { steps } : {}) }, null, 2)}\n`);
366
886
  return ran;
367
887
  }
368
888
  if (command === 'record') {
369
- const result = recordReviewLoop(root, reviewLoopPlan(root, options), { skipped: list(flags['--skip']) });
889
+ // The shared record is detected without the host's tools; those go to the local record.
890
+ const result = recordReviewLoop(root, reviewLoopPlan(root, { ...options, hostTools: [] }), {
891
+ skipped: many('--skip'), choose: many('--choose'), commands: many('--command', false), canShow: many('--can-show', false),
892
+ host: flags['--host'] ?? null, hostTools: options.hostTools });
370
893
  process.stdout.write(`${JSON.stringify(result)}\n`);
371
894
  return result;
372
895
  }
373
- throw new Error('Usage: review-tools.mjs plan|install|record --root <project> [--packages apps/web,apps/api] [--host-tools browser,simulator] [--tools playwright --yes] [--skip playwright]');
896
+ throw new Error('Usage: review-tools.mjs plan|install|record --root <project> [--packages apps/web,apps/api] [--host-tools browser,simulator] [--tools playwright --yes]'
897
+ + ' [record: --choose <package>=<tool> --command <package>=<command> --can-show <package>=picture,run --skip <tool>|<package>:<tool>|<package> --host <name>]');
374
898
  }
375
899
 
376
900
  if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {