GitNexus/gitnexus/scripts
Gergő Magyar de63418f7e
fix(mcp): close MCP server timeout — stdout discipline + cold-start friction (#1383)
* fix(lbug): route diagnostic logs to stderr to avoid MCP stdio corruption

Replace console.log/console.warn with console.error in core/lbug so
diagnostic messages reach stderr and never corrupt the JSON-RPC stream
on MCP stdio. Per spec, the server MUST NOT write anything to stdout
that is not a valid MCP message.

- lbug-adapter.ts:367 - schema creation warning (MCP-reachable via lazy
  DB init from tool handlers)
- lbug-adapter.ts:1047,1054 - legacy embedding fallback diagnostics
  (currently HTTP-only, but covered by upcoming no-console lint rule)
- extension-loader.ts:191 - default warn handler fallback used during
  DuckDB extension loading

* feat(mcp): add stdout sentinel via AsyncLocalStorage transport-write tagging

Untagged process.stdout.write calls now redirect to stderr with a
[mcp:stdout-redirect] prefix instead of corrupting the JSON-RPC frame
stream. Identification is correctness-by-construction: the transport
wraps every send() in withMcpWrite() (AsyncLocalStorage) and the
sentinel checks isMcpWrite() per call. A byte-shape heuristic would
have falsely rejected Content-Length frames (start with C, end with })
and misclassified multi-chunk writes.

- gitnexus/src/mcp/stdio-context.ts: AsyncLocalStorage helpers + factory
- gitnexus/src/mcp/server.ts: install sentinel in safeStdout Proxy,
  flush summary at process exit
- gitnexus/src/mcp/compatible-stdio-transport.ts: wrap send() write in
  withMcpWrite so transport frames pass through cleanly
- gitnexus/test/unit/mcp-stdout-sentinel.test.ts: 17 cases covering
  pass-through, redirect, prefix, truncation (default 200 / custom),
  rate limit (default 10), one-shot warning, summary, mixed sequences

* feat(eslint): forbid console.log/warn and process.stdout.write in MCP-reachable code

Add a narrow ESLint override for gitnexus/src/mcp/**, gitnexus/src/core/lbug/**,
gitnexus/src/core/embeddings/**, and gitnexus/src/cli/mcp.ts that:
  - sets no-console: ['error', { allow: ['error'] }] — only console.error
    survives, since stderr is the only spec-safe channel for diagnostics
    while the MCP stdio transport owns stdout for JSON-RPC frames
  - adds no-restricted-syntax matching MemberExpression and CallExpression
    forms of process.stdout.write to close the bypass path that the
    AsyncLocalStorage sentinel cannot guarantee

Migrates 18 pre-existing console.log/warn call sites in core/embeddings/
(embedder.ts, embedding-pipeline.ts) to console.error; these are reached
from gitnexus_query semantic search and would have polluted MCP stdio
once a query triggered the embedding pipeline.

Adds eslint-disable-next-line comments in pool-adapter.ts at the four
legitimate process.stdout.write sites — they ARE the captured-real-write
infrastructure used by the sentinel and the silenceStdout/restoreStdout
mechanism.

The override is forward-compatible with feat/pino-logger (PR #1336)
which adds a broader no-console rule for gitnexus/src/; the narrow rule
here is a strict subset and rebases trivially when #1336 lands.

* feat(setup): pin setup-generated MCP config to installed version, keep static configs on @latest

The user-facing MCP config that 'gitnexus setup' writes into editor configs
now references gitnexus@<installed-version> instead of gitnexus@latest, read
dynamically from gitnexus/package.json#version at module load. This skips
the npm-registry metadata roundtrip on every MCP connect and stays
reproducible until the user explicitly upgrades.

Static example configs and quickstart docs intentionally keep @latest:
  - .mcp.json, gitnexus-claude-plugin/.mcp.json
  - gitnexus-claude-plugin/skills/*/mcp.json (6 files)
  - README.md / gitnexus/README.md MCP examples
Pinning these would create per-release version-bump churn for marginal
(~100-500ms) savings. The dominant cold-cache cost is the native rebuild
addressed separately by the GITNEXUS_SKIP_OPTIONAL_GRAMMARS env var.

README adds a one-line steer above the @latest quickstart pointing
repeated users at 'gitnexus setup' for the absolute-path config that
bypasses npx entirely.

Tests refactored to assert against the dynamic version (createRequire of
package.json) so they don't break on every release bump:
  - gitnexus/test/unit/setup.test.ts
  - gitnexus/test/unit/setup-jsonc.test.ts
  - gitnexus/test/unit/setup-codex.test.ts
  - gitnexus/test/integration/setup-skills.test.ts (regex match)

* feat(install,mcp): GITNEXUS_SKIP_OPTIONAL_GRAMMARS opt-out + missing-grammar warnings

Postinstall scripts (build-tree-sitter-dart.cjs, build-tree-sitter-proto.cjs)
gain a strict 'process.env.GITNEXUS_SKIP_OPTIONAL_GRAMMARS === "1"'
early-exit so users without a C++ toolchain (or anyone wanting fast
'npm install gitnexus') can skip the native rebuild. Strict '=1' only —
'true', 'yes', '0' and any other value fall through to the rebuild.

Add gitnexus/src/cli/optional-grammars.ts: cheap require.resolve probe for
each optional grammar, with a stderr warning helper. The warning surfaces:
  - At MCP server start (cli/mcp.ts) — unconditional, since the server
    serves any indexed repo and we cannot pre-filter by language.
  - At 'gitnexus analyze' start (cli/analyze.ts) — conditional on the
    target repo containing .dart/.proto files (cheap glob), so users with
    no relevant code don't see noise.

README documents the env var with the strict '=1' value and the trade-off
(faster install, no Dart/Proto parsing until reinstalled).

* test(mcp): child-process integration test asserts end-to-end stdout discipline

Spawns 'node dist/cli/index.js mcp' as a child, drives the MCP stdio
handshake (initialize -> initialized -> tools/list), reassembles every
stdout chunk into Content-Length-framed JSON-RPC messages, and asserts
zero stray bytes. Any byte outside a valid header-then-body window is
captured and surfaced in the failure message alongside the server's
stderr — this is the regression gate for U1 (no console.log/warn in
MCP-reachable code) and U3 (AsyncLocalStorage stdout sentinel).

Time budget: 5s local / 15s CI for first frame; 10s/30s total. Asserts
the published GitNexus tool surface (list_repos, query, context, impact,
detect_changes, rename) is reported by tools/list.

Adds 'pretest:integration': 'node scripts/build.js' so 'npm run
test:integration' rebuilds dist before the spawn — closes the
'stale dist masks regression' DX gap.

* fix(mcp): address PR #1383 review — sentinel scope, grammar detection, lint, contract

Blockers:
- B2: detectMissingOptionalGrammars now actually require()s each grammar
  instead of require.resolve(). For 'file:' optional dependencies the
  package directory is always installed regardless of postinstall outcome,
  so resolve() never threw and the missing-grammar warning never fired
  for the exact target users (those who set GITNEXUS_SKIP_OPTIONAL_GRAMMARS=1
  or whose native rebuild soft-failed). require() loads the entry, which
  triggers node-gyp-build and throws if .node is absent. Result memoized.

Should-fix:
- S1: Removed duplicate uncaughtException/unhandledRejection handlers from
  cli/mcp.ts. server.ts:startMCPServer already registers handlers with
  full stack traces; cli/mcp.ts handlers fired first with worse output and
  never got a chance to exit because server.ts shuts down immediately.
- S2: Sentinel is now actually global. New setActiveStdoutWrite() in
  pool-adapter so silenceStdout/restoreStdout cycles preserve a
  registered wrapper instead of unwinding to raw realStdoutWrite. At
  startMCPServer: install sentinel.write as process.stdout.write AND
  register it as the active handler. Direct process.stdout.write calls
  from anywhere (console.log, dependency banners, etc.) now route through
  the sentinel instead of bypassing it. The transport's _safeStdout Proxy
  remains as belt-and-suspenders.
- S3: ESLint no-restricted-syntax now also forbids destructuring of
  process.stdout (covers both 'const { write } = process.stdout' shapes
  and rest patterns).

Minor:
- M1: chunkToBuffer now handles plain Uint8Array (Buffer.from(u8)) instead
  of falling through to String(chunk) which produced '1,2,3,...' garbage.
- M2: Untagged-write callbacks are now invoked on next tick per the
  Node Writable.write contract — both within and beyond the rate-limit cap.
  extractCallback handles the (chunk, cb) and (chunk, encoding, cb) overloads.
- M3: setup.ts throws early if package.json#version is missing/non-string
  instead of emitting 'gitnexus@undefined'.
- M4: parser-loader.ts console.warn → console.error; ESLint scope extended
  to gitnexus/src/core/tree-sitter/** so future violations are caught.

New tests cover:
- Plain Uint8Array redirect (asserts no String(chunk) garbage).
- Writable callback fired async (next-tick) for both normal and
  past-rate-limit redirects.

Validation: cd gitnexus && npx tsc --noEmit clean; vitest run 7863 passed,
11 skipped; eslint clean on MCP-reachable scope; integration test green
against rebuilt dist/.

* fix(mcp): close pre-sentinel stdout window + tighten contracts

Address ce-code-review findings on PR #1383:

P1 — Sentinel install order (was: stdout corruption window during
mcpCommand pre-startup):
- Add idempotent installGlobalStdoutSentinel() to mcp/stdio-context.ts.
  It captures realStdoutWrite/realStderrWrite, replaces process.stdout.write,
  and registers with pool-adapter's setActiveStdoutWrite — exactly once.
- cli/mcp.ts now installs the sentinel as the FIRST line of mcpCommand,
  before warnMissingOptionalGrammars (which after the B2 fix actually
  require()s each native grammar binding and could emit node-gyp-build
  banners to raw stdout in the pre-sentinel window).
- mcp/server.ts startMCPServer keeps a safety-net call to the same helper;
  the second invocation is a no-op.

P1 — WriteFn type erasure:
- WriteFn now declared as  instead of
  , so the assignment
   and the
  setActiveStdoutWrite(sentinel.write) call don't silently cross a
  type boundary.

P1 — extractCallback fragility:
- Replaced backward-scan-with-undefined-break heuristic with a strict
  'last arg if function' check matching the documented Writable.write
  contract. No longer breaks on a future (chunk, options, cb) overload.

P2 — _detectionCache premature memoization:
- Removed the explicit cache. Node's module cache already memoizes
  require() — calling detectMissingOptionalGrammars multiple times is
  cheap. Removing the module-level mutable state makes the helper
  trivially testable (no need for a reset hatch).

P2 — Misleading 'reinstall' message on broken (not missing) grammars:
- detectMissingOptionalGrammars now distinguishes MODULE_NOT_FOUND /
  node-gyp-build 'no native build' patterns from other errors
  (SyntaxError, EACCES, native crash). Broken bindings get an
  actionable stderr line naming the real failure instead of the
  misleading 'reinstall to enable' hint.

Other:
- mcp/core/lbug-adapter.ts updated with a KEEP-THIS-FILE note. Tests
  use the path as a vi.mock seam (calltool-dispatch.test.ts and 7
  others); new non-test code may import core/lbug/pool-adapter.js
  directly. The maintainability finding flagging the shim as
  self-contradictory was incorrect — the shim has a real test purpose.

Validation: tsc clean, vitest 7863 passed (no regressions), eslint
clean on MCP-reachable scope, integration test green against rebuilt
dist/.

* fix(mcp): close import-time stdout corruption window

Codex's adversarial review on PR #1383 found that even though cli/mcp.ts
is loaded lazily by Commander, ITS static imports (startMCPServer,
LocalBackend, installGlobalStdoutSentinel, warnMissingOptionalGrammars)
evaluate synchronously when the module loads — well before mcpCommand's
function body runs. Three of those four imports transitively pulled in
core/lbug/pool-adapter.ts, which imports @ladybugdb/core at module top
level. The native binding's init can write to raw stdout in that
pre-sentinel window and corrupt the JSON-RPC frame stream.

Fix: shrink cli/mcp.ts's static-import closure to a single zero-dep
chain (mcp/stdio-context.js -> mcp/stdio-capture.js, both leaf-clean),
install the sentinel as the first executable statement of mcpCommand,
then dynamically import the heavy backend modules in parallel via
await Promise.all.

Per the plan at docs/plans/2026-05-06-002-fix-import-time-stdout-window-plan.md:

- U1: New leaf module gitnexus/src/mcp/stdio-capture.ts owns the
  stdout-capture singleton state (realStdoutWrite, realStderrWrite,
  activeStdoutWrite + setActiveStdoutWrite/getActiveStdoutWrite).
  Zero non-node: imports — adding any would re-introduce the hazard.

- U2: pool-adapter.ts re-exports the relocated symbols under the
  existing names so the test mock seam (8+ files use vi.mock on
  mcp/core/lbug-adapter.ts which re-exports * from pool-adapter)
  keeps working without churn. restoreStdout and the watchdog now
  read the active handler via getActiveStdoutWrite(). stdio-context.ts
  imports from stdio-capture directly.

- U3: cli/mcp.ts's static imports collapse to one
  (installGlobalStdoutSentinel). startMCPServer / LocalBackend /
  warnMissingOptionalGrammars become parallel await import()
  inside mcpCommand, after the sentinel install.

- U4: New regression test gitnexus/test/integration/mcp/import-closure.test.ts
  spawns a child Node process that imports dist/cli/mcp.js (without
  invoking mcpCommand), inspects the CJS module cache via createRequire,
  and asserts @ladybugdb/core (and tree-sitter native bindings) are
  NOT in the static-import closure. Characterization-first: this test
  was authored to fail against the pre-fix code and confirmed to do so
  before U1-U3 landed.

Validation: tsc clean; vitest 7865 passed / 11 skipped (2 new U4 cases);
eslint clean on MCP-reachable scope; integration server-startup test
green against rebuilt dist/.

* fix(mcp): drop dead ESLint selector + suppress redundant grammar warning

Two minor PR #1383 review findings:

1. eslint.config.mjs: removed Selector 3 (`Property[key.name='write'].properties:has(...)`).
   `.properties` is not a valid attribute on a Property node in the ESTree
   AST, so the :has clause never matched — dead code. Selector 4 covers
   the canonical `const { write } = process.stdout` shape; tightened its
   comment to make that explicit.

2. cli/mcp.ts: removed the unconditional warnMissingOptionalGrammars call
   at MCP startup. The analyze path already emits this warning at index
   time with relevantExtensions filtered to the repo's actual file types,
   and a repo can only be served by MCP after analyze has run. Repeating
   the warning unconditionally on every MCP session was pure noise on
   machines whose indexed repos don't use .dart/.proto.

* chore(mcp): address PR #1383 review nits

Three minor hygiene findings from the production-readiness review:

- cli/mcp.ts: rewrite stale comment that described
  warnMissingOptionalGrammars as living inside mcpCommand. The call was
  removed in ca617552 — this path no longer invokes it at all.
- test/integration/mcp/import-closure.test.ts: same comment drift fixed.
  Test assertion is unchanged and still passes for the right reason
  (cli/mcp.js's static-import closure is leaf-only).
- mcp/server.ts: rename _safeStdout to safeStdout. The leading underscore
  conventionally signals "intentionally unused" but the Proxy is passed
  to CompatibleStdioServerTransport on the next line.

No behavior change. Typecheck clean; ESLint MCP-reachable scope still 0
errors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 09:14:33 +01:00
..
bench-scope-resolution.ts feat(python): scope-based call resolution + registry-primary flip + perf + generalization (RFC #909 Ring 3) (#980) 2026-04-21 15:50:00 +01:00
build-tree-sitter-dart.cjs fix(mcp): close MCP server timeout — stdout discipline + cold-start friction (#1383) 2026-05-07 09:14:33 +01:00
build-tree-sitter-proto.cjs fix(mcp): close MCP server timeout — stdout discipline + cold-start friction (#1383) 2026-05-07 09:14:33 +01:00
build.js fix(serve): serve web UI at root path instead of 404 (#1048) 2026-04-27 13:17:40 +01:00
ci-list-migrated-languages.ts feat(python): scope-based call resolution + registry-primary flip + perf + generalization (RFC #909 Ring 3) (#980) 2026-04-21 15:50:00 +01:00
install-duckdb-extension.mjs fix(deps): upgrade @ladybugdb/core to 0.16.0 to resolve native segfaults (#1235) 2026-04-30 17:40:39 +01:00