harness-everything 1.3.2 → 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.
Files changed (46) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.github/workflows/release.yml +23 -6
  4. package/CHANGELOG.md +42 -0
  5. package/RELEASING.md +2 -0
  6. package/ci/fixtures/system-one-colab-fit-layer-sitecustomize.py +72 -0
  7. package/ci/mechanism-2x-release-automation.test.js +17 -0
  8. package/ci/mechanism-system-one-colab.test.js +528 -0
  9. package/ci/mechanism-system-one-contract.test.js +30 -0
  10. package/ci/mechanism-system-one-curves.test.js +85 -0
  11. package/ci/mechanism-system-one-cycle.test.js +344 -34
  12. package/ci/mechanism-system-one-install.test.js +47 -0
  13. package/ci/mechanism-system-one-provider.test.js +2 -0
  14. package/ci/mechanism-system-one-resident.test.js +69 -0
  15. package/ci/system-one-adapter-test.py +86 -0
  16. package/ci/system-one-fit-layer-test.py +371 -0
  17. package/ci/system-one-layer-test.py +122 -0
  18. package/ci/system-one-train-test.py +26 -0
  19. package/docs/system-one-cycle.md +10 -0
  20. package/docs/system-one-training.md +3 -1
  21. package/harness-everything/SKILL.md +1 -1
  22. package/harness-everything/scripts/system-one/cua_adapter.py +36 -1
  23. package/harness-everything/scripts/system-one/install.js +10 -0
  24. package/harness-everything/scripts/system-one/layer.py +178 -0
  25. package/harness-everything/scripts/system-one/manifest.js +8 -1
  26. package/harness-everything/scripts/system-one/provider.js +12 -2
  27. package/opencode-plugin/plugin.json +1 -1
  28. package/package.json +1 -1
  29. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  30. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  31. package/plugins/harness-everything/plugin.json +1 -1
  32. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  33. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +36 -1
  34. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +10 -0
  35. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/layer.py +178 -0
  36. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +8 -1
  37. package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +12 -2
  38. package/sbom.cdx.json +7 -7
  39. package/scripts/system-one-colab.js +240 -0
  40. package/scripts/system-one-curves.js +52 -8
  41. package/scripts/system-one-cycle/evaluate.js +56 -5
  42. package/scripts/system-one-cycle/package.js +61 -3
  43. package/scripts/system-one-cycle/score.py +23 -2
  44. package/scripts/system-one-cycle/train.js +212 -20
  45. package/scripts/system-one-fit-layer.py +369 -0
  46. package/scripts/system-one-train.py +36 -9
@@ -0,0 +1,122 @@
1
+ import hashlib
2
+ import importlib.util
3
+ import json
4
+ import math
5
+ import tempfile
6
+ import sys
7
+ import unittest
8
+ from pathlib import Path
9
+
10
+ sys.dont_write_bytecode = True
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ MODULE = ROOT / 'harness-everything' / 'scripts' / 'system-one' / 'layer.py'
13
+ spec = importlib.util.spec_from_file_location('system_one_layer', MODULE)
14
+ layer = importlib.util.module_from_spec(spec)
15
+ spec.loader.exec_module(layer)
16
+
17
+
18
+ class LayerTest(unittest.TestCase):
19
+ def valid(self, stage='tier', options=None, **changes):
20
+ options = options or (['invalid'] if stage == 'validity' else ['a', 'b'])
21
+ return {
22
+ 'schemaVersion': 1, 'kind': 'echl-h', 'stage': stage, 'options': options,
23
+ 'temperature': 1.0, 'bias': None, 'alpha': 0.0, 'k': 15,
24
+ 'ngrams': [3, 4, 5], 'maxChars': 2000, 'index': [],
25
+ 'fit': {'candidate': 'H-temp', 'heldOutRows': 1, 'nll': 0.1, 'baseNll': 0.2, 'oof': True},
26
+ **changes,
27
+ }
28
+
29
+ def test_legacy_transform_and_validity_shapes(self):
30
+ logits = [0.25, -0.5, 1.0]
31
+ raw = [1 / (1 + math.exp(-value)) for value in logits]
32
+ for actual, expected in zip(layer.transform(logits, 'intent'), [value / sum(raw) for value in raw]):
33
+ self.assertAlmostEqual(actual, expected, places=15)
34
+ p = 1 / (1 + math.exp(-0.25))
35
+ self.assertEqual(layer.transform([0.25], 'validity'), [1 - p, p])
36
+ self.assertEqual(layer.apply_layer(self.valid(options=['a', 'b', 'c']), logits, 'ignored'),
37
+ layer.transform(logits, 'tier'))
38
+
39
+ def test_tie_order_matches_experiment_counter_first_encounter(self):
40
+ index = layer.KnnIndex([
41
+ {'text': 'abc', 'target': [1, 0]}, {'text': 'xyz', 'target': [0, 1]},
42
+ ], 'tier', k=1)
43
+ # For xyz abc, xyz grams are encountered first and select row 1 on the tie.
44
+ self.assertEqual(index.dist('xyz abc', 2), [0.0, 1.0])
45
+ control = layer.KnnIndex([
46
+ {'text': 'xyz', 'target': [1, 0]}, {'text': 'abc', 'target': [0, 1]},
47
+ ], 'tier', k=1)
48
+ self.assertEqual(control.dist('xyz abc', 2), [1.0, 0.0])
49
+
50
+ def test_apply_matches_temperature_bias_and_neighbor_blend(self):
51
+ data = self.valid(alpha=0.6, k=1, ngrams=[3], maxChars=2000,
52
+ index=[{'text': 'small change', 'target': [0, 1]}])
53
+ logits = [0.0, 0.0]
54
+ result = layer.apply_layer(data, logits, 'small change')
55
+ self.assertEqual(result, [0.2, 0.8])
56
+ self.assertEqual(layer.apply_layer({**data, 'alpha': 0.0}, logits, 'small change'), [0.5, 0.5])
57
+
58
+ def test_intent_soft_targets_and_temperature_bias_match_shared_transform(self):
59
+ data = self.valid(stage='intent', temperature=2.0, bias=[math.log(3), 0.0],
60
+ alpha=1.0, index=[{'text': 'multi label', 'target': [0.25, 0.75]}])
61
+ for actual, expected in zip(layer.apply_layer(data, [0.0, 0.0], 'multi label'), [0.25, 0.75]):
62
+ self.assertAlmostEqual(actual, expected)
63
+ fitted = layer.transform([0.0, 0.0], 'intent', 2.0, [math.log(3), 0.0])
64
+ self.assertAlmostEqual(fitted[0], 0.6)
65
+ self.assertAlmostEqual(fitted[1], 0.4)
66
+ self.assertEqual(layer.apply_layer({**data, 'alpha': 0.0, 'index': []}, [0, 0], 'multi label'),
67
+ fitted)
68
+
69
+ def test_validity_neighbors_convert_binary_target_to_two_classes(self):
70
+ data = self.valid('validity', alpha=1.0, index=[{'text': 'bad request', 'target': [0.8]}])
71
+ self.assertEqual(layer.apply_layer(data, [0.0], 'bad request'), [0.8])
72
+
73
+ def test_load_builds_the_knn_index_once_and_requests_reuse_it(self):
74
+ index = [{'text': 'fix the login test', 'target': [1.0, 0.0]}, {'text': 'plan the release', 'target': [0.0, 1.0]}]
75
+ with tempfile.TemporaryDirectory() as temp:
76
+ file = Path(temp) / 'tier.layer.json'
77
+ payload = json.dumps(self.valid(alpha=0.5, index=index)).encode()
78
+ file.write_bytes(payload)
79
+ loaded = layer.load_layer(file, hashlib.sha256(payload).hexdigest(), 'tier', ['a', 'b'])
80
+ built = loaded['_knn']
81
+ reference = layer.apply_layer(dict(self.valid(alpha=0.5, index=index)), [0.2, -0.1], 'fix the login')
82
+ self.assertEqual(layer.apply_layer(loaded, [0.2, -0.1], 'fix the login'), reference)
83
+ self.assertIs(loaded['_knn'], built)
84
+
85
+ def test_load_checks_hash_then_schema_and_stage_option_order(self):
86
+ with tempfile.TemporaryDirectory() as temp:
87
+ file = Path(temp) / 'tier.layer.json'
88
+ payload = json.dumps(self.valid()).encode()
89
+ file.write_bytes(payload)
90
+ digest = hashlib.sha256(payload).hexdigest()
91
+ self.assertEqual(layer.load_layer(file, digest, 'tier', ['a', 'b'])['stage'], 'tier')
92
+ with self.assertRaisesRegex(ValueError, 'artifact-hash'):
93
+ layer.load_layer(file, '0' * 64, 'tier', ['a', 'b'])
94
+ with self.assertRaisesRegex(ValueError, 'checkpoint-format'):
95
+ layer.load_layer(file, digest, 'intent', ['a', 'b'])
96
+ with self.assertRaisesRegex(ValueError, 'checkpoint-format'):
97
+ layer.load_layer(file, digest, 'tier', ['b', 'a'])
98
+
99
+ def test_rejects_nonfinite_values_and_malformed_pairs(self):
100
+ for changes in (
101
+ {'temperature': float('nan')}, {'temperature': 0}, {'alpha': float('inf')},
102
+ {'bias': [float('nan'), 0]}, {'index': [{'text': 'x', 'target': [0, float('nan')]}]},
103
+ {'k': True}, {'ngrams': [0]}, {'maxChars': True},
104
+ ):
105
+ with self.subTest(changes=changes), tempfile.TemporaryDirectory() as temp:
106
+ file = Path(temp) / 'layer.json'
107
+ raw = json.dumps(self.valid(**changes)).encode()
108
+ file.write_bytes(raw)
109
+ with self.assertRaisesRegex(ValueError, 'checkpoint-format'):
110
+ layer.load_layer(file, hashlib.sha256(raw).hexdigest(), 'tier', ['a', 'b'])
111
+
112
+ def test_file_size_limit_is_checked_before_read(self):
113
+ with tempfile.TemporaryDirectory() as temp:
114
+ file = Path(temp) / 'large.layer.json'
115
+ with file.open('wb') as handle:
116
+ handle.truncate(32 * 1024 * 1024 + 1)
117
+ with self.assertRaisesRegex(ValueError, 'checkpoint-format'):
118
+ layer.load_layer(file, '0' * 64, 'tier', ['a', 'b'])
119
+
120
+
121
+ if __name__ == '__main__':
122
+ unittest.main()
@@ -12,6 +12,32 @@ trainer = importlib.util.module_from_spec(spec)
12
12
  spec.loader.exec_module(trainer)
13
13
  assert 'torch' not in sys.modules, 'importing the trainer must not import torch'
14
14
 
15
+ device_cases = [
16
+ ('cpu', False, 'cpu'),
17
+ ('cpu', True, 'cpu'),
18
+ ('auto', True, 'cuda'),
19
+ ('auto', False, 'cpu'),
20
+ ('cuda', True, 'cuda'),
21
+ ]
22
+ for requested, cuda_available, expected in device_cases:
23
+ assert trainer.resolve_device(requested, cuda_available) == expected, (requested, cuda_available)
24
+ try:
25
+ trainer.resolve_device('cuda', False)
26
+ raise AssertionError('cuda without an available device must fail')
27
+ except ValueError as exc:
28
+ assert 'CUDA' in str(exc) and 'unavailable' in str(exc), exc
29
+ try:
30
+ trainer.resolve_device('unknown', False)
31
+ raise AssertionError('unknown device must fail')
32
+ except ValueError:
33
+ pass
34
+ try:
35
+ trainer.main(['--data-dir', 'unused', '--out', 'unused', '--device', 'unknown'])
36
+ raise AssertionError('argparse must reject an unknown device')
37
+ except SystemExit as exc:
38
+ assert exc.code == 2, exc.code
39
+ print('PASS device resolution: cpu, auto, cuda availability and invalid choices')
40
+
15
41
  tier_catalog = trainer.catalog_for('tier')
16
42
  intent_catalog = trainer.catalog_for('intent')
17
43
  validity_catalog = trainer.catalog_for('validity')
@@ -36,6 +36,16 @@ flowchart LR
36
36
 
37
37
  ¹ Durations are planning estimates, not measurements from this checkout. Model latency and dataset size vary.
38
38
 
39
+ ## Train on Colab
40
+
41
+ The owner can start the same ordered training stages on a Colab VM from the local private cycle directory:
42
+
43
+ ```sh
44
+ node scripts/system-one-colab.js --data-dir "<private-cycle-dir>" --version <version-id> [--gpu T4|L4|A100]
45
+ ```
46
+
47
+ CPU is the default. `--gpu` selects the Colab GPU and passes `--device cuda`; CUDA runs need not be bit-identical to CPU runs. The launcher creates the remote bundle directories, then uploads only the built `training/v1/` and `training/v1-validity/` trainer inputs, the public trainer, and the two public holdout catalogs. It sends a SHA-256 manifest and checks every uploaded file on the VM before each stage. After training, the VM writes a status record with hashes for that stage's outputs; the launcher downloads the record first and verifies each downloaded file against it. Raw observations, relabels, adjudication, history, and private holdouts stay local. Each finished stage is downloaded and calibrated locally before the next task starts. Completed stages are reused on the next invocation, including after a later task fails. The launcher always attempts to stop the VM; if stopping fails, its diagnostic, the session ID, and a manual stop command are included in the CLI error. Set `COLAB_BIN` or pass `--colab` to use a different CLI binary, and optionally pass `--session` to choose its session name.
48
+
39
49
  F6 extends per-stage manifest metadata with `referenceOnly`; it does not
40
50
  authorize an additional top-level `workflowPlan.systemOne` field. The routing
41
51
  guide records the separate H1b output enrichment and the unresolved output
@@ -176,10 +176,12 @@ prompts written by an agent, not by the owner. VS Code terminal notifications
176
176
  `labels-intent.jsonl` rows and the fixed intent catalog; its hard target is multi-hot for
177
177
  `gold` plus `secondary`. With `--target scores`, each intent's value from
178
178
  `labels-intent-scores.jsonl` is its soft target.
179
- - **Optimization**: per-option binary cross-entropy with logits, AdamW, a fixed seed and CPU.
179
+ - **Optimization**: per-option binary cross-entropy with logits, AdamW, a fixed seed and `--device {cpu,cuda,auto}` (default `cpu`).
180
180
  Validation applies sigmoid independently to each option; `val-scores.jsonl` stores rows as
181
181
  `{id, gold, scores: {option: probability}}`; option probabilities are independent and do
182
182
  not have to sum to one.
183
+ - `auto` selects CUDA when available; requesting unavailable CUDA exits with an error. The
184
+ resolved device and PyTorch version are recorded in checkpoint metadata and `train-report.json`.
183
185
  - The epoch with the lowest validation negative log-likelihood is kept.
184
186
  - The checkpoint metadata records the dataset hashes, the config and the validation metrics.
185
187
  - **Calibration**: `minConfidence` and `minMargin` are chosen on validation to maximize
@@ -4,7 +4,7 @@ description: "Route software/project work through Harness: classify tier/topolog
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 1.3.2
7
+ version: 1.5.0
8
8
  ---
9
9
 
10
10
  # Harness Everything
@@ -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 => `${stage}\0${loadedStages[stage].sha256}\0${loadedStages[stage].configSha256}`).join('\0')}`);
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) };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-enforcement",
3
3
  "description": "Repository inventory for the opencode enforcement plugin and its standalone helper",
4
- "version": "1.3.2",
4
+ "version": "1.5.0",
5
5
  "runtime": "index.mjs",
6
6
  "hooks": {
7
7
  "verify": "hooks/verify.js"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.3.2",
3
+ "version": "1.5.0",
4
4
  "description": "Harness OS: An Orchestrated Agent Operating System for AI-driven Development",
5
5
  "main": "harness-everything/scripts/bootstrap.js",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.3.2",
3
+ "version": "1.5.0",
4
4
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
5
5
  "author": {
6
6
  "name": "Miya Daniel",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.3.2",
3
+ "version": "1.5.0",
4
4
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
5
5
  "author": {
6
6
  "name": "Miya Daniel",
@@ -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.3.2",
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",
@@ -4,7 +4,7 @@ description: "Route software/project work through Harness: classify tier/topolog
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 1.3.2
7
+ version: 1.5.0
8
8
  ---
9
9
 
10
10
  # Harness Everything