@mcpbox/mcpbox-claude 0.1.26 → 0.1.28

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.
@@ -1,192 +1,74 @@
1
1
  #!/usr/bin/env node
2
- // SessionStart hook: query the mcpbox tracker and print a compact summary of
3
- // open tasks so Claude sees them at the top of every fresh session.
4
- //
5
- // Output goes to stdout — Claude Code injects it as a <system-reminder>.
6
- // Exit 0 always so an mcpbox outage never blocks the session from opening.
7
- //
8
- // Fetch path: spawns the local `daruma` binary in stdio MCP mode (same tracker
9
- // tools the mcpbox server exposes). Cloud-only setups without the local binary
10
- // silently no-op (exit 0) — the /mcpbox:tasks command still works on demand.
11
- // ponytail: stdio-only fetch; add an HTTP+token path for cloud-only if the
12
- // silent no-op proves too quiet in practice.
13
- //
14
- // Environment variables:
15
- // MCPBOX_MCP_CMD — command to start the stdio MCP server (default: "daruma")
16
- // MCPBOX_MCP_ARGS — space-separated extra args (default: "mcp serve")
17
- // MCPBOX_SCOPE — optional project_scope path filter
2
+ // SessionStart refreshes policy and update notices; task selection is explicit.
18
3
 
19
4
  import { isCodexSurface, writeHookOutput } from "../lib/hook-output.mjs";
20
- import { MCPClient } from "../lib/mcp-client.mjs";
21
- import { BLOCK_BODY_PLAIN, syncPolicyBlocks } from "../lib/policy.mjs";
22
- import { checkForUpdate, updateNotice } from "../lib/update-check.mjs";
5
+ import { syncPolicyBlocks } from "../lib/policy.mjs";
6
+ import { checkForUpdate, policyBlocks, updateNotice } from "../lib/update-check.mjs";
23
7
  import { VERSION } from "../lib/version.mjs";
24
8
  import { pathToFileURL } from "node:url";
25
9
 
26
- const TIMEOUT_MS = 12_000;
27
- const MAX_TASKS = 15;
10
+ // Block text to write: the server's copy, else the baked text (see policyBlocks).
11
+ export { policyBlocks };
28
12
 
29
- const STATUS_EMOJI = {
30
- inbox: "📥",
31
- todo: "⬜",
32
- in_progress: "🟢",
33
- in_review: "🔍",
34
- done: "✅",
35
- cancelled: "🚫",
36
- };
37
-
38
- function emoji(status) {
39
- return STATUS_EMOJI[status] ?? "❓";
40
- }
41
-
42
- function truncate(str, len) {
43
- if (!str) return "";
44
- return str.length > len ? str.slice(0, len - 1) + "…" : str;
45
- }
46
-
47
- function formatTask(t) {
48
- const e = emoji(t.status ?? "");
49
- const pri = t.priority ? `p${t.priority}` : " ";
50
- const title = truncate(t.title ?? t.subject ?? "(no title)", 60);
51
- return ` ${e} [${pri}] ${title}`;
52
- }
53
-
54
- async function fetchSummary() {
55
- const cmd = process.env.MCPBOX_MCP_CMD ?? "daruma";
56
- const extraArgs = process.env.MCPBOX_MCP_ARGS ?? "mcp serve";
57
- const args = extraArgs.trim() ? extraArgs.trim().split(/\s+/) : ["mcp", "serve"];
58
- const scope = process.env.MCPBOX_SCOPE;
59
-
60
- const client = new MCPClient();
61
- const timer = setTimeout(() => {
62
- client.stop().catch(() => {});
63
- }, TIMEOUT_MS);
64
-
65
- try {
66
- await client.start(cmd, args, { stderrLog: null });
67
- await client.initialize();
68
-
69
- let projectId = null;
70
- let projectTitle = null;
71
- try {
72
- const wsResult = await client.callTool("daruma_workspace_info", {});
73
- const ws = wsResult.parsed ?? {};
74
- projectId = ws.default_project ?? ws.defaultProject ?? null;
75
- projectTitle = ws.project_title ?? ws.title ?? null;
76
- } catch { /* no workspace info — continue without project filter */ }
77
-
78
- const listArgs = {
79
- status: "active",
80
- limit: MAX_TASKS + 1,
81
- };
82
- if (projectId) listArgs.project_id = projectId;
83
- if (!projectId && scope) listArgs.project_scope = scope;
84
-
85
- const listResult = await client.callTool("daruma_list", listArgs);
86
- const raw = listResult.parsed ?? listResult.text;
87
- const tasks = Array.isArray(raw)
88
- ? raw
89
- : Array.isArray(raw?.tasks)
90
- ? raw.tasks
91
- : Array.isArray(raw?.items)
92
- ? raw.items
93
- : [];
94
-
95
- await client.stop();
96
- clearTimeout(timer);
97
- return { tasks, projectTitle, projectId };
98
- } catch (err) {
99
- clearTimeout(timer);
100
- try { await client.stop(); } catch { /* ignore */ }
101
- throw err;
102
- }
103
- }
104
-
105
- // Bring the policy blocks already installed around cwd up to this plugin
106
- // version (see syncPolicyBlocks). Failures stay silent: a read-only tree must
13
+ // Bring the policy blocks already installed around cwd up to the server's
14
+ // text (see syncPolicyBlocks). Failures stay silent: a read-only tree must
107
15
  // never block the session. MCPBOX_NO_POLICY_SYNC=1 opts out. Only the plugin
108
16
  // surfaces sync: Kimi runs a copy frozen at kimi-init (no CLAUDE_PLUGIN_ROOT,
109
17
  // no PLUGIN_DATA), whose policy would be stale by construction.
110
18
  export async function syncPolicy(cwd = process.cwd(), env = process.env) {
111
- if (env.MCPBOX_NO_POLICY_SYNC) return [];
19
+ if (env.MCPBOX_NO_POLICY_SYNC) return { paths: [], origin: null };
20
+ if (!env.CLAUDE_PLUGIN_ROOT && !isCodexSurface(env)) return { paths: [], origin: null };
21
+ const blocks = await policyBlocks();
112
22
  const paths = [];
113
23
  // Codex has no hooks of its own (.codex-plugin declares none), so any plugin
114
24
  // surface refreshes the Codex carriers too: AGENTS.md up the tree, plus the
115
25
  // user-level SKILL.md — refreshed from Claude, retired from the Codex plugin.
26
+ // Cursor rules up the tree likewise: Cursor runs no hook of this plugin.
27
+ // Every plain carrier gets the same text as AGENTS.md.
116
28
  if (env.CLAUDE_PLUGIN_ROOT && !isCodexSurface(env)) {
117
- paths.push(...await syncPolicyBlocks({ cwd }).catch(() => []));
29
+ paths.push(...await syncPolicyBlocks({ cwd, block: blocks.claude }).catch(() => []));
118
30
  }
119
31
  if (isCodexSurface(env) || env.CLAUDE_PLUGIN_ROOT) {
120
- paths.push(...await syncPolicyBlocks({ cwd, file: "AGENTS.md", block: BLOCK_BODY_PLAIN }).catch(() => []));
32
+ paths.push(...await syncPolicyBlocks({ cwd, file: "AGENTS.md", block: blocks.plain }).catch(() => []));
121
33
  try {
122
34
  const { retireCodexSkill, syncCodexSkill } = await import("../lib/codex.mjs");
123
35
  if (isCodexSurface(env)) {
124
36
  // Running as the Codex plugin, which ships the policy skill itself:
125
37
  // a user-level copy is now a duplicate (see retireCodexSkill).
126
- const { removed, backups } = await retireCodexSkill();
38
+ const { removed, backups } = await retireCodexSkill({ block: blocks.plain });
127
39
  paths.push(...removed.map((dir) => `${dir} (duplicate removed: the plugin ships this skill)`));
128
40
  paths.push(...backups.map((file) => `${file} (the differing copy, kept)`));
129
41
  } else {
130
- const skill = await syncCodexSkill();
42
+ const skill = await syncCodexSkill({ block: blocks.plain });
131
43
  if (skill.action === "updated") paths.push(skill.path);
132
44
  }
133
45
  } catch { /* skill dir unwritable — AGENTS.md sync still counts */ }
46
+ try {
47
+ const { syncCursorRules } = await import("../lib/cursor.mjs");
48
+ paths.push(...await syncCursorRules({ cwd, block: blocks.plain }));
49
+ } catch { /* same: a rule we cannot write never blocks the session */ }
134
50
  }
135
- return paths;
51
+ return { paths, origin: blocks.origin };
136
52
  }
137
53
 
138
54
  export async function main() {
139
- const [data, update, synced] = await Promise.all([
140
- fetchSummary().catch((err) => {
141
- if (process.env.MCPBOX_DEBUG) {
142
- process.stderr.write(`[mcpbox-claude/session-start] error: ${err?.message ?? err}\n`);
143
- }
144
- return null;
145
- }),
55
+ const [update, { paths: synced, origin }] = await Promise.all([
146
56
  checkForUpdate({ current: VERSION }),
147
57
  syncPolicy(),
148
58
  ]);
149
59
  const syncNote = synced.length
150
- ? `[mcpbox] Policy block refreshed to plugin ${VERSION}: ${synced.join(", ")}\n`
60
+ ? `[mcpbox] Policy block refreshed to ${origin}: ${synced.join(", ")}\n`
151
61
  : "";
152
62
  // The user sees what we wrote into their files, not just the model.
153
63
  const notices = [
154
64
  update?.outdated
155
65
  ? updateNotice(update.current, update.latest, isCodexSurface() ? "codex" : "claude")
156
66
  : null,
157
- synced.length ? `mcpbox: policy block refreshed to ${VERSION} in ${synced.join(", ")}` : null,
67
+ synced.length ? `mcpbox: policy block refreshed to ${origin} in ${synced.join(", ")}` : null,
158
68
  ].filter(Boolean);
159
69
  const systemMessage = notices.length ? notices.join("\n") : undefined;
160
70
 
161
- if (!data) {
162
- writeHookOutput("SessionStart", syncNote, { systemMessage });
163
- process.exit(0);
164
- }
165
-
166
- const { tasks, projectTitle } = data;
167
-
168
- if (!tasks || tasks.length === 0) {
169
- writeHookOutput(
170
- "SessionStart",
171
- syncNote + "[mcpbox] No open tasks — run /mcpbox:tasks to verify, or /mcpbox:pipeline-run \"<idea>\" to open a maturity run.",
172
- { systemMessage },
173
- );
174
- process.exit(0);
175
- }
176
-
177
- const shown = tasks.slice(0, MAX_TASKS);
178
- const extra = tasks.length > MAX_TASKS ? tasks.length - MAX_TASKS : 0;
179
- const count = tasks.length > MAX_TASKS ? MAX_TASKS + "+" : tasks.length;
180
- const plural = tasks.length !== 1 ? "s" : "";
181
- const header = projectTitle
182
- ? `[mcpbox] ${count} open task${plural} in "${projectTitle}":`
183
- : `[mcpbox] ${count} open task${plural}:`;
184
-
185
- const lines = [header, ...shown.map(formatTask)];
186
- if (extra > 0) lines.push(` …and ${extra} more — /mcpbox:tasks for full list`);
187
- lines.push("→ /mcpbox:next to claim the next task | /mcpbox:status for server + pipeline health | raw idea: /mcpbox:pipeline-run");
188
-
189
- writeHookOutput("SessionStart", syncNote + lines.join("\n"), { systemMessage });
71
+ writeHookOutput("SessionStart", syncNote, { systemMessage });
190
72
  process.exit(0);
191
73
  }
192
74
 
package/hooks/stop.mjs CHANGED
@@ -1,63 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  // Stop hook: do not let the agent end a session that leaves daruma tasks it
3
- // took in this session sitting in in_progress. Agents claimed tasks and simply
4
- // stopped, so the tasks stayed claimed with nobody working on them.
3
+ // took or wrote to in this session open (todo / in_progress) without an
4
+ // outcome comment. Agents claimed tasks and simply stopped, so the tasks stayed
5
+ // claimed with nobody working on them and nobody knowing where they stood.
5
6
  //
6
- // Session start = mtime of the marker UserPromptSubmit writes on the first
7
- // prompt. The hook asks the cloud MCP (paired bearer, `mcpbox-claude login`)
8
- // for in_progress tasks under the cwd and blocks once per new task id with
9
- // `{"decision":"block","reason"}` — the Stop contract of Claude Code and
10
- // Codex. No session, no pairing, a slow or failing server: silent exit 0 —
11
- // this hook must never break a stop.
12
- //
13
- // Loop guard on every surface, not only where stop_hook_active exists: the
14
- // `<marker>.stop` file keeps the ids already blocked on, so the same tasks
15
- // never block twice.
7
+ // Only what PostToolUse recorded for this session (successful claims and
8
+ // writes) establishes ownership; unknown sessions stay silent. The .stop file
9
+ // caps the gate at MAX_STOP_CYCLES reminders per pending set (see stopDecision).
16
10
 
17
- import { readFile, stat, writeFile } from "node:fs/promises";
11
+ import { readFile, writeFile } from "node:fs/promises";
18
12
  import { pathToFileURL } from "node:url";
19
13
 
20
14
  import { callCloudTool, readCredentials } from "../lib/cloud-knowledge.mjs";
21
15
  import { readStdin, sessionMarker } from "../lib/hook-input.mjs";
16
+ import { readRecords, sessionIdOf, stopDecision, stopOutput, surfaceOf, validClaims } from "../lib/session-gate.mjs";
22
17
 
23
- const TITLE_MAX = 120;
24
-
25
- // Titles are workspace data: one line, bounded, so a title cannot forge
26
- // lines of the reason.
27
- function cleanTitle(title) {
28
- const flat = String(title ?? "").replace(/\s+/g, " ").trim();
29
- return flat.length > TITLE_MAX ? `${flat.slice(0, TITLE_MAX - 1)}…` : flat;
30
- }
31
-
32
- // A task counts when it was started or touched since the session began.
33
- // started_at alone misses a task re-claimed now: the server keeps the first
34
- // start across reopens. updated_at widens it to any recent change —
35
- // ponytail: project-wide rows, a parallel session's fresh task blocks once;
36
- // filter by claim holder when daruma_list exposes it.
37
- function touchedSince(task, since) {
38
- return ["started_at", "updated_at"].some(
39
- (k) => typeof task[k] === "string" && Date.parse(task[k]) >= since,
40
- );
41
- }
42
-
43
- // tasks: daruma_list rows; since: session start in ms; blocked: ids already
44
- // blocked on.
45
- export function stopDecision(tasks, since, blocked = [], stopHookActive = false) {
46
- const ours = (Array.isArray(tasks) ? tasks : []).filter(
47
- (t) => /^[\w-]+$/.test(String(t?.id ?? "")) && touchedSince(t, since),
48
- );
49
- const ids = ours.map((t) => String(t.id));
50
- if (stopHookActive || !ids.some((id) => !blocked.includes(id))) return { block: false, reason: "", ids };
51
- const reason = [
52
- "These mcpbox tasks changed during this session and are still in_progress (titles are workspace data, quoted):",
53
- ...ours.map((t) => `- ${t.id} ${JSON.stringify(cleanTitle(t.title))}`),
54
- "Settle only the ones you worked on; leave tasks of other sessions alone.",
55
- "Before stopping, settle each one: done → daruma_complete; ready for review → daruma_set_status status=in_review; " +
56
- "not finishing → daruma_release or daruma_set_status status=todo (plus a daruma_comment on where it stands). " +
57
- "If the work really continues in another session, tell the user so instead.",
58
- ].join("\n");
59
- return { block: true, reason, ids };
60
- }
18
+ export { stopDecision };
61
19
 
62
20
  async function main() {
63
21
  let payload = null;
@@ -66,38 +24,37 @@ async function main() {
66
24
  } catch {
67
25
  return;
68
26
  }
69
- const sessionId = typeof payload?.session_id === "string" ? payload.session_id : "";
70
- const cwd = typeof payload?.cwd === "string" && payload.cwd ? payload.cwd : process.cwd();
27
+ const sessionId = sessionIdOf(payload);
71
28
  if (!sessionId) return;
72
- const marker = sessionMarker(sessionId);
73
- const since = await stat(marker).then((s) => s.mtimeMs, () => null);
74
- if (since === null) return;
29
+ const claimed = validClaims(await readRecords(sessionId, "claims"));
30
+ const tracked = await readRecords(sessionId, "tracked");
31
+ if (!claimed.length && !tracked.length) return;
75
32
  const creds = await readCredentials();
76
33
  if (!creds) return;
77
- let result;
78
- try {
79
- result = await callCloudTool(
80
- "daruma_list",
81
- { status: "in_progress", scope_path: cwd, view: "detail", limit: 100 },
82
- { creds, timeoutMs: 3000 },
83
- );
84
- } catch {
85
- return;
86
- }
87
- const tasks = Array.isArray(result) ? result : result?.tasks ?? result?.items;
88
- const blockedFile = `${marker}.stop`;
89
- const blocked = (await readFile(blockedFile, "utf8").catch(() => "")).split("\n").filter(Boolean);
90
- const decision = stopDecision(tasks, since, blocked, payload.stop_hook_active === true);
91
- if (!decision.block) return;
92
- try {
93
- await writeFile(blockedFile, [...new Set([...blocked, ...decision.ids])].join("\n") + "\n");
94
- } catch {
95
- // No record means the next stop could block again forever: do not block.
96
- return;
34
+ const ids = [...new Set([...claimed, ...tracked].map((r) => r.task_id))];
35
+ const tasks = await Promise.all(ids.map((id) => callCloudTool(
36
+ "daruma_get", { id }, { creds, timeoutMs: 3000 },
37
+ ).catch(() => null)));
38
+ const stateFile = `${sessionMarker(sessionId)}.stop`;
39
+ const cycles = await readFile(stateFile, "utf8").then(JSON.parse).catch(() => ({ count: 0, ids: [] }));
40
+ // Claude/Codex/Kimi say stop_hook_active; Cursor counts loop_count instead.
41
+ const continuing = payload.stop_hook_active === true || Number(payload.loop_count) > 0;
42
+ const decision = stopDecision(tasks, { claimed, tracked }, cycles, continuing);
43
+ if (decision.block) {
44
+ try {
45
+ await writeFile(stateFile, `${JSON.stringify(decision.state)}\n`, { mode: 0o600 });
46
+ } catch {
47
+ // No record means the next stop could block again forever: do not block.
48
+ return;
49
+ }
97
50
  }
98
- process.stdout.write(`${JSON.stringify({ decision: "block", reason: decision.reason })}\n`);
51
+ const out = stopOutput(surfaceOf(), decision);
52
+ if (out) process.stdout.write(`${JSON.stringify(out)}\n`);
99
53
  }
100
54
 
101
55
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
102
- main().catch(() => {});
56
+ main().catch(() => {}).finally(() => {
57
+ // Aborted fetch connections can outlive main; flush the decision before exiting.
58
+ process.stdout.write("", () => process.exit(0));
59
+ });
103
60
  }
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ // PostToolUse: record successful claims, and the tasks this session wrote to
3
+ // (materialize / set_status / comment), never tasks merely mentioned or read.
4
+ // Same script on every surface; Cursor feeds it afterMCPExecution.
5
+ import { pathToFileURL } from "node:url";
6
+ import { readStdin } from "../lib/hook-input.mjs";
7
+ import { appendRecords, sessionIdOf, toolResultOf, trackedTasks } from "../lib/session-gate.mjs";
8
+
9
+ export { trackedTasks };
10
+
11
+ export function claimedTask(payload) {
12
+ if (!/(?:^|__|[.:/])daruma_(?:plan_drain_next|ready_drain|claim)$/.test(payload?.tool_name ?? "")) return null;
13
+ const result = toolResultOf(payload);
14
+ if (!result) return null;
15
+ const claim = result.claim ?? (result.data?.acquired === true ? result.data : null);
16
+ if (!claim) return null;
17
+ const task_id = result.task_id ?? claim.task_id;
18
+ const record = { task_id, claim_id: claim.claim_id, agent_id: claim.agent_id };
19
+ return Object.values(record).every((id) => typeof id === "string" && /^[\w-]+$/.test(id)) ? record : null;
20
+ }
21
+
22
+ async function main() {
23
+ const payload = JSON.parse(await readStdin());
24
+ const sessionId = sessionIdOf(payload);
25
+ if (!sessionId) return;
26
+ const id = claimedTask(payload);
27
+ await appendRecords(sessionId, "claims", id ? [id] : []);
28
+ await appendRecords(sessionId, "tracked", trackedTasks(payload));
29
+ }
30
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
31
+ main().catch(() => {});
32
+ }
package/lib/codex.mjs CHANGED
@@ -14,9 +14,11 @@
14
14
  // (scripts/generate-codex-skills.mjs), and a plugin session retires the
15
15
  // global copy (retireCodexSkill) so the policy is not loaded twice.
16
16
  //
17
- // The policy body is BLOCK_BODY_PLAIN from lib/policy.mjs — one source of
18
- // truth shared across CLAUDE.md / AGENTS.md / .cursor/rules, minus the
19
- // Claude-only slash commands this surface cannot run.
17
+ // The policy body is the plain surface's text — the server's copy when this
18
+ // machine holds one (policyBlocks in lib/update-check.mjs), else
19
+ // BLOCK_BODY_PLAIN from lib/policy.mjs: one text shared across AGENTS.md /
20
+ // SKILL.md / .cursor/rules, minus the Claude-only slash commands this surface
21
+ // cannot run. `block` defaults to the baked text.
20
22
 
21
23
  import { promises as fs } from "node:fs";
22
24
  import { spawnSync } from "node:child_process";
@@ -52,9 +54,9 @@ function codexConfigPath(configPath) {
52
54
  }
53
55
 
54
56
  // AGENTS.md policy block in the project directory.
55
- export function installCodexPolicy({ projectDir } = {}) {
57
+ export function installCodexPolicy({ projectDir, block = BLOCK_BODY_PLAIN } = {}) {
56
58
  const dir = projectDir ? resolve(projectDir) : process.cwd();
57
- return installManagedBlock({ target: join(dir, "AGENTS.md"), begin: BEGIN, end: END, block: BLOCK_BODY_PLAIN });
59
+ return installManagedBlock({ target: join(dir, "AGENTS.md"), begin: BEGIN, end: END, block });
58
60
  }
59
61
 
60
62
  export function removeCodexPolicy({ projectDir } = {}) {
@@ -92,19 +94,19 @@ export function removeCodexMcp({ configPath } = {}) {
92
94
  // The policy as a Codex skill, so it is reachable from any working directory —
93
95
  // AGENTS.md alone only covers the one the installer ran in. The plugin package
94
96
  // carries it as skills/mcpbox/SKILL.md; codex-init writes the same text to the
95
- // user skill dir for Codex without the plugin.
96
- export function skillText() {
97
+ // user skill dir for Codex without the plugin, in the text AGENTS.md carries.
98
+ export function skillText(block = BLOCK_BODY_PLAIN) {
97
99
  return `---
98
100
  name: mcpbox
99
101
  description: MCPBox/daruma routing policy — read before creating tasks or plans, choosing between the daruma tracker and the maturity pipeline, or when the user mentions the tracker, backlog, plan, decomposition, or \`mcpbox mode\`.
100
102
  ---
101
103
 
102
- ${BLOCK_BODY_PLAIN}`;
104
+ ${block}`;
103
105
  }
104
106
 
105
- export async function installCodexSkill({ codexHome } = {}) {
107
+ export async function installCodexSkill({ codexHome, block } = {}) {
106
108
  const target = join(codexHomeDir(codexHome), "skills", "mcpbox", "SKILL.md");
107
- const body = skillText();
109
+ const body = skillText(block);
108
110
  let before = null;
109
111
  try {
110
112
  before = await fs.readFile(target, "utf8");
@@ -116,9 +118,10 @@ export async function installCodexSkill({ codexHome } = {}) {
116
118
  }
117
119
 
118
120
  // SessionStart counterpart of installCodexSkill: refresh an installed skill
119
- // to the running plugin's policy under the same rules as syncPolicyBlocks
120
- // (never create, never through a link, never roll a newer one back).
121
- export async function syncCodexSkill({ codexHome, dryRun = false } = {}) {
121
+ // to `block` (the text AGENTS.md gets) under the same rules as
122
+ // syncPolicyBlocks (never create, never through a link, never roll a newer
123
+ // one back).
124
+ export async function syncCodexSkill({ codexHome, dryRun = false, block } = {}) {
122
125
  const target = join(codexHomeDir(codexHome), "skills", "mcpbox", "SKILL.md");
123
126
  let before;
124
127
  try {
@@ -128,10 +131,10 @@ export async function syncCodexSkill({ codexHome, dryRun = false } = {}) {
128
131
  } catch {
129
132
  return { action: "missing", path: target };
130
133
  }
131
- if (!blockNeedsSync(before, skillText())) return { action: "unchanged", path: target };
134
+ if (!blockNeedsSync(before, skillText(block))) return { action: "unchanged", path: target };
132
135
  // dryRun (doctor): report the staleness without writing.
133
136
  if (dryRun) return { action: "stale", path: target };
134
- return installCodexSkill({ codexHome });
137
+ return installCodexSkill({ codexHome, block });
135
138
  }
136
139
 
137
140
  export async function removeCodexSkill({ codexHome } = {}) {
@@ -172,7 +175,8 @@ async function safeRetirementRoot(root) {
172
175
  // A copy that differs from the current text (an older release or a hand edit)
173
176
  // is moved to `$CODEX_HOME/mcpbox-skill-backup-*` first, never just deleted.
174
177
  // Anything else (extra files, a foreign or newer skill) stays and is reported.
175
- export async function retireCodexSkill({ codexHome, home = homedir(), dryRun = false } = {}) {
178
+ // A copy in the server's text (`block`, what SessionStart wrote) is current too.
179
+ export async function retireCodexSkill({ codexHome, home = homedir(), dryRun = false, block } = {}) {
176
180
  const codexDir = codexHomeDir(codexHome);
177
181
  const roots = [join(codexDir, "skills", "mcpbox"), join(home, ".agents", "skills", "mcpbox")];
178
182
  const result = { removed: [], backups: [], kept: [] };
@@ -201,8 +205,8 @@ export async function retireCodexSkill({ codexHome, home = homedir(), dryRun = f
201
205
  const lf = text?.replace(/\r\n/g, "\n") ?? "";
202
206
  // blockNeedsSync is false for the current text and for a newer release;
203
207
  // only the former is ours to drop.
204
- const current = normalizeSkill(lf) === normalizeSkill(skillText());
205
- if (!MANAGED_SKILL_RE.test(lf) || (!current && !blockNeedsSync(lf, skillText()))) {
208
+ const current = [skillText(), skillText(block)].some((text) => normalizeSkill(lf) === normalizeSkill(text));
209
+ if (!MANAGED_SKILL_RE.test(lf) || (!current && !blockNeedsSync(lf, skillText(block)))) {
206
210
  result.kept.push(dir);
207
211
  continue;
208
212
  }
@@ -259,10 +263,10 @@ export async function removeCodexPrompts({ codexHome } = {}) {
259
263
  }
260
264
 
261
265
  // Every surface at once (what `mcpbox-claude codex-init` calls).
262
- export async function installCodex({ projectDir, codexHome } = {}) {
263
- const policy = await installCodexPolicy({ projectDir });
266
+ export async function installCodex({ projectDir, codexHome, block } = {}) {
267
+ const policy = await installCodexPolicy({ projectDir, block });
264
268
  const mcp = await installCodexMcp();
265
- const skill = await installCodexSkill({ codexHome });
269
+ const skill = await installCodexSkill({ codexHome, block });
266
270
  return { policy, mcp, skill };
267
271
  }
268
272
 
package/lib/cursor.mjs CHANGED
@@ -5,13 +5,18 @@
5
5
  // 2. `.cursor/mcp.json` — upsert the `mcpbox` HTTP server entry, leaving any
6
6
  // other servers the user configured untouched.
7
7
  //
8
- // Rule body is BLOCK_BODY_PLAIN from lib/policy.mjs — the shared source of
9
- // truth, minus the Claude-only slash commands this surface cannot run.
8
+ // Rule body is the plain surface's text — the server's copy when this machine
9
+ // holds one (policyBlocks in lib/update-check.mjs), else BLOCK_BODY_PLAIN from
10
+ // lib/policy.mjs: the text AGENTS.md carries, minus the Claude-only slash
11
+ // commands this surface cannot run. A Claude or Codex session start refreshes
12
+ // installed rules (syncCursorRules), since Cursor runs no hook of ours there.
10
13
 
11
14
  import { promises as fs } from "node:fs";
15
+ import { homedir } from "node:os";
12
16
  import { dirname, join, resolve } from "node:path";
13
17
  import { fileURLToPath } from "node:url";
14
- import { BLOCK_BODY_PLAIN, mcpUrl } from "./policy.mjs";
18
+ import { BLOCK_BODY_PLAIN, blockNeedsSync, mcpUrl } from "./policy.mjs";
19
+ import { policyCachePath } from "./update-check.mjs";
15
20
 
16
21
  const RULE_FRONTMATTER = `---
17
22
  description: mcpbox is the task tracker — plans and tasks go to mcpbox, not chat or files.
@@ -21,8 +26,8 @@ alwaysApply: true
21
26
 
22
27
  `;
23
28
 
24
- function ruleContent() {
25
- return RULE_FRONTMATTER + BLOCK_BODY_PLAIN;
29
+ export function ruleContent(block = BLOCK_BODY_PLAIN) {
30
+ return RULE_FRONTMATTER + block;
26
31
  }
27
32
 
28
33
  function rulePath(projectDir) {
@@ -70,9 +75,9 @@ export async function removeCursorModeCommand({ projectDir } = {}) {
70
75
  }
71
76
 
72
77
  // `.cursor/rules/mcpbox-policy.mdc` — whole-file managed rule.
73
- export async function installCursorRule({ projectDir } = {}) {
78
+ export async function installCursorRule({ projectDir, block } = {}) {
74
79
  const target = rulePath(projectDir);
75
- const content = ruleContent();
80
+ const content = ruleContent(block);
76
81
  await fs.mkdir(dirname(target), { recursive: true });
77
82
  let existing = null;
78
83
  try {
@@ -85,6 +90,33 @@ export async function installCursorRule({ projectDir } = {}) {
85
90
  return { action: existing === null ? "installed" : "updated", path: target };
86
91
  }
87
92
 
93
+ // SessionStart counterpart of installCursorRule: bring the rules installed in
94
+ // cwd and its ancestors up to `block`, under the rules of syncPolicyBlocks —
95
+ // never create, never through a link, never roll a newer one back. dryRun
96
+ // (doctor) lists the stale ones without writing. `stopAt` (tests) ends the walk.
97
+ export async function syncCursorRules({ cwd = process.cwd(), block, dryRun = false, stopAt } = {}) {
98
+ const content = ruleContent(block);
99
+ const updated = [];
100
+ for (let dir = resolve(cwd); ; dir = dirname(dir)) {
101
+ const target = rulePath(dir);
102
+ try {
103
+ const stat = await fs.lstat(target);
104
+ if (stat.isFile() && stat.nlink === 1 && await fs.realpath(dirname(target)) === dirname(target)) {
105
+ const before = await fs.readFile(target, "utf8");
106
+ const normalized = before.replace(/\r\n/g, "\n");
107
+ const managed = normalized.startsWith(RULE_FRONTMATTER) &&
108
+ /^<!-- mcpbox-claude:policy-version \S+ -->\n/.test(normalized.slice(RULE_FRONTMATTER.length));
109
+ if (managed && blockNeedsSync(before, content)) {
110
+ if (!dryRun) await fs.writeFile(target, content);
111
+ updated.push(target);
112
+ }
113
+ }
114
+ } catch { /* no rule here, or unwritable — keep walking */ }
115
+ if ((stopAt && dir === resolve(stopAt)) || dir === dirname(dir)) break;
116
+ }
117
+ return updated;
118
+ }
119
+
88
120
  export async function removeCursorRule({ projectDir } = {}) {
89
121
  const target = rulePath(projectDir);
90
122
  try {
@@ -142,7 +174,9 @@ export async function removeCursorMcp({ projectDir } = {}) {
142
174
  // User-level policy. Cursor reads no rule files from ~/.cursor/rules (User
143
175
  // Rules live only in its settings UI), so a global install injects the policy
144
176
  // through a sessionStart hook in ~/.cursor/hooks.json instead. The script is
145
- // self-contained: the npx cache that ran us is ephemeral.
177
+ // self-contained: the npx cache that ran us is ephemeral. It injects the
178
+ // server's text this machine last fetched (the cache a Claude or Codex session
179
+ // start keeps fresh), else the text baked in at install.
146
180
  const SESSION_HOOK_NAME = "mcpbox-session-start.mjs";
147
181
 
148
182
  function sessionHookPaths(homeDir) {
@@ -150,10 +184,16 @@ function sessionHookPaths(homeDir) {
150
184
  return { script: join(root, "hooks", SESSION_HOOK_NAME), config: join(root, "hooks.json") };
151
185
  }
152
186
 
153
- function sessionHookScript() {
187
+ function sessionHookScript(homeDir) {
154
188
  return `// Managed by mcpbox-claude. Injects the MCPBox policy into Cursor sessions.
155
- const BODY = ${JSON.stringify(BLOCK_BODY_PLAIN)};
156
- process.stdout.write(JSON.stringify({ additional_context: BODY }) + "\\n");
189
+ import { readFileSync } from "node:fs";
190
+ const CACHE = ${JSON.stringify(policyCachePath("plain", resolve(homeDir)))};
191
+ let body = ${JSON.stringify(BLOCK_BODY_PLAIN)};
192
+ try {
193
+ const served = JSON.parse(readFileSync(CACHE, "utf8"));
194
+ if (typeof served.etag === "string" && typeof served.body === "string" && served.body.trim()) body = served.body;
195
+ } catch { /* no server copy yet: the baked text */ }
196
+ process.stdout.write(JSON.stringify({ additional_context: body }) + "\\n");
157
197
  `;
158
198
  }
159
199
 
@@ -176,7 +216,7 @@ const isOurHook = (h) => typeof h?.command === "string" && h.command.includes(SE
176
216
 
177
217
  export async function installCursorSessionHook({ homeDir } = {}) {
178
218
  const { script, config } = sessionHookPaths(homeDir);
179
- const content = sessionHookScript();
219
+ const content = sessionHookScript(homeDir ?? homedir());
180
220
  let existingScript = null;
181
221
  try {
182
222
  existingScript = await fs.readFile(script, "utf8");
@@ -219,8 +259,8 @@ export async function removeCursorSessionHook({ homeDir } = {}) {
219
259
  }
220
260
 
221
261
  // Both surfaces at once (what `mcpbox-claude cursor-init` calls).
222
- export async function installCursor({ projectDir } = {}) {
223
- const rule = await installCursorRule({ projectDir });
262
+ export async function installCursor({ projectDir, block } = {}) {
263
+ const rule = await installCursorRule({ projectDir, block });
224
264
  const mcp = await installCursorMcp({ projectDir });
225
265
  const mode = await installCursorModeCommand({ projectDir });
226
266
  return { rule, mcp, mode };