@mcpbox/mcpbox-claude 0.1.27 → 0.1.29

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 (54) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/.codex-plugin/plugin.json +4 -4
  3. package/README.md +280 -20
  4. package/bin/mcpbox-claude.mjs +61 -11
  5. package/commands/close.md +2 -0
  6. package/commands/mine.md +4 -4
  7. package/commands/mode.md +4 -12
  8. package/commands/next.md +4 -3
  9. package/commands/pipeline-run.md +4 -4
  10. package/commands/plan.md +4 -4
  11. package/commands/sync.md +1 -1
  12. package/commands/tasks.md +4 -4
  13. package/hooks/acceptance-guard.mjs +5 -62
  14. package/hooks/bootstrap.mjs +167 -0
  15. package/hooks/edit-gate.mjs +7 -0
  16. package/hooks/hooks.json +37 -1
  17. package/hooks/impl/acceptance-guard.mjs +63 -0
  18. package/hooks/impl/edit-gate.mjs +32 -0
  19. package/hooks/impl/prepare-commit-msg.mjs +8 -0
  20. package/hooks/impl/session-gate.mjs +81 -0
  21. package/hooks/impl/session-start.mjs +89 -0
  22. package/hooks/impl/stop.mjs +64 -0
  23. package/hooks/impl/track-claims.mjs +35 -0
  24. package/hooks/impl/user-prompt-submit.mjs +234 -0
  25. package/hooks/prepare-commit-msg.mjs +7 -0
  26. package/hooks/session-gate.mjs +7 -0
  27. package/hooks/session-start.mjs +5 -204
  28. package/hooks/stop.mjs +5 -104
  29. package/hooks/track-claims.mjs +7 -0
  30. package/hooks/user-prompt-submit.mjs +5 -259
  31. package/lib/cloud-knowledge.mjs +19 -3
  32. package/lib/codex.mjs +2 -2
  33. package/lib/cursor.mjs +1 -1
  34. package/lib/edit-gate.mjs +120 -0
  35. package/lib/git-trailer.mjs +104 -0
  36. package/lib/harness-hooks.mjs +186 -0
  37. package/lib/hook-doctor.mjs +517 -0
  38. package/lib/hook-output.mjs +16 -0
  39. package/lib/kimi.mjs +16 -4
  40. package/lib/knowledge-skills.mjs +259 -0
  41. package/lib/mode.mjs +2 -12
  42. package/lib/policy.mjs +54 -127
  43. package/lib/session-gate.mjs +385 -0
  44. package/lib/version.mjs +1 -1
  45. package/package.json +2 -2
  46. package/skills/mcpbox/SKILL.md +17 -94
  47. package/skills/mcpbox-close/SKILL.md +2 -0
  48. package/skills/mcpbox-mine/SKILL.md +4 -4
  49. package/skills/mcpbox-mode/SKILL.md +4 -12
  50. package/skills/mcpbox-next/SKILL.md +4 -3
  51. package/skills/mcpbox-pipeline-run/SKILL.md +4 -4
  52. package/skills/mcpbox-plan/SKILL.md +4 -4
  53. package/skills/mcpbox-sync/SKILL.md +1 -1
  54. package/skills/mcpbox-tasks/SKILL.md +4 -4
package/commands/mode.md CHANGED
@@ -1,30 +1,22 @@
1
1
  ---
2
- description: Set how strictly raw ideas route through the mcpbox maturity pipeline (off | lite | full).
2
+ description: Set MCPBox prompt hints (off | lite | full).
3
3
  ---
4
4
 
5
5
  The user invoked `/mcpbox:mode` with `$ARGUMENTS` = `off` | `lite` | `full` (empty → show current).
6
6
 
7
7
  ## What each level does
8
8
 
9
- Mode sets how eagerly to suggest `mcpbox_pipeline_run`: `off` never, `lite` only when asked, `full` for any substantive request.
9
+ Mode sets how eagerly to suggest `mcpbox_pipeline_run`: `off` hides pipeline hints, `lite` matches explicit intents, `full` also reminds you to skip tracking operational work.
10
10
 
11
11
  - **off** — no pipeline nudging; don't raise the pipeline on your own.
12
12
  - **lite** (default) — nudge toward the pipeline only when the input explicitly mentions it
13
13
  (pipeline / maturity / handoff / конвейер …).
14
- - **full** — assess every substantive request for **rawness**. A raw idea, hypothesis, or
15
- undecided direction matures through the pipeline (`mcpbox_pipeline_run` → handoff)
16
- before it becomes a task.
17
-
18
- The mode only tunes how actively you *offer* the pipeline. It does not change where work
19
- lands — that is the MCP server's routing rule: decided-and-bounded work and
20
- follow-ups extending a run that already handed off go straight to daruma; raw material — and
21
- anything belonging to a run still in flight — goes through the pipeline.
14
+ - **full** — add the operational reminder to matched intents. Unmatched prompts stay silent. Pipeline and advisor calls are optional in every mode.
22
15
 
23
16
  The level persists across sessions (stored in `~/.agents/mcpbox/mode`) and is read by the
24
17
  UserPromptSubmit hook, which injects the matching reminder on each prompt.
25
18
 
26
- Codex/Cursor/Kimi/OpenCode have no such hook: their `*-init` command writes the mode into the
27
- MCP URL (`?mode=`), so re-run it after changing the mode.
19
+ Hosts with a configured MCP URL record its `?mode=` in metrics. Re-run the host’s `*-init` command to refresh that URL.
28
20
 
29
21
  ## Steps
30
22
 
package/commands/next.md CHANGED
@@ -7,10 +7,10 @@ to the user/agent to actually execute it.
7
7
 
8
8
  ## Steps
9
9
 
10
- 1. Resolve project (`daruma_workspace_info` → `default_project`).
11
- 2. Active plan: `daruma_plan_list` with `status = "active"`, `sort = "updated"`,
10
+ 1. Resolve the project as in `/mcpbox:tasks`.
11
+ 2. Active plan: `daruma_plan_list` with the resolved project_id, `status = "active"`, `sort = "updated"`,
12
12
  `limit = 1` — the most recently updated plan (the default order is by creation).
13
- If none, stop with "no active plan — decided work: `daruma_plan_materialize`; raw idea: `/mcpbox:pipeline-run`".
13
+ If none, stop with "no active plan — decided work: `daruma_plan_materialize`; optional exploration: `/mcpbox:pipeline-run`".
14
14
  3. `daruma_plan_drain_next` with the plan id. The server atomically picks the next
15
15
  ready (unblocked) task and claims it for this session; it returns null when no
16
16
  unclaimed ready task remains. Keep the returned `run_id`: the server opened that
@@ -40,6 +40,7 @@ to the user/agent to actually execute it.
40
40
  then daruma_run_abort run_id=<run_id> reason=<reason>
41
41
  ```
42
42
 
43
+ When the completion schema includes `side_findings`, review and include them as in `/mcpbox:close`.
43
44
  An open run keeps the plan from auto-closing after its last task; the
44
45
  `plan_close_blocked_by_run` warning names it in `details.run_id`.
45
46
 
@@ -1,11 +1,10 @@
1
1
  ---
2
- description: Open an mcpbox pipeline run from a raw idea; it ends as a daruma task via handoff.
2
+ description: Open an mcpbox pipeline run from a raw idea; hand off a ready action packet to Daruma.
3
3
  ---
4
4
 
5
5
  The user invoked `/mcpbox:pipeline-run` with a raw idea/request in `$ARGUMENTS`.
6
6
 
7
- The run turns the idea into a ready task; the task is created **only** via handoff,
8
- never by materializing it directly.
7
+ Only a ready action packet can become a task through handoff. Report a terminal run without a packet and stop.
9
8
 
10
9
  ## Steps
11
10
 
@@ -18,7 +17,8 @@ never by materializing it directly.
18
17
  `run_id` immediately while the run proceeds in the background. Poll
19
18
  `mcpbox_trace_get { run_id }` until the status is no longer `running`.
20
19
  3. On failure, report the reason from `mcpbox_trace_get`; do not hand off an
21
- incomplete run. Recovery: a run `failed` at layer L → retry with
20
+ incomplete run. For `needs_input`, show the recorded question and use
21
+ `mcpbox_pipeline_answer` with the user’s answer before continuing. Recovery: a run `failed` at layer L → retry with
22
22
  `mcpbox_pipeline_advance { run_id, layer: L }` after fixing the input; fujin
23
23
  `not_ready` → advance from `yatagarasu`; or ask the owner. Never
24
24
  `daruma_plan_materialize` the idea directly to get around a failed run.
package/commands/plan.md CHANGED
@@ -6,10 +6,10 @@ The user invoked `/mcpbox:plan`.
6
6
 
7
7
  ## Steps
8
8
 
9
- 1. Resolve project (`daruma_workspace_info` → `default_project`).
10
- 2. `daruma_plan_list status="draft,active" sort="updated" limit=1` — the most recently
9
+ 1. Resolve the project as in `/mcpbox:tasks`.
10
+ 2. `daruma_plan_list project_id=<resolved> status="draft,active" sort="updated" limit=1` — the most recently
11
11
  updated plan (the default order is by creation, and its first page can miss it).
12
- If none, stop with "no active plan — decided work: `daruma_plan_materialize`; raw idea: `/mcpbox:pipeline-run`".
12
+ If none, stop with "no active plan — decided work: `daruma_plan_materialize`; optional exploration: `/mcpbox:pipeline-run`".
13
13
  3. For the chosen plan, `daruma_plan_get view="tasks"` (single call — do not enumerate the archive).
14
14
  It lists every plan task (done included) with `status`, `priority`, `depends_on` and
15
15
  `blocked_by`; the default `progress` view caps each group at five open tasks.
@@ -25,4 +25,4 @@ The user invoked `/mcpbox:plan`.
25
25
 
26
26
  - Progress bar from `progress.tasks_done`/`progress.tasks_total`; one row per task in plan order.
27
27
  - Tasks with a non-empty `blocked_by` marked ⛔ with those blocker ids.
28
- 5. Do not call `daruma_plan_list status=completed` (token-heavy). Read-only.
28
+ 5. Do not call `daruma_plan_list project_id=<resolved> status=completed` (token-heavy). Read-only.
package/commands/sync.md CHANGED
@@ -6,7 +6,7 @@ The user invoked `/mcpbox:sync`.
6
6
 
7
7
  ## Steps
8
8
 
9
- 1. Resolve project (`daruma_workspace_info` → `default_project`).
9
+ 1. Resolve the project as in `/mcpbox:tasks`.
10
10
  2. Re-fetch server-side: one scoped `daruma_list status=active`, and if a plan is active,
11
11
  one `daruma_plan_get`.
12
12
  3. Summarize what changed since the session's last view (new / closed / newly blocked),
package/commands/tasks.md CHANGED
@@ -9,11 +9,11 @@ Drive the mcpbox MCP server (do not invent IDs, do not write local plan files).
9
9
  ## Steps
10
10
 
11
11
  1. Resolve project:
12
- - `daruma_workspace_info` → use `default_project` if set.
13
- - Else `daruma_project_list` → pick first. If none, say "no projects yet" and stop.
12
+ - Use the repo binding or match the cwd to the nearest scope in `daruma_workspace_info`. Use `default_project` if unambiguous.
13
+ - Else `daruma_project_list` → use the only project or ask which project the user means. If none, say "no projects yet" and stop.
14
14
 
15
15
  2. Fetch tasks server-side (don't filter locally):
16
- - `daruma_list project_id=<resolved> status=active limit=50`.
16
+ - `daruma_list project_id=<resolved> status=active limit=30`.
17
17
  - **Never** use `status=all` unless the user explicitly asked for the full archive; it is token-heavy.
18
18
 
19
19
  3. Render exactly this format:
@@ -29,6 +29,6 @@ Drive the mcpbox MCP server (do not invent IDs, do not write local plan files).
29
29
  - Status emoji: 📥 inbox, ⬜ todo, 🟢 in_progress, ✅ done.
30
30
  - Title truncated to 60 chars with `…`; `Plan` = last 8 chars of `plan_id` or `—`.
31
31
 
32
- 4. If >30 rows: show first 30, footer `…and <N> more — narrow with /mcpbox:mine`.
32
+ 4. Use the response total for N. If more than 30 tasks match, show the returned rows and footer `…and <total minus displayed> more — /mcpbox:mine shows project tasks in progress or in review`.
33
33
  5. On `daruma_list` error: print it verbatim and stop.
34
34
  6. Read-only — do not transition any task in this command.
@@ -1,64 +1,7 @@
1
1
  #!/usr/bin/env node
2
- // Integrity check, not an OS sandbox. The controller pins the baseline before execution.
3
- import { execFileSync } from "node:child_process";
4
- import { readFileSync, lstatSync, realpathSync, writeSync } from "node:fs";
5
- import { resolve, relative, isAbsolute } from "node:path";
6
- import { pathToFileURL } from "node:url";
2
+ // PreToolUse / PostToolUse: acceptance lock integrity (exit 2 on a breach).
3
+ // Entry only: hooks/bootstrap.mjs loads hooks/impl/acceptance-guard.mjs and reports any
4
+ // failure to the host instead of exiting 1.
5
+ import { runHook } from "./bootstrap.mjs";
7
6
 
8
- export function checkAcceptanceLock(lock, event = {}) {
9
- if (!lock || typeof lock.repo !== "string" || !isAbsolute(lock.repo)
10
- || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(lock.base)
11
- || !Array.isArray(lock.paths) || !lock.paths.length) {
12
- throw new Error("invalid acceptance lock: expected absolute repo, immutable commit SHA and paths");
13
- }
14
- const repo = realpathSync(lock.repo);
15
- const gitEnv = { ...process.env };
16
- for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"]) delete gitEnv[key];
17
- const git = (args) => execFileSync("git", ["--no-replace-objects", ...args], {
18
- cwd: repo, timeout: 5000, maxBuffer: 16 * 1024 * 1024,
19
- env: gitEnv,
20
- stdio: ["ignore", "pipe", "pipe"],
21
- });
22
- // Do not allow Git environment overrides to redirect the baseline lookup.
23
- if (realpathSync(git(["rev-parse", "--show-toplevel"]).toString().replace(/\r?\n$/, "")) !== repo) {
24
- throw new Error("acceptance repo must be the Git root");
25
- }
26
- for (const path of lock.paths) {
27
- if (typeof path !== "string" || !path || isAbsolute(path)
28
- || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) {
29
- throw new Error("acceptance paths must be normalized repository-relative files");
30
- }
31
- const file = resolve(repo, path);
32
- const actual = realpathSync(file);
33
- const rel = relative(repo, actual);
34
- if (rel.startsWith("../") || isAbsolute(rel) || actual !== file || !lstatSync(file).isFile()) {
35
- throw new Error(`protected assertion must be a regular file without symlink traversal: ${path}`);
36
- }
37
- if (!readFileSync(file).equals(git(["show", `${lock.base}:${path}`]))) {
38
- throw new Error(`protected assertion changed: ${path}`);
39
- }
40
- if (event.hook_event_name === "PreToolUse" && ["Edit", "Write", "MultiEdit"].includes(event.tool_name)) {
41
- const target = event.tool_input?.file_path ?? event.tool_input?.path;
42
- if (typeof target === "string" && resolve(event.cwd ?? repo, target) === file) {
43
- throw new Error(`executor cannot edit protected assertion: ${path}`);
44
- }
45
- }
46
- }
47
- }
48
-
49
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
50
- if (process.env.MCPBOX_ACCEPTANCE_LOCK) {
51
- try {
52
- let input = "";
53
- for await (const chunk of process.stdin) {
54
- input += chunk;
55
- // Hook transports may keep stdin open after the JSON message.
56
- try { JSON.parse(input); break; } catch { /* await the remaining JSON */ }
57
- }
58
- checkAcceptanceLock(JSON.parse(process.env.MCPBOX_ACCEPTANCE_LOCK), input.trim() ? JSON.parse(input) : {});
59
- } catch (error) {
60
- writeSync(2, `[mcpbox/acceptance-integrity] ${error.message}\nStop execution; record an integrity warning in Daruma. Do not rebaseline the oracle to obtain PASS.\n`);
61
- process.exitCode = 2;
62
- }
63
- }
64
- }
7
+ runHook(import.meta.url, "PreToolUse", function () { return import("./impl/acceptance-guard.mjs"); });
@@ -0,0 +1,167 @@
1
+ // Entry wrapper of every hooks/<name>.mjs: the hook itself lives in
2
+ // hooks/impl/<name>.mjs and is loaded by a dynamic import, so a failure to
3
+ // load it (ERR_MODULE_NOT_FOUND, a SyntaxError on an old Node) is caught here
4
+ // like a runtime throw — static imports fail before any code of ours runs.
5
+ //
6
+ // A failing hook never exits 1 and never fails silently: Codex shows only
7
+ // "hook exited with code N" and drops stderr, but parses stdout on exit 0.
8
+ // So the reason goes to stdout as one JSON document (shape per event and
9
+ // surface: hookFailureOutput in lib/hook-output.mjs), and to stderr with the
10
+ // stack for logs and `mcpbox-claude doctor`, then exit 0. A hook that already
11
+ // wrote its document gets no second one: stderr only; output main() still
12
+ // writes after the failure goes to stderr too. The text is capped at 1 KB of
13
+ // UTF-8.
14
+ //
15
+ // Plain syntax on purpose — no `??`, `?.`, `node:` specifiers or top-level
16
+ // await — so that Node 12–18 parse this file and can say which node runs it.
17
+
18
+ import { writeSync } from "fs";
19
+ import { pathToFileURL } from "url";
20
+
21
+ export const MIN_NODE_MAJOR = 20;
22
+ // Whole failure text, counted in UTF-8 bytes: it becomes additionalContext.
23
+ export const CONTEXT_MAX_BYTES = 1024;
24
+ const PATH_MAX_BYTES = 256;
25
+ const CODE_MAX_BYTES = 64;
26
+ const ELLIPSIS = "…";
27
+
28
+ // Message for a node older than `engines`, null when it is new enough.
29
+ export function nodeVersionProblem(version, execPath) {
30
+ const major = Number(String(version).split(".")[0]);
31
+ if (major >= MIN_NODE_MAJOR) return null;
32
+ return "Node " + version + " at " + execPath + " is not supported (need >= " + MIN_NODE_MAJOR + ")";
33
+ }
34
+
35
+ function utf8Bytes(text) {
36
+ return Buffer.byteLength(text, "utf8");
37
+ }
38
+
39
+ // `text` cut to at most maxBytes of UTF-8 between code points, "…" marking
40
+ // the cut; a string that fits comes back as is.
41
+ export function clipUtf8(text, maxBytes) {
42
+ text = String(text);
43
+ if (utf8Bytes(text) <= maxBytes) return text;
44
+ const room = maxBytes - utf8Bytes(ELLIPSIS);
45
+ if (room < 0) return "";
46
+ let used = 0;
47
+ let out = "";
48
+ for (const ch of text) {
49
+ const n = utf8Bytes(ch);
50
+ if (used + n > room) break;
51
+ used += n;
52
+ out += ch;
53
+ }
54
+ return out + ELLIPSIS;
55
+ }
56
+
57
+ // head + middle + tail within CONTEXT_MAX_BYTES; the middle (the error
58
+ // message) is what gets cut.
59
+ function fit(head, middle, tail) {
60
+ const room = CONTEXT_MAX_BYTES - utf8Bytes(head) - utf8Bytes(tail);
61
+ return clipUtf8(head + clipUtf8(middle, Math.max(room, 0)) + tail, CONTEXT_MAX_BYTES);
62
+ }
63
+
64
+ // One line for the agent and the user; doctor recognises the prefix.
65
+ export function failureText(name, err, node) {
66
+ const runtime = node || { version: process.versions.node, execPath: process.execPath };
67
+ const head = "[mcpbox] hook " + name + " failed: ";
68
+ if (err && err.mcpboxNodeProblem) return fit(head, err.message, "; run: mcpbox-claude doctor");
69
+ let message = err && err.message ? String(err.message) : String(err);
70
+ // "Unexpected end of input" alone does not say it is the code that broke.
71
+ if (err && err.name && err.name !== "Error") message = err.name + ": " + message;
72
+ const code = err && err.code ? " (" + clipUtf8(err.code, CODE_MAX_BYTES) + ")" : "";
73
+ const tail = code + " — node " + runtime.version + " " + clipUtf8(runtime.execPath, PATH_MAX_BYTES)
74
+ + "; run: mcpbox-claude doctor";
75
+ return fit(head, message, tail);
76
+ }
77
+
78
+ function hookName(entryUrl) {
79
+ const file = String(entryUrl).split("/").pop();
80
+ return file.replace(/\.mjs$/, "");
81
+ }
82
+
83
+ function isEntry(entryUrl) {
84
+ return Boolean(process.argv[1]) && pathToFileURL(process.argv[1]).href === entryUrl;
85
+ }
86
+
87
+ function flushThenExit(code) {
88
+ process.stdout.write("", function () { process.exit(code); });
89
+ }
90
+
91
+ // Run hooks/impl/<name>.mjs's main() when entryUrl is the script node was
92
+ // started with; importing a hook file (tests) runs nothing. `event` is the
93
+ // host event (SessionStart, Stop, …); null for a git hook — stderr only.
94
+ export function runHook(entryUrl, event, load) {
95
+ if (!isEntry(entryUrl)) return;
96
+ const name = hookName(entryUrl);
97
+ // Single writer of stdout: once a failure is reported, whatever main() still
98
+ // writes (a deferred write, a timer) goes to stderr, so the host never gets
99
+ // a second document after the failure one — nor one before it.
100
+ const out = { wrote: false, failed: false, write: process.stdout.write };
101
+ process.stdout.write = function (chunk) {
102
+ if (!out.failed) {
103
+ if (chunk && chunk.length) out.wrote = true;
104
+ return out.write.apply(process.stdout, arguments);
105
+ }
106
+ if (chunk && chunk.length) {
107
+ try { writeSync(2, typeof chunk === "string" ? chunk : Buffer.from(chunk)); } catch (e) { /* no stderr */ }
108
+ }
109
+ const done = arguments[arguments.length - 1];
110
+ if (typeof done === "function") process.nextTick(done);
111
+ return true;
112
+ };
113
+ let reported = false;
114
+ const report = function (err) {
115
+ if (reported) return;
116
+ reported = true;
117
+ out.failed = true;
118
+ reportHookFailure(event, name, err, out);
119
+ };
120
+ process.on("uncaughtException", report);
121
+ process.on("unhandledRejection", report);
122
+
123
+ const problem = nodeVersionProblem(process.versions.node, process.execPath);
124
+ if (problem) {
125
+ const err = new Error(problem);
126
+ err.mcpboxNodeProblem = true;
127
+ report(err);
128
+ return;
129
+ }
130
+ let exitAfterMain = false;
131
+ Promise.resolve()
132
+ .then(load)
133
+ .then(function (mod) {
134
+ exitAfterMain = mod.exitAfterMain === true;
135
+ return mod.main();
136
+ })
137
+ // Otherwise the process ends on its own: work main() left running on
138
+ // purpose finishes, and an exit code main() set (acceptance-guard's 2) holds.
139
+ .then(function () { if (exitAfterMain && !reported) flushThenExit(0); }, report);
140
+ }
141
+
142
+ // `out` is runHook's stdout state: `wrote` — main() already wrote, so no
143
+ // document of ours; `write` — the real stdout write, which only this function
144
+ // still uses once the failure is reported.
145
+ export function reportHookFailure(event, name, err, out) {
146
+ const text = failureText(name, err);
147
+ const stack = err && err.stack && !err.mcpboxNodeProblem ? "\n" + err.stack : "";
148
+ try { writeSync(2, text + stack + "\n"); } catch (e) { /* no stderr to write to */ }
149
+ const write = function (chunk, done) { out.write.call(process.stdout, chunk, done); };
150
+ const exit = function () { write("", function () { process.exit(0); }); };
151
+ if (out.wrote || !event) {
152
+ exit();
153
+ return;
154
+ }
155
+ import("../lib/hook-output.mjs")
156
+ .then(function (lib) { return lib.hookFailureOutput(event, text); })
157
+ // The lib itself does not load (old node, broken copy): systemMessage is
158
+ // accepted on every event by Codex and Claude Code.
159
+ .catch(function () { return { systemMessage: text }; })
160
+ .then(function (payload) {
161
+ if (!payload) {
162
+ exit();
163
+ return;
164
+ }
165
+ write(JSON.stringify(payload) + "\n", function () { process.exit(0); });
166
+ });
167
+ }
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse: claim-before-edit gate.
3
+ // Entry only: hooks/bootstrap.mjs loads hooks/impl/edit-gate.mjs and reports any
4
+ // failure to the host instead of exiting 1.
5
+ import { runHook } from "./bootstrap.mjs";
6
+
7
+ runHook(import.meta.url, "PreToolUse", function () { return import("./impl/edit-gate.mjs"); });
package/hooks/hooks.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "description": "mcpbox-claude hooks: proactive session summary, capture/pipeline hints, and a Stop guard against tasks left in_progress",
2
+ "description": "mcpbox-claude hooks: proactive session summary with this agent's open tasks, capture/pipeline hints, a claim-before-edit gate (advisory by default), a Stop gate against tasks left open without an outcome comment, and SessionEnd release of this session's claims",
3
3
  "hooks": {
4
4
  "SessionStart": [
5
5
  {
@@ -8,6 +8,11 @@
8
8
  "type": "command",
9
9
  "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.mjs\"",
10
10
  "timeout": 15
11
+ },
12
+ {
13
+ "type": "command",
14
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-gate.mjs\" start",
15
+ "timeout": 10
11
16
  }
12
17
  ]
13
18
  }
@@ -42,6 +47,16 @@
42
47
  "timeout": 15
43
48
  }
44
49
  ]
50
+ },
51
+ {
52
+ "matcher": "^(Edit|Write|MultiEdit|NotebookEdit|Bash|PowerShell|mcp__.*serena.*)$",
53
+ "hooks": [
54
+ {
55
+ "type": "command",
56
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/edit-gate.mjs\"",
57
+ "timeout": 5
58
+ }
59
+ ]
45
60
  }
46
61
  ],
47
62
  "PostToolUse": [
@@ -53,6 +68,27 @@
53
68
  "timeout": 15
54
69
  }
55
70
  ]
71
+ },
72
+ {
73
+ "matcher": ".*daruma_(plan_drain_next|ready_drain|claim|plan_materialize|set_status|comment|release|complete)$",
74
+ "hooks": [
75
+ {
76
+ "type": "command",
77
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/track-claims.mjs\"",
78
+ "timeout": 5
79
+ }
80
+ ]
81
+ }
82
+ ],
83
+ "SessionEnd": [
84
+ {
85
+ "hooks": [
86
+ {
87
+ "type": "command",
88
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-gate.mjs\" end",
89
+ "timeout": 10
90
+ }
91
+ ]
56
92
  }
57
93
  ]
58
94
  }
@@ -0,0 +1,63 @@
1
+ // Integrity check, not an OS sandbox. The controller pins the baseline before execution.
2
+ import { execFileSync } from "node:child_process";
3
+ import { readFileSync, lstatSync, realpathSync, writeSync } from "node:fs";
4
+ import { resolve, relative, isAbsolute } from "node:path";
5
+
6
+ export function checkAcceptanceLock(lock, event = {}) {
7
+ if (!lock || typeof lock.repo !== "string" || !isAbsolute(lock.repo)
8
+ || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(lock.base)
9
+ || !Array.isArray(lock.paths) || !lock.paths.length) {
10
+ throw new Error("invalid acceptance lock: expected absolute repo, immutable commit SHA and paths");
11
+ }
12
+ const repo = realpathSync(lock.repo);
13
+ const gitEnv = { ...process.env };
14
+ for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"]) delete gitEnv[key];
15
+ const git = (args) => execFileSync("git", ["--no-replace-objects", ...args], {
16
+ cwd: repo, timeout: 5000, maxBuffer: 16 * 1024 * 1024,
17
+ env: gitEnv,
18
+ stdio: ["ignore", "pipe", "pipe"],
19
+ });
20
+ // Do not allow Git environment overrides to redirect the baseline lookup.
21
+ if (realpathSync(git(["rev-parse", "--show-toplevel"]).toString().replace(/\r?\n$/, "")) !== repo) {
22
+ throw new Error("acceptance repo must be the Git root");
23
+ }
24
+ for (const path of lock.paths) {
25
+ if (typeof path !== "string" || !path || isAbsolute(path)
26
+ || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) {
27
+ throw new Error("acceptance paths must be normalized repository-relative files");
28
+ }
29
+ const file = resolve(repo, path);
30
+ const actual = realpathSync(file);
31
+ const rel = relative(repo, actual);
32
+ if (rel.startsWith("../") || isAbsolute(rel) || actual !== file || !lstatSync(file).isFile()) {
33
+ throw new Error(`protected assertion must be a regular file without symlink traversal: ${path}`);
34
+ }
35
+ if (!readFileSync(file).equals(git(["show", `${lock.base}:${path}`]))) {
36
+ throw new Error(`protected assertion changed: ${path}`);
37
+ }
38
+ if (event.hook_event_name === "PreToolUse" && ["Edit", "Write", "MultiEdit"].includes(event.tool_name)) {
39
+ const target = event.tool_input?.file_path ?? event.tool_input?.path;
40
+ if (typeof target === "string" && resolve(event.cwd ?? repo, target) === file) {
41
+ throw new Error(`executor cannot edit protected assertion: ${path}`);
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ // A broken lock or a changed oracle exits 2 with the reason on stderr — on
48
+ // purpose, it stops the tool call; only load failures go through the bootstrap.
49
+ export async function main() {
50
+ if (!process.env.MCPBOX_ACCEPTANCE_LOCK) return;
51
+ try {
52
+ let input = "";
53
+ for await (const chunk of process.stdin) {
54
+ input += chunk;
55
+ // Hook transports may keep stdin open after the JSON message.
56
+ try { JSON.parse(input); break; } catch { /* await the remaining JSON */ }
57
+ }
58
+ checkAcceptanceLock(JSON.parse(process.env.MCPBOX_ACCEPTANCE_LOCK), input.trim() ? JSON.parse(input) : {});
59
+ } catch (error) {
60
+ writeSync(2, `[mcpbox/acceptance-integrity] ${error.message}\nStop execution; record an integrity warning in Daruma. Do not rebaseline the oracle to obtain PASS.\n`);
61
+ process.exitCode = 2;
62
+ }
63
+ }
@@ -0,0 +1,32 @@
1
+ // PreToolUse (Claude Code): claim-before-edit gate over the claim projection
2
+ // in hook state — see lib/edit-gate.mjs for coverage and modes. No tracker
3
+ // call. A broken payload or a state read failure lets the call through in
4
+ // advisory mode; strict treats an unreadable state as no claim.
5
+ import {
6
+ adviceGiven, adviceKey, editGateDecision, gateModeOf, preToolUseOutput, recordAdvice, writeSurface,
7
+ } from "../../lib/edit-gate.mjs";
8
+ import { readStdin } from "../../lib/hook-input.mjs";
9
+ import { sessionClaimState, sessionIdOf } from "../../lib/session-gate.mjs";
10
+
11
+ export async function main() {
12
+ const mode = gateModeOf();
13
+ if (mode === "off") return;
14
+ let payload;
15
+ try {
16
+ payload = JSON.parse((await readStdin()) || "{}");
17
+ } catch {
18
+ return;
19
+ }
20
+ const surface = writeSurface(payload.tool_name, payload.tool_input);
21
+ if (!surface) return;
22
+ const sessionId = sessionIdOf(payload);
23
+ const state = await sessionClaimState(sessionId, payload.cwd ?? process.cwd()).catch(() => ({ ready: [], stale: [] }));
24
+ const decision = editGateDecision({ surface, mode, state });
25
+ if (!decision) return;
26
+ if (decision.context && sessionId) {
27
+ const key = adviceKey(surface, state);
28
+ if ((await adviceGiven(sessionId)).has(key)) return;
29
+ await recordAdvice(sessionId, key);
30
+ }
31
+ process.stdout.write(`${JSON.stringify(preToolUseOutput(decision))}\n`);
32
+ }
@@ -0,0 +1,8 @@
1
+ // git prepare-commit-msg: add "Daruma-Task: <id>" for the work/<id> branch or
2
+ // the tasks this agent session claimed. Installed by `mcpbox-claude git-hook
3
+ // install`; any failure leaves the message untouched and the commit proceeds.
4
+ import { prepareCommitMsg } from "../../lib/git-trailer.mjs";
5
+
6
+ export async function main() {
7
+ await prepareCommitMsg({ messageFile: process.argv[2] });
8
+ }
@@ -0,0 +1,81 @@
1
+ // Session lifecycle half of the gate, one script for every CLI surface:
2
+ // session-gate.mjs start [--surface=…] SessionStart (also after compaction):
3
+ // print this agent's open tasks.
4
+ // session-gate.mjs end [--surface=…] SessionEnd: release the claims this
5
+ // session still holds.
6
+ // Failures stay silent: the tracker being away never blocks a session.
7
+
8
+ import { callCloudTool, readCredentials, releaseClaimGeneration } from "../../lib/cloud-knowledge.mjs";
9
+ import { readStdin } from "../../lib/hook-input.mjs";
10
+ import {
11
+ claimNote, localClaimAgents, openTasksNote, readRecords, sessionClaimState, sessionIdOf, sessionStartOutput,
12
+ surfaceOf, validClaims,
13
+ } from "../../lib/session-gate.mjs";
14
+
15
+ const TIMEOUT_MS = 2500;
16
+ // Tracker connections can outlive main: hooks/bootstrap.mjs exits once stdout is flushed.
17
+ export const exitAfterMain = true;
18
+ const DETAIL_MAX = 10;
19
+
20
+ export async function openTasks(cwd, { creds, call = callCloudTool } = {}) {
21
+ const opts = { creds, timeoutMs: TIMEOUT_MS };
22
+ const [info, local, list] = await Promise.all([
23
+ call("daruma_workspace_info", {}, opts).catch(() => null),
24
+ localClaimAgents(),
25
+ call("daruma_list", { status: "in_progress,in_review", scope_path: cwd, limit: 50 }, opts),
26
+ ]);
27
+ const items = Array.isArray(list?.items) ? list.items : [];
28
+ // Summary rows carry no claim: read the in_progress ones back to keep only ours.
29
+ const detailed = await Promise.all(items.map((t, i) => (
30
+ t.status === "in_progress" && i < DETAIL_MAX
31
+ ? call("daruma_get", { id: t.id }, opts).then((full) => ({ ...t, current_claim: full?.current_claim }), () => t)
32
+ : t
33
+ )));
34
+ // This agent: the pairing token's (workspace_info) and the MCP connections
35
+ // that claimed on this machine (local session records).
36
+ const agents = [info?.mcp_agent_id, ...local].filter(Boolean);
37
+ return openTasksNote(detailed.filter((t) => t.status === "in_review" || t.current_claim), agents);
38
+ }
39
+
40
+ // Claims recorded in this session that the server still shows as ours.
41
+ export function releasable(tasks, claimed) {
42
+ return (Array.isArray(tasks) ? tasks : []).filter((t) => t?.status === "in_progress" && claimed.some(
43
+ (c) => c.task_id === String(t.id) && c.claim_id === t.current_claim?.claim_id && c.agent_id === t.current_claim?.agent_id,
44
+ )).map((t) => ({ task_id: String(t.id), agent_id: t.current_claim.agent_id, claim_id: t.current_claim.claim_id }));
45
+ }
46
+
47
+ async function start(payload, surface) {
48
+ const cwd = payload?.cwd ?? payload?.workspace_roots?.[0] ?? process.cwd();
49
+ const creds = await readCredentials();
50
+ // This session's own claim (resume / after compaction) comes from local
51
+ // hook state, so it shows unpaired and offline too.
52
+ const claim = claimNote(await sessionClaimState(sessionIdOf(payload), cwd, { creds }).catch(() => ({})));
53
+ const tasks = creds ? await openTasks(cwd, { creds }).catch(() => "") : "";
54
+ const out = sessionStartOutput(surface, [claim, tasks].filter(Boolean).join("\n"));
55
+ if (out) process.stdout.write(typeof out === "string" ? `${out}\n` : `${JSON.stringify(out)}\n`);
56
+ }
57
+
58
+ async function end(payload) {
59
+ const sessionId = sessionIdOf(payload);
60
+ if (!sessionId) return;
61
+ const claimed = validClaims(await readRecords(sessionId, "claims"));
62
+ if (!claimed.length) return;
63
+ const creds = await readCredentials();
64
+ if (!creds) return;
65
+ const opts = { creds, timeoutMs: TIMEOUT_MS };
66
+ const ids = [...new Set(claimed.map((c) => c.task_id))];
67
+ const tasks = await Promise.all(ids.map((id) => callCloudTool("daruma_get", { id }, opts).catch(() => null)));
68
+ // The claim's own agent: the hook's pairing token is a different agent than
69
+ // the MCP connection that claimed, and release defaults to the token's.
70
+ await Promise.all(releasable(tasks, claimed).map((claim) => (
71
+ releaseClaimGeneration(claim, opts).catch(() => null)
72
+ )));
73
+ }
74
+
75
+ export async function main() {
76
+ const event = process.argv[2];
77
+ let payload = {};
78
+ try { payload = JSON.parse((await readStdin()) || "{}"); } catch { /* no payload */ }
79
+ if (event === "start") await start(payload, surfaceOf());
80
+ else if (event === "end") await end(payload);
81
+ }