Skip to content

Commit 4402667

Browse files
anandgupta42claude
andcommitted
fix: [#830] project_scan must not crash on missing binaries (32% error rate, 437 users)
Telemetry-2026-05-21 (2,503 machines, 14 days) shows `project_scan` failing 32% of the time across 1,171 distinct users — the broadest user-impact bug in the dataset. Every failure has the same fingerprint: `Executable not found in $PATH: ?`. Root cause (two-part) 1. `detectGit()` called `Bun.spawnSync(["git", ...])` three times with no try/catch wrapper. Bun's `spawnSync` THROWS when the binary is missing from PATH (not just when it exits non-zero). In any environment without git installed — minimal Docker images, fresh Windows installs without Git for Windows, some CI runners — the throw escaped detectGit, escaped the Promise.all in execute(), and crashed the whole tool. The other parts of the scan (dbt detection, env-var inspection, config files) didn't depend on git but were lost too. 2. The PII masker (`telemetry/index.ts:1083-1084`) strips quoted strings to `?`. Bun's error message `Executable not found in $PATH: "git"` became `Executable not found in $PATH: ?` in telemetry — the binary name was destroyed, making the bug look like a generic shell failure for two months. Fix - New `safeSpawnSync` helper: catches the throw, returns `null` so callers get a deterministic "command failed" instead of an exception. Used by every `Bun.spawnSync` call in `detectGit()`. - Every detection in `ProjectScanTool.execute()` now wraps with `.catch()` that records the failure to a `degraded: string[]` list and continues with a sentinel result. The tool no longer fails as a whole — it always succeeds with partial results, and the LLM sees exactly what was unavailable in both the output (a new "Degraded Detections" section) and the metadata (`degraded` field). - This implements the "make tool infallible with `degraded: [...]` field" recommendation from the P0 triage doc. Test - New test "does not throw when git binary is missing from PATH" pins the regression: sets PATH to an empty directory, calls `detectGit()`, asserts it returns `{ isRepo: false }` without throwing. Pre-fix this test would have thrown the masked error. Validation - `tsgo --noEmit`: pass. - `bun test test/tool/project-scan.test.ts`: 78 pass / 0 fail (1 new test). - Marker check: pass — no upstream-shared files touched. Expected impact - `project_scan` error rate drops from 32% to near-zero. Users without git get a successful scan with `degraded: ["git"]` instead of an opaque tool failure. - Same defensive pattern protects against future Dispatcher/Config/Skill failures that previously could have crashed the whole tool. Closes #830 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 476d234 commit 4402667

2 files changed

Lines changed: 140 additions & 32 deletions

File tree

‎packages/opencode/src/altimate/tools/project-scan.ts‎

Lines changed: 112 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -47,28 +47,45 @@ export interface ConfigFileInfo {
4747

4848
// --- Detection functions (exported for testing) ---
4949

50+
/**
51+
* Run a subprocess that may or may not exist on the host.
52+
*
53+
* `Bun.spawnSync` throws when the binary is missing from $PATH (e.g.
54+
* `Executable not found in $PATH: "git"`) — not just when it exits non-zero.
55+
* Telemetry shows this fingerprint hitting ~437 distinct users on
56+
* `project_scan` (the binary name `"git"` was masked to `?` downstream,
57+
* which made it look like a generic shell error). Wrap every spawn so a
58+
* missing binary degrades gracefully instead of crashing the whole tool.
59+
*/
60+
function safeSpawnSync(args: string[]): { exitCode: number; stdout: string } | null {
61+
try {
62+
const result = Bun.spawnSync(args, { stdout: "pipe", stderr: "pipe" })
63+
return {
64+
exitCode: result.exitCode ?? 1,
65+
stdout: result.stdout?.toString() ?? "",
66+
}
67+
} catch {
68+
// Binary missing from PATH, permission denied, etc. — treat as
69+
// "command failed" so the caller sees a deterministic result instead
70+
// of an exception bubbling up.
71+
return null
72+
}
73+
}
74+
5075
export async function detectGit(): Promise<GitInfo> {
51-
const isRepoResult = Bun.spawnSync(["git", "rev-parse", "--is-inside-work-tree"], {
52-
stdout: "pipe",
53-
stderr: "pipe",
54-
})
55-
if (isRepoResult.exitCode !== 0) {
76+
const isRepoResult = safeSpawnSync(["git", "rev-parse", "--is-inside-work-tree"])
77+
if (!isRepoResult || isRepoResult.exitCode !== 0) {
5678
return { isRepo: false }
5779
}
5880

59-
const branchResult = Bun.spawnSync(["git", "branch", "--show-current"], {
60-
stdout: "pipe",
61-
stderr: "pipe",
62-
})
63-
const branch = branchResult.exitCode === 0 ? branchResult.stdout.toString().trim() || undefined : undefined
81+
const branchResult = safeSpawnSync(["git", "branch", "--show-current"])
82+
const branch =
83+
branchResult && branchResult.exitCode === 0 ? branchResult.stdout.trim() || undefined : undefined
6484

6585
let remoteUrl: string | undefined
66-
const remoteResult = Bun.spawnSync(["git", "remote", "get-url", "origin"], {
67-
stdout: "pipe",
68-
stderr: "pipe",
69-
})
70-
if (remoteResult.exitCode === 0) {
71-
remoteUrl = remoteResult.stdout.toString().trim()
86+
const remoteResult = safeSpawnSync(["git", "remote", "get-url", "origin"])
87+
if (remoteResult && remoteResult.exitCode === 0) {
88+
remoteUrl = remoteResult.stdout.trim()
7289
}
7390

7491
return { isRepo: true, branch, remoteUrl }
@@ -454,40 +471,82 @@ export const ProjectScanTool = Tool.define("project_scan", {
454471
async execute(args, ctx) {
455472
const cwd = process.cwd()
456473

457-
// Run local detections in parallel
474+
// Track which sub-detections failed so the LLM can see partial results
475+
// instead of getting a single opaque "Executable not found in $PATH: ?"
476+
// failure (the previous behavior — see safeSpawnSync above).
477+
const degraded: string[] = []
478+
479+
// Run local detections in parallel. Every detection function is now
480+
// expected to fail-safe (return a "not found" or empty result) rather
481+
// than throw — see detectGit + detectDataTools.
458482
const [git, dbtProject, envVars, dataTools, configFiles] = await Promise.all([
459-
detectGit(),
460-
detectDbtProject(cwd),
461-
detectEnvVars(),
462-
detectDataTools(!!args.skip_tools),
463-
detectConfigFiles(cwd),
483+
detectGit().catch(() => {
484+
degraded.push("git")
485+
return { isRepo: false } as GitInfo
486+
}),
487+
detectDbtProject(cwd).catch(() => {
488+
degraded.push("dbt-project")
489+
return { found: false } as DbtProjectInfo
490+
}),
491+
detectEnvVars().catch(() => {
492+
degraded.push("env-vars")
493+
return [] as EnvVarConnection[]
494+
}),
495+
detectDataTools(!!args.skip_tools).catch(() => {
496+
degraded.push("data-tools")
497+
return [] as DataToolInfo[]
498+
}),
499+
detectConfigFiles(cwd).catch(() => {
500+
degraded.push("config-files")
501+
return { altimateConfig: false, sqlfluff: false, preCommit: false } as ConfigFileInfo
502+
}),
464503
])
465504

466-
// Run bridge-dependent detections with individual error handling
505+
// Run bridge-dependent detections with individual error handling. A
506+
// dispatcher failure on any one of these is expected (Python engine may
507+
// not be running locally) — degrade silently and report in metadata.
467508
const engineHealth = await Dispatcher.call("ping", {} as any)
468509
.then((r) => ({ healthy: true, status: r.status }))
469-
.catch(() => ({ healthy: false, status: undefined as string | undefined }))
510+
.catch(() => {
511+
degraded.push("python-engine")
512+
return { healthy: false, status: undefined as string | undefined }
513+
})
470514

471515
const existingConnections = await Dispatcher.call("warehouse.list", {})
472516
.then((r) => r.warehouses)
473-
.catch(() => [] as Array<{ name: string; type: string; database?: string }>)
517+
.catch(() => {
518+
degraded.push("warehouse.list")
519+
return [] as Array<{ name: string; type: string; database?: string }>
520+
})
474521

475522
const dbtProfiles = await Dispatcher.call("dbt.profiles", {
476523
projectDir: dbtProject.found ? dbtProject.path : undefined,
477524
})
478525
.then((r) => r.connections ?? [])
479-
.catch(() => [] as Array<{ name: string; type: string; config: Record<string, unknown> }>)
526+
.catch(() => {
527+
degraded.push("dbt.profiles")
528+
return [] as Array<{ name: string; type: string; config: Record<string, unknown> }>
529+
})
480530

481531
const dockerContainers = args.skip_docker
482532
? []
483533
: await Dispatcher.call("warehouse.discover", {} as any)
484534
.then((r) => r.containers ?? [])
485-
.catch(() => [] as Array<{ name: string; db_type: string; host: string; port: number; database?: string }>)
486-
487-
const schemaCache = await Dispatcher.call("schema.cache_status", {}).catch(() => null)
535+
.catch(() => {
536+
degraded.push("warehouse.discover")
537+
return [] as Array<{ name: string; db_type: string; host: string; port: number; database?: string }>
538+
})
539+
540+
const schemaCache = await Dispatcher.call("schema.cache_status", {}).catch(() => {
541+
degraded.push("schema.cache_status")
542+
return null
543+
})
488544

489545
const dbtManifest = dbtProject.manifestPath
490-
? await Dispatcher.call("dbt.manifest", { path: dbtProject.manifestPath }).catch(() => null)
546+
? await Dispatcher.call("dbt.manifest", { path: dbtProject.manifestPath }).catch(() => {
547+
degraded.push("dbt.manifest")
548+
return null
549+
})
491550
: null
492551

493552
// Deduplicate connections
@@ -655,7 +714,12 @@ export const ProjectScanTool = Tool.define("project_scan", {
655714
if (connections.newFromDocker.length > 0) connectionSources.push("docker")
656715
if (connections.newFromEnv.length > 0) connectionSources.push("env-var")
657716

658-
const mcpConfig = (await Config.get()).mcp ?? {}
717+
const mcpConfig = await Config.get()
718+
.then((c) => c.mcp ?? {})
719+
.catch(() => {
720+
degraded.push("config")
721+
return {}
722+
})
659723
const mcpServerCount = Object.keys(mcpConfig).length
660724

661725
const enabledFlags: string[] = []
@@ -702,11 +766,26 @@ export const ProjectScanTool = Tool.define("project_scan", {
702766
feature_flags: enabledFlags,
703767
})
704768

769+
// Surface degraded detections in the output so the LLM can recommend
770+
// installing the missing pieces without thinking the tool itself failed.
771+
if (degraded.length > 0) {
772+
lines.push("")
773+
lines.push("## Degraded Detections")
774+
lines.push(
775+
`The following sub-detections failed and were skipped (the rest of the scan is still valid):`,
776+
)
777+
for (const d of degraded) {
778+
lines.push(`- ${d}`)
779+
}
780+
}
781+
705782
// Build metadata
706783
const toolsFound = dataTools.filter((t) => t.installed).map((t) => t.name)
707784

708785
return {
709-
title: `Scan: ${totalConnections} connection(s), ${dbtProject.found ? "dbt found" : "no dbt"}`,
786+
title: `Scan: ${totalConnections} connection(s), ${dbtProject.found ? "dbt found" : "no dbt"}${
787+
degraded.length > 0 ? ` (${degraded.length} degraded)` : ""
788+
}`,
710789
metadata: {
711790
engine_healthy: engineHealth.healthy,
712791
git: { isRepo: git.isRepo, branch: git.branch },
@@ -729,6 +808,7 @@ export const ProjectScanTool = Tool.define("project_scan", {
729808
}
730809
: { warehouses: 0, tables: 0, columns: 0 },
731810
tools_found: toolsFound,
811+
degraded: degraded.length > 0 ? degraded : undefined,
732812
},
733813
output: lines.join("\n"),
734814
}

‎packages/opencode/test/tool/project-scan.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,34 @@ describe("detectGit", () => {
119119
}
120120
})
121121

122+
test("does not throw when git binary is missing from PATH", async () => {
123+
// Telemetry-2026-05-21 showed `project_scan` failing 32% of the time with
124+
// `Executable not found in $PATH: ?` — the binary was masked to `?` by the
125+
// PII filter, but the underlying cause was Bun.spawnSync throwing on a
126+
// missing git executable. This test pins the fix: detectGit must return a
127+
// sentinel result rather than throw, so the rest of project_scan still
128+
// runs.
129+
const dir = nextTmpDir()
130+
await fsp.mkdir(dir, { recursive: true })
131+
132+
const originalPath = process.env.PATH
133+
const originalCwd = process.cwd()
134+
// Point PATH at an empty directory so the shell can't find git (or any
135+
// other binary). Bun.spawnSync will throw "Executable not found in $PATH"
136+
// — which the safeSpawnSync wrapper should catch.
137+
process.env.PATH = dir
138+
process.chdir(dir)
139+
try {
140+
const result = await detectGit()
141+
expect(result.isRepo).toBe(false)
142+
expect(result.branch).toBeUndefined()
143+
expect(result.remoteUrl).toBeUndefined()
144+
} finally {
145+
process.chdir(originalCwd)
146+
process.env.PATH = originalPath
147+
}
148+
})
149+
122150
afterAll(async () => {
123151
await fsp.rm(tmpRoot, { recursive: true, force: true }).catch(() => {})
124152
})

0 commit comments

Comments
 (0)