@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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcpbox-claude",
3
3
  "description": "MCPBox × Claude Code glue. Drives the mcpbox MCP server (daruma tracker + full MeiSei pipeline torii→…→fujin→daruma). Ships /mcpbox:{tasks,plan,next,mine,status,close,sync,capture,doctor,mode} and pipeline commands, SessionStart/Stop/UserPromptSubmit hooks, and a managed CLAUDE.md policy that makes mcpbox the default tracker AND pipeline substrate.",
4
- "version": "0.1.18",
4
+ "version": "0.1.20",
5
5
  "author": {
6
6
  "name": "tupical"
7
7
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcpbox",
3
- "version": "0.1.18",
3
+ "version": "0.1.20",
4
4
  "description": "MCPBox agent stack for Codex: the daruma tracker plus the MeiSei maturity pipeline behind one MCP server.",
5
5
  "author": {
6
6
  "name": "tupical"
package/README.md CHANGED
@@ -60,9 +60,37 @@ npx -y @mcpbox/mcpbox-claude@latest kimi-init
60
60
  npx -y @mcpbox/mcpbox-claude@latest opencode-init
61
61
  ```
62
62
 
63
+ On Claude and Codex a plugin update also reaches the policy you already
64
+ 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
67
+ session context. It never adds a block and never touches text outside the
68
+ markers; `doctor --json` reports `policy_stale` until it has run. Set
69
+ `MCPBOX_NO_POLICY_SYNC=1` to keep installed blocks as they are.
70
+
71
+ ### Project knowledge in every session
72
+
73
+ Agents answer repo questions right when they have the project's knowledge
74
+ (`mcpbox_knowledge_read`) in front of them, and rarely fetch it on their own.
75
+ Pair the machine once so the first prompt of every session carries it:
76
+
77
+ ```bash
78
+ npx -y @mcpbox/mcpbox-claude login # confirm the code in the browser
79
+ ```
80
+
81
+ The workspace-bound token is kept in `~/.agents/mcpbox/credentials.json`
82
+ (mode 0600) and only ever sent over https; `logout` deletes the file, and
83
+ revoking the token itself happens in the workspace settings (Tokens). The
84
+ repo path of each new session goes to the server to find its project. Unpaired, rejected, or with the path
85
+ unbound in the paired workspace, the hook adds a ready `mcpbox_knowledge_read`
86
+ call instead of the text. Knowledge rows arrive
87
+ marked as workspace data, not instructions. Mode `off` disables both.
88
+
63
89
  A stale version announces itself at session start on Claude, Codex, and Kimi.
64
- Cursor exposes no hooks at all, so nothing can announce anything there — check
65
- manually, or let `cursor-init` in a routine update pass do it. Set
90
+ The Cursor adapter's only hook is the user-level `sessionStart` that carries
91
+ the policy (global installs); it does no update check, so nothing announces
92
+ anything there — check manually, or let
93
+ `cursor-init` in a routine update pass do it. Set
66
94
  `MCPBOX_NO_UPDATE_CHECK=1` to disable the registry lookup entirely (air-gapped
67
95
  installs, CI).
68
96
 
@@ -72,7 +100,7 @@ installs, CI).
72
100
  |--------|----------------------------------------|-------------------------------------|-------|
73
101
  | Claude | `CLAUDE.md` block + plugin (hooks, `/mcpbox:*`) | `claude mcp add` (`.mcp.json` / `~/.claude.json`) | plugin `hooks.json` |
74
102
  | Codex | `AGENTS.md` block + model-invoked plugin skills | `[mcp_servers.mcpbox]` in `~/.codex/config.toml` | — |
75
- | Cursor | `.cursor/rules/mcpbox-policy.mdc` + `/mcpbox-mode` | `mcpbox` entry in `.cursor/mcp.json` | — |
103
+ | Cursor | `.cursor/rules/mcpbox-policy.mdc` + `/mcpbox-mode` (repo); in `$HOME` a `sessionStart` hook in `~/.cursor/hooks.json` instead — Cursor reads no `~/.cursor/rules` | `mcpbox` entry in `.cursor/mcp.json` | `~/.cursor/hooks.json` `sessionStart` (global only) |
76
104
  | Kimi | `AGENTS.md` block (`mcpbox:policy`) | `mcpbox` entry in `~/.kimi-code/mcp.json` | `[[hooks]]` block in `~/.kimi-code/config.toml` |
77
105
  | OpenCode | `AGENTS.md` block (`mcpbox:policy`) | `mcpbox` remote entry under `mcp` in `~/.config/opencode/opencode.json` | — |
78
106
 
@@ -101,7 +129,8 @@ mcpbox-claude init [--dir DIR] Managed CLAUDE.md policy block. Idempote
101
129
  mcpbox-claude uninit [--dir DIR] Remove the CLAUDE.md policy block.
102
130
  mcpbox-claude codex-init [--dir DIR] AGENTS.md policy + config.toml server + routing skill.
103
131
  mcpbox-claude codex-uninit [--dir DIR]
104
- mcpbox-claude cursor-init [--dir DIR] .cursor/rules policy + .cursor/mcp.json server.
132
+ mcpbox-claude cursor-init [--dir DIR] .cursor/rules policy + .cursor/mcp.json server
133
+ (in $HOME: ~/.cursor/hooks.json sessionStart hook).
105
134
  mcpbox-claude cursor-uninit [--dir DIR]
106
135
  mcpbox-claude kimi-init [--dir DIR] AGENTS.md policy + ~/.kimi-code/mcp.json server
107
136
  + ~/.kimi-code/config.toml [[hooks]].
@@ -147,6 +176,7 @@ approved by the owner with a $0.30 cap; no local instruction text is published.
147
176
 
148
177
  The managed policy is a compact index (at most 100 lines) for all clients.
149
178
  It retains tracker safety rules, mode handling and tool/skill entry points.
150
- The routing decision tree is supplied by MCP `initialize.instructions`
151
- (`PLATFORM_INSTRUCTIONS`); clients without command skills use the plain tool
179
+ Routing and the execution-path verification rule before editing are supplied by
180
+ MCP `initialize.instructions` (`PLATFORM_INSTRUCTIONS` in
181
+ `crates/cloud-api/src/v1_gateway.rs`); clients without command skills use the plain tool
152
182
  entry points. Reconnect the MCP server if its instructions are unavailable.
@@ -19,13 +19,20 @@ 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 } from "../lib/policy.mjs";
22
+ import { installPolicy, removePolicy, policyHierarchy, stalePolicyPaths, competingPolicyPaths } from "../lib/policy.mjs";
23
+ import { credentialsPath, login, logout, readCredentials } from "../lib/cloud-knowledge.mjs";
23
24
  import { installCodex, removeCodex, installCodexPolicy } from "../lib/codex.mjs";
24
25
  import {
25
26
  installCursor,
26
27
  removeCursor,
27
28
  installCursorRule,
29
+ removeCursorRule,
30
+ installCursorMcp,
31
+ removeCursorMcp,
28
32
  installCursorModeCommand,
33
+ removeCursorModeCommand,
34
+ installCursorSessionHook,
35
+ removeCursorSessionHook,
29
36
  } from "../lib/cursor.mjs";
30
37
  import { installKimi, removeKimi } from "../lib/kimi.mjs";
31
38
  import { installOpencode, removeOpencode } from "../lib/opencode.mjs";
@@ -46,6 +53,8 @@ Usage:
46
53
  mcpbox-claude codex-uninit [--dir DIR]
47
54
  mcpbox-claude cursor-init [--dir DIR] Write .cursor/rules/mcpbox-policy.mdc +
48
55
  .cursor/mcp.json mcpbox entry. Idempotent.
56
+ In $HOME the policy goes to a sessionStart
57
+ hook in ~/.cursor/hooks.json instead.
49
58
  mcpbox-claude cursor-uninit [--dir DIR]
50
59
  mcpbox-claude kimi-init [--dir DIR] Write AGENTS.md policy + ~/.kimi-code/mcp.json
51
60
  mcpbox entry + [[hooks]] in ~/.kimi-code/config.toml.
@@ -56,6 +65,8 @@ Usage:
56
65
  opencode.json. Idempotent.
57
66
  mcpbox-claude opencode-uninit [--dir DIR]
58
67
  mcpbox-claude doctor [--json] Check the mcpbox MCP server + policy are wired.
68
+ mcpbox-claude login Pair this machine so hooks load project knowledge.
69
+ mcpbox-claude logout Forget the pairing token.
59
70
  mcpbox-claude mode [off|lite|full] Get/set pipeline strictness (how raw ideas route).
60
71
  mcpbox-claude export-marketplace [--dir DIR]
61
72
  Mirror this package to a stable directory usable as
@@ -88,6 +99,7 @@ const VERB = {
88
99
  "removed-block": "Removed mcpbox block from",
89
100
  "removed-file": "Removed",
90
101
  missing: "No mcpbox block found at",
102
+ malformed: "Left alone (broken or repeated mcpbox markers — fix by hand):",
91
103
  };
92
104
 
93
105
  async function cmdInit(rest) {
@@ -124,8 +136,26 @@ async function cmdCodexUninit(rest) {
124
136
  report(prompts);
125
137
  }
126
138
 
139
+ // Cursor ignores ~/.cursor/rules: in the home dir the policy goes through the
140
+ // user-level sessionStart hook, and a rule left by older installs is dropped.
141
+ function isHomeDir(projectDir) {
142
+ return resolve(projectDir ?? process.cwd()) === resolve(homedir());
143
+ }
144
+
145
+ async function installCursorHome(homeDir) {
146
+ report(await installCursorSessionHook({ homeDir }));
147
+ const stale = await removeCursorRule({ projectDir: homeDir });
148
+ if (stale.action !== "missing") report(stale);
149
+ report(await installCursorModeCommand({ projectDir: homeDir }));
150
+ }
151
+
127
152
  async function cmdCursorInit(rest) {
128
153
  const { projectDir } = parseDirFlag(rest);
154
+ if (isHomeDir(projectDir)) {
155
+ await installCursorHome(homedir());
156
+ report(await installCursorMcp({ projectDir: homedir() }));
157
+ return;
158
+ }
129
159
  const { rule, mcp, mode } = await installCursor({ projectDir });
130
160
  report(rule);
131
161
  report(mcp);
@@ -134,6 +164,13 @@ async function cmdCursorInit(rest) {
134
164
 
135
165
  async function cmdCursorUninit(rest) {
136
166
  const { projectDir } = parseDirFlag(rest);
167
+ if (isHomeDir(projectDir)) {
168
+ report(await removeCursorSessionHook({ homeDir: homedir() }));
169
+ report(await removeCursorRule({ projectDir: homedir() }));
170
+ report(await removeCursorMcp({ projectDir: homedir() }));
171
+ report(await removeCursorModeCommand({ projectDir: homedir() }));
172
+ return;
173
+ }
137
174
  const { rule, mcp, mode } = await removeCursor({ projectDir });
138
175
  report(rule);
139
176
  report(mcp);
@@ -179,6 +216,7 @@ async function cmdCodexPolicy(rest) {
179
216
 
180
217
  async function cmdCursorPolicy(rest) {
181
218
  const { projectDir } = parseDirFlag(rest);
219
+ if (isHomeDir(projectDir)) return installCursorHome(homedir());
182
220
  report(await installCursorRule({ projectDir }));
183
221
  report(await installCursorModeCommand({ projectDir }));
184
222
  }
@@ -201,6 +239,25 @@ async function cmdMode(rest) {
201
239
  process.stdout.write(`✓ mcpbox pipeline mode: ${m}\n`);
202
240
  }
203
241
 
242
+ // Pairs this machine with a workspace so hooks can put its project knowledge
243
+ // into new sessions (lib/cloud-knowledge.mjs). The token stays in
244
+ // ~/.agents/mcpbox/credentials.json, readable by this user only.
245
+ async function cmdLogin(rest) {
246
+ const i = rest.indexOf("--base-url");
247
+ const baseUrl = i !== -1 ? rest[i + 1] : undefined;
248
+ if (i !== -1 && (!baseUrl || baseUrl.startsWith("--"))) throw new Error("--base-url needs a value");
249
+ const creds = await login(baseUrl ? { baseUrl } : {});
250
+ process.stdout.write(`✓ Paired with workspace ${creds.workspace_id}; token in ${credentialsPath()}\n`);
251
+ }
252
+
253
+ async function cmdLogout() {
254
+ await logout();
255
+ process.stdout.write(
256
+ `✓ Removed ${credentialsPath()}\n` +
257
+ "The token itself stays valid until revoked in the workspace settings (Tokens).\n",
258
+ );
259
+ }
260
+
204
261
  async function cmdDoctor(rest) {
205
262
  const json = rest.includes("--json");
206
263
  const flags = rest.filter((a) => a !== "--json");
@@ -210,15 +267,31 @@ async function cmdDoctor(rest) {
210
267
  const policy = hierarchy.present;
211
268
  const mcp = mcpServerPresent();
212
269
  const ready = policy && !hierarchy.duplicate && mcp === true;
270
+ // Stale is a warning, not NOT READY: the next SessionStart refreshes it.
271
+ const stale = await stalePolicyPaths(hierarchy.paths);
272
+ // Also a warning: two policies in one file, one of them from the daruma CLI.
273
+ const competing = await competingPolicyPaths({ projectDir });
274
+ // Not required: without it hooks hint at the knowledge instead of loading it.
275
+ const paired = (await readCredentials()) !== null;
213
276
 
214
277
  if (json) {
215
- process.stdout.write(JSON.stringify({ ready, policy, mcp, policy_paths: hierarchy.paths, policy_duplicate: hierarchy.duplicate }) + "\n");
278
+ process.stdout.write(JSON.stringify({
279
+ ready, policy, mcp,
280
+ policy_paths: hierarchy.paths,
281
+ policy_duplicate: hierarchy.duplicate,
282
+ policy_stale: stale.length > 0,
283
+ policy_stale_paths: stale,
284
+ policy_competing_paths: competing,
285
+ knowledge_paired: paired,
286
+ }) + "\n");
216
287
  } else {
217
288
  const mark = (v) => (v === true ? "✓" : v === false ? "✗" : "?");
218
289
  process.stdout.write(
219
290
  `mcpbox MCP server: ${mark(mcp)}${mcp === null ? " (claude CLI not found)" : ""}\n` +
220
291
  `CLAUDE.md policy: ${mark(policy)}${hierarchy.duplicate ? " (duplicate managed blocks)" : ""}\n` +
221
- hierarchy.paths.map((p) => ` ${p}\n`).join("") +
292
+ hierarchy.paths.map((p) => ` ${p}${stale.includes(p) ? " (stale — the next session start of this plugin version refreshes it)" : ""}\n`).join("") +
293
+ competing.map((p) => ` ! ${p} also holds a daruma CLI policy block — keep one\n`).join("") +
294
+ `Project knowledge: ${paired ? "✓ paired" : "hint only — run: npx -y @mcpbox/mcpbox-claude login"}\n` +
222
295
  `${ready ? "READY" : "NOT READY — run: npx @mcpbox/mcpbox setup"}\n`
223
296
  );
224
297
  }
@@ -283,6 +356,10 @@ async function main(argv) {
283
356
  return cmdCursorPolicy(rest);
284
357
  case "doctor":
285
358
  return cmdDoctor(rest);
359
+ case "login":
360
+ return cmdLogin(rest);
361
+ case "logout":
362
+ return cmdLogout();
286
363
  case "mode":
287
364
  return cmdMode(rest);
288
365
  case "export-marketplace":
@@ -11,5 +11,9 @@ The user invoked `/mcpbox:doctor`.
11
11
  `npx @mcpbox/mcpbox setup` and restart Claude Code.
12
12
  2. Reachability: `daruma_healthz`. Report version + git_sha, or the failure verbatim.
13
13
  3. Policy: confirm this project's `CLAUDE.md` contains the `mcpbox:policy` managed block.
14
- If missing, `npx -y @mcpbox/mcpbox-claude init` (or re-run setup).
14
+ If missing, `npx -y @mcpbox/mcpbox-claude init` (or re-run setup). If
15
+ `npx -y @mcpbox/mcpbox-claude doctor --json` reports `policy_stale`, the block
16
+ predates the installed plugin; the next session start refreshes it. Paths in
17
+ `policy_competing_paths` also carry a daruma CLI policy block
18
+ (`daruma-claude` / `daruma-codex`); tell the user to keep one of the two.
15
19
  4. Render a short checklist with ✓ / ✗ per item and a final READY / NOT READY line.
@@ -18,6 +18,7 @@
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";
21
22
  import { checkForUpdate, updateNotice } from "../lib/update-check.mjs";
22
23
  import { VERSION } from "../lib/version.mjs";
23
24
  import { pathToFileURL } from "node:url";
@@ -101,8 +102,29 @@ async function fetchSummary() {
101
102
  }
102
103
  }
103
104
 
105
+ // Bring the policy blocks already installed around cwd up to this plugin
106
+ // version (see syncPolicyBlocks). Failures stay silent: a read-only tree must
107
+ // never block the session. MCPBOX_NO_POLICY_SYNC=1 opts out. Only the plugin
108
+ // surfaces sync: Kimi runs a copy frozen at kimi-init (no CLAUDE_PLUGIN_ROOT,
109
+ // no PLUGIN_DATA), whose policy would be stale by construction.
110
+ export async function syncPolicy(cwd = process.cwd(), env = process.env) {
111
+ if (env.MCPBOX_NO_POLICY_SYNC) return [];
112
+ const paths = [];
113
+ if (isCodexSurface(env)) {
114
+ paths.push(...await syncPolicyBlocks({ cwd, file: "AGENTS.md", block: BLOCK_BODY_PLAIN }).catch(() => []));
115
+ try {
116
+ const { syncCodexSkill } = await import("../lib/codex.mjs");
117
+ const skill = await syncCodexSkill();
118
+ if (skill.action === "updated") paths.push(skill.path);
119
+ } catch { /* skill dir unwritable — AGENTS.md sync still counts */ }
120
+ } else if (env.CLAUDE_PLUGIN_ROOT) {
121
+ paths.push(...await syncPolicyBlocks({ cwd }).catch(() => []));
122
+ }
123
+ return paths;
124
+ }
125
+
104
126
  export async function main() {
105
- const [data, update] = await Promise.all([
127
+ const [data, update, synced] = await Promise.all([
106
128
  fetchSummary().catch((err) => {
107
129
  if (process.env.MCPBOX_DEBUG) {
108
130
  process.stderr.write(`[mcpbox-claude/session-start] error: ${err?.message ?? err}\n`);
@@ -110,13 +132,22 @@ export async function main() {
110
132
  return null;
111
133
  }),
112
134
  checkForUpdate({ current: VERSION }),
135
+ syncPolicy(),
113
136
  ]);
114
- const systemMessage = update?.outdated
115
- ? updateNotice(update.current, update.latest, isCodexSurface() ? "codex" : "claude")
116
- : undefined;
137
+ const syncNote = synced.length
138
+ ? `[mcpbox] Policy block refreshed to plugin ${VERSION}: ${synced.join(", ")}\n`
139
+ : "";
140
+ // The user sees what we wrote into their files, not just the model.
141
+ const notices = [
142
+ update?.outdated
143
+ ? updateNotice(update.current, update.latest, isCodexSurface() ? "codex" : "claude")
144
+ : null,
145
+ synced.length ? `mcpbox: policy block refreshed to ${VERSION} in ${synced.join(", ")}` : null,
146
+ ].filter(Boolean);
147
+ const systemMessage = notices.length ? notices.join("\n") : undefined;
117
148
 
118
149
  if (!data) {
119
- writeHookOutput("SessionStart", "", { systemMessage });
150
+ writeHookOutput("SessionStart", syncNote, { systemMessage });
120
151
  process.exit(0);
121
152
  }
122
153
 
@@ -125,7 +156,7 @@ export async function main() {
125
156
  if (!tasks || tasks.length === 0) {
126
157
  writeHookOutput(
127
158
  "SessionStart",
128
- "[mcpbox] No open tasks — run /mcpbox:tasks to verify, or /mcpbox:pipeline-run \"<idea>\" to open a maturity run.",
159
+ syncNote + "[mcpbox] No open tasks — run /mcpbox:tasks to verify, or /mcpbox:pipeline-run \"<idea>\" to open a maturity run.",
129
160
  { systemMessage },
130
161
  );
131
162
  process.exit(0);
@@ -143,7 +174,7 @@ export async function main() {
143
174
  if (extra > 0) lines.push(` …and ${extra} more — /mcpbox:tasks for full list`);
144
175
  lines.push("→ /mcpbox:next to claim the next task | /mcpbox:status for server + pipeline health");
145
176
 
146
- writeHookOutput("SessionStart", lines.join("\n"), { systemMessage });
177
+ writeHookOutput("SessionStart", syncNote + lines.join("\n"), { systemMessage });
147
178
  process.exit(0);
148
179
  }
149
180
 
@@ -13,11 +13,18 @@
13
13
  // event JSON on stdin (Kimi Code passes the payload via stdin, and so does
14
14
  // Claude Code — this also covers Claude setups without the env var).
15
15
 
16
- import { mkdir, readFile, writeFile } from "node:fs/promises";
16
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
17
17
  import { homedir } from "node:os";
18
- import { dirname, join } from "node:path";
18
+ import { join } from "node:path";
19
19
  import { pathToFileURL } from "node:url";
20
20
 
21
+ import {
22
+ KNOWLEDGE_BUDGET,
23
+ KNOWLEDGE_KINDS,
24
+ fetchProjectKnowledge,
25
+ formatKnowledge,
26
+ readCredentials,
27
+ } from "../lib/cloud-knowledge.mjs";
21
28
  import { writeHookOutput } from "../lib/hook-output.mjs";
22
29
  import { readMode } from "../lib/mode.mjs";
23
30
  import { checkForUpdate, updateNotice } from "../lib/update-check.mjs";
@@ -137,6 +144,39 @@ export function promptFromHookPayload(payload) {
137
144
  return "";
138
145
  }
139
146
 
147
+ // Whether this is the session's first prompt, claimed once through an empty
148
+ // marker file per session (`wx` fails when the marker already exists).
149
+ // Without a session id there is no "first": callers treat it as not first.
150
+ // Markers older than a week are swept on each successful claim, so the
151
+ // directory stays bounded however many sessions run.
152
+ const SESSION_MARKERS = () => join(homedir(), ".agents", "mcpbox", "sessions");
153
+ const MARKER_TTL_MS = 7 * 24 * 3600 * 1000;
154
+
155
+ function sweepMarkers(dir) {
156
+ const now = Date.now();
157
+ readdir(dir)
158
+ .then((names) => Promise.all(names.map(async (name) => {
159
+ const marker = join(dir, name);
160
+ if (now - (await stat(marker)).mtimeMs > MARKER_TTL_MS) await rm(marker, { force: true });
161
+ }).map((p) => p.catch(() => {}))))
162
+ .catch(() => { /* best effort */ });
163
+ }
164
+
165
+ export async function claimFirstPrompt(payload) {
166
+ const sessionId = typeof payload?.session_id === "string" ? payload.session_id : "";
167
+ if (!sessionId) return false;
168
+ const dir = SESSION_MARKERS();
169
+ try {
170
+ await mkdir(dir, { recursive: true });
171
+ await writeFile(join(dir, sessionId.replace(/[^\w.-]/g, "_")), "", { flag: "wx" });
172
+ } catch {
173
+ return false;
174
+ }
175
+ // Off the critical path: the prompt does not wait for the sweep.
176
+ sweepMarkers(dir);
177
+ return true;
178
+ }
179
+
140
180
  // Kimi never fires SessionStart (its hook block registers it, but the event
141
181
  // does not arrive) and it reads AGENTS.md from the working directory ONLY —
142
182
  // no walk up the tree, no user-level instruction file. A globally-installed
@@ -144,56 +184,78 @@ export function promptFromHookPayload(payload) {
144
184
  // agent answers "no such command" to `mcpbox mode`. UserPromptSubmit does
145
185
  // fire, so for Kimi the policy rides in on the first prompt of a session.
146
186
  // Claude registers this hook without --policy: it reads CLAUDE.md already.
147
- async function policyForFirstPrompt(payload) {
148
- if (!process.argv.includes("--policy")) return { policy: "", firstPrompt: false };
187
+ async function policyForPrompt(payload, firstPrompt) {
188
+ if (!process.argv.includes("--policy")) return "";
149
189
  // PLAIN: this path only ever serves non-Claude surfaces, which have no
150
190
  // /mcpbox:* commands.
151
191
  const { BLOCK_BODY_PLAIN, BEGIN } = await import("../lib/policy.mjs");
152
192
  const cwd = typeof payload?.cwd === "string" && payload.cwd ? payload.cwd : process.cwd();
153
- let policy = BLOCK_BODY_PLAIN;
154
193
  try {
155
194
  // An AGENTS.md right here already carries the block — the agent is
156
195
  // reading it, so a second copy would be pure noise.
157
- if ((await readFile(join(cwd, "AGENTS.md"), "utf8")).includes(BEGIN)) policy = "";
196
+ if ((await readFile(join(cwd, "AGENTS.md"), "utf8")).includes(BEGIN)) return "";
158
197
  } catch { /* no AGENTS.md here — the policy has to come from us */ }
198
+ // No session id: the policy repeats on every prompt rather than never.
199
+ return firstPrompt || !payload?.session_id ? BLOCK_BODY_PLAIN : "";
200
+ }
159
201
 
160
- if (!policy) return { policy: "", firstPrompt: false };
161
- const sessionId = typeof payload?.session_id === "string" ? payload.session_id : "";
162
- if (!sessionId) return { policy, firstPrompt: false }; // policy repeats; update notices must not
163
- // ponytail: one empty marker file per session, never swept. They are 0
164
- // bytes; add a cleanup pass only if a long-lived install ever complains.
165
- const marker = join(homedir(), ".agents", "mcpbox", "sessions", sessionId.replace(/[^\w.-]/g, "_"));
202
+ // Project knowledge is read only when the agent is told to, next to the
203
+ // question, with a call it can make as is (measured 2026-09-27, ADR-0010 D4:
204
+ // the same three repo questions, 6/6 right when told to read vs 1/5 as
205
+ // usual; a policy line alone was ignored). The hook knows the repo path, not
206
+ // the project, so the call resolves the project by scope_path.
207
+ export function knowledgeHint(cwd, { relogin = false } = {}) {
208
+ const call = JSON.stringify({ scope: "project", scope_path: cwd, kinds: KNOWLEDGE_KINDS, budget: KNOWLEDGE_BUDGET });
209
+ const hint = `[mcpbox] Before answering or changing anything in this repo, read its project knowledge (rules its files do not carry): mcpbox_knowledge_read ${call}. If no project is bound to this path, go on without it.`;
210
+ return relogin
211
+ ? `${hint} (The pairing token was rejected — tell the user to run: npx -y @mcpbox/mcpbox-claude login)`
212
+ : hint;
213
+ }
214
+
215
+ // Paired (`mcpbox-claude login`): the knowledge text itself. Not paired, the
216
+ // read failed, or the path is unbound in the paired workspace (the client's
217
+ // own MCP session may be in another one): the ready call as a hint. No rows
218
+ // for a bound project: nothing.
219
+ export async function knowledgeForSession(cwd, { fetchKnowledge = fetchProjectKnowledge, creds } = {}) {
220
+ const auth = creds === undefined ? await readCredentials() : creds;
221
+ if (!auth) return knowledgeHint(cwd);
166
222
  try {
167
- await mkdir(dirname(marker), { recursive: true });
168
- // wx fails if it exists → the policy already went out this session.
169
- await writeFile(marker, "", { flag: "wx" });
170
- } catch {
171
- return { policy: "", firstPrompt: false };
223
+ const result = await fetchKnowledge(cwd, { creds: auth });
224
+ if (!result || result.unbound_scope_path) return knowledgeHint(cwd);
225
+ return formatKnowledge(result);
226
+ } catch (err) {
227
+ return knowledgeHint(cwd, { relogin: Boolean(err?.rejected) });
172
228
  }
173
- return { policy, firstPrompt: true };
174
229
  }
175
230
 
176
231
  async function main() {
177
- let prompt = process.env.CLAUDE_USER_PROMPT ?? "";
232
+ // Always read the event: session_id and cwd live only there, even when
233
+ // Claude Code also exports the prompt as CLAUDE_USER_PROMPT.
178
234
  let payload = null;
179
- if (!prompt) {
180
- const raw = await readStdin();
181
- if (raw.trim()) {
182
- try {
183
- payload = JSON.parse(raw);
184
- prompt = promptFromHookPayload(payload);
185
- } catch { /* not JSON — no prompt to route */ }
186
- }
235
+ // The env var already gave the prompt: wait for the event only briefly.
236
+ const raw = await readStdin(process.env.CLAUDE_USER_PROMPT ? 300 : 3000);
237
+ if (raw.trim()) {
238
+ try {
239
+ payload = JSON.parse(raw);
240
+ } catch { /* not JSON — no event to read */ }
187
241
  }
188
- const { policy, firstPrompt } = await policyForFirstPrompt(payload);
189
- const update = firstPrompt ? await checkForUpdate({ current: VERSION }) : null;
190
- const hint = promptSubmitHint(prompt, readMode());
242
+ const prompt = process.env.CLAUDE_USER_PROMPT ?? (payload ? promptFromHookPayload(payload) : "");
243
+ const mode = readMode();
244
+ const firstPrompt = await claimFirstPrompt(payload);
245
+ const policy = await policyForPrompt(payload, firstPrompt);
246
+ const cwd = typeof payload?.cwd === "string" && payload.cwd ? payload.cwd : "";
247
+ // In parallel: both are network calls on the session's first prompt.
248
+ const [knowledge, update] = await Promise.all([
249
+ firstPrompt && cwd && mode !== "off" ? knowledgeForSession(cwd) : "",
250
+ firstPrompt && policy ? checkForUpdate({ current: VERSION }) : null,
251
+ ]);
252
+ const hint = promptSubmitHint(prompt, mode);
191
253
  const notice = update?.outdated ? updateNotice(update.current, update.latest, "kimi") : "";
192
254
  // One write, not two: Codex parses stdout as a single JSON document, so a
193
255
  // policy object followed by a hint object is as invalid as plain text.
194
256
  writeHookOutput(
195
257
  "UserPromptSubmit",
196
- [notice, policy, hint].filter(Boolean).join("\n"),
258
+ [notice, policy, knowledge, hint].filter(Boolean).join("\n"),
197
259
  );
198
260
  }
199
261