@mcpbox/mcpbox-claude 0.1.24 → 0.1.26

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.24",
4
+ "version": "0.1.26",
5
5
  "author": {
6
6
  "name": "tupical"
7
7
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcpbox",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
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
@@ -46,9 +46,17 @@ codex plugin add mcpbox --marketplace mcpbox
46
46
  codex plugin marketplace upgrade mcpbox # later, to update
47
47
  ```
48
48
 
49
- Codex exposes the plugin's command workflows as skills. `codex-init` installs
50
- the managed policy, MCP server, and routing skill; it does not write the unused
51
- `~/.codex/prompts` surface. `codex-uninit` still removes legacy `mcpbox-*.md`
49
+ Codex exposes the plugin's command workflows as skills, and the plugin ships
50
+ the routing policy itself as the `mcpbox` skill. `codex-init` is for Codex
51
+ without the plugin: it installs the managed policy, MCP server, and a
52
+ user-level copy of that skill (`$CODEX_HOME/skills/mcpbox`); it does not write
53
+ the unused `~/.codex/prompts` surface. With the plugin, that copy is a
54
+ duplicate: a Codex plugin session (and `mcpbox setup`, via
55
+ `codex-skill-retire`) removes it when it is a copy mcpbox wrote, after saving
56
+ a copy that differs from the current text to `$CODEX_HOME/mcpbox-skill-backup-*`.
57
+ A skill without the mcpbox header, with extra files, from a newer release,
58
+ inside Git, or beneath a linked directory is left alone. Cleanup also skips
59
+ paths when Git ownership cannot be checked. `codex-uninit` still removes legacy `mcpbox-*.md`
52
60
  prompt files left by older installs.
53
61
 
54
62
  Cursor and Kimi have no plugin manager; they are file installs, so re-run their
@@ -62,8 +70,8 @@ npx -y @mcpbox/mcpbox-claude@latest opencode-init
62
70
 
63
71
  On Claude and Codex a plugin update also reaches the policy you already
64
72
  installed: at session start the hook rewrites every existing `mcpbox:policy`
65
- block from the working directory up (`CLAUDE.md` on Claude, `AGENTS.md` plus
66
- the `mcpbox` skill on Codex) to the running version, and says so in the
73
+ block from the working directory up (`CLAUDE.md` on Claude, `AGENTS.md` on
74
+ Codex; Claude also refreshes a user-level Codex `mcpbox` skill) to the running version, and says so in the
67
75
  session context. It never adds a block and never touches text outside the
68
76
  markers; `doctor --json` reports `policy_stale` until it has run. Set
69
77
  `MCPBOX_NO_POLICY_SYNC=1` to keep installed blocks as they are.
@@ -86,6 +94,8 @@ unbound in the paired workspace, the hook adds a ready `mcpbox_knowledge_read`
86
94
  call instead of the text. Knowledge rows arrive
87
95
  marked as workspace data, not instructions. Mode `off` disables both.
88
96
 
97
+ 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.
98
+
89
99
  A stale version announces itself at session start on Claude, Codex, and Kimi.
90
100
  The Cursor adapter's only hook is the user-level `sessionStart` that carries
91
101
  the policy (global installs); it does no update check, so nothing announces
@@ -105,7 +115,8 @@ installs, CI).
105
115
  | OpenCode | `AGENTS.md` block (`mcpbox:policy`) | `mcpbox` remote entry under `mcp` in `~/.config/opencode/opencode.json` | — |
106
116
 
107
117
  Codex skills are generated at package time from the same `commands/*.md` files
108
- that provide Claude's `/mcpbox:*` commands. Codex selects these skills by their
118
+ that provide Claude's `/mcpbox:*` commands, plus `skills/mcpbox` from the shared
119
+ plain policy (`BLOCK_BODY_PLAIN`). Codex selects these skills by their
109
120
  descriptions; they are not user-entered slash commands.
110
121
 
111
122
  All four agents accept `mcpbox mode [off|lite|full]` through the managed
@@ -118,7 +129,7 @@ Kimi specifics:
118
129
  `~/.kimi-code/config.toml`; `$KIMI_CODE_HOME` is honored). One
119
130
  `/mcp-config login mcpbox` OAuth then covers every project.
120
131
  - The hook scripts (`SessionStart` task summary, `UserPromptSubmit` routing
121
- hints, `Stop` auto-record nudge) are the same ones the Claude plugin ships;
132
+ hints, `Stop` guard) are the same ones the Claude plugin ships;
122
133
  `kimi-init` copies them into `~/.kimi-code/mcpbox/` so the config never
123
134
  references an ephemeral npx cache path. `kimi-uninit` removes that directory.
124
135
 
@@ -129,6 +140,8 @@ mcpbox-claude init [--dir DIR] Managed CLAUDE.md policy block. Idempote
129
140
  mcpbox-claude uninit [--dir DIR] Remove the CLAUDE.md policy block.
130
141
  mcpbox-claude codex-init [--dir DIR] AGENTS.md policy + config.toml server + routing skill.
131
142
  mcpbox-claude codex-uninit [--dir DIR]
143
+ mcpbox-claude codex-skill User-level routing skill only (Codex without the plugin).
144
+ mcpbox-claude codex-skill-retire Remove that user-level copy once the plugin ships it.
132
145
  mcpbox-claude cursor-init [--dir DIR] .cursor/rules policy + .cursor/mcp.json server
133
146
  (in $HOME: ~/.cursor/hooks.json sessionStart hook).
134
147
  mcpbox-claude cursor-uninit [--dir DIR]
@@ -19,9 +19,16 @@ 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 } from "../lib/policy.mjs";
22
+ import { installPolicy, removePolicy, policyHierarchy, stalePolicyPaths, competingPolicyPaths, BLOCK_BODY_PLAIN } from "../lib/policy.mjs";
23
23
  import { credentialsPath, login, logout, readCredentials } from "../lib/cloud-knowledge.mjs";
24
- import { installCodex, removeCodex, installCodexPolicy } from "../lib/codex.mjs";
24
+ import {
25
+ installCodex,
26
+ removeCodex,
27
+ installCodexPolicy,
28
+ installCodexSkill,
29
+ retireCodexSkill,
30
+ syncCodexSkill,
31
+ } from "../lib/codex.mjs";
25
32
  import {
26
33
  installCursor,
27
34
  removeCursor,
@@ -48,8 +55,9 @@ Usage:
48
55
  (daruma tracker + full pipeline). Idempotent.
49
56
  mcpbox-claude uninit [--dir DIR] Remove the managed CLAUDE.md policy block.
50
57
  mcpbox-claude codex-init [--dir DIR] Write AGENTS.md policy, ~/.codex/config.toml
51
- [mcp_servers.mcpbox] and the mcpbox skill.
52
- Idempotent.
58
+ [mcp_servers.mcpbox] and the mcpbox skill
59
+ (for Codex without the plugin, which ships
60
+ that skill itself). Idempotent.
53
61
  mcpbox-claude codex-uninit [--dir DIR]
54
62
  mcpbox-claude cursor-init [--dir DIR] Write .cursor/rules/mcpbox-policy.mdc +
55
63
  .cursor/mcp.json mcpbox entry. Idempotent.
@@ -214,6 +222,20 @@ async function cmdCodexPolicy(rest) {
214
222
  report(await installCodexPolicy({ projectDir }));
215
223
  }
216
224
 
225
+ // The user-level policy skill alone: `codex-skill` for Codex without the
226
+ // plugin, `codex-skill-retire` once the plugin (which ships it) is installed.
227
+ async function cmdCodexSkill() {
228
+ report(await installCodexSkill());
229
+ }
230
+
231
+ async function cmdCodexSkillRetire() {
232
+ const { removed, backups, kept } = await retireCodexSkill();
233
+ for (const path of removed) process.stdout.write(`✓ Removed duplicate ${path}\n`);
234
+ for (const path of backups) process.stdout.write(`✓ Saved the differing copy to ${path}\n`);
235
+ for (const path of kept) process.stdout.write(`! Left alone (not a copy mcpbox wrote) ${path}\n`);
236
+ if (!removed.length && !kept.length) process.stdout.write("✓ No user-level mcpbox skill to retire\n");
237
+ }
238
+
217
239
  async function cmdCursorPolicy(rest) {
218
240
  const { projectDir } = parseDirFlag(rest);
219
241
  if (isHomeDir(projectDir)) return installCursorHome(homedir());
@@ -269,6 +291,11 @@ async function cmdDoctor(rest) {
269
291
  const ready = policy && !hierarchy.duplicate && mcp === true;
270
292
  // Stale is a warning, not NOT READY: the next SessionStart refreshes it.
271
293
  const stale = await stalePolicyPaths(hierarchy.paths);
294
+ // Codex carriers (no Codex hooks exist): AGENTS.md up the tree and the user skill.
295
+ 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" }));
298
+ const skillStale = skill.action === "stale" ? [skill.path] : [];
272
299
  // Also a warning: two policies in one file, one of them from the daruma CLI.
273
300
  const competing = await competingPolicyPaths({ projectDir });
274
301
  // Not required: without it hooks hint at the knowledge instead of loading it.
@@ -282,6 +309,9 @@ async function cmdDoctor(rest) {
282
309
  policy_stale: stale.length > 0,
283
310
  policy_stale_paths: stale,
284
311
  policy_competing_paths: competing,
312
+ agents_md_paths: agents.paths,
313
+ agents_md_stale_paths: agentsStale,
314
+ codex_skill_stale_paths: skillStale,
285
315
  knowledge_paired: paired,
286
316
  }) + "\n");
287
317
  } else {
@@ -290,6 +320,9 @@ async function cmdDoctor(rest) {
290
320
  `mcpbox MCP server: ${mark(mcp)}${mcp === null ? " (claude CLI not found)" : ""}\n` +
291
321
  `CLAUDE.md policy: ${mark(policy)}${hierarchy.duplicate ? " (duplicate managed blocks)" : ""}\n` +
292
322
  hierarchy.paths.map((p) => ` ${p}${stale.includes(p) ? " (stale — the next session start of this plugin version refreshes it)" : ""}\n`).join("") +
323
+ (agents.paths.length ? `AGENTS.md policy: ✓\n` : "") +
324
+ agents.paths.map((p) => ` ${p}${agentsStale.includes(p) ? " (stale — run: mcpbox-claude codex-init)" : ""}\n`).join("") +
325
+ skillStale.map((p) => ` ${p} (stale — run: mcpbox-claude codex-init)\n`).join("") +
293
326
  competing.map((p) => ` ! ${p} also holds a daruma CLI policy block — keep one\n`).join("") +
294
327
  `Project knowledge: ${paired ? "✓ paired" : "hint only — run: npx -y @mcpbox/mcpbox-claude login"}\n` +
295
328
  `${ready ? "READY" : "NOT READY — run: npx @mcpbox/mcpbox setup"}\n`
@@ -352,6 +385,10 @@ async function main(argv) {
352
385
  return cmdOpencodeUninit(rest);
353
386
  case "codex-policy":
354
387
  return cmdCodexPolicy(rest);
388
+ case "codex-skill":
389
+ return cmdCodexSkill();
390
+ case "codex-skill-retire":
391
+ return cmdCodexSkillRetire();
355
392
  case "cursor-policy":
356
393
  return cmdCursorPolicy(rest);
357
394
  case "doctor":
package/commands/mode.md CHANGED
@@ -6,8 +6,9 @@ The user invoked `/mcpbox:mode` with `$ARGUMENTS` = `off` | `lite` | `full` (emp
6
6
 
7
7
  ## What each level does
8
8
 
9
- - **off** — no pipeline nudging; don't raise the pipeline on your own. Raw material still
10
- isn't materialized straight into daruma — ask the user instead.
9
+ Mode sets how eagerly to suggest `mcpbox_pipeline_run`: `off` never, `lite` only when asked, `full` for any substantive request.
10
+
11
+ - **off** — no pipeline nudging; don't raise the pipeline on your own.
11
12
  - **lite** (default) — nudge toward the pipeline only when the input explicitly mentions it
12
13
  (pipeline / maturity / handoff / конвейер …).
13
14
  - **full** — assess every substantive request for **rawness**. A raw idea, hypothesis, or
@@ -22,6 +23,9 @@ anything belonging to a run still in flight — goes through the pipeline.
22
23
  The level persists across sessions (stored in `~/.agents/mcpbox/mode`) and is read by the
23
24
  UserPromptSubmit hook, which injects the matching reminder on each prompt.
24
25
 
26
+ Codex/Cursor/Kimi/OpenCode have no such hook: their `*-init` command writes the mode into the
27
+ MCP URL (`?mode=`), so re-run it after changing the mode.
28
+
25
29
  ## Steps
26
30
 
27
31
  1. Run:
package/commands/next.md CHANGED
@@ -9,7 +9,7 @@ to the user/agent to actually execute it.
9
9
 
10
10
  1. Resolve project (`daruma_workspace_info` → `default_project`).
11
11
  2. Active plan: `daruma_plan_list` filtered to `status = "active"`, most recent.
12
- If none, stop with "no active plan — create one with `daruma_plan_materialize`".
12
+ If none, stop with "no active plan — decided work: `daruma_plan_materialize`; raw idea: `/mcpbox:pipeline-run`".
13
13
  3. `daruma_plan_drain_next` with the plan id. The server atomically picks the next
14
14
  ready (unblocked) task and claims it for this session; it returns null when no
15
15
  unclaimed ready task remains.
@@ -10,15 +10,26 @@ never by materializing it directly.
10
10
  ## Steps
11
11
 
12
12
  1. If `$ARGUMENTS` is empty, ask for the raw idea/request and stop.
13
- 2. Call `mcpbox_pipeline_run { source, kind:"text", body:"<idea>" }`. It returns
13
+ 2. Call `mcpbox_pipeline_run { source, kind:"text", body:"<idea>", project_id }`.
14
+ `source` is a URI or short label of where the idea came from (as `plan.source`;
15
+ never an invented link); `project_id` comes from `daruma_workspace_info` for this
16
+ repo (omit it only if unbound). Any `kind` outside text/document/reference/binary/event
17
+ is a 422. It returns
14
18
  `run_id` immediately while the run proceeds in the background. Poll
15
19
  `mcpbox_trace_get { run_id }` until the status is no longer `running`.
16
20
  3. On failure, report the reason from `mcpbox_trace_get`; do not hand off an
17
- incomplete run.
21
+ incomplete run. Recovery: a run `failed` at layer L → retry with
22
+ `mcpbox_pipeline_advance { run_id, layer: L }` after fixing the input; fujin
23
+ `not_ready` → advance from `yatagarasu`; or ask the owner. Never
24
+ `daruma_plan_materialize` the idea directly to get around a failed run.
25
+ A 409 with `existing_run_id` means the same intake is already a run: follow that
26
+ run instead of opening another. If `mcpbox_runs_list` shows a *running* run of the
27
+ same idea you are restating, pass `relation:{supersedes:<run_id>}` to replace it.
18
28
  4. Once the run is ready for handoff, call
19
- `mcpbox_pipeline_handoff { run_id, action_packet, policy_snapshot, project_slug? }`,
20
- taking `action_packet` from `artifacts.fujin.action_packet` and
21
- `policy_snapshot` from `artifacts.policy_snapshot` in the trace. This
22
- materializes the daruma task and returns `task_id`.
29
+ `mcpbox_pipeline_handoff { run_id, project_slug? }`: the packet and policy
30
+ come from the run (an `action_packet` with another id is a 422). Without
31
+ `run_id`, pass `action_packet` and `policy_snapshot` from the trace. This
32
+ materializes the daruma task, returns `task_id` and any `warnings`
33
+ (`plan_source_*`, `source_upstream_kept`) — fix the source or ask.
23
34
  5. Verify with `mcpbox_trace_get { run_id }` (expect `status=handed_off`, a `task_id`) and
24
35
  report the run_id + task_id.
package/commands/plan.md CHANGED
@@ -8,7 +8,7 @@ The user invoked `/mcpbox:plan`.
8
8
 
9
9
  1. Resolve project (`daruma_workspace_info` → `default_project`).
10
10
  2. `daruma_plan_list status="draft,active"`, most recent first.
11
- If none, stop with "no active plan".
11
+ If none, stop with "no active plan — decided work: `daruma_plan_materialize`; raw idea: `/mcpbox:pipeline-run`".
12
12
  3. For the chosen plan, `daruma_plan_get` (single call — do not enumerate the archive).
13
13
  4. Render:
14
14
 
@@ -19,7 +19,11 @@ The user invoked `/mcpbox:status`.
19
19
  may be absent. Omit the line entirely — never print `null` or a bare UUID.
20
20
  2. Resolve the project **title** for that `project_id` via `daruma_project_list`
21
21
  (the `name` inside `scopes` is only the directory basename, not the project's
22
- title). Skip if the cwd matches no scope.
22
+ title). Skip if the cwd matches no scope. If that project carries
23
+ `possible_duplicates`, the repo was registered twice and its history is
24
+ split: add a `duplicates:` line with those ids (title, slug) and, when the
25
+ user asks about tasks, plans or findings, check each id — never conclude
26
+ history is missing from the bound id alone.
23
27
  3. One scoped `daruma_list status=active` → count open tasks (do not enumerate
24
28
  the archive).
25
29
  4. `mcpbox_runs_list` with `limit=5` (and `status=failed` if the user asked about
@@ -31,6 +35,7 @@ The user invoked `/mcpbox:status`.
31
35
  workspace: <title> (<slug>)
32
36
  account: <email>
33
37
  project: <project title> — <repo path>
38
+ duplicates: <id> (<slug>) · … — only when `possible_duplicates` is set
34
39
  open: <N> tasks
35
40
  server: ok (v<version>, sha <git_sha>) — only when `/mcpbox:doctor` ran
36
41
  runs: <run_id> <status> · <run_id> <status> …
package/hooks/hooks.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "description": "mcpbox-claude hooks: proactive session summary, capture/pipeline hints, and auto-record",
2
+ "description": "mcpbox-claude hooks: proactive session summary, capture/pipeline hints, and a Stop guard against tasks left in_progress",
3
3
  "hooks": {
4
4
  "SessionStart": [
5
5
  {
@@ -28,9 +28,7 @@
28
28
  {
29
29
  "type": "command",
30
30
  "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/stop.mjs\"",
31
- "asyncRewake": true,
32
- "rewakeMessage": "mcpbox-claude auto-record: consider capturing a reusable lesson from this session, or skip.",
33
- "rewakeSummary": "mcpbox-claude captured a session lesson"
31
+ "timeout": 10
34
32
  }
35
33
  ]
36
34
  }
@@ -110,15 +110,27 @@ async function fetchSummary() {
110
110
  export async function syncPolicy(cwd = process.cwd(), env = process.env) {
111
111
  if (env.MCPBOX_NO_POLICY_SYNC) return [];
112
112
  const paths = [];
113
- if (isCodexSurface(env)) {
113
+ // Codex has no hooks of its own (.codex-plugin declares none), so any plugin
114
+ // surface refreshes the Codex carriers too: AGENTS.md up the tree, plus the
115
+ // user-level SKILL.md — refreshed from Claude, retired from the Codex plugin.
116
+ if (env.CLAUDE_PLUGIN_ROOT && !isCodexSurface(env)) {
117
+ paths.push(...await syncPolicyBlocks({ cwd }).catch(() => []));
118
+ }
119
+ if (isCodexSurface(env) || env.CLAUDE_PLUGIN_ROOT) {
114
120
  paths.push(...await syncPolicyBlocks({ cwd, file: "AGENTS.md", block: BLOCK_BODY_PLAIN }).catch(() => []));
115
121
  try {
116
- const { syncCodexSkill } = await import("../lib/codex.mjs");
117
- const skill = await syncCodexSkill();
118
- if (skill.action === "updated") paths.push(skill.path);
122
+ const { retireCodexSkill, syncCodexSkill } = await import("../lib/codex.mjs");
123
+ if (isCodexSurface(env)) {
124
+ // Running as the Codex plugin, which ships the policy skill itself:
125
+ // a user-level copy is now a duplicate (see retireCodexSkill).
126
+ const { removed, backups } = await retireCodexSkill();
127
+ paths.push(...removed.map((dir) => `${dir} (duplicate removed: the plugin ships this skill)`));
128
+ paths.push(...backups.map((file) => `${file} (the differing copy, kept)`));
129
+ } else {
130
+ const skill = await syncCodexSkill();
131
+ if (skill.action === "updated") paths.push(skill.path);
132
+ }
119
133
  } catch { /* skill dir unwritable — AGENTS.md sync still counts */ }
120
- } else if (env.CLAUDE_PLUGIN_ROOT) {
121
- paths.push(...await syncPolicyBlocks({ cwd }).catch(() => []));
122
134
  }
123
135
  return paths;
124
136
  }
@@ -172,7 +184,7 @@ export async function main() {
172
184
 
173
185
  const lines = [header, ...shown.map(formatTask)];
174
186
  if (extra > 0) lines.push(` …and ${extra} more — /mcpbox:tasks for full list`);
175
- lines.push("→ /mcpbox:next to claim the next task | /mcpbox:status for server + pipeline health");
187
+ lines.push("→ /mcpbox:next to claim the next task | /mcpbox:status for server + pipeline health | raw idea: /mcpbox:pipeline-run");
176
188
 
177
189
  writeHookOutput("SessionStart", syncNote + lines.join("\n"), { systemMessage });
178
190
  process.exit(0);
package/hooks/stop.mjs CHANGED
@@ -1,32 +1,103 @@
1
1
  #!/usr/bin/env node
2
- // Stop hook: auto-record nudge. Prints a <system-reminder>-style hint so Claude
3
- // considers capturing a reusable lesson via daruma_comment at session end.
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.
4
5
  //
5
- // Prints nothing when there is no active tracked task (MCPBOX_ACTIVE_TASK env
6
- // absent), so it only fires when the agent was working on a tracked task.
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.
7
12
  //
8
- // asyncRewake: true in hooks.json re-wakes Claude with the rewakeMessage only
9
- // when this script exits 0 AND prints non-empty output.
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.
10
16
 
17
+ import { readFile, stat, writeFile } from "node:fs/promises";
11
18
  import { pathToFileURL } from "node:url";
12
19
 
13
- import { writeHookOutput } from "../lib/hook-output.mjs";
20
+ import { callCloudTool, readCredentials } from "../lib/cloud-knowledge.mjs";
21
+ import { readStdin, sessionMarker } from "../lib/hook-input.mjs";
14
22
 
15
- export function stopHookMessage(activeTask = "") {
16
- if (!activeTask) return "";
17
- return (
18
- `[mcpbox/auto-record] Active task: ${activeTask}\n` +
19
- `If this session produced a concrete reusable lesson (command, invariant, bug pattern, file path), ` +
20
- `capture it now via /mcpbox:capture or call daruma_comment directly:\n` +
21
- ` daruma_comment task_id="${activeTask}" body="lesson: <short durable lesson>"\n` +
22
- `Skip if there is nothing durable to record.\n`
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),
23
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 };
24
60
  }
25
61
 
26
- function main() {
27
- writeHookOutput("Stop", stopHookMessage(process.env.MCPBOX_ACTIVE_TASK ?? ""));
62
+ async function main() {
63
+ let payload = null;
64
+ try {
65
+ payload = JSON.parse(await readStdin());
66
+ } catch {
67
+ return;
68
+ }
69
+ const sessionId = typeof payload?.session_id === "string" ? payload.session_id : "";
70
+ const cwd = typeof payload?.cwd === "string" && payload.cwd ? payload.cwd : process.cwd();
71
+ if (!sessionId) return;
72
+ const marker = sessionMarker(sessionId);
73
+ const since = await stat(marker).then((s) => s.mtimeMs, () => null);
74
+ if (since === null) return;
75
+ const creds = await readCredentials();
76
+ 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;
97
+ }
98
+ process.stdout.write(`${JSON.stringify({ decision: "block", reason: decision.reason })}\n`);
28
99
  }
29
100
 
30
101
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
31
- main();
102
+ main().catch(() => {});
32
103
  }
@@ -14,7 +14,6 @@
14
14
  // Claude Code — this also covers Claude setups without the env var).
15
15
 
16
16
  import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
17
- import { homedir } from "node:os";
18
17
  import { join } from "node:path";
19
18
  import { pathToFileURL } from "node:url";
20
19
 
@@ -25,6 +24,7 @@ import {
25
24
  formatKnowledge,
26
25
  readCredentials,
27
26
  } from "../lib/cloud-knowledge.mjs";
27
+ import { SESSION_MARKERS, readStdin, sessionMarker } from "../lib/hook-input.mjs";
28
28
  import { writeHookOutput } from "../lib/hook-output.mjs";
29
29
  import { readMode } from "../lib/mode.mjs";
30
30
  import { checkForUpdate, updateNotice } from "../lib/update-check.mjs";
@@ -41,7 +41,7 @@ const PATTERNS = [
41
41
  {
42
42
  // create / import — ACTION + task/issue OBJECT (avoids bare-verb false positives).
43
43
  re: /\b(add|create|new|log|move|import)\s+(a\s+|an\s+)?(task|issue|ticket|subtask)\b|(?<![а-яёА-ЯЁ])(добавь|добавить|заведи|завести|создай|создать)\s+(задачу|таск|подзадачу|тикет)(?![а-яёА-ЯЁ])|(?<![а-яёА-ЯЁ])(перенеси|перенести|импортируй|заведи)\s+(ишью|задачу|таск|тикет|issue)(?![а-яёА-ЯЁ])/,
44
- hint: "[mcpbox] Detected task-intake/import intent → daruma_plan_materialize (tasks are created only with a plan; an external issue is its source — plan.source.ref = the issue URL, not a second tracker). Adding to an EXISTING plan: still materialize (no bare-task intake), then attach via daruma_plan_add_task (recompose) or pass parent_plan_id. Not a lookup — don't treat the id as an existing task.",
44
+ hint: "[mcpbox] Detected task-intake/import intent → daruma_plan_materialize (tasks are created only with a plan; an external issue is its source — plan.source.ref = the issue URL, not a second tracker). Raw / undecided → mcpbox_pipeline_run instead. Adding to an EXISTING plan: still materialize (no bare-task intake), then attach via daruma_plan_add_task (recompose) or pass parent_plan_id. Not a lookup — don't treat the id as an existing task.",
45
45
  },
46
46
  {
47
47
  // "Создай план" / "make a plan": the plan goes to mcpbox, not into chat.
@@ -93,6 +93,11 @@ const PATTERNS = [
93
93
  const OPERATIONAL_EXIT =
94
94
  "If this is an operational action you can just carry out — start/restart something, read a log, check status, open a file, answer a question — do it and record nothing, in neither daruma nor the pipeline. Otherwise: ";
95
95
 
96
+ // full mode: after the exit and before any pattern hint — raw material goes to
97
+ // the pipeline first, so no hint reads as "straight to daruma".
98
+ const RAW_FIRST =
99
+ "Raw material (idea, hypothesis, undecided direction) → mcpbox_pipeline_run first; only decided, bounded work follows the hint: ";
100
+
96
101
  const FULL_ASSESS_HINT =
97
102
  "[mcpbox:full] " + OPERATIONAL_EXIT + "assess rawness: only raw material — an idea, hypothesis, or undecided direction — goes to mcpbox_pipeline_run. Work that is already decided and bounded, and follow-up work extending a run that has already handed off (it has a task_id), both go straight to daruma via daruma_plan_materialize. A run still in flight is not a shortcut — finish it first.";
98
103
 
@@ -109,35 +114,14 @@ export function promptSubmitHint(promptText = "", mode = "lite") {
109
114
  for (const { re, hint } of patterns) {
110
115
  if (re.test(prompt)) {
111
116
  // A keyword match is a guess about intent, not a verdict on it — in full
112
- // mode the operational exit goes ahead of the guess.
113
- return mode === "full" ? `[mcpbox:full] ${OPERATIONAL_EXIT}${hint}` : hint;
117
+ // mode the operational exit and the rawness check go ahead of the guess.
118
+ return mode === "full" ? `[mcpbox:full] ${OPERATIONAL_EXIT}${RAW_FIRST}${hint}` : hint;
114
119
  }
115
120
  }
116
121
  if (mode === "full" && prompt.length >= SUBSTANTIVE_MIN) return FULL_ASSESS_HINT;
117
122
  return "";
118
123
  }
119
124
 
120
- // Reads stdin to EOF with a timeout so a hook caller that keeps stdin open
121
- // can never hang the prompt submit path.
122
- function readStdin(timeoutMs = 3000) {
123
- return new Promise((resolve) => {
124
- if (process.stdin.isTTY) return resolve("");
125
- let raw = "";
126
- const done = () => {
127
- clearTimeout(timer);
128
- resolve(raw);
129
- };
130
- const timer = setTimeout(() => {
131
- process.stdin.destroy();
132
- resolve(raw);
133
- }, timeoutMs);
134
- process.stdin.setEncoding("utf8");
135
- process.stdin.on("data", (chunk) => { raw += chunk; });
136
- process.stdin.on("end", done);
137
- process.stdin.on("error", done);
138
- });
139
- }
140
-
141
125
  // Kimi's UserPromptSubmit payload carries the prompt text; the exact field
142
126
  // name is not documented, so accept the common shapes. Kimi sends it as an
143
127
  // array of content blocks — `prompt: [{type: "text", text: "…"}]` — which the
@@ -163,7 +147,6 @@ export function promptFromHookPayload(payload) {
163
147
  // Without a session id there is no "first": callers treat it as not first.
164
148
  // Markers older than a week are swept on each successful claim, so the
165
149
  // directory stays bounded however many sessions run.
166
- const SESSION_MARKERS = () => join(homedir(), ".agents", "mcpbox", "sessions");
167
150
  const MARKER_TTL_MS = 7 * 24 * 3600 * 1000;
168
151
 
169
152
  function sweepMarkers(dir) {
@@ -182,7 +165,7 @@ export async function claimFirstPrompt(payload) {
182
165
  const dir = SESSION_MARKERS();
183
166
  try {
184
167
  await mkdir(dir, { recursive: true });
185
- await writeFile(join(dir, sessionId.replace(/[^\w.-]/g, "_")), "", { flag: "wx" });
168
+ await writeFile(sessionMarker(sessionId), "", { flag: "wx" });
186
169
  } catch {
187
170
  return false;
188
171
  }
@@ -145,20 +145,14 @@ export function toolResult(text) {
145
145
  throw new Error("unrecognised tool response");
146
146
  }
147
147
 
148
- export async function fetchProjectKnowledge(cwd, { creds, budget = KNOWLEDGE_BUDGET, timeoutMs = 2500 } = {}) {
148
+ // One tools/call on the cloud MCP with the paired bearer. null when the
149
+ // machine is not paired; throws on network/server errors (401 → `rejected`).
150
+ export async function callCloudTool(name, args, { creds, timeoutMs = 2500 } = {}) {
149
151
  const auth = creds ?? (await readCredentials());
150
152
  if (!auth) return null;
151
153
  const res = await postJson(
152
154
  `${normalizeBaseUrl(auth.base_url ?? DEFAULT_BASE_URL)}/v1/mcp`,
153
- {
154
- jsonrpc: "2.0",
155
- id: 1,
156
- method: "tools/call",
157
- params: {
158
- name: "mcpbox_knowledge_read",
159
- arguments: { scope: "project", scope_path: cwd, kinds: KNOWLEDGE_KINDS, budget },
160
- },
161
- },
155
+ { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } },
162
156
  {
163
157
  Accept: "application/json, text/event-stream",
164
158
  Authorization: `Bearer ${auth.access_token}`,
@@ -170,10 +164,18 @@ export async function fetchProjectKnowledge(cwd, { creds, budget = KNOWLEDGE_BUD
170
164
  if (res.status === 401) {
171
165
  throw Object.assign(new Error("pairing token rejected"), { rejected: true });
172
166
  }
173
- if (res.status !== 200) throw new Error(`knowledge read failed (${res.status})`);
167
+ if (res.status !== 200) throw new Error(`${name} failed (${res.status})`);
174
168
  return toolResult(res.text);
175
169
  }
176
170
 
171
+ export function fetchProjectKnowledge(cwd, { creds, budget = KNOWLEDGE_BUDGET, timeoutMs = 2500 } = {}) {
172
+ return callCloudTool(
173
+ "mcpbox_knowledge_read",
174
+ { scope: "project", scope_path: cwd, kinds: KNOWLEDGE_KINDS, budget },
175
+ { creds, timeoutMs },
176
+ );
177
+ }
178
+
177
179
  // Knowledge rows as context. They are workspace data anyone in the workspace
178
180
  // could have written, so they travel as JSON between a fixed pair of markers:
179
181
  // escaped newlines mean a row can neither forge a `[mcpbox]` hook line nor