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,142 @@
1
+ #!/usr/bin/env node
2
+ // Daily check for a newer Joycraft. Prints nothing unless there is something to say,
3
+ // and never fails a session. The request is the package metadata only.
4
+ import { lstatSync, mkdirSync, openSync, closeSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
5
+ import { join, resolve } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+
8
+ const registry = 'https://registry.npmjs.org/joycraft/latest';
9
+ const day = 24 * 60 * 60 * 1000;
10
+ const retryAfter = 60 * 60 * 1000;
11
+ const snoozeFor = 7 * day;
12
+ const lockFor = 10_000;
13
+ const deadline = 2_000;
14
+ const stable = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
15
+ const policies = ['notify', 'auto-safe', 'off'];
16
+
17
+ const readJson = path => {
18
+ try {
19
+ const value = JSON.parse(readFileSync(path, 'utf8'));
20
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
21
+ } catch { return {}; }
22
+ };
23
+
24
+ /** Return the path of a file in .joycraft/local, or null when a parent is a link. */
25
+ function localPath(root, name) {
26
+ let current = resolve(root);
27
+ for (const part of ['.joycraft', 'local']) {
28
+ current = join(current, part);
29
+ try { if (!lstatSync(current).isDirectory()) return null; }
30
+ catch (error) {
31
+ if (error.code !== 'ENOENT') return null;
32
+ mkdirSync(current);
33
+ }
34
+ }
35
+ return join(current, name);
36
+ }
37
+
38
+ function writeLocal(root, name, value) {
39
+ const path = localPath(root, name);
40
+ if (!path) return false;
41
+ const temporary = `${path}.${process.pid}`;
42
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`);
43
+ renameSync(temporary, path);
44
+ return true;
45
+ }
46
+
47
+ export function isNewer(candidate, installed) {
48
+ const a = candidate.match(stable), b = installed.match(stable);
49
+ if (!a || !b) return false;
50
+ for (let i = 1; i <= 3; i += 1) if (BigInt(a[i]) !== BigInt(b[i])) return BigInt(a[i]) > BigInt(b[i]);
51
+ return false;
52
+ }
53
+
54
+ const updateKind = (latest, installed) => latest.split('.')[0] === installed.split('.')[0] ? 'patch' : 'migration';
55
+ const oneLine = value => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 300) : '';
56
+
57
+ function holdLock(root) {
58
+ const path = localPath(root, 'update-check.lock');
59
+ if (!path) return null;
60
+ try { if (Date.now() - statSync(path).mtimeMs > lockFor) unlinkSync(path); } catch { /* no lock yet */ }
61
+ try { closeSync(openSync(path, 'wx')); return () => { try { unlinkSync(path); } catch { /* already gone */ } }; }
62
+ catch { return null; }
63
+ }
64
+
65
+ /** One network read per day; concurrent sessions and failures fall back to the cache. */
66
+ async function latestRelease(root, { fetcher, now }) {
67
+ const cachePath = localPath(root, 'update-check.json');
68
+ if (!cachePath) return null;
69
+ const cache = readJson(cachePath);
70
+ if (typeof cache.fetchedAt === 'number' && now - cache.fetchedAt < day) return cache;
71
+ if (typeof cache.failedAt === 'number' && now - cache.failedAt < retryAfter) return cache;
72
+ const release = holdLock(root);
73
+ if (!release) return cache;
74
+ try {
75
+ const response = await fetcher(registry, { signal: AbortSignal.timeout(deadline), headers: { accept: 'application/json' } });
76
+ if (!response.ok) throw new Error(`registry ${response.status}`);
77
+ const metadata = await response.json();
78
+ if (typeof metadata?.version !== 'string' || !stable.test(metadata.version)) throw new Error('not a stable release');
79
+ const notes = metadata.joycraft?.release === metadata.version ? metadata.joycraft : {};
80
+ const fresh = { fetchedAt: now, version: metadata.version, summary: oneLine(notes.summary), autoSafeEligible: notes.autoSafeEligible === true };
81
+ writeLocal(root, 'update-check.json', fresh);
82
+ return fresh;
83
+ } catch {
84
+ writeLocal(root, 'update-check.json', { ...cache, failedAt: now });
85
+ return cache;
86
+ } finally { release(); }
87
+ }
88
+
89
+ export async function check(root, { fetcher = fetch, now = Date.now() } = {}) {
90
+ const installed = readJson(join(root, '.joycraft/installation.json')).joycraft;
91
+ if (typeof installed !== 'string' || !stable.test(installed)) return null;
92
+ const { update = {} } = readJson(join(root, '.joycraft/local/preferences.json'));
93
+ const policy = policies.includes(update.policy) ? update.policy : 'notify';
94
+ if (policy === 'off') return null;
95
+ const cache = await latestRelease(root, { fetcher, now });
96
+ const latest = cache?.version;
97
+ if (typeof latest !== 'string' || !isNewer(latest, installed)) return null;
98
+ if (update.snoozed?.version === latest && now < update.snoozed.until) return null;
99
+ const kind = updateKind(latest, installed);
100
+ const summary = cache.summary || 'See the changelog for what changed.';
101
+ if (update.pin === true) return { action: 'note', installed, latest, kind, message: `Joycraft ${latest} is available. This project stays on ${installed} by choice.` };
102
+ const action = policy === 'auto-safe' && kind === 'patch' && cache.autoSafeEligible === true ? 'apply' : 'ask';
103
+ return { action, installed, latest, kind, summary, message: `Joycraft ${latest} is available (you have ${installed}; ${kind}). ${summary}` };
104
+ }
105
+
106
+ function savePreference(root, change) {
107
+ const path = localPath(root, 'preferences.json');
108
+ if (!path) throw new Error('.joycraft/local is not a plain directory');
109
+ const preferences = readJson(path);
110
+ return writeLocal(root, 'preferences.json', { ...preferences, update: change(preferences.update ?? {}) });
111
+ }
112
+
113
+ export const snooze = (root, version, now = Date.now()) => {
114
+ if (!stable.test(version ?? '')) throw new Error('Snooze needs a version');
115
+ return savePreference(root, update => ({ ...update, snoozed: { version, until: now + snoozeFor } }));
116
+ };
117
+
118
+ export const setPolicy = (root, policy) => {
119
+ if (!policies.includes(policy)) throw new Error(`Policy must be one of: ${policies.join(', ')}`);
120
+ return savePreference(root, update => ({ ...update, policy }));
121
+ };
122
+
123
+ export const setPin = (root, pin) => savePreference(root, update => ({ ...update, pin }));
124
+
125
+ export async function main(argv, root = process.cwd(), options) {
126
+ const [command = 'check', value] = argv;
127
+ if (command === 'check') {
128
+ let result = null;
129
+ try { result = await check(root, options); } catch { /* a version check never stops a session */ }
130
+ if (result) console.log(JSON.stringify(result, null, 2));
131
+ return result;
132
+ }
133
+ if (command === 'snooze') return snooze(root, value);
134
+ if (command === 'policy') return setPolicy(root, value);
135
+ if (command === 'pin') return setPin(root, true);
136
+ if (command === 'unpin') return setPin(root, false);
137
+ throw new Error('Use check, snooze <version>, policy notify|auto-safe|off, pin or unpin');
138
+ }
139
+
140
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
141
+ main(process.argv.slice(2)).catch(error => { console.error(`Update check stopped: ${error.message}`); process.exitCode = 1; });
142
+ }
@@ -0,0 +1,201 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { ensureLocal, mainTree, withLock } from './coordinator.mjs';
6
+ import { isObject, parseJson, readLocal, relativePath, requireValue, validateQueue } from './identity.mjs';
7
+
8
+ // Worker worktrees have one home and one ledger, so a later session can tell
9
+ // its own trees from someone else's and release them once their work is in.
10
+ export const ledgerPath = '.joycraft/local/worktrees.json';
11
+ export const treeHome = '.joycraft/local/worktrees';
12
+
13
+ const git = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
14
+ const gitOk = (cwd, args) => { try { git(cwd, args); return true; } catch { return false; } };
15
+
16
+ // The ledger and tree home live in the main checkout, so a coordinator in any
17
+ // linked tree reads and writes the same records.
18
+ function gitRoot(root) {
19
+ try { git(root, ['rev-parse', '--show-toplevel']); } catch { throw new Error(`Not a Git working tree: ${root}`); }
20
+ return mainTree(root);
21
+ }
22
+
23
+ export function readLedger(root) {
24
+ const file = path.join(root, ledgerPath);
25
+ if (!existsSync(file)) return { schemaVersion: 1, trees: [] };
26
+ const ledger = parseJson(readFileSync(file), ledgerPath);
27
+ requireValue(isObject(ledger) && ledger.schemaVersion === 1 && Array.isArray(ledger.trees), `Unsupported worktree ledger: ${ledgerPath}`);
28
+ return ledger;
29
+ }
30
+
31
+ function writeLedger(root, ledger) {
32
+ ensureLocal(root);
33
+ writeFileSync(path.join(root, ledgerPath), `${JSON.stringify(ledger, null, 2)}\n`);
34
+ }
35
+
36
+ function readQueueFile(root, queuePath) {
37
+ const queue = parseJson(readLocal(root, queuePath), queuePath);
38
+ validateQueue(queue, { select: () => false });
39
+ return queue;
40
+ }
41
+
42
+ /** Create a worker tree for one spec from a captured base revision and record its owner. */
43
+ export function createWorktree({ root = process.cwd(), queuePath, specId, session, base = 'HEAD' }) {
44
+ root = gitRoot(root);
45
+ queuePath = relativePath(queuePath);
46
+ requireValue(typeof session === 'string' && session.trim(), 'Creating a worker tree needs the coordinator --session');
47
+ const queue = readQueueFile(root, queuePath);
48
+ requireValue(/^[a-z0-9][a-z0-9-]*$/.test(queue.feature), 'Worker trees need a queue feature that is a lowercase slug');
49
+ requireValue(queue.specs.some(spec => spec.id === specId), `Spec ${specId} does not exist in queue`);
50
+ const name = `${queue.feature}-${specId}`;
51
+ const treePath = `${treeHome}/${name}`;
52
+ const branch = `joycraft/${name}`;
53
+ let baseRevision;
54
+ try { baseRevision = git(root, ['rev-parse', '--verify', `${base}^{commit}`]).trim(); } catch { throw new Error(`Unknown base revision: ${base}`); }
55
+ ensureLocal(root);
56
+ return withLock(path.join(root, ledgerPath), () => {
57
+ const ledger = readLedger(root);
58
+ requireValue(!ledger.trees.some(tree => tree.path === treePath), `A worker tree for spec ${specId} is already recorded: ${treePath}; run prune or list first`);
59
+ requireValue(!existsSync(path.join(root, treePath)), `Worker tree path already exists: ${treePath}`);
60
+ mkdirSync(path.join(root, treeHome), { recursive: true });
61
+ git(root, ['worktree', 'add', '-b', branch, treePath, baseRevision]);
62
+ const entry = { path: treePath, branch, feature: queue.feature, queuePath, specId, baseRevision, coordinatorSession: session, createdAt: new Date().toISOString() };
63
+ ledger.trees.push(entry);
64
+ writeLedger(root, ledger);
65
+ return { ...entry, next: 'Run the project bootstrap in this tree before any edit.' };
66
+ });
67
+ }
68
+
69
+ function linkedTrees(root) {
70
+ const blocks = git(root, ['worktree', 'list', '--porcelain']).split(/\n\n+/).filter(Boolean);
71
+ const trees = blocks.map(block => {
72
+ const tree = {};
73
+ for (const line of block.split('\n')) {
74
+ const [key, ...rest] = line.split(' ');
75
+ tree[key] = rest.join(' ') || true;
76
+ }
77
+ return tree;
78
+ });
79
+ // The first entry is the main working tree; the coordinator never prunes itself.
80
+ return trees.slice(1).filter(tree => !existsSync(tree.worktree) || realpathSync(tree.worktree) !== root);
81
+ }
82
+
83
+ function sizeOf(target) {
84
+ let total = 0;
85
+ const stack = [target];
86
+ while (stack.length) {
87
+ const current = stack.pop();
88
+ let stat;
89
+ try { stat = lstatSync(current); } catch { continue; }
90
+ if (stat.isDirectory()) for (const name of readdirSync(current)) stack.push(path.join(current, name));
91
+ else total += stat.size;
92
+ }
93
+ return total;
94
+ }
95
+
96
+ function queueSpec(root, entry, queues) {
97
+ try {
98
+ if (!queues.has(entry.queuePath)) queues.set(entry.queuePath, readQueueFile(root, entry.queuePath));
99
+ return queues.get(entry.queuePath).specs.find(spec => spec.id === entry.specId) ?? { status: 'missing' };
100
+ } catch { return { status: 'unknown' }; }
101
+ }
102
+
103
+ // Ignored files are not "uncommitted changes", so git removes them with the tree.
104
+ // List them, and name accepted evidence that exists only in this tree.
105
+ function ignoredEntries(tree) {
106
+ return git(tree, ['status', '--ignored', '--porcelain']).split('\n').filter(line => line.startsWith('!! ')).map(line => line.slice(3));
107
+ }
108
+
109
+ function evidenceOnlyHere(root, tree, spec) {
110
+ return [spec.acceptedReport?.path, spec.ownerAcceptance?.path].filter(Boolean)
111
+ .filter(file => existsSync(path.join(tree, file)) && !existsSync(path.join(root, file)));
112
+ }
113
+
114
+ /** Every linked tree with its owner, spec status, merged and clean state. */
115
+ export function listWorktrees({ root = process.cwd(), into = 'HEAD', sizes = true } = {}) {
116
+ root = gitRoot(root);
117
+ const ledger = readLedger(root);
118
+ const owned = new Map(ledger.trees.map(entry => [path.resolve(root, entry.path), entry]));
119
+ const queues = new Map();
120
+ const seen = new Set();
121
+ const trees = linkedTrees(root).map(tree => {
122
+ const absolute = existsSync(tree.worktree) ? realpathSync(tree.worktree) : tree.worktree;
123
+ const entry = owned.get(absolute) ?? owned.get(tree.worktree);
124
+ if (entry) seen.add(entry.path);
125
+ const exists = existsSync(absolute);
126
+ const spec = entry ? queueSpec(root, entry, queues) : null;
127
+ const record = {
128
+ path: path.relative(root, absolute) || '.',
129
+ branch: typeof tree.branch === 'string' ? tree.branch.replace(/^refs\/heads\//, '') : null,
130
+ owner: entry ? 'joycraft' : 'unknown-owner',
131
+ ...(entry ? { feature: entry.feature, specId: entry.specId, coordinatorSession: entry.coordinatorSession, ledgerBranch: entry.branch, specStatus: spec.status } : {}),
132
+ ...(entry && exists ? { ignored: ignoredEntries(absolute), evidenceOnlyHere: evidenceOnlyHere(root, absolute, spec) } : {}),
133
+ merged: typeof tree.HEAD === 'string' && gitOk(root, ['merge-base', '--is-ancestor', tree.HEAD, into]),
134
+ clean: exists && gitOk(absolute, ['diff', '--quiet', 'HEAD']) && git(absolute, ['status', '--porcelain']).trim() === '',
135
+ exists,
136
+ };
137
+ if (sizes) record.bytes = exists ? sizeOf(absolute) : 0;
138
+ return record;
139
+ });
140
+ const missing = ledger.trees.filter(entry => !seen.has(entry.path)).map(entry => ({ path: entry.path, branch: entry.branch, owner: 'joycraft', feature: entry.feature, specId: entry.specId, exists: false, missing: true }));
141
+ return { root, into, trees: [...trees, ...missing] };
142
+ }
143
+
144
+ function decide(tree) {
145
+ if (tree.owner === 'joycraft' && !tree.exists) return { action: 'forget', reason: 'Recorded tree no longer exists; drop the ledger entry.' };
146
+ if (tree.owner !== 'joycraft') return { action: 'keep', reason: 'Not created by worktrees.mjs; inspect it, then remove it with git worktree remove if it is yours.' };
147
+ if (tree.specStatus !== 'done') return { action: 'keep', reason: `Spec ${tree.specId} is ${tree.specStatus}; keep the tree until it is done.` };
148
+ if (!tree.clean) return { action: 'keep', reason: 'The tree has uncommitted changes; commit or discard them first.' };
149
+ if (!tree.merged) return { action: 'keep', reason: 'The branch has commits that are not in the integration ref.' };
150
+ if (tree.evidenceOnlyHere.length) return { action: 'keep', reason: `Accepted evidence exists only in this tree: ${tree.evidenceOnlyHere.join(', ')}; copy it to the main checkout first.` };
151
+ return { action: 'remove', reason: 'Spec done, tree clean, branch integrated.', ...(tree.ignored.length ? { deletesIgnored: tree.ignored } : {}) };
152
+ }
153
+
154
+ /** Preview by default; apply removes only owned, clean, integrated trees of done specs. */
155
+ export function pruneWorktrees({ root = process.cwd(), into = 'HEAD', apply = false } = {}) {
156
+ const listing = listWorktrees({ root, into, sizes: false });
157
+ root = listing.root;
158
+ const plan = listing.trees.map(tree => ({ path: tree.path, branch: tree.branch, specId: tree.specId, ...decide(tree), ledgerBranch: tree.ledgerBranch }));
159
+ const strip = items => items.map(({ ledgerBranch, ...item }) => item);
160
+ if (!apply) return { applied: false, into, plan: strip(plan) };
161
+ ensureLocal(root);
162
+ return withLock(path.join(root, ledgerPath), () => {
163
+ const ledger = readLedger(root);
164
+ for (const item of plan.filter(item => item.action !== 'keep')) {
165
+ if (item.action === 'remove') {
166
+ try { git(root, ['worktree', 'remove', item.path]); } catch (error) {
167
+ item.action = 'keep'; item.reason = `git worktree remove refused: ${String(error.stderr ?? error.message).trim()}`; continue;
168
+ }
169
+ // Delete only the branch Joycraft created, and only if it is merged (-d).
170
+ item.branchDeleted = item.branch !== null && item.branch === item.ledgerBranch && gitOk(root, ['branch', '-d', item.branch]);
171
+ }
172
+ ledger.trees = ledger.trees.filter(entry => entry.path !== item.path);
173
+ }
174
+ gitOk(root, ['worktree', 'prune']);
175
+ writeLedger(root, ledger);
176
+ return { applied: true, into, plan: strip(plan) };
177
+ });
178
+ }
179
+
180
+ export async function main(argv = process.argv.slice(2)) {
181
+ const [command, ...rest] = argv;
182
+ const flags = {};
183
+ for (let index = 0; index < rest.length; index += 1) {
184
+ if (['--apply', '--no-size'].includes(rest[index])) { flags[rest[index]] = true; continue; }
185
+ flags[rest[index]] = rest[index + 1]; index += 1;
186
+ }
187
+ const root = path.resolve(flags['--root'] ?? '.');
188
+ let result;
189
+ if (command === 'create') {
190
+ requireValue(/^(?:0|[1-9]\d*)$/.test(flags['--spec'] ?? ''), 'Spec ID must be a nonnegative integer');
191
+ result = createWorktree({ root, queuePath: flags['--queue'], specId: Number(flags['--spec']), session: flags['--session'], base: flags['--base'] ?? 'HEAD' });
192
+ } else if (command === 'list') result = listWorktrees({ root, into: flags['--into'] ?? 'HEAD', sizes: flags['--no-size'] !== true });
193
+ else if (command === 'prune') result = pruneWorktrees({ root, into: flags['--into'] ?? 'HEAD', apply: flags['--apply'] === true });
194
+ else throw new Error('Usage: worktrees.mjs create --queue <queue> --spec <id> --session <coordinator> [--base <rev>] | list [--into <ref>] [--no-size] | prune [--into <ref>] [--apply] [--root <project>]');
195
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
196
+ return result;
197
+ }
198
+
199
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
200
+ main().catch(error => { process.stderr.write(`Worktrees stopped: ${error.message}\n`); process.exitCode = 1; });
201
+ }
@@ -0,0 +1,7 @@
1
+ # Queue template location
2
+
3
+ Copy `queue.json` to
4
+ `docs/features/<slug>/specs/.joycraft-spec-queue.json`. Spec filenames in its
5
+ `file` fields remain relative to that `specs/` directory; verification paths are
6
+ project-relative. Replace the example feature and paths with the current brief
7
+ and spec locations before dispatch.
@@ -0,0 +1,33 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "artifactId": "example-feature-review",
4
+ "title": "Example feature review",
5
+ "summary": "Choose the collection presentation after comparing the current and proposed views.",
6
+ "decisionIds": ["presentation"],
7
+ "comparisons": [
8
+ {
9
+ "title": "Collection presentation",
10
+ "decisionId": "presentation",
11
+ "images": [
12
+ {
13
+ "path": "docs/features/example-feature/screens/rows.png",
14
+ "label": "Compact rows",
15
+ "alt": "Example collection rendered as compact rows",
16
+ "caption": "Best when scan speed matters."
17
+ },
18
+ {
19
+ "path": "docs/features/example-feature/screens/cards.png",
20
+ "label": "Visual cards",
21
+ "alt": "Example collection rendered as visual cards",
22
+ "caption": "Best when imagery carries the choice."
23
+ }
24
+ ]
25
+ }
26
+ ],
27
+ "reviews": [
28
+ {
29
+ "path": "docs/features/example-feature/specs/review-1.report.json",
30
+ "title": "Recorded implementation review"
31
+ }
32
+ ]
33
+ }
@@ -0,0 +1,35 @@
1
+ ---
2
+ feature: example-feature
3
+ decisions: [
4
+ {"id":"presentation","status":"open","question":"Which presentation fits your task?","answer":null,"options":[{"value":"rows","label":"Compact rows"},{"value":"cards","label":"Visual cards"}],"affected":["collection-presentation"]}
5
+ ]
6
+ ---
7
+ # Feature intent
8
+
9
+ Replace this example with the user's full request, retaining repairs and new
10
+ behavior together. Link existing briefs when they already own part of the scope.
11
+
12
+ ## Context and authorization
13
+
14
+ Link relevant existing decisions/facts and record the authorization already given.
15
+ Keep assumptions explicit. Remove the example decision when no choice is needed.
16
+
17
+ ## Goals
18
+
19
+ - Describe each requested outcome with a stable heading below, and give each a
20
+ **Done when** line: example inputs or states with their expected results. For
21
+ a rule over open-ended input, also name the check set, which error costs more,
22
+ and the pass threshold.
23
+
24
+ ## Agent work and pending choices
25
+
26
+ Name understood work that can continue and the decision IDs blocking other work.
27
+
28
+ ## collection-presentation
29
+
30
+ After the choice is saved above, describe its requirement here and reference the
31
+ decision ID. This heading is the stable source for an affected queue criterion.
32
+
33
+ ## Scope and limits
34
+
35
+ Record relevant exclusions without replacing the user's goals.
@@ -0,0 +1,13 @@
1
+ # Decision log
2
+
3
+ Copy to `docs/context/decision-log.md` during a kickoff when there is at least
4
+ one decision. One entry per decision, newest first. A feature brief still owns
5
+ its current decisions; this log keeps the reasons that outlive one feature.
6
+
7
+ ## <Decision title>
8
+
9
+ - **Status:** decided | proposed | not established
10
+ - **Decision:** what was chosen, or the preference the user stated.
11
+ - **Why:** the user's reason, quoted where possible.
12
+ - **Rejected:** the options considered and why they lost.
13
+ - **Source:** [kickoff notes](kickoff-notes.md) or the brief that owns it.
@@ -0,0 +1,36 @@
1
+ # <Project name>
2
+
3
+ Copy to `docs/context/project.md` during a kickoff. Delete every section that
4
+ has no content yet; never leave a placeholder. Mark each statement as the
5
+ user's words, a decision, or an assumption.
6
+
7
+ ## Vision
8
+
9
+ What the user wants to exist and why, in two to five sentences. Quote the
10
+ user's own phrasing for the core idea.
11
+
12
+ ## Users
13
+
14
+ Who uses it, what they are trying to do, and who else has a stake.
15
+
16
+ ## First outcome
17
+
18
+ The first result that counts as done. The first brief owns its "Done when";
19
+ link it here.
20
+
21
+ ## Non-goals
22
+
23
+ What this project will not do, as the user stated it.
24
+
25
+ ## Glossary
26
+
27
+ | Term | Meaning, in the user's words |
28
+ |---|---|
29
+
30
+ ## Open questions
31
+
32
+ Consequential unknowns that are not decided yet. Do not write them as boundaries.
33
+
34
+ ## Sources
35
+
36
+ - [Kickoff notes](kickoff-notes.md): the user's verbatim words.
@@ -0,0 +1,27 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "feature": "example-feature",
4
+ "specs": [
5
+ {
6
+ "id": 1,
7
+ "file": "01-outcome.md",
8
+ "depends_on": [],
9
+ "status": "todo",
10
+ "mode": "batch",
11
+ "execution": { "parallel": false },
12
+ "verification": {
13
+ "inputs": [
14
+ { "path": "docs/features/example-feature/brief.md", "kind": "requirement" },
15
+ { "path": "docs/features/example-feature/specs/01-outcome.md", "kind": "requirement" }
16
+ ],
17
+ "criteria": [
18
+ {
19
+ "id": "outcome",
20
+ "requirement": { "path": "docs/features/example-feature/specs/01-outcome.md", "anchor": "acceptance" },
21
+ "requiredKinds": ["runtime"]
22
+ }
23
+ ]
24
+ }
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,39 @@
1
+ ---
2
+ id: 1
3
+ status: todo
4
+ ---
5
+ # Outcome
6
+
7
+ State one testable authorized outcome. Link the parent brief and any decisions
8
+ that constrain it; a material open decision cannot be assumed resolved.
9
+
10
+ ## acceptance
11
+
12
+ Describe observable behavior, representative state and failure behavior. End
13
+ each bullet with `Check:` naming a concrete input or state, the expected result,
14
+ and the command or test that shows it. Reference the source requirement instead
15
+ of copying open decisions here; quote settled rulings with their ID.
16
+
17
+ For a rule over open-ended input (names, documents, classifications), add an
18
+ **Open-input rule** line: the closed check set (path), which error costs more,
19
+ and the pass threshold.
20
+
21
+ ## Not covered
22
+
23
+ Accepted limits and cases this spec deliberately leaves out.
24
+
25
+ ## Implementation and verification scope
26
+
27
+ List the relevant implementation, test/configuration and fixture paths and needed
28
+ evidence. For a change crossing a state, data, or responsibility boundary, name
29
+ the owning and coupled sources plus an observable scenario that distinguishes the
30
+ intended behavior from a stale or mismatched path. Omit that detail for a simple
31
+ local edit. Keep the queue's exact verification inputs current as work reveals
32
+ them.
33
+
34
+ ## Deferred until deploy
35
+
36
+ List checks that only a deployed environment can show, such as a preview or
37
+ production URL, live webhooks, DNS, real email or payment delivery, or production
38
+ data. They are not verification criteria and do not block review; the owner
39
+ checks them after deploy. Omit this section when there are none.
@@ -0,0 +1,71 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <meta charset="utf-8">
4
+ <meta name="viewport" content="width=device-width, initial-scale=1">
5
+ <title>Try a small slice</title>
6
+ <style>
7
+ *{box-sizing:border-box}body{margin:0;background:#f4f5f2;color:#192b26;font:16px/1.45 system-ui,sans-serif}main{max-width:940px;margin:auto;padding:24px}header{display:flex;align-items:baseline;gap:16px;justify-content:space-between}h1{font-size:20px;margin:0}small{color:#53645d}iframe{display:block;width:100%;height:360px;border:1px solid #d4ded6;border-radius:16px;background:white;margin:18px 0}fieldset{border:0;padding:0;margin:0}legend{font-weight:650;margin-bottom:10px}.options{display:flex;gap:8px;flex-wrap:wrap}label{padding:9px 12px;border:1px solid #aebbb3;border-radius:10px;cursor:pointer;background:white}input{accent-color:#176444;margin-right:7px}button{border:0;background:#176444;color:white;border-radius:10px;padding:11px 18px;font:inherit;font-weight:600;cursor:pointer}button:disabled{opacity:.55;cursor:default}.actions{display:flex;gap:14px;align-items:center;margin:14px 0 8px}#notice{font-size:14px;margin:0}details{font-size:13px;color:#53645d}summary{cursor:pointer}pre{white-space:pre-wrap}#error{color:#97361e}@media(max-width:520px){main{padding:16px}header{display:block}iframe{height:390px;margin:12px 0}.actions{align-items:flex-start;flex-direction:column;gap:8px}}
8
+ </style>
9
+ <main>
10
+ <header><h1>Try a small slice</h1><small>One choice, then keep building</small></header>
11
+ <iframe id="preview" title="Product preview" sandbox="allow-scripts"></iframe>
12
+ <form id="choice-form">
13
+ <fieldset><legend id="question">Loading choice…</legend><div class="options" id="options"></div></fieldset>
14
+ <div class="actions"><button id="save" disabled>Save choice</button><p id="notice" role="status" aria-live="polite"></p></div>
15
+ </form>
16
+ <p id="error" role="alert"></p>
17
+ <details><summary>Context and affected work</summary><p>This explores a choice within your request. Saving updates the feature brief; production work follows its authorized scope.</p><pre id="context"></pre></details>
18
+ </main>
19
+ <script>
20
+ const token = __REQUEST_TOKEN__;
21
+ const form = document.querySelector('#choice-form'), options = document.querySelector('#options');
22
+ const save = document.querySelector('#save'), notice = document.querySelector('#notice'), error = document.querySelector('#error');
23
+ let current, selected;
24
+ function preview(){document.querySelector('#preview').src = '/slice?choice=' + encodeURIComponent(selected)}
25
+ function render(state){
26
+ const previous = current;
27
+ current = state;
28
+ if(!state.decision){
29
+ document.querySelector('#question').textContent = 'All choices are settled.';
30
+ options.replaceChildren(); save.disabled = true;
31
+ notice.textContent = 'The current brief has no unanswered choices.';
32
+ document.querySelector('#context').textContent = 'Read the current brief for settled decisions.';
33
+ document.querySelector('#preview').removeAttribute('src');
34
+ return;
35
+ }
36
+ const decision = state.decision, editable = ['open','assigned'].includes(decision.status);
37
+ const preserveDraft = previous && previous.decision && previous.decision.id === decision.id && decision.options.some(option => option.value === selected);
38
+ selected = preserveDraft ? selected : decision.answer ?? decision.options[0].value;
39
+ document.querySelector('#question').textContent = decision.question;
40
+ options.replaceChildren();
41
+ for(const option of decision.options){
42
+ const label = document.createElement('label'), input = document.createElement('input');
43
+ input.type = 'radio'; input.name = 'choice'; input.value = option.value; input.checked = selected === option.value; input.disabled = !editable;
44
+ input.addEventListener('change',()=>{selected = option.value; preview(); notice.textContent = 'Preview only — save when it fits.'});
45
+ label.append(input, document.createTextNode(option.label)); options.append(label);
46
+ }
47
+ save.disabled = !editable;
48
+ notice.textContent = decision.status === 'clarified' ? 'Saved in the brief. Ready to continue.' : editable ? 'Preview only — no answer saved yet.' : 'Outside current scope. Reopen in the brief to revisit.';
49
+ document.querySelector('#context').textContent = 'Decision: ' + decision.id + '\nAffected: ' + (decision.affected.join(', ') || 'None listed');
50
+ preview();
51
+ }
52
+ form.addEventListener('submit', async event=>{
53
+ event.preventDefault(); save.disabled = true; error.textContent = '';
54
+ try{
55
+ const response = await fetch('/answer',{method:'POST',headers:{'Content-Type':'application/json','X-Slice-Token':token},body:JSON.stringify({id:current.decision.id,answer:selected,revision:current.revision})});
56
+ const result = await response.json();
57
+ if(!response.ok) throw new Error(result.error);
58
+ render(result);
59
+ }catch(problem){error.textContent = problem.message + ' Reload to read the current brief.'}
60
+ });
61
+ async function refresh(){
62
+ try{
63
+ const response = await fetch('/state'), state = await response.json();
64
+ if(!response.ok) throw new Error(state.error);
65
+ if(!current || state.revision !== current.revision) render(state);
66
+ }catch(problem){error.textContent = problem.message}
67
+ }
68
+ refresh();
69
+ setInterval(refresh, 1000);
70
+ </script>
71
+ </html>