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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/ci.yml +23 -0
- package/CHANGELOG.md +34 -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/ci/mechanism-2am-observations-session-import.test.js +4 -1
- package/ci/mechanism-34-observations.test.js +127 -23
- package/ci/mechanism-349-ci-change-scope.test.js +260 -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 +206 -0
- package/ci/mechanism-system-one-cycle.test.js +585 -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/routing.md +2 -2
- package/docs/system-one-cycle.md +68 -0
- package/docs/system-one-observations.md +9 -8
- 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 +43 -4
- 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 +43 -4
- 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 +332 -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 +50 -0
- package/scripts/system-one-cycle/common.js +137 -0
- package/scripts/system-one-cycle/engines.js +62 -0
- package/scripts/system-one-cycle/evaluate.js +70 -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 +131 -0
- package/scripts/system-one-observations-export.js +29 -6
- package/scripts/system-one-observations-review.js +4 -5
- package/scripts/system-one-train.py +117 -61
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('node:crypto');
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { spawnSync } = require('node:child_process');
|
|
7
|
+
const { REPO, dataPath, writeJson, assertPrivateDataDir } = require('./common');
|
|
8
|
+
const { TASKS } = require('./train');
|
|
9
|
+
const { validateVersionManifest } = require('../../harness-everything/scripts/system-one/manifest');
|
|
10
|
+
|
|
11
|
+
function trainerCatalogs() {
|
|
12
|
+
const trainer = path.join(REPO, 'scripts', 'system-one-train.py');
|
|
13
|
+
const code = 'import importlib.util,json,sys; spec=importlib.util.spec_from_file_location("system_one_train",sys.argv[1]); module=importlib.util.module_from_spec(spec); spec.loader.exec_module(module); print(json.dumps({task:[o["id"] for o in module.catalog_for(task)] for task in ("validity","intent","tier")}))';
|
|
14
|
+
const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
|
|
15
|
+
const result = spawnSync(python, ['-c', code, trainer], { cwd: REPO, encoding: 'utf8', windowsHide: true });
|
|
16
|
+
if (result.error || result.status !== 0) throw new Error('trainer-catalog-unavailable');
|
|
17
|
+
let catalogs;
|
|
18
|
+
try { catalogs = JSON.parse(result.stdout); } catch { throw new Error('trainer-catalog-invalid'); }
|
|
19
|
+
if (!catalogs || Object.keys(catalogs).sort().join(',') !== [...TASKS].sort().join(',')
|
|
20
|
+
|| TASKS.some(task => !Array.isArray(catalogs[task]) || !catalogs[task].length
|
|
21
|
+
|| catalogs[task].some(id => typeof id !== 'string')
|
|
22
|
+
|| (task !== 'intent' && catalogs[task].includes('unclassified'))
|
|
23
|
+
|| new Set(catalogs[task]).size !== catalogs[task].length)) {
|
|
24
|
+
throw new Error('trainer-catalog-invalid');
|
|
25
|
+
}
|
|
26
|
+
return catalogs;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function validateVersion(version) {
|
|
30
|
+
if (typeof version !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(version)) throw new Error('invalid --version');
|
|
31
|
+
return version;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function digest(file) {
|
|
35
|
+
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function copy(source, target) {
|
|
39
|
+
fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
40
|
+
fs.copyFileSync(source, target);
|
|
41
|
+
if (process.platform !== 'win32') fs.chmodSync(target, 0o600);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function safeRelative(value) {
|
|
45
|
+
return typeof value === 'string' && value.length > 0 && !path.isAbsolute(value)
|
|
46
|
+
&& !value.split(/[\\/]/).some(part => part === '..' || part === '.');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function buildVersion({ dataDir, version, versionDir, sourceDir }) {
|
|
50
|
+
validateVersion(version);
|
|
51
|
+
const privateDir = assertPrivateDataDir(dataDir);
|
|
52
|
+
const catalogs = trainerCatalogs();
|
|
53
|
+
const target = assertPrivateDataDir(versionDir || dataPath(privateDir, 'training', 'versions', version));
|
|
54
|
+
const source = assertPrivateDataDir(sourceDir ? path.resolve(sourceDir) : dataPath(privateDir, 'training', 'runs', version));
|
|
55
|
+
const sourceManifestPath = path.join(source, 'manifest.json');
|
|
56
|
+
const hasManifest = fs.existsSync(sourceManifestPath);
|
|
57
|
+
const prior = hasManifest ? JSON.parse(fs.readFileSync(sourceManifestPath, 'utf8')) : null;
|
|
58
|
+
if (prior) validateVersionManifest(prior, version);
|
|
59
|
+
const stages = {};
|
|
60
|
+
|
|
61
|
+
for (const task of TASKS) {
|
|
62
|
+
let sourceWeights;
|
|
63
|
+
let sourceConfig;
|
|
64
|
+
let options;
|
|
65
|
+
let thresholds;
|
|
66
|
+
let priorReferenceOnly = [];
|
|
67
|
+
let targetWeights = `${task}.safetensors`;
|
|
68
|
+
let targetConfig = `${task}.json`;
|
|
69
|
+
|
|
70
|
+
if (prior) {
|
|
71
|
+
const stage = prior.stages?.[task];
|
|
72
|
+
if (!stage || !safeRelative(stage.weights) || !safeRelative(stage.config)) throw new Error(`candidate manifest is missing ${task}`);
|
|
73
|
+
options = catalogs[task];
|
|
74
|
+
const legacyOptions = task === 'intent' ? options.filter(id => id !== 'unclassified') : options;
|
|
75
|
+
if (!Array.isArray(stage.options) || (stage.options.join('\0') !== options.join('\0')
|
|
76
|
+
&& stage.options.join('\0') !== legacyOptions.join('\0'))) {
|
|
77
|
+
throw new Error(`${task} checkpoint catalog does not match the trainer catalog`);
|
|
78
|
+
}
|
|
79
|
+
sourceWeights = path.join(source, stage.weights);
|
|
80
|
+
sourceConfig = path.join(source, stage.config);
|
|
81
|
+
thresholds = { ...stage.thresholds };
|
|
82
|
+
priorReferenceOnly = stage.referenceOnly ?? [];
|
|
83
|
+
if (digest(sourceWeights) !== stage.sha256) throw new Error(`${task} checkpoint hash does not match its manifest`);
|
|
84
|
+
} else {
|
|
85
|
+
const runDir = path.join(source, task);
|
|
86
|
+
sourceWeights = path.join(runDir, 'harness-routing-v1.safetensors');
|
|
87
|
+
sourceConfig = path.join(runDir, 'harness-routing-v1.json');
|
|
88
|
+
const calibration = JSON.parse(fs.readFileSync(path.join(runDir, 'calibration.json'), 'utf8'));
|
|
89
|
+
thresholds = calibration.thresholds;
|
|
90
|
+
options = catalogs[task];
|
|
91
|
+
}
|
|
92
|
+
// Older packages omitted this non-selectable intent option; restore its metadata without retraining.
|
|
93
|
+
if (task === 'intent' && options.includes('unclassified') && thresholds && typeof thresholds === 'object'
|
|
94
|
+
&& !Array.isArray(thresholds) && !Object.hasOwn(thresholds, 'unclassified')) {
|
|
95
|
+
thresholds = { ...thresholds, unclassified: null };
|
|
96
|
+
}
|
|
97
|
+
if (!Array.isArray(options) || !options.length || new Set(options).size !== options.length
|
|
98
|
+
|| !thresholds || Object.keys(thresholds).length !== options.length
|
|
99
|
+
|| options.some(id => !Object.hasOwn(thresholds, id))
|
|
100
|
+
|| Object.values(thresholds).some(value => value !== null && (!Number.isFinite(value) || value < 0 || value > 1))
|
|
101
|
+
|| !Array.isArray(priorReferenceOnly) || priorReferenceOnly.some(id => !options.includes(id))) {
|
|
102
|
+
throw new Error(`${task} calibration has no finite per-option thresholds`);
|
|
103
|
+
}
|
|
104
|
+
// A null threshold means calibration found no cutoff reaching the precision target: the option
|
|
105
|
+
// is reference-only, pinned to 1 so it is never auto-selected while its score is still reported.
|
|
106
|
+
const referenceOnly = options.filter(id => thresholds[id] === null || priorReferenceOnly.includes(id));
|
|
107
|
+
const finalThresholds = Object.fromEntries(options.map(id => [id, thresholds[id] === null ? 1 : thresholds[id]]));
|
|
108
|
+
if (!fs.existsSync(sourceWeights) || !fs.existsSync(sourceConfig)) throw new Error(`${task} checkpoint artifacts are missing`);
|
|
109
|
+
const targetWeightsPath = path.join(target, targetWeights);
|
|
110
|
+
const targetConfigPath = path.join(target, targetConfig);
|
|
111
|
+
if (path.resolve(sourceWeights) !== targetWeightsPath) copy(sourceWeights, targetWeightsPath);
|
|
112
|
+
if (path.resolve(sourceConfig) !== targetConfigPath) copy(sourceConfig, targetConfigPath);
|
|
113
|
+
stages[task] = { weights: targetWeights, config: targetConfig, sha256: digest(targetWeightsPath),
|
|
114
|
+
options: [...options], thresholds: finalThresholds, ...(referenceOnly.length ? { referenceOnly } : {}) };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const sourceEvaluation = path.join(source, 'evaluation');
|
|
118
|
+
const targetEvaluation = path.join(target, 'evaluation');
|
|
119
|
+
let evaluation = null;
|
|
120
|
+
if (fs.existsSync(path.join(sourceEvaluation, 'curves.json'))) {
|
|
121
|
+
fs.mkdirSync(targetEvaluation, { recursive: true, mode: 0o700 });
|
|
122
|
+
for (const file of ['curves.json', 'trend.json']) {
|
|
123
|
+
const from = path.join(sourceEvaluation, file);
|
|
124
|
+
if (fs.existsSync(from) && path.resolve(from) !== path.join(targetEvaluation, file)) copy(from, path.join(targetEvaluation, file));
|
|
125
|
+
}
|
|
126
|
+
evaluation = 'evaluation/curves.json';
|
|
127
|
+
} else if (prior?.evaluation !== null && prior?.evaluation !== undefined) {
|
|
128
|
+
if (!safeRelative(prior.evaluation) || !fs.existsSync(path.join(source, prior.evaluation))) throw new Error('candidate evaluation artifact is missing');
|
|
129
|
+
const relative = prior.evaluation.split(/[\\/]/).join(path.sep);
|
|
130
|
+
const from = path.join(source, relative);
|
|
131
|
+
const to = path.join(target, relative);
|
|
132
|
+
if (path.resolve(from) !== to) copy(from, to);
|
|
133
|
+
evaluation = relative.split(path.sep).join('/');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const manifest = { schemaVersion: 1, version, createdAt: prior?.createdAt || new Date().toISOString(), stages, evaluation };
|
|
137
|
+
validateVersionManifest(manifest, version);
|
|
138
|
+
writeJson(path.join(target, 'manifest.json'), manifest);
|
|
139
|
+
return { version, versionDir: target, evaluation };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function publishVersion({ dataDir, version }) {
|
|
143
|
+
validateVersion(version);
|
|
144
|
+
const privateDir = assertPrivateDataDir(dataDir);
|
|
145
|
+
const source = dataPath(privateDir, 'training', 'versions', version);
|
|
146
|
+
const target = dataPath(privateDir, 'models', 'cua-s1', version);
|
|
147
|
+
const sourceStat = fs.lstatSync(source);
|
|
148
|
+
const manifestFile = path.join(source, 'manifest.json');
|
|
149
|
+
const manifestStat = fs.lstatSync(manifestFile);
|
|
150
|
+
if (!sourceStat.isDirectory() || sourceStat.isSymbolicLink() || !manifestStat.isFile() || manifestStat.isSymbolicLink()) {
|
|
151
|
+
throw new Error('invalid-package: version directory must contain a regular manifest');
|
|
152
|
+
}
|
|
153
|
+
validateVersionManifest(JSON.parse(fs.readFileSync(manifestFile, 'utf8')), version);
|
|
154
|
+
for (const parent of [path.join(privateDir, 'models'), path.join(privateDir, 'models', 'cua-s1')]) {
|
|
155
|
+
try {
|
|
156
|
+
const stat = fs.lstatSync(parent);
|
|
157
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('invalid-publish-dir');
|
|
158
|
+
} catch (error) {
|
|
159
|
+
if (error.code !== 'ENOENT') throw error;
|
|
160
|
+
fs.mkdirSync(parent, { mode: 0o700 });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
try { fs.lstatSync(target); throw new Error('publish-target-exists'); }
|
|
164
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
165
|
+
try { fs.cpSync(source, target, { recursive: true, errorOnExist: true, force: false }); }
|
|
166
|
+
catch (error) {
|
|
167
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
return { version, publishedPath: target };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = { buildVersion, publishVersion, trainerCatalogs, validateVersion, digest, safeRelative };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Write per-option sigmoid scores for a fixed System One holdout.
|
|
3
|
+
|
|
4
|
+
Options come from the same catalog the trainer built for the task (scripts/system-one-train.py) and are
|
|
5
|
+
ordered by the version manifest, so the score keys match what the stage was trained on. The fixture
|
|
6
|
+
supplies only request.context and the gold label. A holdout case whose gold is not a catalog id (for
|
|
7
|
+
example a tier case with no tier) is skipped and counted in the printed `skipped` field.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import importlib.util
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
sys.dont_write_bytecode = True
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def validate_manifest(manifest):
|
|
23
|
+
node = os.environ.get('HARNESS_SYSTEM_ONE_NODE') or shutil.which('node')
|
|
24
|
+
validator = Path(__file__).resolve().parents[2] / 'harness-everything' / 'scripts' / 'system-one' / 'manifest.js'
|
|
25
|
+
if not node:
|
|
26
|
+
raise ValueError('version manifest is invalid')
|
|
27
|
+
try:
|
|
28
|
+
result = subprocess.run([node, str(validator)], input=json.dumps(manifest), text=True,
|
|
29
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5,
|
|
30
|
+
shell=False, check=False)
|
|
31
|
+
except (OSError, subprocess.SubprocessError):
|
|
32
|
+
raise ValueError('version manifest is invalid') from None
|
|
33
|
+
if result.returncode != 0:
|
|
34
|
+
raise ValueError('version manifest is invalid')
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def trained_catalog(weights, task, holdout):
|
|
38
|
+
"""Option id/text pairs the stage was trained on, in the version manifest's option order."""
|
|
39
|
+
trainer_path = Path(__file__).resolve().parents[2] / 'scripts' / 'system-one-train.py'
|
|
40
|
+
spec = importlib.util.spec_from_file_location('system_one_train', trainer_path)
|
|
41
|
+
trainer = importlib.util.module_from_spec(spec)
|
|
42
|
+
spec.loader.exec_module(trainer)
|
|
43
|
+
catalog = trainer.catalog_for(task, holdout)
|
|
44
|
+
catalog_ids = [option['id'] for option in catalog]
|
|
45
|
+
texts = {option['id']: option['text'] for option in catalog}
|
|
46
|
+
manifest = json.loads((Path(weights).parent / 'manifest.json').read_text(encoding='utf-8'))
|
|
47
|
+
validate_manifest(manifest)
|
|
48
|
+
ids = manifest['stages'][task]['options']
|
|
49
|
+
if ids != catalog_ids:
|
|
50
|
+
raise ValueError(f'{task} manifest options do not match the trainer catalog')
|
|
51
|
+
return [{'id': option_id, 'text': texts[option_id]} for option_id in ids]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def eligible(case, task, ids):
|
|
55
|
+
"""A case is scored when its gold label is a catalog id; validity always scores."""
|
|
56
|
+
if task == 'validity':
|
|
57
|
+
return True
|
|
58
|
+
gold = case.get('gold')
|
|
59
|
+
labels = gold if isinstance(gold, list) else [gold]
|
|
60
|
+
return bool(labels) and all(label in ids for label in labels)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def main():
|
|
64
|
+
parser = argparse.ArgumentParser()
|
|
65
|
+
parser.add_argument('--weights', required=True)
|
|
66
|
+
parser.add_argument('--holdout', required=True)
|
|
67
|
+
parser.add_argument('--task', choices=['validity', 'intent', 'tier'], required=True)
|
|
68
|
+
parser.add_argument('--out', required=True)
|
|
69
|
+
args = parser.parse_args()
|
|
70
|
+
|
|
71
|
+
import torch
|
|
72
|
+
from cua_s1.model import ChoiceExample, load_checkpoint
|
|
73
|
+
|
|
74
|
+
torch.set_num_threads(1)
|
|
75
|
+
torch.use_deterministic_algorithms(True)
|
|
76
|
+
model, collator, _ = load_checkpoint(args.weights, 'cpu')
|
|
77
|
+
model.eval()
|
|
78
|
+
catalog = trained_catalog(args.weights, args.task, args.holdout)
|
|
79
|
+
ids = {option['id'] for option in catalog}
|
|
80
|
+
options = tuple(option['text'] for option in catalog)
|
|
81
|
+
|
|
82
|
+
corpus = json.loads(Path(args.holdout).read_text(encoding='utf-8'))
|
|
83
|
+
cases = [case for case in corpus.get('cases', []) if case.get('split') == 'holdout']
|
|
84
|
+
if not cases:
|
|
85
|
+
raise ValueError('holdout has no holdout cases')
|
|
86
|
+
scored = [case for case in cases if eligible(case, args.task, ids)]
|
|
87
|
+
skipped = len(cases) - len(scored)
|
|
88
|
+
rows = []
|
|
89
|
+
with torch.inference_mode():
|
|
90
|
+
for start in range(0, len(scored), 32):
|
|
91
|
+
batch = scored[start:start + 32]
|
|
92
|
+
examples = []
|
|
93
|
+
for case in batch:
|
|
94
|
+
request = case.get('request', {})
|
|
95
|
+
if not isinstance(request.get('context'), str):
|
|
96
|
+
raise ValueError('holdout case has no request.context')
|
|
97
|
+
examples.append(ChoiceExample(context=request['context'], options=options, label=0))
|
|
98
|
+
scores = model(collator(examples)).sigmoid().tolist()
|
|
99
|
+
for case, values in zip(batch, scores, strict=True):
|
|
100
|
+
gold = ('invalid' if case['gold'] is None else 'actionable') if args.task == 'validity' else case['gold']
|
|
101
|
+
rows.append({'id': case['id'], 'gold': gold, 'scores': {option['id']: value for option, value in zip(catalog, values, strict=True)}})
|
|
102
|
+
|
|
103
|
+
output = Path(args.out)
|
|
104
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
output.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in rows), encoding='utf-8')
|
|
106
|
+
if os.name != 'nt': output.chmod(0o600)
|
|
107
|
+
print(json.dumps({'task': args.task, 'rows': len(rows), 'skipped': skipped}))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == '__main__':
|
|
111
|
+
main()
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { spawn, spawnSync } = require('node:child_process');
|
|
6
|
+
const { REPO, dataPath, writeJson, runNode, assertPrivateDataDir } = require('./common');
|
|
7
|
+
|
|
8
|
+
const TASKS = ['validity', 'intent', 'tier'];
|
|
9
|
+
|
|
10
|
+
function processTreeRssMb(rootPid) {
|
|
11
|
+
if (process.platform === 'win32') {
|
|
12
|
+
const script = `$all=Get-CimInstance Win32_Process; $ids=New-Object 'System.Collections.Generic.HashSet[int]'; [void]$ids.Add(${Number(rootPid)}); do { $changed=$false; foreach($p in $all) { if($ids.Contains([int]$p.ParentProcessId) -and $ids.Add([int]$p.ProcessId)) { $changed=$true } } } while($changed); $total=($all | Where-Object { $ids.Contains([int]$_.ProcessId) } | Measure-Object WorkingSetSize -Sum).Sum; if($null -eq $total) { $total=0 }; [Console]::WriteLine($total)`;
|
|
13
|
+
const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true });
|
|
14
|
+
if (result.status !== 0) throw new Error('rss-sample-failed');
|
|
15
|
+
const bytes = Number(result.stdout.trim());
|
|
16
|
+
if (!Number.isFinite(bytes)) throw new Error('rss-sample-failed');
|
|
17
|
+
return bytes / (1024 * 1024);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const result = spawnSync('ps', ['-axo', 'pid=,ppid=,rss='], { encoding: 'utf8' });
|
|
21
|
+
if (result.status !== 0) throw new Error('rss-sample-failed');
|
|
22
|
+
const rows = result.stdout.split(/\r?\n/).map(line => line.trim().split(/\s+/).map(Number))
|
|
23
|
+
.filter(row => row.length === 3 && row.every(Number.isFinite));
|
|
24
|
+
const children = new Map();
|
|
25
|
+
const rssByPid = new Map();
|
|
26
|
+
for (const [pid, ppid, rssKb] of rows) {
|
|
27
|
+
rssByPid.set(pid, rssKb);
|
|
28
|
+
if (!children.has(ppid)) children.set(ppid, []);
|
|
29
|
+
children.get(ppid).push([pid, rssKb]);
|
|
30
|
+
}
|
|
31
|
+
const pending = [Number(rootPid)];
|
|
32
|
+
const found = new Set();
|
|
33
|
+
let totalKb = 0;
|
|
34
|
+
while (pending.length) {
|
|
35
|
+
const pid = pending.pop();
|
|
36
|
+
if (found.has(pid)) continue;
|
|
37
|
+
found.add(pid);
|
|
38
|
+
totalKb += rssByPid.get(pid) || 0;
|
|
39
|
+
for (const [childPid, rssKb] of children.get(pid) || []) {
|
|
40
|
+
pending.push(childPid);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return totalKb / 1024;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function killTree(child) {
|
|
47
|
+
if (!child.pid) return;
|
|
48
|
+
if (process.platform === 'win32') {
|
|
49
|
+
const result = spawnSync('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
|
|
50
|
+
if (result.status !== 0) { try { child.kill(); } catch { /* already exited */ } }
|
|
51
|
+
} else {
|
|
52
|
+
try { process.kill(-child.pid, 'SIGKILL'); }
|
|
53
|
+
catch { try { child.kill('SIGKILL'); } catch { /* already exited */ } }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function runGuarded(command, args, { maxRssMb = 6144, threads = 4, pollMs = 500, rssReader = processTreeRssMb } = {}) {
|
|
58
|
+
if (!Number.isFinite(maxRssMb) || maxRssMb <= 0 || !Number.isInteger(threads) || threads < 1) {
|
|
59
|
+
throw new Error('invalid resource guard limits');
|
|
60
|
+
}
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: process.platform !== 'win32', windowsHide: true });
|
|
63
|
+
let peakRssMb = 0;
|
|
64
|
+
let killedForLimit = false;
|
|
65
|
+
let monitorFailed = false;
|
|
66
|
+
let sampling = false;
|
|
67
|
+
let timer;
|
|
68
|
+
const sample = () => {
|
|
69
|
+
if (sampling || !child.pid || child.exitCode !== null || child.signalCode !== null) return;
|
|
70
|
+
sampling = true;
|
|
71
|
+
try {
|
|
72
|
+
const rss = rssReader(child.pid);
|
|
73
|
+
if (!Number.isFinite(rss) || rss < 0) throw new Error('invalid-rss-sample');
|
|
74
|
+
peakRssMb = Math.max(peakRssMb, rss);
|
|
75
|
+
if (rss > maxRssMb && !killedForLimit) {
|
|
76
|
+
killedForLimit = true;
|
|
77
|
+
killTree(child);
|
|
78
|
+
}
|
|
79
|
+
} catch {
|
|
80
|
+
monitorFailed = true;
|
|
81
|
+
killTree(child);
|
|
82
|
+
} finally { sampling = false; }
|
|
83
|
+
};
|
|
84
|
+
child.once('error', () => { clearInterval(timer); reject(new Error('training process could not start')); });
|
|
85
|
+
child.once('close', (exitCode, signal) => {
|
|
86
|
+
clearInterval(timer);
|
|
87
|
+
resolve({ exitCode, signal, peakRssMb: Number(peakRssMb.toFixed(1)), maxRssMb, threads, killedForLimit, monitorFailed });
|
|
88
|
+
});
|
|
89
|
+
sample();
|
|
90
|
+
timer = setInterval(sample, pollMs);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function pythonExecutable() {
|
|
95
|
+
return process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function trainCycle({ dataDir, version, threads = 4, maxRssMb = 6144, run = runGuarded }) {
|
|
99
|
+
const privateDir = assertPrivateDataDir(dataDir);
|
|
100
|
+
const trainer = path.join(REPO, 'scripts', 'system-one-train.py');
|
|
101
|
+
const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
|
|
102
|
+
const outputs = [];
|
|
103
|
+
let trained = 0;
|
|
104
|
+
let skipped = 0;
|
|
105
|
+
|
|
106
|
+
for (const task of TASKS) {
|
|
107
|
+
const source = dataPath(privateDir, 'training', task === 'validity' ? 'v1-validity' : 'v1');
|
|
108
|
+
const out = dataPath(privateDir, 'training', 'runs', version, task);
|
|
109
|
+
fs.mkdirSync(out, { recursive: true, mode: 0o700 });
|
|
110
|
+
const requiredFiles = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json', 'calibration.json', 'resource-guard.json'];
|
|
111
|
+
const guardFile = path.join(out, 'resource-guard.json');
|
|
112
|
+
if (requiredFiles.every(file => fs.existsSync(path.join(out, file)))) {
|
|
113
|
+
const priorGuard = JSON.parse(fs.readFileSync(guardFile, 'utf8'));
|
|
114
|
+
if (priorGuard.exitCode === 0 && !priorGuard.killedForLimit && !priorGuard.monitorFailed) {
|
|
115
|
+
skipped++;
|
|
116
|
+
outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const result = await run(pythonExecutable(), [trainer, '--data-dir', source, '--out', out, '--task', task, '--threads', String(threads)], {
|
|
121
|
+
threads, maxRssMb,
|
|
122
|
+
});
|
|
123
|
+
const guard = { schemaVersion: 1, ...result, createdAt: new Date().toISOString() };
|
|
124
|
+
writeJson(path.join(out, 'resource-guard.json'), guard);
|
|
125
|
+
if (result.killedForLimit) throw new Error(`training ${task} exceeded the ${maxRssMb} MB RSS limit`);
|
|
126
|
+
if (result.monitorFailed) throw new Error(`training ${task} RSS monitoring failed`);
|
|
127
|
+
if (result.exitCode !== 0) throw new Error(`training ${task} failed`);
|
|
128
|
+
runNode(calibrator, [path.join(out, 'val-scores.jsonl'), path.join(out, 'calibration.json'), '--task', task,
|
|
129
|
+
'--catalog', path.join(out, 'train-report.json')]);
|
|
130
|
+
trained++;
|
|
131
|
+
outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
|
|
132
|
+
}
|
|
133
|
+
return { trained, skipped, threads, maxRssMb, outputs };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
module.exports = { runGuarded, processTreeRssMb, trainCycle, TASKS };
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const {
|
|
6
|
+
STEPS, parseFlags, flag, required, markStep, stepComplete, resultSummary,
|
|
7
|
+
} = require('./system-one-cycle/common');
|
|
8
|
+
const { collect } = require('./system-one-cycle/collect');
|
|
9
|
+
const { labelData } = require('./system-one-cycle/label');
|
|
10
|
+
const { judgeRows } = require('./system-one-cycle/judge');
|
|
11
|
+
const { buildDataset } = require('./system-one-cycle/build');
|
|
12
|
+
const { trainCycle } = require('./system-one-cycle/train');
|
|
13
|
+
const { evaluateCycle } = require('./system-one-cycle/evaluate');
|
|
14
|
+
const { buildVersion, publishVersion, validateVersion } = require('./system-one-cycle/package');
|
|
15
|
+
|
|
16
|
+
const USAGE = `Usage:
|
|
17
|
+
node scripts/system-one-cycle.js <collect|label|judge|build|train|evaluate|package|publish> --data-dir <private cycle directory> [options]
|
|
18
|
+
node scripts/system-one-cycle.js all --until <step> --data-dir <private cycle directory> [options]
|
|
19
|
+
|
|
20
|
+
Steps: ${STEPS.join(', ')}
|
|
21
|
+
Options: --since YYYY-MM-DD --sessions <Codex sessions dir> --version <id> --threads 4 --max-rss-mb 6144 --holdout <file> (repeatable)`;
|
|
22
|
+
|
|
23
|
+
function values(flags, name) {
|
|
24
|
+
const value = flags[name];
|
|
25
|
+
return value === undefined ? [] : Array.isArray(value) ? value : [value];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function integerFlag(flags, name, fallback) {
|
|
29
|
+
const value = Number(flag(flags, name, fallback));
|
|
30
|
+
if (!Number.isInteger(value) || value < 1) throw new Error(`--${name} must be a positive integer`);
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function numberFlag(flags, name, fallback) {
|
|
35
|
+
const value = Number(flag(flags, name, fallback));
|
|
36
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error(`--${name} must be positive`);
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function outputsFor(step, dataDir, version, versionDir, result) {
|
|
41
|
+
switch (step) {
|
|
42
|
+
case 'collect': return ['training/observed/prompts-observed.jsonl', 'training/observed/labels-observed.jsonl'];
|
|
43
|
+
case 'label': return ['training/relabel-luna/labels.jsonl', 'training/relabel-luna/labels-intent.jsonl'];
|
|
44
|
+
case 'judge': return ['training/adjudication/input.jsonl', 'training/adjudication/consensus.jsonl'];
|
|
45
|
+
case 'build': return ['training/v1/prompts.jsonl', 'training/v1/labels.jsonl', 'training/v1/labels-intent.jsonl',
|
|
46
|
+
'training/v1-validity/prompts.jsonl', 'training/v1-validity/labels.jsonl'];
|
|
47
|
+
case 'train': return result.outputs;
|
|
48
|
+
case 'evaluate': return [`training/candidates/${version}/evaluation/curves.json`, `training/candidates/${version}/evaluation/trend.json`];
|
|
49
|
+
case 'package': {
|
|
50
|
+
const target = versionDir || path.join(dataDir, 'training', 'versions', version);
|
|
51
|
+
const relative = path.relative(dataDir, target);
|
|
52
|
+
return path.isAbsolute(relative) || relative.startsWith('..') ? [] : [path.join(relative, 'manifest.json')];
|
|
53
|
+
}
|
|
54
|
+
case 'publish': return [path.join('models', 'cua-s1', version, 'manifest.json')];
|
|
55
|
+
default: return [];
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function runStep(step, flags, dataDir) {
|
|
60
|
+
if (!STEPS.includes(step)) throw new Error(`unknown cycle step: ${step}`);
|
|
61
|
+
if (['collect', 'label', 'judge'].includes(step) && stepComplete(dataDir, step)) return resultSummary(step, { skipped: true });
|
|
62
|
+
|
|
63
|
+
let result;
|
|
64
|
+
let version;
|
|
65
|
+
let versionDir;
|
|
66
|
+
switch (step) {
|
|
67
|
+
case 'collect':
|
|
68
|
+
result = collect({ dataDir, since: flag(flags, 'since'), sessionsDir: flag(flags, 'sessions') });
|
|
69
|
+
break;
|
|
70
|
+
case 'label':
|
|
71
|
+
result = await labelData({ dataDir, batchSize: integerFlag(flags, 'batch', 20), concurrency: integerFlag(flags, 'concurrency', 4) });
|
|
72
|
+
break;
|
|
73
|
+
case 'judge':
|
|
74
|
+
result = await judgeRows({ dataDir, batchSize: integerFlag(flags, 'batch', 20) });
|
|
75
|
+
break;
|
|
76
|
+
case 'build':
|
|
77
|
+
result = buildDataset({ dataDir, holdoutFiles: values(flags, 'holdout').length ? values(flags, 'holdout') : undefined });
|
|
78
|
+
break;
|
|
79
|
+
case 'train':
|
|
80
|
+
version = validateVersion(required(flags, 'version'));
|
|
81
|
+
result = await trainCycle({ dataDir, version, threads: integerFlag(flags, 'threads', 4), maxRssMb: numberFlag(flags, 'max-rss-mb', 6144) });
|
|
82
|
+
break;
|
|
83
|
+
case 'evaluate':
|
|
84
|
+
version = validateVersion(required(flags, 'version'));
|
|
85
|
+
result = evaluateCycle({ dataDir, version });
|
|
86
|
+
break;
|
|
87
|
+
case 'package':
|
|
88
|
+
version = validateVersion(required(flags, 'version'));
|
|
89
|
+
versionDir = flag(flags, 'version-dir');
|
|
90
|
+
result = buildVersion({ dataDir, version, versionDir, sourceDir: path.join(dataDir, 'training', 'candidates', version) });
|
|
91
|
+
result = { version, evaluation: result.evaluation };
|
|
92
|
+
break;
|
|
93
|
+
case 'publish':
|
|
94
|
+
version = validateVersion(required(flags, 'version'));
|
|
95
|
+
result = publishVersion({ dataDir, version });
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
const completed = step === 'label'
|
|
99
|
+
? Object.values(result).every(stage => stage.failed === 0)
|
|
100
|
+
: step === 'judge' ? result.failed === 0 : true;
|
|
101
|
+
if (completed) markStep(dataDir, step, outputsFor(step, dataDir, version, versionDir, result));
|
|
102
|
+
return resultSummary(step, { ...result, completed });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function main(argv) {
|
|
106
|
+
const [command, ...rawFlags] = argv;
|
|
107
|
+
if (command === '--help' || command === 'help' || !command) { process.stdout.write(`${USAGE}\n`); return; }
|
|
108
|
+
const flags = parseFlags(rawFlags);
|
|
109
|
+
if (flag(flags, 'help') === true) { process.stdout.write(`${USAGE}\n`); return; }
|
|
110
|
+
const dataDir = path.resolve(required(flags, 'data-dir'));
|
|
111
|
+
let results;
|
|
112
|
+
if (command === 'all') {
|
|
113
|
+
const until = required(flags, 'until');
|
|
114
|
+
const end = STEPS.indexOf(until);
|
|
115
|
+
if (end < 0) throw new Error('--until must name a cycle step');
|
|
116
|
+
results = [];
|
|
117
|
+
for (const step of STEPS.slice(0, end + 1)) {
|
|
118
|
+
const result = await runStep(step, flags, dataDir);
|
|
119
|
+
results.push(result);
|
|
120
|
+
if (result.completed === false) break;
|
|
121
|
+
}
|
|
122
|
+
} else {
|
|
123
|
+
results = [await runStep(command, flags, dataDir)];
|
|
124
|
+
}
|
|
125
|
+
process.stdout.write(`${JSON.stringify({ steps: results })}\n`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
main(process.argv.slice(2)).catch(error => {
|
|
129
|
+
process.stderr.write(`system-one-cycle: ${error.message}\n`);
|
|
130
|
+
process.exitCode = 1;
|
|
131
|
+
});
|
|
@@ -30,8 +30,7 @@ function family(text) {
|
|
|
30
30
|
function validDecision(d) {
|
|
31
31
|
return d && typeof d.id === 'string'
|
|
32
32
|
&& [undefined, null, 'actionable', 'invalid', 'unsure'].includes(d.validity)
|
|
33
|
-
&& [undefined, null, ...obs.TIERS].includes(d.tier)
|
|
34
|
-
&& [undefined, null, true, false].includes(d.contextDependent);
|
|
33
|
+
&& [undefined, null, ...obs.TIERS].includes(d.tier);
|
|
35
34
|
}
|
|
36
35
|
|
|
37
36
|
function loadReview(file) {
|
|
@@ -47,15 +46,13 @@ function derive(record, owner) {
|
|
|
47
46
|
const self = record.selfReport;
|
|
48
47
|
const behavior = record.captureMethod === 'session-backfill' ? null : record.behavior;
|
|
49
48
|
let validity = self ? self.validity : null;
|
|
50
|
-
let contextDependent = self ? self.contextDependent : null;
|
|
51
49
|
if (owner && owner.validity && owner.validity !== 'unsure') validity = owner.validity;
|
|
52
|
-
if (owner && typeof owner.contextDependent === 'boolean') contextDependent = owner.contextDependent;
|
|
53
50
|
let { tier, source: tierSource } = obs.labelTier(self, owner);
|
|
54
51
|
if (validity === 'invalid' && !(owner && obs.TIERS.includes(owner.tier))) { tier = null; tierSource = tierSource && 'self-report'; }
|
|
55
52
|
const skills = record.behavior && record.behavior.skills && record.behavior.skills.length
|
|
56
53
|
? record.behavior.skills : (self ? self.skills : []);
|
|
57
54
|
return {
|
|
58
|
-
id: record.id, validity,
|
|
55
|
+
id: record.id, validity, tier, tierSource,
|
|
59
56
|
intents: self ? self.intents : [], workflow: (self && self.workflow) || (record.router && record.router.strategy) || null,
|
|
60
57
|
skills,
|
|
61
58
|
behaviorEvidence: behavior ? 'observed' : 'unobserved',
|
|
@@ -68,6 +65,11 @@ function rate(pairs) {
|
|
|
68
65
|
return pairs.length ? pairs.filter(([a, b]) => a === b).length / pairs.length : null;
|
|
69
66
|
}
|
|
70
67
|
|
|
68
|
+
function exportSystemOne(record) {
|
|
69
|
+
const systemOne = obs.normalizeSystemOne(record && record.router && record.router.systemOne);
|
|
70
|
+
return systemOne ? { version: systemOne.version, sha256: systemOne.sha256, mode: systemOne.mode, decision: systemOne.decision } : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
71
73
|
function run(args) {
|
|
72
74
|
const store = path.resolve(option(args, '--store', obs.storeRoot()));
|
|
73
75
|
const out = option(args, '--out');
|
|
@@ -102,7 +104,9 @@ function run(args) {
|
|
|
102
104
|
const prompts = rows.map((r, i) => JSON.stringify({ id: r.record.id, family: family(r.text.prompt), source: 'observation',
|
|
103
105
|
split: i >= rows.length - validation ? 'validation' : 'train', text: r.text.prompt, previous: r.text.previous || '' }));
|
|
104
106
|
fs.writeFileSync(path.join(out, 'prompts-observed.jsonl'), prompts.join('\n') + (prompts.length ? '\n' : ''));
|
|
105
|
-
fs.writeFileSync(path.join(out, 'labels-observed.jsonl'), rows.map(r => JSON.stringify(
|
|
107
|
+
fs.writeFileSync(path.join(out, 'labels-observed.jsonl'), rows.map(r => JSON.stringify({
|
|
108
|
+
...r.label, systemOne: exportSystemOne(r.record),
|
|
109
|
+
})).join('\n') + (rows.length ? '\n' : ''));
|
|
106
110
|
const withSelf = rows.filter(r => r.record.selfReport);
|
|
107
111
|
// Only turns where the router chose a tier; 'unclassified' is not one.
|
|
108
112
|
const routerSelf = withSelf.filter(r => r.record.router && obs.TIERS.includes(r.record.router.tier)).map(r => [r.record.router.tier, r.record.selfReport.tier]);
|
|
@@ -110,6 +114,24 @@ function run(args) {
|
|
|
110
114
|
const contradictions = {};
|
|
111
115
|
for (const r of rows) for (const c of r.label.contradictions) contradictions[c] = (contradictions[c] || 0) + 1;
|
|
112
116
|
const count = key => rows.reduce((acc, r) => { const k = String(key(r)); acc[k] = (acc[k] || 0) + 1; return acc; }, {});
|
|
117
|
+
const systemOneVersions = new Map();
|
|
118
|
+
for (const r of rows) {
|
|
119
|
+
const systemOne = obs.normalizeSystemOne(r.record.router && r.record.router.systemOne);
|
|
120
|
+
if (!systemOne) continue;
|
|
121
|
+
const version = systemOneVersions.get(systemOne.version) || { rows: 0, matches: 0, comparisons: 0 };
|
|
122
|
+
version.rows++;
|
|
123
|
+
const selfTier = r.record.selfReport && r.record.selfReport.tier;
|
|
124
|
+
if (obs.TIERS.includes(systemOne.decision.tier) && obs.TIERS.includes(selfTier)) {
|
|
125
|
+
version.comparisons++;
|
|
126
|
+
if (systemOne.decision.tier === selfTier) version.matches++;
|
|
127
|
+
}
|
|
128
|
+
systemOneVersions.set(systemOne.version, version);
|
|
129
|
+
}
|
|
130
|
+
const systemOneReport = Object.fromEntries([...systemOneVersions].map(([version, counts]) => [version, {
|
|
131
|
+
rows: counts.rows,
|
|
132
|
+
tierAgreement: { matches: counts.matches, comparisons: counts.comparisons,
|
|
133
|
+
rate: counts.comparisons ? counts.matches / counts.comparisons : null },
|
|
134
|
+
}]));
|
|
113
135
|
const report = {
|
|
114
136
|
schemaVersion: 1, exportedAt: new Date().toISOString(), records: index.records.length, exported: rows.length,
|
|
115
137
|
since: sinceText, selfReportOnly, skippedBeforeSince, skippedUnlabeled,
|
|
@@ -122,6 +144,7 @@ function run(args) {
|
|
|
122
144
|
},
|
|
123
145
|
contradictionEvidence: 'observed-behavior-only',
|
|
124
146
|
ownerDecisions: Object.keys(owner).length, agreement, contradictions,
|
|
147
|
+
systemOne: { versions: systemOneReport },
|
|
125
148
|
};
|
|
126
149
|
fs.writeFileSync(path.join(out, 'export-report.json'), JSON.stringify(report, null, 2) + '\n');
|
|
127
150
|
return report;
|