joycraft 0.7.16 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -156
- package/dist/cli.js +1593 -373
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/joycraft-release.json +1 -1
- package/package.json +9 -3
- package/payload/.agents/skills/joycraft-context/SKILL.md +36 -0
- package/payload/.agents/skills/joycraft-decompose/SKILL.md +68 -0
- package/payload/.agents/skills/joycraft-entry/SKILL.md +103 -0
- package/payload/.agents/skills/joycraft-implement/SKILL.md +106 -0
- package/payload/.agents/skills/joycraft-retro/SKILL.md +54 -0
- package/payload/.agents/skills/joycraft-retro/agents/openai.yaml +5 -0
- package/payload/.agents/skills/joycraft-session-end/SKILL.md +78 -0
- package/payload/.agents/skills/joycraft-testing/SKILL.md +60 -0
- package/payload/.agents/skills/joycraft-ui-slice/SKILL.md +59 -0
- package/payload/.agents/skills/joycraft-ui-slice/scripts/serve.mjs +97 -0
- package/payload/.agents/skills/joycraft-verify/SKILL.md +103 -0
- package/payload/.claude/agents/joycraft-implementer.md +31 -0
- package/payload/.claude/agents/joycraft-reviewer.md +30 -0
- package/payload/.joycraft/assets/artifacts/kit.css +102 -0
- package/payload/.joycraft/assets/artifacts/kit.js +301 -0
- package/payload/.joycraft/assets/artifacts/transports.js +236 -0
- package/payload/.joycraft/contracts/types.d.ts +185 -0
- package/payload/.joycraft/references/architecture.md +90 -0
- package/payload/.joycraft/references/archive.md +211 -0
- package/payload/.joycraft/references/artifacts.md +176 -0
- package/payload/.joycraft/references/completion.md +109 -0
- package/payload/.joycraft/references/context.md +80 -0
- package/payload/.joycraft/references/delivery.md +32 -0
- package/payload/.joycraft/references/dispatch.md +226 -0
- package/payload/.joycraft/references/recurring-failures.md +33 -0
- package/payload/.joycraft/references/retro.md +94 -0
- package/payload/.joycraft/references/setup.md +279 -0
- package/payload/.joycraft/references/testing.md +120 -0
- package/payload/.joycraft/references/update.md +44 -0
- package/payload/.joycraft/references/workflow.md +113 -0
- package/payload/.joycraft/references/worktrees.md +148 -0
- package/payload/.joycraft/runtime/archive.mjs +463 -0
- package/payload/.joycraft/runtime/artifacts/cli.mjs +61 -0
- package/payload/.joycraft/runtime/artifacts/decisions.mjs +214 -0
- package/payload/.joycraft/runtime/artifacts/model.mjs +161 -0
- package/payload/.joycraft/runtime/artifacts/preferences.mjs +127 -0
- package/payload/.joycraft/runtime/artifacts/render.mjs +21 -0
- package/payload/.joycraft/runtime/artifacts/server.mjs +40 -0
- package/payload/.joycraft/runtime/completion.mjs +300 -0
- package/payload/.joycraft/runtime/context/cli.mjs +75 -0
- package/payload/.joycraft/runtime/context/index.mjs +29 -0
- package/payload/.joycraft/runtime/context/search.mjs +149 -0
- package/payload/.joycraft/runtime/delivery.mjs +142 -0
- package/payload/.joycraft/runtime/dispatch-preflight.mjs +535 -0
- package/payload/.joycraft/runtime/dispatch-start.mjs +98 -0
- package/payload/.joycraft/runtime/evidence.mjs +137 -0
- package/payload/.joycraft/runtime/identity.mjs +486 -0
- package/payload/.joycraft/runtime/kickoff.mjs +174 -0
- package/payload/.joycraft/runtime/redact.mjs +9 -0
- package/payload/.joycraft/runtime/retro.mjs +151 -0
- package/payload/.joycraft/runtime/review-tools.json +34 -0
- package/payload/.joycraft/runtime/review-tools.mjs +331 -0
- package/payload/.joycraft/runtime/scope.mjs +129 -0
- package/payload/.joycraft/runtime/update-check.mjs +142 -0
- package/payload/.joycraft/templates/README.md +7 -0
- package/payload/.joycraft/templates/artifact.json +33 -0
- package/payload/.joycraft/templates/brief.md +35 -0
- package/payload/.joycraft/templates/decisions.md +13 -0
- package/payload/.joycraft/templates/project-context.md +36 -0
- package/payload/.joycraft/templates/queue.json +27 -0
- package/payload/.joycraft/templates/spec.md +39 -0
- package/payload/.joycraft/templates/ui-slice.html +71 -0
- package/payload/PIN +74 -0
- package/payload/scripts/export.mjs +301 -0
- package/payload/scripts/hook-paths.mjs +35 -0
- package/payload/scripts/legacy-hooks.mjs +128 -0
- package/payload/scripts/legacy-inventory.json +117 -0
- package/dist/chunk-35RQLGKM.js +0 -2167
- package/dist/chunk-35RQLGKM.js.map +0 -1
- package/dist/chunk-7BPB2IKY.js +0 -255
- package/dist/chunk-7BPB2IKY.js.map +0 -1
- package/dist/chunk-B73DPYYC.js +0 -377
- package/dist/chunk-B73DPYYC.js.map +0 -1
- package/dist/chunk-GTP7Z52K.js +0 -3942
- package/dist/chunk-GTP7Z52K.js.map +0 -1
- package/dist/chunk-K4AI6FKB.js +0 -417
- package/dist/chunk-K4AI6FKB.js.map +0 -1
- package/dist/chunk-KKDKC4FM.js +0 -115
- package/dist/chunk-KKDKC4FM.js.map +0 -1
- package/dist/chunk-OMFGDJW4.js +0 -97
- package/dist/chunk-OMFGDJW4.js.map +0 -1
- package/dist/chunk-Z5JFEGWG.js +0 -563
- package/dist/chunk-Z5JFEGWG.js.map +0 -1
- package/dist/init-MUB5CC6L.js +0 -60
- package/dist/init-MUB5CC6L.js.map +0 -1
- package/dist/init-autofix-2DMBO4QN.js +0 -122
- package/dist/init-autofix-2DMBO4QN.js.map +0 -1
- package/dist/install-manifest-EQHT4474.js +0 -37
- package/dist/install-manifest-EQHT4474.js.map +0 -1
- package/dist/release-artifact-4TL5L2ZY.js +0 -14
- package/dist/release-artifact-4TL5L2ZY.js.map +0 -1
- package/dist/release-resolver-P2H46QTU.js +0 -293
- package/dist/release-resolver-P2H46QTU.js.map +0 -1
- package/dist/telemetry-store-IBO5GRTA.js +0 -14
- package/dist/telemetry-store-IBO5GRTA.js.map +0 -1
- package/dist/update-LFLQTPUA.js +0 -19
- package/dist/update-LFLQTPUA.js.map +0 -1
- package/dist/update-check-YT765NE7.js +0 -36
- package/dist/update-check-YT765NE7.js.map +0 -1
- package/dist/upgrade-L5WERK4X.js +0 -28
- package/dist/upgrade-L5WERK4X.js.map +0 -1
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
import { accessSync, existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { canonical, isObject, isSha256, nonempty, parseJson, readLocal, readQueue, relativePath, requireAbsent, requireValue, sha256, snapshot, validateNativeActor, validateQueue } from './identity.mjs';
|
|
7
|
+
import { checkReport } from './completion.mjs';
|
|
8
|
+
import { reviewLoopSection } from './review-tools.mjs';
|
|
9
|
+
|
|
10
|
+
const unknown = 'unknown';
|
|
11
|
+
const forbiddenDeliveryFields = new Set(['expected', 'expectedverdict', 'verdict', 'reasoning', 'conclusion', 'answer']);
|
|
12
|
+
const decisionStates = new Set(['open', 'clarified', 'backlogged', 'discarded', 'assigned']);
|
|
13
|
+
|
|
14
|
+
function workerDirectory(workerRoot) {
|
|
15
|
+
requireValue(nonempty(workerRoot) && path.isAbsolute(workerRoot), 'Dispatch needs an explicit absolute worker root');
|
|
16
|
+
const resolved = path.resolve(workerRoot);
|
|
17
|
+
requireValue(existsSync(resolved), `Worker root does not exist: ${resolved}`);
|
|
18
|
+
return realpathSync(resolved);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function realDirectory(directory, label) {
|
|
22
|
+
requireValue(nonempty(directory) && path.isAbsolute(directory), `${label} needs an explicit absolute path`);
|
|
23
|
+
const resolved = path.resolve(directory);
|
|
24
|
+
requireValue(existsSync(resolved), `${label} does not exist: ${resolved}`);
|
|
25
|
+
return realpathSync(resolved);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function gitDirectory(root, label) {
|
|
29
|
+
let topLevel;
|
|
30
|
+
let commonDir;
|
|
31
|
+
let gitDir;
|
|
32
|
+
try {
|
|
33
|
+
topLevel = realpathSync(execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());
|
|
34
|
+
commonDir = realpathSync(path.resolve(root, execFileSync('git', ['rev-parse', '--git-common-dir'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()));
|
|
35
|
+
gitDir = realpathSync(path.resolve(root, execFileSync('git', ['rev-parse', '--git-dir'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()));
|
|
36
|
+
} catch {
|
|
37
|
+
throw new Error(`${label} must be a Git worktree`);
|
|
38
|
+
}
|
|
39
|
+
requireValue(topLevel === realpathSync(root), `${label} must name the Git worktree root, not a subdirectory`);
|
|
40
|
+
return { topLevel, commonDir, gitDir };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The native host owns worktree creation. This only attests an already-created
|
|
45
|
+
* linked worktree before parallel mutation; it is not a sandbox boundary.
|
|
46
|
+
*/
|
|
47
|
+
function queueSpecForSource(root, sourceView) {
|
|
48
|
+
const queue = parseJson(readLocal(root, sourceView.queue.path), sourceView.queue.path);
|
|
49
|
+
const queueDirectory = path.posix.dirname(sourceView.queue.path);
|
|
50
|
+
validateQueue(queue, { select: spec => isObject(spec) && nonempty(spec.file) && path.posix.join(queueDirectory, spec.file) === sourceView.spec.path });
|
|
51
|
+
const matching = queue.specs.filter(spec => isObject(spec) && nonempty(spec.file) && path.posix.join(queueDirectory, spec.file) === sourceView.spec.path);
|
|
52
|
+
requireValue(matching.length === 1, 'Dispatch source spec must match exactly one queue spec');
|
|
53
|
+
return { queue, spec: matching[0] };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function queueRequestsParallel(root, sourceView) {
|
|
57
|
+
return queueSpecForSource(root, sourceView).spec.execution?.parallel === true;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function fullCommitSha(value, label) {
|
|
61
|
+
requireValue(typeof value === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value), `${label} must be a full Git commit SHA`);
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function worktreeRevision(root, label) {
|
|
66
|
+
gitDirectory(root, label);
|
|
67
|
+
try {
|
|
68
|
+
return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
69
|
+
} catch {
|
|
70
|
+
throw new Error(`${label} must have a current Git revision`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Implementation may begin only after every declared dependency has reached
|
|
76
|
+
* its queue's done state. This is a scheduling guard, not completion evidence:
|
|
77
|
+
* validateQueue deliberately permits legacy done records without a receipt.
|
|
78
|
+
*/
|
|
79
|
+
export function assertImplementerDependenciesReady(root, sourceView, roles) {
|
|
80
|
+
if (!roles.some(role => role.name === 'implementer')) return;
|
|
81
|
+
const { queue, spec } = queueSpecForSource(root, sourceView);
|
|
82
|
+
const byId = new Map(queue.specs.map(item => [item.id, item]));
|
|
83
|
+
const pending = spec.depends_on.filter(id => byId.get(id)?.status !== 'done');
|
|
84
|
+
requireValue(pending.length === 0, `Implementer dispatch is blocked until dependencies are done: ${pending.join(', ')}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function attestWorkspace(workspace, workerRoot, roles, queueParallel) {
|
|
88
|
+
const defaultAccess = roles.every(role => role.name === 'reviewer') ? 'read-only' : 'mutating';
|
|
89
|
+
if (workspace === undefined) {
|
|
90
|
+
requireValue(!(queueParallel && defaultAccess === 'mutating'), 'Parallel queue execution needs an attested workspace');
|
|
91
|
+
return { workerRoot, coordinatorRoot: workerRoot, kind: 'serial', parallel: false, access: defaultAccess };
|
|
92
|
+
}
|
|
93
|
+
requireValue(isObject(workspace), 'Dispatch workspace must be an object');
|
|
94
|
+
requireValue(Object.keys(workspace).every(key => ['coordinatorRoot', 'parallel', 'access', 'baseRevision'].includes(key)), 'Dispatch workspace has an unknown field');
|
|
95
|
+
requireValue(workspace.access === 'mutating' || workspace.access === 'read-only', 'Dispatch workspace access must be mutating or read-only');
|
|
96
|
+
requireValue(workspace.parallel === undefined || typeof workspace.parallel === 'boolean', 'Dispatch workspace parallel must be a boolean when supplied');
|
|
97
|
+
const baseRevision = workspace.baseRevision === undefined ? undefined : fullCommitSha(workspace.baseRevision, 'Dispatch workspace baseRevision');
|
|
98
|
+
const coordinatorRoot = realDirectory(workspace.coordinatorRoot, 'Dispatch coordinator root');
|
|
99
|
+
const parallel = queueParallel || workspace.parallel === true;
|
|
100
|
+
if (workspace.access === 'read-only') {
|
|
101
|
+
requireValue(roles.every(role => role.name === 'reviewer'), 'Shared worktree dispatch is restricted to reviewers');
|
|
102
|
+
requireValue(workerRoot === coordinatorRoot, 'Shared read-only dispatch must use the coordinator worktree');
|
|
103
|
+
return { workerRoot, coordinatorRoot, kind: 'shared-readonly', parallel, access: workspace.access };
|
|
104
|
+
}
|
|
105
|
+
if (!parallel) {
|
|
106
|
+
if (baseRevision === undefined) return { workerRoot, coordinatorRoot, kind: 'serial', parallel, access: workspace.access };
|
|
107
|
+
const revision = worktreeRevision(workerRoot, 'Actual worker worktree');
|
|
108
|
+
requireValue(revision === baseRevision, `Actual worker worktree revision differs from declared base revision: expected ${baseRevision}, got ${revision}`);
|
|
109
|
+
return { workerRoot, coordinatorRoot, kind: 'serial', parallel, access: workspace.access, baseRevision, revision };
|
|
110
|
+
}
|
|
111
|
+
requireValue(workerRoot !== coordinatorRoot, 'Parallel mutation dispatch needs a distinct linked worker worktree');
|
|
112
|
+
const workerGit = gitDirectory(workerRoot, 'Actual worker worktree');
|
|
113
|
+
const coordinatorGit = gitDirectory(coordinatorRoot, 'Coordinator worktree');
|
|
114
|
+
requireValue(workerGit.commonDir === coordinatorGit.commonDir, 'Parallel mutation worktree must share the coordinator Git common directory');
|
|
115
|
+
requireValue(workerGit.gitDir !== coordinatorGit.gitDir, 'Parallel mutation worker must be a linked Git worktree, not the coordinator');
|
|
116
|
+
const branch = execFileSync('git', ['branch', '--show-current'], { cwd: workerRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
|
|
117
|
+
const revision = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: workerRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
118
|
+
if (baseRevision !== undefined) requireValue(revision === baseRevision, `Actual worker worktree revision differs from declared base revision: expected ${baseRevision}, got ${revision}`);
|
|
119
|
+
return { workerRoot, coordinatorRoot, kind: 'git-worktree', parallel, access: workspace.access, gitCommonDir: workerGit.commonDir, branch, revision, ...(baseRevision === undefined ? {} : { baseRevision }) };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function rejectReviewerSteering(value) {
|
|
123
|
+
if (Array.isArray(value)) return value.forEach(rejectReviewerSteering);
|
|
124
|
+
if (!isObject(value)) return;
|
|
125
|
+
for (const [key, nested] of Object.entries(value)) {
|
|
126
|
+
requireValue(!forbiddenDeliveryFields.has(key.replace(/[^a-z]/gi, '').toLowerCase()), `Dispatch source view cannot include reviewer steering: ${key}`);
|
|
127
|
+
rejectReviewerSteering(nested);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function decisionAnchor(id) { return `frontmatter.decisions.${id}`; }
|
|
132
|
+
|
|
133
|
+
function readBriefDecisions(root, brief) {
|
|
134
|
+
const text = readLocal(root, brief.path).toString('utf8');
|
|
135
|
+
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---/m.exec(text)?.[1];
|
|
136
|
+
const marker = /^decisions:\s*/m.exec(frontmatter ?? '');
|
|
137
|
+
if (!marker) return { decisions: [], limitations: [] };
|
|
138
|
+
const raw = frontmatter.slice(marker.index + marker[0].length);
|
|
139
|
+
if (!raw.startsWith('[')) return { decisions: [], limitations: [{ path: brief.path, sha256: brief.sha256, reason: 'decisions-unreadable' }] };
|
|
140
|
+
let quoted = false; let escaped = false; let depth = 0;
|
|
141
|
+
for (let index = 0; index < raw.length; index++) {
|
|
142
|
+
const char = raw[index];
|
|
143
|
+
if (quoted) { if (escaped) escaped = false; else if (char === '\\') escaped = true; else if (char === '"') quoted = false; continue; }
|
|
144
|
+
if (char === '"') { quoted = true; continue; }
|
|
145
|
+
if (char === '[') depth++;
|
|
146
|
+
if (char === ']') {
|
|
147
|
+
depth--;
|
|
148
|
+
if (depth === 0) {
|
|
149
|
+
try {
|
|
150
|
+
const decisions = JSON.parse(raw.slice(0, index + 1));
|
|
151
|
+
if (!Array.isArray(decisions)) throw new Error('not-array');
|
|
152
|
+
return { decisions, limitations: [] };
|
|
153
|
+
} catch { return { decisions: [], limitations: [{ path: brief.path, sha256: brief.sha256, reason: 'decisions-unreadable' }] }; }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return { decisions: [], limitations: [{ path: brief.path, sha256: brief.sha256, reason: 'decisions-unreadable' }] };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function classifyDecisions(root, brief, requestedIds = undefined) {
|
|
161
|
+
const parsed = readBriefDecisions(root, brief);
|
|
162
|
+
const selected = [];
|
|
163
|
+
const limitations = [...parsed.limitations];
|
|
164
|
+
const ids = new Set();
|
|
165
|
+
const requested = requestedIds === undefined ? undefined : new Set(requestedIds);
|
|
166
|
+
const counts = new Map();
|
|
167
|
+
for (const decision of parsed.decisions) {
|
|
168
|
+
if (isObject(decision) && nonempty(decision.id) && /^[A-Za-z0-9_-]{1,100}$/.test(decision.id)) counts.set(decision.id, (counts.get(decision.id) ?? 0) + 1);
|
|
169
|
+
}
|
|
170
|
+
for (const decision of parsed.decisions) {
|
|
171
|
+
if (!isObject(decision) || !nonempty(decision.id) || !/^[A-Za-z0-9_-]{1,100}$/.test(decision.id)) {
|
|
172
|
+
limitations.push({ path: brief.path, sha256: brief.sha256, reason: 'decision-id-unreadable' });
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
if (counts.get(decision.id) > 1) {
|
|
176
|
+
if (!ids.has(decision.id)) limitations.push({ path: brief.path, sha256: brief.sha256, anchor: decisionAnchor(decision.id), reason: 'decision-id-ambiguous' });
|
|
177
|
+
ids.add(decision.id);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
ids.add(decision.id);
|
|
181
|
+
if (requested !== undefined && !requested.has(decision.id)) continue;
|
|
182
|
+
const base = { path: brief.path, sha256: brief.sha256, anchor: decisionAnchor(decision.id) };
|
|
183
|
+
const answered = typeof decision.answer === 'string' ? nonempty(decision.answer) : decision.answer !== null && decision.answer !== undefined;
|
|
184
|
+
if (!decisionStates.has(decision.status)) {
|
|
185
|
+
limitations.push({ ...base, status: typeof decision.status === 'string' ? decision.status : null, reason: 'decision-state-unrecognized' });
|
|
186
|
+
} else if ((decision.status === 'clarified' || decision.status === 'assigned') && answered) {
|
|
187
|
+
selected.push({ ...base, decision });
|
|
188
|
+
} else {
|
|
189
|
+
limitations.push({ ...base, status: decision.status, reason: ['clarified', 'assigned'].includes(decision.status) ? `${decision.status}-decision-without-answer` : 'decision-not-settled' });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (requested !== undefined) for (const id of requested) {
|
|
193
|
+
if (!ids.has(id)) limitations.push({ path: brief.path, sha256: brief.sha256, anchor: decisionAnchor(id), reason: 'decision-referent-missing' });
|
|
194
|
+
}
|
|
195
|
+
return { decisions: selected, decisionLimitations: limitations };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function scopedDecisionIds(spec, briefPath) {
|
|
199
|
+
let selectorsSeen = false;
|
|
200
|
+
const ids = new Set();
|
|
201
|
+
for (const input of spec.verification.inputs) {
|
|
202
|
+
if (input.kind !== 'requirement' || relativePath(input.path) !== briefPath || input.scope?.decisionIds === undefined) continue;
|
|
203
|
+
selectorsSeen = true;
|
|
204
|
+
requireValue(Array.isArray(input.scope.decisionIds) && input.scope.decisionIds.every(id => nonempty(id) && /^[A-Za-z0-9_-]{1,100}$/.test(id)), 'Decision scope selectors must be valid IDs');
|
|
205
|
+
for (const id of input.scope.decisionIds) ids.add(id);
|
|
206
|
+
}
|
|
207
|
+
return selectorsSeen ? [...ids] : undefined;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function hashedSource(root, source, label, { anchor = false, allowAbsent = false } = {}) {
|
|
211
|
+
requireValue(isObject(source) && nonempty(source.path) && ((allowAbsent && source.state === 'absent') || isSha256(source.sha256)), `${label} needs a project-relative path and SHA-256`);
|
|
212
|
+
const sourcePath = relativePath(source.path);
|
|
213
|
+
if (source.state === 'absent') {
|
|
214
|
+
requireValue(allowAbsent && !anchor, `${label} cannot be absent`);
|
|
215
|
+
requireAbsent(root, sourcePath);
|
|
216
|
+
return { path: sourcePath, state: 'absent' };
|
|
217
|
+
}
|
|
218
|
+
if (anchor) requireValue(nonempty(source.anchor), `${label} needs an owning decision anchor`);
|
|
219
|
+
requireValue(sha256(readLocal(root, sourcePath)) === source.sha256, `Current ${label} bytes differ: ${sourcePath}`);
|
|
220
|
+
return anchor ? { path: sourcePath, anchor: source.anchor, sha256: source.sha256 } : { path: sourcePath, sha256: source.sha256 };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export function readInstallationManifest(root, manifestPath = '.joycraft/installation.json') {
|
|
224
|
+
manifestPath = relativePath(manifestPath);
|
|
225
|
+
const manifest = parseJson(readLocal(root, manifestPath), manifestPath);
|
|
226
|
+
requireValue(isObject(manifest) && manifest.schemaVersion === 1 && Array.isArray(manifest.files) && manifest.files.length > 0, 'Installation manifest must be schemaVersion 1 with exported files');
|
|
227
|
+
const files = new Map();
|
|
228
|
+
for (const entry of manifest.files) {
|
|
229
|
+
requireValue(isObject(entry) && nonempty(entry.path) && isSha256(entry.sha256), 'Installation manifest file needs path and SHA-256');
|
|
230
|
+
const filePath = relativePath(entry.path);
|
|
231
|
+
requireValue(!files.has(filePath), `Installation manifest repeats ${filePath}`);
|
|
232
|
+
requireValue(sha256(readLocal(root, filePath)) === entry.sha256, `Installed file differs from manifest: ${filePath}`);
|
|
233
|
+
files.set(filePath, entry.sha256);
|
|
234
|
+
}
|
|
235
|
+
return { path: manifestPath, files, sourceRevision: manifest.sourceRevision, harness: manifest.harness };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function readExpectedManifest(expectedManifestPath) {
|
|
239
|
+
requireValue(nonempty(expectedManifestPath) && path.isAbsolute(expectedManifestPath), 'Dispatch needs an explicit absolute pinned expected manifest path');
|
|
240
|
+
const manifest = parseJson(readFileSync(expectedManifestPath), expectedManifestPath);
|
|
241
|
+
requireValue(isObject(manifest) && manifest.schemaVersion === 1 && Array.isArray(manifest.files) && manifest.files.length > 0, 'Expected installation manifest must be schemaVersion 1 with exported files');
|
|
242
|
+
const files = new Map();
|
|
243
|
+
for (const entry of manifest.files) {
|
|
244
|
+
requireValue(isObject(entry) && nonempty(entry.path) && isSha256(entry.sha256), 'Expected manifest file needs path and SHA-256');
|
|
245
|
+
const filePath = relativePath(entry.path);
|
|
246
|
+
requireValue(!files.has(filePath), `Expected manifest repeats ${filePath}`);
|
|
247
|
+
files.set(filePath, entry.sha256);
|
|
248
|
+
}
|
|
249
|
+
return { path: expectedManifestPath, files, sourceRevision: manifest.sourceRevision, harness: manifest.harness };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function validateRoles(manifest, roles) {
|
|
253
|
+
requireValue(Array.isArray(roles) && roles.length > 0, 'Dispatch needs at least one worker role');
|
|
254
|
+
const names = new Set();
|
|
255
|
+
return roles.map(role => {
|
|
256
|
+
requireValue(isObject(role) && nonempty(role.name) && !names.has(role.name), 'Worker roles need unique names');
|
|
257
|
+
requireValue(['implementer', 'reviewer'].includes(role.name), `Unsupported worker role: ${role.name}`);
|
|
258
|
+
names.add(role.name);
|
|
259
|
+
requireValue(nonempty(role.skillPath), `Worker role ${role.name} needs a skill path`);
|
|
260
|
+
const requiredFiles = [role.skillPath, ...(role.referencePaths ?? []), ...(role.runtimePaths ?? [])];
|
|
261
|
+
requireValue(requiredFiles.every(nonempty), `Worker role ${role.name} has an invalid delivery path`);
|
|
262
|
+
const files = requiredFiles.map(relativePath);
|
|
263
|
+
for (const file of files) requireValue(manifest.files.has(file), `Worker role ${role.name} is not attested by the installation manifest: ${file}`);
|
|
264
|
+
const requiredCapabilities = role.requiredCapabilities ?? [];
|
|
265
|
+
requireValue(Array.isArray(requiredCapabilities) && requiredCapabilities.every(nonempty), `Worker role ${role.name} has invalid required capabilities`);
|
|
266
|
+
return { name: role.name, files, requiredCapabilities: [...new Set(requiredCapabilities)] };
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function validateSourceView(root, sourceView) {
|
|
271
|
+
requireValue(isObject(sourceView), 'Dispatch needs a bounded current source view');
|
|
272
|
+
const { decisions: suppliedDecisions, decisionLimitations: suppliedLimitations, ...untrusted } = sourceView;
|
|
273
|
+
rejectReviewerSteering(untrusted);
|
|
274
|
+
const brief = hashedSource(root, sourceView.brief, 'brief');
|
|
275
|
+
const spec = hashedSource(root, sourceView.spec, 'spec');
|
|
276
|
+
const queue = hashedSource(root, sourceView.queue, 'queue');
|
|
277
|
+
requireValue(Array.isArray(sourceView.inputs), 'Dispatch source view needs current verification inputs');
|
|
278
|
+
const inputs = sourceView.inputs.map((input, index) => hashedSource(root, input, `input ${index + 1}`, { allowAbsent: true }));
|
|
279
|
+
requireValue(sourceView.plannedMissing === undefined || (Array.isArray(sourceView.plannedMissing) && sourceView.plannedMissing.every(item => isObject(item) && nonempty(item.path) && item.reason === 'not-created-yet')), 'Invalid planned missing input disclosure');
|
|
280
|
+
requireValue(Array.isArray(suppliedDecisions), 'Dispatch source view needs scoped owning decision records');
|
|
281
|
+
requireValue(sourceView.decisionScope === undefined || sourceView.decisionScope === null || (Array.isArray(sourceView.decisionScope) && sourceView.decisionScope.every(id => nonempty(id) && /^[A-Za-z0-9_-]{1,100}$/.test(id))), 'Dispatch decision scope must contain valid IDs');
|
|
282
|
+
const decisionScope = sourceView.decisionScope === null ? undefined : sourceView.decisionScope;
|
|
283
|
+
const current = classifyDecisions(root, brief, decisionScope);
|
|
284
|
+
const currentByAnchor = new Map(current.decisions.map(decision => [decision.anchor, decision]));
|
|
285
|
+
const decisions = suppliedDecisions.map((decision, index) => {
|
|
286
|
+
requireValue(isObject(decision) && isObject(decision.decision), `Decision ${index + 1} needs an exact current record`);
|
|
287
|
+
const pointer = hashedSource(root, decision, `decision ${index + 1}`, { anchor: true });
|
|
288
|
+
requireValue(pointer.path === brief.path, `Decision ${index + 1} must be anchored in the owning brief`);
|
|
289
|
+
const actual = currentByAnchor.get(pointer.anchor);
|
|
290
|
+
requireValue(actual !== undefined, `Decision referent is missing, unsettled, or unreadable: ${pointer.anchor}`);
|
|
291
|
+
requireValue(canonical(actual.decision) === canonical(decision.decision), `Decision record differs from current brief: ${pointer.anchor}`);
|
|
292
|
+
return actual;
|
|
293
|
+
});
|
|
294
|
+
requireValue(canonical(decisions) === canonical(current.decisions), 'Dispatch decision records must exactly match current selected decision records');
|
|
295
|
+
requireValue(Array.isArray(suppliedLimitations ?? current.decisionLimitations), 'Dispatch decision limitations must be an array');
|
|
296
|
+
requireValue(canonical(suppliedLimitations ?? current.decisionLimitations) === canonical(current.decisionLimitations), 'Dispatch decision limitations differ from the current brief');
|
|
297
|
+
return { brief, spec, queue, inputs, plannedMissing: sourceView.plannedMissing ?? [], decisions, decisionScope: decisionScope ?? null, decisionLimitations: current.decisionLimitations, sourceAuthority: sourceView.sourceAuthority ?? null };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function validateReportDestination(root, destination) {
|
|
301
|
+
requireValue(nonempty(destination), 'Dispatch needs a writable report destination claim');
|
|
302
|
+
const reportPath = relativePath(destination);
|
|
303
|
+
const target = path.join(root, reportPath);
|
|
304
|
+
const parent = path.dirname(target);
|
|
305
|
+
requireValue(existsSync(parent), `Report destination directory does not exist: ${path.posix.dirname(reportPath)}`);
|
|
306
|
+
accessSync(parent, constants.W_OK);
|
|
307
|
+
return reportPath;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function rejectSharedSourceOverwrite(workspace, sourceView, reportDestination) {
|
|
311
|
+
if (workspace.kind !== 'shared-readonly') return;
|
|
312
|
+
const frozen = new Set([sourceView.brief.path, sourceView.spec.path, sourceView.queue.path, ...sourceView.inputs.map(input => input.path), ...sourceView.plannedMissing.map(input => input.path)]);
|
|
313
|
+
requireValue(!frozen.has(reportDestination), 'Shared read-only report destination must not overwrite a declared source input');
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function validateClaims(claims, roles, reportDestination, availableCapabilities = undefined) {
|
|
317
|
+
requireValue(isObject(claims) && Array.isArray(claims.capabilities), 'Dispatch needs explicit capability claims');
|
|
318
|
+
const claimed = new Set(claims.capabilities);
|
|
319
|
+
requireValue([...claimed].every(nonempty), 'Capability claims must be nonempty strings');
|
|
320
|
+
requireValue(claims.reportDestination === reportDestination, 'Report destination must be the claimed writable destination');
|
|
321
|
+
const required = new Set(['filesystem:read', 'filesystem:write-report']);
|
|
322
|
+
for (const role of roles) for (const capability of role.requiredCapabilities) required.add(capability);
|
|
323
|
+
for (const capability of required) requireValue(claimed.has(capability), `Missing required capability claim: ${capability}`);
|
|
324
|
+
if (availableCapabilities !== undefined) {
|
|
325
|
+
requireValue(Array.isArray(availableCapabilities), 'Available capabilities must be an array when provided');
|
|
326
|
+
const available = new Set(availableCapabilities);
|
|
327
|
+
for (const capability of required) requireValue(available.has(capability), `Worker cannot provide claimed capability: ${capability}`);
|
|
328
|
+
}
|
|
329
|
+
return [...required].sort();
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Validate delivery for a native worker adapter. This is intentionally only a
|
|
334
|
+
* preflight: callers dispatch in their host and completion remains the sole
|
|
335
|
+
* acceptance writer.
|
|
336
|
+
*/
|
|
337
|
+
export function preflightDispatch(request, { availableCapabilities } = {}) {
|
|
338
|
+
requireValue(isObject(request) && request.schemaVersion === 1, 'Dispatch request must use schemaVersion 1');
|
|
339
|
+
const root = workerDirectory(request.workerRoot);
|
|
340
|
+
const manifest = readInstallationManifest(root, request.manifestPath);
|
|
341
|
+
const roles = validateRoles(manifest, request.delivery?.roles);
|
|
342
|
+
if (request.expectedManifestPath !== undefined) {
|
|
343
|
+
const expected = readExpectedManifest(request.expectedManifestPath);
|
|
344
|
+
for (const role of roles) for (const file of role.files) {
|
|
345
|
+
requireValue(expected.files.has(file), `Pinned expected installation does not include ${file}`);
|
|
346
|
+
requireValue(expected.files.get(file) === manifest.files.get(file), `Installed role/shared file differs from pinned expected installation: ${file}`);
|
|
347
|
+
}
|
|
348
|
+
if (expected.sourceRevision !== undefined) requireValue(manifest.sourceRevision === expected.sourceRevision, 'Installed source revision differs from pinned expected installation');
|
|
349
|
+
}
|
|
350
|
+
const sourceView = validateSourceView(root, request.delivery?.sourceView);
|
|
351
|
+
assertImplementerDependenciesReady(root, sourceView, roles);
|
|
352
|
+
const workspace = attestWorkspace(request.workspace, root, roles, queueRequestsParallel(root, sourceView));
|
|
353
|
+
const reportDestination = validateReportDestination(root, request.delivery?.reportDestination);
|
|
354
|
+
rejectSharedSourceOverwrite(workspace, sourceView, reportDestination);
|
|
355
|
+
const requiredCapabilities = validateClaims(request.claims, roles, reportDestination, availableCapabilities);
|
|
356
|
+
return {
|
|
357
|
+
schemaVersion: 1,
|
|
358
|
+
workerRoot: root,
|
|
359
|
+
workspace,
|
|
360
|
+
manifestPath: manifest.path,
|
|
361
|
+
roles,
|
|
362
|
+
sourceView,
|
|
363
|
+
reportDestination,
|
|
364
|
+
requiredCapabilities,
|
|
365
|
+
effectiveModel: nonempty(request.effectiveModel) ? request.effectiveModel : unknown,
|
|
366
|
+
effectiveEffort: nonempty(request.effectiveEffort) ? request.effectiveEffort : unknown,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function rolePaths(role, root) {
|
|
371
|
+
requireValue(['implementer', 'reviewer'].includes(role), 'Role must be implementer or reviewer');
|
|
372
|
+
const suffix = `joycraft-${role === 'implementer' ? 'implement' : 'verify'}/SKILL.md`;
|
|
373
|
+
const manifest = readInstallationManifest(root);
|
|
374
|
+
// A multi-host install has one skill tree per discovery path. Workers read the
|
|
375
|
+
// primary host's copy: .claude/skills for Claude Code, else .agents/skills.
|
|
376
|
+
const tree = manifest.harness === 'claude' ? '.claude/skills/' : '.agents/skills/';
|
|
377
|
+
const pick = name => {
|
|
378
|
+
const all = [...manifest.files.keys()].filter(file => file.endsWith(name));
|
|
379
|
+
return all.length > 1 ? all.filter(file => file.startsWith(tree)) : all;
|
|
380
|
+
};
|
|
381
|
+
const matches = pick(suffix);
|
|
382
|
+
requireValue(matches.length === 1, `Installation manifest must contain exactly one ${suffix}`);
|
|
383
|
+
const testing = pick('joycraft-testing/SKILL.md');
|
|
384
|
+
requireValue(testing.length === 1, 'Installation manifest must contain exactly one joycraft-testing skill');
|
|
385
|
+
return {
|
|
386
|
+
name: role,
|
|
387
|
+
skillPath: matches[0],
|
|
388
|
+
referencePaths: [testing[0], '.joycraft/references/testing.md', '.joycraft/references/completion.md', '.joycraft/references/dispatch.md', '.joycraft/references/worktrees.md', '.joycraft/contracts/types.d.ts'],
|
|
389
|
+
runtimePaths: ['.joycraft/runtime/completion.mjs', '.joycraft/runtime/identity.mjs', '.joycraft/runtime/evidence.mjs', '.joycraft/runtime/dispatch-preflight.mjs', '.joycraft/runtime/dispatch-start.mjs', '.joycraft/runtime/scope.mjs'],
|
|
390
|
+
requiredCapabilities: role === 'reviewer' ? ['agent:separate-context'] : [],
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function source(root, file) { return { path: file, sha256: sha256(readLocal(root, file)) }; }
|
|
395
|
+
|
|
396
|
+
/** Generate a bounded native-host packet from current queue/spec sources. */
|
|
397
|
+
export function prepareDispatch({ workerRoot, coordinatorRoot, parallel, access, baseRevision, expectedManifestPath, queuePath, specId, role, implementerSessionId, implementerActor, briefPath, outPath, effectiveModel, effectiveEffort, availableCapabilities }) {
|
|
398
|
+
const root = workerDirectory(workerRoot);
|
|
399
|
+
queuePath = relativePath(queuePath);
|
|
400
|
+
requireValue(Number.isSafeInteger(specId) && specId >= 0, 'Spec ID must be a nonnegative integer');
|
|
401
|
+
requireValue(nonempty(implementerSessionId), 'Dispatch needs the actual implementer session identity');
|
|
402
|
+
if (implementerActor !== undefined) {
|
|
403
|
+
implementerActor = validateNativeActor(implementerActor, 'Dispatch implementer actor');
|
|
404
|
+
requireValue(implementerActor.sessionId === implementerSessionId, 'Dispatch implementer actor sessionId must match implementer session');
|
|
405
|
+
}
|
|
406
|
+
const state = readQueue({ root, queuePath, specId });
|
|
407
|
+
const inferredBrief = path.posix.join(path.posix.dirname(path.posix.dirname(queuePath)), 'brief.md');
|
|
408
|
+
const actualBrief = relativePath(briefPath ?? inferredBrief);
|
|
409
|
+
const existingInputs = [];
|
|
410
|
+
const plannedMissing = [];
|
|
411
|
+
for (const input of state.spec.verification.inputs) {
|
|
412
|
+
if (input.state === 'absent') {
|
|
413
|
+
// Before implementation, a planned removal can still be present. Review
|
|
414
|
+
// binds the resulting absence; preparation never performs the deletion.
|
|
415
|
+
if (role === 'implementer') {
|
|
416
|
+
try { existingInputs.push(source(root, input.path)); continue; }
|
|
417
|
+
catch (error) { if (error?.code !== 'ENOENT') throw error; }
|
|
418
|
+
}
|
|
419
|
+
requireAbsent(root, input.path);
|
|
420
|
+
existingInputs.push({ path: relativePath(input.path), state: 'absent' });
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
try { existingInputs.push(source(root, input.path)); } catch (error) {
|
|
424
|
+
if (role === 'implementer' && error?.code === 'ENOENT') plannedMissing.push({ path: relativePath(input.path), reason: 'not-created-yet' });
|
|
425
|
+
else throw error;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
const brief = source(root, actualBrief);
|
|
429
|
+
const decisionScope = scopedDecisionIds(state.spec, actualBrief);
|
|
430
|
+
const decisionState = classifyDecisions(root, brief, decisionScope);
|
|
431
|
+
const sourceView = {
|
|
432
|
+
brief, spec: source(root, state.specPath), queue: source(root, queuePath),
|
|
433
|
+
inputs: existingInputs, plannedMissing, decisionScope: decisionScope ?? null, ...decisionState,
|
|
434
|
+
};
|
|
435
|
+
const reportDestination = path.posix.join(path.posix.dirname(queuePath), `review-${specId}.report.json`);
|
|
436
|
+
const request = {
|
|
437
|
+
schemaVersion: 1, workerRoot: root, expectedManifestPath,
|
|
438
|
+
delivery: { roles: [rolePaths(role, root)], sourceView, reportDestination },
|
|
439
|
+
claims: { capabilities: availableCapabilities, reportDestination },
|
|
440
|
+
effectiveModel, effectiveEffort,
|
|
441
|
+
};
|
|
442
|
+
if (coordinatorRoot !== undefined || parallel !== undefined || access !== undefined || baseRevision !== undefined) {
|
|
443
|
+
request.workspace = {
|
|
444
|
+
coordinatorRoot: coordinatorRoot ?? root,
|
|
445
|
+
...(parallel === undefined ? {} : { parallel }),
|
|
446
|
+
access: access ?? (role === 'reviewer' ? 'read-only' : 'mutating'),
|
|
447
|
+
...(baseRevision === undefined ? {} : { baseRevision }),
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
requireValue(Array.isArray(availableCapabilities), 'Prepare needs observed host capabilities; unknown capabilities hold dependent acceptance');
|
|
451
|
+
const prepared = preflightDispatch(request, { availableCapabilities });
|
|
452
|
+
const subject = role === 'reviewer' ? snapshot({ root, queuePath, specId }) : null;
|
|
453
|
+
const packet = {
|
|
454
|
+
schemaVersion: 1, ...prepared, role, implementerSessionId, ...(implementerActor === undefined ? {} : { implementerActor }), subject,
|
|
455
|
+
readFirst: prepared.roles[0].files,
|
|
456
|
+
outputContract: { reportPath: reportDestination, schemaVersion: 1, completeWith: 'node .joycraft/runtime/completion.mjs finalize-review --queue <queue-path> --spec <id> --report <report-path>' },
|
|
457
|
+
nativePrompt: role === 'reviewer' ? 'Read the listed files first. Review current raw sources and report observed evidence only. Do not infer an expected verdict or reasoning. Return the schema-v1 report at the declared report path.' : 'Read the listed files first. Implement only the current raw task sources. Do not certify acceptance; preserve planned missing inputs as work to create, then prepare an independent review after committing.',
|
|
458
|
+
};
|
|
459
|
+
// The project's recorded review-loop tools and commands, so workers use the same setup.
|
|
460
|
+
const reviewLoop = reviewLoopSection(root);
|
|
461
|
+
if (reviewLoop) packet.reviewLoop = { path: 'AGENTS.md', section: reviewLoop };
|
|
462
|
+
if (role === 'reviewer' && implementerActor !== undefined) {
|
|
463
|
+
// The native host supplies this only after creating the reviewer. Do not
|
|
464
|
+
// synthesize an actor record in a pre-dispatch packet.
|
|
465
|
+
packet.reviewerIdentityRequest = { distinctFrom: implementerActor };
|
|
466
|
+
}
|
|
467
|
+
// Hooks bind only hash-checked pointers today. The packet retains exact raw
|
|
468
|
+
// decision records for workers; do not widen this hook interface here.
|
|
469
|
+
packet.hookSourceView = { brief: prepared.sourceView.brief, decisions: prepared.sourceView.decisions.map(({ path, anchor, sha256 }) => ({ path, anchor, sha256 })), spec: prepared.sourceView.spec, queue: prepared.sourceView.queue, inputs: prepared.sourceView.inputs };
|
|
470
|
+
packet.hookSourceViewHash = sha256(canonical(packet.hookSourceView));
|
|
471
|
+
if (outPath !== undefined) {
|
|
472
|
+
const output = path.resolve(outPath);
|
|
473
|
+
requireValue(!existsSync(output), `Packet output already exists: ${output}`);
|
|
474
|
+
writeFileSync(output, `${JSON.stringify(packet, null, 2)}\n`, { flag: 'wx' });
|
|
475
|
+
}
|
|
476
|
+
return packet;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** Thin mapping layer for Codex, Claude, Pi, OMP, and Copilot native adapters. */
|
|
480
|
+
export function nativeDispatch(request, native = {}) {
|
|
481
|
+
const prepared = preflightDispatch(request, { availableCapabilities: native.availableCapabilities });
|
|
482
|
+
return {
|
|
483
|
+
...prepared,
|
|
484
|
+
effectiveModel: nonempty(native.effectiveModel) ? native.effectiveModel : prepared.effectiveModel,
|
|
485
|
+
effectiveEffort: nonempty(native.effectiveEffort) ? native.effectiveEffort : prepared.effectiveEffort,
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Validate a returned report without accepting it or changing queue/spec status. */
|
|
490
|
+
export async function checkDispatchedReport({ workerRoot, queuePath, specId, reportPath }) {
|
|
491
|
+
return checkReport({ root: workerDirectory(workerRoot), queuePath, specId, reportPath });
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function argumentsFor(argv) {
|
|
495
|
+
const [command, ...args] = argv;
|
|
496
|
+
requireValue(['preflight', 'prepare', 'check-report'].includes(command), 'Usage: dispatch-preflight.mjs preflight --request <request.json> | prepare --worker-root <root> --expected-manifest <manifest> --queue <path> --spec <id> --role implementer|reviewer --implementer-session <id> --out <packet.json> [--coordinator <root> --parallel true|false --access mutating|read-only --base-revision <full-commit-sha>] [--implementer-host <host> --implementer-agent <host-issued-id>] [--brief <path>] | check-report --worker-root <root> --queue <path> --spec <id> --report <report-path>');
|
|
497
|
+
const flags = {};
|
|
498
|
+
for (let i = 0; i < args.length; i += 2) {
|
|
499
|
+
requireValue(nonempty(args[i]) && nonempty(args[i + 1]) && flags[args[i]] === undefined, `Invalid or duplicate argument: ${args[i]}`);
|
|
500
|
+
flags[args[i]] = args[i + 1];
|
|
501
|
+
}
|
|
502
|
+
return { command, flags };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
506
|
+
const { command, flags } = argumentsFor(argv);
|
|
507
|
+
if (command === 'preflight') {
|
|
508
|
+
requireValue(Object.keys(flags).length === 1 && flags['--request'], 'preflight requires --request <request.json>');
|
|
509
|
+
const requestPath = path.resolve(flags['--request']);
|
|
510
|
+
const request = parseJson(readFileSync(requestPath), requestPath);
|
|
511
|
+
const result = preflightDispatch(request);
|
|
512
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
513
|
+
return result;
|
|
514
|
+
}
|
|
515
|
+
if (command === 'prepare') {
|
|
516
|
+
const allowed = new Set(['--worker-root', '--expected-manifest', '--queue', '--spec', '--role', '--implementer-session', '--implementer-host', '--implementer-agent', '--out', '--brief', '--capabilities', '--coordinator', '--parallel', '--access', '--base-revision']);
|
|
517
|
+
requireValue(Object.keys(flags).every(flag => allowed.has(flag)) && ['--worker-root', '--expected-manifest', '--queue', '--spec', '--role', '--implementer-session', '--out', '--capabilities'].every(flag => flags[flag]), 'prepare requires worker root, expected manifest, queue, spec, role, implementer session, observed capabilities, and output');
|
|
518
|
+
requireValue(flags['--implementer-agent'] === undefined || flags['--implementer-host'] !== undefined, 'prepare needs an implementer host with a host-issued agent ID');
|
|
519
|
+
requireValue(flags['--parallel'] === undefined || ['true', 'false'].includes(flags['--parallel']), 'prepare --parallel must be true or false');
|
|
520
|
+
requireValue(/^(?:0|[1-9]\d*)$/.test(flags['--spec']), 'Spec ID must be a nonnegative integer');
|
|
521
|
+
const implementerActor = flags['--implementer-host'] === undefined ? undefined : { host: flags['--implementer-host'], sessionId: flags['--implementer-session'], ...(flags['--implementer-agent'] === undefined ? {} : { agentId: flags['--implementer-agent'] }) };
|
|
522
|
+
const result = prepareDispatch({ workerRoot: flags['--worker-root'], coordinatorRoot: flags['--coordinator'], parallel: flags['--parallel'] === undefined ? undefined : flags['--parallel'] === 'true', access: flags['--access'], baseRevision: flags['--base-revision'], expectedManifestPath: flags['--expected-manifest'], queuePath: flags['--queue'], specId: Number(flags['--spec']), role: flags['--role'], implementerSessionId: flags['--implementer-session'], implementerActor, briefPath: flags['--brief'], outPath: flags['--out'], availableCapabilities: flags['--capabilities'].split(',').filter(Boolean) });
|
|
523
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
524
|
+
return result;
|
|
525
|
+
}
|
|
526
|
+
requireValue(Object.keys(flags).length === 4 && flags['--worker-root'] && flags['--queue'] && flags['--spec'] && flags['--report'], 'check-report requires --worker-root, --queue, --spec, and --report');
|
|
527
|
+
requireValue(/^(?:0|[1-9]\d*)$/.test(flags['--spec']), 'Spec ID must be a nonnegative integer');
|
|
528
|
+
const result = await checkDispatchedReport({ workerRoot: flags['--worker-root'], queuePath: flags['--queue'], specId: Number(flags['--spec']), reportPath: flags['--report'] });
|
|
529
|
+
process.stdout.write(`${JSON.stringify({ ok: true, acceptedReport: result.acceptedReport }, null, 2)}\n`);
|
|
530
|
+
return result;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
|
534
|
+
main().catch(error => { process.stderr.write(`Dispatch stopped: ${error.message}\n`); process.exitCode = 1; });
|
|
535
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { prepareDispatch } from './dispatch-preflight.mjs';
|
|
6
|
+
import { localPath, readQueue, relativePath, requireValue, validateNativeActor } from './identity.mjs';
|
|
7
|
+
|
|
8
|
+
// The native hook runtime is optional; without it, startup takes the manual path.
|
|
9
|
+
async function hookRuntime() {
|
|
10
|
+
try { return { ...await import('./hooks/context.mjs'), ...await import('./hooks/cli.mjs') }; }
|
|
11
|
+
catch (error) { if (error?.code === 'ERR_MODULE_NOT_FOUND') return null; throw error; }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Start in the actual worker after the host has supplied its identity.
|
|
15
|
+
* Adapters supply native event fields; CLI users relay observed host identity.
|
|
16
|
+
* Neither interface authenticates a human or invents missing prompt history. */
|
|
17
|
+
export async function startDispatch(options, nativeEvent) {
|
|
18
|
+
const root = realpathSync(options.workerRoot);
|
|
19
|
+
requireValue(nativeEvent && typeof nativeEvent.cwd === 'string' && path.isAbsolute(nativeEvent.cwd)
|
|
20
|
+
&& realpathSync(nativeEvent.cwd) === root, 'Task startup needs the actual native worker cwd');
|
|
21
|
+
validateNativeActor({ host: options.nativeHost ?? 'claude', sessionId: nativeEvent.session_id,
|
|
22
|
+
...(nativeEvent.agent_id === undefined ? {} : { agentId: nativeEvent.agent_id }) }, 'Current native worker');
|
|
23
|
+
const outPath = relativePath(options.outPath);
|
|
24
|
+
const output = localPath(root, outPath, true);
|
|
25
|
+
requireValue(!existsSync(output), `Packet output already exists: ${outPath}; use a fresh packet path`);
|
|
26
|
+
// Startup owns the packet directory: it creates a missing one under .joycraft/local/ and checks it is
|
|
27
|
+
// git-ignored, so the worker never chains its own mkdir or git check with startup (a worktree-isolated
|
|
28
|
+
// host refuses git inside a compound command).
|
|
29
|
+
const parentPath = path.posix.dirname(outPath);
|
|
30
|
+
if (!existsSync(path.dirname(output))) {
|
|
31
|
+
requireValue(parentPath === '.joycraft/local' || parentPath.startsWith('.joycraft/local/'),
|
|
32
|
+
`Packet output parent does not exist: ${parentPath}; use a .joycraft/local/ path, which startup creates`);
|
|
33
|
+
mkdirSync(path.dirname(output), { recursive: true, mode: 0o700 });
|
|
34
|
+
// Self-ignoring, like the hook state directory, so a project without a root ignore rule still passes.
|
|
35
|
+
writeFileSync(path.join(path.dirname(output), '.gitignore'), '*\n', { flag: 'wx', mode: 0o600 });
|
|
36
|
+
}
|
|
37
|
+
const parent = realpathSync(path.dirname(output));
|
|
38
|
+
const rel = path.relative(root, parent);
|
|
39
|
+
requireValue(rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel), 'Packet output parent must stay inside the worker root');
|
|
40
|
+
requireValue(gitIgnored(root, outPath), `Packet output must be git-ignored so it never becomes a scope path: ${outPath}; use .joycraft/local/packets/`);
|
|
41
|
+
readQueue({ root, queuePath: options.queuePath, specId: options.specId });
|
|
42
|
+
requireValue(options.role === 'implementer' || options.role === 'reviewer', 'Task startup role must be implementer or reviewer');
|
|
43
|
+
// Change scope is opt-in per spec: startup never writes it, and a reviewer
|
|
44
|
+
// without one reviews against the verification inputs alone.
|
|
45
|
+
const packet = prepareDispatch({ ...options, outPath: output });
|
|
46
|
+
const runtime = await hookRuntime();
|
|
47
|
+
const config = runtime ? await runtime.readConfig(root) : { enabled: false };
|
|
48
|
+
const hooks = config.enabled
|
|
49
|
+
? { enabled: true, ...await runtime.bindPreparedSource({ event: nativeEvent, packetPath: outPath }) }
|
|
50
|
+
: { enabled: false, eligible: false, reason: runtime ? 'hooks-disabled' : 'hooks-not-installed' };
|
|
51
|
+
return { schemaVersion: 1, packetPath: outPath, packet, hooks,
|
|
52
|
+
ready: !config.enabled || hooks.eligible === true };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function gitIgnored(root, relative) {
|
|
56
|
+
try {
|
|
57
|
+
execFileSync('git', ['check-ignore', '-q', '--', relative], { cwd: root, stdio: 'ignore' });
|
|
58
|
+
return true;
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error.status === 1) return false;
|
|
61
|
+
throw new Error(`Could not check whether ${relative} is git-ignored`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
66
|
+
const flags = {};
|
|
67
|
+
const allowed = new Set(['--worker-root', '--expected-manifest', '--queue', '--spec', '--role', '--implementer-session',
|
|
68
|
+
'--implementer-host', '--implementer-agent', '--out', '--brief', '--capabilities', '--coordinator', '--parallel',
|
|
69
|
+
'--access', '--base-revision', '--native-session', '--native-agent', '--native-host']);
|
|
70
|
+
for (let index = 0; index < argv.length; index += 2) {
|
|
71
|
+
const key = argv[index]; const value = argv[index + 1];
|
|
72
|
+
requireValue(allowed.has(key) && typeof value === 'string' && value && !value.startsWith('--') && flags[key] === undefined,
|
|
73
|
+
`Invalid startup argument: ${key}; use named flags with literal values`);
|
|
74
|
+
flags[key] = value;
|
|
75
|
+
}
|
|
76
|
+
for (const key of ['--worker-root', '--expected-manifest', '--queue', '--spec', '--role', '--implementer-session', '--out', '--capabilities', '--native-session']) {
|
|
77
|
+
requireValue(flags[key], `Task startup requires ${key}; native identities must come from the active host`);
|
|
78
|
+
}
|
|
79
|
+
requireValue(/^(?:0|[1-9]\d*)$/.test(flags['--spec']), 'Spec ID must be a nonnegative integer');
|
|
80
|
+
requireValue(flags['--parallel'] === undefined || ['true', 'false'].includes(flags['--parallel']), '--parallel must be true or false');
|
|
81
|
+
requireValue(!flags['--implementer-agent'] || flags['--implementer-host'], 'A native implementer agent ID needs its host');
|
|
82
|
+
const result = await startDispatch({ workerRoot: flags['--worker-root'], expectedManifestPath: flags['--expected-manifest'],
|
|
83
|
+
queuePath: flags['--queue'], specId: Number(flags['--spec']), role: flags['--role'], implementerSessionId: flags['--implementer-session'],
|
|
84
|
+
implementerActor: flags['--implementer-host'] ? { host: flags['--implementer-host'], sessionId: flags['--implementer-session'],
|
|
85
|
+
...(flags['--implementer-agent'] ? { agentId: flags['--implementer-agent'] } : {}) } : undefined,
|
|
86
|
+
outPath: flags['--out'], briefPath: flags['--brief'], availableCapabilities: flags['--capabilities'].split(',').filter(Boolean),
|
|
87
|
+
coordinatorRoot: flags['--coordinator'], parallel: flags['--parallel'] === undefined ? undefined : flags['--parallel'] === 'true',
|
|
88
|
+
access: flags['--access'], baseRevision: flags['--base-revision'], nativeHost: flags['--native-host'],
|
|
89
|
+
}, { cwd: flags['--worker-root'], session_id: flags['--native-session'], ...(flags['--native-agent'] ? { agent_id: flags['--native-agent'] } : {}) });
|
|
90
|
+
const { packet, ...status } = result;
|
|
91
|
+
process.stdout.write(`${JSON.stringify(status, null, 2)}\n`);
|
|
92
|
+
if (!result.ready) process.exitCode = 2;
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
|
97
|
+
main().catch(error => { process.stderr.write(`Task startup stopped: ${error.message}\n`); process.exitCode = 1; });
|
|
98
|
+
}
|