harness-everything 0.11.5 → 0.11.7

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 (55) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +32 -0
  4. package/README.md +7 -3
  5. package/ci/mechanism-2a-rule-of-3.test.js +71 -0
  6. package/ci/mechanism-2ah-workflow-lifecycle.test.js +314 -8
  7. package/ci/mechanism-2c-state-persist.test.js +45 -2
  8. package/ci/mechanism-2t-issue-20.test.js +0 -8
  9. package/ci/mechanism-30-opencode-plugin-loadability.test.js +39 -7
  10. package/docs/architecture.md +17 -0
  11. package/docs/audit.md +52 -5
  12. package/docs/release-evidence.md +3 -0
  13. package/docs/workflow-runtime.md +13 -0
  14. package/docs/workflows/environment-detection.md +47 -37
  15. package/docs/workflows/eval-harness.md +45 -38
  16. package/docs/workflows/fable-discipline.md +45 -33
  17. package/docs/workflows/git-commit.md +53 -45
  18. package/docs/workflows/grill-me.md +36 -38
  19. package/docs/workflows/grill-with-docs.md +36 -46
  20. package/docs/workflows/harness-everything.md +59 -57
  21. package/docs/workflows/improve-codebase-architecture.md +36 -44
  22. package/docs/workflows/install-cognitive-os.md +36 -29
  23. package/docs/workflows/repo-docs.md +29 -40
  24. package/docs/workflows/rewrite-commits.md +40 -36
  25. package/docs/workflows/security-review.md +34 -53
  26. package/docs/workflows/skill-creator.md +39 -56
  27. package/docs/workflows/skill-style.md +35 -40
  28. package/docs/workflows/using-git-worktrees.md +40 -44
  29. package/docs/workflows/verification-loop.md +43 -48
  30. package/docs/workflows/verify-before-claim.md +37 -40
  31. package/docs/workflows/zoom-out.md +39 -51
  32. package/harness-everything/SKILL.md +1 -1
  33. package/harness-everything/scripts/kernel-router.js +38 -10
  34. package/hooks/hooks.json +25 -1
  35. package/hooks/scripts/lib/workflow-isolation.js +111 -6
  36. package/hooks/scripts/lib/workflow-runtime.js +138 -2
  37. package/hooks/scripts/rule-of-3-tracker.js +17 -9
  38. package/hooks/scripts/state-persist.js +52 -9
  39. package/hooks/scripts/workflow-gate.js +22 -7
  40. package/hooks/scripts/workflow-mutation-denied.js +17 -0
  41. package/opencode-plugin/plugin.json +1 -1
  42. package/package.json +1 -1
  43. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  44. package/plugins/harness-everything/hooks/hooks.json +1 -1
  45. package/plugins/harness-everything/hooks/scripts/lib/workflow-isolation.js +111 -6
  46. package/plugins/harness-everything/hooks/scripts/lib/workflow-runtime.js +138 -2
  47. package/plugins/harness-everything/hooks/scripts/rule-of-3-tracker.js +17 -9
  48. package/plugins/harness-everything/hooks/scripts/state-persist.js +52 -9
  49. package/plugins/harness-everything/hooks/scripts/workflow-gate.js +22 -7
  50. package/plugins/harness-everything/hooks/scripts/workflow-mutation-denied.js +17 -0
  51. package/plugins/harness-everything/plugin.json +1 -1
  52. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  53. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +38 -10
  54. package/docs/issue-20-rollup.md +0 -47
  55. package/docs/reviews/pr-142-issue-131.md +0 -89
@@ -1,74 +1,62 @@
1
1
  # Workflow: Zoom Out
2
2
 
3
- > High-level reflection report generation to break out of error loops, analyze failure patterns, and backtrack to alternative paths.
3
+ > Reflect-first breaker after three failures: stop edits, rebuild the full picture with read-only tools, write a fact-check report, then resume or escalate.
4
4
 
5
- ---
5
+ Source of truth: `zoom-out/SKILL.md`.
6
6
 
7
- ## 1. Skill Behavior Workflow
7
+ Contract summary from SKILL.md — Trigger: three same-signature failures or an explicit loop/rethink request. Output: fact-checked report ending in `RESUME` or `ESCALATE`. State: writes the session `zoom-out-report.md`; reset may clear breaker state. Gate: `hooks/scripts/rule-of-3.js` plus a valid report; reset only after the second cycle. USE FOR: "you are stuck in a loop", "the same error keeps failing", "rethink your assumptions". DO NOT USE FOR: routine single-failure debugging, greenfield planning without failures.
8
8
 
9
- This section visualizes how the `zoom-out` skill executes internally, detailing the sequence of operations, state transitions, and evaluation steps.
9
+ ## 1. Skill Behavior Workflow
10
10
 
11
11
  ```mermaid
12
12
  graph TD
13
- Start([3 Consecutive Failures / Goal Drift Triggered]) --> CeaseFire["1. Phase 1: Cease Fire - Stop Code Edits Immediately"]
14
- CeaseFire --> Rebuild["2. Phase 2: Rebuild Full Picture using Read-Only Tools"]
15
- Rebuild --> CheckPath{3. Resolve Reflection Report Path}
16
-
17
- CheckPath -->|Session Path Provided| WriteSession["Copy template to Session zoom-out-report.md"]
18
- CheckPath -->|Template / Path Unavailable| WritePlatform["Write to .github/harness-everything/zoom-out-report.md or Inline"]
19
-
20
- WriteSession --> DecisionGate{4. Phase 4: Decision Gate}
21
- WritePlatform --> DecisionGate
22
-
23
- DecisionGate -->|Untried Path Identified| Resume["RESUME: Execute Fresh Diagnosis in TDD / Fable"]
24
- DecisionGate -->|Requirement Conflict / Access Gap| Escalate["ESCALATE: Present 2-3 Options + Recommendation to Human"]
25
-
26
- Resume --> Resolved{5. Problem Cracking Succeeds?}
27
- Resolved -->|Yes| SelfEvolve["Call self-evolve to Persist Insight"]
28
- Resolved -->|No: 3 More Failures| Escalate
29
- SelfEvolve --> End([Reflection Completed & Lessons Persisted])
30
- Escalate --> End
13
+ Third[Third Same Signature Failure] --> Stop[Stop Edits No User Ask Yet]
14
+ Stop --> ReadOnly[ReadOnly Restate Goal Check Files Config Logs]
15
+ ReadOnly --> Fill[Fill zoom-out-report template]
16
+ Fill --> Decide{RESUME or ESCALATE?}
17
+ Decide -->|untried path| Resume[RESUME On Untried Path]
18
+ Decide -->|genuine user decision| Escalate[ESCALATE With Options]
19
+ Resume --> Again{Repeated Breaker Cycle?}
20
+ Again -->|second cycle| Reset[npm run harness reset]
21
+ Reset --> Evolve[Record Insight With self-evolve]
22
+ Again -->|no| Done([Report Complete])
23
+ Escalate --> Done
31
24
  ```
32
25
 
33
- ---
34
-
35
26
  ## 2. Triggering and Routing Path
36
27
 
37
- This diagram illustrates how the `zoom-out` skill is triggered through user requests or developer actions, and how it integrates or chains together with other companion skills in the Harness OS ecosystem to form unified workflows.
38
-
39
28
  ```mermaid
40
- graph LR
41
- RuleOf3["Rule of 3 Circuit Breaker"] -->|Tripped!| ZoomOut["zoom-out / SKILL.md"]
42
- ZoomOut -->|Halts execution for| ActiveWork["Active workspace edits"]
43
- ZoomOut -->|Asks for human direction via| AskQuestions["host user-input mechanism"]
44
- ZoomOut -->|Unlocks workspace state after| HumanReset["Human Partner Response"]
29
+ graph TD
30
+ LoopReq[Stuck In Loop Request] --> Skill[zoom-out SKILL]
31
+ SameErr[Same Error Keeps Failing] --> Skill
32
+ Rethink[Rethink Assumptions Request] --> Skill
33
+ ThreeFail[Three Same Signature Failures] --> Breaker[hooks scripts rule-of-3 js]
34
+ Breaker --> Skill
35
+ SingleFail[Routine Single Failure] --> DirectFix[Fix Directly]
36
+ Greenfield[Greenfield Planning No Failures] --> Fable[fable-mode SKILL]
37
+ Skill --> ReportGate[Valid Report RESUME or ESCALATE]
45
38
  ```
46
39
 
47
- ---
48
-
49
- ## 3. Real-World Use Case Flowchart
50
-
51
- Here we model concrete real-world scenarios and use cases of the `zoom-out` skill, illustrating standard success paths, error handling, or recovery loops.
40
+ ## 3. Real-World Use Case
52
41
 
53
42
  ```mermaid
54
43
  graph TD
55
- Start["Attempting to fix Python import error; fails 3 times consecutively with same trace"] --> Trigger["Rule of 3 circuit breaker trips"]
56
- Trigger --> Lock["Workspace writes locked"]
57
- Trigger --> Awaken["Awaken: Stop error-fixing; review imports design & requirements (Law 2)"]
58
- Awaken --> Collect["Collect error traces and diff history"]
59
- Collect --> WriteReport["Create the session zoom-out-report.md detailing the import cyclic dependency"]
60
- WriteReport --> Present["Present options to human: Option A - Merge imports, Option B - Extract shared modules"]
61
- Present --> UserChoice["User select: 'Option B'"]
62
- UserChoice --> Unlock["Unlock workspace and execute Option B"]
63
- Unlock --> Done([Error loop successfully broken and resolved])
44
+ Fail[Same Test Fails Three Times Same Signature] --> Halt[Stop Edits Rebuild Picture ReadOnly]
45
+ Halt --> Inspect[Restate Goal Check Files Config Logs]
46
+ Inspect --> Write[Fill templates zoom-out-report template md]
47
+ Write --> Choice{Untried Path Exists?}
48
+ Choice -->|yes| Resume2[RESUME On Untried Path]
49
+ Choice -->|no| Esc2[ESCALATE With Options]
50
+ Resume2 -->|repeated cycle| Reset2[npm run harness reset Then self-evolve]
64
51
  ```
65
52
 
66
- ---
53
+ Template: `zoom-out/templates/zoom-out-report.template.md`. Enforcement: `hooks/scripts/rule-of-3.js`. Deep dive: `zoom-out/references/circuit-breaker.md`.
67
54
 
68
55
  ## 4. Verification Check
69
56
 
70
- To ensure that the `zoom-out` skill is operating in strict compliance with Harness OS design laws, verify the following:
71
-
72
- - [ ] **Physical Boundary Verification**: The skill boundaries are respected and do not leak context.
73
- - [ ] **State Checkpoint Verification**: The active state is established, validated, and recorded at the beginning and end of each execution branch.
74
- - [ ] **Cognitive Alignment**: The skill conforms to the **Think > Try > Summarize > Record** cognitive loop.
57
+ - [ ] After three same-signature failures, edits stopped and the same approach was not retried
58
+ - [ ] Goal, files, configuration, and logs were rechecked with read-only tools before any resume
59
+ - [ ] `templates/zoom-out-report.template.md` was filled and the session `zoom-out-report.md` ends in `RESUME` or `ESCALATE`
60
+ - [ ] Resume targeted only an untried path; genuine user decisions were escalated with options
61
+ - [ ] Reset via `npm run harness:reset` happened only after the second cycle, with the insight recorded via `self-evolve`
62
+ - [ ] Routine single-failure debugging and greenfield planning without failures were not routed here
@@ -4,7 +4,7 @@ description: "Route software/project work through the Harness kernel: classify T
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.11.2
7
+ version: 0.11.7
8
8
  ---
9
9
 
10
10
  # Harness Everything
@@ -33,12 +33,26 @@ function issueMemoryCapability(workflow) {
33
33
  return token;
34
34
  }
35
35
 
36
+ // Host-generated background-task notifications arrive as UserPromptSubmit
37
+ // hook payloads but are not user input (#168). Routing them like prompts
38
+ // replaces the workflow contract mid-turn (e.g. deferred -> a new Tier-2).
39
+ // A prompt that is entirely a notification envelope must never create or
40
+ // replace a workflow; the current contract is kept unchanged.
41
+ function isHostNotificationPrompt(prompt) {
42
+ const text = String(prompt || '').trim();
43
+ if (!text) return false;
44
+ return /^<task-notification[\s>][\s\S]*<\/task-notification>\s*$/i.test(text);
45
+ }
46
+
36
47
  function persistWorkflow(plan, payload, prompt) {
37
48
  if (!payload || !(payload.session_id || payload.sessionId)) return null;
38
49
  const { runtime, hooksRoot } = loadRuntime();
39
50
  const context = runtime.loadWorkflow(payload);
40
51
  const { writeCurrentSession } = require(path.join(hooksRoot, 'lib/harness-state'));
41
52
  writeCurrentSession(context.root, context.sessionId);
53
+ if (isHostNotificationPrompt(prompt)) {
54
+ return { ...context, hooksRoot, retained: true, hostNotification: true };
55
+ }
42
56
  if (context.workflow && runtime.OPEN_STATES.has(context.workflow.state)) {
43
57
  if (!context.workflow.workflowPlan) throw new Error('legacy unresolved workflow needs explicit migration; refusing to replace its obligations');
44
58
  // Steering/status prompts cannot drop an unresolved execution contract.
@@ -92,17 +106,30 @@ function run(raw) {
92
106
  try { payload = JSON.parse(raw); } catch (_) { console.error('[Workflow Router] Invalid hook payload; lifecycle persistence unavailable.'); }
93
107
  }
94
108
  const prompt = promptArg || (typeof payload?.prompt === 'string' ? payload.prompt : '');
95
- const result = core.route(promptArg, raw || null);
96
- let plan = result.contract.workflowPlan;
109
+ const hostNotification = isHostNotificationPrompt(prompt);
110
+ // Host-generated notifications are lifecycle events, not user-authored task
111
+ // input. Never feed their text into the router: when there is an active
112
+ // contract we retain it below; when there is none, the event is a no-op.
113
+ const result = hostNotification ? null : core.route(promptArg, raw || null);
114
+ let plan = result?.contract?.workflowPlan || null;
97
115
  let persisted = null;
98
116
  let failure = null;
99
117
  try {
100
118
  persisted = persistWorkflow(plan, payload, prompt);
101
- if (persisted?.retained) plan = persisted.workflow.workflowPlan;
119
+ if (persisted?.retained && persisted.workflow) plan = persisted.workflow.workflowPlan;
102
120
  } catch (error) { failure = error; }
103
- if (result.sanitized) console.log(result.sanitized);
104
- if (result.stderr) process.stderr.write(result.stderr);
105
- if (persisted?.retained) console.log('\n=> Retaining unresolved workflow from earlier prompts; the checkpoint below is the active execution contract.');
121
+ if (hostNotification && !persisted?.workflow) {
122
+ console.log('\n=> Host notification — no active execution contract; ignored for routing.');
123
+ if (failure) {
124
+ console.error('[Workflow Router] ' + failure.message);
125
+ process.exitCode = 2;
126
+ }
127
+ return;
128
+ }
129
+ if (result?.sanitized) console.log(result.sanitized);
130
+ if (result?.stderr) process.stderr.write(result.stderr);
131
+ if (persisted?.hostNotification) console.log('\n=> Host notification — routing unchanged; keeping the active execution contract.');
132
+ else if (persisted?.retained) console.log('\n=> Retaining unresolved workflow from earlier prompts; the checkpoint below is the active execution contract.');
106
133
  core.printWorkflowPlan(plan);
107
134
  core.printRoutingCheckpoint(plan);
108
135
  core.printKernelContract(plan);
@@ -116,7 +143,7 @@ function run(raw) {
116
143
  console.log(' - Tier 3 / Fable source and artifact mutations require Git worktree isolation; unavailable isolation means BLOCKED.');
117
144
  console.log(' - Escape is limited to workflow-uncovered-scope or host-capability-unavailable, with stage, scope and evidence; other obligations remain mandatory.');
118
145
  }
119
- if (persisted) {
146
+ if (persisted?.workflow) {
120
147
  const controller = path.join(persisted.hooksRoot, 'workflow-disposition.js');
121
148
  console.log(' - Workflow id: ' + persisted.workflow.workflowId);
122
149
  console.log(' - Memory write disposition: ' + (persisted.workflow.workflowPlan.memory?.write || 'none'));
@@ -130,12 +157,13 @@ function run(raw) {
130
157
  if (failure) {
131
158
  console.error('[Workflow Router] ' + failure.message);
132
159
  process.exitCode = 2;
133
- } else if (result.status !== 0) process.exitCode = result.status || 1;
160
+ } else if (result && result.status !== 0) process.exitCode = result.status || 1;
134
161
  }
135
162
 
163
+ if (typeof module !== 'undefined') module.exports = { isHostNotificationPrompt };
164
+
136
165
  if (process.argv.length > 2 || process.stdin.isTTY) run('');
137
- else {
138
- let input = '';
166
+ else { let input = '';
139
167
  let finished = false;
140
168
  const finish = () => { if (finished) return; finished = true; clearTimeout(timeout); run(input); };
141
169
  const timeout = setTimeout(finish, 500);
package/hooks/hooks.json CHANGED
@@ -157,6 +157,19 @@
157
157
  "id": "harness:stop:skill-telemetry"
158
158
  }
159
159
  ],
160
+ "PermissionDenied": [
161
+ {
162
+ "matcher": "Bash|PowerShell",
163
+ "hooks": [
164
+ {
165
+ "type": "command",
166
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/scripts/workflow-mutation-denied.js\""
167
+ }
168
+ ],
169
+ "description": "Release reserved mutation capacity when Claude auto mode denies a shell tool call",
170
+ "id": "harness:permission-denied:mutation-probe"
171
+ }
172
+ ],
160
173
  "PostToolUse": [
161
174
  {
162
175
  "matcher": "Bash|PowerShell|mcp__.*",
@@ -188,7 +201,7 @@
188
201
  "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/scripts/state-persist.js\""
189
202
  }
190
203
  ],
191
- "description": "Save skill transition state",
204
+ "description": "Persist tool outcome, observed workspace mutation, and verification milestones",
192
205
  "id": "harness:post:state-persist"
193
206
  },
194
207
  {
@@ -259,6 +272,17 @@
259
272
  "description": "Track failed tool error signatures for Rule of 3",
260
273
  "id": "harness:post-failure:rule-of-3-tracker"
261
274
  },
275
+ {
276
+ "matcher": "Bash|PowerShell",
277
+ "hooks": [
278
+ {
279
+ "type": "command",
280
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/scripts/state-persist.js\""
281
+ }
282
+ ],
283
+ "description": "Persist failed shell outcome and any workspace mutation that occurred before failure",
284
+ "id": "harness:post-failure:state-persist"
285
+ },
262
286
  {
263
287
  "matcher": "Skill",
264
288
  "hooks": [
@@ -1,13 +1,89 @@
1
1
  'use strict';
2
2
 
3
3
  const fs = require('fs');
4
+ const crypto = require('crypto');
4
5
  const path = require('path');
5
6
  const { spawnSync } = require('child_process');
6
7
 
7
- function git(cwd, args) {
8
- const result = spawnSync('git', args, { cwd, encoding: 'utf8', windowsHide: true, timeout: 5000 });
8
+ function gitRaw(cwd, args) {
9
+ const result = spawnSync('git', args, { cwd, encoding: 'utf8', windowsHide: true, timeout: 5000, maxBuffer: 16 * 1024 * 1024 });
9
10
  if (result.status !== 0) throw new Error('cannot verify Git worktree isolation');
10
- return result.stdout.trim();
11
+ return result.stdout;
12
+ }
13
+
14
+ function git(cwd, args) {
15
+ return gitRaw(cwd, args).trim();
16
+ }
17
+
18
+ function hashWorktreePath(root, relative) {
19
+ const target = path.join(root, relative);
20
+ let stat;
21
+ try { stat = fs.lstatSync(target); }
22
+ catch (error) {
23
+ if (error.code === 'ENOENT') return null;
24
+ throw error;
25
+ }
26
+ if (stat.isDirectory()) {
27
+ const result = spawnSync('git', ['-C', target, 'rev-parse', 'HEAD'], { encoding: 'utf8', windowsHide: true, timeout: 5000 });
28
+ return { mode: '160000', oid: result.status === 0 ? result.stdout.trim() : 'directory' };
29
+ }
30
+ const mode = stat.isSymbolicLink() ? '120000' : ((stat.mode & 0o111) ? '100755' : '100644');
31
+ const result = spawnSync('git', ['hash-object', '--path=' + relative, '--', relative], {
32
+ cwd: root, encoding: 'utf8', windowsHide: true, timeout: 5000,
33
+ });
34
+ if (result.status !== 0) throw new Error('cannot fingerprint workspace content');
35
+ return { mode, oid: result.stdout.trim() };
36
+ }
37
+
38
+ function workspaceFingerprint(cwd) {
39
+ const root = canonical(git(cwd, ['rev-parse', '--show-toplevel']));
40
+ const entries = new Map();
41
+ for (const record of gitRaw(root, ['ls-files', '-s', '-z']).split('\0')) {
42
+ if (!record) continue;
43
+ const tab = record.indexOf('\t');
44
+ if (tab < 0) throw new Error('cannot fingerprint workspace index');
45
+ const meta = record.slice(0, tab).trim().split(/\s+/);
46
+ const relative = record.slice(tab + 1);
47
+ const mode = meta[0];
48
+ const oid = meta[1];
49
+ entries.set(relative, { relative, mode, oid });
50
+ }
51
+
52
+ // Substitute current worktree content for tracked paths that differ from the
53
+ // index. This keeps the fingerprint stable across git add / git commit when
54
+ // visible workspace content did not change.
55
+ for (const relative of gitRaw(root, ['diff-files', '--name-only', '-z']).split('\0').filter(Boolean)) {
56
+ const value = hashWorktreePath(root, relative);
57
+ if (value) entries.set(relative, { relative, mode: value.mode, oid: value.oid });
58
+ else entries.delete(relative);
59
+ }
60
+
61
+ for (const relative of gitRaw(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean)) {
62
+ const value = hashWorktreePath(root, relative);
63
+ entries.set(relative, { relative, mode: value.mode, oid: value.oid });
64
+ }
65
+
66
+ const digest = crypto.createHash('sha256');
67
+ digest.update('harness-workspace-fingerprint-v1\0');
68
+ for (const entry of [...entries.values()].sort((a, b) => a.relative.localeCompare(b.relative))) {
69
+ digest.update(entry.relative); digest.update('\0');
70
+ digest.update(entry.mode); digest.update('\0');
71
+ digest.update(entry.oid); digest.update('\0');
72
+ }
73
+ return digest.digest('hex');
74
+ }
75
+
76
+ function shellProbeKey(payload, cwd) {
77
+ const toolUseId = String(payload?.tool_use_id || payload?.toolUseId || '').trim();
78
+ const tool = String(payload?.tool_name || payload?.tool || '');
79
+ const command = commandOf(payload);
80
+ return crypto.createHash('sha256')
81
+ .update('harness-shell-probe-v2\0')
82
+ .update(toolUseId || 'no-tool-use-id').update('\0')
83
+ .update(tool).update('\0')
84
+ .update(key(cwd)).update('\0')
85
+ .update(command)
86
+ .digest('hex');
11
87
  }
12
88
 
13
89
  function canonical(value) {
@@ -144,9 +220,9 @@ function splitShellSegments(text) {
144
220
 
145
221
  function classifyShell(command) {
146
222
  const text = String(command || '').trim();
147
- if (!text) return 'mutation-or-unknown';
223
+ if (!text) return 'untrusted';
148
224
  const segments = splitShellSegments(text);
149
- if (!segments) return 'mutation-or-unknown';
225
+ if (!segments) return 'untrusted';
150
226
  if (segments.length === 1) {
151
227
  if (/^git\s+worktree\s+add\s+/i.test(segments[0]) && !/\s--(?:force|checkout|detach)(?:\s|=|$)/i.test(segments[0])) return 'worktree-setup';
152
228
  return isReadOnlySegment(segments[0]) ? 'read-only' : 'mutation-or-unknown';
@@ -172,6 +248,35 @@ function mutationPaths(payload) {
172
248
  }
173
249
  return [input.file_path || input.filePath || input.path].filter(value => typeof value === 'string' && value.trim());
174
250
  }
251
+
252
+ // Bound workspace root plus its linked worktrees. Git failures (e.g. a
253
+ // non-git workspace) degrade to the root alone instead of throwing, so
254
+ // Tier-2 accounting never blocks on this enumeration (#165; cf. #162).
255
+ function worktreeRoots(root) {
256
+ const roots = [root];
257
+ try {
258
+ for (const field of git(root, ['worktree', 'list', '--porcelain', '-z']).split('\0')) {
259
+ if (field.startsWith('worktree ')) {
260
+ const candidate = field.slice('worktree '.length).trim();
261
+ if (candidate) roots.push(candidate);
262
+ }
263
+ }
264
+ } catch (_) { /* root alone */ }
265
+ return roots;
266
+ }
267
+
268
+ // Direct-tool (Edit/Write/apply_patch) targets count against the Tier-2
269
+ // budget only when at least one target lies inside the workspace (#165).
270
+ // Unknown targets (no parseable path) stay conservative and count.
271
+ function directMutationInWorkspace(payload, cwd, root) {
272
+ const targets = mutationPaths(payload);
273
+ if (!targets.length) return true;
274
+ const roots = worktreeRoots(root);
275
+ return targets.some(target => {
276
+ const resolved = path.resolve(cwd, target);
277
+ return roots.some(candidate => within(candidate, resolved));
278
+ });
279
+ }
175
280
  function assertTargets(payload, cwd, isolatedRoot) {
176
281
  const targets = mutationPaths(payload);
177
282
  if (!targets.length) throw new Error('mutation target is unknown; cannot verify worktree isolation');
@@ -198,4 +303,4 @@ function assertShellScope(command, cwd, isolatedRoot) {
198
303
  }
199
304
  }
200
305
 
201
- module.exports = { canonical, key, within, linkedWorktree, classifyShell, inputOf, cwdOf, commandOf, mutationPaths, assertTargets, assertShellScope };
306
+ module.exports = { canonical, key, within, linkedWorktree, classifyShell, workspaceFingerprint, shellProbeKey, inputOf, cwdOf, commandOf, mutationPaths, worktreeRoots, directMutationInWorkspace, assertTargets, assertShellScope };
@@ -43,6 +43,140 @@ function loadWorkflow(payload) {
43
43
 
44
44
  function saveWorkflow(context) { atomicWriteJson(context.file, context.workflow); }
45
45
 
46
+ const MUTATION_PROBE_KEY = /^[a-f0-9]{64}$/;
47
+ const MUTATION_PROBE_WAIT = new Int32Array(new SharedArrayBuffer(4));
48
+
49
+ function mutationProbeDir(context) {
50
+ return path.join(context.sessionDir, 'mutation-probes');
51
+ }
52
+
53
+ function mutationProbeFile(context, key) {
54
+ if (!MUTATION_PROBE_KEY.test(String(key || ''))) throw new Error('invalid mutation probe identity');
55
+ return path.join(mutationProbeDir(context), key + '.json');
56
+ }
57
+
58
+ function withMutationProbeLock(context, callback) {
59
+ fs.mkdirSync(context.sessionDir, { recursive: true });
60
+ const lockDir = path.join(context.sessionDir, '.mutation-probes.lock');
61
+ let acquired = false;
62
+ for (let attempt = 0; attempt < 200; attempt++) {
63
+ try {
64
+ fs.mkdirSync(lockDir);
65
+ acquired = true;
66
+ break;
67
+ } catch (error) {
68
+ if (error.code !== 'EEXIST') throw error;
69
+ try {
70
+ const stat = fs.statSync(lockDir);
71
+ if (Date.now() - stat.mtimeMs > 30000) {
72
+ fs.rmSync(lockDir, { recursive: true, force: true });
73
+ continue;
74
+ }
75
+ } catch (_) { /* retry below */ }
76
+ Atomics.wait(MUTATION_PROBE_WAIT, 0, 0, 10);
77
+ }
78
+ }
79
+ if (!acquired) throw new Error('cannot acquire mutation probe lock');
80
+ try { return callback(); }
81
+ finally { fs.rmSync(lockDir, { recursive: true, force: true }); }
82
+ }
83
+
84
+ function mutationProbeReservations(context) {
85
+ const dir = mutationProbeDir(context);
86
+ let files = [];
87
+ try { files = fs.readdirSync(dir).filter(file => /^[a-f0-9]{64}\.json$/.test(file)); }
88
+ catch (_) { return 0; }
89
+ let count = 0;
90
+ for (const file of files) {
91
+ const probe = readJson(path.join(dir, file));
92
+ if (probe?.schemaVersion === 1 && probe.reserveIteration === true) count++;
93
+ }
94
+ return count;
95
+ }
96
+
97
+ function refreshWorkflowForProbe(context) {
98
+ const latest = readJson(context.file);
99
+ if (!latest || latest.sessionId !== context.sessionId) throw new Error('cannot refresh workflow for mutation probe');
100
+ context.workflow = latest;
101
+ return latest;
102
+ }
103
+
104
+ function assertIterationCapacity(context, evidence) {
105
+ const { workflow } = context;
106
+ if (!workflow) throw budgetError('no workflow available for iteration capacity');
107
+ const budget = ensureWorkflowBudget(workflow);
108
+ if (budget.state !== 'active') throw budgetError(`workflow budget is ${budget.state}: ${budget.reasonCode || 'unavailable'}`);
109
+ const limit = budget.limits.maxIterations;
110
+ if (limit === null) return { applicable: false, value: budget.counters.iterations, reserved: 0 };
111
+ const reserved = mutationProbeReservations(context);
112
+ if (budget.counters.iterations + reserved >= limit) {
113
+ return exhaustBudget(context, 'iteration-budget-exhausted', evidence || 'untrusted-shell-capacity');
114
+ }
115
+ return { applicable: true, value: budget.counters.iterations, reserved, limit };
116
+ }
117
+
118
+ function registerMutationProbe(context, key, fingerprint, reserveIteration) {
119
+ if (!MUTATION_PROBE_KEY.test(String(key || '')) || !MUTATION_PROBE_KEY.test(String(fingerprint || ''))) {
120
+ throw new Error('invalid mutation probe identity');
121
+ }
122
+ return withMutationProbeLock(context, () => {
123
+ refreshWorkflowForProbe(context);
124
+ if (reserveIteration) assertIterationCapacity(context, 'shell:untrusted');
125
+ const dir = mutationProbeDir(context);
126
+ fs.mkdirSync(dir, { recursive: true });
127
+ const file = mutationProbeFile(context, key);
128
+ if (fs.existsSync(file)) throw new Error('mutation probe is already pending for this tool call');
129
+ const probe = {
130
+ schemaVersion: 1,
131
+ fingerprint,
132
+ reserveIteration: Boolean(reserveIteration),
133
+ observedAt: Date.now(),
134
+ };
135
+ atomicWriteJson(file, probe);
136
+ return probe;
137
+ });
138
+ }
139
+
140
+ function peekMutationProbe(context, key) {
141
+ return readJson(mutationProbeFile(context, key));
142
+ }
143
+
144
+ function settleMutationProbe(context, key, afterFingerprint, tool) {
145
+ if (!MUTATION_PROBE_KEY.test(String(afterFingerprint || ''))) throw new Error('invalid mutation probe fingerprint');
146
+ return withMutationProbeLock(context, () => {
147
+ const file = mutationProbeFile(context, key);
148
+ const probe = readJson(file);
149
+ if (!probe || probe.schemaVersion !== 1) return null;
150
+ refreshWorkflowForProbe(context);
151
+ fs.unlinkSync(file);
152
+ const changed = afterFingerprint !== probe.fingerprint;
153
+ if (changed) {
154
+ context.workflow.lastMutationAt = Date.now();
155
+ if (probe.reserveIteration && context.workflow.strategy === 'iterative-single') {
156
+ recordBudgetEvent(context, 'iteration', { evidence: String(tool || 'shell') + ':observed-workspace-mutation' });
157
+ } else {
158
+ saveWorkflow(context);
159
+ }
160
+ }
161
+ return { changed, probe };
162
+ });
163
+ }
164
+
165
+ function discardMutationProbe(context, key) {
166
+ return withMutationProbeLock(context, () => {
167
+ const file = mutationProbeFile(context, key);
168
+ if (!fs.existsSync(file)) return false;
169
+ fs.unlinkSync(file);
170
+ return true;
171
+ });
172
+ }
173
+
174
+ function clearMutationProbes(context) {
175
+ return withMutationProbeLock(context, () => {
176
+ fs.rmSync(mutationProbeDir(context), { recursive: true, force: true });
177
+ });
178
+ }
179
+
46
180
  function budgetLimits(workflow) {
47
181
  const limits = workflow?.workflowPlan?.limits || {};
48
182
  return {
@@ -123,7 +257,8 @@ function recordBudgetEvent(context, type, options = {}) {
123
257
  const consume = (counter, limitName, reasonCode) => {
124
258
  const limit = budget.limits[limitName];
125
259
  if (limit === null) return { applicable: false, value: budget.counters[counter] };
126
- if (budget.counters[counter] >= limit) return exhaustBudget(context, reasonCode, evidence);
260
+ const reserved = type === 'iteration' ? mutationProbeReservations(context) : 0;
261
+ if (budget.counters[counter] + reserved >= limit) return exhaustBudget(context, reasonCode, evidence);
127
262
  budget.counters[counter]++;
128
263
  appendBudgetEvent(budget, { type, counter, value: budget.counters[counter], limit, evidence, observedAt: now });
129
264
  persistBudget(context);
@@ -175,6 +310,7 @@ function resetWorkflowBudget(context, evidence) {
175
310
  evidence: String(evidence).trim(),
176
311
  resetAt: now,
177
312
  }].slice(-16);
313
+ clearMutationProbes(context);
178
314
  workflow.budget = {
179
315
  schemaVersion: 1,
180
316
  epoch: previous.epoch + 1,
@@ -260,4 +396,4 @@ function readHookInput(decide) {
260
396
  process.stdin.on('error', finish);
261
397
  }
262
398
 
263
- module.exports = { OPEN_STATES, SAFE_ID, WORKFLOW_CONTROLLER_COMMANDS, isMajorWorkflow, loadWorkflow, saveWorkflow, budgetLimits, ensureWorkflowBudget, recordBudgetEvent, resetWorkflowBudget, syncBudgetToRun, matchingRun, unresolvedStages, readHookInput };
399
+ module.exports = { OPEN_STATES, SAFE_ID, WORKFLOW_CONTROLLER_COMMANDS, isMajorWorkflow, loadWorkflow, saveWorkflow, budgetLimits, ensureWorkflowBudget, mutationProbeReservations, assertIterationCapacity, registerMutationProbe, peekMutationProbe, settleMutationProbe, discardMutationProbe, clearMutationProbes, recordBudgetEvent, resetWorkflowBudget, syncBudgetToRun, matchingRun, unresolvedStages, readHookInput };
@@ -17,6 +17,7 @@ process.stdin.on('end', () => {
17
17
  const payload = JSON.parse(inputData);
18
18
  const hookEventName = payload.hook_event_name || payload.hookEventName || '';
19
19
  const isFailureEvent = hookEventName === 'PostToolUseFailure';
20
+ const isSuccessEvent = hookEventName === 'PostToolUse';
20
21
  const toolResponse = payload.tool_response || {};
21
22
  const stdout = toolResponse.stdout ?? payload.stdout ?? '';
22
23
  const stderr = toolResponse.stderr ?? payload.stderr ?? '';
@@ -25,10 +26,10 @@ process.stdin.on('end', () => {
25
26
  const exitCode = typeof rawExitCode === 'number' ? rawExitCode : undefined;
26
27
 
27
28
  const explicitFailure = exitCode !== undefined && exitCode !== 0;
28
- const explicitSuccess = exitCode === 0;
29
29
  const stderrSignal = typeof stderr === 'string' && stderr.trim().length > 0;
30
30
  const looksLikeError = /\b(error|fail|failed|failure|exception|fatal|panic|traceback|denied|refused|cannot|unable)\b/i.test(stderr);
31
- const isFailure = isFailureEvent || explicitFailure || (exitCode === undefined && stderrSignal && looksLikeError);
31
+ const isFailure = isFailureEvent || explicitFailure ||
32
+ (!isSuccessEvent && exitCode === undefined && stderrSignal && looksLikeError);
32
33
  const errorText = isFailureEvent
33
34
  ? (failureText || (stderrSignal ? stderr : stdout) || '')
34
35
  : ((stderrSignal ? stderr : stdout) || failureText || '');
@@ -47,19 +48,22 @@ process.stdin.on('end', () => {
47
48
  const filePath = payload.tool_input?.file_path || payload.tool_input?.filePath || '';
48
49
  const command = payload.tool_input?.command || '';
49
50
 
50
- // Categorize failure type for context-aware thresholds
51
+ // Categorize failure type for context-aware thresholds.
52
+ // NOTE (#167): match anchored diagnostic phrases, not bare substrings.
53
+ // A bare `denied`/`timeout` substring matches file names such as
54
+ // `workflow-mutation-denied.js` and misclassifies the failure.
51
55
  let category = 'unknown';
52
- if (/SyntaxError|Unexpected token|Syntax Error/i.test(errorText)) {
56
+ if (/\bSyntaxError\b|Unexpected token|Syntax Error/i.test(errorText)) {
53
57
  category = 'syntax';
54
- } else if (/ENOENT|not found|No such file|找不到|不存在/i.test(errorText)) {
58
+ } else if (/\bENOENT\b|\bnot found\b|No such file|找不到|不存在/i.test(errorText)) {
55
59
  category = 'environment';
56
- } else if (/timeout|timed out|超時|逾時/i.test(errorText)) {
60
+ } else if (/\bETIMEDOUT\b|TimeoutError|\btimeout\b|\btimed out\b|\btiming out\b|超時|逾時/i.test(errorText)) {
57
61
  category = 'timeout';
58
62
  } else if (/test.*fail|assertion|AssertionError|測試.*失敗|斷言.*錯誤/i.test(errorText)) {
59
63
  category = 'test';
60
- } else if (/permission|denied|EACCES|權限/i.test(errorText)) {
64
+ } else if (/\bpermission denied\b|\bEACCES\b|\bEPERM\b|權限.*(拒絕|不足|被拒)|拒絕.*權限/i.test(errorText)) {
61
65
  category = 'permission';
62
- } else if (/dependency|module not found|Cannot find module|模組.*找不到/i.test(errorText)) {
66
+ } else if (/\bdependency\b|\bmodule not found\b|Cannot find module|模組.*找不到/i.test(errorText)) {
63
67
  category = 'dependency';
64
68
  }
65
69
 
@@ -114,7 +118,11 @@ process.stdin.on('end', () => {
114
118
  state.lastFailureAt = Date.now();
115
119
 
116
120
  fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
117
- } else if (!isFailureEvent && explicitSuccess) {
121
+ } else if (!isFailure) {
122
+ // NOTE (#166, follows #153): Claude Code PostToolUse success payloads
123
+ // carry no numeric exit code. The lifecycle event is authoritative:
124
+ // PostToolUse is success unless a numeric non-zero status contradicts it;
125
+ // hosts without lifecycle event names keep the conservative stderr fallback.
118
126
  // A successful action after an accepted zoom-out is an objective recovery
119
127
  // boundary. Emit only IDs/hashes/category; never copy command/output text.
120
128
  if ((state.zoomOutCycles || 0) > 0 && state.lastHash) {