harness-everything 0.57.4 → 1.0.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 (67) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.releaserc.json +2 -0
  4. package/AGENTS.md +8 -2
  5. package/CHANGELOG.md +23 -0
  6. package/README.md +4 -4
  7. package/benchmarks/results/live-host/agy-2026-11-22/README.md +49 -0
  8. package/benchmarks/results/live-host/agy-2026-11-23/README.md +48 -0
  9. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/README.md +40 -0
  10. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/edit-state-final.json +11 -0
  11. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/events-2026-11-24.jsonl +103 -0
  12. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/host-version.txt +3 -0
  13. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/live-event-trace-probe.js +11 -0
  14. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/plugin-load-lines.txt +2 -0
  15. package/benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/reminder-excerpt.txt +1 -0
  16. package/ci/doc-capability-consistency.test.js +15 -3
  17. package/ci/lib/opencode-v2-driver.js +169 -0
  18. package/ci/mechanism-2ao-plugin-sync.test.js +235 -2
  19. package/ci/mechanism-2n-opencode-plugin.test.js +387 -223
  20. package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +24 -15
  21. package/ci/mechanism-2u-issue-42-regressions.test.js +41 -2
  22. package/ci/mechanism-2w-platform-compatibility.test.js +29 -5
  23. package/ci/mechanism-2x-release-automation.test.js +3 -1
  24. package/ci/mechanism-30-opencode-plugin-loadability.test.js +78 -45
  25. package/ci/mechanism-338-opencode-async.test.js +367 -194
  26. package/ci/mechanism-341-opencode-lane.test.js +143 -183
  27. package/ci/mechanism-39-opencode-verify-outcomes.test.js +118 -86
  28. package/ci/mechanism-394-opencode-ledger-lesson.test.js +46 -97
  29. package/ci/mechanism-397-opencode-observations.test.js +58 -47
  30. package/ci/mechanism-453-opencode-v2-driver.test.js +51 -0
  31. package/ci/mechanism-453-opencode-v2-only-events.test.js +241 -0
  32. package/ci/mechanism-agy-hooks.test.js +1096 -0
  33. package/ci/mechanism-agy-plugin-package.test.js +76 -0
  34. package/ci/telemetry.test.js +31 -24
  35. package/docs/architecture.md +4 -2
  36. package/docs/platform-capabilities.md +62 -26
  37. package/docs/platform-compatibility.json +41 -6
  38. package/docs/system-one-observations.md +1 -1
  39. package/docs/telemetry.md +1 -1
  40. package/docs/troubleshooting.md +2 -2
  41. package/hooks/scripts/agy-post-tool.js +124 -0
  42. package/hooks/scripts/agy-pre-invocation.js +185 -0
  43. package/hooks/scripts/agy-pre-tool.js +158 -0
  44. package/hooks/scripts/agy-session-start.js +54 -0
  45. package/hooks/scripts/agy-stop.js +152 -0
  46. package/hooks/scripts/lib/agy-adapter-core.js +168 -0
  47. package/hooks/scripts/state-persist.js +50 -10
  48. package/opencode-plugin/README.md +60 -66
  49. package/opencode-plugin/index.mjs +11 -13
  50. package/opencode-plugin/plugin.json +1 -1
  51. package/package.json +1 -1
  52. package/plugins/harness-everything/.antigravity-plugin/plugin.json +18 -0
  53. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  54. package/plugins/harness-everything/hooks/scripts/agy-post-tool.js +124 -0
  55. package/plugins/harness-everything/hooks/scripts/agy-pre-invocation.js +185 -0
  56. package/plugins/harness-everything/hooks/scripts/agy-pre-tool.js +158 -0
  57. package/plugins/harness-everything/hooks/scripts/agy-session-start.js +54 -0
  58. package/plugins/harness-everything/hooks/scripts/agy-stop.js +152 -0
  59. package/plugins/harness-everything/hooks/scripts/lib/agy-adapter-core.js +168 -0
  60. package/plugins/harness-everything/hooks/scripts/state-persist.js +50 -10
  61. package/plugins/harness-everything/hooks.json +44 -0
  62. package/plugins/harness-everything/plugin.json +1 -1
  63. package/plugins/harness-everything/rules/AGENTS.md +117 -0
  64. package/sbom.cdx.json +12 -12
  65. package/scripts/plugin-sync.js +105 -14
  66. package/scripts/sync-openai-plugin.js +16 -1
  67. package/scripts/sync-release-version.js +1 -0
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Antigravity (AGY) PreInvocation Hook Adapter
6
+ *
7
+ * Runs before model invocation. Invokes the Harness kernel router and ledger lessons
8
+ * ONCE per user turn (deduplicated across tool-call roundtrips within a turn), then
9
+ * returns systemMessage injectSteps in AGY's required protojson format.
10
+ * Bridges AGY conversationId to session_id for workflow persistence.
11
+ */
12
+
13
+ const crypto = require('crypto');
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const { spawnSync } = require('child_process');
17
+ const {
18
+ readJsonStdin,
19
+ resolveKernelRouter,
20
+ getAgySessionId,
21
+ getAgyEffectiveCwd,
22
+ normalizeAgyStatePayload
23
+ } = require('./lib/agy-adapter-core');
24
+ const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
25
+
26
+ const DEDUP_STATE_FILE = 'agy-pre-invocation-state.json';
27
+
28
+ function hashUserInput(text) {
29
+ return crypto.createHash('sha256').update(String(text || ''), 'utf8').digest('hex').slice(0, 16);
30
+ }
31
+
32
+ function readDedupState(filePath) {
33
+ try {
34
+ if (!fs.existsSync(filePath)) return null;
35
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
36
+ return parsed && typeof parsed === 'object' ? parsed : null;
37
+ } catch (_) {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ function writeDedupState(filePath, state) {
43
+ try {
44
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
45
+ const temp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
46
+ fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', 'utf8');
47
+ fs.renameSync(temp, filePath);
48
+ } catch (_) {
49
+ // Best-effort marker write; never fail invocation on state IO.
50
+ }
51
+ }
52
+
53
+ function shouldSkipInjection(payload, userInput, dedupFile) {
54
+ const hasInvNum = payload && payload.invocationNum !== undefined && payload.invocationNum !== null && payload.invocationNum !== '';
55
+ const invNum = hasInvNum ? Number(payload.invocationNum) : 0;
56
+ const hasInitialSteps = payload && payload.initialNumSteps !== undefined && payload.initialNumSteps !== null && payload.initialNumSteps !== '';
57
+ const inputHash = hashUserInput(userInput);
58
+ const turnKey = hasInitialSteps
59
+ ? `step:${payload.initialNumSteps}:${inputHash}`
60
+ : `input:${inputHash}`;
61
+
62
+ if (!dedupFile) {
63
+ return {
64
+ skip: Number.isFinite(invNum) && invNum > 0,
65
+ turnKey,
66
+ invNum: Number.isFinite(invNum) ? invNum : 0,
67
+ base: 0
68
+ };
69
+ }
70
+
71
+ const saved = readDedupState(dedupFile);
72
+ const sameTurn = Boolean(saved && saved.turnKey === turnKey);
73
+
74
+ if (sameTurn) {
75
+ // When initialNumSteps is absent and a host explicitly sends invocationNum: 0
76
+ // (or restarts at 0 after a previous positive invocation), treat it as a new turn.
77
+ if (!hasInitialSteps && (saved.sawPositiveInvocation || hasInvNum) && Number.isFinite(invNum) && invNum === 0) {
78
+ return { skip: false, turnKey, invNum: 0, base: 0 };
79
+ }
80
+ if (Number.isFinite(invNum) && invNum > 0 && !saved.sawPositiveInvocation) {
81
+ writeDedupState(dedupFile, { ...saved, sawPositiveInvocation: true, updatedAt: new Date().toISOString() });
82
+ }
83
+ return { skip: true, turnKey, invNum: Number.isFinite(invNum) ? invNum : 0, base: saved.base || 0 };
84
+ }
85
+
86
+ // Not the same turnKey: guard against mid-turn calls (both 0-based and 1-based).
87
+ if (Number.isFinite(invNum) && invNum > 1) {
88
+ return { skip: true, turnKey, invNum, base: (saved && saved.base) || 0 };
89
+ }
90
+ if (Number.isFinite(invNum) && invNum === 1 && (!hasInitialSteps || (saved && saved.base === 0))) {
91
+ return { skip: true, turnKey, invNum, base: 0 };
92
+ }
93
+
94
+ const base = Number.isFinite(invNum) && invNum === 1 ? 1 : 0;
95
+ return { skip: false, turnKey, invNum: Number.isFinite(invNum) ? invNum : 0, base };
96
+ }
97
+
98
+ async function main() {
99
+ const payload = await readJsonStdin();
100
+ const userInput = payload.lastUserInput || payload.prompt || '';
101
+ const routerScript = resolveKernelRouter();
102
+
103
+ if (!routerScript || !String(userInput).trim()) {
104
+ process.stdout.write(JSON.stringify({ injectSteps: [] }) + '\n');
105
+ return;
106
+ }
107
+
108
+ const sessionId = getAgySessionId(payload);
109
+ const effectiveCwd = getAgyEffectiveCwd(payload);
110
+ const normalizedPayload = normalizeAgyStatePayload(payload, effectiveCwd);
111
+
112
+ let dedupFile = null;
113
+ if (sessionId) {
114
+ try {
115
+ const root = getWorkspaceRoot(normalizedPayload) || effectiveCwd;
116
+ const sessionDir = getSessionDir(root, sessionId);
117
+ dedupFile = path.join(sessionDir, DEDUP_STATE_FILE);
118
+ } catch (_) {
119
+ dedupFile = null;
120
+ }
121
+ }
122
+
123
+ const dedup = shouldSkipInjection(payload, userInput, dedupFile);
124
+ if (dedup.skip) {
125
+ process.stdout.write(JSON.stringify({ injectSteps: [] }) + '\n');
126
+ return;
127
+ }
128
+
129
+ try {
130
+ const routerInput = {
131
+ hook_event_name: 'UserPromptSubmit',
132
+ prompt: userInput,
133
+ lastUserInput: userInput,
134
+ cwd: effectiveCwd,
135
+ conversationId: sessionId,
136
+ session_id: sessionId,
137
+ sessionId: sessionId,
138
+ ...(payload.workspacePaths ? { workspacePaths: payload.workspacePaths } : {})
139
+ };
140
+
141
+ const run = spawnSync(process.execPath, [routerScript], {
142
+ input: JSON.stringify(routerInput),
143
+ encoding: 'utf8',
144
+ env: process.env,
145
+ timeout: 20000
146
+ });
147
+
148
+ const context = String(run.stdout || '').trim();
149
+ if (context) {
150
+ if (dedupFile) {
151
+ writeDedupState(dedupFile, {
152
+ turnKey: dedup.turnKey,
153
+ base: dedup.base,
154
+ sawPositiveInvocation: dedup.invNum > 0,
155
+ updatedAt: new Date().toISOString()
156
+ });
157
+ }
158
+ const response = {
159
+ injectSteps: [
160
+ {
161
+ systemMessage: {
162
+ systemMessage: context
163
+ }
164
+ }
165
+ ]
166
+ };
167
+ process.stdout.write(JSON.stringify(response) + '\n');
168
+ return;
169
+ }
170
+ } catch (err) {
171
+ if (process.env.HARNESS_DEBUG) {
172
+ console.error('[AGY-PreInvocation] Routing error:', err);
173
+ }
174
+ }
175
+
176
+ process.stdout.write(JSON.stringify({ injectSteps: [] }) + '\n');
177
+ }
178
+
179
+ if (require.main === module) {
180
+ main().catch(() => {
181
+ process.stdout.write(JSON.stringify({ injectSteps: [] }) + '\n');
182
+ });
183
+ }
184
+
185
+ module.exports = { main, shouldSkipInjection };
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Antigravity (AGY) PreToolUse Hook Adapter
6
+ *
7
+ * Intercepts tool execution to enforce:
8
+ * - Worktree and filesystem boundary containment for file writes
9
+ * (allows writes inside any workspacePaths entry, cwd, or artifactDirectoryPath).
10
+ * - Canonical Action Gate policies (destructive operations, forced pushes, publish, reset).
11
+ *
12
+ * Returns protojson: {"decision": "allow" | "deny" | "ask", "reason": "..."}
13
+ */
14
+
15
+ const {
16
+ readJsonStdin,
17
+ getAgySessionId,
18
+ getAgyWorkspacePaths,
19
+ getAgyEffectiveCwd,
20
+ isOutOfBoundsPath
21
+ } = require('./lib/agy-adapter-core');
22
+ const { evaluatePreToolUse } = require('./action-gate');
23
+
24
+ const FILE_MUTATION_TOOLS = new Set([
25
+ 'write_file',
26
+ 'edit_file',
27
+ 'write_to_file',
28
+ 'replace_file_content',
29
+ 'multi_replace_file_content'
30
+ ]);
31
+
32
+ function extractToolCall(payload) {
33
+ if (!payload || typeof payload !== 'object') {
34
+ return { id: undefined, name: '', args: {} };
35
+ }
36
+ const raw = payload.toolCall && typeof payload.toolCall === 'object' ? payload.toolCall : null;
37
+ const name = (raw && raw.name) || payload.tool_name || payload.toolName || payload.tool || '';
38
+ const args = (raw && raw.args && typeof raw.args === 'object')
39
+ ? raw.args
40
+ : ((payload.tool_input && typeof payload.tool_input === 'object') ? payload.tool_input : {});
41
+ const id = (raw && raw.id) || payload.tool_use_id || payload.toolUseId || undefined;
42
+ return { id, name, args };
43
+ }
44
+
45
+ function collectAllowedWriteRoots(cwd, context = {}) {
46
+ const payload = (context && context.payload) || {};
47
+ const roots = [];
48
+ if (Array.isArray(context.workspacePaths)) {
49
+ for (const entry of context.workspacePaths) {
50
+ if (typeof entry === 'string' && entry.trim()) roots.push(entry.trim());
51
+ }
52
+ }
53
+ for (const entry of getAgyWorkspacePaths(payload)) {
54
+ roots.push(entry);
55
+ }
56
+ if (typeof cwd === 'string' && cwd.trim()) {
57
+ roots.push(cwd.trim());
58
+ }
59
+ const artifactDir = context.artifactDirectoryPath || payload.artifactDirectoryPath;
60
+ if (typeof artifactDir === 'string' && artifactDir.trim()) {
61
+ roots.push(artifactDir.trim());
62
+ }
63
+ return [...new Set(roots)];
64
+ }
65
+
66
+ function evaluateToolCall(toolCall, cwd, context = {}) {
67
+ if (!toolCall || !toolCall.name) {
68
+ return { decision: 'allow' };
69
+ }
70
+
71
+ const name = toolCall.name;
72
+ const args = (toolCall.args && typeof toolCall.args === 'object') ? toolCall.args : {};
73
+
74
+ // 1. Filesystem boundary containment for file mutations
75
+ if (FILE_MUTATION_TOOLS.has(name)) {
76
+ const rawPath = args.TargetFile ?? args.Path ?? args.path ?? args.targetFile ?? args.filePath ?? args.file_path;
77
+ const filePath = typeof rawPath === 'string' ? rawPath.trim() : '';
78
+ if (!filePath) {
79
+ return {
80
+ decision: 'deny',
81
+ reason: `Harness boundary guard: missing target file path for ${name}.`
82
+ };
83
+ }
84
+
85
+ const allowedRoots = collectAllowedWriteRoots(cwd, context);
86
+ if (isOutOfBoundsPath(filePath, allowedRoots, cwd)) {
87
+ return {
88
+ decision: 'deny',
89
+ reason: `Harness boundary guard: modification outside workspace root is forbidden (${filePath}).`
90
+ };
91
+ }
92
+ return { decision: 'allow' };
93
+ }
94
+
95
+ // 2. Command safety via canonical Action Gate
96
+ if (name === 'run_command') {
97
+ const command = String(args.CommandLine || args.command || '').trim();
98
+ if (!command) {
99
+ return { decision: 'allow' };
100
+ }
101
+
102
+ const payload = context.payload || {};
103
+ const sessionId = context.sessionId || getAgySessionId(payload) || undefined;
104
+ const commandCwd = (typeof args.Cwd === 'string' && args.Cwd.trim())
105
+ || (typeof args.cwd === 'string' && args.cwd.trim())
106
+ || cwd;
107
+ const toolUseId = toolCall.id || payload.tool_use_id || payload.toolUseId || undefined;
108
+
109
+ const actionPayload = {
110
+ hook_event_name: 'PreToolUse',
111
+ tool_name: 'Bash',
112
+ tool_input: { command },
113
+ ...(toolUseId ? { tool_use_id: toolUseId } : {}),
114
+ cwd: commandCwd,
115
+ ...(cwd ? { workspace_root: cwd } : {}),
116
+ ...(sessionId ? { session_id: sessionId, sessionId } : {})
117
+ };
118
+
119
+ const gateResult = evaluatePreToolUse(actionPayload, { host: 'agy' });
120
+
121
+ if (gateResult.kind === 'block') {
122
+ const reason = gateResult.rule
123
+ ? `[Harness actionGate:${gateResult.rule.id}] ${gateResult.rule.reason}`
124
+ : (gateResult.stderr || 'Harness action gate: command rejected.');
125
+ return { decision: 'deny', reason };
126
+ }
127
+
128
+ if (gateResult.kind === 'ask') {
129
+ const reason = gateResult.rule
130
+ ? `[Harness actionGate:${gateResult.rule.id}] ${gateResult.rule.reason}`
131
+ : 'Harness action gate: confirmation required.';
132
+ return { decision: 'ask', reason };
133
+ }
134
+
135
+ return { decision: 'allow' };
136
+ }
137
+
138
+ return { decision: 'allow' };
139
+ }
140
+
141
+ async function main() {
142
+ const payload = await readJsonStdin();
143
+ const cwd = getAgyEffectiveCwd(payload);
144
+ const toolCall = extractToolCall(payload);
145
+ const sessionId = getAgySessionId(payload) || undefined;
146
+
147
+ const result = evaluateToolCall(toolCall, cwd, { sessionId, payload });
148
+ process.stdout.write(JSON.stringify(result) + '\n');
149
+ }
150
+
151
+ if (require.main === module) {
152
+ main().catch(err => {
153
+ // Fail closed on evaluation failure if error occurs
154
+ process.stdout.write(JSON.stringify({ decision: 'deny', reason: `Internal hook error: ${err.message}` }) + '\n');
155
+ });
156
+ }
157
+
158
+ module.exports = { main, evaluateToolCall, extractToolCall };
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Antigravity (AGY) SessionStart Hook Adapter
6
+ *
7
+ * Runs once when a new conversation session begins.
8
+ * Binds session workspace identity (when provided) and injects Harness bootstrap message.
9
+ */
10
+
11
+ const {
12
+ readJsonStdin,
13
+ getAgySessionId,
14
+ normalizeAgyStatePayload
15
+ } = require('./lib/agy-adapter-core');
16
+ const { getWorkspaceRoot } = require('./lib/harness-state');
17
+
18
+ async function main() {
19
+ const payload = await readJsonStdin();
20
+
21
+ try {
22
+ const sessionId = getAgySessionId(payload);
23
+ const hasWorkspaceHint = Boolean(
24
+ (typeof payload.cwd === 'string' && payload.cwd.trim()) ||
25
+ (Array.isArray(payload.workspacePaths) && payload.workspacePaths.some(entry => typeof entry === 'string' && entry.trim()))
26
+ );
27
+ if (sessionId && hasWorkspaceHint) {
28
+ const normalized = normalizeAgyStatePayload(payload);
29
+ getWorkspaceRoot(normalized);
30
+ }
31
+ } catch (_) {
32
+ // Session workspace binding is best-effort and must never fail startup.
33
+ }
34
+
35
+ const response = {
36
+ injectSteps: [
37
+ {
38
+ systemMessage: {
39
+ systemMessage: 'Harness Skills OS active. Operating under AGENTS.md invariant-first routing.'
40
+ }
41
+ }
42
+ ]
43
+ };
44
+
45
+ process.stdout.write(JSON.stringify(response) + '\n');
46
+ }
47
+
48
+ if (require.main === module) {
49
+ main().catch(() => {
50
+ process.stdout.write('{}\n');
51
+ });
52
+ }
53
+
54
+ module.exports = { main };
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Antigravity (AGY) Stop Hook Adapter
6
+ *
7
+ * Implements the Verify-Before-Claim gate:
8
+ * - Inspects real session verification state (handoff-state.json in sessionDir).
9
+ * - If unverified edits exist or an unresolved tool failure exists, returns
10
+ * {"decision": "continue", "reason": "..."} to keep the agent in the loop.
11
+ * - If verified (or no unverified edits), returns {"decision": "allow"}.
12
+ * - Tracks the last continued state fingerprint in agy-stop-state.json so each
13
+ * unverified edit or failure triggers at most one forced continuation (preventing
14
+ * infinite loops on hosts that omit exitCode or continuationActive).
15
+ * - Respects compatibility recursion guards (continuationActive / stop_hook_active)
16
+ * to prevent infinite continuation loops, and allows stop on explicit abnormal
17
+ * terminationReason values (USER_CANCELED, ERROR, limits, etc.) while evaluating
18
+ * NO_TOOL_CALL, model_stop, and empty/normal reasons.
19
+ */
20
+
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const {
24
+ readJsonStdin,
25
+ getAgySessionId,
26
+ normalizeAgyStatePayload
27
+ } = require('./lib/agy-adapter-core');
28
+ const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
29
+
30
+ const STOP_STATE_FILE = 'agy-stop-state.json';
31
+
32
+ function readStopState(filePath) {
33
+ try {
34
+ if (!fs.existsSync(filePath)) return null;
35
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
36
+ return parsed && typeof parsed === 'object' ? parsed : null;
37
+ } catch (_) {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ function writeStopState(filePath, state) {
43
+ try {
44
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
45
+ const temp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
46
+ fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', 'utf8');
47
+ fs.renameSync(temp, filePath);
48
+ } catch (_) {
49
+ // Best-effort marker write; never fail stop evaluation on state IO.
50
+ }
51
+ }
52
+
53
+ const ABNORMAL_TERMINATION_REASONS = new Set([
54
+ 'USER_CANCELED',
55
+ 'CANCELED',
56
+ 'CANCELLED',
57
+ 'ERROR',
58
+ 'MAX_INVOCATIONS',
59
+ 'MAX_STEPS_EXCEEDED',
60
+ 'MAX_TOKEN_BUDGET_EXCEEDED',
61
+ 'TERMINAL_CUSTOM_HOOK',
62
+ 'INTERRUPTED',
63
+ 'ABORTED'
64
+ ]);
65
+
66
+ function evaluateStop(payload) {
67
+ if (!payload || typeof payload !== 'object') return { decision: 'allow' };
68
+
69
+ // 1. Compatibility recursion guards (not official documented Stop input fields):
70
+ // if a previous Stop hook already continued work during this turn, allow stop to prevent loops.
71
+ if (payload.continuationActive || payload.stop_hook_active) {
72
+ return { decision: 'allow' };
73
+ }
74
+
75
+ // 2. Allow stop only on explicit abnormal termination reasons; normal reasons
76
+ // (NO_TOOL_CALL, model_stop, empty/unknown) must still evaluate handoff-state.json.
77
+ const terminationReason = typeof payload.terminationReason === 'string'
78
+ ? payload.terminationReason.trim().toUpperCase()
79
+ : '';
80
+ if (terminationReason && ABNORMAL_TERMINATION_REASONS.has(terminationReason)) {
81
+ return { decision: 'allow' };
82
+ }
83
+
84
+ // 3. Locate session state using normalized AGY workspace/session context
85
+ const normalized = normalizeAgyStatePayload(payload);
86
+ const sessionId = getAgySessionId(payload);
87
+ const root = getWorkspaceRoot(normalized) || normalized.cwd;
88
+ const sessionDir = getSessionDir(root, sessionId);
89
+ const handoffFile = path.join(sessionDir, 'handoff-state.json');
90
+
91
+ let handoff = null;
92
+ if (fs.existsSync(handoffFile)) {
93
+ try {
94
+ handoff = JSON.parse(fs.readFileSync(handoffFile, 'utf8'));
95
+ } catch (_) {}
96
+ }
97
+
98
+ const lastEditAt = (handoff && handoff.lastEditAt) || 0;
99
+ const lastVerifyAt = (handoff && handoff.lastVerifyAt) || 0;
100
+ const isFailed = handoff && handoff.status === 'failed';
101
+
102
+ // 4. Check for unverified edits or unresolved failure (bounded to 1 continuation per pending state)
103
+ let pending = null;
104
+ if (isFailed) {
105
+ pending = {
106
+ fingerprint: `failed:${handoff.timestamp || ''}:${handoff.tool || ''}:${handoff.exitCode ?? ''}`,
107
+ reason: 'Harness Verify-Before-Claim: pending tool failure must be resolved before claiming completion.'
108
+ };
109
+ } else if (lastEditAt > 0 && lastVerifyAt < lastEditAt) {
110
+ pending = {
111
+ fingerprint: `edit:${lastEditAt}`,
112
+ reason: 'Harness Verify-Before-Claim: unverified edits exist in session. Run relevant test/build/lint verification before claiming completion.'
113
+ };
114
+ } else if (process.env.HARNESS_REQUIRE_VERIFICATION === '1' && (!lastVerifyAt || lastVerifyAt < lastEditAt)) {
115
+ pending = {
116
+ fingerprint: `strict:${lastVerifyAt}`,
117
+ reason: 'Harness Verify-Before-Claim: objective test verification is required before claiming completion.'
118
+ };
119
+ }
120
+
121
+ if (pending) {
122
+ const stopStateFile = path.join(sessionDir, STOP_STATE_FILE);
123
+ const saved = readStopState(stopStateFile);
124
+ if (saved && saved.lastContinuedFingerprint === pending.fingerprint) {
125
+ return { decision: 'allow' };
126
+ }
127
+ writeStopState(stopStateFile, {
128
+ lastContinuedFingerprint: pending.fingerprint,
129
+ updatedAt: new Date().toISOString()
130
+ });
131
+ return {
132
+ decision: 'continue',
133
+ reason: pending.reason
134
+ };
135
+ }
136
+
137
+ return { decision: 'allow' };
138
+ }
139
+
140
+ async function main() {
141
+ const payload = await readJsonStdin();
142
+ const result = evaluateStop(payload);
143
+ process.stdout.write(JSON.stringify(result) + '\n');
144
+ }
145
+
146
+ if (require.main === module) {
147
+ main().catch(() => {
148
+ process.stdout.write('{"decision":"allow"}\n');
149
+ });
150
+ }
151
+
152
+ module.exports = { main, evaluateStop };