@@ -3023,15 +3023,41 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
30233023 readonly plan_id : string ;
30243024 readonly run_id : string ;
30253025 readonly provider_thread_id : string | null ;
3026+ readonly last_plan_id : string ;
30263027 } > `
3027- SELECT plan.plan_id, owner.run_id, owner.provider_thread_id
3028- FROM orchestration_v2_projection_plans AS plan
3029- INNER JOIN orchestration_v2_projection_runs AS owner
3030- ON owner.thread_id = plan.thread_id AND owner.run_id = plan.run_id
3031- WHERE plan.thread_id = ${ threadId }
3032- AND plan.kind = 'todo_list' AND plan.status <> 'superseded'
3033- ORDER BY owner.ordinal DESC, plan.plan_id DESC
3034- LIMIT 1
3028+ WITH latest_owner AS MATERIALIZED (
3029+ SELECT plan.plan_id, owner.run_id, owner.provider_thread_id
3030+ FROM orchestration_v2_projection_plans AS plan
3031+ INNER JOIN orchestration_v2_projection_runs AS owner
3032+ ON owner.thread_id = plan.thread_id AND owner.run_id = plan.run_id
3033+ WHERE plan.thread_id = ${ threadId }
3034+ AND plan.kind = 'todo_list' AND plan.status <> 'superseded'
3035+ ORDER BY owner.ordinal DESC, plan.plan_id DESC
3036+ LIMIT 1
3037+ )
3038+ SELECT COALESCE(CASE WHEN EXISTS (
3039+ SELECT 1 FROM orchestration_v2_projection_plans
3040+ WHERE thread_id = ${ threadId } AND run_id = owner.run_id
3041+ AND kind = 'todo_list' AND status <> 'superseded'
3042+ AND plan_id <> owner.plan_id
3043+ ) THEN (
3044+ -- Plan UUIDs cannot order replacements within a run.
3045+ SELECT plan.plan_id
3046+ FROM orchestration_v2_projection_turn_items AS item
3047+ CROSS JOIN orchestration_v2_projection_plans AS plan
3048+ ON plan.plan_id = json_extract(item.payload_json, '$.planId')
3049+ WHERE item.run_id = owner.run_id AND item.thread_id = ${ threadId }
3050+ AND item.type = 'todo_list'
3051+ AND plan.run_id = owner.run_id AND plan.thread_id = ${ threadId }
3052+ AND plan.kind = 'todo_list' AND plan.status <> 'superseded'
3053+ ORDER BY item.ordinal DESC
3054+ LIMIT 1
3055+ ) END, owner.plan_id) AS plan_id, owner.run_id, owner.provider_thread_id,
3056+ (
3057+ SELECT MAX(plan_id) FROM orchestration_v2_projection_plans
3058+ WHERE thread_id = ${ threadId } AND run_id = owner.run_id
3059+ ) AS last_plan_id
3060+ FROM latest_owner AS owner
30353061 ` ;
30363062
30373063 const [
@@ -3282,7 +3308,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
32823308 SELECT value FROM json_each(${ cohortPlanIds } )
32833309 )
32843310 )
3285- ORDER BY plan_id ASC
3311+ -- Keep the selected artifact last within its run for equal-run consumers.
3312+ ORDER BY CASE WHEN plan_id = ${ latestTodoList ?. plan_id ?? null }
3313+ THEN ${ latestTodoList ?. last_plan_id ?? null } ELSE plan_id END ASC,
3314+ plan_id = ${ latestTodoList ?. plan_id ?? null } ASC
32863315 ` ,
32873316 fields !== undefined && ! fields . includes ( "checkpointScopes" )
32883317 ? Effect . succeed ( [ ] )
0 commit comments