// engine/db/migrations/012-steering-deliveries.js
//
// W-mq066js7000fff1f-a (Gap D): observable steering delivery state.
//
// Adds the `steering_deliveries` table — one row per inbox steering
// message — so the engine can transition each message through a
// well-defined state machine (queued → live_kill | deferred →
// re_spawning → delivered → acknowledged) instead of relying on the
// stdout-timestamp heuristic alone for visibility. The legacy
// heuristic ack (engine/steering.js#ackProcessedSteeringMessages) is
// kept as a back-compat path for inbox files that predate this
// migration (no `steerId:` in frontmatter, no row in this table).
//
// SQL-first per CLAUDE.md "New state goes into SQL first" — no JSON
// sidecar; reads/writes go through engine/steering-store.js.

module.exports = {
  version: 12,
  description: 'steering_deliveries: observable delivery-state rows for inbox steering messages',
  up(db) {
    db.exec(`
      CREATE TABLE steering_deliveries (
        id                TEXT PRIMARY KEY,
        agent_id          TEXT NOT NULL,
        message_id        TEXT NOT NULL,
        dispatch_id       TEXT,
        status            TEXT NOT NULL,
        created_at        INTEGER,
        updated_at        INTEGER,
        delivered_at      INTEGER,
        acknowledged_at   INTEGER,
        last_error        TEXT,
        payload_excerpt   TEXT,
        source            TEXT,
        runtime           TEXT
      );
      CREATE INDEX idx_steering_deliveries_agent_id_created
        ON steering_deliveries(agent_id, created_at DESC);
      CREATE INDEX idx_steering_deliveries_status
        ON steering_deliveries(status);
    `);
  },
};
