harness-everything 0.51.0 → 0.53.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/ci.yml +23 -0
- package/CHANGELOG.md +54 -0
- package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-a-evid-001.md +123 -0
- package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-b-route-001.md +130 -0
- package/benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md +7 -0
- package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-probe.js +16 -0
- package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-trace-2026-11-15.jsonl +4 -0
- package/ci/mechanism-2am-observations-session-import.test.js +4 -1
- package/ci/mechanism-2n-opencode-plugin.test.js +1 -1
- package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +18 -3
- package/ci/mechanism-338-opencode-async.test.js +20 -3
- package/ci/mechanism-34-observations.test.js +127 -23
- package/ci/mechanism-341-opencode-lane.test.js +7 -1
- package/ci/mechanism-349-ci-change-scope.test.js +260 -0
- package/ci/mechanism-397-cycle-import.test.js +399 -0
- package/ci/mechanism-397-host-acceptance.test.js +119 -0
- package/ci/mechanism-397-opencode-observations.test.js +1922 -0
- package/ci/mechanism-handoff-file.test.js +121 -0
- package/ci/mechanism-system-one-contract.test.js +9 -2
- package/ci/mechanism-system-one-curves.test.js +223 -0
- package/ci/mechanism-system-one-cycle.test.js +1204 -0
- package/ci/mechanism-system-one-evaluation.test.js +32 -5
- package/ci/mechanism-system-one-handoff-input.test.js +208 -0
- package/ci/mechanism-system-one-install.test.js +202 -77
- package/ci/mechanism-system-one-live.test.js +361 -0
- package/ci/mechanism-system-one-relevance.test.js +11 -1
- package/ci/mechanism-system-one-train.test.js +136 -53
- package/ci/system-one-adapter-test.py +331 -0
- package/ci/system-one-train-test.py +116 -24
- package/docs/adr/EVID-001.md +123 -0
- package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
- package/docs/governed-index.md +2 -0
- package/docs/platform-capabilities.md +13 -6
- package/docs/routing.md +2 -2
- package/docs/system-one-cycle.md +77 -0
- package/docs/system-one-observations.md +43 -11
- package/docs/system-one-routing.md +163 -115
- package/docs/system-one-suggestion-gates.md +6 -8
- package/docs/system-one-training.md +44 -7
- package/docs/workflow-runtime.md +19 -0
- package/harness-everything/SKILL.md +1 -1
- package/harness-everything/scripts/kernel-router.js +2 -1
- package/harness-everything/scripts/system-one/contract.js +19 -15
- package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
- package/harness-everything/scripts/system-one/evaluate.js +4 -9
- package/harness-everything/scripts/system-one/handoff-input.js +76 -0
- package/harness-everything/scripts/system-one/install.js +281 -113
- package/harness-everything/scripts/system-one/manifest.js +58 -0
- package/harness-everything/scripts/system-one/provider.js +96 -2
- package/harness-everything/scripts/system-one/resident.js +47 -1
- package/harness-everything/scripts/system-one/router.js +80 -1
- package/harness-everything/scripts/tier-router.js +21 -6
- package/hooks/scripts/lib/observations.js +48 -7
- package/opencode-plugin/README.md +22 -8
- package/opencode-plugin/index.mjs +424 -44
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/hooks/scripts/lib/observations.js +48 -7
- package/plugins/harness-everything/plugin.json +1 -1
- package/plugins/harness-everything/scripts/handoff-file.js +223 -0
- package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
- package/sbom.cdx.json +7 -7
- package/scripts/ci-change-scope.js +59 -0
- package/scripts/handoff-file.js +223 -0
- package/scripts/sync-openai-plugin.js +4 -0
- package/scripts/system-one-calibrate.js +108 -41
- package/scripts/system-one-curves.js +472 -0
- package/scripts/system-one-cycle/adjudication-input.js +65 -0
- package/scripts/system-one-cycle/build.js +165 -0
- package/scripts/system-one-cycle/collect.js +67 -0
- package/scripts/system-one-cycle/common.js +175 -0
- package/scripts/system-one-cycle/engines.js +62 -0
- package/scripts/system-one-cycle/evaluate.js +73 -0
- package/scripts/system-one-cycle/judge.js +106 -0
- package/scripts/system-one-cycle/label.js +59 -0
- package/scripts/system-one-cycle/package.js +173 -0
- package/scripts/system-one-cycle/score.py +111 -0
- package/scripts/system-one-cycle/train.js +136 -0
- package/scripts/system-one-cycle.js +136 -0
- package/scripts/system-one-observations-export.js +58 -6
- package/scripts/system-one-observations-import-store.js +128 -0
- package/scripts/system-one-observations-review.js +4 -5
- package/scripts/system-one-train.py +117 -61
|
@@ -1,73 +1,140 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';
|
|
3
|
-
//
|
|
4
|
-
// The holdout is never used here.
|
|
3
|
+
// Fits independent option thresholds from the trainer's validation-score artifact.
|
|
5
4
|
const fs = require('node:fs');
|
|
6
5
|
const { CATALOGS } = require('../harness-everything/scripts/system-one/catalogs');
|
|
7
6
|
const { gradedAgreement } = require('../harness-everything/scripts/system-one/intent');
|
|
8
7
|
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
if (
|
|
16
|
-
|
|
8
|
+
const TIER_IDS = ['tier1', 'tier2', 'tier3'];
|
|
9
|
+
const LEGACY_TIER_IDS = [...TIER_IDS, 'unclassified'];
|
|
10
|
+
|
|
11
|
+
function scoreIds(task) {
|
|
12
|
+
if (task === 'validity') return ['invalid'];
|
|
13
|
+
if (task === 'tier') return TIER_IDS;
|
|
14
|
+
if (task === 'intent') return CATALOGS.intent.map(option => option.id);
|
|
15
|
+
throw new TypeError('unknown-task');
|
|
17
16
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
17
|
+
|
|
18
|
+
function normalizeRow(row, task, ids) {
|
|
19
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) throw new TypeError('invalid-row');
|
|
20
|
+
if (row.split !== undefined && row.split !== 'validation') throw new TypeError('non-validation-row');
|
|
21
|
+
const legacyIds = task === 'tier' ? LEGACY_TIER_IDS : ids;
|
|
22
|
+
let scores;
|
|
23
|
+
if (Object.hasOwn(row, 'scores')) {
|
|
24
|
+
scores = row.scores;
|
|
25
|
+
if (!scores || typeof scores !== 'object' || Array.isArray(scores)
|
|
26
|
+
|| Object.keys(scores).length !== ids.length || ids.some(id => !Object.hasOwn(scores, id))) throw new TypeError('invalid-scores');
|
|
27
|
+
} else if (Array.isArray(row.probs) && row.probs.length === legacyIds.length) {
|
|
28
|
+
scores = Object.fromEntries(legacyIds.map((id, i) => [id, row.probs[i]]));
|
|
29
|
+
} else throw new TypeError('invalid-scores');
|
|
30
|
+
if (Object.values(scores).some(value => !Number.isFinite(value) || value < 0 || value > 1)) throw new TypeError('invalid-scores');
|
|
31
|
+
|
|
32
|
+
const goldIds = task === 'validity' ? ['invalid', 'actionable']
|
|
33
|
+
: task === 'tier' ? [...LEGACY_TIER_IDS, null] : [...ids, null];
|
|
34
|
+
if (!goldIds.includes(row.gold) || (row.secondary !== undefined && !Array.isArray(row.secondary))) throw new TypeError('invalid-gold');
|
|
35
|
+
const positive = new Set([row.gold, ...(row.secondary || [])].filter(id => ids.includes(id) && id !== 'unclassified'));
|
|
36
|
+
return { scores, positive };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function fitOption(rows, id, minPrecision) {
|
|
22
40
|
let best = null;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
41
|
+
const candidates = [...new Set(rows.map(row => row.scores[id]))].sort((a, b) => a - b);
|
|
42
|
+
for (const threshold of candidates) {
|
|
43
|
+
let accepted = 0; let correct = 0;
|
|
44
|
+
for (const row of rows) {
|
|
45
|
+
if (row.scores[id] < threshold) continue;
|
|
46
|
+
accepted++;
|
|
47
|
+
if (row.positive.has(id)) correct++;
|
|
30
48
|
}
|
|
31
|
-
const
|
|
32
|
-
if (
|
|
49
|
+
const precision = correct / accepted;
|
|
50
|
+
if (precision < minPrecision) continue;
|
|
51
|
+
const result = { feasible: true, threshold, accepted, coverage: accepted / rows.length, precision };
|
|
52
|
+
if (!best || result.coverage > best.coverage || (result.coverage === best.coverage && threshold < best.threshold)) best = result;
|
|
33
53
|
}
|
|
34
|
-
return best
|
|
54
|
+
return best || { feasible: false, threshold: null, accepted: 0, coverage: 0, precision: null };
|
|
35
55
|
}
|
|
36
|
-
|
|
37
|
-
|
|
56
|
+
|
|
57
|
+
function calibrateLegacy(rows, task, ids, minPrecision) {
|
|
38
58
|
const multi = task === 'intent';
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
59
|
+
const secondaryThreshold = multi ? (() => {
|
|
60
|
+
let best = null;
|
|
61
|
+
for (let s = 5; s <= 50; s += 5) {
|
|
62
|
+
let tp = 0; let fp = 0; let fn = 0;
|
|
63
|
+
for (const row of rows) {
|
|
64
|
+
const primary = ids[row.probs.indexOf(Math.max(...row.probs))];
|
|
65
|
+
const predicted = new Set(ids.filter((id, i) => id !== primary && id !== 'unclassified' && row.probs[i] >= s / 100));
|
|
66
|
+
const gold = new Set(row.secondary || []);
|
|
67
|
+
for (const id of predicted) (gold.has(id) ? tp++ : fp++);
|
|
68
|
+
for (const id of gold) if (!predicted.has(id)) fn++;
|
|
69
|
+
}
|
|
70
|
+
const f1 = 2 * tp + fp + fn ? 2 * tp / (2 * tp + fp + fn) : 0;
|
|
71
|
+
if (!best || f1 > best.f1) best = { threshold: s / 100, f1 };
|
|
72
|
+
}
|
|
73
|
+
return best.threshold;
|
|
74
|
+
})() : undefined;
|
|
75
|
+
const decide = (probs, minConfidence, minMargin) => {
|
|
76
|
+
const ranked = probs.map((probability, index) => [probability, index]).sort((a, b) => b[0] - a[0] || a[1] - b[1]);
|
|
77
|
+
const [top, second] = ranked;
|
|
78
|
+
const margin = top[0] - second[0];
|
|
79
|
+
return margin === 0 || top[0] < minConfidence || margin < minMargin || ids[top[1]] === 'unclassified' ? null : ids[top[1]];
|
|
80
|
+
};
|
|
81
|
+
const secondaryOf = (probs, primary) => ids.filter((id, i) => id !== primary && id !== 'unclassified' && probs[i] >= secondaryThreshold);
|
|
43
82
|
let best = null;
|
|
44
83
|
for (let c = 50; c <= 99; c++) {
|
|
45
84
|
for (let m = 0; m <= 90; m += 5) {
|
|
46
|
-
const
|
|
85
|
+
const minConfidence = c / 100; const minMargin = m / 100;
|
|
47
86
|
let accepted = 0; let points = 0; let exact = 0;
|
|
48
|
-
for (const
|
|
87
|
+
for (const row of rows) {
|
|
88
|
+
const prediction = decide(row.probs, minConfidence, minMargin);
|
|
89
|
+
if (prediction === null) continue;
|
|
90
|
+
accepted++;
|
|
91
|
+
points += multi ? gradedAgreement({ gold: row.gold, secondary: row.secondary || [] },
|
|
92
|
+
{ gold: prediction, secondary: secondaryOf(row.probs, prediction) })
|
|
93
|
+
: Number(prediction === (row.gold === null ? 'unclassified' : row.gold));
|
|
94
|
+
if (prediction === row.gold) exact++;
|
|
95
|
+
}
|
|
49
96
|
const precision = accepted ? points / accepted : 0;
|
|
50
97
|
if (!accepted || precision < minPrecision) continue;
|
|
51
98
|
const coverage = accepted / rows.length;
|
|
52
|
-
|
|
53
|
-
|
|
99
|
+
if (!best || coverage > best.coverage) best = { minConfidence, minMargin, coverage, precision, accepted,
|
|
100
|
+
...(multi ? { exactPrecision: exact / accepted } : {}) };
|
|
54
101
|
}
|
|
55
102
|
}
|
|
56
|
-
const extra = multi ? { task, secondaryThreshold
|
|
103
|
+
const extra = multi ? { task, secondaryThreshold } : {};
|
|
57
104
|
return best ? { feasible: true, rows: rows.length, minPrecision, ...extra, ...best }
|
|
58
105
|
: { feasible: false, rows: rows.length, minPrecision, ...extra, minConfidence: null, minMargin: null, coverage: 0, precision: null, accepted: 0 };
|
|
59
106
|
}
|
|
60
107
|
|
|
108
|
+
function calibrate(rows, { minPrecision = 0.85, task = 'tier', catalogIds } = {}) {
|
|
109
|
+
if (!Array.isArray(rows) || !Number.isFinite(minPrecision) || minPrecision < 0 || minPrecision > 1) throw new TypeError('invalid-calibration-input');
|
|
110
|
+
const allIds = catalogIds ?? scoreIds(task);
|
|
111
|
+
if (!Array.isArray(allIds) || !allIds.length || allIds.some(id => typeof id !== 'string' || !id)
|
|
112
|
+
|| new Set(allIds).size !== allIds.length) throw new TypeError('invalid-calibration-catalog');
|
|
113
|
+
const ids = allIds;
|
|
114
|
+
const normalized = rows.map(row => normalizeRow(row, task, allIds));
|
|
115
|
+
// Legacy simplex artifacts keep single-winner calibration; keyed scores are sigmoid targets.
|
|
116
|
+
if (task !== 'validity' && rows.length && rows.every(row => !Object.hasOwn(row, 'scores') && Array.isArray(row.probs)
|
|
117
|
+
&& Math.abs(row.probs.reduce((sum, probability) => sum + probability, 0) - 1) <= 1e-6)) {
|
|
118
|
+
return calibrateLegacy(rows, task, allIds, minPrecision);
|
|
119
|
+
}
|
|
120
|
+
const options = Object.fromEntries(ids.map(id => [id, fitOption(normalized, id, minPrecision)]));
|
|
121
|
+
return { feasible: ids.every(id => id === 'unclassified' || options[id].feasible), task, rows: normalized.length, minPrecision,
|
|
122
|
+
thresholds: Object.fromEntries(ids.map(id => [id, options[id].threshold])), options };
|
|
123
|
+
}
|
|
124
|
+
|
|
61
125
|
if (require.main === module) {
|
|
62
126
|
try {
|
|
63
127
|
const args = process.argv.slice(2);
|
|
64
128
|
const ti = args.indexOf('--task'); const task = ti >= 0 ? args.splice(ti, 2)[1] : 'tier';
|
|
129
|
+
const ci = args.indexOf('--catalog'); const catalogFile = ci >= 0 ? args.splice(ci, 2)[1] : null;
|
|
65
130
|
const [input, output, extra] = args;
|
|
66
|
-
if (!input || !output || extra ||
|
|
67
|
-
const rows = fs.readFileSync(input, 'utf8').split('\n').filter(Boolean).map(
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
131
|
+
if (!input || !output || extra || (ci >= 0 && !catalogFile)) throw new Error('usage: system-one-calibrate.js <val-scores.jsonl> <calibration.json> [--task validity|intent|tier] [--catalog <train-report.json>]');
|
|
132
|
+
const rows = fs.readFileSync(input, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line));
|
|
133
|
+
const report = catalogFile ? JSON.parse(fs.readFileSync(catalogFile, 'utf8')) : null;
|
|
134
|
+
if (report && (report.task !== task || !Array.isArray(report.catalog))) throw new Error('trainer catalog does not match task');
|
|
135
|
+
const catalogIds = report?.catalog;
|
|
136
|
+
fs.writeFileSync(output, JSON.stringify(calibrate(rows, { task, catalogIds }), null, 2) + '\n');
|
|
137
|
+
console.log(JSON.stringify({ task, rows: rows.length }));
|
|
71
138
|
} catch (err) { console.error(`system-one-calibrate: ${err.message}`); process.exitCode = 1; }
|
|
72
139
|
}
|
|
73
|
-
module.exports = {
|
|
140
|
+
module.exports = { calibrate };
|
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { isDeepStrictEqual } = require('node:util');
|
|
7
|
+
const { STAGES, validateVersionManifest } = require('../harness-everything/scripts/system-one/manifest');
|
|
8
|
+
const { assertPrivateHistoryFile, appendPrivateHistory } = require('./system-one-cycle/common');
|
|
9
|
+
|
|
10
|
+
const STAGE_SET = new Set(STAGES);
|
|
11
|
+
const EPSILON = 1e-12;
|
|
12
|
+
const LOG_EPSILON = Number.EPSILON;
|
|
13
|
+
const fail = () => { throw new TypeError('invalid-system-one-curves-input'); };
|
|
14
|
+
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
+
const isText = value => typeof value === 'string' && value.trim().length > 0;
|
|
16
|
+
const isProbability = value => Number.isFinite(value) && value >= 0 && value <= 1;
|
|
17
|
+
|
|
18
|
+
function readJsonl(file) {
|
|
19
|
+
let lines;
|
|
20
|
+
try { lines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(line => line.trim()); } catch (_) { fail(); }
|
|
21
|
+
if (!lines.length) fail();
|
|
22
|
+
try { return lines.map(line => JSON.parse(line)); } catch (_) { fail(); }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readManifest(dir, version) {
|
|
26
|
+
let manifest;
|
|
27
|
+
try { manifest = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8')); } catch (_) { fail(); }
|
|
28
|
+
try { validateVersionManifest(manifest, version); } catch (_) { fail(); }
|
|
29
|
+
for (const entry of Object.values(manifest.stages)) {
|
|
30
|
+
if (!fs.existsSync(path.join(dir, entry.weights)) || !fs.existsSync(path.join(dir, entry.config))) fail();
|
|
31
|
+
}
|
|
32
|
+
return manifest;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function positives(row, stage, options) {
|
|
36
|
+
if (stage === 'validity') {
|
|
37
|
+
if (!['invalid', 'actionable'].includes(row.gold) || options.length !== 1 || options[0] !== 'invalid') fail();
|
|
38
|
+
return new Set(row.gold === 'invalid' ? ['invalid'] : []);
|
|
39
|
+
}
|
|
40
|
+
if (stage === 'tier') {
|
|
41
|
+
if (!isText(row.gold) || !options.includes(row.gold)) fail();
|
|
42
|
+
return new Set([row.gold]);
|
|
43
|
+
}
|
|
44
|
+
const gold = Array.isArray(row.gold) ? row.gold : [row.gold];
|
|
45
|
+
if (gold.some(id => !isText(id) || !options.includes(id)) || new Set(gold).size !== gold.length) fail();
|
|
46
|
+
return new Set(gold);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function readRows(file, stage, options) {
|
|
50
|
+
const rows = readJsonl(file);
|
|
51
|
+
const ids = new Set();
|
|
52
|
+
return rows.map(row => {
|
|
53
|
+
if (!isObject(row) || Object.keys(row).length !== 3 || !Object.hasOwn(row, 'id')
|
|
54
|
+
|| !Object.hasOwn(row, 'gold') || !Object.hasOwn(row, 'scores') || !isText(row.id) || ids.has(row.id)
|
|
55
|
+
|| !isObject(row.scores) || Object.keys(row.scores).length !== options.length
|
|
56
|
+
|| options.some(option => !Object.hasOwn(row.scores, option) || !isProbability(row.scores[option]))) fail();
|
|
57
|
+
ids.add(row.id);
|
|
58
|
+
return { id: row.id, positive: positives(row, stage, options), scores: row.scores };
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function quantile(values, probability) {
|
|
63
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
64
|
+
const position = (sorted.length - 1) * probability;
|
|
65
|
+
const lower = Math.floor(position);
|
|
66
|
+
const fraction = position - lower;
|
|
67
|
+
return sorted[lower] + (sorted[Math.min(lower + 1, sorted.length - 1)] - sorted[lower]) * fraction;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function decision(row, stage, options, referenceOnly) {
|
|
71
|
+
if (stage === 'validity') {
|
|
72
|
+
const probability = row.scores.invalid;
|
|
73
|
+
if (referenceOnly.includes('invalid')) return { confidence: 1 - probability, correct: !row.positive.has('invalid') };
|
|
74
|
+
const id = probability >= 0.5 ? 'invalid' : 'actionable';
|
|
75
|
+
// gold actionable has positive = Set([]), so compare predicted-vs-gold validity equivalence.
|
|
76
|
+
return { confidence: Math.max(probability, 1 - probability), correct: (id === 'invalid') === row.positive.has('invalid') };
|
|
77
|
+
}
|
|
78
|
+
const selectable = options.filter(option => !referenceOnly.includes(option) && !(stage === 'intent' && option === 'unclassified'));
|
|
79
|
+
if (!selectable.length) return { confidence: null, correct: false };
|
|
80
|
+
let id = selectable[0];
|
|
81
|
+
for (const option of selectable.slice(1)) if (row.scores[option] > row.scores[id]) id = option;
|
|
82
|
+
return { confidence: row.scores[id], correct: row.positive.has(id) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function coverageCurve(rows, stage, options, referenceOnly) {
|
|
86
|
+
const decisions = rows.map(row => decision(row, stage, options, referenceOnly));
|
|
87
|
+
return Array.from({ length: 101 }, (_, i) => {
|
|
88
|
+
const confidence = i / 100;
|
|
89
|
+
let count = 0; let correct = 0;
|
|
90
|
+
for (const item of decisions) {
|
|
91
|
+
if (item.confidence === null || item.confidence < confidence) continue;
|
|
92
|
+
count++;
|
|
93
|
+
if (item.correct) correct++;
|
|
94
|
+
}
|
|
95
|
+
return [confidence, count / rows.length, count ? correct / count : null];
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function coverageAccuracyAuc(curve) {
|
|
100
|
+
const points = curve.filter(([, coverage, accuracy]) => coverage > 0 && Number.isFinite(accuracy));
|
|
101
|
+
if (!points.length) return 0;
|
|
102
|
+
let area = 0;
|
|
103
|
+
for (let i = 1; i < points.length; i++) {
|
|
104
|
+
const width = Math.abs(points[i - 1][1] - points[i][1]);
|
|
105
|
+
area += width * (points[i - 1][2] + points[i][2]) / 2;
|
|
106
|
+
}
|
|
107
|
+
const last = points[points.length - 1];
|
|
108
|
+
return area + last[1] * last[2];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function scoreRows(rows, stage, options, referenceOnly = []) {
|
|
112
|
+
const bins = Array.from({ length: 10 }, (_, i) => ({ low: i / 10, high: (i + 1) / 10, sum: 0, positive: 0, n: 0 }));
|
|
113
|
+
const distributions = Object.fromEntries(options.map(option => [option, []]));
|
|
114
|
+
let logLoss = 0; let brier = 0; let count = 0;
|
|
115
|
+
for (const row of rows) {
|
|
116
|
+
for (const option of options) {
|
|
117
|
+
const probability = row.scores[option];
|
|
118
|
+
const target = row.positive.has(option) ? 1 : 0;
|
|
119
|
+
const clipped = Math.min(1 - LOG_EPSILON, Math.max(LOG_EPSILON, probability));
|
|
120
|
+
logLoss -= target ? Math.log(clipped) : Math.log(1 - clipped);
|
|
121
|
+
brier += (probability - target) ** 2;
|
|
122
|
+
const bin = bins[Math.min(9, Math.floor(probability * 10))];
|
|
123
|
+
bin.sum += probability; bin.positive += target; bin.n++;
|
|
124
|
+
distributions[option].push(probability);
|
|
125
|
+
count++;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const reliability = bins.map(bin => [bin.low, bin.high, bin.n ? bin.sum / bin.n : null,
|
|
129
|
+
bin.n ? bin.positive / bin.n : null, bin.n]);
|
|
130
|
+
const ece = bins.reduce((sum, bin) => sum + (bin.n / count) * (bin.n ? Math.abs(bin.sum / bin.n - bin.positive / bin.n) : 0), 0);
|
|
131
|
+
const curve = coverageCurve(rows, stage, options, referenceOnly);
|
|
132
|
+
return {
|
|
133
|
+
logLoss: logLoss / count,
|
|
134
|
+
brier: brier / count,
|
|
135
|
+
ece,
|
|
136
|
+
reliability,
|
|
137
|
+
coverageCurve: curve,
|
|
138
|
+
optionDistributions: Object.fromEntries(options.map(option => [option,
|
|
139
|
+
[0.05, 0.25, 0.5, 0.75, 0.95].map(q => quantile(distributions[option], q))])),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function comparisonMetrics(metrics) {
|
|
144
|
+
return { auc: Number.isFinite(metrics.coverageAccuracyAuc)
|
|
145
|
+
? metrics.coverageAccuracyAuc : coverageAccuracyAuc(metrics.coverageCurve), logLoss: metrics.logLoss, ece: metrics.ece };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function metricDeltas(current, previous) {
|
|
149
|
+
return { auc: current.auc - previous.auc, logLoss: current.logLoss - previous.logLoss, ece: current.ece - previous.ece };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function noWorse(deltas) {
|
|
153
|
+
return deltas.auc >= -EPSILON && deltas.logLoss <= EPSILON && deltas.ece <= EPSILON;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function noBetter(deltas) {
|
|
157
|
+
return deltas.auc <= EPSILON && deltas.logLoss >= -EPSILON && deltas.ece >= -EPSILON;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function strictlyWorse(deltas) {
|
|
161
|
+
return deltas.auc < -EPSILON || deltas.logLoss > EPSILON || deltas.ece > EPSILON;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function fmt(value) {
|
|
165
|
+
return `${value >= 0 ? '+' : ''}${value.toFixed(6)}`;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function assessFloor(holdout, history) {
|
|
169
|
+
if (!holdout) return { oldHoldoutRegression: false, detail: { status: 'unknown', stages: {} } };
|
|
170
|
+
const detail = { status: 'checked', stages: {}, baselineVersion: null };
|
|
171
|
+
let oldHoldoutRegression = false;
|
|
172
|
+
let baselineMissing = false;
|
|
173
|
+
for (const [stage, metrics] of Object.entries(holdout)) {
|
|
174
|
+
const current = comparisonMetrics(metrics);
|
|
175
|
+
const baseline = baselineForStage(history, stage);
|
|
176
|
+
const prior = baseline?.metrics ? {
|
|
177
|
+
auc: baseline.metrics.coverageAccuracyAuc,
|
|
178
|
+
logLoss: baseline.metrics.logLoss,
|
|
179
|
+
ece: baseline.metrics.ece,
|
|
180
|
+
} : null;
|
|
181
|
+
if (!prior) {
|
|
182
|
+
baselineMissing = true;
|
|
183
|
+
detail.stages[stage] = { coverageAccuracyAuc: current.auc, logLoss: current.logLoss, ece: current.ece,
|
|
184
|
+
baselineAvailable: false, ...(baseline?.version ? { baselineVersion: baseline.version } : {}) };
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
detail.stages[stage] = { coverageAccuracyAuc: current.auc, logLoss: current.logLoss, ece: current.ece,
|
|
188
|
+
baselineAvailable: true, baselineVersion: baseline.version };
|
|
189
|
+
const deltas = metricDeltas(current, prior);
|
|
190
|
+
if (!noWorse(deltas)) oldHoldoutRegression = true;
|
|
191
|
+
detail.stages[stage].deltas = deltas;
|
|
192
|
+
}
|
|
193
|
+
const baselineVersions = Object.values(detail.stages).map(stage => stage.baselineVersion);
|
|
194
|
+
if (baselineVersions.length && baselineVersions.every(isText) && new Set(baselineVersions).size === 1) {
|
|
195
|
+
detail.baselineVersion = baselineVersions[0];
|
|
196
|
+
}
|
|
197
|
+
if (oldHoldoutRegression) detail.status = 'regression';
|
|
198
|
+
else if (baselineMissing || Object.keys(holdout).length === 0) detail.status = 'baseline-unavailable';
|
|
199
|
+
return { oldHoldoutRegression, detail };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function floorMetrics(item, stage) {
|
|
203
|
+
const metrics = item?.floor?.detail?.stages?.[stage];
|
|
204
|
+
return metrics && [metrics.coverageAccuracyAuc, metrics.logLoss, metrics.ece].every(Number.isFinite) ? metrics : null;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function baselineForStage(history, stage) {
|
|
208
|
+
let version;
|
|
209
|
+
for (const item of history) {
|
|
210
|
+
const stageVersion = item.floor?.detail?.stages?.[stage]?.baselineVersion;
|
|
211
|
+
const legacyVersion = item.floor?.detail?.baselineVersion;
|
|
212
|
+
if (isText(stageVersion) || isText(legacyVersion)) {
|
|
213
|
+
version = isText(stageVersion) ? stageVersion : legacyVersion;
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (version) {
|
|
218
|
+
const item = history.find(row => row.version === version);
|
|
219
|
+
return { version, metrics: floorMetrics(item, stage) };
|
|
220
|
+
}
|
|
221
|
+
const item = history.find(row => floorMetrics(row, stage));
|
|
222
|
+
return item ? { version: item.version, metrics: floorMetrics(item, stage) } : null;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function readHistory(file) {
|
|
226
|
+
if (!fs.existsSync(file)) return [];
|
|
227
|
+
let lines;
|
|
228
|
+
try { lines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(line => line.trim()); } catch (_) { fail(); }
|
|
229
|
+
try {
|
|
230
|
+
const history = lines.map(line => JSON.parse(line));
|
|
231
|
+
const versions = new Set();
|
|
232
|
+
for (const item of history) {
|
|
233
|
+
validateCurveRecord(item);
|
|
234
|
+
if (versions.has(item.version)) fail();
|
|
235
|
+
versions.add(item.version);
|
|
236
|
+
}
|
|
237
|
+
return history;
|
|
238
|
+
} catch (_) { fail(); }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function validateCurveRecord(curves) {
|
|
242
|
+
if (!isObject(curves) || curves.schemaVersion !== 1 || !isText(curves.version) || !isText(curves.createdAt)
|
|
243
|
+
|| !isObject(curves.stages) || !Object.keys(curves.stages).length
|
|
244
|
+
|| !isObject(curves.floor) || typeof curves.floor.oldHoldoutRegression !== 'boolean'
|
|
245
|
+
|| !isObject(curves.floor.detail) || !isObject(curves.floor.detail.stages)
|
|
246
|
+
|| !['unknown', 'checked', 'regression', 'baseline-unavailable'].includes(curves.floor.detail.status)
|
|
247
|
+
|| (curves.floor.detail.baselineVersion !== null && curves.floor.detail.baselineVersion !== undefined
|
|
248
|
+
&& !isText(curves.floor.detail.baselineVersion))) fail();
|
|
249
|
+
for (const [stage, metrics] of Object.entries(curves.stages)) {
|
|
250
|
+
if (!STAGE_SET.has(stage) || !isObject(metrics) || ![metrics.logLoss, metrics.brier, metrics.ece].every(Number.isFinite)
|
|
251
|
+
|| !Array.isArray(metrics.coverageCurve) || metrics.coverageCurve.length !== 101
|
|
252
|
+
|| metrics.coverageCurve.some(point => !Array.isArray(point) || point.length !== 3
|
|
253
|
+
|| !Number.isFinite(point[0]) || point[0] < 0 || point[0] > 1
|
|
254
|
+
|| !Number.isFinite(point[1]) || point[1] < 0 || point[1] > 1
|
|
255
|
+
|| (point[2] !== null && (!Number.isFinite(point[2]) || point[2] < 0 || point[2] > 1)))) fail();
|
|
256
|
+
}
|
|
257
|
+
for (const [stage, metrics] of Object.entries(curves.floor.detail.stages)) {
|
|
258
|
+
if (!Object.hasOwn(curves.stages, stage) || !isObject(metrics)
|
|
259
|
+
|| ![metrics.coverageAccuracyAuc, metrics.logLoss, metrics.ece].every(Number.isFinite)
|
|
260
|
+
|| typeof metrics.baselineAvailable !== 'boolean'
|
|
261
|
+
|| (metrics.baselineVersion !== undefined && !isText(metrics.baselineVersion))) fail();
|
|
262
|
+
if (metrics.baselineAvailable && (!isObject(metrics.deltas)
|
|
263
|
+
|| !['auc', 'logLoss', 'ece'].every(key => Number.isFinite(metrics.deltas[key]))
|
|
264
|
+
|| (!isText(metrics.baselineVersion) && !isText(curves.floor.detail.baselineVersion)))) fail();
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function withoutCreatedAt(curves) {
|
|
269
|
+
const immutable = JSON.parse(JSON.stringify(curves));
|
|
270
|
+
delete immutable.createdAt;
|
|
271
|
+
for (const stage of Object.values(immutable.floor?.detail?.stages || {})) {
|
|
272
|
+
if (!isText(stage.baselineVersion) && isText(immutable.floor.detail.baselineVersion)) {
|
|
273
|
+
stage.baselineVersion = immutable.floor.detail.baselineVersion;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return immutable;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function assertVersionReusable(history, curves) {
|
|
280
|
+
const existing = history.find(item => item.version === curves.version);
|
|
281
|
+
if (existing && !isDeepStrictEqual(withoutCreatedAt(existing), withoutCreatedAt(curves))) fail();
|
|
282
|
+
return existing;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function validateSavedCurves(curves, version, manifest) {
|
|
286
|
+
validateCurveRecord(curves);
|
|
287
|
+
if (curves.version !== version || Object.keys(curves.stages).length !== Object.keys(manifest.stages).length
|
|
288
|
+
|| Object.keys(curves.stages).some(stage => !Object.hasOwn(manifest.stages, stage))) fail();
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function validateSavedTrend(trend, version) {
|
|
292
|
+
if (!isObject(trend) || !['promote', 'hold', 'rollback'].includes(trend.verdict)
|
|
293
|
+
|| !Array.isArray(trend.compared) || trend.compared.some(version => !isText(version))
|
|
294
|
+
|| !trend.compared.includes(version)
|
|
295
|
+
|| !Array.isArray(trend.reasons) || trend.reasons.some(reason => !isText(reason))) fail();
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function validateBaselineReferences(curves, history) {
|
|
299
|
+
for (const [stage, baseline] of Object.entries(curves.floor.detail.stages)) {
|
|
300
|
+
if (baseline.baselineAvailable !== true) continue;
|
|
301
|
+
const baselineVersion = isText(baseline.baselineVersion) ? baseline.baselineVersion : curves.floor.detail.baselineVersion;
|
|
302
|
+
if (!isText(baselineVersion) || !floorMetrics(history.find(row => row.version === baselineVersion), stage)) fail();
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function validateResumeDecision(curves, trend, history) {
|
|
307
|
+
const candidateIndex = history.findIndex(row => row.version === curves.version);
|
|
308
|
+
const predecessor = candidateIndex < 0 ? history : history.slice(0, candidateIndex);
|
|
309
|
+
const compared = [...predecessor.slice(-3).map(row => row.version), curves.version];
|
|
310
|
+
if (!isDeepStrictEqual(trend.compared, compared)) fail();
|
|
311
|
+
|
|
312
|
+
const holdout = Object.keys(curves.floor.detail.stages).length ? curves.floor.detail.stages : null;
|
|
313
|
+
const floor = assessFloor(holdout, predecessor);
|
|
314
|
+
if (!isDeepStrictEqual(curves.floor, floor) || !isDeepStrictEqual(trend, decideTrend(curves, predecessor, floor))) fail();
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function appendHistoryRow(file, history, curves) {
|
|
318
|
+
if (assertVersionReusable(history, curves)) return;
|
|
319
|
+
appendPrivateHistory(file, `${JSON.stringify(curves)}\n`);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function worseningCycles(history, stages) {
|
|
323
|
+
if (history.length < 3) return null;
|
|
324
|
+
// shortcut: history has no active-version field, so its latest three records stand in for the active trend; upgrade when the shared schema records active identity.
|
|
325
|
+
const [older, previous, active] = history.slice(-3);
|
|
326
|
+
for (const stage of Object.keys(stages)) {
|
|
327
|
+
const a = older.stages?.[stage]; const b = previous.stages?.[stage]; const c = active.stages?.[stage];
|
|
328
|
+
if (!a?.coverageCurve || !b?.coverageCurve || !c?.coverageCurve) continue;
|
|
329
|
+
const first = metricDeltas(comparisonMetrics(b), comparisonMetrics(a));
|
|
330
|
+
const second = metricDeltas(comparisonMetrics(c), comparisonMetrics(b));
|
|
331
|
+
if (!noBetter(first) || !strictlyWorse(first) || !noBetter(second) || !strictlyWorse(second)) continue;
|
|
332
|
+
return { stage, first, second, versions: [older.version, previous.version, active.version] };
|
|
333
|
+
}
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function decideTrend(candidate, history, floor) {
|
|
338
|
+
const reasons = [];
|
|
339
|
+
const previous = history.at(-1);
|
|
340
|
+
let candidateNoWorse = !!previous;
|
|
341
|
+
if (!previous) {
|
|
342
|
+
candidateNoWorse = false;
|
|
343
|
+
reasons.push('no previous version is available for curve comparison');
|
|
344
|
+
} else {
|
|
345
|
+
for (const [stage, metrics] of Object.entries(candidate.stages)) {
|
|
346
|
+
const priorMetrics = previous.stages?.[stage];
|
|
347
|
+
if (!priorMetrics?.coverageCurve) {
|
|
348
|
+
candidateNoWorse = false;
|
|
349
|
+
reasons.push(`${stage} curves cannot be compared with ${previous.version}`);
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
const deltas = metricDeltas(comparisonMetrics(metrics), comparisonMetrics(priorMetrics));
|
|
353
|
+
for (const [name, value] of Object.entries(deltas)) reasons.push(`${stage} ${name === 'auc' ? 'coverage-accuracy AUC' : name === 'logLoss' ? 'log-loss' : 'ECE'} delta ${fmt(value)} vs ${previous.version}`);
|
|
354
|
+
if (!noWorse(deltas)) candidateNoWorse = false;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const floorAllowsPromotion = floor.detail.status === 'checked' && !floor.oldHoldoutRegression;
|
|
358
|
+
for (const [stage, metrics] of Object.entries(floor.detail.stages)) {
|
|
359
|
+
if (!metrics.deltas) continue;
|
|
360
|
+
const detail = Object.entries(metrics.deltas).map(([name, value]) => `${name === 'auc' ? 'coverage-accuracy AUC' : name === 'logLoss' ? 'log-loss' : 'ECE'} delta ${fmt(value)}`).join(', ');
|
|
361
|
+
reasons.push(`${stage} old-holdout ${noWorse(metrics.deltas) ? 'curve deltas' : 'regression'}: ${detail}`);
|
|
362
|
+
}
|
|
363
|
+
if (!floorAllowsPromotion && !floor.oldHoldoutRegression) reasons.push(`old-holdout floor ${floor.detail.status}; promotion requires a checked floor`);
|
|
364
|
+
if (candidateNoWorse && floorAllowsPromotion) return { compared: [...history.slice(-3).map(item => item.version), candidate.version], verdict: 'promote', reasons };
|
|
365
|
+
|
|
366
|
+
const worsening = worseningCycles(history, candidate.stages);
|
|
367
|
+
if (worsening) {
|
|
368
|
+
reasons.push(`${worsening.stage} active curve worsened across two consecutive cycles (${worsening.versions.join(' → ')}): `
|
|
369
|
+
+ `coverage-accuracy AUC ${fmt(worsening.first.auc)}, ${fmt(worsening.second.auc)}; `
|
|
370
|
+
+ `log-loss ${fmt(worsening.first.logLoss)}, ${fmt(worsening.second.logLoss)}; `
|
|
371
|
+
+ `ECE ${fmt(worsening.first.ece)}, ${fmt(worsening.second.ece)}`);
|
|
372
|
+
return { compared: [...history.slice(-3).map(item => item.version), candidate.version], verdict: 'rollback', reasons };
|
|
373
|
+
}
|
|
374
|
+
return { compared: [...history.slice(-3).map(item => item.version), candidate.version], verdict: 'hold', reasons };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function stageFiles(args, option) {
|
|
378
|
+
const result = {};
|
|
379
|
+
for (const value of args[option]) {
|
|
380
|
+
const split = value.indexOf('=');
|
|
381
|
+
if (split < 1) fail();
|
|
382
|
+
const stage = value.slice(0, split); const file = value.slice(split + 1);
|
|
383
|
+
if (!STAGE_SET.has(stage) || !isText(file) || Object.hasOwn(result, stage)) fail();
|
|
384
|
+
result[stage] = file;
|
|
385
|
+
}
|
|
386
|
+
return result;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function parseArgs(argv) {
|
|
390
|
+
const parsed = { val: [], holdout: [] };
|
|
391
|
+
const names = { '--version': 'version', '--version-dir': 'versionDir', '--val-scores': 'val', '--holdout-scores': 'holdout',
|
|
392
|
+
'--history': 'history', '--out': 'out', '--resume-curves': 'resumeCurves' };
|
|
393
|
+
for (let i = 0; i < argv.length; i++) {
|
|
394
|
+
const key = names[argv[i]]; const value = argv[++i];
|
|
395
|
+
if (!key || value === undefined) fail();
|
|
396
|
+
if (key === 'val' || key === 'holdout') parsed[key].push(value);
|
|
397
|
+
else if (Object.hasOwn(parsed, key)) fail();
|
|
398
|
+
else parsed[key] = value;
|
|
399
|
+
}
|
|
400
|
+
if (!isText(parsed.version) || !isText(parsed.versionDir) || !isText(parsed.history) || !isText(parsed.out)) fail();
|
|
401
|
+
if (parsed.resumeCurves) {
|
|
402
|
+
if (!isText(parsed.resumeCurves) || parsed.val.length || parsed.holdout.length) fail();
|
|
403
|
+
} else if (!parsed.val.length) fail();
|
|
404
|
+
return parsed;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function run(argv) {
|
|
408
|
+
const args = parseArgs(argv);
|
|
409
|
+
args.history = assertPrivateHistoryFile(args.history);
|
|
410
|
+
const manifest = readManifest(args.versionDir, args.version);
|
|
411
|
+
if (args.resumeCurves) {
|
|
412
|
+
let curves; let trend;
|
|
413
|
+
try {
|
|
414
|
+
curves = JSON.parse(fs.readFileSync(args.resumeCurves, 'utf8'));
|
|
415
|
+
trend = JSON.parse(fs.readFileSync(path.join(args.out, 'trend.json'), 'utf8'));
|
|
416
|
+
} catch (_) { fail(); }
|
|
417
|
+
validateSavedCurves(curves, args.version, manifest);
|
|
418
|
+
validateSavedTrend(trend, args.version);
|
|
419
|
+
const history = readHistory(args.history);
|
|
420
|
+
validateBaselineReferences(curves, history);
|
|
421
|
+
validateResumeDecision(curves, trend, history);
|
|
422
|
+
appendHistoryRow(args.history, history, curves);
|
|
423
|
+
console.log(JSON.stringify({ resumed: true, version: args.version }));
|
|
424
|
+
return { curves, trend };
|
|
425
|
+
}
|
|
426
|
+
const valFiles = stageFiles(args, 'val');
|
|
427
|
+
const holdoutFiles = stageFiles(args, 'holdout');
|
|
428
|
+
if (Object.keys(holdoutFiles).some(stage => !Object.hasOwn(valFiles, stage))) fail();
|
|
429
|
+
const stages = {}; const holdoutMetrics = {};
|
|
430
|
+
for (const [stage, file] of Object.entries(valFiles)) {
|
|
431
|
+
const entry = manifest.stages[stage];
|
|
432
|
+
if (!entry) fail();
|
|
433
|
+
const valRows = readRows(file, stage, entry.options);
|
|
434
|
+
const referenceOnly = entry.referenceOnly ?? [];
|
|
435
|
+
stages[stage] = scoreRows(valRows, stage, entry.options, referenceOnly);
|
|
436
|
+
if (holdoutFiles[stage]) {
|
|
437
|
+
const holdoutRows = readRows(holdoutFiles[stage], stage, entry.options);
|
|
438
|
+
const valIds = new Set(valRows.map(row => row.id));
|
|
439
|
+
if (holdoutRows.some(row => valIds.has(row.id))) fail();
|
|
440
|
+
holdoutMetrics[stage] = scoreRows(holdoutRows, stage, entry.options, referenceOnly);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
if (Object.keys(holdoutFiles).length && Object.keys(holdoutFiles).length !== Object.keys(valFiles).length) fail();
|
|
444
|
+
const history = readHistory(args.history);
|
|
445
|
+
const floor = assessFloor(Object.keys(holdoutMetrics).length ? holdoutMetrics : null, history);
|
|
446
|
+
const curves = { schemaVersion: 1, version: args.version, createdAt: new Date().toISOString(), stages, floor };
|
|
447
|
+
const existing = assertVersionReusable(history, curves);
|
|
448
|
+
validateBaselineReferences(curves, history);
|
|
449
|
+
const trend = decideTrend(curves, history, floor);
|
|
450
|
+
fs.mkdirSync(args.out, { recursive: true });
|
|
451
|
+
fs.writeFileSync(path.join(args.out, 'curves.json'), `${JSON.stringify(curves, null, 2)}\n`);
|
|
452
|
+
fs.writeFileSync(path.join(args.out, 'trend.json'), `${JSON.stringify(trend, null, 2)}\n`);
|
|
453
|
+
if (!existing) appendHistoryRow(args.history, history, curves);
|
|
454
|
+
const summary = Object.fromEntries(Object.entries(stages).map(([stage, value]) => [stage, {
|
|
455
|
+
rows: readJsonl(valFiles[stage]).length,
|
|
456
|
+
logLoss: value.logLoss,
|
|
457
|
+
brier: value.brier,
|
|
458
|
+
ece: value.ece,
|
|
459
|
+
coverageAccuracyAuc: coverageAccuracyAuc(value.coverageCurve),
|
|
460
|
+
}]));
|
|
461
|
+
console.log(JSON.stringify({ rows: Object.values(summary).reduce((sum, item) => sum + item.rows, 0), stages: summary }));
|
|
462
|
+
return { curves, trend };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
if (require.main === module) {
|
|
466
|
+
try { run(process.argv.slice(2)); } catch (_) {
|
|
467
|
+
console.error('system-one-curves: invalid arguments, manifest, history, or score input');
|
|
468
|
+
process.exitCode = 1;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
module.exports = { coverageAccuracyAuc, run, scoreRows };
|