diff --git a/src/db.ts b/src/db.ts index e528195..9877f00 100644 --- a/src/db.ts +++ b/src/db.ts @@ -516,18 +516,26 @@ export async function listStoryThreads(args: { status?: string; limit?: number; } = {}) { - const values: unknown[] = []; - const where: string[] = []; + const limit = Math.min(Math.max(Number(args.limit ?? 30), 1), 100); if (args.status) { if (!STORY_STATUSES.has(args.status)) throw new Error("Invalid story status"); - values.push(args.status); - where.push(`t.status=${values.length}`); + const result = await pool.query( + `SELECT t.*, + (SELECT COUNT(*)::int FROM story_nodes n WHERE n.thread_id=t.id) AS node_count, + (SELECT COUNT(*)::int FROM story_edges e WHERE e.thread_id=t.id) AS edge_count, + (SELECT result FROM story_research_checks c + WHERE c.thread_id=t.id AND c.check_type='counter_evidence' + LIMIT 1) AS counter_evidence_result + FROM story_threads t + WHERE t.status=$1 + ORDER BY t.updated_at DESC + LIMIT $2`, + [args.status, limit] + ); + return result.rows; } - const limit = Math.min(Math.max(Number(args.limit ?? 30), 1), 100); - values.push(limit); - const result = await pool.query( `SELECT t.*, (SELECT COUNT(*)::int FROM story_nodes n WHERE n.thread_id=t.id) AS node_count, @@ -536,10 +544,9 @@ export async function listStoryThreads(args: { WHERE c.thread_id=t.id AND c.check_type='counter_evidence' LIMIT 1) AS counter_evidence_result FROM story_threads t - ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY t.updated_at DESC - LIMIT ${values.length}`, - values + LIMIT $1`, + [limit] ); return result.rows; }