grepmax 0.26.50 → 0.26.51

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.
@@ -10,7 +10,7 @@
10
10
  "name": "grepmax",
11
11
  "source": "./plugins/grepmax",
12
12
  "description": "Semantic code search for Claude Code. Automatically indexes your project and provides intelligent search capabilities.",
13
- "version": "0.26.50",
13
+ "version": "0.26.51",
14
14
  "author": {
15
15
  "name": "Robert Owens",
16
16
  "email": "robowens@me.com"
package/README.md CHANGED
@@ -119,9 +119,11 @@ gmax plugin remove claude # Remove specific plugin
119
119
 
120
120
  After upgrading with `npm install -g grepmax@latest`, run `gmax plugin update` (or `gmax plugin update <client>`) to refresh integrations. Package installation does not modify your agent configuration; its postinstall script only prints this reminder.
121
121
 
122
+ Starting with v0.26.51, the installer refreshes an existing Claude marketplace from its configured source and updates each existing user/project/local installation in its original scope. It does not remove the marketplace, reset disabled preferences, or reinstall after a refresh failure. New installations use the local npm package. An existing source is retained; moving to another source is a separate migration. Codex instructions follow `CODEX_HOME` (default `~/.codex`), and a matching STDIO registration retains its existing options. A different existing launch configuration is reported for review instead of overwritten. Refresh the plugins after upgrading to activate the hook and installer repairs.
123
+
122
124
  ### How it works per client
123
125
 
124
- - **Claude Code:** Plugin with hooks (SessionStart, SessionEnd, CwdChanged, SubagentStart, PreToolUse). Model uses CLI via `Bash(gmax ... --agent)`.
126
+ - **Claude Code:** Plugin with session/directory hooks, guidance hooks and activity renewal on UserPromptSubmit/PostToolUse for Bash. Model uses CLI via `Bash(gmax ... --agent)`; the plugin does not register an MCP server. Source hooks honor the autostart kill switch, start only after a definite absent socket and never fall back to a separate watcher beside a live daemon.
125
127
  - **OpenCode:** Tool shim with dynamic SKILL + session plugin for daemon startup. Model calls gmax tool directly.
126
128
  - **Codex:** MCP server registration + AGENTS.md skill instructions.
127
129
  - **Factory Droid:** Skills + SessionStart/SessionEnd hooks for daemon lifecycle.
@@ -486,7 +488,7 @@ whether you need to act.
486
488
  | `disabling auto-rebuild until an optimize succeeds` | Transient, not a wedge. The next successful optimize clears it. Search stays available. |
487
489
  | `ANN: vector index not built` | Normal — exact search is the default. |
488
490
  | `cannot reach the daemon socket from this sandbox` (exit 2) | The shell is sandboxed. Add the two keys in [Running under the Claude Code sandbox](#running-under-the-claude-code-sandbox); `gmax doctor` warns about the same gap. |
489
- | `npm audit` reports advisories on install | v0.26.49 passed production and fresh packed-consumer audits. Audit findings can change: record the installed version and dependency path and report new findings; do not assume historical advisories still apply. |
491
+ | `npm audit` reports advisories on install | v0.26.50 passed production and fresh packed-consumer audits. Audit findings can change: record the installed version and dependency path and report new findings; do not assume historical advisories still apply. |
490
492
 
491
493
  ## Contributing
492
494
 
@@ -46,32 +46,36 @@ exports.installClaudeCode = void 0;
46
46
  const node_child_process_1 = require("node:child_process");
47
47
  const fs = __importStar(require("node:fs"));
48
48
  const path = __importStar(require("node:path"));
49
+ const node_util_1 = require("node:util");
49
50
  const commander_1 = require("commander");
50
- function runClaudeCommand(args) {
51
- return new Promise((resolve, reject) => {
52
- const child = (0, node_child_process_1.spawn)("claude", ["plugin", ...args], {
51
+ const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
52
+ function runClaudeCommand(args_1) {
53
+ return __awaiter(this, arguments, void 0, function* (args, options = {}) {
54
+ const { stdout, stderr } = yield execFileAsync("claude", ["plugin", ...args], {
53
55
  env: process.env,
54
- stdio: "inherit",
55
- });
56
- const timeout = setTimeout(() => {
57
- child.kill("SIGTERM");
58
- reject(new Error("claude command timed out after 60s"));
59
- }, 60000);
60
- child.on("error", (error) => {
61
- clearTimeout(timeout);
62
- reject(error);
63
- });
64
- child.on("exit", (code) => {
65
- clearTimeout(timeout);
66
- if (code === 0) {
67
- resolve();
68
- }
69
- else {
70
- reject(new Error(`claude exited with code ${code !== null && code !== void 0 ? code : "unknown"}`));
71
- }
56
+ encoding: "utf8",
57
+ timeout: 60000,
58
+ maxBuffer: 2 * 1024 * 1024,
59
+ cwd: options.cwd,
72
60
  });
61
+ if (!options.quiet) {
62
+ process.stdout.write(stdout);
63
+ process.stderr.write(stderr);
64
+ }
65
+ return stdout;
73
66
  });
74
67
  }
68
+ function parseList(raw, label) {
69
+ const parsed = JSON.parse(raw);
70
+ const key = label === "marketplace list" ? "name" : "id";
71
+ if (!Array.isArray(parsed) ||
72
+ parsed.some((entry) => !entry ||
73
+ typeof entry !== "object" ||
74
+ typeof entry[key] !== "string" ||
75
+ !entry[key]))
76
+ throw new Error(`Unexpected Claude ${label} response; configuration preserved`);
77
+ return parsed;
78
+ }
75
79
  /**
76
80
  * Resolve the gmax package root directory.
77
81
  * Works for both npm global installs (symlinked binary) and dev mode.
@@ -94,19 +98,47 @@ function installPlugin() {
94
98
  return;
95
99
  }
96
100
  console.log(`Installing plugin from ${marketplacePath}`);
97
- // Remove old GitHub-based marketplace if present (ignore errors)
98
- try {
99
- yield runClaudeCommand(["marketplace", "remove", "grepmax"]);
101
+ // Query the CLI so account selection and CLAUDE_CONFIG_DIR match the client.
102
+ // A failed/invalid inventory must never trigger a destructive reinstall.
103
+ const marketplaces = parseList(yield runClaudeCommand(["marketplace", "list", "--json"], {
104
+ quiet: true,
105
+ }), "marketplace list");
106
+ const installed = parseList(yield runClaudeCommand(["list", "--json"], { quiet: true }), "plugin list").filter((entry) => entry.id === "grepmax@grepmax");
107
+ const updates = installed.filter((entry) => entry.scope !== "managed");
108
+ // Validate every target before even refreshing the source.
109
+ for (const entry of updates) {
110
+ if (!["user", "project", "local"].includes(String(entry.scope)))
111
+ throw new Error("Unknown gmax installation scope; configuration preserved");
112
+ if (entry.scope !== "user" &&
113
+ (typeof entry.projectPath !== "string" ||
114
+ !fs.existsSync(entry.projectPath)))
115
+ throw new Error("Missing gmax installation project; configuration preserved");
100
116
  }
101
- catch (_a) {
102
- // May not exist — fine
117
+ if (installed.length > 0 && updates.length === 0) {
118
+ console.log("gmax is managed by your administrator; installation preserved.");
119
+ return;
120
+ }
121
+ if (marketplaces.some((entry) => entry.name === "grepmax")) {
122
+ // Retain the user's chosen source, including GitHub or another npm prefix.
123
+ // Retargeting by removing a marketplace also deletes plugin-owned state.
124
+ yield runClaudeCommand(["marketplace", "update", "grepmax"]);
125
+ console.log("✔ Marketplace refreshed (existing source preserved)");
126
+ }
127
+ else {
128
+ yield runClaudeCommand(["marketplace", "add", marketplacePath]);
129
+ console.log("✔ Marketplace registered (local)");
130
+ }
131
+ if (updates.length === 0) {
132
+ yield runClaudeCommand(["install", "grepmax@grepmax", "--scope", "user"]);
133
+ }
134
+ else {
135
+ for (const entry of updates) {
136
+ yield runClaudeCommand(["update", "grepmax@grepmax", "--scope", String(entry.scope)], {
137
+ cwd: entry.scope === "user" ? undefined : String(entry.projectPath),
138
+ });
139
+ }
103
140
  }
104
- // Add local package directory as marketplace source
105
- yield runClaudeCommand(["marketplace", "add", marketplacePath]);
106
- console.log("✔ Marketplace registered (local)");
107
- // Install the plugin from the local marketplace
108
- yield runClaudeCommand(["install", "grepmax"]);
109
- console.log("✅ Successfully installed the gmax plugin for Claude Code");
141
+ console.log("✅ Successfully refreshed the gmax plugin for Claude Code");
110
142
  console.log("\nNext steps:");
111
143
  console.log("1. Restart Claude Code if it's running");
112
144
  console.log("2. Run `gmax add` in your project to index it");
@@ -15,13 +15,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.uninstallCodex = exports.installCodex = void 0;
16
16
  const node_child_process_1 = require("node:child_process");
17
17
  const node_fs_1 = __importDefault(require("node:fs"));
18
- const node_os_1 = __importDefault(require("node:os"));
19
18
  const node_path_1 = __importDefault(require("node:path"));
20
19
  const node_util_1 = require("node:util");
21
20
  const commander_1 = require("commander");
21
+ const codex_home_1 = require("../lib/utils/codex-home");
22
22
  const shell = process.env.SHELL || (process.platform === "win32" ? "cmd.exe" : "/bin/sh");
23
23
  const execAsync = (0, node_util_1.promisify)(node_child_process_1.exec);
24
- const AGENTS_PATH = node_path_1.default.join(node_os_1.default.homedir(), ".codex", "AGENTS.md");
25
24
  const SKILL_START = "<!-- gmax:start -->";
26
25
  const SKILL_END = "<!-- gmax:end -->";
27
26
  function ownedSkillBlocks() {
@@ -48,6 +47,7 @@ function loadSkill() {
48
47
  }
49
48
  }
50
49
  function writeSkillToAgents(skill) {
50
+ const AGENTS_PATH = (0, codex_home_1.codexAgentsPath)();
51
51
  node_fs_1.default.mkdirSync(node_path_1.default.dirname(AGENTS_PATH), { recursive: true });
52
52
  const block = `${SKILL_START}\n${skill.trim()}\n${SKILL_END}`;
53
53
  if (!node_fs_1.default.existsSync(AGENTS_PATH)) {
@@ -74,20 +74,37 @@ function writeSkillToAgents(skill) {
74
74
  }
75
75
  function installPlugin() {
76
76
  return __awaiter(this, void 0, void 0, function* () {
77
+ var _a;
77
78
  try {
79
+ const inventory = yield execAsync("codex mcp list --json", {
80
+ shell,
81
+ env: process.env,
82
+ });
83
+ const servers = JSON.parse(inventory.stdout);
84
+ if (!Array.isArray(servers) ||
85
+ servers.some((server) => !server || typeof server.name !== "string"))
86
+ throw new Error("Unexpected Codex MCP inventory; configuration preserved");
87
+ const existing = servers.find((server) => (server === null || server === void 0 ? void 0 : server.name) === "gmax");
88
+ if (existing &&
89
+ (((_a = existing.transport) === null || _a === void 0 ? void 0 : _a.type) !== "stdio" ||
90
+ node_path_1.default.basename(String(existing.transport.command)) !== "gmax" ||
91
+ JSON.stringify(existing.transport.args) !== JSON.stringify(["mcp"])))
92
+ throw new Error("Existing gmax MCP launch differs; review it before replacing");
78
93
  // 1. Register MCP tool. Codex requires the stdio command after `--`:
79
94
  // codex mcp add [OPTIONS] <NAME> -- <COMMAND>...
80
95
  // Without the separator the launch command is misparsed. AGENTS.md is only
81
96
  // written after this resolves, so a failed registration leaves it untouched.
82
- yield execAsync("codex mcp add gmax -- gmax mcp", {
83
- shell,
84
- env: process.env,
85
- });
86
- console.log("✅ gmax MCP tool registered with Codex");
97
+ if (!existing) {
98
+ yield execAsync("codex mcp add gmax -- gmax mcp", {
99
+ shell,
100
+ env: process.env,
101
+ });
102
+ }
103
+ console.log("✅ gmax MCP registration ready (existing options preserved)");
87
104
  // 2. Write SKILL to AGENTS.md (idempotent)
88
105
  const skill = loadSkill();
89
106
  writeSkillToAgents(skill);
90
- console.log("✅ gmax skill instructions written to", AGENTS_PATH);
107
+ console.log("✅ gmax skill instructions written to", (0, codex_home_1.codexAgentsPath)());
91
108
  }
92
109
  catch (error) {
93
110
  console.error(`❌ Error installing Codex plugin: ${error}`);
@@ -97,6 +114,7 @@ function installPlugin() {
97
114
  }
98
115
  function uninstallPlugin() {
99
116
  return __awaiter(this, void 0, void 0, function* () {
117
+ const AGENTS_PATH = (0, codex_home_1.codexAgentsPath)();
100
118
  try {
101
119
  yield execAsync("codex mcp remove gmax", { shell, env: process.env });
102
120
  console.log("✅ gmax MCP tool removed");
@@ -49,6 +49,7 @@ const fs = __importStar(require("node:fs"));
49
49
  const os = __importStar(require("node:os"));
50
50
  const path = __importStar(require("node:path"));
51
51
  const commander_1 = require("commander");
52
+ const codex_home_1 = require("../lib/utils/codex-home");
52
53
  const exit_1 = require("../lib/utils/exit");
53
54
  function commandExists(cmd) {
54
55
  try {
@@ -106,7 +107,7 @@ function getClients() {
106
107
  id: "codex",
107
108
  detect: () => commandExists("codex"),
108
109
  isInstalled: () => {
109
- const p = path.join(os.homedir(), ".codex", "AGENTS.md");
110
+ const p = (0, codex_home_1.codexAgentsPath)();
110
111
  try {
111
112
  return (fs.existsSync(p) && fs.readFileSync(p, "utf-8").includes("gmax"));
112
113
  }
@@ -53,6 +53,7 @@ const watcher_1 = require("../lib/index/watcher");
53
53
  const index_state_footer_1 = require("../lib/output/index-state-footer");
54
54
  const meta_cache_1 = require("../lib/store/meta-cache");
55
55
  const vector_db_1 = require("../lib/store/vector-db");
56
+ const autostart_1 = require("../lib/utils/autostart");
56
57
  const daemon_restart_1 = require("../lib/utils/daemon-restart");
57
58
  const exit_1 = require("../lib/utils/exit");
58
59
  const filter_builder_1 = require("../lib/utils/filter-builder");
@@ -92,11 +93,18 @@ exports.watch = new commander_1.Command("watch")
92
93
  return;
93
94
  }
94
95
  if (options.background) {
96
+ const startOnly = process.env.GMAX_DAEMON_START_ONLY === "1";
97
+ // Plugin hooks are implicit starts. Recheck quarantine in this child
98
+ // and never use their launch as a version-upgrade restart.
99
+ if (startOnly && (0, autostart_1.isAutostartDisabled)())
100
+ return;
95
101
  // Skip spawn if daemon already running at the same version.
96
102
  // If version mismatches (e.g. after npm install -g), shut down the old
97
103
  // daemon so we can start a fresh one with the new code.
98
104
  const { isDaemonRunning, isDaemonHeartbeatFresh, sendDaemonCommand, readDaemonPid, waitForProcessExit, } = yield Promise.resolve().then(() => __importStar(require("../lib/utils/daemon-client")));
99
105
  if (yield isDaemonRunning()) {
106
+ if (startOnly)
107
+ return;
100
108
  const cliVersion = JSON.parse(fs.readFileSync(path.join(__dirname, "../../package.json"), "utf-8")).version;
101
109
  const resp = yield sendDaemonCommand({ cmd: "ping" });
102
110
  if (resp.version && resp.version === cliVersion) {
@@ -49,7 +49,7 @@ const config_1 = require("../../config");
49
49
  * Explicit `gmax watch --daemon` is never gated: typing it is the user asking
50
50
  * for a daemon in that moment.
51
51
  *
52
- * plugins/grepmax/hooks/start.js carries a plain-JS copy of these semantics
52
+ * plugins/grepmax/hooks/watch-lease.js carries a plain-JS copy of these semantics
53
53
  * (env var checked first, then the file) because a SessionStart hook cannot
54
54
  * import from dist. Keep the two in sync.
55
55
  */
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.codexAgentsPath = codexAgentsPath;
37
+ const os = __importStar(require("node:os"));
38
+ const path = __importStar(require("node:path"));
39
+ function codexAgentsPath() {
40
+ const home = process.env.CODEX_HOME
41
+ ? path.resolve(process.env.CODEX_HOME)
42
+ : path.join(os.homedir(), ".codex");
43
+ return path.join(home, "AGENTS.md");
44
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grepmax",
3
- "version": "0.26.50",
3
+ "version": "0.26.51",
4
4
  "author": "Robert Owens <78518764+reowens@users.noreply.github.com>",
5
5
  "homepage": "https://github.com/reowens/grepmax",
6
6
  "bugs": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grepmax",
3
- "version": "0.26.50",
3
+ "version": "0.26.51",
4
4
  "description": "Semantic code search for Claude Code. Automatically indexes your project and provides intelligent search capabilities.",
5
5
  "author": {
6
6
  "name": "Robert Owens",
@@ -0,0 +1,12 @@
1
+ const { ensureSessionLease, readHookInput } = require("./watch-lease");
2
+
3
+ // Bounded renewal on turns and Bash activity keeps long CLI sessions watched.
4
+ // No detached timer, global watcher or additional MCP process is needed.
5
+ async function main() {
6
+ const input = await readHookInput();
7
+ await ensureSessionLease(input, input.cwd || process.cwd(), {
8
+ allowStart: true,
9
+ });
10
+ }
11
+
12
+ main();
@@ -1,6 +1,5 @@
1
- const { execFileSync } = require("node:child_process");
2
1
  const {
3
- acquireSessionLease,
2
+ ensureSessionLease,
4
3
  readHookInput,
5
4
  registeredRootFor,
6
5
  releaseSessionLeases,
@@ -20,19 +19,7 @@ async function main() {
20
19
  }
21
20
  }
22
21
 
23
- if (!registeredRootFor(newCwd)) return;
24
-
25
- try {
26
- execFileSync("gmax", ["watch", "--daemon", "-b"], {
27
- timeout: 5000,
28
- stdio: "ignore",
29
- });
30
- } catch {
31
- try {
32
- execFileSync("gmax", ["watch", "-b"], { timeout: 5000, stdio: "ignore" });
33
- } catch {}
34
- }
35
- await acquireSessionLease(input, newCwd);
22
+ await ensureSessionLease(input, newCwd, { allowStart: true });
36
23
  }
37
24
 
38
25
  main();
@@ -2,7 +2,7 @@ const fs = require("node:fs");
2
2
  const _path = require("node:path");
3
3
  const { execFileSync } = require("node:child_process");
4
4
  const {
5
- acquireSessionLease,
5
+ ensureSessionLease,
6
6
  readHookInput,
7
7
  registeredRootFor,
8
8
  } = require("./watch-lease");
@@ -70,43 +70,10 @@ function isProjectRegistered(dir) {
70
70
  return registeredRootFor(dir) !== null;
71
71
  }
72
72
 
73
- // A kill switch for the auto-start. Create ~/.gmax/autostart-disabled (or export
74
- // GMAX_NO_AUTOSTART=1) to keep sessions from reviving the daemon — needed when the
75
- // host is quarantined after a kernel-zone incident and the daemon's write volume is
76
- // the thing under investigation. Delete the file to restore normal behavior.
77
- //
78
- // The CLI honors the same switch via src/lib/utils/autostart.ts (PATHS.autostartDisabledFile).
79
- // This copy exists because a hook cannot import from dist — keep the two in sync.
80
- function isAutostartDisabled() {
81
- if (process.env.GMAX_NO_AUTOSTART === "1") return true;
82
- try {
83
- return require("node:fs").existsSync(
84
- _path.join(require("node:os").homedir(), ".gmax", "autostart-disabled"),
85
- );
86
- } catch {
87
- return false;
88
- }
89
- }
90
-
91
73
  async function startWatcher(input) {
92
- if (isAutostartDisabled()) return;
93
74
  const dir = input.cwd || process.cwd();
94
75
  if (!isProjectRegistered(dir)) return;
95
- try {
96
- execFileSync("gmax", ["watch", "--daemon", "-b"], {
97
- timeout: 5000,
98
- stdio: "ignore",
99
- });
100
- } catch {
101
- // Fallback to per-project mode (older gmax without --daemon)
102
- try {
103
- execFileSync("gmax", ["watch", "-b"], { timeout: 5000, stdio: "ignore" });
104
- } catch {
105
- // Watcher may already be running or gmax not in PATH — ignore
106
- }
107
- }
108
- // The daemon only watches projects a session holds a lease on.
109
- await acquireSessionLease(input, dir);
76
+ await ensureSessionLease(input, dir, { allowStart: true });
110
77
  }
111
78
 
112
79
  async function main() {
@@ -1,10 +1,9 @@
1
1
  // Session watch leases for the hooks.
2
2
  //
3
- // The daemon only watches projects that some session holds a lease on (see
4
- // src/lib/daemon/watch-leases.ts). The MCP server holds the long-lived one; the
5
- // hooks take a session lease so a project is watched from the first moment of a
6
- // session, and drop it at SessionEnd. A hook cannot import from dist, so this
7
- // speaks the daemon's one-line JSON protocol directly.
3
+ // Claude's CLI integration takes a lease at startup, renews it during activity,
4
+ // and releases it at SessionEnd. Other MCP clients own separate leases. A hook
5
+ // cannot import from dist, so this speaks the one-line Unix socket protocol.
6
+ const { spawn } = require("node:child_process");
8
7
  const fs = require("node:fs");
9
8
  const net = require("node:net");
10
9
  const os = require("node:os");
@@ -13,10 +12,18 @@ const path = require("node:path");
13
12
  const GMAX_DIR = path.join(os.homedir(), ".gmax");
14
13
  const SOCKET = path.join(GMAX_DIR, "daemon.sock");
15
14
 
16
- // Long enough to cover a session without an MCP server; SessionEnd releases it
17
- // early, and the daemon caps any lease at 12h.
15
+ // Activity refreshes this TTL; idle sessions do not watch forever.
18
16
  const SESSION_LEASE_TTL_MS = 4 * 60 * 60 * 1000;
19
17
 
18
+ function isAutostartDisabled() {
19
+ if (process.env.GMAX_NO_AUTOSTART === "1") return true;
20
+ try {
21
+ return fs.existsSync(path.join(GMAX_DIR, "autostart-disabled"));
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+
20
27
  function readHookInput(timeoutMs = 1000) {
21
28
  return new Promise((resolve) => {
22
29
  let data = "";
@@ -102,6 +109,7 @@ function sendOnce(cmd, timeoutMs) {
102
109
  socket.on("error", (err) =>
103
110
  finish({
104
111
  ok: false,
112
+ absent: err.code === "ENOENT" || err.code === "ECONNREFUSED",
105
113
  retry: err.code === "ENOENT" || err.code === "ECONNREFUSED",
106
114
  }),
107
115
  );
@@ -143,6 +151,42 @@ async function acquireSessionLease(input, dir) {
143
151
  return resp !== null;
144
152
  }
145
153
 
154
+ /** Reuse a lease-capable daemon; start one only after a definite absent socket. */
155
+ async function ensureSessionLease(input, dir, { allowStart = false } = {}) {
156
+ if (isAutostartDisabled() || !sessionHolder(input) || !registeredRootFor(dir))
157
+ return false;
158
+ const ping = await sendOnce({ cmd: "ping" }, 500);
159
+ if (ping.ok) {
160
+ if (!ping.resp.capabilities?.watchLeases) return false;
161
+ return acquireSessionLease(input, dir);
162
+ }
163
+ // Busy, initializing, denied and timed-out sockets belong to an existing
164
+ // daemon. Never start a per-project writer or replace that process here.
165
+ if (!allowStart || !ping.absent) return false;
166
+ try {
167
+ const child = spawn("gmax", ["watch", "--daemon", "-b"], {
168
+ detached: true,
169
+ stdio: "ignore",
170
+ cwd: dir,
171
+ // Another session can win the race after the absent-socket probe. The
172
+ // launcher must reuse that peer, even if its package version differs.
173
+ env: { ...process.env, GMAX_DAEMON_START_ONLY: "1" },
174
+ });
175
+ await new Promise((resolve, reject) => {
176
+ child.once("spawn", resolve);
177
+ child.once("error", reject);
178
+ });
179
+ child.unref();
180
+ } catch {
181
+ return false;
182
+ }
183
+ // A cold daemon may take longer than a hook's budget to become ready. Later
184
+ // activity retries ownership instead of opening another watcher.
185
+ const ready = await sendDaemonLine({ cmd: "ping" }, 1500);
186
+ if (!ready?.capabilities?.watchLeases) return false;
187
+ return acquireSessionLease(input, dir);
188
+ }
189
+
146
190
  async function releaseSessionLeases(input, dir) {
147
191
  const holder = sessionHolder(input);
148
192
  const root = registeredRootFor(dir);
@@ -157,6 +201,8 @@ async function releaseSessionLeases(input, dir) {
157
201
 
158
202
  module.exports = {
159
203
  acquireSessionLease,
204
+ ensureSessionLease,
205
+ isAutostartDisabled,
160
206
  readHookInput,
161
207
  registeredRootFor,
162
208
  releaseSessionLeases,
@@ -5,7 +5,7 @@
5
5
  "hooks": [
6
6
  {
7
7
  "type": "command",
8
- "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/start.js",
8
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/start.js\"",
9
9
  "timeout": 10
10
10
  }
11
11
  ]
@@ -16,7 +16,7 @@
16
16
  "hooks": [
17
17
  {
18
18
  "type": "command",
19
- "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/stop.js",
19
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/stop.js\"",
20
20
  "timeout": 10
21
21
  }
22
22
  ]
@@ -27,8 +27,8 @@
27
27
  "hooks": [
28
28
  {
29
29
  "type": "command",
30
- "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/cwd-changed.js",
31
- "timeout": 5
30
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/cwd-changed.js\"",
31
+ "timeout": 10
32
32
  }
33
33
  ]
34
34
  }
@@ -38,7 +38,7 @@
38
38
  "hooks": [
39
39
  {
40
40
  "type": "command",
41
- "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/subagent-start.js",
41
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/subagent-start.js\"",
42
42
  "timeout": 3
43
43
  }
44
44
  ]
@@ -50,11 +50,34 @@
50
50
  "hooks": [
51
51
  {
52
52
  "type": "command",
53
- "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/pre-grep.js",
53
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/pre-grep.js\"",
54
54
  "timeout": 2
55
55
  }
56
56
  ]
57
57
  }
58
+ ],
59
+ "UserPromptSubmit": [
60
+ {
61
+ "hooks": [
62
+ {
63
+ "type": "command",
64
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/activity.js\"",
65
+ "timeout": 10
66
+ }
67
+ ]
68
+ }
69
+ ],
70
+ "PostToolUse": [
71
+ {
72
+ "matcher": "Bash",
73
+ "hooks": [
74
+ {
75
+ "type": "command",
76
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/activity.js\"",
77
+ "timeout": 10
78
+ }
79
+ ]
80
+ }
58
81
  ]
59
82
  }
60
83
  }