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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/AGENTS.md +3 -1
- package/CHANGELOG.md +38 -0
- package/benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md +7 -0
- package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-probe.js +16 -0
- package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-trace-2026-11-15.jsonl +4 -0
- package/bin/cli.js +1 -0
- package/ci/invariant-routing.test.js +22 -3
- package/ci/mechanism-2al-codex-hooks-compat.test.js +56 -2
- package/ci/mechanism-2n-opencode-plugin.test.js +1 -1
- package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +18 -3
- package/ci/mechanism-338-opencode-async.test.js +20 -3
- package/ci/mechanism-341-opencode-lane.test.js +7 -1
- package/ci/mechanism-349-ci-change-scope.test.js +78 -57
- package/ci/mechanism-397-cycle-import.test.js +414 -0
- package/ci/mechanism-397-host-acceptance.test.js +119 -0
- package/ci/mechanism-397-opencode-observations.test.js +1922 -0
- package/ci/mechanism-check-packet-write-set.test.js +232 -0
- package/ci/mechanism-codex-prompt-pass-through.test.js +8 -4
- package/ci/mechanism-error-handling-map.test.js +219 -0
- package/ci/mechanism-report-writer.test.js +335 -0
- package/ci/mechanism-system-one-curves.test.js +17 -0
- package/ci/mechanism-system-one-cycle.test.js +621 -2
- package/ci/router-workflow-plan.test.js +50 -7
- package/docs/architecture.md +4 -3
- package/docs/error-handling/README.md +250 -0
- package/docs/error-handling/actions/c1-action-map.md +89 -0
- package/docs/error-handling/actions/c2-action-map.md +22 -0
- package/docs/error-handling/actions/c3-action-map.md +26 -0
- package/docs/error-handling/actions/c5-action-map.md +31 -0
- package/docs/error-handling/actions/c6-action-map.md +37 -0
- package/docs/error-handling/actions/c7-action-map.md +18 -0
- package/docs/error-handling/actions/e0002-action-map.md +101 -0
- package/docs/error-handling/activity.puml +84 -0
- package/docs/error-handling/details/c1-authority-conformance.md +93 -0
- package/docs/error-handling/details/c2-test-root-containment.md +35 -0
- package/docs/error-handling/details/c3-mode-ownership.md +50 -0
- package/docs/error-handling/details/c5-host-replay-contract.md +40 -0
- package/docs/error-handling/details/c6-packet-briefing.md +65 -0
- package/docs/error-handling/details/c7-write-set-check.md +54 -0
- package/docs/error-handling/details/e0002-capture-evidence.md +93 -0
- package/docs/error-handling/details/e0002-report-writer.md +116 -0
- package/docs/error-handling/nodes.yaml +44 -0
- package/docs/error-handling/registry.md +59 -0
- package/docs/error-handling/templates/packet-briefing.md +45 -0
- package/docs/platform-capabilities.md +16 -7
- package/docs/system-one-cycle.md +12 -3
- package/docs/system-one-observations.md +35 -4
- package/hooks/scripts/codex-user-prompt.js +2 -3
- package/hooks/scripts/lib/observations.js +5 -3
- package/opencode-plugin/README.md +22 -8
- package/opencode-plugin/index.mjs +424 -44
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +2 -1
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/hooks/scripts/codex-user-prompt.js +2 -3
- package/plugins/harness-everything/hooks/scripts/lib/observations.js +5 -3
- package/plugins/harness-everything/plugin.json +1 -1
- package/sbom.cdx.json +7 -7
- package/scripts/check-packet-write-set.js +155 -0
- package/scripts/codex-hooks-compat.js +46 -5
- package/scripts/error-handling-map.js +288 -0
- package/scripts/report-writer.js +261 -0
- package/scripts/system-one-curves.js +154 -14
- package/scripts/system-one-cycle/collect.js +20 -3
- package/scripts/system-one-cycle/common.js +39 -1
- package/scripts/system-one-cycle/evaluate.js +8 -5
- package/scripts/system-one-cycle.js +7 -2
- package/scripts/system-one-observations-export.js +29 -0
- package/scripts/system-one-observations-import-store.js +128 -0
|
@@ -345,7 +345,7 @@ function transcriptMessage(file, turnId) {
|
|
|
345
345
|
|
|
346
346
|
function detectHost(payload, hints) {
|
|
347
347
|
const direct = String(payload.host || payload.runtime || '').toLowerCase();
|
|
348
|
-
if (['claude', 'codex'].includes(direct)) return direct;
|
|
348
|
+
if (['claude', 'codex', 'opencode'].includes(direct)) return direct;
|
|
349
349
|
if (hints.codex || payload.turn_id || payload.last_agent_message) return 'codex';
|
|
350
350
|
if (process.env.CLAUDE_PLUGIN_ROOT || process.env.CLAUDECODE || process.env.CLAUDE_CODE_ENTRYPOINT || process.env.CLAUDE) return 'claude';
|
|
351
351
|
if (process.env.CODEX_HOME || process.env.CODEX_THREAD_ID) return 'codex';
|
|
@@ -587,6 +587,8 @@ function collectEvents(root, sessionId, turn) {
|
|
|
587
587
|
function startTurn(payload, root) {
|
|
588
588
|
const file = sessionFile(root, payload.session_id);
|
|
589
589
|
const session = readJson(file, null) || { turn: 0, lastFinal: '', pending: null };
|
|
590
|
+
const turnId = String(payload.turn_id || payload.turnId || '');
|
|
591
|
+
if (session.pending && turnId && session.pending.turnId === turnId) return;
|
|
590
592
|
if (session.pending) finishPending(session, payload, root, { text: null, reason: 'stop-missing' });
|
|
591
593
|
if (!session.lastFinalAt || Date.now() - Date.parse(session.lastFinalAt) > RETENTION_MS) session.lastFinal = '';
|
|
592
594
|
// Events left from an earlier turn arrived after its Stop; they belong to no record.
|
|
@@ -594,7 +596,7 @@ function startTurn(payload, root) {
|
|
|
594
596
|
session.turn++;
|
|
595
597
|
session.pending = {
|
|
596
598
|
turn: session.turn,
|
|
597
|
-
turnId
|
|
599
|
+
turnId,
|
|
598
600
|
startedAt: new Date().toISOString(),
|
|
599
601
|
prompt: redact(typeof payload.prompt === 'string' ? payload.prompt : ''),
|
|
600
602
|
previous: session.lastFinal || '',
|
|
@@ -654,7 +656,7 @@ function finishPending(session, payload, root, final) {
|
|
|
654
656
|
selfReport: label,
|
|
655
657
|
selfReportReason: reason,
|
|
656
658
|
};
|
|
657
|
-
|
|
659
|
+
appendRecordDetailed(root, record, textExpired ? null : text, { dedupeById: true, dedupeByTurn: true });
|
|
658
660
|
fs.rmSync(eventsDir(root, payload.session_id, pending.turn), { recursive: true, force: true });
|
|
659
661
|
session.lastFinal = final.text ? redact(tailBytes(stripLabels(final.text), PREVIOUS_BYTES)) : '';
|
|
660
662
|
session.lastFinalAt = observedAt;
|
|
@@ -15,9 +15,9 @@ only SUGGEST rules (soft guidance). This means:
|
|
|
15
15
|
|
|
16
16
|
## The plugin
|
|
17
17
|
|
|
18
|
-
**File:** `index.mjs` -
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
**File:** `index.mjs` - the ESM plugin entrypoint. The OpenCode 2 adapter uses
|
|
19
|
+
the documented prompt and context hooks; the V1 factory remains available for
|
|
20
|
+
existing OpenCode 1 installations. There is no manifest-to-script
|
|
21
21
|
mechanism; an earlier version of this plugin assumed one (a `plugin.json`
|
|
22
22
|
mapping event names to standalone scripts) and opencode never invoked it -
|
|
23
23
|
see issue #37 for how that was found and fixed. **Naming caveat (issue
|
|
@@ -26,7 +26,7 @@ must be copied to a `.js` name when installed - see Installation below.
|
|
|
26
26
|
|
|
27
27
|
It implements three lifecycle mechanisms across opencode's real hooks:
|
|
28
28
|
|
|
29
|
-
The
|
|
29
|
+
The V1 factory follows opencode's plugin contract directly: the named
|
|
30
30
|
`HarnessEnforcement` export is an async factory receiving the opencode context
|
|
31
31
|
(`client`, `directory`, `project`, `worktree`, and `$`) and returning the hook
|
|
32
32
|
map. Copying this one file into `.opencode/plugins/` under a `.js` name is
|
|
@@ -35,6 +35,9 @@ repository
|
|
|
35
35
|
inventory and is not an opencode runtime manifest. The hook callbacks use the
|
|
36
36
|
V1 `(input, output)` shape, including
|
|
37
37
|
`output.args` when the host supplies tool arguments only in the result object.
|
|
38
|
+
OpenCode 2's prompt injection and observation path resolves the canonical
|
|
39
|
+
`harness-everything/scripts/kernel-router.js` and
|
|
40
|
+
`hooks/scripts/lib/observations.js` from an ancestor Harness checkout/runtime.
|
|
38
41
|
|
|
39
42
|
### 1. Edit tracking (`tool.execute.after`)
|
|
40
43
|
|
|
@@ -102,8 +105,9 @@ new breaker failure. A reflection artifact itself does not count as a code edit.
|
|
|
102
105
|
|
|
103
106
|
## Installation
|
|
104
107
|
|
|
105
|
-
**OpenCode 2.x
|
|
106
|
-
`{ id: "harness.enforcement", setup(ctx) }` and registers
|
|
108
|
+
**OpenCode 2.x:** the module default-exports
|
|
109
|
+
`{ id: "harness.enforcement", setup(ctx) }` and registers
|
|
110
|
+
`ctx.session.hook("prompt|context")`, `ctx.tool.hook("execute.before|after")`,
|
|
107
111
|
plus `ctx.event.subscribe()` through the OpenCode 2 plugin context. OpenCode 2
|
|
108
112
|
never loads a named-export-only plugin: it fails with `Plugin must export a
|
|
109
113
|
default definition with an id and an effect or setup function`
|
|
@@ -114,11 +118,17 @@ available for OpenCode 1.x hosts: it receives the V1 context
|
|
|
114
118
|
adapter wraps that factory and maps the V2 hook events onto it, so the
|
|
115
119
|
enforcement logic is shared, not duplicated.
|
|
116
120
|
|
|
121
|
+
The prompt/context routing and System One observation hooks are V2-only. The
|
|
122
|
+
V1 factory keeps its existing enforcement hooks; it does not capture turns.
|
|
123
|
+
|
|
117
124
|
Direction:
|
|
118
125
|
named factory (V1 hosts/tests) → default-export setup adapter → V2 domains.
|
|
119
126
|
|
|
120
|
-
Copy `index.mjs` into opencode's plugin directory **under a `.js` filename
|
|
121
|
-
|
|
127
|
+
Copy `index.mjs` into opencode's plugin directory **under a `.js` filename**.
|
|
128
|
+
The router and observation hooks resolve from a Harness checkout above the
|
|
129
|
+
plugin, or from sibling `harness-everything/`, `hooks/scripts/`, and
|
|
130
|
+
`scripts/lib/` runtime directories. A project install inside the Harness
|
|
131
|
+
checkout already has those files.
|
|
122
132
|
|
|
123
133
|
```bash
|
|
124
134
|
mkdir -p .opencode/plugins
|
|
@@ -126,6 +136,10 @@ cp opencode-plugin/index.mjs .opencode/plugins/harness-enforcement.js # projec
|
|
|
126
136
|
# or
|
|
127
137
|
mkdir -p ~/.config/opencode/plugins
|
|
128
138
|
cp opencode-plugin/index.mjs ~/.config/opencode/plugins/harness-enforcement.js # global
|
|
139
|
+
mkdir -p ~/.config/opencode/hooks ~/.config/opencode/scripts
|
|
140
|
+
cp -R harness-everything ~/.config/opencode/
|
|
141
|
+
cp -R hooks/scripts ~/.config/opencode/hooks/
|
|
142
|
+
cp -R scripts/lib ~/.config/opencode/scripts/
|
|
129
143
|
```
|
|
130
144
|
|
|
131
145
|
Restart OpenCode after copying so the plugin is discovered at startup.
|
|
@@ -45,11 +45,199 @@ import { createRequire } from "node:module"
|
|
|
45
45
|
import { fileURLToPath } from "node:url"
|
|
46
46
|
|
|
47
47
|
const EDIT_TOOLS = new Set(["edit", "write", "apply_patch"])
|
|
48
|
+
// shortcut: the 5s race cannot cancel a pending host lookup, upgrade when OpenCode exposes session.get cancellation.
|
|
49
|
+
const SESSION_LOOKUP_TIMEOUT_MS = 5000
|
|
48
50
|
const OPENCODE_CAPTURE_FILE = "opencode-captures.jsonl"
|
|
49
51
|
const OPENCODE_CAPTURE_LIMIT_BYTES = 4 * 1024 * 1024
|
|
50
52
|
const OPENCODE_CAPTURE_RECORD_LIMIT_BYTES = 16 * 1024
|
|
51
53
|
const requireFromPlugin = createRequire(import.meta.url)
|
|
52
|
-
const
|
|
54
|
+
const PLUGIN_DIRECTORY = dirname(fileURLToPath(import.meta.url))
|
|
55
|
+
|
|
56
|
+
function findHarnessRoot(start = PLUGIN_DIRECTORY) {
|
|
57
|
+
let directory = resolve(start)
|
|
58
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
59
|
+
if (existsSync(join(directory, "harness-everything", "scripts", "kernel-router.js"))
|
|
60
|
+
&& existsSync(join(directory, "hooks", "scripts", "lib", "observations.js"))) return directory
|
|
61
|
+
const parent = dirname(directory)
|
|
62
|
+
if (parent === directory) break
|
|
63
|
+
directory = parent
|
|
64
|
+
}
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const HARNESS_ROOT = findHarnessRoot()
|
|
69
|
+
const STOP_GATE_FILE = join(HARNESS_ROOT || resolve(PLUGIN_DIRECTORY, ".."), "hooks", "scripts", "workflow-stop-gate.js")
|
|
70
|
+
const OBSERVATIONS_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "hooks", "scripts", "lib", "observations.js")
|
|
71
|
+
const ROUTER_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "harness-everything", "scripts", "kernel-router.js")
|
|
72
|
+
let observationsApi
|
|
73
|
+
|
|
74
|
+
function systemOneObservations() {
|
|
75
|
+
if (!OBSERVATIONS_FILE) return null
|
|
76
|
+
if (!observationsApi) {
|
|
77
|
+
try { observationsApi = requireFromPlugin(OBSERVATIONS_FILE) } catch { return null }
|
|
78
|
+
}
|
|
79
|
+
return observationsApi
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// OpenCode's host process is a compiled Bun binary, so process.execPath is the
|
|
83
|
+
// opencode executable. That binary cannot run a Node .js script - it treats the
|
|
84
|
+
// script path as a project directory (ENOTDIR) - so a non-Node host must run
|
|
85
|
+
// Harness scripts with `node` from PATH. Under Node the checked-in runtime is
|
|
86
|
+
// used as before; a Node that cannot be found stays fail-open, because the
|
|
87
|
+
// spawn error yields no injection and blocks no turn.
|
|
88
|
+
function harnessRuntime() {
|
|
89
|
+
return process.versions.bun ? "node" : process.execPath
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function runKernelRouter(payload, signal) {
|
|
93
|
+
if (!ROUTER_FILE || signal?.aborted) return Promise.resolve(null)
|
|
94
|
+
return new Promise(resolveOutput => {
|
|
95
|
+
let stdout = ""
|
|
96
|
+
let child, timeout, termination, spawnError = false, timedOut = false, cancelled = false, settled = false
|
|
97
|
+
const terminate = () => {
|
|
98
|
+
if (!termination && child) termination = terminateVerificationChild(child)
|
|
99
|
+
}
|
|
100
|
+
const finish = async code => {
|
|
101
|
+
if (settled) return
|
|
102
|
+
settled = true
|
|
103
|
+
clearTimeout(timeout)
|
|
104
|
+
signal?.removeEventListener("abort", abort)
|
|
105
|
+
if (termination) await termination
|
|
106
|
+
resolveOutput(!spawnError && !timedOut && !cancelled && code === 0 ? stdout.trim() : null)
|
|
107
|
+
}
|
|
108
|
+
const abort = () => { cancelled = true; terminate() }
|
|
109
|
+
try {
|
|
110
|
+
child = spawn(harnessRuntime(), [ROUTER_FILE], {
|
|
111
|
+
cwd: payload.cwd || HARNESS_ROOT,
|
|
112
|
+
env: process.env,
|
|
113
|
+
detached: process.platform !== "win32",
|
|
114
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
115
|
+
windowsHide: true,
|
|
116
|
+
})
|
|
117
|
+
} catch {
|
|
118
|
+
resolveOutput(null)
|
|
119
|
+
return
|
|
120
|
+
}
|
|
121
|
+
child.stdout.on("data", chunk => { stdout += chunk })
|
|
122
|
+
child.stdin.on("error", () => { spawnError = true; terminate() })
|
|
123
|
+
child.once("error", () => {
|
|
124
|
+
spawnError = true
|
|
125
|
+
if (!child.pid) void finish(null)
|
|
126
|
+
else terminate()
|
|
127
|
+
})
|
|
128
|
+
child.once("close", code => { void finish(code) })
|
|
129
|
+
signal?.addEventListener("abort", abort, { once: true })
|
|
130
|
+
if (signal?.aborted) abort()
|
|
131
|
+
timeout = setTimeout(() => { timedOut = true; terminate() }, 5000)
|
|
132
|
+
try { child.stdin.end(JSON.stringify(payload)) } catch { spawnError = true; terminate() }
|
|
133
|
+
})
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function assistantTextForCurrentTurn(messages, userMessageID) {
|
|
137
|
+
const items = Array.isArray(messages) ? messages : Array.isArray(messages?.data) ? messages.data : []
|
|
138
|
+
const role = message => message?.info?.role || message?.info?.type || message?.role || message?.type
|
|
139
|
+
const messageID = message => message?.info?.id ?? message?.id
|
|
140
|
+
let lastUser = userMessageID
|
|
141
|
+
? items.findIndex(message => messageID(message) === userMessageID && role(message) === "user")
|
|
142
|
+
: -1
|
|
143
|
+
if (!userMessageID) {
|
|
144
|
+
for (let i = items.length - 1; i >= 0; i--) {
|
|
145
|
+
if (role(items[i]) === "user") { lastUser = i; break }
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (lastUser < 0) return null
|
|
149
|
+
for (let i = items.length - 1; i > lastUser; i--) {
|
|
150
|
+
const message = items[i]
|
|
151
|
+
if (role(message) !== "assistant") continue
|
|
152
|
+
const parts = Array.isArray(message.parts) ? message.parts : Array.isArray(message.content) ? message.content : []
|
|
153
|
+
const text = parts
|
|
154
|
+
.filter(part => part?.type === "text" && typeof part.text === "string")
|
|
155
|
+
.map(part => part.text).join("")
|
|
156
|
+
if (text) return text
|
|
157
|
+
}
|
|
158
|
+
return null
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function observeOpenCodeTool(event, workspace) {
|
|
162
|
+
try {
|
|
163
|
+
const observations = systemOneObservations()
|
|
164
|
+
if (!observations || !observations.enabled() || !event?.sessionID) return
|
|
165
|
+
const args = isRecord(event.input) ? event.input : {}
|
|
166
|
+
const names = { edit: "Edit", write: "Write", apply_patch: "apply_patch", bash: "shell", skill: "Skill", read: "Read", task: "Task" }
|
|
167
|
+
const toolInput = {
|
|
168
|
+
...args,
|
|
169
|
+
file_path: args.filePath || args.file_path || args.path,
|
|
170
|
+
command: args.command || args.cmd,
|
|
171
|
+
skill: args.skill || args.name,
|
|
172
|
+
}
|
|
173
|
+
const failed = event.status === "error" || Boolean(event.error)
|
|
174
|
+
observations.handle({
|
|
175
|
+
hook_event_name: failed ? "PostToolUseFailure" : "PostToolUse",
|
|
176
|
+
host: "opencode",
|
|
177
|
+
session_id: event.sessionID,
|
|
178
|
+
cwd: workspace,
|
|
179
|
+
tool_name: names[String(event.tool || "").toLowerCase()] || event.tool,
|
|
180
|
+
tool_input: toolInput,
|
|
181
|
+
tool_response: event.result,
|
|
182
|
+
error: failed,
|
|
183
|
+
})
|
|
184
|
+
} catch { /* turn observation is always fail-open */ }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function observeOpenCodeCompletion(sessionID, ctx, promptRoutes, signal) {
|
|
188
|
+
const prompt = promptRoutes.get(sessionID)
|
|
189
|
+
promptRoutes.delete(sessionID)
|
|
190
|
+
if (!prompt?.workspace || signal?.aborted) return
|
|
191
|
+
try {
|
|
192
|
+
const observations = systemOneObservations()
|
|
193
|
+
if (!observations || !observations.enabled()) return
|
|
194
|
+
let lastMessage = null
|
|
195
|
+
const context = await awaitAbortableHostRead(() => ctx.session.context({ sessionID }), signal)
|
|
196
|
+
if (context.status === "aborted" || signal?.aborted) return
|
|
197
|
+
if (context.status === "resolved") lastMessage = assistantTextForCurrentTurn(context.value, prompt?.messageID)
|
|
198
|
+
const payload = {
|
|
199
|
+
hook_event_name: "Stop",
|
|
200
|
+
host: "opencode",
|
|
201
|
+
session_id: sessionID,
|
|
202
|
+
...(prompt?.messageID ? { turn_id: prompt.messageID } : {}),
|
|
203
|
+
cwd: prompt.workspace,
|
|
204
|
+
...(lastMessage === null ? {} : { last_assistant_message: lastMessage }),
|
|
205
|
+
}
|
|
206
|
+
if (signal?.aborted) return
|
|
207
|
+
observations.handle(payload)
|
|
208
|
+
} catch { /* turn observation is always fail-open */ }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function awaitAbortableHostRead(read, signal) {
|
|
212
|
+
return new Promise(resolveRead => {
|
|
213
|
+
let settled = false
|
|
214
|
+
const finish = result => {
|
|
215
|
+
if (settled) return
|
|
216
|
+
settled = true
|
|
217
|
+
signal.removeEventListener("abort", onAbort)
|
|
218
|
+
resolveRead(result)
|
|
219
|
+
}
|
|
220
|
+
const onAbort = () => finish({ status: "aborted" })
|
|
221
|
+
if (signal.aborted) {
|
|
222
|
+
onAbort()
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
signal.addEventListener("abort", onAbort, { once: true })
|
|
226
|
+
if (signal.aborted) {
|
|
227
|
+
onAbort()
|
|
228
|
+
return
|
|
229
|
+
}
|
|
230
|
+
let raw
|
|
231
|
+
try { raw = read() } catch (error) {
|
|
232
|
+
finish({ status: "rejected", error })
|
|
233
|
+
return
|
|
234
|
+
}
|
|
235
|
+
Promise.resolve(raw).then(
|
|
236
|
+
value => finish({ status: "resolved", value }),
|
|
237
|
+
error => finish({ status: "rejected", error }),
|
|
238
|
+
)
|
|
239
|
+
})
|
|
240
|
+
}
|
|
53
241
|
|
|
54
242
|
function canonicalJson(value) {
|
|
55
243
|
if (Array.isArray(value)) return value.map(canonicalJson)
|
|
@@ -1143,61 +1331,253 @@ export default {
|
|
|
1143
1331
|
id: "harness.enforcement",
|
|
1144
1332
|
async setup(ctx) {
|
|
1145
1333
|
const events = new AbortController()
|
|
1146
|
-
const
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1334
|
+
const promptRoutes = new Map()
|
|
1335
|
+
const sessionBindings = new Map()
|
|
1336
|
+
const sessionOwners = new Map()
|
|
1337
|
+
const invalidatedSessions = new Set()
|
|
1338
|
+
const enforcementByWorkspace = new Map()
|
|
1339
|
+
const pendingEvents = new Set()
|
|
1340
|
+
const trackPending = work => {
|
|
1341
|
+
const pending = Promise.resolve().then(work)
|
|
1342
|
+
pendingEvents.add(pending)
|
|
1343
|
+
pending.then(() => pendingEvents.delete(pending), () => pendingEvents.delete(pending))
|
|
1344
|
+
return pending
|
|
1345
|
+
}
|
|
1346
|
+
let unresolvedIdentityCount = 0
|
|
1347
|
+
|
|
1348
|
+
const unresolvedIdentity = reason => {
|
|
1349
|
+
unresolvedIdentityCount++
|
|
1350
|
+
try { console.warn(`[Harness] OpenCode session workspace unresolved (${reason}; count=${unresolvedIdentityCount}); workspace-dependent handling skipped.`) } catch {}
|
|
1351
|
+
}
|
|
1352
|
+
const resolveSessionWorkspace = sessionID => new Promise(resolveIdentity => {
|
|
1353
|
+
if (events.signal.aborted) {
|
|
1354
|
+
resolveIdentity({ reason: "plugin-disposed" })
|
|
1355
|
+
return
|
|
1356
|
+
}
|
|
1357
|
+
let settled = false
|
|
1358
|
+
let timer
|
|
1359
|
+
const onAbort = () => finish({ reason: "plugin-disposed" })
|
|
1360
|
+
const finish = result => {
|
|
1361
|
+
if (settled) return
|
|
1362
|
+
settled = true
|
|
1363
|
+
clearTimeout(timer)
|
|
1364
|
+
events.signal.removeEventListener("abort", onAbort)
|
|
1365
|
+
resolveIdentity(result)
|
|
1366
|
+
}
|
|
1367
|
+
timer = setTimeout(() => finish({ reason: "session-lookup-timeout" }), SESSION_LOOKUP_TIMEOUT_MS)
|
|
1368
|
+
events.signal.addEventListener("abort", onAbort, { once: true })
|
|
1369
|
+
if (events.signal.aborted) {
|
|
1370
|
+
onAbort()
|
|
1371
|
+
return
|
|
1372
|
+
}
|
|
1373
|
+
if (typeof ctx.session?.get !== "function") {
|
|
1374
|
+
finish({ reason: "session-lookup-unavailable" })
|
|
1375
|
+
return
|
|
1376
|
+
}
|
|
1377
|
+
let lookup
|
|
1378
|
+
try { lookup = ctx.session.get({ sessionID }) } catch {
|
|
1379
|
+
finish({ reason: "session-lookup-failed" })
|
|
1380
|
+
return
|
|
1381
|
+
}
|
|
1382
|
+
Promise.resolve(lookup).then(session => {
|
|
1383
|
+
const directory = session?.location?.directory
|
|
1384
|
+
if (typeof directory !== "string" || !directory.trim()) {
|
|
1385
|
+
finish({ reason: "session-directory-unavailable" })
|
|
1386
|
+
} else if (!isAbsolute(directory)) {
|
|
1387
|
+
finish({ reason: "session-directory-invalid" })
|
|
1388
|
+
} else {
|
|
1389
|
+
finish({ workspace: resolve(directory) })
|
|
1390
|
+
}
|
|
1391
|
+
}, () => finish({ reason: "session-lookup-failed" }))
|
|
1392
|
+
})
|
|
1393
|
+
const enforcementFor = workspace => {
|
|
1394
|
+
if (events.signal.aborted) return Promise.resolve(null)
|
|
1395
|
+
if (!enforcementByWorkspace.has(workspace)) {
|
|
1396
|
+
enforcementByWorkspace.set(workspace, HarnessEnforcement({
|
|
1397
|
+
signal: events.signal,
|
|
1398
|
+
client: {
|
|
1399
|
+
session: {
|
|
1400
|
+
// V1 shutdown path calls client.session.prompt({path, body}) twice;
|
|
1401
|
+
// map it onto the V2 session API instead of duplicating the code.
|
|
1402
|
+
prompt: ({ path, body }) =>
|
|
1403
|
+
ctx.session.prompt({
|
|
1404
|
+
sessionID: path && path.id,
|
|
1405
|
+
text: (body && body.parts || []).map((part) => part && part.text || "").join(""),
|
|
1406
|
+
}),
|
|
1407
|
+
},
|
|
1408
|
+
},
|
|
1409
|
+
directory: workspace,
|
|
1410
|
+
}))
|
|
1411
|
+
}
|
|
1412
|
+
return enforcementByWorkspace.get(workspace)
|
|
1413
|
+
}
|
|
1414
|
+
const bindSessionWorkspace = (sessionID, workspace, hooks) => {
|
|
1415
|
+
const owners = sessionOwners.get(sessionID) || new Set()
|
|
1416
|
+
let binding = [...owners].find(owner => owner.workspace === workspace)
|
|
1417
|
+
if (!binding) {
|
|
1418
|
+
binding = { workspace, hooks }
|
|
1419
|
+
owners.add(binding)
|
|
1420
|
+
sessionOwners.set(sessionID, owners)
|
|
1421
|
+
}
|
|
1422
|
+
sessionBindings.set(sessionID, binding)
|
|
1423
|
+
return binding
|
|
1424
|
+
}
|
|
1425
|
+
const bindingForSession = async sessionID => {
|
|
1426
|
+
if (events.signal.aborted || typeof sessionID !== "string" || !sessionID) return null
|
|
1427
|
+
if (invalidatedSessions.has(sessionID)) return null
|
|
1428
|
+
const prompt = promptRoutes.get(sessionID)
|
|
1429
|
+
if (prompt && prompt.status !== "resolved") return null
|
|
1430
|
+
const existing = sessionBindings.get(sessionID)
|
|
1431
|
+
if (existing) return existing
|
|
1432
|
+
const identity = await resolveSessionWorkspace(sessionID)
|
|
1433
|
+
if (events.signal.aborted || !identity.workspace) {
|
|
1434
|
+
if (!events.signal.aborted) unresolvedIdentity(identity.reason)
|
|
1435
|
+
return null
|
|
1436
|
+
}
|
|
1437
|
+
if (invalidatedSessions.has(sessionID) || promptRoutes.get(sessionID) !== prompt) return null
|
|
1438
|
+
let hooks = null
|
|
1439
|
+
try { hooks = await enforcementFor(identity.workspace) } catch {}
|
|
1440
|
+
if (events.signal.aborted || invalidatedSessions.has(sessionID) || promptRoutes.get(sessionID) !== prompt) return null
|
|
1441
|
+
return bindSessionWorkspace(sessionID, identity.workspace, hooks)
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
await ctx.session.hook("prompt", event => {
|
|
1445
|
+
if (events.signal.aborted) return
|
|
1446
|
+
return trackPending(async () => {
|
|
1447
|
+
try {
|
|
1448
|
+
if (events.signal.aborted || typeof event?.sessionID !== "string" || typeof event.prompt?.text !== "string") return
|
|
1449
|
+
const messageID = event.messageID || event.messageId || null
|
|
1450
|
+
const previous = promptRoutes.get(event.sessionID)
|
|
1451
|
+
if (messageID && previous?.messageID === messageID) {
|
|
1452
|
+
await previous.routerPromise
|
|
1453
|
+
return
|
|
1454
|
+
}
|
|
1455
|
+
invalidatedSessions.delete(event.sessionID)
|
|
1456
|
+
const prompt = { messageID, text: event.prompt.text, routerOutput: null, routerPromise: null,
|
|
1457
|
+
workspace: null, hooks: null, status: "pending" }
|
|
1458
|
+
promptRoutes.set(event.sessionID, prompt)
|
|
1459
|
+
prompt.routerPromise = (previous?.routerPromise || Promise.resolve())
|
|
1460
|
+
.catch(() => null)
|
|
1461
|
+
.then(async () => {
|
|
1462
|
+
if (events.signal.aborted || promptRoutes.get(event.sessionID) !== prompt) return
|
|
1463
|
+
const identity = await resolveSessionWorkspace(event.sessionID)
|
|
1464
|
+
if (events.signal.aborted || promptRoutes.get(event.sessionID) !== prompt) return
|
|
1465
|
+
if (!identity.workspace) {
|
|
1466
|
+
prompt.status = "failed"
|
|
1467
|
+
unresolvedIdentity(identity.reason)
|
|
1468
|
+
return
|
|
1469
|
+
}
|
|
1470
|
+
prompt.workspace = identity.workspace
|
|
1471
|
+
try { prompt.hooks = await enforcementFor(prompt.workspace) } catch {}
|
|
1472
|
+
if (events.signal.aborted || promptRoutes.get(event.sessionID) !== prompt) return
|
|
1473
|
+
bindSessionWorkspace(event.sessionID, prompt.workspace, prompt.hooks)
|
|
1474
|
+
prompt.status = "resolved"
|
|
1475
|
+
try {
|
|
1476
|
+
if (events.signal.aborted) return
|
|
1477
|
+
const observations = systemOneObservations()
|
|
1478
|
+
if (observations && observations.enabled()) {
|
|
1479
|
+
observations.handle({ hook_event_name: "UserPromptSubmit", host: "opencode", session_id: event.sessionID,
|
|
1480
|
+
...(prompt.messageID ? { turn_id: prompt.messageID } : {}), cwd: prompt.workspace, prompt: event.prompt.text })
|
|
1481
|
+
}
|
|
1482
|
+
} catch { /* turn observation is always fail-open */ }
|
|
1483
|
+
if (events.signal.aborted) return
|
|
1484
|
+
const routerPayload = { host: "opencode", session_id: event.sessionID,
|
|
1485
|
+
...(prompt.messageID ? { turn_id: prompt.messageID } : {}), cwd: prompt.workspace, prompt: event.prompt.text }
|
|
1486
|
+
const routerOutput = await runKernelRouter(routerPayload, events.signal)
|
|
1487
|
+
if (!events.signal.aborted && promptRoutes.get(event.sessionID) === prompt) prompt.routerOutput = routerOutput
|
|
1488
|
+
})
|
|
1489
|
+
await prompt.routerPromise
|
|
1490
|
+
} catch { /* routing context is fail-open; do not reject prompt admission */ }
|
|
1491
|
+
})
|
|
1492
|
+
})
|
|
1493
|
+
await ctx.session.hook("context", event => {
|
|
1494
|
+
if (events.signal.aborted) return
|
|
1495
|
+
const output = promptRoutes.get(event?.sessionID)?.routerOutput
|
|
1496
|
+
if (!output || (event.kind && event.kind !== "primary") || !Array.isArray(event.system)) return
|
|
1497
|
+
if (!event.system.some(part => part && part.text === output)) event.system.push({ type: "text", text: output })
|
|
1498
|
+
})
|
|
1499
|
+
|
|
1500
|
+
await ctx.tool.hook("execute.before", event => {
|
|
1501
|
+
if (events.signal.aborted) return
|
|
1502
|
+
return trackPending(async () => {
|
|
1503
|
+
if (events.signal.aborted) return
|
|
1504
|
+
const binding = await bindingForSession(event?.sessionID)
|
|
1505
|
+
if (events.signal.aborted || !binding?.workspace || !binding.hooks) return
|
|
1506
|
+
return binding.hooks["tool.execute.before"](toolEventInput(event), { args: event.input })
|
|
1507
|
+
})
|
|
1508
|
+
})
|
|
1509
|
+
await ctx.tool.hook("execute.after", event => {
|
|
1510
|
+
if (events.signal.aborted) return
|
|
1511
|
+
return trackPending(async () => {
|
|
1512
|
+
if (events.signal.aborted) return
|
|
1513
|
+
const prompt = promptRoutes.get(event?.sessionID)
|
|
1514
|
+
const binding = await bindingForSession(event?.sessionID)
|
|
1515
|
+
if (events.signal.aborted || !binding?.workspace) return
|
|
1516
|
+
if (prompt?.status === "resolved" && prompt.workspace) observeOpenCodeTool(event, prompt.workspace)
|
|
1517
|
+
if (!binding.hooks) return
|
|
1518
|
+
return binding.hooks["tool.execute.after"](toolEventInput(event), {
|
|
1519
|
+
args: event.input,
|
|
1520
|
+
status: event.status,
|
|
1521
|
+
result: event.result,
|
|
1522
|
+
error: event.error,
|
|
1523
|
+
messageID: event.messageID,
|
|
1524
|
+
})
|
|
1525
|
+
})
|
|
1160
1526
|
})
|
|
1161
1527
|
|
|
1162
|
-
|
|
1163
|
-
hooks["tool.execute.before"](toolEventInput(event), { args: event.input }))
|
|
1164
|
-
await ctx.tool.hook("execute.after", (event) =>
|
|
1165
|
-
hooks["tool.execute.after"](toolEventInput(event), {
|
|
1166
|
-
args: event.input,
|
|
1167
|
-
status: event.status,
|
|
1168
|
-
result: event.result,
|
|
1169
|
-
error: event.error,
|
|
1170
|
-
messageID: event.messageID,
|
|
1171
|
-
}))
|
|
1172
|
-
|
|
1173
|
-
const pendingIdles = new Set()
|
|
1174
|
-
void (async () => {
|
|
1528
|
+
trackPending(async () => {
|
|
1175
1529
|
try {
|
|
1176
1530
|
for await (const raw of ctx.event.subscribe({ signal: events.signal })) {
|
|
1177
1531
|
if (events.signal.aborted) break
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
if (raw.type === "session.
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1532
|
+
// OpenCode 2.x events are flat with the session id at data.sessionID;
|
|
1533
|
+
// V1 hosts keep it top-level. V2 hosts send no session.idle, so a
|
|
1534
|
+
// completed turn ends with session.execution.succeeded.
|
|
1535
|
+
const sessionID = raw.sessionID || (raw.data && raw.data.sessionID)
|
|
1536
|
+
|| (raw.properties && (raw.properties.sessionID || raw.properties.info?.id))
|
|
1537
|
+
const turnEnded = raw.type === "session.idle" || raw.type === "session.execution.succeeded"
|
|
1538
|
+
const lifecycleEvent = ["session.idle", "session.created", "session.deleted"].includes(raw.type)
|
|
1539
|
+
if ((!turnEnded && !lifecycleEvent) || typeof sessionID !== "string" || !sessionID) continue
|
|
1540
|
+
if (raw.type === "session.deleted") invalidatedSessions.add(sessionID)
|
|
1541
|
+
else if (raw.type === "session.created") invalidatedSessions.delete(sessionID)
|
|
1542
|
+
if (raw.type === "session.created" || raw.type === "session.deleted") promptRoutes.delete(sessionID)
|
|
1543
|
+
const prompt = promptRoutes.get(sessionID)
|
|
1544
|
+
if (turnEnded && prompt?.status === "resolved") {
|
|
1545
|
+
trackPending(() => observeOpenCodeCompletion(sessionID, ctx, promptRoutes, events.signal))
|
|
1546
|
+
}
|
|
1547
|
+
let bindings
|
|
1548
|
+
if (raw.type === "session.created" || raw.type === "session.deleted") {
|
|
1549
|
+
bindings = [...(sessionOwners.get(sessionID) || [])]
|
|
1550
|
+
if (!bindings.length && !invalidatedSessions.has(sessionID)) {
|
|
1551
|
+
const binding = await bindingForSession(sessionID)
|
|
1552
|
+
if (binding) bindings = [binding]
|
|
1553
|
+
}
|
|
1191
1554
|
} else {
|
|
1192
|
-
|
|
1555
|
+
const binding = await bindingForSession(sessionID)
|
|
1556
|
+
bindings = binding ? [binding] : []
|
|
1557
|
+
}
|
|
1558
|
+
const event = {
|
|
1559
|
+
type: turnEnded ? "session.idle" : raw.type,
|
|
1560
|
+
properties: { ...raw, ...(isRecord(raw.properties) ? raw.properties : {}), sessionID },
|
|
1561
|
+
}
|
|
1562
|
+
const cleanupDelivery = raw.type === "session.created" || raw.type === "session.deleted"
|
|
1563
|
+
const delivery = trackPending(() => Promise.allSettled(bindings.filter(binding => binding?.hooks?.event)
|
|
1564
|
+
.map(binding => Promise.resolve().then(() => {
|
|
1565
|
+
if (events.signal.aborted && !cleanupDelivery) return
|
|
1566
|
+
return binding.hooks.event({ event })
|
|
1567
|
+
}))))
|
|
1568
|
+
if (!turnEnded) await delivery
|
|
1569
|
+
if (raw.type === "session.created" || raw.type === "session.deleted") {
|
|
1570
|
+
promptRoutes.delete(sessionID)
|
|
1571
|
+
sessionBindings.delete(sessionID)
|
|
1572
|
+
sessionOwners.delete(sessionID)
|
|
1193
1573
|
}
|
|
1194
1574
|
}
|
|
1195
1575
|
} catch { /* aborting the host subscription is normal shutdown */ }
|
|
1196
1576
|
finally { events.abort() }
|
|
1197
|
-
})
|
|
1577
|
+
})
|
|
1198
1578
|
return async () => {
|
|
1199
1579
|
events.abort()
|
|
1200
|
-
await Promise.allSettled([...
|
|
1580
|
+
while (pendingEvents.size) await Promise.allSettled([...pendingEvents])
|
|
1201
1581
|
}
|
|
1202
1582
|
},
|
|
1203
1583
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "harness-everything",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.54.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": {
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"repo:contract": "node scripts/repository-contract.js",
|
|
19
19
|
"docs:sync": "node scripts/sync-current-docs.js",
|
|
20
20
|
"errors:sync": "node scripts/errors-sync.js",
|
|
21
|
+
"report": "node scripts/report-writer.js",
|
|
21
22
|
"test:repo-contract": "node ci/repository-contract.test.js",
|
|
22
23
|
"test:consistency": "node ci/consistency-check.js && node ci/doc-capability-consistency.test.js && node ci/repository-contract.test.js && node ci/mechanism-2ao-plugin-sync.test.js && node ci/prompt-contract-regressions.test.js",
|
|
23
24
|
"test:docs:capabilities": "node ci/doc-capability-consistency.test.js",
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';
|
|
3
3
|
// Codex UserPromptSubmit adapter (docs/system-one-observations.md#hosts).
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
// reaches the model. This runs the kernel router and wraps its output.
|
|
4
|
+
// Wrap router output in JSON hookSpecificOutput.additionalContext. Codex
|
|
5
|
+
// treats stdout beginning with "[" (including routing banners) as JSON-like.
|
|
7
6
|
|
|
8
7
|
const fs = require('fs');
|
|
9
8
|
const path = require('path');
|