mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
Add cron-based scheduling with prompt templates integration (#164)
This commit is contained in:
1 parent
cbd0ee2958
commit
1e863c5fc5
63 files changed
+7797
-64
No files matched your search
@@ -0,0 +1,58 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 7,
|
||||
name: 'schedules',
|
||||
|
||||
up(db) {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS schedule_jobs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
interval_minutes INTEGER,
|
||||
agent_slug TEXT,
|
||||
prompt TEXT NOT NULL,
|
||||
model TEXT,
|
||||
skill_metadata TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
last_run_at INTEGER,
|
||||
next_run_at INTEGER
|
||||
)
|
||||
`)
|
||||
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS schedule_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
job_id INTEGER NOT NULL REFERENCES schedule_jobs(id) ON DELETE CASCADE,
|
||||
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||
trigger_source TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
started_at INTEGER NOT NULL,
|
||||
finished_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
session_id TEXT,
|
||||
session_title TEXT,
|
||||
log_text TEXT,
|
||||
response_text TEXT,
|
||||
error_text TEXT
|
||||
)
|
||||
`)
|
||||
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_job ON schedule_runs(job_id, started_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_repo ON schedule_runs(repo_id, started_at DESC)')
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run('DROP TABLE IF EXISTS schedule_runs')
|
||||
db.run('DROP TABLE IF EXISTS schedule_jobs')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -0,0 +1,129 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
dflt_value: string | null
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 8,
|
||||
name: 'schedule-cron-support',
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
const existingColumns = new Set(tableInfo.map((column) => column.name))
|
||||
const intervalMinutesColumn = tableInfo.find((column) => column.name === 'interval_minutes')
|
||||
const scheduleModeColumn = tableInfo.find((column) => column.name === 'schedule_mode')
|
||||
const hasCronColumns = existingColumns.has('schedule_mode') && existingColumns.has('cron_expression') && existingColumns.has('timezone')
|
||||
const scheduleModeDefault = scheduleModeColumn?.dflt_value?.replaceAll("'", '')
|
||||
|
||||
if (intervalMinutesColumn?.notnull === 0 && hasCronColumns && scheduleModeDefault === 'interval') {
|
||||
return
|
||||
}
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE schedule_jobs_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
interval_minutes INTEGER,
|
||||
schedule_mode TEXT NOT NULL DEFAULT 'interval',
|
||||
cron_expression TEXT,
|
||||
timezone TEXT,
|
||||
agent_slug TEXT,
|
||||
prompt TEXT NOT NULL,
|
||||
model TEXT,
|
||||
skill_metadata TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
last_run_at INTEGER,
|
||||
next_run_at INTEGER
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_jobs_new (
|
||||
id, repo_id, name, description, enabled, interval_minutes, schedule_mode, cron_expression, timezone,
|
||||
agent_slug, prompt, model, skill_metadata, created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
SELECT
|
||||
id,
|
||||
repo_id,
|
||||
name,
|
||||
description,
|
||||
enabled,
|
||||
interval_minutes,
|
||||
${existingColumns.has('schedule_mode') ? "COALESCE(schedule_mode, 'interval')" : "'interval'"},
|
||||
${existingColumns.has('cron_expression') ? 'cron_expression' : 'NULL'},
|
||||
${existingColumns.has('timezone') ? 'timezone' : 'NULL'},
|
||||
agent_slug,
|
||||
prompt,
|
||||
model,
|
||||
skill_metadata,
|
||||
created_at,
|
||||
updated_at,
|
||||
last_run_at,
|
||||
next_run_at
|
||||
FROM schedule_jobs
|
||||
`)
|
||||
|
||||
db.run('DROP TABLE schedule_jobs')
|
||||
db.run('ALTER TABLE schedule_jobs_new RENAME TO schedule_jobs')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run(`
|
||||
CREATE TABLE schedule_jobs_old (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
interval_minutes INTEGER NOT NULL,
|
||||
agent_slug TEXT,
|
||||
prompt TEXT NOT NULL,
|
||||
model TEXT,
|
||||
skill_metadata TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
last_run_at INTEGER,
|
||||
next_run_at INTEGER
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_jobs_old (
|
||||
id, repo_id, name, description, enabled, interval_minutes, agent_slug, prompt, model, skill_metadata,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
SELECT
|
||||
id,
|
||||
repo_id,
|
||||
name,
|
||||
description,
|
||||
enabled,
|
||||
COALESCE(interval_minutes, 60),
|
||||
agent_slug,
|
||||
prompt,
|
||||
model,
|
||||
skill_metadata,
|
||||
created_at,
|
||||
updated_at,
|
||||
last_run_at,
|
||||
next_run_at
|
||||
FROM schedule_jobs
|
||||
`)
|
||||
|
||||
db.run('DROP TABLE schedule_jobs')
|
||||
db.run('ALTER TABLE schedule_jobs_old RENAME TO schedule_jobs')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -0,0 +1,315 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 10,
|
||||
name: '010-prompt-templates',
|
||||
|
||||
up(db) {
|
||||
db.run(`
|
||||
CREATE TABLE prompt_templates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
cadence_hint TEXT NOT NULL,
|
||||
suggested_name TEXT NOT NULL,
|
||||
suggested_description TEXT NOT NULL DEFAULT '',
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
prompt TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
|
||||
const now = Date.now()
|
||||
const insert = db.prepare(`
|
||||
INSERT INTO prompt_templates (title, category, cadence_hint, suggested_name, suggested_description, description, prompt, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
insert.run(
|
||||
'Repo Health Report',
|
||||
'Health',
|
||||
'Weekly',
|
||||
'Weekly repo health report',
|
||||
'Summarize code health, risk areas, and the next highest-leverage follow-ups.',
|
||||
'A broad weekly review of project health, risks, and recommended next actions.',
|
||||
[
|
||||
'Review this repository and prepare a concise weekly health report.',
|
||||
'',
|
||||
'Focus on:',
|
||||
'- overall code health and maintainability signals',
|
||||
'- risky or stale areas in the codebase',
|
||||
'- flaky, fragile, or untested workflows',
|
||||
'- notable recent drift in tooling, scripts, or structure',
|
||||
'',
|
||||
'Do not modify files or create commits.',
|
||||
'',
|
||||
'Return the result in these sections:',
|
||||
'1. Overall Status',
|
||||
'2. Key Risks',
|
||||
'3. What Changed or Drifted',
|
||||
'4. Recommended Next Actions',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
|
||||
insert.run(
|
||||
'Dependency Watchlist',
|
||||
'Maintenance',
|
||||
'Weekly',
|
||||
'Dependency watchlist',
|
||||
'Review dependency health, upgrade pressure, and risky package drift.',
|
||||
'Surfaces outdated, risky, or inconsistent dependencies and upgrade priorities.',
|
||||
[
|
||||
'Audit this repository for dependency risk and upgrade pressure.',
|
||||
'',
|
||||
'Inspect package manifests, lockfiles, build tooling, runtime dependencies, and obvious version drift.',
|
||||
'',
|
||||
'Focus on:',
|
||||
'- outdated or inconsistent package versions',
|
||||
'- packages that look risky, abandoned, duplicated, or unnecessary',
|
||||
'- tooling mismatches that could cause local vs CI drift',
|
||||
'- high-priority upgrades to tackle next',
|
||||
'',
|
||||
'Do not change files.',
|
||||
'',
|
||||
'Return:',
|
||||
'1. Highest Priority Upgrades',
|
||||
'2. Risky or Inconsistent Dependencies',
|
||||
'3. Tooling Drift',
|
||||
'4. Suggested Upgrade Order',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
|
||||
insert.run(
|
||||
'Release Readiness Review',
|
||||
'Release',
|
||||
'Before release',
|
||||
'Release readiness review',
|
||||
'Check whether the repo looks ready to ship and what could block release confidence.',
|
||||
'A pre-release checkpoint for blockers, missing validation, and confidence gaps.',
|
||||
[
|
||||
'Review this repository for release readiness.',
|
||||
'',
|
||||
'Focus on anything that would reduce confidence in shipping soon, including:',
|
||||
'- missing validation, tests, or smoke coverage',
|
||||
'- fragile configuration or deployment assumptions',
|
||||
'- unfinished, ambiguous, or risky recent work',
|
||||
'- docs or scripts that appear stale relative to the implementation',
|
||||
'',
|
||||
'Do not edit files.',
|
||||
'',
|
||||
'Return:',
|
||||
'1. Release Confidence',
|
||||
'2. Blockers',
|
||||
'3. Follow-ups Before Shipping',
|
||||
'4. Nice-to-have Cleanup After Release',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
|
||||
insert.run(
|
||||
'Test Stability Audit',
|
||||
'Quality',
|
||||
'Weekly',
|
||||
'Test stability audit',
|
||||
'Find flaky areas, missing coverage signals, and brittle testing patterns.',
|
||||
'Looks at test quality, slow paths, brittle coverage, and likely flaky areas.',
|
||||
[
|
||||
'Inspect this repository for test stability and coverage risk.',
|
||||
'',
|
||||
'Focus on:',
|
||||
'- flaky or brittle test patterns',
|
||||
'- important product areas with weak or missing coverage',
|
||||
'- slow or overcomplicated test flows',
|
||||
'- test setup/config problems that could cause false confidence',
|
||||
'',
|
||||
'Do not modify files.',
|
||||
'',
|
||||
'Return:',
|
||||
'1. Confidence Gaps',
|
||||
'2. Flaky or Fragile Areas',
|
||||
'3. Coverage Priorities',
|
||||
'4. Suggested Test Improvements',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
|
||||
insert.run(
|
||||
'Docs Drift Review',
|
||||
'Docs',
|
||||
'Biweekly',
|
||||
'Docs drift review',
|
||||
'Check whether README, setup steps, and docs still match the current repo.',
|
||||
'Finds README/setup/documentation drift relative to the actual codebase.',
|
||||
[
|
||||
'Review this repository for documentation drift.',
|
||||
'',
|
||||
'Compare README files, setup instructions, scripts, and other repo docs against the actual implementation and project structure.',
|
||||
'',
|
||||
'Focus on:',
|
||||
'- stale setup or run instructions',
|
||||
'- missing documentation for important workflows',
|
||||
'- docs that no longer match the codebase structure or tooling',
|
||||
'- confusing or duplicated documentation',
|
||||
'',
|
||||
'Do not edit files.',
|
||||
'',
|
||||
'Return:',
|
||||
'1. Docs That Look Stale',
|
||||
'2. Missing Documentation',
|
||||
'3. Confusing or Conflicting Guidance',
|
||||
'4. Suggested Documentation Updates',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
|
||||
insert.run(
|
||||
'Tech Debt Triage',
|
||||
'Planning',
|
||||
'Weekly',
|
||||
'Tech debt triage',
|
||||
'Identify the most expensive sources of drag and rank cleanup opportunities.',
|
||||
'Ranks the most valuable cleanup and refactor opportunities in the repo.',
|
||||
[
|
||||
'Review this repository and identify the most important technical debt to address next.',
|
||||
'',
|
||||
'Focus on debt that creates drag for delivery, reliability, or maintainability, such as:',
|
||||
'- duplicated logic or tangled ownership',
|
||||
'- brittle architecture seams',
|
||||
'- outdated patterns or confusing abstractions',
|
||||
'- hotspots that are hard to safely change',
|
||||
'',
|
||||
'Do not make changes.',
|
||||
'',
|
||||
'Return:',
|
||||
'1. Top Technical Debt Items',
|
||||
'2. Why Each Item Matters',
|
||||
'3. Cost vs Impact',
|
||||
'4. Recommended Cleanup Order',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
|
||||
insert.run(
|
||||
'Security and Config Review',
|
||||
'Security',
|
||||
'Weekly',
|
||||
'Security and config review',
|
||||
'Inspect obvious security, secrets, and environment/config handling risks.',
|
||||
'Looks for obvious secrets, auth, and configuration handling issues.',
|
||||
[
|
||||
'Inspect this repository for obvious security and configuration handling risks.',
|
||||
'',
|
||||
'Focus on:',
|
||||
'- secrets or credentials handling problems',
|
||||
'- risky defaults in environment or auth configuration',
|
||||
'- places where permission checks or trust assumptions look weak',
|
||||
'- config sprawl that could cause unsafe deployments',
|
||||
'',
|
||||
'Stay read-only. Do not modify files.',
|
||||
'',
|
||||
'Return:',
|
||||
'1. High-Risk Findings',
|
||||
'2. Medium-Risk Findings',
|
||||
'3. Configuration Concerns',
|
||||
'4. Recommended Fixes',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
|
||||
insert.run(
|
||||
'CI and Ops Review',
|
||||
'Operations',
|
||||
'Weekly',
|
||||
'CI and ops review',
|
||||
'Check CI, scripts, and operational workflows for fragility or drift.',
|
||||
'Surfaces friction or fragility in CI, automation, and repo operations.',
|
||||
[
|
||||
'Review this repository for CI, automation, and operational workflow issues.',
|
||||
'',
|
||||
'Focus on:',
|
||||
'- brittle build or test assumptions',
|
||||
'- scripts that look stale, redundant, or inconsistent',
|
||||
'- automation that appears slow, noisy, or easy to break',
|
||||
'- workflow gaps that could hurt developer reliability',
|
||||
'',
|
||||
'Do not edit files.',
|
||||
'',
|
||||
'Return:',
|
||||
'1. Operational Risks',
|
||||
'2. CI or Automation Drift',
|
||||
'3. Reliability Improvements',
|
||||
'4. Highest-Leverage Next Steps',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
|
||||
insert.run(
|
||||
'Onboarding Brief',
|
||||
'Knowledge',
|
||||
'Monthly',
|
||||
'Onboarding brief refresh',
|
||||
'Produce a concise orientation summary for someone new to the repo.',
|
||||
'Creates a concise orientation guide for engineers who are new to the repo.',
|
||||
[
|
||||
'Prepare an onboarding brief for an engineer who is new to this repository.',
|
||||
'',
|
||||
'Focus on:',
|
||||
'- the repo structure and major areas of responsibility',
|
||||
'- the core development workflows and important commands',
|
||||
'- risky or confusing areas worth knowing early',
|
||||
'- where a new engineer should start reading or exploring',
|
||||
'',
|
||||
'Do not modify files.',
|
||||
'',
|
||||
'Return:',
|
||||
'1. What This Repo Does',
|
||||
'2. Important Areas to Know',
|
||||
'3. Local Workflow Cheatsheet',
|
||||
'4. Common Pitfalls and First Reading List',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
|
||||
insert.run(
|
||||
'Memory Candidate Review',
|
||||
'Knowledge',
|
||||
'Biweekly',
|
||||
'Memory candidate review',
|
||||
'Identify stable conventions, decisions, and context worth preserving as memory.',
|
||||
'Great for repos using durable memory or team conventions that should be captured.',
|
||||
[
|
||||
'Review this repository and identify durable knowledge worth preserving as long-lived memory.',
|
||||
'',
|
||||
'Focus on conventions, architectural decisions, recurring workflows, and stable context that future sessions should know.',
|
||||
'',
|
||||
'Do not create or update memory directly. Just recommend candidates.',
|
||||
'',
|
||||
'Return:',
|
||||
'1. Candidate Conventions',
|
||||
'2. Candidate Decisions',
|
||||
'3. Candidate Context',
|
||||
'4. Why Each Item Should Be Preserved',
|
||||
].join('\n'),
|
||||
now,
|
||||
now,
|
||||
)
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run('DROP TABLE IF EXISTS prompt_templates')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -5,7 +5,10 @@ import migration003 from './003-repos-add-columns'
|
||||
import migration004 from './004-repos-indexes'
|
||||
import migration005 from './005-repos-local-path-prefix'
|
||||
import migration006 from './006-git-token-to-credentials'
|
||||
import migration007 from './007-schedules'
|
||||
import migration008 from './008-schedule-cron-support'
|
||||
import migration009 from './009-repo-source-path'
|
||||
import migration010 from './009-prompt-templates'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -14,5 +17,8 @@ export const allMigrations: Migration[] = [
|
||||
migration004,
|
||||
migration005,
|
||||
migration006,
|
||||
migration007,
|
||||
migration008,
|
||||
migration009,
|
||||
migration010,
|
||||
]
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import {
|
||||
PromptTemplateSchema,
|
||||
type PromptTemplate,
|
||||
type CreatePromptTemplateRequest,
|
||||
type UpdatePromptTemplateRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
interface PromptTemplateRow {
|
||||
id: number
|
||||
title: string
|
||||
category: string
|
||||
cadence_hint: string
|
||||
suggested_name: string
|
||||
suggested_description: string
|
||||
description: string
|
||||
prompt: string
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
function rowToPromptTemplate(row: PromptTemplateRow): PromptTemplate {
|
||||
return PromptTemplateSchema.parse({
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
category: row.category,
|
||||
cadenceHint: row.cadence_hint,
|
||||
suggestedName: row.suggested_name,
|
||||
suggestedDescription: row.suggested_description,
|
||||
description: row.description,
|
||||
prompt: row.prompt,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
})
|
||||
}
|
||||
|
||||
export function listPromptTemplates(db: Database): PromptTemplate[] {
|
||||
const rows = db.prepare('SELECT * FROM prompt_templates ORDER BY id ASC').all() as PromptTemplateRow[]
|
||||
return rows.map(rowToPromptTemplate)
|
||||
}
|
||||
|
||||
export function getPromptTemplateById(db: Database, id: number): PromptTemplate | null {
|
||||
const row = db.prepare('SELECT * FROM prompt_templates WHERE id = ?').get(id) as PromptTemplateRow | null
|
||||
return row ? rowToPromptTemplate(row) : null
|
||||
}
|
||||
|
||||
export function createPromptTemplate(db: Database, data: CreatePromptTemplateRequest): PromptTemplate {
|
||||
const now = Date.now()
|
||||
const result = db.prepare(`
|
||||
INSERT INTO prompt_templates (title, category, cadence_hint, suggested_name, suggested_description, description, prompt, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(data.title, data.category, data.cadenceHint, data.suggestedName, data.suggestedDescription, data.description, data.prompt, now, now)
|
||||
return getPromptTemplateById(db, result.lastInsertRowid as number)!
|
||||
}
|
||||
|
||||
export function updatePromptTemplate(db: Database, id: number, data: UpdatePromptTemplateRequest): PromptTemplate | null {
|
||||
const existing = getPromptTemplateById(db, id)
|
||||
if (!existing) return null
|
||||
const now = Date.now()
|
||||
db.prepare(`
|
||||
UPDATE prompt_templates SET
|
||||
title = ?, category = ?, cadence_hint = ?, suggested_name = ?,
|
||||
suggested_description = ?, description = ?, prompt = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
data.title ?? existing.title,
|
||||
data.category ?? existing.category,
|
||||
data.cadenceHint ?? existing.cadenceHint,
|
||||
data.suggestedName ?? existing.suggestedName,
|
||||
data.suggestedDescription ?? existing.suggestedDescription,
|
||||
data.description ?? existing.description,
|
||||
data.prompt ?? existing.prompt,
|
||||
now,
|
||||
id,
|
||||
)
|
||||
return getPromptTemplateById(db, id)
|
||||
}
|
||||
|
||||
export function deletePromptTemplate(db: Database, id: number): boolean {
|
||||
const result = db.prepare('DELETE FROM prompt_templates WHERE id = ?').run(id)
|
||||
return result.changes > 0
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import {
|
||||
ScheduleJobSchema,
|
||||
ScheduleRunSchema,
|
||||
ScheduleSkillMetadataSchema,
|
||||
type ScheduleJob,
|
||||
type ScheduleMode,
|
||||
type ScheduleRun,
|
||||
type ScheduleRunStatus,
|
||||
type ScheduleRunTriggerSource,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
|
||||
|
||||
interface ScheduleJobRow {
|
||||
id: number
|
||||
repo_id: number
|
||||
name: string
|
||||
description: string | null
|
||||
enabled: number
|
||||
schedule_mode: ScheduleMode | null
|
||||
interval_minutes: number | null
|
||||
cron_expression: string | null
|
||||
timezone: string | null
|
||||
agent_slug: string | null
|
||||
prompt: string
|
||||
model: string | null
|
||||
skill_metadata: string | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
last_run_at: number | null
|
||||
next_run_at: number | null
|
||||
}
|
||||
|
||||
interface ScheduleRunRow {
|
||||
id: number
|
||||
job_id: number
|
||||
repo_id: number
|
||||
trigger_source: string
|
||||
status: string
|
||||
started_at: number
|
||||
finished_at: number | null
|
||||
created_at: number
|
||||
session_id: string | null
|
||||
session_title: string | null
|
||||
log_text: string | null
|
||||
response_text: string | null
|
||||
error_text: string | null
|
||||
}
|
||||
|
||||
function parseSkillMetadata(raw: string | null) {
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
const result = ScheduleSkillMetadataSchema.safeParse(parsed)
|
||||
return result.success ? result.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
|
||||
return ScheduleJobSchema.parse({
|
||||
id: row.id,
|
||||
repoId: row.repo_id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
enabled: Boolean(row.enabled),
|
||||
scheduleMode: row.schedule_mode ?? 'interval',
|
||||
intervalMinutes: row.interval_minutes,
|
||||
cronExpression: row.cron_expression,
|
||||
timezone: row.timezone,
|
||||
agentSlug: row.agent_slug,
|
||||
prompt: row.prompt,
|
||||
model: row.model,
|
||||
skillMetadata: parseSkillMetadata(row.skill_metadata),
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
lastRunAt: row.last_run_at,
|
||||
nextRunAt: row.next_run_at,
|
||||
})
|
||||
}
|
||||
|
||||
function rowToScheduleRun(row: ScheduleRunRow): ScheduleRun {
|
||||
return ScheduleRunSchema.parse({
|
||||
id: row.id,
|
||||
jobId: row.job_id,
|
||||
repoId: row.repo_id,
|
||||
triggerSource: row.trigger_source,
|
||||
status: row.status,
|
||||
startedAt: row.started_at,
|
||||
finishedAt: row.finished_at,
|
||||
createdAt: row.created_at,
|
||||
sessionId: row.session_id,
|
||||
sessionTitle: row.session_title,
|
||||
logText: row.log_text,
|
||||
responseText: row.response_text,
|
||||
errorText: row.error_text,
|
||||
})
|
||||
}
|
||||
|
||||
function serializeSkillMetadata(skillMetadata: ScheduleJobPersistenceInput['skillMetadata']): string | null {
|
||||
if (!skillMetadata) {
|
||||
return null
|
||||
}
|
||||
|
||||
return JSON.stringify(skillMetadata)
|
||||
}
|
||||
|
||||
export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(repoId) as ScheduleJobRow[]
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function listDueScheduleJobs(db: Database, now: number, limit: number = 20): ScheduleJob[] {
|
||||
const stmt = db.prepare(`
|
||||
SELECT * FROM schedule_jobs
|
||||
WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ?
|
||||
ORDER BY next_run_at ASC
|
||||
LIMIT ?
|
||||
`)
|
||||
const rows = stmt.all(now, limit) as ScheduleJobRow[]
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function listEnabledScheduleJobs(db: Database): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC')
|
||||
const rows = stmt.all() as ScheduleJobRow[]
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function getScheduleJobById(db: Database, repoId: number, jobId: number): ScheduleJob | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
const row = stmt.get(repoId, jobId) as ScheduleJobRow | undefined
|
||||
return row ? rowToScheduleJob(row) : null
|
||||
}
|
||||
|
||||
export function createScheduleJob(db: Database, repoId: number, input: ScheduleJobPersistenceInput): ScheduleJob {
|
||||
const now = Date.now()
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO schedule_jobs (
|
||||
repo_id, name, description, enabled, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const result = stmt.run(
|
||||
repoId,
|
||||
input.name,
|
||||
input.description ?? null,
|
||||
input.enabled ? 1 : 0,
|
||||
input.scheduleMode,
|
||||
input.intervalMinutes,
|
||||
input.cronExpression,
|
||||
input.timezone,
|
||||
input.agentSlug ?? null,
|
||||
input.prompt,
|
||||
input.model ?? null,
|
||||
serializeSkillMetadata(input.skillMetadata),
|
||||
now,
|
||||
now,
|
||||
null,
|
||||
input.nextRunAt,
|
||||
)
|
||||
|
||||
const job = getScheduleJobById(db, repoId, Number(result.lastInsertRowid))
|
||||
if (!job) {
|
||||
throw new Error('Failed to load created schedule job')
|
||||
}
|
||||
return job
|
||||
}
|
||||
|
||||
export function updateScheduleJob(db: Database, repoId: number, jobId: number, input: ScheduleJobPersistenceInput): ScheduleJob | null {
|
||||
const existing = getScheduleJobById(db, repoId, jobId)
|
||||
if (!existing) {
|
||||
return null
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_jobs
|
||||
SET name = ?, description = ?, enabled = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?, agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, updated_at = ?, next_run_at = ?
|
||||
WHERE repo_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
input.name,
|
||||
input.description,
|
||||
input.enabled ? 1 : 0,
|
||||
input.scheduleMode,
|
||||
input.intervalMinutes,
|
||||
input.cronExpression,
|
||||
input.timezone,
|
||||
input.agentSlug,
|
||||
input.prompt,
|
||||
input.model,
|
||||
serializeSkillMetadata(input.skillMetadata),
|
||||
now,
|
||||
input.nextRunAt,
|
||||
repoId,
|
||||
jobId,
|
||||
)
|
||||
|
||||
return getScheduleJobById(db, repoId, jobId)
|
||||
}
|
||||
|
||||
export function deleteScheduleJob(db: Database, repoId: number, jobId: number): boolean {
|
||||
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
const result = stmt.run(repoId, jobId)
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
export function reserveScheduleJobNextRun(db: Database, repoId: number, jobId: number, nextRunAt: number): void {
|
||||
const stmt = db.prepare('UPDATE schedule_jobs SET next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||
stmt.run(nextRunAt, Date.now(), repoId, jobId)
|
||||
}
|
||||
|
||||
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
|
||||
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
|
||||
}
|
||||
|
||||
export function createScheduleRun(
|
||||
db: Database,
|
||||
input: {
|
||||
jobId: number
|
||||
repoId: number
|
||||
triggerSource: ScheduleRunTriggerSource
|
||||
status: ScheduleRunStatus
|
||||
startedAt: number
|
||||
createdAt: number
|
||||
},
|
||||
): ScheduleRun {
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const result = stmt.run(
|
||||
input.jobId,
|
||||
input.repoId,
|
||||
input.triggerSource,
|
||||
input.status,
|
||||
input.startedAt,
|
||||
input.createdAt,
|
||||
)
|
||||
|
||||
const run = getScheduleRunById(db, input.repoId, input.jobId, Number(result.lastInsertRowid))
|
||||
if (!run) {
|
||||
throw new Error('Failed to load created schedule run')
|
||||
}
|
||||
return run
|
||||
}
|
||||
|
||||
export function updateScheduleRun(
|
||||
db: Database,
|
||||
repoId: number,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
input: {
|
||||
status: ScheduleRunStatus
|
||||
finishedAt: number
|
||||
sessionId?: string | null
|
||||
sessionTitle?: string | null
|
||||
logText?: string | null
|
||||
responseText?: string | null
|
||||
errorText?: string | null
|
||||
},
|
||||
): ScheduleRun | null {
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_runs
|
||||
SET status = ?, finished_at = ?, session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
|
||||
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
input.status,
|
||||
input.finishedAt,
|
||||
input.sessionId ?? null,
|
||||
input.sessionTitle ?? null,
|
||||
input.logText ?? null,
|
||||
input.responseText ?? null,
|
||||
input.errorText ?? null,
|
||||
repoId,
|
||||
jobId,
|
||||
runId,
|
||||
)
|
||||
|
||||
return getScheduleRunById(db, repoId, jobId, runId)
|
||||
}
|
||||
|
||||
export function updateScheduleRunMetadata(
|
||||
db: Database,
|
||||
repoId: number,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
input: {
|
||||
sessionId?: string | null
|
||||
sessionTitle?: string | null
|
||||
logText?: string | null
|
||||
responseText?: string | null
|
||||
errorText?: string | null
|
||||
},
|
||||
): ScheduleRun | null {
|
||||
const existing = getScheduleRunById(db, repoId, jobId, runId)
|
||||
if (!existing) {
|
||||
return null
|
||||
}
|
||||
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_runs
|
||||
SET session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
|
||||
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
input.sessionId === undefined ? existing.sessionId : input.sessionId,
|
||||
input.sessionTitle === undefined ? existing.sessionTitle : input.sessionTitle,
|
||||
input.logText === undefined ? existing.logText : input.logText,
|
||||
input.responseText === undefined ? existing.responseText : input.responseText,
|
||||
input.errorText === undefined ? existing.errorText : input.errorText,
|
||||
repoId,
|
||||
jobId,
|
||||
runId,
|
||||
)
|
||||
|
||||
return getScheduleRunById(db, repoId, jobId, runId)
|
||||
}
|
||||
|
||||
export function getScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||
const row = stmt.get(repoId, jobId, runId) as ScheduleRunRow | undefined
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
|
||||
export function getRunningScheduleRunByJob(db: Database, repoId: number, jobId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare(`
|
||||
SELECT * FROM schedule_runs
|
||||
WHERE repo_id = ? AND job_id = ? AND status = 'running'
|
||||
ORDER BY started_at DESC
|
||||
LIMIT 1
|
||||
`)
|
||||
const row = stmt.get(repoId, jobId) as ScheduleRunRow | undefined
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
|
||||
export function listRunningScheduleRuns(db: Database, limit: number = 100): ScheduleRun[] {
|
||||
const stmt = db.prepare(`
|
||||
SELECT * FROM schedule_runs
|
||||
WHERE status = 'running'
|
||||
ORDER BY started_at ASC
|
||||
LIMIT ?
|
||||
`)
|
||||
const rows = stmt.all(limit) as ScheduleRunRow[]
|
||||
return rows.map(rowToScheduleRun)
|
||||
}
|
||||
|
||||
export function listScheduleRunsByJob(db: Database, repoId: number, jobId: number, limit: number = 20): ScheduleRun[] {
|
||||
const stmt = db.prepare(`
|
||||
SELECT
|
||||
id,
|
||||
job_id,
|
||||
repo_id,
|
||||
trigger_source,
|
||||
status,
|
||||
started_at,
|
||||
finished_at,
|
||||
created_at,
|
||||
session_id,
|
||||
session_title,
|
||||
NULL AS log_text,
|
||||
NULL AS response_text,
|
||||
error_text
|
||||
FROM schedule_runs
|
||||
WHERE repo_id = ? AND job_id = ?
|
||||
ORDER BY started_at DESC
|
||||
LIMIT ?
|
||||
`)
|
||||
const rows = stmt.all(repoId, jobId, limit) as ScheduleRunRow[]
|
||||
return rows.map(rowToScheduleRun)
|
||||
}
|
||||
Reference in new issue
Block a user