"use strict"; const { AgentRpcError } = require("./private-rpc"); const STATE_FIELDS = "enabled, CAST(generation AS CHAR) AS generation, UNIX_TIMESTAMP(enabled_since) * 1000 AS enabled_since_ms"; const AUTOMATIC_EDIT_STOP_ERROR_SQL = "WHEN auto_approve_file_edits = TRUE AND auto_file_edit_attempts > 0 THEN 'agent_automatic_edit_interrupted'"; const LEGACY_AUTOMATIC_EDIT_QUARANTINE_SQL = `UPDATE ai_agent_jobs SET status = 'failed', completed_at = NOW(), error = 'agent_automatic_edit_upgrade' WHERE status = 'queued' AND auto_approve_file_edits = TRUE AND auto_file_edit_generation IS NULL`; async function ensureAgentQueueSchema(db) { await db.query(`CREATE TABLE IF NOT EXISTS ai_agent_worker_state ( id TINYINT UNSIGNED PRIMARY KEY, enabled BOOLEAN NOT NULL DEFAULT FALSE, generation BIGINT UNSIGNED NOT NULL DEFAULT 0, enabled_since DATETIME(3) NULL ) ENGINE=InnoDB`); await db.query("INSERT IGNORE INTO ai_agent_worker_state (id) VALUES (1)"); await db.query(`CREATE TABLE IF NOT EXISTS ai_agent_schedule_receipts ( schedule_ref CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, occurrence_ref CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, job_id BIGINT UNSIGNED NULL, chat_id BIGINT UNSIGNED NULL, PRIMARY KEY (schedule_ref, occurrence_ref) ) ENGINE=InnoDB`); const additions = [ ["ADD COLUMN feature_generation BIGINT UNSIGNED NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN claim_token CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN request_key CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN request_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN submission_message_id BIGINT UNSIGNED NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN result_message_id BIGINT UNSIGNED NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN action_proposal MEDIUMTEXT NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN action_review_state VARCHAR(16) NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN action_edit_result VARCHAR(160) NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN action_file_edits MEDIUMTEXT NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN read_only BOOLEAN NOT NULL DEFAULT FALSE", "ER_DUP_FIELDNAME"], ["ADD COLUMN review_file_plan BOOLEAN NOT NULL DEFAULT FALSE", "ER_DUP_FIELDNAME"], ["ADD COLUMN account_epoch BIGINT UNSIGNED NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN auto_approve_file_edits BOOLEAN NOT NULL DEFAULT FALSE", "ER_DUP_FIELDNAME"], ["ADD COLUMN auto_file_edit_attempts TINYINT UNSIGNED NOT NULL DEFAULT 0", "ER_DUP_FIELDNAME"], ["ADD COLUMN auto_file_edit_generation BIGINT UNSIGNED NULL", "ER_DUP_FIELDNAME"], ["ADD COLUMN schedule_ref CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL", "ER_DUP_FIELDNAME"], ["ADD KEY idx_ai_agent_schedule_ref (schedule_ref, status)", "ER_DUP_KEYNAME"], ["ADD UNIQUE KEY uniq_ai_agent_submission (user_id, request_key)", "ER_DUP_KEYNAME"], ]; for (const [addition, duplicate] of additions) { try { await db.query(`ALTER TABLE ai_agent_jobs ${addition}`); } catch (error) { if (error.code !== duplicate) throw error; } } } function asState(row) { return row ? { enabled: Number(row.enabled) === 1, generation: String(row.generation), enabledSinceMs: Number(row.enabled_since_ms) } : null; } async function readAgentQueueState(db) { const [row] = await db.query(`SELECT ${STATE_FIELDS} FROM ai_agent_worker_state WHERE id = 1`); return asState(row); } async function lockAgentQueueState(connection) { const [[row]] = await connection.execute(`SELECT ${STATE_FIELDS} FROM ai_agent_worker_state WHERE id = 1 FOR UPDATE`); if (!row) throw new AgentRpcError(503, "agent_unavailable"); return asState(row); } async function retireAgentSchedule(connection, scheduleRef) { await lockAgentQueueState(connection); // adpanel:agent-schedule-retirement - the marker and queued-job retraction commit together under the admission lock. await connection.execute(`INSERT INTO ai_agent_schedule_receipts (schedule_ref, occurrence_ref) VALUES (?, '') ON DUPLICATE KEY UPDATE occurrence_ref = ''`, [scheduleRef]); } async function transact(pool, operation) { const connection = await pool.getConnection(); try { await connection.beginTransaction(); const result = await operation(connection); await connection.commit(); return result; } catch (error) { try { await connection.rollback(); } catch { connection.destroy(); } throw error; } finally { connection.release(); } } async function reconcileAgentQueueState(pool, enabled) { return transact(pool, async (connection) => { const state = await lockAgentQueueState(connection); if (state.enabled !== enabled) { await connection.execute(`UPDATE ai_agent_worker_state SET enabled = ?, generation = generation + 1, enabled_since = IF(?, CURRENT_TIMESTAMP(3), NULL) WHERE id = 1`, [enabled, enabled]); } if (!enabled || state.enabled !== enabled) { // adpanel:agent-generation - a disabled generation cannot publish or replay its work after re-enable. await connection.execute(`UPDATE ai_agent_jobs SET status = 'cancelled', completed_at = NOW(), error = CASE ${AUTOMATIC_EDIT_STOP_ERROR_SQL} ELSE 'agent_disabled' END WHERE status IN ('queued','running')`); } else { await connection.execute(LEGACY_AUTOMATIC_EDIT_QUARANTINE_SQL); } return lockAgentQueueState(connection); }); } function agentOccurrencePredatesEnable(job, state) { if (!state?.enabled) return true; const repeatAt = Number(job.opts?.prevMillis); const scheduledAt = repeatAt > 0 ? repeatAt : Number(job.timestamp) + (Number(job.opts?.delay ?? job.delay) || 0); return !Number.isFinite(scheduledAt) || scheduledAt < state.enabledSinceMs; } module.exports = { AUTOMATIC_EDIT_STOP_ERROR_SQL, LEGACY_AUTOMATIC_EDIT_QUARANTINE_SQL, ensureAgentQueueSchema, readAgentQueueState, lockAgentQueueState, transact, reconcileAgentQueueState, agentOccurrencePredatesEnable, retireAgentSchedule };