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,137 @@
|
|
|
1
|
+
const kinds = new Set(['runtime', 'visual', 'structural']);
|
|
2
|
+
const methods = new Set(['test', 'command', 'browser', 'manual', 'source']);
|
|
3
|
+
const results = new Set(['PASS', 'FAIL', 'UNVERIFIED']);
|
|
4
|
+
const text = value => typeof value === 'string' && value.trim().length > 0;
|
|
5
|
+
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
+
const texts = value => Array.isArray(value) && value.every(text);
|
|
7
|
+
const hash = value => typeof value === 'string' && /^[a-f0-9]{64}$/i.test(value);
|
|
8
|
+
const relativePath = value => text(value) && !/[\\\0]/.test(value)
|
|
9
|
+
&& !value.startsWith('/') && !/^[a-z]:/i.test(value)
|
|
10
|
+
&& value.split('/').every(part => part !== '' && part !== '.' && part !== '..');
|
|
11
|
+
|
|
12
|
+
/** Check declared evidence sufficiency, not observational truth or file contents.
|
|
13
|
+
* Identity, receipt bytes, independent review and status writes belong to completion.
|
|
14
|
+
* @returns {{ ok: boolean, errors: string[] }}
|
|
15
|
+
*/
|
|
16
|
+
export function validateEvidence(report, criteria) {
|
|
17
|
+
const errors = [];
|
|
18
|
+
const requirements = new Map();
|
|
19
|
+
const covered = new Map();
|
|
20
|
+
const fail = message => errors.push(message);
|
|
21
|
+
|
|
22
|
+
if (!Array.isArray(criteria) || criteria.length === 0) {
|
|
23
|
+
fail('criteria must be a nonempty array');
|
|
24
|
+
} else {
|
|
25
|
+
criteria.forEach((criterion, index) => {
|
|
26
|
+
const label = `criteria[${index}]`;
|
|
27
|
+
if (!record(criterion) || !text(criterion.id)) {
|
|
28
|
+
fail(`${label} needs an id`);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (requirements.has(criterion.id)) fail(`${label} duplicates criterion ${criterion.id}`);
|
|
32
|
+
if (!record(criterion.requirement) || !relativePath(criterion.requirement.path)
|
|
33
|
+
|| !text(criterion.requirement.anchor)) fail(`${label} needs a project-relative requirement path and anchor`);
|
|
34
|
+
if (!Array.isArray(criterion.requiredKinds) || criterion.requiredKinds.length === 0
|
|
35
|
+
|| criterion.requiredKinds.some(kind => !kinds.has(kind))
|
|
36
|
+
|| new Set(criterion.requiredKinds).size !== criterion.requiredKinds.length) {
|
|
37
|
+
fail(`${label} needs distinct supported requiredKinds`);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
requirements.set(criterion.id, criterion.requiredKinds);
|
|
41
|
+
covered.set(criterion.id, new Set());
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (!record(report) || report.schemaVersion !== 1) {
|
|
46
|
+
fail('report must use schemaVersion 1');
|
|
47
|
+
return { ok: false, errors };
|
|
48
|
+
}
|
|
49
|
+
if (!record(report.subject) || !hash(report.subject.identity)) {
|
|
50
|
+
fail('report.subject.identity must be a SHA-256 identity');
|
|
51
|
+
}
|
|
52
|
+
if (!Array.isArray(report.flows)) {
|
|
53
|
+
fail('report.flows must be an array');
|
|
54
|
+
return { ok: false, errors };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const flowIds = new Set();
|
|
58
|
+
report.flows.forEach((flow, index) => {
|
|
59
|
+
const label = `flows[${index}]`;
|
|
60
|
+
if (!record(flow)) { fail(`${label} must be an object`); return; }
|
|
61
|
+
if (!text(flow.id)) fail(`${label} needs an id`);
|
|
62
|
+
else if (flowIds.has(flow.id)) fail(`${label} duplicates flow ${flow.id}`);
|
|
63
|
+
else flowIds.add(flow.id);
|
|
64
|
+
if (!hash(flow.subjectIdentity) || flow.subjectIdentity !== report.subject?.identity) {
|
|
65
|
+
fail(`${label} does not reference the report subject identity`);
|
|
66
|
+
}
|
|
67
|
+
if (!text(flow.representativeInput)) fail(`${label} needs representative input or initial state`);
|
|
68
|
+
if (!text(flow.expected)) fail(`${label} needs expected behavior`);
|
|
69
|
+
if (!texts(flow.limits)) fail(`${label}.limits must be an array of nonempty strings`);
|
|
70
|
+
const references = Array.isArray(flow.criteria) ? flow.criteria : [];
|
|
71
|
+
if (!texts(flow.criteria) || references.length === 0 || new Set(references).size !== references.length) {
|
|
72
|
+
fail(`${label} needs distinct criterion references`);
|
|
73
|
+
}
|
|
74
|
+
for (const id of references) {
|
|
75
|
+
if (!requirements.has(id)) fail(`${label} references undeclared criterion ${String(id)}`);
|
|
76
|
+
}
|
|
77
|
+
if (!Array.isArray(flow.observations) || flow.observations.length === 0) {
|
|
78
|
+
fail(`${label} needs observations`);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
flow.observations.forEach((observation, observationIndex) => {
|
|
83
|
+
const at = `${label}.observations[${observationIndex}]`;
|
|
84
|
+
const before = errors.length;
|
|
85
|
+
if (!record(observation)) { fail(`${at} must be an object`); return; }
|
|
86
|
+
if (!kinds.has(observation.kind)) fail(`${at} has an unsupported evidence kind`);
|
|
87
|
+
if (!methods.has(observation.method)) fail(`${at} has an unsupported method`);
|
|
88
|
+
if (!results.has(observation.result)) fail(`${at} has an unsupported result`);
|
|
89
|
+
else if (observation.result !== 'PASS') fail(`${at} remains ${observation.result}`);
|
|
90
|
+
if (!text(observation.actual)) fail(`${at} needs an actual observation`);
|
|
91
|
+
if (observation.method === 'source' && observation.kind !== 'structural') {
|
|
92
|
+
fail(`${at}: a source scan supports structural claims only`);
|
|
93
|
+
}
|
|
94
|
+
if (!Array.isArray(observation.receipts) || observation.receipts.length === 0) {
|
|
95
|
+
fail(`${at} needs supporting receipt references`);
|
|
96
|
+
} else {
|
|
97
|
+
observation.receipts.forEach((receipt, receiptIndex) => {
|
|
98
|
+
if (!record(receipt) || !relativePath(receipt.path) || !hash(receipt.sha256)) {
|
|
99
|
+
fail(`${at}.receipts[${receiptIndex}] needs a project-relative path and SHA-256`);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
if (observation.method === 'test' || observation.method === 'command'
|
|
104
|
+
|| observation.command !== undefined) {
|
|
105
|
+
const command = observation.command;
|
|
106
|
+
if (!record(command) || !texts(command.argv) || command.argv.length === 0) {
|
|
107
|
+
fail(`${at} needs the executed command argv`);
|
|
108
|
+
}
|
|
109
|
+
if (!record(command) || !Number.isInteger(command.exitCode) || command.exitCode !== 0) {
|
|
110
|
+
fail(`${at} needs actual successful command exitCode 0; unavailable or nonzero is insufficient`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (observation.kind === 'visual') {
|
|
114
|
+
const visual = observation.visual;
|
|
115
|
+
if (!record(visual) || !text(visual.route) || !text(visual.state)) {
|
|
116
|
+
fail(`${at} needs the rendered route and state`);
|
|
117
|
+
}
|
|
118
|
+
if (!record(visual?.viewport) || !Number.isInteger(visual.viewport.width)
|
|
119
|
+
|| !Number.isInteger(visual.viewport.height) || visual.viewport.width <= 0 || visual.viewport.height <= 0) {
|
|
120
|
+
fail(`${at} needs a positive viewport width and height`);
|
|
121
|
+
}
|
|
122
|
+
if (visual?.inspected !== true) fail(`${at}: a saved but uninspected render is UNVERIFIED`);
|
|
123
|
+
if (!texts(visual?.interactions)) fail(`${at} needs an array of observed interaction outcomes`);
|
|
124
|
+
}
|
|
125
|
+
if (errors.length === before) {
|
|
126
|
+
for (const id of references) covered.get(id)?.add(observation.kind);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
for (const [id, requiredKinds] of requirements) {
|
|
132
|
+
for (const kind of requiredKinds) {
|
|
133
|
+
if (!covered.get(id).has(kind)) fail(`criterion ${id} lacks PASS ${kind} evidence`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return { ok: errors.length === 0, errors };
|
|
137
|
+
}
|
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { captureChangeScope, validateChangeScope } from './scope.mjs';
|
|
6
|
+
|
|
7
|
+
const statuses = ['todo', 'in-review', 'done'];
|
|
8
|
+
const kinds = ['code', 'requirement', 'check', 'fixture'];
|
|
9
|
+
const evidenceKinds = ['runtime', 'visual', 'structural'];
|
|
10
|
+
export const sha256 = value => createHash('sha256').update(value).digest('hex');
|
|
11
|
+
export const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
12
|
+
export const nonempty = value => typeof value === 'string' && value.trim().length > 0;
|
|
13
|
+
export const isSha256 = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
|
14
|
+
export function requireValue(condition, message) {
|
|
15
|
+
if (!condition) throw new Error(message);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const nativeIdentityMaxLength = 512;
|
|
19
|
+
|
|
20
|
+
function nativeIdentityString(value, label) {
|
|
21
|
+
requireValue(typeof value === 'string' && value.length > 0 && value.length <= nativeIdentityMaxLength && value === value.trim() && !/[\u0000-\u001f\u007f]/.test(value), `${label} must be a nonempty, bounded, trim-stable string without control characters`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Native identity is host-adapter attestation. The runtime validates record
|
|
26
|
+
* shape only; it does not establish authenticity or classify opaque IDs.
|
|
27
|
+
*/
|
|
28
|
+
export function validateNativeActor(actor, label = 'Native actor') {
|
|
29
|
+
requireValue(isObject(actor), `${label} must be an object`);
|
|
30
|
+
nativeIdentityString(actor.host, `${label} host`);
|
|
31
|
+
nativeIdentityString(actor.sessionId, `${label} sessionId`);
|
|
32
|
+
if (actor.agentId !== undefined) {
|
|
33
|
+
nativeIdentityString(actor.agentId, `${label} agentId`);
|
|
34
|
+
}
|
|
35
|
+
return actor.agentId === undefined
|
|
36
|
+
? { host: actor.host, sessionId: actor.sessionId }
|
|
37
|
+
: { host: actor.host, sessionId: actor.sessionId, agentId: actor.agentId };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Root actors omit agentId; a child actor must carry the host-issued ID. */
|
|
41
|
+
export function nativeActorTuple(actor) {
|
|
42
|
+
const valid = validateNativeActor(actor);
|
|
43
|
+
// Host adapters identify themselves case-insensitively. Session and child
|
|
44
|
+
// identities remain opaque host-provided values and are never normalized.
|
|
45
|
+
return [valid.host.toLowerCase(), valid.sessionId, valid.agentId ?? null];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function sameNativeActor(left, right) {
|
|
49
|
+
return canonical(nativeActorTuple(left)) === canonical(nativeActorTuple(right));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Validate the role-attested independent-review identity shared by completion
|
|
54
|
+
* and session-end archival. This is intentionally an integrity check, not a
|
|
55
|
+
* cryptographic authentication service.
|
|
56
|
+
*/
|
|
57
|
+
export function validateIndependentReview(report) {
|
|
58
|
+
requireValue(nonempty(report?.implementerSessionId) && isObject(report?.reviewer) && nonempty(report.reviewer.sessionId), 'Report needs implementer and reviewer session IDs');
|
|
59
|
+
const hasImplementerActor = report.implementerActor !== undefined;
|
|
60
|
+
const hasReviewerActor = report.reviewer.actor !== undefined;
|
|
61
|
+
requireValue(hasImplementerActor === hasReviewerActor, 'Native implementer and reviewer actors must be reported together');
|
|
62
|
+
if (hasImplementerActor) {
|
|
63
|
+
const implementerActor = validateNativeActor(report.implementerActor, 'Implementer actor');
|
|
64
|
+
const reviewerActor = validateNativeActor(report.reviewer.actor, 'Reviewer actor');
|
|
65
|
+
requireValue(implementerActor.sessionId === report.implementerSessionId, 'Implementer actor sessionId must match implementerSessionId');
|
|
66
|
+
requireValue(reviewerActor.sessionId === report.reviewer.sessionId, 'Reviewer actor sessionId must match reviewer.sessionId');
|
|
67
|
+
requireValue(!sameNativeActor(implementerActor, reviewerActor), 'An independent reviewer must have a distinct native actor');
|
|
68
|
+
if (implementerActor.host.toLowerCase() === reviewerActor.host.toLowerCase() && implementerActor.sessionId === reviewerActor.sessionId) {
|
|
69
|
+
requireValue(reviewerActor.agentId !== undefined, 'A reviewer sharing the implementer root session needs its host-issued child identity');
|
|
70
|
+
requireValue(implementerActor.agentId !== reviewerActor.agentId, 'A reviewer sharing the implementer root session needs a distinct child identity');
|
|
71
|
+
}
|
|
72
|
+
} else {
|
|
73
|
+
requireValue(report.reviewer.sessionId !== report.implementerSessionId, 'An independent reviewer with a distinct session ID is required');
|
|
74
|
+
}
|
|
75
|
+
requireValue(report.reviewer.independent === true, 'An independent reviewer is required');
|
|
76
|
+
requireValue(report.reviewer.scopeReviewed === true, 'Independent reviewer must attest scope completeness');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function canonical(value) {
|
|
80
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
|
81
|
+
if (isObject(value)) return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
|
|
82
|
+
return JSON.stringify(value);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function relativePath(value) {
|
|
86
|
+
requireValue(nonempty(value) && !value.includes('\\') && !value.includes('\0'), 'Expected a nonempty project-relative path such as docs/features/example/brief.md');
|
|
87
|
+
requireValue(!path.posix.isAbsolute(value) && !/^[a-z]:/i.test(value), `Expected a project-relative path; use a path relative to the project root, such as docs/features/example/brief.md, not absolute path: ${value}`);
|
|
88
|
+
requireValue(!value.split('/').includes('..'), `Parent traversal is not allowed: ${value}`);
|
|
89
|
+
const normalized = path.posix.normalize(value);
|
|
90
|
+
requireValue(normalized !== '.' && !normalized.endsWith('/'), `Expected a file path: ${value}`);
|
|
91
|
+
return normalized;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Reject symlinks on either read or write paths; the helper only owns local files.
|
|
95
|
+
export function localPath(root, value, allowMissing = false) {
|
|
96
|
+
const relative = relativePath(value);
|
|
97
|
+
let current = realpathSync(root);
|
|
98
|
+
const parts = relative.split('/');
|
|
99
|
+
for (let i = 0; i < parts.length; i++) {
|
|
100
|
+
current = path.join(current, parts[i]);
|
|
101
|
+
let stat;
|
|
102
|
+
try { stat = lstatSync(current); } catch (error) {
|
|
103
|
+
if (allowMissing && error.code === 'ENOENT') return path.join(realpathSync(root), relative);
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
requireValue(!stat.isSymbolicLink(), `Symlink paths are not supported: ${relative}`);
|
|
107
|
+
requireValue(i === parts.length - 1 ? stat.isFile() : stat.isDirectory(), `Not a plain ${i === parts.length - 1 ? 'file' : 'directory'}: ${relative}`);
|
|
108
|
+
}
|
|
109
|
+
return current;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function readLocal(root, value) {
|
|
113
|
+
return readFileSync(localPath(root, value));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Validate an intentionally absent local input without relaxing path safety. */
|
|
117
|
+
export function requireAbsent(root, value) {
|
|
118
|
+
const relative = relativePath(value);
|
|
119
|
+
localPath(root, relative, true);
|
|
120
|
+
requireValue(!existsSync(path.join(root, relative)), `Verification input declared absent exists: ${relative}`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function parseJson(bytes, label) {
|
|
124
|
+
try { return JSON.parse(bytes.toString('utf8')); } catch { throw new Error(`Invalid JSON: ${label}`); }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function validateCriteria(criteria) {
|
|
128
|
+
requireValue(Array.isArray(criteria) && criteria.length > 0, 'Verification needs at least one criterion');
|
|
129
|
+
const ids = new Set();
|
|
130
|
+
for (const criterion of criteria) {
|
|
131
|
+
requireValue(isObject(criterion) && nonempty(criterion.id) && !ids.has(criterion.id), 'Criterion IDs must be nonempty and unique');
|
|
132
|
+
ids.add(criterion.id);
|
|
133
|
+
requireValue(isObject(criterion.requirement) && nonempty(criterion.requirement.anchor), `Criterion ${criterion.id} needs a requirement anchor`);
|
|
134
|
+
relativePath(criterion.requirement.path);
|
|
135
|
+
requireValue(Array.isArray(criterion.requiredKinds) && criterion.requiredKinds.length > 0 && criterion.requiredKinds.every(kind => evidenceKinds.includes(kind)) && new Set(criterion.requiredKinds).size === criterion.requiredKinds.length, `Invalid required evidence kinds: ${criterion.id}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function validateScope(scope, label) {
|
|
140
|
+
requireValue(isObject(scope), `${label} scope must be an object`);
|
|
141
|
+
requireValue(Object.keys(scope).every(key => key === 'anchors' || key === 'decisionIds'), `${label} scope has an unknown selector key`);
|
|
142
|
+
const anchors = scope.anchors;
|
|
143
|
+
const decisionIds = scope.decisionIds;
|
|
144
|
+
requireValue((anchors === undefined || (Array.isArray(anchors) && anchors.length > 0 && anchors.every(nonempty) && new Set(anchors).size === anchors.length)) &&
|
|
145
|
+
(decisionIds === undefined || (Array.isArray(decisionIds) && decisionIds.length > 0 && decisionIds.every(nonempty) && new Set(decisionIds).size === decisionIds.length)) &&
|
|
146
|
+
(anchors !== undefined || decisionIds !== undefined), `${label} scope needs nonempty unique anchors or decisionIds`);
|
|
147
|
+
return {
|
|
148
|
+
...(anchors === undefined ? {} : { anchors: [...anchors] }),
|
|
149
|
+
...(decisionIds === undefined ? {} : { decisionIds: [...decisionIds] }),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** `select` limits criteria checks to the specs being worked on, so a sibling
|
|
154
|
+
* spec's unfinished criteria never block dispatch or review of another spec. */
|
|
155
|
+
export function validateQueue(queue, { select } = {}) {
|
|
156
|
+
requireValue(isObject(queue) && queue.schemaVersion === 1, 'Unsupported or missing queue schemaVersion');
|
|
157
|
+
requireValue(nonempty(queue.feature) && Array.isArray(queue.specs) && queue.specs.length > 0, 'Queue needs a feature and specs');
|
|
158
|
+
const ids = new Set();
|
|
159
|
+
const files = new Set();
|
|
160
|
+
for (const spec of queue.specs) {
|
|
161
|
+
requireValue(isObject(spec) && Number.isSafeInteger(spec.id) && spec.id >= 0 && !ids.has(spec.id), 'Spec IDs must be unique nonnegative integers');
|
|
162
|
+
ids.add(spec.id);
|
|
163
|
+
const file = relativePath(spec.file);
|
|
164
|
+
requireValue(!files.has(file), `Duplicate spec file: ${file}`);
|
|
165
|
+
files.add(file);
|
|
166
|
+
requireValue(statuses.includes(spec.status), `Invalid status for spec ${spec.id}`);
|
|
167
|
+
requireValue(['batch', 'checkpoint', 'isolated'].includes(spec.mode), `Invalid mode for spec ${spec.id}`);
|
|
168
|
+
if (spec.execution !== undefined) {
|
|
169
|
+
requireValue(isObject(spec.execution) && Object.keys(spec.execution).every(key => key === 'parallel') && typeof spec.execution.parallel === 'boolean', `Invalid execution plan for spec ${spec.id}; parallel must be a boolean`);
|
|
170
|
+
}
|
|
171
|
+
requireValue(Array.isArray(spec.depends_on) && spec.depends_on.every(Number.isSafeInteger) && !spec.depends_on.includes(spec.id) && new Set(spec.depends_on).size === spec.depends_on.length, `Invalid dependencies for spec ${spec.id}`);
|
|
172
|
+
requireValue(isObject(spec.verification) && Array.isArray(spec.verification.inputs), `Missing verification scope for spec ${spec.id}`);
|
|
173
|
+
if (!select || select(spec)) validateCriteria(spec.verification.criteria);
|
|
174
|
+
const inputs = new Set();
|
|
175
|
+
for (const [inputIndex, input] of spec.verification.inputs.entries()) {
|
|
176
|
+
requireValue(isObject(input) && kinds.includes(input.kind), `Invalid verification input at index ${inputIndex} for spec ${spec.id}: kind must be one of code, requirement, check, fixture; got ${JSON.stringify(input?.kind)}`);
|
|
177
|
+
const inputPath = relativePath(input.path);
|
|
178
|
+
requireValue(!inputs.has(inputPath), `Duplicate verification input: ${inputPath}`);
|
|
179
|
+
inputs.add(inputPath);
|
|
180
|
+
if (input.scope !== undefined) {
|
|
181
|
+
requireValue(input.kind === 'requirement', `Only requirement inputs may have a scope: ${inputPath}`);
|
|
182
|
+
validateScope(input.scope, `Verification input ${inputPath}`);
|
|
183
|
+
}
|
|
184
|
+
if (input.state !== undefined) requireValue(input.state === 'absent' && input.kind !== 'requirement', `Verification input ${inputPath} at index ${inputIndex} may use state: absent only for code, check or fixture inputs`);
|
|
185
|
+
}
|
|
186
|
+
if (spec.verification.changeScope !== undefined) validateChangeScope(spec.verification.changeScope, relativePath);
|
|
187
|
+
if (spec.acceptedReport !== undefined) {
|
|
188
|
+
requireValue(isObject(spec.acceptedReport) && isSha256(spec.acceptedReport.sha256), `Invalid accepted report for spec ${spec.id}`);
|
|
189
|
+
relativePath(spec.acceptedReport.path);
|
|
190
|
+
}
|
|
191
|
+
if (spec.ownerAcceptance !== undefined) {
|
|
192
|
+
requireValue(spec.acceptedReport === undefined, `Spec ${spec.id} cannot have both a PASS acceptance and an owner acceptance`);
|
|
193
|
+
requireValue(isObject(spec.ownerAcceptance) && isSha256(spec.ownerAcceptance.sha256), `Invalid owner acceptance for spec ${spec.id}`);
|
|
194
|
+
relativePath(spec.ownerAcceptance.path);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
for (const spec of queue.specs) requireValue(spec.depends_on.every(id => ids.has(id)), `Unknown dependency for spec ${spec.id}`);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function specStatus(bytes) {
|
|
201
|
+
const text = bytes.toString('utf8');
|
|
202
|
+
const frontmatter = /^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
203
|
+
requireValue(frontmatter, 'Spec needs YAML frontmatter');
|
|
204
|
+
const entries = [...frontmatter[1].matchAll(/^status:[ \t]*(?:([a-z-]+)|'([a-z-]+)'|"([a-z-]+)")([ \t]*(?:#[^\r\n]*)?)\r?$/gm)];
|
|
205
|
+
const declarations = [...frontmatter[1].matchAll(/^status\s*:/gm)];
|
|
206
|
+
requireValue(entries.length === 1 && declarations.length === 1, 'Spec needs exactly one plain top-level status');
|
|
207
|
+
const entry = entries[0];
|
|
208
|
+
const status = entry[1] ?? entry[2] ?? entry[3];
|
|
209
|
+
requireValue(statuses.includes(status), `Invalid spec frontmatter status: ${status}`);
|
|
210
|
+
const valueIndex = frontmatter.index + frontmatter[0].indexOf(frontmatter[1]) + entry.index + entry[0].indexOf(status);
|
|
211
|
+
return { status, replace: value => text.slice(0, valueIndex) + value + text.slice(valueIndex + status.length) };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function readQueue({ root = process.cwd(), queuePath, specId }) {
|
|
215
|
+
queuePath = relativePath(queuePath);
|
|
216
|
+
const queueBytes = readLocal(root, queuePath);
|
|
217
|
+
const queue = parseJson(queueBytes, queuePath);
|
|
218
|
+
validateQueue(queue, { select: item => item.id === specId });
|
|
219
|
+
const spec = queue.specs.find(item => item.id === specId);
|
|
220
|
+
requireValue(spec, `Spec ${specId} does not exist in queue`);
|
|
221
|
+
const specPath = path.posix.join(path.posix.dirname(queuePath), spec.file);
|
|
222
|
+
const specBytes = readLocal(root, specPath);
|
|
223
|
+
const status = specStatus(specBytes);
|
|
224
|
+
requireValue(status.status === spec.status, `Queue/spec status disagreement for spec ${specId}; restore consistency before proceeding`);
|
|
225
|
+
return { queuePath, queue, queueBytes, spec, specPath, specBytes, status };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export function subjectIdentity(subject) {
|
|
229
|
+
const { identity, ...fields } = subject;
|
|
230
|
+
return sha256(canonical(fields));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Queue status and completion receipt metadata do not change reviewed requirements. */
|
|
234
|
+
function queueSpecRequirements(spec) {
|
|
235
|
+
const requirements = { ...spec };
|
|
236
|
+
delete requirements.status;
|
|
237
|
+
delete requirements.acceptedReport;
|
|
238
|
+
delete requirements.ownerAcceptance;
|
|
239
|
+
return requirements;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function normalizedQueueForSubject(queue) {
|
|
243
|
+
return canonical({ ...queue, specs: queue.specs.map(queueSpecRequirements) });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function boundQueueForSubject(queue, specId) {
|
|
247
|
+
const byId = new Map(queue.specs.map(spec => [spec.id, spec]));
|
|
248
|
+
const included = new Set();
|
|
249
|
+
const include = id => {
|
|
250
|
+
requireValue(byId.has(id), `Unknown dependency ${id}`);
|
|
251
|
+
if (included.has(id)) return;
|
|
252
|
+
included.add(id);
|
|
253
|
+
for (const dependency of byId.get(id).depends_on) include(dependency);
|
|
254
|
+
};
|
|
255
|
+
include(specId);
|
|
256
|
+
const specIds = [...included].sort((left, right) => left - right);
|
|
257
|
+
const specs = queue.specs.filter(spec => included.has(spec.id)).map(queueSpecRequirements);
|
|
258
|
+
return { specIds, value: canonical({ ...queue, specs }) };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function markdownHeadingId(line) {
|
|
262
|
+
const match = /^(#{1,6})[ \t]+(.+?)[ \t]*$/.exec(line);
|
|
263
|
+
if (!match) return null;
|
|
264
|
+
const explicit = /\s+\{#([^}\s]+)\}\s*$/.exec(match[2]);
|
|
265
|
+
const title = (explicit ? match[2].slice(0, explicit.index) : match[2]).trim();
|
|
266
|
+
const slug = title.toLowerCase().replace(/[`*_~]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
|
267
|
+
return { level: match[1].length, id: explicit?.[1] ?? slug, line };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function markdownHeadings(lines, cursor, inputPath) {
|
|
271
|
+
const headings = [];
|
|
272
|
+
let fence = null;
|
|
273
|
+
for (let index = cursor; index < lines.length; index += 1) {
|
|
274
|
+
const line = lines[index].replace(/\r?\n$/, '');
|
|
275
|
+
const marker = /^(?: {0,3})(`{3,}|~{3,})/.exec(line);
|
|
276
|
+
if (fence) {
|
|
277
|
+
if (marker && marker[1][0] === fence.character && marker[1].length >= fence.length) fence = null;
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
if (marker) { fence = { character: marker[1][0], length: marker[1].length }; continue; }
|
|
281
|
+
const heading = markdownHeadingId(line);
|
|
282
|
+
if (heading) headings.push({ ...heading, index });
|
|
283
|
+
}
|
|
284
|
+
requireValue(fence === null, `Unclosed fenced code block in scoped requirement: ${inputPath}`);
|
|
285
|
+
return headings;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function jsonArrayAt(text, offset, inputPath) {
|
|
289
|
+
let start = offset;
|
|
290
|
+
while (/\s/.test(text[start] ?? '')) start += 1;
|
|
291
|
+
requireValue(text[start] === '[', `decisions must be a JSON array in ${inputPath}`);
|
|
292
|
+
let depth = 0, quote = false, escaped = false;
|
|
293
|
+
for (let index = start; index < text.length; index += 1) {
|
|
294
|
+
const char = text[index];
|
|
295
|
+
if (quote) {
|
|
296
|
+
if (escaped) escaped = false;
|
|
297
|
+
else if (char === '\\') escaped = true;
|
|
298
|
+
else if (char === '"') quote = false;
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
if (char === '"') quote = true;
|
|
302
|
+
else if (char === '[') depth += 1;
|
|
303
|
+
else if (char === ']') {
|
|
304
|
+
depth -= 1;
|
|
305
|
+
if (depth === 0) {
|
|
306
|
+
const raw = text.slice(start, index + 1);
|
|
307
|
+
try { return { records: JSON.parse(raw), end: index + 1 }; } catch { throw new Error(`Invalid decisions JSON array in ${inputPath}`); }
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
throw new Error(`Unclosed decisions JSON array in ${inputPath}`);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** The `decisions` JSON array in a Markdown brief's frontmatter, or [] when it declares none. */
|
|
315
|
+
export function briefDecisionRecords(bytes, inputPath) {
|
|
316
|
+
const text = Buffer.from(bytes).toString('utf8');
|
|
317
|
+
const frontmatter = /^(?:)?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
318
|
+
if (!frontmatter) return [];
|
|
319
|
+
const markers = [...frontmatter[1].matchAll(/^decisions\s*:/gm)];
|
|
320
|
+
if (markers.length === 0) return [];
|
|
321
|
+
requireValue(markers.length === 1, `decisions is duplicated in ${inputPath}`);
|
|
322
|
+
const offset = markers[0].index + markers[0][0].length;
|
|
323
|
+
const { records } = jsonArrayAt(frontmatter[1], offset, inputPath);
|
|
324
|
+
requireValue(Array.isArray(records), `decisions must be a JSON array in ${inputPath}`);
|
|
325
|
+
return records;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function selectDecisionRecords(records, ids, inputPath) {
|
|
329
|
+
requireValue(Array.isArray(records), `decisions must be a JSON array in ${inputPath}`);
|
|
330
|
+
return ids.map(id => {
|
|
331
|
+
const matches = records.filter(record => isObject(record) && record.id === id);
|
|
332
|
+
requireValue(matches.length === 1, `Decision ${id} is missing or ambiguous in ${inputPath}`);
|
|
333
|
+
return matches[0];
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function markdownScope(bytes, scope, inputPath) {
|
|
338
|
+
const text = bytes.toString('utf8');
|
|
339
|
+
const lines = text.split(/(?<=\n)/);
|
|
340
|
+
let cursor = 0;
|
|
341
|
+
let frontmatter = '';
|
|
342
|
+
let selectedDecisions;
|
|
343
|
+
if (/^(?:\uFEFF)?---\r?\n/.test(text)) {
|
|
344
|
+
const end = lines.findIndex((line, index) => index > 0 && /^---\r?\n?$/.test(line));
|
|
345
|
+
requireValue(end > 0, `Unclosed frontmatter in scoped requirement: ${inputPath}`);
|
|
346
|
+
const rawFrontmatter = lines.slice(1, end).join('');
|
|
347
|
+
const markers = [...rawFrontmatter.matchAll(/^decisions\s*:/gm)];
|
|
348
|
+
if (scope.decisionIds === undefined) {
|
|
349
|
+
// Without an explicit selector, decisions are part of the conservative
|
|
350
|
+
// whole-requirement context and cannot be silently ignored.
|
|
351
|
+
frontmatter = `${lines[0]}${rawFrontmatter}${lines[end]}`;
|
|
352
|
+
} else {
|
|
353
|
+
requireValue(markers.length === 1, `decisions is missing or duplicated in ${inputPath}`);
|
|
354
|
+
const marker = markers[0];
|
|
355
|
+
const parsed = jsonArrayAt(rawFrontmatter, marker.index + marker[0].length, inputPath);
|
|
356
|
+
selectedDecisions = selectDecisionRecords(parsed.records, scope.decisionIds, inputPath);
|
|
357
|
+
frontmatter = `${lines[0]}${rawFrontmatter.slice(0, marker.index)}${rawFrontmatter.slice(parsed.end)}${lines[end]}`;
|
|
358
|
+
}
|
|
359
|
+
cursor = end + 1;
|
|
360
|
+
}
|
|
361
|
+
if (scope.decisionIds !== undefined) requireValue(frontmatter !== '', `Decision-scoped Markdown requirement needs frontmatter: ${inputPath}`);
|
|
362
|
+
// The supported subset is ATX (`#`) headings outside fenced code blocks.
|
|
363
|
+
// Setext/linked headings are deliberately not selectors.
|
|
364
|
+
const headings = markdownHeadings(lines, cursor, inputPath);
|
|
365
|
+
const firstHeading = headings[0]?.index ?? lines.length;
|
|
366
|
+
const selected = [];
|
|
367
|
+
for (const anchor of scope.anchors ?? []) {
|
|
368
|
+
const matches = headings.filter(heading => heading.id === anchor);
|
|
369
|
+
requireValue(matches.length === 1, `Requirement anchor ${anchor} is missing or ambiguous in ${inputPath}`);
|
|
370
|
+
selected.push(matches[0]);
|
|
371
|
+
}
|
|
372
|
+
const chunks = [frontmatter, lines.slice(cursor, firstHeading).join('')];
|
|
373
|
+
const ancestorIndexes = new Set();
|
|
374
|
+
for (const heading of selected) {
|
|
375
|
+
for (const candidate of headings) {
|
|
376
|
+
if (candidate.index >= heading.index || candidate.level >= heading.level) continue;
|
|
377
|
+
const nextAtLevel = headings.find(next => next.index > candidate.index && next.level <= candidate.level);
|
|
378
|
+
if (!nextAtLevel || nextAtLevel.index > heading.index) ancestorIndexes.add(candidate.index);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
for (const index of [...ancestorIndexes].sort((a, b) => a - b)) {
|
|
382
|
+
const heading = headings.find(item => item.index === index);
|
|
383
|
+
const next = headings.find(item => item.index > index && item.level <= heading.level)?.index ?? lines.length;
|
|
384
|
+
const directChild = headings.find(item => item.index > index && item.index < next)?.index ?? next;
|
|
385
|
+
chunks.push(lines.slice(index, directChild).join(''));
|
|
386
|
+
}
|
|
387
|
+
for (const heading of [...selected].sort((a, b) => a.index - b.index)) {
|
|
388
|
+
const end = headings.find(next => next.index > heading.index && next.level <= heading.level)?.index ?? lines.length;
|
|
389
|
+
chunks.push(lines.slice(heading.index, end).join(''));
|
|
390
|
+
}
|
|
391
|
+
const value = { frontmatterAndPreamble: chunks.slice(0, 2) };
|
|
392
|
+
if (scope.anchors === undefined) value.fullBody = lines.slice(cursor).join('');
|
|
393
|
+
else {
|
|
394
|
+
value.ancestorDirectText = chunks.slice(2, 2 + ancestorIndexes.size);
|
|
395
|
+
value.selectedSubtrees = chunks.slice(2 + ancestorIndexes.size);
|
|
396
|
+
}
|
|
397
|
+
if (selectedDecisions !== undefined) value.decisionRecords = selectedDecisions;
|
|
398
|
+
return canonical(value);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function decisionRecords(value) {
|
|
402
|
+
if (Array.isArray(value)) return value;
|
|
403
|
+
if (isObject(value) && Array.isArray(value.decisions)) return value.decisions;
|
|
404
|
+
throw new Error('Decision-scoped requirement JSON needs a top-level array or decisions array');
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export function scopedRequirementForSubject(bytes, scope, inputPath) {
|
|
408
|
+
const normalized = validateScope(scope, `Verification input ${inputPath}`);
|
|
409
|
+
if (normalized.decisionIds !== undefined) {
|
|
410
|
+
try {
|
|
411
|
+
const value = parseJson(bytes, inputPath);
|
|
412
|
+
requireValue(normalized.anchors === undefined, `anchors are not supported for a JSON decision requirement: ${inputPath}`);
|
|
413
|
+
const records = decisionRecords(value);
|
|
414
|
+
const selected = selectDecisionRecords(records, normalized.decisionIds, inputPath);
|
|
415
|
+
if (Array.isArray(value)) return canonical({ decisionRecords: selected });
|
|
416
|
+
const { decisions, ...nondecisionMetadata } = value;
|
|
417
|
+
return canonical({ nondecisionMetadata, decisionRecords: selected });
|
|
418
|
+
} catch (error) {
|
|
419
|
+
if (!String(error.message).startsWith('Invalid JSON:')) throw error;
|
|
420
|
+
return markdownScope(bytes, normalized, inputPath);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return markdownScope(bytes, normalized, inputPath);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function criterionCoveredByScope(scope, anchor) {
|
|
427
|
+
if (scope === undefined) return true;
|
|
428
|
+
const decision = /^frontmatter\.decisions\.([^\.\s]+)$/.exec(anchor);
|
|
429
|
+
if (decision) return scope.decisionIds === undefined || scope.decisionIds.includes(decision[1]);
|
|
430
|
+
return scope.anchors === undefined || scope.anchors.includes(anchor);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export function snapshot({ root = process.cwd(), queuePath, specId, implementationRevision, bindingVersion = 1, artifactPaths = [] }) {
|
|
434
|
+
requireValue(bindingVersion === 0 || bindingVersion === 1, 'Unsupported binding version');
|
|
435
|
+
const state = readQueue({ root, queuePath, specId });
|
|
436
|
+
const { queue, spec, specPath } = state;
|
|
437
|
+
queuePath = state.queuePath;
|
|
438
|
+
const briefPath = path.posix.join(path.posix.dirname(path.posix.dirname(queuePath)), 'brief.md');
|
|
439
|
+
const declared = spec.verification.inputs.map(input => ({ path: relativePath(input.path), kind: input.kind, ...(input.state === undefined ? {} : { state: input.state }), ...(input.scope === undefined ? {} : { scope: validateScope(input.scope, `Verification input ${input.path}`) }) }));
|
|
440
|
+
for (const required of [specPath, briefPath, ...spec.verification.criteria.map(criterion => relativePath(criterion.requirement.path))]) {
|
|
441
|
+
requireValue(declared.some(input => input.path === required && input.kind === 'requirement'), `Verification inputs must explicitly bind required ${required === briefPath ? 'brief' : 'requirement'}: ${required}; queues belong at docs/features/<feature>/specs/.joycraft-spec-queue.json, with the brief at docs/features/<feature>/brief.md. Current queue: ${queuePath}`);
|
|
442
|
+
}
|
|
443
|
+
const queueInput = declared.find(input => input.path === queuePath);
|
|
444
|
+
requireValue(!queueInput || queueInput.kind === 'requirement', `The queue input ${queuePath} must use kind requirement; got ${queueInput?.kind}`);
|
|
445
|
+
if (!queueInput) declared.push({ path: queuePath, kind: 'requirement' });
|
|
446
|
+
const specPaths = new Set(queue.specs.map(item => path.posix.join(path.posix.dirname(queuePath), item.file)));
|
|
447
|
+
const queueBinding = bindingVersion === 1 ? boundQueueForSubject(queue, specId) : null;
|
|
448
|
+
const governing = bindingVersion === 1 ? declared.filter(input => input.kind === 'requirement' && input.scope !== undefined).map(input => ({ path: input.path, ...input.scope })) : [];
|
|
449
|
+
for (const criterion of spec.verification.criteria) {
|
|
450
|
+
const input = declared.find(candidate => candidate.path === criterion.requirement.path);
|
|
451
|
+
requireValue(criterionCoveredByScope(input?.scope, criterion.requirement.anchor), `Criterion anchor ${criterion.requirement.anchor} is omitted by requirement scope: ${input.path}`);
|
|
452
|
+
}
|
|
453
|
+
// Scope is checked before any input snapshotting, so an undeclared change
|
|
454
|
+
// cannot be hidden behind a later review or completion artifact.
|
|
455
|
+
const changeScope = spec.verification.changeScope === undefined ? undefined : captureChangeScope({ root, changeScope: spec.verification.changeScope, relativePath, inputs: declared, artifactPaths, topologyIgnoredPaths: [queuePath, ...specPaths] });
|
|
456
|
+
const inputs = declared.sort((a, b) => a.path.localeCompare(b.path, 'en')).map(input => {
|
|
457
|
+
requireValue(!(input.path === queuePath || input.path === specPath) || input.scope === undefined, `Queue and own spec inputs cannot narrow their binding: ${input.path}`);
|
|
458
|
+
const absent = input.state === 'absent';
|
|
459
|
+
if (absent) requireAbsent(root, input.path);
|
|
460
|
+
const bytes = absent ? Buffer.from(`joycraft:absent:${input.path}\n`) : readLocal(root, input.path);
|
|
461
|
+
let normalized = bytes;
|
|
462
|
+
let normalization = absent ? 'absent' : 'none';
|
|
463
|
+
if (!absent && input.path === queuePath) {
|
|
464
|
+
normalized = bindingVersion === 1 ? queueBinding.value : normalizedQueueForSubject(queue);
|
|
465
|
+
normalization = bindingVersion === 1 ? 'queue-scope' : 'queue-status';
|
|
466
|
+
} else if (!absent && specPaths.has(input.path)) {
|
|
467
|
+
normalized = specStatus(bytes).replace('__review_status__');
|
|
468
|
+
normalization = 'spec-status';
|
|
469
|
+
} else if (!absent && input.scope !== undefined) {
|
|
470
|
+
normalized = scopedRequirementForSubject(bytes, input.scope, input.path);
|
|
471
|
+
normalization = 'requirement-scope';
|
|
472
|
+
}
|
|
473
|
+
return { ...input, sha256: sha256(normalized), normalization };
|
|
474
|
+
});
|
|
475
|
+
if (implementationRevision === undefined) {
|
|
476
|
+
implementationRevision = execFileSync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
477
|
+
}
|
|
478
|
+
requireValue(typeof implementationRevision === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(implementationRevision), 'Invalid implementation revision');
|
|
479
|
+
let objectType;
|
|
480
|
+
try {
|
|
481
|
+
objectType = execFileSync('git', ['cat-file', '-t', implementationRevision], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
482
|
+
} catch { throw new Error('Implementation revision is not available in this repository'); }
|
|
483
|
+
requireValue(objectType === 'commit', 'Implementation revision must name a commit');
|
|
484
|
+
const subject = { schemaVersion: 1, implementationRevision, queuePath, specId, specPath, criteria: spec.verification.criteria, inputs, ...(bindingVersion === 1 ? { binding: { version: 1, queue: { specIds: queueBinding.specIds }, governing, ...(changeScope === undefined ? {} : { changeScope }) } } : {}) };
|
|
485
|
+
return { ...subject, identity: subjectIdentity(subject) };
|
|
486
|
+
}
|