harness-everything 0.52.0 → 0.53.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 (34) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +20 -0
  4. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md +7 -0
  5. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-probe.js +16 -0
  6. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-trace-2026-11-15.jsonl +4 -0
  7. package/ci/mechanism-2n-opencode-plugin.test.js +1 -1
  8. package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +18 -3
  9. package/ci/mechanism-338-opencode-async.test.js +20 -3
  10. package/ci/mechanism-341-opencode-lane.test.js +7 -1
  11. package/ci/mechanism-397-cycle-import.test.js +399 -0
  12. package/ci/mechanism-397-host-acceptance.test.js +119 -0
  13. package/ci/mechanism-397-opencode-observations.test.js +1922 -0
  14. package/ci/mechanism-system-one-curves.test.js +17 -0
  15. package/ci/mechanism-system-one-cycle.test.js +621 -2
  16. package/docs/platform-capabilities.md +13 -6
  17. package/docs/system-one-cycle.md +12 -3
  18. package/docs/system-one-observations.md +35 -4
  19. package/hooks/scripts/lib/observations.js +5 -3
  20. package/opencode-plugin/README.md +22 -8
  21. package/opencode-plugin/index.mjs +424 -44
  22. package/opencode-plugin/plugin.json +1 -1
  23. package/package.json +1 -1
  24. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  25. package/plugins/harness-everything/hooks/scripts/lib/observations.js +5 -3
  26. package/plugins/harness-everything/plugin.json +1 -1
  27. package/sbom.cdx.json +7 -7
  28. package/scripts/system-one-curves.js +154 -14
  29. package/scripts/system-one-cycle/collect.js +20 -3
  30. package/scripts/system-one-cycle/common.js +39 -1
  31. package/scripts/system-one-cycle/evaluate.js +8 -5
  32. package/scripts/system-one-cycle.js +7 -2
  33. package/scripts/system-one-observations-export.js +29 -0
  34. package/scripts/system-one-observations-import-store.js +128 -0
@@ -10,7 +10,7 @@
10
10
  "name": "harness-everything",
11
11
  "source": "./",
12
12
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
13
- "version": "0.52.0",
13
+ "version": "0.53.0",
14
14
  "author": {
15
15
  "name": "Miya Daniel"
16
16
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-everything",
3
3
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
4
- "version": "0.52.0",
4
+ "version": "0.53.0",
5
5
  "author": {
6
6
  "name": "Miya Daniel"
7
7
  },
package/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [0.53.0](https://github.com/dyphn1/Harness-everything/compare/v0.52.0...v0.53.0) (2026-11-18)
6
+
7
+ ### Features
8
+
9
+ * **observations:** inject the label contract and record opencode turns ([2fa9d6d](https://github.com/dyphn1/Harness-everything/commit/2fa9d6d4c516c858c763a9a6a5110edf778f5019))
10
+ * **system-one:** import live observations into the cycle store ([aa8af52](https://github.com/dyphn1/Harness-everything/commit/aa8af5256efef61807f6b7927b43927f0b4abaf5))
11
+ * **system-one:** report per-host label acceptance before filtering ([63c817b](https://github.com/dyphn1/Harness-everything/commit/63c817b5e9c8481df1da7206e37673f45275ef8e))
12
+
13
+ ### Bug Fixes
14
+
15
+ * **opencode:** bind each prompt to its session workspace ([861e55e](https://github.com/dyphn1/Harness-everything/commit/861e55ec1627a41b31c6139c6e7ba7b53ef3bb7d))
16
+ * **opencode:** close the observation turn on v2 execution events ([9051c28](https://github.com/dyphn1/Harness-everything/commit/9051c28e2818aa6826e483e0edb4e458c94a4871))
17
+ * **opencode:** read the final reply from the v2 session context ([fb24958](https://github.com/dyphn1/Harness-everything/commit/fb2495817e27f596aa4001ff3a99f97c7d021588))
18
+ * **opencode:** run the router with node inside the bun host ([f7addfc](https://github.com/dyphn1/Harness-everything/commit/f7addfc0290af7622a1e30560b1ea746bb77cd10))
19
+ * **opencode:** settle disposal while completion context is pending ([554b812](https://github.com/dyphn1/Harness-everything/commit/554b81232854b67e3abf4d85a217d8e0277753c3)), closes [#448](https://github.com/dyphn1/Harness-everything/issues/448)
20
+ * **opencode:** stop publishing state after plugin disposal ([a0f8204](https://github.com/dyphn1/Harness-everything/commit/a0f8204a9a70834c990284c9ba5f49652553ec6d)), closes [#448](https://github.com/dyphn1/Harness-everything/issues/448)
21
+ * **opencode:** translate v2 lifecycle events and guard stale bindings ([5371ead](https://github.com/dyphn1/Harness-everything/commit/5371ead206de2622dcb7616380be48855cf3e493))
22
+ * **system-one:** keep cross-month cycle history for trend decisions ([e918e45](https://github.com/dyphn1/Harness-everything/commit/e918e455c47ad53940d8f6c22cb37e9ec0d28d20)), closes [#443](https://github.com/dyphn1/Harness-everything/issues/443) [#446](https://github.com/dyphn1/Harness-everything/issues/446)
23
+ * **system-one:** reject incompatible history on cycle resume ([e6af72f](https://github.com/dyphn1/Harness-everything/commit/e6af72f87cfb552d6683fde9683677f41ae2e892)), closes [#446](https://github.com/dyphn1/Harness-everything/issues/446)
24
+
5
25
  ## [0.52.0](https://github.com/dyphn1/Harness-everything/compare/v0.51.0...v0.52.0) (2026-11-15)
6
26
 
7
27
  ### Features
@@ -0,0 +1,7 @@
1
+ # OpenCode session workspace field trace
2
+
3
+ **Observed:** OpenCode 2.1.4 on macOS, 2026-11-15. One server process handled sessions from two workspaces.
4
+
5
+ The retained [probe](live-workspace-probe.js) logged setup and prompt field shapes to [JSONL](live-workspace-trace-2026-11-15.jsonl). Setup exposed `ctx.location.directory`; prompt events exposed `sessionID`, `messageID`, `prompt`, `metadata`, and `delivery`, with no event location. For each prompt, `ctx.session.get({sessionID})` returned a session whose `location.directory` matched that session's setup workspace. The server process cwd was a different directory.
6
+
7
+ This trace establishes that the session lookup and directory field were available in these two runs. Both setup locations already matched their session directories, so the trace does not establish behavior for a setup/session mismatch, missing setup location, failed lookup, or V2 router/tool/completion hook firing. It is not a live reproduction of the workspace attribution defect or verification of the fix. The cross-workspace counterexample and fix are covered by the deterministic V2 default-export test `ci/mechanism-397-opencode-observations.test.js`.
@@ -0,0 +1,16 @@
1
+ import { appendFileSync } from "node:fs"
2
+ import { basename } from "node:path"
3
+ const log = o => appendFileSync(process.env.PROBE_TRACE || "trace.jsonl", JSON.stringify(o) + "\n")
4
+ const shape = v => v && typeof v === "object" ? Object.keys(v) : typeof v
5
+ export default {
6
+ id: "probe.workspace",
7
+ async setup(ctx) {
8
+ const id = Math.random().toString(36).slice(2, 8)
9
+ log({ ev: "setup", id, ctxKeys: Object.keys(ctx), location: ctx.location && { keys: Object.keys(ctx.location), dir: ctx.location.directory && basename(ctx.location.directory) }, directory: ctx.directory && basename(ctx.directory), cwd: basename(process.cwd()) })
10
+ await ctx.session.hook("prompt", async event => {
11
+ let info = null
12
+ try { const s = await ctx.session.get({ sessionID: event.sessionID }); info = { keys: shape(s), dir: s && (s.directory || s.location?.directory) ? basename(s.directory || s.location.directory) : null, location: shape(s?.location) } } catch (e) { info = { error: String(e).slice(0, 80) } }
13
+ log({ ev: "prompt", id, eventKeys: Object.keys(event), eventLocation: shape(event.location), session: info })
14
+ })
15
+ },
16
+ }
@@ -0,0 +1,4 @@
1
+ {"ev":"setup","id":"97zahz","ctxKeys":["app","location","options","agent","aisdk","command","credential","event","experimental","generate","model","provider","integration","mcp","permission","plugin","reference","rpc","skill","storage","tool","vcs","websearch","worktree","session","shell"],"location":{"keys":["directory","workspaceID","project"],"dir":"wsA"},"cwd":"probe"}
2
+ {"ev":"prompt","id":"97zahz","eventKeys":["sessionID","messageID","prompt","metadata","delivery"],"eventLocation":"undefined","session":{"keys":["id","projectID","model","cost","tokens","time","location"],"dir":"wsA","location":["directory"]}}
3
+ {"ev":"setup","id":"xlcnsl","ctxKeys":["app","location","options","agent","aisdk","command","credential","event","experimental","generate","model","provider","integration","mcp","permission","plugin","reference","rpc","skill","storage","tool","vcs","websearch","worktree","session","shell"],"location":{"keys":["directory","workspaceID","project"],"dir":"wsB"},"cwd":"probe"}
4
+ {"ev":"prompt","id":"xlcnsl","eventKeys":["sessionID","messageID","prompt","metadata","delivery"],"eventLocation":"undefined","session":{"keys":["id","projectID","model","cost","tokens","time","location"],"dir":"wsB","location":["directory"]}}
@@ -42,7 +42,7 @@ if (fs.existsSync(pluginManifestFile)) {
42
42
  }
43
43
 
44
44
  helper.check(
45
- '2n. the plugin ships as a single self-contained module (installable by copying one file)',
45
+ '2n. the V1 enforcement factory remains in the plugin entrypoint',
46
46
  fs.existsSync(pluginFile) && !/require\(['"]\.\//.test(fs.readFileSync(pluginFile, 'utf8')),
47
47
  `${pluginFile} missing or imports a sibling file`
48
48
  );
@@ -12,9 +12,11 @@ console.log('\n[2p] opencode 2.x default-export entrypoint: registration and fir
12
12
  // V2 adapter that the real host actually loads.
13
13
 
14
14
  helper.check(
15
- '2p. the plugin ships as a single self-contained module',
16
- fs.existsSync(path.join(helper.root, 'opencode-plugin', 'index.mjs')),
17
- 'index.mjs missing'
15
+ '2p. the plugin entrypoint resolves the canonical router and observations runtime from the source checkout',
16
+ fs.existsSync(path.join(helper.root, 'opencode-plugin', 'index.mjs'))
17
+ && fs.existsSync(path.join(helper.root, 'harness-everything', 'scripts', 'kernel-router.js'))
18
+ && fs.existsSync(path.join(helper.root, 'hooks', 'scripts', 'lib', 'observations.js')),
19
+ 'plugin entrypoint or shared runtime missing'
18
20
  );
19
21
 
20
22
  (async () => {
@@ -41,6 +43,7 @@ helper.check(
41
43
 
42
44
  const prompts = [];
43
45
  const registered = [];
46
+ const sessionHooks = [];
44
47
  let subscribeCount = 0;
45
48
  const eventQueue = [];
46
49
  const fakeCtx = {
@@ -52,10 +55,16 @@ helper.check(
52
55
  },
53
56
  },
54
57
  session: {
58
+ get: async ({ sessionID }) => ({ id: sessionID, location: { directory: workspace } }),
55
59
  prompt: async (input) => {
56
60
  prompts.push(input);
57
61
  return {};
58
62
  },
63
+ hook: async (name, callback) => {
64
+ sessionHooks.push({ name, callback });
65
+ return { dispose: async () => {} };
66
+ },
67
+ context: async () => [],
59
68
  },
60
69
  event: {
61
70
  subscribe: (options) => {
@@ -108,6 +117,12 @@ helper.check(
108
117
  JSON.stringify(registered.map((r) => r.name))
109
118
  );
110
119
 
120
+ helper.check(
121
+ '2p. setup registers documented prompt admission and model context hooks',
122
+ sessionHooks.some((r) => r.name === 'prompt') && sessionHooks.some((r) => r.name === 'context'),
123
+ JSON.stringify(sessionHooks.map((r) => r.name))
124
+ );
125
+
111
126
  helper.check('2p. setup subscribes to the event stream exactly once', subscribeCount === 1, `subscribes: ${subscribeCount}`);
112
127
 
113
128
  const before = registered.find((r) => r.name === 'execute.before').callback;
@@ -161,11 +161,16 @@ const helper = require('./test-helper');
161
161
 
162
162
  // The V2 adapter must keep consuming reset/delete events while idle
163
163
  // verification is pending, and its disposer must await child cleanup.
164
- const queue = [], registrations = new Map();
164
+ const queue = [], registrations = new Map(), sessionHooks = new Map();
165
165
  const dispose = await mod.default.setup({
166
166
  location: { directory: workspace },
167
167
  tool: { hook: async (name, callback) => { registrations.set(name, callback); } },
168
- session: { prompt: async value => { prompts.push(value.text); } },
168
+ session: {
169
+ get: async ({ sessionID }) => ({ id: sessionID, location: { directory: workspace } }),
170
+ hook: async (name, callback) => { sessionHooks.set(name, callback); return { dispose: async () => {} }; },
171
+ prompt: async value => { prompts.push(value.text); },
172
+ context: async () => [],
173
+ },
169
174
  event: { subscribe: async function* ({ signal }) {
170
175
  while (!signal.aborted) {
171
176
  if (queue.length) yield queue.shift();
@@ -196,9 +201,21 @@ const helper = require('./test-helper');
196
201
  queue.push({ type: 'session.idle', sessionID: 'v2-disposed' });
197
202
  await waitFor(() => fs.existsSync(v2Ready));
198
203
  await dispose();
204
+ const v2DisposedDir = path.join(sessions, 'v2-disposed');
205
+ const disposeStateFiles = ['edit-state.json', 'circuit-breaker.json', 'compliance.json']
206
+ .map(name => path.join(v2DisposedDir, name));
207
+ const stateAtDispose = disposeStateFiles.map(file => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null);
199
208
  const stopped = fs.statSync(v2Heartbeat).size;
200
209
  await new Promise(resolve => setTimeout(resolve, 150));
201
- helper.check('338. V2 disposal waits for active child cleanup without a stale follow-up', fs.statSync(v2Heartbeat).size === stopped && prompts.length === beforeConcurrent);
210
+ const stateStable = disposeStateFiles.every((file, index) =>
211
+ (fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null) === stateAtDispose[index]);
212
+ const editAtDispose = JSON.parse(stateAtDispose[0]);
213
+ const complianceAtDispose = JSON.parse(stateAtDispose[2]);
214
+ helper.check('338. V2 disposal waits for active child cleanup without late follow-up, breaker, or compliance writes',
215
+ fs.statSync(v2Heartbeat).size === stopped && prompts.length === beforeConcurrent && stateStable
216
+ && editAtDispose.verificationPending === true && editAtDispose.followUpPending === false
217
+ && complianceAtDispose.verifiedEdits === 0 && complianceAtDispose.circuitBreakerTrips === 0,
218
+ JSON.stringify({ stateStable, editAtDispose, complianceAtDispose, prompts: prompts.length - beforeConcurrent }));
202
219
  // A new idle can arrive while an edit-cancelled child is still being reaped.
203
220
  // That idle must verify the newer revision after cleanup, rather than vanish.
204
221
  fs.unlinkSync(path.join(workspace, 'ready.txt'));
@@ -143,11 +143,17 @@ function createEventStream() {
143
143
  async function startPlugin(workspace) {
144
144
  const plugin = await import(pathToFileURL(path.join(ROOT, 'opencode-plugin/index.mjs')).href);
145
145
  const registered = new Map();
146
+ const sessionHooks = new Map();
146
147
  const stream = createEventStream();
147
148
  const dispose = await plugin.default.setup({
148
149
  location: { directory: workspace },
149
150
  tool: { hook: async (name, callback) => registered.set(name, callback) },
150
- session: { prompt: async () => ({}) },
151
+ session: {
152
+ get: async ({ sessionID }) => ({ id: sessionID, location: { directory: workspace } }),
153
+ hook: async (name, callback) => { sessionHooks.set(name, callback); return { dispose: async () => {} }; },
154
+ prompt: async () => ({}),
155
+ context: async () => [],
156
+ },
151
157
  event: { subscribe: ({ signal }) => stream.subscribe(signal) },
152
158
  });
153
159
  return { registered, stream, dispose };
@@ -0,0 +1,399 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { pathToFileURL } = require('node:url');
8
+ const { test } = require('node:test');
9
+ const { collect } = require('../scripts/system-one-cycle/collect');
10
+ const { importStore } = require('../scripts/system-one-observations-import-store');
11
+ const observations = require('../hooks/scripts/lib/observations');
12
+
13
+ const ROOT = path.resolve(__dirname, '..');
14
+ const PLUGIN = path.join(ROOT, 'opencode-plugin', 'index.mjs');
15
+ function isOutside(root, dir, pathApi = path) {
16
+ const relative = pathApi.relative(root, dir);
17
+ return relative.startsWith('..') || pathApi.isAbsolute(relative);
18
+ }
19
+
20
+ const win32Root = 'D:\\a\\Harness-everything\\Harness-everything';
21
+ assert.equal(isOutside(win32Root, 'C:\\Users\\runner\\AppData\\Local\\Temp\\fixture', path.win32), true, 'cross-drive temp path is outside the repository');
22
+ assert.equal(isOutside(win32Root, path.win32.join(win32Root, 'ci'), path.win32), false, 'same-drive child is inside the repository');
23
+
24
+ const LABELS = [
25
+ '<!-- harness-label {"v":1,"validity":"actionable","tier":"tier2","intents":["fix"],"workflow":"iterative-single","skills":[]} -->',
26
+ '<!-- harness-label {"v":1,"validity":"actionable","tier":"tier2","intents":["edit"],"workflow":"iterative-single","skills":[]} -->',
27
+ ];
28
+
29
+ function recordList(store) {
30
+ const file = path.join(store, 'observations-index.json');
31
+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')).records : [];
32
+ }
33
+
34
+ function fixture() {
35
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mechanism-397-cycle-import-'));
36
+ assert.ok(isOutside(ROOT, dir), 'fixture data must stay outside the repository');
37
+ const workspace = path.join(dir, 'workspace');
38
+ const store = path.join(dir, 'live-observations');
39
+ const sessions = path.join(dir, 'codex-sessions');
40
+ const cycle = path.join(dir, 'cycle');
41
+ fs.mkdirSync(workspace, { recursive: true });
42
+ fs.mkdirSync(sessions, { recursive: true });
43
+
44
+ const envKeys = ['HOME', 'USERPROFILE', 'CODEX_HOME', 'HARNESS_STATE_HOME', 'HARNESS_OBSERVATIONS_DIR', 'HARNESS_OBSERVATIONS', 'HARNESS_DOC_RECONCILIATION_PILOT'];
45
+ const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]));
46
+ process.env.HOME = dir;
47
+ process.env.USERPROFILE = dir;
48
+ process.env.CODEX_HOME = path.join(dir, 'codex-home');
49
+ process.env.HARNESS_STATE_HOME = path.join(dir, 'harness-state');
50
+ process.env.HARNESS_OBSERVATIONS_DIR = store;
51
+ process.env.HARNESS_OBSERVATIONS = 'on';
52
+ process.env.HARNESS_DOC_RECONCILIATION_PILOT = '0';
53
+
54
+ const sessionHooks = new Map();
55
+ const toolHooks = new Map();
56
+ const events = [];
57
+ const waiters = [];
58
+ let currentTurn = { messageID: null, prompt: '', final: '' };
59
+ const ctx = {
60
+ location: { directory: workspace },
61
+ session: {
62
+ hook: async (name, callback) => {
63
+ sessionHooks.set(name, callback);
64
+ return { dispose: async () => {} };
65
+ },
66
+ prompt: async () => ({}),
67
+ get: async ({ sessionID }) => ({ id: sessionID, location: { directory: workspace } }),
68
+ context: async () => [
69
+ { info: { role: 'user', id: currentTurn.messageID }, parts: [{ type: 'text', text: currentTurn.prompt }] },
70
+ { info: { role: 'assistant', id: `assistant-${currentTurn.messageID}` }, parts: [{ type: 'text', text: currentTurn.final }] },
71
+ ],
72
+ },
73
+ tool: { hook: async (name, callback) => { toolHooks.set(name, callback); return { dispose: async () => {} }; } },
74
+ event: {
75
+ subscribe: ({ signal }) => ({
76
+ [Symbol.asyncIterator]: () => ({
77
+ next: () => {
78
+ if (events.length) return Promise.resolve({ value: events.shift(), done: false });
79
+ if (signal.aborted) return Promise.resolve({ done: true });
80
+ return new Promise(resolve => {
81
+ waiters.push(resolve);
82
+ signal.addEventListener('abort', () => resolve({ done: true }), { once: true });
83
+ });
84
+ },
85
+ }),
86
+ }),
87
+ },
88
+ };
89
+ const push = event => {
90
+ const waiter = waiters.shift();
91
+ if (waiter) waiter({ value: event, done: false });
92
+ else events.push(event);
93
+ };
94
+
95
+ return {
96
+ dir, workspace, store, sessions, cycle, ctx, sessionHooks, toolHooks, push,
97
+ setTurn(messageID, prompt, final) { currentTurn = { messageID, prompt, final }; },
98
+ restore() {
99
+ for (const [key, value] of Object.entries(oldEnv)) {
100
+ if (value === undefined) delete process.env[key];
101
+ else process.env[key] = value;
102
+ }
103
+ fs.rmSync(dir, { recursive: true, force: true });
104
+ },
105
+ };
106
+ }
107
+
108
+ async function waitFor(predicate) {
109
+ const deadline = Date.now() + 5000;
110
+ while (!predicate()) {
111
+ if (Date.now() >= deadline) throw new Error('OpenCode observations were not captured');
112
+ await new Promise(resolve => setTimeout(resolve, 10));
113
+ }
114
+ }
115
+
116
+ function writeCodexSession(sessions, sessionID = 'codex-backfill-session', turnId = 'codex-backfill-turn') {
117
+ const startedAt = new Date().toISOString();
118
+ const completedAt = new Date(Date.now() + 1).toISOString();
119
+ const rows = [
120
+ { type: 'session_meta', payload: { session_id: sessionID } },
121
+ { type: 'event_msg', timestamp: startedAt, payload: { type: 'task_started', turn_id: turnId, started_at: startedAt } },
122
+ { type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Codex positive control' }] } },
123
+ { type: 'event_msg', timestamp: completedAt, payload: { type: 'task_complete', turn_id: turnId, last_agent_message: LABELS[0] } },
124
+ ];
125
+ fs.writeFileSync(path.join(sessions, `${sessionID}.jsonl`), rows.map(row => JSON.stringify(row)).join('\n') + '\n');
126
+ }
127
+
128
+ function captureTurn(store, { host = 'opencode', sessionID, turnId, prompt, final }) {
129
+ const env = { HARNESS_OBSERVATIONS: 'on', HARNESS_OBSERVATIONS_DIR: store };
130
+ observations.handle({ hook_event_name: 'UserPromptSubmit', host, session_id: sessionID, turn_id: turnId, prompt }, env);
131
+ observations.handle({ hook_event_name: 'Stop', host, session_id: sessionID, turn_id: turnId, last_assistant_message: final }, env);
132
+ }
133
+
134
+ function jsonl(file) {
135
+ return fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean).map(JSON.parse);
136
+ }
137
+
138
+ function json(file) {
139
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
140
+ }
141
+
142
+ function collectReport(dataDir) {
143
+ return json(path.join(dataDir, 'training/observed/import-report.json'));
144
+ }
145
+
146
+ function snapshotCycle(dataDir) {
147
+ const training = path.join(dataDir, 'training');
148
+ const files = {};
149
+ function walk(directory) {
150
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
151
+ const file = path.join(directory, entry.name);
152
+ if (entry.isDirectory()) walk(file);
153
+ else {
154
+ const relative = path.relative(training, file).split(path.sep).join('/');
155
+ let content = fs.readFileSync(file, 'utf8');
156
+ if (relative === 'observed/import-report.json') {
157
+ const report = JSON.parse(content);
158
+ report.run.startedAt = '<run-time>';
159
+ content = JSON.stringify(report, null, 2) + '\n';
160
+ } else if (relative === 'observed/export-report.json') {
161
+ const report = JSON.parse(content);
162
+ report.exportedAt = '<run-time>';
163
+ content = JSON.stringify(report, null, 2) + '\n';
164
+ }
165
+ files[relative] = content;
166
+ }
167
+ }
168
+ }
169
+ walk(training);
170
+ return files;
171
+ }
172
+
173
+ test('cycle collect imports production OpenCode captures into private prompt/label pairs', { concurrency: false }, async () => {
174
+ const f = fixture();
175
+ let dispose;
176
+ try {
177
+ const plugin = await import(pathToFileURL(PLUGIN).href);
178
+ dispose = await plugin.default.setup(f.ctx);
179
+ assert.ok(f.sessionHooks.has('prompt'), 'the production OpenCode plugin registered prompt capture');
180
+
181
+ const turns = [
182
+ { sessionID: 'opencode-cycle-session-a', prompt: 'Fix parser. Contact synthetic.user@example.test at /Users/synthetic-owner/private-alpha.txt' },
183
+ { sessionID: 'opencode-cycle-session-b', prompt: 'Edit response. Contact second.user@example.test at /Users/synthetic-owner/private-beta.txt' },
184
+ ];
185
+ for (const [index, turn] of turns.entries()) {
186
+ const messageID = 'shared-turn';
187
+ f.setTurn(messageID, turn.prompt, LABELS[index]);
188
+ await f.sessionHooks.get('prompt')({ sessionID: turn.sessionID, messageID, prompt: { text: turn.prompt } });
189
+ f.push({ type: 'session.execution.succeeded', data: { sessionID: turn.sessionID } });
190
+ await waitFor(() => recordList(f.store).length === index + 1);
191
+ }
192
+
193
+ const openCodeRecords = recordList(f.store).filter(record => record.host === 'opencode');
194
+ assert.equal(openCodeRecords.length, 2, 'both valid OpenCode turns were captured in the isolated live store');
195
+ captureTurn(f.store, { host: 'codex', sessionID: turns[0].sessionID, turnId: 'shared-turn', prompt: 'Codex live overlap', final: LABELS[0] });
196
+ writeCodexSession(f.sessions, turns[0].sessionID, 'shared-turn');
197
+ const result = collect({ dataDir: f.cycle, since: '2026-01-01', sessionsDir: f.sessions });
198
+ assert.equal(result.prompts, 3, 'two OpenCode turns and the production Codex backfill are collected');
199
+ const equivalentCycle = path.join(f.dir, 'equivalent-cycle');
200
+ const equivalentResult = collect({ dataDir: equivalentCycle, since: '2026-01-01', sessionsDir: f.sessions });
201
+ assert.deepEqual(equivalentResult, result);
202
+ assert.deepEqual(snapshotCycle(equivalentCycle), snapshotCycle(f.cycle),
203
+ 'clean equivalent collects produce the same files and persistent state apart from per-run timestamps');
204
+
205
+ const prompts = jsonl(path.join(f.cycle, 'training/observed/prompts-observed.jsonl'));
206
+ const labels = jsonl(path.join(f.cycle, 'training/observed/labels-observed.jsonl'));
207
+ for (const record of openCodeRecords) {
208
+ const prompt = prompts.find(row => row.id === record.id);
209
+ const label = labels.find(row => row.id === record.id);
210
+ assert.ok(prompt, 'OpenCode rows are absent because collect never imports the live observations store');
211
+ assert.ok(label, 'every imported OpenCode prompt has its matching label');
212
+ assert.equal(label.host, 'opencode', 'the final label projection preserves the capture host');
213
+ assert.equal(label.tier, record.selfReport.tier);
214
+ assert.deepEqual(label.intents, record.selfReport.intents);
215
+ assert.match(prompt.text, /<email>/);
216
+ assert.match(prompt.text, /<home>/);
217
+ assert.ok(!prompt.text.includes('synthetic.user@example.test') && !prompt.text.includes('second.user@example.test'));
218
+ assert.ok(!prompt.text.includes('/Users/synthetic-owner'));
219
+ }
220
+
221
+ const destinationRecords = recordList(path.join(f.cycle, 'training/observation-store'));
222
+ const sharedTurn = destinationRecords.filter(record => record.writer.turnId === 'shared-turn');
223
+ assert.equal(sharedTurn.length, 3, 'the shared turn id remains distinct across two sessions and two hosts');
224
+ assert.equal(new Set(sharedTurn.map(record => record.id)).size, 3);
225
+ assert.deepEqual(sharedTurn.map(record => record.host).sort(), ['codex', 'opencode', 'opencode']);
226
+ const codexRecord = destinationRecords.find(record => record.host === 'codex');
227
+ assert.equal(codexRecord.captureMethod, 'session-backfill', 'Codex backfill remains the positive control and wins this arrival order');
228
+ assert.equal(labels.find(row => row.id === codexRecord.id).host, 'codex');
229
+ const firstReport = collectReport(f.cycle);
230
+ assert.equal(firstReport.schemaVersion, 1);
231
+ assert.deepEqual(Object.keys(firstReport).sort(), ['byHost', 'run', 'schemaVersion', 'sources']);
232
+ assert.deepEqual(Object.keys(firstReport.sources).sort(), ['codex', 'live']);
233
+ assert.deepEqual(Object.keys(firstReport.sources.live).sort(), ['root', 'status']);
234
+ assert.deepEqual(Object.keys(firstReport.sources.codex).sort(), ['status']);
235
+ assert.ok(Number.isFinite(Date.parse(firstReport.run.startedAt)));
236
+ assert.equal(firstReport.sources.live.root, 'configured-private-store');
237
+ const reportJson = JSON.stringify(firstReport);
238
+ assert.ok(!reportJson.includes(f.dir));
239
+ assert.ok(!reportJson.includes('synthetic.user@example.test') && !reportJson.includes('private-alpha.txt'));
240
+ if (process.platform !== 'win32') {
241
+ assert.equal(fs.statSync(path.join(f.cycle, 'training/observed/import-report.json')).mode & 0o777, 0o600);
242
+ assert.equal(fs.statSync(f.cycle).mode & 0o777, 0o700);
243
+ }
244
+ assert.equal(firstReport.sources.live.status, 'ok');
245
+ assert.equal(firstReport.sources.codex.status, 'ok');
246
+ assert.deepEqual(firstReport.byHost.opencode, { persisted: 2, duplicate: 0, ambiguous: 0, importFailure: 0 });
247
+ assert.deepEqual(firstReport.byHost.codex, { persisted: 0, duplicate: 1, ambiguous: 0, importFailure: 0 });
248
+
249
+ collect({ dataDir: f.cycle, since: '2026-01-01', sessionsDir: f.sessions });
250
+ const repeatReport = collectReport(f.cycle);
251
+ assert.deepEqual(repeatReport.byHost.opencode, { persisted: 0, duplicate: 2, ambiguous: 0, importFailure: 0 });
252
+ assert.deepEqual(repeatReport.byHost.codex, { persisted: 0, duplicate: 1, ambiguous: 0, importFailure: 0 });
253
+ assert.equal(recordList(path.join(f.cycle, 'training/observation-store')).length, 3, 'repeat collect adds no observation rows');
254
+
255
+ const liveFirstCycle = path.join(f.dir, 'live-first-cycle');
256
+ const liveFirstStore = path.join(liveFirstCycle, 'training/observation-store');
257
+ const liveFirst = importStore({ sourceRoot: f.store, store: liveFirstStore, since: '2026-01-01' });
258
+ assert.equal(liveFirst.byHost.opencode.persisted, 2);
259
+ assert.equal(liveFirst.byHost.codex.persisted, 1);
260
+ collect({ dataDir: liveFirstCycle, since: '2026-01-01', sessionsDir: f.sessions });
261
+ const reverseOrderReport = collectReport(liveFirstCycle);
262
+ assert.equal(reverseOrderReport.byHost.opencode.duplicate, 2);
263
+ assert.equal(reverseOrderReport.byHost.codex.duplicate, 1);
264
+ assert.equal(recordList(liveFirstStore).find(record => record.host === 'codex').captureMethod, undefined,
265
+ 'live capture wins when it arrives before the Codex backfill');
266
+ } finally {
267
+ if (dispose) await dispose();
268
+ f.restore();
269
+ }
270
+ });
271
+
272
+ test('live-store merge retains unlabeled metadata without reviving unavailable text', () => {
273
+ const f = fixture();
274
+ try {
275
+ captureTurn(f.store, { sessionID: 'unlabeled-session', turnId: 'unlabeled-turn', prompt: 'Unlabeled observation', final: 'No label was emitted.' });
276
+ captureTurn(f.store, { sessionID: 'malformed-session', turnId: 'malformed-turn', prompt: 'Malformed observation', final: '<!-- harness-label {bad json} -->' });
277
+ captureTurn(f.store, { sessionID: 'missing-text-session', turnId: 'missing-text-turn', prompt: 'Missing text observation', final: LABELS[0] });
278
+ captureTurn(f.store, { sessionID: 'expired-text-session', turnId: 'expired-text-turn', prompt: 'Expired text observation', final: LABELS[1] });
279
+ captureTurn(f.store, { sessionID: 'before-cutoff-session', turnId: 'before-cutoff-turn', prompt: 'Before cutoff', final: LABELS[0] });
280
+
281
+ const sourceIndexFile = path.join(f.store, 'observations-index.json');
282
+ const sourceIndex = json(sourceIndexFile);
283
+ const missing = sourceIndex.records.find(record => record.writer.turnId === 'missing-text-turn');
284
+ const expired = sourceIndex.records.find(record => record.writer.turnId === 'expired-text-turn');
285
+ sourceIndex.records.find(record => record.writer.turnId === 'before-cutoff-turn').observedAt = '2025-12-31T23:59:59.000Z';
286
+ const expiredUntil = new Date(Date.now() - 1000).toISOString();
287
+ expired.validUntil = expiredUntil;
288
+ expired.status = 'active';
289
+ fs.writeFileSync(sourceIndexFile, JSON.stringify(sourceIndex));
290
+ fs.unlinkSync(path.join(f.store, 'text', `${missing.contentSha256}.json`));
291
+
292
+ const result = collect({ dataDir: f.cycle, since: '2026-01-01', sessionsDir: f.sessions });
293
+ assert.equal(result.prompts, 0);
294
+ const output = path.join(f.cycle, 'training/observed');
295
+ assert.deepEqual(jsonl(path.join(output, 'prompts-observed.jsonl')), []);
296
+ assert.deepEqual(jsonl(path.join(output, 'labels-observed.jsonl')), []);
297
+
298
+ const destinationStore = path.join(f.cycle, 'training/observation-store');
299
+ const records = recordList(destinationStore);
300
+ assert.equal(records.length, 4, 'unlabeled, malformed, missing-text and expired-text metadata all survive import');
301
+ assert.equal(records.find(record => record.writer.turnId === 'unlabeled-turn').selfReportReason, 'label-missing');
302
+ assert.equal(records.find(record => record.writer.turnId === 'malformed-turn').selfReportReason, 'label-unparseable');
303
+ const storedMissing = records.find(record => record.writer.turnId === 'missing-text-turn');
304
+ const storedExpired = records.find(record => record.writer.turnId === 'expired-text-turn');
305
+ assert.equal(fs.existsSync(path.join(destinationStore, 'text', `${storedMissing.contentSha256}.json`)), false);
306
+ assert.equal(storedExpired.validUntil, expiredUntil, 'import keeps the original expiry deadline');
307
+ assert.equal(storedExpired.status, 'expired');
308
+ assert.equal(storedExpired.textDeleted, true);
309
+ assert.equal(fs.existsSync(path.join(destinationStore, 'text', `${storedExpired.contentSha256}.json`)), false);
310
+ assert.deepEqual(collectReport(f.cycle).byHost.opencode,
311
+ { persisted: 4, duplicate: 0, ambiguous: 0, importFailure: 0 });
312
+ const exportReport = json(path.join(output, 'export-report.json'));
313
+ assert.equal(exportReport.skippedUnlabeled, 2);
314
+ assert.equal(exportReport.skippedNoText, 2);
315
+ const reportText = fs.readFileSync(path.join(output, 'import-report.json'), 'utf8');
316
+ assert.ok(!reportText.includes(f.dir) && !reportText.includes('Unlabeled observation'));
317
+ } finally {
318
+ f.restore();
319
+ }
320
+ });
321
+
322
+ test('missing live source is explicit and failed live imports never report persistence', () => {
323
+ const f = fixture();
324
+ try {
325
+ const emptyLiveStore = path.join(f.dir, 'empty-live-store');
326
+ fs.mkdirSync(emptyLiveStore);
327
+ process.env.HARNESS_OBSERVATIONS_DIR = emptyLiveStore;
328
+ const omittedSource = importStore({ store: path.join(f.dir, 'omitted-source-cycle'), since: '2026-01-01' });
329
+ assert.equal(omittedSource.source.status, 'absent', 'omitting sourceRoot uses the configured observation store');
330
+ const invalidSince = importStore({ sourceRoot: emptyLiveStore, store: path.join(f.dir, 'invalid-since-cycle'), since: 'not-a-date' });
331
+ assert.equal(invalidSince.source.error, 'invalid-since');
332
+ assert.equal(invalidSince.byHost.unknown.persisted, 0);
333
+ const missingStore = importStore({ sourceRoot: emptyLiveStore, since: '2026-01-01' });
334
+ assert.equal(missingStore.source.error, 'invalid-destination');
335
+ assert.equal(missingStore.byHost.unknown.persisted, 0);
336
+ const wrongTypeStore = importStore({ sourceRoot: emptyLiveStore, store: { path: 'unsafe' }, since: '2026-01-01' });
337
+ assert.equal(wrongTypeStore.source.error, 'invalid-destination');
338
+ const empty = collect({ dataDir: f.cycle, since: '2026-01-01', sessionsDir: f.sessions });
339
+ assert.equal(empty.prompts, 0);
340
+ const absentReport = collectReport(f.cycle);
341
+ assert.equal(absentReport.sources.live.status, 'absent');
342
+ assert.equal(absentReport.sources.codex.status, 'ok');
343
+ assert.deepEqual(absentReport.byHost, {});
344
+
345
+ const brokenCycle = path.join(f.dir, 'broken-cycle');
346
+ process.env.HARNESS_OBSERVATIONS_DIR = f.store;
347
+ fs.mkdirSync(f.store, { recursive: true });
348
+ fs.writeFileSync(path.join(f.store, 'observations-index.json'), '{broken index');
349
+ assert.throws(() => collect({ dataDir: brokenCycle, since: '2026-01-01', sessionsDir: f.sessions }), /observation import incomplete/);
350
+ const failedReport = collectReport(brokenCycle);
351
+ assert.equal(failedReport.sources.live.status, 'error');
352
+ assert.equal(failedReport.sources.live.error, 'source-index-invalid');
353
+ assert.deepEqual(failedReport.byHost.unknown, { persisted: 0, duplicate: 0, ambiguous: 0, importFailure: 1 });
354
+ assert.equal(recordList(path.join(brokenCycle, 'training/observation-store')).length, 0);
355
+ assert.equal(fs.existsSync(path.join(brokenCycle, 'training/observed/prompts-observed.jsonl')), false,
356
+ 'failed imports do not proceed to export');
357
+
358
+ const ambiguousStore = path.join(f.dir, 'ambiguous-live-store');
359
+ captureTurn(ambiguousStore, { sessionID: 'ambiguous-session', turnId: 'ambiguous-turn', prompt: 'Ambiguous identity', final: LABELS[0] });
360
+ const ambiguousIndex = json(path.join(ambiguousStore, 'observations-index.json'));
361
+ delete ambiguousIndex.records[0].writer.sessionId;
362
+ fs.writeFileSync(path.join(ambiguousStore, 'observations-index.json'), JSON.stringify(ambiguousIndex));
363
+ const ambiguousCycle = path.join(f.dir, 'ambiguous-cycle');
364
+ process.env.HARNESS_OBSERVATIONS_DIR = ambiguousStore;
365
+ assert.throws(() => collect({ dataDir: ambiguousCycle, since: '2026-01-01', sessionsDir: f.sessions }), /observation import incomplete/);
366
+ const ambiguousReport = collectReport(ambiguousCycle);
367
+ assert.equal(ambiguousReport.sources.live.error, 'ambiguous-records');
368
+ assert.deepEqual(ambiguousReport.byHost.opencode, { persisted: 0, duplicate: 0, ambiguous: 1, importFailure: 0 });
369
+ assert.equal(recordList(path.join(ambiguousCycle, 'training/observation-store')).length, 0);
370
+
371
+ const unsafeHashStore = path.join(f.dir, 'unsafe-hash-live-store');
372
+ captureTurn(unsafeHashStore, { sessionID: 'unsafe-hash-session', turnId: 'unsafe-hash-turn', prompt: 'Unsafe hash', final: LABELS[0] });
373
+ const unsafeIndex = json(path.join(unsafeHashStore, 'observations-index.json'));
374
+ unsafeIndex.records[0].contentSha256 = '../../outside-private-root';
375
+ fs.writeFileSync(path.join(unsafeHashStore, 'observations-index.json'), JSON.stringify(unsafeIndex));
376
+ const unsafeCycle = path.join(f.dir, 'unsafe-hash-cycle');
377
+ process.env.HARNESS_OBSERVATIONS_DIR = unsafeHashStore;
378
+ assert.throws(() => collect({ dataDir: unsafeCycle, since: '2026-01-01', sessionsDir: f.sessions }), /observation import incomplete/);
379
+ const unsafeReport = collectReport(unsafeCycle);
380
+ assert.equal(unsafeReport.sources.live.error, 'source-record-invalid');
381
+ assert.deepEqual(unsafeReport.byHost.opencode, { persisted: 0, duplicate: 0, ambiguous: 0, importFailure: 1 });
382
+ assert.equal(recordList(path.join(unsafeCycle, 'training/observation-store')).length, 0);
383
+
384
+ const lockedStore = path.join(f.dir, 'locked-live-store');
385
+ captureTurn(lockedStore, { sessionID: 'locked-session', turnId: 'locked-turn', prompt: 'Lock failure', final: LABELS[0] });
386
+ const lockedDestination = path.join(f.dir, 'locked-destination');
387
+ fs.mkdirSync(lockedDestination, { recursive: true });
388
+ fs.writeFileSync(path.join(lockedDestination, 'observations-index.json'), JSON.stringify({ schemaVersion: 1, kind: 'system-one-observations', records: [] }));
389
+ fs.writeFileSync(path.join(lockedDestination, '.index.lock'), 'fixture lock');
390
+ const lockFailure = importStore({ sourceRoot: lockedStore, store: lockedDestination, since: '2026-01-01', lockTimeoutMs: 1 });
391
+ assert.equal(lockFailure.source.status, 'error');
392
+ assert.equal(lockFailure.source.error, 'append-failed');
393
+ assert.deepEqual(lockFailure.byHost.opencode, { persisted: 0, duplicate: 0, ambiguous: 0, importFailure: 1 });
394
+ assert.equal(recordList(lockedDestination).length, 0);
395
+ } finally {
396
+ f.restore();
397
+ }
398
+ });
399
+