Skip to content

Connectome degree-preserving rewired-null control (Phase 6a) — degree-statistics, not wiring - #264

Merged
chrisjz merged 7 commits into
mainfrom
openspec/add-connectome-structure-controls
Jul 5, 2026
Merged

Connectome degree-preserving rewired-null control (Phase 6a) — degree-statistics, not wiring#264
chrisjz merged 7 commits into
mainfrom
openspec/add-connectome-structure-controls

Conversation

@chrisjz

@chrisjz chrisjz commented Jul 5, 2026

Copy link
Copy Markdown
Member

Summary

The credibility control for the connectome half of the Phase-6a synthesis. The continuous-substrate ranking (Logbook 029) placed the wild-type C. elegans connectome 5th of 6 under PPO weight search. This change answers the obvious question: is that its specific wiring, or just its degree / sparsity statistics?

A degree-preserving rewired-null (Dhiman 2026) — rewire the connectome so every neuron keeps its exact in/out degree but which neurons connect is scrambled — as a config option on the existing connectome brain (wiring: wild_type | rewired_degree_preserving + rewire_seed), byte-identical when wild-type, matched initialisation (dedicated RNG) + budget. Full write-up: Logbook 034.

Result — DEGREE-STATISTICS

Panel: wild-type vs rewired-null, n=8 paired seeds, 6000ep, same recipe/budget as the 029 connectome cell.

arm mean success
wild_type 52.78%
rewired_null 56.06%

Paired delta (wild − rewired): d = −3.28, CI[−8.56, +1.61] (spans 0), BH-FDR q = 0.770 → indistinguishable (rewired nominally higher).

The connectome's ranking is a degree-statistics result, not a wiring result. Under PPO weight search — which re-optimises the chemical weights freely on whatever topology it is given — the specific C. elegans wiring confers no advantage over degree-matched alternatives (the Beiran & Litwin-Kumar 2025 degeneracy prediction). It does not say the wiring is functionless — its value is presumably the evolved fixed weights + specific I/O routing, not a better substrate for gradient descent.

A single-seed smoke hinted "specific wiring" (57.2 vs 46.5) but reversed at n=8 — a clean caution that connectome results must not be read off one seed.

Mechanism

  • connectome/rewiring.py — a seeded degree-preserving double-edge-swap (directed configuration-model for chemical synapses, undirected for gap junctions; no networkx dependency). On the real connectome: 91% of chemical edges moved, degree exactly preserved, mixes cleanly.
  • ConnectomePPOBrain gains the wiring/rewire_seed fields; the transform runs at the load→topology seam on a dedicated RNG so the weight-init stream is unperturbed (matched init vs wild-type for the same seed). Byte-identical when wiring: wild_type (guarded by a test).
  • scripts/analysis/connectome_structure_controls.py — paired wild-vs-rewired comparison reusing the committed 029 ranked metric + the paired-seed Wilcoxon / bootstrap / BH-FDR layer.

Self-review

Ran a multi-angle review of the branch (edge-swap correctness, seam+harness, tests/conventions). The algorithm and the matched-init seam verified correct; applied fixes for a one-sided-Wilcoxon verdict-branch reachability bug, two load-bearing test gaps (matched-init assertion, rewired-brain-trains), and cheap robustness guards. None changed the verdict.

Scope

Ships the gating rewired-null; the learnable-gap-junction control (T7.controls.learnable_gj) is a tracked fast-follow.

Gates

openspec validate --strict valid; change archived (spec requirement applied); full pytest -m "not nightly" → 4090 passed; full pre-commit run -a clean.

ðŸĪ– Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a new connectome wiring option with a degree-preserving rewired-null variant.
    • Introduced a new scenario configuration using the rewired-null control.
    • Added analysis and reporting for comparing wild-type vs rewired connectomes across paired runs.
  • Documentation

    • Expanded experiment docs and logbooks with results, interpretation, and reproducibility details.
    • Updated scenario documentation to include the new variant suffix.

chrisjz and others added 7 commits July 4, 2026 21:03
Degree-preserving rewired-null control for the wild-type connectome — tests
whether its 029 5th-of-6 standing is its specific C. elegans wiring or merely
its degree statistics (Dhiman 2026). Config-option on the existing connectome
brain (wiring: wild_type | rewired_degree_preserving + rewire_seed), a
hand-rolled seeded degree-preserving double-edge-swap (chemical directed + gap
undirected, no networkx dep), matched init/budget vs the 029 connectome cell,
paired-seed Wilcoxon + BH-FDR verdict. Byte-identical when wiring: wild_type.

Scope trimmed to the gating rewired-null; the learnable-gap-junction control
(T7.controls.learnable_gj) is a tracked fast-follow. Authored + reviewed
(/nematode-review-spec: matched-init RNG-independence fix applied); validate
--strict + pre-commit green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- connectome/rewiring.py: seeded degree-preserving double-edge-swap (directed
  chemical + undirected gap), no networkx dep; preserves every neuron's in/out
  degree, rejects self-loops/duplicates, deterministic under seed. 12 tests.
- ConnectomePPOBrain: `wiring` (wild_type | rewired_degree_preserving) +
  `rewire_seed` config fields; the transform runs at the load->topology seam on
  a DEDICATED RNG so the weight-init stream is unperturbed (matched init vs
  wild-type for the same seed). wild_type is byte-identical (guarded by a test
  reconstructing the mask from the loaded Cook adjacency).
- TestWiringControl: wild-type == loaded connectome; rewired preserves degree
  but changes edges; gap stays symmetric; forward pass finite; seed controls the
  draw.
- Rewired-null config: verbatim copy of the combined-C3 connectome cell + the
  one wiring field.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
scripts/analysis/connectome_structure_controls.py — paired wild-type vs
rewired-null comparison on the C3 ranked-success metric, reusing the committed
t7_continuous_ranking._plateau_tail metric + the paired-seed Wilcoxon / 80%
bootstrap / BH-FDR layer. Pre-registered verdict: SPECIFIC-WIRING (wild-type >
rewired at q<0.05) vs DEGREE-STATISTICS (CI spans 0), with the rewired-beats-
wild-type edge case reported honestly. 6 tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Degree-preserving rewired-null control for the connectome's 029 5th-of-6
standing: is it the specific C. elegans wiring or just the degree statistics?

Panel (wild-type vs degree-preserving rewired-null, n=8 paired seeds, 6000ep,
matched init/budget): wild-type 52.78% vs rewired-null 56.06% — paired delta
d=-3.28, CI[-8.56,+1.61] (spans 0), BH-FDR q=0.770 → indistinguishable (rewired
nominally higher). The connectome's ranking is a DEGREE-STATISTICS result, not a
wiring result: under PPO weight search the specific wiring confers no advantage
over degree-matched alternatives (Beiran & Litwin-Kumar 2025 degeneracy). Does
NOT say the wiring is functionless — its value is the evolved fixed weights.
A single-seed smoke hinted "specific wiring" (57.2 vs 46.5) but reversed at n=8.

Logbook 034 + committed supporting artefacts (controls.json + per-seed CSV +
forensics), README row, tracker tick (T7.controls.rewired_null RESOLVED:
DEGREE-STATISTICS; learnable_gj deferred as fast-follow), AGENTS.md _rewired_null
variant doc, §5-§7 tasks ticked.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Change complete + evaluated (DEGREE-STATISTICS, Logbook 034). Archived to
openspec/changes/archive/2026-07-05-add-connectome-structure-controls/ with all
tasks ticked (§1–§8); the degree-preserving rewired-null wiring requirement is
applied to openspec/specs/connectome-ppo-brain/ (heading spacing fixed post-archive).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Pre-push `pre-commit run -a` normalisation (magic trailing comma; no behaviour
change).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Harness (scripts/analysis/connectome_structure_controls.py):
- The reused Wilcoxon is one-sided (H1: wild > rewired), so the `rewired_beats`
  branch was unreachable — a significant rewired-WIN would be mislabeled
  "inconclusive". Detect it via the bootstrap CI (ci_hi < 0). + a regression test.
- Warn when n < 5 paired seeds (the 1/2^n signed-rank floor makes q<0.05 —
  `specific_wiring` — unreachable; the n>=8 lesson from bit-memory 030); record
  `underpowered` in the summary.
- Skip manifest lines whose seed token isn't an integer (no crash on a stray line).

Rewiring (connectome/rewiring.py):
- Guard against a non-simple input graph (parallel edges would silently collapse
  the weight dicts) with a clear ValueError. + a test.

Tests:
- Assert the matched-init invariant (food_gains/readout byte-identical between
  wild_type and rewired at the same seed — the control's load-bearing claim).
- A rewired brain survives a PPO update (strict-mask holds on the rewired mask,
  not just wild-type).
- Degree-preservation on a non-regular graph (the regular fixture hid in/out
  confusion); rewired-beats verdict reachability.

None of these change the reported DEGREE-STATISTICS verdict (re-verified). Also:
drop the AGENTS.md variant-suffix parenthetical for consistency, and drop the
tmp/ path reference from the 034 supporting details.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 5, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a degree-preserving double-edge-swap rewiring utility for connectomes, integrates it into ConnectomePPOBrain via new wiring/rewire_seed config fields, adds a paired-seed statistical analysis script and CLI, a new rewired-null scenario config, spec updates, tests, and experiment/OpenSpec documentation.

Changes

Rewired-Null Connectome Control

Layer / File(s) Summary
Degree-preserving rewiring utility and tests
packages/quantum-nematode/quantumnematode/connectome/rewiring.py, packages/quantum-nematode/tests/quantumnematode_tests/connectome/test_rewiring.py
Adds directed/undirected double-edge-swap functions and rewire_degree_preserving, validated by tests for degree preservation, no self-loops/duplicates, determinism, sorted output, and rejection of non-simple input.
ConnectomePPOBrain wiring integration
packages/quantum-nematode/quantumnematode/brain/arch/connectome_ppo.py, packages/quantum-nematode/tests/quantumnematode_tests/brain/arch/test_connectome_ppo.py
Adds wiring/rewire_seed config fields, conditionally rewires the connectome before topology construction using a dedicated RNG, and adds TestWiringControl tests plus minor punctuation formatting tweaks in unrelated tests.
Paired-seed analysis script and tests
scripts/analysis/connectome_structure_controls.py, packages/quantum-nematode/tests/quantumnematode_tests/analysis/test_connectome_structure_controls.py
Adds load, analyse, _success, main computing paired Wilcoxon/bootstrap verdicts with BH-FDR correction, and corresponding tests.
Scenario config and spec updates
configs/scenarios/foraging_predator_thermal/connectomeppo_small_continuous2d_combined_klinotaxis_rewired_null.yml, AGENTS.md, openspec/specs/connectome-ppo-brain/spec.md
Adds a new rewired-null scenario YAML, documents the new variant suffix, and updates the connectome-ppo-brain spec with wiring configuration invariants.
Experiment logbook and OpenSpec change docs
docs/experiments/README.md, docs/experiments/logbooks/034-connectome-structure-controls.md, docs/experiments/logbooks/supporting/034-connectome-structure-controls/*, openspec/changes/archive/2026-07-05-add-connectome-structure-controls/*, openspec/changes/phase6-tracking/tasks.md
Documents experiment 034 results, supporting statistics/forensics, and the archived OpenSpec proposal/design/tasks/spec, plus tracker updates marking the control complete.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Possibly related PRs

  • SyntheticBrains/nematode#183: Extends the ConnectomePPOBrainConfig/connectome_ppo.py implementation introduced there with the new wiring/rewiring path.
  • SyntheticBrains/nematode#191: Modifies the same foraging_predator_thermal combined C3 scenario config family, adding a rewired-null variant alongside prior config work.

Poem

A rabbit rewired the worm's own wires,
Swapped each edge but kept degree's desires,
No self-loops, no doubling of thread,
Just shuffled paths where signals once led,
Statistics win where structure once inspired.

ðŸšĨ Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: a Phase 6a degree-preserving rewired-null connectome control with a degree-statistics conclusion.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
âœĻ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧊 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch openspec/add-connectome-structure-controls

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

ðŸ§đ Nitpick comments (3)
scripts/analysis/connectome_structure_controls.py (2)

32-33: 📐 Maintainability & Code Quality | ðŸ”ĩ Trivial | ⚡ Quick win

Importing a private (_-prefixed) helper across module boundaries.

_plateau_tail is name-mangled as private in t7_continuous_ranking.py, yet it's imported and relied upon here as the load-bearing metric contract. This couples the two scripts to an internal implementation detail rather than a stable public API, so a future rename/refactor of _plateau_tail in t7_continuous_ranking.py will silently break this harness without any import-time signal beyond a linter warning.

Consider exporting a public wrapper (e.g., plateau_tail) from t7_continuous_ranking.py for cross-module reuse.

ðŸĪ– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/analysis/connectome_structure_controls.py` around lines 32 - 33, The
harness is importing the private helper _plateau_tail directly from
t7_continuous_ranking, which couples connectome_structure_controls to an
internal implementation detail. Update t7_continuous_ranking to expose a stable
public wrapper such as plateau_tail, then switch the import in
connectome_structure_controls to that public symbol and keep the existing metric
usage unchanged. Ensure the cross-module contract references the public API
only, while _plateau_tail remains internal if still needed.

52-67: 🗄ïļ Data Integrity & Integration | ðŸ”ĩ Trivial | ⚡ Quick win

Malformed manifest lines are silently dropped with no diagnostic.

Lines that don't match len(parts) != 3 or not parts[1].isdigit() are skipped silently (Line 59-60), unlike the parseable-plateau failure path just below which logs a WARN. A typo'd arm/seed manifest entry (e.g., wrong token count, non-integer seed) would vanish from the analysis with no trace, which is harder to debug than the plateau-parse failures that do get logged. Also, a duplicate <arm> <seed> entry (Line 66) silently overwrites the prior value with no warning.

ðŸ’Ą Proposed fix: warn on unparseable (non-comment) manifest lines
     for line in manifest.read_text().splitlines():
         parts = line.split()
-        if (
-            len(parts) != 3 or not parts[1].isdigit()
-        ):  # `<arm> <int seed> <out>`; skip anything else
+        if not parts or parts[0].startswith("#"):
+            continue
+        if len(parts) != 3 or not parts[1].isdigit():
+            print(f"  WARN unparseable manifest line, skipping: {line!r}")
             continue
         arm, seed, out_path = parts[0], int(parts[1]), Path(parts[2])
         success = _success(REPO / out_path)
         if success is None:
             print(f"  WARN {arm} seed {seed}: no parseable plateau in {out_path} - dropped")
             continue
+        if seed in arms.get(arm, {}):
+            print(f"  WARN {arm} seed {seed}: duplicate manifest entry, overwriting")
         arms.setdefault(arm, {})[seed] = success
ðŸĪ– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/analysis/connectome_structure_controls.py` around lines 52 - 67, The
load(manifest) parser in connectome_structure_controls.py is dropping malformed
non-comment manifest lines and duplicate <arm> <seed> entries without any
visibility. Update load() to emit a WARN for any line that fails the
token-count/int-seed check instead of silently continuing, and add a warning
when arms.setdefault(arm, {})[seed] would overwrite an existing seed entry so
analysis issues are traceable. Keep the existing _success() warning path intact
and use the load() loop’s existing arm/seed parsing to centralize the
diagnostics.
packages/quantum-nematode/tests/quantumnematode_tests/analysis/test_connectome_structure_controls.py (1)

8-9: 📐 Maintainability & Code Quality | ðŸ”ĩ Trivial | ðŸ’Ī Low value

Hardcoded parents[5] traversal is brittle to future file moves.

The fixed-depth .resolve().parents[5] walk to locate the repo root (and hence scripts/analysis) will silently resolve to the wrong directory if this test file is ever relocated, without raising an error — it'd just fail to import connectome_structure_controls or (worse) find an unrelated directory. Low risk today, but worth a comment or a more robust anchor (e.g., searching upward for pyproject.toml) if this pattern spreads.

ðŸĪ– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/quantum-nematode/tests/quantumnematode_tests/analysis/test_connectome_structure_controls.py`
around lines 8 - 9, The path setup in the test module is brittle because
_ANALYSIS_DIR relies on Path(__file__).resolve().parents[5], so update the
import bootstrap to use a stable repo-root anchor or add an explicit comment
documenting the fixed depth; in test_connectome_structure_controls, keep the
sys.path insertion tied to a robust locator for scripts/analysis rather than a
hardcoded parent index.
ðŸĪ– Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@configs/scenarios/foraging_predator_thermal/connectomeppo_small_continuous2d_combined_klinotaxis_rewired_null.yml`:
- Line 1: Rename the scenario config so the variant suffix appears before the
sensing suffix, matching the documented
`{brain}_{size}[_{variant}]_{sensing}.yml` convention. Update the filename to
place `_rewired_null` before `_klinotaxis`, keeping it aligned with the sibling
`connectomeppo_small_continuous2d_combined_klinotaxis.yml` and the AGENTS.md
naming rule.

In `@packages/quantum-nematode/quantumnematode/connectome/rewiring.py`:
- Around line 149-154: The simple-graph validation in rewire_degree_preserving
only checks for duplicate/parallel edges, but it still allows chemical
self-loops through. Update the guard near the chem_edges/gap_edges validation to
also reject any ChemicalSynapse where pre == post, since the Cook loader can
preserve those fixtures unchanged. Keep the fix localized to
rewire_degree_preserving and ensure the ValueError is raised for any self-looped
chemical edge before rewiring proceeds.

---

Nitpick comments:
In
`@packages/quantum-nematode/tests/quantumnematode_tests/analysis/test_connectome_structure_controls.py`:
- Around line 8-9: The path setup in the test module is brittle because
_ANALYSIS_DIR relies on Path(__file__).resolve().parents[5], so update the
import bootstrap to use a stable repo-root anchor or add an explicit comment
documenting the fixed depth; in test_connectome_structure_controls, keep the
sys.path insertion tied to a robust locator for scripts/analysis rather than a
hardcoded parent index.

In `@scripts/analysis/connectome_structure_controls.py`:
- Around line 32-33: The harness is importing the private helper _plateau_tail
directly from t7_continuous_ranking, which couples connectome_structure_controls
to an internal implementation detail. Update t7_continuous_ranking to expose a
stable public wrapper such as plateau_tail, then switch the import in
connectome_structure_controls to that public symbol and keep the existing metric
usage unchanged. Ensure the cross-module contract references the public API
only, while _plateau_tail remains internal if still needed.
- Around line 52-67: The load(manifest) parser in
connectome_structure_controls.py is dropping malformed non-comment manifest
lines and duplicate <arm> <seed> entries without any visibility. Update load()
to emit a WARN for any line that fails the token-count/int-seed check instead of
silently continuing, and add a warning when arms.setdefault(arm, {})[seed] would
overwrite an existing seed entry so analysis issues are traceable. Keep the
existing _success() warning path intact and use the load() loop’s existing
arm/seed parsing to centralize the diagnostics.
🊄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

â„đïļ Review info
⚙ïļ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 13e3b839-e330-4809-b128-aee53de44f3d

ðŸ“Ĩ Commits

Reviewing files that changed from the base of the PR and between 8ef945a and 669475d.

⛔ Files ignored due to path filters (1)
  • docs/experiments/logbooks/supporting/034-connectome-structure-controls/success-per-seed.csv is excluded by !**/*.csv
📒 Files selected for processing (19)
  • AGENTS.md
  • configs/scenarios/foraging_predator_thermal/connectomeppo_small_continuous2d_combined_klinotaxis_rewired_null.yml
  • docs/experiments/README.md
  • docs/experiments/logbooks/034-connectome-structure-controls.md
  • docs/experiments/logbooks/supporting/034-connectome-structure-controls/controls.json
  • docs/experiments/logbooks/supporting/034-connectome-structure-controls/details.md
  • openspec/changes/archive/2026-07-05-add-connectome-structure-controls/.openspec.yaml
  • openspec/changes/archive/2026-07-05-add-connectome-structure-controls/design.md
  • openspec/changes/archive/2026-07-05-add-connectome-structure-controls/proposal.md
  • openspec/changes/archive/2026-07-05-add-connectome-structure-controls/specs/connectome-ppo-brain/spec.md
  • openspec/changes/archive/2026-07-05-add-connectome-structure-controls/tasks.md
  • openspec/changes/phase6-tracking/tasks.md
  • openspec/specs/connectome-ppo-brain/spec.md
  • packages/quantum-nematode/quantumnematode/brain/arch/connectome_ppo.py
  • packages/quantum-nematode/quantumnematode/connectome/rewiring.py
  • packages/quantum-nematode/tests/quantumnematode_tests/analysis/test_connectome_structure_controls.py
  • packages/quantum-nematode/tests/quantumnematode_tests/brain/arch/test_connectome_ppo.py
  • packages/quantum-nematode/tests/quantumnematode_tests/connectome/test_rewiring.py
  • scripts/analysis/connectome_structure_controls.py

@@ -0,0 +1,142 @@
# Degree-preserving rewired-null control of the ConnectomePPO combined-C3 cell.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Filename places the new variant suffix after the sensing suffix.

Per AGENTS.md's own convention ({brain}_{size}[_{variant}]_{sensing}.yml, sensing suffixes listed last), _rewired_null is documented as a variant suffix but is appended here after the _klinotaxis sensing suffix, unlike the sibling connectomeppo_small_continuous2d_combined_klinotaxis.yml file this is meant to pair with. Consider connectomeppo_small_continuous2d_combined_rewired_null_klinotaxis.yml to match the documented ordering.

As per coding guidelines: configs/scenarios/**/*.yml: "Scenario configuration files must follow the naming convention {brain}_{size}[_{variant}]_{sensing}.yml."

ðŸĪ– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@configs/scenarios/foraging_predator_thermal/connectomeppo_small_continuous2d_combined_klinotaxis_rewired_null.yml`
at line 1, Rename the scenario config so the variant suffix appears before the
sensing suffix, matching the documented
`{brain}_{size}[_{variant}]_{sensing}.yml` convention. Update the filename to
place `_rewired_null` before `_klinotaxis`, keeping it aligned with the sibling
`connectomeppo_small_continuous2d_combined_klinotaxis.yml` and the AGENTS.md
naming rule.

Source: Coding guidelines

Comment on lines +149 to +154
# The swap assumes a SIMPLE input graph (no parallel edges) - the weight dicts below key on the
# edge tuple and would silently collapse duplicates. The Cook loader dedups both edge types, so
# this is a guard against a hand-built/alternate-loader fixture, not a live path.
if len(set(chem_edges)) != len(chem_edges) or len(set(gap_edges)) != len(gap_edges):
msg = "rewire_degree_preserving requires a simple connectome (no duplicate/parallel edges)"
raise ValueError(msg)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄ïļ Data Integrity & Integration | ðŸŸĄ Minor | ⚡ Quick win

ðŸ§Đ Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm whether ChemicalSynapse forbids self-loops (pre == post) at construction.
rg -n -A 15 'class ChemicalSynapse' packages/quantum-nematode/quantumnematode/connectome/model.py

Repository: SyntheticBrains/nematode

Length of output: 706


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== model.py around ChemicalSynapse =="
sed -n '55,130p' packages/quantum-nematode/quantumnematode/connectome/model.py

echo
echo "== rewiring.py around the degree-preserving swap and output checks =="
sed -n '1,240p' packages/quantum-nematode/quantumnematode/connectome/rewiring.py

Repository: SyntheticBrains/nematode

Length of output: 10650


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== search for self-loop handling in connectome code =="
rg -n -A 3 -B 3 'self-loop|pre == post|a < b|duplicate|parallel' packages/quantum-nematode/quantumnematode/connectome

echo
echo "== locate parser/loader entry points =="
rg -n -A 5 -B 5 'ChemicalSynapse|GapJunction|Connectome' packages/quantum-nematode/quantumnematode/connectome

Repository: SyntheticBrains/nematode

Length of output: 45748


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== chemical edge parsing and any self-loop filtering in loader.py =="
sed -n '120,240p' packages/quantum-nematode/quantumnematode/connectome/loader.py

echo
echo "== direct search for chemical self-loop checks =="
rg -n 'pre == post|a == b|self-loop' packages/quantum-nematode/quantumnematode/connectome/loader.py

Repository: SyntheticBrains/nematode

Length of output: 4686


Reject chemical self-loops here. ChemicalSynapse accepts pre == post, and the Cook loader doesn’t filter them, so a fixture with a pre-existing self-loop can still be returned unchanged and violate the simple-graph contract.

ðŸĪ– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/quantum-nematode/quantumnematode/connectome/rewiring.py` around
lines 149 - 154, The simple-graph validation in rewire_degree_preserving only
checks for duplicate/parallel edges, but it still allows chemical self-loops
through. Update the guard near the chem_edges/gap_edges validation to also
reject any ChemicalSynapse where pre == post, since the Cook loader can preserve
those fixtures unchanged. Keep the fix localized to rewire_degree_preserving and
ensure the ValueError is raised for any self-looped chemical edge before
rewiring proceeds.

@codecov

codecov Bot commented Jul 5, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.79882% with 24 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
scripts/analysis/connectome_structure_controls.py 74.68% 16 Missing and 4 partials ⚠ïļ
...um-nematode/quantumnematode/connectome/rewiring.py 95.18% 2 Missing and 2 partials ⚠ïļ

ðŸ“Ē Thoughts on this report? Let us know!

@chrisjz
chrisjz merged commit d22f051 into main Jul 5, 2026
4 checks passed
@chrisjz
chrisjz deleted the openspec/add-connectome-structure-controls branch July 5, 2026 02:15
@chrisjz
chrisjz restored the openspec/add-connectome-structure-controls branch July 5, 2026 02:15
@chrisjz
chrisjz deleted the openspec/add-connectome-structure-controls branch July 5, 2026 02:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant