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 type StepStatus = "pending" | "running" | "completed" | "failed";

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;
}

export interface StepState {
  id: string;
  phase_id: string;
  name: string;
  agent: string;
  status: StepStatus;
  output: string;
  error: string | null;
  attempts: number;
}

export class Store {
  private db: Database;

  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 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
      )
    `);

    this.db.run(`
      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)
      )
    `);

    this.db.run(`
      CREATE TABLE IF NOT EXISTS step_state (
        id TEXT PRIMARY KEY,
        phase_id TEXT NOT NULL,
        name TEXT NOT NULL,
        agent TEXT NOT NULL,
        status TEXT NOT NULL,
        output TEXT,
        error TEXT,
        attempts INTEGER DEFAULT 0,
        FOREIGN KEY (phase_id) REFERENCES phase_state(id)
      )
    `);

    // Add indexes for foreign key lookups
    this.db.run(
      "CREATE INDEX IF NOT EXISTS idx_phase_pipeline ON phase_state(pipeline_id)",
    );
    this.db.run(
      "CREATE INDEX IF NOT EXISTS idx_step_phase ON step_state(phase_id)",
    );
  }

  // 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 filtered = Object.fromEntries(
      Object.entries(updates).filter(([k]) => k !== "id"),
    );
    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);
  }

  // Step operations
  createStep(phaseId: string, name: string, agent: string): StepState {
    const id = randomUUID();

    this.db.run(
      `INSERT INTO step_state (id, phase_id, name, agent, status, output, error, attempts)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [id, phaseId, name, agent, "pending", "{}", null, 0],
    );

    return this.getStep(id)!;
  }

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

    return result || null;
  }

  updateStep(id: string, updates: Partial<StepState>): void {
    this.updateRecord("step_state", id, updates);
  }

  getStepsByPhase(phaseId: string): StepState[] {
    return this.db.query<StepState, [string]>(
      "SELECT * FROM step_state WHERE phase_id = ?",
    ).all(phaseId);
  }

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