ALTER TABLE `task_occurrences` ADD `closed_at` integer;--> statement-breakpoint
-- Recover the state at the deadline from the first correction after it, when present.
-- This also repairs expiry previously inferred from an uncheck made after completion.
UPDATE task_occurrences
SET closed_at = (SELECT ends_at FROM habit_days WHERE id = task_occurrences.day_id),
    expired_at = CASE WHEN COALESCE(
      (SELECT json_extract(e.before, '$.done') FROM progress_events e
       WHERE e.occurrence_id = task_occurrences.id
         AND e.created_at >= (SELECT ends_at FROM habit_days WHERE id = task_occurrences.day_id)
       ORDER BY e.created_at, e.id LIMIT 1), done) = 0
      THEN (SELECT ends_at FROM habit_days WHERE id = task_occurrences.day_id)
      ELSE NULL END
WHERE day_id IN (
  SELECT d.id FROM habit_days d
  WHERE d.ends_at <= CAST(unixepoch('subsec') * 1000 AS INTEGER)
    AND d.id = (SELECT MAX(d2.id) FROM habit_days d2 WHERE d2.habit_id = d.habit_id AND d2.date = d.date)
);
