harness-everything 0.52.0 → 0.54.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 (71) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/AGENTS.md +3 -1
  4. package/CHANGELOG.md +38 -0
  5. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md +7 -0
  6. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-probe.js +16 -0
  7. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-trace-2026-11-15.jsonl +4 -0
  8. package/bin/cli.js +1 -0
  9. package/ci/invariant-routing.test.js +22 -3
  10. package/ci/mechanism-2al-codex-hooks-compat.test.js +56 -2
  11. package/ci/mechanism-2n-opencode-plugin.test.js +1 -1
  12. package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +18 -3
  13. package/ci/mechanism-338-opencode-async.test.js +20 -3
  14. package/ci/mechanism-341-opencode-lane.test.js +7 -1
  15. package/ci/mechanism-349-ci-change-scope.test.js +78 -57
  16. package/ci/mechanism-397-cycle-import.test.js +414 -0
  17. package/ci/mechanism-397-host-acceptance.test.js +119 -0
  18. package/ci/mechanism-397-opencode-observations.test.js +1922 -0
  19. package/ci/mechanism-check-packet-write-set.test.js +232 -0
  20. package/ci/mechanism-codex-prompt-pass-through.test.js +8 -4
  21. package/ci/mechanism-error-handling-map.test.js +219 -0
  22. package/ci/mechanism-report-writer.test.js +335 -0
  23. package/ci/mechanism-system-one-curves.test.js +17 -0
  24. package/ci/mechanism-system-one-cycle.test.js +621 -2
  25. package/ci/router-workflow-plan.test.js +50 -7
  26. package/docs/architecture.md +4 -3
  27. package/docs/error-handling/README.md +250 -0
  28. package/docs/error-handling/actions/c1-action-map.md +89 -0
  29. package/docs/error-handling/actions/c2-action-map.md +22 -0
  30. package/docs/error-handling/actions/c3-action-map.md +26 -0
  31. package/docs/error-handling/actions/c5-action-map.md +31 -0
  32. package/docs/error-handling/actions/c6-action-map.md +37 -0
  33. package/docs/error-handling/actions/c7-action-map.md +18 -0
  34. package/docs/error-handling/actions/e0002-action-map.md +101 -0
  35. package/docs/error-handling/activity.puml +84 -0
  36. package/docs/error-handling/details/c1-authority-conformance.md +93 -0
  37. package/docs/error-handling/details/c2-test-root-containment.md +35 -0
  38. package/docs/error-handling/details/c3-mode-ownership.md +50 -0
  39. package/docs/error-handling/details/c5-host-replay-contract.md +40 -0
  40. package/docs/error-handling/details/c6-packet-briefing.md +65 -0
  41. package/docs/error-handling/details/c7-write-set-check.md +54 -0
  42. package/docs/error-handling/details/e0002-capture-evidence.md +93 -0
  43. package/docs/error-handling/details/e0002-report-writer.md +116 -0
  44. package/docs/error-handling/nodes.yaml +44 -0
  45. package/docs/error-handling/registry.md +59 -0
  46. package/docs/error-handling/templates/packet-briefing.md +45 -0
  47. package/docs/platform-capabilities.md +16 -7
  48. package/docs/system-one-cycle.md +12 -3
  49. package/docs/system-one-observations.md +35 -4
  50. package/hooks/scripts/codex-user-prompt.js +2 -3
  51. package/hooks/scripts/lib/observations.js +5 -3
  52. package/opencode-plugin/README.md +22 -8
  53. package/opencode-plugin/index.mjs +424 -44
  54. package/opencode-plugin/plugin.json +1 -1
  55. package/package.json +2 -1
  56. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  57. package/plugins/harness-everything/hooks/scripts/codex-user-prompt.js +2 -3
  58. package/plugins/harness-everything/hooks/scripts/lib/observations.js +5 -3
  59. package/plugins/harness-everything/plugin.json +1 -1
  60. package/sbom.cdx.json +7 -7
  61. package/scripts/check-packet-write-set.js +155 -0
  62. package/scripts/codex-hooks-compat.js +46 -5
  63. package/scripts/error-handling-map.js +288 -0
  64. package/scripts/report-writer.js +261 -0
  65. package/scripts/system-one-curves.js +154 -14
  66. package/scripts/system-one-cycle/collect.js +20 -3
  67. package/scripts/system-one-cycle/common.js +39 -1
  68. package/scripts/system-one-cycle/evaluate.js +8 -5
  69. package/scripts/system-one-cycle.js +7 -2
  70. package/scripts/system-one-observations-export.js +29 -0
  71. package/scripts/system-one-observations-import-store.js +128 -0
@@ -0,0 +1,261 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const crypto = require('node:crypto');
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+
8
+ const USAGE = 'usage: report-writer write --output <path> --status <DONE|BLOCKED|0|nonzero-int> (--body-file <path>|--context <text>|--from-codex-output <path>) [--reason <text>|--error <text>...] | report-writer check --file <path>';
9
+ const WRITE_OPTIONS = new Set(['--output', '--status', '--reason', '--error', '--body-file', '--context', '--from-codex-output']);
10
+ const LABEL_MARKER = '<!-- harness-label';
11
+
12
+ function error(message) {
13
+ throw new Error(message);
14
+ }
15
+
16
+ function parseOptions(args, allowed, repeatable = new Set()) {
17
+ const options = new Map();
18
+ for (let i = 0; i < args.length; i += 2) {
19
+ const key = args[i];
20
+ if (!allowed.has(key)) error(`unknown option: ${key}`);
21
+ if (i + 1 >= args.length) error(`missing value for ${key}`);
22
+ if (options.has(key) && !repeatable.has(key)) error(`duplicate option: ${key}`);
23
+ if (repeatable.has(key)) options.set(key, [...(options.get(key) || []), args[i + 1]]);
24
+ else options.set(key, args[i + 1]);
25
+ }
26
+ return options;
27
+ }
28
+
29
+ function required(options, key) {
30
+ const value = options.get(key);
31
+ if (value === undefined || value === '') error(`missing value for ${key}`);
32
+ return value;
33
+ }
34
+
35
+ function singleLine(value, name) {
36
+ if (/\r|\n/.test(value)) error(`${name} must be a single line`);
37
+ return value;
38
+ }
39
+
40
+ function statusFrom(options) {
41
+ const value = singleLine(required(options, '--status'), 'status');
42
+ const reason = options.get('--reason');
43
+ const errors = options.get('--error') || [];
44
+
45
+ let done;
46
+ if (value === 'DONE' || value === '0') done = true;
47
+ else if (value === 'BLOCKED') done = false;
48
+ else if (/^[+-]?\d+$/.test(value) && Number.isSafeInteger(Number(value))) done = Number(value) === 0;
49
+ else error('status must be DONE, BLOCKED, 0, or a nonzero integer');
50
+
51
+ if (done) {
52
+ if (reason !== undefined || errors.length) error('DONE status cannot include a reason or error');
53
+ return 'STATUS: DONE';
54
+ }
55
+ if (reason !== undefined && errors.length) error('provide either --reason or --error, not both');
56
+ const message = reason !== undefined ? reason : errors.join('; ');
57
+ if (message === undefined || message.trim() === '') error('BLOCKED status requires a nonempty --reason or --error');
58
+ singleLine(message, 'reason');
59
+ return `STATUS: BLOCKED: ${message.trim()}`;
60
+ }
61
+
62
+ function splitLines(text) {
63
+ if (/\r(?!\n)/.test(text)) error('bare carriage return is not a valid line ending');
64
+ const lines = [];
65
+ const separators = /\r\n|\n/g;
66
+ let start = 0;
67
+ let match;
68
+ while ((match = separators.exec(text))) {
69
+ lines.push({ value: text.slice(start, match.index), start, eol: match[0] });
70
+ start = separators.lastIndex;
71
+ }
72
+ if (start < text.length || text.length === 0 || !text.endsWith('\n')) {
73
+ lines.push({ value: text.slice(start), start, eol: '' });
74
+ }
75
+ return lines;
76
+ }
77
+
78
+ function statusLineStatus(line) {
79
+ if (line === 'STATUS: DONE') return 'STATUS: DONE';
80
+ const blocked = /^STATUS: BLOCKED: (.+)$/.exec(line);
81
+ if (blocked && blocked[1].trim() !== '') return line;
82
+ error('expected STATUS: DONE or STATUS: BLOCKED: <reason>');
83
+ }
84
+
85
+ function validateReport(text) {
86
+ if (text.includes(LABEL_MARKER)) error('report contains a host label marker');
87
+ const lines = splitLines(text);
88
+ const controls = lines.filter(line => line.value.startsWith('STATUS:'));
89
+ if (controls.length !== 1) error(`expected exactly one STATUS line; found ${controls.length}`);
90
+ const last = lines[lines.length - 1];
91
+ if (!last || !last.value.startsWith('STATUS:')) error('STATUS line must be terminal with nothing after it');
92
+ return statusLineStatus(last.value);
93
+ }
94
+
95
+ function validateBody(body) {
96
+ if (body.includes(LABEL_MARKER)) error('body contains a host label marker');
97
+ if (splitLines(body).some(line => line.value.startsWith('STATUS:'))) {
98
+ error('body contains a column-zero STATUS line');
99
+ }
100
+ }
101
+
102
+ function parseHostLabel(line) {
103
+ const prefix = '<!-- harness-label ';
104
+ const suffix = ' -->';
105
+ if (!line.startsWith(prefix) || !line.endsWith(suffix)) error('malformed terminal host label');
106
+ let value;
107
+ try {
108
+ value = JSON.parse(line.slice(prefix.length, -suffix.length));
109
+ } catch {
110
+ error('terminal host label must contain valid JSON');
111
+ }
112
+ if (!value || typeof value !== 'object' || Array.isArray(value)) error('terminal host label JSON must be an object');
113
+ }
114
+
115
+ function extractCodexBody(raw, expectedStatus) {
116
+ const lines = splitLines(raw);
117
+ let strippedLabel = false;
118
+ let bodyEnd = raw.length;
119
+ const markers = lines.filter(line => line.value.includes(LABEL_MARKER));
120
+
121
+ if (markers.length) {
122
+ if (markers.length !== 1 || markers[0] !== lines[lines.length - 1]) error('host label is allowed only once at EOF');
123
+ parseHostLabel(lines[lines.length - 1].value);
124
+ strippedLabel = true;
125
+ bodyEnd = lines[lines.length - 1].start;
126
+ }
127
+
128
+ const controls = lines.filter(line => line.value.startsWith('STATUS:'));
129
+ if (controls.length > 1) error(`raw output must contain exactly one STATUS line; found ${controls.length}`);
130
+ if (controls.length === 1) {
131
+ const statusIndex = lines.indexOf(controls[0]);
132
+ const terminalIndex = lines.length - (strippedLabel ? 2 : 1);
133
+ if (statusIndex !== terminalIndex) error('raw STATUS must be terminal or immediately before the host label');
134
+ if (controls[0].value !== expectedStatus) error('raw terminal STATUS does not match the requested status');
135
+ if (strippedLabel && !controls[0].eol) error('host label must be on the line immediately after STATUS');
136
+ bodyEnd = controls[0].start;
137
+ }
138
+
139
+ const body = raw.slice(0, bodyEnd);
140
+ validateBody(body);
141
+ return { body, strippedLabel };
142
+ }
143
+
144
+ function assertDistinctFiles(input, output) {
145
+ const inputPath = path.resolve(input);
146
+ const outputPath = path.resolve(output);
147
+ if (inputPath === outputPath) error('output aliases an input file');
148
+
149
+ const inputStat = fs.statSync(inputPath);
150
+ try {
151
+ const outputStat = fs.statSync(outputPath);
152
+ if (inputStat.dev === outputStat.dev && inputStat.ino === outputStat.ino) error('output aliases an input file');
153
+ } catch (cause) {
154
+ if (cause.code !== 'ENOENT') throw cause;
155
+ try {
156
+ const candidate = path.join(fs.realpathSync(path.dirname(outputPath)), path.basename(outputPath));
157
+ if (candidate === fs.realpathSync(inputPath)) error('output aliases an input file');
158
+ } catch (parentError) {
159
+ if (parentError.code !== 'ENOENT') throw parentError;
160
+ }
161
+ }
162
+ }
163
+
164
+ function readText(file, description) {
165
+ try {
166
+ return fs.readFileSync(file, 'utf8');
167
+ } catch (cause) {
168
+ error(`cannot read ${description} ${file}: ${cause.message}`);
169
+ }
170
+ }
171
+
172
+ function reportBytes(body, statusLine) {
173
+ validateBody(body);
174
+ const newline = body.endsWith('\r\n') ? '\r\n' : '\n';
175
+ const separator = body === '' || body.endsWith('\n') ? '' : newline;
176
+ return Buffer.from(`${body}${separator}${statusLine}${newline}`, 'utf8');
177
+ }
178
+
179
+ function atomicWrite(output, bytes, expectedStatus) {
180
+ const directory = path.dirname(output);
181
+ const temp = path.join(directory, `.${path.basename(output)}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp`);
182
+ let descriptor;
183
+ let published = false;
184
+ try {
185
+ descriptor = fs.openSync(temp, 'wx', 0o666);
186
+ fs.writeFileSync(descriptor, bytes);
187
+ fs.closeSync(descriptor);
188
+ descriptor = undefined;
189
+
190
+ const staged = fs.readFileSync(temp);
191
+ if (!staged.equals(bytes)) error('staged report bytes differ from the intended report');
192
+ if (validateReport(staged.toString('utf8')) !== expectedStatus) error('staged report status differs from the requested status');
193
+
194
+ fs.renameSync(temp, output);
195
+ published = true;
196
+
197
+ const actual = fs.readFileSync(output);
198
+ if (!actual.equals(bytes)) error('published report bytes differ from the staged report');
199
+ if (validateReport(actual.toString('utf8')) !== expectedStatus) error('published report status differs from the requested status');
200
+ } catch (cause) {
201
+ if (descriptor !== undefined) {
202
+ try { fs.closeSync(descriptor); } catch {}
203
+ }
204
+ try { fs.unlinkSync(temp); } catch {}
205
+ if (published) error(`report was published but could not be verified; coordinator disposition required: ${cause.message}`);
206
+ error(`could not publish report before replacement: ${cause.message}`);
207
+ }
208
+ }
209
+
210
+ function write(args) {
211
+ const options = parseOptions(args, WRITE_OPTIONS, new Set(['--error']));
212
+ const output = path.resolve(required(options, '--output'));
213
+ const expectedStatus = statusFrom(options);
214
+ const modes = ['--body-file', '--context', '--from-codex-output'].filter(key => options.has(key));
215
+ if (modes.length !== 1) error('provide exactly one of --body-file, --context, or --from-codex-output');
216
+
217
+ let body;
218
+ let strippedLabel = false;
219
+ if (modes[0] === '--context') {
220
+ body = options.get('--context');
221
+ } else {
222
+ const input = required(options, modes[0]);
223
+ assertDistinctFiles(input, output);
224
+ const contents = readText(path.resolve(input), modes[0] === '--body-file' ? 'body file' : 'raw Codex output');
225
+ if (modes[0] === '--from-codex-output') {
226
+ const extracted = extractCodexBody(contents, expectedStatus);
227
+ body = extracted.body;
228
+ strippedLabel = extracted.strippedLabel;
229
+ } else {
230
+ body = contents;
231
+ }
232
+ }
233
+
234
+ validateBody(body);
235
+ const bytes = reportBytes(body, expectedStatus);
236
+ atomicWrite(output, bytes, expectedStatus);
237
+ if (strippedLabel) console.error('report-writer: stripped the terminal host label from raw Codex output');
238
+ console.log(`Wrote ${output}`);
239
+ }
240
+
241
+ function check(args) {
242
+ const options = parseOptions(args, new Set(['--file']));
243
+ if (options.size !== 1) error('check requires only --file <path>');
244
+ const file = path.resolve(required(options, '--file'));
245
+ const status = validateReport(readText(file, 'report'));
246
+ console.log(`${file}: valid (${status})`);
247
+ }
248
+
249
+ function main() {
250
+ try {
251
+ const [command, ...args] = process.argv.slice(2);
252
+ if (command === 'write') write(args);
253
+ else if (command === 'check') check(args);
254
+ else error(USAGE);
255
+ } catch (cause) {
256
+ console.error(`report-writer: ${cause.message}`);
257
+ process.exitCode = 1;
258
+ }
259
+ }
260
+
261
+ if (require.main === module) main();
@@ -3,7 +3,9 @@
3
3
 
4
4
  const fs = require('node:fs');
5
5
  const path = require('node:path');
6
+ const { isDeepStrictEqual } = require('node:util');
6
7
  const { STAGES, validateVersionManifest } = require('../harness-everything/scripts/system-one/manifest');
8
+ const { assertPrivateHistoryFile, appendPrivateHistory } = require('./system-one-cycle/common');
7
9
 
8
10
  const STAGE_SET = new Set(STAGES);
9
11
  const EPSILON = 1e-12;
@@ -139,7 +141,8 @@ function scoreRows(rows, stage, options, referenceOnly = []) {
139
141
  }
140
142
 
141
143
  function comparisonMetrics(metrics) {
142
- return { auc: coverageAccuracyAuc(metrics.coverageCurve), logLoss: metrics.logLoss, ece: metrics.ece };
144
+ return { auc: Number.isFinite(metrics.coverageAccuracyAuc)
145
+ ? metrics.coverageAccuracyAuc : coverageAccuracyAuc(metrics.coverageCurve), logLoss: metrics.logLoss, ece: metrics.ece };
143
146
  }
144
147
 
145
148
  function metricDeltas(current, previous) {
@@ -169,36 +172,153 @@ function assessFloor(holdout, history) {
169
172
  let baselineMissing = false;
170
173
  for (const [stage, metrics] of Object.entries(holdout)) {
171
174
  const current = comparisonMetrics(metrics);
172
- const previous = [...history].reverse().find(item => Number.isFinite(item.floor?.detail?.stages?.[stage]?.coverageAccuracyAuc));
173
- if (previous && !detail.baselineVersion) detail.baselineVersion = previous.version;
174
- const baseline = previous?.floor.detail.stages[stage];
175
- const prior = baseline && Number.isFinite(baseline.coverageAccuracyAuc)
176
- ? { auc: baseline.coverageAccuracyAuc, logLoss: baseline.logLoss, ece: baseline.ece } : null;
175
+ const baseline = baselineForStage(history, stage);
176
+ const prior = baseline?.metrics ? {
177
+ auc: baseline.metrics.coverageAccuracyAuc,
178
+ logLoss: baseline.metrics.logLoss,
179
+ ece: baseline.metrics.ece,
180
+ } : null;
177
181
  if (!prior) {
178
182
  baselineMissing = true;
179
- detail.stages[stage] = { coverageAccuracyAuc: current.auc, logLoss: current.logLoss, ece: current.ece, baselineAvailable: false };
183
+ detail.stages[stage] = { coverageAccuracyAuc: current.auc, logLoss: current.logLoss, ece: current.ece,
184
+ baselineAvailable: false, ...(baseline?.version ? { baselineVersion: baseline.version } : {}) };
180
185
  continue;
181
186
  }
187
+ detail.stages[stage] = { coverageAccuracyAuc: current.auc, logLoss: current.logLoss, ece: current.ece,
188
+ baselineAvailable: true, baselineVersion: baseline.version };
182
189
  const deltas = metricDeltas(current, prior);
183
190
  if (!noWorse(deltas)) oldHoldoutRegression = true;
184
- detail.stages[stage] = { coverageAccuracyAuc: current.auc, logLoss: current.logLoss, ece: current.ece, deltas, baselineAvailable: true };
191
+ detail.stages[stage].deltas = deltas;
192
+ }
193
+ const baselineVersions = Object.values(detail.stages).map(stage => stage.baselineVersion);
194
+ if (baselineVersions.length && baselineVersions.every(isText) && new Set(baselineVersions).size === 1) {
195
+ detail.baselineVersion = baselineVersions[0];
185
196
  }
186
197
  if (oldHoldoutRegression) detail.status = 'regression';
187
198
  else if (baselineMissing || Object.keys(holdout).length === 0) detail.status = 'baseline-unavailable';
188
199
  return { oldHoldoutRegression, detail };
189
200
  }
190
201
 
202
+ function floorMetrics(item, stage) {
203
+ const metrics = item?.floor?.detail?.stages?.[stage];
204
+ return metrics && [metrics.coverageAccuracyAuc, metrics.logLoss, metrics.ece].every(Number.isFinite) ? metrics : null;
205
+ }
206
+
207
+ function baselineForStage(history, stage) {
208
+ let version;
209
+ for (const item of history) {
210
+ const stageVersion = item.floor?.detail?.stages?.[stage]?.baselineVersion;
211
+ const legacyVersion = item.floor?.detail?.baselineVersion;
212
+ if (isText(stageVersion) || isText(legacyVersion)) {
213
+ version = isText(stageVersion) ? stageVersion : legacyVersion;
214
+ break;
215
+ }
216
+ }
217
+ if (version) {
218
+ const item = history.find(row => row.version === version);
219
+ return { version, metrics: floorMetrics(item, stage) };
220
+ }
221
+ const item = history.find(row => floorMetrics(row, stage));
222
+ return item ? { version: item.version, metrics: floorMetrics(item, stage) } : null;
223
+ }
224
+
191
225
  function readHistory(file) {
192
226
  if (!fs.existsSync(file)) return [];
193
227
  let lines;
194
228
  try { lines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(line => line.trim()); } catch (_) { fail(); }
195
229
  try {
196
230
  const history = lines.map(line => JSON.parse(line));
197
- if (history.some(item => !isObject(item) || item.schemaVersion !== 1 || !isText(item.version) || !isObject(item.stages))) fail();
231
+ const versions = new Set();
232
+ for (const item of history) {
233
+ validateCurveRecord(item);
234
+ if (versions.has(item.version)) fail();
235
+ versions.add(item.version);
236
+ }
198
237
  return history;
199
238
  } catch (_) { fail(); }
200
239
  }
201
240
 
241
+ function validateCurveRecord(curves) {
242
+ if (!isObject(curves) || curves.schemaVersion !== 1 || !isText(curves.version) || !isText(curves.createdAt)
243
+ || !isObject(curves.stages) || !Object.keys(curves.stages).length
244
+ || !isObject(curves.floor) || typeof curves.floor.oldHoldoutRegression !== 'boolean'
245
+ || !isObject(curves.floor.detail) || !isObject(curves.floor.detail.stages)
246
+ || !['unknown', 'checked', 'regression', 'baseline-unavailable'].includes(curves.floor.detail.status)
247
+ || (curves.floor.detail.baselineVersion !== null && curves.floor.detail.baselineVersion !== undefined
248
+ && !isText(curves.floor.detail.baselineVersion))) fail();
249
+ for (const [stage, metrics] of Object.entries(curves.stages)) {
250
+ if (!STAGE_SET.has(stage) || !isObject(metrics) || ![metrics.logLoss, metrics.brier, metrics.ece].every(Number.isFinite)
251
+ || !Array.isArray(metrics.coverageCurve) || metrics.coverageCurve.length !== 101
252
+ || metrics.coverageCurve.some(point => !Array.isArray(point) || point.length !== 3
253
+ || !Number.isFinite(point[0]) || point[0] < 0 || point[0] > 1
254
+ || !Number.isFinite(point[1]) || point[1] < 0 || point[1] > 1
255
+ || (point[2] !== null && (!Number.isFinite(point[2]) || point[2] < 0 || point[2] > 1)))) fail();
256
+ }
257
+ for (const [stage, metrics] of Object.entries(curves.floor.detail.stages)) {
258
+ if (!Object.hasOwn(curves.stages, stage) || !isObject(metrics)
259
+ || ![metrics.coverageAccuracyAuc, metrics.logLoss, metrics.ece].every(Number.isFinite)
260
+ || typeof metrics.baselineAvailable !== 'boolean'
261
+ || (metrics.baselineVersion !== undefined && !isText(metrics.baselineVersion))) fail();
262
+ if (metrics.baselineAvailable && (!isObject(metrics.deltas)
263
+ || !['auc', 'logLoss', 'ece'].every(key => Number.isFinite(metrics.deltas[key]))
264
+ || (!isText(metrics.baselineVersion) && !isText(curves.floor.detail.baselineVersion)))) fail();
265
+ }
266
+ }
267
+
268
+ function withoutCreatedAt(curves) {
269
+ const immutable = JSON.parse(JSON.stringify(curves));
270
+ delete immutable.createdAt;
271
+ for (const stage of Object.values(immutable.floor?.detail?.stages || {})) {
272
+ if (!isText(stage.baselineVersion) && isText(immutable.floor.detail.baselineVersion)) {
273
+ stage.baselineVersion = immutable.floor.detail.baselineVersion;
274
+ }
275
+ }
276
+ return immutable;
277
+ }
278
+
279
+ function assertVersionReusable(history, curves) {
280
+ const existing = history.find(item => item.version === curves.version);
281
+ if (existing && !isDeepStrictEqual(withoutCreatedAt(existing), withoutCreatedAt(curves))) fail();
282
+ return existing;
283
+ }
284
+
285
+ function validateSavedCurves(curves, version, manifest) {
286
+ validateCurveRecord(curves);
287
+ if (curves.version !== version || Object.keys(curves.stages).length !== Object.keys(manifest.stages).length
288
+ || Object.keys(curves.stages).some(stage => !Object.hasOwn(manifest.stages, stage))) fail();
289
+ }
290
+
291
+ function validateSavedTrend(trend, version) {
292
+ if (!isObject(trend) || !['promote', 'hold', 'rollback'].includes(trend.verdict)
293
+ || !Array.isArray(trend.compared) || trend.compared.some(version => !isText(version))
294
+ || !trend.compared.includes(version)
295
+ || !Array.isArray(trend.reasons) || trend.reasons.some(reason => !isText(reason))) fail();
296
+ }
297
+
298
+ function validateBaselineReferences(curves, history) {
299
+ for (const [stage, baseline] of Object.entries(curves.floor.detail.stages)) {
300
+ if (baseline.baselineAvailable !== true) continue;
301
+ const baselineVersion = isText(baseline.baselineVersion) ? baseline.baselineVersion : curves.floor.detail.baselineVersion;
302
+ if (!isText(baselineVersion) || !floorMetrics(history.find(row => row.version === baselineVersion), stage)) fail();
303
+ }
304
+ }
305
+
306
+ function validateResumeDecision(curves, trend, history) {
307
+ const candidateIndex = history.findIndex(row => row.version === curves.version);
308
+ const predecessor = candidateIndex < 0 ? history : history.slice(0, candidateIndex);
309
+ const compared = [...predecessor.slice(-3).map(row => row.version), curves.version];
310
+ if (!isDeepStrictEqual(trend.compared, compared)) fail();
311
+
312
+ const holdout = Object.keys(curves.floor.detail.stages).length ? curves.floor.detail.stages : null;
313
+ const floor = assessFloor(holdout, predecessor);
314
+ if (!isDeepStrictEqual(curves.floor, floor) || !isDeepStrictEqual(trend, decideTrend(curves, predecessor, floor))) fail();
315
+ }
316
+
317
+ function appendHistoryRow(file, history, curves) {
318
+ if (assertVersionReusable(history, curves)) return;
319
+ appendPrivateHistory(file, `${JSON.stringify(curves)}\n`);
320
+ }
321
+
202
322
  function worseningCycles(history, stages) {
203
323
  if (history.length < 3) return null;
204
324
  // shortcut: history has no active-version field, so its latest three records stand in for the active trend; upgrade when the shared schema records active identity.
@@ -268,7 +388,8 @@ function stageFiles(args, option) {
268
388
 
269
389
  function parseArgs(argv) {
270
390
  const parsed = { val: [], holdout: [] };
271
- const names = { '--version': 'version', '--version-dir': 'versionDir', '--val-scores': 'val', '--holdout-scores': 'holdout', '--history': 'history', '--out': 'out' };
391
+ const names = { '--version': 'version', '--version-dir': 'versionDir', '--val-scores': 'val', '--holdout-scores': 'holdout',
392
+ '--history': 'history', '--out': 'out', '--resume-curves': 'resumeCurves' };
272
393
  for (let i = 0; i < argv.length; i++) {
273
394
  const key = names[argv[i]]; const value = argv[++i];
274
395
  if (!key || value === undefined) fail();
@@ -276,13 +397,32 @@ function parseArgs(argv) {
276
397
  else if (Object.hasOwn(parsed, key)) fail();
277
398
  else parsed[key] = value;
278
399
  }
279
- if (!isText(parsed.version) || !isText(parsed.versionDir) || !parsed.val.length || !isText(parsed.history) || !isText(parsed.out)) fail();
400
+ if (!isText(parsed.version) || !isText(parsed.versionDir) || !isText(parsed.history) || !isText(parsed.out)) fail();
401
+ if (parsed.resumeCurves) {
402
+ if (!isText(parsed.resumeCurves) || parsed.val.length || parsed.holdout.length) fail();
403
+ } else if (!parsed.val.length) fail();
280
404
  return parsed;
281
405
  }
282
406
 
283
407
  function run(argv) {
284
408
  const args = parseArgs(argv);
409
+ args.history = assertPrivateHistoryFile(args.history);
285
410
  const manifest = readManifest(args.versionDir, args.version);
411
+ if (args.resumeCurves) {
412
+ let curves; let trend;
413
+ try {
414
+ curves = JSON.parse(fs.readFileSync(args.resumeCurves, 'utf8'));
415
+ trend = JSON.parse(fs.readFileSync(path.join(args.out, 'trend.json'), 'utf8'));
416
+ } catch (_) { fail(); }
417
+ validateSavedCurves(curves, args.version, manifest);
418
+ validateSavedTrend(trend, args.version);
419
+ const history = readHistory(args.history);
420
+ validateBaselineReferences(curves, history);
421
+ validateResumeDecision(curves, trend, history);
422
+ appendHistoryRow(args.history, history, curves);
423
+ console.log(JSON.stringify({ resumed: true, version: args.version }));
424
+ return { curves, trend };
425
+ }
286
426
  const valFiles = stageFiles(args, 'val');
287
427
  const holdoutFiles = stageFiles(args, 'holdout');
288
428
  if (Object.keys(holdoutFiles).some(stage => !Object.hasOwn(valFiles, stage))) fail();
@@ -304,13 +444,13 @@ function run(argv) {
304
444
  const history = readHistory(args.history);
305
445
  const floor = assessFloor(Object.keys(holdoutMetrics).length ? holdoutMetrics : null, history);
306
446
  const curves = { schemaVersion: 1, version: args.version, createdAt: new Date().toISOString(), stages, floor };
447
+ const existing = assertVersionReusable(history, curves);
448
+ validateBaselineReferences(curves, history);
307
449
  const trend = decideTrend(curves, history, floor);
308
450
  fs.mkdirSync(args.out, { recursive: true });
309
- fs.mkdirSync(path.dirname(args.history), { recursive: true });
310
451
  fs.writeFileSync(path.join(args.out, 'curves.json'), `${JSON.stringify(curves, null, 2)}\n`);
311
452
  fs.writeFileSync(path.join(args.out, 'trend.json'), `${JSON.stringify(trend, null, 2)}\n`);
312
- const oldHistory = fs.existsSync(args.history) ? fs.readFileSync(args.history, 'utf8') : '';
313
- fs.appendFileSync(args.history, `${oldHistory && !oldHistory.endsWith('\n') ? '\n' : ''}${JSON.stringify(curves)}\n`);
453
+ if (!existing) appendHistoryRow(args.history, history, curves);
314
454
  const summary = Object.fromEntries(Object.entries(stages).map(([stage, value]) => [stage, {
315
455
  rows: readJsonl(valFiles[stage]).length,
316
456
  logLoss: value.logLoss,
@@ -3,6 +3,8 @@
3
3
  const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
  const { REPO, readJsonl, writeJsonl, writeJson, runNode, assertPrivateDataDir } = require('./common');
6
+ const observations = require('../../hooks/scripts/lib/observations');
7
+ const { importStore } = require('../system-one-observations-import-store');
6
8
 
7
9
  function collect({ dataDir, since, sessionsDir }) {
8
10
  const privateDir = assertPrivateDataDir(dataDir);
@@ -14,7 +16,21 @@ function collect({ dataDir, since, sessionsDir }) {
14
16
  const exporter = path.join(REPO, 'scripts', 'system-one-observations-export.js');
15
17
  const importArgs = ['--store', store, '--since', since];
16
18
  if (sessionsDir) importArgs.push('--sessions', sessionsDir);
17
- runNode(importer, importArgs);
19
+ const importStartedAt = new Date().toISOString();
20
+ let codexStatus = 'ok';
21
+ try { runNode(importer, importArgs); }
22
+ catch { codexStatus = 'error'; }
23
+ const live = importStore({ sourceRoot: observations.storeRoot(), store, since });
24
+ const importReportFile = path.join(observed, 'import-report.json');
25
+ writeJson(importReportFile, {
26
+ schemaVersion: 1,
27
+ run: { startedAt: importStartedAt },
28
+ sources: { live: live.source, codex: { status: codexStatus } },
29
+ byHost: live.byHost,
30
+ });
31
+ if (codexStatus !== 'ok' || live.source.status === 'error') {
32
+ throw new Error('observation import incomplete; see import-report.json');
33
+ }
18
34
  runNode(exporter, ['--store', store, '--out', observed, '--self-report-only', '--since', since]);
19
35
 
20
36
  const promptsFile = path.join(observed, 'prompts-observed.jsonl');
@@ -29,6 +45,7 @@ function collect({ dataDir, since, sessionsDir }) {
29
45
  id: row.id,
30
46
  tier: row.tier ?? null,
31
47
  intents: Array.isArray(row.intents) ? row.intents : [],
48
+ host: row.host ?? null,
32
49
  behaviorEvidence: row.behaviorEvidence || 'unobserved',
33
50
  contradictions: Array.isArray(row.contradictions) ? row.contradictions : [],
34
51
  }));
@@ -37,11 +54,11 @@ function collect({ dataDir, since, sessionsDir }) {
37
54
  const exportReportFile = path.join(observed, 'export-report.json');
38
55
  const exported = JSON.parse(fs.readFileSync(exportReportFile, 'utf8'));
39
56
  writeJson(exportReportFile, Object.fromEntries(['schemaVersion', 'records', 'exported', 'skippedBeforeSince', 'skippedUnlabeled',
40
- 'skippedNoText', 'validationRows', 'withSelfReport'].filter(key => Object.hasOwn(exported, key)).map(key => [key, exported[key]])));
57
+ 'skippedNoText', 'validationRows', 'withSelfReport', 'hostAcceptance'].filter(key => Object.hasOwn(exported, key)).map(key => [key, exported[key]])));
41
58
  for (const dir of [training, path.dirname(store), store, observed]) {
42
59
  try { fs.chmodSync(dir, 0o700); } catch { /* Windows does not expose POSIX modes. */ }
43
60
  }
44
- for (const file of [promptsFile, labelsFile, path.join(observed, 'export-report.json')]) {
61
+ for (const file of [promptsFile, labelsFile, path.join(observed, 'export-report.json'), importReportFile]) {
45
62
  try { if (fs.existsSync(file)) fs.chmodSync(file, 0o600); } catch { /* Windows does not expose POSIX modes. */ }
46
63
  }
47
64
  return { prompts: prompts.length, selfLabels: labels.length, since };
@@ -127,11 +127,49 @@ function assertPrivateDataDir(dataDir, { allowSyntheticBuildRoot = false, create
127
127
  return target;
128
128
  }
129
129
 
130
+ function assertPrivateHistoryFile(file) {
131
+ if (typeof file !== 'string' || !file.trim()) throw new Error('private history path must be nonempty');
132
+ let target;
133
+ try { target = canonicalDestination(file); }
134
+ catch { throw new Error('invalid private history path'); }
135
+ const repo = fs.realpathSync.native(REPO);
136
+ if (isWithin(repo, target)) throw new Error('private history must be stored outside the repository');
137
+ try {
138
+ if (!fs.statSync(target).isFile()) throw new Error('private history path must name a file');
139
+ } catch (error) {
140
+ if (error.code !== 'ENOENT') throw error;
141
+ }
142
+ return target;
143
+ }
144
+
145
+ function appendPrivateHistory(file, text) {
146
+ const target = assertPrivateHistoryFile(file);
147
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
148
+ let separator = '';
149
+ try {
150
+ const fd = fs.openSync(assertPrivateHistoryFile(target), 'r');
151
+ try {
152
+ const size = fs.fstatSync(fd).size;
153
+ if (size) {
154
+ const lastByte = Buffer.alloc(1);
155
+ fs.readSync(fd, lastByte, 0, 1, size - 1);
156
+ if (lastByte[0] !== 0x0a) separator = '\n';
157
+ }
158
+ } finally {
159
+ fs.closeSync(fd);
160
+ }
161
+ } catch (error) {
162
+ if (error.code !== 'ENOENT') throw error;
163
+ }
164
+ fs.appendFileSync(assertPrivateHistoryFile(target), `${separator}${text}`, { encoding: 'utf8', mode: 0o600 });
165
+ }
166
+
130
167
  function resultSummary(step, details) {
131
168
  return { step, ...details };
132
169
  }
133
170
 
134
171
  module.exports = {
135
172
  REPO, STEPS, readJsonl, writeJsonl, writeJson, parseFlags, flag, required, dataPath,
136
- readState, stepComplete, markStep, runNode, assertPrivateDataDir, isSyntheticBuildDataDir, resultSummary,
173
+ readState, stepComplete, markStep, runNode, assertPrivateDataDir, assertPrivateHistoryFile,
174
+ appendPrivateHistory, isSyntheticBuildDataDir, resultSummary,
137
175
  };
@@ -3,7 +3,7 @@
3
3
  const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
  const { spawnSync } = require('node:child_process');
6
- const { REPO, dataPath, writeJson, assertPrivateDataDir } = require('./common');
6
+ const { REPO, dataPath, writeJson, assertPrivateDataDir, assertPrivateHistoryFile } = require('./common');
7
7
  const { buildVersion } = require('./package');
8
8
  const { TASKS } = require('./train');
9
9
  const { validateVersionManifest } = require('../../harness-everything/scripts/system-one/manifest');
@@ -29,21 +29,25 @@ function recordEvaluation(manifestFile, version) {
29
29
  return manifest;
30
30
  }
31
31
 
32
- function evaluateCycle({ dataDir, version }) {
32
+ function evaluateCycle({ dataDir, version, history: historyOption }) {
33
33
  const privateDir = assertPrivateDataDir(dataDir);
34
+ const history = assertPrivateHistoryFile(historyOption === undefined
35
+ ? dataPath(privateDir, 'training', 'history.jsonl') : historyOption);
34
36
  const source = dataPath(privateDir, 'training', 'runs', version);
35
37
  const versionDir = dataPath(privateDir, 'training', 'candidates', version);
36
38
  const evaluationDir = path.join(versionDir, 'evaluation');
37
39
  const curvesFile = path.join(evaluationDir, 'curves.json');
38
40
  const trendFile = path.join(evaluationDir, 'trend.json');
41
+ const curvesScript = path.join(REPO, 'scripts', 'system-one-curves.js');
42
+ if (!fs.existsSync(curvesScript)) throw new Error('contract C curves CLI is not available in this checkout');
39
43
  if (fs.existsSync(curvesFile) && fs.existsSync(trendFile)) {
44
+ runProcess(process.execPath, [curvesScript, '--version', version, '--version-dir', versionDir,
45
+ '--history', history, '--out', evaluationDir, '--resume-curves', curvesFile]);
40
46
  const manifestFile = path.join(versionDir, 'manifest.json');
41
47
  recordEvaluation(manifestFile, version);
42
48
  const trend = JSON.parse(fs.readFileSync(trendFile, 'utf8'));
43
49
  return { version, verdict: trend.verdict, compared: trend.compared.length, resumed: true };
44
50
  }
45
- const curvesScript = path.join(REPO, 'scripts', 'system-one-curves.js');
46
- if (!fs.existsSync(curvesScript)) throw new Error('contract C curves CLI is not available in this checkout');
47
51
  buildVersion({ dataDir: privateDir, version, sourceDir: source, versionDir });
48
52
 
49
53
  fs.mkdirSync(evaluationDir, { recursive: true, mode: 0o700 });
@@ -57,7 +61,6 @@ function evaluateCycle({ dataDir, version }) {
57
61
  curvesArgs.push('--val-scores', `${task}=${path.join(source, task, 'val-scores.jsonl')}`);
58
62
  curvesArgs.push('--holdout-scores', `${task}=${scores}`);
59
63
  }
60
- const history = dataPath(privateDir, 'training', 'history.jsonl');
61
64
  curvesArgs.push('--history', history, '--out', evaluationDir);
62
65
  runProcess(process.execPath, [curvesScript, ...curvesArgs]);
63
66