The design language that makes your AI harness better at design.
JavaScript
Deal unseen challengers before repeating one on late Operate re-rolls (#896)
Paul Bakausdc78b325e753
diff --git a/crates/context/src/roll_selection.rs b/crates/context/src/roll_selection.rsindex 7399756f9..993553aa2 100644--- a/crates/context/src/roll_selection.rs+++ b/crates/context/src/roll_selection.rs@@ -103,10 +103,11 @@ fn tier_quotas(mode: Option<&str>) -> Option<HashMap<String, usize>> {/// JS: pickFromFamilies. Up to `count` concepts in ranked order, preferring one/// from a family not yet picked, then any concept not yet picked. At a count of/// two this is exactly the first-then-different-family pick of every roll-/// before quotas.-fn pick_from_families(order: &[Value], count: usize) -> Vec<Value> {+/// before quotas. `prior` are picks already in the hand, whose families count+/// as taken.+fn pick_from_families(order: &[Value], count: usize, prior: &[Value]) -> Vec<Value> {let mut picks: Vec<Value> = Vec::new();- let mut families: Vec<Value> = Vec::new();+ let mut families: Vec<Value> = prior.iter().map(|c| c.get("familyId").cloned().unwrap_or(Value::Null)).collect();let id_of = |c: &Value| s(c, "id").unwrap_or("").to_string();while picks.len() < count {let picked = |c: &Value| picks.iter().any(|p| id_of(p) == id_of(c));@@ -127,6 +128,24 @@ fn pick_from_families(order: &[Value], count: usize) -> Vec<Value> {picks}+/// JS: rankTier. A tier's pool in ticket order, one entry per concept.+fn rank_tier(pool: &[Value], salt_input: &str) -> Vec<Value> {+ let mut tickets = challenger_tickets(pool);+ if tickets.is_empty() {+ tickets = pool.iter().map(|c| Ticket { item: c.clone(), ticket: 0 }).collect();+ }+ let ranked = rank(&tickets, salt_input, |e| format!("{}#{}", s(&e.item, "id").unwrap_or(""), e.ticket));+ let mut ordered: Vec<Value> = Vec::new();+ let mut seen: HashSet<String> = HashSet::new();+ for e in ranked {+ let id = s(&e.item, "id").unwrap_or("").to_string();+ if seen.insert(id) {+ ordered.push(e.item);+ }+ }+ ordered+}+pub struct ChallengerSelection {pub approved: Vec<Value>,pub picks: Vec<Value>,@@ -202,30 +221,25 @@ pub fn select_approved_challengers(continue;}let full = by_tier.get(tier).cloned().unwrap_or_default();- let mut pool: Vec<Value> = full.iter().filter(|c| !excluded.contains(s(c, "id").unwrap_or(""))).cloned().collect();- // Reuse over starvation; under a quota, also when the tier can no- // longer fill its quota, so a re-roll still deals six.- if pool.is_empty() || (quotas.is_some() && pool.len() < quota) {- pool = full;- }- let mut tickets = challenger_tickets(&pool);- if tickets.is_empty() {- tickets = pool.iter().map(|c| Ticket { item: c.clone(), ticket: 0 }).collect();+ let fresh: Vec<Value> = full.iter().filter(|c| !excluded.contains(s(c, "id").unwrap_or(""))).cloned().collect();+ let salt_input = format!("{}:{}:challenger-{}{}", scope, key, index, salt);+ // Reuse over starvation.+ let first_pool = if fresh.is_empty() { &full } else { &fresh };+ let mut tier_picks = pick_from_families(&rank_tier(first_pool, &salt_input), quota, &[]);+ // Under a quota, a tier whose unseen worlds cannot fill the quota+ // deals every unseen one first and only then tops up from worlds+ // already shown, so a late re-roll never repeats a world ahead of a+ // new one.+ if quotas.is_some() && tier_picks.len() < quota && !fresh.is_empty() && fresh.len() < full.len() {+ let rest: Vec<Value> = full+ .iter()+ .filter(|c| !tier_picks.iter().any(|p| s(p, "id") == s(c, "id")))+ .cloned()+ .collect();+ let more = pick_from_families(&rank_tier(&rest, &salt_input), quota - tier_picks.len(), &tier_picks);+ tier_picks.extend(more);}- let ranked = rank(&tickets, &format!("{}:{}:challenger-{}{}", scope, key, index, salt), |e| {- format!("{}#{}", s(&e.item, "id").unwrap_or(""), e.ticket)- });- let mut ordered: Vec<Value> = Vec::new();- let mut seen: HashSet<String> = HashSet::new();- for e in ranked {- let id = s(&e.item, "id").unwrap_or("").to_string();- if seen.contains(&id) {- continue;- }- seen.insert(id);- ordered.push(e.item);- }- picks.extend(pick_from_families(&ordered, quota));+ picks.extend(tier_picks);}picks};@@ -461,6 +475,49 @@ mod tests {}}+ // A late re-roll whose unseen graphic concepts cannot fill the quota deals+ // every unseen one first, then tops up with families not yet in the hand.+ #[test]+ fn a_short_tier_deals_unseen_first_and_tops_up_across_families() {+ let open: Vec<Value> = parity()["concepts"].as_array().unwrap().clone();+ let graphic: Vec<Value> = open+ .iter()+ .filter(|c| {+ s(c, "status") == Some("approved")+ && s(c, "wellTier") == Some("graphic")+ && mode_allows(c, "operate")+ && matches!(s(c, "strength"), Some("world") | Some("dual"))+ && review_field(c, "breadth").and_then(|b| b.as_str()) != Some("niche")+ })+ .cloned()+ .collect();+ let mut seen: HashSet<String> = HashSet::new();+ let mut short_rounds = 0;+ for round in 0..6 {+ let sel = select_approved_challengers("direction", "chain", round, Some("operate"), &open).unwrap();+ let dealt: Vec<Value> = sel.picks.iter().filter(|p| s(p, "wellTier") == Some("graphic")).cloned().collect();+ let unseen: Vec<&Value> = graphic.iter().filter(|c| !seen.contains(s(c, "id").unwrap())).collect();+ let dealt_ids: HashSet<String> = ids(&dealt).into_iter().collect();+ if !unseen.is_empty() && unseen.len() < 5 && dealt.len() == 5 {+ short_rounds += 1;+ for c in &unseen {+ assert!(dealt_ids.contains(s(c, "id").unwrap()), "round {round} skipped unseen {}", s(c, "id").unwrap());+ }+ let taken: Vec<Value> = unseen.iter().map(|c| c["familyId"].clone()).collect();+ let top_up: Vec<&Value> = dealt.iter().filter(|p| !unseen.iter().any(|c| s(c, "id") == s(p, "id"))).collect();+ let families_left = graphic.iter().map(|c| c["familyId"].clone()).filter(|f| !taken.contains(f)).collect::<Vec<_>>();+ if !families_left.is_empty() {+ assert!(!taken.contains(&top_up[0]["familyId"]), "round {round} top-up reused a taken family");+ }+ }+ if unseen.is_empty() {+ break;+ }+ seen.extend(dealt_ids);+ }+ assert!(short_rounds > 0, "the chain never reached a short round");+ }+#[test]fn modes_without_a_quota_keep_two_per_tier() {let open: Vec<Value> = parity()["concepts"].as_array().unwrap().clone();diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex fcf92d66a..66b54fede 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -400,7 +400,7 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI- **Init gate** (render path only): imports `./context.mjs` `loadContext(cwd)`; if `!hasProduct` → `stdout> NO_PRODUCT_MD: the dice stay in the cup until product truth exists. Complete the init ask round and write PRODUCT.md first (reference/init.md), then re-run this exact command. Challengers fuse their form with facts from PRODUCT.md; without it every direction is ungrounded.\n`, `exit 1`.- **Assigned index math**: `unit(salt) = sha256(`${scope}:${salt}:${key}`).readUInt32BE(0)/0xffffffff`; `indexSalt = reroll===0 ? 'index' : `index:reroll-${reroll}``; `buildIndex = 3 + floor(unit(indexSalt)*(candidateCount-2))` (3..candidateCount). Surface scope deals `dealtIndices=[buildIndex]` plus up to 2 more distinct in 1..candidateCount via `unit(`${indexSalt}:deal-${draw}`)` (fills sequentially after 64 draws).- **Data resolution**: local catalog → `source:'local'` (challengers via `selectApprovedChallengers`, compositions via `selectApprovedCompositions`, both in `lib/roll-selection.mjs`, hash = Node sha256 hex; `poolRevision` = first 12 hex of sha256 over sorted approved `familyId:id:strength:form:spark:JSON(system):webLeverage` lines); else **roll API** `GET ${API_BASE}/roll?scope=&key=&reroll=[&mode=][&grain=][&platform=]` (`URLSearchParams` order: scope, key, reroll, mode, grain, platform), raced against the shared budget; non-ok, timeout, or `challengers` empty → null; response fields used: `poolRevision, approvedCount, catalogCount, challengers, compositions|stagings|staging`; else **degraded**.-- **Selection algorithm** (roll-selection): challengers: approved concepts; per `wellTier` in `['graphic','interaction','atmosphere']` (all three must be non-empty), optional `minRating` gate, `mode` gate (`review.allowedModes` absent = all; a tier the gate would empty keeps its full pool, except under a mode with tier quotas, where that tier's quota moves to `graphic` and the tier is not refilled; `graphic` itself always falls back), strength filter (`direction` wants `world|dual`, `surface` wants `composition|dual`; per-tier fallback to full pool). Per-tier quota: `TIER_QUOTAS = { operate: { graphic: 5, interaction: 1, atmosphere: 0 } }`, every other mode (and no mode) 2 per tier. Tier order ranked by digests of `${scope}:${key}:tiers${salt}:${tierId}` desc; a zero-quota tier is skipped without shifting `index`; per tier tickets (`breadth==='niche'` excluded; tickets by rating `{1:1,2:2,3:2}`, default 2) ranked by `${scope}:${key}:challenger-${index}${salt}:${id}#${ticket}`; take `quota` picks in ranked order, each the first concept of a `familyId` not yet picked in that tier, else the next distinct id (at quota 2: first pick + first of a different family) → 6 picks when every tier can fill its quota, fewer on a thin catalog; re-roll round n excludes all earlier picks (fallback to the full tier pool if exhausted, and under a quota also when fewer than `quota` remain); `salt = round===0 ? '' : `:reroll-${round}``. Compositions: approved, non-niche (fallback all), `surface===mode` (empty → none), platform hard filter (`platforms` absent = all), tickets ranked with salt `${scope}:${key}:staging[:reroll-${round}]`, grain-preferred stable partition, distinct `familyId` first then top-up, count 3; `match = {grain, atGrain, grainAvailable, platform, platformExcluded}`.+- **Selection algorithm** (roll-selection): challengers: approved concepts; per `wellTier` in `['graphic','interaction','atmosphere']` (all three must be non-empty), optional `minRating` gate, `mode` gate (`review.allowedModes` absent = all; a tier the gate would empty keeps its full pool, except under a mode with tier quotas, where that tier's quota moves to `graphic` and the tier is not refilled; `graphic` itself always falls back), strength filter (`direction` wants `world|dual`, `surface` wants `composition|dual`; per-tier fallback to full pool). Per-tier quota: `TIER_QUOTAS = { operate: { graphic: 5, interaction: 1, atmosphere: 0 } }`, every other mode (and no mode) 2 per tier. Tier order ranked by digests of `${scope}:${key}:tiers${salt}:${tierId}` desc; a zero-quota tier is skipped without shifting `index`; per tier tickets (`breadth==='niche'` excluded; tickets by rating `{1:1,2:2,3:2}`, default 2) ranked by `${scope}:${key}:challenger-${index}${salt}:${id}#${ticket}`; take `quota` picks in ranked order, each the first concept of a `familyId` not yet picked in that tier, else the next distinct id (at quota 2: first pick + first of a different family) → 6 picks when every tier can fill its quota, fewer on a thin catalog; re-roll round n excludes all earlier picks (fallback to the full tier pool if exhausted; under a quota, when fewer than `quota` unseen concepts remain, deal those first, then top up from the rest of the tier ranked with the same salt); `salt = round===0 ? '' : `:reroll-${round}``. Compositions: approved, non-niche (fallback all), `surface===mode` (empty → none), platform hard filter (`platforms` absent = all), tickets ranked with salt `${scope}:${key}:staging[:reroll-${round}]`, grain-preferred stable partition, distinct `familyId` first then top-up, count 3; `match = {grain, atGrain, grainAvailable, platform, platformExcluded}`.- **stdout (full roll)**: header line `${SCOPE} CONCEPT SEED (key: ${key}; mode: ${mode ?? 'unscoped'}; source: ${local|api}; approved pool: ${poolRevision}; ${approvedCount}/${catalogCount} human-approved; rerun with --scope ${scope}[ --mode m] --from ${key}[ --reroll n][ --register r] --candidate-count ${n} to reproduce this roll against this catalog revision)`, then `[RE-ROLL ROUND n ...]`, the assigned block (`ASSIGNED INDEX: N` / `DEALT INDICES: a, b, c (index N leads)` + instruction, or SAFER/BOLDER REGISTER block), `CHALLENGERS:` with `renderChallenger` per concept:```${i+1}. ${form}diff --git a/tests/fixtures/roll-quota-parity.json b/tests/fixtures/roll-quota-parity.jsonindex 5d64c8551..8e6aad714 100644--- a/tests/fixtures/roll-quota-parity.json+++ b/tests/fixtures/roll-quota-parity.json@@ -1608,10 +1608,10 @@"key": "alpha","reroll": 1,"picks": [+ "graphic-f3-c2","graphic-f1-c0","graphic-f0-c2","graphic-f2-c2",- "graphic-f3-c0","graphic-f2-c0","interaction-f3-c2"]@@ -1668,8 +1668,8 @@"key": "beta","reroll": 1,"picks": [- "graphic-f1-c0","graphic-f3-c2",+ "graphic-f1-c0","graphic-f2-c0","graphic-f0-c2","graphic-f3-c0",@@ -1729,8 +1729,8 @@"reroll": 1,"picks": ["interaction-f1-c2",- "graphic-f3-c0","graphic-f2-c0",+ "graphic-f3-c0","graphic-f1-c0","graphic-f0-c2","graphic-f3-c2"@@ -1789,10 +1789,10 @@"reroll": 1,"picks": ["interaction-f3-c2",+ "graphic-f3-c0","graphic-f2-c0","graphic-f1-c0","graphic-f0-c2",- "graphic-f3-c0","graphic-f2-c2"]},@@ -1848,11 +1848,11 @@"key": "alpha","reroll": 1,"picks": [- "graphic-f1-c1",+ "graphic-f1-c0","graphic-f3-c0","graphic-f2-c1","graphic-f0-c1",- "graphic-f1-c0",+ "graphic-f1-c1","interaction-f2-c0"]},@@ -1908,10 +1908,10 @@"key": "beta","reroll": 1,"picks": [+ "graphic-f1-c0","graphic-f3-c0","graphic-f2-c0","graphic-f0-c1",- "graphic-f1-c0","graphic-f1-c1","interaction-f1-c1"]@@ -1968,9 +1968,9 @@"key": "gamma","reroll": 1,"picks": [+ "graphic-f2-c0","graphic-f0-c1","graphic-f1-c0",- "graphic-f2-c1","graphic-f3-c0","graphic-f1-c1","interaction-f0-c1"@@ -2029,9 +2029,9 @@"reroll": 1,"picks": ["interaction-f1-c1",+ "graphic-f1-c0","graphic-f0-c1","graphic-f3-c0",- "graphic-f1-c0","graphic-f2-c1","graphic-f2-c0"]