repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(chef): Fortified Kitchen — table validation, session ID redaction, auto-mkdir, SDK smoke test

170bd86bd7551917ecb570fb7589b0f3203dbfc7

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Concern 1: Add ALLOWED_TABLES guard derived from ALLOWED_COLUMNS keys
to reject unknown table names in updateRecord() (defense-in-depth).

Concern 2: Add Executor.redactId() to truncate session UUIDs to first
8 chars before logging. Applied to 4 sites in cleanupSession() and
execute() finally block.

Concern 3: Store constructor now auto-creates .opencode/chef/
directory via mkdirSync({ recursive: true }).

Concern 4: Add SDK smoke test gated behind CHEF_SDK_SMOKE_TEST=1
that verifies ChefPlugin loads, imports resolve, and all 5 tools
register correctly.

Tests: 85 pass, 0 fail (80 existing + 5 new).

Changed files (5)

opencode/plugins/chef/executor.ts

Modified
77 77 DEFAULT_MAX_LOOP_ITERATIONS;
80 + /** Truncate IDs for safe logging. Keeps first 8 chars + ellipsis. */
81 + private static redactId(id: string): string {
82 + return id.length > 8 ? `${id.slice(0, 8)}…` : id;
83 + }
80 85 private async cleanupSession(sessionId: string): Promise<void> {
81 86 try {
82 87 await this.client.session.delete({ path: { id: sessionId } });
83 88 } catch (e) {
84 89 this.leakedSessions.add(sessionId);
85 90 const msg = e instanceof Error ? e.message : String(e);
86 - console.warn(`Chef: session cleanup failed for ${sessionId}: ${msg}`);
91 + console.warn(
92 + `Chef: session cleanup failed for ${
93 + Executor.redactId(sessionId)
94 + }: ${msg}`,
95 + );
87 96 try {
88 97 await this.client.app.log({
89 98 body: {
90 99 service: "chef",
91 100 level: "warn",
92 101 message: `Session cleanup failed`,
93 - extra: { sessionId, error: msg },
102 + extra: { sessionId: Executor.redactId(sessionId), error: msg },
96 105 } catch {
194 203 const ids = Array.from(this.leakedSessions);
195 204 console.warn(
196 205 `Chef: pipeline ${pipelineId} completed with ${ids.length} leaked session(s): ${
197 - ids.join(", ")
206 + ids.map((id) => Executor.redactId(id)).join(", ")
203 212 service: "chef",
204 213 level: "warn",
205 214 message: `Pipeline completed with leaked sessions`,
206 - extra: { pipelineId, leakedSessionIds: ids },
215 + extra: {
216 + pipelineId,
217 + leakedSessionIds: ids.map((id) => Executor.redactId(id)),
218 + },
209 221 } catch {

opencode/plugins/chef/store.ts

Modified
1 1 import { Database } from "bun:sqlite";
2 +import { mkdirSync } from "node:fs";
2 3 import { join } from "path";
3 4 import { randomUUID } from "crypto";
66 +/** Defense-in-depth: tripwire in case new callers pass an invalid table. */
67 +const ALLOWED_TABLES: ReadonlySet<string> = new Set(
68 + Object.keys(ALLOWED_COLUMNS),
69 +);
65 71 export class Store {
66 72 private db: Database;
114 120 constructor(directory: string) {
115 - const dbPath = join(directory, ".opencode/chef/chef.db");
121 + const chefDir = join(directory, ".opencode/chef");
122 + mkdirSync(chefDir, { recursive: true });
123 + const dbPath = join(chefDir, "chef.db");
116 124 this.db = new Database(dbPath);
117 125 this.db.run("PRAGMA journal_mode = WAL");
118 126 this.initSchema();
177 185 updates: Record<string, any>,
178 186 withTimestamp = false,
179 187 ): void {
188 + if (!ALLOWED_TABLES.has(table)) {
189 + throw new Error(`Chef Store: unknown table "${table}"`);
180 191 const allowed = ALLOWED_COLUMNS[table];
181 192 const filtered = Object.fromEntries(
182 193 Object.entries(updates).filter(

opencode/plugins/chef/test/executor.test.ts

Modified
1 1 import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
2 -import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
2 +import { mkdtempSync, rmSync } from "node:fs";
3 3 import { join } from "node:path";
4 4 import { tmpdir } from "node:os";
21 21 beforeEach(() => {
22 22 tempDir = mkdtempSync(join(tmpdir(), "chef-exec-test-"));
23 - mkdirSync(join(tempDir, ".opencode/chef"), { recursive: true });
24 23 store = new Store(tempDir);
26 25 mockClient = {
463 462 // The cleanup failed but pipeline still completed
464 463 expect(mockClient.app.log).toHaveBeenCalled();
466 + test("redacts session IDs in leaked session logs", async () => {
467 + const longSessionId = "abcdefghijklmnop-1234-5678-9abc-def012345678";
468 + mockClient.session.create = mock(() =>
469 + Promise.resolve({ id: longSessionId })
470 + );
471 + mockClient.session.delete = mock(() =>
472 + Promise.reject(new Error("Delete failed"))
473 + );
475 + // Capture console.warn output
476 + const warnSpy: string[] = [];
477 + const origWarn = console.warn;
478 + console.warn = (...args: any[]) => warnSpy.push(args.join(" "));
480 + try {
481 + const definition = createDefinition([
483 + name: "step1",
484 + type: "step",
485 + agent: "test-agent",
486 + prompt: "do thing",
487 + output: z.object({ result: z.string() }),
488 + },
489 + ]);
490 + const instance = store.createPipeline("test-pipe", {});
491 + const executor = createExecutor(definition);
492 + await executor.execute(instance.id, {});
494 + // Check that the warn output contains truncated ID, not full ID
495 + const leakedWarn = warnSpy.find((w) => w.includes("leaked session"));
496 + expect(leakedWarn).toBeDefined();
497 + expect(leakedWarn!).toContain("abcdefgh…");
498 + expect(leakedWarn!).not.toContain(
499 + "abcdefghijklmnop-1234-5678-9abc-def012345678",
500 + );
501 + } finally {
502 + console.warn = origWarn;
504 + });
506 + test("redactId handles short and long IDs correctly", () => {
507 + // Access the private static method via (Executor as any)
508 + const redact = (Executor as any).redactId;
509 + expect(redact).toBeDefined();
511 + // Long IDs are truncated to first 8 chars + ellipsis
512 + expect(redact("abcdefghijklmnop")).toBe("abcdefgh…");
513 + expect(redact("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")).toBe("aaaaaaaa…");
515 + // Short IDs (<= 8 chars) are returned unchanged
516 + expect(redact("short")).toBe("short");
517 + expect(redact("12345678")).toBe("12345678");
518 + });
468 521 describe("Executor - Gate execution", () => {

opencode/plugins/chef/test/sdk-smoke.test.ts

Added
new file mode 100644
1 +import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 +import { mkdtempSync, rmSync } from "node:fs";
3 +import { tmpdir } from "node:os";
4 +import { join } from "node:path";
6 +// Gate the test behind the environment variable
7 +// In bun:test, describe.skip is used directly, so we conditionally select describe or describe.skip
8 +const describeSmokeTest = process.env.CHEF_SDK_SMOKE_TEST === "1"
9 + ? describe
10 + : describe.skip;
12 +describeSmokeTest("Chef Plugin SDK Smoke Test", () => {
13 + let tempDir: string;
15 + beforeAll(() => {
16 + // Create a temporary directory for the test
17 + tempDir = mkdtempSync(join(tmpdir(), "chef-smoke-test-"));
18 + });
20 + afterAll(() => {
21 + // Clean up the temporary directory
22 + rmSync(tempDir, { recursive: true, force: true });
23 + });
25 + test("SDK imports resolve without throwing", async () => {
26 + // This tests that the plugin can import its dependencies
27 + const { ChefPlugin } = await import("../chef.ts");
28 + expect(ChefPlugin).toBeDefined();
29 + expect(typeof ChefPlugin).toBe("function");
30 + });
32 + test("ChefPlugin returns tools when called with mock input", async () => {
33 + const { ChefPlugin } = await import("../chef.ts");
35 + const mockClient = {
36 + session: {
37 + create: () => Promise.resolve({ id: "test-session" }),
38 + prompt: () =>
39 + Promise.resolve({ data: { info: { structured_output: {} } } }),
40 + delete: () => Promise.resolve(),
41 + },
42 + app: {
43 + log: () => Promise.resolve(),
44 + agents: () => Promise.resolve([]),
45 + },
46 + };
48 + const mockInput = {
49 + client: mockClient as any,
50 + project: {
51 + id: "test-project",
52 + worktree: tempDir,
53 + time: { created: Date.now() },
54 + },
55 + directory: tempDir,
56 + worktree: tempDir,
57 + serverUrl: new URL("http://localhost:0"),
58 + $: {} as any,
59 + };
61 + const result = await ChefPlugin(mockInput);
63 + expect(result).toBeDefined();
64 + expect(result.tool).toBeDefined();
65 + });
67 + test("all 5 expected tools are present", async () => {
68 + const { ChefPlugin } = await import("../chef.ts");
70 + const mockClient = {
71 + session: {
72 + create: () => Promise.resolve({ id: "test-session" }),
73 + prompt: () =>
74 + Promise.resolve({ data: { info: { structured_output: {} } } }),
75 + delete: () => Promise.resolve(),
76 + },
77 + app: {
78 + log: () => Promise.resolve(),
79 + agents: () => Promise.resolve([]),
80 + },
81 + };
83 + const mockInput = {
84 + client: mockClient as any,
85 + project: {
86 + id: "test-project",
87 + worktree: tempDir,
88 + time: { created: Date.now() },
89 + },
90 + directory: tempDir,
91 + worktree: tempDir,
92 + serverUrl: new URL("http://localhost:0"),
93 + $: {} as any,
94 + };
96 + const result = await ChefPlugin(mockInput);
98 + const expectedTools = [
99 + "pipeline.start",
100 + "pipeline.status",
101 + "pipeline.continue",
102 + "pipeline.abort",
103 + "pipeline.list",
104 + ];
106 + // Type assertion since we verified result.tool is defined above
107 + const tools = result.tool!;
108 + const actualTools = Object.keys(tools);
110 + for (const toolName of expectedTools) {
111 + expect(actualTools).toContain(toolName);
112 + expect(tools[toolName]).toBeDefined();
113 + expect(typeof tools[toolName]).toBe("object");
114 + expect(tools[toolName].execute).toBeDefined();
115 + expect(typeof tools[toolName].execute).toBe("function");
118 + expect(actualTools).toHaveLength(expectedTools.length);
119 + });
120 +});

opencode/plugins/chef/test/store.test.ts

Modified
1 1 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2 -import { mkdirSync, rmSync } from "node:fs";
2 +import { existsSync, rmSync } from "node:fs";
3 3 import { join } from "node:path";
4 4 import { tmpdir } from "node:os";
5 5 import { mkdtempSync } from "node:fs";
11 11 beforeEach(() => {
12 12 tempDir = mkdtempSync(join(tmpdir(), "chef-test-"));
13 - // Ensure the .opencode/chef directory exists for bun:sqlite
14 - mkdirSync(join(tempDir, ".opencode/chef"), { recursive: true });
15 13 store = new Store(tempDir);
244 242 expect(() => testStore.close()).not.toThrow();
246 +describe("Store - auto-creates parent directories", () => {
247 + test("creates .opencode/chef if it does not exist", () => {
248 + const deepDir = join(tempDir, "a", "b", "c");
249 + const deepStore = new Store(deepDir);
250 + try {
251 + const pipeline = deepStore.createPipeline("auto-dir-test", {});
252 + expect(pipeline.id).toBeDefined();
253 + expect(pipeline.status).toBe("running");
254 + expect(existsSync(join(deepDir, ".opencode", "chef"))).toBe(true);
255 + } finally {
256 + deepStore.close();
258 + });
259 +});
261 +describe("Store - Table name validation", () => {
262 + test("updatePipeline and updatePhase use valid tables", () => {
263 + const pipeline = store.createPipeline("test-pipeline", {});
264 + expect(() => store.updatePipeline(pipeline.id, { status: "completed" }))
265 + .not.toThrow();
267 + const phase = store.createPhase(pipeline.id, "test-phase");
268 + expect(() => store.updatePhase(phase.id, { status: "completed" }))
269 + .not.toThrow();
270 + });
272 + test("updateRecord throws on unknown table name", () => {
273 + expect(() =>
274 + (store as any).updateRecord("evil_table", "some-id", { status: "hacked" })
276 + .toThrow(/unknown table/);
277 + });
278 +});