specbox 6.29.1 → 6.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/bin/specbox.mjs +38 -2
- package/hooks/app-docs-sync-guard.mjs +326 -0
- package/hooks/branch-guard.mjs +79 -0
- package/hooks/checkpoint-freshness-guard.mjs +56 -0
- package/hooks/commit-spec-guard.mjs +61 -0
- package/hooks/context-budget-guard.mjs +130 -0
- package/hooks/design-gate.mjs +144 -0
- package/hooks/design-review-gate.mjs +102 -0
- package/hooks/design-system-gate.mjs +134 -0
- package/hooks/e2e-gate.mjs +86 -0
- package/hooks/file-ownership-guard.mjs +163 -0
- package/hooks/freeform-fragment.mjs +160 -0
- package/hooks/freeform-path-guard.mjs +172 -0
- package/hooks/healing-budget-guard.mjs +83 -0
- package/hooks/hooks-history.json +176 -0
- package/hooks/hooks-manifest.json +51 -0
- package/hooks/implement-checkpoint.mjs +46 -0
- package/hooks/implement-healing.mjs +38 -0
- package/hooks/lib/autopilot.mjs +240 -0
- package/hooks/lib/config.mjs +117 -0
- package/hooks/lib/decisiones.mjs +58 -0
- package/hooks/lib/design-gaps.mjs +272 -0
- package/hooks/lib/execution-context.mjs +69 -0
- package/hooks/lib/freeform-fragment.mjs +379 -0
- package/hooks/lib/freeform-path.mjs +115 -0
- package/hooks/lib/handoff-builder.mjs +388 -0
- package/hooks/lib/heartbeat-send.mjs +91 -0
- package/hooks/lib/heartbeat.mjs +110 -0
- package/hooks/lib/mcp-client-io.mjs +210 -0
- package/hooks/lib/mcp-client.mjs +91 -0
- package/hooks/lib/native-reservation-revalidate.mjs +80 -0
- package/hooks/lib/output.mjs +70 -0
- package/hooks/lib/ownership-map.mjs +162 -0
- package/hooks/lib/token-counter.mjs +81 -0
- package/hooks/lib/utils.mjs +235 -0
- package/hooks/no-bypass-guard.mjs +57 -0
- package/hooks/on-session-end.mjs +163 -0
- package/hooks/pipeline-phase-guard.mjs +140 -0
- package/hooks/post-implement-validate.mjs +61 -0
- package/hooks/pre-commit-lint.mjs +76 -0
- package/hooks/pre-prd-discovery-check.mjs +242 -0
- package/hooks/pre-read-budget-guard.mjs +83 -0
- package/hooks/quality-first-guard.mjs +85 -0
- package/hooks/read-tracker.mjs +33 -0
- package/hooks/session-heartbeat.mjs +113 -0
- package/hooks/session-start.mjs +159 -0
- package/hooks/settings-hooks.json +363 -0
- package/hooks/spec-guard.mjs +152 -0
- package/hooks/stripe-safety-guard.mjs +262 -0
- package/hooks/uc-lifecycle-guard.mjs +87 -0
- package/lib/hooks.mjs +156 -0
- package/lib/install.mjs +9 -0
- package/lib/internal.mjs +26 -3
- package/lib/mcp-headers.mjs +31 -3
- package/lib/messages.mjs +41 -0
- package/package.json +5 -3
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/mcp-client-io.mjs — Client-side filesystem I/O for content-passing MCP tools (v6.0.1).
|
|
3
|
+
*
|
|
4
|
+
* The v6.0.1 "MCP Path Contract" makes the MCP server filesystem-agnostic:
|
|
5
|
+
* every tool that used to read or write client files now receives the
|
|
6
|
+
* content as a string parameter and returns content to be written. The
|
|
7
|
+
* client (skill or hook) is responsible for the actual filesystem I/O,
|
|
8
|
+
* resolved against the local repo so it works identically whether the
|
|
9
|
+
* MCP runs as stdio (local) or HTTP/SSE (remote VPS, claude.ai web, ...).
|
|
10
|
+
*
|
|
11
|
+
* This module exposes three helpers used by skills:
|
|
12
|
+
*
|
|
13
|
+
* resolveProjectRoot() → absolute path to the git toplevel of the CWD.
|
|
14
|
+
* readContentBundle(paths) → { "<relative>": string | null } map.
|
|
15
|
+
* writeContentBundle(bundle) → writes everything, returns { written, skipped }.
|
|
16
|
+
*
|
|
17
|
+
* All paths in bundles are RELATIVE to the project root so payloads sent to
|
|
18
|
+
* MCP tools are independent of the caller's absolute filesystem layout.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { execSync } from 'node:child_process';
|
|
22
|
+
import {
|
|
23
|
+
existsSync,
|
|
24
|
+
mkdirSync,
|
|
25
|
+
readFileSync,
|
|
26
|
+
writeFileSync,
|
|
27
|
+
} from 'node:fs';
|
|
28
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Locate the git toplevel of the caller's CWD. Used as the canonical
|
|
32
|
+
* "project root" against which all relative bundle paths are resolved.
|
|
33
|
+
*
|
|
34
|
+
* @param {object} [opts]
|
|
35
|
+
* @param {string} [opts.cwd] - Override CWD (default: process.cwd()).
|
|
36
|
+
* @returns {string} Absolute path to the project root.
|
|
37
|
+
* @throws {Error} When the CWD is not inside a git repository.
|
|
38
|
+
*/
|
|
39
|
+
export function resolveProjectRoot(opts = {}) {
|
|
40
|
+
const cwd = opts.cwd || process.cwd();
|
|
41
|
+
let toplevel;
|
|
42
|
+
try {
|
|
43
|
+
toplevel = execSync('git rev-parse --show-toplevel', {
|
|
44
|
+
cwd,
|
|
45
|
+
encoding: 'utf-8',
|
|
46
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
47
|
+
}).trim();
|
|
48
|
+
} catch {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`resolveProjectRoot: ${cwd} is not inside a git repository. `
|
|
51
|
+
+ 'mcp-client-io requires a git repo to anchor relative paths.'
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
if (!toplevel) {
|
|
55
|
+
throw new Error('resolveProjectRoot: git rev-parse returned empty output');
|
|
56
|
+
}
|
|
57
|
+
return toplevel;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Read a list of files relative to the project root and return a bundle
|
|
62
|
+
* suitable for passing as `*_content` parameters to MCP tools.
|
|
63
|
+
*
|
|
64
|
+
* - Files that exist → bundle[relpath] = file content (UTF-8 string).
|
|
65
|
+
* - Files that do not exist → bundle[relpath] = null.
|
|
66
|
+
* - Absolute paths are rejected — bundles must be relative to project root.
|
|
67
|
+
*
|
|
68
|
+
* @param {string[]} relativePaths
|
|
69
|
+
* @param {object} [opts]
|
|
70
|
+
* @param {string} [opts.root] - Override project root (default: resolveProjectRoot()).
|
|
71
|
+
* @returns {Record<string, string | null>}
|
|
72
|
+
*/
|
|
73
|
+
export function readContentBundle(relativePaths, opts = {}) {
|
|
74
|
+
if (!Array.isArray(relativePaths)) {
|
|
75
|
+
throw new TypeError('readContentBundle: paths must be an array');
|
|
76
|
+
}
|
|
77
|
+
const root = opts.root || resolveProjectRoot(opts);
|
|
78
|
+
const bundle = {};
|
|
79
|
+
for (const rel of relativePaths) {
|
|
80
|
+
if (typeof rel !== 'string' || rel.length === 0) {
|
|
81
|
+
throw new TypeError(
|
|
82
|
+
`readContentBundle: each path must be a non-empty string (got ${JSON.stringify(rel)})`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
if (isAbsolute(rel)) {
|
|
86
|
+
throw new Error(
|
|
87
|
+
`readContentBundle: refusing to read absolute path ${JSON.stringify(rel)}. `
|
|
88
|
+
+ 'Pass paths relative to the project root.'
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
// Prevent path traversal outside root.
|
|
92
|
+
const abs = resolve(root, rel);
|
|
93
|
+
if (!abs.startsWith(root + '/') && abs !== root) {
|
|
94
|
+
throw new Error(
|
|
95
|
+
`readContentBundle: path ${JSON.stringify(rel)} escapes the project root.`
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
if (!existsSync(abs)) {
|
|
99
|
+
bundle[rel] = null;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
bundle[rel] = readFileSync(abs, { encoding: 'utf-8' });
|
|
103
|
+
}
|
|
104
|
+
return bundle;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Write a bundle of relative-path → content entries under the project root.
|
|
109
|
+
* Each non-null value is written (creating parent directories as needed).
|
|
110
|
+
* Null/undefined values are skipped (caller can pass a single dict mixing
|
|
111
|
+
* "files I want written" and "files I read but won't touch").
|
|
112
|
+
*
|
|
113
|
+
* @param {Record<string, string | null | undefined>} bundle
|
|
114
|
+
* @param {object} [opts]
|
|
115
|
+
* @param {string} [opts.root] - Override project root.
|
|
116
|
+
* @returns {{ written: string[], skipped: string[] }}
|
|
117
|
+
*/
|
|
118
|
+
export function writeContentBundle(bundle, opts = {}) {
|
|
119
|
+
if (bundle === null || typeof bundle !== 'object') {
|
|
120
|
+
throw new TypeError('writeContentBundle: bundle must be an object');
|
|
121
|
+
}
|
|
122
|
+
const root = opts.root || resolveProjectRoot(opts);
|
|
123
|
+
const written = [];
|
|
124
|
+
const skipped = [];
|
|
125
|
+
for (const [rel, content] of Object.entries(bundle)) {
|
|
126
|
+
if (typeof rel !== 'string' || rel.length === 0) {
|
|
127
|
+
throw new TypeError(
|
|
128
|
+
`writeContentBundle: each key must be a non-empty string (got ${JSON.stringify(rel)})`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
if (isAbsolute(rel)) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
`writeContentBundle: refusing to write absolute path ${JSON.stringify(rel)}. `
|
|
134
|
+
+ 'Bundle keys must be relative to the project root.'
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
if (content === null || content === undefined) {
|
|
138
|
+
skipped.push(rel);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (typeof content !== 'string') {
|
|
142
|
+
throw new TypeError(
|
|
143
|
+
`writeContentBundle: value for ${JSON.stringify(rel)} must be a string or null (got ${typeof content})`
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
const abs = resolve(root, rel);
|
|
147
|
+
if (!abs.startsWith(root + '/') && abs !== root) {
|
|
148
|
+
throw new Error(
|
|
149
|
+
`writeContentBundle: path ${JSON.stringify(rel)} escapes the project root.`
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
mkdirSync(dirname(abs), { recursive: true });
|
|
153
|
+
writeFileSync(abs, content, { encoding: 'utf-8' });
|
|
154
|
+
written.push(rel);
|
|
155
|
+
}
|
|
156
|
+
return { written, skipped };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ── FreeForm tracking helpers (UC-661) ───────────────────────────────
|
|
160
|
+
//
|
|
161
|
+
// The FreeForm backend's source of truth is doc/tracking/items.json. With a
|
|
162
|
+
// remote MCP server (SPECBOX_ENGINE_MCP_URL set) the server cannot read or
|
|
163
|
+
// write this file — UC-660 made the mutation tools content-passing, so the
|
|
164
|
+
// client reads items.json, sends its content, and writes back the mutated
|
|
165
|
+
// string the tool returns. These two helpers are the single client-side door
|
|
166
|
+
// for that round-trip: skills never compute the path themselves.
|
|
167
|
+
|
|
168
|
+
/** Canonical relative path to the FreeForm source-of-truth file. */
|
|
169
|
+
export const TRACKING_ITEMS_PATH = 'doc/tracking/items.json';
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Read the FreeForm tracking items.json as a string, ready to pass as the
|
|
173
|
+
* `items_content` parameter of a content-passing mutation tool (UC-660).
|
|
174
|
+
*
|
|
175
|
+
* Resolves the repo root via `git rev-parse --show-toplevel` (inherited from
|
|
176
|
+
* readContentBundle) and honours the path-traversal guard. A board that has
|
|
177
|
+
* never been initialised (no items.json yet) reads as "[]" so the first
|
|
178
|
+
* import_spec / add_uc starts from an empty board instead of crashing.
|
|
179
|
+
*
|
|
180
|
+
* @param {object} [opts]
|
|
181
|
+
* @param {string} [opts.root] - Override project root (default: git toplevel of CWD).
|
|
182
|
+
* @returns {string} The items.json content, or "[]" when the file is absent.
|
|
183
|
+
*/
|
|
184
|
+
export function readTrackingBundle(opts = {}) {
|
|
185
|
+
const bundle = readContentBundle([TRACKING_ITEMS_PATH], opts);
|
|
186
|
+
const content = bundle[TRACKING_ITEMS_PATH];
|
|
187
|
+
return content === null ? '[]' : content;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Write the mutated items.json string back to the FreeForm tracking file.
|
|
192
|
+
*
|
|
193
|
+
* Call this with the `items_content` a content-passing mutation tool returned.
|
|
194
|
+
* Same root resolution + traversal guard as writeContentBundle. The readable
|
|
195
|
+
* layer (progress/, us/, uc/) is regenerated separately by the skill — this
|
|
196
|
+
* helper only persists the source of truth.
|
|
197
|
+
*
|
|
198
|
+
* @param {string} itemsContent - The mutated items.json string.
|
|
199
|
+
* @param {object} [opts]
|
|
200
|
+
* @param {string} [opts.root] - Override project root.
|
|
201
|
+
* @returns {{ written: string[], skipped: string[] }}
|
|
202
|
+
*/
|
|
203
|
+
export function writeTrackingBundle(itemsContent, opts = {}) {
|
|
204
|
+
if (typeof itemsContent !== 'string') {
|
|
205
|
+
throw new TypeError(
|
|
206
|
+
`writeTrackingBundle: itemsContent must be a string (got ${typeof itemsContent})`
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
return writeContentBundle({ [TRACKING_ITEMS_PATH]: itemsContent }, opts);
|
|
210
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/mcp-client.mjs — cliente MCP mínimo para los hooks (US-99 · UC-9901).
|
|
3
|
+
*
|
|
4
|
+
* Los hooks no tenían cómo hablar con el servidor MCP. Este cliente hace lo justo por HTTP
|
|
5
|
+
* («Streamable HTTP»): `initialize`, `notifications/initialized` y un `tools/call`, con un tope de
|
|
6
|
+
* tiempo para todo. Acepta respuestas JSON o en `text/event-stream`. Sin dependencias.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const PROTOCOLO = '2025-06-18';
|
|
10
|
+
|
|
11
|
+
/** El mensaje JSON-RPC con ese `id` dentro de una respuesta JSON o SSE. */
|
|
12
|
+
export function mensajeDe(texto, tipo, id) {
|
|
13
|
+
if ((tipo || '').includes('text/event-stream')) {
|
|
14
|
+
for (const linea of String(texto).split('\n')) {
|
|
15
|
+
if (!linea.startsWith('data:')) continue;
|
|
16
|
+
try {
|
|
17
|
+
const m = JSON.parse(linea.slice(5).trim());
|
|
18
|
+
if (m && m.id === id) return m;
|
|
19
|
+
} catch {
|
|
20
|
+
// una línea que no es JSON: se ignora
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(texto);
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function enviar(fetchImpl, url, cabeceras, cuerpo, sesion, signal) {
|
|
33
|
+
const h = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...cabeceras };
|
|
34
|
+
if (sesion) h['mcp-session-id'] = sesion;
|
|
35
|
+
const res = await fetchImpl(url, { method: 'POST', headers: h, body: JSON.stringify(cuerpo), signal });
|
|
36
|
+
const texto = res.status === 202 || res.status === 204 ? '' : await res.text();
|
|
37
|
+
return {
|
|
38
|
+
estado: res.status,
|
|
39
|
+
sesion: res.headers.get('mcp-session-id') || sesion,
|
|
40
|
+
mensaje: cuerpo.id === undefined ? null : mensajeDe(texto, res.headers.get('content-type'), cuerpo.id),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Llama a la tool `nombre` con `args` y devuelve su resultado (el JSON que devuelve la tool).
|
|
46
|
+
* Lanza un Error corto (sin cabeceras ni token) si algo falla o pasa de `topeMs`.
|
|
47
|
+
*/
|
|
48
|
+
export async function llamarTool({ url, cabeceras = {}, nombre, args = {}, topeMs = 3000, fetchImpl = fetch }) {
|
|
49
|
+
const control = new AbortController();
|
|
50
|
+
const reloj = setTimeout(() => control.abort(), topeMs);
|
|
51
|
+
try {
|
|
52
|
+
const ini = await enviar(
|
|
53
|
+
fetchImpl,
|
|
54
|
+
url,
|
|
55
|
+
cabeceras,
|
|
56
|
+
{
|
|
57
|
+
jsonrpc: '2.0',
|
|
58
|
+
id: 1,
|
|
59
|
+
method: 'initialize',
|
|
60
|
+
params: { protocolVersion: PROTOCOLO, capabilities: {}, clientInfo: { name: 'specbox-heartbeat', version: '1' } },
|
|
61
|
+
},
|
|
62
|
+
null,
|
|
63
|
+
control.signal,
|
|
64
|
+
);
|
|
65
|
+
if (ini.estado >= 400 || !ini.mensaje?.result) throw new Error(`initialize ${ini.estado}`);
|
|
66
|
+
await enviar(fetchImpl, url, cabeceras, { jsonrpc: '2.0', method: 'notifications/initialized' }, ini.sesion, control.signal);
|
|
67
|
+
const r = await enviar(
|
|
68
|
+
fetchImpl,
|
|
69
|
+
url,
|
|
70
|
+
cabeceras,
|
|
71
|
+
{ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: nombre, arguments: args } },
|
|
72
|
+
ini.sesion,
|
|
73
|
+
control.signal,
|
|
74
|
+
);
|
|
75
|
+
if (r.estado >= 400 || !r.mensaje) throw new Error(`tools/call ${r.estado}`);
|
|
76
|
+
if (r.mensaje.error) throw new Error(`tools/call ${r.mensaje.error.code ?? 'error'}`);
|
|
77
|
+
const resultado = r.mensaje.result || {};
|
|
78
|
+
if (resultado.structuredContent) return resultado.structuredContent;
|
|
79
|
+
const texto = resultado.content?.find?.((c) => c.type === 'text')?.text;
|
|
80
|
+
try {
|
|
81
|
+
return texto ? JSON.parse(texto) : {};
|
|
82
|
+
} catch {
|
|
83
|
+
return { text: texto };
|
|
84
|
+
}
|
|
85
|
+
} catch (err) {
|
|
86
|
+
if (err?.name === 'AbortError') throw new Error(`tope de ${topeMs} ms`);
|
|
87
|
+
throw err instanceof Error ? new Error(err.message.slice(0, 120)) : new Error('fallo');
|
|
88
|
+
} finally {
|
|
89
|
+
clearTimeout(reloj);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* native-reservation-revalidate.mjs — pure decision logic for spec-guard's
|
|
3
|
+
* native reservation revalidation (UC-304 / AC-21 / AC-22, renamed in
|
|
4
|
+
* UC-613 from native-claim-revalidate.mjs).
|
|
5
|
+
*
|
|
6
|
+
* spec-guard.mjs treats `.quality/active_uc.json` as a CACHE of the remote
|
|
7
|
+
* reservation. The policy:
|
|
8
|
+
*
|
|
9
|
+
* - Offline (no MCP URL, or the revalidation call failed/timed out) →
|
|
10
|
+
* trust the cache and ALLOW. The cached reservation is the dev's
|
|
11
|
+
* last-known-good state [AC-21].
|
|
12
|
+
* - Online and the MCP says the reservation is still the dev's → ALLOW.
|
|
13
|
+
* - Online and the MCP says the reservation is gone or now belongs to
|
|
14
|
+
* someone else → BLOCK with a message naming the conflict [AC-22].
|
|
15
|
+
*
|
|
16
|
+
* This module is pure (no I/O) so it is unit-testable. The hook performs
|
|
17
|
+
* the actual network probe and feeds the result here.
|
|
18
|
+
*
|
|
19
|
+
* Wire-protocol compat (v5.35-v5.36)
|
|
20
|
+
* ----------------------------------
|
|
21
|
+
* The revalidation argument accepts BOTH the new shape
|
|
22
|
+
* `{ reachable, reservation: {…} | null }` and the legacy shape
|
|
23
|
+
* `{ reachable, claim: {…} | null }`. The legacy field is honoured as a
|
|
24
|
+
* fallback so the hook continues to work against an MCP that has not yet
|
|
25
|
+
* upgraded to the renamed endpoint. UC-612 removes the legacy fallback
|
|
26
|
+
* in v5.37.0.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {object|null} reservation The cached reservation:
|
|
31
|
+
* { ucId, developerId, reservedAt? }.
|
|
32
|
+
* @param {object} revalidation The probe result:
|
|
33
|
+
* { reachable: boolean,
|
|
34
|
+
* reservation?: { developer_id } | null,
|
|
35
|
+
* claim?: { developer_id } | null } // legacy fallback (UC-612)
|
|
36
|
+
* - reachable=false → could not reach the MCP (offline / error / timeout).
|
|
37
|
+
* - reachable=true, reservation=null → the UC has no active reservation
|
|
38
|
+
* anymore.
|
|
39
|
+
* - reachable=true, reservation={developer_id} → the current remote owner.
|
|
40
|
+
* @returns {{ allow: boolean, reason: string, conflict?: object }}
|
|
41
|
+
*/
|
|
42
|
+
export function decideNativeReservation(reservation, revalidation) {
|
|
43
|
+
// No native reservation cached → this policy does not apply; let the
|
|
44
|
+
// caller's normal freshness logic decide.
|
|
45
|
+
if (!reservation) {
|
|
46
|
+
return { allow: true, reason: 'no-native-reservation' };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Offline / unreachable → trust the cache [AC-21].
|
|
50
|
+
if (!revalidation || revalidation.reachable !== true) {
|
|
51
|
+
return { allow: true, reason: 'offline-cache-trusted' };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Accept new field `reservation`; fall back to legacy `claim` for
|
|
55
|
+
// compat with an MCP that has not yet upgraded. Removed in v5.37.0
|
|
56
|
+
// by UC-612.
|
|
57
|
+
const remote =
|
|
58
|
+
revalidation.reservation !== undefined ? revalidation.reservation : revalidation.claim;
|
|
59
|
+
|
|
60
|
+
// Reservation vanished remotely (released or expired) → block [AC-22].
|
|
61
|
+
if (!remote || !remote.developer_id) {
|
|
62
|
+
return {
|
|
63
|
+
allow: false,
|
|
64
|
+
reason: 'reservation-released',
|
|
65
|
+
conflict: { expected: reservation.developerId, actual: null },
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Reservation now belongs to someone else → block [AC-22].
|
|
70
|
+
if (remote.developer_id !== reservation.developerId) {
|
|
71
|
+
return {
|
|
72
|
+
allow: false,
|
|
73
|
+
reason: 'reservation-taken-over',
|
|
74
|
+
conflict: { expected: reservation.developerId, actual: remote.developer_id },
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Still the dev's reservation → allow.
|
|
79
|
+
return { allow: true, reason: 'reservation-confirmed' };
|
|
80
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/output.mjs — Formatted output for SpecBox Engine hooks
|
|
3
|
+
* Matches the exact output format of the original bash hooks.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Print a formatted block with ===== borders.
|
|
8
|
+
* Uses stderr for error messages (blocking hooks).
|
|
9
|
+
*
|
|
10
|
+
* @param {string} title - Block title
|
|
11
|
+
* @param {string[]} lines - Lines to print inside the block
|
|
12
|
+
* @param {object} [opts]
|
|
13
|
+
* @param {boolean} [opts.useStderr=false] - Print to stderr instead of stdout
|
|
14
|
+
*/
|
|
15
|
+
export function printBlock(title, lines, opts = {}) {
|
|
16
|
+
const { useStderr = false } = opts;
|
|
17
|
+
const out = useStderr ? process.stderr : process.stdout;
|
|
18
|
+
|
|
19
|
+
out.write('\n');
|
|
20
|
+
out.write('============================================================\n');
|
|
21
|
+
out.write(` ${title}\n`);
|
|
22
|
+
out.write('============================================================\n');
|
|
23
|
+
for (const line of lines) {
|
|
24
|
+
out.write(` ${line}\n`);
|
|
25
|
+
}
|
|
26
|
+
out.write('============================================================\n');
|
|
27
|
+
out.write('\n');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Print a warning message (non-blocking).
|
|
32
|
+
*/
|
|
33
|
+
export function printWarning(message) {
|
|
34
|
+
process.stdout.write(`\nWARNING: ${message}\n`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Print an informational message.
|
|
39
|
+
*/
|
|
40
|
+
export function printInfo(message) {
|
|
41
|
+
process.stdout.write(`${message}\n`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ── Canales que llegan al agente (US-93 · UC-9302) ──────────────────────
|
|
45
|
+
//
|
|
46
|
+
// Comprobado en sesiones reales de Claude Code 2.1.288 (doc/research/hooks-que-no-saltaban/):
|
|
47
|
+
// - exit 2 + stderr: en PreToolUse impide la acción y el agente recibe el motivo; en
|
|
48
|
+
// PostToolUse el agente recibe el motivo (la acción ya ocurrió).
|
|
49
|
+
// - exit 0 + JSON con hookSpecificOutput.additionalContext: nota para el agente, sin impedir nada
|
|
50
|
+
// (PreToolUse y PostToolUse).
|
|
51
|
+
// - exit 1, o exit 0 con texto por stdout o stderr: no llega al agente ni bloquea. No usarlos.
|
|
52
|
+
|
|
53
|
+
/** Formatea un bloque con título y líneas. */
|
|
54
|
+
export function formatBlock(title, lines) {
|
|
55
|
+
const bar = '============================================================';
|
|
56
|
+
return [bar, ` ${title}`, bar, ...lines.map((l) => ` ${l}`), bar].join('\n');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Impide la acción (PreToolUse) o le dice al agente que corrija (PostToolUse): stderr + exit 2. */
|
|
60
|
+
export function blockWith(title, lines) {
|
|
61
|
+
process.stderr.write(`\n${formatBlock(title, lines)}\n`);
|
|
62
|
+
process.exit(2);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Nota para el agente, sin impedir la acción: additionalContext + exit 0. */
|
|
66
|
+
export function noteWith(event, title, lines) {
|
|
67
|
+
const text = [title, ...lines].join('\n');
|
|
68
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event || 'PostToolUse', additionalContext: text } }));
|
|
69
|
+
process.exit(0);
|
|
70
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// lib/ownership-map.mjs — parse file-ownership.md → {agent → glob[]} (v5.32.0).
|
|
2
|
+
//
|
|
3
|
+
// The single source of truth for ownership lives in
|
|
4
|
+
// .claude/skills/implement/file-ownership.md as a Markdown table.
|
|
5
|
+
// This parser reads that table without forcing a YAML/JSON copy that
|
|
6
|
+
// would drift. If the table is malformed, returns an empty map and
|
|
7
|
+
// lets the caller fail-open (degradation graceful — never block on
|
|
8
|
+
// a parser bug).
|
|
9
|
+
|
|
10
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
11
|
+
|
|
12
|
+
const DEFAULT_OWNERSHIP_PATH = '.claude/skills/implement/file-ownership.md';
|
|
13
|
+
const AGENT_ID_RE = /\b(AG-\d{2}[a-z]?)\b/;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Parse a Markdown table cell that contains a comma-separated list of
|
|
17
|
+
* globs. Returns the trimmed glob array.
|
|
18
|
+
* @param {string} cell
|
|
19
|
+
* @returns {string[]}
|
|
20
|
+
*/
|
|
21
|
+
export function parseOwnershipCell(cell) {
|
|
22
|
+
if (!cell) return [];
|
|
23
|
+
return cell
|
|
24
|
+
.split(',')
|
|
25
|
+
.map((g) => g.trim())
|
|
26
|
+
.filter((g) => g.length > 0);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Parse file-ownership.md and return a map { "AG-01": ["lib/features/**", ...] }.
|
|
31
|
+
* @param {string} [path]
|
|
32
|
+
* @returns {Record<string, string[]>}
|
|
33
|
+
*/
|
|
34
|
+
export function parseOwnershipMap(path = DEFAULT_OWNERSHIP_PATH) {
|
|
35
|
+
if (!existsSync(path)) return {};
|
|
36
|
+
let body;
|
|
37
|
+
try {
|
|
38
|
+
body = readFileSync(path, 'utf-8');
|
|
39
|
+
} catch {
|
|
40
|
+
return {};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const map = {};
|
|
44
|
+
const lines = body.split('\n');
|
|
45
|
+
for (const line of lines) {
|
|
46
|
+
if (!line.includes('|')) continue;
|
|
47
|
+
if (line.includes('---')) continue; // separator row
|
|
48
|
+
const cells = line
|
|
49
|
+
.split('|')
|
|
50
|
+
.map((c) => c.trim())
|
|
51
|
+
.filter((_, i, arr) => i > 0 && i < arr.length - 1); // strip leading/trailing empties
|
|
52
|
+
if (cells.length < 2) continue;
|
|
53
|
+
const agentMatch = cells[0].match(AGENT_ID_RE);
|
|
54
|
+
if (!agentMatch) continue;
|
|
55
|
+
map[agentMatch[1]] = parseOwnershipCell(cells[cells.length - 1]);
|
|
56
|
+
}
|
|
57
|
+
return map;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Convert one of our supported glob patterns to a RegExp.
|
|
61
|
+
//
|
|
62
|
+
// Supported tokens:
|
|
63
|
+
// /<DBLSTAR>/ → matches any number of path segments (incl. zero)
|
|
64
|
+
// <DBLSTAR> → matches any number of path segments
|
|
65
|
+
// * → matches any chars except '/'
|
|
66
|
+
// ? → matches any single char except '/'
|
|
67
|
+
//
|
|
68
|
+
// (DBLSTAR = literally two asterisks — written this way in the comment
|
|
69
|
+
// to avoid closing JSDoc parsing inside the source.)
|
|
70
|
+
//
|
|
71
|
+
// Also normalises a leading "./".
|
|
72
|
+
export function globToRegExp(pattern) {
|
|
73
|
+
const cleaned = pattern.replace(/^\.\//, '');
|
|
74
|
+
// Token-by-token transformation: walk the string and emit regex
|
|
75
|
+
// pieces. This avoids the trap where a later replacement of "*"
|
|
76
|
+
// accidentally rewrites a "*" that came from an earlier escape.
|
|
77
|
+
let out = '';
|
|
78
|
+
let i = 0;
|
|
79
|
+
while (i < cleaned.length) {
|
|
80
|
+
const c = cleaned[i];
|
|
81
|
+
// /**/ → match any number of segments (including zero) — handle
|
|
82
|
+
// before the bare "**" rule.
|
|
83
|
+
if (cleaned.startsWith('/**/', i)) {
|
|
84
|
+
out += '(?:/.+)?/'; // "/" or "/anything/"
|
|
85
|
+
i += 4;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
// trailing /**
|
|
89
|
+
if (cleaned.startsWith('/**', i) && i + 3 === cleaned.length) {
|
|
90
|
+
out += '(?:/.*)?';
|
|
91
|
+
i += 3;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
// leading **/
|
|
95
|
+
if (i === 0 && cleaned.startsWith('**/', i)) {
|
|
96
|
+
out += '(?:.*/)?';
|
|
97
|
+
i += 3;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
// bare ** anywhere else
|
|
101
|
+
if (cleaned.startsWith('**', i)) {
|
|
102
|
+
out += '.*';
|
|
103
|
+
i += 2;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
// single *
|
|
107
|
+
if (c === '*') {
|
|
108
|
+
out += '[^/]*';
|
|
109
|
+
i += 1;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (c === '?') {
|
|
113
|
+
out += '[^/]';
|
|
114
|
+
i += 1;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
// regex meta → escape
|
|
118
|
+
if ('.+^${}()|[]\\'.includes(c)) {
|
|
119
|
+
out += '\\' + c;
|
|
120
|
+
i += 1;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
out += c;
|
|
124
|
+
i += 1;
|
|
125
|
+
}
|
|
126
|
+
return new RegExp(`^${out}$`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Reject suspicious paths that try to escape the repo (`..`, absolute
|
|
131
|
+
* paths). Hooks should call this BEFORE matching against ownership
|
|
132
|
+
* to fail fast on attempted directory traversal.
|
|
133
|
+
* @param {string} path
|
|
134
|
+
* @returns {boolean}
|
|
135
|
+
*/
|
|
136
|
+
export function isSuspiciousPath(path) {
|
|
137
|
+
if (typeof path !== 'string' || path.length === 0) return true;
|
|
138
|
+
if (path.includes('..')) return true;
|
|
139
|
+
if (path.startsWith('/')) return true; // absolute path
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Check whether a relative repo path is allowed for a given agent.
|
|
145
|
+
*
|
|
146
|
+
* Rules:
|
|
147
|
+
* - Suspicious paths return false (caller should reject).
|
|
148
|
+
* - Unknown agent → returns null (caller should fail-open with warning).
|
|
149
|
+
* - Empty ownership → returns null (same: probably a parsing problem).
|
|
150
|
+
* - Otherwise: true if any glob matches, false otherwise.
|
|
151
|
+
*
|
|
152
|
+
* @param {string} repoRelativePath
|
|
153
|
+
* @param {string} agent
|
|
154
|
+
* @param {Record<string, string[]>} map
|
|
155
|
+
* @returns {boolean | null}
|
|
156
|
+
*/
|
|
157
|
+
export function pathAllowedForAgent(repoRelativePath, agent, map) {
|
|
158
|
+
if (isSuspiciousPath(repoRelativePath)) return false;
|
|
159
|
+
const globs = map?.[agent];
|
|
160
|
+
if (!globs || globs.length === 0) return null;
|
|
161
|
+
return globs.some((g) => globToRegExp(g).test(repoRelativePath));
|
|
162
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/token-counter.mjs — zero-deps token estimator (v5.32.0).
|
|
3
|
+
*
|
|
4
|
+
* The chars/4 heuristic is a well-known approximation for Anthropic
|
|
5
|
+
* tokenisation that holds within ~8% for typical mixed text+code.
|
|
6
|
+
* We use it because:
|
|
7
|
+
* 1. Counting is on the hot path (PreToolUse Task hook) — must be
|
|
8
|
+
* synchronous and fast.
|
|
9
|
+
* 2. Calling Anthropic's count_tokens API would add latency and
|
|
10
|
+
* cost per Task spawn.
|
|
11
|
+
* 3. The guard's purpose is to flag "this prompt is way too big",
|
|
12
|
+
* which doesn't need single-token precision.
|
|
13
|
+
*
|
|
14
|
+
* If telemetry shows the heuristic underestimates dangerously, we
|
|
15
|
+
* can swap it for a tiktoken-style counter in a follow-up patch
|
|
16
|
+
* without changing the call sites.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const CHARS_PER_TOKEN = 4;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Estimate tokens in a single string. Returns at least 1 for any
|
|
23
|
+
* non-empty input.
|
|
24
|
+
* @param {string} text
|
|
25
|
+
* @returns {number}
|
|
26
|
+
*/
|
|
27
|
+
export function estimateTokens(text) {
|
|
28
|
+
if (!text) return 0;
|
|
29
|
+
return Math.max(1, Math.ceil(text.length / CHARS_PER_TOKEN));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Estimate tokens for a structured prompt payload.
|
|
34
|
+
*
|
|
35
|
+
* Accepts the shape that PreToolUse(Task) hooks observe:
|
|
36
|
+
* { tool_input: { description, prompt, ... } }
|
|
37
|
+
* Or, equivalently, raw fields: { prompt, description, system }.
|
|
38
|
+
*
|
|
39
|
+
* Files arrays are included if present (some Task harnesses pass
|
|
40
|
+
* files explicitly), counted by their content.
|
|
41
|
+
*
|
|
42
|
+
* @param {object} payload
|
|
43
|
+
* @returns {{ total: number, breakdown: Record<string, number> }}
|
|
44
|
+
*/
|
|
45
|
+
export function estimatePromptTokens(payload) {
|
|
46
|
+
const breakdown = {};
|
|
47
|
+
let total = 0;
|
|
48
|
+
|
|
49
|
+
// PreToolUse harness shape: payload.tool_input.{description, prompt, ...}
|
|
50
|
+
const fields = payload?.tool_input ?? payload ?? {};
|
|
51
|
+
|
|
52
|
+
if (typeof fields.description === 'string') {
|
|
53
|
+
const t = estimateTokens(fields.description);
|
|
54
|
+
breakdown.description = t;
|
|
55
|
+
total += t;
|
|
56
|
+
}
|
|
57
|
+
if (typeof fields.prompt === 'string') {
|
|
58
|
+
const t = estimateTokens(fields.prompt);
|
|
59
|
+
breakdown.prompt = t;
|
|
60
|
+
total += t;
|
|
61
|
+
}
|
|
62
|
+
if (typeof fields.system === 'string') {
|
|
63
|
+
const t = estimateTokens(fields.system);
|
|
64
|
+
breakdown.system = t;
|
|
65
|
+
total += t;
|
|
66
|
+
}
|
|
67
|
+
if (Array.isArray(fields.files)) {
|
|
68
|
+
let filesTotal = 0;
|
|
69
|
+
for (const f of fields.files) {
|
|
70
|
+
if (typeof f?.content === 'string') {
|
|
71
|
+
filesTotal += estimateTokens(f.content);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (filesTotal > 0) {
|
|
75
|
+
breakdown.files = filesTotal;
|
|
76
|
+
total += filesTotal;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return { total, breakdown };
|
|
81
|
+
}
|