@aroman22/codegraph-vba 1.3.3

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.
Files changed (153) hide show
  1. package/README.md +855 -0
  2. package/dist/bin/codegraph.d.ts +26 -0
  3. package/dist/bin/command-supervision.d.ts +12 -0
  4. package/dist/bin/fatal-handler.d.ts +20 -0
  5. package/dist/bin/node-version-check.d.ts +37 -0
  6. package/dist/bin/uninstall.d.ts +14 -0
  7. package/dist/context/formatter.d.ts +30 -0
  8. package/dist/context/index.d.ts +119 -0
  9. package/dist/context/markers.d.ts +19 -0
  10. package/dist/db/index.d.ts +122 -0
  11. package/dist/db/migrations.d.ts +44 -0
  12. package/dist/db/queries.d.ts +402 -0
  13. package/dist/db/sqlite-adapter.d.ts +53 -0
  14. package/dist/directory.d.ts +179 -0
  15. package/dist/errors.d.ts +136 -0
  16. package/dist/extraction/astro-extractor.d.ts +79 -0
  17. package/dist/extraction/dfm-extractor.d.ts +31 -0
  18. package/dist/extraction/extraction-version.d.ts +25 -0
  19. package/dist/extraction/function-ref.d.ts +118 -0
  20. package/dist/extraction/generated-detection.d.ts +30 -0
  21. package/dist/extraction/grammars.d.ts +128 -0
  22. package/dist/extraction/index.d.ts +187 -0
  23. package/dist/extraction/languages/c-cpp.d.ts +12 -0
  24. package/dist/extraction/languages/csharp.d.ts +25 -0
  25. package/dist/extraction/languages/dart.d.ts +3 -0
  26. package/dist/extraction/languages/go.d.ts +3 -0
  27. package/dist/extraction/languages/index.d.ts +10 -0
  28. package/dist/extraction/languages/java.d.ts +3 -0
  29. package/dist/extraction/languages/javascript.d.ts +3 -0
  30. package/dist/extraction/languages/kotlin.d.ts +3 -0
  31. package/dist/extraction/languages/lua.d.ts +3 -0
  32. package/dist/extraction/languages/luau.d.ts +3 -0
  33. package/dist/extraction/languages/objc.d.ts +3 -0
  34. package/dist/extraction/languages/pascal.d.ts +3 -0
  35. package/dist/extraction/languages/php.d.ts +3 -0
  36. package/dist/extraction/languages/python.d.ts +3 -0
  37. package/dist/extraction/languages/r.d.ts +3 -0
  38. package/dist/extraction/languages/ruby.d.ts +3 -0
  39. package/dist/extraction/languages/rust.d.ts +3 -0
  40. package/dist/extraction/languages/scala.d.ts +3 -0
  41. package/dist/extraction/languages/swift.d.ts +3 -0
  42. package/dist/extraction/languages/typescript.d.ts +16 -0
  43. package/dist/extraction/liquid-extractor.d.ts +59 -0
  44. package/dist/extraction/mybatis-extractor.d.ts +48 -0
  45. package/dist/extraction/parse-pool.d.ts +126 -0
  46. package/dist/extraction/parse-worker.d.ts +8 -0
  47. package/dist/extraction/razor-extractor.d.ts +42 -0
  48. package/dist/extraction/sql-query-extractor.d.ts +25 -0
  49. package/dist/extraction/svelte-extractor.d.ts +56 -0
  50. package/dist/extraction/tree-sitter-helpers.d.ts +28 -0
  51. package/dist/extraction/tree-sitter-types.d.ts +239 -0
  52. package/dist/extraction/tree-sitter.d.ts +647 -0
  53. package/dist/extraction/vba-extractor.d.ts +394 -0
  54. package/dist/extraction/vba-form-extractor.d.ts +89 -0
  55. package/dist/extraction/vba-preprocess.d.ts +81 -0
  56. package/dist/extraction/vue-extractor.d.ts +51 -0
  57. package/dist/extraction/wasm-runtime-flags.d.ts +38 -0
  58. package/dist/graph/index.d.ts +8 -0
  59. package/dist/graph/queries.d.ts +106 -0
  60. package/dist/graph/traversal.d.ts +127 -0
  61. package/dist/index.d.ts +563 -0
  62. package/dist/installer/config-writer.d.ts +28 -0
  63. package/dist/installer/index.d.ts +100 -0
  64. package/dist/installer/instructions-template.d.ts +41 -0
  65. package/dist/installer/targets/antigravity.d.ts +57 -0
  66. package/dist/installer/targets/claude.d.ts +62 -0
  67. package/dist/installer/targets/codex.d.ts +18 -0
  68. package/dist/installer/targets/cursor.d.ts +35 -0
  69. package/dist/installer/targets/gemini.d.ts +26 -0
  70. package/dist/installer/targets/hermes.d.ts +18 -0
  71. package/dist/installer/targets/kiro.d.ts +27 -0
  72. package/dist/installer/targets/opencode.d.ts +38 -0
  73. package/dist/installer/targets/registry.d.ts +35 -0
  74. package/dist/installer/targets/shared.d.ts +101 -0
  75. package/dist/installer/targets/toml.d.ts +52 -0
  76. package/dist/installer/targets/types.d.ts +108 -0
  77. package/dist/mcp/daemon-manager.d.ts +42 -0
  78. package/dist/mcp/daemon-paths.d.ts +73 -0
  79. package/dist/mcp/daemon-registry.d.ts +47 -0
  80. package/dist/mcp/daemon.d.ts +258 -0
  81. package/dist/mcp/dynamic-boundaries.d.ts +41 -0
  82. package/dist/mcp/engine.d.ts +122 -0
  83. package/dist/mcp/index.d.ts +113 -0
  84. package/dist/mcp/liveness-watchdog.d.ts +18 -0
  85. package/dist/mcp/ppid-watchdog.d.ts +62 -0
  86. package/dist/mcp/proxy.d.ts +87 -0
  87. package/dist/mcp/query-pool.d.ts +94 -0
  88. package/dist/mcp/query-worker.d.ts +24 -0
  89. package/dist/mcp/server-instructions.d.ts +34 -0
  90. package/dist/mcp/session.d.ts +79 -0
  91. package/dist/mcp/stdin-teardown.d.ts +27 -0
  92. package/dist/mcp/tools.d.ts +591 -0
  93. package/dist/mcp/transport.d.ts +188 -0
  94. package/dist/mcp/version.d.ts +19 -0
  95. package/dist/project-config.d.ts +56 -0
  96. package/dist/reasoning/config.d.ts +45 -0
  97. package/dist/reasoning/credentials.d.ts +5 -0
  98. package/dist/reasoning/login.d.ts +21 -0
  99. package/dist/reasoning/reasoner.d.ts +43 -0
  100. package/dist/resolution/c-fnptr-synthesizer.d.ts +5 -0
  101. package/dist/resolution/callback-synthesizer.d.ts +15 -0
  102. package/dist/resolution/frameworks/astro.d.ts +9 -0
  103. package/dist/resolution/frameworks/cargo-workspace.d.ts +18 -0
  104. package/dist/resolution/frameworks/csharp.d.ts +8 -0
  105. package/dist/resolution/frameworks/drupal.d.ts +51 -0
  106. package/dist/resolution/frameworks/expo-modules.d.ts +3 -0
  107. package/dist/resolution/frameworks/express.d.ts +8 -0
  108. package/dist/resolution/frameworks/fabric.d.ts +3 -0
  109. package/dist/resolution/frameworks/go.d.ts +8 -0
  110. package/dist/resolution/frameworks/goframe.d.ts +41 -0
  111. package/dist/resolution/frameworks/index.d.ts +50 -0
  112. package/dist/resolution/frameworks/java.d.ts +8 -0
  113. package/dist/resolution/frameworks/laravel.d.ts +13 -0
  114. package/dist/resolution/frameworks/nestjs.d.ts +26 -0
  115. package/dist/resolution/frameworks/play.d.ts +19 -0
  116. package/dist/resolution/frameworks/python.d.ts +10 -0
  117. package/dist/resolution/frameworks/react-native.d.ts +3 -0
  118. package/dist/resolution/frameworks/react.d.ts +8 -0
  119. package/dist/resolution/frameworks/ruby.d.ts +8 -0
  120. package/dist/resolution/frameworks/rust.d.ts +8 -0
  121. package/dist/resolution/frameworks/svelte.d.ts +9 -0
  122. package/dist/resolution/frameworks/swift-objc.d.ts +37 -0
  123. package/dist/resolution/frameworks/swift.d.ts +10 -0
  124. package/dist/resolution/frameworks/vue.d.ts +9 -0
  125. package/dist/resolution/go-module.d.ts +26 -0
  126. package/dist/resolution/goframe-synthesizer.d.ts +28 -0
  127. package/dist/resolution/import-resolver.d.ts +78 -0
  128. package/dist/resolution/index.d.ts +196 -0
  129. package/dist/resolution/lru-cache.d.ts +24 -0
  130. package/dist/resolution/name-matcher.d.ts +93 -0
  131. package/dist/resolution/path-aliases.d.ts +68 -0
  132. package/dist/resolution/strip-comments.d.ts +27 -0
  133. package/dist/resolution/swift-objc-bridge.d.ts +134 -0
  134. package/dist/resolution/types.d.ts +233 -0
  135. package/dist/resolution/workspace-packages.d.ts +48 -0
  136. package/dist/search/query-parser.d.ts +57 -0
  137. package/dist/search/query-utils.d.ts +87 -0
  138. package/dist/sync/git-hooks.d.ts +45 -0
  139. package/dist/sync/index.d.ts +19 -0
  140. package/dist/sync/watch-policy.d.ts +48 -0
  141. package/dist/sync/watcher.d.ts +358 -0
  142. package/dist/sync/worktree.d.ts +54 -0
  143. package/dist/telemetry/index.d.ts +143 -0
  144. package/dist/types.d.ts +409 -0
  145. package/dist/ui/glyphs.d.ts +42 -0
  146. package/dist/ui/shimmer-progress.d.ts +11 -0
  147. package/dist/ui/shimmer-worker.d.ts +2 -0
  148. package/dist/ui/types.d.ts +17 -0
  149. package/dist/upgrade/index.d.ts +132 -0
  150. package/dist/utils.d.ts +224 -0
  151. package/npm-sdk.js +75 -0
  152. package/npm-shim.js +246 -0
  153. package/package.json +32 -0
@@ -0,0 +1,113 @@
1
+ /**
2
+ * CodeGraph MCP Server
3
+ *
4
+ * Model Context Protocol server that exposes CodeGraph functionality
5
+ * as tools for AI assistants like Claude.
6
+ *
7
+ * @module mcp
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { MCPServer } from 'codegraph';
12
+ *
13
+ * const server = new MCPServer('/path/to/project');
14
+ * await server.start();
15
+ * ```
16
+ *
17
+ * Runtime modes (decided in {@link MCPServer.start}):
18
+ *
19
+ * - **Direct** — one process serves one MCP client over stdio. The pre-#411
20
+ * behavior; used when the user opts out (`CODEGRAPH_NO_DAEMON=1`), no
21
+ * `.codegraph/` is reachable, or the daemon machinery fails for any reason.
22
+ * - **Proxy** — what an MCP host actually talks to when sharing is on: a thin
23
+ * stdio↔socket pipe to the shared daemon. The proxy carries the #277 PPID
24
+ * watchdog, so a SIGKILL'd host reaps its proxy promptly. See {@link ./proxy.ts}.
25
+ * - **Daemon** — a *detached* background process (its own session/process
26
+ * group) that serves N proxies over a Unix-domain socket / named pipe,
27
+ * sharing one CodeGraph + watcher + SQLite handle. Spawned on demand; never a
28
+ * child of any host, so it survives individual sessions and is reaped by
29
+ * client-refcount + idle timeout. See {@link ./daemon.ts} and issue #411.
30
+ *
31
+ * The detached-daemon + always-proxy split is the fix for the review finding
32
+ * that the original in-process daemon (a) was the first host's child, so closing
33
+ * that terminal severed every other client, and (b) disabled the PPID watchdog,
34
+ * regressing #277 (orphaned daemons on host SIGKILL).
35
+ */
36
+ /**
37
+ * MCP Server for CodeGraph
38
+ *
39
+ * Implements the Model Context Protocol to expose CodeGraph
40
+ * functionality as tools that can be called by AI assistants.
41
+ *
42
+ * Backwards-compatible constructor and `start()` signature with the
43
+ * pre-issue-#411 implementation: callers continue to do
44
+ * `new MCPServer(path).start()`. Internally we now pick from direct / proxy /
45
+ * daemon at start time.
46
+ */
47
+ export declare class MCPServer {
48
+ private projectPath;
49
+ private session;
50
+ private engine;
51
+ private daemon;
52
+ private ppidWatchdog;
53
+ private livenessWatchdog;
54
+ private originalPpid;
55
+ private hostPpid;
56
+ private stopped;
57
+ private mode;
58
+ constructor(projectPath?: string);
59
+ /**
60
+ * Start the MCP server.
61
+ *
62
+ * Decision order:
63
+ * 1. `CODEGRAPH_NO_DAEMON=1` → direct mode (unchanged pre-#411 behavior).
64
+ * 2. `CODEGRAPH_DAEMON_INTERNAL=1` → we ARE the detached daemon; listen.
65
+ * 3. No `.codegraph/` reachable → direct mode (the daemon's lockfile and
66
+ * socket both live under `.codegraph/`).
67
+ * 4. Otherwise connect to (or spawn) the shared daemon and proxy to it.
68
+ *
69
+ * On any unexpected failure in step 4 we transparently fall back to direct
70
+ * mode — a misbehaving daemon must never block a session from starting.
71
+ */
72
+ start(): Promise<void>;
73
+ /**
74
+ * Stop the server. In daemon mode this triggers graceful shutdown of every
75
+ * connected session; in direct mode it mirrors the pre-#411 behavior (close
76
+ * cg, exit). Proxy mode never routes through here — the proxy exits itself.
77
+ */
78
+ stop(): void;
79
+ /** Single-process stdio MCP session — the pre-issue-#411 code path. */
80
+ private startDirect;
81
+ /**
82
+ * Run as the detached shared daemon (process spawned with
83
+ * `CODEGRAPH_DAEMON_INTERNAL=1`). Arbitrate the O_EXCL lock, then either
84
+ * become the daemon (bind the socket, serve forever) or — if a live daemon
85
+ * already holds the lock — exit so we don't leak a redundant process.
86
+ *
87
+ * No PPID watchdog and no stdin handlers: the daemon is detached on purpose
88
+ * and reaps itself via client-refcount + idle timeout (see {@link Daemon}).
89
+ */
90
+ private startDaemonProcess;
91
+ /**
92
+ * Proxy mode (the common case). Serve the MCP handshake LOCALLY for instant
93
+ * tool registration, forwarding tool calls to the shared daemon — which is
94
+ * connected in the background (probed, then spawned + polled if absent) so the
95
+ * handshake never waits ~600ms on it. Runs until the host disconnects; the
96
+ * proxy falls back to an in-process engine if the daemon never binds, so this
97
+ * never wedges a session.
98
+ */
99
+ private runProxyWithLocalHandshake;
100
+ /** Standard SIGINT/SIGTERM handlers that route to our `stop()` (direct mode). */
101
+ private installSignalHandlers;
102
+ /**
103
+ * PPID watchdog (#277) — direct mode only. Daemon mode is detached on purpose
104
+ * and reaps via idle timeout; proxy mode installs its own watchdog inside
105
+ * {@link runProxy}. So this only ever runs for an in-process direct session.
106
+ */
107
+ private installPpidWatchdog;
108
+ }
109
+ export { StdioTransport } from './transport';
110
+ export { tools, ToolHandler } from './tools';
111
+ export { Daemon } from './daemon';
112
+ export { CodeGraphPackageVersion } from './version';
113
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,18 @@
1
+ /** Default: 60s — ~300× shorter than the 5h #850 wedge, far longer than any real main-thread block. */
2
+ export declare const DEFAULT_WATCHDOG_TIMEOUT_MS = 60000;
3
+ /** Parse the timeout env, falling back to the default for missing/invalid values. */
4
+ export declare function parseWatchdogTimeoutMs(raw: string | undefined, fallback?: number): number;
5
+ /** Derive a heartbeat cadence that emits several beats inside the timeout window. */
6
+ export declare function deriveCheckIntervalMs(timeoutMs: number): number;
7
+ export interface WatchdogHandle {
8
+ /** Stop heartbeating and shut the watchdog child down. Idempotent. */
9
+ stop(): void;
10
+ }
11
+ /**
12
+ * Install the main-thread liveness watchdog for a long-lived process. Returns a
13
+ * handle to stop it, or `null` when disabled or when the child can't be spawned
14
+ * (degraded, never throws — a missing watchdog must never keep a process from
15
+ * starting).
16
+ */
17
+ export declare function installMainThreadWatchdog(): WatchdogHandle | null;
18
+ //# sourceMappingURL=liveness-watchdog.d.ts.map
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Shared decision logic for the PPID watchdog (#277, #692).
3
+ *
4
+ * The watchdog's job: notice that the process we depend on — our parent, or the
5
+ * MCP host reached past an intermediate launcher — has died, so an orphaned
6
+ * proxy / direct server shuts itself down instead of leaking forever.
7
+ *
8
+ * Parent death surfaces differently per OS, and getting this wrong is what
9
+ * caused the unbounded daemon/proxy leak on Windows (#692, #576):
10
+ *
11
+ * - **POSIX** reparents an orphan to init (pid 1), so `process.ppid` *changes*
12
+ * the instant the parent dies. That divergence is the classic #277 signal.
13
+ * - **Windows** never reparents: `process.ppid` keeps reporting the original
14
+ * (now-dead) parent forever, so the change-check can never fire. There we
15
+ * must poll the original parent's *liveness* instead.
16
+ *
17
+ * The liveness fallback is deliberately gated to Windows. On POSIX a
18
+ * double-forked grandparent can legitimately outlive the reparent, so a dead
19
+ * `originalPpid` is not proof of orphaning there — the change-check is the
20
+ * correct and sufficient POSIX signal, and using liveness too would risk a
21
+ * false-positive shutdown.
22
+ */
23
+ export interface SupervisionState {
24
+ /** `process.ppid` captured at startup. */
25
+ originalPpid: number;
26
+ /** `process.ppid` right now. */
27
+ currentPpid: number;
28
+ /**
29
+ * The MCP host pid threaded past an intermediate launcher
30
+ * (`CODEGRAPH_HOST_PPID`), or null when unknown — e.g. the standalone bundle,
31
+ * which pre-bakes `--liftoff-only` and so never runs the relaunch that sets it.
32
+ */
33
+ hostPpid: number | null;
34
+ /** Liveness probe — `process.kill(pid, 0)` in production, stubbed in tests. */
35
+ isAlive: (pid: number) => boolean;
36
+ /** Defaults to `process.platform`. */
37
+ platform?: NodeJS.Platform;
38
+ }
39
+ /**
40
+ * Returns a human-readable reason string when the process has lost its
41
+ * supervisor and should shut down, or null while it is still supervised.
42
+ */
43
+ export declare function supervisionLostReason(state: SupervisionState): string | null;
44
+ /** Default PPID poll cadence (ms). Shared by the MCP server and CLI commands. */
45
+ export declare const DEFAULT_PPID_POLL_MS = 5000;
46
+ /**
47
+ * Resolve the PPID watchdog poll interval from an env override
48
+ * (`CODEGRAPH_PPID_POLL_MS`). A value of `0` disables the watchdog entirely
49
+ * (escape hatch for embedded scenarios where the parent legitimately re-parents
50
+ * the process on purpose). Anything non-numeric or negative falls back to the
51
+ * default.
52
+ */
53
+ export declare function parsePpidPollMs(raw: string | undefined): number;
54
+ /**
55
+ * Parse the host PID propagated across the `--liftoff-only` re-exec
56
+ * (`CODEGRAPH_HOST_PPID`). Returns a positive integer PID, or null when
57
+ * unset/invalid — the direct-launch path, where the watchdog falls back to
58
+ * `process.ppid` divergence. PIDs of 0/1 are rejected (0 = unknown, 1 = init,
59
+ * i.e. already orphaned), so the watchdog doesn't latch onto init.
60
+ */
61
+ export declare function parseHostPpid(raw: string | undefined): number | null;
62
+ //# sourceMappingURL=ppid-watchdog.d.ts.map
@@ -0,0 +1,87 @@
1
+ /**
2
+ * MCP proxy mode — issue #411.
3
+ *
4
+ * The proxy is a near-transparent stdio↔socket pipe. Once it has verified
5
+ * the daemon's hello line (same major.minor.patch as ours), it does no
6
+ * protocol parsing of its own: every byte the MCP host writes to the proxy's
7
+ * stdin goes straight to the daemon socket, and every byte the daemon emits
8
+ * goes straight to the host's stdout. Server-initiated JSON-RPC requests
9
+ * (e.g. `roots/list`) flow through the same pipe transparently.
10
+ *
11
+ * Lifecycle expectations:
12
+ * - The proxy exits when *either* stream closes (host stdin closed →
13
+ * daemon socket end, or daemon-side socket close → host stdout end).
14
+ * - Closing the socket on the proxy side is what tells the daemon to
15
+ * decrement its connected-clients refcount.
16
+ * - On a parent-process death we can't detect via stdin close (e.g. SIGKILL
17
+ * of the MCP host), the proxy's PPID watchdog catches it — same logic
18
+ * the direct-mode server uses; see issue #277.
19
+ */
20
+ import * as net from 'net';
21
+ import { DaemonHello } from './daemon';
22
+ import type { MCPEngine } from './engine';
23
+ /**
24
+ * Log a successful daemon attach — gated behind {@link LOG_ATTACH_ENV} so it is
25
+ * silent by default (see #618). Exported for tests.
26
+ */
27
+ export declare function logAttachedDaemon(socketPath: string, hello: DaemonHello): void;
28
+ export interface ProxyResult {
29
+ /**
30
+ * `proxied` — successfully attached to a same-version daemon and piped
31
+ * stdio. The proxy stays alive until either end closes.
32
+ * `fallback-needed` — the daemon rejected us (version mismatch / unreachable
33
+ * socket) and the caller should run the server in direct mode.
34
+ */
35
+ outcome: 'proxied' | 'fallback-needed';
36
+ reason?: string;
37
+ }
38
+ /**
39
+ * Attempt to connect to the daemon at `socketPath` and pipe stdio through it.
40
+ *
41
+ * Returns a promise that resolves when either:
42
+ * - the connection succeeded and one of stdin/socket has now closed
43
+ * (after which the process should exit), or
44
+ * - the connection failed early enough that the caller can still fall
45
+ * back to direct mode.
46
+ *
47
+ * The `expectedVersion` param defaults to the package's own version — daemon
48
+ * and proxy MUST match exactly. Mismatch resolves with
49
+ * `outcome: 'fallback-needed'` so the caller can transparently start its own
50
+ * server. (We accept the cost of two concurrent servers in this case as the
51
+ * price of never silently running a stale daemon against newer client code.)
52
+ */
53
+ export declare function runProxy(socketPath: string, expectedVersion?: string): Promise<ProxyResult>;
54
+ /**
55
+ * Connect to a daemon at `socketPath` and verify its hello (exact version match).
56
+ * Returns the live socket (hello already consumed) or null if unreachable / stale
57
+ * / version-mismatched. Unlike {@link runProxy} it does NOT pipe — the caller
58
+ * owns the socket. Used by the local-handshake proxy's background connect.
59
+ */
60
+ export declare function connectWithHello(socketPath: string, expectedVersion?: string): Promise<net.Socket | 'version-mismatch' | null>;
61
+ /** Dependencies the local-handshake proxy needs, injected by MCPServer (which
62
+ * owns the daemon-spawn machinery and the engine factory). */
63
+ export interface LocalHandshakeDeps {
64
+ /** Probe → spawn → retry → hello-verify; resolves a connected daemon socket,
65
+ * or null when the daemon path is genuinely unavailable (→ in-process fallback). */
66
+ getDaemonSocket(): Promise<net.Socket | null>;
67
+ /** Lazily create an in-process engine — used ONLY if the daemon never comes up,
68
+ * preserving the "a broken daemon never wedges a session" guarantee. */
69
+ makeEngine(): MCPEngine;
70
+ /** Project root for the fallback engine's lazy init. */
71
+ root: string;
72
+ }
73
+ /**
74
+ * Local-handshake proxy (the cold-start fix).
75
+ *
76
+ * Answers `initialize` + `tools/list` from STATIC constants the instant the
77
+ * client asks — tools register in ~process-startup time instead of waiting
78
+ * ~600ms for the daemon to spawn+bind, which is what produced the "No such tool
79
+ * available" race that made headless agents flail into grep/Read. Tool CALLS are
80
+ * forwarded to the shared daemon (connected in the background); the daemon's
81
+ * response to the forwarded `initialize` is suppressed (the client already got
82
+ * the local one). If the daemon never comes up (version mismatch / spawn fail),
83
+ * a lazily-created in-process engine serves the calls — so the handshake speedup
84
+ * never costs the old fall-back-to-direct robustness.
85
+ */
86
+ export declare function runLocalHandshakeProxy(deps: LocalHandshakeDeps): Promise<void>;
87
+ //# sourceMappingURL=proxy.d.ts.map
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Query pool — runs CPU-heavy read-tool calls on a pool of worker threads so
3
+ * the shared daemon's main event loop stays free for the MCP transport.
4
+ *
5
+ * Why this exists: see {@link ./query-worker}. One daemon, one event loop, one
6
+ * synchronous SQLite connection serializes every concurrent `codegraph_explore`
7
+ * AND starves the transport (a 10-way wave delivered 0 transport heartbeats in
8
+ * 25s — responses can't flush until the whole batch drains, so clients time
9
+ * out). Spreading the dispatch across worker threads (each its own WAL read
10
+ * connection) restores true multi-core parallelism and an idle main loop.
11
+ *
12
+ * Properties:
13
+ * - lazy growth: one warm worker on construct, grows to `size` on demand, so a
14
+ * single-agent session pays for one connection and a 10-subagent burst grows
15
+ * to the core budget.
16
+ * - crash recovery: a dead worker is respawned and its in-flight call retried
17
+ * once; a poison call that keeps crashing fails gracefully (never wedges the
18
+ * pool). A crash budget trips a circuit breaker (`healthy` → false) so the
19
+ * caller falls back to in-process dispatch instead of thrashing respawns.
20
+ * - graceful backstop: a call that can't be served within `softTimeoutMs`
21
+ * resolves with SUCCESS-shaped "busy, retry" guidance — never `isError`, so
22
+ * a momentary overload can't teach the agent to abandon codegraph — instead
23
+ * of hanging past the client's hard timeout.
24
+ */
25
+ import type { ToolResult } from './tools';
26
+ /**
27
+ * Minimal worker surface the pool drives — satisfied by a real `worker_threads`
28
+ * Worker. Abstracted so tests can inject a fake worker and exercise the pool's
29
+ * queue / growth / crash-recovery / backstop logic without spawning threads or
30
+ * needing a built `dist/`.
31
+ */
32
+ export interface PoolWorker {
33
+ postMessage(msg: unknown): void;
34
+ terminate(): Promise<number> | void;
35
+ on(event: 'message', cb: (m: unknown) => void): void;
36
+ on(event: 'error', cb: (e: Error) => void): void;
37
+ on(event: 'exit', cb: (code: number) => void): void;
38
+ }
39
+ export interface QueryPoolOptions {
40
+ /** Default project root each worker opens at spawn. */
41
+ root: string;
42
+ /** Max worker threads. Defaults to `clamp(cores-1, 1, 16)`. */
43
+ size?: number;
44
+ /** Linger before a queued call gets busy-guidance. Default 45s. */
45
+ softTimeoutMs?: number;
46
+ /** Retries for an in-flight call whose worker crashed. Default 1. */
47
+ maxRetries?: number;
48
+ /** Worker factory (tests inject a fake). Defaults to a real `worker_threads` Worker. */
49
+ createWorker?: () => PoolWorker;
50
+ }
51
+ /**
52
+ * Resolve the pool size from the `CODEGRAPH_QUERY_POOL_SIZE` override and the
53
+ * machine's core count. `0` (or a negative) explicitly disables the pool (the
54
+ * caller serves in-process — today's behavior). Unset → `clamp(cores-1, 1, 16)`:
55
+ * leave a core for the main loop + OS, but never zero, since even one worker
56
+ * frees the transport and lets responses flush incrementally.
57
+ */
58
+ export declare function resolvePoolSize(envVal: string | undefined, cpuCount: number): number;
59
+ export declare class QueryPool {
60
+ private idle;
61
+ private queue;
62
+ private inflight;
63
+ private workers;
64
+ private pendingWorkers;
65
+ private nextId;
66
+ private totalCrashes;
67
+ private destroyed;
68
+ private readonly root;
69
+ private readonly maxSize;
70
+ private readonly softTimeoutMs;
71
+ private readonly maxRetries;
72
+ private readonly createWorker;
73
+ constructor(opts: QueryPoolOptions);
74
+ /** Pool size cap (for logging/status). */
75
+ get size(): number;
76
+ /** Live worker count (for tests/status). */
77
+ get liveWorkers(): number;
78
+ /**
79
+ * False once the crash budget is exhausted (or after destroy). The ToolHandler
80
+ * checks this and falls back to in-process dispatch — a broken worker platform
81
+ * degrades to today's behavior instead of failing tool calls.
82
+ */
83
+ get healthy(): boolean;
84
+ private spawnOne;
85
+ private onMessage;
86
+ private onWorkerGone;
87
+ private drain;
88
+ private settle;
89
+ /** Run a read tool on the pool. Always resolves (never rejects). */
90
+ run(toolName: string, args: Record<string, unknown>): Promise<ToolResult>;
91
+ /** Terminate all workers and answer any outstanding calls gracefully. */
92
+ destroy(): Promise<void>;
93
+ }
94
+ //# sourceMappingURL=query-pool.d.ts.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Query worker thread — issue: concurrent MCP tool calls starve the daemon.
3
+ *
4
+ * The shared daemon serves every session on ONE event loop with synchronous
5
+ * `node:sqlite`. `codegraph_explore` is CPU-heavy (FTS + RWR/personalized-
6
+ * PageRank + impact + output building) stitched together by microtask `await`s,
7
+ * so N concurrent explores keep the microtask queue continuously full and
8
+ * starve the macrotask phases — timers AND socket I/O. The transport freezes:
9
+ * no response flushes, no request is read, until the whole batch drains. With
10
+ * ~10 subagents that routinely exceeds the MCP client's request timeout.
11
+ *
12
+ * This worker moves the heavy read-tool dispatch OFF the daemon's main loop.
13
+ * Each worker owns its OWN read connection (node:sqlite WAL allows N concurrent
14
+ * readers across connections — verified: a worker reader sees the main writer's
15
+ * committed catch-up/watcher writes), so {@link QueryPool} runs N tool calls in
16
+ * true parallel up to core count while the main loop stays free for the MCP
17
+ * transport. The worker runs {@link ToolHandler.executeReadTool} — validation +
18
+ * dispatch + error classification — and returns the raw {@link ToolResult}; the
19
+ * MAIN thread keeps the catch-up gate, the watcher-state notices (staleness /
20
+ * worktree), `codegraph_status`, and telemetry, none of which a watcher-less
21
+ * read connection can answer.
22
+ */
23
+ export {};
24
+ //# sourceMappingURL=query-worker.d.ts.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Server-level instructions emitted in the MCP `initialize` response.
3
+ *
4
+ * MCP clients (Claude Code, Cursor, opencode, LangChain, OpenAI Agent
5
+ * SDK, …) surface this text in the agent's system prompt automatically,
6
+ * giving the agent a high-level playbook for the codegraph toolset
7
+ * before it sees individual tool descriptions.
8
+ *
9
+ * Goals when editing this:
10
+ * - Lead the agent to codegraph_explore for any structural/flow question
11
+ * - Reinforce "explore instead of Read/Grep" for indexed code
12
+ * - Anti-patterns (don't re-verify with grep; don't hand-reconstruct flows)
13
+ *
14
+ * Keep it tight. The agent reads this every session — long instructions
15
+ * burn tokens. The DEFAULT MCP surface is `codegraph_explore` ALONE (see
16
+ * DEFAULT_MCP_TOOLS in tools.ts) — reference only that tool here. The other
17
+ * tools (node/search/callers/…) stay defined and are re-enablable via
18
+ * CODEGRAPH_MCP_TOOLS, but they are NOT listed to agents, so don't name them.
19
+ */
20
+ export declare const SERVER_INSTRUCTIONS = "# Codegraph \u2014 code intelligence over an indexed knowledge graph\n\nCodegraph is a SQLite knowledge graph of every symbol, edge, and file in\nthe workspace \u2014 pre-computed structure you would otherwise re-derive by\nreading files (cached intelligence: thousands of parse/trace decisions you\ndon't pay to re-reason each run). Reads are sub-millisecond; the index lags\nwrites by ~1s through the file watcher. Reach for it BEFORE *and* while\nwriting or editing code \u2014 not just for questions: one call returns the\nverbatim source PLUS who calls it and what it affects, so you edit with the\nblast radius in view. More accurate context, in far fewer tokens and\nround-trips than reading files yourself.\n\n## One tool: codegraph_explore \u2014 use it instead of reading files\n\nThere is a single tool, `codegraph_explore`, and it is Read-equivalent. It\ntakes either a natural-language question or a bag of symbol/file names and\nreturns the **verbatim, line-numbered source** of the relevant symbols\ngrouped by file \u2014 the same `<n>\\t<line>` shape `Read` gives you, safe to\n`Edit` from \u2014 PLUS the call path among them (including dynamic-dispatch hops\nlike callbacks, React re-render, and JSX children that grep can't follow) and\na blast-radius summary of what depends on them.\n\nWhether you're answering \"how does X work\" or implementing a change (fixing a\nbug, adding a feature), call `codegraph_explore` before you Read. ONE call\nusually answers the whole question. Codegraph IS the pre-built search index \u2014\nso running your own grep + read loop, or delegating the lookup to a separate\nfile-reading sub-task/agent, repeats work codegraph already did and costs more\nfor the same answer. A direct codegraph answer is typically one to a few\ncalls; a grep/read exploration is dozens.\n\n## How to query\n\n- **Almost any question \u2014 \"how does X work\", architecture, a bug, \"what/where is X\", or surveying an area** \u2192 `codegraph_explore` with a natural-language question or the relevant names. ONE capped call returns the verbatim source grouped by file; most often the ONLY call you need.\n- **\"How does X reach/become Y? / the flow / the path from X to Y\"** \u2192 `codegraph_explore`, naming the symbols that span the flow (e.g. `mutateElement renderScene`) \u2014 it surfaces the call path among them, riding dynamic-dispatch hops, and returns their source.\n- **Reading or editing a file/symbol you can name** \u2192 put its name or file path in the `codegraph_explore` query \u2014 it returns that current line-numbered source (safe to `Edit` from) with the call path and blast radius attached, so you don't Read it separately. For an overloaded name it returns every matching definition's body in one call.\n- **Need more?** Call `codegraph_explore` again with more specific names \u2014 treat the source it returns as already Read.\n\n## Anti-patterns\n\n- **Trust codegraph's results \u2014 don't re-verify them with grep.** They come from a full AST parse; re-checking with grep is slower, less accurate, and wastes context.\n- **Don't grep or Read first** to find or understand indexed code \u2014 ONE `codegraph_explore` returns the relevant symbols' source together in a single round-trip. Reach for raw `Read`/`Grep` only to confirm a specific detail codegraph didn't cover, or for what codegraph doesn't index (configs, docs).\n- **Don't reconstruct a flow by hand** \u2014 name the endpoints in one `codegraph_explore` and it surfaces the path between them, dynamic-dispatch hops included.\n- **After editing, check the staleness banner.** When a tool response starts with \"\u26A0\uFE0F Some files referenced below were edited since the last index sync\u2026\", the listed files are pending re-index \u2014 Read those specific files for accurate content. Every file NOT in that banner is fresh, so still trust codegraph. A different, rarer banner \u2014 \"\u26A0\uFE0F CodeGraph auto-sync is DISABLED\u2026\" \u2014 means live watching stopped entirely (the whole index is frozen, not just a few files); until it's resolved, Read files directly to confirm anything that may have changed.\n\n## Limitations\n\n- If a tool reports a project isn't indexed (no `.codegraph/`), stop calling codegraph tools for that project for the rest of the session and use your built-in tools there instead. Indexing is the user's decision \u2014 mention they can run `codegraph init` if it comes up, but don't run it yourself.\n- Index lags file writes by ~1 second.\n- Cross-file resolution is best-effort name matching; ambiguous calls may return multiple candidates.\n- No live correctness validation \u2014 that's still the TypeScript compiler / test suite / linter's job. Codegraph supplements those with structural context they don't have.\n\n## Supported Languages\n\nThe indexer recognizes a fixed set of languages; if you ask about symbols in a\nfile with an unsupported extension, codegraph will report the project isn't\nindexed for that file and you should fall back to Read/Grep. The fork-specific\naddition beyond upstream codegraph is **VBA / Access** (Dysflow export\nformat):\n\n- **VBA / Access** - Dysflow exports Access/VBA source as `.bas`/`.cls`/\n `.form.txt`/`.report.txt`. Codegraph extracts `.bas`/`.cls` as `module`/\n `class`/`function` nodes with `calls`/`implements`/`references` edges\n (procedural-level; regex-based, not full AST). Cross-module calls, qualified\n `Dim As`, `WithEvents`, and SQL table references inside string literals\n emit synthesized edges tagged `metadata.synthesizedBy` (`vba-name-resolution`,\n `vba-withevents`, `vba-sql-table`). `.form.txt` and `.report.txt` are\n extracted as a `module` plus one `property` per Access control - **no**\n `function`/`sub`/`class` nodes come from form files; the canonical code\n lives in the sibling `.cls`, parsed by the same extractor on that file.\n Pass `projectPath` to a codegraph index that includes VBA files.\n";
21
+ /**
22
+ * Instructions variant sent when the server's own root has NO codegraph index.
23
+ *
24
+ * The tools are still exposed (gating tool availability on whether `./` has an
25
+ * index is the bug behind #964: it breaks monorepos where only sub-projects are
26
+ * indexed, and a server that started before `codegraph init` never surfaces the
27
+ * tools afterward). Instead of an "inactive" note, this variant tells the agent
28
+ * codegraph works **per project**: there's no default project to query, so pass
29
+ * a `projectPath` to any project that HAS a `.codegraph/`. The full single-
30
+ * project playbook ({@link SERVER_INSTRUCTIONS}) is sent instead when the root
31
+ * IS indexed, so the common case stays tight.
32
+ */
33
+ export declare const SERVER_INSTRUCTIONS_NO_ROOT_INDEX = "# Codegraph \u2014 available (per-project; pass projectPath)\n\nCodegraph is a SQLite knowledge graph of a codebase's symbols, edges, and\nfiles: one `codegraph_explore` call returns the verbatim, line-numbered source\nof the relevant symbols PLUS the call paths between them and a blast-radius\nsummary \u2014 replacing a grep + Read loop with one round-trip.\n\nThis server started somewhere with no `.codegraph/` of its own, so there is no\ndefault project \u2014 but the tools are available and work **per project**:\n\n- To query a project that HAS a `.codegraph/` index (e.g. a service inside a\n monorepo, or a second repo), pass its path as `projectPath` to\n `codegraph_explore` (and any other codegraph tool). Codegraph resolves the\n nearest `.codegraph/` at or above that path and answers from it \u2014 for as many\n projects as you like in one session.\n- For a project with no `.codegraph/`, use your built-in tools (Read/Grep/Glob)\n for that project. Indexing is the user's decision \u2014 don't run it yourself, but\n if it comes up they can run `codegraph init` in a project to enable codegraph\n there (a new index is picked up live, no restart).\n";
34
+ //# sourceMappingURL=server-instructions.d.ts.map
@@ -0,0 +1,79 @@
1
+ /**
2
+ * MCP per-connection session — speaks the JSON-RPC protocol (initialize,
3
+ * tools/list, tools/call) over a single {@link JsonRpcTransport}. It owns
4
+ * per-client state only (which protocol version the client asked for, whether
5
+ * it advertised `roots`, the one-shot roots/list latch); the heavyweight
6
+ * resources (CodeGraph, watcher, ToolHandler) live in the shared
7
+ * {@link MCPEngine} so daemon mode can collapse N inotify sets / DB handles
8
+ * to one.
9
+ *
10
+ * The state-machine itself mirrors what `MCPServer` used to do inline before
11
+ * issue #411 split it out — the same regression tests in
12
+ * `__tests__/mcp-initialize.test.ts` still drive this code path.
13
+ */
14
+ import { JsonRpcTransport } from './transport';
15
+ import { MCPEngine } from './engine';
16
+ /**
17
+ * MCP Server Info — kept on the session because some clients log it. The
18
+ * version tracks the real package version (was a hard-coded '0.1.0').
19
+ */
20
+ export declare const SERVER_INFO: {
21
+ name: string;
22
+ version: string;
23
+ };
24
+ /** MCP Protocol Version (latest the server claims). */
25
+ export declare const PROTOCOL_VERSION = "2024-11-05";
26
+ export interface MCPSessionOptions {
27
+ /**
28
+ * Explicit project path from the `--path` CLI flag. When set, the session
29
+ * will not bother asking the client for `roots/list` — we already know
30
+ * where the project lives.
31
+ */
32
+ explicitProjectPath?: string | null;
33
+ }
34
+ /**
35
+ * One MCP client's view of the server. Created fresh per stdio launch
36
+ * (direct mode) or per socket connection (daemon mode).
37
+ */
38
+ export declare class MCPSession {
39
+ private transport;
40
+ private engine;
41
+ private clientSupportsRoots;
42
+ /** From the initialize handshake — attributes usage rollups to the agent host. */
43
+ private clientInfo;
44
+ private rootsAttempted;
45
+ private resolvePromise;
46
+ private explicitProjectPath;
47
+ constructor(transport: JsonRpcTransport, engine: MCPEngine, opts?: MCPSessionOptions);
48
+ /**
49
+ * Start handling messages from the transport. Returns immediately — the
50
+ * session lives for as long as the transport is open.
51
+ */
52
+ start(): void;
53
+ /**
54
+ * Tear down the session. Does NOT touch the engine (the engine may serve
55
+ * other sessions) or call `process.exit` (the daemon decides when to exit).
56
+ */
57
+ stop(): void;
58
+ /** Underlying transport — exposed for daemon-side close hooks. */
59
+ getTransport(): JsonRpcTransport;
60
+ private handleMessage;
61
+ private handleInitialize;
62
+ private handleToolsList;
63
+ private handleToolsCall;
64
+ /**
65
+ * Lazy default-project resolution. Three layers:
66
+ * 1. await the in-flight init kicked off from `handleInitialize` (if any);
67
+ * 2. if still uninitialized and we never asked the client for its roots,
68
+ * do so now (one-shot); fall back to cwd if the client lacks roots;
69
+ * 3. last-resort: re-walk from the best candidate — picks up projects
70
+ * that were `codegraph init`'d *after* the server started.
71
+ */
72
+ private retryInitIfNeeded;
73
+ /**
74
+ * Ask the client for its workspace root via `roots/list` and open the
75
+ * first one. Falls back to `process.cwd()` on timeout or empty answer.
76
+ */
77
+ private initFromRoots;
78
+ }
79
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Treat a stdin failure as a shutdown signal — issue #799.
3
+ *
4
+ * An MCP stdio server's lifeline is its stdin: when the host/client goes away,
5
+ * stdin should end and the server should exit. The server paths listened for
6
+ * `'end'` and `'close'` — but NOT `'error'`.
7
+ *
8
+ * That gap bites with a socket-backed stdin, which is the shape VS Code /
9
+ * Claude Code use (a socketpair, not a pipe). When the client dies, the socket
10
+ * can surface as an `'error'` (ECONNRESET / hangup) rather than a clean
11
+ * `'close'`. With no `'error'` listener, Node escalates it to the process-wide
12
+ * `uncaughtException` handler, which logs and keeps running — so the server
13
+ * orphans instead of exiting. Worse, on Linux a `POLLHUP` socket fd left
14
+ * registered in epoll wakes the event loop continuously, pinning a core at
15
+ * 100% CPU (the spin reported in #799); once the main thread spins, the
16
+ * `setInterval` PPID watchdog can't even fire, so the orphan runs forever.
17
+ *
18
+ * Fix: listen for `'error'` as well, and DESTROY the stdin stream on any
19
+ * terminal event so the fd leaves epoll and can't keep churning, then run the
20
+ * caller's shutdown. Fires `onTerminal` at most once — callers' shutdowns are
21
+ * already re-entry-guarded, but the single-shot guard also keeps `destroy()`'s
22
+ * follow-on `'close'` from re-invoking it.
23
+ *
24
+ * `stream` is injectable for tests; it defaults to `process.stdin`.
25
+ */
26
+ export declare function treatStdinFailureAsShutdown(onTerminal: () => void, stream?: NodeJS.ReadableStream): void;
27
+ //# sourceMappingURL=stdin-teardown.d.ts.map