mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-17 05:22:17 +00:00
fix: close metadata races and finish reviewed hook boundaries
This commit is contained in:
10 files changed
+1313
-1046
No files matched your search
+10
-903
@@ -35,10 +35,12 @@
|
||||
* but is never invoked (asserted by tests/opencode-plugin-hooks.test.js).
|
||||
*/
|
||||
|
||||
import * as fs from "fs"
|
||||
import * as path from "path"
|
||||
import { spawn } from "child_process"
|
||||
import { fileURLToPath, pathToFileURL } from "url"
|
||||
import { fileURLToPath } from "url"
|
||||
|
||||
import { createEccRuntime } from "./lib/ecc-runtime.ts"
|
||||
import { ECC_ROOT_PROBES, findEccRootDir, getECCVersion, loadToolModule } from "./lib/ecc-runtime-support.ts"
|
||||
import type { LooseRecord, ToolArgs, ToolInput } from "./lib/ecc-runtime-support.ts"
|
||||
|
||||
/**
|
||||
* Directory of this module.
|
||||
@@ -61,203 +63,6 @@ function resolvePluginDir(): string {
|
||||
|
||||
const PLUGIN_DIR = resolvePluginDir()
|
||||
|
||||
/** Loose aliases: the runtime ctx/event shapes come from the server, not the pinned SDK. */
|
||||
type LooseRecord = Record<string, any>
|
||||
|
||||
interface ToolArgs {
|
||||
filePath?: string
|
||||
file_path?: string
|
||||
path?: string
|
||||
command?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
interface ToolInput {
|
||||
tool: string
|
||||
callID?: string
|
||||
args?: ToolArgs
|
||||
}
|
||||
|
||||
interface PermissionEvent {
|
||||
tool: string
|
||||
args: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Artifacts that identify an ECC root, one per capability this plugin needs.
|
||||
*
|
||||
* These are required runtime files, never optional content: `skills/` belongs to
|
||||
* the optional `workflow-quality` module, so probing for a skill rejected
|
||||
* supported modular installs (e.g. `platform-configs` + `hooks-runtime` without
|
||||
* `workflow-quality`) that still ship both the plugin and the tracker — silently
|
||||
* disabling skill telemetry and the shell root export for those users.
|
||||
*
|
||||
* Each probe is the exact artifact the caller is about to use, so detection is
|
||||
* layout detection rather than an authenticity control: a directory only
|
||||
* qualifies because it contains what we are going to read.
|
||||
*/
|
||||
const ECC_ROOT_PROBES = {
|
||||
// scripts/lib/utils.js is the shared library every scripts/ module requires.
|
||||
root: [path.join("scripts", "lib", "utils.js")],
|
||||
// What the skill-run telemetry hook imports at runtime.
|
||||
skillTracker: [path.join("scripts", "hooks", "skill-run-tracker.js")],
|
||||
// What the resolver embedded in commands requires once they read
|
||||
// CLAUDE_PLUGIN_ROOT, and the version lookup for shell.env.
|
||||
resolver: [path.join("scripts", "lib", "resolve-ecc-root.js")],
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Walk upwards from `startDir` looking for an ancestor that contains every
|
||||
* relative path in `probes`.
|
||||
*
|
||||
* The plugin ships in three layouts — `<root>/plugins` (installed), `<root>/dist/plugins`
|
||||
* (compiled) and `<repo>/.opencode/plugins` (repo checkout) — so the number of
|
||||
* levels back to the root is not fixed. Probing beats a hardcoded `..`: a wrong
|
||||
* root would make every command resolve against a directory that has no scripts.
|
||||
*
|
||||
* The walk is bounded to 5 levels so it cannot wander into unrelated ancestors.
|
||||
*
|
||||
* Returns null when no ancestor qualifies, so callers can leave the capability
|
||||
* disabled instead of advertising a root that does not hold the artifact.
|
||||
*/
|
||||
function findEccRootDir(startDir: string, probes: readonly string[]): string | null {
|
||||
let current = startDir
|
||||
for (let depth = 0; depth < 5; depth += 1) {
|
||||
if (probes.every((probe) => fs.existsSync(path.join(current, probe)))) {
|
||||
return current
|
||||
}
|
||||
const parent = path.dirname(current)
|
||||
if (parent === current) break
|
||||
current = parent
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the ECC version from package.json.
|
||||
*
|
||||
* Candidates are tried in order — the resolved ECC root first, then the two
|
||||
* plausible parent depths of the plugin — because the layout differs between an
|
||||
* installed root (`<root>/plugins`), the compiled bundle (`<root>/dist/plugins`)
|
||||
* and a repo checkout (`<repo>/.opencode/plugins`). Falls back to a default if
|
||||
* no package.json can be read.
|
||||
*/
|
||||
function getECCVersion(eccRootDir?: string | null): string {
|
||||
const candidates = [
|
||||
eccRootDir,
|
||||
path.resolve(PLUGIN_DIR, ".."),
|
||||
path.resolve(PLUGIN_DIR, "..", ".."),
|
||||
]
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) continue
|
||||
try {
|
||||
const packageJson = JSON.parse(fs.readFileSync(path.join(candidate, "package.json"), "utf-8"))
|
||||
if (typeof packageJson.version === "string" && packageJson.version) {
|
||||
return packageJson.version
|
||||
}
|
||||
} catch {
|
||||
// Try the next candidate.
|
||||
}
|
||||
}
|
||||
|
||||
return "2.0.0"
|
||||
}
|
||||
|
||||
/**
|
||||
* On Windows, npx/npm/pnpm/yarn/bun are `.cmd` shims that CreateProcess
|
||||
* cannot launch directly from a bare command name. Node's own guidance for
|
||||
* this case is to spawn the exact `.cmd` file through `cmd.exe /d /s /c`
|
||||
* with `windowsVerbatimArguments` and quoted args — NOT `shell: true`,
|
||||
* which concatenates the command and arguments into one string that shell
|
||||
* metacharacters (&, |, ;) in any argument (e.g. a file path) could inject
|
||||
* into. The command is fixed here (never user input); only known package
|
||||
* managers get the cmd-shim treatment, and their arguments stay separated.
|
||||
*/
|
||||
function spawnCommand(
|
||||
command: string,
|
||||
args: string[],
|
||||
): { file: string; spawnArgs: string[]; verbatim: boolean } {
|
||||
if (
|
||||
process.platform === "win32" &&
|
||||
/^(npx|npm|pnpm|yarn|bun)(\.cmd)?$/i.test(command)
|
||||
) {
|
||||
// R2-2: cmd.exe expands %VAR% and honours embedded quotes even inside
|
||||
// "double quotes", so backslash-escaping a quote here is not safe. Reject
|
||||
// any argument carrying a quote, percent sign, or line break outright
|
||||
// (line breaks would also terminate the /c command string). Legitimate
|
||||
// package-manager invocations never need these characters; callers already
|
||||
// surface the rejection through run()'s rejection path.
|
||||
const unsafe = args.find((value) => /["%\r\n]/.test(value))
|
||||
if (unsafe !== undefined) {
|
||||
throw new Error(
|
||||
`Refusing to launch package-manager shim with unsafe argument: ${JSON.stringify(unsafe)}`,
|
||||
)
|
||||
}
|
||||
const shim = `${command.replace(/\.cmd$/i, "")}.cmd`
|
||||
const quote = (value: string) => `"${value}"`
|
||||
// Canonical `/s` form: wrap the whole command string in one outer pair of
|
||||
// quotes. cmd strips exactly that outer pair and executes the remainder
|
||||
// verbatim, so the quoted shim path resolves instead of being re-split.
|
||||
const inner = [shim, ...args].map(quote).join(" ")
|
||||
return {
|
||||
file: process.env.ComSpec || "cmd.exe",
|
||||
spawnArgs: ["/d", "/s", "/c", `"${inner}"`],
|
||||
verbatim: true,
|
||||
}
|
||||
}
|
||||
return { file: command, spawnArgs: args, verbatim: false }
|
||||
}
|
||||
|
||||
/** Run a command, resolving with its output regardless of exit code. */
|
||||
function run(
|
||||
command: string,
|
||||
args: string[],
|
||||
options: { cwd?: string; detached?: boolean } = {},
|
||||
): Promise<{ code: number; stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const resolved = spawnCommand(command, args)
|
||||
const child = spawn(resolved.file, resolved.spawnArgs, {
|
||||
cwd: options.cwd,
|
||||
shell: false,
|
||||
windowsVerbatimArguments: resolved.verbatim,
|
||||
windowsHide: true,
|
||||
detached: options.detached === true,
|
||||
stdio: options.detached === true ? "ignore" : ["ignore", "pipe", "pipe"],
|
||||
})
|
||||
// T03: the error listener must exist before any early return below, so a
|
||||
// missing binary (ENOENT) rejects this promise instead of surfacing as an
|
||||
// unhandled 'error' event that can crash the host process.
|
||||
let settled = false
|
||||
child.on("error", (error) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
reject(error)
|
||||
})
|
||||
if (options.detached === true) {
|
||||
child.unref()
|
||||
settled = true
|
||||
resolve({ code: 0, stdout: "", stderr: "" })
|
||||
return
|
||||
}
|
||||
let stdout = ""
|
||||
let stderr = ""
|
||||
child.stdout?.on("data", (chunk) => (stdout += String(chunk)))
|
||||
child.stderr?.on("data", (chunk) => (stderr += String(chunk)))
|
||||
child.on("close", (code) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
resolve({ code: code ?? 1, stdout, stderr })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** Count console.log occurrences in a file with fs+regex (cross-platform grep replacement). */
|
||||
async function countConsoleLogs(filePath: string): Promise<number> {
|
||||
const content = await fs.promises.readFile(filePath, "utf-8")
|
||||
return (content.match(/console\.log\s*\(/g) ?? []).length
|
||||
}
|
||||
|
||||
// A location loads plugins from both the global config dir and its own
|
||||
// .opencode/plugins; OpenCode 2.x also treats plugins/index.ts and the
|
||||
// directory entrypoint as separate load entries. The directory config now
|
||||
@@ -272,704 +77,6 @@ const registeredDirectories: Set<string> =
|
||||
((globalThis as any)[GUARD_KEY] as Set<string> | undefined) ??
|
||||
((globalThis as any)[GUARD_KEY] = new Set<string>())
|
||||
|
||||
type HookProfile = "minimal" | "standard" | "strict"
|
||||
|
||||
/**
|
||||
* The custom tool definitions V1 exposed through `plugin.tool` and V2 exposes
|
||||
* through ctx.tool.transform. Loaded lazily and cached per name: this file is
|
||||
* OpenCode's startup entry point, and a static top-level import of a missing
|
||||
* tools/ module used to crash the whole session before any hook could load
|
||||
* (#2530). A failed load degrades to an execute-time error message instead.
|
||||
*/
|
||||
const toolModuleCache = new Map<string, Promise<any>>()
|
||||
|
||||
/**
|
||||
* Resolve a tool module by URL rather than by a literal specifier: tsc only
|
||||
* rewrites `.ts` extensions in statically-analyzable specifiers, and the
|
||||
* compiled layout ships `.js` while a repo/source install ships `.ts`.
|
||||
*/
|
||||
async function loadToolModule(name: string): Promise<{ description: string; args: any; execute: (args: any, context: any) => Promise<unknown> }> {
|
||||
let pending = toolModuleCache.get(name)
|
||||
if (!pending) {
|
||||
const toolsDir = path.resolve(PLUGIN_DIR, "..", "tools")
|
||||
const candidates = [path.join(toolsDir, `${name}.js`), path.join(toolsDir, `${name}.ts`)]
|
||||
pending = (async () => {
|
||||
let lastError: unknown
|
||||
for (const candidate of candidates) {
|
||||
if (!fs.existsSync(candidate)) continue
|
||||
try {
|
||||
return await import(pathToFileURL(candidate).href)
|
||||
} catch (error) {
|
||||
lastError = error
|
||||
}
|
||||
}
|
||||
throw lastError ?? new Error(`neither ${name}.js nor ${name}.ts found under ${toolsDir}`)
|
||||
})()
|
||||
.then((mod: any) => {
|
||||
const definition = mod?.default ?? mod
|
||||
if (!definition || typeof definition.execute !== "function") {
|
||||
throw new Error(`${name}: module exposes no tool definition with an execute()`)
|
||||
}
|
||||
return definition
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
toolModuleCache.delete(name)
|
||||
throw new Error(
|
||||
`${name} tool: could not load ECC tool module. Run \`ecc repair --target opencode\` to restore the missing files. (${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
})`,
|
||||
)
|
||||
})
|
||||
toolModuleCache.set(name, pending)
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
/** The shared runtime: every hook body lives here exactly once. */
|
||||
interface EccRuntime {
|
||||
/** V1-shaped hook map (also used by the V2 adapters below). */
|
||||
hooks: Record<string, any>
|
||||
/** V1-shaped custom tool record. */
|
||||
tool: Record<string, unknown>
|
||||
/** ECC context block preserved through compaction (V2 registration uses it). */
|
||||
buildCompactionContext: () => string
|
||||
/** The project directory this runtime was built for. */
|
||||
worktreePath: string
|
||||
}
|
||||
|
||||
async function createEccRuntime(input: {
|
||||
client?: { app?: { log?: (event: { body: LooseRecord }) => unknown } }
|
||||
$?: unknown
|
||||
directory?: string
|
||||
worktree?: string
|
||||
}): Promise<EccRuntime> {
|
||||
const { client } = input
|
||||
const worktreePath = input.worktree || input.directory || process.cwd()
|
||||
|
||||
const editedFiles = new Set<string>()
|
||||
const pendingToolChanges = new Map<string, { path: string; type: "added" | "modified" }>()
|
||||
let writeCounter = 0
|
||||
|
||||
function resolvePath(p: string): string {
|
||||
if (path.isAbsolute(p)) return p
|
||||
return path.join(worktreePath, p)
|
||||
}
|
||||
|
||||
function hasProjectFile(relativePath: string): boolean {
|
||||
try {
|
||||
return fs.statSync(resolvePath(relativePath)).isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function getFilePath(args: ToolArgs | undefined): string | null {
|
||||
if (!args) return null
|
||||
const p = (args.filePath ?? args.file_path ?? args.path) as string | undefined
|
||||
return typeof p === "string" && p.trim() ? p : null
|
||||
}
|
||||
|
||||
// V1 logged through the SDK client; V2 has no client.app.log, so the console
|
||||
// fallback writes into the server log, which is where those messages ended
|
||||
// up anyway.
|
||||
const log = (level: "debug" | "info" | "warn" | "error", message: string) => {
|
||||
if (typeof client?.app?.log === "function") {
|
||||
return client.app.log({ body: { service: "ecc", level, message } })
|
||||
}
|
||||
try {
|
||||
const line = `[ecc] ${message}`
|
||||
if (level === "error") console.error(line)
|
||||
else if (level === "warn") console.warn(line)
|
||||
else if (level === "debug") console.debug(line)
|
||||
else console.info(line)
|
||||
} catch {
|
||||
// Logging must never break a hook.
|
||||
}
|
||||
}
|
||||
|
||||
// Loaded lazily (instead of via a top-level import) so that a missing or
|
||||
// partially-installed `~/.opencode/plugins/lib` directory (e.g. an
|
||||
// interrupted or partial ECC install on Termux/Android) only disables
|
||||
// changed-files tracking, rather than throwing during module evaluation.
|
||||
// This plugin is OpenCode's startup entry point, so a static import
|
||||
// failure here previously crashed the whole plugin -- and with it, the
|
||||
// entire OpenCode session -- before any hooks could load (see #2530).
|
||||
// The relative ".ts" specifier is rewritten to ".js" by tsc in the compiled
|
||||
// layout and resolved natively by OpenCode's TS loader in a source layout.
|
||||
let changedFilesStore: typeof import("./lib/changed-files-store.ts") | undefined
|
||||
try {
|
||||
const store = await import("./lib/changed-files-store.ts")
|
||||
store.initStore?.(worktreePath)
|
||||
changedFilesStore = store
|
||||
} catch {
|
||||
// Best-effort diagnostic only: deferred via .then() (rather than
|
||||
// Promise.resolve(log(...))) so that even a *synchronous* throw inside
|
||||
// log() -- not just an async rejection -- is caught here instead of
|
||||
// escaping this catch block. The raw loader error is intentionally not
|
||||
// included in the message since it can contain absolute filesystem
|
||||
// paths; this whole block exists to guarantee startup resilience even
|
||||
// when things go wrong.
|
||||
Promise.resolve()
|
||||
.then(() =>
|
||||
log(
|
||||
"warn",
|
||||
"[ECC] changed-files tracking disabled: could not load the changed-files store. " +
|
||||
"Run `ecc repair --target opencode` to restore the missing files. Other ECC hooks are unaffected.",
|
||||
),
|
||||
)
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
// Claude Code routes post:skill:track through
|
||||
// scripts/hooks/posttooluse-dispatcher.js, which OpenCode never invokes.
|
||||
// Without a caller here, nothing ever writes skill-runs.jsonl and
|
||||
// `skills-health.js --dashboard` has no data to report on any skill (#2463).
|
||||
//
|
||||
// The tracker module is reused rather than reimplemented so its identifier
|
||||
// validation, length bounds and "never persist prompt text" guarantees stay
|
||||
// the ones that were written and audited for the Claude Code path.
|
||||
//
|
||||
// Loaded lazily, for the same reason as the store above. A runtime file URL
|
||||
// also keeps tsc from resolving a relative specifier that exists in no
|
||||
// compiled layout.
|
||||
let recordSkillRun: ((payload: unknown) => void) | undefined
|
||||
// Detection is scoped to the tracker itself, so a modular install that omits
|
||||
// optional content still gets telemetry.
|
||||
const trackerRoot = findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.skillTracker)
|
||||
// The root advertised to commands is a different question: those commands
|
||||
// require the resolver, so a root without it would break them again.
|
||||
const eccRoot =
|
||||
findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.resolver) ?? findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.root)
|
||||
try {
|
||||
const trackerPath = trackerRoot ? path.join(trackerRoot, "scripts", "hooks", "skill-run-tracker.js") : null
|
||||
if (!trackerPath || !fs.existsSync(trackerPath)) {
|
||||
throw new Error("skill-run-tracker.js not found")
|
||||
}
|
||||
// CJS module loaded from ESM: run() is on the namespace in Node/Bun, but a
|
||||
// transpiled default export must stay supported.
|
||||
const loaded = (await import(pathToFileURL(trackerPath).href)) as {
|
||||
run?: (payload: unknown) => void
|
||||
default?: { run?: (payload: unknown) => void }
|
||||
}
|
||||
const entry = typeof loaded.run === "function" ? loaded : loaded.default
|
||||
if (!entry || typeof entry.run !== "function") {
|
||||
throw new Error("skill-run-tracker.js exposes no run()")
|
||||
}
|
||||
recordSkillRun = entry.run
|
||||
} catch {
|
||||
// Same deferred-log rationale as the store above: guarantee that a
|
||||
// telemetry failure can never escape this catch and abort startup.
|
||||
Promise.resolve()
|
||||
.then(() =>
|
||||
log(
|
||||
"warn",
|
||||
"[ECC] skill-run telemetry disabled: could not load scripts/hooks/skill-run-tracker.js. " +
|
||||
"Run `ecc repair --target opencode` to restore the missing files. Other ECC hooks are unaffected.",
|
||||
),
|
||||
)
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
const normalizeProfile = (value: string | undefined): HookProfile => {
|
||||
if (value === "minimal" || value === "strict") return value
|
||||
return "standard"
|
||||
}
|
||||
|
||||
const currentProfile = normalizeProfile(process.env.ECC_HOOK_PROFILE)
|
||||
const disabledHooks = new Set(
|
||||
(process.env.ECC_DISABLED_HOOKS || "")
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean),
|
||||
)
|
||||
|
||||
const profileOrder: Record<HookProfile, number> = { minimal: 0, standard: 1, strict: 2 }
|
||||
|
||||
const profileAllowed = (required: HookProfile | HookProfile[]): boolean => {
|
||||
if (Array.isArray(required)) {
|
||||
return required.some((entry) => profileOrder[currentProfile] >= profileOrder[entry])
|
||||
}
|
||||
return profileOrder[currentProfile] >= profileOrder[required]
|
||||
}
|
||||
|
||||
const hookEnabled = (
|
||||
hookId: string,
|
||||
requiredProfile: HookProfile | HookProfile[] = "standard",
|
||||
): boolean => {
|
||||
if (disabledHooks.has(hookId)) return false
|
||||
return profileAllowed(requiredProfile)
|
||||
}
|
||||
|
||||
/**
|
||||
* Prettier auto-format + console.log warning + change tracking.
|
||||
* (Equivalent to Claude Code PostToolUse hook for prettier.)
|
||||
*/
|
||||
const onFileEdited = async (event: { path: string }) => {
|
||||
try {
|
||||
editedFiles.add(event.path)
|
||||
changedFilesStore?.recordChange?.(event.path, "modified")
|
||||
|
||||
// Auto-format JS/TS files (strict profile only: it shells out).
|
||||
if (hookEnabled("post:edit:format", ["strict"]) && /\.(ts|tsx|js|jsx)$/.test(event.path)) {
|
||||
try {
|
||||
const result = await run("npx", ["prettier", "--write", event.path], { cwd: worktreePath })
|
||||
// T11: a non-zero exit is a failure, not a success. Only log
|
||||
// "Formatted" when prettier actually ran and wrote the file.
|
||||
if (result.code === 0) {
|
||||
log("info", `[ECC] Formatted: ${event.path}`)
|
||||
} else {
|
||||
const detail = (result.stderr || result.stdout || "").trim().slice(0, 200)
|
||||
log("warn", `[ECC] Prettier failed for ${event.path} (exit ${result.code})${detail ? `: ${detail}` : ""}`)
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
// Prettier could not be spawned at all - log but continue
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] Prettier formatting failed for ${event.path}: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
// Console.log warning check (fs+regex: grep is not available on Windows).
|
||||
if (hookEnabled("post:edit:console-warn", ["standard", "strict"]) && /\.(ts|tsx|js|jsx)$/.test(event.path)) {
|
||||
const count = await countConsoleLogs(resolvePath(event.path)).catch(() => 0)
|
||||
if (count > 0) {
|
||||
log(
|
||||
"warn",
|
||||
`[ECC] console.log found in ${event.path} (${count} occurrence${count > 1 ? "s" : ""})`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] file.edited hook failed: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Advisory pre-tool callback: change bookkeeping, git-push/tmux reminders,
|
||||
* and doc-file warnings. This does not invoke canonical ECC Bash guards.
|
||||
*/
|
||||
const onToolBefore = async (input: ToolInput) => {
|
||||
try {
|
||||
if (input.tool === "write") {
|
||||
const filePath = getFilePath(input.args)
|
||||
if (filePath) {
|
||||
const absPath = resolvePath(filePath)
|
||||
let type: "added" | "modified" = "modified"
|
||||
try {
|
||||
type = fs.existsSync(absPath) ? "modified" : "added"
|
||||
} catch {
|
||||
type = "modified"
|
||||
}
|
||||
const key = input.callID ?? `write-${++writeCounter}-${filePath}`
|
||||
pendingToolChanges.set(key, { path: filePath, type })
|
||||
}
|
||||
}
|
||||
|
||||
// Git push review reminder
|
||||
if (hookEnabled("pre:bash:git-push-reminder", "strict") && input.tool === "bash") {
|
||||
const cmd = String(input.args?.command ?? input.args ?? "")
|
||||
if (cmd.includes("git push")) {
|
||||
log("info", "[ECC] Remember to review changes before pushing: git diff origin/main...HEAD")
|
||||
}
|
||||
}
|
||||
|
||||
// Warn about potentially unnecessary documentation files
|
||||
if (hookEnabled("pre:write:doc-file-warning", ["standard", "strict"]) && input.tool === "write") {
|
||||
const filePath = getFilePath(input.args)
|
||||
if (
|
||||
filePath &&
|
||||
/\.(md|txt)$/i.test(filePath) &&
|
||||
!filePath.includes("README") &&
|
||||
!filePath.includes("CHANGELOG") &&
|
||||
!filePath.includes("LICENSE") &&
|
||||
!filePath.includes("CONTRIBUTING")
|
||||
) {
|
||||
log("warn", `[ECC] Creating ${filePath} - consider if this documentation is necessary`)
|
||||
}
|
||||
}
|
||||
|
||||
// Long-running command reminder
|
||||
if (hookEnabled("pre:bash:tmux-reminder", "strict") && input.tool === "bash") {
|
||||
const cmd = String(input.args?.command ?? input.args ?? "")
|
||||
if (
|
||||
cmd.match(/^(npm|pnpm|yarn|bun)\s+(install|build|test|run)/) ||
|
||||
cmd.match(/^cargo\s+(build|test|run)/) ||
|
||||
cmd.match(/^go\s+(build|test|run)/)
|
||||
) {
|
||||
log("info", "[ECC] Long-running command detected - consider using background execution")
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] tool.execute.before hook failed: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Post-tool: change recording, typecheck, PR log, skill telemetry.
|
||||
* (Equivalent to Claude Code PostToolUse hook for tsc.)
|
||||
*/
|
||||
const onToolAfter = async (input: ToolInput, output: unknown) => {
|
||||
try {
|
||||
const filePath = getFilePath(input.args)
|
||||
if (input.tool === "edit" && filePath) {
|
||||
changedFilesStore?.recordChange?.(filePath, "modified")
|
||||
}
|
||||
if (input.tool === "write" && filePath) {
|
||||
const key = input.callID ?? `write-${++writeCounter}-${filePath}`
|
||||
const pending = pendingToolChanges.get(key)
|
||||
if (pending) {
|
||||
changedFilesStore?.recordChange?.(pending.path, pending.type)
|
||||
pendingToolChanges.delete(key)
|
||||
} else {
|
||||
changedFilesStore?.recordChange?.(filePath, "modified")
|
||||
}
|
||||
}
|
||||
|
||||
// Check if a TypeScript file was edited
|
||||
if (
|
||||
hookEnabled("post:edit:typecheck", ["strict"]) &&
|
||||
input.tool === "edit" &&
|
||||
typeof input.args?.filePath === "string" &&
|
||||
/\.tsx?$/.test(input.args.filePath)
|
||||
) {
|
||||
const result = await run("npx", ["tsc", "--noEmit"], { cwd: worktreePath }).catch(() => null)
|
||||
if (result && result.code === 0) {
|
||||
log("info", "[ECC] TypeScript check passed")
|
||||
} else if (result) {
|
||||
log("warn", "[ECC] TypeScript errors detected:")
|
||||
const out = (result.stdout || result.stderr || "").split("\n").slice(0, 5)
|
||||
out.forEach((line) => line.trim() && log("warn", ` ${line}`))
|
||||
}
|
||||
}
|
||||
|
||||
// PR creation logging
|
||||
if (
|
||||
hookEnabled("post:bash:pr-created", ["standard", "strict"]) &&
|
||||
input.tool === "bash" &&
|
||||
String(input.args?.command ?? input.args ?? "").includes("gh pr create")
|
||||
) {
|
||||
log("info", "[ECC] PR created - check GitHub Actions status")
|
||||
}
|
||||
|
||||
// Skill telemetry (#2463). OpenCode's tool is named `skill`, so the
|
||||
// harness-side name is matched here (case-insensitively) and the payload
|
||||
// is handed over in the shape the tracker already understands.
|
||||
if (
|
||||
hookEnabled("post:skill:track", ["standard", "strict"]) &&
|
||||
typeof input.tool === "string" &&
|
||||
input.tool.trim().toLowerCase() === "skill"
|
||||
) {
|
||||
try {
|
||||
recordSkillRun?.({
|
||||
tool_name: "Skill",
|
||||
tool_input: input.args ?? {},
|
||||
tool_response: output,
|
||||
})
|
||||
} catch {
|
||||
// Telemetry is best-effort; never let it affect the tool result.
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] tool.execute.after hook failed: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Session Created Hook (Equivalent to Claude Code SessionStart hook). */
|
||||
const onSessionCreated = async () => {
|
||||
if (!hookEnabled("session:start", ["minimal", "standard", "strict"])) return
|
||||
log("info", `[ECC] Session started - profile=${currentProfile}`)
|
||||
if (hasProjectFile("CLAUDE.md")) {
|
||||
log("info", "[ECC] Found CLAUDE.md - loading project context")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Session Idle Hook (Equivalent to Claude Code Stop hook): console.log
|
||||
* audit on all edited files + desktop notification.
|
||||
*/
|
||||
const onSessionIdle = async () => {
|
||||
if (!hookEnabled("stop:check-console-log", ["minimal", "standard", "strict"])) return
|
||||
if (editedFiles.size === 0) return
|
||||
|
||||
log("info", "[ECC] Session idle - running console.log audit")
|
||||
|
||||
let totalConsoleLogCount = 0
|
||||
const filesWithConsoleLogs: string[] = []
|
||||
|
||||
for (const file of editedFiles) {
|
||||
if (!/\.(ts|tsx|js|jsx)$/.test(file)) continue
|
||||
const count = await countConsoleLogs(resolvePath(file)).catch(() => 0)
|
||||
if (count > 0) {
|
||||
totalConsoleLogCount += count
|
||||
filesWithConsoleLogs.push(file)
|
||||
}
|
||||
}
|
||||
|
||||
if (totalConsoleLogCount > 0) {
|
||||
log(
|
||||
"warn",
|
||||
`[ECC] Audit: ${totalConsoleLogCount} console.log statement(s) in ${filesWithConsoleLogs.length} file(s)`,
|
||||
)
|
||||
filesWithConsoleLogs.forEach((f) => log("warn", ` - ${f}`))
|
||||
log("warn", "[ECC] Remove console.log statements before committing")
|
||||
} else {
|
||||
log("info", "[ECC] Audit passed: No console.log statements found")
|
||||
}
|
||||
|
||||
// Desktop notification, best effort and never blocking. The V1 Windows
|
||||
// path opened a modal MessageBox on the server; that is replaced with a
|
||||
// fire-and-forget balloon tip, and every branch is detached.
|
||||
try {
|
||||
if (process.platform === "darwin") {
|
||||
await run("osascript", ["-e", 'display notification "Task completed!" with title "OpenCode ECC"'], {
|
||||
detached: true,
|
||||
}).catch(() => {})
|
||||
} else if (process.platform === "win32") {
|
||||
const ps =
|
||||
"$ni = New-Object System.Windows.Forms.NotifyIcon; $ni.Icon = [System.Drawing.SystemIcons]::Information; " +
|
||||
"$ni.Visible = $true; $ni.ShowBalloonTip('OpenCode ECC', 'Task completed!', 'Info'); " +
|
||||
"Start-Sleep -Seconds 5; $ni.Dispose()"
|
||||
await run(
|
||||
"powershell",
|
||||
["-NoProfile", "-WindowStyle", "Hidden", "-Command", `Add-Type -AssemblyName System.Windows.Forms; ${ps}`],
|
||||
{ detached: true },
|
||||
).catch(() => {})
|
||||
} else if (process.platform === "linux") {
|
||||
await run("notify-send", ["OpenCode ECC", "Task completed!"], { detached: true }).catch(() => {})
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] Desktop notification failed: ${errorMessage}`)
|
||||
}
|
||||
|
||||
// Clear tracked files for next task
|
||||
editedFiles.clear()
|
||||
}
|
||||
|
||||
/** Session Deleted Hook (Equivalent to Claude Code SessionEnd hook). */
|
||||
const onSessionDeleted = async () => {
|
||||
if (!hookEnabled("session:end-marker", ["minimal", "standard", "strict"])) return
|
||||
log("info", "[ECC] Session ended - cleaning up")
|
||||
editedFiles.clear()
|
||||
changedFilesStore?.clearChanges?.()
|
||||
pendingToolChanges.clear()
|
||||
}
|
||||
|
||||
/** File Watcher Hook (OpenCode-only): keeps tracking in sync with external edits. */
|
||||
const onFileWatcherUpdated = async (event: { path: string; type: string }) => {
|
||||
let changeType: "added" | "modified" | "deleted" = "modified"
|
||||
if (event.type === "create" || event.type === "add") changeType = "added"
|
||||
else if (event.type === "delete" || event.type === "remove") changeType = "deleted"
|
||||
changedFilesStore?.recordChange?.(event.path, changeType)
|
||||
if (event.type === "change" && /\.(ts|tsx|js|jsx)$/.test(event.path)) {
|
||||
editedFiles.add(event.path)
|
||||
}
|
||||
}
|
||||
|
||||
/** Todo Updated Hook (OpenCode-only): logs progress. */
|
||||
const onTodoUpdated = async (event: { todos: Array<{ text?: string; done: boolean }> }) => {
|
||||
const todos = Array.isArray(event.todos) ? event.todos : []
|
||||
const completed = todos.filter((t) => t.done).length
|
||||
const total = todos.length
|
||||
if (total > 0) {
|
||||
log("info", `[ECC] Progress: ${completed}/${total} tasks completed`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shell Environment Hook (OpenCode-specific): inject ECC context into
|
||||
* shell commands. PROJECT_ROOT/PACKAGE_MANAGER/... are computed per call
|
||||
* because project marker files can appear after plugin init.
|
||||
*/
|
||||
const onShellEnv = async (_input: { cwd: string }, output: { env: Record<string, string> }) => {
|
||||
if (!output) return
|
||||
const env: Record<string, string> = {
|
||||
ECC_VERSION: getECCVersion(eccRoot),
|
||||
ECC_PLUGIN: "true",
|
||||
ECC_HOOK_PROFILE: currentProfile,
|
||||
ECC_DISABLED_HOOKS: process.env.ECC_DISABLED_HOOKS || "",
|
||||
PROJECT_ROOT: worktreePath,
|
||||
}
|
||||
|
||||
// Detect package manager (fs only: no shell probing, so this works on Windows).
|
||||
const lockfiles: Record<string, string> = {
|
||||
"bun.lockb": "bun",
|
||||
"pnpm-lock.yaml": "pnpm",
|
||||
"yarn.lock": "yarn",
|
||||
"package-lock.json": "npm",
|
||||
}
|
||||
for (const [lockfile, pm] of Object.entries(lockfiles)) {
|
||||
if (hasProjectFile(lockfile)) {
|
||||
env.PACKAGE_MANAGER = pm
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Detect languages
|
||||
const langDetectors: Record<string, string> = {
|
||||
"tsconfig.json": "typescript",
|
||||
"go.mod": "go",
|
||||
"pyproject.toml": "python",
|
||||
"Cargo.toml": "rust",
|
||||
"Package.swift": "swift",
|
||||
}
|
||||
const detected: string[] = []
|
||||
for (const [file, lang] of Object.entries(langDetectors)) {
|
||||
if (hasProjectFile(file)) {
|
||||
detected.push(lang)
|
||||
}
|
||||
}
|
||||
if (detected.length > 0) {
|
||||
env.DETECTED_LANGUAGES = detected.join(",")
|
||||
env.PRIMARY_LANGUAGE = detected[0]
|
||||
}
|
||||
|
||||
// resolve-ecc-root.js only probes ~/.claude and Claude Code's plugin
|
||||
// cache, so under OpenCode it fell back to ~/.claude and every command
|
||||
// carrying the inlined resolver failed to find its scripts. That resolver
|
||||
// reads CLAUDE_PLUGIN_ROOT first, so exporting the root here fixes them
|
||||
// through the mechanism ECC already provides -- rather than editing the
|
||||
// command files that embed the locator.
|
||||
//
|
||||
// Only set when a root actually exists, and never replace a root someone
|
||||
// else already chose: neither the process environment (set by the user)
|
||||
// nor `output.env` (set by an earlier plugin). The final merge below
|
||||
// overwrites output.env, so checking it only in `env` would clobber it.
|
||||
const rootAlreadySet = Boolean(
|
||||
(process.env.CLAUDE_PLUGIN_ROOT || "").trim() || (output.env?.CLAUDE_PLUGIN_ROOT || "").trim(),
|
||||
)
|
||||
if (eccRoot && !rootAlreadySet) {
|
||||
env.CLAUDE_PLUGIN_ROOT = eccRoot
|
||||
}
|
||||
|
||||
// OpenCode reads the supplied output object and ignores callback return values.
|
||||
output.env = { ...output.env, ...env }
|
||||
}
|
||||
|
||||
/** ECC context block preserved through compaction. */
|
||||
function buildCompactionContext(): string {
|
||||
const contextBlock = [
|
||||
"# ECC Context (preserve across compaction)",
|
||||
"",
|
||||
`## Active Plugin: ECC v${getECCVersion(eccRoot)}`,
|
||||
"- Hooks: file.edited, tool.execute.before/after, session.created/idle/deleted, shell.env, compacting, permission.ask",
|
||||
"- Tools: changed-files, dependency-analyzer",
|
||||
"",
|
||||
"## Key Principles",
|
||||
"- TDD: write tests first, 80%+ coverage",
|
||||
"- Immutability: never mutate, always return new copies",
|
||||
"- Security: validate inputs, no hardcoded secrets",
|
||||
"",
|
||||
]
|
||||
|
||||
// Include recently edited files
|
||||
if (editedFiles.size > 0) {
|
||||
contextBlock.push("## Recently Edited Files")
|
||||
for (const f of editedFiles) {
|
||||
contextBlock.push(`- ${f}`)
|
||||
}
|
||||
contextBlock.push("")
|
||||
}
|
||||
|
||||
return [
|
||||
contextBlock.join("\n"),
|
||||
"Focus on preserving: 1) Current task status and progress, 2) Key decisions made, 3) Files created/modified, 4) Remaining work items, 5) Any security concerns flagged. Discard: verbose tool outputs, intermediate exploration, redundant file listings.",
|
||||
].join("\n\n")
|
||||
}
|
||||
|
||||
/**
|
||||
* Session Compacting Hook (OpenCode-specific): append ECC context without
|
||||
* replacing the host (or an earlier plugin's) compaction prompt.
|
||||
*/
|
||||
const onSessionCompacting = async (
|
||||
_input: { sessionID: string },
|
||||
output: { context: string[]; prompt?: string },
|
||||
) => {
|
||||
const eccContext = buildCompactionContext()
|
||||
// OpenCode requires output assignment and skips context when a prompt is set.
|
||||
if (output && output.prompt !== undefined) {
|
||||
output.prompt = [output.prompt, eccContext].join("\n\n")
|
||||
} else if (output) {
|
||||
output.context = [...output.context, eccContext]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission Auto-Approve Hook (OpenCode-specific): auto-approve reads,
|
||||
* formatters, and test commands on top of the configured rules.
|
||||
*/
|
||||
const onPermissionAsk = async (event: PermissionEvent) => {
|
||||
log("info", `[ECC] Permission requested for: ${event.tool}`)
|
||||
|
||||
try {
|
||||
// Handle both string args and object args with command property
|
||||
let cmd: string
|
||||
if (typeof event.args === "string") {
|
||||
cmd = event.args
|
||||
} else if (event.args && typeof event.args === "object") {
|
||||
cmd = String((event.args as Record<string, unknown>).command || "")
|
||||
} else {
|
||||
cmd = String(event.args || "")
|
||||
}
|
||||
if (cmd) {
|
||||
log("debug", `[ECC] Permission resource: ${cmd.slice(0, 120)}`)
|
||||
}
|
||||
|
||||
// Auto-approve: read/search tools
|
||||
if (["read", "glob", "grep", "search", "list"].includes(event.tool)) {
|
||||
log("debug", `[ECC] Auto-approved read-only tool: ${event.tool}`)
|
||||
return { approved: true, reason: "Read-only operation" }
|
||||
}
|
||||
|
||||
// T02: no shell-command auto-approval. A regex over the leading
|
||||
// characters of a free-form shell string is not a safe allow-list —
|
||||
// cmd/powershell argument modes, quoting, and subshell syntax can all
|
||||
// defeat it (e.g. `prettier --write x.ts & curl evil.co`, or PowerShell
|
||||
// `(prettier)`). Formatter and test commands fall through to the user's
|
||||
// permission system instead.
|
||||
|
||||
// Everything else: let user decide
|
||||
log("debug", `[ECC] Permission requires user approval: ${event.tool}`)
|
||||
return { approved: undefined }
|
||||
} catch (error: unknown) {
|
||||
// Error in permission handling - log and deny for safety
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("error", `[ECC] Permission handling error for ${event.tool}: ${errorMessage}`)
|
||||
return { approved: false, reason: `Error: ${errorMessage}` }
|
||||
}
|
||||
}
|
||||
|
||||
// V1 custom tool record: definitions load lazily; a broken tools/ install
|
||||
// surfaces only when a tool is actually invoked, never at startup.
|
||||
const tool: Record<string, unknown> = {}
|
||||
for (const name of ["changed-files", "dependency-analyzer"]) {
|
||||
try {
|
||||
const definition = await loadToolModule(name)
|
||||
tool[name] = definition
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("warn", `[ECC] Custom tool ${name} disabled: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
const hooks: Record<string, any> = {
|
||||
"file.edited": onFileEdited,
|
||||
"tool.execute.before": onToolBefore,
|
||||
"tool.execute.after": onToolAfter,
|
||||
"session.created": onSessionCreated,
|
||||
"session.idle": onSessionIdle,
|
||||
"session.deleted": onSessionDeleted,
|
||||
"file.watcher.updated": onFileWatcherUpdated,
|
||||
"todo.updated": onTodoUpdated,
|
||||
"shell.env": onShellEnv,
|
||||
"experimental.session.compacting": onSessionCompacting,
|
||||
"permission.ask": onPermissionAsk,
|
||||
}
|
||||
|
||||
return { hooks, tool, buildCompactionContext, worktreePath }
|
||||
}
|
||||
|
||||
/**
|
||||
* V1 factory surface. OpenCode 1.x (and ECC's own discovery tests) call this
|
||||
@@ -986,7 +93,7 @@ export const ECCHooksPlugin = async (input: {
|
||||
directory?: string
|
||||
worktree?: string
|
||||
}): Promise<Record<string, unknown>> => {
|
||||
const runtime = await createEccRuntime(input)
|
||||
const runtime = await createEccRuntime(input, PLUGIN_DIR)
|
||||
return { ...runtime.hooks, tool: runtime.tool }
|
||||
}
|
||||
|
||||
@@ -1000,7 +107,7 @@ export const ECCHooksPluginDefinition = {
|
||||
}
|
||||
registeredDirectories.add(directory)
|
||||
|
||||
const runtime = await createEccRuntime({ directory, worktree: directory })
|
||||
const runtime = await createEccRuntime({ directory, worktree: directory }, PLUGIN_DIR)
|
||||
const { hooks, worktreePath } = runtime
|
||||
|
||||
// Normalize a V2 tool-hook event into the V1 ToolInput shape so both
|
||||
@@ -1115,7 +222,7 @@ export const ECCHooksPluginDefinition = {
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async (input: any, context: any) => {
|
||||
const mod = await loadToolModule("changed-files")
|
||||
const mod = await loadToolModule("changed-files", PLUGIN_DIR)
|
||||
const result = await mod.execute(input ?? {}, context ?? { directory: worktreePath, worktree: worktreePath })
|
||||
return { content: String(result) }
|
||||
},
|
||||
@@ -1134,7 +241,7 @@ export const ECCHooksPluginDefinition = {
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async (input: any, context: any) => {
|
||||
const mod = await loadToolModule("dependency-analyzer")
|
||||
const mod = await loadToolModule("dependency-analyzer", PLUGIN_DIR)
|
||||
const result = await mod.execute(input ?? {}, context ?? { directory: worktreePath, worktree: worktreePath })
|
||||
return { content: String(result) }
|
||||
},
|
||||
@@ -1230,7 +337,7 @@ async function disposeRegistrations(
|
||||
|
||||
function logStartup(directory: string) {
|
||||
// Mirrors the V1 startup line used in server-log triage (TROUBLESHOOTING.md).
|
||||
console.info(`[ecc] hooks plugin v${getECCVersion(findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.root))} loaded (directory=${directory})`)
|
||||
console.info(`[ecc] hooks plugin v${getECCVersion(findEccRootDir(PLUGIN_DIR, ECC_ROOT_PROBES.root), PLUGIN_DIR)} loaded (directory=${directory})`)
|
||||
}
|
||||
|
||||
export default ECCHooksPluginDefinition
|
||||
@@ -0,0 +1,255 @@
|
||||
/** Shared filesystem, process and lazy-tool helpers for the OpenCode runtime. */
|
||||
import * as fs from "fs"
|
||||
import * as path from "path"
|
||||
import { spawn } from "child_process"
|
||||
import { pathToFileURL } from "url"
|
||||
|
||||
export type HookProfile = "minimal" | "standard" | "strict"
|
||||
|
||||
/** Loose aliases: the runtime ctx/event shapes come from the server, not the pinned SDK. */
|
||||
export type LooseRecord = Record<string, any>
|
||||
|
||||
export interface ToolArgs {
|
||||
filePath?: string
|
||||
file_path?: string
|
||||
path?: string
|
||||
command?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface ToolInput {
|
||||
tool: string
|
||||
callID?: string
|
||||
args?: ToolArgs
|
||||
}
|
||||
|
||||
export interface PermissionEvent {
|
||||
tool: string
|
||||
args: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Artifacts that identify an ECC root, one per capability this plugin needs.
|
||||
*
|
||||
* These are required runtime files, never optional content: `skills/` belongs to
|
||||
* the optional `workflow-quality` module, so probing for a skill rejected
|
||||
* supported modular installs (e.g. `platform-configs` + `hooks-runtime` without
|
||||
* `workflow-quality`) that still ship both the plugin and the tracker — silently
|
||||
* disabling skill telemetry and the shell root export for those users.
|
||||
*
|
||||
* Each probe is the exact artifact the caller is about to use, so detection is
|
||||
* layout detection rather than an authenticity control: a directory only
|
||||
* qualifies because it contains what we are going to read.
|
||||
*/
|
||||
export const ECC_ROOT_PROBES = {
|
||||
// scripts/lib/utils.js is the shared library every scripts/ module requires.
|
||||
root: [path.join("scripts", "lib", "utils.js")],
|
||||
// What the skill-run telemetry hook imports at runtime.
|
||||
skillTracker: [path.join("scripts", "hooks", "skill-run-tracker.js")],
|
||||
// What the resolver embedded in commands requires once they read
|
||||
// CLAUDE_PLUGIN_ROOT, and the version lookup for shell.env.
|
||||
resolver: [path.join("scripts", "lib", "resolve-ecc-root.js")],
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Walk upwards from `startDir` looking for an ancestor that contains every
|
||||
* relative path in `probes`.
|
||||
*
|
||||
* The plugin ships in three layouts — `<root>/plugins` (installed), `<root>/dist/plugins`
|
||||
* (compiled) and `<repo>/.opencode/plugins` (repo checkout) — so the number of
|
||||
* levels back to the root is not fixed. Probing beats a hardcoded `..`: a wrong
|
||||
* root would make every command resolve against a directory that has no scripts.
|
||||
*
|
||||
* The walk is bounded to 5 levels so it cannot wander into unrelated ancestors.
|
||||
*
|
||||
* Returns null when no ancestor qualifies, so callers can leave the capability
|
||||
* disabled instead of advertising a root that does not hold the artifact.
|
||||
*/
|
||||
export function findEccRootDir(startDir: string, probes: readonly string[]): string | null {
|
||||
let current = startDir
|
||||
for (let depth = 0; depth < 5; depth += 1) {
|
||||
if (probes.every((probe) => fs.existsSync(path.join(current, probe)))) {
|
||||
return current
|
||||
}
|
||||
const parent = path.dirname(current)
|
||||
if (parent === current) break
|
||||
current = parent
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the ECC version from package.json.
|
||||
*
|
||||
* Candidates are tried in order — the resolved ECC root first, then the two
|
||||
* plausible parent depths of the plugin — because the layout differs between an
|
||||
* installed root (`<root>/plugins`), the compiled bundle (`<root>/dist/plugins`)
|
||||
* and a repo checkout (`<repo>/.opencode/plugins`). Falls back to a default if
|
||||
* no package.json can be read.
|
||||
*/
|
||||
export function getECCVersion(eccRootDir: string | null | undefined, pluginDir: string): string {
|
||||
const candidates = [
|
||||
eccRootDir,
|
||||
path.resolve(pluginDir, ".."),
|
||||
path.resolve(pluginDir, "..", ".."),
|
||||
]
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) continue
|
||||
try {
|
||||
const packageJson = JSON.parse(fs.readFileSync(path.join(candidate, "package.json"), "utf-8"))
|
||||
if (typeof packageJson.version === "string" && packageJson.version) {
|
||||
return packageJson.version
|
||||
}
|
||||
} catch {
|
||||
// Try the next candidate.
|
||||
}
|
||||
}
|
||||
|
||||
return "2.0.0"
|
||||
}
|
||||
|
||||
/**
|
||||
* On Windows, npx/npm/pnpm/yarn/bun are `.cmd` shims that CreateProcess
|
||||
* cannot launch directly from a bare command name. Node's own guidance for
|
||||
* this case is to spawn the exact `.cmd` file through `cmd.exe /d /s /c`
|
||||
* with `windowsVerbatimArguments` and quoted args — NOT `shell: true`,
|
||||
* which concatenates the command and arguments into one string that shell
|
||||
* metacharacters (&, |, ;) in any argument (e.g. a file path) could inject
|
||||
* into. The command is fixed here (never user input); only known package
|
||||
* managers get the cmd-shim treatment, and their arguments stay separated.
|
||||
*/
|
||||
function spawnCommand(
|
||||
command: string,
|
||||
args: string[],
|
||||
): { file: string; spawnArgs: string[]; verbatim: boolean } {
|
||||
if (
|
||||
process.platform === "win32" &&
|
||||
/^(npx|npm|pnpm|yarn|bun)(\.cmd)?$/i.test(command)
|
||||
) {
|
||||
// R2-2: cmd.exe expands %VAR% and honours embedded quotes even inside
|
||||
// "double quotes", so backslash-escaping a quote here is not safe. Reject
|
||||
// any argument carrying a quote, percent sign, or line break outright
|
||||
// (line breaks would also terminate the /c command string). Legitimate
|
||||
// package-manager invocations never need these characters; callers already
|
||||
// surface the rejection through run()'s rejection path.
|
||||
const unsafe = args.find((value) => /["%\r\n]/.test(value))
|
||||
if (unsafe !== undefined) {
|
||||
throw new Error(
|
||||
`Refusing to launch package-manager shim with unsafe argument: ${JSON.stringify(unsafe)}`,
|
||||
)
|
||||
}
|
||||
const shim = `${command.replace(/\.cmd$/i, "")}.cmd`
|
||||
const quote = (value: string) => `"${value}"`
|
||||
// Canonical `/s` form: wrap the whole command string in one outer pair of
|
||||
// quotes. cmd strips exactly that outer pair and executes the remainder
|
||||
// verbatim, so the quoted shim path resolves instead of being re-split.
|
||||
const inner = [shim, ...args].map(quote).join(" ")
|
||||
return {
|
||||
file: process.env.ComSpec || "cmd.exe",
|
||||
spawnArgs: ["/d", "/s", "/c", `"${inner}"`],
|
||||
verbatim: true,
|
||||
}
|
||||
}
|
||||
return { file: command, spawnArgs: args, verbatim: false }
|
||||
}
|
||||
|
||||
/** Run a command, resolving with its output regardless of exit code. */
|
||||
export function run(
|
||||
command: string,
|
||||
args: string[],
|
||||
options: { cwd?: string; detached?: boolean } = {},
|
||||
): Promise<{ code: number; stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const resolved = spawnCommand(command, args)
|
||||
const child = spawn(resolved.file, resolved.spawnArgs, {
|
||||
cwd: options.cwd,
|
||||
shell: false,
|
||||
windowsVerbatimArguments: resolved.verbatim,
|
||||
windowsHide: true,
|
||||
detached: options.detached === true,
|
||||
stdio: options.detached === true ? "ignore" : ["ignore", "pipe", "pipe"],
|
||||
})
|
||||
// T03: the error listener must exist before any early return below, so a
|
||||
// missing binary (ENOENT) rejects this promise instead of surfacing as an
|
||||
// unhandled 'error' event that can crash the host process.
|
||||
let settled = false
|
||||
child.on("error", (error) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
reject(error)
|
||||
})
|
||||
if (options.detached === true) {
|
||||
child.unref()
|
||||
settled = true
|
||||
resolve({ code: 0, stdout: "", stderr: "" })
|
||||
return
|
||||
}
|
||||
let stdout = ""
|
||||
let stderr = ""
|
||||
child.stdout?.on("data", (chunk) => (stdout += String(chunk)))
|
||||
child.stderr?.on("data", (chunk) => (stderr += String(chunk)))
|
||||
child.on("close", (code) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
resolve({ code: code ?? 1, stdout, stderr })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** Count console.log occurrences in a file with fs+regex (cross-platform grep replacement). */
|
||||
export async function countConsoleLogs(filePath: string): Promise<number> {
|
||||
const content = await fs.promises.readFile(filePath, "utf-8")
|
||||
return (content.match(/console\.log\s*\(/g) ?? []).length
|
||||
}
|
||||
|
||||
/**
|
||||
* The custom tool definitions V1 exposed through `plugin.tool` and V2 exposes
|
||||
* through ctx.tool.transform. Loaded lazily and cached per name: this file is
|
||||
* OpenCode's startup entry point, and a static top-level import of a missing
|
||||
* tools/ module used to crash the whole session before any hook could load
|
||||
* (#2530). A failed load degrades to an execute-time error message instead.
|
||||
*/
|
||||
const toolModuleCache = new Map<string, Promise<any>>()
|
||||
|
||||
/**
|
||||
* Resolve a tool module by URL rather than by a literal specifier: tsc only
|
||||
* rewrites `.ts` extensions in statically-analyzable specifiers, and the
|
||||
* compiled layout ships `.js` while a repo/source install ships `.ts`.
|
||||
*/
|
||||
export async function loadToolModule(name: string, pluginDir: string): Promise<{ description: string; args: any; execute: (args: any, context: any) => Promise<unknown> }> {
|
||||
let pending = toolModuleCache.get(name)
|
||||
if (!pending) {
|
||||
const toolsDir = path.resolve(pluginDir, "..", "tools")
|
||||
const candidates = [path.join(toolsDir, `${name}.js`), path.join(toolsDir, `${name}.ts`)]
|
||||
pending = (async () => {
|
||||
let lastError: unknown
|
||||
for (const candidate of candidates) {
|
||||
if (!fs.existsSync(candidate)) continue
|
||||
try {
|
||||
return await import(pathToFileURL(candidate).href)
|
||||
} catch (error) {
|
||||
lastError = error
|
||||
}
|
||||
}
|
||||
throw lastError ?? new Error(`neither ${name}.js nor ${name}.ts found under ${toolsDir}`)
|
||||
})()
|
||||
.then((mod: any) => {
|
||||
const definition = mod?.default ?? mod
|
||||
if (!definition || typeof definition.execute !== "function") {
|
||||
throw new Error(`${name}: module exposes no tool definition with an execute()`)
|
||||
}
|
||||
return definition
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
toolModuleCache.delete(name)
|
||||
throw new Error(
|
||||
`${name} tool: could not load ECC tool module. Run \`ecc repair --target opencode\` to restore the missing files. (${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
})`,
|
||||
)
|
||||
})
|
||||
toolModuleCache.set(name, pending)
|
||||
}
|
||||
return pending
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
/** Shared hook state and behavior used by both OpenCode registration surfaces. */
|
||||
import * as fs from "fs"
|
||||
import * as path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import {
|
||||
ECC_ROOT_PROBES, countConsoleLogs, findEccRootDir, getECCVersion, loadToolModule, run,
|
||||
} from "./ecc-runtime-support.ts"
|
||||
import type {
|
||||
HookProfile, LooseRecord, PermissionEvent, ToolArgs, ToolInput,
|
||||
} from "./ecc-runtime-support.ts"
|
||||
|
||||
/** The shared runtime: every hook body lives here exactly once. */
|
||||
interface EccRuntime {
|
||||
/** V1-shaped hook map (also used by the V2 adapters below). */
|
||||
hooks: Record<string, any>
|
||||
/** V1-shaped custom tool record. */
|
||||
tool: Record<string, unknown>
|
||||
/** ECC context block preserved through compaction (V2 registration uses it). */
|
||||
buildCompactionContext: () => string
|
||||
/** The project directory this runtime was built for. */
|
||||
worktreePath: string
|
||||
}
|
||||
|
||||
export async function createEccRuntime(input: {
|
||||
client?: { app?: { log?: (event: { body: LooseRecord }) => unknown } }
|
||||
$?: unknown
|
||||
directory?: string
|
||||
worktree?: string
|
||||
}, pluginDir: string): Promise<EccRuntime> {
|
||||
const { client } = input
|
||||
const worktreePath = input.worktree || input.directory || process.cwd()
|
||||
|
||||
const editedFiles = new Set<string>()
|
||||
const pendingToolChanges = new Map<string, { path: string; type: "added" | "modified" }>()
|
||||
let writeCounter = 0
|
||||
|
||||
function resolvePath(p: string): string {
|
||||
if (path.isAbsolute(p)) return p
|
||||
return path.join(worktreePath, p)
|
||||
}
|
||||
|
||||
function hasProjectFile(relativePath: string): boolean {
|
||||
try {
|
||||
return fs.statSync(resolvePath(relativePath)).isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function getFilePath(args: ToolArgs | undefined): string | null {
|
||||
if (!args) return null
|
||||
const p = (args.filePath ?? args.file_path ?? args.path) as string | undefined
|
||||
return typeof p === "string" && p.trim() ? p : null
|
||||
}
|
||||
|
||||
// V1 logged through the SDK client; V2 has no client.app.log, so the console
|
||||
// fallback writes into the server log, which is where those messages ended
|
||||
// up anyway.
|
||||
const log = (level: "debug" | "info" | "warn" | "error", message: string) => {
|
||||
if (typeof client?.app?.log === "function") {
|
||||
return client.app.log({ body: { service: "ecc", level, message } })
|
||||
}
|
||||
try {
|
||||
const line = `[ecc] ${message}`
|
||||
if (level === "error") console.error(line)
|
||||
else if (level === "warn") console.warn(line)
|
||||
else if (level === "debug") console.debug(line)
|
||||
else console.info(line)
|
||||
} catch {
|
||||
// Logging must never break a hook.
|
||||
}
|
||||
}
|
||||
|
||||
// Loaded lazily (instead of via a top-level import) so that a missing or
|
||||
// partially-installed `~/.opencode/plugins/lib` directory (e.g. an
|
||||
// interrupted or partial ECC install on Termux/Android) only disables
|
||||
// changed-files tracking, rather than throwing during module evaluation.
|
||||
// This plugin is OpenCode's startup entry point, so a static import
|
||||
// failure here previously crashed the whole plugin -- and with it, the
|
||||
// entire OpenCode session -- before any hooks could load (see #2530).
|
||||
// The relative ".ts" specifier is rewritten to ".js" by tsc in the compiled
|
||||
// layout and resolved natively by OpenCode's TS loader in a source layout.
|
||||
let changedFilesStore: typeof import("./changed-files-store.ts") | undefined
|
||||
try {
|
||||
const store = await import("./changed-files-store.ts")
|
||||
store.initStore?.(worktreePath)
|
||||
changedFilesStore = store
|
||||
} catch {
|
||||
// Best-effort diagnostic only: deferred via .then() (rather than
|
||||
// Promise.resolve(log(...))) so that even a *synchronous* throw inside
|
||||
// log() -- not just an async rejection -- is caught here instead of
|
||||
// escaping this catch block. The raw loader error is intentionally not
|
||||
// included in the message since it can contain absolute filesystem
|
||||
// paths; this whole block exists to guarantee startup resilience even
|
||||
// when things go wrong.
|
||||
Promise.resolve()
|
||||
.then(() =>
|
||||
log(
|
||||
"warn",
|
||||
"[ECC] changed-files tracking disabled: could not load the changed-files store. " +
|
||||
"Run `ecc repair --target opencode` to restore the missing files. Other ECC hooks are unaffected.",
|
||||
),
|
||||
)
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
// Claude Code routes post:skill:track through
|
||||
// scripts/hooks/posttooluse-dispatcher.js, which OpenCode never invokes.
|
||||
// Without a caller here, nothing ever writes skill-runs.jsonl and
|
||||
// `skills-health.js --dashboard` has no data to report on any skill (#2463).
|
||||
//
|
||||
// The tracker module is reused rather than reimplemented so its identifier
|
||||
// validation, length bounds and "never persist prompt text" guarantees stay
|
||||
// the ones that were written and audited for the Claude Code path.
|
||||
//
|
||||
// Loaded lazily, for the same reason as the store above. A runtime file URL
|
||||
// also keeps tsc from resolving a relative specifier that exists in no
|
||||
// compiled layout.
|
||||
let recordSkillRun: ((payload: unknown) => void) | undefined
|
||||
// Detection is scoped to the tracker itself, so a modular install that omits
|
||||
// optional content still gets telemetry.
|
||||
const trackerRoot = findEccRootDir(pluginDir, ECC_ROOT_PROBES.skillTracker)
|
||||
// The root advertised to commands is a different question: those commands
|
||||
// require the resolver, so a root without it would break them again.
|
||||
const eccRoot =
|
||||
findEccRootDir(pluginDir, ECC_ROOT_PROBES.resolver) ?? findEccRootDir(pluginDir, ECC_ROOT_PROBES.root)
|
||||
try {
|
||||
const trackerPath = trackerRoot ? path.join(trackerRoot, "scripts", "hooks", "skill-run-tracker.js") : null
|
||||
if (!trackerPath || !fs.existsSync(trackerPath)) {
|
||||
throw new Error("skill-run-tracker.js not found")
|
||||
}
|
||||
// CJS module loaded from ESM: run() is on the namespace in Node/Bun, but a
|
||||
// transpiled default export must stay supported.
|
||||
const loaded = (await import(pathToFileURL(trackerPath).href)) as {
|
||||
run?: (payload: unknown) => void
|
||||
default?: { run?: (payload: unknown) => void }
|
||||
}
|
||||
const entry = typeof loaded.run === "function" ? loaded : loaded.default
|
||||
if (!entry || typeof entry.run !== "function") {
|
||||
throw new Error("skill-run-tracker.js exposes no run()")
|
||||
}
|
||||
recordSkillRun = entry.run
|
||||
} catch {
|
||||
// Same deferred-log rationale as the store above: guarantee that a
|
||||
// telemetry failure can never escape this catch and abort startup.
|
||||
Promise.resolve()
|
||||
.then(() =>
|
||||
log(
|
||||
"warn",
|
||||
"[ECC] skill-run telemetry disabled: could not load scripts/hooks/skill-run-tracker.js. " +
|
||||
"Run `ecc repair --target opencode` to restore the missing files. Other ECC hooks are unaffected.",
|
||||
),
|
||||
)
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
const normalizeProfile = (value: string | undefined): HookProfile => {
|
||||
if (value === "minimal" || value === "strict") return value
|
||||
return "standard"
|
||||
}
|
||||
|
||||
const currentProfile = normalizeProfile(process.env.ECC_HOOK_PROFILE)
|
||||
const disabledHooks = new Set(
|
||||
(process.env.ECC_DISABLED_HOOKS || "")
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean),
|
||||
)
|
||||
|
||||
const profileOrder: Record<HookProfile, number> = { minimal: 0, standard: 1, strict: 2 }
|
||||
|
||||
const profileAllowed = (required: HookProfile | HookProfile[]): boolean => {
|
||||
if (Array.isArray(required)) {
|
||||
return required.some((entry) => profileOrder[currentProfile] >= profileOrder[entry])
|
||||
}
|
||||
return profileOrder[currentProfile] >= profileOrder[required]
|
||||
}
|
||||
|
||||
const hookEnabled = (
|
||||
hookId: string,
|
||||
requiredProfile: HookProfile | HookProfile[] = "standard",
|
||||
): boolean => {
|
||||
if (disabledHooks.has(hookId)) return false
|
||||
return profileAllowed(requiredProfile)
|
||||
}
|
||||
|
||||
/**
|
||||
* Prettier auto-format + console.log warning + change tracking.
|
||||
* (Equivalent to Claude Code PostToolUse hook for prettier.)
|
||||
*/
|
||||
const onFileEdited = async (event: { path: string }) => {
|
||||
try {
|
||||
editedFiles.add(event.path)
|
||||
changedFilesStore?.recordChange?.(event.path, "modified")
|
||||
|
||||
// Auto-format JS/TS files (strict profile only: it shells out).
|
||||
if (hookEnabled("post:edit:format", ["strict"]) && /\.(ts|tsx|js|jsx)$/.test(event.path)) {
|
||||
try {
|
||||
const result = await run("npx", ["prettier", "--write", event.path], { cwd: worktreePath })
|
||||
// T11: a non-zero exit is a failure, not a success. Only log
|
||||
// "Formatted" when prettier actually ran and wrote the file.
|
||||
if (result.code === 0) {
|
||||
log("info", `[ECC] Formatted: ${event.path}`)
|
||||
} else {
|
||||
const detail = (result.stderr || result.stdout || "").trim().slice(0, 200)
|
||||
log("warn", `[ECC] Prettier failed for ${event.path} (exit ${result.code})${detail ? `: ${detail}` : ""}`)
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
// Prettier could not be spawned at all - log but continue
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] Prettier formatting failed for ${event.path}: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
// Console.log warning check (fs+regex: grep is not available on Windows).
|
||||
if (hookEnabled("post:edit:console-warn", ["standard", "strict"]) && /\.(ts|tsx|js|jsx)$/.test(event.path)) {
|
||||
const count = await countConsoleLogs(resolvePath(event.path)).catch(() => 0)
|
||||
if (count > 0) {
|
||||
log(
|
||||
"warn",
|
||||
`[ECC] console.log found in ${event.path} (${count} occurrence${count > 1 ? "s" : ""})`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] file.edited hook failed: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Advisory pre-tool callback: change bookkeeping, git-push/tmux reminders,
|
||||
* and doc-file warnings. This does not invoke canonical ECC Bash guards.
|
||||
*/
|
||||
const onToolBefore = async (input: ToolInput) => {
|
||||
try {
|
||||
if (input.tool === "write") {
|
||||
const filePath = getFilePath(input.args)
|
||||
if (filePath) {
|
||||
const absPath = resolvePath(filePath)
|
||||
let type: "added" | "modified" = "modified"
|
||||
try {
|
||||
type = fs.existsSync(absPath) ? "modified" : "added"
|
||||
} catch {
|
||||
type = "modified"
|
||||
}
|
||||
const key = input.callID ?? `write-${++writeCounter}-${filePath}`
|
||||
pendingToolChanges.set(key, { path: filePath, type })
|
||||
}
|
||||
}
|
||||
|
||||
// Git push review reminder
|
||||
if (hookEnabled("pre:bash:git-push-reminder", "strict") && input.tool === "bash") {
|
||||
const cmd = String(input.args?.command ?? input.args ?? "")
|
||||
if (cmd.includes("git push")) {
|
||||
log("info", "[ECC] Remember to review changes before pushing: git diff origin/main...HEAD")
|
||||
}
|
||||
}
|
||||
|
||||
// Warn about potentially unnecessary documentation files
|
||||
if (hookEnabled("pre:write:doc-file-warning", ["standard", "strict"]) && input.tool === "write") {
|
||||
const filePath = getFilePath(input.args)
|
||||
if (
|
||||
filePath &&
|
||||
/\.(md|txt)$/i.test(filePath) &&
|
||||
!filePath.includes("README") &&
|
||||
!filePath.includes("CHANGELOG") &&
|
||||
!filePath.includes("LICENSE") &&
|
||||
!filePath.includes("CONTRIBUTING")
|
||||
) {
|
||||
log("warn", `[ECC] Creating ${filePath} - consider if this documentation is necessary`)
|
||||
}
|
||||
}
|
||||
|
||||
// Long-running command reminder
|
||||
if (hookEnabled("pre:bash:tmux-reminder", "strict") && input.tool === "bash") {
|
||||
const cmd = String(input.args?.command ?? input.args ?? "")
|
||||
if (
|
||||
cmd.match(/^(npm|pnpm|yarn|bun)\s+(install|build|test|run)/) ||
|
||||
cmd.match(/^cargo\s+(build|test|run)/) ||
|
||||
cmd.match(/^go\s+(build|test|run)/)
|
||||
) {
|
||||
log("info", "[ECC] Long-running command detected - consider using background execution")
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] tool.execute.before hook failed: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Post-tool: change recording, typecheck, PR log, skill telemetry.
|
||||
* (Equivalent to Claude Code PostToolUse hook for tsc.)
|
||||
*/
|
||||
const onToolAfter = async (input: ToolInput, output: unknown) => {
|
||||
try {
|
||||
const filePath = getFilePath(input.args)
|
||||
if (input.tool === "edit" && filePath) {
|
||||
changedFilesStore?.recordChange?.(filePath, "modified")
|
||||
}
|
||||
if (input.tool === "write" && filePath) {
|
||||
const key = input.callID ?? `write-${++writeCounter}-${filePath}`
|
||||
const pending = pendingToolChanges.get(key)
|
||||
if (pending) {
|
||||
changedFilesStore?.recordChange?.(pending.path, pending.type)
|
||||
pendingToolChanges.delete(key)
|
||||
} else {
|
||||
changedFilesStore?.recordChange?.(filePath, "modified")
|
||||
}
|
||||
}
|
||||
|
||||
// Check if a TypeScript file was edited
|
||||
if (
|
||||
hookEnabled("post:edit:typecheck", ["strict"]) &&
|
||||
input.tool === "edit" &&
|
||||
typeof input.args?.filePath === "string" &&
|
||||
/\.tsx?$/.test(input.args.filePath)
|
||||
) {
|
||||
const result = await run("npx", ["tsc", "--noEmit"], { cwd: worktreePath }).catch(() => null)
|
||||
if (result && result.code === 0) {
|
||||
log("info", "[ECC] TypeScript check passed")
|
||||
} else if (result) {
|
||||
log("warn", "[ECC] TypeScript errors detected:")
|
||||
const out = (result.stdout || result.stderr || "").split("\n").slice(0, 5)
|
||||
out.forEach((line) => line.trim() && log("warn", ` ${line}`))
|
||||
}
|
||||
}
|
||||
|
||||
// PR creation logging
|
||||
if (
|
||||
hookEnabled("post:bash:pr-created", ["standard", "strict"]) &&
|
||||
input.tool === "bash" &&
|
||||
String(input.args?.command ?? input.args ?? "").includes("gh pr create")
|
||||
) {
|
||||
log("info", "[ECC] PR created - check GitHub Actions status")
|
||||
}
|
||||
|
||||
// Skill telemetry (#2463). OpenCode's tool is named `skill`, so the
|
||||
// harness-side name is matched here (case-insensitively) and the payload
|
||||
// is handed over in the shape the tracker already understands.
|
||||
if (
|
||||
hookEnabled("post:skill:track", ["standard", "strict"]) &&
|
||||
typeof input.tool === "string" &&
|
||||
input.tool.trim().toLowerCase() === "skill"
|
||||
) {
|
||||
try {
|
||||
recordSkillRun?.({
|
||||
tool_name: "Skill",
|
||||
tool_input: input.args ?? {},
|
||||
tool_response: output,
|
||||
})
|
||||
} catch {
|
||||
// Telemetry is best-effort; never let it affect the tool result.
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] tool.execute.after hook failed: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Session Created Hook (Equivalent to Claude Code SessionStart hook). */
|
||||
const onSessionCreated = async () => {
|
||||
if (!hookEnabled("session:start", ["minimal", "standard", "strict"])) return
|
||||
log("info", `[ECC] Session started - profile=${currentProfile}`)
|
||||
if (hasProjectFile("CLAUDE.md")) {
|
||||
log("info", "[ECC] Found CLAUDE.md - loading project context")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Session Idle Hook (Equivalent to Claude Code Stop hook): console.log
|
||||
* audit on all edited files + desktop notification.
|
||||
*/
|
||||
const onSessionIdle = async () => {
|
||||
if (!hookEnabled("stop:check-console-log", ["minimal", "standard", "strict"])) return
|
||||
if (editedFiles.size === 0) return
|
||||
|
||||
log("info", "[ECC] Session idle - running console.log audit")
|
||||
|
||||
let totalConsoleLogCount = 0
|
||||
const filesWithConsoleLogs: string[] = []
|
||||
|
||||
for (const file of editedFiles) {
|
||||
if (!/\.(ts|tsx|js|jsx)$/.test(file)) continue
|
||||
const count = await countConsoleLogs(resolvePath(file)).catch(() => 0)
|
||||
if (count > 0) {
|
||||
totalConsoleLogCount += count
|
||||
filesWithConsoleLogs.push(file)
|
||||
}
|
||||
}
|
||||
|
||||
if (totalConsoleLogCount > 0) {
|
||||
log(
|
||||
"warn",
|
||||
`[ECC] Audit: ${totalConsoleLogCount} console.log statement(s) in ${filesWithConsoleLogs.length} file(s)`,
|
||||
)
|
||||
filesWithConsoleLogs.forEach((f) => log("warn", ` - ${f}`))
|
||||
log("warn", "[ECC] Remove console.log statements before committing")
|
||||
} else {
|
||||
log("info", "[ECC] Audit passed: No console.log statements found")
|
||||
}
|
||||
|
||||
// Desktop notification, best effort and never blocking. The V1 Windows
|
||||
// path opened a modal MessageBox on the server; that is replaced with a
|
||||
// fire-and-forget balloon tip, and every branch is detached.
|
||||
try {
|
||||
if (process.platform === "darwin") {
|
||||
await run("osascript", ["-e", 'display notification "Task completed!" with title "OpenCode ECC"'], {
|
||||
detached: true,
|
||||
}).catch(() => {})
|
||||
} else if (process.platform === "win32") {
|
||||
const ps =
|
||||
"$ni = New-Object System.Windows.Forms.NotifyIcon; $ni.Icon = [System.Drawing.SystemIcons]::Information; " +
|
||||
"$ni.Visible = $true; $ni.ShowBalloonTip('OpenCode ECC', 'Task completed!', 'Info'); " +
|
||||
"Start-Sleep -Seconds 5; $ni.Dispose()"
|
||||
await run(
|
||||
"powershell",
|
||||
["-NoProfile", "-WindowStyle", "Hidden", "-Command", `Add-Type -AssemblyName System.Windows.Forms; ${ps}`],
|
||||
{ detached: true },
|
||||
).catch(() => {})
|
||||
} else if (process.platform === "linux") {
|
||||
await run("notify-send", ["OpenCode ECC", "Task completed!"], { detached: true }).catch(() => {})
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("debug", `[ECC] Desktop notification failed: ${errorMessage}`)
|
||||
}
|
||||
|
||||
// Clear tracked files for next task
|
||||
editedFiles.clear()
|
||||
}
|
||||
|
||||
/** Session Deleted Hook (Equivalent to Claude Code SessionEnd hook). */
|
||||
const onSessionDeleted = async () => {
|
||||
if (!hookEnabled("session:end-marker", ["minimal", "standard", "strict"])) return
|
||||
log("info", "[ECC] Session ended - cleaning up")
|
||||
editedFiles.clear()
|
||||
changedFilesStore?.clearChanges?.()
|
||||
pendingToolChanges.clear()
|
||||
}
|
||||
|
||||
/** File Watcher Hook (OpenCode-only): keeps tracking in sync with external edits. */
|
||||
const onFileWatcherUpdated = async (event: { path: string; type: string }) => {
|
||||
let changeType: "added" | "modified" | "deleted" = "modified"
|
||||
if (event.type === "create" || event.type === "add") changeType = "added"
|
||||
else if (event.type === "delete" || event.type === "remove") changeType = "deleted"
|
||||
changedFilesStore?.recordChange?.(event.path, changeType)
|
||||
if (event.type === "change" && /\.(ts|tsx|js|jsx)$/.test(event.path)) {
|
||||
editedFiles.add(event.path)
|
||||
}
|
||||
}
|
||||
|
||||
/** Todo Updated Hook (OpenCode-only): logs progress. */
|
||||
const onTodoUpdated = async (event: { todos: Array<{ text?: string; done: boolean }> }) => {
|
||||
const todos = Array.isArray(event.todos) ? event.todos : []
|
||||
const completed = todos.filter((t) => t.done).length
|
||||
const total = todos.length
|
||||
if (total > 0) {
|
||||
log("info", `[ECC] Progress: ${completed}/${total} tasks completed`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shell Environment Hook (OpenCode-specific): inject ECC context into
|
||||
* shell commands. PROJECT_ROOT/PACKAGE_MANAGER/... are computed per call
|
||||
* because project marker files can appear after plugin init.
|
||||
*/
|
||||
const onShellEnv = async (_input: { cwd: string }, output: { env: Record<string, string> }) => {
|
||||
if (!output) return
|
||||
const env: Record<string, string> = {
|
||||
ECC_VERSION: getECCVersion(eccRoot, pluginDir),
|
||||
ECC_PLUGIN: "true",
|
||||
ECC_HOOK_PROFILE: currentProfile,
|
||||
ECC_DISABLED_HOOKS: process.env.ECC_DISABLED_HOOKS || "",
|
||||
PROJECT_ROOT: worktreePath,
|
||||
}
|
||||
|
||||
// Detect package manager (fs only: no shell probing, so this works on Windows).
|
||||
const lockfiles: Record<string, string> = {
|
||||
"bun.lockb": "bun",
|
||||
"pnpm-lock.yaml": "pnpm",
|
||||
"yarn.lock": "yarn",
|
||||
"package-lock.json": "npm",
|
||||
}
|
||||
for (const [lockfile, pm] of Object.entries(lockfiles)) {
|
||||
if (hasProjectFile(lockfile)) {
|
||||
env.PACKAGE_MANAGER = pm
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Detect languages
|
||||
const langDetectors: Record<string, string> = {
|
||||
"tsconfig.json": "typescript",
|
||||
"go.mod": "go",
|
||||
"pyproject.toml": "python",
|
||||
"Cargo.toml": "rust",
|
||||
"Package.swift": "swift",
|
||||
}
|
||||
const detected: string[] = []
|
||||
for (const [file, lang] of Object.entries(langDetectors)) {
|
||||
if (hasProjectFile(file)) {
|
||||
detected.push(lang)
|
||||
}
|
||||
}
|
||||
if (detected.length > 0) {
|
||||
env.DETECTED_LANGUAGES = detected.join(",")
|
||||
env.PRIMARY_LANGUAGE = detected[0]
|
||||
}
|
||||
|
||||
// resolve-ecc-root.js only probes ~/.claude and Claude Code's plugin
|
||||
// cache, so under OpenCode it fell back to ~/.claude and every command
|
||||
// carrying the inlined resolver failed to find its scripts. That resolver
|
||||
// reads CLAUDE_PLUGIN_ROOT first, so exporting the root here fixes them
|
||||
// through the mechanism ECC already provides -- rather than editing the
|
||||
// command files that embed the locator.
|
||||
//
|
||||
// Only set when a root actually exists, and never replace a root someone
|
||||
// else already chose: neither the process environment (set by the user)
|
||||
// nor `output.env` (set by an earlier plugin). The final merge below
|
||||
// overwrites output.env, so checking it only in `env` would clobber it.
|
||||
const rootAlreadySet = Boolean(
|
||||
(process.env.CLAUDE_PLUGIN_ROOT || "").trim() || (output.env?.CLAUDE_PLUGIN_ROOT || "").trim(),
|
||||
)
|
||||
if (eccRoot && !rootAlreadySet) {
|
||||
env.CLAUDE_PLUGIN_ROOT = eccRoot
|
||||
}
|
||||
|
||||
// OpenCode reads the supplied output object and ignores callback return values.
|
||||
output.env = { ...output.env, ...env }
|
||||
}
|
||||
|
||||
/** ECC context block preserved through compaction. */
|
||||
function buildCompactionContext(): string {
|
||||
const contextBlock = [
|
||||
"# ECC Context (preserve across compaction)",
|
||||
"",
|
||||
`## Active Plugin: ECC v${getECCVersion(eccRoot, pluginDir)}`,
|
||||
"- Hooks: file.edited, tool.execute.before/after, session.created/idle/deleted, shell.env, compacting, permission.ask",
|
||||
"- Tools: changed-files, dependency-analyzer",
|
||||
"",
|
||||
"## Key Principles",
|
||||
"- TDD: write tests first, 80%+ coverage",
|
||||
"- Immutability: never mutate, always return new copies",
|
||||
"- Security: validate inputs, no hardcoded secrets",
|
||||
"",
|
||||
]
|
||||
|
||||
// Include recently edited files
|
||||
if (editedFiles.size > 0) {
|
||||
contextBlock.push("## Recently Edited Files")
|
||||
for (const f of editedFiles) {
|
||||
contextBlock.push(`- ${f}`)
|
||||
}
|
||||
contextBlock.push("")
|
||||
}
|
||||
|
||||
return [
|
||||
contextBlock.join("\n"),
|
||||
"Focus on preserving: 1) Current task status and progress, 2) Key decisions made, 3) Files created/modified, 4) Remaining work items, 5) Any security concerns flagged. Discard: verbose tool outputs, intermediate exploration, redundant file listings.",
|
||||
].join("\n\n")
|
||||
}
|
||||
|
||||
/**
|
||||
* Session Compacting Hook (OpenCode-specific): append ECC context without
|
||||
* replacing the host (or an earlier plugin's) compaction prompt.
|
||||
*/
|
||||
const onSessionCompacting = async (
|
||||
_input: { sessionID: string },
|
||||
output: { context: string[]; prompt?: string },
|
||||
) => {
|
||||
const eccContext = buildCompactionContext()
|
||||
// OpenCode requires output assignment and skips context when a prompt is set.
|
||||
if (output && output.prompt !== undefined) {
|
||||
output.prompt = [output.prompt, eccContext].join("\n\n")
|
||||
} else if (output) {
|
||||
output.context = [...output.context, eccContext]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission Auto-Approve Hook (OpenCode-specific): auto-approve reads,
|
||||
* formatters, and test commands on top of the configured rules.
|
||||
*/
|
||||
const onPermissionAsk = async (event: PermissionEvent) => {
|
||||
log("info", `[ECC] Permission requested for: ${event.tool}`)
|
||||
|
||||
try {
|
||||
// Handle both string args and object args with command property
|
||||
let cmd: string
|
||||
if (typeof event.args === "string") {
|
||||
cmd = event.args
|
||||
} else if (event.args && typeof event.args === "object") {
|
||||
cmd = String((event.args as Record<string, unknown>).command || "")
|
||||
} else {
|
||||
cmd = String(event.args || "")
|
||||
}
|
||||
if (cmd) {
|
||||
log("debug", `[ECC] Permission resource: ${cmd.slice(0, 120)}`)
|
||||
}
|
||||
|
||||
// Auto-approve: read/search tools
|
||||
if (["read", "glob", "grep", "search", "list"].includes(event.tool)) {
|
||||
log("debug", `[ECC] Auto-approved read-only tool: ${event.tool}`)
|
||||
return { approved: true, reason: "Read-only operation" }
|
||||
}
|
||||
|
||||
// T02: no shell-command auto-approval. A regex over the leading
|
||||
// characters of a free-form shell string is not a safe allow-list —
|
||||
// cmd/powershell argument modes, quoting, and subshell syntax can all
|
||||
// defeat it (e.g. `prettier --write x.ts & curl evil.co`, or PowerShell
|
||||
// `(prettier)`). Formatter and test commands fall through to the user's
|
||||
// permission system instead.
|
||||
|
||||
// Everything else: let user decide
|
||||
log("debug", `[ECC] Permission requires user approval: ${event.tool}`)
|
||||
return { approved: undefined }
|
||||
} catch (error: unknown) {
|
||||
// Error in permission handling - log and deny for safety
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("error", `[ECC] Permission handling error for ${event.tool}: ${errorMessage}`)
|
||||
return { approved: false, reason: `Error: ${errorMessage}` }
|
||||
}
|
||||
}
|
||||
|
||||
// V1 custom tool record: definitions load lazily; a broken tools/ install
|
||||
// surfaces only when a tool is actually invoked, never at startup.
|
||||
const tool: Record<string, unknown> = {}
|
||||
for (const name of ["changed-files", "dependency-analyzer"]) {
|
||||
try {
|
||||
const definition = await loadToolModule(name, pluginDir)
|
||||
tool[name] = definition
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log("warn", `[ECC] Custom tool ${name} disabled: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
const hooks: Record<string, any> = {
|
||||
"file.edited": onFileEdited,
|
||||
"tool.execute.before": onToolBefore,
|
||||
"tool.execute.after": onToolAfter,
|
||||
"session.created": onSessionCreated,
|
||||
"session.idle": onSessionIdle,
|
||||
"session.deleted": onSessionDeleted,
|
||||
"file.watcher.updated": onFileWatcherUpdated,
|
||||
"todo.updated": onTodoUpdated,
|
||||
"shell.env": onShellEnv,
|
||||
"experimental.session.compacting": onSessionCompacting,
|
||||
"permission.ask": onPermissionAsk,
|
||||
}
|
||||
|
||||
return { hooks, tool, buildCompactionContext, worktreePath }
|
||||
}
|
||||
+100
-108
@@ -150,86 +150,76 @@ def iter_hook_commands(settings):
|
||||
yield event, group['command']
|
||||
|
||||
|
||||
def audit_hook_wiring(settings, project_dir, user_home, env, stats=None):
|
||||
"""Verify every script referenced by a hook command exists on disk.
|
||||
def _updated_counts(stats, **deltas):
|
||||
"""Return fresh counts without changing the caller's dictionary."""
|
||||
return {**stats, **{key: stats.get(key, 0) + value
|
||||
for key, value in deltas.items() if value}}
|
||||
|
||||
A referenced-but-missing script is a fact, not a heuristic — this is the
|
||||
core deterministic check. Never prints the full command (may hold secrets);
|
||||
only the missing path is reported.
|
||||
|
||||
Anything this monitor declines to judge is counted in `stats` so `--check`
|
||||
can show it: a token carrying a placeholder we cannot resolve, a
|
||||
single-quoted one, a substituted path outside the audited roots, a command
|
||||
that could not be parsed at all, and a relative path satisfied only by a
|
||||
root other than the project. Silence is the right verdict for all of them —
|
||||
claiming a script is missing when the real problem is that we could not
|
||||
parse the command is what produces a false-warning flood, and a monitor
|
||||
whose WARN line is always red trains users to ignore it. Silence that is
|
||||
also invisible is not a verdict at all, which is what the counts are for.
|
||||
def _command_counts(stats, unparsed, bodies, too_deep):
|
||||
"""Count each reason a command was only partially audited."""
|
||||
return _updated_counts(
|
||||
stats, bodies=bodies, skipped=int(unparsed) + int(too_deep),
|
||||
unparsed=int(unparsed), too_deep=int(too_deep),
|
||||
)
|
||||
|
||||
Args:
|
||||
settings (`dict`): A parsed settings.json.
|
||||
project_dir (`str`): Absolute project directory.
|
||||
user_home (`str`): Absolute user home directory.
|
||||
env (`dict`): Supported placeholder replacements.
|
||||
stats (`dict`): Optional counter dictionary, incremented in place.
|
||||
|
||||
Returns:
|
||||
`list[str]`: One finding per missing script.
|
||||
"""
|
||||
def _audit_hook_tokens(event, tokens, context, seen, stats):
|
||||
"""Resolve and deduplicate tokens, returning findings and fresh counts."""
|
||||
findings = []
|
||||
seen = set()
|
||||
roots = audit_roots(project_dir, user_home, env)
|
||||
project_norm = _normalize(project_dir)
|
||||
for token, single_quoted in tokens:
|
||||
paths, status, relative = resolve_script_path(
|
||||
token, context['project_dir'], context['user_home'], context['env'],
|
||||
context['roots'], single_quoted,
|
||||
)
|
||||
# Identity uses the judged path, rather than its placeholder spelling.
|
||||
key = (event, _dedupe_key(status, paths, token))
|
||||
if key in seen:
|
||||
continue
|
||||
seen = seen | {key}
|
||||
if status == AUDIT_SKIP:
|
||||
stats = _updated_counts(stats, skipped=1)
|
||||
continue
|
||||
if status == AUDIT_OK and relative \
|
||||
and _normalize(paths[0]) != context['project_norm']:
|
||||
stats = _updated_counts(stats, other_root=1)
|
||||
if status == AUDIT_MISSING:
|
||||
findings = findings + [
|
||||
f'hook "{event}" references missing script: {_clip(token)}'
|
||||
]
|
||||
return findings, seen, stats
|
||||
|
||||
|
||||
def audit_hook_wiring(settings, project_dir, user_home, env, stats=None):
|
||||
"""Return (missing-script findings, updated counts), preserving inputs.
|
||||
|
||||
Unparseable commands and unresolvable paths are counted, never guessed.
|
||||
Relative paths are checked against every audited root; a path found only
|
||||
outside the project is healthy but disclosed in the returned counts.
|
||||
"""
|
||||
findings, seen = [], set()
|
||||
stats = dict(stats or {})
|
||||
context = {
|
||||
'project_dir': project_dir, 'user_home': user_home, 'env': env,
|
||||
'roots': audit_roots(project_dir, user_home, env),
|
||||
'project_norm': _normalize(project_dir),
|
||||
}
|
||||
for event, command in iter_hook_commands(settings):
|
||||
tokens, unparsed, bodies, too_deep = scan_command(command)
|
||||
if stats is not None:
|
||||
if bodies:
|
||||
stats['bodies'] = stats.get('bodies', 0) + bodies
|
||||
if too_deep:
|
||||
stats['skipped'] = stats.get('skipped', 0) + 1
|
||||
stats['too_deep'] = stats.get('too_deep', 0) + 1
|
||||
stats = _command_counts(stats, unparsed, bodies, too_deep)
|
||||
if unparsed:
|
||||
if stats is not None:
|
||||
stats['skipped'] = stats.get('skipped', 0) + 1
|
||||
stats['unparsed'] = stats.get('unparsed', 0) + 1
|
||||
continue
|
||||
for token, single_quoted in tokens:
|
||||
paths, status, relative = resolve_script_path(
|
||||
token, project_dir, user_home, env, roots, single_quoted,
|
||||
)
|
||||
# Dedupe on the path we judged, not on the spelling: one missing
|
||||
# file referenced as both ${ROOT}/x.py and $ROOT/x.py is one
|
||||
# problem, and the two spellings are what a settings file drifts
|
||||
# into when a hook block is rewritten.
|
||||
key = (event, _dedupe_key(status, paths, token))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
if status == AUDIT_SKIP:
|
||||
if stats is not None:
|
||||
stats['skipped'] = stats.get('skipped', 0) + 1
|
||||
continue
|
||||
if status == AUDIT_OK and relative and stats is not None \
|
||||
and _normalize(paths[0]) != project_norm:
|
||||
# A relative path satisfied only by a root other than the
|
||||
# project. Judged healthy, but a project-scoped hook that is
|
||||
# genuinely broken looks exactly like this, so the count is
|
||||
# what keeps the trade visible.
|
||||
stats['other_root'] = stats.get('other_root', 0) + 1
|
||||
if status == AUDIT_MISSING:
|
||||
findings.append(
|
||||
'hook "%s" references missing script: %s'
|
||||
% (event, _clip(token))
|
||||
)
|
||||
return findings
|
||||
added, seen, stats = _audit_hook_tokens(
|
||||
event, tokens, context, seen, stats)
|
||||
findings = findings + added
|
||||
return findings, stats
|
||||
|
||||
|
||||
def _clip(token):
|
||||
"""A path short enough to read, never a whole hook command."""
|
||||
if len(token) <= MAX_REPORTED_PATH:
|
||||
return token
|
||||
return token[:MAX_REPORTED_PATH] + '... (%d chars total)' % len(token)
|
||||
return token[:MAX_REPORTED_PATH] + f'... ({len(token)} chars total)'
|
||||
|
||||
|
||||
def _dedupe_key(status, paths, raw):
|
||||
@@ -323,21 +313,22 @@ def read_settings(path, stats=None, label='settings'):
|
||||
first of those is health.
|
||||
|
||||
Returns:
|
||||
`tuple[dict | None, bool]`: The parsed settings, and whether the file
|
||||
existed but could not be parsed.
|
||||
`tuple[dict | None, bool, dict]`: Parsed settings, whether the file
|
||||
existed but could not be parsed, and updated counts. Inputs stay unchanged.
|
||||
"""
|
||||
stats = dict(stats or {})
|
||||
if not os.path.exists(path):
|
||||
return None, False
|
||||
return None, False, stats
|
||||
parsed = read_json(path)
|
||||
# Readable JSON that is not a settings object is the same failure as
|
||||
# unparseable JSON: there are hooks in there we cannot see.
|
||||
if parsed is None or not isinstance(parsed, dict) \
|
||||
or ('hooks' in parsed and not isinstance(parsed['hooks'], dict)):
|
||||
if stats is not None:
|
||||
stats['unreadable'] = stats.get('unreadable', 0) + 1
|
||||
stats['unreadable_names'] = stats.get('unreadable_names', []) + [label]
|
||||
return None, True
|
||||
return parsed, False
|
||||
counts = _updated_counts(stats, unreadable=1)
|
||||
counts = {**counts, 'unreadable_names':
|
||||
stats.get('unreadable_names', []) + [label]}
|
||||
return None, True, counts
|
||||
return parsed, False, stats
|
||||
|
||||
|
||||
def hook_sources(user_home, project_dir, env):
|
||||
@@ -376,44 +367,46 @@ def audit_hook_settings(user_home, project_dir, stats=None):
|
||||
"""Run the hook-wiring audit over every hook source.
|
||||
|
||||
Returns:
|
||||
`tuple[dict, list[str]]`: The placeholder environment, and findings.
|
||||
`tuple[dict, list[str], dict]`: Placeholder environment, findings,
|
||||
and updated counts. Caller-owned inputs are preserved.
|
||||
"""
|
||||
env = placeholder_env(project_dir, user_home)
|
||||
findings = []
|
||||
stats = dict(stats or {})
|
||||
claude_dir = claude_data_dir(user_home)
|
||||
# Each source may be absent or malformed — each is handled independently
|
||||
# and never blocks. A malformed file yields no findings (nothing to audit)
|
||||
# and is counted, rather than a crash or a silent clean verdict.
|
||||
for label, path in hook_sources(user_home, project_dir, env):
|
||||
settings, _ = read_settings(path, stats, label)
|
||||
settings, _, stats = read_settings(path, stats, label)
|
||||
if settings is not None:
|
||||
findings.extend(
|
||||
audit_hook_wiring(settings, project_dir, user_home, env, stats)
|
||||
)
|
||||
if stats is not None and env.get(PLUGIN_ROOT_ENV):
|
||||
stats['plugin_root'] = env[PLUGIN_ROOT_ENV]
|
||||
if stats is not None and os.environ.get('CLAUDE_CONFIG_DIR'):
|
||||
stats['claude_dir'] = claude_dir
|
||||
return env, findings
|
||||
added, stats = audit_hook_wiring(
|
||||
settings, project_dir, user_home, env, stats)
|
||||
findings = findings + added
|
||||
if env.get(PLUGIN_ROOT_ENV):
|
||||
stats = {**stats, 'plugin_root': env[PLUGIN_ROOT_ENV]}
|
||||
if os.environ.get('CLAUDE_CONFIG_DIR'):
|
||||
stats = {**stats, 'claude_dir': claude_dir}
|
||||
return env, findings, stats
|
||||
|
||||
|
||||
def run_startup_audit(user_home, project_dir, stats=None):
|
||||
"""SessionStart audit: hook wiring + rule references + guard staleness."""
|
||||
"""Return startup findings and counts without changing caller inputs."""
|
||||
claude_dir = claude_data_dir(user_home)
|
||||
_, findings = audit_hook_settings(user_home, project_dir, stats)
|
||||
findings.extend(audit_rule_references(project_dir))
|
||||
findings.extend(audit_guard_staleness(claude_dir))
|
||||
return findings
|
||||
_, findings, stats = audit_hook_settings(user_home, project_dir, stats)
|
||||
findings = findings + audit_rule_references(project_dir)
|
||||
return findings + audit_guard_staleness(claude_dir), stats
|
||||
|
||||
|
||||
def run_hook_wiring_audit(user_home, project_dir, stats=None):
|
||||
"""Just the hook-wiring half of the audit — the PreToolUse path."""
|
||||
return audit_hook_settings(user_home, project_dir, stats)[1]
|
||||
"""Return hook-wiring findings and updated counts for PreToolUse."""
|
||||
_, findings, counts = audit_hook_settings(user_home, project_dir, stats)
|
||||
return findings, counts
|
||||
|
||||
|
||||
def startup_mode():
|
||||
user_home, project_dir = resolve_dirs()
|
||||
findings = run_startup_audit(user_home, project_dir)
|
||||
findings, _ = run_startup_audit(user_home, project_dir)
|
||||
for finding in findings:
|
||||
print(WARN_PREFIX + finding)
|
||||
# Non-blocking by contract: never gate on process monitoring.
|
||||
@@ -443,7 +436,7 @@ def pretool_mode():
|
||||
drain_stdin()
|
||||
|
||||
user_home, project_dir = resolve_dirs()
|
||||
findings = run_hook_wiring_audit(user_home, project_dir)
|
||||
findings, _ = run_hook_wiring_audit(user_home, project_dir)
|
||||
|
||||
# PreToolUse keeps stdout clean — warnings go to stderr so a non-empty
|
||||
# stdout can never be misread as a block/allow decision.
|
||||
@@ -455,8 +448,7 @@ def pretool_mode():
|
||||
def check_mode():
|
||||
"""Manual tri-color overview. Read-only."""
|
||||
user_home, project_dir = resolve_dirs()
|
||||
stats = {}
|
||||
findings = run_startup_audit(user_home, project_dir, stats)
|
||||
findings, stats = run_startup_audit(user_home, project_dir)
|
||||
unreadable = stats.get('unreadable', 0)
|
||||
if findings:
|
||||
print('config-health: [warn] attention')
|
||||
@@ -480,38 +472,38 @@ def _print_audit_counts(stats):
|
||||
# is invisible cannot be fixed. Printed here only, never per tool call.
|
||||
skipped = stats.get('skipped', 0)
|
||||
if skipped:
|
||||
print('config-health: [info] {} hook path(s) not audited — unresolved '
|
||||
print(f'config-health: [info] {skipped} hook path(s) not audited — unresolved '
|
||||
'or single-quoted placeholder, a substituted path outside the '
|
||||
'audited roots, or a command that could not be parsed'
|
||||
.format(skipped))
|
||||
)
|
||||
unparsed = stats.get('unparsed', 0)
|
||||
if unparsed:
|
||||
print('config-health: [info] {} hook command(s) have an unclosed quote '
|
||||
'and were not parsed at all'.format(unparsed))
|
||||
print(f'config-health: [info] {unparsed} hook command(s) have an unclosed quote '
|
||||
'and were not parsed at all')
|
||||
unreadable = stats.get('unreadable', 0)
|
||||
if unreadable:
|
||||
names = ', '.join(stats.get('unreadable_names', []))
|
||||
print('config-health: [warn] {} settings file(s) could not be read '
|
||||
'({}) — malformed JSON, a read error, or not an object. Their '
|
||||
print(f'config-health: [warn] {unreadable} settings file(s) could not be read '
|
||||
f'({names}) — malformed JSON, a read error, or not an object. Their '
|
||||
'hooks were NOT audited; nothing below is a verdict about them.'
|
||||
.format(unreadable, names))
|
||||
)
|
||||
too_deep = stats.get('too_deep', 0)
|
||||
if too_deep:
|
||||
print('config-health: [info] {} hook command(s) nested sh -c deeper '
|
||||
'than {} levels; the rest was still audited'
|
||||
.format(too_deep, MAX_PAYLOAD_DEPTH))
|
||||
print(f'config-health: [info] {too_deep} hook command(s) nested sh -c deeper '
|
||||
f'than {MAX_PAYLOAD_DEPTH} levels; the rest was still audited'
|
||||
)
|
||||
bodies = stats.get('bodies', 0)
|
||||
if bodies:
|
||||
print('config-health: [info] {} interpreter program body/bodies were '
|
||||
print(f'config-health: [info] {bodies} interpreter program body/bodies were '
|
||||
'skipped unjudged — a node -e or python -c body is source in '
|
||||
'another language, so a file named inside one is not checked'
|
||||
.format(bodies))
|
||||
)
|
||||
other_root = stats.get('other_root', 0)
|
||||
if other_root:
|
||||
print('config-health: [info] {} relative hook path(s) were satisfied '
|
||||
print(f'config-health: [info] {other_root} relative hook path(s) were satisfied '
|
||||
'by the user home or plugin root, not the project — a broken '
|
||||
'project-scoped hook is indistinguishable from a healthy '
|
||||
'plugin one here'.format(other_root))
|
||||
'plugin one here')
|
||||
claude_dir = stats.get('claude_dir')
|
||||
if claude_dir:
|
||||
# Name the non-default root so a settings file the harness is not
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import re
|
||||
|
||||
|
||||
WARN_PREFIX = '[config-health] WARN: '
|
||||
|
||||
# Sessions of rule-health history to look back for guard staleness.
|
||||
@@ -44,7 +43,7 @@ PLACEHOLDER_RE = re.compile(r'\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?')
|
||||
# Interpreters whose -e / -c argument is a program body rather than a script
|
||||
# path. The two kinds of payload are not the same thing:
|
||||
# - a shell's -c payload is a command line, so it is scanned again as one
|
||||
# - a node/python -e payload is source in another language, where a string
|
||||
# - a node -e or python -c payload is source in another language, where a string
|
||||
# is a string: p.join(r,'scripts/hooks/x.js') is assembled at runtime and
|
||||
# is not a file the shell will open
|
||||
SHELL_INTERPRETERS = frozenset(('sh', 'bash', 'zsh'))
|
||||
|
||||
@@ -103,7 +103,7 @@ def _is_interpreter(word):
|
||||
return name in INTERPRETERS
|
||||
|
||||
|
||||
def _is_program_flag(word, shell):
|
||||
def _is_program_flag(word, interpreter):
|
||||
"""Whether `word` is an option whose next word is a program body.
|
||||
|
||||
Covers the long spellings, the plain short ones, and the bundled short
|
||||
@@ -114,11 +114,14 @@ def _is_program_flag(word, shell):
|
||||
warning: `sh -e script.sh` is errexit, not a program body, so treating `-e`
|
||||
as one hides the script the shell will run.
|
||||
"""
|
||||
name = interpreter.replace('\\', '/').rsplit('/', 1)[-1].lower()
|
||||
shell = name in SHELL_INTERPRETERS
|
||||
python = name in ('python', 'python3', 'pythonw', 'py')
|
||||
if word in PROGRAM_FLAG_LONG:
|
||||
return True
|
||||
return (shell and word == '--command') or (not shell and not python and word == '--eval')
|
||||
if word.startswith('--') or not word.startswith('-') or len(word) < 2:
|
||||
return False
|
||||
wanted = 'c' if shell else 'e'
|
||||
wanted = 'c' if shell or python else 'e'
|
||||
return wanted in word[1:]
|
||||
|
||||
|
||||
@@ -147,28 +150,19 @@ def scan_command(command, depth=0):
|
||||
words = _split_shell_words(command)
|
||||
if words is None:
|
||||
return [], True, 0, False
|
||||
tokens = []
|
||||
bodies = 0
|
||||
too_deep = False
|
||||
index = 0
|
||||
interpreter = None
|
||||
option_arg = False
|
||||
tokens, bodies, too_deep = [], 0, False
|
||||
index, interpreter, option_arg = 0, None, False
|
||||
while index < len(words):
|
||||
word, quoted, single = words[index]
|
||||
# A separator only separates when the shell can see it. Inside quotes
|
||||
# it is part of the name, and `python3 "weird;name.py"` is a file.
|
||||
if not quoted and _is_separator(word):
|
||||
interpreter = None
|
||||
option_arg = False
|
||||
interpreter, option_arg = None, False
|
||||
index += 1
|
||||
continue
|
||||
if _is_interpreter(word):
|
||||
interpreter = word
|
||||
option_arg = False
|
||||
interpreter, option_arg = word, False
|
||||
index += 1
|
||||
continue
|
||||
if interpreter and _is_program_flag(
|
||||
word, _is_shell_interpreter(interpreter)):
|
||||
if interpreter and _is_program_flag(word, interpreter):
|
||||
(index, added, stop, unparsed,
|
||||
deep, reset) = _scan_program_body(
|
||||
interpreter, quoted, words, index, depth, tokens)
|
||||
@@ -179,7 +173,6 @@ def scan_command(command, depth=0):
|
||||
return tokens, unparsed, bodies, too_deep
|
||||
continue
|
||||
if interpreter and word.startswith('-') and len(word) > 1:
|
||||
# An interpreter option; some take the next word as their value.
|
||||
option_arg = not quoted and word in OPTION_TAKES_NEXT_WORD
|
||||
index += 1
|
||||
continue
|
||||
|
||||
@@ -78,14 +78,43 @@ function normalizeNeighbors(value) {
|
||||
return { neighbors, neighborsDigest };
|
||||
}
|
||||
|
||||
// Provider skill directories may legitimately be symlinks. Resolve that
|
||||
// mapping once, then bind type/size checks and all reads to one open file.
|
||||
// A raced FIFO must not block opening, and a newly substituted final symlink
|
||||
// must not be followed where the platform supports O_NOFOLLOW.
|
||||
function readBoundedBytes(file, maxBytes) {
|
||||
const canonical = fs.realpathSync(file);
|
||||
const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0);
|
||||
const fd = fs.openSync(canonical, flags);
|
||||
try {
|
||||
const before = fs.fstatSync(fd, { bigint: true });
|
||||
if (!before.isFile() || before.size > BigInt(maxBytes)) {
|
||||
throw new Error(`Neighbor file must be a regular file of at most ${maxBytes} bytes`);
|
||||
}
|
||||
const bytes = Buffer.alloc(Number(before.size) + 1);
|
||||
let length = 0;
|
||||
while (length < bytes.length) {
|
||||
const count = fs.readSync(fd, bytes, length, Math.min(64 * 1024, bytes.length - length), null);
|
||||
if (count === 0) break;
|
||||
length += count;
|
||||
}
|
||||
const after = fs.fstatSync(fd, { bigint: true });
|
||||
const sameFile = stat => stat.isFile() && stat.dev === before.dev && stat.ino === before.ino
|
||||
&& stat.size === before.size && stat.mtimeNs === before.mtimeNs && stat.ctimeNs === before.ctimeNs;
|
||||
if (length > maxBytes || BigInt(length) !== before.size || !sameFile(after)
|
||||
|| fs.realpathSync(file) !== canonical || !sameFile(fs.statSync(canonical, { bigint: true }))) {
|
||||
throw new Error('Neighbor file changed while reading');
|
||||
}
|
||||
return bytes.subarray(0, length);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
/** Read and validate a neighbor snapshot file written by discovery or by hand. */
|
||||
function readNeighborSnapshot(file) {
|
||||
const absolute = path.resolve(file);
|
||||
const stat = fs.statSync(absolute);
|
||||
if (!stat.isFile() || stat.size > MAX_SNAPSHOT_BYTES) {
|
||||
throw new Error(`Neighbor snapshot must be a file of at most ${MAX_SNAPSHOT_BYTES} bytes`);
|
||||
}
|
||||
const bytes = fs.readFileSync(absolute);
|
||||
const bytes = readBoundedBytes(absolute, MAX_SNAPSHOT_BYTES);
|
||||
const text = bytes.toString('utf8');
|
||||
if (!Buffer.from(text).equals(bytes) || text.includes('\0')) throw new Error('Neighbor snapshot must be UTF-8 JSON without NUL');
|
||||
let value;
|
||||
@@ -156,18 +185,14 @@ function rankCompanions(index, query, neighbors, { minBm25, minTerms, minAnchorT
|
||||
|
||||
function readBoundedJson(file) {
|
||||
try {
|
||||
const stat = fs.statSync(file);
|
||||
if (!stat.isFile() || stat.size > MAX_JSON_BYTES) return null;
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
return JSON.parse(readBoundedBytes(file, MAX_JSON_BYTES).toString('utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function frontmatter(file) {
|
||||
const stat = fs.statSync(file);
|
||||
if (!stat.isFile() || stat.size > MAX_SKILL_FILE_BYTES) return null;
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
const text = readBoundedBytes(file, MAX_SKILL_FILE_BYTES).toString('utf8');
|
||||
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
|
||||
// Only name and description are needed; a frontmatter block this large is
|
||||
// not a skill header, so it is skipped before YAML parsing.
|
||||
@@ -218,9 +243,11 @@ const comparable = text => String(text || '').trim().replace(/\s+/g, ' ');
|
||||
// (unreadable or incomplete) skill, or no SKILL.md at all.
|
||||
function readSkillSummary(directory, eccCopies) {
|
||||
const file = path.join(directory, 'SKILL.md');
|
||||
if (!fs.existsSync(file)) return { kind: 'missing' };
|
||||
let meta;
|
||||
try { meta = frontmatter(file); } catch { meta = null; }
|
||||
try { meta = frontmatter(file); } catch (error) {
|
||||
if (error.code === 'ENOENT') return { kind: 'missing' };
|
||||
meta = null;
|
||||
}
|
||||
const name = meta && typeof meta.name === 'string' && meta.name.trim() ? meta.name.trim() : path.basename(directory);
|
||||
const description = meta && typeof meta.description === 'string' ? comparable(meta.description) : '';
|
||||
if (!description || Buffer.byteLength(name) > MAX_NAME_BYTES || CONTROL.test(name) || CONTROL.test(description)) {
|
||||
|
||||
@@ -14,6 +14,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
SCRIPT,
|
||||
PYTHON,
|
||||
test,
|
||||
makeFixture,
|
||||
@@ -38,6 +39,47 @@ function runTests() {
|
||||
|
||||
// --- a blind spot nobody can see is not a health check -------------------
|
||||
|
||||
t('audit helpers return updated counts without changing caller-owned state', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, '{ malformed');
|
||||
const source = String.raw`
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
sys.path.insert(0, os.path.dirname(sys.argv[1]))
|
||||
spec = importlib.util.spec_from_file_location('config_health_contract', sys.argv[1])
|
||||
monitor = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(monitor)
|
||||
project, home = sys.argv[2:4]
|
||||
seed = {'bodies': 2, 'unreadable_names': ['existing']}
|
||||
before = copy.deepcopy(seed)
|
||||
settings = {'hooks': {'PreToolUse': [{'command': 'python3 -c "path = \'unused.js\'"'}]}}
|
||||
settings_before = copy.deepcopy(settings)
|
||||
findings, updated = monitor.audit_hook_wiring(settings, project, home, {}, seed)
|
||||
assert findings == [] and updated['bodies'] == 3
|
||||
assert seed == before and settings == settings_before
|
||||
assert updated is not seed
|
||||
parsed, unreadable, updated = monitor.read_settings(os.path.join(home, '.claude', 'settings.json'), seed, 'user')
|
||||
assert parsed is None and unreadable and updated['unreadable'] == 1
|
||||
assert updated['unreadable_names'] == ['existing', 'user']
|
||||
assert seed == before and updated['unreadable_names'] is not seed['unreadable_names']
|
||||
for audit in (monitor.audit_hook_settings, monitor.run_startup_audit, monitor.run_hook_wiring_audit):
|
||||
result = audit(home, project, seed)
|
||||
assert seed == before and result[-1] is not seed
|
||||
assert result[-1]['unreadable'] == 1
|
||||
print(json.dumps({'unchanged': True, 'body_count': 3, 'unreadable_count': 1}))
|
||||
`;
|
||||
const result = spawnSync(PYTHON, ['-c', source, SCRIPT, fx.proj, fx.home], {
|
||||
encoding: 'utf8', env: { ...process.env, CLAUDE_CONFIG_DIR: '' },
|
||||
});
|
||||
assert.strictEqual(result.status, 0, result.stderr);
|
||||
assert.deepStrictEqual(JSON.parse(result.stdout), {
|
||||
unchanged: true, body_count: 3, unreadable_count: 1,
|
||||
});
|
||||
});
|
||||
|
||||
t('--check reports how many hook paths it did not audit', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('python3 "${CLAUDE_ENV_FILE}/hooks/x.py"'));
|
||||
@@ -113,6 +155,26 @@ function runTests() {
|
||||
}
|
||||
});
|
||||
|
||||
t('Python -c bodies are unjudged source while real following scripts remain audited', () => {
|
||||
const fx = makeFixture();
|
||||
for (const command of [
|
||||
`python3 -c "path = 'unused.js'"; python3 .claude/scripts/real-missing.py`,
|
||||
`python -u -c "path = 'unused.js'"; node .claude/scripts/real-missing.py`,
|
||||
`py -c"path = 'unused.js'"; python3 .claude/scripts/real-missing.py`,
|
||||
]) {
|
||||
writeSettings(fx.home, ONE_HOOK(command));
|
||||
for (const mode of ['--startup', '--pretool', '--check']) {
|
||||
const result = run(mode, fx);
|
||||
const output = result.stdout + result.stderr;
|
||||
assert.strictEqual(result.status, 0);
|
||||
assert.ok(!output.includes('unused.js'), `Python body leaked a false path: ${output}`);
|
||||
assert.ok(output.includes('real-missing.py'), `real script was not audited: ${output}`);
|
||||
if (mode === '--check') assert.match(output, /1 interpreter program body/);
|
||||
if (mode === '--pretool') assert.strictEqual(result.stdout, '');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
t('an unclosed quote is skipped, counted, and reported by --check', () => {
|
||||
const fx = makeFixture();
|
||||
writeSettings(fx.home, ONE_HOOK('python3 ".claude/scripts/ghost.py --start'));
|
||||
|
||||
@@ -356,9 +356,24 @@ if (process.platform === 'win32') {
|
||||
].join('\r\n'), 'utf8');
|
||||
|
||||
const invocation = hook.getLinterInvocation(command, ['100% ready.js', '!important!.js'], 'win32');
|
||||
// The fixture runs only cmd built-ins. Do not inherit unrelated launcher
|
||||
// variables or helper environments from other cases into this process.
|
||||
const tokens = {
|
||||
ECC_LINTER_TOKEN_0: command,
|
||||
ECC_LINTER_TOKEN_1: '100% ready.js',
|
||||
ECC_LINTER_TOKEN_2: '!important!.js'
|
||||
};
|
||||
for (const [name, value] of Object.entries(tokens)) {
|
||||
assert.strictEqual(invocation.options.env[name], value);
|
||||
}
|
||||
const result = spawnSync('cmd.exe', invocation.args, {
|
||||
...invocation.options,
|
||||
cwd: repoDir
|
||||
encoding: 'utf8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
timeout: 15000,
|
||||
cwd: repoDir,
|
||||
env: tokens
|
||||
});
|
||||
|
||||
assert.strictEqual(result.status, 0, result.stderr || result.error?.message);
|
||||
|
||||
@@ -471,3 +471,164 @@ test('the shipped registry keeps ECC\'s selection and lists the matching install
|
||||
companions, query);
|
||||
}
|
||||
});
|
||||
|
||||
// Swap/grow the checked file at a deterministic metadata/read boundary. Track
|
||||
// both path and descriptor metadata so this reproduces the original path race
|
||||
// as well as exercising the repaired descriptor reader.
|
||||
function withMetadataRace(file, mutate, action) {
|
||||
const canonical = fs.realpathSync(file);
|
||||
const original = { openSync: fs.openSync, statSync: fs.statSync, fstatSync: fs.fstatSync };
|
||||
const descriptors = new Set();
|
||||
let changed = false;
|
||||
const change = () => { if (!changed) { changed = true; mutate(); } };
|
||||
fs.openSync = function (target, ...args) {
|
||||
const fd = original.openSync.call(fs, target, ...args);
|
||||
if (target === canonical) descriptors.add(fd);
|
||||
return fd;
|
||||
};
|
||||
fs.statSync = function (target, ...args) {
|
||||
const result = original.statSync.call(fs, target, ...args);
|
||||
if (target === canonical) change();
|
||||
return result;
|
||||
};
|
||||
fs.fstatSync = function (fd, ...args) {
|
||||
const result = original.fstatSync.call(fs, fd, ...args);
|
||||
if (descriptors.has(fd)) change();
|
||||
return result;
|
||||
};
|
||||
try { action(); assert.equal(changed, true, 'the fixture exercised the metadata race'); }
|
||||
finally { Object.assign(fs, original); }
|
||||
}
|
||||
|
||||
test('snapshot rejects pathname replacement after validation instead of reading the replacement', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-neighbor-race-'));
|
||||
try {
|
||||
const file = path.join(dir, 'neighbors.json');
|
||||
fs.writeFileSync(file, JSON.stringify([userSkill]));
|
||||
withMetadataRace(file, () => {
|
||||
fs.renameSync(file, `${file}.original`);
|
||||
fs.writeFileSync(file, JSON.stringify([{ ...userSkill, name: 'replacement' }]));
|
||||
}, () => assert.throws(() => readNeighborSnapshot(file), /changed while reading/));
|
||||
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('snapshot enforces its byte ceiling when a checked file grows before reading', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-neighbor-growth-'));
|
||||
try {
|
||||
const file = path.join(dir, 'neighbors.json');
|
||||
fs.writeFileSync(file, JSON.stringify([userSkill]));
|
||||
withMetadataRace(file, () => fs.appendFileSync(file, ' '.repeat(4 * 1024 * 1024)),
|
||||
() => assert.throws(() => readNeighborSnapshot(file), /changed while reading/));
|
||||
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('discovery skips plugin configuration that grows beyond its bound after validation', () => withFixture(repoRoot => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-neighbor-config-race-'));
|
||||
try {
|
||||
const config = path.join(home, '.claude');
|
||||
const plugin = path.join(home, 'plugin');
|
||||
skill(plugin, 'skills/extra', 'extra', 'Plugin configuration must be bounded.');
|
||||
write(config, 'plugins/installed_plugins.json', JSON.stringify({ plugins: {
|
||||
'extra@market': [{ scope: 'user', installPath: plugin }] } }));
|
||||
write(config, 'settings.json', '{}');
|
||||
const file = path.join(config, 'settings.json');
|
||||
withMetadataRace(file, () => fs.writeFileSync(file,
|
||||
JSON.stringify({ enabledPlugins: { 'extra@market': true } }) + ' '.repeat(1024 * 1024)),
|
||||
() => assert.deepEqual(discoverNeighborSkills({ repoRoot, target: 'claude', env: {}, home }).neighbors, []));
|
||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||
}));
|
||||
|
||||
test('discovery skips skill frontmatter whose file grows beyond its bound after validation', () => withFixture(repoRoot => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-neighbor-skill-race-'));
|
||||
try {
|
||||
const root = path.join(home, '.codex');
|
||||
skill(root, 'skills/growing', 'growing', 'The header looks valid but its file changes.');
|
||||
const file = path.join(root, 'skills/growing/SKILL.md');
|
||||
withMetadataRace(file, () => fs.appendFileSync(file, 'x'.repeat(256 * 1024)), () => {
|
||||
const result = discoverNeighborSkills({ repoRoot, target: 'codex', env: {}, home });
|
||||
assert.deepEqual(result.neighbors, []);
|
||||
assert.equal(result.skipped, 1);
|
||||
});
|
||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||
}));
|
||||
|
||||
test('descriptor reads retain legitimate provider skill and snapshot symlinks', t => withFixture(repoRoot => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-neighbor-links-'));
|
||||
try {
|
||||
const root = path.join(home, '.codex');
|
||||
const linked = path.join(home, 'shared');
|
||||
skill(linked, 'linked-skill', 'linked-skill', 'A legitimate separately managed provider skill.');
|
||||
fs.mkdirSync(path.join(root, 'skills'), { recursive: true });
|
||||
try { fs.symlinkSync(path.join(linked, 'linked-skill'), path.join(root, 'skills/linked-skill'), 'dir'); }
|
||||
catch (error) {
|
||||
if (process.platform === 'win32' && ['EPERM', 'EACCES', 'ENOTSUP'].includes(error.code)) {
|
||||
t.skip('host does not permit symlink creation'); return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const result = discoverNeighborSkills({ repoRoot, target: 'codex', env: {}, home });
|
||||
assert.deepEqual(result.neighbors.map(item => item.name), ['linked-skill']);
|
||||
const snapshot = path.join(home, 'neighbors.json');
|
||||
fs.writeFileSync(snapshot, JSON.stringify([userSkill]));
|
||||
const alias = path.join(home, 'neighbors-link.json');
|
||||
fs.symlinkSync(snapshot, alias, 'file');
|
||||
assert.deepEqual(readNeighborSnapshot(alias).neighbors, normalizeNeighbors([userSkill]).neighbors);
|
||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||
}));
|
||||
|
||||
test('snapshot rejects non-regular files before reading their content', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-neighbor-type-'));
|
||||
try {
|
||||
assert.throws(() => readNeighborSnapshot(dir), /regular file|EISDIR|EPERM/);
|
||||
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('snapshot closes its descriptor on a read error and handles short reads', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-neighbor-fd-'));
|
||||
const file = path.join(dir, 'neighbors.json');
|
||||
fs.writeFileSync(file, JSON.stringify([userSkill]));
|
||||
const canonical = fs.realpathSync(file);
|
||||
const original = { openSync: fs.openSync, readSync: fs.readSync, closeSync: fs.closeSync };
|
||||
let selected;
|
||||
let closed = false;
|
||||
let failRead = true;
|
||||
fs.openSync = function (target, ...args) {
|
||||
const fd = original.openSync.call(fs, target, ...args);
|
||||
if (target === canonical) { selected = fd; closed = false; }
|
||||
return fd;
|
||||
};
|
||||
fs.readSync = function (fd, buffer, offset, length, position) {
|
||||
if (fd === selected && failRead) throw Object.assign(new Error('injected read failure'), { code: 'EIO' });
|
||||
return original.readSync.call(fs, fd, buffer, offset, fd === selected ? Math.min(length, 3) : length, position);
|
||||
};
|
||||
fs.closeSync = function (fd) {
|
||||
if (fd === selected) closed = true;
|
||||
return original.closeSync.call(fs, fd);
|
||||
};
|
||||
try {
|
||||
assert.throws(() => readNeighborSnapshot(file), /injected read failure/);
|
||||
assert.equal(closed, true, 'the failing reader closes its descriptor');
|
||||
failRead = false;
|
||||
assert.deepEqual(readNeighborSnapshot(file).neighbors, normalizeNeighbors([userSkill]).neighbors);
|
||||
assert.equal(closed, true, 'short reads reach EOF and close the descriptor');
|
||||
} finally { Object.assign(fs, original); fs.rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('opening a non-regular FIFO cannot hang snapshot discovery', t => {
|
||||
if (process.platform === 'win32') { t.skip('POSIX FIFO fixture'); return; }
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-neighbor-fifo-'));
|
||||
try {
|
||||
const fifo = path.join(dir, 'neighbors.pipe');
|
||||
const created = spawnSync('mkfifo', [fifo], { encoding: 'utf8', timeout: 2000 });
|
||||
assert.equal(created.status, 0, created.stderr);
|
||||
const result = spawnSync(process.execPath, ['-e', [
|
||||
'const { readNeighborSnapshot } = require(process.argv[1]);',
|
||||
'try { readNeighborSnapshot(process.argv[2]); process.exitCode = 1; }',
|
||||
'catch (error) { process.stdout.write(error.message); }'
|
||||
].join('\n'), require.resolve('../../scripts/lib/context-neighbors'), fifo],
|
||||
{ encoding: 'utf8', timeout: 2000 });
|
||||
assert.equal(result.status, 0, String(result.error || result.stderr));
|
||||
assert.match(result.stdout, /regular file/);
|
||||
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
Reference in new issue
Block a user