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,169 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { isObject, nonempty, parseJson, readLocal, relativePath, requireValue, validateQueue } from './identity.mjs';
6
+
7
+ // One session coordinates a queue at a time. The lease is a coordination record
8
+ // that every worker tree of the repository can read; it is not authentication.
9
+ export const staleMinutesDefault = 30;
10
+
11
+ /** The main working tree, which all linked worker trees share. */
12
+ export function mainTree(root) {
13
+ let listing;
14
+ try { listing = execFileSync('git', ['worktree', 'list', '--porcelain'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); }
15
+ catch { return realpathSync(root); }
16
+ const first = /^worktree (.+)$/m.exec(listing);
17
+ return first && existsSync(first[1]) ? realpathSync(first[1]) : realpathSync(root);
18
+ }
19
+
20
+ const leaseRelative = feature => `.joycraft/local/coordinators/${feature}.json`;
21
+ const isSlug = feature => /^[a-z0-9][a-z0-9-]*$/.test(feature ?? '');
22
+
23
+ export function leasePath(root, feature) {
24
+ requireValue(isSlug(feature), 'A coordinator lease needs a queue feature that is a lowercase slug');
25
+ return path.join(mainTree(root), leaseRelative(feature));
26
+ }
27
+
28
+ /** Serialize a read-modify-write of a small local record with an exclusive lock file. */
29
+ export function withLock(file, action, { waitMs = 5000 } = {}) {
30
+ const lock = `${file}.lock`;
31
+ mkdirSync(path.dirname(file), { recursive: true });
32
+ const deadline = Date.now() + waitMs;
33
+ for (;;) {
34
+ try { closeSync(openSync(lock, 'wx')); break; } catch (error) {
35
+ if (error.code !== 'EEXIST') throw error;
36
+ // A lock older than the wait limit belongs to a process that died mid-write.
37
+ try { if (Date.now() - statSync(lock).mtimeMs > waitMs) { unlinkSync(lock); continue; } } catch { continue; }
38
+ requireValue(Date.now() < deadline, `Another Joycraft process holds ${path.basename(lock)}; try again`);
39
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
40
+ }
41
+ }
42
+ try { return action(); } finally { rmSync(lock, { force: true }); }
43
+ }
44
+
45
+ /** No lease can exist for a feature name that is not a slug, so 1.0.0 queues keep working. */
46
+ export function readLease(root, feature) {
47
+ if (!isSlug(feature)) return null;
48
+ const file = leasePath(root, feature);
49
+ if (!existsSync(file)) return null;
50
+ const lease = parseJson(readFileSync(file), leaseRelative(feature));
51
+ requireValue(isObject(lease) && lease.schemaVersion === 1 && nonempty(lease.sessionId), `Unsupported coordinator lease: ${leaseRelative(feature)}`);
52
+ return lease;
53
+ }
54
+
55
+ /** Create the main checkout's .joycraft/local as a self-ignoring folder before anything is written in it. */
56
+ export function ensureLocal(root) {
57
+ const local = path.join(mainTree(root), '.joycraft/local');
58
+ if (!existsSync(local)) {
59
+ mkdirSync(local, { recursive: true, mode: 0o700 });
60
+ writeFileSync(path.join(local, '.gitignore'), '*\n', { flag: 'wx', mode: 0o600 });
61
+ }
62
+ }
63
+
64
+ function writeLease(root, feature, lease) {
65
+ const file = leasePath(root, feature);
66
+ ensureLocal(root);
67
+ mkdirSync(path.dirname(file), { recursive: true });
68
+ writeFileSync(file, `${JSON.stringify(lease, null, 2)}\n`);
69
+ }
70
+
71
+ export function queueFeature(root, queuePath) {
72
+ queuePath = relativePath(queuePath);
73
+ const queue = parseJson(readLocal(root, queuePath), queuePath);
74
+ validateQueue(queue, { select: () => false });
75
+ return { feature: queue.feature, queuePath };
76
+ }
77
+
78
+ const isStale = (lease, now, staleMinutes) => now - Date.parse(lease.heartbeatAt) >= staleMinutes * 60_000;
79
+ const holder = lease => `session ${lease.sessionId}${lease.host ? ` on ${lease.host}` : ''}`;
80
+
81
+ /** Claim a queue. A live lease held by another session blocks the claim unless takeOver is set. */
82
+ export function claim(options) {
83
+ const { feature } = queueFeature(options.root ?? process.cwd(), options.queuePath);
84
+ ensureLocal(options.root ?? process.cwd());
85
+ return withLock(leasePath(options.root ?? process.cwd(), feature), () => claimLocked(options));
86
+ }
87
+
88
+ function claimLocked({ root = process.cwd(), queuePath, session, host, takeOver = false, staleMinutes = staleMinutesDefault, now = Date.now() }) {
89
+ requireValue(nonempty(session), 'Claiming a queue needs the active host --session ID');
90
+ const { feature, queuePath: queue } = queueFeature(root, queuePath);
91
+ const current = readLease(root, feature);
92
+ const at = new Date(now).toISOString();
93
+ if (current && current.sessionId === session) {
94
+ const lease = { ...current, heartbeatAt: at };
95
+ writeLease(root, feature, lease);
96
+ return { claimed: true, renewed: true, lease };
97
+ }
98
+ if (current && !takeOver) {
99
+ const stale = isStale(current, now, staleMinutes);
100
+ throw new Error(`Queue ${feature} is coordinated by ${holder(current)} (last heartbeat ${current.heartbeatAt}${stale ? ', stale' : ''}). Work under that session, or rerun with --take-over if it has ended.`);
101
+ }
102
+ const lease = {
103
+ schemaVersion: 1, feature, queuePath: queue, sessionId: session, ...(nonempty(host) ? { host } : {}),
104
+ root: path.relative(mainTree(root), realpathSync(root)) || '.', claimedAt: at, heartbeatAt: at,
105
+ ...(current ? { previous: { sessionId: current.sessionId, ...(current.host ? { host: current.host } : {}), heartbeatAt: current.heartbeatAt, stale: isStale(current, now, staleMinutes), takenOverAt: at } } : {}),
106
+ };
107
+ writeLease(root, feature, lease);
108
+ return { claimed: true, renewed: false, lease };
109
+ }
110
+
111
+ function requireHolder(root, queuePath, session) {
112
+ const { feature } = queueFeature(root, queuePath);
113
+ const lease = readLease(root, feature);
114
+ requireValue(lease, `Queue ${feature} has no coordinator lease`);
115
+ requireValue(lease.sessionId === session, `Queue ${feature} is coordinated by ${holder(lease)}, not session ${session}`);
116
+ return { feature, lease };
117
+ }
118
+
119
+ export function heartbeat({ root = process.cwd(), queuePath, session, now = Date.now() }) {
120
+ const { feature } = queueFeature(root, queuePath);
121
+ ensureLocal(root);
122
+ return withLock(leasePath(root, feature), () => {
123
+ const { lease } = requireHolder(root, queuePath, session);
124
+ const next = { ...lease, heartbeatAt: new Date(now).toISOString() };
125
+ writeLease(root, feature, next);
126
+ return { lease: next };
127
+ });
128
+ }
129
+
130
+ export function release({ root = process.cwd(), queuePath, session }) {
131
+ const { feature } = queueFeature(root, queuePath);
132
+ ensureLocal(root);
133
+ return withLock(leasePath(root, feature), () => {
134
+ requireHolder(root, queuePath, session);
135
+ rmSync(leasePath(root, feature));
136
+ return { released: true, feature };
137
+ });
138
+ }
139
+
140
+ export function show({ root = process.cwd(), queuePath, staleMinutes = staleMinutesDefault, now = Date.now() }) {
141
+ const { feature } = queueFeature(root, queuePath);
142
+ const lease = readLease(root, feature);
143
+ return { feature, lease, stale: lease ? isStale(lease, now, staleMinutes) : null };
144
+ }
145
+
146
+ export async function main(argv = process.argv.slice(2)) {
147
+ const [command, ...rest] = argv;
148
+ const flags = {};
149
+ for (let index = 0; index < rest.length; index += 1) {
150
+ if (rest[index] === '--take-over') { flags[rest[index]] = true; continue; }
151
+ flags[rest[index]] = rest[index + 1]; index += 1;
152
+ }
153
+ const root = path.resolve(flags['--root'] ?? '.');
154
+ const staleMinutes = flags['--stale-minutes'] === undefined ? staleMinutesDefault : Number(flags['--stale-minutes']);
155
+ requireValue(Number.isFinite(staleMinutes) && staleMinutes > 0, '--stale-minutes must be a positive number');
156
+ const options = { root, queuePath: flags['--queue'], session: flags['--session'], staleMinutes };
157
+ let result;
158
+ if (command === 'claim') result = claim({ ...options, host: flags['--host'], takeOver: flags['--take-over'] === true });
159
+ else if (command === 'heartbeat') result = heartbeat(options);
160
+ else if (command === 'release') result = release(options);
161
+ else if (command === 'show') result = show(options);
162
+ else throw new Error('Usage: coordinator.mjs claim --queue <queue> --session <id> [--host <host>] [--take-over] | heartbeat|release --queue <queue> --session <id> | show --queue <queue> [--root <project>] [--stale-minutes <n>]');
163
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
164
+ return result;
165
+ }
166
+
167
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
168
+ main().catch(error => { process.stderr.write(`Coordinator stopped: ${error.message}\n`); process.exitCode = 1; });
169
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * A deliberately small, optional last-mile delivery guard. It observes a
3
+ * committed Git snapshot; it does not review code, authorize a remote, or
4
+ * isolate other writers.
5
+ */
6
+ import { createHash } from 'node:crypto';
7
+ import { mkdir, readFile, rm, stat } from 'node:fs/promises';
8
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
9
+ import { spawn } from 'node:child_process';
10
+ import { TextDecoder } from 'node:util';
11
+
12
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex');
13
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
14
+
15
+ function run(root, args, options = {}) {
16
+ return new Promise((resolveRun, reject) => {
17
+ const child = spawn('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
18
+ const out = []; const err = [];
19
+ child.stdout.on('data', value => out.push(value)); child.stderr.on('data', value => err.push(value));
20
+ child.on('error', reject); child.on('close', code => resolveRun({ code, stdout: Buffer.concat(out), stderr: Buffer.concat(err) }));
21
+ });
22
+ }
23
+ async function git(root, args) {
24
+ const result = await run(root, args);
25
+ if (result.code !== 0) throw new Error(`git-${args[0]}-failed`);
26
+ return result.stdout;
27
+ }
28
+ async function gitText(root, args) { return (await git(root, args)).toString('utf8').trim(); }
29
+ async function gitOk(root, args) { return (await run(root, args)).code === 0; }
30
+ function assertion(value, message) { if (!value) throw new Error(message); }
31
+ function lineJson(bytes, path) {
32
+ let text; try { text = utf8.decode(bytes); } catch { throw new Error(`invalid-json-utf8:${path}`); }
33
+ if (path.endsWith('.jsonl')) {
34
+ for (const line of text.split(/\r?\n/)) if (line.trim()) try { JSON.parse(line); } catch { throw new Error(`malformed-json:${path}`); }
35
+ } else try { JSON.parse(text); } catch { throw new Error(`malformed-json:${path}`); }
36
+ }
37
+
38
+ export async function resolveBase(root, base) {
39
+ assertion(typeof base === 'string' && base, 'base-required');
40
+ return gitText(root, ['rev-parse', '--verify', `${base}^{commit}`]);
41
+ }
42
+
43
+ async function mergeState(root) {
44
+ assertion(await gitOk(root, ['diff-index', '--quiet', 'HEAD', '--']), 'tracked-or-index-not-clean');
45
+ assertion((await git(root, ['ls-files', '-u'])).length === 0, 'unresolved-index');
46
+ for (const name of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'REBASE_HEAD']) assertion(!(await gitOk(root, ['rev-parse', '--verify', '-q', name])), 'unfinished-git-operation');
47
+ const gitDir = await gitText(root, ['rev-parse', '--git-dir']);
48
+ const absoluteGitDir = isAbsolute(gitDir) ? gitDir : resolve(root, gitDir);
49
+ try { await stat(join(absoluteGitDir, 'rebase-merge')); throw new Error('unfinished-git-operation'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
50
+ try { await stat(join(absoluteGitDir, 'rebase-apply')); throw new Error('unfinished-git-operation'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
51
+ }
52
+
53
+ async function committedJson(root, base, head) {
54
+ const names = (await git(root, ['diff', '--name-only', '-z', '--diff-filter=ACMRT', base, head])).toString('utf8').split('\0').filter(Boolean);
55
+ const checked = [];
56
+ for (const path of names.filter(name => name.endsWith('.json') || name.endsWith('.jsonl'))) {
57
+ lineJson(await git(root, ['show', `${head}:${path}`]), path); checked.push(path);
58
+ }
59
+ return checked;
60
+ }
61
+
62
+ async function trackedManifest(root) {
63
+ const paths = (await git(root, ['ls-files', '-z'])).toString('utf8').split('\0').filter(Boolean);
64
+ const entries = [];
65
+ for (const path of paths) entries.push([path, digest(await readFile(join(root, path)))]);
66
+ return digest(JSON.stringify(entries));
67
+ }
68
+
69
+ async function stableState(root) {
70
+ const head = await gitText(root, ['rev-parse', '--verify', 'HEAD^{commit}']);
71
+ // The index file has volatile cache/extension bytes. Its tree is the stable
72
+ // semantic binding and changes when a path is staged or its index mode changes.
73
+ const indexTree = await gitText(root, ['write-tree']);
74
+ return { head, indexTree, trackedSha256: await trackedManifest(root) };
75
+ }
76
+
77
+ async function introducedConflictMarkers(root, base, head) {
78
+ const diff = (await git(root, ['diff', '--no-color', '--unified=0', base, head])).toString('utf8');
79
+ return diff.split('\n').some(line => /^\+(?:<{7,}|={7,}|>{7,}|\|{7,})(?:\s|$)/.test(line));
80
+ }
81
+
82
+ /** Check the committed range only. Returns paths and immutable SHA evidence, never file contents. */
83
+ export async function checkDelivery({ root = process.cwd(), base } = {}) {
84
+ root = resolve(root); const baseSha = await resolveBase(root, base); const head = await gitText(root, ['rev-parse', '--verify', 'HEAD^{commit}']);
85
+ assertion(await gitOk(root, ['merge-base', '--is-ancestor', baseSha, head]), 'base-not-ancestor-of-head');
86
+ await mergeState(root);
87
+ assertion(!(await introducedConflictMarkers(root, baseSha, head)), 'introduced-conflict-markers');
88
+ const jsonPaths = await committedJson(root, baseSha, head);
89
+ return { ok: true, root, base: baseSha, head, jsonPaths, conflictCheck: 'no-introduced-markers' };
90
+ }
91
+
92
+ function streamReceipt(stream) {
93
+ const hash = createHash('sha256'); let byteCount = 0;
94
+ stream.on('data', value => { byteCount += value.length; hash.update(value); });
95
+ stream.resume();
96
+ return () => ({ byteCount, sha256: hash.digest('hex') });
97
+ }
98
+ async function invoke(argv, root) {
99
+ assertion(Array.isArray(argv) && argv.length && argv.every(value => typeof value === 'string' && value), 'verifier-required');
100
+ return new Promise((resolveRun, reject) => {
101
+ const child = spawn(argv[0], argv.slice(1), { cwd: root, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
102
+ // Drain without retaining potentially private verifier output. Close fires
103
+ // after the pipe closes, so the receipts include all observed bytes.
104
+ const stdout = streamReceipt(child.stdout); const stderr = streamReceipt(child.stderr);
105
+ child.on('error', reject); child.on('close', exitCode => resolveRun({ exitCode, stdout: stdout(), stderr: stderr() }));
106
+ });
107
+ }
108
+ async function acquireLock(root, remote, branch) {
109
+ const common = await gitText(root, ['rev-parse', '--git-common-dir']); const directory = isAbsolute(common) ? common : resolve(root, common);
110
+ const lock = join(directory, 'joycraft-delivery-locks', digest(`${remote}\0${branch}`));
111
+ await mkdir(dirname(lock), { recursive: true, mode: 0o700 });
112
+ try { await mkdir(lock, { recursive: false, mode: 0o700 }); } catch (error) { if (error.code === 'EEXIST') throw new Error('delivery-lock-exists-manual-diagnosis-required'); throw error; }
113
+ return lock;
114
+ }
115
+ function validTarget(remote, branch) { return typeof remote === 'string' && remote && !remote.startsWith('-') && typeof branch === 'string' && branch && !branch.startsWith('-') && !/[\s~^:?*\\[\x00]/.test(branch); }
116
+
117
+ export async function deliver({ root = process.cwd(), base, remote, branch, verifier } = {}) {
118
+ root = resolve(root); assertion(validTarget(remote, branch), 'explicit-remote-and-branch-required');
119
+ const lock = await acquireLock(root, remote, branch);
120
+ try {
121
+ const before = await stableState(root); const checked = await checkDelivery({ root, base });
122
+ assertion(checked.head === before.head, 'head-changed-before-verifier');
123
+ const verifierReceipt = await invoke(verifier, root); assertion(verifierReceipt.exitCode === 0, `verifier-exit-${verifierReceipt.exitCode}`);
124
+ const after = await stableState(root); assertion(JSON.stringify(before) === JSON.stringify(after), 'source-changed-during-verifier');
125
+ await mergeState(root);
126
+ const pushed = await run(root, ['push', remote, `${before.head}:refs/heads/${branch}`]);
127
+ assertion(pushed.code === 0, 'push-failed');
128
+ return { ok: true, ...checked, pushedSha: before.head, remote, branch, verifier: verifierReceipt };
129
+ } finally { await rm(lock, { recursive: true, force: false }); }
130
+ }
131
+
132
+ function usage() { throw new Error('Usage: delivery.mjs check --root <repo> --base <revision> | delivery.mjs push --root <repo> --base <revision> --remote <name> --branch <branch> -- <verifier> [args...]'); }
133
+ async function cli(argv) {
134
+ const separator = argv.indexOf('--'); const own = separator < 0 ? argv : argv.slice(0, separator); const verifier = separator < 0 ? [] : argv.slice(separator + 1);
135
+ const command = own.shift(); const flags = {};
136
+ for (let index = 0; index < own.length; index += 2) { const key = own[index]; const value = own[index + 1]; if (!['--root', '--base', '--remote', '--branch'].includes(key) || flags[key] !== undefined || value === undefined) usage(); flags[key] = value; }
137
+ if (!flags['--root'] || !flags['--base']) usage();
138
+ if (command === 'check' && separator < 0) return checkDelivery({ root: flags['--root'], base: flags['--base'] });
139
+ if (command === 'push' && flags['--remote'] && flags['--branch'] && verifier.length) return deliver({ root: flags['--root'], base: flags['--base'], remote: flags['--remote'], branch: flags['--branch'], verifier });
140
+ usage();
141
+ }
142
+ if (import.meta.url === new URL(process.argv[1], 'file:').href) cli(process.argv.slice(2)).then(result => process.stdout.write(`${JSON.stringify(result)}\n`)).catch(error => { process.stderr.write(`${error.message}\n`); process.exitCode = 1; });