# GrowNet Giant PR Handoff for Codex App

## PR Title

GrowNet Cross-Language Stabilization and Parity Cleanup: Java, Python, Mojo, TypeScript, Docs, and Growth Semantics

## PR Type

Large refactor / stabilization / parity / correctness PR

## Important Context

This PR is based on a **static code review** of the current GrowNet repository plus the project’s own docs and parity reports. Treat this as a **Codex implementation handoff**.

The goal is **not** to redesign GrowNet. The goal is to:

1. fix correctness issues,
2. reduce cross-language drift,
3. align behavior with the contract and spec,
4. preserve the current research direction,
5. keep the implementation deterministic and easy to reason about.

This PR must respect the project’s coding style and the contract-first philosophy.

---

# Read These First (Authoritative Order)

Before making changes, read these in this order:

1. `docs/READ_ORDER.md`
2. `docs/contracts/grownet.contract.v5.json`
3. `docs/GrowNet_Design_Spec_V5.md`
4. `docs/CODING_STYLE_MUST_READ.md`
5. `docs/GOLDEN_RULE.md`
6. `docs/GROWTH.md`
7. `docs/CREATION_AND_GROWTH_POINTS.md`
8. `docs/Knowledge_Units_in_GrowNet.md`
9. `README.md`
10. `scripts/API_DIFF_PY_MOJO.md`

Tie-breakers when behavior or docs disagree:

1. contract
2. design spec
3. coding style
4. everything else

---

# Non-Negotiable Coding Style Rules

These rules are mandatory:

- Clarity first.
- Determinism first.
- Preserve parity across languages as much as practical.
- No leading underscores in new public symbols.
- Use the two-phase tick discipline consistently.
- Do not throw inside tick paths for best-effort hooks like growth and pruning.
- Avoid magic numbers; centralize defaults in config/policy types.
- **No single- or double-character identifiers anywhere, including loops.**

Language-specific style must also be respected:

- Python: snake_case
- Java: camelCase / PascalCase
- Mojo: typed `struct` / `fn`, `var`, Python-parity naming where intended
- C++: descriptive names, RAII, light headers

---

# Core Goal of This PR

Make GrowNet feel like **one system with multiple implementations**, rather than multiple neighboring implementations.

The intended growth ladder remains:

```text
Slot -> Neuron -> Layer -> Region
```

The intended high-level semantics remain:

- strict slot capacity,
- deterministic fallback,
- local learning,
- neuron growth from fallback pressure,
- spillover layer growth from neuron limit / region pressure,
- region growth controlled by policy,
- deterministic autowiring,
- pruning pressure balanced with growth pressure,
- best-effort hooks that do not break ticking.

---

# Executive Summary of What Must Be Addressed

## Immediate correctness / hygiene issues

1. Mojo helper-name mismatch in `src/mojo/growth_engine.mojo`
2. Mojo duplicate method definitions in `src/mojo/region.mojo`
3. Mojo shaped input binding leaks dead generic edge layers
4. Java `SlotEngine` fallback must always return a usable existing slot under saturation
5. Self-edge / self-binding hazards in shaped input binding paths
6. Python pruning is currently placeholder behavior and must be replaced or explicitly isolated as test-only

## Structural / semantic issues

7. Growth logic is too distributed and conceptually inconsistent across languages
8. Growth policy defaults differ too much across Java / Python / Mojo
9. Tick ordering and growth timing need to be made explicit and consistent
10. Python scalar tick semantics contain a convenience double-delivery path that creates parity drift
11. Some Java growth machinery is misnamed or conceptually muddy
12. TypeScript should be clearly positioned as partial parity / reference if it is not being fully normalized in this PR

## Repo-level issues

13. Docs / reports / archive sprawl should be cleaned up enough that contributors are not misled
14. Generated or provisional reports should not appear more authoritative than the contract/spec
15. Add stronger parity tests and guardrails so drift does not continue silently

---

# Scope by Language

## Languages in active implementation scope for this PR

- Java
- Python
- Mojo
- TypeScript
- Docs / repo hygiene

## Languages in limited scope

- Rust: keep labeled as Phase 1 scaffolding; do not force full parity yet
- C++: do not do a deep rewrite unless required for parity notes or minor consistency fixes; C++ mostly serves as a reference point in this PR

---

# Phase 1 — Immediate Correctness and Hygiene Fixes

## 1. Mojo: fix broken helper references in growth engine

### File
- `src/mojo/growth_engine.mojo`

### Problem
`maybe_grow(...)` calls helper names that do not match the functions defined in the file.

### Required fix
- Replace incorrect helper calls with the correct function names.
- Ensure the file compiles cleanly.
- Do not introduce alias wrappers unless needed for backwards compatibility.

### Acceptance criteria
- No unresolved helper-name references remain.
- The growth engine compiles.
- Naming is consistent and descriptive.

---

## 2. Mojo: remove duplicate method definitions from Region

### File
- `src/mojo/region.mojo`

### Problem
The file appears to contain duplicate public methods, especially around edge helpers.

### Required fix
- Remove duplicate definitions.
- Keep a single authoritative implementation for each public method.
- Re-run any Mojo tests / compile checks after cleanup.

### Acceptance criteria
- No duplicate public methods remain.
- Public surface is clean and intentional.

---

## 3. Mojo: stop leaking orphan generic edge layers in shaped input binding

### File
- `src/mojo/region.mojo`

### Problem
`bind_input_2d(...)` and `bind_input_nd(...)` call `ensure_input_edge(...)` and then often replace that edge with a new shaped edge layer, leaving the original generic edge layer stranded in `layers`.

### Required fix
Refactor shaped input binding so it does **not** create a generic edge first when the real intended edge is shaped.

Preferred behavior:
- scalar input binding may use generic edge helpers
- 2D / ND input binding should create or reuse a shaped edge directly
- do not create unused intermediate layers

### Acceptance criteria
- Binding a new 2D or ND port does not increase layer count twice
- No orphan unused generic input edge is left behind
- same principle applies to output edge creation if any shaped variant exists later

---

## 4. Java: harden SlotEngine fallback under saturation

### File
- `src/java/ai/nektron/grownet/SlotEngine.java`

### Problem
When at capacity, Java fallback logic can select a fallback slot id that may not actually exist.

### Required fix
Match the safer Python semantics:
- if the desired slot is unavailable under saturation, choose a deterministic fallback id
- if that fallback id is not present and there are already existing slots, reuse an **existing** slot deterministically
- never return a non-existent slot under capacity saturation unless this is the empty bootstrap case

### Acceptance criteria
- `selectOrCreateSlot(...)` always returns a real usable slot
- no null-path remains in `Neuron.onInput(...)`
- scalar and 2D paths are consistent

---

## 5. Add self-edge protection in shaped bind methods

### Files
- `src/java/ai/nektron/grownet/Region.java`
- `src/python/region.py`
- `src/mojo/region.mojo`

### Problem
Some shaped input binding paths can connect an edge layer to itself when the bound list includes the edge layer index.

### Required fix
- Skip self-connections when wiring shaped input edges to attached layers
- Be explicit and readable about it
- Preserve deterministic behavior

### Acceptance criteria
- No shaped bind method can wire edge -> same edge accidentally
- Tests cover this

---

## 6. Python: replace placeholder prune behavior with real prune semantics

### File
- `src/python/neuron.py`

### Problem
`prune_synapses(...)` currently clears all outgoing connections and ignores both `stale_window` and `min_strength`.

### Required fix
Implement real pruning semantics, similar in spirit to Java:
- only prune when a synapse is stale **and** weak
- if the necessary metadata is missing today, add the minimum metadata required
- keep it deterministic
- do not make prune overly clever; just make it real

If a full implementation would explode scope, then:
- move the current implementation behind a clearly labeled test-only stub path
- and implement the real path in production code

### Acceptance criteria
- Production prune uses its parameters meaningfully
- Tests cover prune behavior
- Comments do not pretend placeholder logic is final logic

---

# Phase 2 — Unify Growth Semantics

## 7. Establish one coherent growth state machine across languages

### Goal
Reduce conceptual drift by making growth logic easier to reason about.

### Requirements
Across Java, Python, and Mojo, align the semantics so that:

### Slot growth / allocation
- strict capacity
- deterministic fallback
- mark fallback flag when reuse happens under novelty pressure

### Neuron growth
Trigger only when all relevant conditions are met:
- strict capacity reached
- fallback used
- fallback streak threshold met
- cooldown satisfied
- optional guards respected

### Layer growth
Used as spillover when:
- per-layer neuron limit is reached, or
- region policy chooses to grow a new layer

### Region growth
Policy-driven OR-trigger based on pressure:
- average slots threshold
- percent at-capacity-with-fallback threshold
- cooldown
- max layer cap
- at most one layer per tick

### Required code changes
#### Java
Files likely involved:
- `src/java/ai/nektron/grownet/Neuron.java`
- `src/java/ai/nektron/grownet/Layer.java`
- `src/java/ai/nektron/grownet/growth/GrowthPolicy.java`
- `src/java/ai/nektron/grownet/growth/GrowthEngine.java`
- `src/java/ai/nektron/grownet/Region.java`

#### Python
Files likely involved:
- `src/python/neuron.py`
- `src/python/layer.py`
- `src/python/growth.py`
- `src/python/region.py`

#### Mojo
Files likely involved:
- `src/mojo/neuron.mojo`
- `src/mojo/layer.mojo`
- `src/mojo/growth_policy.mojo`
- `src/mojo/growth_engine.mojo`
- `src/mojo/region.mojo`

### Important note
Do **not** redesign the Golden Rule. This phase is about making the implementation match the existing intended growth ladder more consistently.

---

## 8. Java: rename or refactor misleading growth logic

### File
- `src/java/ai/nektron/grownet/growth/GrowthEngine.java`

### Problem
`maybeGrowNeurons(...)` reads like actual neuron creation but appears to behave more like outlier/focus bookkeeping.

### Required fix
Choose one of these and do it cleanly:

#### Option A
Rename it to reflect what it actually does.

#### Option B
Refactor it so it truly participates in neuron growth policy.

My preference: **Option A unless there is a clear reason to make it true neuron creation.**

### Acceptance criteria
- Name matches behavior
- Conceptual responsibilities are clearer
- Java growth stack is less confusing

---

## 9. Make layer-growth sizing policy consistent

### Problem
Different growth paths create spillover layers differently.

### Required fix
Create one clear spillover-layer sizing rule per language and align them as much as practical.

Examples of acceptable rule:
- small excitatory-only spillover layer
- deterministic size rule based on donor layer or fixed minimum

But do not let `requestLayerGrowth(...)` and policy-driven region growth create materially different kinds of new layers without an explicit documented reason.

### Acceptance criteria
- one documented spillover-layer allocation policy per language
- same concept across Java / Python / Mojo

---

# Phase 3 — Normalize Defaults and Tick Semantics

## 10. Normalize GrowthPolicy defaults across Java / Python / Mojo

### Files
- `src/java/ai/nektron/grownet/growth/GrowthPolicy.java`
- `src/python/growth.py`
- `src/mojo/growth_policy.mojo`

### Problem
Defaults differ too much, causing the “same” GrowNet to behave differently by language.

### Required fix
Pick one of the following strategies and implement it clearly:

#### Strategy A — same defaults everywhere
Best for parity.

#### Strategy B — contract defaults + explicit experimental defaults
If you need more aggressive Python/Mojo defaults for research, make that explicit and not accidental.

### Required output
- document the final chosen defaults in code comments and docs
- update docs if needed

### Acceptance criteria
- default behavior is intentional, not accidental
- contributors can tell whether language differences are by design or drift

---

## 11. Make tick ordering explicit and consistent

### Files likely involved
- `Region` implementations in Java / Python / Mojo
- docs if necessary

### Problem
The intended two-phase tick discipline is strong in the docs but still feels muddy in code.

### Required fix
Make the ordering explicit in implementation and comments:

Suggested final order unless the contract says otherwise:
1. input injection
2. local slot selection / firing
3. tract propagation / phase B work
4. neuron / layer `end_tick`
5. bus decay / step increment
6. growth checks
7. metrics aggregation where appropriate

If the contract/spec says a different exact order, follow that.

### Acceptance criteria
- order is easy to inspect in code
- Java / Python / Mojo follow the same conceptual order
- comments describe the order clearly

---

## 12. Remove or explicitly bless Python’s scalar double-delivery shortcut

### File
- `src/python/region.py`

### Problem
Python scalar tick currently drives the edge layer and then directly forwards the same scalar to bound target layers.

### Required fix
Decide explicitly:

#### Preferred option
Remove the shortcut and use true edge-only graph semantics.

#### Alternate option
If the shortcut is required for behavior, then document it and replicate equivalent semantics elsewhere.

My preference: **remove the shortcut** so Python does not silently diverge from Java and the intended graph model.

### Acceptance criteria
- scalar tick semantics are explicit and consistent
- parity improves

---

# Phase 4 — Language Positioning and Repo Clarity

## 13. Explicitly label implementation maturity by language

### Files
- `README.md`
- possibly `docs/README.md`
- possibly `docs/PROJECT_MEMORY.md`

### Problem
The repo implicitly treats languages differently, but the maturity hierarchy is not explicit enough.

### Required fix
Add a brief implementation maturity table, for example:

- Java: strongest contract implementation
- Python: research reference implementation
- Mojo: parity-in-progress
- TypeScript: reference / demo implementation
- Rust: Phase 1 scaffolding

Adjust the labels if needed, but make the hierarchy explicit.

### Acceptance criteria
- readers can tell which implementation is authoritative vs experimental

---

## 14. Reduce authority confusion in docs / reports

### Files / folders to inspect
- top-level generated reports
- `docs_old/`
- `docs/archive/`
- provisional parity reports

### Problem
Some non-authoritative or chat-generated reports are too visible and can be mistaken for source of truth.

### Required fix
- move clearly provisional/generated reports into archive or reports folders if appropriate
- add brief disclaimers where needed
- do not delete useful history unless it is clearly obsolete and safe to archive

### Acceptance criteria
- contract/spec are visibly primary
- provisional files no longer visually compete with them

---

# Phase 5 — TypeScript and Rust Positioning

## 15. TypeScript: either normalize key semantics or mark partial parity clearly

### File(s)
- `src/typescript/grownet-ts/src/Region.ts`
- other TS core files as needed

### Problem
TypeScript has useful ideas but is not parity-clean enough to be treated as a first-class authoritative implementation.

### Required fix
At minimum:
- improve comments and labels around parity status
- keep mesh rule / autowire behavior sensible
- do not overclaim parity

Optional but desirable:
- simplify and align growth semantics with the core languages

### Acceptance criteria
- TS status is explicit
- no misleading parity assumptions remain

---

## 16. Rust: keep clearly labeled as Phase 1 scaffolding

### File(s)
- `src/rust/...`
- README/docs mentions

### Required fix
Do not force full parity here.
Keep Rust clearly documented as partial scaffold.

---

# Detailed File-by-File Change Checklist

## Java

### `src/java/ai/nektron/grownet/SlotEngine.java`
- harden fallback path
- ensure saturation always returns an existing slot unless bootstrap case
- keep scalar and 2D logic consistent
- add comments explaining fallback behavior

### `src/java/ai/nektron/grownet/Neuron.java`
- normalize `onInput(...)` and `onInput2D(...)` behavior
- review whether `onInput2D(...)` should invoke `onOutput(...)` internally
- keep growth bookkeeping consistent
- do not leave asymmetric semantics unexplained

### `src/java/ai/nektron/grownet/Layer.java`
- make `tryGrowNeuron(...)` preserve seed config more faithfully
- avoid rebuilding neuron with hardcoded `SlotConfig.fixed(10.0)` unless explicitly intended
- preserve same-kind behavior and deterministic autowiring

### `src/java/ai/nektron/grownet/growth/GrowthPolicy.java`
- normalize defaults
- document defaults clearly
- keep naming aligned with contract / intended semantics

### `src/java/ai/nektron/grownet/growth/GrowthEngine.java`
- rename/refactor misleading neuron-growth helper
- unify layer growth creation logic with `requestLayerGrowth(...)`
- keep behavior best-effort and deterministic

### `src/java/ai/nektron/grownet/Region.java`
- add self-edge protection in bind methods
- review tick ordering and growth placement
- keep growth hooks clean and explicit

### Java tests
Update or add tests under:
- `src/java/tests/ai/nektron/grownet/tests/...`

Include tests for:
- fallback returns existing slot under cap
- no self-edge on shaped bind
- one layer max growth per tick
- growth defaults behavior
- prune semantics if applicable

---

## Python

### `src/python/slot_engine.py`
- keep as semantic reference for strict capacity
- ensure it remains clear and deterministic
- only change if needed for parity cleanup

### `src/python/neuron.py`
- replace prune placeholder with real prune logic
- keep neuron-growth trigger semantics crisp
- do not hide placeholder behavior in production path

### `src/python/layer.py`
- preserve seed config faithfully in `try_grow_neuron(...)`
- ensure spillover / neuron-limit behavior is explicit

### `src/python/growth.py`
- normalize defaults or explicitly document research defaults
- keep OR-trigger logic aligned with final intended semantics

### `src/python/region.py`
- remove scalar double-delivery shortcut unless explicitly kept by design
- add self-edge protection in shaped bind methods
- keep tick order explicit

### Python tests
Add / update tests for:
- real prune behavior
- no self-edge on bind
- scalar tick semantics
- growth default semantics
- parity-sensitive growth cases

---

## Mojo

### `src/mojo/growth_engine.mojo`
- fix helper-name bug
- review growth helper naming and logic
- keep deterministic and compile-safe

### `src/mojo/region.mojo`
- remove duplicate method definitions
- fix shaped input binding orphan-edge leak
- add self-edge protection
- review tick order and growth placement

### `src/mojo/neuron.mojo`
- ensure behavior matches intended core semantics
- review growth / fallback bookkeeping
- keep one-shot slot reuse semantics consistent

### `src/mojo/growth_policy.mojo`
- normalize defaults or clearly declare experimental defaults

### Mojo tests / compile checks
- compile sanity
- growth-engine sanity
- no orphan layer leak in shaped binding
- one-growth-per-tick behavior if tests exist

---

## TypeScript

### `src/typescript/grownet-ts/src/Region.ts`
- keep it usable, but do not pretend full parity if not true
- simplify comments and position as partial parity implementation if needed
- review any obviously incorrect growth or metrics behavior

Optional:
- align `preferOutput` handling in spatial metrics if practical

---

## Docs / repo cleanup

### `README.md`
- add implementation maturity table
- clarify which languages are primary vs in-progress

### `docs/README.md`
- align with the above if needed

### provisional/generated reports
- archive or clearly label them where appropriate

### parity reports
- keep useful ones, but reduce authority confusion

---

# Acceptance Criteria

This PR is done only if all of the following are true:

## Correctness
- Mojo compiles cleanly after cleanup
- Java fallback logic is hardened
- Python prune logic is real or explicitly separated as test-only
- shaped input binding does not leak orphan layers
- shaped input binding does not self-wire accidentally

## Semantics
- growth ladder remains Slot -> Neuron -> Layer -> Region
- growth defaults are intentional and documented
- tick ordering is explicit and consistent enough across Java / Python / Mojo
- Python scalar tick semantics no longer silently diverge unless explicitly justified

## Parity
- Java / Python / Mojo are closer in behavior and defaults
- the repo is clearer about language maturity
- type / method names remain style-compliant and descriptive

## Testing
- add or update tests for all key fixes
- do not remove useful tests unless replacing them with stronger equivalents
- keep determinism in tests

## Docs
- update docs if behavior/defaults change
- keep contract/spec authoritative
- reduce authority confusion from provisional files

---

# Testing Plan

## Java
Run all existing relevant tests and add new ones where needed.
Focus especially on:
- Region growth tests
- one-growth-per-tick tests
- proximity tests if touched
- edge binding tests
- spatial metrics tests if touched

## Python
Run relevant test suite and add tests for:
- prune behavior
- bind self-edge prevention
- scalar tick semantics
- region growth semantics

## Mojo
At minimum:
- compile check
- any available unit or smoke tests
- simple shaped-input bind test to verify no orphan edge leak

## TypeScript
Run relevant tests if touched.
Do not expand scope unless necessary.

---

# Important Implementation Constraints for Codex

## Preserve the research direction
Do not “simplify away” GrowNet’s core ideas.

## Avoid unrelated refactors
Keep the PR focused.

## Preserve determinism
Any randomness in growth or wiring must use region-level deterministic RNG and a single code path.

## Best-effort hooks
Growth and pruning logic must not crash tick paths.

## No hidden semantic shortcuts
If a language needs a convenience shortcut, either:
- make it explicit and documented, or
- remove it

## Do not overclaim parity
If a language remains partial after this PR, say so clearly.

---

# Suggested Commit Structure

Use multiple commits inside one giant PR, roughly in this order:

1. Mojo compile / hygiene fixes
2. Java fallback hardening
3. shaped bind cleanup and self-edge prevention
4. Python prune implementation
5. growth semantic cleanup
6. default normalization
7. tick-order clarification
8. tests
9. docs / implementation maturity / archive cleanup

---

# Suggested Branch Name

`grownet-cross-language-stabilization-parity-cleanup`

---

# Suggested PR Summary for GitHub

This PR tightens GrowNet’s multi-language implementations so the codebase behaves more like one contract-driven system and less like several drifting implementations. It fixes immediate correctness issues in Mojo and Java, replaces placeholder behavior in Python, reduces growth-policy drift, clarifies tick ordering, hardens shaped input binding, improves tests, and cleans up repo-level authority confusion around docs and parity status.

---

# Final Note to Codex

Be conservative, precise, and contract-first.

This is a **stabilization PR**, not a speculative redesign.
The objective is to make GrowNet more coherent, more deterministic, more maintainable, and easier to trust across Java, Python, and Mojo without losing the project’s research identity.
