harness-everything 0.51.0 → 0.52.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.
Files changed (83) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/ci.yml +23 -0
  4. package/CHANGELOG.md +34 -0
  5. package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-a-evid-001.md +123 -0
  6. package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-b-route-001.md +130 -0
  7. package/ci/mechanism-2am-observations-session-import.test.js +4 -1
  8. package/ci/mechanism-34-observations.test.js +127 -23
  9. package/ci/mechanism-349-ci-change-scope.test.js +260 -0
  10. package/ci/mechanism-handoff-file.test.js +121 -0
  11. package/ci/mechanism-system-one-contract.test.js +9 -2
  12. package/ci/mechanism-system-one-curves.test.js +206 -0
  13. package/ci/mechanism-system-one-cycle.test.js +585 -0
  14. package/ci/mechanism-system-one-evaluation.test.js +32 -5
  15. package/ci/mechanism-system-one-handoff-input.test.js +208 -0
  16. package/ci/mechanism-system-one-install.test.js +202 -77
  17. package/ci/mechanism-system-one-live.test.js +361 -0
  18. package/ci/mechanism-system-one-relevance.test.js +11 -1
  19. package/ci/mechanism-system-one-train.test.js +136 -53
  20. package/ci/system-one-adapter-test.py +331 -0
  21. package/ci/system-one-train-test.py +116 -24
  22. package/docs/adr/EVID-001.md +123 -0
  23. package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
  24. package/docs/governed-index.md +2 -0
  25. package/docs/routing.md +2 -2
  26. package/docs/system-one-cycle.md +68 -0
  27. package/docs/system-one-observations.md +9 -8
  28. package/docs/system-one-routing.md +163 -115
  29. package/docs/system-one-suggestion-gates.md +6 -8
  30. package/docs/system-one-training.md +44 -7
  31. package/docs/workflow-runtime.md +19 -0
  32. package/harness-everything/SKILL.md +1 -1
  33. package/harness-everything/scripts/kernel-router.js +2 -1
  34. package/harness-everything/scripts/system-one/contract.js +19 -15
  35. package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  36. package/harness-everything/scripts/system-one/evaluate.js +4 -9
  37. package/harness-everything/scripts/system-one/handoff-input.js +76 -0
  38. package/harness-everything/scripts/system-one/install.js +281 -113
  39. package/harness-everything/scripts/system-one/manifest.js +58 -0
  40. package/harness-everything/scripts/system-one/provider.js +96 -2
  41. package/harness-everything/scripts/system-one/resident.js +47 -1
  42. package/harness-everything/scripts/system-one/router.js +80 -1
  43. package/harness-everything/scripts/tier-router.js +21 -6
  44. package/hooks/scripts/lib/observations.js +43 -4
  45. package/opencode-plugin/plugin.json +1 -1
  46. package/package.json +1 -1
  47. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  48. package/plugins/harness-everything/hooks/scripts/lib/observations.js +43 -4
  49. package/plugins/harness-everything/plugin.json +1 -1
  50. package/plugins/harness-everything/scripts/handoff-file.js +223 -0
  51. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  52. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
  53. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
  54. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
  55. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
  56. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
  57. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
  58. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
  59. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
  60. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
  61. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
  62. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
  63. package/sbom.cdx.json +7 -7
  64. package/scripts/ci-change-scope.js +59 -0
  65. package/scripts/handoff-file.js +223 -0
  66. package/scripts/sync-openai-plugin.js +4 -0
  67. package/scripts/system-one-calibrate.js +108 -41
  68. package/scripts/system-one-curves.js +332 -0
  69. package/scripts/system-one-cycle/adjudication-input.js +65 -0
  70. package/scripts/system-one-cycle/build.js +165 -0
  71. package/scripts/system-one-cycle/collect.js +50 -0
  72. package/scripts/system-one-cycle/common.js +137 -0
  73. package/scripts/system-one-cycle/engines.js +62 -0
  74. package/scripts/system-one-cycle/evaluate.js +70 -0
  75. package/scripts/system-one-cycle/judge.js +106 -0
  76. package/scripts/system-one-cycle/label.js +59 -0
  77. package/scripts/system-one-cycle/package.js +173 -0
  78. package/scripts/system-one-cycle/score.py +111 -0
  79. package/scripts/system-one-cycle/train.js +136 -0
  80. package/scripts/system-one-cycle.js +131 -0
  81. package/scripts/system-one-observations-export.js +29 -6
  82. package/scripts/system-one-observations-review.js +4 -5
  83. package/scripts/system-one-train.py +117 -61
@@ -1,73 +1,140 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
- // Chooses System One acceptance thresholds on validation scores (docs/system-one-training.md).
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 IDS = ['tier1', 'tier2', 'tier3', 'unclassified'];
10
- // Same acceptance rule as contract.decide: top probability and top-minus-second margin, unclassified abstains.
11
- function decideRow(probs, { minConfidence, minMargin }, ids = IDS) {
12
- const order = probs.map((p, i) => [p, i]).sort((a, b) => b[0] - a[0] || a[1] - b[1]);
13
- const [top, second] = order;
14
- const margin = top[0] - second[0];
15
- if (margin === 0 || top[0] < minConfidence || margin < minMargin || ids[top[1]] === 'unclassified') return null;
16
- return ids[top[1]];
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
- // Predicted secondary intents: every other catalog intent at or above the threshold.
19
- const secondaryOf = (probs, primary, threshold, ids) => ids.filter((id, i) => id !== primary && id !== 'unclassified' && probs[i] >= threshold);
20
- // Threshold with the best secondary micro-F1 on validation; ties keep the lowest.
21
- function secondaryThreshold(rows, ids) {
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
- for (let s = 5; s <= 50; s += 5) {
24
- let tp = 0; let fp = 0; let fn = 0;
25
- for (const r of rows) {
26
- const primary = ids[r.probs.indexOf(Math.max(...r.probs))];
27
- const predicted = new Set(secondaryOf(r.probs, primary, s / 100, ids)); const gold = new Set(r.secondary || []);
28
- for (const x of predicted) (gold.has(x) ? tp++ : fp++);
29
- for (const x of gold) if (!predicted.has(x)) fn++;
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 f1 = 2 * tp + fp + fn ? 2 * tp / (2 * tp + fp + fn) : 0;
32
- if (!best || f1 > best.f1) best = { threshold: s / 100, f1 };
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.threshold;
54
+ return best || { feasible: false, threshold: null, accepted: 0, coverage: 0, precision: null };
35
55
  }
36
- function calibrate(rows, { minPrecision = 0.85, task = 'tier' } = {}) {
37
- const ids = CATALOGS[task].map(o => o.id);
56
+
57
+ function calibrateLegacy(rows, task, ids, minPrecision) {
38
58
  const multi = task === 'intent';
39
- const sThreshold = multi ? secondaryThreshold(rows, ids) : undefined;
40
- // Intent rows score by graded agreement against { gold, secondary }; tier rows by exact match.
41
- const score = (r, d) => (multi ? gradedAgreement({ gold: r.gold, secondary: r.secondary || [] }, { gold: d, secondary: secondaryOf(r.probs, d, sThreshold, ids) })
42
- : Number(d === (r.gold === null ? 'unclassified' : r.gold)));
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 t = { minConfidence: c / 100, minMargin: m / 100 };
85
+ const minConfidence = c / 100; const minMargin = m / 100;
47
86
  let accepted = 0; let points = 0; let exact = 0;
48
- for (const r of rows) { const d = decideRow(r.probs, t, ids); if (d) { accepted++; points += score(r, d); if (d === r.gold) exact++; } }
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
- // Highest coverage wins; ties keep the first (lowest) thresholds scanned.
53
- if (!best || coverage > best.coverage) best = { ...t, coverage, precision, accepted, ...(multi ? { exactPrecision: exact / accepted } : {}) };
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: sThreshold } : {};
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 || !Object.hasOwn(CATALOGS, task)) throw new Error('usage: system-one-calibrate.js <val-scores.jsonl> <calibration.json> [--task tier|intent]');
67
- const rows = fs.readFileSync(input, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l));
68
- const result = calibrate(rows, { task });
69
- fs.writeFileSync(output, `${JSON.stringify(result, null, 2)}\n`);
70
- console.log(JSON.stringify(result));
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 = { decideRow, calibrate };
140
+ module.exports = { calibrate };
@@ -0,0 +1,332 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { STAGES, validateVersionManifest } = require('../harness-everything/scripts/system-one/manifest');
7
+
8
+ const STAGE_SET = new Set(STAGES);
9
+ const EPSILON = 1e-12;
10
+ const LOG_EPSILON = Number.EPSILON;
11
+ const fail = () => { throw new TypeError('invalid-system-one-curves-input'); };
12
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
13
+ const isText = value => typeof value === 'string' && value.trim().length > 0;
14
+ const isProbability = value => Number.isFinite(value) && value >= 0 && value <= 1;
15
+
16
+ function readJsonl(file) {
17
+ let lines;
18
+ try { lines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(line => line.trim()); } catch (_) { fail(); }
19
+ if (!lines.length) fail();
20
+ try { return lines.map(line => JSON.parse(line)); } catch (_) { fail(); }
21
+ }
22
+
23
+ function readManifest(dir, version) {
24
+ let manifest;
25
+ try { manifest = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8')); } catch (_) { fail(); }
26
+ try { validateVersionManifest(manifest, version); } catch (_) { fail(); }
27
+ for (const entry of Object.values(manifest.stages)) {
28
+ if (!fs.existsSync(path.join(dir, entry.weights)) || !fs.existsSync(path.join(dir, entry.config))) fail();
29
+ }
30
+ return manifest;
31
+ }
32
+
33
+ function positives(row, stage, options) {
34
+ if (stage === 'validity') {
35
+ if (!['invalid', 'actionable'].includes(row.gold) || options.length !== 1 || options[0] !== 'invalid') fail();
36
+ return new Set(row.gold === 'invalid' ? ['invalid'] : []);
37
+ }
38
+ if (stage === 'tier') {
39
+ if (!isText(row.gold) || !options.includes(row.gold)) fail();
40
+ return new Set([row.gold]);
41
+ }
42
+ const gold = Array.isArray(row.gold) ? row.gold : [row.gold];
43
+ if (gold.some(id => !isText(id) || !options.includes(id)) || new Set(gold).size !== gold.length) fail();
44
+ return new Set(gold);
45
+ }
46
+
47
+ function readRows(file, stage, options) {
48
+ const rows = readJsonl(file);
49
+ const ids = new Set();
50
+ return rows.map(row => {
51
+ if (!isObject(row) || Object.keys(row).length !== 3 || !Object.hasOwn(row, 'id')
52
+ || !Object.hasOwn(row, 'gold') || !Object.hasOwn(row, 'scores') || !isText(row.id) || ids.has(row.id)
53
+ || !isObject(row.scores) || Object.keys(row.scores).length !== options.length
54
+ || options.some(option => !Object.hasOwn(row.scores, option) || !isProbability(row.scores[option]))) fail();
55
+ ids.add(row.id);
56
+ return { id: row.id, positive: positives(row, stage, options), scores: row.scores };
57
+ });
58
+ }
59
+
60
+ function quantile(values, probability) {
61
+ const sorted = [...values].sort((a, b) => a - b);
62
+ const position = (sorted.length - 1) * probability;
63
+ const lower = Math.floor(position);
64
+ const fraction = position - lower;
65
+ return sorted[lower] + (sorted[Math.min(lower + 1, sorted.length - 1)] - sorted[lower]) * fraction;
66
+ }
67
+
68
+ function decision(row, stage, options, referenceOnly) {
69
+ if (stage === 'validity') {
70
+ const probability = row.scores.invalid;
71
+ if (referenceOnly.includes('invalid')) return { confidence: 1 - probability, correct: !row.positive.has('invalid') };
72
+ const id = probability >= 0.5 ? 'invalid' : 'actionable';
73
+ // gold actionable has positive = Set([]), so compare predicted-vs-gold validity equivalence.
74
+ return { confidence: Math.max(probability, 1 - probability), correct: (id === 'invalid') === row.positive.has('invalid') };
75
+ }
76
+ const selectable = options.filter(option => !referenceOnly.includes(option) && !(stage === 'intent' && option === 'unclassified'));
77
+ if (!selectable.length) return { confidence: null, correct: false };
78
+ let id = selectable[0];
79
+ for (const option of selectable.slice(1)) if (row.scores[option] > row.scores[id]) id = option;
80
+ return { confidence: row.scores[id], correct: row.positive.has(id) };
81
+ }
82
+
83
+ function coverageCurve(rows, stage, options, referenceOnly) {
84
+ const decisions = rows.map(row => decision(row, stage, options, referenceOnly));
85
+ return Array.from({ length: 101 }, (_, i) => {
86
+ const confidence = i / 100;
87
+ let count = 0; let correct = 0;
88
+ for (const item of decisions) {
89
+ if (item.confidence === null || item.confidence < confidence) continue;
90
+ count++;
91
+ if (item.correct) correct++;
92
+ }
93
+ return [confidence, count / rows.length, count ? correct / count : null];
94
+ });
95
+ }
96
+
97
+ function coverageAccuracyAuc(curve) {
98
+ const points = curve.filter(([, coverage, accuracy]) => coverage > 0 && Number.isFinite(accuracy));
99
+ if (!points.length) return 0;
100
+ let area = 0;
101
+ for (let i = 1; i < points.length; i++) {
102
+ const width = Math.abs(points[i - 1][1] - points[i][1]);
103
+ area += width * (points[i - 1][2] + points[i][2]) / 2;
104
+ }
105
+ const last = points[points.length - 1];
106
+ return area + last[1] * last[2];
107
+ }
108
+
109
+ function scoreRows(rows, stage, options, referenceOnly = []) {
110
+ const bins = Array.from({ length: 10 }, (_, i) => ({ low: i / 10, high: (i + 1) / 10, sum: 0, positive: 0, n: 0 }));
111
+ const distributions = Object.fromEntries(options.map(option => [option, []]));
112
+ let logLoss = 0; let brier = 0; let count = 0;
113
+ for (const row of rows) {
114
+ for (const option of options) {
115
+ const probability = row.scores[option];
116
+ const target = row.positive.has(option) ? 1 : 0;
117
+ const clipped = Math.min(1 - LOG_EPSILON, Math.max(LOG_EPSILON, probability));
118
+ logLoss -= target ? Math.log(clipped) : Math.log(1 - clipped);
119
+ brier += (probability - target) ** 2;
120
+ const bin = bins[Math.min(9, Math.floor(probability * 10))];
121
+ bin.sum += probability; bin.positive += target; bin.n++;
122
+ distributions[option].push(probability);
123
+ count++;
124
+ }
125
+ }
126
+ const reliability = bins.map(bin => [bin.low, bin.high, bin.n ? bin.sum / bin.n : null,
127
+ bin.n ? bin.positive / bin.n : null, bin.n]);
128
+ const ece = bins.reduce((sum, bin) => sum + (bin.n / count) * (bin.n ? Math.abs(bin.sum / bin.n - bin.positive / bin.n) : 0), 0);
129
+ const curve = coverageCurve(rows, stage, options, referenceOnly);
130
+ return {
131
+ logLoss: logLoss / count,
132
+ brier: brier / count,
133
+ ece,
134
+ reliability,
135
+ coverageCurve: curve,
136
+ optionDistributions: Object.fromEntries(options.map(option => [option,
137
+ [0.05, 0.25, 0.5, 0.75, 0.95].map(q => quantile(distributions[option], q))])),
138
+ };
139
+ }
140
+
141
+ function comparisonMetrics(metrics) {
142
+ return { auc: coverageAccuracyAuc(metrics.coverageCurve), logLoss: metrics.logLoss, ece: metrics.ece };
143
+ }
144
+
145
+ function metricDeltas(current, previous) {
146
+ return { auc: current.auc - previous.auc, logLoss: current.logLoss - previous.logLoss, ece: current.ece - previous.ece };
147
+ }
148
+
149
+ function noWorse(deltas) {
150
+ return deltas.auc >= -EPSILON && deltas.logLoss <= EPSILON && deltas.ece <= EPSILON;
151
+ }
152
+
153
+ function noBetter(deltas) {
154
+ return deltas.auc <= EPSILON && deltas.logLoss >= -EPSILON && deltas.ece >= -EPSILON;
155
+ }
156
+
157
+ function strictlyWorse(deltas) {
158
+ return deltas.auc < -EPSILON || deltas.logLoss > EPSILON || deltas.ece > EPSILON;
159
+ }
160
+
161
+ function fmt(value) {
162
+ return `${value >= 0 ? '+' : ''}${value.toFixed(6)}`;
163
+ }
164
+
165
+ function assessFloor(holdout, history) {
166
+ if (!holdout) return { oldHoldoutRegression: false, detail: { status: 'unknown', stages: {} } };
167
+ const detail = { status: 'checked', stages: {}, baselineVersion: null };
168
+ let oldHoldoutRegression = false;
169
+ let baselineMissing = false;
170
+ for (const [stage, metrics] of Object.entries(holdout)) {
171
+ const current = comparisonMetrics(metrics);
172
+ const previous = [...history].reverse().find(item => Number.isFinite(item.floor?.detail?.stages?.[stage]?.coverageAccuracyAuc));
173
+ if (previous && !detail.baselineVersion) detail.baselineVersion = previous.version;
174
+ const baseline = previous?.floor.detail.stages[stage];
175
+ const prior = baseline && Number.isFinite(baseline.coverageAccuracyAuc)
176
+ ? { auc: baseline.coverageAccuracyAuc, logLoss: baseline.logLoss, ece: baseline.ece } : null;
177
+ if (!prior) {
178
+ baselineMissing = true;
179
+ detail.stages[stage] = { coverageAccuracyAuc: current.auc, logLoss: current.logLoss, ece: current.ece, baselineAvailable: false };
180
+ continue;
181
+ }
182
+ const deltas = metricDeltas(current, prior);
183
+ if (!noWorse(deltas)) oldHoldoutRegression = true;
184
+ detail.stages[stage] = { coverageAccuracyAuc: current.auc, logLoss: current.logLoss, ece: current.ece, deltas, baselineAvailable: true };
185
+ }
186
+ if (oldHoldoutRegression) detail.status = 'regression';
187
+ else if (baselineMissing || Object.keys(holdout).length === 0) detail.status = 'baseline-unavailable';
188
+ return { oldHoldoutRegression, detail };
189
+ }
190
+
191
+ function readHistory(file) {
192
+ if (!fs.existsSync(file)) return [];
193
+ let lines;
194
+ try { lines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(line => line.trim()); } catch (_) { fail(); }
195
+ try {
196
+ const history = lines.map(line => JSON.parse(line));
197
+ if (history.some(item => !isObject(item) || item.schemaVersion !== 1 || !isText(item.version) || !isObject(item.stages))) fail();
198
+ return history;
199
+ } catch (_) { fail(); }
200
+ }
201
+
202
+ function worseningCycles(history, stages) {
203
+ if (history.length < 3) return null;
204
+ // 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.
205
+ const [older, previous, active] = history.slice(-3);
206
+ for (const stage of Object.keys(stages)) {
207
+ const a = older.stages?.[stage]; const b = previous.stages?.[stage]; const c = active.stages?.[stage];
208
+ if (!a?.coverageCurve || !b?.coverageCurve || !c?.coverageCurve) continue;
209
+ const first = metricDeltas(comparisonMetrics(b), comparisonMetrics(a));
210
+ const second = metricDeltas(comparisonMetrics(c), comparisonMetrics(b));
211
+ if (!noBetter(first) || !strictlyWorse(first) || !noBetter(second) || !strictlyWorse(second)) continue;
212
+ return { stage, first, second, versions: [older.version, previous.version, active.version] };
213
+ }
214
+ return null;
215
+ }
216
+
217
+ function decideTrend(candidate, history, floor) {
218
+ const reasons = [];
219
+ const previous = history.at(-1);
220
+ let candidateNoWorse = !!previous;
221
+ if (!previous) {
222
+ candidateNoWorse = false;
223
+ reasons.push('no previous version is available for curve comparison');
224
+ } else {
225
+ for (const [stage, metrics] of Object.entries(candidate.stages)) {
226
+ const priorMetrics = previous.stages?.[stage];
227
+ if (!priorMetrics?.coverageCurve) {
228
+ candidateNoWorse = false;
229
+ reasons.push(`${stage} curves cannot be compared with ${previous.version}`);
230
+ continue;
231
+ }
232
+ const deltas = metricDeltas(comparisonMetrics(metrics), comparisonMetrics(priorMetrics));
233
+ 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}`);
234
+ if (!noWorse(deltas)) candidateNoWorse = false;
235
+ }
236
+ }
237
+ const floorAllowsPromotion = floor.detail.status === 'checked' && !floor.oldHoldoutRegression;
238
+ for (const [stage, metrics] of Object.entries(floor.detail.stages)) {
239
+ if (!metrics.deltas) continue;
240
+ const detail = Object.entries(metrics.deltas).map(([name, value]) => `${name === 'auc' ? 'coverage-accuracy AUC' : name === 'logLoss' ? 'log-loss' : 'ECE'} delta ${fmt(value)}`).join(', ');
241
+ reasons.push(`${stage} old-holdout ${noWorse(metrics.deltas) ? 'curve deltas' : 'regression'}: ${detail}`);
242
+ }
243
+ if (!floorAllowsPromotion && !floor.oldHoldoutRegression) reasons.push(`old-holdout floor ${floor.detail.status}; promotion requires a checked floor`);
244
+ if (candidateNoWorse && floorAllowsPromotion) return { compared: [...history.slice(-3).map(item => item.version), candidate.version], verdict: 'promote', reasons };
245
+
246
+ const worsening = worseningCycles(history, candidate.stages);
247
+ if (worsening) {
248
+ reasons.push(`${worsening.stage} active curve worsened across two consecutive cycles (${worsening.versions.join(' → ')}): `
249
+ + `coverage-accuracy AUC ${fmt(worsening.first.auc)}, ${fmt(worsening.second.auc)}; `
250
+ + `log-loss ${fmt(worsening.first.logLoss)}, ${fmt(worsening.second.logLoss)}; `
251
+ + `ECE ${fmt(worsening.first.ece)}, ${fmt(worsening.second.ece)}`);
252
+ return { compared: [...history.slice(-3).map(item => item.version), candidate.version], verdict: 'rollback', reasons };
253
+ }
254
+ return { compared: [...history.slice(-3).map(item => item.version), candidate.version], verdict: 'hold', reasons };
255
+ }
256
+
257
+ function stageFiles(args, option) {
258
+ const result = {};
259
+ for (const value of args[option]) {
260
+ const split = value.indexOf('=');
261
+ if (split < 1) fail();
262
+ const stage = value.slice(0, split); const file = value.slice(split + 1);
263
+ if (!STAGE_SET.has(stage) || !isText(file) || Object.hasOwn(result, stage)) fail();
264
+ result[stage] = file;
265
+ }
266
+ return result;
267
+ }
268
+
269
+ function parseArgs(argv) {
270
+ const parsed = { val: [], holdout: [] };
271
+ const names = { '--version': 'version', '--version-dir': 'versionDir', '--val-scores': 'val', '--holdout-scores': 'holdout', '--history': 'history', '--out': 'out' };
272
+ for (let i = 0; i < argv.length; i++) {
273
+ const key = names[argv[i]]; const value = argv[++i];
274
+ if (!key || value === undefined) fail();
275
+ if (key === 'val' || key === 'holdout') parsed[key].push(value);
276
+ else if (Object.hasOwn(parsed, key)) fail();
277
+ else parsed[key] = value;
278
+ }
279
+ if (!isText(parsed.version) || !isText(parsed.versionDir) || !parsed.val.length || !isText(parsed.history) || !isText(parsed.out)) fail();
280
+ return parsed;
281
+ }
282
+
283
+ function run(argv) {
284
+ const args = parseArgs(argv);
285
+ const manifest = readManifest(args.versionDir, args.version);
286
+ const valFiles = stageFiles(args, 'val');
287
+ const holdoutFiles = stageFiles(args, 'holdout');
288
+ if (Object.keys(holdoutFiles).some(stage => !Object.hasOwn(valFiles, stage))) fail();
289
+ const stages = {}; const holdoutMetrics = {};
290
+ for (const [stage, file] of Object.entries(valFiles)) {
291
+ const entry = manifest.stages[stage];
292
+ if (!entry) fail();
293
+ const valRows = readRows(file, stage, entry.options);
294
+ const referenceOnly = entry.referenceOnly ?? [];
295
+ stages[stage] = scoreRows(valRows, stage, entry.options, referenceOnly);
296
+ if (holdoutFiles[stage]) {
297
+ const holdoutRows = readRows(holdoutFiles[stage], stage, entry.options);
298
+ const valIds = new Set(valRows.map(row => row.id));
299
+ if (holdoutRows.some(row => valIds.has(row.id))) fail();
300
+ holdoutMetrics[stage] = scoreRows(holdoutRows, stage, entry.options, referenceOnly);
301
+ }
302
+ }
303
+ if (Object.keys(holdoutFiles).length && Object.keys(holdoutFiles).length !== Object.keys(valFiles).length) fail();
304
+ const history = readHistory(args.history);
305
+ const floor = assessFloor(Object.keys(holdoutMetrics).length ? holdoutMetrics : null, history);
306
+ const curves = { schemaVersion: 1, version: args.version, createdAt: new Date().toISOString(), stages, floor };
307
+ const trend = decideTrend(curves, history, floor);
308
+ fs.mkdirSync(args.out, { recursive: true });
309
+ fs.mkdirSync(path.dirname(args.history), { recursive: true });
310
+ fs.writeFileSync(path.join(args.out, 'curves.json'), `${JSON.stringify(curves, null, 2)}\n`);
311
+ fs.writeFileSync(path.join(args.out, 'trend.json'), `${JSON.stringify(trend, null, 2)}\n`);
312
+ const oldHistory = fs.existsSync(args.history) ? fs.readFileSync(args.history, 'utf8') : '';
313
+ fs.appendFileSync(args.history, `${oldHistory && !oldHistory.endsWith('\n') ? '\n' : ''}${JSON.stringify(curves)}\n`);
314
+ const summary = Object.fromEntries(Object.entries(stages).map(([stage, value]) => [stage, {
315
+ rows: readJsonl(valFiles[stage]).length,
316
+ logLoss: value.logLoss,
317
+ brier: value.brier,
318
+ ece: value.ece,
319
+ coverageAccuracyAuc: coverageAccuracyAuc(value.coverageCurve),
320
+ }]));
321
+ console.log(JSON.stringify({ rows: Object.values(summary).reduce((sum, item) => sum + item.rows, 0), stages: summary }));
322
+ return { curves, trend };
323
+ }
324
+
325
+ if (require.main === module) {
326
+ try { run(process.argv.slice(2)); } catch (_) {
327
+ console.error('system-one-curves: invalid arguments, manifest, history, or score input');
328
+ process.exitCode = 1;
329
+ }
330
+ }
331
+
332
+ module.exports = { coverageAccuracyAuc, run, scoreRows };
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+
3
+ const path = require('node:path');
4
+ const { readJsonl, writeJsonl, assertPrivateDataDir } = require('./common');
5
+ const { CATALOGS } = require('../../harness-everything/scripts/system-one/catalogs');
6
+
7
+ const TIERS = new Set(['tier1', 'tier2', 'tier3']);
8
+ const INTENTS = new Set(CATALOGS.intent.map(option => option.id));
9
+
10
+ function intentDisagrees(self, lunaIntent) {
11
+ return Array.isArray(self?.intents) && lunaIntent !== undefined && (self.intents[0] ?? null) !== lunaIntent;
12
+ }
13
+
14
+ function buildAdjudicationInput({ dataDir }) {
15
+ const privateDir = assertPrivateDataDir(dataDir);
16
+ const training = path.join(privateDir, 'training');
17
+ const prompts = readJsonl(path.join(training, 'observed', 'prompts-observed.jsonl'));
18
+ const index = (rows, file) => {
19
+ const map = new Map();
20
+ for (const row of rows) {
21
+ if (typeof row?.id !== 'string' || !row.id || map.has(row.id)) throw new Error(`${path.basename(file)} has an invalid or duplicate id`);
22
+ map.set(row.id, row);
23
+ }
24
+ return map;
25
+ };
26
+ const observedFile = path.join(training, 'observed', 'labels-observed.jsonl');
27
+ const lunaFile = path.join(training, 'relabel-luna', 'labels.jsonl');
28
+ const lunaIntentFile = path.join(training, 'relabel-luna', 'labels-intent.jsonl');
29
+ const observed = index(readJsonl(observedFile, true), observedFile);
30
+ const luna = index(readJsonl(lunaFile), lunaFile);
31
+ const lunaIntents = index(readJsonl(lunaIntentFile), lunaIntentFile);
32
+ const rows = [];
33
+ const seen = new Set();
34
+
35
+ for (const prompt of prompts) {
36
+ if (typeof prompt?.id !== 'string' || !prompt.id) throw new Error('observed prompt is missing an id');
37
+ if (seen.has(prompt.id)) throw new Error('duplicate observed prompt id');
38
+ seen.add(prompt.id);
39
+ const self = observed.get(prompt.id);
40
+ const textLabel = luna.get(prompt.id);
41
+ const intentLabel = lunaIntents.get(prompt.id);
42
+ if (!self || self.tier === undefined || !textLabel) continue;
43
+ if ((self.tier !== null && !TIERS.has(self.tier)) || (textLabel.gold !== null && !TIERS.has(textLabel.gold))) {
44
+ throw new Error('invalid tier label for adjudication input');
45
+ }
46
+ if (intentLabel && (!Object.hasOwn(intentLabel, 'gold') || (intentLabel.gold !== null && !INTENTS.has(intentLabel.gold)))) {
47
+ throw new Error('invalid intent label for adjudication input');
48
+ }
49
+ const hasSelfIntent = Array.isArray(self.intents);
50
+ const selfIntent = hasSelfIntent ? (self.intents[0] ?? null) : null;
51
+ if (selfIntent !== null && !INTENTS.has(selfIntent)) throw new Error('invalid self intent for adjudication input');
52
+ const tierDisagrees = self.tier !== textLabel.gold;
53
+ const intentsDisagree = intentLabel && intentDisagrees(self, intentLabel.gold);
54
+ if (tierDisagrees || intentsDisagree) {
55
+ if (typeof prompt.text !== 'string' || !prompt.text) throw new Error('observed prompt is missing text');
56
+ rows.push({ id: prompt.id, text: prompt.text, selfTier: self.tier, lunaTier: textLabel.gold,
57
+ ...(intentsDisagree ? { selfIntent, lunaIntent: intentLabel.gold } : {}) });
58
+ }
59
+ }
60
+
61
+ writeJsonl(path.join(training, 'adjudication', 'input.jsonl'), rows);
62
+ return { candidates: rows.length };
63
+ }
64
+
65
+ module.exports = { buildAdjudicationInput, intentDisagrees };