joycraft 1.1.1 → 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.
- package/README.md +57 -16
- package/dist/cli.js +50 -9
- package/dist/cli.js.map +1 -1
- package/dist/joycraft-release.json +1 -1
- package/package.json +3 -3
- package/payload/.agents/skills/joycraft-cleanup/SKILL.md +81 -34
- package/payload/.agents/skills/joycraft-context/SKILL.md +30 -4
- package/payload/.agents/skills/joycraft-decompose/SKILL.md +5 -1
- package/payload/.agents/skills/joycraft-entry/SKILL.md +35 -8
- package/payload/.agents/skills/joycraft-implement/SKILL.md +16 -0
- package/payload/.agents/skills/joycraft-session-end/SKILL.md +9 -4
- package/payload/.agents/skills/joycraft-testing/SKILL.md +7 -5
- package/payload/.agents/skills/joycraft-ui-slice/SKILL.md +4 -3
- package/payload/.agents/skills/joycraft-verify/SKILL.md +1 -1
- package/payload/.claude/agents/joycraft-reviewer.md +7 -2
- package/payload/.joycraft/assets/artifacts/kit.css +8 -0
- package/payload/.joycraft/assets/artifacts/kit.js +163 -21
- package/payload/.joycraft/assets/artifacts/transports.js +14 -3
- package/payload/.joycraft/contracts/types.d.ts +22 -0
- package/payload/.joycraft/references/archive.md +4 -2
- package/payload/.joycraft/references/artifacts.md +21 -2
- package/payload/.joycraft/references/cleanup.md +109 -3
- package/payload/.joycraft/references/completion.md +55 -2
- package/payload/.joycraft/references/context.md +64 -2
- package/payload/.joycraft/references/dispatch.md +12 -0
- package/payload/.joycraft/references/doc-cleanup-LICENSE.md +23 -0
- package/payload/.joycraft/references/knowledge.md +58 -0
- package/payload/.joycraft/references/setup.md +165 -151
- package/payload/.joycraft/references/testing.md +14 -7
- package/payload/.joycraft/references/update.md +13 -3
- package/payload/.joycraft/references/workflow.md +3 -2
- package/payload/.joycraft/runtime/archive.mjs +19 -4
- package/payload/.joycraft/runtime/artifacts/decisions.mjs +16 -5
- package/payload/.joycraft/runtime/artifacts/server.mjs +14 -1
- package/payload/.joycraft/runtime/cleanup.mjs +95 -8
- package/payload/.joycraft/runtime/completion.mjs +210 -10
- package/payload/.joycraft/runtime/config.mjs +5 -3
- package/payload/.joycraft/runtime/dispatch-preflight.mjs +16 -3
- package/payload/.joycraft/runtime/evidence.mjs +4 -0
- package/payload/.joycraft/runtime/identity.mjs +11 -0
- package/payload/.joycraft/runtime/review-tools.json +110 -30
- package/payload/.joycraft/runtime/review-tools.mjs +702 -131
- package/payload/.joycraft/runtime/status.mjs +1 -1
- package/payload/.joycraft/runtime/update-check.mjs +38 -8
- package/payload/.joycraft/runtime/wiring.mjs +156 -0
- package/payload/.joycraft/runtime/worktrees.mjs +1 -1
- package/payload/.joycraft/templates/joycraft.yaml +2 -0
- package/payload/.joycraft/templates/project-context.md +6 -1
- package/payload/PIN +45 -42
|
@@ -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
|
|
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/;
|
|
@@ -34,6 +36,40 @@ function workspaceDirs(root) {
|
|
|
34
36
|
return [...new Set(dirs)];
|
|
35
37
|
}
|
|
36
38
|
|
|
39
|
+
const manifestFile = /(^|\/)(package\.json|pubspec\.yaml|Package\.swift|build\.gradle(\.kts)?|pyproject\.toml|requirements\.txt|setup\.py|Cargo\.toml|go\.mod)$/;
|
|
40
|
+
const skipDir = name => name.startsWith('.') || ['node_modules', 'vendor', 'Pods', 'dist', 'build', 'target'].includes(name);
|
|
41
|
+
|
|
42
|
+
/** Project files below the root: git's view when it has one (so .gitignore holds), else a bounded walk. */
|
|
43
|
+
function projectFiles(root) {
|
|
44
|
+
try {
|
|
45
|
+
const out = execFileSync('git', ['-C', root, 'ls-files', '--cached', '--others', '--exclude-standard'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 });
|
|
46
|
+
return out.split('\n').filter(Boolean);
|
|
47
|
+
} catch {
|
|
48
|
+
const files = [];
|
|
49
|
+
const walk = (rel, depth) => {
|
|
50
|
+
for (const name of listDir(path.join(root, rel))) {
|
|
51
|
+
const file = rel ? `${rel}/${name}` : name;
|
|
52
|
+
if (isDir(path.join(root, file))) { if (depth < 6 && !skipDir(name)) walk(file, depth + 1); } else files.push(file);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
walk('', 0);
|
|
56
|
+
return files;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Folders holding a manifest when no workspaces are declared. The shallowest wins; an Android `app/` belongs to its parent. */
|
|
61
|
+
function nestedPackageDirs(root) {
|
|
62
|
+
const dirs = new Set();
|
|
63
|
+
for (const file of projectFiles(root)) {
|
|
64
|
+
if (!manifestFile.test(file) || file.split('/').some(skipDir)) continue;
|
|
65
|
+
let dir = path.posix.dirname(file);
|
|
66
|
+
if (/build\.gradle/.test(file) && path.posix.basename(dir) === 'app') dir = path.posix.dirname(dir);
|
|
67
|
+
if (dir !== '.') dirs.add(dir);
|
|
68
|
+
}
|
|
69
|
+
const sorted = [...dirs].sort();
|
|
70
|
+
return sorted.filter(dir => !sorted.some(other => other !== dir && dir.startsWith(`${other}/`)));
|
|
71
|
+
}
|
|
72
|
+
|
|
37
73
|
/** Categories for one package directory, from its manifests and project files only. */
|
|
38
74
|
export function classifyPackage(dir) {
|
|
39
75
|
const found = new Set();
|
|
@@ -65,11 +101,19 @@ export function classifyPackage(dir) {
|
|
|
65
101
|
return [...found];
|
|
66
102
|
}
|
|
67
103
|
|
|
68
|
-
/**
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
104
|
+
/**
|
|
105
|
+
* Each package of a project with its categories. A workspace root without its own app is not a package.
|
|
106
|
+
* `packages` names the folders outright; with no workspaces and no root manifest, nested manifests are scanned.
|
|
107
|
+
*/
|
|
108
|
+
export function detectProjects(root, { packages: named = null } = {}) {
|
|
109
|
+
const outside = (named ?? []).find(dir => path.isAbsolute(dir) || dir.split(/[\\/]/).includes('..'));
|
|
110
|
+
if (outside) throw new Error(`--packages takes folders inside the project; ${outside} is not`);
|
|
72
111
|
const own = classifyPackage(root);
|
|
112
|
+
const declared = named ?? workspaceDirs(root);
|
|
113
|
+
const dirs = named || declared.length || own.length ? declared : nestedPackageDirs(root);
|
|
114
|
+
const packages = dirs.map(dir => ({ path: dir, categories: classifyPackage(path.join(root, dir)) }))
|
|
115
|
+
.filter(entry => entry.categories.length);
|
|
116
|
+
if (named) return packages;
|
|
73
117
|
const workspaceOnly = packages.length && own.every(category => category === 'cli-library');
|
|
74
118
|
return [...(workspaceOnly || !own.length ? [] : [{ path: '.', categories: own }]), ...packages];
|
|
75
119
|
}
|
|
@@ -83,6 +127,17 @@ export function packageManager(dir, root = dir) {
|
|
|
83
127
|
return { name: 'npm', add: ['npm', 'install', '-D'], exec: ['npx'] };
|
|
84
128
|
}
|
|
85
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
|
+
|
|
86
141
|
/** Read-only probe: run a version or list command with no shell. Never installs. */
|
|
87
142
|
export function defaultRun(command, args) {
|
|
88
143
|
try { return { ok: true, stdout: execFileSync(command, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10000 }) }; }
|
|
@@ -90,160 +145,536 @@ export function defaultRun(command, args) {
|
|
|
90
145
|
}
|
|
91
146
|
|
|
92
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');
|
|
93
154
|
|
|
94
|
-
|
|
155
|
+
/** Is a downloaded Playwright Chromium in the browser cache? A directory listing only. */
|
|
156
|
+
export function playwrightBrowsers(env, home) {
|
|
95
157
|
const roots = env.PLAYWRIGHT_BROWSERS_PATH ? [env.PLAYWRIGHT_BROWSERS_PATH]
|
|
96
158
|
: [path.join(home, 'Library/Caches/ms-playwright'), path.join(home, '.cache/ms-playwright')];
|
|
97
159
|
return roots.some(dir => listDir(dir).some(name => name.startsWith('chromium')));
|
|
98
160
|
}
|
|
99
161
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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;
|
|
136
207
|
}
|
|
137
|
-
|
|
208
|
+
channels.push(...(projects.length ? projects : [top]));
|
|
138
209
|
}
|
|
210
|
+
return channels.length ? [...new Set(channels)] : [null];
|
|
139
211
|
}
|
|
140
212
|
|
|
141
|
-
|
|
142
|
-
|
|
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);
|
|
240
|
+
}
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
|
|
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 = [];
|
|
143
337
|
for (const category of categories) {
|
|
144
|
-
|
|
338
|
+
kinds.push(category);
|
|
145
339
|
if (catalog.categories[category].mobile) {
|
|
146
340
|
const ios = isDir(path.join(dir, 'ios')); const android = isDir(path.join(dir, 'android'));
|
|
147
|
-
if (ios || !android)
|
|
148
|
-
if (android || !ios)
|
|
341
|
+
if (ios || !android) kinds.push('ios');
|
|
342
|
+
if (android || !ios) kinds.push('android');
|
|
149
343
|
}
|
|
150
344
|
}
|
|
151
|
-
return [...
|
|
345
|
+
return [...new Set(kinds)].flatMap(kind => catalog.categories[kind].needs.map(role => [kind, role]));
|
|
152
346
|
}
|
|
153
347
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
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 };
|
|
163
378
|
}
|
|
164
379
|
|
|
165
|
-
/**
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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 });
|
|
174
453
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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 } : {}) };
|
|
185
528
|
});
|
|
186
|
-
|
|
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 } : {}) };
|
|
187
547
|
}
|
|
188
548
|
|
|
189
|
-
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})` : ''}`
|
|
190
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' };
|
|
191
552
|
|
|
192
553
|
/** One table and at most one question, decision first. */
|
|
193
554
|
export function renderPlan(plan, changes = null) {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
555
|
+
if (!plan.packages.length) {
|
|
556
|
+
return ['Review loop plan', '', 'No packages found: no workspaces are declared and no project manifest was found below the root.',
|
|
557
|
+
'', 'Which folders hold the apps? Name them with `--packages <dir,dir>` on plan, install and record.'].join('\n');
|
|
558
|
+
}
|
|
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' : ''})`
|
|
197
565
|
: tool.install ? `you: ${tool.install.steps.join('; ')} (${tool.install.size}${tool.install.sudo ? ', needs sudo' : ''})` : '';
|
|
198
|
-
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.`);
|
|
199
579
|
}
|
|
200
580
|
if (changes) lines.push('', `Changed since the recorded Review loop: ${changes.join('; ')}.`);
|
|
201
|
-
const local = missingProjectTools(plan);
|
|
202
|
-
|
|
203
|
-
|
|
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
|
+
}
|
|
204
592
|
return lines.join('\n');
|
|
205
593
|
}
|
|
206
594
|
|
|
595
|
+
/** Per-package project installs. A shared gap is one question, so it adds no per-package install here. */
|
|
207
596
|
export function missingProjectTools(plan) {
|
|
208
597
|
return plan.packages.flatMap(entry => entry.tools.filter(tool => tool.install?.scope === 'project').map(tool => ({ path: entry.path, tool })));
|
|
209
598
|
}
|
|
210
599
|
|
|
211
|
-
/**
|
|
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
|
+
*/
|
|
212
632
|
export function installProjectTools(root, plan, { approved, tools = null, run = (command, args, cwd) => execFileSync(command, args, { cwd, stdio: 'inherit' }) }) {
|
|
213
633
|
if (approved !== true) throw new Error('Install needs the user\'s yes in this conversation');
|
|
214
634
|
const ran = [];
|
|
215
|
-
for (const {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
}
|
|
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);
|
|
219
638
|
return ran;
|
|
220
639
|
}
|
|
221
640
|
|
|
641
|
+
|
|
642
|
+
/** The recorded marker with its version, or null. A v1 marker still reads, so its statuses are kept. */
|
|
222
643
|
function recorded(root) {
|
|
223
644
|
const text = read(path.join(root, 'AGENTS.md'));
|
|
224
645
|
const match = text && marker.exec(text);
|
|
225
|
-
|
|
646
|
+
const data = match && json(match[2]);
|
|
647
|
+
return data ? { ...data, version: Number(match[1]) } : null;
|
|
226
648
|
}
|
|
227
649
|
|
|
228
|
-
|
|
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, {
|
|
229
652
|
categories: entry.categories,
|
|
230
|
-
tools: Object.fromEntries(entry.tools.
|
|
653
|
+
tools: Object.fromEntries(entry.tools.filter(tool => !tool.host).map(tool => [tool.id, tool.status])),
|
|
231
654
|
}]));
|
|
232
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
|
+
|
|
233
664
|
/** Differences between this detection and the recorded Review loop; null when nothing is recorded. */
|
|
234
665
|
export function reviewLoopChanges(root, plan) {
|
|
235
666
|
const before = recorded(root);
|
|
236
667
|
if (!before) return null;
|
|
237
668
|
const now = summary(plan);
|
|
238
|
-
const changes = [];
|
|
669
|
+
const changes = before.version < 2 ? ['recorded with v1; re-record to keep it'] : [];
|
|
239
670
|
for (const [pkg, entry] of Object.entries(now)) {
|
|
240
671
|
const old = before.packages?.[pkg];
|
|
241
672
|
if (!old) { changes.push(`new ${entry.categories.join(', ')} package ${pkg}`); continue; }
|
|
242
|
-
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}`);
|
|
243
674
|
for (const [id, status] of Object.entries(entry.tools)) {
|
|
244
|
-
const was = old.tools[id];
|
|
245
|
-
if (was === undefined) changes.push(`${pkg} needs ${
|
|
246
|
-
else if (was !== status && !(was === 'skipped' && status === 'missing')) changes.push(`${
|
|
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}`);
|
|
247
678
|
}
|
|
248
679
|
}
|
|
249
680
|
for (const pkg of Object.keys(before.packages ?? {})) if (!now[pkg]) changes.push(`package ${pkg} is gone`);
|
|
@@ -252,44 +683,164 @@ export function reviewLoopChanges(root, plan) {
|
|
|
252
683
|
|
|
253
684
|
/** Plan only what changed: an unchanged recorded loop asks nothing. */
|
|
254
685
|
export function planForSetup(root, options) {
|
|
255
|
-
const plan = reviewLoopPlan(root, options);
|
|
686
|
+
const plan = reviewLoopPlan(root, { chosen: recordedChoices(root), ...options });
|
|
256
687
|
const changes = reviewLoopChanges(root, plan);
|
|
257
688
|
return { plan, changes, ask: changes === null || changes.length > 0, text: changes && !changes.length ? 'Review loop unchanged.' : renderPlan(plan, changes) };
|
|
258
689
|
}
|
|
259
690
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
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]));
|
|
269
757
|
}
|
|
270
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 = [] } = {}) {
|
|
785
|
+
if (!plan.packages.length) throw new Error('No packages found, so there is nothing to record; name them with --packages <dir,dir>');
|
|
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 = {};
|
|
793
|
+
for (const entry of plan.packages) {
|
|
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 } : {}) };
|
|
821
|
+
}
|
|
271
822
|
const section = [sectionHeading, '',
|
|
272
|
-
'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.`, '',
|
|
273
825
|
...rows,
|
|
274
|
-
|
|
275
|
-
'', `<!-- joycraft:review-loop v1 ${JSON.stringify({ packages: summary(plan, skipped) })} -->`, ''].join('\n');
|
|
826
|
+
'', `<!-- joycraft:review-loop v2 ${JSON.stringify({ packages })} -->`, ''].join('\n');
|
|
276
827
|
const file = path.join(root, 'AGENTS.md');
|
|
277
828
|
const text = read(file);
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
writeFileSync(file, `${text}${text.endsWith('\n') ? '' : '\n'}\n${section}`);
|
|
282
|
-
|
|
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
|
+
}
|
|
283
839
|
}
|
|
284
|
-
|
|
285
|
-
const next = text.slice(from + sectionHeading.length).search(/\n## /);
|
|
286
|
-
const end = next < 0 ? text.length : from + sectionHeading.length + next + 1;
|
|
287
|
-
writeFileSync(file, `${text.slice(0, from)}${section}${end < text.length ? `\n${text.slice(end)}` : ''}`);
|
|
288
|
-
return { created: false };
|
|
840
|
+
return { created, ...(host ? { local: recordHostTools(root, { host, tools: hostTools }) } : {}) };
|
|
289
841
|
}
|
|
290
842
|
|
|
291
|
-
|
|
292
|
-
export function reviewLoopSection(root) {
|
|
843
|
+
function sharedSection(root) {
|
|
293
844
|
const text = read(path.join(root, 'AGENTS.md'));
|
|
294
845
|
if (!text) return null;
|
|
295
846
|
const start = text.startsWith(`${sectionHeading}\n`) ? 0 : text.indexOf(`\n${sectionHeading}\n`) + 1;
|
|
@@ -298,32 +849,52 @@ export function reviewLoopSection(root) {
|
|
|
298
849
|
return text.slice(start, next < 0 ? undefined : start + sectionHeading.length + next).trim();
|
|
299
850
|
}
|
|
300
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
|
+
|
|
301
860
|
export async function main(argv = process.argv.slice(2)) {
|
|
302
861
|
const [command, ...rest] = argv;
|
|
303
862
|
const flags = {};
|
|
863
|
+
const repeated = new Set(['--choose', '--command', '--can-show', '--skip']);
|
|
304
864
|
for (let index = 0; index < rest.length; index += 1) {
|
|
305
865
|
if (rest[index] === '--yes') { flags['--yes'] = true; continue; }
|
|
306
|
-
flags[rest[index]]
|
|
866
|
+
if (repeated.has(rest[index])) (flags[rest[index]] ??= []).push(rest[index + 1]);
|
|
867
|
+
else flags[rest[index]] = rest[index + 1];
|
|
868
|
+
index += 1;
|
|
307
869
|
}
|
|
308
870
|
const root = path.resolve(flags['--root'] ?? '.');
|
|
309
871
|
const list = value => (value ? value.split(',').filter(Boolean) : []);
|
|
310
|
-
|
|
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] : []));
|
|
874
|
+
const options = { hostTools: list(flags['--host-tools']), packages: flags['--packages'] ? list(flags['--packages']) : null };
|
|
311
875
|
if (command === 'plan') {
|
|
312
876
|
const { text, ask } = planForSetup(root, options);
|
|
313
877
|
process.stdout.write(`${text}\n`);
|
|
314
878
|
return { ask };
|
|
315
879
|
}
|
|
316
880
|
if (command === 'install') {
|
|
317
|
-
const
|
|
318
|
-
|
|
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`);
|
|
319
886
|
return ran;
|
|
320
887
|
}
|
|
321
888
|
if (command === 'record') {
|
|
322
|
-
|
|
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 });
|
|
323
893
|
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
324
894
|
return result;
|
|
325
895
|
}
|
|
326
|
-
throw new Error('Usage: review-tools.mjs plan|install|record --root <project> [--host-tools browser,simulator] [--tools playwright --yes]
|
|
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>]');
|
|
327
898
|
}
|
|
328
899
|
|
|
329
900
|
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|