mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-17 05:22:17 +00:00
fix(opencode): address round-2 review findings on the hooks surface
- R2-1: the V2 execute.after adapter passed { result: ... } as the tool
output; skill-run-tracker derives outcomes from error fields on the
response itself, so failed skills recorded as successes. The adapter
now forwards the raw event.result ?? event.output. Covered by a T05
assertion that an is_error skill event records outcome failure and a
clean event still records success.
- R2-2: cmd.exe expands %VAR% and honors embedded quotes even inside
double quotes, so escaping " was unsafe. spawnCommand now refuses
arguments carrying ", %, CR or LF (nothing spawns; the rejection
surfaces through the formatter's catch) and emits the canonical /s
form with one outer quote pair around the whole command. T01 asserts
the outer pair, strips it before inspecting the inner quoting, and
covers two refusal payloads.
- R2-3: repo review rules ban console.log; the client-less log fallback
and the startup line now use console.info (identical stdout behavior).
- R2-4: declined installs recorded before the barrel split retained the
old module/factory stub in plugins/index.ts, and a later selective
install (e.g. commands-core) has no operation rewriting it, so the
strict deactivation gate failed the install after all writes landed.
The strict branch now migrates such retained files in place only when
ownership is proven twice (managed-recorded contentSha256 matches disk
AND disk equals an exact historical disabled-stub payload), written
through writeFileNoFollow with that digest as expectedContent;
anything else keeps failing closed. The preflight branch accepts an
already-inactive recorded config under the same digest-verified
condition, since selective installs legitimately plan no .opencode
writes. New lifecycle test covers both the migration (install ok,
doctor clean, ownership retained) and the refusal path (mis-recorded
digest never grants a rewrite).
This commit is contained in:
1 parent
6286b7c2f1
commit
76f8ea4bd3
5 files changed
+234
-10
No files matched your search
@@ -183,11 +183,27 @@ function spawnCommand(
|
||||
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.replace(/"/g, '\\"')}"`
|
||||
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", [shim, ...args].map(quote).join(" ")],
|
||||
spawnArgs: ["/d", "/s", "/c", `"${inner}"`],
|
||||
verbatim: true,
|
||||
}
|
||||
}
|
||||
@@ -366,7 +382,7 @@ async function createEccRuntime(input: {
|
||||
if (level === "error") console.error(line)
|
||||
else if (level === "warn") console.warn(line)
|
||||
else if (level === "debug") console.debug(line)
|
||||
else console.log(line)
|
||||
else console.info(line)
|
||||
} catch {
|
||||
// Logging must never break a hook.
|
||||
}
|
||||
@@ -1025,7 +1041,11 @@ export const ECCHooksPluginDefinition = {
|
||||
registrations.push(await ctx.tool.hook("execute.before", safe("execute.before", (event: LooseRecord) => hooks["tool.execute.before"](toToolInput(event), {}))))
|
||||
registrations.push(
|
||||
await ctx.tool.hook("execute.after", safe("execute.after", (event: LooseRecord) =>
|
||||
hooks["tool.execute.after"](toToolInput(event), { result: event.result ?? event.output }),
|
||||
// R2-1: hand the shared handler the tool output object directly. The
|
||||
// skill tracker reads error fields (isError/is_error/status/error) off
|
||||
// `tool_response` itself; a `{ result: … }` wrapper made failed skill
|
||||
// runs look like successes.
|
||||
hooks["tool.execute.after"](toToolInput(event), event.result ?? event.output),
|
||||
)),
|
||||
)
|
||||
}
|
||||
@@ -1208,7 +1228,7 @@ async function disposeRegistrations(
|
||||
|
||||
function logStartup(directory: string) {
|
||||
// Mirrors the V1 startup line used in server-log triage (TROUBLESHOOTING.md).
|
||||
console.log(`[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))} loaded (directory=${directory})`)
|
||||
}
|
||||
|
||||
export default ECCHooksPluginDefinition
|
||||
@@ -14,6 +14,7 @@ const {
|
||||
parseJsoncConfig,
|
||||
getDisabledOpenCodePluginContent,
|
||||
isInertOpenCodePluginStub,
|
||||
isLegacyDisabledOpenCodePluginStub,
|
||||
isOpenCodeHookConfigRegistration,
|
||||
getRecordedHookConsent,
|
||||
getOpenCodeActivationPathKind,
|
||||
@@ -538,7 +539,35 @@ function assertOpenCodeHookDeactivationReady(plan, options = {}) {
|
||||
const digest = content === null ? null : crypto.createHash('sha256').update(content).digest('hex');
|
||||
snapshot.set(key, digest);
|
||||
if (content === null) continue;
|
||||
const inactive = activationIsInactive(kind, operation, content, options.requireInactive);
|
||||
let inactive = activationIsInactive(kind, operation, content, options.requireInactive);
|
||||
if (options.requireInactive && !inactive && kind === 'plugin') {
|
||||
// R2-4 (review 4456945413): installs that declined hooks before the
|
||||
// barrel split wrote the module stub (or the older factory stub) to
|
||||
// EVERY plugin file, the barrel included. This selective plan has no
|
||||
// operation that would rewrite the retained file, so the strict gate
|
||||
// would fail the install after all writes landed. Migrate it in place
|
||||
// — ownership is proven twice: install-state records the file as
|
||||
// managed AND its bytes still match a historical disabled-stub payload
|
||||
// exactly, so no user edit can be lost. Anything else keeps failing.
|
||||
const recorded = previous.get(key);
|
||||
if (recorded
|
||||
&& typeof recorded.contentSha256 === 'string'
|
||||
&& recorded.contentSha256 === digest
|
||||
&& isLegacyDisabledOpenCodePluginStub(content)) {
|
||||
const current = getDisabledOpenCodePluginContent(operation.sourceRelativePath);
|
||||
writeFileNoFollow(operation.destinationPath, current, {
|
||||
expectedContent: { kind: 'sha256', digest },
|
||||
action: 'migrate legacy OpenCode plugin stub',
|
||||
validateDestination(destinationPath) {
|
||||
assertSafeInstallOperation(plan, { destinationPath });
|
||||
assertSafeClaudeSkillOperation(plan, { destinationPath });
|
||||
return destinationPath;
|
||||
},
|
||||
});
|
||||
snapshot.set(key, crypto.createHash('sha256').update(current).digest('hex'));
|
||||
inactive = activationIsInactive(kind, operation, current, true);
|
||||
}
|
||||
}
|
||||
if (options.requireInactive) {
|
||||
if (!inactive) {
|
||||
throw new Error(`OpenCode hook activation remains active at ${operation.destinationPath}`);
|
||||
@@ -546,7 +575,12 @@ function assertOpenCodeHookDeactivationReady(plan, options = {}) {
|
||||
continue;
|
||||
}
|
||||
const recorded = previous.get(key);
|
||||
if (inactive && (kind === 'plugin' || options.allowVerifiedLegacyRemoval || !recorded)) continue;
|
||||
// R2-4: a recorded config that already parses as inactive needs no
|
||||
// replacement operation when its bytes still match the managed digest —
|
||||
// selective installs (e.g. commands-core) legitimately plan no .opencode
|
||||
// writes at all. Unverifiable or modified records keep refusing.
|
||||
if (inactive && (kind === 'plugin' || options.allowVerifiedLegacyRemoval || !recorded
|
||||
|| (typeof recorded.contentSha256 === 'string' && recorded.contentSha256 === digest))) continue;
|
||||
if (options.allowVerifiedLegacyRemoval && recorded) {
|
||||
const verified = verifyManagedLegacyFile(recorded, {
|
||||
targetRoot: plan.targetRoot, installStatePath: plan.installStatePath,
|
||||
|
||||
@@ -233,6 +233,17 @@ function isInertOpenCodePluginStub(content) {
|
||||
|| text === LEGACY_DISABLED_OPENCODE_PLUGIN_CONTENT;
|
||||
}
|
||||
|
||||
// Exact historical disabled-entrypoint payloads that earlier ECC releases
|
||||
// wrote to EVERY plugin file, barrel included. Retained copies of these are
|
||||
// migrated in place to the current expected stub before the strict
|
||||
// deactivation gate verifies the install; a rewrite is only allowed for
|
||||
// files whose managed-recorded digest still matches these bytes.
|
||||
function isLegacyDisabledOpenCodePluginStub(content) {
|
||||
const text = content.toString('utf8');
|
||||
return text === DISABLED_OPENCODE_PLUGIN_STUB
|
||||
|| text === LEGACY_DISABLED_OPENCODE_PLUGIN_CONTENT;
|
||||
}
|
||||
|
||||
function isOpenCodeHookActivationOperation(operation = {}) {
|
||||
return getOpenCodeSourceActivationKind(operation) !== null;
|
||||
}
|
||||
@@ -472,6 +483,7 @@ module.exports = {
|
||||
parseJsoncConfig,
|
||||
getDisabledOpenCodePluginContent,
|
||||
isInertOpenCodePluginStub,
|
||||
isLegacyDisabledOpenCodePluginStub,
|
||||
getOpenCodeActivationPathKind,
|
||||
getOpenCodeSourceActivationKind,
|
||||
formatHookCapabilityDisclosure,
|
||||
|
||||
@@ -2126,6 +2126,100 @@ function runTests() {
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('selective declined install migrates retained legacy plugin stubs before the strict gate', () => {
|
||||
// R2-4 (review 4456945413): declined installs before the barrel split wrote
|
||||
// the module stub (or the older factory stub) to EVERY plugin file, barrel
|
||||
// included. A later selective install such as commands-core has no
|
||||
// operation that rewrites those retained files, so the strict deactivation
|
||||
// gate would fail the install after all writes landed. The gate now
|
||||
// migrates them in place — only when ownership is proven twice.
|
||||
const legacyFactoryStub = 'export default async () => ({});\n';
|
||||
const homeDir = createTempDir('install-lifecycle-opencode-stub-migration-');
|
||||
try {
|
||||
withTemporarilyMovedPath(path.join(REPO_ROOT, '.opencode', 'dist'), () => {
|
||||
const createDeclinePlan = modules => createInstallPlanFromRequest({
|
||||
mode: 'manifest', target: 'opencode', profileId: null,
|
||||
moduleIds: modules, includeComponentIds: [], excludeComponentIds: [],
|
||||
legacyLanguages: [], hookConsent: 'declined',
|
||||
}, {
|
||||
sourceRoot: REPO_ROOT, homeDir, projectRoot: homeDir,
|
||||
exemptValidationCodes: ['opencode-plugin-not-built'],
|
||||
});
|
||||
|
||||
// A current declined install records fully managed plugin operations...
|
||||
const basePlan = createDeclinePlan(['platform-configs']);
|
||||
applyInstallPlan(basePlan);
|
||||
const pluginDir = path.join(basePlan.targetRoot, 'plugins');
|
||||
const comparableRelative = operation => String(operation.sourceRelativePath || '')
|
||||
.split(path.sep).join('/');
|
||||
const moduleStub = getDisabledOpenCodePluginContent('.opencode/plugins/ecc-hooks.ts');
|
||||
const barrelStub = getDisabledOpenCodePluginContent('.opencode/plugins/index.ts');
|
||||
assert.notStrictEqual(moduleStub, barrelStub, 'the legacy fixture needs the two stubs to differ');
|
||||
|
||||
// ...then roll the install back in time: the barrel holds the module
|
||||
// stub, ecc-hooks.ts holds the pre-V2-fix factory stub, and the
|
||||
// recorded digests are re-hashed so ownership stays provable.
|
||||
const ageInstalledStubs = () => {
|
||||
fs.writeFileSync(path.join(pluginDir, 'index.ts'), moduleStub);
|
||||
fs.writeFileSync(path.join(pluginDir, 'ecc-hooks.ts'), legacyFactoryStub);
|
||||
const aged = readInstallState(basePlan.installStatePath);
|
||||
for (const [relative, content] of [
|
||||
['.opencode/plugins/index.ts', moduleStub],
|
||||
['.opencode/plugins/ecc-hooks.ts', legacyFactoryStub],
|
||||
]) {
|
||||
aged.operations.find(operation => comparableRelative(operation) === relative)
|
||||
.contentSha256 = crypto.createHash('sha256').update(content).digest('hex');
|
||||
}
|
||||
writeInstallState(basePlan.installStatePath, aged);
|
||||
};
|
||||
ageInstalledStubs();
|
||||
|
||||
const selectivePlan = createDeclinePlan(['commands-core']);
|
||||
assert.ok(!selectivePlan.operations.some(operation => (
|
||||
comparableRelative(operation).startsWith('.opencode/plugins/')
|
||||
)), 'the selective plan must not rewrite the retained plugin files');
|
||||
applyInstallPlan(selectivePlan);
|
||||
|
||||
// Both retained files migrated to their current per-path inert stubs.
|
||||
assert.strictEqual(fs.readFileSync(path.join(pluginDir, 'index.ts'), 'utf8'), barrelStub);
|
||||
assert.strictEqual(fs.readFileSync(path.join(pluginDir, 'ecc-hooks.ts'), 'utf8'), moduleStub);
|
||||
const state = readInstallState(basePlan.installStatePath);
|
||||
assert.strictEqual(state.request.hookConsent, 'declined');
|
||||
for (const relative of ['.opencode/plugins/index.ts', '.opencode/plugins/ecc-hooks.ts']) {
|
||||
const operation = state.operations.find(candidate => comparableRelative(candidate) === relative);
|
||||
assert.strictEqual(operation.ownership, 'managed', 'migration must retain managed ownership');
|
||||
}
|
||||
|
||||
// Only planned destinations get refreshed digests, so the migrated
|
||||
// retained files keep their historical record; the doctor must verify
|
||||
// deactivation operations by transform content, not by that digest.
|
||||
const doctor = buildDoctorReport({
|
||||
repoRoot: REPO_ROOT, homeDir, projectRoot: homeDir, targets: ['opencode'],
|
||||
});
|
||||
assert.ok(!doctor.results[0].issues.some(issue => (
|
||||
['missing-managed-files', 'drifted-managed-files', 'unverified-managed-operations'].includes(issue.code)
|
||||
)));
|
||||
|
||||
// Ownership is proven twice: identical legacy bytes alone never grant a
|
||||
// rewrite. A mis-recorded digest keeps the strict gate refusing.
|
||||
ageInstalledStubs();
|
||||
const tampered = readInstallState(basePlan.installStatePath);
|
||||
tampered.operations.find(operation => (
|
||||
comparableRelative(operation) === '.opencode/plugins/index.ts'
|
||||
)).contentSha256 = crypto.createHash('sha256').update('tampered\n').digest('hex');
|
||||
writeInstallState(basePlan.installStatePath, tampered);
|
||||
assert.throws(
|
||||
() => applyInstallPlan(createDeclinePlan(['commands-core'])),
|
||||
/OpenCode hook activation remains active/i
|
||||
);
|
||||
assert.strictEqual(fs.readFileSync(path.join(pluginDir, 'index.ts'), 'utf8'), moduleStub,
|
||||
'an unverifiable retained file must never be rewritten');
|
||||
});
|
||||
} finally {
|
||||
cleanup(homeDir);
|
||||
}
|
||||
})) passed++; else failed++;
|
||||
|
||||
if (test('OpenCode repair refuses modified activation before building or restoring missing files', () => {
|
||||
const homeDir = createTempDir('install-lifecycle-opencode-modified-activation-');
|
||||
try {
|
||||
|
||||
@@ -830,17 +830,42 @@ async function main() {
|
||||
assert.strictEqual(call.options.shell, false, "spawn must never use shell:true")
|
||||
if (process.platform === "win32") {
|
||||
// Routed through cmd.exe ONLY as the documented .cmd-shim
|
||||
// escape: /d /s /c with every argument double-quoted, so the
|
||||
// & ; | characters in the path are data, not separators.
|
||||
// escape: /d /s /c with the complete command string wrapped in
|
||||
// one outer quote pair (which cmd strips) and every argument
|
||||
// double-quoted inside it, so the & ; | characters in the path
|
||||
// are data, not separators.
|
||||
assert.match(call.file, /cmd\.exe$/i)
|
||||
assert.deepStrictEqual(call.args.slice(0, 3), ["/d", "/s", "/c"])
|
||||
const inner = call.args[3]
|
||||
const commandString = call.args[3]
|
||||
assert.ok(
|
||||
commandString.startsWith('"') && commandString.endsWith('"'),
|
||||
`the full command must carry the /s outer quote pair: ${commandString}`,
|
||||
)
|
||||
// cmd strips exactly the outer pair; what it then executes is
|
||||
// the remainder.
|
||||
const inner = commandString.slice(1, -1)
|
||||
assert.ok(inner.includes(`"${evil}"`), `evil path must be quoted inside: ${inner}`)
|
||||
assert.strictEqual(
|
||||
unquotedMetachars(inner),
|
||||
"",
|
||||
`unquoted shell metacharacters survived: ${inner}`,
|
||||
)
|
||||
|
||||
// R2-2: characters cmd expands or that terminate quoting even
|
||||
// INSIDE double quotes (quote, percent, line breaks) must be
|
||||
// refused outright — never escaped, never spawned.
|
||||
resetSpawns()
|
||||
await hooks["file.edited"]({ path: 'evil" %PATH% expand.ts' })
|
||||
assert.strictEqual(spawnCalls.length, 0, "quote/percent-bearing args must never reach spawn")
|
||||
assert.ok(
|
||||
client.logs.some(
|
||||
(entry) => entry.level === "debug" && entry.message.includes("unsafe argument"),
|
||||
),
|
||||
"the shim refusal must be visible in the debug log",
|
||||
)
|
||||
resetSpawns()
|
||||
await hooks["file.edited"]({ path: "evil\r\nx && calc.ts" })
|
||||
assert.strictEqual(spawnCalls.length, 0, "line-break-bearing args must never reach spawn")
|
||||
} else {
|
||||
assert.strictEqual(call.file, "npx")
|
||||
assert.deepStrictEqual(call.args, ["prettier", "--write", evil])
|
||||
@@ -965,6 +990,45 @@ async function main() {
|
||||
await ctx.state.handlers["tool.execute.before"]({ tool: "write", callID: "c1", input: { filePath: "a.ts" } })
|
||||
await ctx.state.handlers["tool.execute.after"]({ tool: "write", callID: "c1", input: { filePath: "a.ts" }, output: {} })
|
||||
|
||||
// R2-1: the execute.after adapter must hand the skill tracker the RAW
|
||||
// tool output. The tracker reads error fields (is_error/isError/
|
||||
// status/error) directly off tool_response, so a `{ result: … }`
|
||||
// wrapper made failed skills record as successes.
|
||||
{
|
||||
const previousHome = process.env.HOME
|
||||
const previousUserProfile = process.env.USERPROFILE
|
||||
const skillHome = fs.mkdtempSync(path.join(os.tmpdir(), "ecc-v2-skill-home-"))
|
||||
process.env.HOME = skillHome
|
||||
process.env.USERPROFILE = skillHome
|
||||
try {
|
||||
await ctx.state.handlers["tool.execute.after"]({
|
||||
tool: "skill",
|
||||
callID: "c2",
|
||||
input: { name: "code-review" },
|
||||
output: { output: "skill crashed", is_error: true },
|
||||
})
|
||||
const runs = readRecordedRuns(skillHome)
|
||||
assert.strictEqual(runs.length, 1, "the skill run must be recorded through V2")
|
||||
assert.strictEqual(
|
||||
runs[0].outcome,
|
||||
"failure",
|
||||
"an error-bearing skill response must record as failure, not success",
|
||||
)
|
||||
await ctx.state.handlers["tool.execute.after"]({
|
||||
tool: "skill",
|
||||
callID: "c3",
|
||||
input: { name: "code-review" },
|
||||
output: { output: "all good" },
|
||||
})
|
||||
const both = readRecordedRuns(skillHome)
|
||||
assert.strictEqual(both.length, 2)
|
||||
assert.strictEqual(both[1].outcome, "success", "clean responses still record as success")
|
||||
} finally {
|
||||
restoreEnv({ HOME: previousHome, USERPROFILE: previousUserProfile })
|
||||
fs.rmSync(skillHome, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
// Session compaction appends ECC context through the V2 event object.
|
||||
const compactionEvent = { system: [] }
|
||||
await ctx.state.handlers["session.compaction"](compactionEvent)
|
||||
|
||||
Reference in new issue
Block a user