@mcpbox/mcpbox-claude 0.1.28 → 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.
- package/.claude-plugin/plugin.json +2 -2
- package/.codex-plugin/plugin.json +4 -4
- package/README.md +261 -26
- package/bin/mcpbox-claude.mjs +21 -8
- package/commands/close.md +2 -0
- package/commands/mine.md +4 -4
- package/commands/mode.md +4 -12
- package/commands/next.md +4 -3
- package/commands/pipeline-run.md +4 -4
- package/commands/plan.md +4 -4
- package/commands/sync.md +1 -1
- package/commands/tasks.md +4 -4
- package/hooks/acceptance-guard.mjs +5 -62
- package/hooks/bootstrap.mjs +167 -0
- package/hooks/edit-gate.mjs +7 -0
- package/hooks/hooks.json +12 -2
- package/hooks/impl/acceptance-guard.mjs +63 -0
- package/hooks/impl/edit-gate.mjs +32 -0
- package/hooks/impl/prepare-commit-msg.mjs +8 -0
- package/hooks/impl/session-gate.mjs +81 -0
- package/hooks/impl/session-start.mjs +89 -0
- package/hooks/impl/stop.mjs +64 -0
- package/hooks/impl/track-claims.mjs +35 -0
- package/hooks/impl/user-prompt-submit.mjs +234 -0
- package/hooks/prepare-commit-msg.mjs +5 -9
- package/hooks/session-gate.mjs +5 -82
- package/hooks/session-start.mjs +5 -75
- package/hooks/stop.mjs +5 -58
- package/hooks/track-claims.mjs +5 -30
- package/hooks/user-prompt-submit.mjs +5 -259
- package/lib/cloud-knowledge.mjs +19 -3
- package/lib/codex.mjs +2 -2
- package/lib/cursor.mjs +1 -1
- package/lib/edit-gate.mjs +120 -0
- package/lib/harness-hooks.mjs +53 -5
- package/lib/hook-doctor.mjs +517 -0
- package/lib/hook-output.mjs +16 -0
- package/lib/kimi.mjs +9 -3
- package/lib/knowledge-skills.mjs +259 -0
- package/lib/mode.mjs +2 -12
- package/lib/policy.mjs +54 -127
- package/lib/session-gate.mjs +195 -15
- package/lib/version.mjs +1 -1
- package/package.json +2 -2
- package/skills/mcpbox/SKILL.md +17 -94
- package/skills/mcpbox-close/SKILL.md +2 -0
- package/skills/mcpbox-mine/SKILL.md +4 -4
- package/skills/mcpbox-mode/SKILL.md +4 -12
- package/skills/mcpbox-next/SKILL.md +4 -3
- package/skills/mcpbox-pipeline-run/SKILL.md +4 -4
- package/skills/mcpbox-plan/SKILL.md +4 -4
- package/skills/mcpbox-sync/SKILL.md +1 -1
- package/skills/mcpbox-tasks/SKILL.md +4 -4
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
|
|
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
|
|
13
|
-
- Else `daruma_project_list` →
|
|
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=
|
|
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
|
|
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
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import {
|
|
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
|
-
|
|
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 with this agent's open tasks, capture/pipeline hints, a Stop gate against tasks left open without an outcome comment, and SessionEnd release of this session's claims",
|
|
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
|
{
|
|
@@ -47,6 +47,16 @@
|
|
|
47
47
|
"timeout": 15
|
|
48
48
|
}
|
|
49
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
|
+
]
|
|
50
60
|
}
|
|
51
61
|
],
|
|
52
62
|
"PostToolUse": [
|
|
@@ -60,7 +70,7 @@
|
|
|
60
70
|
]
|
|
61
71
|
},
|
|
62
72
|
{
|
|
63
|
-
"matcher": ".*daruma_(plan_drain_next|ready_drain|claim|plan_materialize|set_status|comment)$",
|
|
73
|
+
"matcher": ".*daruma_(plan_drain_next|ready_drain|claim|plan_materialize|set_status|comment|release|complete)$",
|
|
64
74
|
"hooks": [
|
|
65
75
|
{
|
|
66
76
|
"type": "command",
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// SessionStart refreshes policy and update notices; task selection is explicit.
|
|
2
|
+
|
|
3
|
+
import { isCodexSurface, writeHookOutput } from "../../lib/hook-output.mjs";
|
|
4
|
+
import { syncPolicyBlocks } from "../../lib/policy.mjs";
|
|
5
|
+
import { checkForUpdate, policyBlocks, updateNotice } from "../../lib/update-check.mjs";
|
|
6
|
+
import { VERSION } from "../../lib/version.mjs";
|
|
7
|
+
|
|
8
|
+
// Block text to write: the server's copy, else the baked text (see policyBlocks).
|
|
9
|
+
export { policyBlocks };
|
|
10
|
+
|
|
11
|
+
// Bring the policy blocks already installed around cwd up to the server's
|
|
12
|
+
// text (see syncPolicyBlocks). Failures stay silent: a read-only tree must
|
|
13
|
+
// never block the session. MCPBOX_NO_POLICY_SYNC=1 opts out. Only the plugin
|
|
14
|
+
// surfaces sync: Kimi runs a copy frozen at kimi-init (no CLAUDE_PLUGIN_ROOT,
|
|
15
|
+
// no PLUGIN_DATA), whose policy would be stale by construction.
|
|
16
|
+
export async function syncPolicy(cwd = process.cwd(), env = process.env) {
|
|
17
|
+
if (env.MCPBOX_NO_POLICY_SYNC) return { paths: [], origin: null };
|
|
18
|
+
if (!env.CLAUDE_PLUGIN_ROOT && !isCodexSurface(env)) return { paths: [], origin: null };
|
|
19
|
+
const blocks = await policyBlocks();
|
|
20
|
+
const paths = [];
|
|
21
|
+
// Codex has no hooks of its own (.codex-plugin declares none), so any plugin
|
|
22
|
+
// surface refreshes the Codex carriers too: AGENTS.md up the tree, plus the
|
|
23
|
+
// user-level SKILL.md — refreshed from Claude, retired from the Codex plugin.
|
|
24
|
+
// Cursor rules up the tree likewise: Cursor runs no hook of this plugin.
|
|
25
|
+
// Every plain carrier gets the same text as AGENTS.md.
|
|
26
|
+
if (env.CLAUDE_PLUGIN_ROOT && !isCodexSurface(env)) {
|
|
27
|
+
paths.push(...await syncPolicyBlocks({ cwd, block: blocks.claude }).catch(() => []));
|
|
28
|
+
}
|
|
29
|
+
if (isCodexSurface(env) || env.CLAUDE_PLUGIN_ROOT) {
|
|
30
|
+
paths.push(...await syncPolicyBlocks({ cwd, file: "AGENTS.md", block: blocks.plain }).catch(() => []));
|
|
31
|
+
try {
|
|
32
|
+
const { retireCodexSkill, syncCodexSkill } = await import("../../lib/codex.mjs");
|
|
33
|
+
if (isCodexSurface(env)) {
|
|
34
|
+
// Running as the Codex plugin, which ships the policy skill itself:
|
|
35
|
+
// a user-level copy is now a duplicate (see retireCodexSkill).
|
|
36
|
+
const { removed, backups } = await retireCodexSkill({ block: blocks.plain });
|
|
37
|
+
paths.push(...removed.map((dir) => `${dir} (duplicate removed: the plugin ships this skill)`));
|
|
38
|
+
paths.push(...backups.map((file) => `${file} (the differing copy, kept)`));
|
|
39
|
+
} else {
|
|
40
|
+
const skill = await syncCodexSkill({ block: blocks.plain });
|
|
41
|
+
if (skill.action === "updated") paths.push(skill.path);
|
|
42
|
+
}
|
|
43
|
+
} catch { /* skill dir unwritable — AGENTS.md sync still counts */ }
|
|
44
|
+
try {
|
|
45
|
+
const { syncCursorRules } = await import("../../lib/cursor.mjs");
|
|
46
|
+
paths.push(...await syncCursorRules({ cwd, block: blocks.plain }));
|
|
47
|
+
} catch { /* same: a rule we cannot write never blocks the session */ }
|
|
48
|
+
}
|
|
49
|
+
return { paths, origin: blocks.origin };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Published workspace skills (consolidated kind=skill) as skill files of this
|
|
53
|
+
// client. Here and not per prompt: the client lists skills at session start.
|
|
54
|
+
export async function syncSkills(cwd = process.cwd(), env = process.env) {
|
|
55
|
+
try {
|
|
56
|
+
const { syncKnowledgeSkills } = await import("../../lib/knowledge-skills.mjs");
|
|
57
|
+
return await syncKnowledgeSkills({ cwd, env });
|
|
58
|
+
} catch {
|
|
59
|
+
return { written: [], removed: [] };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function main() {
|
|
64
|
+
const [update, { paths: synced, origin }, skills] = await Promise.all([
|
|
65
|
+
checkForUpdate({ current: VERSION }),
|
|
66
|
+
syncPolicy(),
|
|
67
|
+
syncSkills(),
|
|
68
|
+
]);
|
|
69
|
+
const syncNote = synced.length
|
|
70
|
+
? `[mcpbox] Policy block refreshed to ${origin}: ${synced.join(", ")}\n`
|
|
71
|
+
: "";
|
|
72
|
+
// The user sees what we wrote into their files, not just the model.
|
|
73
|
+
const notices = [
|
|
74
|
+
update?.outdated
|
|
75
|
+
? updateNotice(update.current, update.latest, isCodexSurface() ? "codex" : "claude")
|
|
76
|
+
: null,
|
|
77
|
+
synced.length ? `mcpbox: policy block refreshed to ${origin} in ${synced.join(", ")}` : null,
|
|
78
|
+
skills.written.length || skills.removed.length
|
|
79
|
+
? `mcpbox: workspace skills ${[
|
|
80
|
+
skills.written.length ? `written ${skills.written.join(", ")}` : "",
|
|
81
|
+
skills.removed.length ? `removed ${skills.removed.join(", ")}` : "",
|
|
82
|
+
].filter(Boolean).join("; ")}`
|
|
83
|
+
: null,
|
|
84
|
+
].filter(Boolean);
|
|
85
|
+
const systemMessage = notices.length ? notices.join("\n") : undefined;
|
|
86
|
+
|
|
87
|
+
writeHookOutput("SessionStart", syncNote, { systemMessage });
|
|
88
|
+
process.exit(0);
|
|
89
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Stop hook: do not let the agent end a session that leaves daruma tasks it
|
|
2
|
+
// took in this session (claim, set_status in_progress) open (todo /
|
|
3
|
+
// in_progress) without settling them. Agents claimed tasks and simply stopped,
|
|
4
|
+
// so the tasks stayed claimed with nobody working on them and nobody knowing
|
|
5
|
+
// where they stood. Creating tasks or commenting on them takes nothing.
|
|
6
|
+
//
|
|
7
|
+
// Only what PostToolUse recorded for this session (successful claims, clears
|
|
8
|
+
// and writes) establishes ownership; unknown sessions stay silent. The .stop
|
|
9
|
+
// file caps the gate at MAX_STOP_CYCLES reminders per pending set (see
|
|
10
|
+
// stopDecision and pendingTasks).
|
|
11
|
+
|
|
12
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
13
|
+
|
|
14
|
+
import { callCloudTool, readCredentials } from "../../lib/cloud-knowledge.mjs";
|
|
15
|
+
import { readStdin, sessionMarker } from "../../lib/hook-input.mjs";
|
|
16
|
+
import {
|
|
17
|
+
appendRecords, gateCandidates, readRecords, reconcileClaims, sessionIdOf, stopDecision, stopOutput, surfaceOf,
|
|
18
|
+
validClaims,
|
|
19
|
+
} from "../../lib/session-gate.mjs";
|
|
20
|
+
|
|
21
|
+
export { stopDecision };
|
|
22
|
+
|
|
23
|
+
// Aborted fetch connections can outlive main: hooks/bootstrap.mjs exits once
|
|
24
|
+
// the decision is flushed.
|
|
25
|
+
export const exitAfterMain = true;
|
|
26
|
+
|
|
27
|
+
export async function main() {
|
|
28
|
+
let payload = null;
|
|
29
|
+
try {
|
|
30
|
+
payload = JSON.parse(await readStdin());
|
|
31
|
+
} catch {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const sessionId = sessionIdOf(payload);
|
|
35
|
+
if (!sessionId) return;
|
|
36
|
+
const claimed = validClaims(await readRecords(sessionId, "claims"));
|
|
37
|
+
const tracked = await readRecords(sessionId, "tracked");
|
|
38
|
+
const ids = gateCandidates({ claimed, tracked });
|
|
39
|
+
if (!ids.length) return;
|
|
40
|
+
const cleared = await readRecords(sessionId, "cleared");
|
|
41
|
+
const creds = await readCredentials();
|
|
42
|
+
if (!creds) return;
|
|
43
|
+
const tasks = await Promise.all(ids.map((id) => callCloudTool(
|
|
44
|
+
"daruma_get", { id }, { creds, timeoutMs: 3000 },
|
|
45
|
+
).catch(() => null)));
|
|
46
|
+
// Keep the claim projection honest: what the server no longer shows as this
|
|
47
|
+
// claim stops counting for the next prompt and session start.
|
|
48
|
+
await appendRecords(sessionId, "cleared", reconcileClaims(tasks, claimed)).catch(() => {});
|
|
49
|
+
const stateFile = `${sessionMarker(sessionId)}.stop`;
|
|
50
|
+
const cycles = await readFile(stateFile, "utf8").then(JSON.parse).catch(() => ({ count: 0, ids: [] }));
|
|
51
|
+
// Claude/Codex/Kimi say stop_hook_active; Cursor counts loop_count instead.
|
|
52
|
+
const continuing = payload.stop_hook_active === true || Number(payload.loop_count) > 0;
|
|
53
|
+
const decision = stopDecision(tasks, { claimed, tracked, cleared }, cycles, continuing);
|
|
54
|
+
if (decision.block) {
|
|
55
|
+
try {
|
|
56
|
+
await writeFile(stateFile, `${JSON.stringify(decision.state)}\n`, { mode: 0o600 });
|
|
57
|
+
} catch {
|
|
58
|
+
// No record means the next stop could block again forever: do not block.
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const out = stopOutput(surfaceOf(), decision);
|
|
63
|
+
if (out) process.stdout.write(`${JSON.stringify(out)}\n`);
|
|
64
|
+
}
|