Repository navigation
ltm: discovery-mode correctness fixes from deep review - #705
Conversation
ReviewNo qualifying findings. I traced the four behavior-changing arms end-to-end:
The new regression tests drive the production paths ( Overall correctness verdict: correct. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cd78e58603
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let instances: HashSet<&Ident<Canonical>> = causal_graph | ||
| .variables() | ||
| .iter() | ||
| .filter_map(|(name, var)| match var { | ||
| Variable::Module { model_name, .. } if model_name.as_str() == sub_model_name => { | ||
| Some(name) | ||
| } | ||
| _ => None, | ||
| }) | ||
| .collect(); |
There was a problem hiding this comment.
Use project-wide output-port set for module pathways
When the same sub-model is instantiated in another model that reads an additional output port, this parent-only scan no longer matches the emission path: db::ltm::find_model_output_ports builds the sub-model's $⁚ltm⁚path⁚{entry}⁚{idx} ordering from reads across all project models. If that other port sorts before the port used by the current loop, recompute_module_input_edge_series will look up the wrong pathway index and can reintroduce the wrong-signed module edge the override is meant to fix. Please derive this set from the same project-wide source/order as emission, or carry the emitted ordering into discovery.
Useful? React with 👍 / 👎.
The discovery-mode per-exit-port pathway recompute (GH #698) reconstructed a sub-model's output-port set by scanning only the analyzed model's variables. Emission (db::ltm::find_model_output_ports) derives it from reads across ALL project models, and the sub-model emits its $.ltm.path.{port}.{idx} vars against that project-wide sorted set. So when the same sub-model is also instantiated in another project model (or nested in another sub-model) that reads an additional output port sorting BEFORE the port the loop traverses, every pathway index shifts and the recompute read the wrong pathway var -- re-introducing the wrong-signed module edge the GH #698 fix was meant to eliminate. Fix by identity-by-construction: discover_loops_with_graph now takes a SubModelOutputPorts map (sub-model canonical name -> emitted sorted port set). analyze_model builds it via the new public build_sub_model_output_ports, which calls the SAME db::ltm::sub_model_output_ports decision emission uses (one per project model, including the stdlib output-convention short-circuit), so the recompute enumerates pathway indices against the identical set the sub-model emitted against regardless of which project model the loop lives in. The db-less discover_loops(&Results, &Project) convenience path (tests only) reconstructs the same project-wide-union + stdlib-output semantics in project_sub_model_output_ports rather than scanning the analyzed model alone. The shared ltm_discovery_inputs test harness threads the map (and now uses the module-enriched element graph) so the wasm/VM parity and large-model harnesses mirror production exactly. This replaces the parent-scoped discovery_sub_model_output_ports (removed). causal_graph_from_element_edges_with_modules is now pub so the harness mirrors the production graph. Reference: #705 (comment) GH #698
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d78e05e305
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let entry_port = inputs.iter().find_map(|inp| { | ||
| if normalize_module_ref(&inp.src) == link.from { | ||
| Some(inp.dst.clone()) | ||
| } else { | ||
| None | ||
| } | ||
| })?; |
There was a problem hiding this comment.
Avoid choosing an arbitrary module input port
When the same upstream variable feeds more than one input port on a module, this find_map silently picks the first matching input and recomputes the loop edge from that port's pathway series. Because the collapsed causal edge is only x -> m, a model with x wired to both m.a and m.b can select the wrong pathway (or miss the active one) and report the wrong loop score/polarity; this should treat multiple matching inputs as ambiguous and fall back to the composite score, like the exit-port helper does for multi-output readers.
Useful? React with 👍 / 👎.
A multi-agent deep review of the LTM implementation against the four papers empirically validated the scoring core (paper Tables 1-3, chain rule and aggregation invariance, isolated-loop +/-1, Bass inflection crossing all reproduce exactly), but found three places where our documentation overstates or omits behavior: - The discovery-mode zero-edge-exclusion comments claimed per-step exclusion "loses no loop that ever matters". That is only true for loops simultaneously active at a sampled step: a baton-passing loop whose links are active at disjoint times is invisible to discovery at every step (GH #699, demonstrated by the decoupled_stocks fixture). Two test comments also still attributed discovery behavior to the removed best_score pruning, one misattributing the actual root cause. - The design doc's Discovery Mode step 4 claimed discovered loops flow through build_element_level_loops; discovery has its own path and never runs recover_cross_agg_loops, so cross-element reducer loops are silently dropped (GH #696). The multi-output module asymmetry is also elevated from "approximation" to what it empirically is: a possible polarity inversion (GH #698). - Design-doc divergence 6 documented the 1-DT flow-to-stock numerator shift but not the time_step factor, which is load-bearing (without it every flow-to-stock score is 1/dt too large, compounding per stock in a loop); the papers hide this by using dt=1 in every worked example.
Git hooks live in the repository's common git dir, shared by every linked worktree, but dev-init.sh computed the symlink target from the current checkout's REPO_ROOT. Running dev-init inside a temporary worktree (which Claude Code agent worktrees do as a matter of course) therefore re-pointed the shared hook at the worktree's copy of scripts/pre-commit; once the worktree was removed the symlink dangled and git silently skipped pre-commit for every subsequent commit in the main checkout. This bit a real session: a commit on main bypassed fmt/clippy/tests with no warning. Resolve the target against the common dir's parent (the main checkout) instead, and guard on the target existing so a bare or unusual layout degrades to a no-op rather than installing a broken link. Verified by running dev-init from a throwaway linked worktree: the shared hook now stays pointed at the main checkout and survives worktree removal. Closes #700.
In discovery mode a feedback loop traversing a multi-output module could get the WRONG polarity (inverted sign) relative to exhaustive mode. The input->module link score there was the module composite, which max-abs- selects across ALL output-port pathways; single-dependency pathways all normalize to magnitude exactly 1, so the composite's tie-break picked an arbitrary (first-enumerated) port -- possibly one whose sign opposes the pathway the loop actually reads, flipping the loop's reported polarity. Exhaustive mode already fixes this with a per-exit-port pathway-selection override on the loop-score equation (PR #684). Discovery emits no loop-score equations, so it had nothing to override. This applies the same selection during the post-simulation score recompute (path -> FoundLoop): for a loop edge x->m whose next edge m->y identifies the exit port, the edge's score series is recomputed by max-abs-selecting over the sub-model's per-pathway scores (m.$.ltm.path.{entry}.{idx}) that end at that port, instead of reading the composite. Pathway indices are recovered from the module's sub-graph via the same enumerate_pathways_to_outputs machinery and the same sorted output-port set the sub-model emitted against (including the stdlib output-convention short-circuit), so they match the emitted pathway vars index-for-index -- the same parity guarantee exhaustive relies on. The DFS still uses the composite for edge ordering and zero-exclusion, so no loop is lost; the recompute falls back to the composite for single-output / pathless / indeterminate-port edges, so SMOOTH/DELAY and pathless modules are unaffected. The recompute needs module sub-graphs + the variable map on the discovery CausalGraph. The PRODUCTION discovery path (analyze_model) builds that graph from element-level edges via causal_graph_from_element_edges, which hardcodes both empty -- so the recompute silently never fired there. analyze_model now uses causal_graph_from_element_edges_with_modules, which enriches the element-level graph with the shared model_variables_and_module_graphs pair. That builder (and CausalGraph::from_model, the discover_loops convenience path) builds a sub-graph for EVERY referenced sub-model, not only stockful DynamicModules: a stockless passthrough emits pathway vars (PR #684) but otherwise has no sub-graph to consult. The now-redundant classify_module_for_ltm stock gate (and its ModuleLtmRole enum) is removed. reconstruct_model_variables reconstructs a module instance through reconstruct_implicit_variable so its ModuleInputs survive (the generic parse+lower path drops them against an empty scope.models), letting the recompute read a module's entry/exit ports -- the same fix reconstruct_single_variable already applied for the exhaustive override. Design choice: a post-discovery recompute (approach (a)) rather than emitting per-exit-port via-alias link-score vars in discovery mode (approach (b)). The recompute is self-contained in ltm_finding.rs, needs no new synthetic vars, and reuses the existing max_abs_score_series helper; the parity-critical pathway-index derivation reuses CausalGraph::enumerate_pathways_to_outputs. Regression coverage: cross-mode polarity agreement in tests/simulate_ltm.rs (discover_loops convenience path) plus two analyze_model end-to-end tests (production path) for the aux-reader and module->module exit-port arms. GH #698
Discovery mode silently dropped every cross-element feedback loop that
traverses a hoisted reducer's synthetic $:ltm:agg:{n} node more than once
(pop[a] -> agg -> pop[b] -> agg -> pop[a]). Such a loop is non-elementary
in the element graph, and the strongest-path DFS's `visiting` set forbids
revisiting any node -- including the agg -- so the search could never
construct it. Exhaustive mode reconstructs these by stitching the single-agg
"petals" together via recover_cross_agg_loops; discovery never ran any
recovery. The bite was worst exactly where it matters: a reducer-in-feedback
model over a large dimension trips MAX_LTM_SCC_NODES, auto-flips to discovery,
and loses precisely the loops that matter there, with no signal.
Fix with approach (a) from GH #696: post-discovery petal stitching that
reuses the SAME combinatorial core exhaustive uses, rather than relaxing the
DFS's elementary-cycle invariant. The petal priority / pairwise-disjoint-
internal-node rule / MAX_AGG_PETALS / cyclic_orderings enumeration / loop-count
budget are extracted from recover_cross_agg_loops into a mode-agnostic
stitch_cross_agg_petals (generic over the node representation: &str circuit
nodes for exhaustive, owned Ident for discovery) plus a shared collect_agg_petals
extractor. recover_cross_agg_loops now calls them, so its behavior is unchanged
(the four-petal cyclic-orderings test still passes bit-for-bit). Discovery
treats each discovered single-agg path as a petal, stitches the disjoint subsets,
appends the stitched element-level sequences back into all_paths (deduped by
canonical rotation), and lets them flow through the identical FoundLoop
construction / score-product / trim / dedup / rank pipeline -- so a stitched
loop is scored exactly as any discovered loop (its edge multiset is the union
of its petals' disjoint edges, hence the per-step product of the petals' link
scores). This is the principled choice: it keeps the DFS's invariants intact,
mirrors the exhaustive design exactly, and guarantees discovery recovers the
same loop set exhaustive does (cross-validated by value, not just count).
Recovery is post-simulation, so there is no salsa diagnostic accumulator to
emit the truncation Warning exhaustive uses; DiscoveryResult gains an
agg_recovery_truncated flag (the analogue of LtmVariablesResult's), threaded
through analysis::ModelAnalysis.
The multi-agg subtlety is handled identically to exhaustive: a petal is a
circuit touching exactly one agg once, so a discovered path through two
distinct aggs is already a complete loop, not a petal.
GH #696.
The test helper claimed to use "the same wiring analyze_model uses", but it builds its graph with the bare causal_graph_from_element_edges constructor while production analyze_model uses the _with_modules enriching variant. The distinction is exactly the kind that masked the GH #698 production no-op, so the docstring should not invite a future reader to rely on it; the production wiring is covered end-to-end by the cross-validation test in tests/simulate_ltm.rs.
model_detected_loops is a pre-simulation salsa query, so it can only report a loop's structural polarity. Pervasively for module-heavy models the static polarity of a variable->module / module->variable black-box link is Unknown, so a loop through a module boundary is labelled Undetermined even when its simulated loop score is single-signed at every active step (GH #679). Reclassifying from runtime scores is therefore a post-simulation concern. This adds db::analysis::reclassify_loops_from_results, the canonical in-engine primitive: it reads each loop's $:ltm:loop_score:{id} slot(s) from a Results and applies LoopPolarity::from_runtime_scores to overwrite the polarity and polarity_confidence, keeping the loop id stable (the FFI id->score correspondence and salsa caching depend on a loop detected as u1 keeping the id u1 even when its runtime polarity is Reinforcing). A loop whose score is never active keeps its structural polarity. Scope is deliberately narrow and the framing is honest about what does NOT change behavior: - The helper has NO production caller yet. The libsimlin/WASM/TS simlin_analyze_get_loops surface takes only a SimlinModel (no Results in hand), is intentionally structural-only, and folds Mostly* to R/B and drops confidence at the C ABI boundary. Surfacing runtime polarity there is the FFI work tracked under GH #495; this change does NOT unblock that on the exhaustive path (the coalescing/confidence-drop happens regardless of how the polarity was computed). The helper exists so a future sim-bearing Rust consumer has one correct place to call. - pysimlin Run.loops already reclassified via its own Python from_runtime_scores mirror; that behavior predates this commit. A regression test now pins the exhaustive module-boundary case there. - The engine analyze_model / MCP surface is discovery-based and already reclassifies through the FoundLoop path. The three reclassification sites use DIFFERENT A2A input constructions (the Rust helper concatenates all element slots; pysimlin reads slot 0; discovery uses one strongest-path scalar per FoundLoop), so the docs and docstrings deliberately do not claim they "match exactly" -- they agree on scalar loops and the shared from_runtime_scores semantics, and diverge only in how an A2A loop's element slots are reduced. The structural-vs-runtime polarity match-blocks in model_detected_loops are factored through a shared detected_polarity_from_ltm mapper. C-LEARN runs in discovery mode, so the change has nil impact there. GH #679
The discovery-mode per-exit-port pathway recompute (GH #698) reconstructed a sub-model's output-port set by scanning only the analyzed model's variables. Emission (db::ltm::find_model_output_ports) derives it from reads across ALL project models, and the sub-model emits its $.ltm.path.{port}.{idx} vars against that project-wide sorted set. So when the same sub-model is also instantiated in another project model (or nested in another sub-model) that reads an additional output port sorting BEFORE the port the loop traverses, every pathway index shifts and the recompute read the wrong pathway var -- re-introducing the wrong-signed module edge the GH #698 fix was meant to eliminate. Fix by identity-by-construction: discover_loops_with_graph now takes a SubModelOutputPorts map (sub-model canonical name -> emitted sorted port set). analyze_model builds it via the new public build_sub_model_output_ports, which calls the SAME db::ltm::sub_model_output_ports decision emission uses (one per project model, including the stdlib output-convention short-circuit), so the recompute enumerates pathway indices against the identical set the sub-model emitted against regardless of which project model the loop lives in. The db-less discover_loops(&Results, &Project) convenience path (tests only) reconstructs the same project-wide-union + stdlib-output semantics in project_sub_model_output_ports rather than scanning the analyzed model alone. The shared ltm_discovery_inputs test harness threads the map (and now uses the module-enriched element graph) so the wasm/VM parity and large-model harnesses mirror production exactly. This replaces the parent-scoped discovery_sub_model_output_ports (removed). causal_graph_from_element_edges_with_modules is now pub so the harness mirrors the production graph. Reference: #705 (comment) GH #698
When one parent variable x is wired to MORE THAN ONE input port of module m (x -> m.a AND x -> m.b), the causal edges collapse to a single x -> m edge, so the per-exit-port pathway recompute (GH #698) had no unambiguous entry port. Both the discovery recompute (recompute_module_input_edge_series) and the exhaustive twin (compute_module_link_overrides) resolved the entry port with a find_map that silently picked the FIRST matching ModuleInput, then recomputed the loop edge from that port's pathway -- which can be the wrong port (or miss the active one), reporting a wrong-signed loop score/polarity. Treat multiple matching ModuleInputs as ambiguous and decline (return None/continue), leaving the base composite link score (the documented pre-existing first-matched-port approximation) in place -- exactly mirroring the multi-match -> ambiguous semantics the exit-port helpers (discovery_module_exit_port / module_exit_port_for_reader) already use. Both sides had the identical bug, so both are fixed for parity. The regression fixture wires a stock to two input ports of a sub-model whose loop-exit output (late = 0 - a) has the opposite sign of the base composite's tie-broken pathway (early = a, +1); before the fix the first-match recompute flipped the loop to balancing, now it follows the base composite (reinforcing) in both modes. Reference: #705 (comment) GH #698
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4d20dec63b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| Variable::Module { inputs: y_in, .. } => y_in.iter().find_map(|inp| { | ||
| if normalize_module_ref(&inp.src) == *module_name { | ||
| inp.src | ||
| .as_str() | ||
| .split_once('\u{00B7}') | ||
| .map(|(_, port)| Ident::new(port)) |
There was a problem hiding this comment.
Treat ambiguous module-to-module exits as fallback
When the next reader y is also a module and has multiple inputs sourced from the same module instance (for example m.pos -> y.a and m.neg -> y.b), the collapsed loop edge is just m -> y, so it does not identify a unique exit port. This new discovery recompute currently takes the first matching input via find_map, which can select the wrong output pathway and flip or zero the recomputed x -> m score; it should mirror discovery_module_exit_port and return None on multiple matches so the base composite is left in place.
Useful? React with 👍 / 👎.
ReviewI reviewed the PR's code-changing files ( Findings: none I'd ask the author to fix. Notes on what I checked:
Overall correctnessCorrect. |
The per-exit-port pathway recompute (GH #698) reads the loop's exit port off the next link m -> y. The module-to-module exit arm -- where y is itself a module fed by m's output -- resolved that port with a find_map that silently picked the FIRST of y's inputs sourced from m. When y reads MORE THAN ONE distinct output port of m (m.early -> y.p AND m.late -> y.q), the collapsed m -> y edge has no unique exit port, so first-match could select the wrong output pathway and recompute the x -> m edge against it, flipping or zeroing the loop's score/polarity. This is the third symmetric instance of the multi-match family (after the entry port and the project-wide output set). Count distinct matching ports and decline (None -> base composite fallback) when two DISTINCT ports match, mirroring the multi-match -> ambiguous semantics the non-module exit helper (module_exit_port_for_reader / discovery_module_exit_port) and the entry-port resolution already use. Two of y's inputs naming the SAME m.port are NOT ambiguous (a unique distinct port). Both the discovery recompute (recompute_module_input_edge_series) and the exhaustive twin (compute_module_link_overrides) had the identical bug, so both are fixed for parity. The regression fixture wires a consumer module to two opposite-signed output ports of an upstream producer module inside a feedback loop, ordered so first-match would pick the (-) port; before the fix the recompute flipped the loop to balancing, now it follows the base composite (reinforcing) in both modes. Reference: #705 (comment) GH #698
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0672537aae
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let mut matching = inputs | ||
| .iter() | ||
| .filter(|inp| normalize_module_ref(&inp.src) == link.from); |
There was a problem hiding this comment.
Normalize element names before matching module ports
When discovery runs on an element-level graph, an arrayed source edge is named like s[NYC] -> m, while the module input wiring still stores the base source s; this exact comparison therefore makes recompute_module_input_edge_series return None for arrayed loops through a multi-output module. In that case discovery falls back to the module composite score across all outputs, so the same wrong-exit-port polarity bug this override is meant to fix still occurs for loops such as s[e] -> m -> growth[e] -> s[e]. The exhaustive override strips subscripts before this match, and the discovery path needs the same normalization for element-level names.
Useful? React with 👍 / 👎.
|
Code Review [P2] Discovery's per-exit-port recompute does not strip element subscripts, unlike the exhaustive twin File: src/simlin-engine/src/ltm_finding.rs (lines 2100-2122)
Overall correctness verdict: correct (with the above caveat) The patch is internally consistent and the core fixes (per-exit-port recompute, cross-agg petal-stitching extraction, project-wide port-set threading, ambiguous entry/exit fallback, dev-init hook resolution) look right and are well-covered by regression tests against the exhaustive sibling. The arrayed-source/reader-through-module asymmetry above is the only meaningful correctness gap I see, and it does not regress against the pre-PR baseline (discovery's pre-PR behavior was the composite fallback on every module edge), so it is a missed optimization rather than a new bug. The rest of the changes -- documentation, test coverage, the new |
Discovery runs on the element-level graph, so an arrayed loop's non-module nodes carry element subscripts (s[nyc] -> m -> growth[nyc]). recompute_module_input_edge_series matched the entry port with an exact `normalize_module_ref(inp.src) == link.from` and looked the exit reader up in the bare-keyed variables() map -- both fail on the subscripted forms, so the recompute declined for EVERY arrayed module loop and the wrong-exit-port composite bug the override exists to fix re-occurred. Strip the subscript via the canonical crate::ltm::strip_subscript on link.from (entry match), link.to/next.from (module node + sequentiality guard), and next.to (exit reader lookup) before each name comparison, preserving the prior ambiguity semantics (two distinct ports -> decline; same port twice -> unique). This mirrors the exhaustive twin compute_module_link_overrides, which already strips link.from/link.to/next.from/next.to (db/ltm/mod.rs). The end-to-end arrayed manifestation is currently masked by an upstream gap: a scalar module output feeding an arrayed reader (growth[Region] = m.pos) emits a single scalar constant-0 link score rather than per-element m->growth[e] scores, so the loop product is 0 and discovery drops the loop before the recompute runs. That gap is tracked separately as GH #716. This change is therefore latent defense that restores name-handling parity with the exhaustive override; it is covered by a unit-level red-green test (recompute_strips_element_subscripts_before_port_match) that drives the matching code directly with a real compiled module project's graph/results and a hand-built subscripted links chain (fails returning None before, passes returning the pos-pathway series after), plus a documentation test (analyze_model_arrayed_module_loop_blocked_by_scalar_output_gap) pinning the current masked end-to-end state so closing #716 is a deliberate change. The `ltm_finding.rs` test module moved to a sibling `ltm_finding_tests.rs` (mounted via `#[cfg(test)] #[path]`) to keep the production file under the per-file line cap. Reference: #705 (comment) GH #698
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Review SummaryI reviewed this PR carefully against its three discovery-mode correctness claims (per-exit-port recompute, cross-agg loop recovery, runtime polarity reclassification) plus the dev-init hook fix. The implementation is careful, the comments are thorough, and the regression tests are strong (including the discriminating power checks). I did not identify any blocking correctness bugs introduced by this change. A few minor observations below for the author's awareness, but none rise to the level of needing a fix. Observations (non-blocking)
Overall correctness verdictCorrect — the change is implemented as documented; existing tests pass; the new regression tests are well-discriminated against stub-reverts of each fix; the dev-init hook fix correctly resolves through |
A multi-agent deep review of the LTM implementation against the four papers empirically validated the scoring core (paper Tables 1-3, chain-rule and aggregation invariance, isolated-loop +/-1, Bass inflection crossing all reproduce exactly) and found the residual risk concentrated in discovery mode. This PR lands the documentation honesty fixes plus three discovery-mode fixes, each implemented TDD-first and passed through an independent adversarial review loop (two of the three needed a fix round after review caught real gaps).
Commits
ltm: document discovery completeness gaps and dt scaling -- softens the overstated "loses nothing" zero-edge-exclusion claims (the baton-passing limitation, GH ltm-finding: discovery zero-edge-exclusion 'loses no loop' claim is overstated; baton-passing loops are invisible #699), corrects stale best_score comments that misattributed the decoupled-stocks miss, fixes the design doc's false claim that discovery flows through build_element_level_loops, and documents the load-bearing
time_stepfactor under divergence 6.build: resolve pre-commit hook target against the main checkout -- dev-init.sh in a linked worktree re-pointed the shared
.git/hooks/pre-commitsymlink at the worktree's copy, leaving it dangling (and git silently skipping the hook) once the worktree was removed. GH build: dev-init.sh in a git worktree re-points the SHARED pre-commit hook at the worktree, silently disabling the hook on main when the worktree is removed #700.ltm: fix discovery-mode wrong loop polarity through multi-output modules (GH ltm: discovery mode can report the wrong loop polarity (sign error) through a multi-output module #698) -- discovery's input->module link score was the composite, whose max-abs tie-break picks an arbitrary output port (single-dependency pathways all normalize to magnitude 1), empirically inverting loop polarity (+1 exhaustive vs -1 discovery). Discovery now applies the same per-exit-port pathway selection exhaustive mode's PR engine: LTM review hardening and module link-score correctness (#675) #684 override applies, during the post-discovery score recompute; wired into the production analyze_model path via causal_graph_from_element_edges_with_modules (review round 1 caught the first attempt being a production no-op). Regression tests drive analyze_model end-to-end for both the aux-reader and module->module exit-port arms.
ltm: recover cross-agg reducer loops in discovery mode (GH ltm-finding: discovery mode silently drops ALL cross-element (cross-agg) reducer loops #696) -- the discovery DFS forbids node revisits, so cross-element loops through a hoisted reducer's
$:ltm:aggnode (non-elementary) were structurally unreachable and silently dropped; worst exactly when a reducer-in-feedback model auto-flips to discovery. Discovery now stitches discovered single-agg petals using the same combinatorial core exhaustive mode uses (extracted into stitch_cross_agg_petals / collect_agg_petals, shared by both paths). On the 3-element repro discovery now returns the same 7 loops as exhaustive with score series matching by value; C-LEARN loop count and discovery runtime unchanged. Truncation surfaces as DiscoveryResult::agg_recovery_truncated (FFI surfacing tracked as GH ltm: discovery results do not say when cross-SUM loop finding was cut off #701).ltm: correct discover_reducer_feedback helper docstring -- the test helper claimed production wiring it does not use.
ltm: add in-engine runtime loop-polarity reclassification primitive (GH ltm: exhaustive-mode loops never get runtime polarity reclassification (Rux/Bux unreachable) #679) -- reclassify_loops_from_results reads a loop's loop_score series and applies from_runtime_scores, keeping loop ids stable and falling back to structural polarity for never-active loops. Honest scope (per review): pysimlin Run.loops already reclassified via its own Python mirror (now pinned by a regression test); libsimlin/WASM/TS get_loops is intentionally structural-only (no Results in hand) -- wiring that surface is GH ltm: surface MostlyReinforcing/MostlyBalancing in JSON/TS/WASM layers #495's; the primitive has no production caller yet.
Verification
Every commit passed the full pre-commit suite (Rust fmt/clippy/tests, TS lint/build/tsc/tests, pysimlin), and the full suite was re-run on the rebased result. The ignored C-LEARN LTM tests (clearn_pinned_climate_loop_is_scored, clearn_ltm_discovery_compiles, clearn_with_ltm_simulates_model_vars_identically, discovery_clearn_matches_vm_wasm) were run explicitly in release mode for both behavior-changing commits. Independent reviewers verified the discriminating power of the new regression tests by stub-reverting the fixes and watching them fail.
Related issues: GH #696, #698, #699, #700, #701, #679, #495.