Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .kit-triage.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{"timestamp":"2026-06-27T18:30:11.622Z","type":"npm","target":"opencode-ai","sandbox":false,"granter":"unknown"}
{"timestamp":"2026-06-27T18:32:17.563Z","type":"npm","target":"@opencode-ai/plugin","sandbox":false,"granter":"unknown"}
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,23 +259,23 @@ adapters for the surfaces each agent exposes. Support today, per agent:

| Agent | Memory index¹ | "use kit" rules block² | Agent/MCP config audit³ | Perm allowlist⁴ | Auto-capture hooks⁵ | Blocking gate⁶ |
| :--- | :---: | :---: | :---: | :---: | :---: | :---: |
| **Claude Code** | ✅ | ✅ `CLAUDE.md` | ✅ + commands/agents/skills/plugins | ✅ | ✅ | 🔜 verified |
| **OpenAI Codex** | ✅ | ✅ `AGENTS.md` | ✅ `.codex/config` | — | — | 🔜 verified |
| **OpenCode** | ✅ | ✅ `AGENTS.md` | ✅ `opencode.json` | — | — | 🔎 research |
| **Cursor** | ✅ | ✅ `.cursorrules` | ✅ `.cursor/mcp.json` | — | — | 🔎 research |
| **Claude Code** | ✅ | ✅ `CLAUDE.md` | ✅ + commands/agents/skills/plugins | ✅ | ✅ | ✅ hook |
| **OpenAI Codex** | ✅ | ✅ `AGENTS.md` | ✅ `.codex/config` | — | — | ✅ hook |
| **OpenCode** | ✅ | ✅ `AGENTS.md` | ✅ `opencode.json` + `.opencode/plugin` | — | — | ✅ plugin |
| **Cursor** | ✅ | ✅ `.cursorrules` | ✅ `.cursor/mcp.json` | — | — | ✅ hook |
| **Cline** | ✅ | ✅ `.clinerules` | — | — | — | 🔎 research |
| **Gemini CLI** | ✅ | — | — | — | — | 🔎 research |
| **Gemini CLI** | ✅ | — | — | — | — | ✅ hook |
| **Continue** | ✅ | — | — | — | — | 🔎 research |
| **Amazon Q** | ✅ | — | — | — | — | 🔜 verified |
| **Amazon Q** | ✅ | — | — | — | — | ✅ hook |

✅ supported · — not yet · 🔜 planned, agent's blocking-hook capability verified · 🔎 planned, needs research ([#146](https://github.com/sandstream/kit/issues/146))
✅ supported · — not yet · 🔎 planned, needs research ([#146](https://github.com/sandstream/kit/issues/146))

1. `kit memory index` parses the agent's local transcripts into the shared store.
2. `kit agent-config` writes the managed "run kit before installs / vault secrets" block into the agent's rules file.
3. `kit agent-audit` flags plaintext secrets, cleartext/inline-code MCP servers, and malware-shaped hooks in the agent's config. Generic `.mcp.json` / `.claude.json` are scanned for every agent regardless.
4. kit can pre-authorize its read-only commands so they run without a prompt (Claude Code's `permissions.allow` today).
5. kit registers lifecycle hooks so memory capture happens automatically (Claude Code `settings.json` hooks today).
6. A **true blocking gate** (deny an un-triaged install before it runs) requires the agent's `PreToolUse`-style hook. Verified available for Claude Code, Codex, and Amazon Q; the rest need a research pass. Until then, the agent-agnostic enforcement floor is **git hooks** (`kit hooks`, pre-commit/pre-push) — they fire in any agent or none. See [#146](https://github.com/sandstream/kit/issues/146).
6. A **true blocking gate** (deny an un-triaged install before it runs) uses the agent's `PreToolUse`-style hook — `kit agent-config --install-gate` wires it for Claude Code, Codex, Amazon Q, Gemini CLI, and Cursor (exit-2 hook commands), and for OpenCode via a generated `.opencode/plugin` that hooks `tool.execute.before` and throws to block. Cline (JSON-cancel protocol) and Continue (unverified) still need a research pass. The agent-agnostic enforcement floor is **git hooks** (`kit hooks`, pre-commit/pre-push) — they fire in any agent or none. See [#146](https://github.com/sandstream/kit/issues/146).

> The git-hook layer enforces at the VCS boundary regardless of agent; the rules-file block is **advisory** (it reminds the agent); only the blocking-gate hook **enforces** before an action runs.

Expand Down
45 changes: 45 additions & 0 deletions src/agent-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ import {
installInstallGateAmazonQ,
installInstallGateGemini,
installInstallGateCursor,
installInstallGateOpenCode,
READONLY_KIT_PERMISSIONS,
} from "./agent-config.js";
import { pathToFileURL } from "node:url";

function tmpRepo(): string {
return mkdtempSync(join(tmpdir(), "kit-agentcfg-"));
Expand Down Expand Up @@ -415,3 +417,46 @@ describe("installInstallGateCursor", () => {
}
});
});

describe("installInstallGateOpenCode", () => {
it("writes a tool.execute.before plugin that loads as a module, idempotently", async () => {
const dir = mkdtempSync(join(tmpdir(), "kit-ocgate-"));
try {
mkdirSync(join(dir, ".opencode"), { recursive: true });
const r1 = await installInstallGateOpenCode(dir);
assert.equal(r1.action, "created");
const pluginPath = join(dir, ".opencode", "plugin", "kit-install-gate.js");
assert.ok(existsSync(pluginPath));
const body = readFileSync(pluginPath, "utf-8");
assert.ok(body.includes("tool.execute.before"), "hooks the documented block point");
assert.ok(body.includes("gate-bash"), "invokes kit gate-bash");
// The generated plugin must be a loadable ESM module exporting the hook factory.
const mod = await import(pathToFileURL(pluginPath).href);
assert.equal(typeof mod.kitInstallGate, "function");
const hooks = await mod.kitInstallGate();
assert.equal(typeof hooks["tool.execute.before"], "function");
// Non-bash tools are ignored (no spawn, no throw).
await hooks["tool.execute.before"]({ tool: "read" }, { args: {} });
assert.equal((await installInstallGateOpenCode(dir)).action, "unchanged");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("detects an opencode.json project even without a .opencode dir", async () => {
const dir = mkdtempSync(join(tmpdir(), "kit-ocgate2-"));
try {
writeFileSync(join(dir, "opencode.json"), "{}");
assert.equal((await installInstallGateOpenCode(dir)).action, "created");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("skips when no OpenCode project is present", async () => {
const dir = mkdtempSync(join(tmpdir(), "kit-ocgate3-"));
try {
assert.equal((await installInstallGateOpenCode(dir)).action, "skipped");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
77 changes: 76 additions & 1 deletion src/agent-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -519,9 +519,83 @@ export async function installInstallGateCursor(
}
}

/** The gate command as an argv array (`[node, cli.js, "gate-bash"]`) for execFileSync. */
export function kitGateArgv(): string[] {
const entry = process.argv[1];
if (entry) return [process.execPath, resolve(entry), "gate-bash"];
return ["kit", "gate-bash"]; // last resort — relies on PATH
}

/**
* OpenCode install-gate: unlike the other agents (which register a hook *command*
* in a config file), OpenCode enforces via a JS **plugin** that hooks
* `tool.execute.before` and BLOCKS by throwing — the verified contract from
* `@opencode-ai/plugin` (opencode-ai@1.17.x). We write a small managed plugin to
* `.opencode/plugin/kit-install-gate.js` that pipes the bash command into
* `kit gate-bash` and throws when it exits non-zero (exit 2 = deny). Idempotent:
* keyed on the generated file's presence. The args are embedded JSON-escaped so
* node/cli paths with spaces survive.
*/
export async function installInstallGateOpenCode(
cwd: string = process.cwd(),
): Promise<HookInstallResult> {
const file = ".opencode/plugin/kit-install-gate.js";
const path = resolve(cwd, file);
const { isReadOnlyMode } = await import("./read-only-mode.js");
if (isReadOnlyMode()) return { file, action: "skipped", detail: "read-only mode" };
const detected =
existsSync(resolve(cwd, ".opencode")) ||
existsSync(resolve(cwd, "opencode.json")) ||
existsSync(resolve(cwd, "opencode.jsonc"));
if (!detected) return { file, action: "skipped", detail: "no OpenCode project detected" };

const existed = existsSync(path);
if (existed) {
try {
if ((await readFile(path, "utf-8")).includes("gate-bash")) {
return { file, action: "unchanged", detail: "install-gate already wired" };
}
} catch {
// unreadable → overwrite below
}
}

const plugin = `// kit install-gate — blocks un-triaged package installs before they run.
// Generated by \`kit agent-config --install-gate\`. Delete this file to disable.
import { execFileSync } from "node:child_process";

const GATE = ${JSON.stringify(kitGateArgv())};

export const kitInstallGate = async () => ({
"tool.execute.before": async (input, output) => {
if ((input?.tool ?? "") !== "bash") return;
const command = output?.args?.command;
if (typeof command !== "string" || command === "") return;
try {
execFileSync(GATE[0], GATE.slice(1), {
input: JSON.stringify({ tool_input: { command } }),
stdio: ["pipe", "ignore", "pipe"],
});
} catch (err) {
// gate-bash exits 2 to deny — throw to block the tool call.
const reason = err && err.stderr ? String(err.stderr).trim() : "untriaged install";
throw new Error("kit install-gate blocked: " + reason);
}
},
});
`;
try {
await mkdir(dirname(path), { recursive: true });
await writeFile(path, plugin, "utf-8");
return { file, action: existed ? "updated" : "created" };
} catch (err) {
return { file, action: "failed", detail: err instanceof Error ? err.message : String(err) };
}
}

/** Per-agent install-gate result. */
export interface GateInstallEntry {
agent: "Claude Code" | "Codex" | "Amazon Q" | "Gemini CLI" | "Cursor";
agent: "Claude Code" | "Codex" | "Amazon Q" | "Gemini CLI" | "Cursor" | "OpenCode";
result: HookInstallResult;
}

Expand All @@ -535,5 +609,6 @@ export async function installAllInstallGates(
{ agent: "Amazon Q", result: await installInstallGateAmazonQ(cwd) },
{ agent: "Gemini CLI", result: await installInstallGateGemini(cwd) },
{ agent: "Cursor", result: await installInstallGateCursor(cwd) },
{ agent: "OpenCode", result: await installInstallGateOpenCode(cwd) },
];
}
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1511,7 +1511,7 @@ async function cmdAgentConfig(): Promise<boolean> {
` ${c.dim}· "use kit" rules block: Claude Code, Codex, Cursor, Cline, OpenCode${c.reset}\n` +
` ${c.dim}· Config/secret audit (kit agent-audit): Claude Code, Codex, Cursor, OpenCode (+ generic .mcp.json)${c.reset}\n` +
` ${c.dim}· Permission allowlist + auto-capture hooks: Claude Code${c.reset}\n` +
` ${c.dim}· Blocking install-gate (PreToolUse): planned — verified for Claude Code/Codex/Amazon Q (see issue #146)${c.reset}\n` +
` ${c.dim}· Blocking install-gate: Claude Code, Codex, Amazon Q, Gemini CLI, Cursor (hooks) + OpenCode (plugin); Cline/Continue tracked in #146${c.reset}\n` +
` ${c.dim}The agent-agnostic enforcement floor is git hooks (${c.reset}${c.bold}kit hooks${c.reset}${c.dim}); the rules block only advises.${c.reset}`,
);
return !failed;
Expand Down
69 changes: 68 additions & 1 deletion src/memory/opencode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { DatabaseSync } from "node:sqlite";
import { DatabaseSync } from "node:sqlite";
import { openMemoryDb, searchMessages } from "./db.js";
import { indexOpenCodeSessions } from "./opencode.js";

Expand Down Expand Up @@ -95,3 +95,70 @@ describe("indexOpenCodeSessions", () => {
empty.close();
});
});

/**
* Build a minimal `opencode.db` matching the verified opencode-ai@1.17.x schema:
* session(id, directory), message(id, session_id, time_created, data),
* part(id, message_id, session_id, data) — data is the serialized Message/Part JSON.
*/
function writeSqliteFixture(root: string): void {
const src = new DatabaseSync(join(root, "opencode.db"));
src.exec(`
CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT NOT NULL);
CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT);
CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, data TEXT);
`);
const ses = "ses_sql";
src.prepare("INSERT INTO session(id, directory) VALUES (?, ?)").run(ses, "/home/dev/myproject");
src
.prepare("INSERT INTO message(id, session_id, time_created, data) VALUES (?, ?, ?, ?)")
.run(
"msg_1",
ses,
1_700_000_000_000,
JSON.stringify({ id: "msg_1", sessionID: ses, role: "user", time: { created: 1 } }),
);
const part = (id: string, data: unknown) =>
src
.prepare("INSERT INTO part(id, message_id, session_id, data) VALUES (?, ?, ?, ?)")
.run(id, "msg_1", ses, JSON.stringify(data));
part("prt_1", { type: "text", text: "deploy the staging cluster" });
part("prt_2", { type: "text", text: "", ignored: true }); // empty/ignored → skip
part("prt_3", { type: "tool", text: "n/a" }); // non-text → skip
src.close();
}

describe("indexOpenCodeSessions — SQLite store (current OpenCode)", () => {
let dir: string;
let db: DatabaseSync;

before(() => {
dir = mkdtempSync(join(tmpdir(), "kit-opencode-sql-"));
process.env.KIT_OPENCODE_DIR = dir;
writeSqliteFixture(dir);
db = openMemoryDb(":memory:");
});

after(() => {
db.close();
delete process.env.KIT_OPENCODE_DIR;
rmSync(dir, { recursive: true, force: true });
});

it("prefers opencode.db and indexes message text from part data blobs", () => {
const res = indexOpenCodeSessions(db);
assert.equal(res.messages, 1, "one message indexed from SQLite");
assert.equal(res.sessions, 1, "one session recorded");
const hits = searchMessages(db, "staging cluster");
assert.equal(hits.length, 1);
assert.equal(
hits[0].content,
"deploy the staging cluster",
"only the text part, no tool/ignored parts",
);
});

it("is idempotent on re-run (stable uuids dedupe)", () => {
assert.equal(indexOpenCodeSessions(db).messages, 0, "re-run adds nothing");
});
});
Loading
Loading