specbox 6.29.0 → 6.29.2

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 (57) hide show
  1. package/README.md +5 -3
  2. package/bin/specbox.mjs +38 -2
  3. package/hooks/app-docs-sync-guard.mjs +326 -0
  4. package/hooks/branch-guard.mjs +79 -0
  5. package/hooks/checkpoint-freshness-guard.mjs +56 -0
  6. package/hooks/commit-spec-guard.mjs +61 -0
  7. package/hooks/context-budget-guard.mjs +130 -0
  8. package/hooks/design-gate.mjs +144 -0
  9. package/hooks/design-review-gate.mjs +102 -0
  10. package/hooks/design-system-gate.mjs +134 -0
  11. package/hooks/e2e-gate.mjs +86 -0
  12. package/hooks/file-ownership-guard.mjs +163 -0
  13. package/hooks/freeform-fragment.mjs +160 -0
  14. package/hooks/freeform-path-guard.mjs +172 -0
  15. package/hooks/healing-budget-guard.mjs +83 -0
  16. package/hooks/hooks-history.json +176 -0
  17. package/hooks/hooks-manifest.json +51 -0
  18. package/hooks/implement-checkpoint.mjs +46 -0
  19. package/hooks/implement-healing.mjs +38 -0
  20. package/hooks/lib/autopilot.mjs +240 -0
  21. package/hooks/lib/config.mjs +117 -0
  22. package/hooks/lib/decisiones.mjs +58 -0
  23. package/hooks/lib/design-gaps.mjs +272 -0
  24. package/hooks/lib/execution-context.mjs +69 -0
  25. package/hooks/lib/freeform-fragment.mjs +379 -0
  26. package/hooks/lib/freeform-path.mjs +115 -0
  27. package/hooks/lib/handoff-builder.mjs +388 -0
  28. package/hooks/lib/heartbeat-send.mjs +91 -0
  29. package/hooks/lib/heartbeat.mjs +110 -0
  30. package/hooks/lib/mcp-client-io.mjs +210 -0
  31. package/hooks/lib/mcp-client.mjs +91 -0
  32. package/hooks/lib/native-reservation-revalidate.mjs +80 -0
  33. package/hooks/lib/output.mjs +70 -0
  34. package/hooks/lib/ownership-map.mjs +162 -0
  35. package/hooks/lib/token-counter.mjs +81 -0
  36. package/hooks/lib/utils.mjs +235 -0
  37. package/hooks/no-bypass-guard.mjs +57 -0
  38. package/hooks/on-session-end.mjs +163 -0
  39. package/hooks/pipeline-phase-guard.mjs +140 -0
  40. package/hooks/post-implement-validate.mjs +61 -0
  41. package/hooks/pre-commit-lint.mjs +76 -0
  42. package/hooks/pre-prd-discovery-check.mjs +242 -0
  43. package/hooks/pre-read-budget-guard.mjs +83 -0
  44. package/hooks/quality-first-guard.mjs +85 -0
  45. package/hooks/read-tracker.mjs +33 -0
  46. package/hooks/session-heartbeat.mjs +113 -0
  47. package/hooks/session-start.mjs +159 -0
  48. package/hooks/settings-hooks.json +363 -0
  49. package/hooks/spec-guard.mjs +152 -0
  50. package/hooks/stripe-safety-guard.mjs +262 -0
  51. package/hooks/uc-lifecycle-guard.mjs +87 -0
  52. package/lib/hooks.mjs +156 -0
  53. package/lib/install.mjs +9 -0
  54. package/lib/internal.mjs +26 -3
  55. package/lib/mcp-headers.mjs +31 -3
  56. package/lib/messages.mjs +41 -0
  57. package/package.json +4 -2
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * file-ownership-guard.mjs — PreToolUse hook for Write/Edit (v5.32.0).
4
+ *
5
+ * Validates that the active sub-agent (declared in
6
+ * .quality/active_agent.json) only writes inside its declared
7
+ * ownership in .claude/skills/implement/file-ownership.md.
8
+ *
9
+ * Behaviour:
10
+ * - No active_agent.json → no-op (the orchestrator itself is
11
+ * acting; not subject to this guard).
12
+ * - mode=warn (default) → stderr WARNING, exit 0.
13
+ * - mode=strict → stderr BLOCKED, exit 2 with actionable
14
+ * message (which agent should own the path).
15
+ * - mode=off → no-op.
16
+ *
17
+ * Settings:
18
+ * specbox.implement.task_isolation.ownership_mode (default "warn")
19
+ */
20
+
21
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
22
+ import { dirname } from 'node:path';
23
+ import { parseOwnershipMap, pathAllowedForAgent, isSuspiciousPath } from './lib/ownership-map.mjs';
24
+ import { readActiveAgent } from './lib/execution-context.mjs';
25
+ import { noteWith } from './lib/output.mjs';
26
+
27
+ const SETTINGS_PATH = '.claude/settings.local.json';
28
+ const TASK_ISOLATION_CACHE = '.quality/task_isolation.json';
29
+ const DEFAULT_MODE = 'warn';
30
+
31
+ const raw = readStdinSync();
32
+ let payload = {};
33
+ try { payload = JSON.parse(raw); } catch { /* ignore */ }
34
+
35
+ const toolName = payload?.tool_name || payload?.toolName || '';
36
+ if (toolName !== 'Write' && toolName !== 'Edit') {
37
+ process.exit(0);
38
+ }
39
+
40
+ const active = readActiveAgent();
41
+ if (!active?.agent) {
42
+ // No active sub-agent = the orchestrator is doing the write itself.
43
+ // Out of scope for this guard.
44
+ process.exit(0);
45
+ }
46
+
47
+ const mode = readMode();
48
+ if (mode === 'off') {
49
+ process.exit(0);
50
+ }
51
+
52
+ const filePath = extractFilePath(payload);
53
+ if (!filePath) {
54
+ // Can't extract the target path — fail open.
55
+ process.exit(0);
56
+ }
57
+
58
+ if (isSuspiciousPath(filePath)) {
59
+ // Always block path traversal, regardless of mode.
60
+ console.error(
61
+ `[file-ownership-guard] BLOCKED — suspicious path '${filePath}' ` +
62
+ `(.. or absolute path). Use a repo-relative path inside the project root.`
63
+ );
64
+ bumpCounter('tasks_failed_ownership');
65
+ process.exit(2);
66
+ }
67
+
68
+ const map = parseOwnershipMap();
69
+ const allowed = pathAllowedForAgent(filePath, active.agent, map);
70
+
71
+ if (allowed === true) {
72
+ process.exit(0);
73
+ }
74
+
75
+ if (allowed === null) {
76
+ // Unknown agent or empty ownership → fail-open with a hint.
77
+ noteWith('PreToolUse', '[file-ownership-guard] Agente sin mapa de propiedad', [
78
+ `${active.agent} no está en el mapa de propiedad (o el mapa está vacío): ${filePath} se permite.`,
79
+ 'Si no es lo esperado, actualiza .claude/skills/implement/file-ownership.md.',
80
+ ]);
81
+ }
82
+
83
+ // allowed === false → mismatch
84
+ const ownerHint = suggestOwner(filePath, map);
85
+ const message = ownerHint
86
+ ? `Path ${filePath} is owned by ${ownerHint}, not ${active.agent}. ` +
87
+ `Either delegate the write to ${ownerHint}, or report it as a pending dependency.`
88
+ : `Path ${filePath} does not match the ownership of ${active.agent}. ` +
89
+ `Either delegate the write to the correct agent, or report it as a pending dependency.`;
90
+
91
+ bumpCounter('tasks_failed_ownership');
92
+
93
+ if (mode === 'strict') {
94
+ console.error(`[file-ownership-guard] BLOCKED — ${message}`);
95
+ process.exit(2);
96
+ }
97
+
98
+ // warn: a note to the agent (US-93/UC-9302: stderr with exit 0 reaches nobody).
99
+ noteWith('PreToolUse', '[file-ownership-guard] Escritura fuera de lo que le toca a este agente', [message, 'La escritura sigue (modo aviso).']);
100
+
101
+ // ── Helpers ───────────────────────────────────────────────────────────
102
+
103
+ function readStdinSync() {
104
+ try { return readFileSync(0, 'utf-8'); } catch { return ''; }
105
+ }
106
+
107
+ function readMode() {
108
+ if (!existsSync(SETTINGS_PATH)) return DEFAULT_MODE;
109
+ try {
110
+ const settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8'));
111
+ const m = settings?.specbox?.implement?.task_isolation?.ownership_mode;
112
+ return typeof m === 'string' ? m : DEFAULT_MODE;
113
+ } catch { return DEFAULT_MODE; }
114
+ }
115
+
116
+ function extractFilePath(payload) {
117
+ const ti = payload?.tool_input ?? {};
118
+ if (typeof ti.file_path === 'string') return normalisePath(ti.file_path);
119
+ if (typeof ti.path === 'string') return normalisePath(ti.path);
120
+ return null;
121
+ }
122
+
123
+ function normalisePath(p) {
124
+ if (!p) return p;
125
+ // If absolute, try to make relative to cwd. We accept both forms but
126
+ // matching is done relative to repo root.
127
+ const cwd = process.cwd();
128
+ if (p.startsWith(cwd + '/')) return p.slice(cwd.length + 1);
129
+ if (p.startsWith('/')) {
130
+ // absolute path that is NOT under cwd — keep absolute so
131
+ // isSuspiciousPath catches it.
132
+ return p;
133
+ }
134
+ return p.replace(/^\.\//, '');
135
+ }
136
+
137
+ function suggestOwner(path, map) {
138
+ for (const [agent, globs] of Object.entries(map)) {
139
+ if (pathAllowedForAgent(path, agent, { [agent]: globs }) === true) {
140
+ return agent;
141
+ }
142
+ }
143
+ return null;
144
+ }
145
+
146
+ function bumpCounter(key) {
147
+ try {
148
+ let cache = {};
149
+ if (existsSync(TASK_ISOLATION_CACHE)) {
150
+ try {
151
+ cache = JSON.parse(readFileSync(TASK_ISOLATION_CACHE, 'utf-8'));
152
+ } catch { cache = {}; }
153
+ }
154
+ cache[key] = (cache[key] || 0) + 1;
155
+ cache.last_event_at = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
156
+ mkdirSync(dirname(TASK_ISOLATION_CACHE), { recursive: true });
157
+ writeFileSync(
158
+ TASK_ISOLATION_CACHE,
159
+ JSON.stringify(cache, null, 2),
160
+ 'utf-8'
161
+ );
162
+ } catch { /* best-effort */ }
163
+ }
@@ -0,0 +1,160 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * freeform-fragment.mjs — FreeForm with the remote MCP, without the whole board (UC-11103, UC-11102).
4
+ *
5
+ * PreToolUse (SpecBox tools that take `items_content`): in a FreeForm project
6
+ * whose SpecBox MCP is remote, puts in `items_content` only the part of
7
+ * doc/tracking/items.json the tool needs, with the highest US/UC/EP number of
8
+ * the whole board (`specbox-freeform-fragment/1`); tools without a fragment get
9
+ * the whole file. The model neither reads nor writes the board.
10
+ *
11
+ * PostToolUse: merges what the tool changed into items.json (field by field
12
+ * against what was sent, under a lock, atomically) and hides `items_content`
13
+ * from the answer the model sees.
14
+ *
15
+ * Never blocks a call: when it cannot act it stays silent and the call goes as
16
+ * the model wrote it. A failed merge exits 2 with what was not saved; the
17
+ * fragment stays in .quality/freeform-fragments/ for recovery.
18
+ */
19
+
20
+ import { execFileSync } from 'node:child_process';
21
+ import { existsSync, readFileSync, unlinkSync } from 'node:fs';
22
+ import { isAbsolute, join } from 'node:path';
23
+ import { isRemoteMcp } from './lib/freeform-path.mjs';
24
+ import {
25
+ CONTENT_TOOLS,
26
+ buildItemsContent,
27
+ extractItemsContent,
28
+ mergeFragment,
29
+ parseToolName,
30
+ pendingPath,
31
+ reservedNumbers,
32
+ withLock,
33
+ withoutItemsContent,
34
+ writeAtomic,
35
+ } from './lib/freeform-fragment.mjs';
36
+ import { readHookInput } from './lib/utils.mjs';
37
+
38
+ const { event, toolName, toolInput, cwd, payload } = readHookInput();
39
+ const parsed = parseToolName(toolName);
40
+ if (!parsed || !CONTENT_TOOLS.has(parsed.tool) || !payload.tool_use_id) process.exit(0);
41
+
42
+ const root = (() => {
43
+ try {
44
+ return execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], {
45
+ encoding: 'utf-8',
46
+ stdio: ['ignore', 'pipe', 'ignore'],
47
+ }).trim() || cwd;
48
+ } catch {
49
+ return cwd;
50
+ }
51
+ })();
52
+ const settings = readJson(join(root, '.claude', 'settings.local.json'))?.specbox ?? {};
53
+ if (settings.backend_type !== 'freeform' || !isRemoteMcp({ cwd: root })) process.exit(0);
54
+
55
+ const trackingDir =
56
+ typeof settings.freeform_root_absolute === 'string' && isAbsolute(settings.freeform_root_absolute)
57
+ ? settings.freeform_root_absolute
58
+ : join(root, 'doc', 'tracking');
59
+ const itemsPath = join(trackingDir, 'items.json');
60
+ const stateDir = join(root, '.quality', 'freeform-fragments');
61
+ const pending = pendingPath(stateDir, payload.tool_use_id);
62
+
63
+ if (event === 'PreToolUse') pre();
64
+ else if (event === 'PostToolUse') post();
65
+ process.exit(0);
66
+
67
+ function pre() {
68
+ const raw = existsSync(itemsPath) ? readFileSync(itemsPath, 'utf-8') : '[]';
69
+ const items = parseJson(raw);
70
+ if (!Array.isArray(items)) return; // another dialect: leave the call as it is
71
+ const given = toolInput.items_content;
72
+ if (typeof given === 'string' && given.trim() !== raw.trim()) return; // explicit content wins
73
+
74
+ const built = withLock(stateDir, () => {
75
+ const result = buildItemsContent({
76
+ tool: parsed.tool,
77
+ args: toolInput,
78
+ items,
79
+ raw,
80
+ reserved: reservedNumbers(stateDir),
81
+ });
82
+ writeAtomic(
83
+ pending,
84
+ JSON.stringify({
85
+ tool: parsed.tool,
86
+ created_at: new Date().toISOString(),
87
+ whole: result.whole,
88
+ reserves: result.reserves,
89
+ sent: result.sent,
90
+ }),
91
+ );
92
+ return result;
93
+ });
94
+ process.stdout.write(
95
+ JSON.stringify({
96
+ hookSpecificOutput: {
97
+ hookEventName: 'PreToolUse',
98
+ updatedInput: { ...toolInput, items_content: built.itemsContent },
99
+ },
100
+ }),
101
+ );
102
+ }
103
+
104
+ function post() {
105
+ if (!existsSync(pending)) return;
106
+ const response = payload.tool_response;
107
+ const content = extractItemsContent(response);
108
+ if (content == null) {
109
+ unlinkSync(pending); // a read, or an error: nothing to merge
110
+ return;
111
+ }
112
+ try {
113
+ const sentInfo = JSON.parse(readFileSync(pending, 'utf-8'));
114
+ const back = JSON.parse(content);
115
+ const returned = Array.isArray(back) ? back : back?.items;
116
+ if (!Array.isArray(returned)) throw new Error('the answer carries no items');
117
+ const changes = withLock(stateDir, () => {
118
+ const local = existsSync(itemsPath) ? JSON.parse(readFileSync(itemsPath, 'utf-8')) : [];
119
+ const merged = mergeFragment(local, sentInfo.sent, returned);
120
+ writeAtomic(itemsPath, `${JSON.stringify(merged, null, 2)}\n`);
121
+ unlinkSync(pending);
122
+ return merged.length - local.length;
123
+ });
124
+ process.stdout.write(
125
+ JSON.stringify({
126
+ hookSpecificOutput: {
127
+ hookEventName: 'PostToolUse',
128
+ updatedToolOutput: withoutItemsContent(response),
129
+ additionalContext:
130
+ `SpecBox: el tablero ya está guardado en ${itemsPath.replace(`${root}/`, '')}` +
131
+ (changes ? ` (${changes > 0 ? '+' : ''}${changes} elementos)` : '') +
132
+ '. No lo escribas a mano.',
133
+ },
134
+ }),
135
+ );
136
+ } catch (err) {
137
+ process.stderr.write(
138
+ `SpecBox freeform-fragment: no se pudo guardar en ${itemsPath} lo que cambió ${parsed.tool} ` +
139
+ `(${err.message}). La respuesta está intacta y lo enviado queda en ${pending}: ` +
140
+ 'vuelve a leer el tablero antes de seguir y repite la llamada si el cambio no está.\n',
141
+ );
142
+ process.exit(2);
143
+ }
144
+ }
145
+
146
+ function readJson(path) {
147
+ try {
148
+ return JSON.parse(readFileSync(path, 'utf-8'));
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+
154
+ function parseJson(text) {
155
+ try {
156
+ return JSON.parse(text);
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * freeform-path-guard.mjs — PreToolUse hook (v5.33.0)
4
+ *
5
+ * Intercepts MCP tool calls that configure or onboard a FreeForm backend
6
+ * (`mcp__SpecBox-MCP__set_auth_token`, `mcp__SpecBox-MCP__onboard_project`)
7
+ * and ensures the FreeForm root path reaching the MCP server is ALWAYS
8
+ * an absolute path on the client filesystem.
9
+ *
10
+ * Why: when the MCP server runs remotely (an http or mcp-remote entry for
11
+ * SpecBox-MCP in the Claude Code config, or env SPECBOX_ENGINE_MCP_URL set),
12
+ * set_auth_token goes without root_path: the board travels as items_content.
13
+ * With a local server, a relative path like "doc/tracking" is resolved against the server CWD,
14
+ * not the client repo — so the tracking folder gets created on the VPS
15
+ * instead of the developer's laptop. Server-side guards already reject
16
+ * this with FREEFORM_PATH_MUST_BE_ABSOLUTE, but that surfaces as an error
17
+ * the user has to fix by hand. This hook auto-rewrites the input so the
18
+ * call just works.
19
+ *
20
+ * Behavior:
21
+ * - If tool is not one of the watched MCP tools → exit 0 (no-op).
22
+ * - If backend_type != "freeform" → exit 0 (no-op).
23
+ * - If path is already absolute → exit 0 (no-op).
24
+ * - If path is relative and we can resolve git toplevel → rewrite to
25
+ * absolute via hookSpecificOutput.updatedInput, exit 0.
26
+ * - If path is relative but CWD is not a git repo → exit 2
27
+ * (block with a clear error) — auto-resolution would be ambiguous.
28
+ *
29
+ * Logs every rewrite to .quality/logs/freeform-path-rewrites.jsonl so the
30
+ * behavior is auditable.
31
+ */
32
+
33
+ import { isAbsolute } from 'path';
34
+ import { resolveFreeformPath, isRemoteMcp } from './lib/freeform-path.mjs';
35
+ import { readStdin, appendLine, now } from './lib/utils.mjs';
36
+
37
+ const WATCHED_TOOLS = new Set([
38
+ 'mcp__SpecBox-MCP__set_auth_token',
39
+ 'mcp__SpecBox-MCP__onboard_project',
40
+ ]);
41
+
42
+ // Map of tool → which argument name carries the FreeForm root.
43
+ const ROOT_ARG_BY_TOOL = {
44
+ 'mcp__SpecBox-MCP__set_auth_token': 'root_path',
45
+ 'mcp__SpecBox-MCP__onboard_project': 'freeform_root_absolute',
46
+ };
47
+
48
+ const DEFAULT_ROOT = 'doc/tracking';
49
+ const LOG_PATH = '.quality/logs/freeform-path-rewrites.jsonl';
50
+
51
+ const raw = readStdin();
52
+ let payload = {};
53
+ try {
54
+ payload = JSON.parse(raw);
55
+ } catch {
56
+ process.exit(0);
57
+ }
58
+
59
+ const toolName = payload?.tool_name || payload?.toolName || '';
60
+ if (!WATCHED_TOOLS.has(toolName)) {
61
+ process.exit(0);
62
+ }
63
+
64
+ const toolInput = payload?.tool_input ?? payload?.toolInput ?? {};
65
+ const backendType = (toolInput?.backend_type || '').toString().trim();
66
+
67
+ // onboard_project defaults to "freeform" when backend_type is empty AND
68
+ // trello_board_name is empty. Mirror that so the hook covers the implicit
69
+ // default case too.
70
+ const trelloBoardName = (toolInput?.trello_board_name || '').toString().trim();
71
+ const effectiveBackend = backendType
72
+ || (toolName === 'mcp__SpecBox-MCP__onboard_project' && !trelloBoardName ? 'freeform' : '');
73
+
74
+ if (effectiveBackend !== 'freeform') {
75
+ process.exit(0);
76
+ }
77
+
78
+ const argName = ROOT_ARG_BY_TOOL[toolName];
79
+ const rawRoot = (toolInput?.[argName] || '').toString().trim();
80
+
81
+ // UC-3801: with a REMOTE MCP the server must never receive a directory at all
82
+ // — it rejects any root_path (FREEFORM_REMOTE_DISK_MODE_REJECTED) because that
83
+ // path lives on this machine, not on the server. The session is opened without
84
+ // root_path (content-only) and the board travels as `items_content` in each
85
+ // call. Only set_auth_token is affected: onboard_project keeps the absolute
86
+ // path because it describes the CLIENT project.
87
+ // UC-11101: remote is read from how Claude Code reaches SpecBox-MCP (http entry or
88
+ // mcp-remote bridge), not only from the env var that the VSCode extension writes.
89
+ const remote = isRemoteMcp({ cwd: payload?.cwd || process.cwd() });
90
+ if (toolName === 'mcp__SpecBox-MCP__set_auth_token' && remote) {
91
+ const { [argName]: droppedRoot, ...updatedInput } = toolInput;
92
+ try {
93
+ appendLine(LOG_PATH, JSON.stringify({
94
+ ts: now(),
95
+ tool: toolName,
96
+ arg: argName,
97
+ from: droppedRoot || DEFAULT_ROOT,
98
+ to: null,
99
+ is_remote_mcp: true,
100
+ reason: 'remote_content_only',
101
+ }));
102
+ } catch {
103
+ // Logging failures must never block the user.
104
+ }
105
+ process.stdout.write(JSON.stringify({
106
+ hookSpecificOutput: {
107
+ hookEventName: 'PreToolUse',
108
+ permissionDecision: 'allow',
109
+ updatedInput,
110
+ },
111
+ }));
112
+ process.exit(0);
113
+ }
114
+
115
+ // If no value provided, fall back to the canonical default before resolving.
116
+ // This covers set_auth_token() with no root_path: server default is the
117
+ // relative string "doc/tracking", which would hit the same bug.
118
+ const effectiveRoot = rawRoot || DEFAULT_ROOT;
119
+
120
+ if (isAbsolute(effectiveRoot)) {
121
+ // Nothing to do — already safe.
122
+ process.exit(0);
123
+ }
124
+
125
+ // Relative path. Try to resolve from git toplevel.
126
+ let absolute;
127
+ try {
128
+ absolute = resolveFreeformPath(effectiveRoot);
129
+ } catch (err) {
130
+ // Cannot determine repo root. Block with an actionable message.
131
+ console.error(
132
+ '[freeform-path-guard] BLOCKED — FreeForm backend received a relative '
133
+ + `root path (${JSON.stringify(effectiveRoot)}) and the hook could not `
134
+ + 'resolve it: ' + err.message + ' '
135
+ + 'Pass an absolute path explicitly, or invoke this tool from inside a '
136
+ + 'git repository so the hook can compute the project root for you.'
137
+ );
138
+ process.exit(2);
139
+ }
140
+
141
+ // Successful rewrite. Log and return updatedInput.
142
+ try {
143
+ appendLine(LOG_PATH, JSON.stringify({
144
+ ts: now(),
145
+ tool: toolName,
146
+ arg: argName,
147
+ from: effectiveRoot,
148
+ to: absolute,
149
+ is_remote_mcp: remote,
150
+ reason: rawRoot ? 'relative_path' : 'unspecified_default',
151
+ }));
152
+ } catch {
153
+ // Logging failures must never block the user.
154
+ }
155
+
156
+ const updatedInput = { ...toolInput, [argName]: absolute };
157
+
158
+ // When set_auth_token is called without backend_type, the server defaults
159
+ // to "trello", so we only stamp backend_type when the caller explicitly
160
+ // said "freeform" or the onboard_project implicit-freeform path applied.
161
+ if (!toolInput?.backend_type && toolName === 'mcp__SpecBox-MCP__onboard_project') {
162
+ updatedInput.backend_type = 'freeform';
163
+ }
164
+
165
+ process.stdout.write(JSON.stringify({
166
+ hookSpecificOutput: {
167
+ hookEventName: 'PreToolUse',
168
+ permissionDecision: 'allow',
169
+ updatedInput,
170
+ },
171
+ }));
172
+ process.exit(0);
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * healing-budget-guard.mjs — PreToolUse hook for Write/Edit during /implement healing
4
+ * BLOCKING (exit 2; US-93/UC-9302 — it exited 1 and read the path from the wrong place, so it
5
+ * never blocked): prevents the agent from exceeding the healing budget (max 8 attempts per feature).
6
+ *
7
+ * The healing budget is defined in GLOBAL_RULES.md as a HARD limit.
8
+ * Previously this was instructional-only — the LLM had to count and stop.
9
+ * Now this hook enforces it mechanically.
10
+ *
11
+ * v5.19.0 — Mechanical Enforcement
12
+ */
13
+
14
+ import { readHookInput, fileExists, readJsonFile } from './lib/utils.mjs';
15
+ import { blockWith } from './lib/output.mjs';
16
+ import { getActiveUC } from './lib/config.mjs';
17
+ import { readFileSync } from 'fs';
18
+
19
+ const MAX_HEALING_ATTEMPTS = 8;
20
+
21
+ // Claude Code sends the path in tool_input (US-93/UC-9302: it was read from the top level).
22
+ const filePath = String(readHookInput().toolInput.file_path || '');
23
+
24
+ if (!filePath) {
25
+ process.exit(0);
26
+ }
27
+
28
+ // Only check source files (same pattern as spec-guard)
29
+ if (!/(^|\/)(?:src|lib)\//.test(filePath)) {
30
+ process.exit(0);
31
+ }
32
+
33
+ // Skip tests, config, generated
34
+ if (/(test\/|tests\/|\.test\.|\.spec\.|_test\.dart|\.g\.dart|\.freezed\.dart|\.config\.|\.json$|\.yaml$|\.md$)/.test(filePath)) {
35
+ process.exit(0);
36
+ }
37
+
38
+ // Get active UC to find feature name
39
+ const activeUC = getActiveUC();
40
+ if (!activeUC || !activeUC.feature) {
41
+ // No active UC → other hooks handle this, not our concern
42
+ process.exit(0);
43
+ }
44
+
45
+ const feature = activeUC.feature;
46
+ const healingLog = `.quality/evidence/${feature}/healing.jsonl`;
47
+
48
+ if (!fileExists(healingLog)) {
49
+ // No healing events yet → allow
50
+ process.exit(0);
51
+ }
52
+
53
+ // Count healing events
54
+ let healingCount = 0;
55
+ try {
56
+ const content = readFileSync(healingLog, 'utf-8');
57
+ const lines = content.trim().split('\n').filter(l => l.trim());
58
+ healingCount = lines.length;
59
+ } catch {
60
+ process.exit(0);
61
+ }
62
+
63
+ if (healingCount >= MAX_HEALING_ATTEMPTS) {
64
+ blockWith('HEALING BUDGET EXCEEDED — Implementation BLOCKED', [
65
+ `Feature: ${feature}`,
66
+ `Healing attempts: ${healingCount} / ${MAX_HEALING_ATTEMPTS}`,
67
+ `Log: ${healingLog}`,
68
+ '',
69
+ 'The healing budget (max 8 attempts) has been exhausted.',
70
+ 'Continuing to retry will waste tokens without progress.',
71
+ '',
72
+ 'REQUIRED ACTIONS:',
73
+ ' 1. STOP implementation immediately',
74
+ ' 2. Generate a healing report with the issues found',
75
+ ' 3. Report to the user: "Healing budget exceeded"',
76
+ ' 4. Let the user decide: manual fix, reset, or escalate',
77
+ '',
78
+ 'This limit is NON-NEGOTIABLE. See GLOBAL_RULES.md.',
79
+ ]);
80
+ }
81
+
82
+ // Allow — budget not yet exhausted
83
+ process.exit(0);