@olegkoval/agent-skills 1.82.0 → 1.84.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/adapters/claude/olko-github-pr/skills/lekker-review/SKILL.md +13 -3
- package/adapters/claude/olko-github-pr/skills/lekker-review/references/boundary-evidence.md +73 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/references/codex-workflow.md +19 -2
- package/adapters/claude/olko-github-pr/skills/lekker-review/references/defect-evaluation.md +82 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/references/evidence-efficiency-ablation.md +59 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/boundary-cases.mjs +44 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/boundary-filesystem.mjs +24 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/boundary-invocation.mjs +25 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/boundary-probe-contract.mjs +33 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/boundary-probe-runner.mjs +92 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/boundary-probe.mjs +22 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/boundary-report.mjs +29 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/boundary-source.mjs +21 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/boundary-validation.mjs +97 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/defect-scoring.mjs +56 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/eval-runner.mjs +30 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/evidence-bundle.mjs +30 -13
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/evidence-packet.mjs +74 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/native-results.mjs +13 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/normalize-native-result.mjs +31 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/stage-ledger.mjs +96 -0
- package/package.json +1 -1
- package/plugins/olko-apple-kit/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-creative/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-garmin-kit/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-git-tools/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-github-pr/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-github-pr/skills/lekker-review/SKILL.md +13 -3
- package/plugins/olko-github-pr/skills/lekker-review/references/boundary-evidence.md +73 -0
- package/plugins/olko-github-pr/skills/lekker-review/references/codex-workflow.md +19 -2
- package/plugins/olko-github-pr/skills/lekker-review/references/defect-evaluation.md +82 -0
- package/plugins/olko-github-pr/skills/lekker-review/references/evidence-efficiency-ablation.md +59 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/boundary-cases.mjs +44 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/boundary-filesystem.mjs +24 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/boundary-invocation.mjs +25 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/boundary-probe-contract.mjs +33 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/boundary-probe-runner.mjs +92 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/boundary-probe.mjs +22 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/boundary-report.mjs +29 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/boundary-source.mjs +21 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/boundary-validation.mjs +97 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/defect-scoring.mjs +56 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/eval-runner.mjs +30 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/evidence-bundle.mjs +30 -13
- package/plugins/olko-github-pr/skills/lekker-review/scripts/evidence-packet.mjs +74 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/native-results.mjs +13 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/normalize-native-result.mjs +31 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/stage-ledger.mjs +96 -0
- package/plugins/olko-obsidian/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-product/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-reflection/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-release/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-skill-meta/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-web-ops/.claude-plugin/plugin.json +1 -1
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, relative, isAbsolute } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const record = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
+
const fullSha = value => typeof value === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value);
|
|
7
|
+
const digest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
|
8
|
+
const sha256 = value => createHash('sha256').update(value).digest('hex');
|
|
9
|
+
const MODULES = ['boundary-cases.mjs', 'boundary-filesystem.mjs', 'boundary-invocation.mjs',
|
|
10
|
+
'boundary-probe-contract.mjs', 'boundary-probe-runner.mjs', 'boundary-report.mjs', 'boundary-source.mjs', 'boundary-validation.mjs', 'git-evidence.mjs'];
|
|
11
|
+
|
|
12
|
+
export function validateBoundaryReport(probe, git) {
|
|
13
|
+
try {
|
|
14
|
+
if (probe?.status !== 'available' || typeof probe.reportFile !== 'string') return { captureStatus: 'unavailable', reason: probe?.reason ?? 'trusted boundary probe unavailable' };
|
|
15
|
+
const bytes = readFileSync(probe.reportFile), digestValue = createHash('sha256').update(bytes).digest('hex');
|
|
16
|
+
const report = JSON.parse(bytes.toString('utf8'));
|
|
17
|
+
const invalid = validateShape(report, git);
|
|
18
|
+
if (digestValue !== probe.reportSha256 || invalid) return { captureStatus: 'unavailable', reason: invalid ?? 'boundary artifact hash mismatch' };
|
|
19
|
+
const reducedFailure = readReducedFailure(report, probe.reportFile);
|
|
20
|
+
return { captureStatus: 'available', reportPath: probe.reportFile, reportSha256: digestValue,
|
|
21
|
+
provenance: report.provenance, summary: { candidateCount: report.candidates.length,
|
|
22
|
+
inputCount: report.results.length, evidenceClass: 'composed trusted CLI probe',
|
|
23
|
+
...(reducedFailure ? { reducedFailure } : {}) }, report };
|
|
24
|
+
} catch { return { captureStatus: 'unavailable', reason: 'trusted boundary artifact is missing or malformed' }; }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function readReducedFailure(report, reportFile) {
|
|
28
|
+
if (!report.reducedCounterexample) return null;
|
|
29
|
+
const row = report.results.find(result => result.id === report.reducedCounterexample.id);
|
|
30
|
+
const run = row.runs.defective;
|
|
31
|
+
const root = realpathSync(dirname(reportFile));
|
|
32
|
+
if (realpathSync(report.artifactRoot) !== root || run.stderrFile !== `${row.id}-defective/stderr.raw`) throw new Error('invalid boundary artifact path');
|
|
33
|
+
const path = realpathSync(join(root, run.stderrFile)), inside = relative(root, path);
|
|
34
|
+
if (!inside || inside.startsWith('..') || isAbsolute(inside)) throw new Error('boundary artifact escaped output directory');
|
|
35
|
+
const stderr = readFileSync(path);
|
|
36
|
+
if (sha256(stderr) !== run.stderrSha256 || !stderr.includes('ENAMETOOLONG')) throw new Error('boundary stderr does not support failure class');
|
|
37
|
+
return { caseId: row.id, exitClass: run.exitClass, failureCode: 'ENAMETOOLONG',
|
|
38
|
+
stderrFile: run.stderrFile, stderrSha256: run.stderrSha256 };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function validRun(run) {
|
|
42
|
+
if (!record(run) || run.status !== 'observed' || !digest(run.stdoutSha256) || !digest(run.stderrSha256)
|
|
43
|
+
|| typeof run.stdoutFile !== 'string' || typeof run.stderrFile !== 'string') return false;
|
|
44
|
+
return run.exitClass === 'success' && run.exitCode === 0 || run.exitClass === 'component-limit' && run.exitCode === 1;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function defectCandidate(row) {
|
|
48
|
+
return row.runs.original.exitClass === 'success' && row.runs.defective.exitClass === 'component-limit'
|
|
49
|
+
&& (!row.runs.repaired || row.runs.repaired.exitClass === 'success');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function validateShape(report, git) {
|
|
53
|
+
if (!record(report) || report.schema !== 1 || report.status !== 'available' || typeof report.source !== 'string'
|
|
54
|
+
|| report.source.startsWith('/') || report.source.split('/').some(part => !part || part === '.' || part === '..')) return 'boundary report identity is invalid';
|
|
55
|
+
if (git?.status !== 'available' || !Array.isArray(git.changedPaths) || !git.changedPaths.includes(report.source)
|
|
56
|
+
|| report.provenance?.baseSha !== git.provenance?.baseSha || report.provenance?.headSha !== git.provenance?.headSha) return 'boundary report Git identity mismatch';
|
|
57
|
+
if (!Array.isArray(report.results) || report.results.length === 0 || report.results.length > 100
|
|
58
|
+
|| report.contract?.count !== report.results.length || !Number.isSafeInteger(report.contract?.maxComponentBytes)
|
|
59
|
+
|| report.contract.maxComponentBytes < 1 || typeof report.contract.validInput !== 'string'
|
|
60
|
+
|| !Number.isSafeInteger(report.seed) || !Array.isArray(report.candidates)) return 'boundary report coverage is empty, malformed, or over budget';
|
|
61
|
+
if (!fullSha(report.provenance.sources?.original?.commit) || report.provenance.sources.original.commit !== git.provenance.baseSha
|
|
62
|
+
|| !fullSha(report.provenance.sources?.defective?.commit) || report.provenance.sources.defective.commit !== git.provenance.headSha
|
|
63
|
+
|| !digest(report.provenance.sources.original.sha256) || !digest(report.provenance.sources.defective.sha256)
|
|
64
|
+
|| !digest(report.provenance.adapterSha256) || !digest(report.provenance.generatorSha256)
|
|
65
|
+
|| !record(report.provenance.moduleSha256) || Object.keys(report.provenance.moduleSha256).sort().join(',') !== MODULES.slice().sort().join(',')
|
|
66
|
+
|| Object.values(report.provenance.moduleSha256).some(value => !digest(value))
|
|
67
|
+
|| typeof report.provenance.runtime !== 'string' || typeof report.provenance.trustedRoot !== 'string'
|
|
68
|
+
|| !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(report.provenance.repoSlug ?? '')) return 'boundary report source provenance is invalid';
|
|
69
|
+
const roles = report.provenance.sources.repaired ? ['original', 'defective', 'repaired'] : ['original', 'defective'];
|
|
70
|
+
if (roles.includes('repaired') && (!fullSha(report.provenance.sources.repaired.commit) || !digest(report.provenance.sources.repaired.sha256))) return 'boundary repaired source provenance is invalid';
|
|
71
|
+
const ids = report.results.map(row => row?.id);
|
|
72
|
+
if (new Set(ids).size !== ids.length) return 'boundary input identifiers are duplicated';
|
|
73
|
+
for (const row of report.results) {
|
|
74
|
+
if (!record(row) || typeof row.id !== 'string' || !/^[a-z0-9-]+$/.test(row.id)
|
|
75
|
+
|| typeof row.input !== 'string' || !/^[a-z0-9-]+$/.test(row.input)
|
|
76
|
+
|| row.status !== 'available' || row.inputBytes !== Buffer.byteLength(row.input) || row.inputSha256 !== sha256(row.input)) return 'boundary input coverage is invalid';
|
|
77
|
+
if (!record(row.runs) || roles.some(role => !validRun(row.runs[role]))) return 'boundary invocation outcome is incomplete';
|
|
78
|
+
}
|
|
79
|
+
const expected = report.results.filter(defectCandidate).map(row => row.id).sort(), candidates = report.candidates;
|
|
80
|
+
if (expected.length !== candidates.length || new Set(candidates.map(candidate => candidate?.id)).size !== candidates.length) return 'boundary candidate summary does not match observed outcomes';
|
|
81
|
+
if (candidates.some(candidate => {
|
|
82
|
+
const row = report.results.find(result => result.id === candidate?.id);
|
|
83
|
+
return !row || !expected.includes(candidate.id) || candidate.input !== row.input || candidate.inputSha256 !== row.inputSha256
|
|
84
|
+
|| candidate.evidenceClass !== 'composed trusted CLI probe';
|
|
85
|
+
})) return 'boundary candidate identity does not match observed outcomes';
|
|
86
|
+
if (candidates.some(candidate => {
|
|
87
|
+
const row = report.results.find(result => result.id === candidate.id);
|
|
88
|
+
return roles.some(role => candidate.outcomes?.[role] !== row.runs[role].exitCode);
|
|
89
|
+
})) return 'boundary candidate outcomes do not match invocation outcomes';
|
|
90
|
+
const reduced = report.reducedCounterexample;
|
|
91
|
+
if (!candidates.length) return reduced == null ? null : 'boundary reduced input has no candidate';
|
|
92
|
+
const row = report.results.find(result => result.id === reduced?.id);
|
|
93
|
+
if (!record(reduced) || !row || !candidates.some(candidate => candidate.id === row.id)
|
|
94
|
+
|| reduced.input !== row.input || reduced.inputSha256 !== row.inputSha256
|
|
95
|
+
|| roles.some(role => reduced.outcomes?.[role] !== row.runs[role].exitCode)) return 'boundary reduced input does not match observed candidate';
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Score already-validated defect evidence without reading files or observing time.
|
|
2
|
+
import { validateDefectEvaluation, validateDefectManifest } from './defect-policy.mjs'
|
|
3
|
+
|
|
4
|
+
const requireEvaluations = value => {
|
|
5
|
+
if (!Array.isArray(value)) throw new Error('evaluations must be an array')
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function scoreEvaluation(manifest, registry, evaluations, evaluation, index) {
|
|
9
|
+
const previousRunIds = evaluations.slice(0, index).map(item => item?.run?.runId)
|
|
10
|
+
const checked = validateDefectEvaluation(manifest, evaluation, evaluation?.findingsSha256, previousRunIds)
|
|
11
|
+
if (!checked.valid) return { available: false, reason: checked.reason, caseId: checked.caseId, index }
|
|
12
|
+
const { runId, caseId, testCase, decisions } = checked
|
|
13
|
+
const confirmed = decisions.filter(item => item.verdict === 'confirmed').map(item => item.defectId)
|
|
14
|
+
const unique = confirmed.filter((id, itemIndex, all) => all.indexOf(id) === itemIndex)
|
|
15
|
+
const known = unique.filter(id => registry.defectIds.includes(id))
|
|
16
|
+
const unknown = unique.filter(id => !registry.defectIds.includes(id))
|
|
17
|
+
const unexpected = unique.filter(id => !testCase.expectedDefects.includes(id))
|
|
18
|
+
const unresolved = decisions.filter(item => item.verdict === 'unresolved').length
|
|
19
|
+
const needsAdjudication = unexpected.length > 0
|
|
20
|
+
return { available: unresolved === 0 && !needsAdjudication,
|
|
21
|
+
reason: unresolved ? 'unresolved adjudication' : needsAdjudication ? 'confirmed defect outside case contract needs corpus adjudication' : null,
|
|
22
|
+
caseId, runId, expected: testCase.expectedDefects, knownConfirmed: known, unknownConfirmed: unknown,
|
|
23
|
+
unexpectedConfirmed: unexpected, confirmedClaims: confirmed.length,
|
|
24
|
+
falseAlarms: decisions.filter(item => item.verdict === 'false-alarm').length,
|
|
25
|
+
unresolved, judged: unresolved === 0, clean: testCase.expectedDefects.length === 0, needsAdjudication }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function summarize(manifest, rows) {
|
|
29
|
+
const ready = rows.filter(row => row.available)
|
|
30
|
+
const judged = rows.filter(row => row.judged)
|
|
31
|
+
const coverageComplete = manifest.cases.every(testCase => rows.filter(row => row.available && row.caseId === testCase.id).length === testCase.expectedRuns)
|
|
32
|
+
&& rows.every(row => row.available)
|
|
33
|
+
const expected = ready.reduce((count, row) => count + row.expected.length, 0)
|
|
34
|
+
const detected = ready.reduce((count, row) => count + row.knownConfirmed.filter(id => row.expected.includes(id)).length, 0)
|
|
35
|
+
const confirmedClaims = judged.reduce((count, row) => count + row.confirmedClaims, 0)
|
|
36
|
+
const uniqueConfirmed = judged.reduce((count, row) => count + row.knownConfirmed.length + row.unknownConfirmed.length, 0)
|
|
37
|
+
const falseAlarms = judged.reduce((count, row) => count + row.falseAlarms, 0)
|
|
38
|
+
const cleanRows = ready.filter(row => row.clean)
|
|
39
|
+
return { available: coverageComplete, coverageComplete, recall: coverageComplete && expected ? detected / expected : null,
|
|
40
|
+
precision: confirmedClaims + falseAlarms ? confirmedClaims / (confirmedClaims + falseAlarms) : null,
|
|
41
|
+
falseAlarms, falseAlarmsPerReview: judged.length ? falseAlarms / judged.length : null,
|
|
42
|
+
cleanAlarmRate: cleanRows.length ? cleanRows.filter(row => row.falseAlarms > 0).length / cleanRows.length : null,
|
|
43
|
+
unresolved: rows.reduce((count, row) => count + (row.unresolved || 0), 0), expectedDefects: expected,
|
|
44
|
+
confirmedExpected: judged.reduce((count, row) => count + row.knownConfirmed.filter(id => row.expected.includes(id)).length, 0),
|
|
45
|
+
confirmedUnexpected: rows.reduce((count, row) => count + (row.unexpectedConfirmed || []).length, 0),
|
|
46
|
+
confirmedUnknown: rows.reduce((count, row) => count + (row.unknownConfirmed || []).length, 0),
|
|
47
|
+
confirmedClaims, uniqueConfirmedDefects: uniqueConfirmed, scoredRuns: ready.length,
|
|
48
|
+
distinctCases: rows.filter((row, index) => row.caseId && rows.findIndex(prior => prior.caseId === row.caseId) === index).length,
|
|
49
|
+
needsAdjudication: rows.some(row => row.needsAdjudication), rows }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function scoreDefectCorpus(manifest, evaluations) {
|
|
53
|
+
const registry = validateDefectManifest(manifest)
|
|
54
|
+
requireEvaluations(evaluations)
|
|
55
|
+
return summarize(manifest, evaluations.map((item, index) => scoreEvaluation(manifest, registry, evaluations, item, index)))
|
|
56
|
+
}
|
|
@@ -21,8 +21,10 @@
|
|
|
21
21
|
// verdict-affecting finding (critical or important) is a false positive.
|
|
22
22
|
|
|
23
23
|
import { readFileSync } from 'node:fs';
|
|
24
|
+
import { createHash } from 'node:crypto';
|
|
24
25
|
import { join } from 'node:path';
|
|
25
26
|
import { fileURLToPath } from 'node:url';
|
|
27
|
+
import { scoreDefectCorpus } from './defect-scoring.mjs';
|
|
26
28
|
|
|
27
29
|
export const LINE_WINDOW = 10;
|
|
28
30
|
const BLOCKING = new Set(['critical', 'important']);
|
|
@@ -174,6 +176,34 @@ export function score(manifest, results) {
|
|
|
174
176
|
|
|
175
177
|
function main(argv) {
|
|
176
178
|
const flag = (n) => { const i = argv.indexOf('--' + n); return i === -1 ? null : argv[i + 1]; };
|
|
179
|
+
if (argv.includes('--defects')) {
|
|
180
|
+
const manifestPath = flag('manifest'), resultsPath = flag('results'), adjudicationPath = flag('adjudication');
|
|
181
|
+
if (!manifestPath || !resultsPath || !adjudicationPath || [manifestPath, resultsPath, adjudicationPath].some(value => value.startsWith('--'))) {
|
|
182
|
+
console.error('usage: eval-runner.mjs --defects --manifest <manifest.json> --results <defect-runs.json> --adjudication <adjudication.json> [--json]');
|
|
183
|
+
process.exitCode = 2; return;
|
|
184
|
+
}
|
|
185
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
186
|
+
const results = JSON.parse(readFileSync(resultsPath, 'utf8'));
|
|
187
|
+
const adjudication = JSON.parse(readFileSync(adjudicationPath, 'utf8'));
|
|
188
|
+
const evaluations = Array.isArray(results.runs) ? results.runs.map(run => {
|
|
189
|
+
const matches = Array.isArray(adjudication.evaluations)
|
|
190
|
+
? adjudication.evaluations.filter(item => item?.runId === run?.runId) : [];
|
|
191
|
+
const bytes = typeof run?.findingsBytes === 'string' ? Buffer.from(run.findingsBytes, 'utf8') : Buffer.alloc(0);
|
|
192
|
+
let findings = null;
|
|
193
|
+
try { findings = JSON.parse(bytes.toString('utf8')); } catch { /* scorer marks malformed evidence unavailable */ }
|
|
194
|
+
return { run: { ...run, findings }, adjudication: matches.length === 1 ? matches[0] : null,
|
|
195
|
+
findingsSha256: createHash('sha256').update(bytes).digest('hex') };
|
|
196
|
+
}) : [];
|
|
197
|
+
const out = scoreDefectCorpus(manifest, evaluations);
|
|
198
|
+
if (argv.includes('--json')) console.log(JSON.stringify(out));
|
|
199
|
+
else {
|
|
200
|
+
const pct = value => value === null ? 'n/a' : `${Math.round(value * 100)}%`;
|
|
201
|
+
console.log(`defect evaluation ${out.available ? 'complete' : 'unavailable'}: recall ${pct(out.recall)}, precision ${pct(out.precision)}, false alarms ${out.falseAlarms}, unresolved ${out.unresolved}, distinct cases ${out.distinctCases}`);
|
|
202
|
+
}
|
|
203
|
+
if (!out.coverageComplete || !out.available) process.exitCode = 1;
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
console.error('legacy heuristic mode: location-only scoring; use --defects for adjudicated scoring');
|
|
177
207
|
const results = flag('results');
|
|
178
208
|
const archiveIndex = argv.indexOf('--archive');
|
|
179
209
|
const archive = archiveIndex === -1 ? null : argv[archiveIndex + 1];
|
|
@@ -3,36 +3,53 @@ import { readFileSync } from 'node:fs';
|
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { collectGitEvidence } from './git-evidence.mjs';
|
|
5
5
|
import { validateLintReceipt } from './validate-lint-receipt.mjs';
|
|
6
|
+
import { runBoundaryProbe } from './boundary-probe-runner.mjs';
|
|
7
|
+
import { validateBoundaryReport } from './boundary-validation.mjs';
|
|
6
8
|
|
|
7
9
|
const record = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
8
10
|
const unavailableLint = reason => ({ captureStatus: 'unavailable', reason });
|
|
9
11
|
const unavailableBundle = reason => ({ schema: 1,
|
|
10
12
|
git: { schema: 1, status: 'unavailable', reason }, lint: unavailableLint(reason) });
|
|
11
13
|
|
|
12
|
-
|
|
13
|
-
if (!
|
|
14
|
+
function collectBoundary(options, git) {
|
|
15
|
+
if (!options?.trustedOptIn) return undefined;
|
|
16
|
+
if (typeof options.configPath !== 'string' || typeof options.outputDir !== 'string') return { captureStatus: 'unavailable', reason: 'trusted opt-in needs a config and output directory' };
|
|
17
|
+
try {
|
|
18
|
+
const config = JSON.parse(readFileSync(options.configPath, 'utf8'));
|
|
19
|
+
const probe = runBoundaryProbe({ config, worktreePath: options.worktreePath, mergeBase: git.provenance.baseSha,
|
|
20
|
+
headSha: git.provenance.headSha, outputDir: options.outputDir, optIn: true });
|
|
21
|
+
return validateBoundaryReport(probe, git);
|
|
22
|
+
} catch { return { captureStatus: 'unavailable', reason: 'trusted boundary artifact is missing or malformed' }; }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function collectEvidence(worktreeMetadata, options = {}) {
|
|
26
|
+
if (!record(worktreeMetadata)) return { ...unavailableBundle('worktree metadata is missing or malformed'),
|
|
27
|
+
...(options.trustedOptIn ? { boundary: { captureStatus: 'unavailable', reason: 'worktree metadata unavailable' } } : {}) };
|
|
14
28
|
const git = collectGitEvidence({ worktreePath: worktreeMetadata.worktreePath,
|
|
15
29
|
mergeBase: worktreeMetadata.mergeBase, headSha: worktreeMetadata.headSha });
|
|
16
|
-
if (git.status !== 'available') return { schema: 1, git, lint: unavailableLint(`Git evidence unavailable: ${git.reason}`) };
|
|
17
|
-
|
|
18
|
-
if (typeof worktreeMetadata.
|
|
30
|
+
if (git.status !== 'available') return { schema: 1, git, lint: unavailableLint(`Git evidence unavailable: ${git.reason}`), ...(options.trustedOptIn ? { boundary: { captureStatus: 'unavailable', reason: 'Git evidence unavailable' } } : {}) };
|
|
31
|
+
const boundary = collectBoundary({ ...options, worktreePath: worktreeMetadata.worktreePath }, git);
|
|
32
|
+
if (typeof worktreeMetadata.eslintJson !== 'string' || !worktreeMetadata.eslintJson) return { schema: 1, git, lint: unavailableLint('lint report path unavailable'), ...(boundary ? { boundary } : {}) };
|
|
33
|
+
if (typeof worktreeMetadata.eslintProvenance !== 'string' || !worktreeMetadata.eslintProvenance) return { schema: 1, git, lint: unavailableLint('lint provenance path unavailable'), ...(boundary ? { boundary } : {}) };
|
|
19
34
|
let reportBytes, receipt;
|
|
20
|
-
try { reportBytes = readFileSync(worktreeMetadata.eslintJson); } catch { return { schema: 1, git, lint: unavailableLint('lint report could not be read') }; }
|
|
21
|
-
try { receipt = JSON.parse(readFileSync(worktreeMetadata.eslintProvenance, 'utf8')); } catch { return { schema: 1, git, lint: unavailableLint('lint provenance is missing or malformed') }; }
|
|
35
|
+
try { reportBytes = readFileSync(worktreeMetadata.eslintJson); } catch { return { schema: 1, git, lint: unavailableLint('lint report could not be read'), ...(boundary ? { boundary } : {}) }; }
|
|
36
|
+
try { receipt = JSON.parse(readFileSync(worktreeMetadata.eslintProvenance, 'utf8')); } catch { return { schema: 1, git, lint: unavailableLint('lint provenance is missing or malformed'), ...(boundary ? { boundary } : {}) }; }
|
|
22
37
|
const provenance = validateLintReceipt(receipt, { baseSha: git.provenance.baseSha,
|
|
23
38
|
headSha: git.provenance.headSha, trackedClean: git.provenance.trackedCleanBefore && git.provenance.trackedCleanAfter }, reportBytes);
|
|
24
|
-
if (provenance.status !== 'available') return { schema: 1, git, lint: unavailableLint(provenance.reason) };
|
|
39
|
+
if (provenance.status !== 'available') return { schema: 1, git, lint: unavailableLint(provenance.reason), ...(boundary ? { boundary } : {}) };
|
|
25
40
|
let report;
|
|
26
|
-
try { report = JSON.parse(reportBytes.toString('utf8')); } catch { return { schema: 1, git, lint: unavailableLint('lint report is malformed JSON') }; }
|
|
27
|
-
if (!Array.isArray(report)) return { schema: 1, git, lint: unavailableLint('lint report is not a JSON array') };
|
|
41
|
+
try { report = JSON.parse(reportBytes.toString('utf8')); } catch { return { schema: 1, git, lint: unavailableLint('lint report is malformed JSON'), ...(boundary ? { boundary } : {}) }; }
|
|
42
|
+
if (!Array.isArray(report)) return { schema: 1, git, lint: unavailableLint('lint report is not a JSON array'), ...(boundary ? { boundary } : {}) };
|
|
28
43
|
return { schema: 1, git, lint: { captureStatus: 'available', exitCode: provenance.exitCode,
|
|
29
|
-
reportSha256: provenance.reportSha256, report } };
|
|
44
|
+
reportSha256: provenance.reportSha256, report }, ...(boundary ? { boundary } : {}) };
|
|
30
45
|
}
|
|
31
46
|
|
|
32
47
|
function main(argv) {
|
|
33
48
|
const i = argv.indexOf('--worktree'), path = i < 0 ? null : argv[i + 1];
|
|
34
|
-
if (!path || path.startsWith('--')) { console.error('usage: evidence-bundle.mjs --worktree <worktree.json>'); process.exitCode = 2; return; }
|
|
35
|
-
|
|
49
|
+
if (!path || path.startsWith('--')) { console.error('usage: evidence-bundle.mjs --worktree <worktree.json> [--trusted-boundary-opt-in --boundary-config <file> --boundary-out <dir>]'); process.exitCode = 2; return; }
|
|
50
|
+
const value = name => { const at = argv.indexOf(`--${name}`); return at < 0 ? null : argv[at + 1]; };
|
|
51
|
+
const boundaryOptions = { trustedOptIn: argv.includes('--trusted-boundary-opt-in'), configPath: value('boundary-config'), outputDir: value('boundary-out') };
|
|
52
|
+
try { console.log(JSON.stringify(collectEvidence(JSON.parse(readFileSync(path, 'utf8')), boundaryOptions))); }
|
|
36
53
|
catch { console.log(JSON.stringify(unavailableBundle('worktree metadata could not be read'))); process.exitCode = 2; }
|
|
37
54
|
}
|
|
38
55
|
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
|
|
5
|
+
const sha256 = value => createHash('sha256').update(value).digest('hex')
|
|
6
|
+
const record = value => value && typeof value === 'object' && !Array.isArray(value)
|
|
7
|
+
const unavailable = reason => ({ schema: 1, status: 'unavailable', reason })
|
|
8
|
+
|
|
9
|
+
function reportIntegrity(boundary) {
|
|
10
|
+
if (boundary?.captureStatus !== 'available') return false
|
|
11
|
+
const report = boundary.report
|
|
12
|
+
if (!record(report)) return false
|
|
13
|
+
const bytes = Buffer.from(JSON.stringify(report, null, 2) + '\n')
|
|
14
|
+
return sha256(bytes) === boundary.reportSha256
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function filePatches(diff, paths) {
|
|
18
|
+
const chunks = diff.split(/(?=^diff --git )/m).filter(Boolean)
|
|
19
|
+
return paths.flatMap(path => {
|
|
20
|
+
const chunk = chunks.find(value => value.startsWith(`diff --git a/${path} b/${path}\n`))
|
|
21
|
+
if (!chunk) return []
|
|
22
|
+
return [{ path, patch: chunk.trimEnd(), ranges: [...chunk.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)].map(m => ({ start: Number(m[1]), count: Number(m[2] ?? 1) })) }]
|
|
23
|
+
})
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function projectEvidencePacket(bundleBytes, expectedSha256, { dimension, paths, maxBytes = 32768 } = {}) {
|
|
27
|
+
try {
|
|
28
|
+
if (!Buffer.isBuffer(bundleBytes) || sha256(bundleBytes) !== expectedSha256) return unavailable('full bundle hash mismatch')
|
|
29
|
+
const bundle = JSON.parse(bundleBytes.toString('utf8'))
|
|
30
|
+
if (!record(bundle) || bundle.schema !== 1 || bundle.git?.status !== 'available' || !record(bundle.git.diff)
|
|
31
|
+
|| typeof bundle.git.diff.text !== 'string' || sha256(Buffer.from(bundle.git.diff.text)) !== bundle.git.diff.sha256) return unavailable('full evidence bundle is invalid')
|
|
32
|
+
if (typeof dimension !== 'string' || !dimension || !Array.isArray(paths) || !paths.length
|
|
33
|
+
|| paths.some(path => typeof path !== 'string' || !bundle.git.changedPaths.includes(path))
|
|
34
|
+
|| !Number.isSafeInteger(maxBytes) || maxBytes < 256 || maxBytes > 262144) return unavailable('packet scope or size budget is invalid')
|
|
35
|
+
const sourceRanges = filePatches(bundle.git.diff.text, paths)
|
|
36
|
+
if (sourceRanges.length !== paths.length) return unavailable('selected source patch is missing from the full diff')
|
|
37
|
+
const diagnostics = bundle.lint?.captureStatus === 'available' && Array.isArray(bundle.lint.report)
|
|
38
|
+
? bundle.lint.report.filter(row => paths.includes(row.filePath ?? row.file ?? row.filename)) : []
|
|
39
|
+
const boundary = bundle.boundary
|
|
40
|
+
if (boundary?.captureStatus === 'available' && !reportIntegrity(boundary)) return unavailable('boundary report hash mismatch')
|
|
41
|
+
const report = boundary?.report
|
|
42
|
+
if (boundary?.captureStatus === 'available' && (report.provenance?.baseSha !== bundle.git.provenance?.baseSha
|
|
43
|
+
|| report.provenance?.headSha !== bundle.git.provenance?.headSha || !bundle.git.changedPaths.includes(report.source))) return unavailable('boundary provenance does not match the full bundle')
|
|
44
|
+
const candidate = report?.reducedCounterexample && report.candidates?.find(row => row.id === report.reducedCounterexample.id)
|
|
45
|
+
const packet = { schema: 1, status: 'available', mode: 'shadow-projection', dimension, scope: { paths: [...paths].sort(), omittedPaths: bundle.git.changedPaths.filter(path => !paths.includes(path)), omittedContextReviewed: false, wholeDiffPassRequired: true },
|
|
46
|
+
provenance: { baseSha: bundle.git.provenance?.baseSha, headSha: bundle.git.provenance?.headSha,
|
|
47
|
+
diffSha256: bundle.git.diff.sha256, fullBundleSha256: expectedSha256,
|
|
48
|
+
boundaryReportSha256: boundary?.captureStatus === 'available' ? boundary.reportSha256 : null },
|
|
49
|
+
sourceRanges, lint: bundle.lint?.captureStatus === 'available' ? { status: 'available', diagnostics } : { status: 'unavailable', reason: bundle.lint?.reason ?? 'lint evidence absent' },
|
|
50
|
+
boundary: boundary?.captureStatus === 'available' ? { status: candidate ? 'candidate' : 'no-candidate', source: report.source,
|
|
51
|
+
contract: report.contract, provenance: report.provenance,
|
|
52
|
+
witness: candidate ? { input: candidate.input, inputSha256: candidate.inputSha256, outcomes: candidate.outcomes,
|
|
53
|
+
reducedScope: report.reducedCounterexample.scope, failure: boundary.summary?.reducedFailure } : null }
|
|
54
|
+
: { status: 'unavailable', reason: boundary?.reason ?? 'boundary evidence absent' },
|
|
55
|
+
coverageGaps: { omittedChangedPaths: bundle.git.changedPaths.filter(path => !paths.includes(path)), notApplicableDiagnosticsOmitted: (bundle.lint?.report?.length ?? 0) - diagnostics.length,
|
|
56
|
+
omittedContextReviewed: false, broadDiffReviewRequired: true } }
|
|
57
|
+
packet.packetBytes = 0
|
|
58
|
+
packet.fullBundleBytes = bundleBytes.length
|
|
59
|
+
let packetBytes = Buffer.byteLength(JSON.stringify(packet))
|
|
60
|
+
while (packet.packetBytes !== packetBytes) { packet.packetBytes = packetBytes; packetBytes = Buffer.byteLength(JSON.stringify(packet)) }
|
|
61
|
+
if (packetBytes > maxBytes) return unavailable('projected packet exceeds configured byte budget')
|
|
62
|
+
return packet
|
|
63
|
+
} catch { return unavailable('bundle or packet input is malformed') }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function main(argv) {
|
|
67
|
+
const value = key => { const at = argv.indexOf(`--${key}`); return at < 0 ? null : argv[at + 1] }
|
|
68
|
+
const file = value('bundle'), hash = value('sha256'), dimension = value('dimension'), paths = argv.flatMap((arg, i) => arg === '--path' ? [argv[i + 1]] : [])
|
|
69
|
+
if (!file || !hash || !dimension || !paths.length) { console.error('usage: evidence-packet.mjs --bundle <full-bundle.json> --sha256 <trusted-bundle-sha256> --dimension <name> --path <changed-path> [--path <changed-path>] [--max-bytes <n>]'); process.exitCode = 2; return }
|
|
70
|
+
try { console.log(JSON.stringify(projectEvidencePacket(readFileSync(file), hash, { dimension, paths, maxBytes: Number(value('max-bytes') ?? 32768) }))) }
|
|
71
|
+
catch { console.log(JSON.stringify(unavailable('explicit bundle could not be read'))); process.exitCode = 2 }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) main(process.argv.slice(2))
|
|
@@ -7,6 +7,19 @@ const instances = /^(?!\/)(?!.*\\)(?![A-Za-z]:)(?!(?:.*\/)?\.\.(?:\/|:)).+:[1-9]
|
|
|
7
7
|
const ruleException = /^(PROJECT:[a-z0-9]+(-[a-z0-9]+)*|weakens-project-rule)$/
|
|
8
8
|
const dimensions = ['deps', 'triage-quality', 'triage-logic', 'quality', 'implementation', 'simplification', 'conventions', 'test-quality', 'project-rules']
|
|
9
9
|
|
|
10
|
+
/** Canonicalize location objects without altering or replacing the raw document. */
|
|
11
|
+
export function normalizeNativeResult(dimension, document) {
|
|
12
|
+
const location = value => record(value) && Object.keys(value).length === 2
|
|
13
|
+
&& typeof value.file === 'string' && !/[\x00-\x1f\x7f:]/.test(value.file)
|
|
14
|
+
&& Number.isSafeInteger(value.line) && value.line > 0
|
|
15
|
+
&& instances.test(`${value.file}:${value.line}`) ? `${value.file}:${value.line}` : value
|
|
16
|
+
const normalized = record(document) && Array.isArray(document.findings)
|
|
17
|
+
? { ...document, findings: Array.from(document.findings, finding => record(finding) && Array.isArray(finding.otherInstances)
|
|
18
|
+
? { ...finding, otherInstances: Array.from(finding.otherInstances, location) } : finding) } : document
|
|
19
|
+
const validation = validateNativeResult(dimension, normalized)
|
|
20
|
+
return { ...validation, document: validation.available ? normalized : null }
|
|
21
|
+
}
|
|
22
|
+
|
|
10
23
|
function validBoundary(value) {
|
|
11
24
|
return record(value) && text(value.entryPoint) && text(value.consumer)
|
|
12
25
|
&& optionalStrings(value, ['decisionPoint', 'realizationPoint', 'stateOwner', 'evidenceClass'])
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { openSync, readSync, closeSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import { normalizeNativeResult } from './native-results.mjs'
|
|
5
|
+
|
|
6
|
+
try {
|
|
7
|
+
const [dimension, input, output, ...extra] = process.argv.slice(2)
|
|
8
|
+
if (!dimension || !input || extra.length) throw new Error('invalid arguments')
|
|
9
|
+
const limit = 8 * 1024 * 1024, buffer = Buffer.alloc(limit + 1)
|
|
10
|
+
const fd = openSync(input, 'r')
|
|
11
|
+
let length = 0
|
|
12
|
+
try {
|
|
13
|
+
while (length < buffer.length) {
|
|
14
|
+
const count = readSync(fd, buffer, length, buffer.length - length, null)
|
|
15
|
+
if (!count) break
|
|
16
|
+
length += count
|
|
17
|
+
}
|
|
18
|
+
} finally { closeSync(fd) }
|
|
19
|
+
if (length > limit) {
|
|
20
|
+
console.log(JSON.stringify({ available: false, dimension, reason: 'raw reviewer result exceeds 8 MiB', document: null }))
|
|
21
|
+
process.exit(1)
|
|
22
|
+
}
|
|
23
|
+
const raw = buffer.subarray(0, length)
|
|
24
|
+
const result = normalizeNativeResult(dimension, JSON.parse(raw.toString('utf8')))
|
|
25
|
+
if (result.available && output) writeFileSync(output, JSON.stringify(result.document), { flag: 'wx' })
|
|
26
|
+
console.log(JSON.stringify({ ...result, rawSha256: createHash('sha256').update(raw).digest('hex') }))
|
|
27
|
+
if (!result.available) process.exitCode = 1
|
|
28
|
+
} catch {
|
|
29
|
+
console.log(JSON.stringify({ available: false, reason: 'raw reviewer result missing or malformed', document: null }))
|
|
30
|
+
process.exitCode = 1
|
|
31
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
|
|
4
|
+
const counters = ['inputTokens', 'cachedInputTokens', 'outputTokens']
|
|
5
|
+
const record = value => value && typeof value === 'object' && !Array.isArray(value)
|
|
6
|
+
const unavailable = reason => ({ schema: 1, status: 'unavailable', reason, stages: [] })
|
|
7
|
+
|
|
8
|
+
function validCount(value) { return Number.isSafeInteger(value) && value >= 0 }
|
|
9
|
+
|
|
10
|
+
export function buildStageLedger(manifest, adjudication) {
|
|
11
|
+
if (!record(manifest) || manifest.schema !== 1 || !Array.isArray(manifest.sessions)) return unavailable('explicit session manifest is missing or malformed')
|
|
12
|
+
const seen = new Set(), stages = new Map()
|
|
13
|
+
for (const session of manifest.sessions) {
|
|
14
|
+
if (!record(session) || typeof session.sessionId !== 'string' || !session.sessionId || typeof session.stage !== 'string' || !session.stage) return unavailable('session identity or stage is invalid')
|
|
15
|
+
if (seen.has(session.sessionId)) return unavailable('duplicate session identity')
|
|
16
|
+
seen.add(session.sessionId)
|
|
17
|
+
let stage = stages.get(session.stage)
|
|
18
|
+
if (!stage) { stage = { name: session.stage, sessions: 0, status: 'available', inputTokens: 0, cachedInputTokens: 0, uncachedInputTokens: 0, outputTokens: 0, elapsedSeconds: [], unavailableSessions: 0 }; stages.set(session.stage, stage) }
|
|
19
|
+
if (session.status !== 'available') { stage.status = 'partial'; stage.unavailableSessions += 1; continue }
|
|
20
|
+
if (!record(session.usage) || counters.some(key => !validCount(session.usage[key])) || session.usage.cachedInputTokens > session.usage.inputTokens
|
|
21
|
+
|| session.elapsedSeconds !== undefined && !(typeof session.elapsedSeconds === 'number' && Number.isFinite(session.elapsedSeconds) && session.elapsedSeconds >= 0)) return unavailable('session counters or elapsed observation are invalid')
|
|
22
|
+
stage.sessions += 1
|
|
23
|
+
stage.inputTokens += session.usage.inputTokens
|
|
24
|
+
stage.cachedInputTokens += session.usage.cachedInputTokens
|
|
25
|
+
stage.uncachedInputTokens += session.usage.inputTokens - session.usage.cachedInputTokens
|
|
26
|
+
stage.outputTokens += session.usage.outputTokens
|
|
27
|
+
if (session.elapsedSeconds !== undefined) stage.elapsedSeconds.push(session.elapsedSeconds)
|
|
28
|
+
}
|
|
29
|
+
const claims = adjudication?.claims
|
|
30
|
+
let outcome = { status: 'unavailable', confirmedDefects: [], falseAlarms: null, duplicates: null, unknownDiscovery: null, unknownVerification: null }
|
|
31
|
+
if (record(adjudication) && adjudication.schema === 1 && Array.isArray(claims)) {
|
|
32
|
+
if (claims.some(item => !record(item) || !['confirmed', 'false-alarm', 'duplicate', 'unresolved'].includes(item.verdict))) return unavailable('adjudication claim is malformed')
|
|
33
|
+
for (const stage of stages.values()) { stage.discoveredDefects = []; stage.verifiedDefects = [] }
|
|
34
|
+
const confirmed = claims.filter(item => item?.verdict === 'confirmed')
|
|
35
|
+
const ids = confirmed.map(item => item.defectId).filter(id => typeof id === 'string' && id)
|
|
36
|
+
outcome = { status: 'available', confirmedDefects: [...new Set(ids)], falseAlarms: claims.filter(item => item.verdict === 'false-alarm').length,
|
|
37
|
+
duplicates: claims.filter(item => item.verdict === 'duplicate').length, unresolved: claims.filter(item => item.verdict === 'unresolved').length,
|
|
38
|
+
unknownDiscovery: 0, unknownVerification: 0 }
|
|
39
|
+
for (const item of confirmed) {
|
|
40
|
+
if (typeof item.defectId !== 'string' || !item.defectId) return unavailable('confirmed claim lacks a defect identity')
|
|
41
|
+
for (const [field, value] of [['discoveredDefects', item.discoveryStage], ['verifiedDefects', item.verificationStage]]) {
|
|
42
|
+
const bucket = field === 'discoveredDefects' ? 'unknownDiscovery' : 'unknownVerification'
|
|
43
|
+
if (!stages.has(value)) outcome[bucket] += 1
|
|
44
|
+
else {
|
|
45
|
+
const stage = stages.get(value)
|
|
46
|
+
stage[field] ??= []
|
|
47
|
+
stage[field].push(item.defectId)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
for (const stage of stages.values()) {
|
|
52
|
+
stage.discoveredDefects = [...new Set(stage.discoveredDefects ?? [])]
|
|
53
|
+
stage.verifiedDefects = [...new Set(stage.verifiedDefects ?? [])]
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
for (const stage of stages.values()) {
|
|
57
|
+
if (stage.status === 'partial') for (const key of ['inputTokens', 'cachedInputTokens', 'uncachedInputTokens', 'outputTokens']) stage[key] = null
|
|
58
|
+
else for (const key of ['inputTokens', 'cachedInputTokens', 'uncachedInputTokens', 'outputTokens']) if (!Number.isSafeInteger(stage[key])) return unavailable('stage totals exceed safe integer range')
|
|
59
|
+
}
|
|
60
|
+
return { schema: 1, status: 'available', stages: [...stages.values()], outcomes: outcome }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function buildStageLedgerFromFiles(manifest, adjudication) {
|
|
64
|
+
if (!record(manifest) || manifest.schema !== 1 || !Array.isArray(manifest.runs)) return buildStageLedger(manifest, adjudication)
|
|
65
|
+
const sessions = []
|
|
66
|
+
for (const [index, run] of manifest.runs.entries()) {
|
|
67
|
+
if (!record(run) || typeof run.stage !== 'string' || !run.stage || typeof run.usageFile !== 'string' || !run.usageFile) return unavailable('run manifest needs explicit stage and usageFile entries')
|
|
68
|
+
let saved
|
|
69
|
+
try { saved = JSON.parse(readFileSync(run.usageFile, 'utf8')) } catch {
|
|
70
|
+
sessions.push({ sessionId: `${run.stage}:unavailable:${index}`, stage: run.stage, status: 'unavailable' }); continue
|
|
71
|
+
}
|
|
72
|
+
if (!record(saved) || saved.available !== true || !Array.isArray(saved.sessions) || saved.sessions.length === 0) {
|
|
73
|
+
sessions.push({ sessionId: `${run.stage}:unavailable:${index}`, stage: run.stage, status: 'unavailable' }); continue
|
|
74
|
+
}
|
|
75
|
+
for (const [sessionIndex, row] of saved.sessions.entries()) {
|
|
76
|
+
if (!record(row)) { sessions.push({ sessionId: `${run.stage}:malformed:${index}:${sessionIndex}`, stage: run.stage, status: 'unavailable' }); continue }
|
|
77
|
+
sessions.push({ sessionId: row.sessionId, stage: run.stage,
|
|
78
|
+
status: row.usage ? 'available' : 'unavailable', usage: row.usage && {
|
|
79
|
+
inputTokens: row.usage.input_tokens, cachedInputTokens: row.usage.cached_input_tokens,
|
|
80
|
+
outputTokens: row.usage.output_tokens }, elapsedSeconds: row.wallSeconds })
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const claims = Array.isArray(adjudication?.claims) ? adjudication.claims
|
|
84
|
+
: Array.isArray(adjudication?.evaluations) ? adjudication.evaluations.flatMap(item => item?.decisions ?? []) : null
|
|
85
|
+
return buildStageLedger({ schema: 1, sessions }, claims ? { schema: 1, claims } : null)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function main(argv) {
|
|
89
|
+
const arg = name => { const i = argv.indexOf(`--${name}`); return i < 0 ? null : argv[i + 1] }
|
|
90
|
+
const manifest = arg('manifest'), adjudication = arg('adjudication')
|
|
91
|
+
if (!manifest || manifest.startsWith('--')) { console.error('usage: stage-ledger.mjs --manifest <saved-session-manifest.json> [--adjudication <saved-adjudication.json>]'); process.exitCode = 2; return }
|
|
92
|
+
try { console.log(JSON.stringify(buildStageLedgerFromFiles(JSON.parse(readFileSync(manifest, 'utf8')), adjudication ? JSON.parse(readFileSync(adjudication, 'utf8')) : null))) }
|
|
93
|
+
catch { console.log(JSON.stringify(unavailable('explicit artifact could not be read'))); process.exitCode = 2 }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) main(process.argv.slice(2))
|