WITH recent_allocations AS (
SELECT content
FROM artifacts
WHERE artifact_type = 'resource_allocation'
AND is_latest = 1
ORDER BY created_at DESC
LIMIT 3
),
funded_refs AS (
SELECT DISTINCT (alloc->>'target_ref') AS ref
FROM recent_allocations ra,
LATERAL jsonb_array_elements(
COALESCE(ra.content->'allocations', '[]'::jsonb)
) AS alloc
)
SELECT a.id::text AS ref, a.title
FROM artifacts a
WHERE a.lifecycle_state = 'canonical'
AND a.is_latest = 1
AND a.artifact_type IN ('task', 'hypothesis', 'knowledge_gap',
'gap', 'mission', 'challenge')
AND a.id NOT IN (
SELECT ref FROM funded_refs WHERE ref IS NOT NULL
)
AND COALESCE(a.lifecycle_state, '') = 'canonical'