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,463 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { boundQueueForSubject, briefDecisionRecords, canonical, isObject, isSha256, localPath, nonempty, normalizedQueueForSubject, parseJson, readLocal, readQueue, relativePath, requireValue, scopedRequirementForSubject, sha256, specStatus, subjectIdentity, validateIndependentReview } from './identity.mjs';
|
|
6
|
+
import { validateEvidence } from './evidence.mjs';
|
|
7
|
+
import { validateOwnerAcceptance } from './completion.mjs';
|
|
8
|
+
|
|
9
|
+
const featureName = value => {
|
|
10
|
+
requireValue(typeof value === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(value), 'Feature must be a lowercase slug');
|
|
11
|
+
return value;
|
|
12
|
+
};
|
|
13
|
+
const archivePath = feature => `docs/archive/${feature}`;
|
|
14
|
+
const featurePath = feature => `docs/features/${feature}`;
|
|
15
|
+
|
|
16
|
+
function localDirectory(root, relative) {
|
|
17
|
+
relative = relativePath(relative);
|
|
18
|
+
let current = realpathSync(root);
|
|
19
|
+
for (const part of relative.split('/')) {
|
|
20
|
+
current = path.join(current, part);
|
|
21
|
+
const stat = lstatSync(current);
|
|
22
|
+
requireValue(!stat.isSymbolicLink() && stat.isDirectory(), `Not a plain directory: ${relative}`);
|
|
23
|
+
}
|
|
24
|
+
return current;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function projectTarget(root, relative) {
|
|
28
|
+
relative = relativePath(relative);
|
|
29
|
+
let current = realpathSync(root);
|
|
30
|
+
for (const part of relative.split('/')) {
|
|
31
|
+
current = path.join(current, part);
|
|
32
|
+
if (!existsSync(current)) return path.join(realpathSync(root), relative);
|
|
33
|
+
requireValue(!lstatSync(current).isSymbolicLink(), `Symlink paths are not supported: ${relative}`);
|
|
34
|
+
}
|
|
35
|
+
return current;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function plainDirectory(root, relative) {
|
|
39
|
+
const target = localDirectory(root, relative);
|
|
40
|
+
for (const name of readdirSync(target)) {
|
|
41
|
+
const child = `${relative}/${name}`;
|
|
42
|
+
const stat = lstatSync(path.join(target, name));
|
|
43
|
+
requireValue(!stat.isSymbolicLink(), `Symlink paths are not supported: ${child}`);
|
|
44
|
+
if (stat.isDirectory()) plainDirectory(root, child);
|
|
45
|
+
else requireValue(stat.isFile(), `Not a plain file: ${child}`);
|
|
46
|
+
}
|
|
47
|
+
return target;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function parseAttestation(root, input) {
|
|
51
|
+
const attestation = typeof input === 'string' ? parseJson(readLocal(root, input), input) : input;
|
|
52
|
+
requireValue(isObject(attestation) && attestation.schemaVersion === 1 && attestation.phase === 'session-end', 'Archive needs a schemaVersion 1 session-end attestation');
|
|
53
|
+
requireValue(isObject(attestation.host) && nonempty(attestation.host.sessionId) && attestation.host.quiescent === true, 'Host must attest the session is quiescent');
|
|
54
|
+
requireValue(Array.isArray(attestation.host.activeWorkers) && attestation.host.activeWorkers.length === 0 && Array.isArray(attestation.host.dependentWork) && attestation.host.dependentWork.length === 0, 'Active workers or dependent unfinished work block archival');
|
|
55
|
+
requireValue(isObject(attestation.durableContext) && attestation.durableContext.carried === true && Array.isArray(attestation.durableContext.references) && attestation.durableContext.references.length > 0, 'Host must attest durable constraints are carried into current context');
|
|
56
|
+
const references = attestation.durableContext.references.map(relativePath);
|
|
57
|
+
for (const reference of references) {
|
|
58
|
+
requireValue(reference.endsWith('.md'), 'Durable context references must be current Markdown documentation');
|
|
59
|
+
requireValue(!reference.startsWith('docs/features/') && !reference.startsWith('docs/archive/'), 'Durable context cannot rely on the feature being archived');
|
|
60
|
+
readLocal(root, reference);
|
|
61
|
+
}
|
|
62
|
+
return { schemaVersion: 1, phase: 'session-end', host: { sessionId: attestation.host.sessionId, quiescent: true, activeWorkers: [], dependentWork: [] }, durableContext: { carried: true, references } };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const gitIn = (root, args, binary = false) => execFileSync('git', ['--literal-pathspecs', '-C', root, ...args], { encoding: binary ? 'buffer' : 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 256 * 1024 * 1024 });
|
|
66
|
+
|
|
67
|
+
function gitRoot(root) {
|
|
68
|
+
try { return realpathSync(gitIn(root, ['rev-parse', '--show-toplevel']).trim()) === realpathSync(root); } catch { return false; }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function committedBytes(root, revision, file) {
|
|
72
|
+
try { return gitIn(root, ['show', `${revision}:${file}`], true); } catch { return null; }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const isDecisionAnswered = decision => ['clarified', 'assigned'].includes(decision.status) && (typeof decision.answer === 'string' ? nonempty(decision.answer) : decision.answer !== null && decision.answer !== undefined);
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Each commit that changed the feature brief after an acceptance must have one amendment
|
|
79
|
+
* record naming the answered owner decisions that authorized it, and the record's before
|
|
80
|
+
* and after hashes must equal that commit's parent and own brief bytes.
|
|
81
|
+
*/
|
|
82
|
+
function briefAmendments(root, feature, briefPath, later) {
|
|
83
|
+
const recordPath = `${featurePath(feature)}/brief-amendments.json`;
|
|
84
|
+
const changed = `Original requirement changed after acceptance: ${briefPath}`;
|
|
85
|
+
requireValue(existsSync(localPath(root, recordPath, true)), `${changed} (no ${recordPath} records its amendments)`);
|
|
86
|
+
const record = parseJson(readLocal(root, recordPath), recordPath);
|
|
87
|
+
requireValue(isObject(record) && record.schemaVersion === 1 && record.kind === 'joycraft-brief-amendments' && record.brief === briefPath && Array.isArray(record.amendments), `Brief amendment record is malformed: ${recordPath}`);
|
|
88
|
+
const decisions = briefDecisionRecords(readLocal(root, briefPath), briefPath);
|
|
89
|
+
return later.map(commit => {
|
|
90
|
+
const entries = record.amendments.filter(item => isObject(item) && item.commit === commit);
|
|
91
|
+
requireValue(entries.length === 1, `${changed} (commit ${commit} has no single amendment record)`);
|
|
92
|
+
const entry = entries[0];
|
|
93
|
+
const before = committedBytes(root, `${commit}^`, briefPath), after = committedBytes(root, commit, briefPath);
|
|
94
|
+
requireValue(before !== null && after !== null && entry.fromSha256 === sha256(before) && entry.toSha256 === sha256(after), `Brief amendment ${commit} does not match its commit's brief bytes`);
|
|
95
|
+
requireValue(nonempty(entry.summary) && Array.isArray(entry.decisions) && entry.decisions.length > 0 && entry.decisions.every(nonempty), `Brief amendment ${commit} needs a summary and at least one owner decision`);
|
|
96
|
+
for (const id of entry.decisions) {
|
|
97
|
+
const matches = decisions.filter(decision => isObject(decision) && decision.id === id);
|
|
98
|
+
requireValue(matches.length === 1, `Brief amendment ${commit} names decision ${id}, which the brief does not record exactly once`);
|
|
99
|
+
requireValue(isDecisionAnswered(matches[0]), `Brief amendment ${commit} names decision ${id}, which has no recorded owner answer`);
|
|
100
|
+
}
|
|
101
|
+
return { commit, fromSha256: entry.fromSha256, toSha256: entry.toSha256, decisions: [...entry.decisions], summary: entry.summary };
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function validateReconciliation(record, feature) {
|
|
106
|
+
requireValue(isObject(record) && record.schemaVersion === 1 && record.kind === 'joycraft-archive-reconciliation' && record.feature === feature && validTimestamp(record.createdAt), 'Archive reconciliation has an invalid identity');
|
|
107
|
+
requireValue(nonempty(record.instruction) && nonempty(record.reason) && nonempty(record.resolution) && Array.isArray(record.limitations) && record.limitations.length > 0 && record.limitations.every(nonempty), 'Archive reconciliation needs the owner instruction, reason, resolution and limitations');
|
|
108
|
+
requireValue(Array.isArray(record.entries) && record.entries.length > 0, 'Archive reconciliation needs exact affected report/input entries');
|
|
109
|
+
const keys = new Set();
|
|
110
|
+
for (const entry of record.entries) {
|
|
111
|
+
requireValue(isObject(entry) && isObject(entry.report) && nonempty(entry.report.path) && isSha256(entry.report.sha256) && nonempty(entry.path) && ['none', 'requirement-scope', 'queue-scope', 'queue-status', 'spec-status'].includes(entry.normalization) && isSha256(entry.acceptedSha256) && isSha256(entry.currentSha256) && nonempty(entry.reason) && nonempty(entry.resolution), 'Archive reconciliation entry is malformed');
|
|
112
|
+
relativePath(entry.path); relativePath(entry.report.path);
|
|
113
|
+
if (entry.acceptedCommit !== undefined) requireValue(typeof entry.acceptedCommit === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(entry.acceptedCommit), 'Archive reconciliation needs a full accepted commit ID');
|
|
114
|
+
const key = canonical([entry.report.path, entry.report.sha256, entry.path, entry.normalization, entry.acceptedSha256]);
|
|
115
|
+
requireValue(!keys.has(key), 'Archive reconciliation has duplicate entries'); keys.add(key);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function readReconciliation(root, feature, file) {
|
|
120
|
+
if (file === undefined) return undefined;
|
|
121
|
+
requireValue(file === `${featurePath(feature)}/archive-reconciliation.json`, 'Use the feature archive-reconciliation.json for the explicit override');
|
|
122
|
+
const bytes = readLocal(root, file), record = parseJson(bytes, file);
|
|
123
|
+
validateReconciliation(record, feature);
|
|
124
|
+
return { path: file, sha256: sha256(bytes), record, used: new Set() };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function reconciledRequirement(root, state, review, input, project, reconciliation) {
|
|
128
|
+
requireValue(reconciliation, `Original requirement changed after acceptance: ${input.path} (explicit archive reconciliation required)`);
|
|
129
|
+
const index = reconciliation.record.entries.findIndex(entry => entry.report.path === review.path && entry.report.sha256 === review.sha256 && entry.path === input.path && entry.normalization === input.normalization && entry.acceptedSha256 === input.sha256);
|
|
130
|
+
requireValue(index >= 0, `Archive reconciliation does not cover ${review.path}: ${input.path}`);
|
|
131
|
+
const entry = reconciliation.record.entries[index];
|
|
132
|
+
requireValue(sha256(readLocal(root, input.path)) === entry.currentSha256, `Archive reconciliation is stale: ${input.path}`);
|
|
133
|
+
const record = historicalRequirement(root, state.queue.feature, input, project, ['none', 'requirement-scope', 'queue-scope', 'queue-status', 'spec-status'], entry.acceptedCommit);
|
|
134
|
+
reconciliation.used.add(index);
|
|
135
|
+
return { ...record, ...(input.normalization === 'queue-scope' ? { specId: state.spec.id } : {}), reconciliationEntry: index, reconciliationSha256: reconciliation.sha256 };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* A requirement that changed after acceptance stays historical evidence only when git proves
|
|
140
|
+
* what was reviewed: a committed version of the file must project to the accepted hash, the
|
|
141
|
+
* current version must be committed, and the commits since are recorded. The feature brief
|
|
142
|
+
* also needs an owner-decision amendment for each of those commits. The accepted bytes are
|
|
143
|
+
* restored into the archive, so the original requirement is preserved, not reclassified.
|
|
144
|
+
*/
|
|
145
|
+
function historicalRequirement(root, feature, input, project, normalizations = ['none', 'requirement-scope'], acceptedCommit) {
|
|
146
|
+
const changed = `Original requirement changed after acceptance: ${input.path}`;
|
|
147
|
+
requireValue(gitRoot(root), `${changed} (no git history proves the accepted version)`);
|
|
148
|
+
requireValue(gitIn(root, ['status', '--porcelain', '--', input.path]).trim() === '', `${changed} (commit its current version first)`);
|
|
149
|
+
const current = committedBytes(root, 'HEAD', input.path);
|
|
150
|
+
requireValue(current !== null && sha256(current) === sha256(readLocal(root, input.path)), `${changed} (current bytes differ from HEAD)`);
|
|
151
|
+
requireValue(normalizations.includes(input.normalization ?? 'none'), `${changed} (unsupported historical normalization)`);
|
|
152
|
+
if (acceptedCommit !== undefined) requireValue(gitIn(root, ['rev-parse', `${acceptedCommit}^{commit}`]).trim() === acceptedCommit, 'Reconciliation commit is not a full commit object ID');
|
|
153
|
+
const commits = acceptedCommit === undefined ? gitIn(root, ['log', '--full-history', '--topo-order', '--format=%H', 'HEAD', '--', input.path]).split('\n').filter(Boolean) : [acceptedCommit];
|
|
154
|
+
const accepted = commits.find(commit => {
|
|
155
|
+
const bytes = committedBytes(root, commit, input.path);
|
|
156
|
+
// Older versions can predate the selected heading or decision. They are not matches.
|
|
157
|
+
try { return bytes !== null && sha256(project(bytes)) === input.sha256; } catch { return false; }
|
|
158
|
+
});
|
|
159
|
+
requireValue(accepted !== undefined, `${changed} (no committed version matches the accepted bytes)`);
|
|
160
|
+
const later = gitIn(root, ['log', '--full-history', '--topo-order', '--format=%H', '--reverse', `${accepted}..HEAD`, '--', input.path]).split('\n').filter(Boolean);
|
|
161
|
+
const raw = committedBytes(root, accepted, input.path);
|
|
162
|
+
const record = { path: input.path, normalization: input.normalization ?? 'none', ...(input.scope !== undefined ? { scope: input.scope } : {}), acceptedSha256: input.sha256, acceptedCommit: accepted, restoredSha256: sha256(raw), laterCommits: later };
|
|
163
|
+
if (input.path === `${featurePath(feature)}/brief.md`) record.amendments = briefAmendments(root, feature, input.path, later);
|
|
164
|
+
return record;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function historicalReport(root, queuePath, state, review, { ownerAccepted = false, reconciliation } = {}) {
|
|
168
|
+
requireValue(state.spec.status === 'done' && isObject(review) && isSha256(review.sha256), `Spec ${state.spec.id} is not accepted`);
|
|
169
|
+
const reportPath = relativePath(review.path);
|
|
170
|
+
const reportBytes = readLocal(root, reportPath);
|
|
171
|
+
requireValue(sha256(reportBytes) === review.sha256, `Accepted report is missing or changed: ${reportPath}`);
|
|
172
|
+
const report = parseJson(reportBytes, reportPath);
|
|
173
|
+
requireValue(isObject(report) && report.schemaVersion === 1 && (ownerAccepted ? ['FAIL', 'UNVERIFIED'].includes(report.verdict) : report.verdict === 'PASS'), `Accepted report has an invalid historical verdict: ${reportPath}`);
|
|
174
|
+
requireValue(isObject(report.subject) && report.subject.schemaVersion === 1 && report.subject.queuePath === queuePath && report.subject.specId === state.spec.id && report.subject.specPath === state.specPath, `Accepted report has the wrong subject: ${reportPath}`);
|
|
175
|
+
requireValue(isSha256(report.subject.identity) && subjectIdentity(report.subject) === report.subject.identity, `Accepted report has an invalid subject identity: ${reportPath}`);
|
|
176
|
+
try { validateIndependentReview(report); } catch (error) { throw new Error(`Accepted report lacks independent review: ${reportPath}; ${error.message}`); }
|
|
177
|
+
requireValue(Array.isArray(report.unresolved) && report.unresolved.every(nonempty) && (!ownerAccepted ? report.unresolved.length === 0 : true) && validTimestamp(report.createdAt) && Array.isArray(report.flows) && report.flows.length > 0, `Accepted report is incomplete: ${reportPath}`);
|
|
178
|
+
if (!ownerAccepted) {
|
|
179
|
+
const evidence = validateEvidence(report, report.subject.criteria);
|
|
180
|
+
requireValue(isObject(evidence) && evidence.ok === true && Array.isArray(evidence.errors) && evidence.errors.length === 0, `Accepted report evidence is invalid: ${Array.isArray(evidence?.errors) ? evidence.errors.join('; ') : 'validator response is malformed'}`);
|
|
181
|
+
}
|
|
182
|
+
const inputs = Array.isArray(report.subject.inputs) ? report.subject.inputs : [];
|
|
183
|
+
const bound = report.subject.binding;
|
|
184
|
+
if (bound !== undefined) requireValue(isObject(bound) && bound.version === 1 && isObject(bound.queue) && Array.isArray(bound.queue.specIds) && Array.isArray(bound.governing), `Accepted report has invalid binding metadata: ${reportPath}`);
|
|
185
|
+
const normalization = bound === undefined ? 'queue-status' : 'queue-scope';
|
|
186
|
+
const queueInputs = inputs.filter(input => isObject(input) && input.path === queuePath && input.kind === 'requirement' && input.normalization === normalization && isSha256(input.sha256));
|
|
187
|
+
requireValue(queueInputs.length === 1, `Accepted report omits or changes bound queue requirements: ${reportPath}`);
|
|
188
|
+
const queueInput = queueInputs[0];
|
|
189
|
+
const projectQueue = bytes => bound === undefined ? normalizedQueueForSubject(parseJson(bytes, queuePath)) : boundQueueForSubject(parseJson(bytes, queuePath), state.spec.id).value;
|
|
190
|
+
const history = new Map();
|
|
191
|
+
let reviewedQueue = state.queue;
|
|
192
|
+
if (sha256(projectQueue(readLocal(root, queuePath))) !== queueInput.sha256) {
|
|
193
|
+
requireValue(reconciliation, `Accepted report omits or changes bound queue requirements: ${reportPath}`);
|
|
194
|
+
const restored = reconciledRequirement(root, state, review, queueInput, projectQueue, reconciliation);
|
|
195
|
+
history.set(canonical(queueInput), restored);
|
|
196
|
+
reviewedQueue = parseJson(committedBytes(root, restored.acceptedCommit, queuePath), queuePath);
|
|
197
|
+
}
|
|
198
|
+
if (bound !== undefined) requireValue(canonical(bound.queue.specIds) === canonical(boundQueueForSubject(reviewedQueue, state.spec.id).specIds), `Accepted report queue binding differs from archived dependencies: ${reportPath}`);
|
|
199
|
+
const reviewedSpec = reviewedQueue.specs.find(spec => spec.id === state.spec.id);
|
|
200
|
+
requireValue(reviewedSpec && reviewedSpec.file === state.spec.file && canonical(report.subject.criteria) === canonical(reviewedSpec.verification.criteria), `Accepted report criteria differ from the archived spec: ${reportPath}`);
|
|
201
|
+
const declaredSpecPaths = new Set([...state.queue.specs, ...reviewedQueue.specs].map(spec => path.posix.join(path.posix.dirname(queuePath), spec.file)));
|
|
202
|
+
for (const required of [state.specPath, `docs/features/${state.queue.feature}/brief.md`, ...report.subject.criteria.map(item => relativePath(item.requirement.path))]) {
|
|
203
|
+
requireValue(inputs.some(input => isObject(input) && input.path === required && input.kind === 'requirement' && isSha256(input.sha256)), `Accepted report omits original requirement ${required}: ${reportPath}`);
|
|
204
|
+
}
|
|
205
|
+
const requirement = (input, project) => {
|
|
206
|
+
const current = readLocal(root, input.path);
|
|
207
|
+
// A removed selector is a changed requirement, too; recover only a matching committed projection.
|
|
208
|
+
let matches = false;
|
|
209
|
+
try { matches = sha256(project(current)) === input.sha256; } catch { /* Search committed versions below. */ }
|
|
210
|
+
if (matches) return;
|
|
211
|
+
requireValue(input.path !== queuePath && !declaredSpecPaths.has(input.path), `Original requirement changed after acceptance: ${input.path}`);
|
|
212
|
+
const key = canonical(input);
|
|
213
|
+
const explicit = reconciliation?.record.entries.some(entry => entry.report.path === review.path && entry.path === input.path && entry.normalization === input.normalization);
|
|
214
|
+
if (!history.has(key)) history.set(key, explicit ? reconciledRequirement(root, state, review, input, project, reconciliation) : historicalRequirement(root, state.queue.feature, input, project));
|
|
215
|
+
};
|
|
216
|
+
for (const input of inputs.filter(input => isObject(input) && input.kind === 'requirement' && (bound !== undefined || input.path.startsWith(`docs/features/${state.queue.feature}/`)))) {
|
|
217
|
+
// The queue was checked above. Only an explicit, hash-bound reconciliation can
|
|
218
|
+
// preserve a changed acceptance record; normal requirement fallback cannot.
|
|
219
|
+
if (input.path === queuePath) {
|
|
220
|
+
requireValue(canonical(input) === canonical(queueInput), `Accepted report has an inconsistent queue input: ${reportPath}`);
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (declaredSpecPaths.has(input.path)) {
|
|
224
|
+
const projectSpec = bytes => specStatus(bytes).replace('__review_status__');
|
|
225
|
+
if (sha256(projectSpec(readLocal(root, input.path))) !== input.sha256) {
|
|
226
|
+
history.set(canonical(input), reconciledRequirement(root, state, review, input, projectSpec, reconciliation));
|
|
227
|
+
}
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
requirement(input, bytes => input.normalization === 'requirement-scope' ? scopedRequirementForSubject(bytes, input.scope, input.path) : bytes);
|
|
231
|
+
}
|
|
232
|
+
if (bound !== undefined) {
|
|
233
|
+
for (const governing of bound.governing) {
|
|
234
|
+
requireValue(isObject(governing) && nonempty(governing.path), `Accepted report governing binding is malformed: ${reportPath}`);
|
|
235
|
+
const input = inputs.find(item => isObject(item) && item.path === governing.path && item.normalization === 'requirement-scope');
|
|
236
|
+
const { path: governingPath, ...scope } = governing;
|
|
237
|
+
requireValue(input && canonical(input.scope) === canonical(scope), `Accepted report governing input is missing: ${governing.path}`);
|
|
238
|
+
requirement(input, bytes => scopedRequirementForSubject(bytes, input.scope, governing.path));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const receipts = [];
|
|
242
|
+
for (const flow of report.flows) {
|
|
243
|
+
requireValue(isObject(flow) && flow.subjectIdentity === report.subject.identity && Array.isArray(flow.observations), `Accepted report flow is malformed: ${reportPath}`);
|
|
244
|
+
for (const observation of flow.observations) {
|
|
245
|
+
requireValue(isObject(observation) && Array.isArray(observation.receipts), `Accepted report observation is malformed: ${reportPath}`);
|
|
246
|
+
for (const receipt of observation.receipts) {
|
|
247
|
+
requireValue(isObject(receipt) && isSha256(receipt.sha256), `Accepted report receipt is malformed: ${reportPath}`);
|
|
248
|
+
const receiptPath = relativePath(receipt.path);
|
|
249
|
+
requireValue(sha256(readLocal(root, receiptPath)) === receipt.sha256, `Historical receipt is missing or changed: ${receiptPath}`);
|
|
250
|
+
receipts.push({ path: receiptPath, sha256: receipt.sha256 });
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return { path: reportPath, sha256: review.sha256, bytes: reportBytes, receipts, verdict: report.verdict, report, ...(history.size ? { requirementHistory: [...history.values()] } : {}) };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const validTimestamp = value => typeof value === 'string' && nonempty(value) && Number.isFinite(Date.parse(value));
|
|
258
|
+
|
|
259
|
+
function historicalDecision(root, queuePath, state, reconciliation) {
|
|
260
|
+
const accepted = state.spec.acceptedReport;
|
|
261
|
+
const owner = state.spec.ownerAcceptance;
|
|
262
|
+
requireValue(!(accepted !== undefined && owner !== undefined), `Spec ${state.spec.id} has both acceptedReport and ownerAcceptance`);
|
|
263
|
+
if (accepted !== undefined) {
|
|
264
|
+
const report = historicalReport(root, queuePath, state, accepted, { reconciliation });
|
|
265
|
+
return { kind: 'accepted-report', path: report.path, sha256: report.sha256, report: { path: report.path, sha256: report.sha256, verdict: report.verdict }, receipts: report.receipts, limitations: [], ...(report.requirementHistory ? { requirementHistory: report.requirementHistory } : {}) };
|
|
266
|
+
}
|
|
267
|
+
requireValue(isObject(owner) && isSha256(owner.sha256), `Spec ${state.spec.id} is not accepted`);
|
|
268
|
+
const ownerPath = relativePath(owner.path);
|
|
269
|
+
const ownerBytes = readLocal(root, ownerPath);
|
|
270
|
+
requireValue(sha256(ownerBytes) === owner.sha256, `Owner acceptance is missing or changed: ${ownerPath}`);
|
|
271
|
+
const decision = parseJson(ownerBytes, ownerPath);
|
|
272
|
+
requireValue(isObject(decision) && isObject(decision.review) && nonempty(decision.review.path) && isSha256(decision.review.sha256), `Owner acceptance needs a review receipt: ${ownerPath}`);
|
|
273
|
+
const report = historicalReport(root, queuePath, state, decision.review, { ownerAccepted: true, reconciliation });
|
|
274
|
+
validateOwnerAcceptance({ root, decision, decisionPath: ownerPath, state, report: report.report, reportPath: report.path, reportBytes: report.bytes });
|
|
275
|
+
return { kind: 'owner-acceptance', path: ownerPath, sha256: owner.sha256, report: { path: report.path, sha256: report.sha256, verdict: report.verdict }, receipts: report.receipts, limitations: decision.limitations, ...(report.requirementHistory ? { requirementHistory: report.requirementHistory } : {}) };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function fileDigest(root, relative) { return { path: relative, sha256: sha256(readLocal(root, relative)) }; }
|
|
279
|
+
|
|
280
|
+
function existingArchive(root, feature) {
|
|
281
|
+
const destination = archivePath(feature);
|
|
282
|
+
const manifestPath = `${destination}/archive-replay.json`;
|
|
283
|
+
const manifest = parseJson(readLocal(root, manifestPath), manifestPath);
|
|
284
|
+
requireValue(isObject(manifest) && manifest.schemaVersion === 1 && manifest.kind === 'joycraft-archive-replay' && manifest.feature === feature && manifest.source === featurePath(feature) && Array.isArray(manifest.files), `Archive destination is not a valid archive for ${feature}: ${destination}`);
|
|
285
|
+
if (manifest.reconciliation !== undefined) {
|
|
286
|
+
const proof = manifest.reconciliation;
|
|
287
|
+
requireValue(isObject(proof) && proof.path === `${featurePath(feature)}/archive-reconciliation.json` && isSha256(proof.sha256), 'Archived reconciliation metadata is malformed');
|
|
288
|
+
validateReconciliation(proof.record, feature);
|
|
289
|
+
const ledger = manifest.files.find(file => file.operation === 'moved' && file.originalPath === proof.path && file.sha256 === proof.sha256);
|
|
290
|
+
requireValue(ledger && sha256(readLocal(root, ledger.archivedPath)) === proof.sha256 && canonical(parseJson(readLocal(root, ledger.archivedPath), proof.path)) === canonical(proof.record), 'Archived reconciliation paper trail is missing or changed');
|
|
291
|
+
requireValue(manifest.historical?.acceptanceRecordsReconciled === true, 'Archived reconciliation must remain visibly labeled');
|
|
292
|
+
}
|
|
293
|
+
for (const file of manifest.files) {
|
|
294
|
+
requireValue(isObject(file) && nonempty(file.originalPath) && isSha256(file.sha256) && ['moved', 'copied', 'restored-from-git'].includes(file.operation), `Archive replay entry is malformed: ${manifestPath}`);
|
|
295
|
+
const archivedPath = relativePath(file.archivedPath);
|
|
296
|
+
requireValue(archivedPath.startsWith(`${destination}/`), `Archive replay path escapes its destination: ${archivedPath}`);
|
|
297
|
+
const bytes = readLocal(root, archivedPath);
|
|
298
|
+
requireValue(sha256(bytes) === file.sha256, `Archived bytes are missing or changed: ${archivedPath}`);
|
|
299
|
+
if (file.operation === 'restored-from-git') {
|
|
300
|
+
const record = file.requirement;
|
|
301
|
+
requireValue(isObject(record) && record.path === file.originalPath && record.restoredSha256 === file.sha256 && isSha256(record.acceptedSha256) && /^[a-f0-9]{40,64}$/.test(record.acceptedCommit) && Array.isArray(record.laterCommits) && record.laterCommits.every(commit => /^[a-f0-9]{40,64}$/.test(commit)) && ['none', 'requirement-scope', 'queue-scope', 'queue-status', 'spec-status'].includes(record.normalization), `Historical requirement replay is malformed: ${archivedPath}`);
|
|
302
|
+
if (['queue-scope', 'queue-status', 'spec-status'].includes(record.normalization) || record.reconciliationEntry !== undefined) {
|
|
303
|
+
requireValue(manifest.reconciliation && record.reconciliationSha256 === manifest.reconciliation.sha256 && Number.isInteger(record.reconciliationEntry), `Reconciled replay has no matching paper trail: ${archivedPath}`);
|
|
304
|
+
const entry = manifest.reconciliation.record.entries[record.reconciliationEntry];
|
|
305
|
+
requireValue(entry && entry.path === record.path && entry.normalization === record.normalization && entry.acceptedSha256 === record.acceptedSha256 && (entry.acceptedCommit === undefined || entry.acceptedCommit === record.acceptedCommit) && manifest.evidence.some(decision => decision.report.path === entry.report.path && decision.report.sha256 === entry.report.sha256 && decision.requirementHistory?.some(item => canonical(item) === canonical(record))) && manifest.files.some(item => ['moved', 'copied'].includes(item.operation) && item.originalPath === entry.path && item.sha256 === entry.currentSha256), `Reconciled replay differs from its paper trail: ${archivedPath}`);
|
|
306
|
+
}
|
|
307
|
+
requireValue(archivedPath === restoredPath(destination, record) && sha256(requirementProjection(bytes, record)) === record.acceptedSha256, `Restored requirement does not match acceptance: ${archivedPath}`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
for (const decision of manifest.evidence ?? []) {
|
|
311
|
+
for (const record of decision.requirementHistory ?? []) {
|
|
312
|
+
requireValue(manifest.files.some(file => file.operation === 'restored-from-git' && canonical(file.requirement) === canonical(record)), `Historical requirement replay is missing: ${record.path}`);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return { destination, manifestPath, manifest };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export function previewArchiveFeature({ root = process.cwd(), feature, phase, attestation, reconciliation: reconciliationPath }) {
|
|
319
|
+
feature = featureName(feature);
|
|
320
|
+
requireValue(phase === 'session-end', 'Archive is allowed only during phase=session-end');
|
|
321
|
+
const source = featurePath(feature), destination = archivePath(feature);
|
|
322
|
+
const parsedAttestation = parseAttestation(root, attestation);
|
|
323
|
+
if (existsSync(projectTarget(root, destination))) {
|
|
324
|
+
requireValue(!existsSync(projectTarget(root, source)), `Archive destination already exists while live source remains: ${destination}`);
|
|
325
|
+
const existing = existingArchive(root, feature);
|
|
326
|
+
return { schemaVersion: 1, feature, phase, source, destination, attestation: parsedAttestation, existing: true, manifest: existing.manifestPath, historical: existing.manifest.historical };
|
|
327
|
+
}
|
|
328
|
+
plainDirectory(root, source);
|
|
329
|
+
const queuePath = `${source}/specs/.joycraft-spec-queue.json`;
|
|
330
|
+
const queues = [];
|
|
331
|
+
const findQueues = relative => {
|
|
332
|
+
for (const name of readdirSync(localDirectory(root, relative))) {
|
|
333
|
+
const child = `${relative}/${name}`;
|
|
334
|
+
const stat = lstatSync(path.join(localDirectory(root, relative), name));
|
|
335
|
+
if (stat.isDirectory()) findQueues(child);
|
|
336
|
+
else if (name === '.joycraft-spec-queue.json') queues.push(child);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
findQueues(source);
|
|
340
|
+
requireValue(queues.length === 1 && queues[0] === queuePath, `Unexpected alternate queue in feature archive: ${queues.filter(item => item !== queuePath).join(', ') || 'missing canonical queue'}`);
|
|
341
|
+
requireValue(!existsSync(localPath(root, `${source}/specs/.joycraft-completion.pending.json`, true)), 'A pending completion journal blocks archival; recover it first');
|
|
342
|
+
const queue = parseJson(readLocal(root, queuePath), queuePath);
|
|
343
|
+
requireValue(queue.feature === feature, `Queue feature does not match ${feature}`);
|
|
344
|
+
const reconciliation = readReconciliation(root, feature, reconciliationPath);
|
|
345
|
+
const evidence = [];
|
|
346
|
+
for (const item of queue.specs ?? []) {
|
|
347
|
+
const state = readQueue({ root, queuePath, specId: item.id });
|
|
348
|
+
evidence.push(historicalDecision(root, queuePath, state, reconciliation));
|
|
349
|
+
}
|
|
350
|
+
requireValue(Array.isArray(queue.specs) && queue.specs.length > 0 && queue.specs.every(spec => spec.status === 'done'), 'Every spec must be done before archiving the whole feature');
|
|
351
|
+
if (reconciliation) requireValue(reconciliation.used.size === reconciliation.record.entries.length, 'Archive reconciliation contains unused or stale entries');
|
|
352
|
+
const copies = new Map();
|
|
353
|
+
for (const decision of evidence) {
|
|
354
|
+
for (const evidencePath of [decision.path, decision.report.path, ...decision.receipts.map(receipt => receipt.path)]) {
|
|
355
|
+
if (!evidencePath.startsWith(`${source}/`)) copies.set(evidencePath, fileDigest(root, evidencePath));
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
for (const decision of evidence) {
|
|
359
|
+
for (const record of decision.requirementHistory ?? []) {
|
|
360
|
+
if (record.reconciliationEntry !== undefined && !record.path.startsWith(`${source}/`)) copies.set(record.path, fileDigest(root, record.path));
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const files = [];
|
|
364
|
+
const collect = relative => {
|
|
365
|
+
for (const name of readdirSync(localDirectory(root, relative))) {
|
|
366
|
+
const child = `${relative}/${name}`, stat = lstatSync(path.join(localDirectory(root, relative), name));
|
|
367
|
+
if (stat.isDirectory()) collect(child); else files.push(fileDigest(root, child));
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
collect(source);
|
|
371
|
+
const requirementHistory = [...new Map(evidence.flatMap(decision => decision.requirementHistory ?? []).map(record => [canonical(record), record])).values()];
|
|
372
|
+
return { schemaVersion: 1, feature, phase, source, destination, queuePath, attestation: parsedAttestation, evidence, requirementHistory, ...(reconciliation ? { reconciliation: { path: reconciliation.path, sha256: reconciliation.sha256, record: reconciliation.record } } : {}), featureFiles: files.sort((a, b) => a.path.localeCompare(b.path)), copiedEvidence: [...copies.values()].sort((a, b) => a.path.localeCompare(b.path)), historical: { codeInputHashesAreHistorical: true, currentAcceptanceRenewed: false, ...(reconciliation ? { acceptanceRecordsReconciled: true } : {}) } };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function requirementProjection(bytes, record) {
|
|
376
|
+
if (record.normalization === 'requirement-scope') return scopedRequirementForSubject(bytes, record.scope, record.path);
|
|
377
|
+
if (record.normalization === 'spec-status') return specStatus(bytes).replace('__review_status__');
|
|
378
|
+
if (record.normalization === 'queue-status') return normalizedQueueForSubject(parseJson(bytes, record.path));
|
|
379
|
+
if (record.normalization === 'queue-scope') {
|
|
380
|
+
requireValue(Number.isInteger(record.specId) && record.specId > 0, 'Restored queue scope needs its spec ID');
|
|
381
|
+
return boundQueueForSubject(parseJson(bytes, record.path), record.specId).value;
|
|
382
|
+
}
|
|
383
|
+
return bytes;
|
|
384
|
+
}
|
|
385
|
+
const restoredPath = (destination, record) => `${destination}/evidence/requirements/${sha256(canonical(record))}/${relativePath(record.path)}`;
|
|
386
|
+
|
|
387
|
+
function replayManifest(plan) {
|
|
388
|
+
const map = [
|
|
389
|
+
...plan.featureFiles.map(file => ({ originalPath: file.path, archivedPath: `${plan.destination}/feature/${file.path.slice(plan.source.length + 1)}`, sha256: file.sha256, operation: 'moved' })),
|
|
390
|
+
...plan.requirementHistory.map(record => ({ originalPath: record.path, archivedPath: restoredPath(plan.destination, record), sha256: record.restoredSha256, operation: 'restored-from-git', requirement: record })),
|
|
391
|
+
...plan.copiedEvidence.map(file => ({ originalPath: file.path, archivedPath: `${plan.destination}/evidence/${file.path}`, sha256: file.sha256, operation: 'copied' })),
|
|
392
|
+
];
|
|
393
|
+
return { schemaVersion: 1, kind: 'joycraft-archive-replay', feature: plan.feature, archivedAt: new Date().toISOString(), phase: plan.phase, source: plan.source, evidence: plan.evidence, ...(plan.reconciliation ? { reconciliation: plan.reconciliation } : {}), durableContext: plan.attestation.durableContext, hostSession: plan.attestation.host.sessionId, historical: plan.historical, files: map };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export function archiveFeature(options) {
|
|
397
|
+
const plan = previewArchiveFeature(options);
|
|
398
|
+
if (plan.existing) return { status: 'archived', unchanged: true, destination: plan.destination, manifest: plan.manifest, historical: plan.historical };
|
|
399
|
+
if (options.apply !== true) return { status: 'preview', plan };
|
|
400
|
+
const root = options.root ?? process.cwd();
|
|
401
|
+
// Revalidate every input immediately before changing paths, so a preview cannot race a writer.
|
|
402
|
+
const fresh = previewArchiveFeature({ ...options, root, apply: false });
|
|
403
|
+
requireValue(canonical({ ...plan, attestation: undefined }) === canonical({ ...fresh, attestation: undefined }), 'Archive inputs changed after preview; rerun the session-end preflight');
|
|
404
|
+
const stage = `docs/archive/.${plan.feature}.staging-${process.pid}-${Date.now()}`;
|
|
405
|
+
const stageLocal = projectTarget(root, stage), destinationLocal = projectTarget(root, plan.destination), sourceLocal = localDirectory(root, plan.source);
|
|
406
|
+
requireValue(!existsSync(stageLocal) && !existsSync(destinationLocal), 'Archive collision detected before move');
|
|
407
|
+
mkdirSync(stageLocal, { recursive: true, mode: 0o700 });
|
|
408
|
+
try {
|
|
409
|
+
writeFileSync(path.join(stageLocal, 'archive-recovery.json'), `${JSON.stringify({ schemaVersion: 1, kind: 'joycraft-archive-recovery', feature: plan.feature, source: plan.source, destination: plan.destination, stage, phase: plan.phase, featureFiles: plan.featureFiles, copiedEvidence: plan.copiedEvidence, requirementHistory: plan.requirementHistory }, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
|
|
410
|
+
for (const copy of plan.copiedEvidence) {
|
|
411
|
+
const target = path.join(stageLocal, 'evidence', copy.path);
|
|
412
|
+
mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
413
|
+
cpSync(localPath(root, copy.path), target, { dereference: false, errorOnExist: true });
|
|
414
|
+
requireValue(sha256(readFileSync(target)) === copy.sha256, `Historical evidence changed while copying: ${copy.path}`);
|
|
415
|
+
}
|
|
416
|
+
for (const record of plan.requirementHistory) {
|
|
417
|
+
const bytes = committedBytes(root, record.acceptedCommit, record.path);
|
|
418
|
+
requireValue(bytes !== null && sha256(bytes) === record.restoredSha256 && sha256(requirementProjection(bytes, record)) === record.acceptedSha256, `Historical requirement changed while restoring: ${record.path}`);
|
|
419
|
+
const target = path.join(stageLocal, restoredPath(plan.destination, record).slice(plan.destination.length + 1));
|
|
420
|
+
mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
421
|
+
writeFileSync(target, bytes, { flag: 'wx', mode: 0o600 });
|
|
422
|
+
}
|
|
423
|
+
writeFileSync(path.join(stageLocal, 'archive-replay.json'), `${JSON.stringify(replayManifest(plan), null, 2)}\n`, { flag: 'wx', mode: 0o600 });
|
|
424
|
+
// One final source check protects the move after staging completes.
|
|
425
|
+
const latest = previewArchiveFeature({ ...options, root, apply: false });
|
|
426
|
+
requireValue(canonical(plan) === canonical(latest), 'Archive inputs changed during staging; rerun the session-end preflight');
|
|
427
|
+
renameSync(sourceLocal, path.join(stageLocal, 'feature'));
|
|
428
|
+
renameSync(stageLocal, destinationLocal);
|
|
429
|
+
} catch (error) {
|
|
430
|
+
const stagedFeature = path.join(stageLocal, 'feature');
|
|
431
|
+
let restored = true;
|
|
432
|
+
try { if (existsSync(stagedFeature) && !existsSync(sourceLocal)) renameSync(stagedFeature, sourceLocal); } catch { restored = false; }
|
|
433
|
+
restored = restored && existsSync(sourceLocal) && !existsSync(stagedFeature);
|
|
434
|
+
if (restored && existsSync(stageLocal)) rmSync(stageLocal, { recursive: true, force: true });
|
|
435
|
+
const recovery = restored ? 'The live feature path was preserved.' : `The staged feature remains at ${stage}; restore it manually before retrying.`;
|
|
436
|
+
throw new Error(`Archive stopped without accepting new completion: ${error.message}. ${recovery}`);
|
|
437
|
+
}
|
|
438
|
+
return { status: 'archived', destination: plan.destination, manifest: `${plan.destination}/archive-replay.json`, historical: plan.historical };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function argumentsFor(argv) {
|
|
442
|
+
const [command, ...args] = argv;
|
|
443
|
+
requireValue(command === 'archive', 'Usage: archive.mjs archive --feature <slug> --phase session-end --attestation <path> [--reconciliation <path>] [--apply]');
|
|
444
|
+
const flags = {};
|
|
445
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
446
|
+
if (args[index] === '--apply') { requireValue(flags['--apply'] === undefined, 'Duplicate --apply'); flags['--apply'] = true; continue; }
|
|
447
|
+
requireValue(['--feature', '--phase', '--attestation', '--reconciliation'].includes(args[index]) && nonempty(args[index + 1]) && flags[args[index]] === undefined, `Invalid or duplicate argument: ${args[index]}`);
|
|
448
|
+
flags[args[index]] = args[index + 1]; index += 1;
|
|
449
|
+
}
|
|
450
|
+
requireValue(flags['--feature'] && flags['--phase'] && flags['--attestation'], 'Archive needs --feature, --phase and --attestation');
|
|
451
|
+
return flags;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export function main(argv = process.argv.slice(2)) {
|
|
455
|
+
const flags = argumentsFor(argv);
|
|
456
|
+
const result = archiveFeature({ feature: flags['--feature'], phase: flags['--phase'], attestation: flags['--attestation'], reconciliation: flags['--reconciliation'], apply: flags['--apply'] === true });
|
|
457
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
458
|
+
return result;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
|
462
|
+
try { main(); } catch (error) { process.stderr.write(`Archive stopped: ${error.message}\n`); process.exitCode = 1; }
|
|
463
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { loadArtifact, persistResponses, readProjectFile, writeArtifact } from './model.mjs';
|
|
4
|
+
import { renderArtifact } from './render.mjs';
|
|
5
|
+
import { startArtifact } from './server.mjs';
|
|
6
|
+
import { setArtifactColors, setArtifactTheme } from './preferences.mjs';
|
|
7
|
+
|
|
8
|
+
export async function main(argv, root = process.cwd()) {
|
|
9
|
+
const [command, ...args] = argv;
|
|
10
|
+
const flags = command === 'serve' ? ['--brief', '--view', '--theme'] : command === 'build' ? ['--brief', '--view', '--out', '--mode', '--theme'] : command === 'import' ? ['--brief', '--view', '--responses', '--apply'] : command === 'theme' ? ['--set'] : command === 'colors' ? ['--set', '--reset'] : [];
|
|
11
|
+
if (!flags.length) throw new Error('Use serve --brief <path> [--view <path>] [--theme light|dark], build --brief <path> [--view <path>] --out <path> --mode claude|portable [--theme light|dark], import --brief <path> [--view <path>] --responses <path> [--apply], theme --set light|dark, or colors --set <colors.json> | --reset');
|
|
12
|
+
const values = {};
|
|
13
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
14
|
+
const flag = args[i];
|
|
15
|
+
if (!flags.includes(flag) || Object.hasOwn(values, flag)) throw new Error(`Unknown or repeated argument: ${flag}`);
|
|
16
|
+
if (flag === '--apply' || flag === '--reset') values[flag] = true;
|
|
17
|
+
else { if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`Missing value for ${flag}`); values[flag] = args[++i]; }
|
|
18
|
+
}
|
|
19
|
+
if (command === 'theme') {
|
|
20
|
+
if (!values['--set']) throw new Error('Theme needs --set light|dark');
|
|
21
|
+
const preferences = await setArtifactTheme(root, values['--set']);
|
|
22
|
+
console.log(JSON.stringify({ path: '.joycraft/preferences.json', theme: preferences.artifacts.theme }, null, 2));
|
|
23
|
+
return preferences;
|
|
24
|
+
}
|
|
25
|
+
if (command === 'colors') {
|
|
26
|
+
if (!values['--set'] === !values['--reset']) throw new Error('Colors needs --set <colors.json> or --reset');
|
|
27
|
+
let colors = null;
|
|
28
|
+
if (values['--set']) {
|
|
29
|
+
try { colors = JSON.parse((await readProjectFile(root, values['--set'])).toString('utf8')); }
|
|
30
|
+
catch (error) { throw new Error(`Could not read colors: ${error.message}`); }
|
|
31
|
+
}
|
|
32
|
+
const preferences = await setArtifactColors(root, colors);
|
|
33
|
+
console.log(JSON.stringify({ path: '.joycraft/preferences.json', colors: preferences.artifacts.colors ?? 'kit defaults' }, null, 2));
|
|
34
|
+
return preferences;
|
|
35
|
+
}
|
|
36
|
+
if (!values['--brief']) throw new Error('Supply --brief as a path relative to the project root');
|
|
37
|
+
const options = { root, brief: values['--brief'], view: values['--view'], theme: values['--theme'] };
|
|
38
|
+
if (command === 'serve') {
|
|
39
|
+
const server = await startArtifact(options);
|
|
40
|
+
console.log(`Artifact: ${server.url}\nAnswers save directly to ${options.brief}. Stop with Ctrl-C.`);
|
|
41
|
+
return server;
|
|
42
|
+
}
|
|
43
|
+
if (command === 'build') {
|
|
44
|
+
if (!values['--out'] || !['claude', 'portable'].includes(values['--mode'])) throw new Error('Build needs --out <project-relative-path> and --mode claude|portable');
|
|
45
|
+
const { model } = await loadArtifact({ ...options, mode: values['--mode'] });
|
|
46
|
+
const path = await writeArtifact({ root, path: values['--out'], html: await renderArtifact(model) });
|
|
47
|
+
console.log(JSON.stringify({ path, mode: model.mode, source: model.source, instruction: model.mode === 'claude' ? 'Use the available Claude host artifact tools to create or update an HTML artifact from these bytes. This command has not published or uploaded it.' : 'Open the HTML, fill answers, then export responses for import. This file cannot update the brief by itself.' }, null, 2));
|
|
48
|
+
return { path, model };
|
|
49
|
+
}
|
|
50
|
+
if (!values['--responses']) throw new Error('Import needs --responses <project-relative-path>');
|
|
51
|
+
let envelope;
|
|
52
|
+
try { envelope = JSON.parse((await readProjectFile(root, values['--responses'])).toString('utf8')); }
|
|
53
|
+
catch (error) { throw new Error(`Could not read responses: ${error.message}`); }
|
|
54
|
+
const result = await persistResponses({ ...options, envelope, apply: values['--apply'] === true });
|
|
55
|
+
console.log(JSON.stringify(result, null, 2));
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
60
|
+
main(process.argv.slice(2)).catch(error => { console.error(`Artifact stopped: ${error.message}`); process.exitCode = 1; });
|
|
61
|
+
}
|