Three function-entry detours, off unless `aivisit=on`:
* StrategyAIAgent::AssignFleetsAndIssueOrders -- the bracket, recording
(agent, task, pass, walked vector, its slots in index order);
* StrategyAIAgent::ClaimShipsOfFleet -- the head loop, one row per element;
* StrategyAIAgent::ReleaseShipsOfFleet -- the tail loop, one row per element.
The two per-element targets have exactly ONE caller each in the whole image and
that caller is the third target, so the module's traffic cannot come from
anywhere else in the game and no return-address filter is needed. The element
loop's own body is deliberately not patched: its first instruction is a branch
target, which is the shape rule 19 exists for.
Each element row carries the element address (the hypothesis under test), the
fleet's id, its ship ids and its Location pointer. The ship ids are the join key
to the command block's list 10; the join must not be by position because the
walk can visit more elements than it emits commands for.
Reads of game addresses are probed before every access and laundered through a
register, so a wrong offset logs a zero instead of faulting inside a detour.
Also: shim.cfg.bupin, which is shim.cfg.bppin plus exactly three non-comment
lines, and is marked `# exhaustive` so tools/check_shim_configs.py enforces
that every registered hook is named in it.
Adds lane-ac.json's six entries via tools/gen_addresses.py: the trade-sector
node-kind gate, the StarMapNode kind ctor, the raid predicate and the two
per-player trade-sector masks, plus the spy detection-roll branch as a
hypothesis. Header regenerated, never hand-resolved (rule 14).
Also removes FUN_xxxxxxxx identifiers from docs/AC-predictions.md, which
clean_room_check.sh caught.
The loop-carried cl_Chance(0.2f) at 0x006ae575 has measured zero on all six
composer calls of all four runs, and a word count cannot say which of its two
gates did it: a null from the UNRESTRICTED weapon lookup skips the whole
point-defence block, a null from the RESTRICTED one short-circuits every
iteration without drawing. Both print zero -- method rule 20 one level below
the level the sub-bracket was built for.
So the chooser 0x006ad2a0 is detoured and its two return values recorded per
composer call, keyed by the return address that distinguishes the call sites
(0x006ae3c6 restricted, 0x006ae3e1 default), and printed as w_alt / w_def.
NOT YET RUN. Every measurement in findings/subsystems/ship-design-composer.md
was taken with the previous build; this hook is the instrument for the next
lane, not for the numbers already published.
Header regenerated from ghidra/addresses.json plus the fragments, never
hand-resolved.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ARBgSooAfokKUy6wKUKEyZ
Extends lane PAR's airng module with a detour on the composer itself, so a
row says what ONE COMPOSER CALL spent rather than what the turn spent.
Three pieces:
* the detour. The composer's calling convention is neither cdecl nor MSVC
__fastcall -- two register arguments, two stack arguments, and the CALLER
cleans -- so it is entered through a hand-written thunk that re-pushes the
four arguments as cdecl, and the trampoline is re-entered through a second
thunk that restores ECX/EDX.
* the sub-bracket. left (RNG+0x9c8) read off the client generator at composer
entry and exit, and the draws seen in between re-tallied by return address.
Two independent numbers per row, printed together, because PAR's own
instrument double-counted a word and only its second measurement caught it.
* cl_Chance's note is now taken AFTER the trampoline, so a row carries the
DECISION as well as the call. Site 0x006ae413's 0.3 coin selects the
fraction that governs the loop-carried draw's trip count, and a call count
alone cannot say which way it went.
The row also carries the model's prediction beside the measurement: N, the
per-section bank counts and the PointDefence flags are read off the design the
call produced, L is computed from them, and the row says HOLDS, WRONG, or
GATED-OR-WRONG when the prediction is positive and the measurement is zero --
which is the weapon-lookup gate, and is not counted as a confirmation.
Header regenerated from ghidra/addresses.json plus the fragments, never
hand-resolved; the six new lane-sd entries do not change any existing constant
and the module uses none of them by name.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ARBgSooAfokKUy6wKUKEyZ
Generated by sots-re tools/gen_addresses.py from sots-re 975c19a. No source change in
this repo; the entries name the single object-id allocator (IDMap::Initialize and the
per-node counter accessors), the two functions that give a client sim its network node
index, StrategySim::CreateDesign's mint-or-honour branch, and the eight instructions in
MasterTechTree's constructor that make the wire techId a sorted index.
New shim module `ai_rng`: a bracket on StrategyClient::OnResumePlaying over the per-client
generator at +0x134, with two independent measurements per bracket (an observer on the existing
seven draw-site detours, and `left` read straight off the object) plus AI-call-site attribution
through the cl_* facades and an optional seed pin.
Measured on VM140/VM145, six runs, five fresh processes, unpinned autosaves byte-identical to the
published oracle:
turn2->turn3 human 0, AI 32 -> 3 words, AI 496 -> 0, AI 512 -> 0
turn1->turn2 human 0, AI 32 -> 7 words, AI 496 -> 0, AI 512 -> 1 word ... or 3
The last row is the answer: 512 makes ONE cl_RandRange call (the research-target tie-break at
0x006a8495, phase 18) and that one call cost 1 word in one process and 3 in another, because
RNG_NextInt is an unbounded rejection loop. The count is not fixed across clients, across turns,
or across processes with the path held fixed.
Also found: cl_RandFloat 0x00579c70, a third cl_* RNG facade that reaches RNG_NextFloat by a TAIL
JUMP and so leaves no rel32 edge for a call-graph sweep -- which is why ai-turn-logic.md 5's "zero
NextFloat calls from the AI module" reads as true when it is not.
The instrument caught its own defect: RNG_Chance calls RNG_NextFloat and both are detoured, so a
drawn word was reported twice. left_delta was never affected, which is the point of having two
measurements.
Gates run separately on a fresh build directory: clean_room_check OK, host ctest 55/55, CT111 shim
cross-build OK.
The milestone needs a second input. The AI is a client, not part of the sim: it decides once,
on one machine, and its decisions reach the server as commands. A save carries the board and
half the input, which is why our turn wrote ModCount 14 where the original writes 24 -- the
missing ten ARE the turn's command stream.
* `game/ai/apply_order` -- the thirty-step schedule the original drains a batch in: twenty-
seven per-LIST steps (every player's elements of one list before the next list starts) with
three per-PLAYER gate loops spliced in at step 10, 29 and 30. Neither list order nor member
order, and both facts are asserted so a port that sorted cannot pass.
* `game/ai/command_capture` -- a `.tcb` recorded turn: gates, list lengths, elements in wire
order, per-client seeds, and `?` for a field the instrument could not read. An element count
that disagrees with its declaration is REJECTED, because a counter quietly one short is
indistinguishable from a turn that issued one fewer command.
* `app/command_replay` -- applies it before the drivers, where the End-Turn dispatcher does.
Every command is CHARGED; only the ones whose subsystem we hold are APPLIED; the rest are
declined with the named gap, or marked incomplete when the capture itself lacks the payload.
* `--turn-commands`, `--replay-count-only`, `--replay-recorded-names`, `--ai-seed`.
Measured on a fresh build directory, canonical pair turn2-state -> turn3-state:
108 -> 62, closed 46, regressed 0 (was 108 -> 63, closed 45) -- /Sim/ModCount now reads the
original's 24, decomposed as 2 drivers + 4 research-rate gates + build + rates + list 10 +
two list-14 + fleet move, with the list-23 population element free.
turn1-state replayed against the SAME run's autosave closes 7 (ModCount and all six research
leaves); against the historical turn2-state it closes 6 and leaves player 512's research pick
diverging -- which is correct, because that recording is from a process that picked differently.
One prediction was falsified and it paid for itself: the first run regressed two leaves because
the rates element's MEMORY field order is not its wire order. The converter no longer claims a
mapping it cannot support.
Two new addresses (the second and third gate-loop heads) via ghidra/addresses.d/lane-rb.json;
header regenerated, never hand-resolved.
The capture lane needs the block dump L4 built; branching off main without it
would mean writing the same detour twice. Header regenerated from sots-re
(rule 14), not hand-resolved: 1,217 entries.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ARBgSooAfokKUy6wKUKEyZ
New shim module src/shim/hooks/ai_orders.{h,cpp}: one register-transparent entry
stub on StrategySim::ApplyTurnCommandBatch dumps every submitted TurnCommands block
(six gates, 27 list lengths, element bytes) at the point where all of them are
complete in memory; sixteen entry probes, with RunTaskList's stub recording the
pass so every later hit is pass-attributed.
Two workloads on VM145, one End Turn each. The rule-19 control passed with all
seventeen detours installed: both autosaves byte-identical to the published oracle.
What the AI actually emits, and three things no reading had produced:
- a list-23 element on EVERY turn, the first element ever observed in the free
half of the cost table -- and both turns still cost the measured 12;
- the ids in AI commands are client-allocated and travel in the command (design
18, fleet 34; neither exists in the input save);
- pass 0 emits nothing, measured from element counts rather than inferred.
tests/game_ai/test_live_blocks.cpp rebuilds both captured blocks through the public
OrderClient API and asserts the list profile, element values, gate counts and
ModCount total: 44 checks. Kept separate from test_orders.cpp, which stays the
record of what static reading predicted.
Gates: clean_room_check OK, host ctest 55/55, CT111 shim cross-build exit 0.
`ComputeBudget`'s savings-interest term is now compared against the running game at
a treasury the corpus actually contains. Three runs on VM146 from turn1-state.sav:
A (widened floats, as shipped) 3,895 calls, 0 diverged, 0 undeclared writes
B (exact decimals, the control) 2,718 calls, 1,359 diverged
The game fills savingsInterest with 499 at a treasury of 50,000, and with 380 at
38,100 -- the exact decimals pay 500 and 381. Every divergence in B lands on a
treasury that is a multiple of 100 and no other state diverges at all, which is
exactly the arithmetic. G3's rule-23 reading is now measured, not inferred, and the
one-money error is shown to propagate into `available` and `researchMoney` too.
The control also settles why the earlier 4,437-call green run was green: slot 5 IS
diffed and the harness CAN see it, so that run simply presented no boundary state.
Coverage is therefore reported as distinct states, not calls: 5 distinct treasuries,
2 of them on the boundary.
Two further rule-23 constants found in the same routine by an operand-width sweep,
corrected, and honestly marked UNVERIFIED because no reference turn can see them:
- the research-yield factor is a widened 0.85f while its two neighbours in the
same product are exact doubles. Boundary: research money a multiple of 40,000;
the run presented 9 distinct values and none is.
- the three research modifiers are summed in single precision, not double.
Boundary: two of the three non-zero; the corpus has shrm = TRM = 0.
Both are pinned by boundary cases in test_economy.cpp that fail with the decimals.
Also verified live, in the same run:
- T31's difficulty-column recovery. The live ServerPlayer+0xf9 / NPC flags on all
eight players are exactly what lane PL's save-only inversion claims, including
the awkward system-owning player that is still ambiguous because it is an NPC.
- BANKRUPTCY_PROTECTION_LIMIT_FACTOR reads 3.29999995 = (float)3.3. Its file image
is zero because the loader fills it at run time, so lane PL-3 had to assume the
value; it is now measured and the assumption was right.
Falsified, and recorded as such: the difficulty-mods record does NOT sit inline at
ServerPlayer+0x36c -- that field is a heap pointer on all eight players. The row IS
reachable from a ServerPlayer (which corrects the hook's standing coverage note),
but the fitted {3.0,1.5}/{1.0,1.0} pair remains unverified. The hook logs the
pointer and does not follow it.
The `verified` column stays 0, deliberately. Every phase this compare touches is
Partial for reasons upstream of it, and promoting one because part of it was checked
is the drift app_test_catalog exists to catch. What moved is models; see
docs/L5-live-verification.md for each one with its coverage.
Gates run separately: clean-room OK, host ctest 54/54, CT111 shim cross-build exit 0.
Lane SV recovered the script-object subsystem statically and predicted that
SVSOSwarmQueen::RegisterHives takes one RNG_NextInt per new hive inside
StrategyServer::BeginProcessTurn -- which runs inside lane Z's autosave bracket
and outside every one of its subtotals, so a draw there had never been
attributed by anything.
Five nested trace hooks, each declaring the strategic generator as a region and
each carrying a model evaluated at entry so the record can disagree with it:
StrategyServer::BeginProcessTurn the unhooked interval, plus a region
over Frame so the increment is a fact
SVSOSwarmQueen::OnTurnBegin evt 0x13, vtable slot +0x60
SVSOSwarmQueen::RegisterHives predict_new_hives from the original's
own two predicates; reads the LO/HI
config pointers live
SVSOSwarmQueen::TickHives the NextQ slip and its three gates
SVSOSlaversRefuel::UpdateDifficultyTier tail phase 20; a 4-byte region over
CDiff so a store and its ABSENCE are
distinguishable (method rule 20)
Also watch.mode=snlv: one arming line moves slot 1 from the NVO map's _Mysize to
the target system's SnLv, and the arming sweep now prints SnLv with its decoded
per-player 2-bit levels for every system, which costs no debug register.
Measured on VM140: hive creation costs 2 words in BeginProcessTurn and the
residual outside the two turn drivers is 2, not 0; the next turn it is 0 again.
LO=20 HI=30. Spica's SnLv reads 0x200 with AFlags 0. The oracle reproduced
byte for byte with every one of these detours live.
Predictions and outcomes: docs/L1-predictions.md.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ARBgSooAfokKUy6wKUKEyZ
Reads the whole colony output chain off the instruction stream (every range
disassembled to the next function start) and compares two of its functions
against the running game.
The population -> output law is linear and is carried by the executable:
output points per head are typeOutputModifier x 1.8 / 500000, and the
three-row population-type table is built in code rather than loaded, so the
imperial (1.0) and civilian (0.33f) modifiers are facts about the binary.
A system's total output is a SUM of three terms, not one multiplicative
chain. The station bonus scales only the imperial term and morale only the
civilian one, so OutputModifiers no longer carries either; they belong to
GroupOutputInputs. The function previously described as the base-output term
is the over-harvest RESOURCE demand, and it is corrected in place.
Live on VM140, both hooks in compare mode over two species and two workloads:
GroupOutput 13,105 calls / 0 divergences; ComputeTotalOutput 11,252 calls /
1 divergence of one ulp, in a value its caller rounds to an integer. Both
functions declare a whole-object Guard: 0 undeclared writes in 24,357 calls,
which is what makes the side-effect-free claim a measurement.
sim::Narrow forces the double rounding a 32-bit x87 build otherwise skips;
without it every civilian row came out one ulp low.
Also fixes ComputeBankruptcyLimits' elimination divisor, which was the
decimal -0.15 rather than the image's widened float -0.15000000596046448.
The two disagree for every maximum income divisible by 3 and for essentially
every empire above ~3,000,000.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ARBgSooAfokKUy6wKUKEyZ
The boundary ledger says which phase spends a turn's words; this says which
call site. Each entry point is detoured with its verified prototype and records
__builtin_return_address(0) plus the word cost from left before/after -- two
4-byte reads, no record per draw, since NextFloat alone has 109 call sites.
Each draw is tagged with WHICH generator it came from. That is not a detail:
the first build counted every Mars::RNG instance in the process and reported 44
words against a bracket of 18. The StrategyClient's generator at +0x134 draws 8
times a turn and must not be in the strategic total.
Also hooks EncounterDetect::AssignContacts, lane I's one inlined-draw site in
ProcessTurn's closure -- invisible to both a call-graph sweep and to the entry-
point detours, so only a boundary hook can see it. It did not fire on this
workload, which is consistent with the site sums reconciling exactly.
The turn's RNG cost has never been measured end to end. combat-done-tail.md
found two draw sites in OnAllCombatDone_Tail that nothing models and that both
run before the autosave, so a reimplementation that reproduces both ProcessTurn
functions exactly still diverges the first turn a node line expires.
RngLedger recovers an ABSOLUTE WORD POSITION from (mt[624], left) alone, by
indexing the forward-only chain of blocks the twist generates. Word deltas
between any two observations are then exact -- across twists, across NextInt
rejection loops, and across draws nobody hooked. That last point is not
theoretical: the image has four draw entry points, one of which (NextUInt
0x004f7670) appears in no previous lane's primitive set, plus inlined draws in
twelve functions. A primitive-counting hook would have undercounted silently.
Six nested trace hooks bracket one End Turn between the two autosaves and
attribute the words: the two turn drivers, the two tail phases that can draw,
and ProcessNodeSpaceTravel because it runs twice a turn. NodeLineDecay carries
a real model -- one word per expired node line under NodePath::RemainingLife --
so compare mode checks the count rather than reporting it.
Corrections from the instruction stream, both load-bearing:
* StrategyHost::Autosave is ret 8, not ret 4, and returns the std::string* in
EAX. A void-returning hook would have dropped it at both call sites.
* node-line decay's 0x20000-fleet skip runs AFTER the Chance(0.5f) call, not
before, so it cannot change the draw count -- combat-done-tail.md reads as
if it gated the roll.
fpu.sample_turn releases StrategyServer::ProcessTurn, which the fpu sampler and
this ledger both want and MinHook grants to one of them. Default on: no
existing run changes behaviour.
Host ctest 37/37; shim cross-built on CT111; clean-room check OK.
Every Coverage note in this repo said RollResearchEvent draws "exactly one
NextFloat". That is the cost of REACHING its branch. When the roll beats the
odds, the plague path draws a SECOND word (NextInt) to pick an owned system and
posts EVENT_PLAGUE_OUTBREAK, and the rebellion path allocates an AIRebellion at
ServerPlayer+0x3b8 and cancels the current research. Nothing has caught this
because the branch has not fired in three sessions.
Corrected in research.h (two Coverage entries plus the scope comment, and the
branch entry raised to Risk::High), research.cpp, tech_effects.h and
tech_effects.cpp. Ours still models the first word only; the branch stays
declared unmodelled, now accurately.
Header regenerated from sots-re bb0f990 (750 entries) - lane K's map of the
combat-done tail: the autosave and save-file writer, the bankruptcy limits, the
turn-results accumulator and outbox, and the encounter-block callees.
Descriptor + pure adapter + host tests for the per-player turn driver. Not
deployed; the WIN32 half is unbuilt here (no cross-compiler on this host).
The declared boundary is narrower than the function on purpose. Phases 2, 3
and 6 -- the savings apply, the aid records and the research refund -- are pure
functions of ComputeBudget's 22 slots and ProcessResearch's overBudget, and
both live in the original's own stack frame. Reaching them would mean calling
ComputeBudget ourselves (it repairs ships in orbit, audit #6), reading the
nested B1/B3 hooks (audit #5, the self-fulfilling compare), or inferring them
from the Sav delta. So they are guarded, not checked, and the three formulas
are written and unit-tested but not wired into the verdict.
Declared: the phase-7 clear, the RebAI decay, the descending timed-bonus
sweep, plus roll_flags and rng as observations ours never writes. Guards over
the whole ServerPlayer and the TechTree header.
docs/T-turn-driver.md states, before any run: which regions must not diverge,
which checks are weak by construction on the reference save, what falsifies
the ResearchRollPending reading, and the save that would finally fire the
branch nobody has seen.
host ctest 36/36 (was 35/35); clean_room_check OK.
First End Turn 3/3/0, five-turn continuation 15/15/0, Zuul 20/20/0, tracecmp
exit 0 on all three. The End-Turn oracle hashes are unchanged, so the cascade
does not perturb the game.
All 22 divergent fields lane V recorded are gone. The prediction in section 4
held field for field on the deterministic half; call 9 turned out to be a
different completion from lane V's (the AI picked another target from turn 5),
which the model reproduced anyway - three unlock costs that appear in no earlier
report.
Honest limit: roll_draws was 0 on all 35 calls. ResearchRollPending is normally
consumed by ProcessTurn before ProcessResearch runs, so the RollResearchEvent
draw is modelled and inside the compare but has never been seen to fire.
Pure module game/sim/techgraph: PrereqsMet (AND of ORs, empty group fails),
SetResearched (stamps, child-cost sweep, sticky turnAvailable, zero-cost
recursion) and the newly-available collector, all read out of 0x00581e10,
0x0057d8e0 and 0x00587cc3.
Wired into the B3 hook in compare mode only, over the scratch node copies:
four more node write-backs, the EVENT_TECHS_UNLOCKED list (still an input,
still nullptr when it could not be computed), the de-duplicating observed-tech
append and the one RNG word RollResearchEvent draws.
docs/U-unlock.md section 4 is the prediction, written before the build was staged.