joycraft 0.7.17 → 1.0.1

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 (109) hide show
  1. package/README.md +148 -140
  2. package/dist/cli.js +1593 -373
  3. package/dist/cli.js.map +1 -1
  4. package/dist/joycraft-release.json +1 -1
  5. package/package.json +9 -3
  6. package/payload/.agents/skills/joycraft-context/SKILL.md +36 -0
  7. package/payload/.agents/skills/joycraft-decompose/SKILL.md +68 -0
  8. package/payload/.agents/skills/joycraft-entry/SKILL.md +109 -0
  9. package/payload/.agents/skills/joycraft-implement/SKILL.md +118 -0
  10. package/payload/.agents/skills/joycraft-retro/SKILL.md +54 -0
  11. package/payload/.agents/skills/joycraft-retro/agents/openai.yaml +5 -0
  12. package/payload/.agents/skills/joycraft-session-end/SKILL.md +82 -0
  13. package/payload/.agents/skills/joycraft-testing/SKILL.md +60 -0
  14. package/payload/.agents/skills/joycraft-ui-slice/SKILL.md +59 -0
  15. package/payload/.agents/skills/joycraft-ui-slice/scripts/serve.mjs +97 -0
  16. package/payload/.agents/skills/joycraft-verify/SKILL.md +103 -0
  17. package/payload/.claude/agents/joycraft-implementer.md +36 -0
  18. package/payload/.claude/agents/joycraft-reviewer.md +35 -0
  19. package/payload/.joycraft/assets/artifacts/kit.css +102 -0
  20. package/payload/.joycraft/assets/artifacts/kit.js +301 -0
  21. package/payload/.joycraft/assets/artifacts/transports.js +236 -0
  22. package/payload/.joycraft/contracts/types.d.ts +185 -0
  23. package/payload/.joycraft/references/architecture.md +90 -0
  24. package/payload/.joycraft/references/archive.md +211 -0
  25. package/payload/.joycraft/references/artifacts.md +176 -0
  26. package/payload/.joycraft/references/completion.md +109 -0
  27. package/payload/.joycraft/references/context.md +85 -0
  28. package/payload/.joycraft/references/delivery.md +32 -0
  29. package/payload/.joycraft/references/dispatch.md +231 -0
  30. package/payload/.joycraft/references/recurring-failures.md +33 -0
  31. package/payload/.joycraft/references/retro.md +94 -0
  32. package/payload/.joycraft/references/setup.md +295 -0
  33. package/payload/.joycraft/references/testing.md +120 -0
  34. package/payload/.joycraft/references/update.md +44 -0
  35. package/payload/.joycraft/references/workflow.md +113 -0
  36. package/payload/.joycraft/references/worktrees.md +174 -0
  37. package/payload/.joycraft/runtime/archive.mjs +463 -0
  38. package/payload/.joycraft/runtime/artifacts/cli.mjs +61 -0
  39. package/payload/.joycraft/runtime/artifacts/decisions.mjs +214 -0
  40. package/payload/.joycraft/runtime/artifacts/model.mjs +161 -0
  41. package/payload/.joycraft/runtime/artifacts/preferences.mjs +127 -0
  42. package/payload/.joycraft/runtime/artifacts/render.mjs +21 -0
  43. package/payload/.joycraft/runtime/artifacts/server.mjs +40 -0
  44. package/payload/.joycraft/runtime/completion.mjs +300 -0
  45. package/payload/.joycraft/runtime/context/cli.mjs +75 -0
  46. package/payload/.joycraft/runtime/context/index.mjs +29 -0
  47. package/payload/.joycraft/runtime/context/search.mjs +149 -0
  48. package/payload/.joycraft/runtime/coordinator.mjs +169 -0
  49. package/payload/.joycraft/runtime/delivery.mjs +142 -0
  50. package/payload/.joycraft/runtime/dispatch-preflight.mjs +535 -0
  51. package/payload/.joycraft/runtime/dispatch-start.mjs +106 -0
  52. package/payload/.joycraft/runtime/evidence.mjs +137 -0
  53. package/payload/.joycraft/runtime/identity.mjs +486 -0
  54. package/payload/.joycraft/runtime/kickoff.mjs +174 -0
  55. package/payload/.joycraft/runtime/redact.mjs +9 -0
  56. package/payload/.joycraft/runtime/retro.mjs +151 -0
  57. package/payload/.joycraft/runtime/review-tools.json +34 -0
  58. package/payload/.joycraft/runtime/review-tools.mjs +331 -0
  59. package/payload/.joycraft/runtime/scope.mjs +129 -0
  60. package/payload/.joycraft/runtime/status.mjs +96 -0
  61. package/payload/.joycraft/runtime/update-check.mjs +142 -0
  62. package/payload/.joycraft/runtime/worktrees.mjs +201 -0
  63. package/payload/.joycraft/templates/README.md +7 -0
  64. package/payload/.joycraft/templates/artifact.json +33 -0
  65. package/payload/.joycraft/templates/brief.md +35 -0
  66. package/payload/.joycraft/templates/decisions.md +13 -0
  67. package/payload/.joycraft/templates/project-context.md +36 -0
  68. package/payload/.joycraft/templates/queue.json +27 -0
  69. package/payload/.joycraft/templates/spec.md +39 -0
  70. package/payload/.joycraft/templates/ui-slice.html +71 -0
  71. package/payload/PIN +77 -0
  72. package/payload/scripts/export.mjs +301 -0
  73. package/payload/scripts/hook-paths.mjs +35 -0
  74. package/payload/scripts/legacy-hooks.mjs +128 -0
  75. package/payload/scripts/legacy-inventory.json +117 -0
  76. package/dist/chunk-35RQLGKM.js +0 -2167
  77. package/dist/chunk-35RQLGKM.js.map +0 -1
  78. package/dist/chunk-7BPB2IKY.js +0 -255
  79. package/dist/chunk-7BPB2IKY.js.map +0 -1
  80. package/dist/chunk-B73DPYYC.js +0 -377
  81. package/dist/chunk-B73DPYYC.js.map +0 -1
  82. package/dist/chunk-K4AI6FKB.js +0 -417
  83. package/dist/chunk-K4AI6FKB.js.map +0 -1
  84. package/dist/chunk-KKDKC4FM.js +0 -115
  85. package/dist/chunk-KKDKC4FM.js.map +0 -1
  86. package/dist/chunk-OMFGDJW4.js +0 -97
  87. package/dist/chunk-OMFGDJW4.js.map +0 -1
  88. package/dist/chunk-YLWBDXF4.js +0 -3999
  89. package/dist/chunk-YLWBDXF4.js.map +0 -1
  90. package/dist/chunk-Z5JFEGWG.js +0 -563
  91. package/dist/chunk-Z5JFEGWG.js.map +0 -1
  92. package/dist/init-O2QC5X57.js +0 -60
  93. package/dist/init-O2QC5X57.js.map +0 -1
  94. package/dist/init-autofix-2DMBO4QN.js +0 -122
  95. package/dist/init-autofix-2DMBO4QN.js.map +0 -1
  96. package/dist/install-manifest-EQHT4474.js +0 -37
  97. package/dist/install-manifest-EQHT4474.js.map +0 -1
  98. package/dist/release-artifact-4TL5L2ZY.js +0 -14
  99. package/dist/release-artifact-4TL5L2ZY.js.map +0 -1
  100. package/dist/release-resolver-P2H46QTU.js +0 -293
  101. package/dist/release-resolver-P2H46QTU.js.map +0 -1
  102. package/dist/telemetry-store-IBO5GRTA.js +0 -14
  103. package/dist/telemetry-store-IBO5GRTA.js.map +0 -1
  104. package/dist/update-LYHS4FBH.js +0 -21
  105. package/dist/update-LYHS4FBH.js.map +0 -1
  106. package/dist/update-check-YT765NE7.js +0 -36
  107. package/dist/update-check-YT765NE7.js.map +0 -1
  108. package/dist/upgrade-GMP6JQ52.js +0 -28
  109. package/dist/upgrade-GMP6JQ52.js.map +0 -1
@@ -0,0 +1,331 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, lstatSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+
7
+ // One catalog for detection, the setup plan and the public docs.
8
+ export const catalog = JSON.parse(readFileSync(new URL('./review-tools.json', import.meta.url), 'utf8'));
9
+ const sectionHeading = '## Review loop';
10
+ const marker = /<!-- joycraft:review-loop v1 (\{.*\}) -->/;
11
+ const webDeps = ['next', 'vite', 'react-dom', 'vue', 'svelte', '@sveltejs/kit', 'astro', 'nuxt', '@remix-run/react', 'solid-js', '@angular/core', 'gatsby'];
12
+ const apiDeps = ['express', 'fastify', 'koa', 'hono', '@nestjs/core', '@hapi/hapi'];
13
+ const devServer = /\b(vite|next dev|nuxt dev|astro dev|webpack serve|react-scripts start|ng serve)\b/;
14
+
15
+ const read = file => { try { return readFileSync(file, 'utf8'); } catch { return null; } };
16
+ const isDir = dir => { try { return lstatSync(dir).isDirectory(); } catch { return false; } };
17
+ const json = text => { try { return JSON.parse(text); } catch { return null; } };
18
+ const listDir = dir => { try { return readdirSync(dir); } catch { return []; } };
19
+
20
+ function workspaceDirs(root) {
21
+ const manifest = json(read(path.join(root, 'package.json')));
22
+ const globs = [...(Array.isArray(manifest?.workspaces) ? manifest.workspaces : manifest?.workspaces?.packages ?? [])];
23
+ const pnpm = read(path.join(root, 'pnpm-workspace.yaml'));
24
+ // Only the top-level `packages:` list; other keys hold unrelated lists.
25
+ const block = pnpm && /^packages:\s*\n((?:[ \t]+.*\n?|[ \t]*\n)*)/m.exec(pnpm);
26
+ if (block) for (const match of block[1].matchAll(/^\s*-\s*['"]?([^'"\n#]+?)['"]?\s*$/gm)) globs.push(match[1]);
27
+ const dirs = [];
28
+ for (const glob of globs.filter(item => !item.startsWith('!') && !['.', './'].includes(item))) {
29
+ if (glob.endsWith('/*')) {
30
+ const parent = glob.slice(0, -2);
31
+ for (const name of listDir(path.join(root, parent)).sort()) if (isDir(path.join(root, parent, name))) dirs.push(path.posix.join(parent, name));
32
+ } else if (!glob.includes('*') && isDir(path.join(root, glob))) dirs.push(glob);
33
+ }
34
+ return [...new Set(dirs)];
35
+ }
36
+
37
+ /** Categories for one package directory, from its manifests and project files only. */
38
+ export function classifyPackage(dir) {
39
+ const found = new Set();
40
+ const manifest = json(read(path.join(dir, 'package.json')));
41
+ const deps = { ...manifest?.dependencies, ...manifest?.devDependencies };
42
+ const has = name => Object.hasOwn(deps, name);
43
+ if (has('expo')) found.add('expo');
44
+ else if (has('react-native')) found.add('react-native');
45
+ if (has('electron')) found.add('electron');
46
+ if (!found.has('expo') && !found.has('react-native') && !found.has('electron')
47
+ && (webDeps.some(has) || Object.values(manifest?.scripts ?? {}).some(script => devServer.test(String(script))))) found.add('web');
48
+ if (apiDeps.some(has)) found.add('api');
49
+ const pubspec = read(path.join(dir, 'pubspec.yaml'));
50
+ if (pubspec && /^\s*flutter\s*:/m.test(pubspec)) found.add('flutter');
51
+ const names = listDir(dir);
52
+ const swift = read(path.join(dir, 'Package.swift'));
53
+ if (!found.has('flutter') && !found.has('react-native') && !found.has('expo')
54
+ && (names.some(name => /\.(xcodeproj|xcworkspace)$/.test(name)) || (swift && /\.(iOS|macOS)\s*\(/.test(swift)))) found.add('ios');
55
+ const gradle = ['build.gradle', 'build.gradle.kts', 'app/build.gradle', 'app/build.gradle.kts'].map(file => read(path.join(dir, file))).filter(Boolean).join('\n');
56
+ if (!found.has('flutter') && !found.has('react-native') && !found.has('expo') && /com\.android\./.test(gradle)) found.add('android');
57
+ const python = ['pyproject.toml', 'requirements.txt', 'setup.py'].map(file => read(path.join(dir, file))).filter(Boolean).join('\n');
58
+ if (/\b(fastapi|flask|django|starlette)\b/i.test(python)) found.add('api');
59
+ const cargo = read(path.join(dir, 'Cargo.toml')) ?? '';
60
+ if (/^\s*(axum|actix-web|rocket|warp)\s*=/m.test(cargo)) found.add('api');
61
+ const go = read(path.join(dir, 'go.mod')) ?? '';
62
+ if (/(gin-gonic\/gin|labstack\/echo|gofiber\/fiber|go-chi\/chi)/.test(go)) found.add('api');
63
+ const anyManifest = manifest || python || cargo || go || swift || pubspec || gradle;
64
+ if (!found.size && anyManifest) found.add('cli-library');
65
+ return [...found];
66
+ }
67
+
68
+ /** Each package of a project with its categories. A workspace root without its own app is not a package. */
69
+ export function detectProjects(root) {
70
+ const packages = workspaceDirs(root).map(dir => ({ path: dir, categories: classifyPackage(path.join(root, dir)) }))
71
+ .filter(entry => entry.categories.length);
72
+ const own = classifyPackage(root);
73
+ const workspaceOnly = packages.length && own.every(category => category === 'cli-library');
74
+ return [...(workspaceOnly || !own.length ? [] : [{ path: '.', categories: own }]), ...packages];
75
+ }
76
+
77
+ export function packageManager(dir, root = dir) {
78
+ for (const base of [dir, root]) {
79
+ if (existsSync(path.join(base, 'pnpm-lock.yaml'))) return { name: 'pnpm', add: ['pnpm', 'add', '-D'], exec: ['pnpm', 'exec'] };
80
+ if (existsSync(path.join(base, 'yarn.lock'))) return { name: 'yarn', add: ['yarn', 'add', '-D'], exec: ['yarn'] };
81
+ if (existsSync(path.join(base, 'bun.lockb')) || existsSync(path.join(base, 'bun.lock'))) return { name: 'bun', add: ['bun', 'add', '-d'], exec: ['bunx'] };
82
+ }
83
+ return { name: 'npm', add: ['npm', 'install', '-D'], exec: ['npx'] };
84
+ }
85
+
86
+ /** Read-only probe: run a version or list command with no shell. Never installs. */
87
+ export function defaultRun(command, args) {
88
+ try { return { ok: true, stdout: execFileSync(command, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10000 }) }; }
89
+ catch { return { ok: false, stdout: '' }; }
90
+ }
91
+
92
+ const firstVersion = text => /\d+(?:\.\d+)+/.exec(text)?.[0] ?? null;
93
+
94
+ function playwrightBrowsers(env, home) {
95
+ const roots = env.PLAYWRIGHT_BROWSERS_PATH ? [env.PLAYWRIGHT_BROWSERS_PATH]
96
+ : [path.join(home, 'Library/Caches/ms-playwright'), path.join(home, '.cache/ms-playwright')];
97
+ return roots.some(dir => listDir(dir).some(name => name.startsWith('chromium')));
98
+ }
99
+
100
+ function probe(id, { dir, root, run, env, home }) {
101
+ const manifest = json(read(path.join(dir, 'package.json')));
102
+ const deps = { ...manifest?.dependencies, ...manifest?.devDependencies };
103
+ switch (id) {
104
+ case 'playwright': {
105
+ if (deps.cypress) return { status: 'present', version: String(deps.cypress), via: 'Cypress (already in the project)' };
106
+ const names = ['@playwright/test', 'playwright'];
107
+ const installed = names.flatMap(name => [dir, root].map(base => json(read(path.join(base, 'node_modules', name, 'package.json'))))).find(Boolean);
108
+ const declared = names.map(name => deps[name]).find(Boolean);
109
+ if (!declared && !installed) return { status: 'missing' };
110
+ if (!playwrightBrowsers(env, home)) return { status: 'missing', version: installed?.version ?? null, note: 'browser not downloaded' };
111
+ return { status: 'present', version: installed?.version ?? String(declared) };
112
+ }
113
+ case 'xcode': { const out = run('xcodebuild', ['-version']); return out.ok ? { status: 'present', version: firstVersion(out.stdout) } : { status: 'missing' }; }
114
+ case 'ios-simulator': {
115
+ const out = run('xcrun', ['simctl', 'list', 'runtimes']);
116
+ const line = out.ok ? out.stdout.split('\n').find(row => /^iOS \d/.test(row.trim())) : null;
117
+ return line ? { status: 'present', version: firstVersion(line) } : { status: 'missing' };
118
+ }
119
+ case 'android-sdk': { const out = run('adb', ['version']); return out.ok ? { status: 'present', version: firstVersion(out.stdout) } : { status: 'missing' }; }
120
+ case 'android-emulator': {
121
+ const out = run('emulator', ['-list-avds']);
122
+ return out.ok && out.stdout.trim() ? { status: 'present', version: null, note: out.stdout.trim().split('\n')[0] } : { status: 'missing' };
123
+ }
124
+ case 'flutter': { const out = run('flutter', ['--version']); return out.ok ? { status: 'present', version: firstVersion(out.stdout) } : { status: 'missing' }; }
125
+ case 'react-native-cli': case 'expo-cli': {
126
+ const name = catalog.tools[id].package;
127
+ return deps[name] ? { status: 'present', version: String(deps[name]) } : { status: 'missing' };
128
+ }
129
+ case 'curl': { const out = run('curl', ['--version']); return out.ok ? { status: 'present', version: firstVersion(out.stdout) } : { status: 'missing' }; }
130
+ case 'test-runner': {
131
+ const declared = manifest?.scripts?.test ? `${packageManager(dir, root).name} test`
132
+ : existsSync(path.join(dir, 'Cargo.toml')) ? 'cargo test'
133
+ : existsSync(path.join(dir, 'go.mod')) ? 'go test ./...'
134
+ : ['pyproject.toml', 'requirements.txt', 'setup.py'].some(file => existsSync(path.join(dir, file))) ? 'python3 -m pytest' : null;
135
+ return declared ? { status: 'present', version: null, note: `${declared} (declared, unrun)` } : { status: 'missing', note: 'no test command declared' };
136
+ }
137
+ default: return { status: 'not-needed' };
138
+ }
139
+ }
140
+
141
+ function toolsFor(categories, dir) {
142
+ const ids = new Set();
143
+ for (const category of categories) {
144
+ for (const id of catalog.categories[category].tools) ids.add(id);
145
+ if (catalog.categories[category].mobile) {
146
+ const ios = isDir(path.join(dir, 'ios')); const android = isDir(path.join(dir, 'android'));
147
+ if (ios || !android) for (const id of catalog.categories.ios.tools) ids.add(id);
148
+ if (android || !ios) for (const id of catalog.categories.android.tools) ids.add(id);
149
+ }
150
+ }
151
+ return [...ids];
152
+ }
153
+
154
+ function startCommand(dir, root, categories) {
155
+ const scripts = json(read(path.join(dir, 'package.json')))?.scripts ?? {};
156
+ const pm = packageManager(dir, root).name;
157
+ const script = ['dev', 'start', 'ios', 'android'].find(name => scripts[name]);
158
+ if (script) return `${pm} run ${script} (package.json, unrun)`;
159
+ if (categories.includes('android')) return './gradlew installDebug (unrun)';
160
+ if (categories.includes('ios')) return 'xcodebuild build (scheme not established)';
161
+ if (categories.includes('flutter')) return 'flutter run (unrun)';
162
+ return 'not established';
163
+ }
164
+
165
+ /** The Review loop plan: each package, each tool it needs, and that tool's status. Probes only. */
166
+ export function reviewLoopPlan(root, { run = defaultRun, hostTools = [], env = process.env, home = homedir() } = {}) {
167
+ const packages = detectProjects(root).map(entry => {
168
+ const dir = path.join(root, entry.path);
169
+ const tools = toolsFor(entry.categories, dir).map(id => {
170
+ const spec = catalog.tools[id];
171
+ let result = probe(id, { dir, root, run, env, home });
172
+ if (result.status === 'missing' && spec.hostAlternative && hostTools.includes(spec.hostAlternative)) {
173
+ result = { status: 'present', version: null, via: `the host's built-in ${spec.hostAlternative}` };
174
+ }
175
+ const pm = packageManager(dir, root);
176
+ const install = result.status !== 'missing' ? null : spec.scope === 'project' && id === 'playwright'
177
+ ? { scope: 'project', commands: [[...pm.add, '@playwright/test'], [...pm.exec, 'playwright', 'install', 'chromium']], size: spec.size, sudo: false }
178
+ : spec.scope === 'project' && spec.package ? { scope: 'project', commands: [[...pm.add, spec.package]], size: spec.size, sudo: false }
179
+ : spec.scope === 'project' ? { scope: 'user', steps: ['Declare a test command for this package'], size: spec.size, sudo: false }
180
+ : { scope: 'user', steps: spec.steps, size: spec.size, sudo: spec.sudo };
181
+ return { id, label: spec.label, ...result, ...(install ? { install } : {}),
182
+ evidence: spec.evidence ? spec.evidence.replace('{exec}', pm.exec.join(' ')) : null };
183
+ });
184
+ return { path: entry.path, categories: entry.categories, start: startCommand(dir, root, entry.categories), tools };
185
+ });
186
+ return { schemaVersion: 1, packages };
187
+ }
188
+
189
+ const statusText = tool => tool.status === 'present' ? `present${tool.version ? ` ${tool.version}` : ''}${tool.via ? ` (${tool.via})` : ''}`
190
+ : tool.status === 'skipped' ? 'skipped' : `missing${tool.note ? ` (${tool.note})` : ''}`;
191
+
192
+ /** One table and at most one question, decision first. */
193
+ export function renderPlan(plan, changes = null) {
194
+ const lines = ['Review loop plan', '', '| Package | Kind | Tool | Status | To install |', '|---|---|---|---|---|'];
195
+ for (const entry of plan.packages) for (const tool of entry.tools) {
196
+ const install = tool.install?.commands ? `\`${tool.install.commands.map(command => command.join(' ')).join(' && ')}\` (${tool.install.size})`
197
+ : 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} |`);
199
+ }
200
+ if (changes) lines.push('', `Changed since the recorded Review loop: ${changes.join('; ')}.`);
201
+ const local = missingProjectTools(plan);
202
+ 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?`);
203
+ 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.');
204
+ return lines.join('\n');
205
+ }
206
+
207
+ export function missingProjectTools(plan) {
208
+ return plan.packages.flatMap(entry => entry.tools.filter(tool => tool.install?.scope === 'project').map(tool => ({ path: entry.path, tool })));
209
+ }
210
+
211
+ /** Run project-local installs the user approved. System tools are never installed here. */
212
+ export function installProjectTools(root, plan, { approved, tools = null, run = (command, args, cwd) => execFileSync(command, args, { cwd, stdio: 'inherit' }) }) {
213
+ if (approved !== true) throw new Error('Install needs the user\'s yes in this conversation');
214
+ const ran = [];
215
+ for (const { path: dir, tool } of missingProjectTools(plan)) {
216
+ if (tools && !tools.includes(tool.id)) continue;
217
+ for (const [command, ...args] of tool.install.commands) { run(command, args, path.join(root, dir)); ran.push([command, ...args].join(' ')); }
218
+ }
219
+ return ran;
220
+ }
221
+
222
+ function recorded(root) {
223
+ const text = read(path.join(root, 'AGENTS.md'));
224
+ const match = text && marker.exec(text);
225
+ return match ? json(match[1]) : null;
226
+ }
227
+
228
+ const summary = (plan, skipped = []) => Object.fromEntries(plan.packages.map(entry => [entry.path, {
229
+ categories: entry.categories,
230
+ tools: Object.fromEntries(entry.tools.map(tool => [tool.id, skipped.includes(tool.id) && tool.status === 'missing' ? 'skipped' : tool.status])),
231
+ }]));
232
+
233
+ /** Differences between this detection and the recorded Review loop; null when nothing is recorded. */
234
+ export function reviewLoopChanges(root, plan) {
235
+ const before = recorded(root);
236
+ if (!before) return null;
237
+ const now = summary(plan);
238
+ const changes = [];
239
+ for (const [pkg, entry] of Object.entries(now)) {
240
+ const old = before.packages?.[pkg];
241
+ 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}`);
243
+ for (const [id, status] of Object.entries(entry.tools)) {
244
+ const was = old.tools[id];
245
+ if (was === undefined) changes.push(`${pkg} needs ${catalog.tools[id].label}`);
246
+ else if (was !== status && !(was === 'skipped' && status === 'missing')) changes.push(`${catalog.tools[id].label} in ${pkg}: ${was} -> ${status}`);
247
+ }
248
+ }
249
+ for (const pkg of Object.keys(before.packages ?? {})) if (!now[pkg]) changes.push(`package ${pkg} is gone`);
250
+ return changes;
251
+ }
252
+
253
+ /** Plan only what changed: an unchanged recorded loop asks nothing. */
254
+ export function planForSetup(root, options) {
255
+ const plan = reviewLoopPlan(root, options);
256
+ const changes = reviewLoopChanges(root, plan);
257
+ return { plan, changes, ask: changes === null || changes.length > 0, text: changes && !changes.length ? 'Review loop unchanged.' : renderPlan(plan, changes) };
258
+ }
259
+
260
+ /** Write the chosen setup to AGENTS.md under `## Review loop`, replacing only that section. */
261
+ export function recordReviewLoop(root, plan, { skipped = [] } = {}) {
262
+ const rows = ['| Package | Tool | Start the app | Take the evidence |', '|---|---|---|---|'];
263
+ const unverified = [];
264
+ for (const entry of plan.packages) {
265
+ for (const tool of entry.tools) {
266
+ const skip = skipped.includes(tool.id) && tool.status === 'missing';
267
+ if ((skip || tool.status === 'missing') && entry.categories.some(category => catalog.categories[category].ui)) unverified.push(entry.path);
268
+ rows.push(`| ${entry.path} | ${tool.label}: ${skip ? 'skipped' : statusText(tool)} | ${entry.start} | ${tool.evidence ?? (tool.note ?? 'not applicable')} |`);
269
+ }
270
+ }
271
+ const section = [sectionHeading, '',
272
+ 'Recorded by Joycraft setup. The implementer, reviewer and UI checks use these tools and commands.', '',
273
+ ...rows,
274
+ ...([...new Set(unverified)].length ? ['', `UI claims in ${[...new Set(unverified)].join(', ')} stay UNVERIFIED in review reports until the missing tools are set up.`] : []),
275
+ '', `<!-- joycraft:review-loop v1 ${JSON.stringify({ packages: summary(plan, skipped) })} -->`, ''].join('\n');
276
+ const file = path.join(root, 'AGENTS.md');
277
+ const text = read(file);
278
+ if (text === null) { writeFileSync(file, `${section}`); return { created: true }; }
279
+ const start = text.indexOf(`\n${sectionHeading}\n`);
280
+ if (start < 0 && !text.startsWith(`${sectionHeading}\n`)) {
281
+ writeFileSync(file, `${text}${text.endsWith('\n') ? '' : '\n'}\n${section}`);
282
+ return { created: false };
283
+ }
284
+ const from = text.startsWith(`${sectionHeading}\n`) ? 0 : start + 1;
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 };
289
+ }
290
+
291
+ /** The recorded section text, for worker and reviewer packets. */
292
+ export function reviewLoopSection(root) {
293
+ const text = read(path.join(root, 'AGENTS.md'));
294
+ if (!text) return null;
295
+ const start = text.startsWith(`${sectionHeading}\n`) ? 0 : text.indexOf(`\n${sectionHeading}\n`) + 1;
296
+ if (start === 0 && !text.startsWith(`${sectionHeading}\n`)) return null;
297
+ const next = text.slice(start + sectionHeading.length).search(/\n## /);
298
+ return text.slice(start, next < 0 ? undefined : start + sectionHeading.length + next).trim();
299
+ }
300
+
301
+ export async function main(argv = process.argv.slice(2)) {
302
+ const [command, ...rest] = argv;
303
+ const flags = {};
304
+ for (let index = 0; index < rest.length; index += 1) {
305
+ if (rest[index] === '--yes') { flags['--yes'] = true; continue; }
306
+ flags[rest[index]] = rest[index + 1]; index += 1;
307
+ }
308
+ const root = path.resolve(flags['--root'] ?? '.');
309
+ const list = value => (value ? value.split(',').filter(Boolean) : []);
310
+ const options = { hostTools: list(flags['--host-tools']) };
311
+ if (command === 'plan') {
312
+ const { text, ask } = planForSetup(root, options);
313
+ process.stdout.write(`${text}\n`);
314
+ return { ask };
315
+ }
316
+ if (command === 'install') {
317
+ const ran = installProjectTools(root, reviewLoopPlan(root, options), { approved: flags['--yes'] === true, tools: flags['--tools'] ? list(flags['--tools']) : null });
318
+ process.stdout.write(`${JSON.stringify({ ran }, null, 2)}\n`);
319
+ return ran;
320
+ }
321
+ if (command === 'record') {
322
+ const result = recordReviewLoop(root, reviewLoopPlan(root, options), { skipped: list(flags['--skip']) });
323
+ process.stdout.write(`${JSON.stringify(result)}\n`);
324
+ return result;
325
+ }
326
+ throw new Error('Usage: review-tools.mjs plan|install|record --root <project> [--host-tools browser,simulator] [--tools playwright --yes] [--skip playwright]');
327
+ }
328
+
329
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
330
+ main().catch(error => { process.stderr.write(`Review tools stopped: ${error.message}\n`); process.exitCode = 1; });
331
+ }
@@ -0,0 +1,129 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const fullCommit = value => typeof value === 'string' && /^[a-f0-9]{40}$/.test(value);
6
+
7
+ function required(condition, message) {
8
+ if (!condition) throw new Error(message);
9
+ }
10
+
11
+ function git(root, args) {
12
+ try {
13
+ return execFileSync('git', args, { cwd: root, encoding: 'buffer', stdio: ['ignore', 'pipe', 'pipe'] });
14
+ } catch (error) {
15
+ const detail = error.stderr?.toString('utf8').trim();
16
+ throw new Error(`Git scope check failed${detail ? `: ${detail}` : ''}`);
17
+ }
18
+ }
19
+
20
+ function nulFields(bytes) {
21
+ const values = bytes.toString('utf8').split('\0');
22
+ values.pop();
23
+ return values;
24
+ }
25
+
26
+ /** Parse Git's NUL-delimited --name-status format without losing unusual names. */
27
+ function nameStatus(bytes, stage) {
28
+ const values = nulFields(bytes);
29
+ const result = [];
30
+ for (let index = 0; index < values.length;) {
31
+ const raw = values[index++];
32
+ required(raw, 'Git emitted an empty name-status record');
33
+ const status = raw[0];
34
+ required('ACDMRTUXB'.includes(status), `Unsupported Git change status: ${raw}`);
35
+ if (status === 'R' || status === 'C') {
36
+ const beforePath = values[index++];
37
+ const path = values[index++];
38
+ required(beforePath !== undefined && path !== undefined, `Incomplete Git ${status} record`);
39
+ result.push({ path, beforePath, status, stage });
40
+ } else {
41
+ const path = values[index++];
42
+ required(path !== undefined, `Incomplete Git ${status} record`);
43
+ result.push({ path, status, stage });
44
+ }
45
+ }
46
+ return result;
47
+ }
48
+
49
+ function trackedChanges(root, baseRevision) {
50
+ // The first view establishes actual base-to-worktree changes. The other two
51
+ // retain index/worktree state for review without parsing line-delimited Git.
52
+ const actual = nameStatus(git(root, ['diff', '--name-status', '-z', '--find-renames', baseRevision, '--']), 'actual');
53
+ // Index/worktree state is relative to HEAD, not the captured base. Comparing
54
+ // --cached to the base would mislabel ordinary committed base-to-HEAD work as
55
+ // staged when the review starts from an older explicit implementation base.
56
+ const staged = nameStatus(git(root, ['diff', '--cached', '--name-status', '-z', '--find-renames', 'HEAD', '--']), 'staged');
57
+ const unstaged = nameStatus(git(root, ['diff', '--name-status', '-z', '--find-renames', '--']), 'unstaged');
58
+ const markers = new Map();
59
+ for (const record of [...staged, ...unstaged]) {
60
+ for (const name of [record.path, record.beforePath].filter(Boolean)) {
61
+ const current = markers.get(name) ?? new Set();
62
+ current.add(record.stage);
63
+ markers.set(name, current);
64
+ }
65
+ }
66
+ return actual.map(record => {
67
+ const stages = [...new Set([...(markers.get(record.path) ?? []), ...(markers.get(record.beforePath) ?? [])])].sort();
68
+ return { ...record, stages: stages.length === 0 ? ['committed'] : stages };
69
+ });
70
+ }
71
+
72
+ function untrackedChanges(root) {
73
+ return nulFields(git(root, ['ls-files', '--others', '--exclude-standard', '-z'])).map(path => ({ path, status: 'U', stages: ['untracked'] }));
74
+ }
75
+
76
+ export function validateChangeScope(value, relativePath) {
77
+ required(value !== null && typeof value === 'object' && !Array.isArray(value), 'verification.changeScope must be an object');
78
+ required(Object.keys(value).every(key => key === 'baseRevision' || key === 'exclusions'), 'verification.changeScope has an unknown field');
79
+ required(fullCommit(value.baseRevision), 'verification.changeScope.baseRevision must be an explicit full 40-character Git commit SHA; origin/main and inferred bases are not accepted');
80
+ const exclusions = value.exclusions ?? [];
81
+ required(Array.isArray(exclusions), 'verification.changeScope.exclusions must be an array when supplied');
82
+ const names = new Set();
83
+ for (const [index, entry] of exclusions.entries()) {
84
+ required(entry !== null && typeof entry === 'object' && !Array.isArray(entry), `verification.changeScope.exclusions[${index}] must be an object`);
85
+ required(Object.keys(entry).every(key => key === 'path' || key === 'reason'), `verification.changeScope.exclusions[${index}] has an unknown field`);
86
+ const file = relativePath(entry.path);
87
+ required(!names.has(file), `verification.changeScope has duplicate exclusion: ${file}`);
88
+ names.add(file);
89
+ required(typeof entry.reason === 'string' && entry.reason.trim().length > 0, `verification.changeScope.exclusions[${index}].reason must be nonempty`);
90
+ }
91
+ return { baseRevision: value.baseRevision, ...(exclusions.length === 0 ? {} : { exclusions: exclusions.map(entry => ({ path: relativePath(entry.path), reason: entry.reason })) }) };
92
+ }
93
+
94
+ export function captureChangeScope({ root = process.cwd(), changeScope, relativePath, inputs, artifactPaths = [], topologyIgnoredPaths = [] }) {
95
+ const declared = validateChangeScope(changeScope, relativePath);
96
+ try { required(git(root, ['cat-file', '-e', `${declared.baseRevision}^{commit}`]).length === 0, ''); } catch { throw new Error(`verification.changeScope.baseRevision is not an available commit: ${declared.baseRevision}`); }
97
+ const actual = [...trackedChanges(root, declared.baseRevision), ...untrackedChanges(root)];
98
+ const inputsByPath = new Map(inputs.map(input => [relativePath(input.path), input.state ?? 'present']));
99
+ const exclusions = new Set([...(declared.exclusions ?? []).map(entry => entry.path), ...artifactPaths.map(relativePath)]);
100
+ const ignored = new Set(topologyIgnoredPaths.map(relativePath));
101
+ const relevant = [];
102
+ for (const item of actual) {
103
+ const targetState = inputsByPath.get(item.path);
104
+ const previousState = item.beforePath === undefined ? undefined : inputsByPath.get(item.beforePath);
105
+ const relevantInput = targetState !== undefined || previousState !== undefined;
106
+ if (relevantInput) {
107
+ // Queue/spec status and completion metadata have their own normalized
108
+ // input binding. Excluding their Git topology avoids staling a report
109
+ // merely because complete() writes those two status surfaces.
110
+ if (ignored.has(item.path) || (item.beforePath !== undefined && ignored.has(item.beforePath))) continue;
111
+ if (item.status === 'D') {
112
+ required(targetState === 'absent', `Relevant verification input was deleted: ${item.path}; declare it with state: absent or take a fresh review`);
113
+ relevant.push({ path: item.path, status: item.status, stages: item.stages, state: 'deleted' });
114
+ } else if (item.beforePath !== undefined) {
115
+ required(targetState === 'present' && previousState === 'absent' && existsSync(path.join(root, item.path)), `Relevant verification input was renamed from ${item.beforePath} to ${item.path}; bind the new path and declare the old non-requirement input state: absent`);
116
+ relevant.push({ path: item.path, beforePath: item.beforePath, status: item.status, stages: item.stages, state: 'present' });
117
+ } else {
118
+ required(targetState === 'present' && existsSync(path.join(root, item.path)), `Relevant verification input is absent: ${item.path}; only an explicitly absent non-requirement input may be deleted`);
119
+ relevant.push({ path: item.path, status: item.status, stages: item.stages, state: 'present' });
120
+ }
121
+ } else {
122
+ required(exclusions.has(item.path), `Changed path is outside verification inputs: ${item.path}; add it to verification.changeScope.exclusions with a reason or include it as a verification input`);
123
+ }
124
+ }
125
+ return { baseRevision: declared.baseRevision, paths: relevant };
126
+ }
127
+
128
+ /** Dispatcher-facing name: validates and captures the current Git topology. */
129
+ export const checkScope = captureChangeScope;
@@ -0,0 +1,96 @@
1
+ import { existsSync, readdirSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { journalPath } from './completion.mjs';
5
+ import { briefDecisionRecords, isObject, localPath, parseJson, readLocal, specStatus, validateQueue } from './identity.mjs';
6
+ import { listWorktrees } from './worktrees.mjs';
7
+
8
+ // The queue is the status authority; spec frontmatter mirrors it. This report
9
+ // shows where the mirror or the working folders have drifted, so a session can
10
+ // close them before they read as current knowledge.
11
+ const featuresHome = 'docs/features';
12
+ const queueName = 'specs/.joycraft-spec-queue.json';
13
+
14
+ function queuePaths(root) {
15
+ const home = path.join(root, featuresHome);
16
+ if (!existsSync(home)) return [];
17
+ return readdirSync(home, { withFileTypes: true })
18
+ .filter(entry => entry.isDirectory() && existsSync(path.join(home, entry.name, queueName)))
19
+ .map(entry => `${featuresHome}/${entry.name}/${queueName}`).sort();
20
+ }
21
+
22
+ const accepted = spec => spec.status === 'done' && (isObject(spec.acceptedReport) || isObject(spec.ownerAcceptance));
23
+
24
+ function openDecisions(root, folder) {
25
+ const brief = `${folder}/brief.md`;
26
+ if (!existsSync(localPath(root, brief, true))) return [];
27
+ try { return briefDecisionRecords(readLocal(root, brief), brief).filter(record => isObject(record) && record.status === 'open').map(record => record.id); }
28
+ catch { return []; }
29
+ }
30
+
31
+ function worktreeCounts(root) {
32
+ try {
33
+ const { trees } = listWorktrees({ root, sizes: false });
34
+ return {
35
+ owned: trees.filter(tree => tree.owner === 'joycraft' && !tree.missing).length,
36
+ prunable: trees.filter(tree => tree.owner === 'joycraft' && !tree.missing && tree.specStatus === 'done' && tree.clean && tree.merged).length,
37
+ unknown: trees.filter(tree => tree.owner !== 'joycraft').length,
38
+ };
39
+ } catch { return null; }
40
+ }
41
+
42
+ /** Report every queue's specs, drift between queue and frontmatter, and features ready to archive. */
43
+ export function projectStatus({ root = process.cwd(), fix = false } = {}) {
44
+ const features = [];
45
+ const drift = [];
46
+ const fixed = [];
47
+ const readyToArchive = [];
48
+ const problems = [];
49
+ for (const queuePath of queuePaths(root)) {
50
+ const folder = path.posix.dirname(path.posix.dirname(queuePath));
51
+ let queue;
52
+ try { queue = parseJson(readLocal(root, queuePath), queuePath); validateQueue(queue, { select: () => false }); }
53
+ catch (error) { problems.push({ queuePath, problem: error.message }); continue; }
54
+ const pendingJournal = existsSync(localPath(root, journalPath(queuePath), true));
55
+ const specs = queue.specs.map(spec => {
56
+ const specPath = path.posix.join(path.posix.dirname(queuePath), spec.file);
57
+ let frontmatter = null;
58
+ let mirror = null;
59
+ try { mirror = specStatus(readLocal(root, specPath)); frontmatter = mirror.status; }
60
+ catch (error) { problems.push({ specPath, problem: error.message }); }
61
+ const row = { id: spec.id, file: specPath, queue: spec.status, frontmatter };
62
+ if (frontmatter !== null && frontmatter !== spec.status) {
63
+ const fixable = accepted(spec) && !pendingJournal;
64
+ const reason = pendingJournal ? `A completion journal is pending; run node .joycraft/runtime/completion.mjs recover --queue ${queuePath}`
65
+ : fixable ? 'The queue records an accepted completion; the frontmatter lags.'
66
+ : 'Only an accepted done spec is repaired automatically; reconcile this one by hand.';
67
+ if (fix && fixable) {
68
+ writeFileSync(localPath(root, specPath), mirror.replace(spec.status));
69
+ fixed.push({ feature: queue.feature, specId: spec.id, file: specPath, from: frontmatter, to: spec.status });
70
+ row.frontmatter = spec.status;
71
+ } else drift.push({ feature: queue.feature, specId: spec.id, file: specPath, queue: spec.status, frontmatter, fixable, reason });
72
+ }
73
+ return row;
74
+ });
75
+ features.push({ feature: queue.feature, queuePath, pendingJournal, specs });
76
+ if (queue.specs.every(spec => spec.status === 'done')) readyToArchive.push({ feature: queue.feature, folder, openDecisions: openDecisions(root, folder) });
77
+ }
78
+ return { features, drift, fixed, readyToArchive, worktrees: worktreeCounts(root), problems };
79
+ }
80
+
81
+ export async function main(argv = process.argv.slice(2)) {
82
+ const flags = {};
83
+ for (let index = 0; index < argv.length; index += 1) {
84
+ if (argv[index] === '--fix') { flags['--fix'] = true; continue; }
85
+ if (argv[index] === '--root') { flags['--root'] = argv[index + 1]; index += 1; continue; }
86
+ throw new Error('Usage: status.mjs [--root <project>] [--fix]');
87
+ }
88
+ const result = projectStatus({ root: path.resolve(flags['--root'] ?? '.'), fix: flags['--fix'] === true });
89
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
90
+ if (result.drift.length || result.problems.length) process.exitCode = 2;
91
+ return result;
92
+ }
93
+
94
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
95
+ main().catch(error => { process.stderr.write(`Status stopped: ${error.message}\n`); process.exitCode = 1; });
96
+ }