joycraft 0.7.17 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +148 -140
- package/dist/cli.js +1593 -373
- package/dist/cli.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 +109 -0
- package/payload/.agents/skills/joycraft-implement/SKILL.md +118 -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 +82 -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 +36 -0
- package/payload/.claude/agents/joycraft-reviewer.md +35 -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 +85 -0
- package/payload/.joycraft/references/delivery.md +32 -0
- package/payload/.joycraft/references/dispatch.md +231 -0
- package/payload/.joycraft/references/recurring-failures.md +33 -0
- package/payload/.joycraft/references/retro.md +94 -0
- package/payload/.joycraft/references/setup.md +295 -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 +174 -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/coordinator.mjs +169 -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 +106 -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/status.mjs +96 -0
- package/payload/.joycraft/runtime/update-check.mjs +142 -0
- package/payload/.joycraft/runtime/worktrees.mjs +201 -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 +77 -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-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-YLWBDXF4.js +0 -3999
- package/dist/chunk-YLWBDXF4.js.map +0 -1
- package/dist/chunk-Z5JFEGWG.js +0 -563
- package/dist/chunk-Z5JFEGWG.js.map +0 -1
- package/dist/init-O2QC5X57.js +0 -60
- package/dist/init-O2QC5X57.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-LYHS4FBH.js +0 -21
- package/dist/update-LYHS4FBH.js.map +0 -1
- package/dist/update-check-YT765NE7.js +0 -36
- package/dist/update-check-YT765NE7.js.map +0 -1
- package/dist/upgrade-GMP6JQ52.js +0 -28
- package/dist/upgrade-GMP6JQ52.js.map +0 -1
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { canonical, isObject, isSha256, localPath, nonempty, parseJson, readLocal, readQueue, relativePath, requireValue, sha256, snapshot, subjectIdentity, validateIndependentReview } from './identity.mjs';
|
|
6
|
+
|
|
7
|
+
export { snapshot } from './identity.mjs';
|
|
8
|
+
|
|
9
|
+
export function journalPath(queuePath) {
|
|
10
|
+
return path.posix.join(path.posix.dirname(relativePath(queuePath)), '.joycraft-completion.pending.json');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function recoveryHint(queuePath) {
|
|
14
|
+
return `Recovery required: inspect ${journalPath(queuePath)}, then run node .joycraft/runtime/completion.mjs recover --queue ${JSON.stringify(queuePath)} to restore the two saved pre-completion files. Recovery refuses edits made after the interruption.`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function assertNoJournal(root, queuePath) {
|
|
18
|
+
requireValue(!existsSync(localPath(root, journalPath(queuePath), true)), recoveryHint(queuePath));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function saveExclusive(file, bytes) {
|
|
22
|
+
const fd = openSync(file, 'wx', 0o600);
|
|
23
|
+
try { writeFileSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function replaceFile(root, relative, bytes) {
|
|
27
|
+
const file = localPath(root, relative);
|
|
28
|
+
const temporary = `${file}.joycraft-${randomUUID()}.tmp`;
|
|
29
|
+
try {
|
|
30
|
+
saveExclusive(temporary, bytes);
|
|
31
|
+
renameSync(temporary, file);
|
|
32
|
+
} finally {
|
|
33
|
+
if (existsSync(temporary)) unlinkSync(temporary);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Validate the parts of an independent review that remain meaningful even when
|
|
39
|
+
* its verdict is not acceptable for ordinary completion. This is a current
|
|
40
|
+
* subject check; archival separately validates historical requirement bindings
|
|
41
|
+
* without renewing the review's implementation evidence.
|
|
42
|
+
*/
|
|
43
|
+
export function validateReview({ root = process.cwd(), report, state, reportPath, artifactPaths = [] }) {
|
|
44
|
+
reportPath = relativePath(reportPath);
|
|
45
|
+
requireValue(isObject(report) && report.schemaVersion === 1, 'Unsupported or missing report schemaVersion');
|
|
46
|
+
requireValue(isObject(report.subject) && report.subject.schemaVersion === 1, 'Unsupported or missing subject schemaVersion');
|
|
47
|
+
validateIndependentReview(report);
|
|
48
|
+
requireValue(['PASS', 'FAIL', 'UNVERIFIED'].includes(report.verdict), 'Report verdict must be PASS, FAIL or UNVERIFIED');
|
|
49
|
+
requireValue(Array.isArray(report.unresolved) && report.unresolved.every(nonempty), 'Report unresolved findings must be an array of nonempty strings');
|
|
50
|
+
requireValue(nonempty(report.createdAt) && Number.isFinite(Date.parse(report.createdAt)), 'Report needs a valid createdAt timestamp');
|
|
51
|
+
requireValue(Array.isArray(report.flows) && report.flows.length > 0, 'Report needs flow evidence');
|
|
52
|
+
const subject = report.subject;
|
|
53
|
+
requireValue(subject.queuePath === state.queuePath && subject.specId === state.spec.id && subject.specPath === state.specPath, 'Report subject does not match this queue/spec');
|
|
54
|
+
requireValue(isSha256(subject.identity) && subjectIdentity(subject) === subject.identity, 'Invalid subject identity');
|
|
55
|
+
const receiptPaths = report.flows.flatMap(flow => Array.isArray(flow?.observations) ? flow.observations.flatMap(observation => Array.isArray(observation?.receipts) ? observation.receipts.map(receipt => receipt?.path).filter(nonempty) : []) : []);
|
|
56
|
+
const current = snapshot({ root, queuePath: state.queuePath, specId: state.spec.id, implementationRevision: subject.implementationRevision, bindingVersion: subject.binding === undefined ? 0 : 1, artifactPaths: [reportPath, journalPath(state.queuePath), ...artifactPaths, ...receiptPaths] });
|
|
57
|
+
requireValue(canonical(subject) === canonical(current), 'Stale report: current code, requirements, checks, fixtures or verification scope differ from the reviewed subject');
|
|
58
|
+
requireValue(!subject.inputs.some(input => input.path === reportPath), 'Report cannot be a bound verification input');
|
|
59
|
+
for (const flow of report.flows) {
|
|
60
|
+
requireValue(isObject(flow) && flow.subjectIdentity === subject.identity && Array.isArray(flow.observations), 'Flow evidence must match the reviewed subject');
|
|
61
|
+
for (const observation of flow.observations) {
|
|
62
|
+
requireValue(isObject(observation) && Array.isArray(observation.receipts), 'Observation needs receipt references');
|
|
63
|
+
for (const receipt of observation.receipts) {
|
|
64
|
+
requireValue(isObject(receipt) && isSha256(receipt.sha256), 'Invalid receipt digest');
|
|
65
|
+
const receiptPath = relativePath(receipt.path);
|
|
66
|
+
requireValue(receiptPath !== state.queuePath && receiptPath !== state.specPath && receiptPath !== reportPath, 'Receipt must be separate from report and completion metadata');
|
|
67
|
+
if (subject.binding !== undefined) requireValue(!subject.inputs.some(input => input.path === receiptPath), `Receipt must be an independent captured output, not a mutable verification input: ${receiptPath}`);
|
|
68
|
+
requireValue(sha256(readLocal(root, receiptPath)) === receipt.sha256, `Receipt is missing or changed: ${receiptPath}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function validatePassingReport(root, report, state, reportPath) {
|
|
75
|
+
validateReview({ root, report, state, reportPath });
|
|
76
|
+
requireValue(report.verdict === 'PASS', 'Report verdict must be PASS; FAIL or UNVERIFIED cannot complete a spec');
|
|
77
|
+
requireValue(report.unresolved.length === 0, 'Report has unresolved review findings');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Validate a completed reviewer report without changing either completion status
|
|
82
|
+
* surface. Dispatch adapters use this before returning a report to the same
|
|
83
|
+
* reviewer for correction; only complete() is allowed to accept it.
|
|
84
|
+
*/
|
|
85
|
+
export async function checkReport({ root = process.cwd(), queuePath, specId, reportPath }) {
|
|
86
|
+
queuePath = relativePath(queuePath);
|
|
87
|
+
reportPath = relativePath(reportPath);
|
|
88
|
+
const state = readQueue({ root, queuePath, specId });
|
|
89
|
+
const reportBytes = readLocal(root, reportPath);
|
|
90
|
+
const report = parseJson(reportBytes, reportPath);
|
|
91
|
+
validatePassingReport(root, report, state, reportPath);
|
|
92
|
+
// Missing or broken peer validation is an error, never a passing fallback.
|
|
93
|
+
const { validateEvidence } = await import('./evidence.mjs');
|
|
94
|
+
requireValue(typeof validateEvidence === 'function', 'Evidence validator is unavailable');
|
|
95
|
+
const evidence = validateEvidence(report, state.spec.verification.criteria);
|
|
96
|
+
requireValue(isObject(evidence) && evidence.ok === true && Array.isArray(evidence.errors) && evidence.errors.length === 0, `Evidence rejected: ${Array.isArray(evidence?.errors) ? evidence.errors.join('; ') : 'invalid validator response'}`);
|
|
97
|
+
return { report, reportBytes, state, acceptedReport: { path: reportPath, sha256: sha256(reportBytes) } };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function restore(root, journal) {
|
|
101
|
+
// Preflight both surfaces before restoring either one; never erase a later edit.
|
|
102
|
+
for (const file of journal.files) {
|
|
103
|
+
const digest = sha256(readLocal(root, file.path));
|
|
104
|
+
requireValue(digest === file.before.sha256 || digest === file.after.sha256, `Recovery conflict: ${file.path} has subsequent edits; preserve them and reconcile with the journal before retrying`);
|
|
105
|
+
}
|
|
106
|
+
for (const file of journal.files) {
|
|
107
|
+
if (sha256(readLocal(root, file.path)) !== file.before.sha256) replaceFile(root, file.path, Buffer.from(file.before.base64, 'base64'));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function recover({ root = process.cwd(), queuePath }) {
|
|
112
|
+
queuePath = relativePath(queuePath);
|
|
113
|
+
const pendingPath = journalPath(queuePath);
|
|
114
|
+
const pendingFile = localPath(root, pendingPath);
|
|
115
|
+
const journal = parseJson(readFileSync(pendingFile), pendingPath);
|
|
116
|
+
requireValue(isObject(journal) && journal.schemaVersion === 1 && journal.queuePath === queuePath && Number.isSafeInteger(journal.specId) && Array.isArray(journal.files) && journal.files.length === 2, 'Invalid completion journal; preserve it for manual recovery');
|
|
117
|
+
for (const file of journal.files) {
|
|
118
|
+
requireValue(isObject(file) && nonempty(file.path), 'Invalid journal file');
|
|
119
|
+
relativePath(file.path);
|
|
120
|
+
for (const version of [file.before, file.after]) {
|
|
121
|
+
requireValue(isObject(version) && typeof version.base64 === 'string' && isSha256(version.sha256) && sha256(Buffer.from(version.base64, 'base64')) === version.sha256, 'Invalid journal backup digest; preserve it for manual recovery');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
requireValue(journal.files[1].path === queuePath, 'Journal queue path mismatch');
|
|
125
|
+
const beforeQueue = parseJson(Buffer.from(journal.files[1].before.base64, 'base64'), 'journal queue backup');
|
|
126
|
+
const beforeSpec = beforeQueue.specs?.find(spec => spec.id === journal.specId);
|
|
127
|
+
requireValue(beforeSpec && journal.files[0].path === path.posix.join(path.posix.dirname(queuePath), relativePath(beforeSpec.file)), 'Journal spec path mismatch');
|
|
128
|
+
restore(root, journal);
|
|
129
|
+
unlinkSync(pendingFile);
|
|
130
|
+
return { status: 'restored', queuePath, specId: journal.specId };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function writeCompletion({ root, queuePath, specId, state, metadataKey, metadata, validate, stableFiles }) {
|
|
134
|
+
const updatedQueue = structuredClone(state.queue);
|
|
135
|
+
Object.assign(updatedQueue.specs.find(spec => spec.id === specId), { status: 'done', [metadataKey]: metadata });
|
|
136
|
+
const journal = {
|
|
137
|
+
schemaVersion: 1, queuePath, specId,
|
|
138
|
+
files: [
|
|
139
|
+
{ path: state.specPath, before: state.specBytes, after: Buffer.from(state.status.replace('done')) },
|
|
140
|
+
{ path: queuePath, before: state.queueBytes, after: Buffer.from(`${JSON.stringify(updatedQueue, null, 2)}\n`) },
|
|
141
|
+
].map(file => ({ path: file.path, before: { sha256: sha256(file.before), base64: file.before.toString('base64') }, after: { sha256: sha256(file.after), base64: file.after.toString('base64') } })),
|
|
142
|
+
};
|
|
143
|
+
const pendingFile = localPath(root, journalPath(queuePath), true);
|
|
144
|
+
try { saveExclusive(pendingFile, `${JSON.stringify(journal, null, 2)}\n`); } catch (error) {
|
|
145
|
+
throw new Error(`${error.message}. ${recoveryHint(queuePath)}`);
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
for (const stable of stableFiles) requireValue(sha256(readLocal(root, stable.path)) === stable.sha256, `${stable.label} changed during completion`);
|
|
149
|
+
for (const file of journal.files) requireValue(sha256(readLocal(root, file.path)) === file.before.sha256, `Completion conflict: ${file.path} changed during validation`);
|
|
150
|
+
validate(state);
|
|
151
|
+
for (const file of journal.files) {
|
|
152
|
+
requireValue(sha256(readLocal(root, file.path)) === file.before.sha256, `Completion conflict: ${file.path} changed before write`);
|
|
153
|
+
replaceFile(root, file.path, Buffer.from(file.after.base64, 'base64'));
|
|
154
|
+
}
|
|
155
|
+
// Catch overlapping worker edits during the two writes before accepting them.
|
|
156
|
+
for (const file of journal.files) requireValue(sha256(readLocal(root, file.path)) === file.after.sha256, `Completion conflict: ${file.path} changed after write`);
|
|
157
|
+
for (const stable of stableFiles) requireValue(sha256(readLocal(root, stable.path)) === stable.sha256, `${stable.label} changed during completion`);
|
|
158
|
+
validate(readQueue({ root, queuePath, specId }));
|
|
159
|
+
unlinkSync(pendingFile);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
let restoration = 'The original statuses were restored.';
|
|
162
|
+
try { restore(root, journal); } catch (restoreError) { restoration = restoreError.message; }
|
|
163
|
+
throw new Error(`${error.message}. ${restoration} ${recoveryHint(queuePath)}`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function complete({ root = process.cwd(), queuePath, specId, reportPath }) {
|
|
168
|
+
queuePath = relativePath(queuePath);
|
|
169
|
+
reportPath = relativePath(reportPath);
|
|
170
|
+
assertNoJournal(root, queuePath);
|
|
171
|
+
const state = readQueue({ root, queuePath, specId });
|
|
172
|
+
requireValue(state.spec.status === 'in-review' || state.spec.status === 'done', 'Only an in-review spec can move to done');
|
|
173
|
+
const checked = await checkReport({ root, queuePath, specId, reportPath });
|
|
174
|
+
const { report, acceptedReport } = checked;
|
|
175
|
+
if (state.spec.status === 'done') {
|
|
176
|
+
requireValue(state.spec.ownerAcceptance === undefined, 'Done spec has an owner acceptance; ordinary completion cannot relabel it as PASS');
|
|
177
|
+
requireValue(canonical(state.spec.acceptedReport) === canonical(acceptedReport), 'Done spec already has a different accepted report; it cannot be silently replaced');
|
|
178
|
+
return { status: 'done', unchanged: true, acceptedReport, implementationRevision: report.subject.implementationRevision };
|
|
179
|
+
}
|
|
180
|
+
requireValue(state.spec.acceptedReport === undefined && state.spec.ownerAcceptance === undefined, 'In-review spec already has completion metadata; reconcile its status before retrying');
|
|
181
|
+
await writeCompletion({
|
|
182
|
+
root, queuePath, specId, state, metadataKey: 'acceptedReport', metadata: acceptedReport,
|
|
183
|
+
stableFiles: [{ path: reportPath, sha256: acceptedReport.sha256, label: 'Report' }],
|
|
184
|
+
validate: currentState => validatePassingReport(root, report, currentState, reportPath),
|
|
185
|
+
});
|
|
186
|
+
return { status: 'done', unchanged: false, acceptedReport, implementationRevision: report.subject.implementationRevision };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The native host attests the instruction text before this helper runs. Local
|
|
191
|
+
* JSON cannot authenticate that a human said it, so this validates only the
|
|
192
|
+
* scoped binding and deliberately never treats the text as cryptographic proof.
|
|
193
|
+
*/
|
|
194
|
+
export function validateOwnerAcceptance({ decision, decisionPath, state, report, reportPath, reportBytes }) {
|
|
195
|
+
decisionPath = relativePath(decisionPath);
|
|
196
|
+
reportPath = relativePath(reportPath);
|
|
197
|
+
requireValue(isObject(decision) && decision.schemaVersion === 1 && decision.kind === 'owner-acceptance', 'Owner acceptance needs schemaVersion 1 and kind owner-acceptance');
|
|
198
|
+
requireValue(Object.keys(decision).every(key => ['schemaVersion', 'kind', 'queuePath', 'specId', 'subjectIdentity', 'review', 'instruction', 'limitations', 'createdAt'].includes(key)), 'Owner acceptance has unknown fields');
|
|
199
|
+
requireValue(decision.queuePath === state.queuePath && decision.specId === state.spec.id, 'Owner acceptance does not match this queue/spec');
|
|
200
|
+
requireValue(isObject(decision.review) && relativePath(decision.review.path) === reportPath && isSha256(decision.review.sha256), 'Owner acceptance review receipt must name this report and have a SHA-256 digest');
|
|
201
|
+
requireValue(decisionPath !== state.queuePath && decisionPath !== state.specPath && decisionPath !== reportPath, 'Owner acceptance decision must be separate from queue, spec and review report');
|
|
202
|
+
requireValue(!report.subject.inputs.some(input => input.path === decisionPath), 'Owner acceptance decision cannot be a verification input');
|
|
203
|
+
requireValue(nonempty(decision.instruction), 'Owner acceptance needs the exact nonempty human instruction');
|
|
204
|
+
requireValue(Array.isArray(decision.limitations) && decision.limitations.length > 0 && decision.limitations.every(nonempty), 'Owner acceptance needs one or more nonempty limitations');
|
|
205
|
+
requireValue(nonempty(decision.createdAt) && Number.isFinite(Date.parse(decision.createdAt)), 'Owner acceptance needs a valid createdAt timestamp');
|
|
206
|
+
requireValue(decision.subjectIdentity === report.subject.identity, 'Owner acceptance subject identity does not match the review');
|
|
207
|
+
requireValue(sha256(reportBytes) === decision.review.sha256, 'Owner acceptance references a missing or changed review report');
|
|
208
|
+
requireValue(report.verdict === 'FAIL' || report.verdict === 'UNVERIFIED', 'Owner acceptance is only for a FAIL or UNVERIFIED review; PASS must use ordinary completion');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function ownerEvidenceErrors(report, criteria) {
|
|
212
|
+
// Evidence remains diagnostic here. An owner exception must make the failed
|
|
213
|
+
// checks visible, but cannot convert their result into a passing condition.
|
|
214
|
+
try {
|
|
215
|
+
const { validateEvidence } = await import('./evidence.mjs');
|
|
216
|
+
if (typeof validateEvidence !== 'function') return ['Evidence validator is unavailable'];
|
|
217
|
+
const result = validateEvidence(report, criteria);
|
|
218
|
+
return Array.isArray(result?.errors) ? result.errors : ['Evidence validator returned an invalid result'];
|
|
219
|
+
} catch (error) {
|
|
220
|
+
return [`Evidence validator is unavailable: ${error.message}`];
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export async function acceptOwner({ root = process.cwd(), queuePath, specId, decisionPath }) {
|
|
225
|
+
queuePath = relativePath(queuePath);
|
|
226
|
+
decisionPath = relativePath(decisionPath);
|
|
227
|
+
assertNoJournal(root, queuePath);
|
|
228
|
+
const state = readQueue({ root, queuePath, specId });
|
|
229
|
+
requireValue(state.spec.status === 'in-review' || state.spec.status === 'done', 'Only an in-review spec can move to done');
|
|
230
|
+
const decisionBytes = readLocal(root, decisionPath);
|
|
231
|
+
const decision = parseJson(decisionBytes, decisionPath);
|
|
232
|
+
requireValue(isObject(decision.review) && nonempty(decision.review.path), 'Owner acceptance needs a review receipt');
|
|
233
|
+
const reportPath = relativePath(decision.review.path);
|
|
234
|
+
const reportBytes = readLocal(root, reportPath);
|
|
235
|
+
const report = parseJson(reportBytes, reportPath);
|
|
236
|
+
validateReview({ root, report, state, reportPath, artifactPaths: [decisionPath] });
|
|
237
|
+
validateOwnerAcceptance({ root, decision, decisionPath, state, report, reportPath, reportBytes });
|
|
238
|
+
const evidenceErrors = await ownerEvidenceErrors(report, state.spec.verification.criteria);
|
|
239
|
+
const ownerAcceptance = { path: decisionPath, sha256: sha256(decisionBytes) };
|
|
240
|
+
if (state.spec.status === 'done') {
|
|
241
|
+
requireValue(state.spec.acceptedReport === undefined, 'Done spec has an accepted PASS report; owner acceptance cannot replace it');
|
|
242
|
+
requireValue(canonical(state.spec.ownerAcceptance) === canonical(ownerAcceptance), 'Done spec already has a different owner acceptance; it cannot be silently replaced');
|
|
243
|
+
return { status: 'done', unchanged: true, ownerAcceptance, verdict: report.verdict, unresolved: report.unresolved, evidenceErrors, limitations: decision.limitations, implementationRevision: report.subject.implementationRevision };
|
|
244
|
+
}
|
|
245
|
+
requireValue(state.spec.acceptedReport === undefined && state.spec.ownerAcceptance === undefined, 'In-review spec already has completion metadata; reconcile its status before retrying');
|
|
246
|
+
await writeCompletion({
|
|
247
|
+
root, queuePath, specId, state, metadataKey: 'ownerAcceptance', metadata: ownerAcceptance,
|
|
248
|
+
stableFiles: [
|
|
249
|
+
{ path: reportPath, sha256: decision.review.sha256, label: 'Review report' },
|
|
250
|
+
{ path: decisionPath, sha256: ownerAcceptance.sha256, label: 'Owner acceptance decision' },
|
|
251
|
+
],
|
|
252
|
+
validate: currentState => {
|
|
253
|
+
validateReview({ root, report, state: currentState, reportPath, artifactPaths: [decisionPath] });
|
|
254
|
+
validateOwnerAcceptance({ root, decision, decisionPath, state: currentState, report, reportPath, reportBytes });
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
return { status: 'done', unchanged: false, ownerAcceptance, verdict: report.verdict, unresolved: report.unresolved, evidenceErrors, limitations: decision.limitations, implementationRevision: report.subject.implementationRevision };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function argumentsFor(argv) {
|
|
261
|
+
const [command, ...args] = argv;
|
|
262
|
+
requireValue(['snapshot', 'scope', 'complete', 'finalize-review', 'accept-owner', 'recover'].includes(command), 'Usage: completion.mjs scope --queue <path> --spec <id> | snapshot --queue <path> --spec <id> --out <subject.json> | complete|finalize-review --queue <path> --spec <id> --report <report.json> | accept-owner --queue <path> --spec <id> --decision <decision.json> | recover --queue <path>');
|
|
263
|
+
const flags = {};
|
|
264
|
+
for (let i = 0; i < args.length; i += 2) {
|
|
265
|
+
requireValue(['--queue', '--spec', '--out', '--report', '--decision'].includes(args[i]) && nonempty(args[i + 1]) && flags[args[i]] === undefined, `Invalid or duplicate argument: ${args[i]}`);
|
|
266
|
+
flags[args[i]] = args[i + 1];
|
|
267
|
+
}
|
|
268
|
+
const expected = command === 'recover' ? ['--queue'] : command === 'scope' ? ['--queue', '--spec'] : ['--queue', '--spec', command === 'snapshot' ? '--out' : command === 'accept-owner' ? '--decision' : '--report'];
|
|
269
|
+
requireValue(Object.keys(flags).length === expected.length && expected.every(flag => flags[flag] !== undefined), `Missing or unexpected arguments for ${command}`);
|
|
270
|
+
if (command !== 'recover') requireValue(/^(?:0|[1-9]\d*)$/.test(flags['--spec']) && Number.isSafeInteger(Number(flags['--spec'])), 'Spec ID must be a nonnegative integer');
|
|
271
|
+
return { command, flags };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
275
|
+
const { command, flags } = argumentsFor(argv);
|
|
276
|
+
const root = process.cwd();
|
|
277
|
+
const queuePath = flags['--queue'];
|
|
278
|
+
let result;
|
|
279
|
+
if (command === 'snapshot') {
|
|
280
|
+
assertNoJournal(root, queuePath);
|
|
281
|
+
result = snapshot({ root, queuePath, specId: Number(flags['--spec']) });
|
|
282
|
+
const outPath = relativePath(flags['--out']);
|
|
283
|
+
requireValue(!result.inputs.some(input => input.path === outPath), 'Snapshot output cannot replace a verification input');
|
|
284
|
+
const out = localPath(root, outPath, true);
|
|
285
|
+
mkdirSync(path.dirname(out), { recursive: true });
|
|
286
|
+
saveExclusive(out, `${JSON.stringify(result, null, 2)}\n`);
|
|
287
|
+
} else if (command === 'scope') {
|
|
288
|
+
assertNoJournal(root, queuePath);
|
|
289
|
+
const current = snapshot({ root, queuePath, specId: Number(flags['--spec']) });
|
|
290
|
+
result = { queuePath: current.queuePath, specId: current.specId, changeScope: current.binding?.changeScope ?? null };
|
|
291
|
+
} else if (command === 'recover') result = recover({ root, queuePath });
|
|
292
|
+
else if (command === 'accept-owner') result = await acceptOwner({ root, queuePath, specId: Number(flags['--spec']), decisionPath: flags['--decision'] });
|
|
293
|
+
else result = await complete({ root, queuePath, specId: Number(flags['--spec']), reportPath: flags['--report'] });
|
|
294
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
295
|
+
return result;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
|
299
|
+
main().catch(error => { process.stderr.write(`Completion stopped: ${error.message}\n`); process.exitCode = 1; });
|
|
300
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, open, readFile, realpath } from 'node:fs/promises';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { rankContext } from './index.mjs';
|
|
6
|
+
import { safeRelativePath } from './search.mjs';
|
|
7
|
+
|
|
8
|
+
async function saveReport(report, path, root) {
|
|
9
|
+
if (!safeRelativePath(path)) throw new Error('invalid-output-path: use a project-relative new file');
|
|
10
|
+
const project = await realpath(root);
|
|
11
|
+
const parts = path.split('/');
|
|
12
|
+
for (let index = 1; index < parts.length; index += 1) {
|
|
13
|
+
const stat = await lstat(join(project, ...parts.slice(0, index)));
|
|
14
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('invalid-output-path: parents must be plain directories');
|
|
15
|
+
}
|
|
16
|
+
let file;
|
|
17
|
+
try { file = await open(join(project, path), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|
|
18
|
+
catch { throw new Error('invalid-output-path: choose a new file in an existing directory'); }
|
|
19
|
+
try { await file.writeFile(`${JSON.stringify(report, null, 2)}\n`); }
|
|
20
|
+
finally { await file.close(); }
|
|
21
|
+
return { schemaVersion: report.schemaVersion, report: path, status: report.status,
|
|
22
|
+
provenance: report.provenance, fallbackReason: report.fallbackReason,
|
|
23
|
+
candidateCount: report.candidateCount, scoredCount: report.scoredCount,
|
|
24
|
+
omittedCount: report.omitted.length, unreadableCount: report.unreadable.length,
|
|
25
|
+
unrankedCount: report.unranked.length };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function runCli(args, options = {}) {
|
|
29
|
+
let query, paths, keychainService, out, includeArchive = false;
|
|
30
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
31
|
+
const flag = args[index];
|
|
32
|
+
if (flag === '--history') {
|
|
33
|
+
if (includeArchive) throw new Error('invalid-arguments: --history may appear once');
|
|
34
|
+
includeArchive = true;
|
|
35
|
+
} else if (flag === '--paths') {
|
|
36
|
+
if (paths) throw new Error('invalid-arguments: --paths may appear once');
|
|
37
|
+
paths = [];
|
|
38
|
+
while (args[index + 1] && !args[index + 1].startsWith('--')) paths.push(args[++index]);
|
|
39
|
+
if (!paths.length) throw new Error('invalid-arguments: --paths needs project-relative paths');
|
|
40
|
+
} else if (flag === '--query' || flag === '--keychain-service' || flag === '--out') {
|
|
41
|
+
const value = args[++index];
|
|
42
|
+
if (!value || value.startsWith('--')) throw new Error('invalid-arguments: missing option value');
|
|
43
|
+
if (flag === '--query') {
|
|
44
|
+
if (query !== undefined) throw new Error('invalid-arguments: duplicate --query');
|
|
45
|
+
query = value;
|
|
46
|
+
} else if (flag === '--keychain-service') {
|
|
47
|
+
if (keychainService !== undefined) throw new Error('invalid-arguments: duplicate --keychain-service');
|
|
48
|
+
keychainService = value;
|
|
49
|
+
} else {
|
|
50
|
+
if (out !== undefined) throw new Error('invalid-arguments: duplicate --out');
|
|
51
|
+
if (!safeRelativePath(value)) throw new Error('invalid-output-path: use a project-relative new file');
|
|
52
|
+
out = value;
|
|
53
|
+
}
|
|
54
|
+
} else throw new Error('invalid-arguments: use --query <request> [--paths <paths...>] [--history] [--out <new-report.json>] [--keychain-service <service>]');
|
|
55
|
+
}
|
|
56
|
+
// An install without the optional ranker has no ranking config; local search needs none.
|
|
57
|
+
const config = options.config ?? await readFile(new URL('../../hooks-config.json', import.meta.url), 'utf8').then(JSON.parse,
|
|
58
|
+
error => { if (error.code === 'ENOENT') return { schemaVersion: 1, enabled: false, keychainService: 'context-ranking', timeoutMs: 4500 }; throw error; });
|
|
59
|
+
if (config.schemaVersion !== 1 || typeof config.keychainService !== 'string'
|
|
60
|
+
|| typeof config.enabled !== 'boolean' || !Number.isSafeInteger(config.timeoutMs) || config.timeoutMs <= 0) throw new Error('invalid-context-config');
|
|
61
|
+
keychainService ??= config.keychainService;
|
|
62
|
+
if (!/^[A-Za-z0-9_.-]{1,128}$/.test(keychainService)) throw new Error('invalid-keychain-service');
|
|
63
|
+
const report = await rankContext({ query, ...(paths ? { paths } : {}), includeArchive }, { ...options,
|
|
64
|
+
enabled: config.enabled, timeoutMs: config.timeoutMs, keychainService });
|
|
65
|
+
return out ? saveReport(report, out, options.root ?? process.cwd()) : report;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
69
|
+
try { console.log(JSON.stringify(await runCli(process.argv.slice(2)), null, 2)); }
|
|
70
|
+
catch (error) {
|
|
71
|
+
const safe = /^(invalid-query|invalid-paths|invalid-arguments|invalid-context-config|invalid-keychain-service|invalid-output-path|inventory-unavailable)(:|$)/.test(error.message);
|
|
72
|
+
console.error(safe ? error.message : 'context-command-failed: check the project and installed context runtime');
|
|
73
|
+
process.exitCode = 1;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { findCandidates } from './search.mjs';
|
|
2
|
+
|
|
3
|
+
// An optional model ranker orders the candidates when it is installed; without
|
|
4
|
+
// it, every candidate stays available in local-search order.
|
|
5
|
+
async function loadRanker() {
|
|
6
|
+
try { return (await import('./rank-model.mjs')).rankReferences; }
|
|
7
|
+
catch (error) { if (error?.code === 'ERR_MODULE_NOT_FOUND') return null; throw error; }
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Rank all selected references. Scores are reading advice, never a scope boundary. */
|
|
11
|
+
export async function rankContext(request, options = {}) {
|
|
12
|
+
const found = await findCandidates(request, options);
|
|
13
|
+
const references = found.candidates.map((candidate, index) => ({
|
|
14
|
+
id: `c${index + 1}`, ...candidate, relevance: null, provenance: 'local-search', batch: null,
|
|
15
|
+
}));
|
|
16
|
+
const rank = options.enabled === false ? null : options.rank ?? await loadRanker();
|
|
17
|
+
const reason = options.enabled === false ? 'scoring-disabled' : 'ranker-not-installed';
|
|
18
|
+
const ranked = rank ? await rank(references, request, options)
|
|
19
|
+
: { batches: [], unranked: references.map(({ path }) => ({ path, reason })), failed: null, provenance: 'local-search' };
|
|
20
|
+
const { batches, unranked, failed } = ranked;
|
|
21
|
+
references.sort((a, b) => (b.relevance ?? -1) - (a.relevance ?? -1) || b.localScore - a.localScore || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
22
|
+
return { schemaVersion: 1, query: request.query,
|
|
23
|
+
provenance: failed ? 'local-search-fallback' : rank && references.length ? ranked.provenance : 'local-search',
|
|
24
|
+
status: failed ? 'incomplete-provider-ranking' : !rank ? 'local-search-only' : references.length ? 'ranked-selected-candidates' : 'no-local-candidates',
|
|
25
|
+
fallbackReason: failed,
|
|
26
|
+
discovery: found.discovery, candidateCount: references.length, scoredCount: rank ? references.filter(item => item.provenance === ranked.provenance).length : 0,
|
|
27
|
+
references, omitted: found.omitted, unreadable: found.unreadable, unranked, batches,
|
|
28
|
+
limitation: 'Relevance scores are advice, not calibrated correctness or an exhaustive project search. Hashes identify the bytes read; open the source before relying on or editing it.' };
|
|
29
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { lstat, open, realpath } from 'node:fs/promises';
|
|
5
|
+
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
|
|
8
|
+
const exec = promisify(execFile);
|
|
9
|
+
export const MAX_FILE_BYTES = 512 * 1024;
|
|
10
|
+
export const MAX_SNIPPET_BYTES = 1800;
|
|
11
|
+
const stopWords = new Set('a an and are as at be by can do for from how i in is it me my of on or our that the this to we what when where which with'.split(' '));
|
|
12
|
+
|
|
13
|
+
export function safeRelativePath(path) {
|
|
14
|
+
return typeof path === 'string' && path.length > 0 && !isAbsolute(path)
|
|
15
|
+
&& !path.includes('\\') && !path.includes('\0')
|
|
16
|
+
&& !path.split('/').some(part => part === '..' || part === '.' || part === '')
|
|
17
|
+
&& !/^[a-z]:/i.test(path);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function excludedReason(path) {
|
|
21
|
+
if (!safeRelativePath(path)) return 'unsafe-path';
|
|
22
|
+
const parts = path.toLowerCase().split('/');
|
|
23
|
+
if (parts.some(part => ['.git', 'node_modules', '.ssh', '.aws', '.gnupg', '.venv', 'venv'].includes(part))) return 'excluded-directory';
|
|
24
|
+
if (parts.some(part => /^\.env($|[._-])/.test(part))) return 'sensitive-path';
|
|
25
|
+
if (parts.some(part => /transcripts?|sessions?|chat[-_]?logs?/.test(part))) return 'private-transcript-path';
|
|
26
|
+
if (parts.some(part => /(^|[._-])(secrets?|credentials?|tokens?|passwords?)([._-]|$)/.test(part))) return 'sensitive-path';
|
|
27
|
+
const name = parts.at(-1);
|
|
28
|
+
if (/^\.npmrc$|^\.netrc$|^\.pypirc$|^id_(rsa|dsa|ecdsa|ed25519)($|\.)|\.(env|pem|key|p12|pfx|jks|keystore|keychain|keychain-db)$/.test(name)) return 'sensitive-path';
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function archivedReason(path, includeArchive) {
|
|
33
|
+
return !includeArchive && (path === 'docs/archive' || path.startsWith('docs/archive/')) ? 'archived-context' : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function keywords(query) {
|
|
37
|
+
return [...new Set((query.toLowerCase().match(/[\p{L}\p{N}_-]{2,}/gu) ?? [])
|
|
38
|
+
.filter(word => !stopWords.has(word)))];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function clipped(text, bytes) {
|
|
42
|
+
let result = '';
|
|
43
|
+
let used = 0;
|
|
44
|
+
for (const char of text) {
|
|
45
|
+
const size = Buffer.byteLength(char);
|
|
46
|
+
if (used + size > bytes) break;
|
|
47
|
+
result += char;
|
|
48
|
+
used += size;
|
|
49
|
+
}
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function excerpt(text, terms) {
|
|
54
|
+
const lines = text.split('\n');
|
|
55
|
+
const hit = lines.findIndex(line => terms.some(term => line.toLowerCase().includes(term)));
|
|
56
|
+
const start = Math.max(0, (hit < 0 ? 0 : hit) - 2);
|
|
57
|
+
const snippet = clipped(lines.slice(start).join('\n'), MAX_SNIPPET_BYTES);
|
|
58
|
+
return { text: snippet, startLine: start + 1, endLine: start + snippet.split('\n').length,
|
|
59
|
+
truncated: start > 0 || Buffer.byteLength(lines.slice(start).join('\n')) > MAX_SNIPPET_BYTES };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function readSafeFile(root, path) {
|
|
63
|
+
const parts = path.split('/');
|
|
64
|
+
const observed = [];
|
|
65
|
+
for (let index = 1; index <= parts.length; index += 1) {
|
|
66
|
+
const stat = await lstat(join(root, ...parts.slice(0, index)));
|
|
67
|
+
if (stat.isSymbolicLink()) return { reason: 'symlink-not-read' };
|
|
68
|
+
if (index < parts.length && !stat.isDirectory()) return { reason: 'non-directory-parent' };
|
|
69
|
+
if (index === parts.length && !stat.isFile()) return { reason: 'not-a-regular-file' };
|
|
70
|
+
observed.push(stat);
|
|
71
|
+
}
|
|
72
|
+
const resolved = await realpath(join(root, path));
|
|
73
|
+
const distance = relative(root, resolved);
|
|
74
|
+
if (distance.startsWith(`..${sep}`) || distance === '..' || isAbsolute(distance)) return { reason: 'outside-project' };
|
|
75
|
+
const file = await open(resolved, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
76
|
+
try {
|
|
77
|
+
const stat = await file.stat();
|
|
78
|
+
if (!stat.isFile()) return { reason: 'not-a-regular-file' };
|
|
79
|
+
if (stat.dev !== observed.at(-1).dev || stat.ino !== observed.at(-1).ino) return { reason: 'file-changed-during-open' };
|
|
80
|
+
for (let index = 1; index <= parts.length; index += 1) {
|
|
81
|
+
const current = await lstat(join(root, ...parts.slice(0, index)));
|
|
82
|
+
if (current.isSymbolicLink() || current.dev !== observed[index - 1].dev || current.ino !== observed[index - 1].ino) return { reason: 'path-changed-during-open' };
|
|
83
|
+
}
|
|
84
|
+
if (stat.size > MAX_FILE_BYTES) return { reason: 'file-exceeds-512-kib', bytes: stat.size };
|
|
85
|
+
const buffer = Buffer.alloc(MAX_FILE_BYTES + 1);
|
|
86
|
+
let length = 0;
|
|
87
|
+
while (length < buffer.length) {
|
|
88
|
+
const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
|
|
89
|
+
if (bytesRead === 0) break;
|
|
90
|
+
length += bytesRead;
|
|
91
|
+
}
|
|
92
|
+
if (length > MAX_FILE_BYTES) return { reason: 'file-exceeds-512-kib', bytes: length };
|
|
93
|
+
const bytes = buffer.subarray(0, length);
|
|
94
|
+
if (bytes.includes(0)) return { reason: 'binary-file' };
|
|
95
|
+
let text;
|
|
96
|
+
try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
|
|
97
|
+
catch { return { reason: 'non-utf8-file' }; }
|
|
98
|
+
return { text, bytes: length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
99
|
+
} finally { await file.close(); }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Discover references without following symlinks or reading ignored/private paths. */
|
|
103
|
+
export async function findCandidates({ query, paths, includeArchive = false }, { root = process.cwd() } = {}) {
|
|
104
|
+
if (typeof query !== 'string' || !query.trim() || Buffer.byteLength(query) > 4000) throw new Error('invalid-query: supply 1–4000 UTF-8 bytes');
|
|
105
|
+
if (paths !== undefined && (!Array.isArray(paths) || !paths.length || paths.some(path => !safeRelativePath(path)))) throw new Error('invalid-paths: use project-relative files or directories');
|
|
106
|
+
if (typeof includeArchive !== 'boolean') throw new Error('invalid-include-archive: use a boolean');
|
|
107
|
+
const project = await realpath(root);
|
|
108
|
+
let stdout;
|
|
109
|
+
try {
|
|
110
|
+
({ stdout } = await exec('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
|
|
111
|
+
cwd: project, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024,
|
|
112
|
+
}));
|
|
113
|
+
} catch { throw new Error('inventory-unavailable: run from a readable Git project'); }
|
|
114
|
+
const inventory = [...new Set(stdout.split('\0').filter(Boolean))].sort();
|
|
115
|
+
const terms = keywords(query);
|
|
116
|
+
const candidates = [], omitted = [], unreadable = [];
|
|
117
|
+
const selections = paths && [...new Set(paths)];
|
|
118
|
+
for (const path of inventory) {
|
|
119
|
+
const archive = archivedReason(path, includeArchive);
|
|
120
|
+
if (archive) { omitted.push({ path, reason: archive }); continue; }
|
|
121
|
+
const exclusion = excludedReason(path);
|
|
122
|
+
if (exclusion) { omitted.push({ path, reason: exclusion }); continue; }
|
|
123
|
+
if (selections && !selections.some(selected => path === selected || path.startsWith(`${selected}/`))) {
|
|
124
|
+
omitted.push({ path, reason: 'outside-selected-paths' }); continue;
|
|
125
|
+
}
|
|
126
|
+
let file;
|
|
127
|
+
try { file = await readSafeFile(project, path); }
|
|
128
|
+
catch (error) { unreadable.push({ path, reason: error?.code === 'ENOENT' ? 'file-missing' : 'file-unreadable' }); continue; }
|
|
129
|
+
if (file.reason) { omitted.push({ path, reason: file.reason, ...(file.bytes === undefined ? {} : { bytes: file.bytes }) }); continue; }
|
|
130
|
+
const lowerPath = path.toLowerCase(), lowerText = file.text.toLowerCase();
|
|
131
|
+
const pathMatches = terms.filter(term => lowerPath.includes(term));
|
|
132
|
+
const contentMatches = terms.filter(term => lowerText.includes(term));
|
|
133
|
+
const localScore = pathMatches.length * 3 + contentMatches.length;
|
|
134
|
+
if (!selections && localScore === 0) { omitted.push({ path, reason: 'no-keyword-match' }); continue; }
|
|
135
|
+
candidates.push({ path, sha256: file.sha256, bytes: file.bytes, localScore,
|
|
136
|
+
matches: { path: pathMatches, content: contentMatches }, snippet: excerpt(file.text, terms) });
|
|
137
|
+
}
|
|
138
|
+
if (selections) {
|
|
139
|
+
for (const path of selections) {
|
|
140
|
+
if (!inventory.some(entry => entry === path || entry.startsWith(`${path}/`))) omitted.push({ path, reason: excludedReason(path) ?? 'not-in-git-inventory' });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
candidates.sort((a, b) => b.localScore - a.localScore || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
144
|
+
return { candidates, omitted, unreadable, discovery: { method: 'git-keyword-path', terms,
|
|
145
|
+
paths: selections ?? null, inventoryCount: inventory.length, maxFileBytes: MAX_FILE_BYTES,
|
|
146
|
+
maxSnippetBytes: MAX_SNIPPET_BYTES, exhaustive: false,
|
|
147
|
+
includeArchive,
|
|
148
|
+
limitation: 'Local keyword/path selection can miss paraphrases; excluded, unreadable and unmatched files are not scored.' } };
|
|
149
|
+
}
|