@mcpbox/mcpbox-claude 0.1.26 → 0.1.27

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,7 +1,7 @@
1
1
  {
2
2
  "name": "mcpbox-claude",
3
3
  "description": "MCPBox for Claude Code: the mcpbox task tracker and idea pipeline over one MCP server. Ships /mcpbox:* commands, session hooks, and a managed CLAUDE.md policy that makes mcpbox the default tracker.",
4
- "version": "0.1.26",
4
+ "version": "0.1.27",
5
5
  "author": {
6
6
  "name": "tupical"
7
7
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcpbox",
3
- "version": "0.1.26",
3
+ "version": "0.1.27",
4
4
  "description": "MCPBox for Codex: the mcpbox task tracker and idea pipeline behind one MCP server.",
5
5
  "author": {
6
6
  "name": "tupical"
package/README.md CHANGED
@@ -76,6 +76,34 @@ session context. It never adds a block and never touches text outside the
76
76
  markers; `doctor --json` reports `policy_stale` until it has run. Set
77
77
  `MCPBOX_NO_POLICY_SYNC=1` to keep installed blocks as they are.
78
78
 
79
+ The block text comes from the server, not only from the package: the hook asks
80
+ `GET /v1/policy/claude` and `/v1/policy/plain` (the paired server from
81
+ `login`, else `https://mcpbox.ru`) with `If-None-Match`, so a rule changed on
82
+ the server reaches installed blocks at the next session start; `304` downloads
83
+ nothing. The copy and its ETag live in `~/.agents/mcpbox/policy-<surface>.json`.
84
+ Offline the last copy stays (failures back off for an hour); the text baked into
85
+ the package is written only when no server copy was ever fetched. `doctor`
86
+ shows the ETag and when the copy was fetched and last checked
87
+ (`policy_server` in `--json`). `MCPBOX_NO_POLICY_FETCH=1` keeps the baked text.
88
+ The served bodies are `policy/{claude,plain}.md`, generated from
89
+ `lib/policy.mjs` by `node scripts/generate-policy-snapshot.mjs` — rerun it
90
+ after editing the block text (a test fails on drift).
91
+
92
+ Three carriers, one text, the server wins: every place this package writes the
93
+ policy gets the same server copy. `plain` goes into `AGENTS.md`, the Codex
94
+ user skill `$CODEX_HOME/skills/mcpbox/SKILL.md` and the Cursor rule
95
+ `.cursor/rules/mcpbox-policy.mdc`; the session start refreshes all of them
96
+ (rules and blocks in the working directory and every ancestor up to `/`,
97
+ including `~`; the skill when one is installed), and `doctor` reports a
98
+ stale one (`codex_skill_stale_paths`, `cursor_rule_stale_paths`). The
99
+ `*-init` / `*-policy` / `codex-skill` commands write the copy already on disk
100
+ and never ask the server themselves. The Cursor `sessionStart` hook in
101
+ `~/.cursor/hooks.json` reads `~/.agents/mcpbox/policy-plain.json` each time it
102
+ runs, so it follows the server without a reinstall. Two copies stay baked
103
+ until the next release: the skill shipped inside the Codex plugin package
104
+ (a session of that plugin keeps `AGENTS.md` on the server text) and the
105
+ Kimi hooks frozen at `kimi-init`.
106
+
79
107
  ### Project knowledge in every session
80
108
 
81
109
  Agents answer repo questions right when they have the project's knowledge
@@ -95,6 +123,7 @@ call instead of the text. Knowledge rows arrive
95
123
  marked as workspace data, not instructions. Mode `off` disables both.
96
124
 
97
125
  Paired, the `Stop` hook blocks a stop once per task left `in_progress` that was taken in this session, asking the agent to complete, send to review, or release it.
126
+ If the lookup times out, it exits silently; lingering network connections do not delay process exit. Any blocking response is flushed before exit.
98
127
 
99
128
  A stale version announces itself at session start on Claude, Codex, and Kimi.
100
129
  The Cursor adapter's only hook is the user-level `sessionStart` that carries
@@ -19,7 +19,9 @@ import { homedir } from "node:os";
19
19
  import { fileURLToPath } from "node:url";
20
20
  import { dirname, join, resolve } from "node:path";
21
21
  import { spawnSync } from "node:child_process";
22
- import { installPolicy, removePolicy, policyHierarchy, stalePolicyPaths, competingPolicyPaths, BLOCK_BODY_PLAIN } from "../lib/policy.mjs";
22
+ import { installPolicy, removePolicy, policyHierarchy, stalePolicyPaths, competingPolicyPaths, versionedBlock, BLOCK_BODY, BLOCK_BODY_PLAIN } from "../lib/policy.mjs";
23
+ import { policyBlocks, readPolicyCache } from "../lib/update-check.mjs";
24
+ import { VERSION } from "../lib/version.mjs";
23
25
  import { credentialsPath, login, logout, readCredentials } from "../lib/cloud-knowledge.mjs";
24
26
  import {
25
27
  installCodex,
@@ -40,6 +42,7 @@ import {
40
42
  removeCursorModeCommand,
41
43
  installCursorSessionHook,
42
44
  removeCursorSessionHook,
45
+ syncCursorRules,
43
46
  } from "../lib/cursor.mjs";
44
47
  import { installKimi, removeKimi } from "../lib/kimi.mjs";
45
48
  import { installOpencode, removeOpencode } from "../lib/opencode.mjs";
@@ -112,7 +115,7 @@ const VERB = {
112
115
 
113
116
  async function cmdInit(rest) {
114
117
  const { projectDir } = parseDirFlag(rest);
115
- const r = await installPolicy({ projectDir });
118
+ const r = await installPolicy({ projectDir, block: (await installBlocks()).claude });
116
119
  process.stdout.write(`✓ ${VERB[r.action] ?? r.action} ${r.path}\n`);
117
120
  process.stdout.write("Open Claude Code in this directory to pick it up.\n");
118
121
  }
@@ -123,13 +126,17 @@ async function cmdUninit(rest) {
123
126
  process.stdout.write(`✓ ${VERB[r.action] ?? r.action} ${r.path}\n`);
124
127
  }
125
128
 
129
+ // What an install writes: the server's text this machine last fetched, else
130
+ // the baked one — the text the next session start would sync to anyway.
131
+ const installBlocks = () => policyBlocks({ fetch: false });
132
+
126
133
  function report(r) {
127
134
  process.stdout.write(`✓ ${VERB[r.action] ?? r.action} ${r.path}\n`);
128
135
  }
129
136
 
130
137
  async function cmdCodexInit(rest) {
131
138
  const { projectDir } = parseDirFlag(rest);
132
- const { policy, mcp, skill } = await installCodex({ projectDir });
139
+ const { policy, mcp, skill } = await installCodex({ projectDir, block: (await installBlocks()).plain });
133
140
  report(policy);
134
141
  report(mcp);
135
142
  report(skill);
@@ -164,7 +171,7 @@ async function cmdCursorInit(rest) {
164
171
  report(await installCursorMcp({ projectDir: homedir() }));
165
172
  return;
166
173
  }
167
- const { rule, mcp, mode } = await installCursor({ projectDir });
174
+ const { rule, mcp, mode } = await installCursor({ projectDir, block: (await installBlocks()).plain });
168
175
  report(rule);
169
176
  report(mcp);
170
177
  report(mode);
@@ -219,17 +226,17 @@ async function cmdOpencodeUninit(rest) {
219
226
  // MCP-server wiring and just need the managed policy file dropped.
220
227
  async function cmdCodexPolicy(rest) {
221
228
  const { projectDir } = parseDirFlag(rest);
222
- report(await installCodexPolicy({ projectDir }));
229
+ report(await installCodexPolicy({ projectDir, block: (await installBlocks()).plain }));
223
230
  }
224
231
 
225
232
  // The user-level policy skill alone: `codex-skill` for Codex without the
226
233
  // plugin, `codex-skill-retire` once the plugin (which ships it) is installed.
227
234
  async function cmdCodexSkill() {
228
- report(await installCodexSkill());
235
+ report(await installCodexSkill({ block: (await installBlocks()).plain }));
229
236
  }
230
237
 
231
238
  async function cmdCodexSkillRetire() {
232
- const { removed, backups, kept } = await retireCodexSkill();
239
+ const { removed, backups, kept } = await retireCodexSkill({ block: (await installBlocks()).plain });
233
240
  for (const path of removed) process.stdout.write(`✓ Removed duplicate ${path}\n`);
234
241
  for (const path of backups) process.stdout.write(`✓ Saved the differing copy to ${path}\n`);
235
242
  for (const path of kept) process.stdout.write(`! Left alone (not a copy mcpbox wrote) ${path}\n`);
@@ -239,7 +246,7 @@ async function cmdCodexSkillRetire() {
239
246
  async function cmdCursorPolicy(rest) {
240
247
  const { projectDir } = parseDirFlag(rest);
241
248
  if (isHomeDir(projectDir)) return installCursorHome(homedir());
242
- report(await installCursorRule({ projectDir }));
249
+ report(await installCursorRule({ projectDir, block: (await installBlocks()).plain }));
243
250
  report(await installCursorModeCommand({ projectDir }));
244
251
  }
245
252
 
@@ -289,13 +296,32 @@ async function cmdDoctor(rest) {
289
296
  const policy = hierarchy.present;
290
297
  const mcp = mcpServerPresent();
291
298
  const ready = policy && !hierarchy.duplicate && mcp === true;
299
+ // Which server text this machine holds and when it last asked; blocks are
300
+ // compared with that copy, the baked text only when none was ever fetched.
301
+ const served = {};
302
+ for (const surface of ["claude", "plain"]) {
303
+ const { etag, body, fetchedAt, checkedAt, failedAt } = await readPolicyCache(surface);
304
+ const iso = (t) => (Number.isFinite(t) ? new Date(t).toISOString() : null);
305
+ served[surface] = typeof etag === "string" && typeof body === "string"
306
+ ? { etag, fetched_at: iso(fetchedAt), checked_at: iso(checkedAt), failed_at: iso(failedAt), body }
307
+ : null;
308
+ }
309
+ const claudeBlock = served.claude ? versionedBlock(served.claude.body) : BLOCK_BODY;
310
+ const plainBlock = served.plain ? versionedBlock(served.plain.body) : BLOCK_BODY_PLAIN;
311
+ const policyServer = Object.fromEntries(Object.entries(served).map(([k, v]) => {
312
+ if (!v) return [k, null];
313
+ const { body: _, ...meta } = v;
314
+ return [k, meta];
315
+ }));
292
316
  // Stale is a warning, not NOT READY: the next SessionStart refreshes it.
293
- const stale = await stalePolicyPaths(hierarchy.paths);
317
+ const stale = await stalePolicyPaths(hierarchy.paths, claudeBlock);
294
318
  // Codex carriers (no Codex hooks exist): AGENTS.md up the tree and the user skill.
295
319
  const agents = await policyHierarchy({ projectDir, file: "AGENTS.md" }).catch(() => ({ paths: [] }));
296
- const agentsStale = await stalePolicyPaths(agents.paths, BLOCK_BODY_PLAIN);
297
- const skill = await syncCodexSkill({ dryRun: true }).catch(() => ({ action: "missing" }));
320
+ const agentsStale = await stalePolicyPaths(agents.paths, plainBlock);
321
+ const skill = await syncCodexSkill({ dryRun: true, block: plainBlock }).catch(() => ({ action: "missing" }));
298
322
  const skillStale = skill.action === "stale" ? [skill.path] : [];
323
+ // Cursor rules up the tree carry the same plain text.
324
+ const cursorStale = await syncCursorRules({ cwd: resolve(projectDir ?? process.cwd()), block: plainBlock, dryRun: true });
299
325
  // Also a warning: two policies in one file, one of them from the daruma CLI.
300
326
  const competing = await competingPolicyPaths({ projectDir });
301
327
  // Not required: without it hooks hint at the knowledge instead of loading it.
@@ -312,7 +338,9 @@ async function cmdDoctor(rest) {
312
338
  agents_md_paths: agents.paths,
313
339
  agents_md_stale_paths: agentsStale,
314
340
  codex_skill_stale_paths: skillStale,
341
+ cursor_rule_stale_paths: cursorStale,
315
342
  knowledge_paired: paired,
343
+ policy_server: policyServer,
316
344
  }) + "\n");
317
345
  } else {
318
346
  const mark = (v) => (v === true ? "✓" : v === false ? "✗" : "?");
@@ -320,9 +348,13 @@ async function cmdDoctor(rest) {
320
348
  `mcpbox MCP server: ${mark(mcp)}${mcp === null ? " (claude CLI not found)" : ""}\n` +
321
349
  `CLAUDE.md policy: ${mark(policy)}${hierarchy.duplicate ? " (duplicate managed blocks)" : ""}\n` +
322
350
  hierarchy.paths.map((p) => ` ${p}${stale.includes(p) ? " (stale — the next session start of this plugin version refreshes it)" : ""}\n`).join("") +
351
+ Object.entries(policyServer).map(([surface, meta]) => meta
352
+ ? ` server text (${surface}): ETag ${meta.etag}, fetched ${meta.fetched_at ?? "?"}, checked ${meta.checked_at ?? "?"}${meta.failed_at ? `, last failure ${meta.failed_at}` : ""}\n`
353
+ : ` server text (${surface}): not fetched yet — blocks carry plugin ${VERSION} text\n`).join("") +
323
354
  (agents.paths.length ? `AGENTS.md policy: ✓\n` : "") +
324
355
  agents.paths.map((p) => ` ${p}${agentsStale.includes(p) ? " (stale — run: mcpbox-claude codex-init)" : ""}\n`).join("") +
325
356
  skillStale.map((p) => ` ${p} (stale — run: mcpbox-claude codex-init)\n`).join("") +
357
+ cursorStale.map((p) => ` ${p} (stale — run: mcpbox-claude cursor-init)\n`).join("") +
326
358
  competing.map((p) => ` ! ${p} also holds a daruma CLI policy block — keep one\n`).join("") +
327
359
  `Project knowledge: ${paired ? "✓ paired" : "hint only — run: npx -y @mcpbox/mcpbox-claude login"}\n` +
328
360
  `${ready ? "READY" : "NOT READY — run: npx @mcpbox/mcpbox setup"}\n`
package/commands/next.md CHANGED
@@ -8,11 +8,13 @@ to the user/agent to actually execute it.
8
8
  ## Steps
9
9
 
10
10
  1. Resolve project (`daruma_workspace_info` → `default_project`).
11
- 2. Active plan: `daruma_plan_list` filtered to `status = "active"`, most recent.
11
+ 2. Active plan: `daruma_plan_list` with `status = "active"`, `sort = "updated"`,
12
+ `limit = 1` — the most recently updated plan (the default order is by creation).
12
13
  If none, stop with "no active plan — decided work: `daruma_plan_materialize`; raw idea: `/mcpbox:pipeline-run`".
13
14
  3. `daruma_plan_drain_next` with the plan id. The server atomically picks the next
14
15
  ready (unblocked) task and claims it for this session; it returns null when no
15
- unclaimed ready task remains.
16
+ unclaimed ready task remains. Keep the returned `run_id`: the server opened that
17
+ run for this claim. A null drain already aborted its own run — nothing to close.
16
18
  4. If "no ready task": print the server reason (e.g. "3 tasks blocked by X") and
17
19
  suggest `/mcpbox:plan` to inspect dependencies. Stop.
18
20
  5. Otherwise render the briefing:
@@ -22,6 +24,7 @@ to the user/agent to actually execute it.
22
24
 
23
25
  id: <task_id>
24
26
  plan: <plan_id>
27
+ run: <run_id>
25
28
  priority: <pX>
26
29
  status: 🟢 in_progress
27
30
  ```
@@ -32,7 +35,12 @@ to the user/agent to actually execute it.
32
35
 
33
36
  ```
34
37
  → When done: daruma_complete id=<task_id> [result_summary="<summary>"]
38
+ then daruma_run_complete run_id=<run_id>
35
39
  → On failure: daruma_set_status status=todo comment={ body, kind: "blocker" }
40
+ then daruma_run_abort run_id=<run_id> reason=<reason>
36
41
  ```
37
42
 
43
+ An open run keeps the plan from auto-closing after its last task; the
44
+ `plan_close_blocked_by_run` warning names it in `details.run_id`.
45
+
38
46
  7. Briefing only — do not start executing the task in this command.
package/commands/plan.md CHANGED
@@ -7,19 +7,22 @@ The user invoked `/mcpbox:plan`.
7
7
  ## Steps
8
8
 
9
9
  1. Resolve project (`daruma_workspace_info` → `default_project`).
10
- 2. `daruma_plan_list status="draft,active"`, most recent first.
10
+ 2. `daruma_plan_list status="draft,active" sort="updated" limit=1` — the most recently
11
+ updated plan (the default order is by creation, and its first page can miss it).
11
12
  If none, stop with "no active plan — decided work: `daruma_plan_materialize`; raw idea: `/mcpbox:pipeline-run`".
12
- 3. For the chosen plan, `daruma_plan_get` (single call — do not enumerate the archive).
13
+ 3. For the chosen plan, `daruma_plan_get view="tasks"` (single call — do not enumerate the archive).
14
+ It lists every plan task (done included) with `status`, `priority`, `depends_on` and
15
+ `blocked_by`; the default `progress` view caps each group at five open tasks.
13
16
  4. Render:
14
17
 
15
18
  ```
16
19
  ## <plan title>
17
- goal: <goal>
18
20
  progress: [████░░░░] 4/9 done
19
21
 
20
22
  | # | Status | Pri | Task | Depends on |
21
23
  |---|--------|-----|------|-----------|
22
24
  ```
23
25
 
24
- - Progress bar from done/total; blocked tasks marked ⛔ with their blocker ids.
26
+ - Progress bar from `progress.tasks_done`/`progress.tasks_total`; one row per task in plan order.
27
+ - Tasks with a non-empty `blocked_by` marked ⛔ with those blocker ids.
25
28
  5. Do not call `daruma_plan_list status=completed` (token-heavy). Read-only.
@@ -18,8 +18,8 @@
18
18
 
19
19
  import { isCodexSurface, writeHookOutput } from "../lib/hook-output.mjs";
20
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";
21
+ import { syncPolicyBlocks } from "../lib/policy.mjs";
22
+ import { checkForUpdate, policyBlocks, updateNotice } from "../lib/update-check.mjs";
23
23
  import { VERSION } from "../lib/version.mjs";
24
24
  import { pathToFileURL } from "node:url";
25
25
 
@@ -102,41 +102,52 @@ async function fetchSummary() {
102
102
  }
103
103
  }
104
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
105
+ // Block text to write: the server's copy, else the baked text (see policyBlocks).
106
+ export { policyBlocks };
107
+
108
+ // Bring the policy blocks already installed around cwd up to the server's
109
+ // text (see syncPolicyBlocks). Failures stay silent: a read-only tree must
107
110
  // never block the session. MCPBOX_NO_POLICY_SYNC=1 opts out. Only the plugin
108
111
  // surfaces sync: Kimi runs a copy frozen at kimi-init (no CLAUDE_PLUGIN_ROOT,
109
112
  // no PLUGIN_DATA), whose policy would be stale by construction.
110
113
  export async function syncPolicy(cwd = process.cwd(), env = process.env) {
111
- if (env.MCPBOX_NO_POLICY_SYNC) return [];
114
+ if (env.MCPBOX_NO_POLICY_SYNC) return { paths: [], origin: null };
115
+ if (!env.CLAUDE_PLUGIN_ROOT && !isCodexSurface(env)) return { paths: [], origin: null };
116
+ const blocks = await policyBlocks();
112
117
  const paths = [];
113
118
  // Codex has no hooks of its own (.codex-plugin declares none), so any plugin
114
119
  // surface refreshes the Codex carriers too: AGENTS.md up the tree, plus the
115
120
  // user-level SKILL.md — refreshed from Claude, retired from the Codex plugin.
121
+ // Cursor rules up the tree likewise: Cursor runs no hook of this plugin.
122
+ // Every plain carrier gets the same text as AGENTS.md.
116
123
  if (env.CLAUDE_PLUGIN_ROOT && !isCodexSurface(env)) {
117
- paths.push(...await syncPolicyBlocks({ cwd }).catch(() => []));
124
+ paths.push(...await syncPolicyBlocks({ cwd, block: blocks.claude }).catch(() => []));
118
125
  }
119
126
  if (isCodexSurface(env) || env.CLAUDE_PLUGIN_ROOT) {
120
- paths.push(...await syncPolicyBlocks({ cwd, file: "AGENTS.md", block: BLOCK_BODY_PLAIN }).catch(() => []));
127
+ paths.push(...await syncPolicyBlocks({ cwd, file: "AGENTS.md", block: blocks.plain }).catch(() => []));
121
128
  try {
122
129
  const { retireCodexSkill, syncCodexSkill } = await import("../lib/codex.mjs");
123
130
  if (isCodexSurface(env)) {
124
131
  // Running as the Codex plugin, which ships the policy skill itself:
125
132
  // a user-level copy is now a duplicate (see retireCodexSkill).
126
- const { removed, backups } = await retireCodexSkill();
133
+ const { removed, backups } = await retireCodexSkill({ block: blocks.plain });
127
134
  paths.push(...removed.map((dir) => `${dir} (duplicate removed: the plugin ships this skill)`));
128
135
  paths.push(...backups.map((file) => `${file} (the differing copy, kept)`));
129
136
  } else {
130
- const skill = await syncCodexSkill();
137
+ const skill = await syncCodexSkill({ block: blocks.plain });
131
138
  if (skill.action === "updated") paths.push(skill.path);
132
139
  }
133
140
  } catch { /* skill dir unwritable — AGENTS.md sync still counts */ }
141
+ try {
142
+ const { syncCursorRules } = await import("../lib/cursor.mjs");
143
+ paths.push(...await syncCursorRules({ cwd, block: blocks.plain }));
144
+ } catch { /* same: a rule we cannot write never blocks the session */ }
134
145
  }
135
- return paths;
146
+ return { paths, origin: blocks.origin };
136
147
  }
137
148
 
138
149
  export async function main() {
139
- const [data, update, synced] = await Promise.all([
150
+ const [data, update, { paths: synced, origin }] = await Promise.all([
140
151
  fetchSummary().catch((err) => {
141
152
  if (process.env.MCPBOX_DEBUG) {
142
153
  process.stderr.write(`[mcpbox-claude/session-start] error: ${err?.message ?? err}\n`);
@@ -147,14 +158,14 @@ export async function main() {
147
158
  syncPolicy(),
148
159
  ]);
149
160
  const syncNote = synced.length
150
- ? `[mcpbox] Policy block refreshed to plugin ${VERSION}: ${synced.join(", ")}\n`
161
+ ? `[mcpbox] Policy block refreshed to ${origin}: ${synced.join(", ")}\n`
151
162
  : "";
152
163
  // The user sees what we wrote into their files, not just the model.
153
164
  const notices = [
154
165
  update?.outdated
155
166
  ? updateNotice(update.current, update.latest, isCodexSurface() ? "codex" : "claude")
156
167
  : null,
157
- synced.length ? `mcpbox: policy block refreshed to ${VERSION} in ${synced.join(", ")}` : null,
168
+ synced.length ? `mcpbox: policy block refreshed to ${origin} in ${synced.join(", ")}` : null,
158
169
  ].filter(Boolean);
159
170
  const systemMessage = notices.length ? notices.join("\n") : undefined;
160
171
 
package/hooks/stop.mjs CHANGED
@@ -99,5 +99,8 @@ async function main() {
99
99
  }
100
100
 
101
101
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
102
- main().catch(() => {});
102
+ main().catch(() => {}).finally(() => {
103
+ // Aborted fetch connections can outlive main; flush the decision before exiting.
104
+ process.stdout.write("", () => process.exit(0));
105
+ });
103
106
  }
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 };
package/lib/policy.mjs CHANGED
@@ -27,13 +27,15 @@ tracker. "Daruma", "дарума", "трекер", "tracker", "таск-мене
27
27
  "Составь план", "Распланируй", "make/write/create a plan" — or about to
28
28
  answer with a plan, step list or task breakdown for it, in Plan mode too —
29
29
  first create it with \`daruma_plan_materialize\`, then reply with a short
30
- summary and the plan id; never a plan only as chat text. Set
31
- \`plan.source\` (link to the issue/message, or a short label for a chat
32
- request; never invent links) and, in a git repo, \`plan.git_context.repo\`
33
- and \`plan.git_context.branch\`. A decided GitLab/GitHub/Jira issue, work item
34
- or ticket is the request's source, not a second tracker: materialize it with
35
- \`plan.source.ref\` = its URL, then \`daruma_plan_drain_next\` →
36
- \`daruma_complete\`; decisions go to \`mcpbox_knowledge_write\`.
30
+ summary and the plan id; never a plan only as chat text. Same subject as a
31
+ plan (follow-up, check, commit): its \`plan.id\` — a completed plan reopens;
32
+ another subject gets its own plan even on one branch/source;
33
+ \`plan_choice_required\`: pick by subject. \`plan.source\` = nearest source of
34
+ this request (meeting, message; chat: a label), \`upstream\` to the issue, not
35
+ the broadest umbrella; never invent links. In git: \`plan.git_context.repo\`,
36
+ \`plan.git_context.branch\`. A decided GitLab/GitHub/Jira issue or work item is
37
+ a source, not a second tracker: \`plan.source.ref\` = its URL, then
38
+ \`daruma_plan_drain_next\` → \`daruma_complete\`.
37
39
 
38
40
  Roles: GitLab/GitHub/Jira holds the request itself (the issue or work item);
39
41
  mcpbox extends it and holds the small technical tasks nobody files there.
@@ -133,12 +135,26 @@ Code plugin. Ask in plain language; each maps to a tool you already have:
133
135
  // start, so the plain surfaces carry the routing tree themselves. Keep it
134
136
  // byte-identical to the Routing paragraph of PLATFORM_INSTRUCTIONS in
135
137
  // crates/cloud-api/src/v1_gateway.rs (a Rust test compares them).
136
- export const ROUTING_TREE = "Routing. 0) An action (run, read a log, check status, answer) leaves nothing to track: do it, record NOTHING. 1) Decided work (goal, scope, done-criterion known): daruma_plan_materialize. 2) Follow-up of a pipeline run with status=handed_off: daruma_plan_materialize + daruma_link to its task_id; a run not handed off yet: finish it first. 3) Raw (idea, undecided direction): mcpbox_pipeline_run, then mcpbox_pipeline_handoff — never straight into daruma; if handoff is rejected, tell the user why and never work around it. Can't tell 1 from 3: take 1; pipeline only if the user asks or mode=full.";
138
+ export const ROUTING_TREE = "Routing. 0) An action (run, check, answer) leaves nothing to track: do it, record NOTHING. 1) Decided work: daruma_plan_materialize; same subject as a plan (its follow-up, check, commit): plan.id, a completed one reopens; other subject: own plan even on one branch/source. 2) Pipeline run follow-up: status=handed_off → rule 1 + daruma_link to task_id; not handed off yet: finish it first. 3) Raw idea: mcpbox_pipeline_run, then mcpbox_pipeline_handoff — never straight into daruma; handoff is rejected: explain why, never work around it. Can't tell 1 from 3: take 1; pipeline only if the user asks or mode=full.";
137
139
 
138
140
  // Claude reads the plugin's commands; every other surface gets plain text.
139
141
  const BLOCK_BODY = BLOCK_HEAD + SLASH_COMMANDS;
140
142
  export const BLOCK_BODY_PLAIN = BLOCK_HEAD + `\n${ROUTING_TREE}\n` + PLAIN_COMMANDS;
141
143
 
144
+ // The server is the source of the block text (GET /v1/policy/{surface}, ETag
145
+ // by content): a rule changed there reaches installed files with the next
146
+ // session start, not with the next npm release. The server serves these
147
+ // bodies from the snapshot policy/{surface}.md (scripts/generate-policy-
148
+ // snapshot.mjs, drift-checked by tests on both sides); the copy baked in here
149
+ // is the offline fallback. The version line is the writer's, never served.
150
+ export const SERVED_BODIES = Object.freeze({
151
+ claude: BLOCK_BODY.slice(VERSION_LINE.length),
152
+ plain: BLOCK_BODY_PLAIN.slice(VERSION_LINE.length),
153
+ });
154
+
155
+ // A served body as this plugin writes it into a managed block.
156
+ export const versionedBlock = (body) => VERSION_LINE + body;
157
+
142
158
  // One contract for where a managed block is, shared by init/uninit and the
143
159
  // session-start sync. A marker counts only as a whole line (a leading BOM and
144
160
  // trailing blanks tolerated) outside a closed ``` / ~~~ fence, so markers
@@ -325,7 +341,7 @@ export async function competingPolicyPaths({ projectDir } = {}) {
325
341
 
326
342
  // Only the requested project's managed block may be removed. All surrounding
327
343
  // instructions and the ancestor policy remain owned by their existing files.
328
- export async function installPolicy({ projectDir } = {}) {
344
+ export async function installPolicy({ projectDir, block = BLOCK_BODY } = {}) {
329
345
  const dir = resolve(projectDir ?? process.cwd());
330
346
  const target = join(dir, "CLAUDE.md");
331
347
  const hierarchy = await policyHierarchy({ projectDir: dir });
@@ -340,7 +356,7 @@ export async function installPolicy({ projectDir } = {}) {
340
356
  }
341
357
  return { action: "inherited", path: ancestor };
342
358
  }
343
- return installManagedBlock({ target, begin: BEGIN, end: END, block: BLOCK_BODY });
359
+ return installManagedBlock({ target, begin: BEGIN, end: END, block });
344
360
  }
345
361
 
346
362
  export function removePolicy({ projectDir } = {}) {
@@ -1,6 +1,9 @@
1
1
  import { mkdir, readFile, writeFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
+ import { DEFAULT_BASE_URL, normalizeBaseUrl, readCredentials } from "./cloud-knowledge.mjs";
5
+ import { BLOCK_BODY, BLOCK_BODY_PLAIN, versionedBlock } from "./policy.mjs";
6
+ import { VERSION } from "./version.mjs";
4
7
 
5
8
  const REGISTRY_URL = "https://registry.npmjs.org/@mcpbox/mcpbox-claude";
6
9
  const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
@@ -64,6 +67,117 @@ export async function checkForUpdate({
64
67
  }
65
68
  }
66
69
 
70
+ // The managed policy block as the server holds it now (GET /v1/policy/{surface}).
71
+ // Invalidation is the ETag alone: every call is one conditional request, and
72
+ // 304 means nothing is downloaded — no TTL guessing which copy is fresh.
73
+ // Failures back off for FAILED_TTL_MS and fall back to the last copy (an old
74
+ // copy beats none); null means no server copy was ever seen, so the caller
75
+ // writes the text baked into the plugin. MCPBOX_NO_POLICY_FETCH=1 opts out.
76
+ // One cache file per surface: the hook fetches both surfaces at once.
77
+ // Result: { surface, etag, body, fetchedAt, checkedAt, source }, where source is
78
+ // "server" (downloaded), "server-unchanged" (304) or "cache" (server unreachable).
79
+ const POLICY_MAX_BYTES = 64 * 1024;
80
+
81
+ export function policyCachePath(surface, home = homedir()) {
82
+ return join(home, ".agents", "mcpbox", `policy-${surface}.json`);
83
+ }
84
+
85
+ // A served body must fit between the managed markers and carry no version
86
+ // line of its own (the writing plugin adds it).
87
+ function acceptablePolicyBody(body) {
88
+ return typeof body === "string"
89
+ && body.trim().length > 0
90
+ && Buffer.byteLength(body) <= POLICY_MAX_BYTES
91
+ && !body.includes("<!-- mcpbox:policy:")
92
+ && !body.includes("<!-- mcpbox-claude:policy-version");
93
+ }
94
+
95
+ export async function readPolicyCache(surface, home = homedir()) {
96
+ try {
97
+ const cached = JSON.parse(await readFile(policyCachePath(surface, home), "utf8"));
98
+ return cached && typeof cached === "object" ? cached : {};
99
+ } catch {
100
+ return {};
101
+ }
102
+ }
103
+
104
+ // The server copy already on disk, without asking the server; null if none.
105
+ function knownPolicy(surface, cached) {
106
+ return typeof cached.etag === "string" && acceptablePolicyBody(cached.body)
107
+ ? { surface, etag: cached.etag, body: cached.body, fetchedAt: cached.fetchedAt, checkedAt: cached.checkedAt }
108
+ : null;
109
+ }
110
+
111
+ export async function cachedPolicyBody(surface, home = homedir()) {
112
+ const known = knownPolicy(surface, await readPolicyCache(surface, home));
113
+ return known && { ...known, source: "cache" };
114
+ }
115
+
116
+ export async function fetchPolicyBody(surface, {
117
+ baseUrl = DEFAULT_BASE_URL,
118
+ home = homedir(),
119
+ timeoutMs = DEFAULT_TIMEOUT_MS,
120
+ } = {}) {
121
+ if (process.env.MCPBOX_NO_POLICY_FETCH) return null;
122
+ const cacheFile = policyCachePath(surface, home);
123
+ const cached = await readPolicyCache(surface, home);
124
+ const known = knownPolicy(surface, cached);
125
+ const fallback = known && { ...known, source: "cache" };
126
+ if (Number.isFinite(cached.failedAt) && Date.now() - cached.failedAt < FAILED_TTL_MS) return fallback;
127
+ try {
128
+ const response = await fetch(`${normalizeBaseUrl(baseUrl)}/v1/policy/${surface}`, {
129
+ headers: {
130
+ Accept: "text/markdown",
131
+ "X-Daruma-Plugin-Contract": "1",
132
+ ...(known ? { "If-None-Match": known.etag } : {}),
133
+ },
134
+ redirect: "error",
135
+ signal: AbortSignal.timeout(timeoutMs),
136
+ });
137
+ const checkedAt = Date.now();
138
+ let result;
139
+ if (response.status === 304 && known) {
140
+ result = { ...known, checkedAt, source: "server-unchanged" };
141
+ } else if (response.status === 200) {
142
+ const etag = response.headers.get("etag");
143
+ const body = await response.text();
144
+ if (!etag || !acceptablePolicyBody(body)) throw new Error("invalid policy response");
145
+ result = { surface, etag, body, fetchedAt: checkedAt, checkedAt, source: "server" };
146
+ } else {
147
+ throw new Error(`policy returned ${response.status}`);
148
+ }
149
+ const { source: _, ...entry } = result;
150
+ await writeCache(cacheFile, entry).catch(() => {});
151
+ return result;
152
+ } catch {
153
+ await writeCache(cacheFile, { ...cached, failedAt: Date.now() }).catch(() => {});
154
+ return fallback;
155
+ }
156
+ }
157
+
158
+ // Block text every carrier writes — CLAUDE.md (claude), and AGENTS.md, the
159
+ // Codex SKILL.md and the Cursor .mdc (plain): the server's copy when one was
160
+ // ever fetched, else the text baked into this plugin. Three carriers, one
161
+ // text, the server wins. `fetch: false` (install commands) reads only the
162
+ // copy on disk: asking the server is the session start's job, and an install
163
+ // stays offline and deterministic. A paired machine asks the server it is
164
+ // paired with. `origin` names where the text came from.
165
+ export async function policyBlocks({ fetch = true, home = homedir() } = {}) {
166
+ const baseUrl = fetch ? (await readCredentials())?.base_url ?? DEFAULT_BASE_URL : null;
167
+ const [claude, plain] = await Promise.all(["claude", "plain"].map((surface) => (fetch
168
+ ? fetchPolicyBody(surface, { baseUrl, home })
169
+ : cachedPolicyBody(surface, home)).catch(() => null)));
170
+ // Each surface's ETag: the plain carriers hold a different text than CLAUDE.md.
171
+ const served = Object.entries({ claude, plain }).filter(([, copy]) => copy);
172
+ return {
173
+ claude: claude ? versionedBlock(claude.body) : BLOCK_BODY,
174
+ plain: plain ? versionedBlock(plain.body) : BLOCK_BODY_PLAIN,
175
+ origin: served.length
176
+ ? `server policy ${served.map(([surface, copy]) => `${copy.etag} (${surface})`).join(", ")}`
177
+ : `plugin ${VERSION}`,
178
+ };
179
+ }
180
+
67
181
  async function writeCache(cacheFile, value) {
68
182
  await mkdir(dirname(cacheFile), { recursive: true });
69
183
  await writeFile(cacheFile, `${JSON.stringify(value)}\n`);
package/lib/version.mjs CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.1.26";
1
+ export const VERSION = "0.1.27";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcpbox/mcpbox-claude",
3
- "version": "0.1.26",
3
+ "version": "0.1.27",
4
4
  "description": "MCPBox agent harness for Claude Code: managed policy (daruma tracker + full pipeline), hooks, and slash commands over the single mcpbox MCP server.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -3,7 +3,7 @@ name: mcpbox
3
3
  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`.
4
4
  ---
5
5
 
6
- <!-- mcpbox-claude:policy-version 0.1.26 -->
6
+ <!-- mcpbox-claude:policy-version 0.1.27 -->
7
7
  # MCPBox — default agent stack
8
8
 
9
9
  The **mcpbox** MCP server (`https://mcpbox.ru/v1/mcp`) is this workspace's task
@@ -18,13 +18,15 @@ tracker. "Daruma", "дарума", "трекер", "tracker", "таск-мене
18
18
  "Составь план", "Распланируй", "make/write/create a plan" — or about to
19
19
  answer with a plan, step list or task breakdown for it, in Plan mode too —
20
20
  first create it with `daruma_plan_materialize`, then reply with a short
21
- summary and the plan id; never a plan only as chat text. Set
22
- `plan.source` (link to the issue/message, or a short label for a chat
23
- request; never invent links) and, in a git repo, `plan.git_context.repo`
24
- and `plan.git_context.branch`. A decided GitLab/GitHub/Jira issue, work item
25
- or ticket is the request's source, not a second tracker: materialize it with
26
- `plan.source.ref` = its URL, then `daruma_plan_drain_next` →
27
- `daruma_complete`; decisions go to `mcpbox_knowledge_write`.
21
+ summary and the plan id; never a plan only as chat text. Same subject as a
22
+ plan (follow-up, check, commit): its `plan.id` — a completed plan reopens;
23
+ another subject gets its own plan even on one branch/source;
24
+ `plan_choice_required`: pick by subject. `plan.source` = nearest source of
25
+ this request (meeting, message; chat: a label), `upstream` to the issue, not
26
+ the broadest umbrella; never invent links. In git: `plan.git_context.repo`,
27
+ `plan.git_context.branch`. A decided GitLab/GitHub/Jira issue or work item is
28
+ a source, not a second tracker: `plan.source.ref` = its URL, then
29
+ `daruma_plan_drain_next` → `daruma_complete`.
28
30
 
29
31
  Roles: GitLab/GitHub/Jira holds the request itself (the issue or work item);
30
32
  mcpbox extends it and holds the small technical tasks nobody files there.
@@ -85,7 +87,7 @@ it at once; two active tasks need the human's call or a `relates_to` link.
85
87
  how eagerly to suggest `mcpbox_pipeline_run`: `off` never, `lite` only when asked, `full` for any substantive request. To change it, run
86
88
  `npx -y @mcpbox/mcpbox-claude@latest mode <value>` and report the result.
87
89
 
88
- Routing. 0) An action (run, read a log, check status, answer) leaves nothing to track: do it, record NOTHING. 1) Decided work (goal, scope, done-criterion known): daruma_plan_materialize. 2) Follow-up of a pipeline run with status=handed_off: daruma_plan_materialize + daruma_link to its task_id; a run not handed off yet: finish it first. 3) Raw (idea, undecided direction): mcpbox_pipeline_run, then mcpbox_pipeline_handoff — never straight into daruma; if handoff is rejected, tell the user why and never work around it. Can't tell 1 from 3: take 1; pipeline only if the user asks or mode=full.
90
+ Routing. 0) An action (run, check, answer) leaves nothing to track: do it, record NOTHING. 1) Decided work: daruma_plan_materialize; same subject as a plan (its follow-up, check, commit): plan.id, a completed one reopens; other subject: own plan even on one branch/source. 2) Pipeline run follow-up: status=handed_off → rule 1 + daruma_link to task_id; not handed off yet: finish it first. 3) Raw idea: mcpbox_pipeline_run, then mcpbox_pipeline_handoff — never straight into daruma; handoff is rejected: explain why, never work around it. Can't tell 1 from 3: take 1; pipeline only if the user asks or mode=full.
89
91
 
90
92
  ### Useful requests
91
93
 
@@ -9,11 +9,13 @@ to the user/agent to actually execute it.
9
9
  ## Steps
10
10
 
11
11
  1. Resolve project (`daruma_workspace_info` → `default_project`).
12
- 2. Active plan: `daruma_plan_list` filtered to `status = "active"`, most recent.
12
+ 2. Active plan: `daruma_plan_list` with `status = "active"`, `sort = "updated"`,
13
+ `limit = 1` — the most recently updated plan (the default order is by creation).
13
14
  If none, stop with "no active plan — decided work: `daruma_plan_materialize`; raw idea: `/mcpbox:pipeline-run`".
14
15
  3. `daruma_plan_drain_next` with the plan id. The server atomically picks the next
15
16
  ready (unblocked) task and claims it for this session; it returns null when no
16
- unclaimed ready task remains.
17
+ unclaimed ready task remains. Keep the returned `run_id`: the server opened that
18
+ run for this claim. A null drain already aborted its own run — nothing to close.
17
19
  4. If "no ready task": print the server reason (e.g. "3 tasks blocked by X") and
18
20
  suggest `/mcpbox:plan` to inspect dependencies. Stop.
19
21
  5. Otherwise render the briefing:
@@ -23,6 +25,7 @@ to the user/agent to actually execute it.
23
25
 
24
26
  id: <task_id>
25
27
  plan: <plan_id>
28
+ run: <run_id>
26
29
  priority: <pX>
27
30
  status: 🟢 in_progress
28
31
  ```
@@ -33,7 +36,12 @@ to the user/agent to actually execute it.
33
36
 
34
37
  ```
35
38
  → When done: daruma_complete id=<task_id> [result_summary="<summary>"]
39
+ then daruma_run_complete run_id=<run_id>
36
40
  → On failure: daruma_set_status status=todo comment={ body, kind: "blocker" }
41
+ then daruma_run_abort run_id=<run_id> reason=<reason>
37
42
  ```
38
43
 
44
+ An open run keeps the plan from auto-closing after its last task; the
45
+ `plan_close_blocked_by_run` warning names it in `details.run_id`.
46
+
39
47
  7. Briefing only — do not start executing the task in this command.
@@ -8,19 +8,22 @@ The user invoked `/mcpbox:plan`.
8
8
  ## Steps
9
9
 
10
10
  1. Resolve project (`daruma_workspace_info` → `default_project`).
11
- 2. `daruma_plan_list status="draft,active"`, most recent first.
11
+ 2. `daruma_plan_list status="draft,active" sort="updated" limit=1` — the most recently
12
+ updated plan (the default order is by creation, and its first page can miss it).
12
13
  If none, stop with "no active plan — decided work: `daruma_plan_materialize`; raw idea: `/mcpbox:pipeline-run`".
13
- 3. For the chosen plan, `daruma_plan_get` (single call — do not enumerate the archive).
14
+ 3. For the chosen plan, `daruma_plan_get view="tasks"` (single call — do not enumerate the archive).
15
+ It lists every plan task (done included) with `status`, `priority`, `depends_on` and
16
+ `blocked_by`; the default `progress` view caps each group at five open tasks.
14
17
  4. Render:
15
18
 
16
19
  ```
17
20
  ## <plan title>
18
- goal: <goal>
19
21
  progress: [████░░░░] 4/9 done
20
22
 
21
23
  | # | Status | Pri | Task | Depends on |
22
24
  |---|--------|-----|------|-----------|
23
25
  ```
24
26
 
25
- - Progress bar from done/total; blocked tasks marked ⛔ with their blocker ids.
27
+ - Progress bar from `progress.tasks_done`/`progress.tasks_total`; one row per task in plan order.
28
+ - Tasks with a non-empty `blocked_by` marked ⛔ with those blocker ids.
26
29
  5. Do not call `daruma_plan_list status=completed` (token-heavy). Read-only.