diff --git a/.kit-triage.jsonl b/.kit-triage.jsonl new file mode 100644 index 00000000..61939a0e --- /dev/null +++ b/.kit-triage.jsonl @@ -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"} diff --git a/README.md b/README.md index cb4927d0..813d7341 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/agent-config.test.ts b/src/agent-config.test.ts index 74ecbfc1..0171207e 100644 --- a/src/agent-config.test.ts +++ b/src/agent-config.test.ts @@ -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-")); @@ -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 }); + } + }); +}); diff --git a/src/agent-config.ts b/src/agent-config.ts index 938b287c..9342ae0b 100644 --- a/src/agent-config.ts +++ b/src/agent-config.ts @@ -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 { + 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; } @@ -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) }, ]; } diff --git a/src/cli.ts b/src/cli.ts index 1f087417..9bdda14d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1511,7 +1511,7 @@ async function cmdAgentConfig(): Promise { ` ${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; diff --git a/src/memory/opencode.test.ts b/src/memory/opencode.test.ts index fd4a1817..cafbcaf8 100644 --- a/src/memory/opencode.test.ts +++ b/src/memory/opencode.test.ts @@ -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"; @@ -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"); + }); +}); diff --git a/src/memory/opencode.ts b/src/memory/opencode.ts index 24f6570a..a7957c06 100644 --- a/src/memory/opencode.ts +++ b/src/memory/opencode.ts @@ -2,35 +2,55 @@ * kit memory — OpenCode session parser (multi-harness). * * OpenCode persists sessions under `$OPENCODE_DATA_DIR` (default - * `~/.local/share/opencode`) as flat JSON in a `storage/` tree: + * `~/.local/share/opencode`). The storage format changed across versions, so we + * support BOTH, preferring the current one: * - * storage/session//.json — session info (id, directory) - * storage/message//msg_.json — one file per message (role, time) - * storage/part/.../.json — message content, split into parts + * 1. SQLite (current, ≥ the mid-2026 `opencode.db` migration). One DB at + * `/opencode.db` with relational tables — verified against + * opencode-ai@1.17.x: + * session(id, directory, time_created, time_updated, …) + * message(id, session_id, time_created, data) — data = JSON Message ({role,…}) + * part (id, message_id, session_id, data) — data = JSON Part (text = {type:"text",text}) + * `session.directory` is the cwd; role lives in `message.data`; the message + * TEXT lives in the `type:"text"` parts' `data`. * - * The message TEXT lives in the *parts*, not the message file. Rather than guess - * the exact part-directory nesting (it has varied across versions), we glob every - * part file and group by the `messageID` field each part carries, then attach the - * `type: "text"` parts to their message. Verified against sst/opencode's - * message-v2 schema (role ∈ user|assistant; text part = { type:"text", text }). + * 2. Flat JSON (legacy) under a `storage/` tree: + * storage/session//.json — session info (id, directory) + * storage/message//msg_.json — one file per message (role, time) + * storage/part/.../.json — message content, split into parts + * The TEXT lives in the parts; we glob every part file and group by the + * `messageID` field each carries (the nesting has varied across versions). + * + * Both paths share the same shape contract (role ∈ user|assistant; text part = + * { type:"text", text }) and the same stable uuid (`opencode::`), + * so a given install is read by exactly one path and re-runs dedupe in insertMessage. * * Defensive + strict: anything that doesn't match the documented shape is skipped, - * so on an unrecognized layout (e.g. newer SQLite-backed installs) this indexes - * nothing rather than garbage. RAW + deterministic; no model calls. + * so on an unrecognized layout this indexes nothing rather than garbage. RAW + + * deterministic; no model calls. */ import { readFileSync, readdirSync, existsSync } from "node:fs"; import { homedir } from "node:os"; import { join, basename } from "node:path"; -import type { DatabaseSync } from "node:sqlite"; +import { DatabaseSync } from "node:sqlite"; import { insertMessage, upsertSession } from "./db.js"; import type { IndexResult } from "./parser.js"; -export function getOpenCodeStorageDir(): string { - const base = +/** OpenCode's data dir (parent of both `storage/` and `opencode.db`). */ +export function getOpenCodeDataDir(): string { + return ( process.env.KIT_OPENCODE_DIR ?? process.env.OPENCODE_DATA_DIR ?? - join(homedir(), ".local", "share", "opencode"); - return join(base, "storage"); + join(homedir(), ".local", "share", "opencode") + ); +} + +export function getOpenCodeStorageDir(): string { + return join(getOpenCodeDataDir(), "storage"); +} + +export function getOpenCodeDbPath(): string { + return join(getOpenCodeDataDir(), "opencode.db"); } /** Recursively yield every *.json file under `dir`. */ @@ -85,6 +105,17 @@ function textPartContent(part: Record): string | null { return typeof text === "string" && text !== "" ? text : null; } +/** The role from a message's `data` JSON blob (SQLite path). */ +function roleFromData(data: unknown): "user" | "assistant" | null { + if (typeof data !== "string") return null; + try { + const obj = JSON.parse(data) as { role?: unknown }; + return obj.role === "user" || obj.role === "assistant" ? obj.role : null; + } catch { + return null; + } +} + /** sessionID → its project basename + cwd, read from the session info files. */ function readSessions(storage: string): { project: Map; @@ -139,8 +170,84 @@ function readParts(storage: string, known: Map): Map:`), so re-runs dedupe in insertMessage. + * + * Prefers the current SQLite store (`opencode.db`); falls back to the legacy + * flat-JSON `storage/` tree for older installs. */ export function indexOpenCodeSessions(db: DatabaseSync): IndexResult { + const dbPath = getOpenCodeDbPath(); + if (existsSync(dbPath)) return indexOpenCodeDb(dbPath, db); + return indexOpenCodeFlat(db); +} + +/** SQLite path (current OpenCode): read `opencode.db` read-only. */ +function indexOpenCodeDb(dbPath: string, db: DatabaseSync): IndexResult { + const result: IndexResult = { files: 0, sessions: 0, messages: 0, toolUses: 0, filesSkipped: 0 }; + let src: DatabaseSync; + try { + src = new DatabaseSync(dbPath, { readOnly: true }); + } catch { + return result; // locked / unreadable / not-a-db → index nothing rather than crash + } + try { + // session.directory is the cwd; its basename is the project. + const cwdOf = new Map(); + const projectOf = new Map(); + for (const s of src.prepare("SELECT id, directory FROM session").all() as { + id: string; + directory: string | null; + }[]) { + cwdOf.set(s.id, s.directory ?? undefined); + projectOf.set(s.id, s.directory ? basename(s.directory) : undefined); + } + + // messages: role lives in `data`; timestamp is the `time_created` column. + // Ordered so first/last-message-at per session are meaningful. + const messages = new Map(); + for (const m of src + .prepare("SELECT id, session_id, time_created, data FROM message ORDER BY time_created ASC") + .all() as { id: string; session_id: string; time_created: number; data: string }[]) { + const role = roleFromData(m.data); + if (!role) continue; + messages.set(m.id, { + sessionId: m.session_id, + role, + timestamp: + typeof m.time_created === "number" ? new Date(m.time_created).toISOString() : undefined, + }); + } + result.files = messages.size; + if (messages.size === 0) return result; + + // parts: text content grouped by message_id. + const content = new Map(); + for (const p of src.prepare("SELECT message_id, data FROM part").all() as { + message_id: string; + data: string; + }[]) { + if (!messages.has(p.message_id)) continue; + let parsed: Record; + try { + parsed = JSON.parse(p.data) as Record; + } catch { + continue; + } + const text = textPartContent(parsed); + if (!text) continue; + const arr = content.get(p.message_id) ?? []; + arr.push(text); + content.set(p.message_id, arr); + } + + writeMessages(db, messages, content, projectOf, cwdOf, result); + return result; + } finally { + src.close(); + } +} + +/** Legacy flat-JSON path (older OpenCode): walk the `storage/` tree. */ +function indexOpenCodeFlat(db: DatabaseSync): IndexResult { const result: IndexResult = { files: 0, sessions: 0, messages: 0, toolUses: 0, filesSkipped: 0 }; const storage = getOpenCodeStorageDir(); if (!existsSync(storage)) return result; @@ -151,6 +258,19 @@ export function indexOpenCodeSessions(db: DatabaseSync): IndexResult { if (messages.size === 0) return result; const content = readParts(storage, messages); + writeMessages(db, messages, content, projectOf, cwdOf, result); + return result; +} + +/** Shared store-writer for both the SQLite and flat-JSON paths. Mutates `result`. */ +function writeMessages( + db: DatabaseSync, + messages: Map, + content: Map, + projectOf: Map, + cwdOf: Map, + result: IndexResult, +): void { const sessionFirst = new Map(); const sessionLast = new Map(); const sessionsSeen = new Set(); @@ -184,5 +304,4 @@ export function indexOpenCodeSessions(db: DatabaseSync): IndexResult { }); result.sessions++; } - return result; }