@mcpbox/mcpbox-claude 0.1.18 → 0.1.20

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/lib/policy.mjs CHANGED
@@ -2,12 +2,17 @@
2
2
  // Clients keep safety rules and discover detailed workflows only when needed.
3
3
 
4
4
  import { promises as fs } from "node:fs";
5
- import { dirname, join, resolve } from "node:path";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ import { VERSION } from "./version.mjs";
6
7
 
7
8
  const BEGIN = "<!-- mcpbox:policy:begin -->";
8
9
  const END = "<!-- mcpbox:policy:end -->";
9
10
 
10
- const BLOCK_HEAD = `# MCPBox — default agent stack (project policy)
11
+ // First line of every block: which plugin release wrote this text. Session-
12
+ // start sync reads it so an older plugin never rolls a newer block back.
13
+ const VERSION_LINE = `<!-- mcpbox-claude:policy-version ${VERSION} -->\n`;
14
+
15
+ const BLOCK_HEAD = VERSION_LINE + `# MCPBox — default agent stack (project policy)
11
16
 
12
17
  Use the **mcpbox** MCP server (\`https://mcpbox.ru/v1/mcp\`). Daruma / дарума /
13
18
  трекер / таск-менеджер / tracker means this server. It exposes \`daruma_*\`
@@ -30,6 +35,10 @@ and platform \`mcpbox_*\` tools. The plugin manages this block; do not hand-edit
30
35
  Do not switch to a local markdown tracker or guess routing rules.
31
36
  6. \`status=all\` requires an explicit user request for the archive in this turn.
32
37
  Default to \`status=active\` for tasks and \`draft,active\` for plans.
38
+ 7. Plan intake (materialize/create): set \`plan.source\` to the nearest source (URI or
39
+ \`label\`), \`plan.source.upstream[]\` only as stated by the issue/e-mail or user —
40
+ never invented; unknown → ask once. In a git repo, pass \`plan.git_context.branch\`
41
+ and \`plan.git_context.repo\`. Details and warnings: server instructions.
33
42
 
34
43
  Inventory: one scoped \`daruma_list status=active\`. Always pass \`project_id\`,
35
44
  \`project_scope\` or \`scope_path\` on the first scoped call. Close only verified work.
@@ -37,11 +46,12 @@ Use \`daruma_search\` with a limit for named text lookup, not open-task inventor
37
46
 
38
47
  ## Part B — MCPBox pipeline: routing authority
39
48
 
40
- Before intake, follow the **server initialize.instructions** routing rule
41
- (\`PLATFORM_INSTRUCTIONS\`). Tool descriptions, including \`daruma_plan_materialize\`
49
+ Before intake or editing code, follow the **server initialize.instructions**
50
+ (\`PLATFORM_INSTRUCTIONS\`) for routing and execution-path verification.
51
+ Tool descriptions, including \`daruma_plan_materialize\`
42
52
  and \`mcpbox_pipeline_handoff\`, point to that authority. This index deliberately
43
53
  does not copy the routing decision tree. If server instructions are unavailable,
44
- reconnect/read them before intake; do not invent a substitute.
54
+ reconnect/read them before intake or editing; do not invent a substitute.
45
55
 
46
56
  Load workflow details on demand through the installed MCPBox command skills
47
57
  (tasks, plan, next, mine, status, pipeline-run, trace). Without skill support,
@@ -99,14 +109,83 @@ Code plugin. Ask in plain language; each maps to a tool you already have:
99
109
  const BLOCK_BODY = BLOCK_HEAD + SLASH_COMMANDS;
100
110
  export const BLOCK_BODY_PLAIN = BLOCK_HEAD + PLAIN_COMMANDS;
101
111
 
112
+ // One contract for where a managed block is, shared by init/uninit and the
113
+ // session-start sync. A marker counts only as a whole line (a leading BOM and
114
+ // trailing blanks tolerated) outside a closed ``` / ~~~ fence, so markers
115
+ // quoted in prose or in an example are not a block. A fence left open to the
116
+ // end of the file hides nothing — a stray ``` above a real block must not
117
+ // turn it into "absent" and make init append a copy on every run. Result:
118
+ // {kind: "absent"} no marker line at all
119
+ // {kind: "block", start, end, inner, eol} one begin line, then one end line
120
+ // {kind: "malformed"} anything else (repeated, reversed,
121
+ // half a pair) — callers refuse
122
+ const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
123
+
124
+ // Marker lines of `text` for each marker, as {index, length, eol}.
125
+ function markerLines(text, markers) {
126
+ const hits = markers.map(() => []);
127
+ let pending = [];
128
+ let fence = null;
129
+ let pos = 0;
130
+ for (const raw of text.split("\n")) {
131
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
132
+ const bare = (pos === 0 ? line.replace(/^/, "") : line).replace(/[ \t]+$/, "");
133
+ const f = FENCE.exec(line);
134
+ if (fence) {
135
+ if (f && f[1][0] === fence[0] && f[1].length >= fence.length && !f[2].trim()) {
136
+ fence = null;
137
+ pending = [];
138
+ }
139
+ } else if (f && !(f[1][0] === "`" && f[2].includes("`"))) {
140
+ fence = f[1];
141
+ } else {
142
+ const at = markers.indexOf(bare);
143
+ if (at !== -1) {
144
+ const offset = line.length - line.replace(/^/, "").length;
145
+ hits[at].push({ index: pos + offset, length: bare.length, eol: raw.endsWith("\r") ? "\r\n" : "\n" });
146
+ }
147
+ }
148
+ if (fence && !f) {
149
+ const at = markers.indexOf(bare);
150
+ if (at !== -1) pending.push([at, { index: pos, length: bare.length, eol: raw.endsWith("\r") ? "\r\n" : "\n" }]);
151
+ }
152
+ pos += raw.length + 1;
153
+ }
154
+ // Unclosed fence: its markers count after all.
155
+ for (const [at, hit] of pending) hits[at].push(hit);
156
+ return hits.map((h) => h.sort((a, b) => a.index - b.index));
157
+ }
158
+
159
+ export function locateBlock(text, begin, end) {
160
+ const [begins, ends] = markerLines(text, [begin, end]);
161
+ if (begins.length === 0 && ends.length === 0) return { kind: "absent" };
162
+ if (begins.length !== 1 || ends.length !== 1 || ends[0].index < begins[0].index) {
163
+ return { kind: "malformed" };
164
+ }
165
+ const b = begins[0], e = ends[0];
166
+ // Keep whatever trailed the end marker on its line (blanks) outside the block.
167
+ const innerStart = text.indexOf("\n", b.index) + 1;
168
+ return {
169
+ kind: "block",
170
+ start: b.index,
171
+ end: e.index + e.length,
172
+ inner: text.slice(innerStart, e.index),
173
+ eol: b.eol,
174
+ };
175
+ }
176
+
177
+ function malformed(target, begin) {
178
+ return new Error(`Malformed or repeated managed-block markers (${begin}): ${target}`);
179
+ }
180
+
102
181
  // Idempotent write of a delimited managed block to `target`. Surrounding
103
182
  // hand-written content is preserved. Shared by the CLAUDE.md, AGENTS.md
104
- // (Codex), and .cursor/rules (Cursor) policy surfaces — see lib/codex.mjs
105
- // and lib/cursor.mjs. Returns { action, path } where action is one of
106
- // installed | updated | appended | unchanged.
183
+ // (Codex, Kimi, OpenCode) policy surfaces and the Codex/Kimi TOML blocks.
184
+ // Returns { action, path } where action is one of
185
+ // installed | updated | appended | unchanged; throws on malformed markers
186
+ // rather than appending a second block or overwriting quoted text.
107
187
  export async function installManagedBlock({ target, begin, end, block }) {
108
188
  await fs.mkdir(resolve(target, ".."), { recursive: true });
109
- const wrapped = `${begin}\n${block}${end}\n`;
110
189
 
111
190
  let existing = null;
112
191
  try {
@@ -116,21 +195,21 @@ export async function installManagedBlock({ target, begin, end, block }) {
116
195
  }
117
196
 
118
197
  if (existing === null) {
119
- await fs.writeFile(target, wrapped);
198
+ await fs.writeFile(target, `${begin}\n${block}${end}\n`);
120
199
  return { action: "installed", path: target };
121
200
  }
122
201
 
123
- const beginIdx = existing.indexOf(begin);
124
- const endIdx = existing.indexOf(end);
125
- if (beginIdx === -1 || endIdx === -1 || endIdx < beginIdx) {
126
- const sep = existing.endsWith("\n") ? "" : "\n";
127
- await fs.writeFile(target, `${existing}${sep}\n${wrapped}`);
202
+ const found = locateBlock(existing, begin, end);
203
+ if (found.kind === "malformed") throw malformed(target, begin);
204
+ if (found.kind === "absent") {
205
+ const eol = existing.includes("\r\n") ? "\r\n" : "\n";
206
+ const sep = existing.endsWith("\n") ? "" : eol;
207
+ await fs.writeFile(target, `${existing}${sep}${eol}${`${begin}\n${block}${end}\n`.replace(/\n/g, eol)}`);
128
208
  return { action: "appended", path: target };
129
209
  }
130
210
 
131
- const before = existing.slice(0, beginIdx);
132
- const after = existing.slice(endIdx + end.length).replace(/^\n/, "");
133
- const next = `${before}${wrapped}${after}`;
211
+ const wrapped = `${begin}\n${block}${end}`.replace(/\n/g, found.eol);
212
+ const next = existing.slice(0, found.start) + wrapped + existing.slice(found.end);
134
213
  if (next === existing) {
135
214
  return { action: "unchanged", path: target };
136
215
  }
@@ -147,19 +226,20 @@ export async function removeManagedBlock({ target, begin, end }) {
147
226
  if (err.code === "ENOENT") return { action: "missing", path: target };
148
227
  throw err;
149
228
  }
150
- const beginIdx = existing.indexOf(begin);
151
- const endIdx = existing.indexOf(end);
152
- if (beginIdx === -1 || endIdx === -1) {
153
- return { action: "missing", path: target };
154
- }
155
- const before = existing.slice(0, beginIdx).replace(/\n+$/, "");
156
- const after = existing.slice(endIdx + end.length).replace(/^\n+/, "");
157
- const next = [before, after].filter(Boolean).join("\n\n");
229
+ const found = locateBlock(existing, begin, end);
230
+ if (found.kind === "absent") return { action: "missing", path: target };
231
+ // Uninstall keeps going over the other surfaces; the file is left as is.
232
+ if (found.kind === "malformed") return { action: "malformed", path: target };
233
+ const eol = found.eol;
234
+ // A lone BOM is not content: it must not leave blank lines on top.
235
+ const before = existing.slice(0, found.start).replace(/(\r?\n)+$/, "").replace(/^\uFEFF$/, "");
236
+ const after = existing.slice(found.end).replace(/^(\r?\n)+/, "");
237
+ const next = [before, after].filter(Boolean).join(eol + eol);
158
238
  if (next.trim().length === 0) {
159
239
  await fs.unlink(target);
160
240
  return { action: "removed-file", path: target };
161
241
  }
162
- await fs.writeFile(target, next.endsWith("\n") ? next : `${next}\n`);
242
+ await fs.writeFile(target, next.endsWith("\n") ? next : `${next}${eol}`);
163
243
  return { action: "removed-block", path: target };
164
244
  }
165
245
 
@@ -171,14 +251,11 @@ export async function policyHierarchy({ projectDir } = {}) {
171
251
  while (true) {
172
252
  const target = join(dir, "CLAUDE.md");
173
253
  try {
174
- const body = await fs.readFile(target, "utf8");
175
- const begin = body.indexOf(BEGIN), end = body.indexOf(END);
176
- if (begin !== -1 || end !== -1) {
177
- if (begin < 0 || end < begin || body.indexOf(BEGIN, begin + BEGIN.length) !== -1 || body.indexOf(END, end + END.length) !== -1) {
178
- throw new Error(`Malformed or repeated mcpbox policy markers: ${target}`);
179
- }
180
- paths.push(target);
254
+ const found = locateBlock(await fs.readFile(target, "utf8"), BEGIN, END);
255
+ if (found.kind === "malformed") {
256
+ throw new Error(`Malformed or repeated mcpbox policy markers: ${target}`);
181
257
  }
258
+ if (found.kind === "block") paths.push(target);
182
259
  } catch (err) {
183
260
  if (err.code !== "ENOENT") throw err;
184
261
  }
@@ -189,6 +266,33 @@ export async function policyHierarchy({ projectDir } = {}) {
189
266
  return { paths, present: paths.length > 0, duplicate: paths.length > 1 };
190
267
  }
191
268
 
269
+ // The OSS daruma CLI installs its own policy under different markers
270
+ // (apps/cli/src/main.rs: daruma-claude / daruma-codex). No overwrite, but a
271
+ // file carrying both gives the agent two policies at once — doctor warns.
272
+ const DARUMA_MARKERS = ["claude", "codex"].map((k) => [
273
+ `<!-- daruma-${k}:policy:begin -->`,
274
+ `<!-- daruma-${k}:policy:end -->`,
275
+ ]);
276
+
277
+ export async function competingPolicyPaths({ projectDir } = {}) {
278
+ const paths = [];
279
+ let dir = resolve(projectDir ?? process.cwd());
280
+ while (true) {
281
+ for (const file of ["CLAUDE.md", "AGENTS.md"]) {
282
+ const target = join(dir, file);
283
+ try {
284
+ const body = await fs.readFile(target, "utf8");
285
+ const daruma = DARUMA_MARKERS.some(([b, e]) => locateBlock(body, b, e).kind === "block");
286
+ if (daruma && locateBlock(body, BEGIN, END).kind === "block") paths.push(target);
287
+ } catch { /* absent or unreadable */ }
288
+ }
289
+ const parent = dirname(dir);
290
+ if (parent === dir) break;
291
+ dir = parent;
292
+ }
293
+ return paths;
294
+ }
295
+
192
296
  // Only the requested project's managed block may be removed. All surrounding
193
297
  // instructions and the ancestor policy remain owned by their existing files.
194
298
  export async function installPolicy({ projectDir } = {}) {
@@ -214,6 +318,109 @@ export function removePolicy({ projectDir } = {}) {
214
318
  return removeManagedBlock({ target: join(dir, "CLAUDE.md"), begin: BEGIN, end: END });
215
319
  }
216
320
 
321
+ // A plugin update ships a new block body, but the copies `init` already wrote
322
+ // into CLAUDE.md / AGENTS.md stay at the version that wrote them (measured
323
+ // 2026-09-27: every installed copy lagged the source, and nothing said so).
324
+ // SessionStart calls syncPolicyBlocks to bring existing managed blocks — cwd
325
+ // and every ancestor — up to the running plugin. Contract:
326
+ // - never adds a block: only a file whose locateBlock() finds a block
327
+ // qualifies (markers quoted in prose or examples are not a block);
328
+ // - touches only the text between the markers, keeps the file's EOL;
329
+ // - never writes through a symlink or hard link (AGENTS.md -> CLAUDE.md
330
+ // would flip between the Claude and Codex bodies every session);
331
+ // - never replaces a block written by a newer plugin, and does not rewrite
332
+ // one that differs only in the version line (no per-release git noise);
333
+ // - atomic (temp file + rename), per-file failures skipped.
334
+ // A managed block of CLAUDE.md / AGENTS.md (the policy markers).
335
+ export function findManagedBlock(text) {
336
+ const found = locateBlock(text, BEGIN, END);
337
+ return found.kind === "block" ? found : null;
338
+ }
339
+
340
+ // Multiline: the line opens a block but sits below the frontmatter of a skill.
341
+ const VERSION_RE = /^<!-- mcpbox-claude:policy-version (\S+) -->\r?\n/m;
342
+
343
+ function versionParts(v) {
344
+ return String(v).split(/[-+]/)[0].split(".").map((n) => Number.parseInt(n, 10) || 0);
345
+ }
346
+
347
+ function newerThanRunning(version) {
348
+ const a = versionParts(version), b = versionParts(VERSION);
349
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
350
+ if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);
351
+ }
352
+ return false;
353
+ }
354
+
355
+ const normalize = (inner) => inner.replace(/\r\n/g, "\n").replace(VERSION_RE, "");
356
+
357
+ // Whether installed text (a block body or a whole generated file) should be
358
+ // replaced by `block`.
359
+ export function blockNeedsSync(inner, block) {
360
+ const lf = inner.replace(/\r\n/g, "\n");
361
+ if (normalize(lf) === normalize(block)) return false;
362
+ const written = lf.match(VERSION_RE)?.[1];
363
+ return !(written && newerThanRunning(written));
364
+ }
365
+
366
+ async function atomicWrite(target, text, mode) {
367
+ const tmp = join(dirname(target), `.${basename(target)}.mcpbox-${process.pid}.tmp`);
368
+ try {
369
+ await fs.writeFile(tmp, text);
370
+ // writeFile's mode is masked by umask; keep a group-writable file so.
371
+ await fs.chmod(tmp, mode);
372
+ await fs.rename(tmp, target);
373
+ } catch (err) {
374
+ await fs.rm(tmp, { force: true });
375
+ throw err;
376
+ }
377
+ }
378
+
379
+ // Replace the block of one file per the contract above. Returns true if written.
380
+ export async function syncManagedFile(target, block) {
381
+ let stat, body;
382
+ try {
383
+ stat = await fs.lstat(target);
384
+ if (!stat.isFile() || stat.nlink > 1) return false;
385
+ body = await fs.readFile(target, "utf8");
386
+ } catch {
387
+ return false;
388
+ }
389
+ const found = findManagedBlock(body);
390
+ if (!found || !blockNeedsSync(found.inner, block)) return false;
391
+ const wrapped = `${BEGIN}\n${block}${END}`.replace(/\n/g, found.eol);
392
+ await atomicWrite(target, body.slice(0, found.start) + wrapped + body.slice(found.end), stat.mode & 0o7777);
393
+ return true;
394
+ }
395
+
396
+ // `stopAt` (tests) ends the walk at that directory instead of the FS root.
397
+ export async function syncPolicyBlocks({ cwd = process.cwd(), file = "CLAUDE.md", block = BLOCK_BODY, stopAt } = {}) {
398
+ const updated = [];
399
+ let dir = resolve(cwd);
400
+ while (true) {
401
+ const target = join(dir, file);
402
+ try {
403
+ if (await syncManagedFile(target, block)) updated.push(target);
404
+ } catch { /* unwritable ancestor — keep walking */ }
405
+ if (stopAt && dir === resolve(stopAt)) break;
406
+ const parent = dirname(dir);
407
+ if (parent === dir) break;
408
+ dir = parent;
409
+ }
410
+ return updated;
411
+ }
412
+
413
+ // Paths among `paths` whose managed block the running plugin would replace.
414
+ // A file sync would never touch (quoted markers, fence) is not stale.
415
+ export async function stalePolicyPaths(paths, block = BLOCK_BODY) {
416
+ const stale = [];
417
+ for (const target of paths) {
418
+ const found = findManagedBlock(await fs.readFile(target, "utf8"));
419
+ if (found && blockNeedsSync(found.inner, block)) stale.push(target);
420
+ }
421
+ return stale;
422
+ }
423
+
217
424
  // The single canonical mcpbox MCP endpoint every surface points at.
218
425
  export const MCP_URL = "https://mcpbox.ru/v1/mcp";
219
426
 
package/lib/version.mjs CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.1.18";
1
+ export const VERSION = "0.1.20";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcpbox/mcpbox-claude",
3
- "version": "0.1.18",
3
+ "version": "0.1.20",
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": {
@@ -12,5 +12,9 @@ The user invoked `/mcpbox:doctor`.
12
12
  `npx @mcpbox/mcpbox setup` and restart Claude Code.
13
13
  2. Reachability: `daruma_healthz`. Report version + git_sha, or the failure verbatim.
14
14
  3. Policy: confirm this project's `CLAUDE.md` contains the `mcpbox:policy` managed block.
15
- If missing, `npx -y @mcpbox/mcpbox-claude init` (or re-run setup).
15
+ If missing, `npx -y @mcpbox/mcpbox-claude init` (or re-run setup). If
16
+ `npx -y @mcpbox/mcpbox-claude doctor --json` reports `policy_stale`, the block
17
+ predates the installed plugin; the next session start refreshes it. Paths in
18
+ `policy_competing_paths` also carry a daruma CLI policy block
19
+ (`daruma-claude` / `daruma-codex`); tell the user to keep one of the two.
16
20
  4. Render a short checklist with ✓ / ✗ per item and a final READY / NOT READY line.