harness-everything 0.58.0 → 1.0.1

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 (53) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/AGENTS.md +8 -2
  4. package/CHANGELOG.md +24 -0
  5. package/README.md +4 -4
  6. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/README.md +40 -0
  7. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/edit-state-final.json +11 -0
  8. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/events-2026-11-24.jsonl +103 -0
  9. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/host-version.txt +3 -0
  10. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/live-event-trace-probe.js +11 -0
  11. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/plugin-load-lines.txt +2 -0
  12. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/reminder-excerpt.txt +1 -0
  13. package/ci/doc-capability-consistency.test.js +4 -2
  14. package/ci/lib/opencode-v2-driver.js +169 -0
  15. package/ci/mechanism-2n-opencode-plugin.test.js +387 -223
  16. package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +24 -15
  17. package/ci/mechanism-2u-issue-42-regressions.test.js +41 -2
  18. package/ci/mechanism-2w-platform-compatibility.test.js +16 -3
  19. package/ci/mechanism-30-opencode-plugin-loadability.test.js +78 -45
  20. package/ci/mechanism-338-opencode-async.test.js +367 -194
  21. package/ci/mechanism-341-opencode-lane.test.js +143 -183
  22. package/ci/mechanism-39-opencode-verify-outcomes.test.js +118 -86
  23. package/ci/mechanism-394-ledger-match.test.js +105 -3
  24. package/ci/mechanism-394-opencode-ledger-lesson.test.js +46 -97
  25. package/ci/mechanism-397-opencode-observations.test.js +58 -47
  26. package/ci/mechanism-453-opencode-v2-driver.test.js +51 -0
  27. package/ci/mechanism-453-opencode-v2-only-events.test.js +241 -0
  28. package/ci/mechanism-516-agy-post-tool-exit.test.js +472 -0
  29. package/ci/mechanism-516-agy-stop-revision.test.js +215 -0
  30. package/ci/telemetry.test.js +31 -24
  31. package/docs/architecture.md +4 -2
  32. package/docs/platform-capabilities.md +60 -26
  33. package/docs/platform-compatibility.json +8 -6
  34. package/docs/system-one-observations.md +1 -1
  35. package/docs/telemetry.md +1 -1
  36. package/docs/troubleshooting.md +2 -2
  37. package/hooks/scripts/agy-post-tool.js +79 -16
  38. package/hooks/scripts/agy-stop.js +63 -10
  39. package/hooks/scripts/lib/ledger-match.js +132 -20
  40. package/hooks/scripts/state-persist.js +7 -1
  41. package/opencode-plugin/README.md +60 -66
  42. package/opencode-plugin/index.mjs +11 -13
  43. package/opencode-plugin/plugin.json +1 -1
  44. package/package.json +1 -1
  45. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  46. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  47. package/plugins/harness-everything/hooks/scripts/agy-post-tool.js +79 -16
  48. package/plugins/harness-everything/hooks/scripts/agy-stop.js +63 -10
  49. package/plugins/harness-everything/hooks/scripts/lib/ledger-match.js +132 -20
  50. package/plugins/harness-everything/hooks/scripts/state-persist.js +7 -1
  51. package/plugins/harness-everything/plugin.json +1 -1
  52. package/plugins/harness-everything/rules/AGENTS.md +8 -2
  53. package/sbom.cdx.json +12 -12
@@ -25,6 +25,66 @@ const FILE_MUTATION_TOOLS = new Set([
25
25
  'multi_replace_file_content'
26
26
  ]);
27
27
 
28
+ const FAILED_STATUSES = new Set([
29
+ 'failed',
30
+ 'fail',
31
+ 'error',
32
+ 'errored',
33
+ 'timed_out',
34
+ 'timeout',
35
+ 'cancelled',
36
+ 'canceled',
37
+ 'aborted'
38
+ ]);
39
+
40
+ function normalizeErrorText(rawError) {
41
+ if (typeof rawError === 'string') return rawError.trim();
42
+ if (rawError === null || rawError === undefined || rawError === false) return '';
43
+ if (typeof rawError === 'object') {
44
+ if (Array.isArray(rawError) && rawError.length === 0) return '';
45
+ if (!Array.isArray(rawError) && Object.keys(rawError).length === 0) return '';
46
+ }
47
+ const serialized = JSON.stringify(rawError);
48
+ return typeof serialized === 'string' ? serialized.trim() : '';
49
+ }
50
+
51
+ function hasExplicitFailureFlag(obj) {
52
+ return obj.isError === true
53
+ || obj.is_error === true
54
+ || obj.success === false
55
+ || obj.ok === false
56
+ || obj.interrupted === true;
57
+ }
58
+
59
+ function classifyStructuredOutcome(safePayload, responseObj, error) {
60
+ const rawExitCodes = [
61
+ safePayload.exitCode,
62
+ safePayload.exit_code,
63
+ responseObj.exitCode,
64
+ responseObj.exit_code
65
+ ].filter(Number.isInteger);
66
+ const nonzeroCode = rawExitCodes.find(code => code !== 0);
67
+ const exitCode = nonzeroCode ?? rawExitCodes[0];
68
+
69
+ const statuses = [safePayload.status, responseObj.status]
70
+ .filter(value => typeof value === 'string' && value.trim())
71
+ .map(value => value.trim().toLowerCase());
72
+
73
+ // Structured host errors, failure flags, and nonzero exit codes win over any
74
+ // zero or generic metadata fields. Text-only stdout/output markers are never parsed here
75
+ // because retained AGY captures do not distinguish host metadata from stdout.
76
+ const isFailed = Boolean(error && error.trim())
77
+ || (exitCode !== undefined && exitCode !== 0)
78
+ || hasExplicitFailureFlag(safePayload)
79
+ || hasExplicitFailureFlag(responseObj)
80
+ || statuses.some(status => FAILED_STATUSES.has(status));
81
+
82
+ return {
83
+ isFailed,
84
+ exitCode: isFailed ? (exitCode !== undefined && exitCode !== 0 ? exitCode : undefined) : exitCode
85
+ };
86
+ }
87
+
28
88
  function mapAgyPayloadToStatePersist(payload) {
29
89
  const safePayload = payload && typeof payload === 'object' ? payload : {};
30
90
  const sessionId = getAgySessionId(safePayload);
@@ -56,21 +116,22 @@ function mapAgyPayloadToStatePersist(payload) {
56
116
  toolInput = { ...args, file_path: filePath };
57
117
  }
58
118
 
59
- const toolResponse = safePayload.toolResponse || safePayload.tool_response || safePayload.result || {};
60
- const rawError = safePayload.error || toolResponse.error || '';
61
- const error = typeof rawError === 'string' ? rawError : (rawError ? JSON.stringify(rawError) : '');
62
- const stdout = toolResponse.stdout || (typeof safePayload.output === 'string' ? safePayload.output : '') || '';
63
- const stderr = toolResponse.stderr || (typeof error === 'string' ? error : '') || '';
64
-
65
- const rawExitCodes = [
66
- safePayload.exitCode,
67
- safePayload.exit_code,
68
- toolResponse.exitCode,
69
- toolResponse.exit_code
70
- ].filter(Number.isInteger);
71
- const exitCode = rawExitCodes.find(code => code !== 0) ?? rawExitCodes[0];
119
+ const rawResponse = safePayload.toolResponse || safePayload.tool_response || safePayload.result;
120
+ const responseObj = (rawResponse && typeof rawResponse === 'object' && !Array.isArray(rawResponse))
121
+ ? rawResponse
122
+ : {};
123
+ const error = normalizeErrorText(safePayload.error) || normalizeErrorText(responseObj.error);
124
+ const stdout = (typeof responseObj.stdout === 'string' && responseObj.stdout)
125
+ || (typeof safePayload.stdout === 'string' && safePayload.stdout)
126
+ || (typeof safePayload.output === 'string' && safePayload.output)
127
+ || (typeof rawResponse === 'string' && rawResponse)
128
+ || '';
129
+ const stderr = (typeof responseObj.stderr === 'string' && responseObj.stderr)
130
+ || (typeof safePayload.stderr === 'string' && safePayload.stderr)
131
+ || error
132
+ || '';
72
133
 
73
- const isFailed = Boolean(error && error.trim()) || (exitCode !== undefined && exitCode !== 0);
134
+ const { isFailed, exitCode } = classifyStructuredOutcome(safePayload, responseObj, error);
74
135
 
75
136
  return {
76
137
  hook_event_name: isFailed ? 'PostToolUseFailure' : 'PostToolUse',
@@ -89,7 +150,9 @@ function mapAgyPayloadToStatePersist(payload) {
89
150
  stderr,
90
151
  ...(exitCode !== undefined ? { exitCode } : {})
91
152
  },
92
- error: isFailed ? (error || stderr || `Command exited with code ${exitCode}`) : '',
153
+ error: isFailed
154
+ ? (error || stderr || (exitCode !== undefined ? `Command exited with code ${exitCode}` : 'Tool execution failed'))
155
+ : '',
93
156
  ...(exitCode !== undefined ? { exitCode } : {})
94
157
  };
95
158
  }
@@ -121,4 +184,4 @@ if (require.main === module) {
121
184
  });
122
185
  }
123
186
 
124
- module.exports = { main, mapAgyPayloadToStatePersist };
187
+ module.exports = { main, mapAgyPayloadToStatePersist, classifyStructuredOutcome };
@@ -26,6 +26,7 @@ const {
26
26
  normalizeAgyStatePayload
27
27
  } = require('./lib/agy-adapter-core');
28
28
  const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
29
+ const { workspaceFingerprint } = require('./lib/workflow-isolation');
29
30
 
30
31
  const STOP_STATE_FILE = 'agy-stop-state.json';
31
32
 
@@ -40,16 +41,58 @@ function readStopState(filePath) {
40
41
  }
41
42
 
42
43
  function writeStopState(filePath, state) {
44
+ let temp;
43
45
  try {
44
46
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
45
- const temp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
47
+ temp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
46
48
  fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', 'utf8');
47
49
  fs.renameSync(temp, filePath);
50
+ return true;
48
51
  } catch (_) {
49
- // Best-effort marker write; never fail stop evaluation on state IO.
52
+ if (temp) { try { fs.unlinkSync(temp); } catch (_) {} }
53
+ return false;
50
54
  }
51
55
  }
52
56
 
57
+ function clearStopState(filePath) {
58
+ try { fs.unlinkSync(filePath); } catch (_) {}
59
+ }
60
+
61
+ function pendingRevision(handoff, root, sessionId) {
62
+ const directRevision = Number.isSafeInteger(handoff && handoff.agyDirectMutationRevision)
63
+ ? handoff.agyDirectMutationRevision
64
+ : null;
65
+ let contentFingerprint = null;
66
+ try { contentFingerprint = workspaceFingerprint(root, { maxPaths: 5000 }); } catch (_) {}
67
+ return {
68
+ revision: directRevision === null ? `session:${sessionId || 'default'}` : `direct:${directRevision}`,
69
+ directRevision,
70
+ contentFingerprint
71
+ };
72
+ }
73
+
74
+ function samePendingRevision(saved, current) {
75
+ if (!saved) return false;
76
+ if (!saved.lastContinuedRevision) {
77
+ // Older markers have no stable revision. Keep their session allowance
78
+ // when handoff state is legacy too; the prior content baseline is unknown.
79
+ return current.directRevision === null && Boolean(saved.lastContinuedFingerprint);
80
+ }
81
+ if (saved.lastContinuedRevision !== current.revision) return false;
82
+ return !current.contentFingerprint || !saved.lastContinuedContentFingerprint
83
+ || saved.lastContinuedContentFingerprint === current.contentFingerprint;
84
+ }
85
+
86
+ function stopMarker(revision, reason) {
87
+ return {
88
+ lastContinuedRevision: revision.revision,
89
+ lastContinuedContentFingerprint: revision.contentFingerprint,
90
+ lastContinuedFingerprint: `${revision.revision}${revision.contentFingerprint ? `|workspace:${revision.contentFingerprint}` : ''}`,
91
+ lastContinuedReason: reason,
92
+ updatedAt: new Date().toISOString()
93
+ };
94
+ }
95
+
53
96
  const ABNORMAL_TERMINATION_REASONS = new Set([
54
97
  'USER_CANCELED',
55
98
  'CANCELED',
@@ -103,17 +146,14 @@ function evaluateStop(payload) {
103
146
  let pending = null;
104
147
  if (isFailed) {
105
148
  pending = {
106
- fingerprint: `failed:${handoff.timestamp || ''}:${handoff.tool || ''}:${handoff.exitCode ?? ''}`,
107
149
  reason: 'Harness Verify-Before-Claim: pending tool failure must be resolved before claiming completion.'
108
150
  };
109
151
  } else if (lastEditAt > 0 && lastVerifyAt < lastEditAt) {
110
152
  pending = {
111
- fingerprint: `edit:${lastEditAt}`,
112
153
  reason: 'Harness Verify-Before-Claim: unverified edits exist in session. Run relevant test/build/lint verification before claiming completion.'
113
154
  };
114
155
  } else if (process.env.HARNESS_REQUIRE_VERIFICATION === '1' && (!lastVerifyAt || lastVerifyAt < lastEditAt)) {
115
156
  pending = {
116
- fingerprint: `strict:${lastVerifyAt}`,
117
157
  reason: 'Harness Verify-Before-Claim: objective test verification is required before claiming completion.'
118
158
  };
119
159
  }
@@ -121,19 +161,32 @@ function evaluateStop(payload) {
121
161
  if (pending) {
122
162
  const stopStateFile = path.join(sessionDir, STOP_STATE_FILE);
123
163
  const saved = readStopState(stopStateFile);
124
- if (saved && saved.lastContinuedFingerprint === pending.fingerprint) {
164
+ const revision = pendingRevision(handoff, root, sessionId);
165
+ if (samePendingRevision(saved, revision)) {
166
+ if (saved.lastContinuedReason !== pending.reason
167
+ || saved.lastContinuedRevision !== revision.revision
168
+ || (!saved.lastContinuedContentFingerprint && revision.contentFingerprint)) {
169
+ const marker = stopMarker(revision, pending.reason);
170
+ // A missed probe can refresh diagnostics, but cannot erase the last content baseline.
171
+ if (!revision.contentFingerprint && saved.lastContinuedContentFingerprint) {
172
+ marker.lastContinuedContentFingerprint = saved.lastContinuedContentFingerprint;
173
+ marker.lastContinuedFingerprint = saved.lastContinuedFingerprint;
174
+ }
175
+ writeStopState(stopStateFile, {
176
+ ...saved,
177
+ ...marker
178
+ });
179
+ }
125
180
  return { decision: 'allow' };
126
181
  }
127
- writeStopState(stopStateFile, {
128
- lastContinuedFingerprint: pending.fingerprint,
129
- updatedAt: new Date().toISOString()
130
- });
182
+ if (!writeStopState(stopStateFile, stopMarker(revision, pending.reason))) return { decision: 'allow' };
131
183
  return {
132
184
  decision: 'continue',
133
185
  reason: pending.reason
134
186
  };
135
187
  }
136
188
 
189
+ clearStopState(path.join(sessionDir, STOP_STATE_FILE));
137
190
  return { decision: 'allow' };
138
191
  }
139
192
 
@@ -190,40 +190,152 @@ function words(command) {
190
190
  return tokens;
191
191
  }
192
192
 
193
- // Recognize only a bounded top-level sequence. Wrappers, pipelines, redirects,
194
- // subshells, and heredocs stay unsupported; quoted separators remain arguments.
193
+ function literalRedirectTarget(command, start) {
194
+ let index = start;
195
+ while (index < command.length && /\s/.test(command[index])) index += 1;
196
+ const targetStart = index;
197
+ let quote = null;
198
+ let length = 0;
199
+ for (; index < command.length; index += 1) {
200
+ const char = command[index];
201
+ if (quote === "'") {
202
+ if (char === "'") quote = null;
203
+ else length += 1;
204
+ continue;
205
+ }
206
+ if (quote === '"') {
207
+ if (char === '"') quote = null;
208
+ else if (char === '\\' && index + 1 < command.length) { index += 1; length += 1; }
209
+ else if (char === '$' || char === '`') return null;
210
+ else length += 1;
211
+ continue;
212
+ }
213
+ if (char === '"' || char === "'") { quote = char; continue; }
214
+ if (char === '\\' && index + 1 < command.length) { index += 1; length += 1; continue; }
215
+ if (/\s/.test(char) || ';|&<>'.includes(char)) break;
216
+ if (char === '#' && index === targetStart) return null;
217
+ if ('()$`'.includes(char) || /[*?\[\]{}]/.test(char) || (char === '~' && length === 0)) return null;
218
+ length += 1;
219
+ }
220
+ return quote || length === 0 ? null : index;
221
+ }
222
+
223
+ function readRedirect(command, index, fileDescriptor) {
224
+ const char = command[index];
225
+ let operatorEnd = index + 1;
226
+ if (char === '<') {
227
+ if (command[index + 1] === '<' || command[index + 1] === '>') return null;
228
+ } else if (char === '>') {
229
+ if (command[index + 1] === '|') return null;
230
+ if (command[index + 1] === '>') operatorEnd += 1;
231
+ else if (command[index + 1] === '&') {
232
+ if (!fileDescriptor) return null;
233
+ let targetEnd = index + 2;
234
+ const digitsStart = targetEnd;
235
+ while (/[0-9]/.test(command[targetEnd] || '')) targetEnd += 1;
236
+ if (targetEnd === digitsStart ||
237
+ (targetEnd < command.length && !/\s/.test(command[targetEnd]) && !';|&<>'.includes(command[targetEnd]))) return null;
238
+ return targetEnd;
239
+ }
240
+ } else if (char === '&') {
241
+ if (command[index + 1] !== '>' || command[index + 2] === '>') return null;
242
+ operatorEnd += 1;
243
+ } else return null;
244
+ return literalRedirectTarget(command, operatorEnd);
245
+ }
246
+
247
+ // Recognize a bounded top-level command list; redirects are removed before
248
+ // candidate matching so their filenames never become command words.
195
249
  function splitSimpleCommandSegments(command) {
196
250
  if (typeof command !== 'string' || command.length > LIMITS.command || /[\r\n\0]/.test(command)) return null;
197
251
  const segments = [];
252
+ let segment = '';
198
253
  let quote = null;
199
- let start = 0;
254
+ let tokenStart = true;
255
+ let afterSeparator = false;
200
256
  for (let index = 0; index < command.length; index += 1) {
201
257
  const char = command[index];
202
- if (quote) {
203
- if (char === quote) quote = null;
204
- else if (char === '\\' && quote === '"' && index + 1 < command.length) index += 1;
258
+ if (quote === "'") {
259
+ segment += char;
260
+ if (char === "'") quote = null;
261
+ tokenStart = false;
262
+ afterSeparator = false;
205
263
  continue;
206
264
  }
207
- if (char === '"' || char === "'") { quote = char; continue; }
208
- if (char === '\\' && index + 1 < command.length) { index += 1; continue; }
209
- if ('<>()`'.includes(char)) return null;
265
+ if (quote === '"') {
266
+ if (char === '"') { segment += char; quote = null; tokenStart = false; afterSeparator = false; continue; }
267
+ if (char === '\\' && index + 1 < command.length) { segment += char + command[++index]; afterSeparator = false; continue; }
268
+ if (char === '`' || (char === '$' && command[index + 1] === '(')) return null;
269
+ segment += char;
270
+ afterSeparator = false;
271
+ continue;
272
+ }
273
+ if (char === '"' || char === "'") { segment += char; quote = char; tokenStart = false; afterSeparator = false; continue; }
274
+ if (char === '\\' && index + 1 < command.length) { segment += char + command[++index]; tokenStart = false; afterSeparator = false; continue; }
275
+ if (char === '`' || (char === '$' && command[index + 1] === '(') || '()'.includes(char)) return null;
276
+ if (char === '#' && tokenStart) {
277
+ if (afterSeparator) return null;
278
+ break;
279
+ }
280
+ if (/\s/.test(char)) { segment += char; tokenStart = true; continue; }
281
+
282
+ let descriptorEnd = index;
283
+ if (tokenStart && /[0-9]/.test(char)) {
284
+ while (/[0-9]/.test(command[descriptorEnd] || '')) descriptorEnd += 1;
285
+ if (command[descriptorEnd] === '>' || command[descriptorEnd] === '<') {
286
+ const end = readRedirect(command, descriptorEnd, true);
287
+ if (end === null) return null;
288
+ index = end - 1;
289
+ tokenStart = true;
290
+ continue;
291
+ }
292
+ }
293
+ if (char === '<' || char === '>') {
294
+ const end = readRedirect(command, index, false);
295
+ if (end === null) return null;
296
+ index = end - 1;
297
+ tokenStart = true;
298
+ continue;
299
+ }
300
+ if (char === '&' && command[index + 1] === '>') {
301
+ const end = readRedirect(command, index, false);
302
+ if (end === null) return null;
303
+ index = end - 1;
304
+ tokenStart = true;
305
+ continue;
306
+ }
307
+
210
308
  let separatorLength = 0;
211
309
  if (char === ';') separatorLength = 1;
212
- else if (char === '&' || char === '|') {
213
- if (command[index + 1] !== char || command[index + 2] === char) return null;
310
+ else if (char === '&') {
311
+ if (command[index + 1] !== '&' || command[index + 2] === '&') return null;
214
312
  separatorLength = 2;
313
+ } else if (char === '|') {
314
+ if (command[index + 1] === '&' || command[index + 2] === '|') return null;
315
+ separatorLength = command[index + 1] === '|' ? 2 : 1;
215
316
  }
216
- if (!separatorLength) continue;
217
- const segment = command.slice(start, index).trim();
218
- if (!segment || segments.length >= LIMITS.commandSegments - 1) return null;
219
- segments.push(segment);
220
- index += separatorLength - 1;
221
- start = index + 1;
317
+ if (separatorLength) {
318
+ const current = segment.trim();
319
+ if (!current || segments.length >= LIMITS.commandSegments - 1) return null;
320
+ segments.push(current);
321
+ segment = '';
322
+ index += separatorLength - 1;
323
+ tokenStart = true;
324
+ afterSeparator = true;
325
+ continue;
326
+ }
327
+ if (char === '&' || char === '|') return null;
328
+ segment += char;
329
+ tokenStart = false;
330
+ afterSeparator = false;
222
331
  }
223
332
  if (quote) return null;
224
- const finalSegment = command.slice(start).trim();
225
- if (!finalSegment || segments.length >= LIMITS.commandSegments) return null;
226
- segments.push(finalSegment);
333
+ const finalSegment = segment.trim();
334
+ if (afterSeparator) return null;
335
+ if (finalSegment) {
336
+ if (segments.length >= LIMITS.commandSegments) return null;
337
+ segments.push(finalSegment);
338
+ }
227
339
  return segments;
228
340
  }
229
341
 
@@ -139,7 +139,13 @@ function processState(payload) {
139
139
  const isDirectTool = toolName === 'Edit' || toolName === 'Write' || toolName === 'apply_patch';
140
140
  if (isDirectTool && (agy
141
141
  ? agyDirectMutationInWorkspace(payload, cwdOf(payload, root), root, toolName)
142
- : directMutationInWorkspace(payload, cwdOf(payload, root), root))) state.lastEditAt = Date.now();
142
+ : directMutationInWorkspace(payload, cwdOf(payload, root), root))) {
143
+ state.lastEditAt = Date.now();
144
+ if (agy) {
145
+ const revision = Number.isSafeInteger(state.agyDirectMutationRevision) ? state.agyDirectMutationRevision : 0;
146
+ if (revision < Number.MAX_SAFE_INTEGER) state.agyDirectMutationRevision = revision + 1;
147
+ }
148
+ }
143
149
  const isShell = toolName === 'Bash' || toolName === 'PowerShell' || toolName === 'exec_command';
144
150
  const command = (payload.tool_input && payload.tool_input.command) || '';
145
151
  if (isShell) {
@@ -2,7 +2,7 @@
2
2
 
3
3
  Adds edit tracking, verification reminders, prompt routing, and observation hooks for OpenCode.
4
4
 
5
- > **Evidence boundary:** the plugin is covered by deterministic mechanism tests. Live plugin loading remains unverified beyond one scoped surface: retained evidence supports project-scope `.js` loading and edit/verification state on OpenCode 1.18.31 (macOS) — [live-host evidence](../benchmarks/results/live-host/opencode-2026-09-16/README.md). That retained snapshot is historical: its final state was post-reset; the hard-lock was only an interactive observation with no retained blocked-tool trace. Reflection was operator-seeded, then agent-rewritten, so no behavioral-effectiveness claim is made. The current plugin does not force reflection or block edits based on verification history. Global scope, npm-package installation, and other host versions remain unverified. See [`../docs/platform-capabilities.md`](../docs/platform-capabilities.md).
5
+ > **Support and evidence boundary:** Harness supports the **OpenCode V2 plugin API only**; OpenCode 1.x / V1 is unsupported (#453). The plugin is covered by deterministic V2 mechanism tests. Tested V2 live observations cover one isolated OpenCode `2.1.4` (macOS 26.6.2) long-lived server run ([V2 lifecycle trace](../benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/README.md): V2 default-export load, V2 tool hooks, V2 event envelope + `session.execution.succeeded` completion, and completion → verification → reminder delivery; standalone `opencode run` exits before verification finishes), alongside OpenCode `2.1.3` (macOS, server-log load-only) and OpenCode `2.1.4` (macOS, [workspace trace](../benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md)); router/context injection, observation recording, ledger lessons, session create/delete reset, cancellation, and a validated minimum patch version remain unverified. Retained historical/unsupported V1 evidence documents project-scope `.js` loading and edit/verification state on OpenCode 1.18.31 (macOS) — [live-host evidence](../benchmarks/results/live-host/opencode-2026-09-16/README.md). That retained snapshot is historical and does not establish current V2 capability: its final state was post-reset; the hard-lock was only an interactive observation with no retained blocked-tool trace. Reflection was operator-seeded, then agent-rewritten, so no behavioral-effectiveness claim is made. The current plugin does not force reflection or block edits based on verification history. Global scope, npm-package installation, and other host versions remain unverified. See [`../docs/platform-capabilities.md`](../docs/platform-capabilities.md).
6
6
 
7
7
  ## Problem
8
8
 
@@ -13,27 +13,25 @@ only SUGGEST rules (soft guidance). This means:
13
13
 
14
14
  ## The plugin
15
15
 
16
- **File:** `index.mjs` - the ESM plugin entrypoint. The OpenCode 2 adapter uses
17
- the documented prompt and context hooks; the V1 factory remains available for
18
- existing OpenCode 1 installations. There is no manifest-to-script
16
+ **File:** `index.mjs` - the OpenCode V2 ESM plugin entrypoint. Harness targets
17
+ the OpenCode V2 plugin API only; OpenCode 1.x / V1 is unsupported, and the
18
+ module's only public surface is its V2 default export
19
+ `{ id: "harness.enforcement", setup(ctx) }`. There is no manifest-to-script
19
20
  mechanism; an earlier version of this plugin assumed one (a `plugin.json`
20
21
  mapping event names to standalone scripts) and opencode never invoked it -
21
22
  see issue #37 for how that was found and fixed. **Naming caveat (issue
22
23
  #127):** opencode's discovery glob only matches `*.js`/`*.ts`, so the file
23
24
  must be copied to a `.js` name when installed - see Installation below.
24
25
 
25
- It implements edit tracking and verification reminders across OpenCode's hooks:
26
-
27
- The V1 factory follows opencode's plugin contract directly: the named
28
- `HarnessEnforcement` export is an async factory receiving the opencode context
29
- (`client`, `directory`, `project`, `worktree`, and `$`) and returning the hook
30
- map. Copying this one file into `.opencode/plugins/` under a `.js` name is
31
- enough for opencode to discover and invoke it; `plugin.json` is only a
32
- repository
33
- inventory and is not an opencode runtime manifest. The hook callbacks use the
34
- V1 `(input, output)` shape, including
35
- `output.args` when the host supplies tool arguments only in the result object.
36
- OpenCode 2's prompt injection and observation path resolves the canonical
26
+ It implements edit tracking, verification reminders, prompt/context routing,
27
+ and observation hooks through the OpenCode V2 plugin context:
28
+
29
+ `setup(ctx)` registers `ctx.session.hook("prompt|context")`,
30
+ `ctx.tool.hook("execute.before|after")`, and `ctx.event.subscribe()` and wires
31
+ them into a private internal enforcement core. Copying this one file into
32
+ `.opencode/plugins/` under a `.js` name is enough for opencode to discover and
33
+ invoke it; `plugin.json` is only a repository inventory and is not an opencode
34
+ runtime manifest. Prompt injection and observation capture resolve the canonical
37
35
  `harness-everything/scripts/kernel-router.js` and
38
36
  `hooks/scripts/lib/observations.js` from an ancestor Harness checkout/runtime.
39
37
 
@@ -42,16 +40,16 @@ OpenCode 2's prompt injection and observation path resolves the canonical
42
40
  Fires after every `edit`, `write` or `apply_patch` tool call and marks
43
41
  verification as pending.
44
42
 
45
- ### 2. Verification reminder (`event`, on `session.idle`)
43
+ ### 2. Verification reminder (`ctx.event.subscribe()`, on `session.execution.succeeded`)
46
44
 
47
- opencode has no "before complete" hook to block the way Claude Code's Stop
48
- hook does. `session.idle` - fired when the agent's turn ends - is the closest
49
- analog, and it cannot be blocked (the hook has no return value that denies
50
- it). So when it fires with verification still pending, the plugin runs the
51
- available `npm test` / `npm run lint` / `npm run build` scripts right there,
52
- and on failure calls `client.session.prompt()` to push a synthetic follow-up
53
- message into the session - forcing the agent to keep working instead of
54
- actually stopping.
45
+ OpenCode has no "before complete" hook to block the way Claude Code's Stop
46
+ hook does. `session.execution.succeeded` (carrying `data.sessionID`) - fired
47
+ when the agent's turn completes in OpenCode V2 - is the closest analog, and it
48
+ cannot be blocked. So when it fires with verification still pending, the plugin
49
+ runs the available `npm test` / `npm run lint` / `npm run build` scripts right
50
+ there, and on failure calls `ctx.session.prompt()` to push a synthetic follow-up
51
+ message into the session - prompting the agent to keep working instead of
52
+ stopping with unverified edits.
55
53
 
56
54
  The async runner streams stdout/stderr and gives the **whole ordered sequence**
57
55
  (`test`, `lint`, `build`) one wall-clock budget: 10 minutes by default, overridden
@@ -65,7 +63,7 @@ signal, or cancellation). The follow-up describes the verification outcome.
65
63
  |---|---|
66
64
  | Retained output | First and last 2,000 characters per stream; the final diagnostic shares a 2,000-character budget across streams, plus labels/elision markers |
67
65
  | Timeout/cancel | Terminate the shell/npm/script process group, then force-kill after 150 ms on POSIX; Windows uses `taskkill /T /F` |
68
- | Concurrent lifecycle | Duplicate idle events share the active run; a code edit or session reset aborts it; an idle arriving during cancellation waits for cleanup before verifying the newer edits; the V2 event stream continues consuming cancellation events; disposal awaits active child cleanup; stale results cannot clear newer edits or recreate deleted state |
66
+ | Concurrent lifecycle | Duplicate turn-completion events share the active run; a code edit or session reset aborts it; a completion arriving during cancellation waits for cleanup before verifying the newer edits; the V2 event stream continues consuming cancellation events; disposal awaits active child cleanup; stale results cannot clear newer edits or recreate deleted state |
69
67
 
70
68
  The event loop remains available while scripts run. The output-retention limit
71
69
  never becomes a check verdict. Mechanism tests cover large output, shared
@@ -73,28 +71,22 @@ budget, child cleanup and concurrent hooks; these are deterministic mechanism
73
71
  evidence, not a new live-host verification claim. Processes deliberately
74
72
  escaping the process group are outside this cleanup boundary.
75
73
 
76
- Idle handling is bounded: after a failed verification, the plugin records that
77
- the follow-up is pending and ignores repeated `session.idle` events until a new
78
- code edit arrives. If prompt delivery fails, the exact follow-up text is saved
79
- and retried on the next idle event without re-running verification.
74
+ Completion handling is bounded: after a failed verification, the plugin records
75
+ that the follow-up is pending and ignores repeated `session.execution.succeeded`
76
+ events until a new code edit arrives. If prompt delivery fails, the exact
77
+ follow-up text is saved and retried on the next completion event without
78
+ re-running verification.
80
79
 
81
80
  ## Installation
82
81
 
83
- **OpenCode 2.x:** the module default-exports
82
+ **OpenCode V2 plugin API only:** the module default-exports
84
83
  `{ id: "harness.enforcement", setup(ctx) }` and registers
85
84
  `ctx.session.hook("prompt|context")`, `ctx.tool.hook("execute.before|after")`,
86
- plus `ctx.event.subscribe()` through the OpenCode 2 plugin context. OpenCode 2
87
- never loads a named-export-only plugin: it fails with `Plugin must export a
88
- default definition with an id and an effect or setup function`
89
- (SchemaError at `["default"]`). The named `HarnessEnforcement` export stays
90
- available for OpenCode 1.x hosts: it receives the V1 context
91
- (`{client, directory}`) and returns a V1 hooks object
92
- (`tool.execute.before`, `tool.execute.after`, `event`); the V2 `setup`
93
- adapter wraps that factory and maps the V2 hook events onto it, so the
94
- enforcement logic is shared, not duplicated.
95
-
96
- The prompt/context routing and System One observation hooks are V2-only. The
97
- V1 factory keeps its existing enforcement hooks; it does not capture turns.
85
+ plus `ctx.event.subscribe()` through the OpenCode V2 plugin context. No named
86
+ V1 factory, host `session.idle`, or legacy session-id event fallback is
87
+ exported or supported; OpenCode 1.x / V1 is unsupported. OpenCode V2 rejects
88
+ named-export-only plugins with `Plugin must export a default definition with an
89
+ id and an effect or setup function` (SchemaError at `["default"]`).
98
90
 
99
91
  When OpenCode runs on Bun, its Harness router needs `node` on the OpenCode
100
92
  process's `PATH`. Run `node --version` from the same environment that launches
@@ -102,9 +94,6 @@ OpenCode and check it against the [Harness Node.js baseline](../docs/repository-
102
94
  If the router cannot start or load, OpenCode still admits prompts and logs a
103
95
  `router-unavailable` warning with a reason and per-plugin count.
104
96
 
105
- Direction:
106
- named factory (V1 hosts/tests) → default-export setup adapter → V2 domains.
107
-
108
97
  Copy `index.mjs` into opencode's plugin directory **under a `.js` filename**.
109
98
  The router and observation hooks resolve from a Harness checkout above the
110
99
  plugin, or from sibling `harness-everything/`, `hooks/scripts/`, and
@@ -126,16 +115,16 @@ cp -R scripts/lib ~/.config/opencode/scripts/
126
115
  Restart OpenCode after copying so the plugin is discovered at startup.
127
116
 
128
117
  The destination extension matters: opencode's plugin auto-discovery scans
129
- only `*.js` / `*.ts` files in those directories (`{plugin,plugins}/*.{ts,js}`
130
- in its v1 loader), so a `.mjs` copy is **silently never loaded** - no error,
131
- no hooks, no state. Verified live on opencode 1.18.31 with an extension A/B
132
- probe (see
118
+ only `*.js` / `*.ts` files in those directories, so a `.mjs` copy is **silently
119
+ never loaded** - no error, no hooks, no state. Keep the `.js` install filename
120
+ for current V2 installs (the original extension A/B probe is preserved as
121
+ historical evidence in
133
122
  [`benchmarks/results/live-host/opencode-2026-09-16/probe-control.md`](../benchmarks/results/live-host/opencode-2026-09-16/probe-control.md)).
134
123
 
135
124
  opencode auto-loads `.js`/`.ts` files dropped in those directories at startup -
136
- no `opencode.json` entry needed. This procedure tests directory discovery;
137
- explicit local-file configuration and npm-package installation are separate
138
- installation surfaces and were not verified in this run.
125
+ no `opencode.json` entry needed. Explicit local-file configuration and
126
+ npm-package installation are separate installation surfaces and remain
127
+ unverified.
139
128
 
140
129
  ## Manual verification CLI
141
130
 
@@ -169,20 +158,25 @@ session root.
169
158
 
170
159
  ## Testing
171
160
 
172
- `ci/mechanism-2n-opencode-plugin.test.js` imports `index.mjs` and drives its
173
- exported hooks directly with a mock `client`/`event` context - the same shape
174
- OpenCode's plugin loader passes in - covering edit → idle → reminder, repeated
175
- failures, legacy pending state remaining inert, prompt-delivery retry,
176
- repeated-idle idempotency, session isolation, reset behavior, and legacy-state
177
- migration. `ci/mechanism-2p-opencode-v2-entrypoint.test.js` exercises the same
178
- edit and legacy-state paths through the default V2 export.
179
-
180
- It does not launch a real opencode process; the test remains a deterministic
181
- hook-sequence check against the documented and source-verified hook signatures.
182
- A passing test is therefore mechanism evidence, not live-host loading evidence.
183
- Live-host evidence and the install-filename loadability guard live elsewhere:
184
- the host session artifact is
161
+ `ci/mechanism-2n-opencode-plugin.test.js` and
162
+ `ci/mechanism-2p-opencode-v2-entrypoint.test.js` import `index.mjs`, enforce the
163
+ V2-only default-export contract (`{ id, setup(ctx) }`), and drive the registered
164
+ V2 hooks with a mock V2 `ctx` - covering edit → `session.execution.succeeded` →
165
+ reminder, repeated failures, legacy pending state remaining inert,
166
+ prompt-delivery retry, repeated-completion idempotency, session isolation, reset
167
+ behavior, and legacy-state migration.
168
+
169
+ They do not launch a real opencode process; the tests remain deterministic
170
+ hook-sequence checks against the documented and source-verified V2 hook
171
+ signatures. A passing test is therefore mechanism evidence, not live-host
172
+ loading evidence. The isolated OpenCode 2.1.4 (macOS 26.6.2) V2 lifecycle trace
173
+ lives at
174
+ [`benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/`](../benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/),
175
+ the limited OpenCode 2.1.4 workspace trace lives at
176
+ [`benchmarks/results/live-host/opencode-2026-11-15-workspace/`](../benchmarks/results/live-host/opencode-2026-11-15-workspace/),
177
+ the historical/unsupported 1.18.31 archive lives at
185
178
  [`benchmarks/results/live-host/opencode-2026-09-16/`](../benchmarks/results/live-host/opencode-2026-09-16/),
186
179
  and `ci/mechanism-30-opencode-plugin-loadability.test.js` (npm script
187
180
  `test:opencode:loadability`) fails any change that reintroduces a
188
181
  silently-ignored install filename such as `harness-enforcement.mjs`.
182
+ Verification reminders need a long-lived server (`opencode serve` + `opencode run --server`); `opencode run --standalone` exits before verification completes.