Skip to content

🎬 Open-source, self-hosted AI agent that runs a YouTube channel end to end: researches topics, writes scripts, generates narration, visuals and video, optimizes SEO, and publishes after your approval, then learns from analytics. Works with Gemini, OpenAI, OpenRouter, DeepSeek and more.

Release v2.7 resumable production runs

darkzOGx0d77cc649808
diff --git a/.env.example b/.env.example
index 87977fb..886877e 100644
--- a/.env.example
+++ b/.env.example
@@ -63,6 +63,10 @@ API_KEY=
# Optional. Generation jobs run one at a time by default to control API spend.
MAX_CONCURRENT_JOBS=1
+# Optional. Each retry-safe generation stage gets one bounded retry by default.
+GENERATION_STAGE_MAX_ATTEMPTS=2
+GENERATION_RETRY_BASE_MS=1000
+
# Optional Slack/Discord-compatible webhook for failures and review alerts.
# NOTIFICATION_WEBHOOK_URL=https://hooks.example.com/...
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6ada4d0..6b8cc2b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,15 @@
## Unreleased
+## v2.7.0 — 2026-08-21
+
+- Added persistent per-stage generation checkpoints with artifact validation, bounded retry-safe backoff, and resume-from-first-incomplete behavior
+- Added dashboard controls to resume failed or interrupted jobs from a selected stage while showing saved and reused stages
+- Added Autonomous Channel Operator recovery from stored research, editorial plans, ideas, and interrupted generation jobs
+- Preserved the actual generation stage across application restarts instead of replacing it with a generic interrupted stage
+- Made scheduling idempotent per production and added YouTube upload reconciliation so recorded or uncertain uploads cannot be duplicated automatically
+- Added API endpoints for individual-job and operator-run recovery plus regression coverage for restart, reuse, transient retry, and duplicate-upload safety
+
## v2.6.0 — 2026-08-20
- Added a user-triggered Production Readiness Gate with live text, narration, YouTube-access, local audio/video MP4, and queued-metadata probes; paid image verification is explicit opt-in
diff --git a/README.md b/README.md
index 44fb2fd..37d3c38 100644
--- a/README.md
+++ b/README.md
@@ -8,14 +8,15 @@ Research topics → write scripts → generate narration and visuals → assembl
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Node.js 18+](https://img.shields.io/badge/node-18%2B-43853d.svg)](package.json)
-## What's new in version 2.6.0
+## What's new in version 2.7.0
-Version 2.6 turns the agent into a safer, self-improving channel operator:
+Version 2.7 makes long-running production recoverable instead of disposable:
-- **Autonomous Channel Operator:** define the audience, objective, content pillars, cadence, and guardrails once; the agent researches, plans, and runs the production workflow.
-- **Closed-loop channel learning:** real 24-hour and 7-day analytics become evidence-backed recommendations that influence future plans only after you approve them.
-- **Production Readiness Gate:** verify text, narration, FFmpeg, YouTube access, and upload metadata before autonomous production or publishing begins.
-- **Safer packaging experiments:** review and select title and thumbnail variants without silently changing live YouTube metadata.
+- **Resumable generation:** strategy, script, thumbnail, SEO, production, and quality-review stages persist as checkpoints and resume from the first unfinished stage.
+- **Selective retry controls:** choose exactly which stage to regenerate while reusing earlier verified artifacts and tracking saved stages in the dashboard.
+- **Operator-run recovery:** interrupted autonomous runs continue from their saved research, editorial plan, ideas, and generation jobs.
+- **Duplicate-upload protection:** YouTube video IDs are persisted immediately; known uploads are reconciled, while uncertain outcomes stop for manual verification instead of uploading twice.
+- **Bounded transient retries:** retry-safe provider and network failures receive one backoff retry without weakening approval, rights, readiness, or publishing gates.
See the complete release history in [CHANGELOG.md](CHANGELOG.md).
@@ -49,6 +50,12 @@ AI image generation can incur a larger provider charge, so its live probe is a s
Results persist locally in SQLite with exact remediation steps. A recorded blocking failure stops autonomous generation and publishing until a later run passes; manual work remains available when readiness has never been checked or the last result is older than 24 hours.
+### Resume an interrupted production
+
+Every generation stage writes a local SQLite checkpoint. If a provider times out or the application restarts, the dashboard shows the saved-stage count and the first incomplete stage. Choose **Resume** to continue from there, or select an earlier stage when you intentionally want to regenerate that stage and everything after it. Saved files are validated before reuse; missing artifacts are regenerated automatically.
+
+Autonomous Operator runs preserve their research and editorial plan, so **Resume run** continues unfinished plan items instead of researching and generating completed videos again. Publishing remains fail-closed: if an upload may have reached YouTube but no video ID was returned, Lumen requires channel reconciliation before another upload attempt.
+
### What you need
- Node.js 18+
@@ -211,6 +218,11 @@ TARGET_AUDIENCE=Your target audience
YOUTUBE_REGION=US
DEFAULT_PRIVACY_STATUS=private
+# Optional recovery tuning (defaults shown)
+MAX_CONCURRENT_JOBS=1
+GENERATION_STAGE_MAX_ATTEMPTS=2
+GENERATION_RETRY_BASE_MS=1000
+
# Optional: protect mutating API routes (POST /generate, /publish)
# API_KEY=some-long-random-string
@@ -265,6 +277,18 @@ curl -X POST http://localhost:3456/generate \
# inspect the returned background job
curl http://localhost:3456/api/jobs/:jobId
+# resume a failed/interrupted job from its first incomplete checkpoint
+curl -X POST http://localhost:3456/api/jobs/:jobId/resume \
+ -H "Content-Type: application/json" \
+ -H "x-api-key: $API_KEY" \
+ -d '{}'
+
+# intentionally regenerate a selected stage and everything after it
+curl -X POST http://localhost:3456/api/jobs/:jobId/resume \
+ -H "Content-Type: application/json" \
+ -H "x-api-key: $API_KEY" \
+ -d '{"stage":"thumbnail"}'
+
# inspect the latest production-readiness evidence
curl http://localhost:3456/api/readiness
@@ -286,6 +310,10 @@ curl -X POST http://localhost:3456/api/operator/start \
-H "x-api-key: $API_KEY" \
-d '{}'
+# resume an interrupted operator run from its saved plan
+curl -X POST http://localhost:3456/api/operator/runs/:runId/resume \
+ -H "x-api-key: $API_KEY"
+
# view schedule
curl http://localhost:3456/schedule
diff --git a/agents/publishing-scheduling-agent.js b/agents/publishing-scheduling-agent.js
index 2b027ce..3c822ef 100644
--- a/agents/publishing-scheduling-agent.js
+++ b/agents/publishing-scheduling-agent.js
@@ -51,6 +51,15 @@ class PublishingSchedulingAgent {
}
this.logger.info(`Scheduling content: ${productionData.id}`);
+ const existing = await this.db.getLatestScheduleEntry?.(productionData.id);
+ if (existing) {
+ if (['scheduled', 'paused'].includes(existing.status) && !this.publishQueue.some(entry => entry.id === existing.id)) {
+ this.publishQueue.push(existing);
+ this.publishQueue.sort((a, b) => new Date(a.publishTime) - new Date(b.publishTime));
+ }
+ this.logger.info(`Reusing existing ${existing.status} schedule entry for: ${productionData.id}`);
+ return existing;
+ }
const scheduleEntry = {
productionId: productionData.id,
@@ -68,13 +77,12 @@ class PublishingSchedulingAgent {
createdAt: new Date().toISOString()
};
- this.publishQueue.push(scheduleEntry);
+ const saved = await this.db.saveScheduleEntry(scheduleEntry) || scheduleEntry;
+ this.publishQueue.push(saved);
this.publishQueue.sort((a, b) => new Date(a.publishTime) - new Date(b.publishTime));
- await this.db.saveScheduleEntry(scheduleEntry);
-
- this.logger.info(`Content scheduled for: ${scheduleEntry.publishTime}`);
- return scheduleEntry;
+ this.logger.info(`Content scheduled for: ${saved.publishTime}`);
+ return saved;
} catch (error) {
this.logger.error('Failed to schedule content:', error);
throw error;
@@ -97,16 +105,48 @@ class PublishingSchedulingAgent {
}
this.logger.info(`Publishing content: ${contentId}`);
- const scheduleEntry = this.publishQueue.find(entry =>
+ let scheduleEntry = this.publishQueue.find(entry =>
entry.productionId === contentId || entry.id === contentId
);
+ if (!scheduleEntry && this.db.getLatestScheduleEntry) {
+ scheduleEntry = await this.db.getLatestScheduleEntry(contentId);
+ }
if (!scheduleEntry) {
throw new Error(`Content not found in queue: ${contentId}`);
}
+ if (scheduleEntry.status === 'published') return scheduleEntry;
+ if (scheduleEntry.youtubeId) {
+ return this.reconcileUploadedVideo(scheduleEntry);
+ }
+ if (['uploading', 'reconciliation_required'].includes(scheduleEntry.status)) {
+ const error = new Error('A previous upload may have reached YouTube without returning a video ID. Reconcile the channel before attempting another upload.');
+ error.status = 409;
+ error.code = 'UPLOAD_OUTCOME_UNKNOWN';
+ throw error;
+ }
+
+ scheduleEntry.status = 'uploading';
+ scheduleEntry.error = null;
+ await this.db.updateScheduleEntry(scheduleEntry);
- // Upload video to YouTube
- const uploadResult = await this.uploadToYouTube(scheduleEntry);
+ let uploadResult;
+ try {
+ uploadResult = await this.uploadToYouTube(scheduleEntry);
+ } catch (error) {
+ if (scheduleEntry.uploadAttempted && this.isUploadOutcomeUnknown(error)) {
+ scheduleEntry.status = 'reconciliation_required';
+ scheduleEntry.error = 'Upload outcome is unknown; verify the YouTube channel before retrying';
+ await this.db.updateScheduleEntry(scheduleEntry);
+ error.code = 'UPLOAD_OUTCOME_UNKNOWN';
+ error.status = 409;
+ } else {
+ scheduleEntry.status = 'failed';
+ scheduleEntry.error = error.message;
+ await this.db.updateScheduleEntry(scheduleEntry);
+ }
+ throw error;
+ }
// Update database
scheduleEntry.status = 'published';
@@ -152,17 +192,24 @@ class PublishingSchedulingAgent {
}
};
- // Upload video file
+ // Resolve the file before marking the network upload as attempted.
+ const videoStream = await this.getVideoStream(metadata.video.path);
+ scheduleEntry.uploadAttempted = true;
const videoUpload = await this.youtube.videos.insert({
part: 'snippet,status',
requestBody: videoMetadata,
media: {
- body: await this.getVideoStream(metadata.video.path)
+ body: videoStream
}
});
const videoId = videoUpload.data.id;
this.logger.info(`Video uploaded with ID: ${videoId}`);
+ scheduleEntry.status = 'uploaded';
+ scheduleEntry.youtubeId = videoId;
+ scheduleEntry.youtubeUrl = `https://www.youtube.com/watch?v=${videoId}`;
+ scheduleEntry.error = null;
+ await this.db.updateScheduleEntry(scheduleEntry);
// Upload thumbnail
if (metadata.thumbnail && metadata.thumbnail.path) {
@@ -177,6 +224,32 @@ class PublishingSchedulingAgent {
return videoUpload.data;
}
+ isUploadOutcomeUnknown(error) {
+ const status = Number(error.status || error.response?.status || 0);
+ return !status || status >= 500;
+ }
+
+ async reconcileUploadedVideo(scheduleEntry) {
+ const response = await this.youtube.videos.list({ part: 'id,status', id: scheduleEntry.youtubeId });
+ if (!response.data.items?.some(video => video.id === scheduleEntry.youtubeId)) {
+ scheduleEntry.status = 'reconciliation_required';
+ scheduleEntry.error = 'The recorded YouTube video ID could not be verified';
+ await this.db.updateScheduleEntry(scheduleEntry);
+ const error = new Error('The recorded upload could not be verified on YouTube. Resolve it before attempting another upload.');
+ error.status = 409;
+ error.code = 'UPLOAD_OUTCOME_UNKNOWN';
+ throw error;
+ }
+ scheduleEntry.status = 'published';
+ scheduleEntry.publishedAt = scheduleEntry.publishedAt || new Date().toISOString();
+ scheduleEntry.youtubeUrl = scheduleEntry.youtubeUrl || `https://www.youtube.com/watch?v=${scheduleEntry.youtubeId}`;
+ scheduleEntry.error = null;
+ await this.db.updateScheduleEntry(scheduleEntry);
+ this.publishQueue = this.publishQueue.filter(entry => entry.productionId !== scheduleEntry.productionId);
+ this.logger.success(`Reconciled existing YouTube upload: ${scheduleEntry.youtubeUrl}`);
+ return scheduleEntry;
+ }
+
async getVideoStream(videoPath) {
try {
const stats = await fs.stat(videoPath);
@@ -260,9 +333,11 @@ class PublishingSchedulingAgent {
}
this.logger.error(`Failed to auto-publish ${entry.title}:`, error);
// Mark as failed but don't stop processing other items
- entry.status = 'failed';
- entry.error = error.message;
- await this.db.updateScheduleEntry(entry);
+ if (error.code !== 'UPLOAD_OUTCOME_UNKNOWN') {
+ entry.status = 'failed';
+ entry.error = error.message;
+ await this.db.updateScheduleEntry(entry);
+ }
}
}
diff --git a/dashboard/app.js b/dashboard/app.js
index 2aab3fb..90abcb7 100644
--- a/dashboard/app.js
+++ b/dashboard/app.js
@@ -109,7 +109,7 @@ function renderDashboard() {
const state = ui.state;
const reviews = state.pipeline.filter(item => ['needs_review', 'needs_attention'].includes(item.review_status));
const scheduled = state.schedule.filter(item => item.status === 'scheduled');
- const activeJobs = state.jobs.filter(job => ['queued', 'running'].includes(job.status));
+ const actionableJobs = state.jobs.filter(job => ['queued', 'running', 'failed', 'interrupted'].includes(job.status));
$('#brand-name').textContent = state.profile?.channel_name || 'Automation Studio';
$('#setup-banner').classList.toggle('hidden', !state.system.setupRequired);
@@ -129,7 +129,7 @@ function renderDashboard() {
$('#stat-score').textContent = state.analytics.averagePerformanceScore ? `${state.analytics.averagePerformanceScore}/100` : '—';
renderReviews(reviews);
- renderJobs(activeJobs.length ? activeJobs : state.jobs.slice(0, 5));
+ renderJobs(actionableJobs.length ? actionableJobs : state.jobs.slice(0, 5));
renderSchedule(state.schedule.slice(0, 5), '#next-schedule');
renderNotifications(state.notifications, state.events);
renderPipeline(state.pipeline);
@@ -192,15 +192,24 @@ function renderJobs(jobs) {
container.innerHTML = empty('No generation runs yet.');
return;
}
- container.innerHTML = jobs.slice(0, 6).map(job => `
+ const stages = ['strategy', 'script', 'thumbnail', 'seo', 'production', 'quality_review'];
+ container.innerHTML = jobs.slice(0, 6).map(job => {
+ const checkpoints = Array.isArray(job.checkpoints) ? job.checkpoints : [];
+ const completed = new Set(checkpoints.filter(item => item.status === 'completed').map(item => item.stage));
+ const resumeFrom = stages.find(stage => !completed.has(stage)) || 'quality_review';
+ const recoverable = ['failed', 'interrupted'].includes(job.status);
+ return `
<article class="job-card">
<div class="job-meta">
<strong>${escapeHTML(job.title || job.topic || 'Agent-selected topic')}</strong>
<div class="meta-line">${statusChip(job.status)} · ${escapeHTML(label(job.stage))} · ${timeAgo(job.updated_at)}</div>
+ ${checkpoints.length ? `<div class="checkpoint-line">${completed.size}/${stages.length} stages saved${job.details?.reusedStages?.length ? ` · ${job.details.reusedStages.length} reused` : ''}</div>` : ''}
<div class="progress"><i style="width:${Math.max(0, Math.min(100, job.progress || 0))}%"></i></div>
</div>
${['queued', 'running'].includes(job.status) ? `<button class="text-button" data-cancel-job="${escapeHTML(job.id)}">Cancel</button>` : ''}
- </article>`).join('');
+ ${recoverable ? `<div class="job-recovery"><select data-resume-stage-for="${escapeHTML(job.id)}" aria-label="Stage to resume from">${stages.map(stage => `<option value="${stage}" ${stage === resumeFrom ? 'selected' : ''}>${escapeHTML(label(stage))}</option>`).join('')}</select><button class="button secondary small" data-resume-job="${escapeHTML(job.id)}">Resume</button></div>` : ''}
+ </article>`;
+ }).join('');
}
function renderSchedule(schedule, selector) {
@@ -376,12 +385,16 @@ function renderOperator(strategy, runs, system) {
$('#operator-strategy-status').textContent = label(strategyStatus);
const run = runs[0];
const active = run && ['queued', 'running', 'cancelling'].includes(run.status);
+ const recoverable = run && ['failed', 'interrupted', 'completed_with_issues'].includes(run.status);
$('#activate-operator-button').disabled = Boolean(system.setupRequired || active || system.readiness?.status === 'failed');
$('#activate-operator-button').title = system.readiness?.status === 'failed' ? 'Resolve the production readiness failures first' : '';
$('#activate-operator-button').textContent = strategy?.status === 'active' ? 'Run strategy now' : 'Activate & run now';
$('#pause-operator-button').classList.toggle('hidden', strategy?.status !== 'active');
$('#cancel-operator-run').classList.toggle('hidden', !active);
if (active) $('#cancel-operator-run').dataset.runId = run.id;
+ $('#resume-operator-run').classList.toggle('hidden', !recoverable);
+ $('#resume-operator-run').disabled = Boolean(system.setupRequired || system.readiness?.status === 'failed');
+ if (recoverable) $('#resume-operator-run').dataset.runId = run.id;
if (!run) {
$('#operator-run-title').textContent = 'Waiting for a strategy';
@@ -558,6 +571,16 @@ document.addEventListener('click', async event => {
await mutate(`/api/ideas/${encodeURIComponent(idea.dataset.generateIdea)}/generate`, 'POST', { length: 'medium' }, 'Idea queued for generation.').catch(() => {});
}
+ const resume = event.target.closest('[data-resume-job]');
+ if (resume) {
+ const jobId = resume.dataset.resumeJob;
+ const select = $$('[data-resume-stage-for]').find(item => item.dataset.resumeStageFor === jobId);
+ const stage = select?.value;
+ if (confirm(`Resume this job from ${label(stage)}? Later checkpoints will be regenerated.`)) {
+ await mutate(`/api/jobs/${encodeURIComponent(jobId)}/resume`, 'POST', { stage }, `Generation resumed from ${label(stage)}.`).catch(() => {});
+ }
+ }
+
const learning = event.target.closest('[data-learning-action]');
if (learning) {
const action = learning.dataset.learningAction;
@@ -662,6 +685,13 @@ $('#cancel-operator-run').addEventListener('click', async event => {
}
});
+$('#resume-operator-run').addEventListener('click', async event => {
+ const runId = event.currentTarget.dataset.runId;
+ if (runId && confirm('Resume this operator run from its saved editorial plan and generation checkpoints?')) {
+ await mutate(`/api/operator/runs/${encodeURIComponent(runId)}/resume`, 'POST', {}, 'Autonomous operator resumed.').catch(() => {});
+ }
+});
+
$('#generate-form').addEventListener('submit', async event => {
event.preventDefault();
const values = Object.fromEntries(new FormData(event.currentTarget));
diff --git a/dashboard/index.html b/dashboard/index.html
index d4343e6..06b1ffd 100644
--- a/dashboard/index.html
+++ b/dashboard/index.html
@@ -98,7 +98,7 @@
</form>
<div class="operator-side">
<article class="panel">
- <div class="panel-heading"><div><p class="eyebrow">CURRENT RUN</p><h2 id="operator-run-title">Waiting for a strategy</h2></div><button id="cancel-operator-run" class="text-button hidden">Stop run</button></div>
+ <div class="panel-heading"><div><p class="eyebrow">CURRENT RUN</p><h2 id="operator-run-title">Waiting for a strategy</h2></div><div class="run-actions"><button id="resume-operator-run" class="text-button approve hidden">Resume run</button><button id="cancel-operator-run" class="text-button hidden">Stop run</button></div></div>
<div id="operator-run-summary"></div>
</article>
<article class="panel">
diff --git a/dashboard/styles.css b/dashboard/styles.css
index d69b23a..4a78fc1 100644
--- a/dashboard/styles.css
+++ b/dashboard/styles.css
@@ -14,7 +14,7 @@
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* { box-sizing: border-box; }
-body { margin: 0; color: var(--text); background: radial-gradient(circle at 80% 0%, #17131b 0, var(--bg) 30%); min-height: 100vh; }
+body { margin: 0; color: var(--text); background: radial-gradient(circle at 80% 0%, #17131b 0, var(--bg) 30%); min-height: 100vh; overflow-x: hidden; }
button, input, select, textarea { font: inherit; }
button { color: inherit; }
.app-shell { display: grid; grid-template-columns: 248px 1fr; min-height: 100vh; }
@@ -60,7 +60,7 @@ h2 { letter-spacing: -.025em; margin-bottom: 0; }
.setup-banner code { background: #0b0e12; border: 1px solid var(--line); border-radius: 8px; padding: 9px 12px; white-space: nowrap; }
@keyframes enter { from { opacity: 0; transform: translateY(5px); } }
.stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; margin-bottom: 18px; }
-.stat, .panel { border: 1px solid var(--line); background: linear-gradient(150deg, rgba(21,26,34,.96), rgba(13,16,21,.96)); border-radius: var(--radius); }
+.stat, .panel { min-width: 0; border: 1px solid var(--line); background: linear-gradient(150deg, rgba(21,26,34,.96), rgba(13,16,21,.96)); border-radius: var(--radius); }
.stat { padding: 20px; min-height: 128px; display: flex; flex-direction: column; }
.stat span, .stat small { color: var(--muted); }
.stat span { font-size: 12px; text-transform: uppercase; letter-spacing: .08em; }
@@ -80,9 +80,12 @@ h2 { letter-spacing: -.025em; margin-bottom: 0; }
.review-meta, .job-meta, .timeline-meta, .idea-meta { min-width: 0; flex: 1; }
.review-meta strong, .job-meta strong, .timeline-meta strong, .idea-meta strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.meta-line { color: var(--muted); font-size: 12px; margin-top: 5px; }
+.checkpoint-line { color: var(--green); font-size: 11px; margin-top: 7px; }
+.job-recovery, .run-actions { display: flex; align-items: center; gap: 8px; min-width: 0; }
+.job-recovery select { width: 132px; padding: 7px 9px; }
.status { display: inline-flex; align-items: center; border-radius: 999px; padding: 4px 8px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .05em; background: rgba(114,165,255,.12); color: var(--blue); }
.status.needs_review, .status.queued { color: var(--amber); background: rgba(245,185,68,.12); }
-.status.needs_attention, .status.failed, .status.rejected { color: #ff8994; background: var(--red-soft); }
+.status.needs_attention, .status.failed, .status.interrupted, .status.reconciliation_required, .status.rejected { color: #ff8994; background: var(--red-soft); }
.status.approved, .status.scheduled, .status.published, .status.completed, .status.passed { color: var(--green); background: rgba(72,213,151,.12); }
.status.warning, .status.skipped, .status.unverified { color: var(--amber); background: rgba(245,185,68,.12); }
.progress { height: 5px; border-radius: 99px; background: #262c35; margin-top: 9px; overflow: hidden; }
@@ -201,16 +204,17 @@ label small { color: var(--muted); font-weight: 400; }
.toast.error { border-color: var(--red); }
.hidden { display: none !important; }
@media (max-width: 900px) {
- .app-shell { grid-template-columns: 1fr; }
+ .app-shell { grid-template-columns: minmax(0, 1fr); width: 100%; max-width: 100vw; overflow: hidden; }
.sidebar { position: static; height: auto; border-right: 0; border-bottom: 1px solid var(--line); padding: 16px; }
.brand { padding-bottom: 14px; }
nav { display: flex; overflow-x: auto; }
.nav-item { white-space: nowrap; }
.sidebar-footer { display: none; }
- main { padding: 0 18px 60px; }
+ main { width: 100%; max-width: 100vw; padding: 0 18px 60px; }
.loading-bar { left: 0; }
.stats-grid { grid-template-columns: 1fr 1fr; }
.overview-grid, .overview-grid.lower, .calendar-grid, .content-layout, .operator-grid, .learning-grid, .readiness-hero, .readiness-grid { grid-template-columns: 1fr; }
+ .overview-grid, .card-list, .job-card { min-width: 0; max-width: 100%; }
.pipeline-item { grid-template-columns: 1fr auto; }
.pipeline-col { display: none; }
}
@@ -220,4 +224,8 @@ label small { color: var(--muted); font-weight: 400; }
.stats-grid, .form-grid, .form-grid.two, .quality-grid { grid-template-columns: 1fr; }
.full-row { grid-column: auto; }
.stat { min-height: 110px; }
+ .section-intro, .split-heading, .panel-heading, .form-actions { align-items: flex-start; flex-wrap: wrap; }
+ .job-card { align-items: flex-start; flex-wrap: wrap; }
+ .job-recovery { width: auto; max-width: 100%; flex: 1 1 100%; }
+ .job-recovery select { width: auto; min-width: 0; flex: 1; }
}
diff --git a/database/db.js b/database/db.js
index 7528897..fde671f 100644
--- a/database/db.js
+++ b/database/db.js
@@ -234,6 +234,19 @@ class Database {
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
completed_at TEXT
)`,
+ `CREATE TABLE IF NOT EXISTS generation_checkpoints (
+ job_id TEXT NOT NULL,
+ stage TEXT NOT NULL,
+ status TEXT DEFAULT 'pending',
+ artifact TEXT,
+ attempt_count INTEGER DEFAULT 0,
+ error TEXT,
+ started_at TEXT,
+ completed_at TEXT,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (job_id, stage),
+ FOREIGN KEY (job_id) REFERENCES generation_jobs(id)
+ )`,
`CREATE TABLE IF NOT EXISTS production_snapshots (
production_id TEXT PRIMARY KEY,
strategy TEXT,
@@ -626,11 +639,16 @@ class Database {
async createGenerationJob(input = {}) {
const id = this.generateId('job');
+ const details = {
+ strategyContext: input.strategyContext || {},
+ resumeCount: 0,
+ reusedStages: []
+ };
await this.executeQuery(
`INSERT INTO generation_jobs (
id, topic, style, length, source, status, stage, progress, details
) VALUES (?, ?, ?, ?, ?, 'queued', 'queued', 0, ?)`,
- [id, input.topic || null, input.style || null, input.length || 'medium', input.source || 'manual', '{}']
+ [id, input.topic || null, input.style || null, input.length || 'medium', input.source || 'manual', JSON.stringify(details)]
);
return this.getGenerationJob(id);
}
@@ -666,12 +684,70 @@ class Database {
async listGenerationJobs(limit = 30) {
const rows = await this.getAllRows('SELECT * FROM generation_jobs ORDER BY created_at DESC LIMIT ?', [limit]);
- return rows.map(row => ({ ...row, details: JSON.parse(row.details || '{}'), cancelRequested: Boolean(row.cancel_requested) }));
+ return Promise.all(rows.map(async row => {
+ const job = { ...row, details: JSON.parse(row.details || '{}'), cancelRequested: Boolean(row.cancel_requested) };
+ job.checkpoints = await this.listGenerationCheckpoints(job.id);
+ return job;
+ }));
+ }
+
+ async saveGenerationCheckpoint(jobId, stage, changes = {}) {
+ const current = await this.getGenerationCheckpoint(jobId, stage);
+ const artifact = changes.artifact === undefined ? current?.artifact : changes.artifact;
+ const attemptCount = changes.incrementAttempt
+ ? Number(current?.attempt_count || 0) + 1
+ : changes.attemptCount ?? current?.attempt_count ?? 0;
+ await this.executeQuery(
+ `INSERT INTO generation_checkpoints (
+ job_id, stage, status, artifact, attempt_count, error, started_at, completed_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
+ ON CONFLICT(job_id, stage) DO UPDATE SET
+ status = excluded.status, artifact = excluded.artifact,
+ attempt_count = excluded.attempt_count, error = excluded.error,
+ started_at = excluded.started_at, completed_at = excluded.completed_at,
+ updated_at = datetime('now')`,
+ [
+ jobId,
+ stage,
+ changes.status ?? current?.status ?? 'pending',
+ artifact === undefined ? null : JSON.stringify(artifact),
+ attemptCount,
+ changes.error === undefined ? current?.error ?? null : changes.error,
+ changes.startedAt === undefined ? current?.started_at ?? null : changes.startedAt,
+ changes.completedAt === undefined ? current?.completed_at ?? null : changes.completedAt
+ ]
+ );
+ return this.getGenerationCheckpoint(jobId, stage);
+ }
+
+ async getGenerationCheckpoint(jobId, stage) {
+ const row = await this.getRow(
+ 'SELECT * FROM generation_checkpoints WHERE job_id = ? AND stage = ?',
+ [jobId, stage]
+ );
+ return row ? { ...row, artifact: JSON.parse(row.artifact || 'null') } : null;
+ }
+
+ async listGenerationCheckpoints(jobId) {
+ const rows = await this.getAllRows(
+ 'SELECT * FROM generation_checkpoints WHERE job_id = ? ORDER BY updated_at, stage',
+ [jobId]
+ );
+ return rows.map(row => ({ ...row, artifact: JSON.parse(row.artifact || 'null') }));
+ }
+
+ async deleteGenerationCheckpoints(jobId, stages = []) {
+ if (!stages.length) return;
+ const placeholders = stages.map(() => '?').join(', ');
+ await this.executeQuery(
+ `DELETE FROM generation_checkpoints WHERE job_id = ? AND stage IN (${placeholders})`,
+ [jobId, ...stages]
+ );
}
async markInterruptedJobs() {
await this.executeQuery(
- `UPDATE generation_jobs SET status = 'interrupted', stage = 'interrupted',
+ `UPDATE generation_jobs SET status = 'interrupted',
error = 'The application restarted before this job finished', updated_at = datetime('now'),
completed_at = datetime('now') WHERE status IN ('queued', 'running')`
);
@@ -897,6 +973,8 @@ class Database {
// Publishing methods
async saveScheduleEntry(entry) {
+ const existing = await this.getLatestScheduleEntry(entry.productionId);
+ if (existing) return existing;
const id = this.generateId('schedule');
entry.id = id;
@@ -941,14 +1019,16 @@ class Database {
);
}
- async getPublishQueue() {
- const rows = await this.getAllRows(
- `SELECT * FROM publish_schedule
- WHERE status IN ('scheduled', 'paused')
- ORDER BY publish_time ASC`
+ async getLatestScheduleEntry(productionId) {
+ const row = await this.getRow(
+ 'SELECT * FROM publish_schedule WHERE production_id = ? ORDER BY created_at DESC LIMIT 1',
+ [productionId]
);
-
- return rows.map(row => ({
+ return row ? this.deserializeScheduleEntry(row) : null;
+ }
+
+ deserializeScheduleEntry(row) {
+ return {
...row,
productionId: row.production_id,
publishTime: row.publish_time,
@@ -957,7 +1037,17 @@ class Database {
publishedAt: row.published_at,
error: row.error_message,
metadata: JSON.parse(row.metadata || '{}')
- }));
+ };
+ }
+
+ async getPublishQueue() {
+ const rows = await this.getAllRows(
+ `SELECT * FROM publish_schedule
+ WHERE status IN ('scheduled', 'paused')
+ ORDER BY publish_time ASC`
+ );
+
+ return rows.map(row => this.deserializeScheduleEntry(row));
}
async getUpcomingSchedule(days = 7) {
@@ -971,16 +1061,7 @@ class Database {
[endDate.toISOString()]
);
- return rows.map(row => ({
- ...row,
- productionId: row.production_id,
- publishTime: row.publish_time,
- youtubeId: row.youtube_id,
- youtubeUrl: row.youtube_url,
- publishedAt: row.published_at,
- error: row.error_message,
- metadata: JSON.parse(row.metadata || '{}')
- }));
+ return rows.map(row => this.deserializeScheduleEntry(row));
}
// Analytics methods
diff --git a/index.js b/index.js
index 18a71d2..86f7c51 100644
--- a/index.js
+++ b/index.js
@@ -19,6 +19,7 @@ const { AutonomousChannelOperator } = require('./utils/autonomous-channel-operat
const { ActivationMetrics } = require('./utils/activation-metrics');
const { AnonymousTelemetry } = require('./utils/anonymous-telemetry');
const { ProductionReadinessService } = require('./utils/production-readiness-service');
+const { GenerationRecoveryService, GENERATION_STAGES } = require('./utils/generation-recovery-service');
const { version } = require('./package.json');
const chalk = require('chalk');
@@ -36,6 +37,7 @@ class YouTubeAutomationAgent {
this.activation = null;
this.telemetry = null;
this.readiness = null;
+ this.recovery = null;
this.setupRequired = false;
}
@@ -49,6 +51,10 @@ class YouTubeAutomationAgent {
this.db = new Database();
await this.db.initialize();
await this.db.markInterruptedJobs();
+ this.recovery = new GenerationRecoveryService(this.db, {
+ logger: this.logger,
+ updateJobStage: (...args) => this.updateJobStage(...args)
+ });
this.operator = new OperatorService(this.db);
this.autonomous = new AutonomousChannelOperator(this.db, {
researchAndPlan: strategy => {
@@ -56,6 +62,7 @@ class YouTubeAutomationAgent {
return this.agents.strategy.researchAndPlanChannel(strategy);
},
startGenerationJob: input => this.startGenerationJob(input),
+ resumeGenerationJob: (jobId, options) => this.resumeGenerationJob(jobId, options),
waitForGenerationJob: jobId => this.waitForGenerationJob(jobId),
notify: notification => this.operator.notify(notification)
});
@@ -388,7 +395,7 @@ class YouTubeAutomationAgent {
const result = await this.agents.publishing.publishContent(contentId);
res.json({ success: true, result });
} catch (error) {
- res.status(500).json({ success: false, error: error.message });
+ res.status(error.status || 500).json({ success: false, error: error.message });
}
});
@@ -447,9 +454,20 @@ class YouTubeAutomationAgent {
this.app.get('/api/jobs/:jobId', async (req, res) => {
const job = await this.db.getGenerationJob(req.params.jobId);
if (!job) return res.status(404).json({ error: 'Job not found' });
+ job.checkpoints = await this.db.listGenerationCheckpoints(job.id);
+ job.resumeFrom = this.recovery?.resumePoint(job.checkpoints);
return res.json(job);
});
+ this.app.post('/api/jobs/:jobId/resume', protect, async (req, res) => {
+ try {
+ const result = await this.resumeGenerationJob(req.params.jobId, { stage: req.body?.stage });
+ return res.status(202).json({ success: true, result });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message });
+ }
+ });
+
this.app.get('/api/readiness', async (_req, res) => {
if (!this.readiness) return res.status(503).json({ error: 'Readiness service is not initialized' });
return res.json(await this.readiness.getSummary());
@@ -619,6 +637,20 @@ class YouTubeAutomationAgent {
return res.json({ success: true, result: run });
});
+ this.app.post('/api/operator/runs/:runId/resume', protect, async (req, res) => {
+ try {
+ if (this.setupRequired || !this.agents.strategy) {
+ return res.status(503).json({ success: false, error: 'Finish setup before resuming the autonomous operator' });
+ }
+ await this.readiness?.assertReady('Autonomous production recovery');
+ const strategy = await this.db.getChannelStrategy();
+ const run = await this.autonomous.resume(req.params.runId, strategy);
+ return res.status(202).json({ success: true, result: run });
+ } catch (error) {
+ return res.status(error.status || 400).json({ success: false, error: error.message });
+ }
+ });
+
this.app.post('/api/learning/recommendations/:recommendationId/:action', protect, async (req, res) => {
const { recommendationId, action } = req.params;
if (!['approve', 'reject'].includes(action)) {
@@ -722,6 +754,71 @@ class YouTubeAutomationAgent {
return job;
}
+ async resumeGenerationJob(jobId, options = {}) {
+ if (this.setupRequired || !this.agents.strategy) {
+ const error = new Error('Finish setup with npm run walkthrough before resuming content generation');
+ error.status = 503;
+ throw error;
+ }
+ const job = await this.db.getGenerationJob(jobId);
+ if (!job) {
+ const error = new Error('Generation job not found');
+ error.status = 404;
+ throw error;
+ }
+ if (!['failed', 'interrupted'].includes(job.status)) {
+ const error = new Error('Only failed or interrupted generation jobs can be resumed');
+ error.status = 409;
+ throw error;
+ }
+ if (this.activeJobs.has(job.id)) {
+ const error = new Error('This generation job is already running');
+ error.status = 409;
+ throw error;
+ }
+ const maxConcurrent = Math.max(1, parseInt(process.env.MAX_CONCURRENT_JOBS || '1', 10));
+ if (this.activeJobs.size >= maxConcurrent) {
+ const error = new Error(`Generation is busy (${this.activeJobs.size}/${maxConcurrent} active jobs). Try again when the current job finishes.`);
+ error.status = 429;
+ throw error;
+ }
+ if (['scheduler', 'autonomous_operator'].includes(job.source)) {
+ await this.readiness?.assertReady('Automated generation recovery');
+ }
+
+ const checkpoints = await this.db.listGenerationCheckpoints(job.id);
+ const resumeFrom = options.stage || this.recovery.resumePoint(checkpoints);
+ if (!GENERATION_STAGES.includes(resumeFrom)) {
+ const error = new Error('Resume stage is not supported');
+ error.status = 400;
+ throw error;
+ }
+ if (options.stage) await this.recovery.resetFrom(job.id, resumeFrom);
+ const input = {
+ topic: job.topic,
+ style: job.style,
+ length: job.length || 'medium',
+ strategyContext: job.details?.strategyContext || {}
+ };
+ const updated = await this.db.updateGenerationJob(job.id, {
+ status: 'queued',
+ stage: resumeFrom,
+ error: null,
+ cancelRequested: false,
+ completedAt: null,
+ details: {
+ resumeCount: Number(job.details?.resumeCount || 0) + 1,
+ resumeFrom,
+ failedStage: null
+ }
+ });
+ const work = this.runGenerationJob(job.id, input)
+ .catch(error => this.logger.error(`Resumed generation job ${job.id} failed:`, error))
+ .finally(() => this.activeJobs.delete(job.id));
+ this.activeJobs.set(job.id, work);
+ return updated;
+ }
+
async waitForGenerationJob(jobId) {
const work = this.activeJobs.get(jobId);
if (work) await work;
@@ -749,7 +846,7 @@ class YouTubeAutomationAgent {
async runGenerationJob(jobId, input) {
try {
- await this.db.updateGenerationJob(jobId, { status: 'running', stage: 'starting', progress: 2, error: null });
+ await this.db.updateGenerationJob(jobId, { status: 'running', progress: 2, error: null, completedAt: null });
const result = await this.generateContent(input.topic, input.style, input.length, {
jobId,
strategyContext: input.strategyContext
@@ -767,10 +864,13 @@ class YouTubeAutomationAgent {
return result;
} catch (error) {
const cancelled = error.code === 'JOB_CANCELLED';
+ const current = await this.db.getGenerationJob(jobId);
+ const failedStage = current?.stage || 'starting';
await this.db.updateGenerationJob(jobId, {
status: cancelled ? 'cancelled' : 'failed',
- stage: cancelled ? 'cancelled' : 'failed',
+ stage: failedStage,
error: error.message,
+ details: { failedStage },
completedAt: new Date().toISOString()
});
await this.operator.notify({
@@ -802,102 +902,129 @@ class YouTubeAutomationAgent {
const lengthLabels = { short: '2-4 minutes', medium: '8-12 minutes', long: '15-20 minutes' };
// Step 1: Strategy
- await this.updateJobStage(jobId, 'strategy', 10);
- const strategy = await this.agents.strategy.generateContentStrategy(topic);
- const contentStyles = new Set(['tutorial', 'explainer', 'list', 'review', 'story']);
- const requestedStyle = style || profile.default_style || null;
- if (requestedStyle && contentStyles.has(requestedStyle.toLowerCase())) {
- strategy.contentType = requestedStyle.charAt(0).toUpperCase() + requestedStyle.slice(1).toLowerCase();
- }
- strategy.requestedStyle = requestedStyle;
- strategy.requestedLengthKey = length;
- strategy.requestedLength = lengthLabels[length] || lengthLabels.medium;
- strategy.angle = strategyContext.angle || strategy.angle;
- strategy.planRationale = strategyContext.rationale || null;
- strategy.targetAudience = strategyContext.audience || profile.target_audience || strategy.targetAudience;
- strategy.brandVoice = profile.brand_voice || null;
- strategy.channelGoal = strategyContext.objective || profile.goal || null;
- strategy.channelValueProposition = strategyContext.valueProposition || null;
- strategy.channelConstraints = strategyContext.constraints || null;
- strategy.callToAction = profile.call_to_action || null;
+ const strategy = await this.runGenerationStage(jobId, 'strategy', 10, async () => {
+ const generated = await this.agents.strategy.generateContentStrategy(topic);
+ const contentStyles = new Set(['tutorial', 'explainer', 'list', 'review', 'story']);
+ const requestedStyle = style || profile.default_style || null;
+ if (requestedStyle && contentStyles.has(requestedStyle.toLowerCase())) {
+ generated.contentType = requestedStyle.charAt(0).toUpperCase() + requestedStyle.slice(1).toLowerCase();
+ }
+ generated.requestedStyle = requestedStyle;
+ generated.requestedLengthKey = length;
+ generated.requestedLength = lengthLabels[length] || lengthLabels.medium;
+ generated.angle = strategyContext.angle || generated.angle;
+ generated.planRationale = strategyContext.rationale || null;
+ generated.targetAudience = strategyContext.audience || profile.target_audience || generated.targetAudience;
+ generated.brandVoice = profile.brand_voice || null;
+ generated.channelGoal = strategyContext.objective || profile.goal || null;
+ generated.channelValueProposition = strategyContext.valueProposition || null;
+ generated.channelConstraints = strategyContext.constraints || null;
+ generated.callToAction = profile.call_to_action || null;
+ return generated;
+ });
this.logger.info(`Strategy generated: ${strategy.topic}`);
// Step 2: Script Writing
- await this.updateJobStage(jobId, 'script', 25, { topic: strategy.topic });
- const script = await this.agents.scriptWriter.generateScript(strategy);
+ const script = await this.runGenerationStage(
+ jobId,
+ 'script',
+ 25,
+ () => this.agents.scriptWriter.generateScript(strategy)
+ );
this.logger.info(`Script generated: ${script.title}`);
// Step 3: Thumbnail Design
- await this.updateJobStage(jobId, 'thumbnail', 40, { title: script.title });
- const thumbnail = await this.agents.thumbnailDesigner.generateThumbnail(script);
+ const thumbnail = await this.runGenerationStage(
+ jobId,
+ 'thumbnail',
+ 40,
+ () => this.agents.thumbnailDesigner.generateThumbnail(script)
+ );
this.logger.info('Thumbnail generated');
// Step 4: SEO Optimization
- await this.updateJobStage(jobId, 'seo', 52);
- const seoData = await this.agents.seoOptimizer.optimize(script, strategy);
+ const seoData = await this.runGenerationStage(
+ jobId,
+ 'seo',
+ 52,
+ () => this.agents.seoOptimizer.optimize(script, strategy)
+ );
this.logger.info('SEO optimization complete');
// Step 5: Production Management
- await this.updateJobStage(jobId, 'production', 62);
- const productionData = await this.agents.production.processContent({
- strategy,
- script,
- thumbnail,
- seo: seoData
- });
+ const productionData = await this.runGenerationStage(
+ jobId,
+ 'production',
+ 62,
+ () => this.agents.production.processContent({ strategy, script, thumbnail, seo: seoData })
+ );
this.logger.info('Production processing complete');
- const approvalRequired = await this.db.getSetting('approval_required') !== 'false';
- const packagingExperiment = approvalRequired
- ? await this.preparePackagingExperiment(thumbnail, productionData, seoData, script)
- : null;
-
- // Step 6: Save to database
+ // Re-persist reused production artifacts in case a restart happened between checkpointing and persistence.
const contentId = await this.db.saveProductionData(productionData);
await this.db.saveProductionSnapshot(productionData);
this.logger.info(`Content saved with ID: ${contentId}`);
- // Step 7: Quality and approval gate
- await this.updateJobStage(jobId, 'quality_review', 90, { contentId });
- const quality = await this.operator.runQualityChecks(productionData, profile);
- const reviewStatus = quality.passed
- ? (approvalRequired ? 'needs_review' : 'approved')
- : 'needs_attention';
- await this.db.saveContentReview(contentId, {
- status: reviewStatus,
- qualityChecks: quality.checks,
- editorData: packagingExperiment ? {
- packagingExperiment,
- selectedTitleVariant: 0,
- selectedThumbnailVariant: 0
- } : {},
- reviewNotes: quality.passed ? null : `Blocking checks failed: ${quality.blockingFailures.join(', ')}`,
- reviewedAt: approvalRequired ? null : new Date().toISOString()
+ // Step 6: Quality and approval gate
+ return this.runGenerationStage(jobId, 'quality_review', 90, async () => {
+ const approvalRequired = await this.db.getSetting('approval_required') !== 'false';
+ const packagingExperiment = approvalRequired
+ ? await this.preparePackagingExperiment(thumbnail, productionData, seoData, script)
+ : null;
+ const quality = await this.operator.runQualityChecks(productionData, profile);
+ const reviewStatus = quality.passed
+ ? (approvalRequired ? 'needs_review' : 'approved')
+ : 'needs_attention';
+ await this.db.saveContentReview(contentId, {
+ status: reviewStatus,
+ qualityChecks: quality.checks,
+ editorData: packagingExperiment ? {
+ packagingExperiment,
+ selectedTitleVariant: 0,
+ selectedThumbnailVariant: 0
+ } : {},
+ reviewNotes: quality.passed ? null : `Blocking checks failed: ${quality.blockingFailures.join(', ')}`,
+ reviewedAt: approvalRequired ? null : new Date().toISOString()
+ });
+
+ let scheduleEntry = null;
+ if (reviewStatus === 'approved') {
+ scheduleEntry = await this.agents.publishing.scheduleContent(productionData);
+ await this.db.updateProductionStatus(contentId, scheduleEntry ? 'scheduled' : productionData.status);
+ } else {
+ await this.db.updateProductionStatus(contentId, reviewStatus);
+ await this.operator.notify({
+ type: 'review_required',
+ level: quality.passed ? 'info' : 'warning',
+ title: quality.passed ? 'Content ready for review' : 'Content needs attention',
+ message: `${script.title} ${quality.passed ? 'is ready for approval' : 'failed one or more quality checks'}`,
+ data: { contentId, qualityScore: quality.score }
+ });
+ }
+
+ return {
+ contentId,
+ title: script.title,
+ status: productionData.status,
+ reviewStatus,
+ qualityScore: quality.score,
+ scheduledFor: scheduleEntry ? scheduleEntry.publishTime : null
+ };
});
+ }
- let scheduleEntry = null;
- if (reviewStatus === 'approved') {
- scheduleEntry = await this.agents.publishing.scheduleContent(productionData);
- await this.db.updateProductionStatus(contentId, scheduleEntry ? 'scheduled' : productionData.status);
- } else {
- await this.db.updateProductionStatus(contentId, reviewStatus);
- await this.operator.notify({
- type: 'review_required',
- level: quality.passed ? 'info' : 'warning',
- title: quality.passed ? 'Content ready for review' : 'Content needs attention',
- message: `${script.title} ${quality.passed ? 'is ready for approval' : 'failed one or more quality checks'}`,
- data: { contentId, qualityScore: quality.score }
+ async runGenerationStage(jobId, stage, progress, producer) {
+ if (!jobId) {
+ await this.updateJobStage(jobId, stage, progress);
+ return producer();
+ }
+ if (!this.recovery) {
+ this.recovery = new GenerationRecoveryService(this.db, {
+ logger: this.logger,
+ updateJobStage: (...args) => this.updateJobStage(...args)
});
}
-
- return {
- contentId,
- title: script.title,
- status: productionData.status,
- reviewStatus,
- qualityScore: quality.score,
- scheduledFor: scheduleEntry ? scheduleEntry.publishTime : null
- };
+ return this.recovery.run(jobId, stage, progress, producer);
}
validateEditorData(input = {}, existing = {}) {
diff --git a/package-lock.json b/package-lock.json
index 5f61b88..3d00018 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "youtube-automation-agent",
- "version": "2.6.0",
+ "version": "2.7.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "youtube-automation-agent",
- "version": "2.6.0",
+ "version": "2.7.0",
"dependencies": {
"@google-cloud/local-auth": "^3.0.0",
"@google/genai": "^2.9.0",
diff --git a/package.json b/package.json
index a62bb6c..aa214c7 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "youtube-automation-agent",
- "version": "2.6.0",
+ "version": "2.7.0",
"description": "Lumen is an open-source AI agent that runs a YouTube channel end to end",
"main": "index.js",
"scripts": {
diff --git a/test.js b/test.js
index 1b94ef3..ca01f22 100644
--- a/test.js
+++ b/test.js
@@ -26,6 +26,7 @@ class SystemTest {
{ name: 'Autonomous Channel Operator', test: () => this.testAutonomousChannelOperator() },
{ name: 'Closed-loop Channel Learning', test: () => this.testChannelLearningLoop() },
{ name: 'Production Readiness Gate', test: () => this.testProductionReadinessGate() },
+ { name: 'Resumable Generation Checkpoints', test: () => this.testResumableGenerationCheckpoints() },
{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },
{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },
{ name: 'Multi-Provider Credential Validation', test: () => this.testCredentialValidation() },
@@ -342,6 +343,7 @@ class SystemTest {
await db.initialize();
const previousStrategy = await db.getChannelStrategy();
let run;
+ let recoverableJob;
try {
const strategy = await db.saveChannelStrategy({
@@ -372,6 +374,7 @@ class SystemTest {
}
const receivedInputs = [];
+ let resumedJobs = 0;
const operator = new AutonomousChannelOperator(db, {
researchAndPlan: async () => planned,
startGenerationJob: async input => {
@@ -383,7 +386,12 @@ class SystemTest {
status: 'completed',
production_id: `production-${jobId}`,
details: { reviewStatus: 'needs_review' }
- })
+ }),
+ resumeGenerationJob: async jobId => {
+ resumedJobs++;
+ await db.updateGenerationJob(jobId, { status: 'completed', productionId: `production-${jobId}` });
+ return db.getGenerationJob(jobId);
+ }
});
run = await operator.start(strategy);
await operator.activeRuns.get(run.id);
@@ -395,6 +403,26 @@ class SystemTest {
) {
throw new Error('Autonomous operator did not execute the planned workflow');
}
+
+ recoverableJob = await db.createGenerationJob({ topic: planned.plan[0].topic, source: 'autonomous_operator' });
+ await db.updateGenerationJob(recoverableJob.id, { status: 'interrupted', stage: 'script' });
+ const interruptedJobs = completed.generatedJobs.map((item, index) => index === 0
+ ? { ...item, jobId: recoverableJob.id, status: 'interrupted', reviewStatus: null }
+ : item);
+ await db.updateOperatorRun(run.id, {
+ status: 'interrupted',
+ stage: 'producing_1_of_2',
+ progress: 40,
+ generatedJobs: interruptedJobs,
+ error: 'The application restarted before this operator run finished',
+ completedAt: new Date().toISOString()
+ });
+ await operator.resume(run.id, strategy);
+ await operator.activeRuns.get(run.id);
+ const recoveredRun = await db.getOperatorRun(run.id);
+ if (resumedJobs !== 1 || recoveredRun.status !== 'waiting_review' || recoveredRun.generatedJobs[0].status !== 'completed') {
+ throw new Error('Autonomous operator did not continue from its saved plan and interrupted job');
+ }
} finally {
if (run) {
const stored = await db.getOperatorRun(run.id);
@@ -420,6 +448,7 @@ class SystemTest {
} else {
await db.executeQuery("DELETE FROM channel_strategies WHERE id = 'default'");
}
+ if (recoverableJob) await db.executeQuery('DELETE FROM generation_jobs WHERE id = ?', [recoverableJob.id]);
await db.close();
}
@@ -624,6 +653,145 @@ class SystemTest {
this.logger.info('Production readiness gate test completed successfully');
}
+ async testResumableGenerationCheckpoints() {
+ const fs = require('fs').promises;
+ const os = require('os');
+ const { YouTubeAutomationAgent } = require('./index');
+ const { GenerationRecoveryService } = require('./utils/generation-recovery-service');
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-recovery-'));
+ const db = new Database();
+ db.dbPath = path.join(directory, 'recovery.db');
+ await db.initialize();
+
+ const thumbnailPath = path.join(directory, 'thumbnail.jpg');
+ const videoPath = path.join(directory, 'video.mp4');
+ await fs.writeFile(thumbnailPath, Buffer.from('thumbnail'));
+ await fs.writeFile(videoPath, Buffer.from('video'));
+ const strategy = {
+ topic: 'Checkpointed automation',
+ contentType: 'Tutorial',
+ requestedStyle: 'tutorial',
+ requestedLengthKey: 'short'
+ };
+ const script = {
+ title: 'Checkpointed automation',
+ fullScript: 'A complete script that can be reused after an interrupted generation run.',
+ mainContent: [{ text: 'Reusable content' }]
+ };
+ let strategyCalls = 0;
+ let scriptCalls = 0;
+ let productionCalls = 0;
+
+ try {
+ const agent = new YouTubeAutomationAgent();
+ agent.db = db;
+ agent.recovery = new GenerationRecoveryService(db, {
+ logger: agent.logger,
+ baseDelayMs: 0,
+ updateJobStage: (...args) => agent.updateJobStage(...args)
+ });
+ agent.readiness = { assertReady: async () => true };
+ agent.operator = {
+ runQualityChecks: async () => ({ passed: true, score: 100, checks: [{ passed: true }], blockingFailures: [] }),
+ notify: async () => null
+ };
+ agent.agents = {
+ strategy: { generateContentStrategy: async () => { strategyCalls++; return strategy; } },
+ scriptWriter: { generateScript: async () => { scriptCalls++; return script; } },
+ thumbnailDesigner: { generateThumbnail: async () => ({ path: thumbnailPath, concept: {} }) },
+ seoOptimizer: { optimize: async () => ({ title: script.title, description: 'A complete description.', tags: ['automation'] }) },
+ production: {
+ processContent: async input => {
+ productionCalls++;
+ return {
+ id: `recovery-production-${Date.now()}`,
+ status: 'ready',
+ ...input,
+ assets: {
+ finalVideo: { path: videoPath, simulated: false },
+ thumbnail: { path: thumbnailPath }
+ },
+ timeline: {},
+ scheduledPublishTime: new Date(Date.now() + 86400000).toISOString(),
+ priority: 50,
+ estimatedDuration: '2:00'
+ };
+ }
+ },
+ publishing: { scheduleContent: async () => null }
+ };
+
+ const job = await db.createGenerationJob({
+ topic: strategy.topic,
+ style: 'tutorial',
+ length: 'short',
+ source: 'manual',
+ strategyContext: { objective: 'Test recovery' }
+ });
+ await db.saveGenerationCheckpoint(job.id, 'strategy', {
+ status: 'completed', artifact: strategy, completedAt: new Date().toISOString()
+ });
+ await db.saveGenerationCheckpoint(job.id, 'script', {
+ status: 'completed', artifact: script, completedAt: new Date().toISOString()
+ });
+ await db.updateGenerationJob(job.id, { status: 'running', stage: 'thumbnail', progress: 40 });
+ await db.markInterruptedJobs();
+ const interrupted = await db.getGenerationJob(job.id);
+ if (interrupted.status !== 'interrupted' || interrupted.stage !== 'thumbnail') {
+ throw new Error('Restart recovery did not preserve the interrupted stage');
+ }
+
+ const resumed = await agent.resumeGenerationJob(job.id);
+ if (resumed.details?.resumeFrom !== 'thumbnail') {
+ throw new Error('Resume did not select the first incomplete stage');
+ }
+ await agent.waitForGenerationJob(job.id);
+ const completed = await db.getGenerationJob(job.id);
+ const checkpoints = await db.listGenerationCheckpoints(job.id);
+ if (
+ completed.status !== 'completed' ||
+ checkpoints.filter(item => item.status === 'completed').length !== 6 ||
+ strategyCalls !== 0 || scriptCalls !== 0 || productionCalls !== 1 ||
+ !completed.details.reusedStages.includes('strategy') || !completed.details.reusedStages.includes('script')
+ ) {
+ throw new Error('Generation did not resume from verified checkpoints');
+ }
+
+ let transientAttempts = 0;
+ const transientJob = await db.createGenerationJob({ topic: 'Transient retry' });
+ const recovered = await agent.recovery.run(transientJob.id, 'strategy', 10, async () => {
+ transientAttempts++;
+ if (transientAttempts === 1) {
+ const error = new Error('Temporary provider failure');
+ error.status = 503;
+ throw error;
+ }
+ return { topic: 'Recovered strategy' };
+ });
+ const transientCheckpoint = await db.getGenerationCheckpoint(transientJob.id, 'strategy');
+ if (recovered.topic !== 'Recovered strategy' || transientAttempts !== 2 || transientCheckpoint.attempt_count !== 2) {
+ throw new Error('A retry-safe transient stage failure was not recovered with bounded attempts');
+ }
+
+ const invalidJob = await db.createGenerationJob({ topic: 'Invalid dependency' });
+ await db.saveGenerationCheckpoint(invalidJob.id, 'strategy', {
+ status: 'completed', artifact: {}, completedAt: new Date().toISOString()
+ });
+ await db.saveGenerationCheckpoint(invalidJob.id, 'script', {
+ status: 'completed', artifact: script, completedAt: new Date().toISOString()
+ });
+ await agent.recovery.run(invalidJob.id, 'strategy', 10, async () => ({ topic: 'Rebuilt dependency' }));
+ if (await db.getGenerationCheckpoint(invalidJob.id, 'script')) {
+ throw new Error('A stale downstream checkpoint survived invalid upstream artifact recovery');
+ }
+ } finally {
+ await db.close();
+ await fs.rm(directory, { recursive: true, force: true });
+ }
+
+ this.logger.info('Resumable generation checkpoints test completed successfully');
+ }
+
async testAPIValidationAndSecurity() {
const { YouTubeAutomationAgent } = require('./index');
const agent = new YouTubeAutomationAgent();
@@ -755,6 +923,61 @@ class SystemTest {
throw new Error('getVideoStream did not reject a missing video file');
}
+ let uncertainUpdates = [];
+ const uncertain = new PublishingSchedulingAgent({
+ updateScheduleEntry: async entry => uncertainUpdates.push({ ...entry })
+ }, {});
+ uncertain.publishQueue = [
+ { id: 'schedule-uncertain', productionId: 'prod-uncertain', title: 'Uncertain', status: 'scheduled', metadata: {} }
+ ];
+ let uploadAttempts = 0;
+ uncertain.uploadToYouTube = async entry => {
+ uploadAttempts++;
+ entry.uploadAttempted = true;
+ const error = new Error('socket closed during upload');
+ error.code = 'ECONNRESET';
+ throw error;
+ };
+ let uncertainBlocked = false;
+ try {
+ await uncertain.publishContent('prod-uncertain');
+ } catch (error) {
+ uncertainBlocked = error.code === 'UPLOAD_OUTCOME_UNKNOWN';
+ }
+ try {
+ await uncertain.publishContent('prod-uncertain');
+ } catch (error) {
+ uncertainBlocked = uncertainBlocked && error.code === 'UPLOAD_OUTCOME_UNKNOWN';
+ }
+ if (!uncertainBlocked || uploadAttempts !== 1 || uncertainUpdates.at(-1)?.status !== 'reconciliation_required') {
+ throw new Error('An uncertain upload outcome was retried or failed to require reconciliation');
+ }
+
+ let reconciliationCalls = 0;
+ const recorded = {
+ id: 'schedule-recorded', productionId: 'prod-recorded', title: 'Recorded', status: 'uploaded',
+ youtubeId: 'youtube-existing', metadata: {}
+ };
+ const reconcile = new PublishingSchedulingAgent({
+ getLatestScheduleEntry: async () => recorded,
+ updateScheduleEntry: async () => {}
+ }, {});
+ reconcile.youtube = {
+ videos: {
+ list: async () => {
+ reconciliationCalls++;
+ return { data: { items: [{ id: 'youtube-existing' }] } };
+ }
+ }
+ };
+ reconcile.uploadToYouTube = async () => {
+ throw new Error('A recorded upload must never be uploaded again');
+ };
+ const reconciled = await reconcile.publishContent('prod-recorded');
+ if (reconciled.status !== 'published' || reconciliationCalls !== 1) {
+ throw new Error('A recorded YouTube upload was not reconciled idempotently');
+ }
+
this.logger.info('Publishing safety test completed successfully');
}
diff --git a/utils/autonomous-channel-operator.js b/utils/autonomous-channel-operator.js
index 86bad23..759e0ec 100644
--- a/utils/autonomous-channel-operator.js
+++ b/utils/autonomous-channel-operator.js
@@ -5,6 +5,7 @@ class AutonomousChannelOperator {
this.db = db;
this.researchAndPlan = options.researchAndPlan;
this.startGenerationJob = options.startGenerationJob;
+ this.resumeGenerationJob = options.resumeGenerationJob;
this.waitForGenerationJob = options.waitForGenerationJob;
this.notify = options.notify || (async () => null);
this.logger = new Logger('AutonomousOperator');
@@ -32,25 +33,84 @@ class AutonomousChannelOperator {
return run;
}
- async execute(runId, strategy) {
+ async resume(runId, strategy) {
+ const run = await this.db.getOperatorRun(runId);
+ if (!run) {
+ const error = new Error('Operator run not found');
+ error.status = 404;
+ throw error;
+ }
+ if (!['failed', 'interrupted', 'completed_with_issues'].includes(run.status)) {
+ const error = new Error('Only failed or interrupted operator runs can be resumed');
+ error.status = 409;
+ throw error;
+ }
+ if (!strategy || strategy.status !== 'active') {
+ const error = new Error('Activate the saved channel strategy before resuming this run');
+ error.status = 409;
+ throw error;
+ }
+ const active = await this.db.getActiveOperatorRun();
+ if (active || this.activeRuns.size) {
+ const error = new Error('An autonomous operator run is already active');
+ error.status = 409;
+ throw error;
+ }
+ await this.update(runId, {
+ status: 'queued',
+ stage: 'resuming',
+ error: null,
+ cancelRequested: false,
+ completedAt: null
+ });
+ const work = this.execute(runId, strategy, { resume: true })
+ .catch(error => this.logger.error(`Resumed operator run ${runId} failed:`, error))
+ .finally(() => this.activeRuns.delete(runId));
+ this.activeRuns.set(runId, work);
+ return this.db.getOperatorRun(runId);
+ }
+
+ async execute(runId, strategy, options = {}) {
try {
- await this.update(runId, { status: 'running', stage: 'researching', progress: 5, error: null });
- const { research, plan } = await this.researchAndPlan(strategy);
+ const stored = options.resume ? await this.db.getOperatorRun(runId) : null;
+ let research = stored?.research || {};
+ let plan = stored?.plan || [];
+ const generatedJobs = stored?.generatedJobs || [];
+ await this.update(runId, {
+ status: 'running',
+ stage: plan.length ? 'resuming_plan' : 'researching',
+ progress: plan.length ? Math.max(20, stored?.progress || 20) : 5,
+ error: null,
+ cancelRequested: false,
+ completedAt: null
+ });
+ if (!plan.length) {
+ ({ research, plan } = await this.researchAndPlan(strategy));
+ }
if (!plan.length) throw new Error('Research did not produce any usable content ideas');
await this.assertNotCancelled(runId);
await this.update(runId, { stage: 'planning', progress: 20, research, plan });
- const generatedJobs = [];
for (let index = 0; index < plan.length; index++) {
await this.assertNotCancelled(runId);
const item = plan[index];
- const idea = await this.db.createContentIdea({
- topic: item.topic,
- angle: item.angle,
- style: item.format,
- status: 'generating',
- rationale: item.rationale
- });
+ let record = generatedJobs[index];
+ if (record?.status === 'completed') continue;
+ let ideaId = record?.ideaId;
+ if (!record) {
+ const idea = await this.db.createContentIdea({
+ topic: item.topic,
+ angle: item.angle,
+ style: item.format,
+ status: 'generating',
+ rationale: item.rationale
+ });
+ ideaId = idea.id;
+ record = { jobId: null, ideaId, topic: item.topic, status: 'queued', planIndex: index };
+ generatedJobs[index] = record;
+ } else if (ideaId) {
+ await this.db.updateContentIdea(ideaId, { status: 'generating' });
+ }
const progress = 20 + Math.round((index / plan.length) * 70);
await this.update(runId, {
stage: `producing_${index + 1}_of_${plan.length}`,
@@ -58,40 +118,43 @@ class AutonomousChannelOperator {
generatedJobs
});
- const record = { jobId: null, ideaId: idea.id, topic: item.topic, status: 'queued' };
- generatedJobs.push(record);
try {
await this.update(runId, { generatedJobs });
await this.assertNotCancelled(runId);
- const job = await this.startGenerationJob({
- topic: item.topic,
- style: item.format,
- length: item.length,
- source: 'autonomous_operator',
- strategyContext: {
- angle: item.angle,
- rationale: item.rationale,
- audience: strategy.audience,
- objective: strategy.objective,
- valueProposition: strategy.value_proposition,
- constraints: strategy.constraints
- }
- });
+ let job = record.jobId ? await this.db.getGenerationJob(record.jobId) : null;
+ if (job && ['failed', 'interrupted'].includes(job.status)) {
+ job = await this.resumeGenerationJob(job.id);
+ } else if (!job || !['queued', 'running', 'completed'].includes(job.status)) {
+ job = await this.startGenerationJob({
+ topic: item.topic,
+ style: item.format,
+ length: item.length,
+ source: 'autonomous_operator',
+ strategyContext: {
+ angle: item.angle,
+ rationale: item.rationale,
+ audience: strategy.audience,
+ objective: strategy.objective,
+ valueProposition: strategy.value_proposition,
+ constraints: strategy.constraints
+ }
+ });
+ }
record.jobId = job.id;
record.status = 'running';
await this.update(runId, { generatedJobs });
- const completed = await this.waitForGenerationJob(job.id);
+ const completed = job.status === 'completed' ? job : await this.waitForGenerationJob(job.id);
record.status = completed.status;
record.productionId = completed.production_id || null;
record.reviewStatus = completed.details?.reviewStatus || null;
record.error = completed.error || null;
- await this.db.updateContentIdea(idea.id, {
+ if (ideaId) await this.db.updateContentIdea(ideaId, {
status: completed.status === 'completed' ? 'generated' : 'failed'
});
} catch (error) {
record.status = error.code === 'OPERATOR_CANCELLED' ? 'cancelled' : 'failed';
record.error = error.message;
- await this.db.updateContentIdea(idea.id, { status: 'failed' });
+ if (ideaId) await this.db.updateContentIdea(ideaId, { status: 'failed' });
if (error.code === 'OPERATOR_CANCELLED') throw error;
}
await this.update(runId, {
diff --git a/utils/generation-recovery-service.js b/utils/generation-recovery-service.js
new file mode 100644
index 0000000..79cb00b
--- /dev/null
+++ b/utils/generation-recovery-service.js
@@ -0,0 +1,130 @@
+const fs = require('fs').promises;
+
+const GENERATION_STAGES = [
+ 'strategy',
+ 'script',
+ 'thumbnail',
+ 'seo',
+ 'production',
+ 'quality_review'
+];
+
+class GenerationRecoveryService {
+ constructor(db, options = {}) {
+ this.db = db;
+ this.updateJobStage = options.updateJobStage || (async () => null);
+ this.logger = options.logger || { info() {}, warn() {} };
+ this.maxAttempts = Math.max(1, Number(options.maxAttempts || process.env.GENERATION_STAGE_MAX_ATTEMPTS || 2));
+ this.baseDelayMs = Math.max(0, Number(options.baseDelayMs ?? process.env.GENERATION_RETRY_BASE_MS ?? 1000));
+ }
+
+ async run(jobId, stage, progress, producer) {
+ if (!GENERATION_STAGES.includes(stage)) throw new Error(`Unknown generation stage: ${stage}`);
+ const checkpoint = await this.db.getGenerationCheckpoint(jobId, stage);
+ if (checkpoint?.status === 'completed') {
+ if (await this.validateArtifact(stage, checkpoint.artifact)) {
+ await this.markReused(jobId, stage, progress);
+ this.logger.info(`Reusing verified ${stage} checkpoint for ${jobId}`);
+ return checkpoint.artifact;
+ }
+ const stageIndex = GENERATION_STAGES.indexOf(stage);
+ await this.db.deleteGenerationCheckpoints(jobId, GENERATION_STAGES.slice(stageIndex + 1));
+ await this.db.saveGenerationCheckpoint(jobId, stage, {
+ status: 'invalid',
+ error: 'The saved artifact is missing or no longer valid',
+ completedAt: null
+ });
+ }
+
+ let lastError;
+ for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
+ await this.updateJobStage(jobId, stage, progress, { attempt });
+ const startedAt = new Date().toISOString();
+ await this.db.saveGenerationCheckpoint(jobId, stage, {
+ status: 'running',
+ error: null,
+ startedAt,
+ completedAt: null,
+ incrementAttempt: true
+ });
+ try {
+ const artifact = await producer();
+ if (!await this.validateArtifact(stage, artifact)) {
+ throw new Error(`${stage} produced an incomplete or missing artifact`);
+ }
+ await this.db.saveGenerationCheckpoint(jobId, stage, {
+ status: 'completed',
+ artifact,
+ error: null,
+ completedAt: new Date().toISOString()
+ });
+ return artifact;
+ } catch (error) {
+ lastError = error;
+ await this.db.saveGenerationCheckpoint(jobId, stage, {
+ status: error.code === 'JOB_CANCELLED' ? 'cancelled' : 'failed',
+ error: error.message,
+ completedAt: new Date().toISOString()
+ });
+ if (error.code === 'JOB_CANCELLED' || attempt >= this.maxAttempts || !this.isRetryable(error)) throw error;
+ const delayMs = this.baseDelayMs * (2 ** (attempt - 1));
+ this.logger.warn(`${stage} failed transiently; retrying in ${delayMs}ms: ${error.message}`);
+ if (delayMs) await new Promise(resolve => setTimeout(resolve, delayMs));
+ }
+ }
+ throw lastError;
+ }
+
+ async validateArtifact(stage, artifact) {
+ if (!artifact || typeof artifact !== 'object') return false;
+ if (stage === 'strategy') return Boolean(artifact.topic);
+ if (stage === 'script') return Boolean(artifact.title && (artifact.fullScript || artifact.mainContent));
+ if (stage === 'thumbnail') return this.validatePathArtifact(artifact.path);
+ if (stage === 'seo') return Boolean(artifact.title && artifact.description && Array.isArray(artifact.tags));
+ if (stage === 'production') {
+ const finalVideo = artifact.assets?.finalVideo;
+ return Boolean(artifact.id && finalVideo?.path && await this.pathExists(finalVideo.path));
+ }
+ if (stage === 'quality_review') return Boolean(artifact.contentId && artifact.reviewStatus);
+ return false;
+ }
+
+ async validatePathArtifact(filePath) {
+ return Boolean(filePath && await this.pathExists(filePath));
+ }
+
+ async pathExists(filePath) {
+ try {
+ const stat = await fs.stat(filePath);
+ return stat.isFile() && stat.size > 0;
+ } catch (_error) {
+ return false;
+ }
+ }
+
+ isRetryable(error) {
+ const status = Number(error.status || error.statusCode || error.response?.status || 0);
+ if ([408, 425, 429].includes(status) || status >= 500) return true;
+ const code = String(error.code || '').toUpperCase();
+ return ['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'ETIMEDOUT', 'ENETUNREACH', 'EAI_AGAIN'].includes(code);
+ }
+
+ async markReused(jobId, stage, progress) {
+ const job = await this.db.getGenerationJob(jobId);
+ const reusedStages = Array.from(new Set([...(job?.details?.reusedStages || []), stage]));
+ await this.updateJobStage(jobId, stage, progress, { reusedStages });
+ }
+
+ resumePoint(checkpoints = []) {
+ const byStage = new Map(checkpoints.map(checkpoint => [checkpoint.stage, checkpoint]));
+ return GENERATION_STAGES.find(stage => byStage.get(stage)?.status !== 'completed') || 'quality_review';
+ }
+
+ async resetFrom(jobId, requestedStage) {
+ if (!GENERATION_STAGES.includes(requestedStage)) throw new Error('Resume stage is not supported');
+ const index = GENERATION_STAGES.indexOf(requestedStage);
+ await this.db.deleteGenerationCheckpoints(jobId, GENERATION_STAGES.slice(index));
+ }
+}
+
+module.exports = { GenerationRecoveryService, GENERATION_STAGES };