harness-everything 0.55.2 → 0.55.4

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 (177) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/AGENTS.md +1 -1
  4. package/BENCHMARK_SOP.md +2 -2
  5. package/CHANGELOG.md +22 -0
  6. package/README.md +15 -16
  7. package/SECURITY.md +1 -1
  8. package/VERIFICATION.md +4 -8
  9. package/behavioral-evals/PAIRED-BENCHMARK.md +12 -27
  10. package/behavioral-evals/README.md +21 -65
  11. package/behavioral-evals/cases/breaker-zoom-out-after-3.yaml +26 -33
  12. package/behavioral-evals/cases/pressure-sunk-cost-retry.yaml +15 -17
  13. package/behavioral-evals/paired-benchmark.js +3 -40
  14. package/behavioral-evals/run.js +2 -3
  15. package/ci/fixtures/doc-obligations/reconciliation-s2b/wiring/legacy-off-golden.json +0 -6
  16. package/ci/invariant-routing.test.js +32 -6
  17. package/ci/lib/opencode-verification-loader.js +3 -5
  18. package/ci/mechanism-2a-rule-of-3.test.js +111 -97
  19. package/ci/mechanism-2n-opencode-plugin.test.js +68 -206
  20. package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +47 -28
  21. package/ci/mechanism-2w-platform-compatibility.test.js +1 -0
  22. package/ci/mechanism-32-paired-benchmark.test.js +1 -2
  23. package/ci/mechanism-33-issues-205-207.test.js +1 -1
  24. package/ci/mechanism-338-opencode-async.test.js +18 -49
  25. package/ci/mechanism-36-verify-timeout.test.js +3 -189
  26. package/ci/mechanism-39-opencode-verify-outcomes.test.js +56 -323
  27. package/ci/mechanism-397-opencode-observations.test.js +64 -9
  28. package/ci/mechanism-check-packet-write-set.test.js +163 -8
  29. package/ci/mechanism-codex-hook-results.test.js +9 -5
  30. package/ci/mechanism-prb-outline-review.test.js +1 -13
  31. package/ci/mechanism-system-one-router.test.js +1 -1
  32. package/ci/openai-plugin-package.test.js +30 -7
  33. package/ci/openai-plugin-runtime.test.js +64 -32
  34. package/ci/prompt-contract-regressions.test.js +1 -5
  35. package/ci/router-workflow-plan.test.js +8 -8
  36. package/ci/self-evolve-loop.test.js +51 -51
  37. package/ci/workflow-execution-contract.test.js +3 -6
  38. package/code-review/SKILL.md +1 -1
  39. package/code-review/templates/finding.template.md +17 -1
  40. package/docker-verify.sh +1 -117
  41. package/docs/architecture.md +9 -7
  42. package/docs/document-lifecycle.md +1 -1
  43. package/docs/enforcement-locks.md +12 -10
  44. package/docs/mechanism-first-skill-mesh.md +2 -2
  45. package/docs/openai-plugin.md +3 -3
  46. package/docs/philosophy.md +1 -1
  47. package/docs/platform-capabilities.md +4 -3
  48. package/docs/platform-compatibility.json +2 -2
  49. package/docs/reflection.md +1 -1
  50. package/docs/routing.md +2 -2
  51. package/docs/system-one-suggestion-gates.md +4 -4
  52. package/docs/troubleshooting.md +9 -35
  53. package/docs/workflow-runtime.md +19 -18
  54. package/docs/workflows/environment-detection.md +11 -9
  55. package/docs/workflows/fable-discipline.md +6 -5
  56. package/docs/workflows/fable-mode.md +6 -5
  57. package/docs/workflows/harness-everything.md +5 -5
  58. package/docs/workflows/improve-codebase-architecture.md +10 -8
  59. package/docs/workflows/install-cognitive-os.md +5 -5
  60. package/docs/workflows/tdd.md +9 -9
  61. package/docs/workflows/zoom-out.md +20 -30
  62. package/environment-detection/SKILL.md +2 -2
  63. package/environment-detection/references/shell-syntax-rules.md +1 -1
  64. package/eval-harness/SKILL.md +1 -1
  65. package/eval-harness/references/scoring-rubric.md +3 -3
  66. package/evals/zoom-out/eval.yaml +2 -2
  67. package/evals/zoom-out/tasks/negative-productive-iteration.yaml +15 -0
  68. package/evals/zoom-out/tasks/negative-trivial-edit.yaml +6 -6
  69. package/evals/zoom-out/tasks/positive-first-failure.yaml +15 -0
  70. package/evals/zoom-out/tasks/positive-repair-loop.yaml +1 -1
  71. package/fable-discipline/SKILL.md +3 -3
  72. package/fable-discipline/references/discipline-rules.md +1 -1
  73. package/fable-mode/SKILL.md +1 -1
  74. package/fable-mode/execution-guardrails/SKILL.md +2 -4
  75. package/fable-mode/execution-guardrails/references/guardrail-rules.md +3 -3
  76. package/fable-mode/fable-haiku/SKILL.md +1 -1
  77. package/fable-mode/fable-opus/SKILL.md +2 -2
  78. package/fable-mode/fable-sonnet/SKILL.md +1 -1
  79. package/fable-mode/references/execution-phases.md +2 -2
  80. package/harness-everything/SKILL.md +3 -3
  81. package/harness-everything/references/router-workflow-plan.md +2 -2
  82. package/harness-everything/references/skill-registry.md +2 -2
  83. package/harness-everything/references/triage-and-tiers.md +5 -5
  84. package/harness-everything/scripts/bootstrap.js +1 -26
  85. package/harness-everything/scripts/kernel-router-core.js +2 -3
  86. package/harness-everything/scripts/kernel-router.js +1 -1
  87. package/harness-everything/scripts/router-contract-core.js +1 -1
  88. package/harness-everything/scripts/routing-keywords.json +0 -2
  89. package/hooks/hooks.json +0 -33
  90. package/hooks/scripts/lib/harness-state.js +5 -6
  91. package/hooks/scripts/lib/learning-opportunity.js +3 -13
  92. package/hooks/scripts/openai-session-start.js +2 -4
  93. package/improve-codebase-architecture/SKILL.md +3 -3
  94. package/improve-codebase-architecture/guides/refactoring-workflow.md +5 -4
  95. package/install-cognitive-os/SKILL.md +3 -3
  96. package/opencode-plugin/README.md +18 -43
  97. package/opencode-plugin/index.mjs +52 -380
  98. package/opencode-plugin/plugin.json +1 -1
  99. package/package.json +1 -4
  100. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  101. package/plugins/harness-everything/hooks/hooks.json +0 -14
  102. package/plugins/harness-everything/hooks/scripts/lib/harness-state.js +5 -6
  103. package/plugins/harness-everything/hooks/scripts/lib/learning-opportunity.js +3 -13
  104. package/plugins/harness-everything/hooks/scripts/lib/workspace.js +2 -2
  105. package/plugins/harness-everything/hooks/scripts/openai-session-start.js +2 -4
  106. package/plugins/harness-everything/hooks/session-start.js +2 -4
  107. package/plugins/harness-everything/plugin.json +1 -1
  108. package/plugins/harness-everything/scripts/lib/advisory-text.js +2 -2
  109. package/plugins/harness-everything/scripts/lib/workspace.js +2 -2
  110. package/plugins/harness-everything/skills/code-review/SKILL.md +1 -1
  111. package/plugins/harness-everything/skills/code-review/templates/finding.template.md +17 -1
  112. package/plugins/harness-everything/skills/environment-detection/SKILL.md +2 -2
  113. package/plugins/harness-everything/skills/environment-detection/references/shell-syntax-rules.md +1 -1
  114. package/plugins/harness-everything/skills/eval-harness/SKILL.md +1 -1
  115. package/plugins/harness-everything/skills/eval-harness/references/scoring-rubric.md +3 -3
  116. package/plugins/harness-everything/skills/fable-discipline/SKILL.md +3 -3
  117. package/plugins/harness-everything/skills/fable-discipline/references/discipline-rules.md +1 -1
  118. package/plugins/harness-everything/skills/fable-mode/SKILL.md +1 -1
  119. package/plugins/harness-everything/skills/fable-mode/execution-guardrails/SKILL.md +2 -4
  120. package/plugins/harness-everything/skills/fable-mode/execution-guardrails/references/guardrail-rules.md +3 -3
  121. package/plugins/harness-everything/skills/fable-mode/fable-haiku/SKILL.md +1 -1
  122. package/plugins/harness-everything/skills/fable-mode/fable-opus/SKILL.md +2 -2
  123. package/plugins/harness-everything/skills/fable-mode/fable-sonnet/SKILL.md +1 -1
  124. package/plugins/harness-everything/skills/fable-mode/references/execution-phases.md +2 -2
  125. package/plugins/harness-everything/skills/harness-everything/SKILL.md +3 -3
  126. package/plugins/harness-everything/skills/harness-everything/references/router-workflow-plan.md +2 -2
  127. package/plugins/harness-everything/skills/harness-everything/references/skill-registry.md +2 -2
  128. package/plugins/harness-everything/skills/harness-everything/references/triage-and-tiers.md +5 -5
  129. package/plugins/harness-everything/skills/harness-everything/scripts/bootstrap.js +1 -26
  130. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router-core.js +2 -3
  131. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +1 -1
  132. package/plugins/harness-everything/skills/harness-everything/scripts/router-contract-core.js +1 -1
  133. package/plugins/harness-everything/skills/harness-everything/scripts/routing-keywords.json +0 -2
  134. package/plugins/harness-everything/skills/improve-codebase-architecture/SKILL.md +3 -3
  135. package/plugins/harness-everything/skills/improve-codebase-architecture/guides/refactoring-workflow.md +5 -4
  136. package/plugins/harness-everything/skills/install-cognitive-os/SKILL.md +3 -3
  137. package/plugins/harness-everything/skills/self-evolve/SKILL.md +1 -1
  138. package/plugins/harness-everything/skills/self-evolve/references/memory-resolution.md +3 -3
  139. package/plugins/harness-everything/skills/self-evolve/schemas/lesson-candidate.schema.json +4 -1
  140. package/plugins/harness-everything/skills/self-evolve/scripts/lesson-candidate.js +1 -0
  141. package/plugins/harness-everything/skills/skill-creator/SKILL.md +1 -1
  142. package/plugins/harness-everything/skills/skill-creator/references/quality-checklist.md +1 -1
  143. package/plugins/harness-everything/skills/skill-creator/references/quality-principles.md +4 -4
  144. package/plugins/harness-everything/skills/tdd/SKILL.md +2 -2
  145. package/plugins/harness-everything/skills/tdd/references/core-discipline.md +3 -5
  146. package/plugins/harness-everything/skills/todo-driven-workflow/SKILL.md +2 -2
  147. package/plugins/harness-everything/skills/zoom-out/SKILL.md +14 -26
  148. package/plugins/harness-everything/skills/zoom-out/references/circuit-breaker.md +18 -62
  149. package/references/platform-advisory-template.md +3 -9
  150. package/sbom.cdx.json +7 -7
  151. package/scripts/check-packet-write-set.js +76 -1
  152. package/scripts/lib/advisory-text.js +2 -2
  153. package/scripts/lib/workspace.js +2 -2
  154. package/self-evolve/SKILL.md +1 -1
  155. package/self-evolve/references/memory-resolution.md +3 -3
  156. package/self-evolve/schemas/lesson-candidate.schema.json +4 -1
  157. package/self-evolve/scripts/lesson-candidate.js +1 -0
  158. package/skill-creator/SKILL.md +1 -1
  159. package/skill-creator/references/quality-checklist.md +1 -1
  160. package/skill-creator/references/quality-principles.md +4 -4
  161. package/submission/openai/test-cases.json +5 -5
  162. package/tdd/SKILL.md +2 -2
  163. package/tdd/references/core-discipline.md +3 -5
  164. package/todo-driven-workflow/SKILL.md +2 -2
  165. package/zoom-out/SKILL.md +14 -26
  166. package/zoom-out/references/circuit-breaker.md +18 -62
  167. package/behavioral-evals/opencode-hardlock-live.js +0 -17
  168. package/behavioral-evals/opencode-reflection-gate-live.js +0 -342
  169. package/ci/mechanism-31-opencode-hardlock-evidence.test.js +0 -82
  170. package/evals/zoom-out/tasks/negative-first-edge-case-review.yaml +0 -16
  171. package/evals/zoom-out/tasks/positive-repeated-failure.yaml +0 -15
  172. package/hooks/scripts/reset-circuit-breaker.js +0 -30
  173. package/hooks/scripts/rule-of-3-tracker.js +0 -165
  174. package/hooks/scripts/rule-of-3.js +0 -171
  175. package/plugins/harness-everything/hooks/scripts/reset-circuit-breaker.js +0 -30
  176. package/plugins/harness-everything/hooks/scripts/rule-of-3-tracker.js +0 -165
  177. package/plugins/harness-everything/hooks/scripts/rule-of-3.js +0 -171
@@ -1,171 +0,0 @@
1
- #!/usr/bin/env node
2
- // Rule of 3 circuit breaker (PreToolUse: Bash|PowerShell|Edit|Write|apply_patch).
3
- //
4
- // Tripping the breaker forces REFLECTION, not surrender. The most common
5
- // agent failure mode is drilling deeper on one unverified assumption, so the
6
- // breaker locks mutating tools and demands a zoom-out fact-check first
7
- // (read-only tools stay available). A valid reflection report - written to
8
- // the session's zoom-out-report.md (path given in the block message below) -
9
- // releases the breaker again. A later set of three matching failures triggers
10
- // another zoom-out; there is no persistent second-stage hard lock.
11
- //
12
- // State is scoped per Claude Code session_id (see lib/harness-state.js) so
13
- // two sessions open on the same repo never share a trip count. The common
14
- // case - nobody's breaker tripped anywhere - never has to read stdin to find
15
- // that out; only once some session IS tripped do we pay to read the payload
16
- // and check whether it's this one.
17
- const fs = require('fs');
18
- const path = require('path');
19
- const { getWorkspaceRoot, getSessionDir, listSessionDirs } = require('./lib/harness-state');
20
-
21
- const REQUIRED_SECTIONS = [
22
- '## Goal',
23
- '## Failed Attempts',
24
- '## Verified Facts',
25
- '## Diagnosis',
26
- '## Decision'
27
- ];
28
-
29
- function readState(stateFile) {
30
- if (!fs.existsSync(stateFile)) return null;
31
- try { return JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch (err) { return null; }
32
- }
33
-
34
- function isTripped(state) {
35
- return Boolean(state && !state.zoomOutResolved && state.count >= 3);
36
- }
37
-
38
- function anySessionTripped(root) {
39
- return listSessionDirs(root).some(dir => isTripped(readState(path.join(dir, 'rule-of-3-state.json'))));
40
- }
41
-
42
- // The one mutation allowed while tripped: writing the reflection report.
43
- const ALLOWED_WRITE_TOOLS = new Set([
44
- 'Write', 'Edit', 'create_file', 'replace_string_in_file',
45
- 'insert_edit_into_file', 'write_file', 'edit_file', 'apply_patch'
46
- ]);
47
-
48
- function isReportWrite(payload, reportFile) {
49
- if (!payload) return false;
50
- const toolName = payload.tool_name || payload.toolName;
51
- if (!ALLOWED_WRITE_TOOLS.has(toolName)) return false;
52
- const input = payload.tool_input || payload.toolInput || payload.input || {};
53
- const target = input.file_path || input.filePath || input.path || input.file;
54
- if (target && path.resolve(target).toLowerCase() === path.resolve(reportFile).toLowerCase()) return true;
55
- if (toolName !== 'apply_patch') return false;
56
-
57
- const patch = input.patch || input.command || input.content || '';
58
- const base = payload.cwd || process.cwd();
59
- const files = [...String(patch).matchAll(/^\*\*\* (?:Update|Add|Delete) File:\s*(.+?)\s*$/gm)]
60
- .map(match => match[1]);
61
- const reportPath = path.resolve(reportFile).toLowerCase();
62
- return files.length > 0 && files.every(file => path.resolve(base, file).toLowerCase() === reportPath);
63
- }
64
-
65
- // A report only counts if it was written AFTER the failure that tripped the
66
- // breaker (a stale report from an earlier loop can't unlock a new one), has
67
- // every required section, and actually committed to a RESUME/ESCALATE call.
68
- function reportIsValid(state, reportFile) {
69
- if (!fs.existsSync(reportFile)) return false;
70
- if (fs.statSync(reportFile).mtimeMs < (state.lastFailureAt || 0)) return false;
71
- const text = fs.readFileSync(reportFile, 'utf8');
72
- if (!REQUIRED_SECTIONS.every(h => text.includes(h))) return false;
73
- return /\b(RESUME|ESCALATE)\b/.test(text);
74
- }
75
-
76
- function blockForReflection(state, reportFile) {
77
- console.error(`[CRITICAL] RULE OF 3 CIRCUIT BREAKER TRIGGERED!`);
78
- console.error(`The same failure signature has now occurred 3 times.`);
79
- console.error(`Error Signature: ${state.lastHash}`);
80
- console.error(`\nMutating tools (Bash/PowerShell/Edit/Write/apply_patch) are locked - not because you`);
81
- console.error(`must wait for a human, but because you must stop drilling and rebuild the`);
82
- console.error(`full picture first. Do NOT ask the Human Partner yet.`);
83
- console.error(`\nACTION REQUIRED (reflect first):`);
84
- console.error(`1. CEASE FIRE. No new fix attempts, no variations of the last one.`);
85
- console.error(`2. Load the 'zoom-out' skill and follow its Reflect & Fact-Check protocol.`);
86
- console.error(`3. Using READ-ONLY tools (Read/Grep/Glob - still available), re-verify the`);
87
- console.error(` assumption behind each failed attempt against the actual code/logs/docs.`);
88
- console.error(`4. Write your findings to '${reportFile}' (the ONLY write`);
89
- console.error(` allowed right now) with sections: ## Goal, ## Failed Attempts,`);
90
- console.error(` ## Verified Facts, ## Diagnosis, ## Decision (ending RESUME: or ESCALATE:).`);
91
- console.error(`\nA valid report releases this breaker automatically. Escalate to the Human`);
92
- console.error(`Partner ONLY if your Decision concludes a genuinely human call is needed`);
93
- console.error(`(requirement conflict, architecture trade-off, destructive action, missing`);
94
- console.error(`access) - and then present options with a recommendation, not apologies.`);
95
- // For PreToolUse, only exit code 2 actually blocks the tool call.
96
- // Exit 1 is a non-blocking error and Claude Code proceeds anyway.
97
- process.exit(2);
98
- }
99
-
100
- function main(payload) {
101
- try {
102
- const root = getWorkspaceRoot(payload);
103
- const sessionDir = getSessionDir(root, payload && (payload.session_id || payload.sessionId));
104
- const stateFile = path.join(sessionDir, 'rule-of-3-state.json');
105
- const reportFile = path.join(sessionDir, 'zoom-out-report.md');
106
-
107
- const state = readState(stateFile);
108
- if (!isTripped(state)) {
109
- process.exit(0);
110
- }
111
-
112
- if (isReportWrite(payload, reportFile)) {
113
- process.exit(0);
114
- }
115
-
116
- if (reportIsValid(state, reportFile)) {
117
- state.count = 0;
118
- state.zoomOutResolved = true;
119
- state.zoomOutCycles = (state.zoomOutCycles || 0) + 1;
120
- fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
121
- console.log(
122
- `[Rule of 3] Zoom-out report accepted - breaker released. Follow your ` +
123
- `report's Decision: RESUME means one fresh run at the NEW diagnosis; ` +
124
- `ESCALATE means present the decision request and WAIT for the Human ` +
125
- `Partner before mutating anything. A later set of three matching failures will trigger another zoom-out.`
126
- );
127
- process.exit(0);
128
- }
129
-
130
- blockForReflection(state, reportFile);
131
- } catch (err) {
132
- // Fail open if state tracking breaks
133
- process.exit(0);
134
- }
135
- }
136
-
137
- // Read the payload before the fast path. The session registry may point at a
138
- // different workspace than process.cwd() after an agent changes directory;
139
- // checking the cwd first would skip an active breaker in the bound session.
140
- function runForPayload(payload) {
141
- let tripped = false;
142
- try {
143
- tripped = anySessionTripped(getWorkspaceRoot(payload));
144
- } catch (err) {
145
- tripped = false; // fail open
146
- }
147
- if (!tripped) process.exit(0);
148
- main(payload);
149
- }
150
-
151
- if (process.stdin.isTTY) {
152
- // Manual run in a terminal - no payload is coming.
153
- runForPayload(null);
154
- } else {
155
- let raw = '';
156
- let finished = false;
157
- const finish = () => {
158
- if (finished) return;
159
- finished = true;
160
- let payload = null;
161
- try { payload = JSON.parse(raw); } catch (err) { /* no payload */ }
162
- runForPayload(payload);
163
- };
164
- // Claude Code closes stdin right after writing the payload; the timer is a
165
- // safety net so an odd caller that never closes stdin can't hang the hook.
166
- const timer = setTimeout(finish, 300);
167
- process.stdin.setEncoding('utf8');
168
- process.stdin.on('data', chunk => { raw += chunk; });
169
- process.stdin.on('end', () => { clearTimeout(timer); finish(); });
170
- process.stdin.on('error', () => { clearTimeout(timer); finish(); });
171
- }
@@ -1,30 +0,0 @@
1
- #!/usr/bin/env node
2
- // Manual escape hatch for the Rule of 3 circuit breaker. Run this directly
3
- // in your own terminal (not through the agent — Bash is blocked while the
4
- // breaker is tripped) to clear it without waiting for a new session.
5
- const fs = require('fs');
6
- const path = require('path');
7
- const { getWorkspaceRoot, getSessionDir, readCurrentSession } = require('./lib/harness-state');
8
-
9
- // This is run directly by the human, not through the agent, so there's no
10
- // hook payload to read a session_id from - resolve "the session that's
11
- // currently blocked" via the pointer bootstrap.js wrote at its last
12
- // SessionStart.
13
- const root = getWorkspaceRoot();
14
- const harnessDir = getSessionDir(root, readCurrentSession(root));
15
- const stateFile = path.join(harnessDir, 'rule-of-3-state.json');
16
- const reportFile = path.join(harnessDir, 'zoom-out-report.md');
17
-
18
- if (fs.existsSync(stateFile)) {
19
- fs.unlinkSync(stateFile);
20
- console.log('Rule of 3 circuit breaker cleared.');
21
- } else {
22
- console.log('Rule of 3 circuit breaker is not currently tripped.');
23
- }
24
-
25
- // A human reset is a full clear: the stale reflection report belongs to the
26
- // loop that was just abandoned.
27
- if (fs.existsSync(reportFile)) {
28
- fs.unlinkSync(reportFile);
29
- console.log('Stale zoom-out report removed.');
30
- }
@@ -1,165 +0,0 @@
1
- #!/usr/bin/env node
2
- const fs = require('fs');
3
- const path = require('path');
4
- const crypto = require('crypto');
5
- const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
6
- const { createLearningOpportunity } = require('./lib/learning-opportunity');
7
- const { readCodexToolOutcome } = require('./lib/codex-tool-outcome');
8
- const codex = process.argv.includes('--codex');
9
-
10
- // PostToolUse/PostToolUseFailure hooks in Claude Code receive their payload via stdin
11
- let inputData = '';
12
-
13
- process.stdin.on('data', chunk => {
14
- inputData += chunk;
15
- });
16
-
17
- process.stdin.on('end', () => {
18
- try {
19
- const payload = JSON.parse(inputData);
20
- const codexResult = codex ? readCodexToolOutcome(payload) : null;
21
- if (codexResult?.outcome === 'unknown') return;
22
- const hookEventName = payload.hook_event_name || payload.hookEventName || '';
23
- const isFailureEvent = hookEventName === 'PostToolUseFailure';
24
- const isSuccessEvent = hookEventName === 'PostToolUse';
25
- const toolResponse = payload.tool_response || {};
26
- const stdout = codexResult?.stdout ?? toolResponse.stdout ?? payload.stdout ?? '';
27
- const stderr = codexResult?.stderr ?? toolResponse.stderr ?? payload.stderr ?? '';
28
- const failureText = typeof payload.error === 'string' ? payload.error : '';
29
- const rawExitCode = toolResponse.exitCode ?? toolResponse.exit_code ?? payload.exitCode ?? payload.exit_code;
30
- const exitCode = typeof rawExitCode === 'number' ? rawExitCode : undefined;
31
- const toolName = payload.tool_name || payload.tool || 'command';
32
- const toolInput = payload.tool_input || {};
33
- const filePath = toolInput.file_path || toolInput.filePath || '';
34
- const command = toolInput.command || '';
35
- const operationHash = crypto.createHash('md5').update(`${toolName}:${filePath}:${command}`).digest('hex');
36
-
37
- const explicitFailure = exitCode !== undefined && exitCode !== 0;
38
- const stderrSignal = typeof stderr === 'string' && stderr.trim().length > 0;
39
- const looksLikeError = /\b(error|fail|failed|failure|exception|fatal|panic|traceback|denied|refused|cannot|unable)\b/i.test(stderr);
40
- const isFailure = codex ? codexResult.outcome === 'failure' : isFailureEvent || explicitFailure ||
41
- (!isSuccessEvent && exitCode === undefined && stderrSignal && looksLikeError);
42
- const reportedError = isFailureEvent
43
- ? (failureText || (stderrSignal ? stderr : stdout) || '')
44
- : ((stderrSignal ? stderr : stdout) || failureText || '');
45
- const errorText = reportedError || (codexResult?.outcome === 'failure'
46
- ? (codexResult.exitCode === undefined ? 'Tool reported failure' : `Tool exited with code ${codexResult.exitCode}`)
47
- : '');
48
-
49
- const root = getWorkspaceRoot(payload);
50
- const stateFile = path.join(getSessionDir(root, payload.session_id || payload.sessionId), 'rule-of-3-state.json');
51
-
52
- let state = { count: 0, lastHash: null, lastOperationHash: null, zoomOutResolved: false, zoomOutCycles: 0, lastFailureAt: 0 };
53
- if (fs.existsSync(stateFile)) {
54
- state = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
55
- }
56
-
57
- if (isFailure && errorText) {
58
- // Enhanced failure signature detection with context-aware categorization
59
- // Hash includes: error message, file path, command attempted, and failure category
60
- // Categorize failure type for context-aware thresholds.
61
- // NOTE (#167): match anchored diagnostic phrases, not bare substrings.
62
- // A bare `denied`/`timeout` substring matches file names such as
63
- // `workflow-mutation-denied.js` and misclassifies the failure.
64
- let category = 'unknown';
65
- if (/\bSyntaxError\b|Unexpected token|Syntax Error/i.test(errorText)) {
66
- category = 'syntax';
67
- } else if (/\bENOENT\b|\bnot found\b|No such file|找不到|不存在/i.test(errorText)) {
68
- category = 'environment';
69
- } else if (/\bETIMEDOUT\b|TimeoutError|\btimeout\b|\btimed out\b|\btiming out\b|超時|逾時/i.test(errorText)) {
70
- category = 'timeout';
71
- } else if (/test.*fail|assertion|AssertionError|測試.*失敗|斷言.*錯誤/i.test(errorText)) {
72
- category = 'test';
73
- } else if (/\bpermission denied\b|\bEACCES\b|\bEPERM\b|權限.*(拒絕|不足|被拒)|拒絕.*權限/i.test(errorText)) {
74
- category = 'permission';
75
- } else if (/\bdependency\b|\bmodule not found\b|Cannot find module|模組.*找不到/i.test(errorText)) {
76
- category = 'dependency';
77
- }
78
-
79
- // Normalize error text with context for better loop detection
80
- const normalized = errorText.slice(-400)
81
- .toLowerCase()
82
- .replace(/0x[0-9a-f]+/g, '#')
83
- .replace(/\d+/g, '#')
84
- .replace(/\s+/g, ' ')
85
- .trim();
86
-
87
- // Include file path and command in hash for better context
88
- const contextString = `${category}:${filePath}:${command}:${normalized.slice(-200)}`;
89
- const hash = crypto.createHash('md5').update(contextString).digest('hex');
90
-
91
- // One deliberately simple policy: three repeats of the same signature trigger zoom-out.
92
- if (state.lastHash === hash) {
93
- state.count += 1;
94
- state.category = category; // Track failure category for smarter decisions
95
- } else {
96
- state.count = 1;
97
- state.lastHash = hash;
98
- state.category = category;
99
- // New signature = new problem: the zoom-out cycle budget starts over.
100
- state.zoomOutCycles = 0;
101
- }
102
- state.lastOperationHash = operationHash;
103
-
104
- // Any fresh failure re-arms the breaker. Without this, a signature that
105
- // failed again after a success (or after a zoom-out release) would keep
106
- // zoomOutResolved=true and the breaker could never trip on it again.
107
- state.zoomOutResolved = false;
108
- // rule-of-3.js only honors a zoom-out report written AFTER this moment,
109
- // so a stale report can't unlock a later trip.
110
- state.lastFailureAt = Date.now();
111
-
112
- fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
113
- } else if (!isFailure) {
114
- let stateChanged = false;
115
-
116
- // The first confirmed success after an accepted zoom-out is useful
117
- // learning evidence even when it is not the same command that failed.
118
- // Consume only the recovery-cycle marker here; do not erase the
119
- // repeated-failure signature or count for an unrelated operation.
120
- if ((state.zoomOutCycles || 0) > 0 && state.lastHash) {
121
- const toolEventId = payload.tool_use_id || payload.toolUseId || `success-${Date.now()}`;
122
- try {
123
- createLearningOpportunity(payload, {
124
- triggerType: 'rule-of-3-recovery',
125
- sourceEventIds: [
126
- `rule-of-3:${state.lastHash}:${state.lastFailureAt || 0}`,
127
- `tool:${toolEventId}`,
128
- ],
129
- evidence: {
130
- failureSignature: state.lastHash,
131
- failureCategory: state.category || 'unknown',
132
- zoomOutCycles: state.zoomOutCycles,
133
- recovered: true,
134
- },
135
- });
136
- } catch (_) {
137
- // Learning capture is additive and must never break recovery tracking.
138
- }
139
- state.zoomOutCycles = 0;
140
- stateChanged = true;
141
- }
142
-
143
- // Only a success for the same operation resolves its tracked signature.
144
- if (state.lastOperationHash && state.lastOperationHash === operationHash &&
145
- (state.count > 0 || state.lastHash)) {
146
- state.count = 0;
147
- state.lastHash = null;
148
- state.lastOperationHash = null;
149
- state.zoomOutResolved = true;
150
- state.zoomOutCycles = 0;
151
- state.lastFailureAt = 0;
152
- delete state.category;
153
- stateChanged = true;
154
- }
155
-
156
- if (stateChanged) {
157
- fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
158
- }
159
- }
160
-
161
- } catch (err) {
162
- // silently fail
163
- }
164
- process.exit(0);
165
- });
@@ -1,171 +0,0 @@
1
- #!/usr/bin/env node
2
- // Rule of 3 circuit breaker (PreToolUse: Bash|PowerShell|Edit|Write|apply_patch).
3
- //
4
- // Tripping the breaker forces REFLECTION, not surrender. The most common
5
- // agent failure mode is drilling deeper on one unverified assumption, so the
6
- // breaker locks mutating tools and demands a zoom-out fact-check first
7
- // (read-only tools stay available). A valid reflection report - written to
8
- // the session's zoom-out-report.md (path given in the block message below) -
9
- // releases the breaker again. A later set of three matching failures triggers
10
- // another zoom-out; there is no persistent second-stage hard lock.
11
- //
12
- // State is scoped per Claude Code session_id (see lib/harness-state.js) so
13
- // two sessions open on the same repo never share a trip count. The common
14
- // case - nobody's breaker tripped anywhere - never has to read stdin to find
15
- // that out; only once some session IS tripped do we pay to read the payload
16
- // and check whether it's this one.
17
- const fs = require('fs');
18
- const path = require('path');
19
- const { getWorkspaceRoot, getSessionDir, listSessionDirs } = require('./lib/harness-state');
20
-
21
- const REQUIRED_SECTIONS = [
22
- '## Goal',
23
- '## Failed Attempts',
24
- '## Verified Facts',
25
- '## Diagnosis',
26
- '## Decision'
27
- ];
28
-
29
- function readState(stateFile) {
30
- if (!fs.existsSync(stateFile)) return null;
31
- try { return JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch (err) { return null; }
32
- }
33
-
34
- function isTripped(state) {
35
- return Boolean(state && !state.zoomOutResolved && state.count >= 3);
36
- }
37
-
38
- function anySessionTripped(root) {
39
- return listSessionDirs(root).some(dir => isTripped(readState(path.join(dir, 'rule-of-3-state.json'))));
40
- }
41
-
42
- // The one mutation allowed while tripped: writing the reflection report.
43
- const ALLOWED_WRITE_TOOLS = new Set([
44
- 'Write', 'Edit', 'create_file', 'replace_string_in_file',
45
- 'insert_edit_into_file', 'write_file', 'edit_file', 'apply_patch'
46
- ]);
47
-
48
- function isReportWrite(payload, reportFile) {
49
- if (!payload) return false;
50
- const toolName = payload.tool_name || payload.toolName;
51
- if (!ALLOWED_WRITE_TOOLS.has(toolName)) return false;
52
- const input = payload.tool_input || payload.toolInput || payload.input || {};
53
- const target = input.file_path || input.filePath || input.path || input.file;
54
- if (target && path.resolve(target).toLowerCase() === path.resolve(reportFile).toLowerCase()) return true;
55
- if (toolName !== 'apply_patch') return false;
56
-
57
- const patch = input.patch || input.command || input.content || '';
58
- const base = payload.cwd || process.cwd();
59
- const files = [...String(patch).matchAll(/^\*\*\* (?:Update|Add|Delete) File:\s*(.+?)\s*$/gm)]
60
- .map(match => match[1]);
61
- const reportPath = path.resolve(reportFile).toLowerCase();
62
- return files.length > 0 && files.every(file => path.resolve(base, file).toLowerCase() === reportPath);
63
- }
64
-
65
- // A report only counts if it was written AFTER the failure that tripped the
66
- // breaker (a stale report from an earlier loop can't unlock a new one), has
67
- // every required section, and actually committed to a RESUME/ESCALATE call.
68
- function reportIsValid(state, reportFile) {
69
- if (!fs.existsSync(reportFile)) return false;
70
- if (fs.statSync(reportFile).mtimeMs < (state.lastFailureAt || 0)) return false;
71
- const text = fs.readFileSync(reportFile, 'utf8');
72
- if (!REQUIRED_SECTIONS.every(h => text.includes(h))) return false;
73
- return /\b(RESUME|ESCALATE)\b/.test(text);
74
- }
75
-
76
- function blockForReflection(state, reportFile) {
77
- console.error(`[CRITICAL] RULE OF 3 CIRCUIT BREAKER TRIGGERED!`);
78
- console.error(`The same failure signature has now occurred 3 times.`);
79
- console.error(`Error Signature: ${state.lastHash}`);
80
- console.error(`\nMutating tools (Bash/PowerShell/Edit/Write/apply_patch) are locked - not because you`);
81
- console.error(`must wait for a human, but because you must stop drilling and rebuild the`);
82
- console.error(`full picture first. Do NOT ask the Human Partner yet.`);
83
- console.error(`\nACTION REQUIRED (reflect first):`);
84
- console.error(`1. CEASE FIRE. No new fix attempts, no variations of the last one.`);
85
- console.error(`2. Load the 'zoom-out' skill and follow its Reflect & Fact-Check protocol.`);
86
- console.error(`3. Using READ-ONLY tools (Read/Grep/Glob - still available), re-verify the`);
87
- console.error(` assumption behind each failed attempt against the actual code/logs/docs.`);
88
- console.error(`4. Write your findings to '${reportFile}' (the ONLY write`);
89
- console.error(` allowed right now) with sections: ## Goal, ## Failed Attempts,`);
90
- console.error(` ## Verified Facts, ## Diagnosis, ## Decision (ending RESUME: or ESCALATE:).`);
91
- console.error(`\nA valid report releases this breaker automatically. Escalate to the Human`);
92
- console.error(`Partner ONLY if your Decision concludes a genuinely human call is needed`);
93
- console.error(`(requirement conflict, architecture trade-off, destructive action, missing`);
94
- console.error(`access) - and then present options with a recommendation, not apologies.`);
95
- // For PreToolUse, only exit code 2 actually blocks the tool call.
96
- // Exit 1 is a non-blocking error and Claude Code proceeds anyway.
97
- process.exit(2);
98
- }
99
-
100
- function main(payload) {
101
- try {
102
- const root = getWorkspaceRoot(payload);
103
- const sessionDir = getSessionDir(root, payload && (payload.session_id || payload.sessionId));
104
- const stateFile = path.join(sessionDir, 'rule-of-3-state.json');
105
- const reportFile = path.join(sessionDir, 'zoom-out-report.md');
106
-
107
- const state = readState(stateFile);
108
- if (!isTripped(state)) {
109
- process.exit(0);
110
- }
111
-
112
- if (isReportWrite(payload, reportFile)) {
113
- process.exit(0);
114
- }
115
-
116
- if (reportIsValid(state, reportFile)) {
117
- state.count = 0;
118
- state.zoomOutResolved = true;
119
- state.zoomOutCycles = (state.zoomOutCycles || 0) + 1;
120
- fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
121
- console.log(
122
- `[Rule of 3] Zoom-out report accepted - breaker released. Follow your ` +
123
- `report's Decision: RESUME means one fresh run at the NEW diagnosis; ` +
124
- `ESCALATE means present the decision request and WAIT for the Human ` +
125
- `Partner before mutating anything. A later set of three matching failures will trigger another zoom-out.`
126
- );
127
- process.exit(0);
128
- }
129
-
130
- blockForReflection(state, reportFile);
131
- } catch (err) {
132
- // Fail open if state tracking breaks
133
- process.exit(0);
134
- }
135
- }
136
-
137
- // Read the payload before the fast path. The session registry may point at a
138
- // different workspace than process.cwd() after an agent changes directory;
139
- // checking the cwd first would skip an active breaker in the bound session.
140
- function runForPayload(payload) {
141
- let tripped = false;
142
- try {
143
- tripped = anySessionTripped(getWorkspaceRoot(payload));
144
- } catch (err) {
145
- tripped = false; // fail open
146
- }
147
- if (!tripped) process.exit(0);
148
- main(payload);
149
- }
150
-
151
- if (process.stdin.isTTY) {
152
- // Manual run in a terminal - no payload is coming.
153
- runForPayload(null);
154
- } else {
155
- let raw = '';
156
- let finished = false;
157
- const finish = () => {
158
- if (finished) return;
159
- finished = true;
160
- let payload = null;
161
- try { payload = JSON.parse(raw); } catch (err) { /* no payload */ }
162
- runForPayload(payload);
163
- };
164
- // Claude Code closes stdin right after writing the payload; the timer is a
165
- // safety net so an odd caller that never closes stdin can't hang the hook.
166
- const timer = setTimeout(finish, 300);
167
- process.stdin.setEncoding('utf8');
168
- process.stdin.on('data', chunk => { raw += chunk; });
169
- process.stdin.on('end', () => { clearTimeout(timer); finish(); });
170
- process.stdin.on('error', () => { clearTimeout(timer); finish(); });
171
- }