-- Task tree structure changes for supervisor architecture
-- - Remove depth constraint (supervisor controls task hierarchy)
-- - Add checkpoint tracking
-- - Add is_supervisor flag
-- - Add supervisor_task_id to contracts

-- Drop the depth constraint (supervisor handles task spawning rules at application level)
ALTER TABLE tasks DROP CONSTRAINT IF EXISTS tasks_depth_check;

-- Add is_supervisor flag to identify contract supervisor tasks
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS is_supervisor BOOLEAN NOT NULL DEFAULT false;

-- Git checkpoint tracking
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS last_checkpoint_sha VARCHAR(40);
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS checkpoint_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS checkpoint_message TEXT;

-- Conversation state preservation for task branches
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS conversation_state JSONB;

-- Daemon migration tracking
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS migrated_from_daemon_id UUID;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS last_active_daemon_id UUID;

-- Add supervisor_task_id to contracts
ALTER TABLE contracts ADD COLUMN IF NOT EXISTS supervisor_task_id UUID REFERENCES tasks(id) ON DELETE SET NULL;

-- Index for tree queries
CREATE INDEX IF NOT EXISTS idx_tasks_tree_path ON tasks(contract_id, parent_task_id, created_at);

-- Index for supervisor lookup
CREATE INDEX IF NOT EXISTS idx_tasks_is_supervisor ON tasks(contract_id, is_supervisor) WHERE is_supervisor = true;

-- Index for checkpoint lookup
CREATE INDEX IF NOT EXISTS idx_tasks_checkpoint_sha ON tasks(last_checkpoint_sha) WHERE last_checkpoint_sha IS NOT NULL;

COMMENT ON COLUMN tasks.is_supervisor IS 'True for contract supervisor tasks. Only supervisors can spawn new tasks.';
COMMENT ON COLUMN tasks.last_checkpoint_sha IS 'Git commit SHA of the most recent checkpoint';
COMMENT ON COLUMN tasks.checkpoint_count IS 'Number of checkpoints created by this task';
COMMENT ON COLUMN tasks.conversation_state IS 'Saved conversation context for task resumption';
COMMENT ON COLUMN contracts.supervisor_task_id IS 'The long-running supervisor task that orchestrates this contract';
