Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .claude/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "hascone-dev",
"runtimeExecutable": ".venv/Scripts/python.exe",
"runtimeArgs": ["app.py", "--desktop"],
"env": {"HASCONE_PORT": "5077"},
"port": 5077,
"url": "http://127.0.0.1:5077"
}
]
}
22 changes: 19 additions & 3 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,15 +299,31 @@ def item_starforce_modes(identifier, slot):
from starforce.cost import item_modes

modes = item_modes((request.get_json(silent=True) or {}).get("modes"))
return _set_item_setting(identifier, slot, "starforce_modes", modes)


@app.post("/api/characters/<identifier>/equipment/<slot>/starforce-target")
def item_starforce_target(identifier, slot):
"""Rank every star up to this item's target, or clear it to rank only the next star.

A target above the item's star limit is kept as typed; ranking stops at the limit."""
from starforce.cost import item_target

target = item_target((request.get_json(silent=True) or {}).get("target"))
return _set_item_setting(identifier, slot, "starforce_target", target)


def _set_item_setting(identifier, slot, key, value):
"""Save a player setting on this slot's scanned item, or clear it when VALUE is empty."""
with characters.lock:
data = characters.load(identifier)
item = data["equipment"].get(slot)
if slot not in LAYOUT["slots"] or not isinstance(item, dict):
raise ValueError("Scan this item first")
if modes:
item["starforce_modes"] = modes
if value:
item[key] = value
else:
item.pop("starforce_modes", None)
item.pop(key, None)
characters.write(data)
return character(identifier)

Expand Down
2 changes: 2 additions & 0 deletions src/enhancement_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ def _add_starforce_row(result, detail, common, slot, item, options_config):

if slot.split("_")[0] in sf_stats.EXCLUDED_SLOTS or reading.get("status") == "not_applicable":
return
# The most stars this item can reach, so the target field can cap what is typed.
detail["starforce_limit"] = sf_stats.star_limit(slot, item)
try:
if reading.get("status") != "scanned":
raise ValueError("Hover this item to scan its stars first.")
Expand Down
4 changes: 3 additions & 1 deletion src/scouter/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,10 +274,12 @@ def snapshot(identifier):
data["history"] = [{k: v for k, v in with_boss_cuts(r).items() if k != "input"} for r in data["history"]]
data["fingerprint"] = fingerprint(values)
from flaming import characters
from scouter.suggestions import MODEL_VERSION, signature

# The page compares saved recommendations against this to flag an outdated model.
data["suggestions_model_version"] = MODEL_VERSION
try:
gear = characters.load(identifier)
from scouter.suggestions import signature

data["gear_fingerprint"] = signature(gear)
except (OSError, ValueError, KeyError, TypeError):
Expand Down
4 changes: 2 additions & 2 deletions src/scouter/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,10 +415,10 @@ def ensure_suggestions(identifier):
if not any(item.get("name") for item in gear.get("equipment",{}).values()):
return {"active":False,"status":"needs_equipment","message":"Scan equipped gear to unlock upgrade recommendations."}
sf = options(data.get("starforce_options"))
key = profiles.fingerprint([digest,suggestions.signature(gear),sf,6])
key = profiles.fingerprint([digest,suggestions.signature(gear),sf,suggestions.MODEL_VERSION])
saved = data.get("suggestions") or {}
if (saved.get("fingerprint")==digest and saved.get("gear_fingerprint")==suggestions.signature(gear)
and saved.get("starforce_options")==sf and saved.get("model_version")==6):
and saved.get("starforce_options")==sf and saved.get("model_version")==suggestions.MODEL_VERSION):
return {"active":False,"status":"complete","message":"Upgrade recommendations are up to date."}
if _job["active"]:
return {**state(),"status":"busy"}
Expand Down
19 changes: 16 additions & 3 deletions src/scouter/suggestions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
from starforce.suggestions import suggestions as starforce_suggestions
from utils.payload_data import read_payload_json

# Stamped on saved recommendations; bump it whenever the ranking math changes so saved results recompute.
MODEL_VERSION = 8

PROTECTED = {"Critical Damage %", "Skill Cooldown Reduction", "Item Drop Rate %", "Meso Amount %"}
VALUE_METRICS = [
"STR",
Expand Down Expand Up @@ -409,10 +412,20 @@ def hat_model(parsed):
)
rows.extend(slot_rows)
skipped.extend(slot_skipped)
rows.sort(key=lambda r: (-r["fd_per_billion"], r["expected_mesos"], r["slot"], r["method"]))
# Star Force steps toward a target share a capped score with the step before them;
# rank_mesos and step keep such a run together and in star order.
rows.sort(
key=lambda r: (
-r["fd_per_billion"],
r.get("rank_mesos", r["expected_mesos"]),
r["slot"],
r.get("step", 1),
r["method"],
)
)
return {
"created": profiles.now(),
"model_version": 6,
"model_version": MODEL_VERSION,
"starforce_options": starforce_options(data.get("starforce_options")),
"cooldown_cache": cooldown_cache,
"baseline_id": record["id"],
Expand All @@ -425,5 +438,5 @@ def hat_model(parsed):
"rows": rows,
"skipped": skipped,
"model": "Expected incremental FD at 380 DEF, using Scouter’s stat efficiencies and cooldown score curves. Gains are estimates, not exact full-build simulations.",
"basis": "Flames/cubes: expected cost and average FD of qualifying rolls. Star Force: expected tap cost and FD at the selected star target, including recovery costs. Use the same preset for scans and Scouter.",
"basis": "Flames/cubes: expected cost and average FD of qualifying rolls. Star Force: expected tap cost and FD of each star up to the item's target (or the next star), including recovery costs; a step never ranks above the one before it. Use the same preset for scans and Scouter.",
}
9 changes: 9 additions & 0 deletions src/starforce/cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ def item_modes(value):
return {str(star): value[str(star)] for star in MODE_STARS}


def item_target(value):
"""An item's target stars (1★–30★), or None to rank only the next star."""
if value is None:
return None
if type(value) is not int or not 1 <= value <= 30:
raise ValueError("Target stars must be a whole number from 1 to 30")
return value


def mode_summary(modes):
"""Item modes as runs of stars, e.g. "15–16★ Safeguard, 17–19★ Mode 1, 20–21★ Mode 4"."""
runs = []
Expand Down
15 changes: 15 additions & 0 deletions src/starforce/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,21 @@ def metadata(slot, item):
}


def star_limit(slot, item, meta=None):
"""The most stars ITEM can reach: its scanned limit and its level's limit, whichever is lower.

Pass META when it is already loaded. None when neither limit is known."""
limits = []
scanned = (item.get("starforce") or {}).get("max_stars")
if type(scanned) is int:
limits.append(scanned)
try:
limits.append((meta or metadata(slot, item))["cap"])
except ValueError:
pass
return min(limits, default=None)


def _stat_and_hp_gain(meta, data, band, current, target):
result = {}
stat = sum(band["stat_per_star"][current + 1 : target + 1])
Expand Down
108 changes: 72 additions & 36 deletions src/starforce/suggestions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def suggestions(slot, item, weights, gear, settings=None):
current, cap = reading.get("stars"), reading.get("max_stars")
if type(current) is not int or type(cap) is not int or not 0 <= current <= cap <= 30:
raise ValueError("Invalid scanned Star Force count; scan again.")
cap = min(cap, meta["cap"])
cap = stats.star_limit(slot, item, meta)
if current >= cap:
raise ValueError("This item is already at its star limit.")
if gear["class"] == "Demon Avenger":
Expand All @@ -31,45 +31,81 @@ def suggestions(slot, item, weights, gear, settings=None):
"Xenon's conversion needs a complete equipped-star total; fewer than 100 stars are confirmed."
)
cfg = cost.options(settings)
target = current + 1
delta = stats.gains(meta, current, target)
gain = sum(weights.get(key, 0) * value for key, value in delta.items())
if gain <= 0:
raise ValueError("No positive modeled FD gain from the next star.")
custom = {**cost.expectations(meta["level"], current, target, cfg), "options": cfg}
modes = cost.item_modes(item.get("starforce_modes"))
wanted = cost.item_target(item.get("starforce_target"))
# A target at or below the current stars does nothing; one above the cap stops at the cap.
end = min(wanted, cap) if wanted is not None and wanted > current else current + 1
clamped = wanted if wanted is not None and wanted > cap else None
strategies = [("custom", "Your modes")] if modes else [("mesos", "Least mesos"), ("booms", "Fewest booms")]
rows, previous, stopped = [], {}, None
for start in range(current, end):
target = start + 1
delta = stats.gains(meta, start, target)
gain = sum(weights.get(key, 0) * value for key, value in delta.items())
if gain <= 0:
if start == current:
raise ValueError("No positive modeled FD gain from the next star.")
stopped = start
break
rows.extend(_step_rows(meta, cfg, modes, strategies, start, target, delta, gain, previous))
steps = len(rows) // len(strategies)
chain_target = current + steps
for row in rows:
row.update(steps=steps, chain_target=chain_target)
if clamped is not None:
row["notes"].append(f"Your {clamped}★ target is above this item's {cap}★ limit; ranked up to {cap}★.")
if stopped is not None:
row["notes"].append(f"Stops at {stopped}★: the next star has no positive modeled FD gain.")
return rows


def _step_rows(meta, cfg, modes, strategies, start, target, delta, gain, previous):
"""One row per strategy for the single star START→TARGET.

PREVIOUS maps each strategy to the prior step's row and is updated in place. A step's
ranking score is capped at its predecessor's, so a later star never outranks an earlier one."""
custom = {**cost.expectations(meta["level"], start, target, cfg), "options": cfg}
rows = []
for strategy, label in strategies:
expected = cost.optimize(
meta["level"], current, target, cfg, objective="booms" if strategy == "booms" else "mesos", modes=modes
)
rows.append(
{
"method": "Star Force",
"kind": "starforce",
"strategy": strategy,
"strategy_label": label,
"current_stars": current,
"target_stars": target,
"stat_gains": delta,
**expected,
"custom_plan": custom,
"expected_fd": gain,
"fd_per_billion": gain / expected["expected_mesos"] * 1e9,
"current": [f"{current} stars · Lv. {meta['level']}"],
"goal": f"Reach {target} stars · {label.lower()}",
"examples": [f"{key}: +{value}" for key, value in delta.items()],
"protected": [],
"notes": [
f"Uses this item's modes: {cost.mode_summary(modes)}, including recovery after destruction."
if modes
else "Optimizes the enhancement mode separately at every star, including recovery after destruction.",
"Expected booms is the average number of destroyed items before reaching the target. Replacement equipment prices are excluded.",
"22★ and above use standard rates; Mode 4 does not prevent destruction there.",
*(["30% meso discount included."] if cfg["discount"] else []),
*(["30% destruction reduction included through 21★."] if cfg["boom_reduction"] else []),
],
}
meta["level"], start, target, cfg, objective="booms" if strategy == "booms" else "mesos", modes=modes
)
raw = gain / expected["expected_mesos"] * 1e9
prior = previous.get(strategy)
row = {
"method": "Star Force",
"kind": "starforce",
"strategy": strategy,
"strategy_label": label,
"current_stars": start,
"target_stars": target,
"step": prior["step"] + 1 if prior else 1,
"stat_gains": delta,
**expected,
"custom_plan": custom,
"expected_fd": gain,
"raw_fd_per_billion": raw,
"fd_per_billion": min(raw, prior["fd_per_billion"]) if prior else raw,
# Held to the previous step's score; the page explains this beside the step.
"capped": bool(prior) and raw > prior["fd_per_billion"],
# Steps tied by the cap sort by their first step's cost, so they stay together and in order.
"rank_mesos": prior["rank_mesos"]
if prior and raw >= prior["fd_per_billion"]
else expected["expected_mesos"],
"current": [f"{start} stars · Lv. {meta['level']}"],
"goal": f"Reach {target} stars · {label.lower()}",
"examples": [f"{key}: +{value}" for key, value in delta.items()],
"protected": [],
"notes": [
f"Uses this item's modes: {cost.mode_summary(modes)}, including recovery after destruction."
if modes
else "Optimizes the enhancement mode separately at every star, including recovery after destruction.",
"Expected booms is the average number of destroyed items before reaching the target. Replacement equipment prices are excluded.",
"22★ and above use standard rates; Mode 4 does not prevent destruction there.",
*(["30% meso discount included."] if cfg["discount"] else []),
*(["30% destruction reduction included through 21★."] if cfg["boom_reduction"] else []),
],
}
previous[strategy] = row
rows.append(row)
return rows
2 changes: 1 addition & 1 deletion src/upgrade_skips.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
KINDS = ("flame", "cube", "starforce")

# Settings the player made on a slot; scans must carry them over to a rescanned or replaced item.
PRESERVED = ("skip_upgrades", "starforce_modes")
PRESERVED = ("skip_upgrades", "starforce_modes", "starforce_target")


def normalize(value):
Expand Down
16 changes: 16 additions & 0 deletions tests/js/number-caps.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const field=(value,{max='20',step=null,type='number'}={})=>({tagName:'INPUT',type,max,value:String(value),get valueAsNumber(){return this.value===''?NaN:Number(this.value);},getAttribute:name=>name==='step'?step:null});
test('whole-number fields snap down to their max while typing',async()=>{
const {capWholeNumber}=await import('../../web/ui.js');
for(const [value,step] of [['25',null],['21','1'],['999','5']]){
const el=field(value,{step});
assert.equal(capWholeNumber(el),true);
assert.equal(el.value,'20');
}
});
test('values within the cap, blanks and non-whole fields are left alone',async()=>{
const {capWholeNumber}=await import('../../web/ui.js');
const cases=[field('20'),field('2'),field(''),field('25',{max:''}),field('80',{max:'75',step:'0.01'}),field('80',{max:'75',step:'any'}),field('25',{type:'text'})];
for(const el of cases){const before=el.value;assert.equal(capWholeNumber(el),false);assert.equal(el.value,before);}
});
44 changes: 44 additions & 0 deletions tests/js/suggestion-filters.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,47 @@ test('all optimized targets retain multiple choices per item',async()=>{
assert.equal(selectSuggestionRows(rows,'all-mesos','cube').length,2);
assert.equal(selectSuggestionRows(rows,'all-booms','starforce')[0].strategy,'booms');
});
const step=(slot,from,stepNo,steps,strategy='mesos',extra={})=>({slot,kind:'starforce',method:'Star Force',strategy,strategy_label:strategy==='mesos'?'Least mesos':'Fewest booms',current_stars:from,target_stars:from+1,step:stepNo,steps,chain_target:19+steps,expected_fd:1,expected_mesos:100*stepNo,expected_rolls:2,expected_booms:0.1,stat_gains:{'Attack Power':stepNo},starforce_plan:[{star:from,mode:1,recovery:false}],notes:['Shared plan note.'],capped:false,fd_per_billion:10-stepNo,raw_fd_per_billion:10-stepNo,...extra});
test('best keeps one row per item, merging the target steps that follow it',async()=>{
const {selectSuggestionRows}=await import('../../web/pages/suggestion-filters.js');
const rows=[step('face',19,1,3),step('face',20,2,3),{slot:'eye',kind:'flame',method:'Black Flame'},step('face',21,3,3),step('face',19,1,3,'booms'),{slot:'face',kind:'cube',method:'Bright'}];
const best=selectSuggestionRows(rows,'best');
assert.deepEqual(best.map(r=>[r.slot,r.kind,r.current_stars,r.target_stars]),[['face','starforce',19,21],['eye','flame',undefined,undefined]]);
const merged=best[0];
assert.equal(merged.expected_mesos,300);
assert.equal(merged.expected_booms,0.2);
assert.deepEqual(merged.stat_gains,{'Attack Power':3});
assert.equal(merged.fd_per_billion,2/300*1e9);
assert.deepEqual(merged.starforce_plan.map(s=>s.star),[19,20]);
assert.ok(merged.notes[0].startsWith('Combines steps 1–2 of 3 toward 22★'));
assert.deepEqual(merged.notes.slice(1),['Shared plan note.']);
});
test('best never places another item between rows of one item',async()=>{
const {selectSuggestionRows}=await import('../../web/pages/suggestion-filters.js');
const flameFirst=selectSuggestionRows([{slot:'face',kind:'flame',method:'Black Flame'},step('face',19,1,3),{slot:'eye',kind:'flame',method:'Black Flame'},step('face',20,2,3)],'best');
assert.deepEqual(flameFirst.map(r=>[r.slot,r.kind]),[['face','flame'],['eye','flame']]);
const skipped=selectSuggestionRows([step('face',19,1,3),{slot:'face',kind:'cube',method:'Bright'},step('face',20,2,3),{slot:'eye',kind:'flame',method:'Black Flame'},step('face',21,3,3)],'best');
assert.deepEqual(skipped.map(r=>[r.slot,r.current_stars,r.target_stars]),[['face',19,21],['eye',undefined,undefined]]);
});
test('steps of different plans or items never merge',async()=>{
const {mergeSequential}=await import('../../web/pages/starforce-steps.js');
const out=mergeSequential([step('face',19,1,3),step('face',20,2,3,'booms'),step('ring1',20,2,3),step('face',21,3,3)]);
assert.equal(out.length,4);
assert.ok(out.every(r=>r.target_stars===r.current_stars+1&&r.notes.some(n=>/^Step \d of 3 toward 22★/.test(n))));
});
test('rows without a target are untouched',async()=>{
const {mergeSequential}=await import('../../web/pages/starforce-steps.js');
const a={slot:'hat',kind:'starforce',strategy:'mesos',current_stars:19,target_stars:20,steps:1};
const b={slot:'hat',kind:'starforce',strategy:'mesos',current_stars:20,target_stars:21,steps:1};
assert.deepEqual(mergeSequential([a,b]),[a,b]);
});
test('capped steps explain their rank once, alone or merged',async()=>{
const {mergeSequential}=await import('../../web/pages/starforce-steps.js');
const capped=note=>note.startsWith('Ranked no higher');
const [alone]=mergeSequential([step('face',20,2,3,'mesos',{capped:true})]);
assert.equal(alone.notes.filter(capped).length,1);
const [merged]=mergeSequential([step('face',20,2,3,'mesos',{capped:true}),step('face',21,3,3,'mesos',{capped:true})]);
assert.equal(merged.notes.filter(capped).length,1);
const [uncappedFirst]=mergeSequential([step('face',19,1,3),step('face',20,2,3,'mesos',{capped:true})]);
assert.equal(uncappedFirst.notes.filter(capped).length,0);
});
2 changes: 1 addition & 1 deletion tests/test_progression.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def test_background_comparison_only_once_per_revision(saved,monkeypatch):

def test_background_reuses_current_result(saved,monkeypatch):
data,gear=saved
data["suggestions"]={"fingerprint":data["history"][0]["fingerprint"],"gear_fingerprint":suggestions.signature(gear),"starforce_options":options(None),"model_version":6}
data["suggestions"]={"fingerprint":data["history"][0]["fingerprint"],"gear_fingerprint":suggestions.signature(gear),"starforce_options":options(None),"model_version":suggestions.MODEL_VERSION}
profiles.write(ID,data)
start=Mock()
monkeypatch.setattr(service,"start_suggestions",start)
Expand Down
Loading
Loading