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
|
@@ -15,6 +15,19 @@ import tempfile
|
|
|
15
15
|
import threading
|
|
16
16
|
import time
|
|
17
17
|
|
|
18
|
+
import importlib.util
|
|
19
|
+
|
|
20
|
+
# Load the sibling layer module by path: callers load this adapter by file location, so its directory is not on sys.path.
|
|
21
|
+
_layer_spec = importlib.util.spec_from_file_location('harness_system_one_layer', Path(__file__).resolve().with_name('layer.py'))
|
|
22
|
+
_layer = importlib.util.module_from_spec(_layer_spec)
|
|
23
|
+
_write_bytecode = sys.dont_write_bytecode
|
|
24
|
+
sys.dont_write_bytecode = True # never leave __pycache__ in the shipped tree (installer stale-tree check)
|
|
25
|
+
try:
|
|
26
|
+
_layer_spec.loader.exec_module(_layer)
|
|
27
|
+
finally:
|
|
28
|
+
sys.dont_write_bytecode = _write_bytecode
|
|
29
|
+
apply_layer, load_layer = _layer.apply_layer, _layer.load_layer
|
|
30
|
+
|
|
18
31
|
ACTIVE_STAGES = ('validity', 'intent', 'tier')
|
|
19
32
|
LEGACY_ROUTING_METADATA = frozenset(('domain', 'bestEpoch', 'validation', 'datasets', 'seed', 'catalog'))
|
|
20
33
|
|
|
@@ -97,6 +110,12 @@ def load_scorer(weights, manifest):
|
|
|
97
110
|
example = ChoiceExample(context=request['context'], options=tuple(o['text'] for o in request['options']), label=0)
|
|
98
111
|
with torch.inference_mode():
|
|
99
112
|
logits = model(collator([example]))
|
|
113
|
+
if 'layerPath' in manifest:
|
|
114
|
+
raw = logits[0].tolist()
|
|
115
|
+
fitted = manifest.get('_loadedLayer')
|
|
116
|
+
if fitted is None:
|
|
117
|
+
fitted = load_layer(manifest['layerPath'], manifest['layerSha256'], task, manifest['options'])
|
|
118
|
+
return apply_layer(fitted, raw, request['context'])
|
|
100
119
|
return (logits.softmax(-1) if semantics == 'categorical' else logits.sigmoid())[0].tolist()
|
|
101
120
|
score.score_semantics = semantics
|
|
102
121
|
score.training_task = task
|
|
@@ -147,6 +166,8 @@ def _active_fingerprint(version, directory, scorers):
|
|
|
147
166
|
for stage in ACTIVE_STAGES:
|
|
148
167
|
entry = scorers[stage]
|
|
149
168
|
values.extend((stage, entry['sha256'], entry['manifest']['configSha256']))
|
|
169
|
+
if entry.get('layerSha256'):
|
|
170
|
+
values.append(entry['layerSha256'])
|
|
150
171
|
return hashlib.sha256('\0'.join(values).encode('utf-8')).hexdigest()
|
|
151
172
|
|
|
152
173
|
|
|
@@ -154,6 +175,8 @@ def _active_stamp(bundle):
|
|
|
154
175
|
paths = [Path(bundle['activePath']), Path(bundle['manifestPath'])]
|
|
155
176
|
for stage in ACTIVE_STAGES:
|
|
156
177
|
paths.extend((bundle['scorers'][stage]['weights'], bundle['scorers'][stage]['configPath']))
|
|
178
|
+
if bundle['scorers'][stage].get('layerPath'):
|
|
179
|
+
paths.append(bundle['scorers'][stage]['layerPath'])
|
|
157
180
|
return [(file.stat().st_size, file.stat().st_mtime_ns) for file in paths]
|
|
158
181
|
|
|
159
182
|
|
|
@@ -195,6 +218,14 @@ def load_active_bundle(active_path, expected_fingerprint=None, scorer_loader=Non
|
|
|
195
218
|
config_path = _active_artifact(directory, entry['config'], '.json')
|
|
196
219
|
if hashlib.sha256(weights.read_bytes()).hexdigest() != entry['sha256']:
|
|
197
220
|
raise ValueError('artifact-hash')
|
|
221
|
+
layer_path = None
|
|
222
|
+
if entry.get('layer') is not None:
|
|
223
|
+
layer_path = _active_artifact(directory, entry['layer'], '.json')
|
|
224
|
+
if not entry['layer'].endswith('.layer.json'):
|
|
225
|
+
raise ValueError('checkpoint-format')
|
|
226
|
+
layer_value = load_layer(layer_path, entry['layerSha256'], stage, entry['options'])
|
|
227
|
+
else:
|
|
228
|
+
layer_value = None
|
|
198
229
|
stage_manifest = {
|
|
199
230
|
'checkpoint': str(weights),
|
|
200
231
|
'config': str(config_path),
|
|
@@ -204,11 +235,15 @@ def load_active_bundle(active_path, expected_fingerprint=None, scorer_loader=Non
|
|
|
204
235
|
'revision': pointer['version'],
|
|
205
236
|
'domain': 'harness-routing-v1',
|
|
206
237
|
}
|
|
238
|
+
if layer_path is not None:
|
|
239
|
+
stage_manifest.update({'layerPath': str(layer_path), 'layerSha256': entry['layerSha256'],
|
|
240
|
+
'options': entry['options'], '_loadedLayer': layer_value})
|
|
207
241
|
score, config = loader(weights, stage_manifest)
|
|
208
242
|
if scorer_loader is None and (score.score_semantics != 'independent' or score.training_task != stage):
|
|
209
243
|
raise ValueError('active-stage')
|
|
210
244
|
scorers[stage] = {**entry, 'manifest': stage_manifest, 'score': score, 'config': config,
|
|
211
|
-
'weights': weights, 'configPath': config_path
|
|
245
|
+
'weights': weights, 'configPath': config_path,
|
|
246
|
+
**({'layerPath': layer_path, 'layer': layer_value} if layer_path is not None else {})}
|
|
212
247
|
fingerprint = _active_fingerprint(pointer['version'], pointer['dir'], scorers)
|
|
213
248
|
if expected_fingerprint is not None and fingerprint != expected_fingerprint:
|
|
214
249
|
raise ValueError('active-changed')
|
|
@@ -164,6 +164,14 @@ function readCheckpoint(dir, version) {
|
|
|
164
164
|
const config = resolveManifestFile(root, record.config);
|
|
165
165
|
if (hash(fs.readFileSync(weights.path)) !== record.sha256) throw new Error(`checkpoint-hash-mismatch: ${stage}`);
|
|
166
166
|
files.set(weights.relative, weights); files.set(config.relative, config);
|
|
167
|
+
if (record.layer !== undefined) {
|
|
168
|
+
const layer = resolveManifestFile(root, record.layer);
|
|
169
|
+
if (!record.layer.endsWith('.layer.json') || fs.statSync(layer.path).size > 32 * 1024 * 1024) {
|
|
170
|
+
throw new Error('checkpoint-format');
|
|
171
|
+
}
|
|
172
|
+
if (hash(fs.readFileSync(layer.path)) !== record.layerSha256) throw new Error('artifact-hash');
|
|
173
|
+
files.set(layer.relative, { ...layer, private: true });
|
|
174
|
+
}
|
|
167
175
|
}
|
|
168
176
|
if (manifest.evaluation !== null) {
|
|
169
177
|
const evaluation = resolveManifestFile(root, manifest.evaluation);
|
|
@@ -191,6 +199,7 @@ function installVersion(source, version, dir = defaultDir()) {
|
|
|
191
199
|
return fs.existsSync(other) && fs.readFileSync(file.path).equals(fs.readFileSync(other));
|
|
192
200
|
});
|
|
193
201
|
if (!same) throw new Error(`version-conflict: ${version} is already installed with different files`);
|
|
202
|
+
for (const file of existing.files) if (file.private) fs.chmodSync(file.path, 0o600);
|
|
194
203
|
return { version, dir: target, status: 'already-installed' };
|
|
195
204
|
}
|
|
196
205
|
const staging = fs.mkdtempSync(path.join(versions, `.${version}.`));
|
|
@@ -200,6 +209,7 @@ function installVersion(source, version, dir = defaultDir()) {
|
|
|
200
209
|
const dest = path.join(staging, relative);
|
|
201
210
|
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
202
211
|
fs.copyFileSync(file.path, dest, fs.constants.COPYFILE_EXCL);
|
|
212
|
+
if (file.private) fs.chmodSync(dest, 0o600);
|
|
203
213
|
}
|
|
204
214
|
fs.renameSync(staging, target);
|
|
205
215
|
} catch (error) {
|
|
@@ -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/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
|
3
3
|
"name": "harness-everything",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.5.0",
|
|
5
5
|
"description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Miya Daniel",
|
package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py
CHANGED
|
@@ -15,6 +15,19 @@ import tempfile
|
|
|
15
15
|
import threading
|
|
16
16
|
import time
|
|
17
17
|
|
|
18
|
+
import importlib.util
|
|
19
|
+
|
|
20
|
+
# Load the sibling layer module by path: callers load this adapter by file location, so its directory is not on sys.path.
|
|
21
|
+
_layer_spec = importlib.util.spec_from_file_location('harness_system_one_layer', Path(__file__).resolve().with_name('layer.py'))
|
|
22
|
+
_layer = importlib.util.module_from_spec(_layer_spec)
|
|
23
|
+
_write_bytecode = sys.dont_write_bytecode
|
|
24
|
+
sys.dont_write_bytecode = True # never leave __pycache__ in the shipped tree (installer stale-tree check)
|
|
25
|
+
try:
|
|
26
|
+
_layer_spec.loader.exec_module(_layer)
|
|
27
|
+
finally:
|
|
28
|
+
sys.dont_write_bytecode = _write_bytecode
|
|
29
|
+
apply_layer, load_layer = _layer.apply_layer, _layer.load_layer
|
|
30
|
+
|
|
18
31
|
ACTIVE_STAGES = ('validity', 'intent', 'tier')
|
|
19
32
|
LEGACY_ROUTING_METADATA = frozenset(('domain', 'bestEpoch', 'validation', 'datasets', 'seed', 'catalog'))
|
|
20
33
|
|
|
@@ -97,6 +110,12 @@ def load_scorer(weights, manifest):
|
|
|
97
110
|
example = ChoiceExample(context=request['context'], options=tuple(o['text'] for o in request['options']), label=0)
|
|
98
111
|
with torch.inference_mode():
|
|
99
112
|
logits = model(collator([example]))
|
|
113
|
+
if 'layerPath' in manifest:
|
|
114
|
+
raw = logits[0].tolist()
|
|
115
|
+
fitted = manifest.get('_loadedLayer')
|
|
116
|
+
if fitted is None:
|
|
117
|
+
fitted = load_layer(manifest['layerPath'], manifest['layerSha256'], task, manifest['options'])
|
|
118
|
+
return apply_layer(fitted, raw, request['context'])
|
|
100
119
|
return (logits.softmax(-1) if semantics == 'categorical' else logits.sigmoid())[0].tolist()
|
|
101
120
|
score.score_semantics = semantics
|
|
102
121
|
score.training_task = task
|
|
@@ -147,6 +166,8 @@ def _active_fingerprint(version, directory, scorers):
|
|
|
147
166
|
for stage in ACTIVE_STAGES:
|
|
148
167
|
entry = scorers[stage]
|
|
149
168
|
values.extend((stage, entry['sha256'], entry['manifest']['configSha256']))
|
|
169
|
+
if entry.get('layerSha256'):
|
|
170
|
+
values.append(entry['layerSha256'])
|
|
150
171
|
return hashlib.sha256('\0'.join(values).encode('utf-8')).hexdigest()
|
|
151
172
|
|
|
152
173
|
|
|
@@ -154,6 +175,8 @@ def _active_stamp(bundle):
|
|
|
154
175
|
paths = [Path(bundle['activePath']), Path(bundle['manifestPath'])]
|
|
155
176
|
for stage in ACTIVE_STAGES:
|
|
156
177
|
paths.extend((bundle['scorers'][stage]['weights'], bundle['scorers'][stage]['configPath']))
|
|
178
|
+
if bundle['scorers'][stage].get('layerPath'):
|
|
179
|
+
paths.append(bundle['scorers'][stage]['layerPath'])
|
|
157
180
|
return [(file.stat().st_size, file.stat().st_mtime_ns) for file in paths]
|
|
158
181
|
|
|
159
182
|
|
|
@@ -195,6 +218,14 @@ def load_active_bundle(active_path, expected_fingerprint=None, scorer_loader=Non
|
|
|
195
218
|
config_path = _active_artifact(directory, entry['config'], '.json')
|
|
196
219
|
if hashlib.sha256(weights.read_bytes()).hexdigest() != entry['sha256']:
|
|
197
220
|
raise ValueError('artifact-hash')
|
|
221
|
+
layer_path = None
|
|
222
|
+
if entry.get('layer') is not None:
|
|
223
|
+
layer_path = _active_artifact(directory, entry['layer'], '.json')
|
|
224
|
+
if not entry['layer'].endswith('.layer.json'):
|
|
225
|
+
raise ValueError('checkpoint-format')
|
|
226
|
+
layer_value = load_layer(layer_path, entry['layerSha256'], stage, entry['options'])
|
|
227
|
+
else:
|
|
228
|
+
layer_value = None
|
|
198
229
|
stage_manifest = {
|
|
199
230
|
'checkpoint': str(weights),
|
|
200
231
|
'config': str(config_path),
|
|
@@ -204,11 +235,15 @@ def load_active_bundle(active_path, expected_fingerprint=None, scorer_loader=Non
|
|
|
204
235
|
'revision': pointer['version'],
|
|
205
236
|
'domain': 'harness-routing-v1',
|
|
206
237
|
}
|
|
238
|
+
if layer_path is not None:
|
|
239
|
+
stage_manifest.update({'layerPath': str(layer_path), 'layerSha256': entry['layerSha256'],
|
|
240
|
+
'options': entry['options'], '_loadedLayer': layer_value})
|
|
207
241
|
score, config = loader(weights, stage_manifest)
|
|
208
242
|
if scorer_loader is None and (score.score_semantics != 'independent' or score.training_task != stage):
|
|
209
243
|
raise ValueError('active-stage')
|
|
210
244
|
scorers[stage] = {**entry, 'manifest': stage_manifest, 'score': score, 'config': config,
|
|
211
|
-
'weights': weights, 'configPath': config_path
|
|
245
|
+
'weights': weights, 'configPath': config_path,
|
|
246
|
+
**({'layerPath': layer_path, 'layer': layer_value} if layer_path is not None else {})}
|
|
212
247
|
fingerprint = _active_fingerprint(pointer['version'], pointer['dir'], scorers)
|
|
213
248
|
if expected_fingerprint is not None and fingerprint != expected_fingerprint:
|
|
214
249
|
raise ValueError('active-changed')
|
|
@@ -164,6 +164,14 @@ function readCheckpoint(dir, version) {
|
|
|
164
164
|
const config = resolveManifestFile(root, record.config);
|
|
165
165
|
if (hash(fs.readFileSync(weights.path)) !== record.sha256) throw new Error(`checkpoint-hash-mismatch: ${stage}`);
|
|
166
166
|
files.set(weights.relative, weights); files.set(config.relative, config);
|
|
167
|
+
if (record.layer !== undefined) {
|
|
168
|
+
const layer = resolveManifestFile(root, record.layer);
|
|
169
|
+
if (!record.layer.endsWith('.layer.json') || fs.statSync(layer.path).size > 32 * 1024 * 1024) {
|
|
170
|
+
throw new Error('checkpoint-format');
|
|
171
|
+
}
|
|
172
|
+
if (hash(fs.readFileSync(layer.path)) !== record.layerSha256) throw new Error('artifact-hash');
|
|
173
|
+
files.set(layer.relative, { ...layer, private: true });
|
|
174
|
+
}
|
|
167
175
|
}
|
|
168
176
|
if (manifest.evaluation !== null) {
|
|
169
177
|
const evaluation = resolveManifestFile(root, manifest.evaluation);
|
|
@@ -191,6 +199,7 @@ function installVersion(source, version, dir = defaultDir()) {
|
|
|
191
199
|
return fs.existsSync(other) && fs.readFileSync(file.path).equals(fs.readFileSync(other));
|
|
192
200
|
});
|
|
193
201
|
if (!same) throw new Error(`version-conflict: ${version} is already installed with different files`);
|
|
202
|
+
for (const file of existing.files) if (file.private) fs.chmodSync(file.path, 0o600);
|
|
194
203
|
return { version, dir: target, status: 'already-installed' };
|
|
195
204
|
}
|
|
196
205
|
const staging = fs.mkdtempSync(path.join(versions, `.${version}.`));
|
|
@@ -200,6 +209,7 @@ function installVersion(source, version, dir = defaultDir()) {
|
|
|
200
209
|
const dest = path.join(staging, relative);
|
|
201
210
|
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
202
211
|
fs.copyFileSync(file.path, dest, fs.constants.COPYFILE_EXCL);
|
|
212
|
+
if (file.private) fs.chmodSync(dest, 0o600);
|
|
203
213
|
}
|
|
204
214
|
fs.renameSync(staging, target);
|
|
205
215
|
} catch (error) {
|