Regenerate published weekly puzzles when a release's prices break them

--check now re-solves every week not over yet and, when its budget no longer
verifies, regenerates it deterministically: the same puzzle with a new budget
if that works, else a fresh one for the key. A regenerated file carries rev 2,
3...; the game keeps stars per revision, so only that week's stars reset.
Past weeks are left alone unless the game rejects them. release.yml runs it
before the tests on every deploy, weekly-puzzle.yml before making the new
week; either fails only if a week cannot be regenerated.
This commit is contained in:
Frederic Jung 2026-10-29 10:03:20 +01:00
parent 77ec31d1a0
commit 7cbe0ec09b
No known key found for this signature in database
10 changed files with 135 additions and 23 deletions

View file

@ -45,7 +45,8 @@ steps.
release tag** with `weekly=true`. That run rebuilds exactly the live release, with every weekly file from `main`
added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in the same `pages` concurrency group.
Players get no update banner (the version does not change). Every release build also copies all weekly files from
`main`, so a release never drops a published week. Weekly files are plain JSON the game fetches only when the
`main`, so a release never drops a published week, and regenerates (in the build, deterministically) any week
not over yet that the release's prices no longer fit. Weekly files are plain JSON the game fetches only when the
Puzzles list opens and never trusts; the service worker serves them network-first. See `docs/ARCHITECTURE.md`.
## Before you hand back a change that touches the build, deploy or loading

View file

@ -21,6 +21,13 @@ version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly
`gh workflow run release.yml --ref <live tag> -f tag=<live tag> -f weekly=true`). A release includes every weekly
file on `main` when it builds.
**Prices change, weeks follow.** `--check` re-solves every week not over yet with the game it runs; a week whose
budget no longer verifies is regenerated deterministically (the same puzzle with a new budget if that works, else a
fresh one for the same key) with `rev` + 1, which resets players' stars for that week only. Past weeks are left alone
unless the game rejects them. `release.yml` runs it before the tests on every deploy and fails only if a week cannot be
regenerated. A change to prices, cables or cities fails `npm test` until you run `node scripts/weekly-puzzle.js --check`
and commit the regenerated files with it.
## Only release when Frederic says so
Never bump the version on your own. Finished work is committed and pushed with its

View file

@ -80,16 +80,20 @@ jobs:
echo "Weekly puzzles: $(ls site/puzzles/weekly | grep -c '^[0-9].*\.json$')"
fi
- run: npm ci
- run: npm test
if: ${{ !inputs.weekly }}
- name: Check the weekly puzzles against this release
if: ${{ inputs.weekly }}
# This release's prices may no longer fit a week already published: --check regenerates every week not over
# yet whose budget no longer verifies (deterministically, so main's next weekly run commits the same files),
# and fails the deploy only if that fails. Before the tests, which check the weeks too.
- name: Fit the weekly puzzles to this release
run: |
set -euo pipefail
# A release from before the weekly puzzles ships the files without reading them: nothing to check.
if [ ! -f scripts/weekly-puzzle.js ]; then echo "This release does not read weekly puzzles yet."; exit 0; fi
node scripts/weekly-puzzle.js --check
npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js
- run: npm test
if: ${{ !inputs.weekly }}
- name: Test the weekly puzzles against this release
if: ${{ inputs.weekly && hashFiles('scripts/weekly-puzzle.js') != '' }}
run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js
- name: Build site
run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build
- uses: actions/upload-pages-artifact@v5

View file

@ -45,6 +45,9 @@ jobs:
node-version: 24
cache: npm
- run: npm ci
# Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current.
- name: Fit the published weeks to main
run: node scripts/weekly-puzzle.js --check
- name: Make the puzzle
run: |
set -euo pipefail

View file

@ -45,6 +45,7 @@ All notable changes to this project are documented here. The project follows
- Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake.
- The intern only signs a customer after a trial run shows the network can carry them without hurting anyone else, and rushes every repair that has a price, while the budget lasts (#185). The bulk peering and PNI batches live in the Ops sheet, next to the orders that repeat them (#181, #192).
- Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere.
- When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs.
## [1.37.0] — 2026-10-28

View file

@ -7,7 +7,8 @@
// node scripts/weekly-puzzle.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing
// node scripts/weekly-puzzle.js --key 2026-W45 that week (--force replaces an existing file)
// node scripts/weekly-puzzle.js --next 3 this week and the next two
// node scripts/weekly-puzzle.js --check validate every file (and re-verify the stars of weeks not over yet)
// node scripts/weekly-puzzle.js --check regenerate weeks not over yet whose budget this game no longer verifies
// (see refresh()), then validate every file; fails only if that fails
// --page FILE play another build of the game (the live release), see the workflow
// --dir DIR where the files live (default site/puzzles/weekly)
//
@ -250,6 +251,7 @@ function play(ev, def, links) {
ev('closeModal()');
return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))'));
}
// A first edition has no rev; refresh() adds rev 2, 3… when it regenerates a week.
const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, via: P.via, avoid: P.avoid, budget,
twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}, P.lat ? { lat: P.lat } : {}),
name: w.name, joke: w.joke, ref: { one: sol.one.cost, three: sol.three.cost } });
@ -267,6 +269,14 @@ function verify(g, W, j, key) {
return { ok: true, sol, s1, s3 };
}
// Three stars need the smart design: the budget sits just above the cheapest N-1 build found, and below the
// obvious one (a second way along every hop) whenever there is room.
function budgetOf(sol) {
let budget = ceil10k(sol.three.cost * 1.05);
if (sol.naive && budget >= sol.naive.cost) budget = Math.max(ceil10k(sol.three.cost), Math.floor((sol.naive.cost - 1) / 10000) * 10000);
return budget;
}
function generate(g, key, dir) {
const { ev } = g, W = world(ev);
if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`);
@ -281,11 +291,7 @@ function generate(g, key, dir) {
if (!P || hist.regs.some((c) => W.C[c] && W.C[c].reg === W.C[P.cities[0]].reg && W.C[c].lands[0] === W.C[P.cities[0]].lands[0])) continue;
const sol = solve(W, P);
if (!sol.one || !sol.three) continue;
// Three stars need the smart design: the budget sits just above the cheapest N-1 build found, and below the
// obvious one (a second way along every hop) whenever there is room.
let budget = ceil10k(sol.three.cost * 1.05);
if (sol.naive && budget >= sol.naive.cost) budget = Math.max(ceil10k(sol.three.cost), Math.floor((sol.naive.cost - 1) / 10000) * 10000);
const smart = sol.naive ? sol.naive.cost / budget : 1.05, slack = budget / sol.one.cost;
const budget = budgetOf(sol), smart = sol.naive ? sol.naive.cost / budget : 1.05, slack = budget / sol.one.cost;
const score = Math.min(smart, 1.6) + Math.min(slack, 2) * 0.2 + r() * 0.05;
cands.push({ P, sol, budget, score, w: words(ev, W, P, r) });
}
@ -315,16 +321,54 @@ function check(g, dir, now = Date.now()) {
}
return bad;
}
/* --check, first part: a release can change prices, cables or cities under weeks that are already published. Every
week not over yet is re-solved with this game; when its budget no longer verifies it is regenerated, deterministically:
the same puzzle (theme, cities, twist, name) with a new budget when that still works, else a fresh puzzle for the
same key. Its rev goes up, so players' stars for that week (and only that week) start again; new references alone
keep the rev. Past weeks can no longer be played, so they keep their stars and are only replaced when the game
rejects them outright. Returns what changed and what could not be fixed. */
function refresh(g, dir, now = Date.now()) {
const { ev } = g, W = world(ev), fixed = [], bad = [];
for (const k of list(dir)) {
const f = path.join(dir, k + '.json');
let j = null; try { j = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { /* regenerated below */ }
const valid = !!j && ev(`!!pzWkValid(${JSON.stringify(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
if (valid && !live) continue;
const v = valid ? verify(g, W, j, k) : null;
if (v && v.ok) {
if (j.ref && j.ref.one === v.sol.one.cost && j.ref.three === v.sol.three.cost) continue;
j.ref = { one: v.sol.one.cost, three: v.sol.three.cost }; writeWeek(dir, j); fixed.push(`${k}: new references`); continue;
}
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
let n = null;
if (valid) {
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(j)},'${k}'))`));
const sol = solve(W, { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: def.lat });
if (sol.one && sol.three) {
const c = Object.assign({}, j, { budget: budgetOf(sol), ref: { one: sol.one.cost, three: sol.three.cost }, rev });
if (verify(g, W, c, k).ok) n = c;
}
}
if (!n) { try { n = Object.assign(generate(g, k, dir), { rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; } }
writeWeek(dir, n); fixed.push(`${k}: regenerated as rev ${rev}${n.theme === (j && j.theme) && JSON.stringify(n.cities) === JSON.stringify(j.cities) ? ', same puzzle, new budget ' + n.budget : ', a new ' + n.theme + ' puzzle'}`);
}
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ }
if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); }
return { fixed, bad };
}
const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n');
const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); };
module.exports = { game, generate, check, solve, world, writeWeek, writeIndex, list };
module.exports = { game, generate, check, refresh, solve, world, writeWeek, writeIndex, list };
if (require.main === module) {
const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
const dir = path.resolve(ROOT, opt('--dir', 'site/puzzles/weekly')), g = game(opt('--page') && path.resolve(opt('--page')));
if (args.includes('--check')) {
const bad = check(g, dir);
// Fix what a release's new prices broke, then check everything; only what could not be fixed fails.
const r = refresh(g, dir);
for (const x of r.fixed) console.log(`fixed: ${x}`);
const bad = [...r.bad, ...check(g, dir)];
for (const b of bad) console.error(`error: ${b}`);
console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly puzzle(s) OK`);
process.exit(bad.length ? 1 : 0);

View file

@ -10,11 +10,13 @@ const pzName=d=>d.id==='weekly'?(d.wn?pzTxt(d.wn):tr('puzzles.weekly_puzzle_key'
const pzStarStr=n=>'⭐'.repeat(n)+'⬜'.repeat(3-n);
// ---------- progress (localStorage, never trusted) ----------
function pzClean(j){const o={s:{},wk:{},streak:{last:null,n:0,best:0}};if(!j||typeof j!=='object')return o;
const rec=r=>r&&typeof r==='object'?{st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)}:null;
const rec=r=>{if(!r||typeof r!=='object')return null;const o={st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)},rv=int(r.rv,1,999,1);if(rv>1)o.rv=rv;return o;};
if(j.s&&typeof j.s==='object')for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;}
if(j.wk&&typeof j.wk==='object')for(const k of Object.keys(j.wk)){const r=rec(j.wk[k]);if(/^\d{4}-W\d{2}$/.test(k)&&r)o.wk[k]=r;}
const st=j.streak;if(st&&typeof st==='object'){o.streak.last=typeof st.last==='string'&&/^\d{4}-W\d{2}$/.test(st.last)?st.last:null;o.streak.n=int(st.n,0,9999,0);o.streak.best=int(st.best,0,9999,0);}
return o;}
// A weekly's stars belong to the revision they were earned on: a week regenerated for new prices starts again.
const pzWkRec=(p,d)=>{const r=p.wk[d.key];return r&&(r.rv||1)===(d.rev||1)?r:null;};
function pzLoad(){try{return pzClean(JSON.parse(localStorage.getItem(PZ_KEY)||'{}'));}catch(e){return pzClean(null);}}
function pzStore(p){try{localStorage.setItem(PZ_KEY,JSON.stringify(p));}catch(e){}}
const pzStarsTotal=p=>PZ.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0);
@ -86,7 +88,7 @@ const pzToastsClear=()=>{$('toasts').textContent='';};
function pzFlush(){save(true);UI.pzKeep=S;}
function pzBegin(def){if(!def)return;
const go=()=>{newGame(pzName(def),def.cities[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null;
S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null};
S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null,rev:def.rev||1};
UI.pzHist=[];UI.pzTop=0;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null;
$('dash').hidden=true;$('bankBox').hidden=true;closeModal();pzToastsClear();document.body.classList.add('pz');
compute();pzCam();renderAll();track('puzzle_'+def.id);
@ -114,8 +116,8 @@ function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI
// Every solved state is recorded, so a cheaper build at the same stars counts too.
function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;pzResults(e,prev);return e;}
// The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend.
function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=bag[k]||{st:0,sp:null};
function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null};
if(e.stars<r.st||(e.stars===r.st&&r.sp!=null&&r.sp<=e.spend))return;
r.sp=e.spend;r.st=e.stars;bag[k]=r;if(P.id==='weekly')pzStreak(p,P.key);pzStore(p);}
r.sp=e.spend;r.st=e.stars;if(P.id==='weekly'&&P.rev>1)r.rv=P.rev;else delete r.rv;bag[k]=r;if(P.id==='weekly')pzStreak(p,P.key);pzStore(p);}
// The next puzzle in the list whose pack is open.
function pzNextDef(){const p=pzLoad(),i=PZ.findIndex(x=>x.id===S.pz.id);for(let j=i+1;j<PZ.length;j++)if(pzPackOpen(PZ[j].pack,p))return PZ[j];return null;}

View file

@ -41,14 +41,16 @@ function pzWkTxt(o,list){if(!pzObj(o)||typeof o.l!=='string'||!list.includes(o.l
for(const k of need){const t=PZ_WK_P[k],v=own(p,k)?p[k]:undefined;
if(t==='c'&&pzCityOk(v))out[k]=v;else if(t==='r'&&typeof v==='string'&&own(WAVE_NAME,v))out[k]=v;else if(t==='n'&&Number.isInteger(v)&&v>0&&v<1000)out[k]=v;else return null;}
return {l:o.l,p:out};}
const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref'];
// rev: the file's revision, from 2 when a release's new prices made the week regenerate (scripts/weekly-puzzle.js).
const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref','rev'];
function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==1||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(PZ_WK_THEMES,j.theme))return null;
const T=PZ_WK_THEMES[j.theme],ids=(a,lo,hi)=>Array.isArray(a)&&a.length>=lo&&a.length<=hi&&a.every(pzCityOk)&&new Set(a).size===a.length?a.slice():null;
const cities=ids(j.cities,3,6),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2);if(!cities||!via||!avoid)return null;
const all=[...cities,...via,...avoid];if(new Set(all).size!==all.length)return null;
if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>1e7)return null;
const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['lat','ring','noSub','minG'].includes(k)))return null;
const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null};
if(j.rev!==undefined&&!(Number.isInteger(j.rev)&&j.rev>=2&&j.rev<=999))return null;
const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null,rev:j.rev||1};
if(own(tw,'ring')){if(tw.ring!==true)return null;d.ring=true;}
if(own(tw,'noSub')){if(tw.noSub!==true)return null;d.noSub=true;}
if(own(tw,'minG')){if(![100,400].includes(tw.minG))return null;d.minG=tw.minG;}
@ -72,4 +74,4 @@ function pzWkRefresh(){const el=$('pzWk');if(el)el.outerHTML=pzWkRow();}
function pzWkNext(now){const key=pzWeekKey(now),t=pzWeekStart(pzKeyAdd(key,1))-now,m=Math.max(1,Math.ceil(t/60e3)),d=Math.floor(m/1440),h=Math.floor(m%1440/60);
return d?tr('puzzles.next_weekly_in_d_h',{d,h}):tr('puzzles.next_weekly_in_h_m',{h,m:m%60});}
// The Puzzles door says so when this week's puzzle has not been played yet.
function pzWkNew(){try{return !pzLoad().wk[pzWeekKey(new Date())];}catch(e){return false;}}
function pzWkNew(){try{const k=pzWeekKey(new Date()),w=UI.pzWk;return !pzWkRec(pzLoad(),w&&w.key===k&&w.def?w.def:{key:k});}catch(e){return false;}}

View file

@ -75,7 +75,7 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left
if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);}
// ---------- the list ----------
// The weekly row: the published puzzle once it has come (or the seeded one), its countdown and the streak.
function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=p.wk[w.key],st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzTwistTag(w);
function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=pzWkRec(p,w),st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzTwistTag(w);
return `<div class="scn wk" id="pzWk"><div class="grow"><div class="eyebrow">📅 ${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})}${wr?'':` <span class="pznew">${tr('puzzles.new_this_sunday')}</span>`}</div>
<div class="nm">${load?tr('puzzles.loading_this_week_s_puzzle'):`${T?T.i+' ':''}${esc(pzName(w))}`} ${wr?`<span class="pzst">${pzStarStr(wr.st)}</span>`:''}</div>${w.wj?`<div class="meta">${esc(pzTxt(w.wj))}</div>`:''}
<div class="meta">${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · <b>'+tg.join(' · ')+'</b>':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}</div>

View file

@ -96,7 +96,8 @@ test('generator: a quarter of weeks, all verified, varied, small and in the sche
test('--check passes on the committed files and rejects tampered ones', () => {
const g = G.game();
// Weeks still to come are re-solved; past ones are checked the way the game reads them.
// Weeks still to come are re-solved; past ones are checked the way the game reads them. check() only reports;
// refresh() (the first half of --check) is what fixes.
assert.deepEqual(G.check(g, DIR), [], 'committed weeklies verify');
const bad = (edit, why) => {
const d = tmp();
@ -117,6 +118,53 @@ test('--check passes on the committed files and rejects tampered ones', () => {
bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks');
});
test('--check regenerates a published week when new prices break its budget, and only then', () => {
const g = G.game(), d = tmp();
for (const k of G.list(DIR)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json'));
G.writeIndex(d);
const read = (k) => JSON.parse(fs.readFileSync(path.join(d, k + '.json'), 'utf8')), [k0, k1] = G.list(d).slice(-2);
assert.deepEqual(G.refresh(g, d, 0), { fixed: [], bad: [] }, 'the committed weeks still verify: nothing changes');
// Prices went up: the old budget no longer buys the N-1 build. The same puzzle comes back with a budget that does.
const old = read(k0), j = read(k0); j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1;
fs.writeFileSync(path.join(d, k0 + '.json'), JSON.stringify(j));
const r = G.refresh(g, d, 0);
assert.deepEqual(r.bad, []);
assert.equal(r.fixed.length, 1, r.fixed.join('; '));
const n = read(k0);
assert.equal(n.rev, 2, 'a new revision');
assert.deepEqual([n.theme, n.cities, n.via, n.avoid, n.twist, n.name, n.joke], [old.theme, old.cities, old.via, old.avoid, old.twist, old.name, old.joke], 'the same puzzle');
assert.ok(n.budget >= n.ref.three && n.ref.three > j.budget);
assert.deepEqual(G.check(g, d, 0), [], 'and it verifies');
assert.deepEqual(G.refresh(g, d, 0), { fixed: [], bad: [] }, 'deterministic and settled: a second run changes nothing');
// A week the game rejects (a city that is gone) gets a fresh puzzle under the same key.
const b = read(k1); b.cities[0] = 'xxx'; fs.writeFileSync(path.join(d, k1 + '.json'), JSON.stringify(b));
assert.equal(G.refresh(g, d, 0).fixed.length, 1);
assert.equal(read(k1).key, k1);
assert.equal(read(k1).rev, 2);
assert.deepEqual(G.check(g, d, 0), []);
// Weeks that are over cannot be played again: their stars stay, so a broken budget there is left alone.
const e = read(k0); e.budget = 50000; fs.writeFileSync(path.join(d, k0 + '.json'), JSON.stringify(e));
assert.deepEqual(G.refresh(g, d, 8.64e15), { fixed: [], bad: [] });
});
test('stars belong to the revision of the week they were earned on', () => {
const { ev, errors } = load();
const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`);
assert.equal(ev(`pzWkValid(${JSON.stringify(j)},'${k}').rev`), 1, 'a first edition is rev 1');
assert.ok(ok({ ...j, rev: 2 }));
for (const rev of [1, 0, '2', 2.5, 1000]) assert.equal(ok({ ...j, rev }), false, `rev ${rev}`);
ev(`localStorage.setItem('sot-puzzles',JSON.stringify({wk:{'${k}':{st:3,sp:1},'2026-W01':{st:2,sp:5}}}))`);
assert.equal(ev(`pzWkRec(pzLoad(),pzWkValid(${JSON.stringify(j)},'${k}')).st`), 3, 'same week, same revision: the stars stand');
const d2 = `pzWkValid(${JSON.stringify({ ...j, rev: 2 })},'${k}')`;
assert.equal(ev(`pzWkRec(pzLoad(),${d2})`), null, 'regenerated: that week starts again');
ev(`pzBegin(${d2});pzRecord({stars:1,spend:9})`);
const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')"));
assert.deepEqual(p.wk[k], { st: 1, sp: 9, rv: 2 }, 'a lower score on the new revision replaces the old one');
assert.deepEqual(p.wk['2026-W01'], { st: 2, sp: 5 }, 'other weeks keep theirs');
assert.equal(ev(`pzWkRec(pzLoad(),${d2}).st`), 1);
assert.deepEqual(errors, []);
});
test('the page never asks for a weekly puzzle on load, only when Puzzles opens', async () => {
const { ev, errors } = load();
ev("window.__f=[];window.fetch=(u,o)=>{__f.push(String(u));return Promise.resolve({ok:false,json:()=>Promise.reject()})}");