repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/plugins/chef/store.ts

Raw
File outline
import { Database } from "bun:sqlite";
import { join } from "path";
import { randomUUID } from "crypto";

export type PipelineStatus =
  | "running"
  | "completed"
  | "failed"
  | "aborted"
  | "needs_input";
export type PhaseStatus =
  | "pending"
  | "running"
  | "completed"
  | "failed"
  | "skipped";

export interface PipelineInstance {
  id: string;
  definition: string;
  status: PipelineStatus;
  input: string;
  context: string;
  current_phase: number;
  created_at: number;
  updated_at: number;
}

export interface PhaseState {
  id: string;
  pipeline_id: string;
  name: string;
  status: PhaseStatus;
  output: string;
  error: string | null;
  attempts: number;
  started_at: number | null;
  completed_at: number | null;
}

const ALLOWED_COLUMNS: Record<string, ReadonlySet<string>> = {
  pipeline_instance: new Set([
    "id",
    "definition",
    "status",
    "input",
    "context",
    "current_phase",
    "created_at",
    "updated_at",
  ]),
  phase_state: new Set([
    "id",
    "pipeline_id",
    "name",
    "status",
    "output",
    "error",
    "attempts",
    "started_at",
    "completed_at",
  ]),
};

export class Store {
  private db: Database;

  private static SCHEMA_VERSION = 2;

  private static MIGRATIONS: Array<{
    version: number;
    description: string;
    sql: string[];
  }> = [
    {
      version: 1,
      description: "Initial schema",
      sql: [
        `CREATE TABLE IF NOT EXISTS pipeline_instance (
          id TEXT PRIMARY KEY,
          definition TEXT NOT NULL,
          status TEXT NOT NULL,
          input TEXT,
          context TEXT,
          current_phase INTEGER DEFAULT 0,
          created_at INTEGER,
          updated_at INTEGER
        )`,
        `CREATE TABLE IF NOT EXISTS phase_state (
          id TEXT PRIMARY KEY,
          pipeline_id TEXT NOT NULL,
          name TEXT NOT NULL,
          status TEXT NOT NULL,
          output TEXT,
          error TEXT,
          attempts INTEGER DEFAULT 0,
          started_at INTEGER,
          completed_at INTEGER,
          FOREIGN KEY (pipeline_id) REFERENCES pipeline_instance(id)
        )`,
        `CREATE INDEX IF NOT EXISTS idx_phase_pipeline ON phase_state(pipeline_id)`,
      ],
    },
    {
      version: 2,
      description: "Remove unused step_state table",
      sql: [
        `DROP TABLE IF EXISTS step_state`,
        `DROP INDEX IF EXISTS idx_step_phase`,
      ],
    },
  ];

  constructor(directory: string) {
    const dbPath = join(directory, ".opencode/chef/chef.db");
    this.db = new Database(dbPath);
    this.db.run("PRAGMA journal_mode = WAL");
    this.initSchema();
  }

  private initSchema() {
    this.db.run(`
      CREATE TABLE IF NOT EXISTS schema_version (
        version INTEGER PRIMARY KEY,
        applied_at INTEGER
      )
    `);

    const row = this.db
      .query<{ version: number | null }, []>(
        "SELECT MAX(version) as version FROM schema_version",
      )
      .get();
    const currentVersion = row?.version ?? 0;

    for (const migration of Store.MIGRATIONS) {
      if (migration.version > currentVersion) {
        for (const sql of migration.sql) {
          this.db.run(sql);
        }
        this.db.run(
          "INSERT INTO schema_version (version, applied_at) VALUES (?, ?)",
          [migration.version, Date.now()],
        );
        console.log(
          `Chef: Applied schema migration v${migration.version}: ${migration.description}`,
        );
      }
    }
  }

  // Pipeline operations
  createPipeline(definition: string, input: any): PipelineInstance {
    const id = randomUUID();
    const now = Date.now();

    this.db.run(
      `INSERT INTO pipeline_instance (id, definition, status, input, context, current_phase, created_at, updated_at)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [id, definition, "running", JSON.stringify(input), "{}", 0, now, now],
    );

    return this.getPipeline(id)!;
  }

  getPipeline(id: string): PipelineInstance | null {
    const result = this.db.query<PipelineInstance, [string]>(
      "SELECT * FROM pipeline_instance WHERE id = ?",
    ).get(id);

    return result || null;
  }

  private updateRecord(
    table: string,
    id: string,
    updates: Record<string, any>,
    withTimestamp = false,
  ): void {
    const allowed = ALLOWED_COLUMNS[table];
    const filtered = Object.fromEntries(
      Object.entries(updates).filter(
        ([k]) => k !== "id" && (allowed ? allowed.has(k) : false),
      ),
    );
    if (Object.keys(filtered).length === 0) {
      if (withTimestamp) {
        this.db.run(
          `UPDATE ${table} SET updated_at = ? WHERE id = ?`,
          [Date.now(), id],
        );
      }
      return;
    }
    const fields = Object.keys(filtered).map((k) => `${k} = ?`).join(", ");
    const values = withTimestamp
      ? [...Object.values(filtered), Date.now(), id]
      : [...Object.values(filtered), id];
    const suffix = withTimestamp ? ", updated_at = ?" : "";
    this.db.run(
      `UPDATE ${table} SET ${fields}${suffix} WHERE id = ?`,
      values,
    );
  }

  updatePipeline(id: string, updates: Partial<PipelineInstance>): void {
    this.updateRecord("pipeline_instance", id, updates, true);
  }

  listPipelines(status?: PipelineStatus): PipelineInstance[] {
    if (status) {
      return this.db.query<PipelineInstance, [string]>(
        "SELECT * FROM pipeline_instance WHERE status = ? ORDER BY created_at DESC",
      ).all(status);
    }

    return this.db.query<PipelineInstance, []>(
      "SELECT * FROM pipeline_instance ORDER BY created_at DESC",
    ).all([]);
  }

  // Phase operations
  createPhase(pipelineId: string, name: string): PhaseState {
    const id = randomUUID();

    this.db.run(
      `INSERT INTO phase_state (id, pipeline_id, name, status, output, error, attempts, started_at, completed_at)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [id, pipelineId, name, "pending", "{}", null, 0, null, null],
    );

    return this.getPhase(id)!;
  }

  getPhase(id: string): PhaseState | null {
    const result = this.db.query<PhaseState, [string]>(
      "SELECT * FROM phase_state WHERE id = ?",
    ).get(id);

    return result || null;
  }

  updatePhase(id: string, updates: Partial<PhaseState>): void {
    this.updateRecord("phase_state", id, updates);
  }

  getPhasesByPipeline(pipelineId: string): PhaseState[] {
    return this.db.query<PhaseState, [string]>(
      "SELECT * FROM phase_state WHERE pipeline_id = ? ORDER BY started_at ASC",
    ).all(pipelineId);
  }

  close() {
    this.db.close();
  }
}