|
| 1 | +import { describe, it, expect } from 'vitest'; |
| 2 | +import fs from 'node:fs'; |
| 3 | +import path from 'node:path'; |
| 4 | + |
| 5 | +import type { CommandHook, CommandHookOutput, MinimalPlugin } from './testTypes.ts'; |
| 6 | +import { |
| 7 | + readOpencodeJsonc, |
| 8 | + stringifyJsonc, |
| 9 | + writeFileAtomic, |
| 10 | +} from '../palantir-mcp/opencode-config.ts'; |
| 11 | + |
| 12 | +function resolveOpencodeBin(): string { |
| 13 | + const fromEnv: string | undefined = process.env.OPENCODE_BIN; |
| 14 | + if (fromEnv && fromEnv.trim().length > 0) return fromEnv.trim(); |
| 15 | + |
| 16 | + // Prefer the opencode-managed install if present (common when multiple installs exist). |
| 17 | + const preferred: string = '/home/anandpant/.opencode/bin/opencode'; |
| 18 | + if (fs.existsSync(preferred)) return preferred; |
| 19 | + |
| 20 | + return 'opencode'; |
| 21 | +} |
| 22 | + |
| 23 | +function readDotEnvValue(envPath: string, key: string): string | null { |
| 24 | + let text: string; |
| 25 | + try { |
| 26 | + text = fs.readFileSync(envPath, 'utf8'); |
| 27 | + } catch { |
| 28 | + return null; |
| 29 | + } |
| 30 | + |
| 31 | + for (const line of text.split('\n')) { |
| 32 | + const trimmed: string = line.trim(); |
| 33 | + if (!trimmed || trimmed.startsWith('#')) continue; |
| 34 | + if (!trimmed.startsWith(`${key}=`)) continue; |
| 35 | + |
| 36 | + const raw: string = trimmed.slice(key.length + 1); |
| 37 | + let val: string = raw.trim(); |
| 38 | + if ( |
| 39 | + val.length >= 2 && |
| 40 | + ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) |
| 41 | + ) { |
| 42 | + val = val.slice(1, -1); |
| 43 | + } |
| 44 | + if (!val) return null; |
| 45 | + return val; |
| 46 | + } |
| 47 | + |
| 48 | + return null; |
| 49 | +} |
| 50 | + |
| 51 | +async function runCommand( |
| 52 | + cmd: string[], |
| 53 | + opts: { cwd: string } |
| 54 | +): Promise<{ exitCode: number; stdout: string; stderr: string }> { |
| 55 | + const proc = Bun.spawn(cmd, { |
| 56 | + cwd: opts.cwd, |
| 57 | + stdout: 'pipe', |
| 58 | + stderr: 'pipe', |
| 59 | + env: process.env, |
| 60 | + }); |
| 61 | + |
| 62 | + const stdout: string = await new Response(proc.stdout).text(); |
| 63 | + const stderr: string = await new Response(proc.stderr).text(); |
| 64 | + const exitCode: number = await proc.exited; |
| 65 | + return { exitCode, stdout, stderr }; |
| 66 | +} |
| 67 | + |
| 68 | +async function runCommandWithRetries( |
| 69 | + cmd: string[], |
| 70 | + opts: { cwd: string; attempts: number; delayMs: number } |
| 71 | +): Promise<{ exitCode: number; stdout: string; stderr: string; attempt: number }> { |
| 72 | + let last: { exitCode: number; stdout: string; stderr: string } | null = null; |
| 73 | + for (let attempt = 1; attempt <= opts.attempts; attempt += 1) { |
| 74 | + const res = await runCommand(cmd, { cwd: opts.cwd }); |
| 75 | + last = res; |
| 76 | + if (res.exitCode === 0) return { ...res, attempt }; |
| 77 | + await new Promise((r) => setTimeout(r, opts.delayMs)); |
| 78 | + } |
| 79 | + return { ...(last ?? { exitCode: 1, stdout: '', stderr: '' }), attempt: opts.attempts }; |
| 80 | +} |
| 81 | + |
| 82 | +function safeWriteBackupIfExists(filePath: string): void { |
| 83 | + if (!fs.existsSync(filePath)) return; |
| 84 | + const ts: string = new Date().toISOString().replace(/[:.]/g, '-'); |
| 85 | + const backup: string = `${filePath}.smoke.bak.${ts}`; |
| 86 | + fs.copyFileSync(filePath, backup); |
| 87 | +} |
| 88 | + |
| 89 | +const canRunSmoke: boolean = !!process.env.OPENCODE_SMOKE_REPO; |
| 90 | + |
| 91 | +const describeSmoke = canRunSmoke ? describe : describe.skip; |
| 92 | + |
| 93 | +describeSmoke('opencode smoke: setup-palantir-mcp -> opencode debug', () => { |
| 94 | + it('writes schema-valid config (no palantir_mcp) and opencode debug loads agents', async () => { |
| 95 | + const repo: string = path.resolve(process.env.OPENCODE_SMOKE_REPO ?? ''); |
| 96 | + const opencodeBin: string = resolveOpencodeBin(); |
| 97 | + |
| 98 | + const urlFromEnv: string | undefined = process.env.OPENCODE_SMOKE_FOUNDRY_URL; |
| 99 | + const urlFromDotEnv: string | null = readDotEnvValue(path.join(repo, '.env'), 'FOUNDRY_URL'); |
| 100 | + const foundryUrl: string | null = (urlFromEnv && urlFromEnv.trim()) || urlFromDotEnv; |
| 101 | + |
| 102 | + expect(fs.existsSync(repo)).toBe(true); |
| 103 | + |
| 104 | + const cfgPath: string = path.join(repo, 'opencode.jsonc'); |
| 105 | + safeWriteBackupIfExists(cfgPath); |
| 106 | + |
| 107 | + const hasToken: boolean = |
| 108 | + typeof process.env.FOUNDRY_TOKEN === 'string' && process.env.FOUNDRY_TOKEN.length > 0; |
| 109 | + |
| 110 | + if (!fs.existsSync(cfgPath)) { |
| 111 | + // If no config exists, only /setup can create it, which requires URL + token. |
| 112 | + expect(foundryUrl).toBeTruthy(); |
| 113 | + expect(hasToken).toBe(true); |
| 114 | + |
| 115 | + const plugin = (await import('../index.ts')).default as unknown as MinimalPlugin; |
| 116 | + const hooks = await plugin({ worktree: repo }); |
| 117 | + const hook = hooks['command.execute.before']; |
| 118 | + expect(typeof hook).toBe('function'); |
| 119 | + |
| 120 | + const output: CommandHookOutput = { parts: [] }; |
| 121 | + await (hook as CommandHook)( |
| 122 | + { |
| 123 | + command: 'setup-palantir-mcp', |
| 124 | + sessionID: 'smoke-session', |
| 125 | + arguments: String(foundryUrl), |
| 126 | + }, |
| 127 | + output |
| 128 | + ); |
| 129 | + } else { |
| 130 | + // If config exists (even if invalid), fix it without requiring Foundry access. |
| 131 | + const read = await readOpencodeJsonc(repo); |
| 132 | + expect(read.ok).toBe(true); |
| 133 | + if (!read.ok) throw new Error('unreachable'); |
| 134 | + |
| 135 | + const data: unknown = read.data; |
| 136 | + expect(!!data && typeof data === 'object' && !Array.isArray(data)).toBe(true); |
| 137 | + const root = data as Record<string, unknown>; |
| 138 | + |
| 139 | + if (root.palantir_mcp !== undefined) { |
| 140 | + delete root.palantir_mcp; |
| 141 | + await writeFileAtomic(cfgPath, stringifyJsonc(root)); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + expect(fs.existsSync(cfgPath)).toBe(true); |
| 146 | + |
| 147 | + const cfgText: string = fs.readFileSync(cfgPath, 'utf8'); |
| 148 | + expect(cfgText).not.toContain('"palantir_mcp"'); |
| 149 | + |
| 150 | + const debugConfig = await runCommandWithRetries( |
| 151 | + [opencodeBin, 'debug', 'config', '--log-level', 'ERROR'], |
| 152 | + { cwd: repo, attempts: 3, delayMs: 750 } |
| 153 | + ); |
| 154 | + if (debugConfig.exitCode !== 0) { |
| 155 | + throw new Error( |
| 156 | + `opencode debug config failed (attempt ${debugConfig.attempt})\\n` + |
| 157 | + `stderr:\\n${debugConfig.stderr.slice(-4000)}\\n` + |
| 158 | + `stdout:\\n${debugConfig.stdout.slice(-4000)}` |
| 159 | + ); |
| 160 | + } |
| 161 | + expect(debugConfig.stderr).not.toContain('Unrecognized key'); |
| 162 | + |
| 163 | + const debugLibrarian = await runCommandWithRetries( |
| 164 | + [opencodeBin, 'debug', 'agent', 'foundry-librarian', '--log-level', 'ERROR'], |
| 165 | + { cwd: repo, attempts: 3, delayMs: 750 } |
| 166 | + ); |
| 167 | + if (debugLibrarian.exitCode !== 0) { |
| 168 | + throw new Error( |
| 169 | + `opencode debug agent foundry-librarian failed (attempt ${debugLibrarian.attempt})\\n` + |
| 170 | + `stderr:\\n${debugLibrarian.stderr.slice(-4000)}\\n` + |
| 171 | + `stdout:\\n${debugLibrarian.stdout.slice(-4000)}` |
| 172 | + ); |
| 173 | + } |
| 174 | + expect(debugLibrarian.stdout).toContain('foundry-librarian'); |
| 175 | + expect(debugLibrarian.stdout).toContain('palantir-mcp_'); |
| 176 | + |
| 177 | + const debugFoundry = await runCommandWithRetries( |
| 178 | + [opencodeBin, 'debug', 'agent', 'foundry', '--log-level', 'ERROR'], |
| 179 | + { |
| 180 | + cwd: repo, |
| 181 | + attempts: 3, |
| 182 | + delayMs: 750, |
| 183 | + } |
| 184 | + ); |
| 185 | + if (debugFoundry.exitCode !== 0) { |
| 186 | + throw new Error( |
| 187 | + `opencode debug agent foundry failed (attempt ${debugFoundry.attempt})\\n` + |
| 188 | + `stderr:\\n${debugFoundry.stderr.slice(-4000)}\\n` + |
| 189 | + `stdout:\\n${debugFoundry.stdout.slice(-4000)}` |
| 190 | + ); |
| 191 | + } |
| 192 | + expect(debugFoundry.stdout).toContain('foundry'); |
| 193 | + }, 60_000); |
| 194 | +}); |
0 commit comments