harness-everything 1.4.0 → 1.5.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/release.yml +16 -5
- package/CHANGELOG.md +25 -0
- package/ci/fixtures/system-one-colab-fit-layer-sitecustomize.py +72 -0
- package/ci/mechanism-2x-release-automation.test.js +17 -0
- package/ci/mechanism-system-one-colab.test.js +83 -5
- package/ci/mechanism-system-one-contract.test.js +30 -0
- package/ci/mechanism-system-one-curves.test.js +85 -0
- package/ci/mechanism-system-one-cycle.test.js +344 -34
- package/ci/mechanism-system-one-install.test.js +47 -0
- package/ci/mechanism-system-one-provider.test.js +2 -0
- package/ci/mechanism-system-one-resident.test.js +69 -0
- package/ci/system-one-adapter-test.py +86 -0
- package/ci/system-one-fit-layer-test.py +371 -0
- package/ci/system-one-layer-test.py +122 -0
- package/harness-everything/SKILL.md +1 -1
- package/harness-everything/scripts/system-one/cua_adapter.py +36 -1
- package/harness-everything/scripts/system-one/install.js +10 -0
- package/harness-everything/scripts/system-one/layer.py +178 -0
- package/harness-everything/scripts/system-one/manifest.js +8 -1
- package/harness-everything/scripts/system-one/provider.js +12 -2
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/plugin.json +1 -1
- package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +36 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +10 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/layer.py +178 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +8 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +12 -2
- package/sbom.cdx.json +7 -7
- package/scripts/system-one-colab.js +6 -4
- package/scripts/system-one-curves.js +52 -8
- package/scripts/system-one-cycle/evaluate.js +56 -5
- package/scripts/system-one-cycle/package.js +61 -3
- package/scripts/system-one-cycle/score.py +23 -2
- package/scripts/system-one-cycle/train.js +212 -20
- package/scripts/system-one-fit-layer.py +369 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Shared System One H-layer scoring primitives (stdlib only)."""
|
|
2
|
+
from collections import Counter
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
MAX_LAYER_BYTES = 32 * 1024 * 1024
|
|
10
|
+
_TOP_KEYS = {'schemaVersion', 'kind', 'stage', 'options', 'temperature', 'bias',
|
|
11
|
+
'alpha', 'k', 'ngrams', 'maxChars', 'index', 'fit'}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _finite_number(value):
|
|
15
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _positive_int(value):
|
|
19
|
+
return isinstance(value, int) and not isinstance(value, bool) and value > 0
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _format_error():
|
|
23
|
+
raise ValueError('checkpoint-format')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _width(stage, options):
|
|
27
|
+
if stage not in ('validity', 'intent', 'tier') or not isinstance(options, list) or not options:
|
|
28
|
+
_format_error()
|
|
29
|
+
return 1 if stage == 'validity' else len(options)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def grams(text, ngrams=(3, 4, 5), max_chars=2000):
|
|
33
|
+
"""Return experiment-order L2-normalized character gram counts."""
|
|
34
|
+
if not isinstance(text, str):
|
|
35
|
+
_format_error()
|
|
36
|
+
# Keep insertion order identical to the experiment: n ascending, then offset ascending.
|
|
37
|
+
counts = Counter()
|
|
38
|
+
padded = ' ' + text.lower()[:max_chars] + ' '
|
|
39
|
+
for n in ngrams:
|
|
40
|
+
for i in range(len(padded) - n + 1):
|
|
41
|
+
counts[padded[i:i + n]] += 1
|
|
42
|
+
norm = math.sqrt(sum(value * value for value in counts.values())) or 1.0
|
|
43
|
+
return {gram: value / norm for gram, value in counts.items()}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class KnnIndex:
|
|
47
|
+
def __init__(self, rows, stage, k=15, ngrams=(3, 4, 5), max_chars=2000):
|
|
48
|
+
self.stage, self.k = stage, k
|
|
49
|
+
self.ngrams, self.max_chars = tuple(ngrams), max_chars
|
|
50
|
+
self.rows = rows
|
|
51
|
+
self.vectors = [grams(row['text'], self.ngrams, self.max_chars) for row in rows]
|
|
52
|
+
self.postings = {}
|
|
53
|
+
for row_id, vector in enumerate(self.vectors):
|
|
54
|
+
for gram, weight in vector.items():
|
|
55
|
+
self.postings.setdefault(gram, []).append((row_id, weight))
|
|
56
|
+
|
|
57
|
+
def _similarities(self, text):
|
|
58
|
+
scores = Counter()
|
|
59
|
+
for gram, weight in grams(text, self.ngrams, self.max_chars).items():
|
|
60
|
+
for row_id, other_weight in self.postings.get(gram, ()):
|
|
61
|
+
scores[row_id] += weight * other_weight
|
|
62
|
+
return scores
|
|
63
|
+
|
|
64
|
+
def maxsim(self, text):
|
|
65
|
+
scores = self._similarities(text)
|
|
66
|
+
return max(scores.values()) if scores else 0.0
|
|
67
|
+
|
|
68
|
+
def dist(self, text, width):
|
|
69
|
+
if not _positive_int(width):
|
|
70
|
+
_format_error()
|
|
71
|
+
result = [0.0] * width
|
|
72
|
+
for row_id, similarity in self._similarities(text).most_common(self.k):
|
|
73
|
+
target = self.rows[row_id]['target']
|
|
74
|
+
vector = [1 - target[0], target[0]] if self.stage == 'validity' else target
|
|
75
|
+
total = sum(vector) or 1.0
|
|
76
|
+
for i in range(width):
|
|
77
|
+
result[i] += similarity * vector[i] / total
|
|
78
|
+
total = sum(result)
|
|
79
|
+
return [value / total for value in result] if total else [1 / width] * width
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def transform(logits, stage, temperature=1.0, bias=None):
|
|
83
|
+
"""Scale raw model logits and reproduce ECHL probabilities."""
|
|
84
|
+
if stage not in ('validity', 'intent', 'tier') or not logits or any(not _finite_number(v) for v in logits):
|
|
85
|
+
_format_error()
|
|
86
|
+
if not _finite_number(temperature) or temperature <= 0 or (
|
|
87
|
+
bias is not None and (not isinstance(bias, list) or len(bias) != len(logits)
|
|
88
|
+
or any(not _finite_number(v) for v in bias))):
|
|
89
|
+
_format_error()
|
|
90
|
+
values = []
|
|
91
|
+
for i, value in enumerate(logits):
|
|
92
|
+
z = value / temperature + (bias[i] if bias is not None else 0.0)
|
|
93
|
+
p = 1 / (1 + math.exp(-z)) if z >= 0 else math.exp(z) / (1 + math.exp(z))
|
|
94
|
+
values.append(p)
|
|
95
|
+
if stage == 'validity':
|
|
96
|
+
if len(values) != 1:
|
|
97
|
+
_format_error()
|
|
98
|
+
return [1 - values[0], values[0]]
|
|
99
|
+
total = max(sum(values), 1e-9)
|
|
100
|
+
return [value / total for value in values]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def blend(q, d, alpha):
|
|
104
|
+
if not _finite_number(alpha) or not 0 <= alpha <= 1 or len(q) != len(d):
|
|
105
|
+
_format_error()
|
|
106
|
+
return [(1 - alpha) * base + alpha * neighbor for base, neighbor in zip(q, d)]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _validate_layer(layer, stage, options):
|
|
110
|
+
width = _width(stage, options)
|
|
111
|
+
if (not isinstance(layer, dict) or set(layer) != _TOP_KEYS
|
|
112
|
+
or not isinstance(layer.get('schemaVersion'), int) or isinstance(layer['schemaVersion'], bool)
|
|
113
|
+
or layer['schemaVersion'] != 1 or layer.get('kind') != 'echl-h'
|
|
114
|
+
or layer.get('stage') != stage or layer.get('options') != options
|
|
115
|
+
or not _finite_number(layer.get('temperature')) or layer['temperature'] <= 0
|
|
116
|
+
or not _finite_number(layer.get('alpha')) or not 0 <= layer['alpha'] <= 1
|
|
117
|
+
or not _positive_int(layer.get('k')) or not isinstance(layer.get('ngrams'), list)
|
|
118
|
+
or not layer['ngrams'] or any(not _positive_int(n) for n in layer['ngrams'])
|
|
119
|
+
or not _positive_int(layer.get('maxChars')) or not isinstance(layer.get('index'), list)
|
|
120
|
+
or not isinstance(layer.get('fit'), dict)):
|
|
121
|
+
_format_error()
|
|
122
|
+
fit = layer['fit']
|
|
123
|
+
if (set(fit) != {'candidate', 'heldOutRows', 'nll', 'baseNll', 'oof'}
|
|
124
|
+
or not isinstance(fit['candidate'], str) or not fit['candidate']
|
|
125
|
+
or not _positive_int(fit['heldOutRows']) or not _finite_number(fit['nll'])
|
|
126
|
+
or not _finite_number(fit['baseNll']) or not isinstance(fit['oof'], bool)):
|
|
127
|
+
_format_error()
|
|
128
|
+
bias = layer.get('bias')
|
|
129
|
+
if bias is not None and (not isinstance(bias, list) or len(bias) != width
|
|
130
|
+
or any(not _finite_number(value) for value in bias)):
|
|
131
|
+
_format_error()
|
|
132
|
+
for row in layer['index']:
|
|
133
|
+
if (not isinstance(row, dict) or set(row) != {'text', 'target'}
|
|
134
|
+
or not isinstance(row['text'], str) or not isinstance(row['target'], list)
|
|
135
|
+
or len(row['target']) != width or any(not _finite_number(value) for value in row['target'])):
|
|
136
|
+
_format_error()
|
|
137
|
+
if layer['alpha'] > 0 and not layer['index']:
|
|
138
|
+
# An empty index is harmless; the reference returns a uniform neighbor distribution.
|
|
139
|
+
pass
|
|
140
|
+
return layer
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def load_layer(path, expected_sha256, stage, options):
|
|
144
|
+
file = Path(path)
|
|
145
|
+
try:
|
|
146
|
+
with file.open('rb') as handle:
|
|
147
|
+
if os.fstat(handle.fileno()).st_size > MAX_LAYER_BYTES:
|
|
148
|
+
_format_error()
|
|
149
|
+
raw = handle.read(MAX_LAYER_BYTES + 1)
|
|
150
|
+
if len(raw) > MAX_LAYER_BYTES:
|
|
151
|
+
_format_error()
|
|
152
|
+
except (OSError, ValueError):
|
|
153
|
+
_format_error()
|
|
154
|
+
if hashlib.sha256(raw).hexdigest() != expected_sha256:
|
|
155
|
+
raise ValueError('artifact-hash')
|
|
156
|
+
try:
|
|
157
|
+
layer = json.loads(raw.decode('utf-8'))
|
|
158
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
159
|
+
_format_error()
|
|
160
|
+
layer = _validate_layer(layer, stage, options)
|
|
161
|
+
if layer['alpha'] > 0: # index at load time (resident startup), never inside a request deadline
|
|
162
|
+
layer['_knn'] = KnnIndex(layer['index'], stage, layer['k'], layer['ngrams'], layer['maxChars'])
|
|
163
|
+
return layer
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def apply_layer(layer, logits, text):
|
|
167
|
+
stage = layer['stage']
|
|
168
|
+
expected_width = 1 if stage == 'validity' else len(layer['options'])
|
|
169
|
+
if len(logits) != expected_width:
|
|
170
|
+
_format_error()
|
|
171
|
+
q = transform(logits, stage, layer['temperature'], layer['bias'])
|
|
172
|
+
if layer['alpha'] > 0:
|
|
173
|
+
# Build the inverted index once per loaded layer; rebuilding it per request costs ~1 s on a 2,000-row index.
|
|
174
|
+
index = layer.get('_knn')
|
|
175
|
+
if index is None:
|
|
176
|
+
index = layer['_knn'] = KnnIndex(layer['index'], stage, layer['k'], layer['ngrams'], layer['maxChars'])
|
|
177
|
+
q = blend(q, index.dist(text, len(q)), layer['alpha'])
|
|
178
|
+
return [q[1]] if stage == 'validity' else q
|
|
@@ -29,7 +29,9 @@ function validateVersionManifest(manifest, expectedVersion) {
|
|
|
29
29
|
for (const name of STAGES) {
|
|
30
30
|
const stage = manifest.stages[name];
|
|
31
31
|
const fields = ['weights', 'config', 'sha256', 'options', 'thresholds'];
|
|
32
|
-
if (!(exact(stage, fields) || exact(stage, [...fields, 'referenceOnly'])
|
|
32
|
+
if (!(exact(stage, fields) || exact(stage, [...fields, 'referenceOnly'])
|
|
33
|
+
|| exact(stage, [...fields, 'layer', 'layerSha256'])
|
|
34
|
+
|| exact(stage, [...fields, 'referenceOnly', 'layer', 'layerSha256']))
|
|
33
35
|
|| !safeRelative(stage.weights) || !safeRelative(stage.config) || !HASH.test(stage.sha256)
|
|
34
36
|
|| !Array.isArray(stage.options) || !stage.options.length
|
|
35
37
|
|| stage.options.some(id => typeof id !== 'string' || !SAFE_ID.test(id)
|
|
@@ -38,6 +40,11 @@ function validateVersionManifest(manifest, expectedVersion) {
|
|
|
38
40
|
|| Object.values(stage.thresholds).some(value => typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1)) {
|
|
39
41
|
fail(`malformed ${name} stage`);
|
|
40
42
|
}
|
|
43
|
+
if ((Object.hasOwn(stage, 'layer') !== Object.hasOwn(stage, 'layerSha256'))
|
|
44
|
+
|| (stage.layer !== undefined && (!safeRelative(stage.layer) || stage.layer.includes('/')
|
|
45
|
+
|| !stage.layer.endsWith('.layer.json') || !HASH.test(stage.layerSha256)))) {
|
|
46
|
+
fail(`malformed ${name} layer`);
|
|
47
|
+
}
|
|
41
48
|
if (stage.weights.includes('/') || stage.config.includes('/')) fail(`${name} weights and config must be flat filenames`);
|
|
42
49
|
if (Object.hasOwn(stage, 'referenceOnly')
|
|
43
50
|
&& (!Array.isArray(stage.referenceOnly) || new Set(stage.referenceOnly).size !== stage.referenceOnly.length
|
|
@@ -20,6 +20,7 @@ const inRange = (v, lo, hi) => typeof v === 'number' && Number.isFinite(v) && v
|
|
|
20
20
|
const LIVE_STAGES = STAGES;
|
|
21
21
|
const SAFE_ID = /^[a-z0-9._-]{1,80}$/;
|
|
22
22
|
const sha256 = value => createHash('sha256').update(value).digest('hex');
|
|
23
|
+
const MAX_LAYER_BYTES = 32 * 1024 * 1024;
|
|
23
24
|
// secondaryThreshold is optional and belongs to intent checkpoints (docs/system-one-intent.md#scoring).
|
|
24
25
|
const validAcceptance = a => (exact(a, ['minConfidence', 'minMargin']) || (exact(a, ['minConfidence', 'minMargin', 'secondaryThreshold']) && inRange(a.secondaryThreshold, 0.05, 0.5)))
|
|
25
26
|
&& inRange(a.minConfidence, 0.5, 0.99) && inRange(a.minMargin, 0, 0.9);
|
|
@@ -158,10 +159,19 @@ function readActive(env = process.env) {
|
|
|
158
159
|
const weightsPath = readableFile(dir, stage.weights, '.safetensors');
|
|
159
160
|
const configPath = readableFile(dir, stage.config, '.json');
|
|
160
161
|
if (!weightsPath || !configPath || sha256(fs.readFileSync(weightsPath)) !== stage.sha256) return null;
|
|
162
|
+
let layerPath;
|
|
163
|
+
if (stage.layer !== undefined) {
|
|
164
|
+
layerPath = readableFile(dir, stage.layer, '.json');
|
|
165
|
+
if (!layerPath || !stage.layer.endsWith('.layer.json') || fs.statSync(layerPath).size > MAX_LAYER_BYTES
|
|
166
|
+
|| sha256(fs.readFileSync(layerPath)) !== stage.layerSha256) return null;
|
|
167
|
+
}
|
|
161
168
|
loadedStages[stageName] = { ...stage, referenceOnly: stage.referenceOnly ?? [], weightsPath, configPath,
|
|
162
|
-
configSha256: sha256(fs.readFileSync(configPath)) };
|
|
169
|
+
...(layerPath ? { layerPath } : {}), configSha256: sha256(fs.readFileSync(configPath)) };
|
|
163
170
|
}
|
|
164
|
-
const fingerprint = sha256(`${pointer.version}\0${dir}\0${LIVE_STAGES.map(stage =>
|
|
171
|
+
const fingerprint = sha256(`${pointer.version}\0${dir}\0${LIVE_STAGES.map(stage => {
|
|
172
|
+
const entry = loadedStages[stage];
|
|
173
|
+
return `${stage}\0${entry.sha256}\0${entry.configSha256}${entry.layerSha256 ? `\0${entry.layerSha256}` : ''}`;
|
|
174
|
+
}).join('\0')}`);
|
|
165
175
|
const python = env.HARNESS_SYSTEM_ONE_PYTHON || env.PYTHON || path.join(home, 'venv', process.platform === 'win32' ? 'Scripts/python.exe' : 'bin/python');
|
|
166
176
|
return { home, pointerPath, pointer, version: pointer.version, dir, manifest, stages: loadedStages,
|
|
167
177
|
fingerprint, python, sha256: loadedStages.tier.sha256.slice(0, 16) };
|
package/sbom.cdx.json
CHANGED
|
@@ -2,23 +2,23 @@
|
|
|
2
2
|
"$schema": "https://cyclonedx.org/schema/bom-1.7.schema.json",
|
|
3
3
|
"bomFormat": "CycloneDX",
|
|
4
4
|
"specVersion": "1.7",
|
|
5
|
-
"serialNumber": "urn:uuid:
|
|
5
|
+
"serialNumber": "urn:uuid:6661f5f0-5209-57ad-9fcc-0e658727ece7",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-
|
|
8
|
+
"timestamp": "2026-12-01T04:13:31.424Z",
|
|
9
9
|
"tools": [
|
|
10
10
|
{
|
|
11
11
|
"vendor": "Harness Everything",
|
|
12
12
|
"name": "generate-sbom.js",
|
|
13
|
-
"version": "1.
|
|
13
|
+
"version": "1.5.0"
|
|
14
14
|
}
|
|
15
15
|
],
|
|
16
16
|
"component": {
|
|
17
17
|
"type": "application",
|
|
18
|
-
"bom-ref": "pkg:npm/harness-everything@1.
|
|
18
|
+
"bom-ref": "pkg:npm/harness-everything@1.5.0",
|
|
19
19
|
"name": "harness-everything",
|
|
20
|
-
"version": "1.
|
|
21
|
-
"purl": "pkg:npm/harness-everything@1.
|
|
20
|
+
"version": "1.5.0",
|
|
21
|
+
"purl": "pkg:npm/harness-everything@1.5.0"
|
|
22
22
|
}
|
|
23
23
|
},
|
|
24
24
|
"components": [
|
|
@@ -2033,7 +2033,7 @@
|
|
|
2033
2033
|
]
|
|
2034
2034
|
},
|
|
2035
2035
|
{
|
|
2036
|
-
"ref": "pkg:npm/harness-everything@1.
|
|
2036
|
+
"ref": "pkg:npm/harness-everything@1.5.0",
|
|
2037
2037
|
"dependsOn": [
|
|
2038
2038
|
"pkg:npm/%40commitlint/cli@19.8.1",
|
|
2039
2039
|
"pkg:npm/%40commitlint/config-conventional@19.8.1",
|
|
@@ -7,7 +7,7 @@ const os = require('node:os');
|
|
|
7
7
|
const path = require('node:path');
|
|
8
8
|
const { spawnSync } = require('node:child_process');
|
|
9
9
|
const { REPO, dataPath, writeJson, runNode, assertPrivateDataDir, parseFlags, flag, required } = require('./system-one-cycle/common');
|
|
10
|
-
const { TASKS } = require('./system-one-cycle/train');
|
|
10
|
+
const { TASKS, fitLayerStage, successfulGuard, hasTrainerReport } = require('./system-one-cycle/train');
|
|
11
11
|
const { validateVersion } = require('./system-one-cycle/package');
|
|
12
12
|
const { PINS } = require('../harness-everything/scripts/system-one/install');
|
|
13
13
|
|
|
@@ -50,8 +50,7 @@ function allowListedFile(root, relative, optional = false) {
|
|
|
50
50
|
|
|
51
51
|
function completeStage(dir) {
|
|
52
52
|
if (!REUSE_FILES.every(file => fs.existsSync(path.join(dir, file)))) return false;
|
|
53
|
-
|
|
54
|
-
return guard.exitCode === 0 && !guard.killedForLimit && !guard.monitorFailed;
|
|
53
|
+
return successfulGuard(dir) && hasTrainerReport(dir, path.basename(dir));
|
|
55
54
|
}
|
|
56
55
|
|
|
57
56
|
function writeJsonAtomic(file, value) {
|
|
@@ -114,6 +113,7 @@ function main(argv) {
|
|
|
114
113
|
const stageDirs = Object.fromEntries(TASKS.map(task => [task, dataPath(dataDir, 'training', 'runs', version, task)]));
|
|
115
114
|
const tasks = TASKS.filter(task => !completeStage(stageDirs[task]));
|
|
116
115
|
if (!tasks.length) {
|
|
116
|
+
for (const task of TASKS) fitLayerStage({ dataDir, runDir: stageDirs[task], task });
|
|
117
117
|
process.stdout.write(`${JSON.stringify({ version, trained: 0, skipped: TASKS.length, session: null })}\n`);
|
|
118
118
|
return;
|
|
119
119
|
}
|
|
@@ -199,7 +199,8 @@ function main(argv) {
|
|
|
199
199
|
}
|
|
200
200
|
}
|
|
201
201
|
const guard = { schemaVersion: 1, exitCode: 0, killedForLimit: false, monitorFailed: false,
|
|
202
|
-
createdAt: new Date().toISOString(), remote: { provider: 'colab', gpu: gpu || null, session
|
|
202
|
+
createdAt: new Date().toISOString(), remote: { provider: 'colab', gpu: gpu || null, session,
|
|
203
|
+
invocationId, manifestSha256: manifestDigest, files: status.files } };
|
|
203
204
|
runNode(calibrator, [path.join(staging, 'val-scores.jsonl'), path.join(staging, 'calibration.json'), '--task', task,
|
|
204
205
|
'--catalog', path.join(staging, 'train-report.json')]);
|
|
205
206
|
fs.mkdirSync(out, { recursive: true, mode: 0o700 });
|
|
@@ -225,6 +226,7 @@ function main(argv) {
|
|
|
225
226
|
}
|
|
226
227
|
}
|
|
227
228
|
if (failure) throw failure;
|
|
229
|
+
for (const task of TASKS) fitLayerStage({ dataDir, runDir: stageDirs[task], task });
|
|
228
230
|
const hashes = manifest.files.map(({ path: file, sha256: hash }) => ({ path: file, sha256: hash }));
|
|
229
231
|
process.stdout.write(`${JSON.stringify({ version, trained: tasks.length, skipped: TASKS.length - tasks.length,
|
|
230
232
|
gpu: gpu || null, device, session, uploaded: files.length + 1, manifestSha256: manifestDigest, files: hashes })}\n`);
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
const fs = require('node:fs');
|
|
5
|
+
const crypto = require('node:crypto');
|
|
5
6
|
const path = require('node:path');
|
|
6
7
|
const { isDeepStrictEqual } = require('node:util');
|
|
7
8
|
const { STAGES, validateVersionManifest } = require('../harness-everything/scripts/system-one/manifest');
|
|
@@ -15,6 +16,7 @@ const fail = () => { throw new TypeError('invalid-system-one-curves-input'); };
|
|
|
15
16
|
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
16
17
|
const isText = value => typeof value === 'string' && value.trim().length > 0;
|
|
17
18
|
const isProbability = value => Number.isFinite(value) && value >= 0 && value <= 1;
|
|
19
|
+
const hasLayeredStages = manifest => Object.values(manifest.stages).some(entry => Object.hasOwn(entry, 'layer'));
|
|
18
20
|
|
|
19
21
|
function readJsonl(file) {
|
|
20
22
|
let lines;
|
|
@@ -27,12 +29,40 @@ function readManifest(dir, version) {
|
|
|
27
29
|
let manifest;
|
|
28
30
|
try { manifest = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8')); } catch (_) { fail(); }
|
|
29
31
|
try { validateVersionManifest(manifest, version); } catch (_) { fail(); }
|
|
32
|
+
const layered = hasLayeredStages(manifest);
|
|
30
33
|
for (const entry of Object.values(manifest.stages)) {
|
|
31
|
-
|
|
34
|
+
const weights = path.join(dir, entry.weights);
|
|
35
|
+
const config = path.join(dir, entry.config);
|
|
36
|
+
if (!fs.existsSync(weights) || !fs.existsSync(config)) fail();
|
|
37
|
+
if (layered && Object.hasOwn(entry, 'layer')
|
|
38
|
+
&& crypto.createHash('sha256').update(fs.readFileSync(weights)).digest('hex') !== entry.sha256) fail();
|
|
39
|
+
if (Object.hasOwn(entry, 'layer') || Object.hasOwn(entry, 'layerSha256')) {
|
|
40
|
+
if (!isText(entry.layer) || !/^[a-f0-9]{64}$/.test(entry.layerSha256 || '')) fail();
|
|
41
|
+
const layerPath = path.join(dir, entry.layer);
|
|
42
|
+
let stat;
|
|
43
|
+
try { stat = fs.statSync(layerPath); } catch (_) { fail(); }
|
|
44
|
+
if (!stat.isFile() || stat.size > 32 * 1024 * 1024
|
|
45
|
+
|| crypto.createHash('sha256').update(fs.readFileSync(layerPath)).digest('hex') !== entry.layerSha256) fail();
|
|
46
|
+
}
|
|
32
47
|
}
|
|
33
48
|
return manifest;
|
|
34
49
|
}
|
|
35
50
|
|
|
51
|
+
function candidateDigest(dir, manifest) {
|
|
52
|
+
const stages = Object.fromEntries(Object.entries(manifest.stages).map(([name, entry]) => {
|
|
53
|
+
const artifactHash = file => crypto.createHash('sha256').update(fs.readFileSync(path.join(dir, file))).digest('hex');
|
|
54
|
+
return [name, { weights: artifactHash(entry.weights), config: artifactHash(entry.config),
|
|
55
|
+
layer: entry.layer ? entry.layerSha256 : null, options: entry.options, thresholds: entry.thresholds,
|
|
56
|
+
referenceOnly: entry.referenceOnly || [] }];
|
|
57
|
+
}));
|
|
58
|
+
return crypto.createHash('sha256').update(JSON.stringify(stages)).digest('hex');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function scoreDigests(files) {
|
|
62
|
+
return Object.fromEntries(Object.entries(files).map(([stage, file]) => [stage,
|
|
63
|
+
crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')]));
|
|
64
|
+
}
|
|
65
|
+
|
|
36
66
|
function positives(row, stage, options) {
|
|
37
67
|
if (stage === 'validity') {
|
|
38
68
|
if (!['invalid', 'actionable'].includes(row.gold) || options.length !== 1 || options[0] !== 'invalid') fail();
|
|
@@ -42,8 +72,8 @@ function positives(row, stage, options) {
|
|
|
42
72
|
if (!isText(row.gold) || !options.includes(row.gold)) fail();
|
|
43
73
|
return new Set([row.gold]);
|
|
44
74
|
}
|
|
45
|
-
const gold = Array.isArray(row.gold) ? row.gold : [row.gold];
|
|
46
|
-
if (gold.some(id => !isText(id) || !options.includes(id)) || new Set(gold).size !== gold.length) fail();
|
|
75
|
+
const gold = [...(Array.isArray(row.gold) ? row.gold : [row.gold]), ...(row.secondary || [])];
|
|
76
|
+
if (!gold.length || gold.some(id => !isText(id) || !options.includes(id)) || new Set(gold).size !== gold.length) fail();
|
|
47
77
|
return new Set(gold);
|
|
48
78
|
}
|
|
49
79
|
|
|
@@ -51,8 +81,9 @@ function readRows(file, stage, options) {
|
|
|
51
81
|
const rows = readJsonl(file);
|
|
52
82
|
const ids = new Set();
|
|
53
83
|
return rows.map(row => {
|
|
54
|
-
if (!isObject(row) || Object.keys(row).length
|
|
84
|
+
if (!isObject(row) || ![3, 4].includes(Object.keys(row).length) || !Object.hasOwn(row, 'id')
|
|
55
85
|
|| !Object.hasOwn(row, 'gold') || !Object.hasOwn(row, 'scores') || !isText(row.id) || ids.has(row.id)
|
|
86
|
+
|| (Object.hasOwn(row, 'secondary') && (!Array.isArray(row.secondary) || stage !== 'intent'))
|
|
56
87
|
|| !isObject(row.scores) || Object.keys(row.scores).length !== options.length
|
|
57
88
|
|| options.some(option => !Object.hasOwn(row.scores, option) || !isProbability(row.scores[option]))) fail();
|
|
58
89
|
ids.add(row.id);
|
|
@@ -283,10 +314,13 @@ function assertVersionReusable(history, curves) {
|
|
|
283
314
|
return existing;
|
|
284
315
|
}
|
|
285
316
|
|
|
286
|
-
function validateSavedCurves(curves, version, manifest) {
|
|
317
|
+
function validateSavedCurves(curves, version, manifest, digest, expectedScores) {
|
|
287
318
|
validateCurveRecord(curves);
|
|
288
319
|
if (curves.version !== version || Object.keys(curves.stages).length !== Object.keys(manifest.stages).length
|
|
289
320
|
|| Object.keys(curves.stages).some(stage => !Object.hasOwn(manifest.stages, stage))) fail();
|
|
321
|
+
const layered = hasLayeredStages(manifest);
|
|
322
|
+
if (layered && curves.candidateDigest !== digest) fail();
|
|
323
|
+
if (layered && (!expectedScores || !isDeepStrictEqual(curves.scoreDigests, expectedScores))) fail();
|
|
290
324
|
}
|
|
291
325
|
|
|
292
326
|
function validateSavedTrend(trend, version) {
|
|
@@ -400,7 +434,7 @@ function parseArgs(argv) {
|
|
|
400
434
|
}
|
|
401
435
|
if (!isText(parsed.version) || !isText(parsed.versionDir) || !isText(parsed.history) || !isText(parsed.out)) fail();
|
|
402
436
|
if (parsed.resumeCurves) {
|
|
403
|
-
if (!isText(parsed.resumeCurves)
|
|
437
|
+
if (!isText(parsed.resumeCurves)) fail();
|
|
404
438
|
} else if (!parsed.val.length) fail();
|
|
405
439
|
return parsed;
|
|
406
440
|
}
|
|
@@ -409,13 +443,21 @@ function run(argv) {
|
|
|
409
443
|
const args = parseArgs(argv);
|
|
410
444
|
args.history = assertPrivateHistoryFile(args.history);
|
|
411
445
|
const manifest = readManifest(args.versionDir, args.version);
|
|
446
|
+
const layered = hasLayeredStages(manifest);
|
|
447
|
+
if (args.resumeCurves && !layered && (args.val.length || args.holdout.length)) fail();
|
|
448
|
+
const digest = layered ? candidateDigest(args.versionDir, manifest) : null;
|
|
412
449
|
if (args.resumeCurves) {
|
|
450
|
+
const valFiles = stageFiles(args, 'val');
|
|
451
|
+
const holdoutFiles = stageFiles(args, 'holdout');
|
|
413
452
|
let curves; let trend;
|
|
414
453
|
try {
|
|
415
454
|
curves = JSON.parse(fs.readFileSync(args.resumeCurves, 'utf8'));
|
|
416
455
|
trend = JSON.parse(fs.readFileSync(path.join(args.out, 'trend.json'), 'utf8'));
|
|
417
456
|
} catch (_) { fail(); }
|
|
418
|
-
|
|
457
|
+
const expectedScores = layered && Object.keys(valFiles).length && Object.keys(holdoutFiles).length
|
|
458
|
+
? { validation: scoreDigests(valFiles), holdout: scoreDigests(holdoutFiles) } : null;
|
|
459
|
+
if (layered && (!expectedScores || !isDeepStrictEqual(Object.keys(valFiles).sort(), Object.keys(holdoutFiles).sort()))) fail();
|
|
460
|
+
validateSavedCurves(curves, args.version, manifest, digest, expectedScores);
|
|
419
461
|
validateSavedTrend(trend, args.version);
|
|
420
462
|
const history = readHistory(args.history);
|
|
421
463
|
validateBaselineReferences(curves, history);
|
|
@@ -445,7 +487,9 @@ function run(argv) {
|
|
|
445
487
|
const history = readHistory(args.history);
|
|
446
488
|
if (history.some(row => row.version === args.version)) throw new TypeError(VERSION_ALREADY_RECORDED);
|
|
447
489
|
const floor = assessFloor(Object.keys(holdoutMetrics).length ? holdoutMetrics : null, history);
|
|
448
|
-
const curves = { schemaVersion: 1, version: args.version, createdAt: new Date().toISOString(),
|
|
490
|
+
const curves = { schemaVersion: 1, version: args.version, createdAt: new Date().toISOString(),
|
|
491
|
+
...(layered ? { candidateDigest: digest,
|
|
492
|
+
scoreDigests: { validation: scoreDigests(valFiles), holdout: scoreDigests(holdoutFiles) } } : {}), stages, floor };
|
|
449
493
|
validateBaselineReferences(curves, history);
|
|
450
494
|
const trend = decideTrend(curves, history, floor);
|
|
451
495
|
fs.mkdirSync(args.out, { recursive: true });
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const crypto = require('node:crypto');
|
|
3
4
|
const fs = require('node:fs');
|
|
4
5
|
const path = require('node:path');
|
|
5
6
|
const { spawnSync } = require('node:child_process');
|
|
6
7
|
const { REPO, dataPath, writeJson, assertPrivateDataDir, assertPrivateHistoryFile } = require('./common');
|
|
7
8
|
const { buildVersion } = require('./package');
|
|
8
|
-
const { TASKS } = require('./train');
|
|
9
|
+
const { TASKS, fitLayerStage, hasTrainerReport } = require('./train');
|
|
9
10
|
const { validateVersionManifest } = require('../../harness-everything/scripts/system-one/manifest');
|
|
10
11
|
|
|
11
12
|
const HOLDOUTS = { validity: 'system-one-holdout.json', tier: 'system-one-holdout.json', intent: 'system-one-intent-holdout.json' };
|
|
@@ -29,6 +30,40 @@ function recordEvaluation(manifestFile, version) {
|
|
|
29
30
|
return manifest;
|
|
30
31
|
}
|
|
31
32
|
|
|
33
|
+
function verifyLayerPair(versionDir, sourceDir, outcomes) {
|
|
34
|
+
const manifestFile = path.join(versionDir, 'manifest.json');
|
|
35
|
+
const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
|
|
36
|
+
validateVersionManifest(manifest);
|
|
37
|
+
const digest = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
38
|
+
for (const task of TASKS) {
|
|
39
|
+
const entry = manifest.stages[task];
|
|
40
|
+
const outcome = outcomes[task];
|
|
41
|
+
if (!outcome) throw new Error(`${task} candidate fit outcome is missing`);
|
|
42
|
+
if (entry.weights !== `${task}.safetensors` || entry.config !== `${task}.json`)
|
|
43
|
+
throw new Error(`${task} candidate manifest paths do not match the scorer checkpoint files`);
|
|
44
|
+
const runDir = path.join(sourceDir, task);
|
|
45
|
+
const calibration = JSON.parse(fs.readFileSync(path.join(runDir, 'calibration.json'), 'utf8'));
|
|
46
|
+
const expectedThresholds = Object.fromEntries(entry.options.map(id => [id,
|
|
47
|
+
calibration.thresholds?.[id] === null ? 1 : calibration.thresholds?.[id]]));
|
|
48
|
+
if (JSON.stringify(expectedThresholds) !== JSON.stringify(entry.thresholds))
|
|
49
|
+
throw new Error(`${task} candidate thresholds do not match the current validated calibration`);
|
|
50
|
+
if (entry.sha256 !== outcome.checkpointSha256)
|
|
51
|
+
throw new Error(`${task} candidate checkpoint does not match its fit outcome`);
|
|
52
|
+
if (!/^[a-f0-9]{64}$/.test(outcome.checkpointConfigSha256 || '')
|
|
53
|
+
|| digest(path.join(versionDir, entry.config)) !== outcome.checkpointConfigSha256)
|
|
54
|
+
throw new Error(`${task} candidate checkpoint config does not match its fit outcome`);
|
|
55
|
+
if (outcome.outcome === 'layer') {
|
|
56
|
+
if (!entry.layer || entry.layerSha256 !== digest(path.join(sourceDir, task, 'layer.json'))
|
|
57
|
+
|| entry.layerSha256 !== outcome.layerSha256 || entry.sha256 !== outcome.checkpointSha256) {
|
|
58
|
+
throw new Error(`${task} candidate layer does not match its fit`);
|
|
59
|
+
}
|
|
60
|
+
} else if (entry.layer || outcome.outcome !== 'keep-base') {
|
|
61
|
+
throw new Error(`${task} candidate layer fit is missing or inconsistent`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return manifest;
|
|
65
|
+
}
|
|
66
|
+
|
|
32
67
|
function evaluateCycle({ dataDir, version, history: historyOption }) {
|
|
33
68
|
const privateDir = assertPrivateDataDir(dataDir);
|
|
34
69
|
const history = assertPrivateHistoryFile(historyOption === undefined
|
|
@@ -40,15 +75,30 @@ function evaluateCycle({ dataDir, version, history: historyOption }) {
|
|
|
40
75
|
const trendFile = path.join(evaluationDir, 'trend.json');
|
|
41
76
|
const curvesScript = path.join(REPO, 'scripts', 'system-one-curves.js');
|
|
42
77
|
if (!fs.existsSync(curvesScript)) throw new Error('contract C curves CLI is not available in this checkout');
|
|
78
|
+
const outcomes = Object.fromEntries(TASKS.map(task => {
|
|
79
|
+
const runDir = path.join(source, task);
|
|
80
|
+
const hasFitInputs = hasTrainerReport(runDir, task);
|
|
81
|
+
return [task, hasFitInputs ? fitLayerStage({ dataDir: privateDir, runDir, task }) : null];
|
|
82
|
+
}));
|
|
43
83
|
if (fs.existsSync(curvesFile) && fs.existsSync(trendFile)) {
|
|
44
|
-
|
|
45
|
-
|
|
84
|
+
const candidate = verifyLayerPair(versionDir, source, outcomes);
|
|
85
|
+
const resumeArgs = [curvesScript, '--version', version, '--version-dir', versionDir,
|
|
86
|
+
'--history', history, '--out', evaluationDir, '--resume-curves', curvesFile];
|
|
87
|
+
if (Object.values(candidate.stages).some(stage => stage.layer)) {
|
|
88
|
+
for (const task of TASKS) {
|
|
89
|
+
const validation = candidate.stages[task].layer ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
|
|
90
|
+
resumeArgs.push('--val-scores', `${task}=${path.join(source, task, validation)}`);
|
|
91
|
+
resumeArgs.push('--holdout-scores', `${task}=${path.join(evaluationDir, `${task}-holdout-scores.jsonl`)}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
runProcess(process.execPath, resumeArgs);
|
|
46
95
|
const manifestFile = path.join(versionDir, 'manifest.json');
|
|
47
96
|
recordEvaluation(manifestFile, version);
|
|
48
97
|
const trend = JSON.parse(fs.readFileSync(trendFile, 'utf8'));
|
|
49
98
|
return { version, verdict: trend.verdict, compared: trend.compared.length, resumed: true };
|
|
50
99
|
}
|
|
51
100
|
buildVersion({ dataDir: privateDir, version, sourceDir: source, versionDir });
|
|
101
|
+
const candidate = verifyLayerPair(versionDir, source, outcomes);
|
|
52
102
|
|
|
53
103
|
fs.mkdirSync(evaluationDir, { recursive: true, mode: 0o700 });
|
|
54
104
|
const scoreScript = path.join(__dirname, 'score.py');
|
|
@@ -58,7 +108,8 @@ function evaluateCycle({ dataDir, version, history: historyOption }) {
|
|
|
58
108
|
const heldOut = path.join(holdoutDir, HOLDOUTS[task]);
|
|
59
109
|
const scores = path.join(evaluationDir, `${task}-holdout-scores.jsonl`);
|
|
60
110
|
runProcess(pythonExecutable(), [scoreScript, '--weights', path.join(versionDir, `${task}.safetensors`), '--holdout', heldOut, '--task', task, '--out', scores]);
|
|
61
|
-
|
|
111
|
+
const validation = candidate.stages[task].layer ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
|
|
112
|
+
curvesArgs.push('--val-scores', `${task}=${path.join(source, task, validation)}`);
|
|
62
113
|
curvesArgs.push('--holdout-scores', `${task}=${scores}`);
|
|
63
114
|
}
|
|
64
115
|
curvesArgs.push('--history', history, '--out', evaluationDir);
|
|
@@ -70,4 +121,4 @@ function evaluateCycle({ dataDir, version, history: historyOption }) {
|
|
|
70
121
|
return { version, verdict: trend.verdict, compared: trend.compared.length };
|
|
71
122
|
}
|
|
72
123
|
|
|
73
|
-
module.exports = { evaluateCycle, HOLDOUTS };
|
|
124
|
+
module.exports = { evaluateCycle, HOLDOUTS, verifyLayerPair };
|