mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 16:25:30 +00:00
Filter the shipped instruction list to files selected by the install profile and make the retained paths independent of the launch directory. Record the resolved paths for repair, and anchor the bundled skill lookup to the same config root. Refs #4029
472 lines
20 KiB
JavaScript
472 lines
20 KiB
JavaScript
/**
|
|
* Tests for scripts/build-opencode.js
|
|
*/
|
|
|
|
const assert = require("assert")
|
|
const fs = require("fs")
|
|
const { builtinModules } = require("module")
|
|
const os = require("os")
|
|
const path = require("path")
|
|
const { spawnSync } = require("child_process")
|
|
const { pathToFileURL } = require("url")
|
|
const { getNpmPackEntry } = require("../lib/npm-pack-output")
|
|
const { createManifestInstallPlan, applyInstallPlan } = require("../../scripts/lib/install-executor")
|
|
const { withHookConsent } = require("../../scripts/lib/install/hook-consent")
|
|
|
|
function checkRuntime(runtimeRoot, extension, loader, installedHome = false) {
|
|
const check = `
|
|
const assert = require("node:assert/strict")
|
|
const path = require("node:path")
|
|
const { pathToFileURL } = require("node:url")
|
|
const [root, extension, installedHome] = process.argv.slice(1)
|
|
const load = (name) => import(pathToFileURL(path.join(root, name + extension)).href)
|
|
|
|
async function main() {
|
|
const tools = await load("tools/index")
|
|
assert.deepEqual(Object.keys(tools).sort(), [
|
|
"changedFiles", "checkCoverage", "dependencyAnalyzer", "formatCode",
|
|
"gitSummary", "lintCheck", "runTests", "securityAudit",
|
|
])
|
|
for (const tool of Object.values(tools)) {
|
|
assert.equal(typeof tool.description, "string")
|
|
assert.equal(typeof tool.execute, "function")
|
|
}
|
|
|
|
const plugins = await load("plugins/index")
|
|
const entry = await load("index")
|
|
assert.deepEqual(Object.keys(entry), ["default"])
|
|
// The entry barrel exposes the real V2 definition; the plugins barrel is
|
|
// an inert distinct-id stub on purpose (OpenCode 2.x loads root plugin
|
|
// files AND the directory barrel, so re-exporting the real id from both
|
|
// would produce red "Duplicate plugin ID" registrations).
|
|
assert.notEqual(entry.default, plugins.default,
|
|
"entry and plugins barrels must not share one plugin id (duplicate registrations)")
|
|
assert.equal(entry.default.id, "ecc-hooks")
|
|
assert.equal(typeof entry.default.setup, "function")
|
|
assert.equal(plugins.default.id, "ecc-hooks-entry")
|
|
assert.equal(typeof plugins.default.setup, "function")
|
|
const logs = []
|
|
const active = await load("plugins/ecc-hooks")
|
|
assert.equal(active.default, entry.default)
|
|
assert.equal(typeof active.ECCHooksPlugin, "function")
|
|
const plugin = await active.ECCHooksPlugin({
|
|
client: { app: { log: (event) => logs.push(event.body) } },
|
|
$: () => { throw new Error("Unexpected shell execution") },
|
|
directory: process.cwd(),
|
|
worktree: process.cwd(),
|
|
})
|
|
assert.equal(typeof plugin["session.created"], "function")
|
|
await plugin["file.edited"]({ path: path.join(process.cwd(), "example.txt") })
|
|
const changed = JSON.parse(await tools.changedFiles.execute({ format: "json" }, {}))
|
|
assert.equal(changed.changed, true)
|
|
assert.deepEqual(changed.files, [{ path: "example.txt", changeType: "modified" }])
|
|
assert.ok(!logs.some((log) => log.message.includes("tracking disabled")))
|
|
}
|
|
main().catch((error) => { console.error(error); process.exit(1) })
|
|
`
|
|
const args = loader ? ["--loader", pathToFileURL(loader).href] : []
|
|
const fixture = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), "ecc-opencode-runtime-"))
|
|
try {
|
|
const home = path.join(fixture, "home")
|
|
const project = path.join(fixture, "project")
|
|
fs.mkdirSync(home)
|
|
fs.mkdirSync(project)
|
|
const result = spawnSync(process.execPath, [...args, "-e", check, runtimeRoot, extension, String(installedHome)], {
|
|
cwd: project,
|
|
encoding: "utf8",
|
|
timeout: 30000,
|
|
env: { ...process.env, HOME: home, USERPROFILE: home,
|
|
CLAUDE_CONFIG_DIR: path.join(home, ".claude"), ECC_AGENT_DATA_HOME: path.join(home, ".claude"),
|
|
XDG_CONFIG_HOME: path.join(home, ".config"), XDG_DATA_HOME: path.join(home, ".local", "share"),
|
|
OPENCODE_CONFIG_DIR: installedHome ? runtimeRoot : path.join(home, ".config", "opencode") },
|
|
})
|
|
assert.strictEqual(result.status, 0, result.error?.message || result.stderr || result.stdout)
|
|
} finally {
|
|
fs.rmSync(fixture, { recursive: true, force: true })
|
|
}
|
|
}
|
|
|
|
function runTest(name, fn) {
|
|
try {
|
|
fn()
|
|
console.log(` ✓ ${name}`)
|
|
return true
|
|
} catch (error) {
|
|
console.log(` ✗ ${name}`)
|
|
console.error(` ${error.message}`)
|
|
return false
|
|
}
|
|
}
|
|
|
|
function main() {
|
|
console.log("\n=== Testing build-opencode.js ===\n")
|
|
|
|
let passed = 0
|
|
let failed = 0
|
|
|
|
const repoRoot = path.join(__dirname, "..", "..")
|
|
const packageJson = JSON.parse(
|
|
fs.readFileSync(path.join(repoRoot, "package.json"), "utf8")
|
|
)
|
|
const buildScript = path.join(repoRoot, "scripts", "build-opencode.js")
|
|
const distEntry = path.join(repoRoot, ".opencode", "dist", "index.js")
|
|
const tests = [
|
|
["package.json exposes the OpenCode build and prepack hooks", () => {
|
|
assert.strictEqual(packageJson.scripts["build:opencode"], "node scripts/build-opencode.js")
|
|
assert.strictEqual(packageJson.scripts.prepack, "npm run build:opencode")
|
|
assert.ok(packageJson.files.includes(".opencode/"))
|
|
}],
|
|
["build script generates .opencode/dist", () => {
|
|
const result = spawnSync("node", [buildScript], {
|
|
cwd: repoRoot,
|
|
encoding: "utf8",
|
|
})
|
|
assert.strictEqual(result.status, 0, result.stderr)
|
|
assert.ok(fs.existsSync(distEntry), ".opencode/dist/index.js should exist after build")
|
|
}],
|
|
["built OpenCode bundle only imports packages declared as runtime dependencies", () => {
|
|
// OpenCode installs npm plugins without devDependencies, so any package
|
|
// the compiled bundle imports at runtime must ship as a dependency.
|
|
const runtimeDeps = new Set([
|
|
...Object.keys(packageJson.dependencies || {}),
|
|
...Object.keys(packageJson.peerDependencies || {}),
|
|
])
|
|
const distDir = path.dirname(distEntry)
|
|
const imported = new Set()
|
|
const walk = (dir) => {
|
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
const entryPath = path.join(dir, entry.name)
|
|
if (entry.isDirectory()) {
|
|
walk(entryPath)
|
|
} else if (entry.name.endsWith(".js")) {
|
|
const source = fs.readFileSync(entryPath, "utf8")
|
|
for (const match of source.matchAll(/(?:\bfrom|\bimport)\s*\(?\s*["']([^"'.][^"']*)["']/g)) {
|
|
const specifier = match[1]
|
|
if (specifier.startsWith("node:") || builtinModules.includes(specifier)) continue
|
|
const parts = specifier.split("/")
|
|
imported.add(specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0])
|
|
}
|
|
}
|
|
}
|
|
}
|
|
walk(distDir)
|
|
assert.ok(imported.size > 0, "expected the OpenCode bundle to import at least one package")
|
|
const undeclared = [...imported].filter((name) => !runtimeDeps.has(name)).sort()
|
|
assert.deepStrictEqual(undeclared, [], `undeclared runtime imports: ${undeclared.join(", ")}`)
|
|
}],
|
|
["package.json declares a resolvable OpenCode plugin entry", () => {
|
|
assert.strictEqual(packageJson.main, ".opencode/dist/index.js")
|
|
assert.ok(packageJson.exports, "package.json must declare an exports map")
|
|
assert.deepStrictEqual(packageJson.exports["."], {
|
|
types: "./.opencode/dist/index.d.ts",
|
|
import: "./.opencode/dist/index.js",
|
|
default: "./.opencode/dist/index.js",
|
|
})
|
|
}],
|
|
["installed package resolves and imports its root module by name", () => {
|
|
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "ecc-opencode-entry-"))
|
|
try {
|
|
fs.mkdirSync(path.join(tempDir, "node_modules"), { recursive: true })
|
|
fs.symlinkSync(
|
|
repoRoot,
|
|
path.join(tempDir, "node_modules", "ecc-universal"),
|
|
process.platform === "win32" ? "junction" : "dir"
|
|
)
|
|
const probe = `
|
|
const resolved = import.meta.resolve("ecc-universal")
|
|
if (!resolved.endsWith("/.opencode/dist/index.js")) {
|
|
throw new Error("unexpected entry resolution: " + resolved)
|
|
}
|
|
const mod = await import("ecc-universal")
|
|
const definition = mod.default
|
|
if (Object.keys(mod).join(",") !== "default") {
|
|
throw new Error("root module must export exactly the plugin definition")
|
|
}
|
|
if (!definition || typeof definition !== "object" || definition.id !== "ecc-hooks" ||
|
|
typeof definition.setup !== "function") {
|
|
throw new Error("root module must export the V2 plugin definition ({ id, setup })")
|
|
}
|
|
`
|
|
const probePath = path.join(tempDir, "probe.mjs")
|
|
fs.writeFileSync(probePath, probe)
|
|
const result = spawnSync(process.execPath, [probePath], {
|
|
cwd: tempDir,
|
|
encoding: "utf8",
|
|
})
|
|
assert.strictEqual(result.status, 0, result.stderr)
|
|
} finally {
|
|
fs.rmSync(tempDir, { recursive: true, force: true })
|
|
}
|
|
}],
|
|
["OpenCode TypeScript sources resolve their relative imports in place", () => {
|
|
const opencodeDir = path.join(repoRoot, ".opencode")
|
|
const sourceFiles = []
|
|
const walk = (dir) => {
|
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
const entryPath = path.join(dir, entry.name)
|
|
if (entry.isDirectory()) {
|
|
if (entry.name !== "node_modules" && entry.name !== "dist") walk(entryPath)
|
|
} else if (entry.name.endsWith(".ts")) {
|
|
sourceFiles.push(entryPath)
|
|
}
|
|
}
|
|
}
|
|
walk(opencodeDir)
|
|
assert.ok(sourceFiles.length > 0, "expected OpenCode TypeScript sources")
|
|
const unresolved = []
|
|
for (const sourceFile of sourceFiles) {
|
|
const source = fs.readFileSync(sourceFile, "utf8")
|
|
for (const match of source.matchAll(/(?:from|import)\s*\(?\s*"(\.[^"]+)"/g)) {
|
|
const target = path.resolve(path.dirname(sourceFile), match[1])
|
|
if (!fs.existsSync(target)) {
|
|
unresolved.push(`${path.relative(repoRoot, sourceFile)} -> ${match[1]}`)
|
|
}
|
|
}
|
|
}
|
|
assert.deepStrictEqual(unresolved, [])
|
|
}],
|
|
["built OpenCode entry exports the V2 definition and the factory hook map", () => {
|
|
const check = `
|
|
const assert = require("assert")
|
|
const path = require("path")
|
|
const { pathToFileURL } = require("url")
|
|
|
|
async function main() {
|
|
let mod
|
|
try {
|
|
mod = await import(pathToFileURL(process.argv[1]).href)
|
|
} catch (error) {
|
|
console.error(error)
|
|
process.exit(1)
|
|
}
|
|
assert.deepStrictEqual(Object.keys(mod).sort(), ["default"])
|
|
// OpenCode 2.x requires the default export to be the plugin
|
|
// definition object; the V1 factory stays as a named export of the
|
|
// hooks module for legacy discovery and the behavioral test suite.
|
|
assert.ok(mod.default && typeof mod.default === "object", "entry default must be the plugin definition")
|
|
assert.strictEqual(mod.default.id, "ecc-hooks")
|
|
assert.strictEqual(typeof mod.default.setup, "function")
|
|
|
|
const hooksMod = await import(pathToFileURL(
|
|
path.join(path.dirname(process.argv[1]), "plugins", "ecc-hooks.js")
|
|
).href)
|
|
assert.strictEqual(hooksMod.default, mod.default, "entry and hooks module must share one definition")
|
|
assert.strictEqual(typeof hooksMod.ECCHooksPlugin, "function", "hooks module must export the V1 factory")
|
|
|
|
let shellCalls = 0
|
|
const plugin = await hooksMod.ECCHooksPlugin({
|
|
client: { app: { log: () => {} } },
|
|
$: async () => {
|
|
shellCalls += 1
|
|
throw new Error("$ must not be called during plugin init")
|
|
},
|
|
directory: process.cwd(),
|
|
worktree: process.cwd(),
|
|
})
|
|
assert.strictEqual(shellCalls, 0, "$ must not be called during plugin init")
|
|
assert.ok(plugin && typeof plugin === "object", "factory must return a plugin record")
|
|
const expectedHooks = [
|
|
"file.edited",
|
|
"tool.execute.after",
|
|
"tool.execute.before",
|
|
"session.created",
|
|
"session.idle",
|
|
"session.deleted",
|
|
"file.watcher.updated",
|
|
"todo.updated",
|
|
"shell.env",
|
|
"experimental.session.compacting",
|
|
"permission.ask",
|
|
]
|
|
for (const hook of expectedHooks) {
|
|
assert.strictEqual(typeof plugin[hook], "function", "missing hook: " + hook)
|
|
}
|
|
assert.ok(plugin.tool && typeof plugin.tool === "object", "plugin record must expose a tool object")
|
|
assert.deepStrictEqual(
|
|
Object.keys(plugin.tool).sort(),
|
|
["changed-files", "dependency-analyzer"],
|
|
"plugin.tool must expose exactly the custom tools"
|
|
)
|
|
for (const toolName of ["changed-files", "dependency-analyzer"]) {
|
|
const toolDefinition = plugin.tool[toolName]
|
|
assert.ok(toolDefinition && typeof toolDefinition === "object", "missing tool: " + toolName)
|
|
assert.strictEqual(typeof toolDefinition.description, "string", toolName + " must declare a description")
|
|
assert.ok(toolDefinition.args && typeof toolDefinition.args === "object", toolName + " must declare args")
|
|
assert.strictEqual(typeof toolDefinition.execute, "function", toolName + " must declare an execute function")
|
|
}
|
|
}
|
|
|
|
main().catch((error) => {
|
|
console.error(error)
|
|
process.exit(1)
|
|
})
|
|
`
|
|
const result = spawnSync(process.execPath, ["-e", check, distEntry], {
|
|
cwd: repoRoot,
|
|
encoding: "utf8",
|
|
})
|
|
assert.strictEqual(result.status, 0, result.stderr)
|
|
}],
|
|
["ecc-universal package ./plugins export resolves to the live hooks entry", () => {
|
|
const pkgDir = path.join(repoRoot, ".opencode")
|
|
const pkg = JSON.parse(fs.readFileSync(path.join(pkgDir, "package.json"), "utf8"))
|
|
assert.strictEqual(pkg.name, "ecc-universal")
|
|
const pluginExport = pkg.exports && pkg.exports["./plugins"]
|
|
assert.ok(pluginExport, "ecc-universal must declare an ./plugins export")
|
|
for (const key of ["types", "import"]) {
|
|
const rel = pluginExport[key]
|
|
assert.ok(rel, `./plugins export must declare ${key}`)
|
|
assert.ok(
|
|
fs.existsSync(path.resolve(pkgDir, rel)),
|
|
`./plugins ${key} target must exist after the build: ${rel}`,
|
|
)
|
|
}
|
|
// The export must point at the LIVE plugin, not the inert barrel: same
|
|
// default definition, V1 factory, and a distinct-id barrel behind it.
|
|
const check = `
|
|
const assert = require("assert")
|
|
const path = require("path")
|
|
const { pathToFileURL } = require("url")
|
|
async function main() {
|
|
const pkgDir = process.argv[1]
|
|
const pkg = require(path.join(pkgDir, "package.json"))
|
|
const live = await import(pathToFileURL(path.resolve(pkgDir, pkg.exports["./plugins"].import)).href)
|
|
assert.strictEqual(live.default.id, "ecc-hooks", "./plugins must expose the live plugin definition")
|
|
assert.strictEqual(typeof live.default.setup, "function")
|
|
assert.strictEqual(typeof live.ECCHooksPlugin, "function", "./plugins must expose the V1 factory")
|
|
const barrel = await import(pathToFileURL(
|
|
path.join(pkgDir, "dist", "plugins", "index.js")
|
|
).href)
|
|
assert.strictEqual(barrel.default.id, "ecc-hooks-entry", "compiled barrel must keep the distinct id")
|
|
assert.notStrictEqual(barrel.default, live.default, "barrel must not re-export the live definition")
|
|
}
|
|
main().catch((error) => { console.error(error); process.exit(1) })
|
|
`
|
|
const result = spawnSync(process.execPath, ["-e", check, pkgDir], {
|
|
cwd: repoRoot,
|
|
encoding: "utf8",
|
|
})
|
|
assert.strictEqual(result.status, 0, result.stderr)
|
|
}],
|
|
["compiled barrels load and share the lazy changed-files store", () => {
|
|
checkRuntime(path.dirname(distEntry), ".js")
|
|
}],
|
|
["full home install loads TypeScript barrels and the lazy changed-files store", () => {
|
|
// Keep the fixture beneath the repo so the installed tools can resolve
|
|
// the real SDK dependency without installing packages in the user's home.
|
|
const fixture = fs.mkdtempSync(path.join(repoRoot, "tests", ".opencode-home-"))
|
|
try {
|
|
const homeDir = path.join(fixture, "home")
|
|
const projectRoot = path.join(fixture, "project")
|
|
fs.mkdirSync(homeDir)
|
|
fs.mkdirSync(projectRoot)
|
|
const plan = withHookConsent(createManifestInstallPlan({
|
|
sourceRoot: repoRoot,
|
|
homeDir,
|
|
projectRoot,
|
|
env: {},
|
|
target: "opencode",
|
|
profileId: "full",
|
|
}), "enabled")
|
|
applyInstallPlan(plan)
|
|
const config = JSON.parse(fs.readFileSync(path.join(plan.targetRoot, "opencode.json"), "utf8"))
|
|
assert.deepStrictEqual(config.skills.paths, [path.join(plan.targetRoot, "skills")])
|
|
assert.ok(fs.existsSync(path.join(config.skills.paths[0], "tdd-workflow", "SKILL.md")))
|
|
assert.ok(!fs.existsSync(path.join(plan.targetRoot, "tools", "run-tests.js")))
|
|
checkRuntime(
|
|
plan.targetRoot,
|
|
".ts",
|
|
path.join(repoRoot, "tests", "fixtures", "opencode-ts-loader.mjs"),
|
|
true,
|
|
)
|
|
} finally {
|
|
fs.rmSync(fixture, { recursive: true, force: true })
|
|
}
|
|
}],
|
|
["npm pack includes the compiled OpenCode dist payload", () => {
|
|
fs.rmSync(path.dirname(distEntry), { recursive: true, force: true })
|
|
const result = spawnSync("npm", ["pack", "--dry-run", "--json", "--ignore-scripts=false"], {
|
|
cwd: repoRoot,
|
|
encoding: "utf8",
|
|
shell: process.platform === "win32",
|
|
})
|
|
assert.strictEqual(result.status, 0, result.error?.message || result.stderr)
|
|
|
|
const packOutput = JSON.parse(result.stdout)
|
|
const packEntry = getNpmPackEntry(packOutput, packageJson.name)
|
|
const packagedPaths = new Set(packEntry?.files?.map((file) => file.path) ?? [])
|
|
|
|
assert.ok(
|
|
packagedPaths.has(".opencode/dist/index.js"),
|
|
"npm pack should include .opencode/dist/index.js"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".opencode/dist/plugins/index.js"),
|
|
"npm pack should include compiled OpenCode plugin output"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".opencode/dist/tools/index.js"),
|
|
"npm pack should include compiled OpenCode tool output"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".claude-plugin/marketplace.json"),
|
|
"npm pack should include .claude-plugin/marketplace.json"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".claude-plugin/plugin.json"),
|
|
"npm pack should include .claude-plugin/plugin.json"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".codex-plugin/plugin.json"),
|
|
"npm pack should include .codex-plugin/plugin.json"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".grok-plugin/plugin.json"),
|
|
"npm pack should include .grok-plugin/plugin.json"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".grok-plugin/marketplace.json"),
|
|
"npm pack should include .grok-plugin/marketplace.json"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".agents/plugins/marketplace.json"),
|
|
"npm pack should include .agents/plugins/marketplace.json"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".opencode/package.json"),
|
|
"npm pack should include .opencode/package.json"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has(".opencode/package-lock.json"),
|
|
"npm pack should include .opencode/package-lock.json"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has("agent.yaml"),
|
|
"npm pack should include agent.yaml"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has("AGENTS.md"),
|
|
"npm pack should include AGENTS.md"
|
|
)
|
|
assert.ok(
|
|
packagedPaths.has("VERSION"),
|
|
"npm pack should include VERSION"
|
|
)
|
|
}],
|
|
]
|
|
|
|
for (const [name, fn] of tests) {
|
|
if (runTest(name, fn)) {
|
|
passed += 1
|
|
} else {
|
|
failed += 1
|
|
}
|
|
}
|
|
|
|
console.log(`\nPassed: ${passed}`)
|
|
console.log(`Failed: ${failed}`)
|
|
process.exit(failed > 0 ? 1 : 0)
|
|
}
|
|
|
|
main()
|