# Tripartite Synapse — Pseudocode v5
Energy and material flows explicit. Variables aggregated to minimum set.

---

## Part 1 — Conventions

```
SCOPE    = { DAY, NIGHT }
CONTEXT  = { AP, NOT_AP, bAP, NOT_bAP, CONTINUOUS }

Variable types:
  FIXED       = externally imposed — does not change during simulation
  VAR         = changes dynamically
  FAST_TRACE  = accumulates and decays within DAY — never reaches NIGHT
                role: biases next behavior within same context
  TAG         = set during DAY, decays slowly, survives to NIGHT
                role: gates structural commit in NIGHT
                for POST only: two phases — CANDIDATE (DAY) → STABLE (DAY) → NIGHT
  BUDGET      = single energy variable per compartment
                all costs deducted here
  MATERIAL    = single structural resource variable per compartment
                all material draws and returns here
  STRUCTURE   = slow architectural variable
                READ during DAY, WRITTEN only in NIGHT
```

---

## Part 2 — Fixed Parameters

```
// Thresholds
FIXED  Ca_TAG_threshold         // Ca²⁺ level sufficient to set post CANDIDATE tag
FIXED  Ca_HIGH                  // LTP-driving Ca²⁺ amplitude
FIXED  Ca_LOW                   // LTD-driving Ca²⁺ amplitude
FIXED  spillover_threshold      // cleft saturation threshold for mGluR activation
FIXED  eligibility_threshold    // minimum fast_trace to be taggable (all components)
FIXED  dopamine_threshold       // minimum dopamine for tag stabilization
FIXED  tagging_threshold        // minimum possible_tagging for tag accumulation
FIXED  tag_expiry_threshold     // minimum tag to survive to NIGHT commit
FIXED  homeostatic_ceiling      // max soma firing rate before global downscale
FIXED  disuse_threshold         // silence duration before passive depotentiation
FIXED  recycling_fraction       // fraction of material recovered after LTD dismantling

// External signals — organism level
FIXED  dopamine_level           // VTA broadcast — reward/save signal
FIXED  NE_level                 // locus coeruleus — arousal/gain
FIXED  ACh_level                // basal forebrain — attention/threshold

// Physical constraints
FIXED  vascular_glucose_supply  // hard energy ceiling — astrocyte root
FIXED  branch_geometry          // dendritic topology — affects bAP decay
FIXED  Ca_cooperativity_n       // Hill coefficient for Ca²⁺-driven NT release (~3-4)
FIXED  Ca_half_max_K            // half-maximal Ca²⁺ for NT release
```

---

## Part 3 — Energy and Material Declarations

```
// ── ENERGY: one budget per compartment ────────────────────────────────

VAR  astro_budget   // ROOT energy variable for synaptic operations
                    // SOURCE: vascular_glucose_supply → glycolysis
                    // COSTS:  glutamate clearance (EAAT transport)
                    //         D-serine synthesis (serine racemase)
                    //         ECM secretion (Glypicans, Thrombospondins)
                    //         process motility (cytoskeletal remodeling)
                    //         lactate production (exported to pre, post, dend)
                    // (simplifies: astro_ATP_budget + all enzyme running costs)

VAR  astro_lactate  // fuel exported by astrocyte → feeds pre, post, dend
                    // = min(glycolysis(vascular_glucose_supply), astro_budget × export_fraction)
                    // hard cap: vascular_glucose_supply (FIXED)

VAR  pre_budget     // bouton energy
                    // SOURCE: astro_lactate (primary) — via perisynaptic delivery
                    // COSTS:  VGCC opening + vesicle fusion + VATPase refill
                    //         active zone maintenance
                    // (simplifies: bouton_ATP + VATPase_running_cost)

VAR  post_budget    // spine energy
                    // SOURCE: astro_lactate (primary) — via perisynaptic delivery
                    // COSTS:  NaK pump membrane reset
                    //         AMPA receptor lateral diffusion + recycling
                    //         actin remodeling for transient spine changes
                    //         NMDA current handling
                    // (simplifies: spine_ATP + NaK_ATPase_cost + actin_cycling_cost)

VAR  dend_budget    // branch energy
                    // SOURCE: astro_lactate (primary) + soma organelle delivery (minor)
                    // COSTS:  bAP propagation along branch
                    //         local mRNA translation
                    //         protein and organelle transport to spines
                    //         branch calcium handling
                    // (simplifies: dend_mitochondria_ATP + local_translation_cost)

VAR  soma_budget    // somatic energy
                    // SOURCE: own mitochondria (self-fueled — not from astrocyte)
                    // COSTS:  AP generation (Na⁺/K⁺ currents)
                    //         CREB transcription
                    //         protein synthesis machinery
                    //         organelle biogenesis
                    //         shipping to dend and axon
                    // (simplifies: soma_ATP + synthesis_running_cost)

VAR  axon_budget    // axonal energy
                    // SOURCE: soma_budget (primary) + astro_lactate along shaft (minor)
                    // COSTS:  AP propagation at each node of Ranvier
                    //         anterograde motor protein transport
                    //         myelin maintenance
                    // (simplifies: axon_ATP + transport_running_cost)

// ── MATERIAL: one material variable per compartment ───────────────────

VAR  astro_material  // astrosynaptic structural components
                     // SOURCE: astrocyte cell body synthesis
                     // CONTAINS: EAAT transporter proteins
                     //           serine racemase enzyme
                     //           ECM proteins (Glypicans, Thrombospondins)
                     //           process cytoskeleton components
                     //           D-serine precursor (serine)
                     // COSTS:    drawn by DAY D-serine release (serine consumed)
                     //           drawn by NIGHT ECM secretion and process remodeling
                     // (simplifies: astro_ECM_pool + racemase_cap + EAAT_pool
                     //              + process_extensions + D_serine_precursor)

VAR  pre_material    // presynaptic bouton structural components
                     // SOURCE: soma_material via axon transport (anterograde)
                     // CONTAINS: RIM, Munc13 (AZ scaffold)
                     //           VGCC subunits
                     //           vesicle membrane proteins
                     //           synaptotagmin, SNARE proteins
                     // COSTS:    drawn by NIGHT active zone expansion
                     // RETURNS:  to shared axonal pool after LTD dismantling
                     // (simplifies: axon_vesicle_protein_pool + AZ_scaffold_proteins)

VAR  post_material   // postsynaptic spine structural components
                     // SOURCE: dend_material (branch local pool + soma delivery)
                     // CONTAINS: AMPA receptor subunits (GluA1, GluA2)
                     //           PSD scaffold proteins (PSD-95, SHANK)
                     //           actin monomers + polymerization machinery
                     //           CaMKII
                     // COSTS:    drawn by NIGHT receptor anchoring + spine enlargement
                     // RETURNS:  to branch pool after LTD internalization
                     // (simplifies: dend_receptor_reserve + dend_actin_machinery
                     //              + PSD_scaffold_pool)

VAR  dend_material   // dendritic branch structural and supply components
                     // SOURCE: soma_material (shipped during DAY NOT_AP + NIGHT)
                     // CONTAINS: plasticity proteins (Arc, Homer)
                     //           mRNA pool (Arc mRNA, BDNF mRNA)
                     //           AMPA receptor subunits (in transit to spines)
                     //           organelles (mitochondria for local energy)
                     // COSTS:    drawn by local translation (mRNA consumed)
                     //           drawn by spine delivery (post_material replenishment)
                     //           drawn by NIGHT branch structural expansion
                     // (simplifies: dend_protein_flux + dend_mRNA_pool
                     //              + dend_organelle_store)

VAR  soma_material   // somatic production output
                     // SOURCE: CREB-driven synthesis (own ribosomes + nucleus)
                     // CONTAINS: all structural proteins for downstream compartments
                     //           mRNA transcripts (Arc, BDNF, receptor subunits)
                     //           organelles (mitochondria, ribosomes)
                     // COSTS:    shipped to dend_material during DAY NOT_AP + NIGHT
                     //           shipped to axon for pre_material replenishment
                     //           depleted by soma's own NIGHT structural commit
                     // (simplifies: soma_protein_synthesis_rate + soma_organelle_pool
                     //              + soma_receptor_synthesis_rate + mRNA_transcription)

VAR  axon_material   // axonal transport and structural components
                     // SOURCE: soma_material (motor proteins, myelin components)
                     // CONTAINS: kinesin/dynein motor proteins
                     //           microtubule components
                     //           myelin maintenance proteins
                     // COSTS:    drawn by NIGHT axon structural expansion
                     //           consumed continuously by anterograde transport
                     // (simplifies: transport_machinery + myelination_proteins)
```

---

## Part 4 — Structural Variables (Written Only in NIGHT)

```
VAR  pre_structure   // active zone capacity
                     // RRP_capacity ∝ pre_structure
                     // VGCC_coupling ∝ pre_structure
                     // refill_ceiling ∝ pre_structure
                     // (simplifies: active_zone_size + VGCC_clustering + RRP_pool_capacity)

VAR  post_structure  // spine sensitivity capacity
                     // anchoring_slots ∝ post_structure
                     // spine_volume ∝ post_structure
                     // local_reserve ∝ post_structure
                     // (simplifies: AMPA_count_ceiling + spine_volume + receptor_reserve_ceiling)

VAR  dend_structure  // branch transmission and supply capacity
                     // bAP_fidelity ∝ dend_structure × attenuation(position)
                     // translation_ceiling ∝ dend_structure
                     // transport_speed ∝ dend_structure
                     // (simplifies: mitochondria_density + cytoskeletal_integrity
                     //              + mRNA_pool_ceiling)

VAR  soma_structure  // somatic output and production capacity
                     // baseline_threshold ∝ 1/soma_structure
                     // AP_reliability ∝ soma_structure
                     // synthesis_ceiling ∝ soma_structure
                     // (simplifies: ion_channel_density + ribosome_density
                     //              + CREB_machinery)

VAR  axon_structure  // axonal transmission and transport capacity
                     // propagation_reliability ∝ axon_structure
                     // transport_rate ∝ axon_structure
                     // (simplifies: myelination_density + transport_machinery_capacity
                     //              + axonal_mitochondria_density)

VAR  astro_structure // astrosynaptic environmental capacity
                     // perisynaptic_distance ∝ 1/astro_structure
                     // EAAT_density ∝ astro_structure
                     // D_serine_tonic ∝ astro_structure
                     // ECM_integrity ∝ astro_structure
                     // SELF-REINFORCING in both directions:
                     //   LTP → astro_structure ↑ → signal more contained,
                     //         D-serine tonic ↑ → future LTP easier
                     //   LTD → astro_structure ↓ → signal dilutes,
                     //         D-serine tonic = 0 → future LTD easier
                     // (simplifies: perisynaptic_distance + ECM_integrity
                     //              + D_serine_tonic_level + EAAT_density)
```

---

## Part 5 — Trace Variables

```
// ── Fast traces: DAY only, decay automatically ────────────────────────

FAST_TRACE  pre_fast_trace
            // += spike_Ca_influx() on each AP
            // *= decay(τ ≈ 100ms)
            // role: (1) biases NT flux in next AP context (residual Ca²⁺)
            //       (2) eligibility condition for pre_possible_tagging
            // energy: no direct cost — Ca²⁺ dynamics are passive
            // material: no direct cost

FAST_TRACE  post_fast_trace
            // += NMDA_Ca_influx × rise_speed() in NOT_bAP context
            // += bAP_Ca_boost() if CANDIDATE tag confirmed in bAP context
            // *= decay(τ ≈ tens of ms)
            // role: (1) encodes LTP vs LTD instruction (amplitude × speed)
            //       (2) eligibility condition for post CANDIDATE tag
            // energy cost: post_budget -= NMDA_current_cost
            // material: no direct cost

FAST_TRACE  dend_fast_trace
            // += bAP_Ca_influx() + spine_Ca_spillover()
            // *= decay(τ ≈ 300ms)
            // role: (1) integrates branch co-activity
            //       (2) eligibility for dend_possible_tagging
            //       (3) gates local translation rate when dend_tag set
            // energy cost: dend_budget -= branch_Ca_handling_cost
            // material: no direct cost

FAST_TRACE  soma_fast_trace
            // += nuclear_Ca_influx() on each somatic AP
            // *= decay(τ ≈ seconds)
            // role: (1) adaptation — raises AP_threshold with recent firing
            //       (2) eligibility condition for soma CREB gate
            // energy cost: soma_budget -= AP_generation_cost
            // material: no direct cost

FAST_TRACE  axon_fast_trace
            // += AP_propagation_load(input_freq) on each AP
            // *= decay(τ ≈ seconds)
            // role: (1) drives propagation failure at branch points under high freq
            //       (2) eligibility for axon_possible_tagging
            // energy cost: axon_budget -= AP_propagation_cost
            // material: no direct cost

FAST_TRACE  astro_fast_trace
            // += mGluR5_Ca_influx() when glutamate > spillover_threshold
            // *= decay(τ ≈ seconds)
            // role: (1) drives D-serine release proportional to magnitude
            //       (2) eligibility for astro_possible_tagging
            //       (3) triggers global lockdown when > OVERLOAD_threshold
            // energy cost: astro_budget -= D_serine_synthesis_cost
            // material cost: astro_material -= D_serine_precursor_cost

// ── Possible tagging: intermediate, decays over seconds–minutes ───────

VAR  pre_possible_tagging    // += pre_fast_trace when > eligibility_threshold
                             // *= decay(τ ≈ seconds)
VAR  post_possible_tagging   // += post_fast_trace when > Ca_TAG_threshold (bAP confirmed)
                             // *= decay(τ ≈ minutes) — CANDIDATE lifetime
VAR  dend_possible_tagging   // += dend_fast_trace when > eligibility_threshold
                             // *= decay(τ ≈ seconds–minutes)
VAR  soma_possible_tagging   // += soma_fast_trace when > eligibility_threshold
                             // *= decay(τ ≈ seconds–minutes)
VAR  axon_possible_tagging   // += axon_fast_trace when > eligibility_threshold
                             // *= decay(τ ≈ seconds–minutes)
VAR  astro_possible_tagging  // += astro_fast_trace when > eligibility_threshold
                             // *= decay(τ ≈ seconds–minutes)

// ── Tags: slow, DAY→NIGHT bridge ──────────────────────────────────────

TAG  pre_tag    // += dopamine × pre_possible_tagging when both > threshold
                // *= decay(τ ≈ hours) — survives to NIGHT
                // gates: pre_structure expansion in NIGHT
                // energy cost: none — tag is a molecular state, not a process

TAG  post_tag   // TWO-PHASE for POST only:
                // CANDIDATE phase:
                //   set when post_fast_trace > Ca_TAG_threshold AND bAP confirmed
                //   decays within minutes if dopamine does not arrive
                // STABLE phase:
                //   += dopamine × post_possible_tagging when both > threshold
                //   *= decay(τ ≈ hours) — survives to NIGHT
                // gates: post_structure expansion in NIGHT
                // energy cost: post_budget -= PKA_phosphorylation_cost (minor)
                // material cost: none

TAG  dend_tag   // += dopamine × dend_possible_tagging when both > threshold
                // *= decay(τ ≈ hours)
                // gates: dend_structure expansion + local translation activation in NIGHT
                // energy cost: none

TAG  soma_tag   // += dopamine × soma_possible_tagging when both > threshold
                // *= decay(τ ≈ hours)
                // gates: soma_structure expansion + protein synthesis peak in NIGHT
                // energy cost: soma_budget -= CREB_phosphorylation_cost (minor)
                // material cost: none

TAG  axon_tag   // += dopamine × axon_possible_tagging when both > threshold
                // *= decay(τ ≈ hours)
                // gates: axon_structure expansion in NIGHT
                // energy cost: none

TAG  astro_tag  // += dopamine × astro_possible_tagging when both > threshold
                // *= decay(τ ≈ hours)
                // gates: astro_structure expansion (process retraction + ECM sealing) in NIGHT
                // energy cost: none
```

---
---

# SCOPE: DAY
Budgets consumed. Fast traces written and decay. Tags set but not cleared.
Structures READ only.

---

## PRE | CONTEXT: AP

```
scope DAY | context AP:

    // Energy gate — release requires ATP
    if pre_budget < AP_release_cost:
        suppress(NT_flux)
        exit context
        // biological basis: ATP depletion → VGCC cannot open reliably

    // Fast trace: residual Ca²⁺ deposit
    pre_fast_trace += spike_Ca_influx(input_freq)
    pre_fast_trace *= decay(τ = 100ms)
    pre_budget     -= Ca_handling_cost
    // biological basis: Ca²⁺ enters via VGCCs, pumped out by PMCA/NCX

    // NT flux: continuous release while RRP has content
    // Ca_drive: Hill function — cooperative Ca²⁺ dependence of synaptotagmin
    Ca_drive  = pre_fast_trace^Ca_cooperativity_n /
                (Ca_half_max_K^Ca_cooperativity_n + pre_fast_trace^Ca_cooperativity_n)

    if RRP_level > 0:
        NT_flux     = RRP_level × Ca_drive             // proportional to pool × Ca²⁺
        glutamate  += NT_flux × Δt                     // cleft concentration rises
        RRP_level  -= NT_flux × Δt                     // pool depletes
        pre_budget -= NT_flux × vesicle_fusion_cost    // ATP per vesicle equivalent
        // biological basis: SNARE-mediated vesicle fusion, each event costs ATP

    // RRP refill from reserve — rate limited by pre_budget and pre_structure
    RRP_refill  = min(refill_rate_constant, pre_structure.refill_ceiling)
    RRP_level  += RRP_refill × Δt
    RRP_level   = clamp(RRP_level, 0, pre_structure.RRP_capacity)
    pre_budget -= RRP_refill × VATPase_cost
    // biological basis: VATPase pumps refill vesicles with NT, costs ATP

    // Overflow brake — mGluR2/3 Gi-mediated autoinhibition
    if glutamate > spillover_threshold:
        Ca_drive *= mGluR_brake_factor
        // biological basis: extrasynaptic glu activates mGluR2/3 → Gi →
        //                   adenylyl cyclase ↓ → cAMP ↓ → VGCC opening ↓

    // Refuel from astrocyte lactate
    pre_budget += astro_lactate × pre_fraction
    // biological basis: lactate → pyruvate → TCA → ATP via bouton mitochondria
```

## PRE | CONTEXT: NOT_AP

```
scope DAY | context NOT_AP:

    // Fast trace decays — eligibility window closing
    pre_fast_trace *= decay(τ = 100ms)

    // RRP refills during silence — STP recovery
    RRP_refill  = min(refill_rate_constant, pre_structure.refill_ceiling)
    RRP_level  += RRP_refill × Δt
    RRP_level   = clamp(RRP_level, 0, pre_structure.RRP_capacity)
    pre_budget -= RRP_refill × VATPase_cost

    // Possible tagging: graded accumulation while eligible
    if pre_fast_trace > eligibility_threshold:
        pre_possible_tagging += pre_fast_trace
    pre_possible_tagging *= decay(τ = seconds)

    // Dopamine decays locally
    dopamine_local *= decay(τ = hundreds_of_ms)
    // biological basis: dopamine reuptake by DAT, enzymatic degradation (MAO, COMT)

    // Tag: set only when BOTH local eligibility AND global validation coincide
    if dopamine_local > dopamine_threshold and
       pre_possible_tagging > tagging_threshold:
        pre_tag += dopamine_local × pre_possible_tagging
    pre_tag *= decay(τ = hours)
    // biological basis: PKA phosphorylation of AZ proteins stabilizes tag
    //                   requires both residual Ca²⁺ eligibility AND dopamine-driven PKA
```

---

## POST | CONTEXT: NOT_bAP

```
scope DAY | context NOT_bAP:

    // AMPA current — gated by post_structure (READ)
    // Occupancy: transient receptor insertion/removal from existing slots
    AMPA_current    = glutamate × post_structure.sensitivity
    Vm             += AMPA_current
    post_budget    -= AMPA_current_cost
    // biological basis: AMPA receptor opening → Na⁺ influx → NaK pump cost

    // NMDA gate: three-way coincidence
    //   (1) sufficient depolarization (Mg²⁺ block ejected)
    //   (2) D-serine from astrosynapse (co-agonist present)
    //   (3) glutamate bound
    if Vm > Mg_eject_threshold and
       astro_D_serine > D_serine_threshold:
        Ca_influx        = NMDA_Ca_influx(glutamate)
        post_fast_trace += Ca_influx × rise_speed(Ca_influx)
        post_budget     -= NMDA_current_cost
        // biological basis: NMDA Ca²⁺ influx → CaMKII vs PP1 competition
        //                   fast rise → CaMKII wins → LTP instruction
        //                   slow rise → PP1 wins → LTD instruction

    // CANDIDATE tag: set when Ca²⁺ crossed tagging threshold
    // This is the Hebbian anticipation — before bAP confirms
    if post_fast_trace > Ca_TAG_threshold:
        post_possible_tagging += post_fast_trace   // graded — higher Ca²⁺ → more contribution
    post_possible_tagging *= decay(τ = minutes)    // CANDIDATE lifetime — minutes
    // biological basis: early CaMKII activation creates labile tag
    //                   decays via phosphatase activity if not stabilized

    // Fast trace decays
    post_fast_trace *= decay(τ = tens_of_ms)

    // Refuel
    post_budget += astro_lactate × post_fraction
```

## POST | CONTEXT: bAP

```
scope DAY | context bAP:

    // bAP arrives — strength set by dend_structure.bAP_fidelity (READ)
    Vm += bAP_depolarization × dend_structure.bAP_fidelity
    post_budget -= bAP_reset_cost
    // biological basis: bAP Ca²⁺ entry via VDCCs in spine, NaK reset costs ATP

    // Coincidence confirmation: bAP finds CANDIDATE already set
    if post_possible_tagging > Ca_TAG_threshold:
        post_fast_trace += bAP_Ca_boost()          // trace amplified above Ca_HIGH
        // biological basis: bAP + prior NMDA Ca²⁺ → supralinear Ca²⁺ summation
        //                   this is the Hebbian coincidence — forward + backward signals

    // else: bAP arrives but spine was not active — no amplification, no tag

    // Dopamine decays locally
    dopamine_local *= decay(τ = hundreds_of_ms)

    // STABLE tag: CANDIDATE stabilized by dopamine within window
    if dopamine_local > dopamine_threshold and
       post_possible_tagging > tagging_threshold:
        post_tag += dopamine_local × post_possible_tagging
    post_tag *= decay(τ = hours)
    post_budget -= PKA_phosphorylation_cost        // minor ATP cost for PKA activity
    // biological basis: dopamine → D1R → PKA → GluA1-Ser845 phosphorylation
    //                   PKA also phosphorylates DARPP-32 → inhibits PP1
    //                   stabilizes tag against phosphatase-driven decay
```

---

## DEND | CONTEXT: CONTINUOUS

```
scope DAY | context CONTINUOUS:

    // Integrate spines upward toward soma
    branch_Vm = integrate(POST.Vm, all_spines_on_branch)

    // Propagate bAP downward — fidelity set by dend_structure (READ)
    bAP_local  = propagate_bAP(SOMA.AP_fired,
                               dend_structure.bAP_fidelity,
                               branch_geometry)
    dend_budget -= bAP_propagation_cost
    // biological basis: bAP propagation requires Na⁺ channel re-activation
    //                   costs ATP via NaK reset along branch length

    // Fast trace: branch Ca²⁺ from bAP + spine spillover
    dend_fast_trace += bAP_Ca_influx(bAP_local)
    dend_fast_trace += spine_Ca_spillover(active_spines)
    dend_fast_trace *= decay(τ = 300ms)
    dend_budget     -= branch_Ca_handling_cost
    // biological basis: Ca²⁺ enters via VDCCs along branch,
    //                   SERCA pump re-sequestration costs ATP

    // Possible tagging: branch co-activity threshold
    if dend_fast_trace > eligibility_threshold:
        dend_possible_tagging += dend_fast_trace
    dend_possible_tagging *= decay(τ = seconds)

    // Dopamine decays
    dopamine_local *= decay(τ = hundreds_of_ms)

    // Tag
    if dopamine_local > dopamine_threshold and
       dend_possible_tagging > tagging_threshold:
        dend_tag += dopamine_local × dend_possible_tagging
    dend_tag *= decay(τ = hours)

    // Local translation: activated when tag set, gated by dend_budget
    if dend_tag > tag_expiry_threshold and dend_budget > translation_cost:
        local_proteins      = translate(dend_material.mRNA_pool,
                                        dend_fast_trace)  // rate ∝ fast trace
        dend_material.mRNA_pool  -= local_proteins × mRNA_cost
        post_material            += local_proteins × delivery_fraction
        dend_budget              -= translation_cost
        // biological basis: Arc mRNA + polyribosomes at branch
        //                   fast local protein supply for early structural changes
        //                   no soma wait required

    // ACh modulates commit threshold globally
    commit_threshold *= (1 / (1 + ACh_level × ACh_gain))

    // Branch maintenance cost
    dend_budget -= branch_maintenance_cost
    dend_budget += astro_lactate × dend_fraction
    // material: replenished by soma shipping during NOT_AP
```

---

## SOMA | CONTEXT: AP

```
scope DAY | context AP:

    // Integrate — fires when branch inputs cross threshold
    // Threshold modulated by fast trace (adaptation) and neuromodulators
    AP_threshold = soma_structure.baseline_threshold
                   × (1 + adaptation_factor(soma_fast_trace))  // rises with recent firing
                   × neuromod_factor(NE_level, ACh_level)      // NE lowers, ACh sharpens
                   × refractory_factor(time_since_last_AP)     // hard block then graded recovery

    if branch_Vm > AP_threshold:
        AP_fired = True
        soma_budget -= AP_generation_cost
        // biological basis: Na⁺/K⁺ currents for AP, NaK pump reset

        // Fast trace: nuclear Ca²⁺ accumulation
        soma_fast_trace += nuclear_Ca_influx()
        soma_fast_trace *= decay(τ = seconds)
        // biological basis: L-type VGCC → nuclear Ca²⁺ → CaM kinase nuclear activation

        // Refractory period
        refractory_timer = absolute_refractory_duration  // ~2ms hard block

        // Possible tagging
        if soma_fast_trace > eligibility_threshold:
            soma_possible_tagging += soma_fast_trace
        soma_possible_tagging *= decay(τ = seconds)

        // Dopamine decays
        dopamine_local *= decay(τ = hundreds_of_ms)

        // Tag: nuclear Ca²⁺ AND dopamine coincidence
        if dopamine_local > dopamine_threshold and
           soma_possible_tagging > tagging_threshold:
            soma_tag += dopamine_local × soma_possible_tagging
        soma_tag *= decay(τ = hours)
        soma_budget -= CREB_phosphorylation_cost
        // biological basis: nuclear Ca²⁺ + PKA → CREB phosphorylation
        //                   requires both activity (Ca²⁺) AND reward (dopamine/PKA)
```

## SOMA | CONTEXT: NOT_AP

```
scope DAY | context NOT_AP:

    // Integrate dendritic inputs
    branch_Vm = integrate(DEND.branch_Vm, all_branches)

    // Refractory timer counts down
    refractory_timer = max(0, refractory_timer - Δt)

    // Fast trace decays — threshold returning to baseline
    soma_fast_trace *= decay(τ = seconds)

    // Ship material to tagged branches — priority by tag magnitude
    for branch in branches_ranked_by(dend_tag):
        delivery         = min(shipping_fraction × soma_material,
                               soma_budget × shipping_cost_fraction)
        dend_material[branch] += delivery
        soma_material        -= delivery
        soma_budget          -= shipping_cost
        // biological basis: kinesin-driven anterograde transport of mRNA + proteins
        //                   tagged branches receive priority allocation

    // Ship material to axon for bouton replenishment
    axon_delivery    = min(axon_shipping_fraction × soma_material,
                           soma_budget × axon_shipping_cost_fraction)
    axon_material   += axon_delivery
    soma_material   -= axon_delivery
    soma_budget     -= axon_shipping_cost
    // biological basis: slow axonal transport — days to reach distal boutons

    // Neuromodulator context: PKA broadcast amplifies all tagged component traces
    if dopamine_level > dopamine_threshold or NE_level > NE_threshold:
        for each component where possible_tagging > tagging_threshold:
            tag += dopamine_level × possible_tagging × PKA_amplifier
        // biological basis: dopamine → cAMP → PKA → phosphorylates targets
        //                   throughout neuron simultaneously
```

---

## AXON | CONTEXT: CONTINUOUS

```
scope DAY | context CONTINUOUS:

    // AP propagation — reliability set by axon_structure (READ)
    propagation_reliability = axon_structure.myelination
                              × (1 - failure_rate(axon_fast_trace))
    // biological basis: high axon_fast_trace → Na⁺ channel inactivation at branch points
    //                   → some APs fail to reach distal boutons
    //                   → this is axonal STD (frequency-dependent filtering)

    APs_delivered = AP_fired × propagation_reliability
    axon_budget  -= AP_propagation_cost × APs_delivered

    // Fast trace: propagation load
    axon_fast_trace += APs_delivered
    axon_fast_trace *= decay(τ = seconds)

    // Anterograde transport — delivers pre_material to boutons
    transport_rate   = min(axon_structure.transport_capacity,
                           axon_budget × transport_fraction)
    pre_material    += transport_rate × Δt    // boutons receive material
    axon_material   -= transport_rate × Δt   // axon pool depletes
    axon_budget     -= transport_cost × transport_rate × Δt
    // biological basis: kinesin moves cargo at ~1μm/s along microtubules
    //                   costs ATP per step (kinesin ATPase)

    // Possible tagging
    if axon_fast_trace > eligibility_threshold:
        axon_possible_tagging += axon_fast_trace
    axon_possible_tagging *= decay(τ = seconds)

    // Dopamine decays
    dopamine_local *= decay(τ = hundreds_of_ms)

    // Tag
    if dopamine_local > dopamine_threshold and
       axon_possible_tagging > tagging_threshold:
        axon_tag += dopamine_local × axon_possible_tagging
    axon_tag *= decay(τ = hours)

    // Refuel from soma budget + local astrocyte
    axon_budget += soma_budget × axon_fuel_fraction
    axon_budget += astro_lactate × axon_astro_fraction
    // biological basis: soma mitochondria supply axon proximally
    //                   local astrocytes supply along shaft distally
```

---

## ASTRO | CONTEXT: CONTINUOUS

```
scope DAY | context CONTINUOUS:

    // ROOT energy production: glycolysis from vascular glucose
    astro_budget    += glycolysis(vascular_glucose_supply) × Δt
    // hard cap: vascular_glucose_supply (FIXED) — cannot be exceeded
    // biological basis: glucose → lactate via glycolysis in astrocyte cytoplasm

    // Lactate export to neuronal compartments
    astro_lactate    = min(astro_budget × lactate_export_fraction,
                           vascular_glucose_supply × max_export_fraction)
    astro_budget    -= astro_lactate
    deliver(astro_lactate → pre_budget × pre_fraction,
                            post_budget × post_fraction,
                            dend_budget × dend_fraction,
                            axon_budget × axon_fraction)
    // biological basis: lactate released into ECS → absorbed by MCT2 on neurons
    //                   neurons convert lactate → pyruvate → TCA → ATP

    // Glutamate clearance — rate set by astro_structure (READ)
    clearance        = astro_structure.EAAT_density × glutamate × Δt
    glutamate       -= clearance
    astro_budget    -= clearance × EAAT_ATP_cost
    // biological basis: EAAT cotransports 3 Na⁺ per glutamate → NaK pump cost

    // Overflow detection and D-serine release
    if glutamate > spillover_threshold:
        astro_fast_trace += mGluR5_Ca_influx()
        // biological basis: spillover activates mGluR5 → Gq → PLC → IP3
        //                   → Ca²⁺ release from ER → Ca²⁺-dependent exocytosis

        // D-serine release: proportional to fast trace, material + budget limited
        D_serine_released = min(proportional_to(astro_fast_trace),
                                astro_material.D_serine_precursor,
                                astro_budget × Ds_fraction)
        astro_material   -= D_serine_released × precursor_cost
        astro_budget     -= D_serine_released × synthesis_cost
        astro_D_serine   += D_serine_released
        // biological basis: serine racemase converts L-serine → D-serine
        //                   costs ATP, consumes serine from astro_material

        // Simultaneous presynaptic brake (cross-compartment, no astro budget cost)
        Ca_drive_pre     *= mGluR_brake_factor
        // biological basis: spillover also activates mGluR2/3 on PRE → Gi →
        //                   suppresses VGCC — brakes release at source

        // Possible tagging
        if astro_fast_trace > eligibility_threshold:
            astro_possible_tagging += astro_fast_trace
        astro_possible_tagging *= decay(τ = seconds)

        // Dopamine decays
        dopamine_local *= decay(τ = hundreds_of_ms)

        // Tag
        if dopamine_local > dopamine_threshold and
           astro_possible_tagging > tagging_threshold:
            astro_tag += dopamine_local × astro_possible_tagging
        astro_tag *= decay(τ = hours)

    astro_fast_trace *= decay(τ = seconds)

    // Global overload: circuit breaker
    if astro_fast_trace > OVERLOAD_threshold:
        trigger(shockwave_lockdown)
        // biological basis: global Ca²⁺ wave → GABA + ATP release
        //                   mass AMPA internalization, hyperpolarization

    // Tonic D-serine baseline — set by astro_structure (READ)
    astro_D_serine += astro_structure.D_serine_tonic × Δt
    astro_budget   -= astro_structure.D_serine_tonic × tonic_synthesis_cost
    astro_material -= astro_structure.D_serine_tonic × tonic_precursor_cost
    // biological basis: constitutive racemase activity maintains baseline
    //                   D-serine availability independent of overflow events
```

---

## Special Case — Shockwave Lockdown (any scope)

```
scope DAY or NIGHT | context OVERLOAD:

    // Emergency — bypasses budget gates
    // Biological basis: global astrocytic Ca²⁺ wave →
    //                   GABA release → hyperpolarization
    //                   ATP release → purinergic inhibition
    post_fast_trace  = 0
    Vm               = HYPERPOLARIZED
    AMPA_occupancy   = mass_internalization()   // returned to post_material reserve
    post_material   += recovered_AMPA
    axon_fast_trace += overdrive_cluster()      // VGCC clustering beneath AZ
    astro_budget    -= emergency_cost           // large deduction — territory depleted
```

---
---

# SCOPE: NIGHT
Structural variables WRITTEN. Budgets replenished. Tags evaluated and cleared.

---

## Step 1 — Replenish Budgets and Material

```
scope NIGHT | step 1:

    // Astrocyte replenishes first — it fuels everything
    astro_budget   += overnight_glycolysis(vascular_glucose_supply) × Δt_night
    astro_material += astrocyte_cellbody_synthesis() × Δt_night
    // biological basis: astrocyte protein synthesis overnight
    //                   replenishes EAAT, racemase, ECM proteins, process cytoskeleton

    // Soma replenishes from own mitochondria — self-fueled
    soma_budget    += overnight_mitochondria_output() × Δt_night

    // Soma material production peaks in NIGHT — driven by soma_tag magnitude
    soma_material  += CREB_driven_synthesis(soma_tag) × Δt_night
    // biological basis: CREB → Arc, BDNF, GluA1, scaffold proteins
    //                   peaks during slow-wave sleep replay

    // Soma ships material to downstream compartments
    dend_material  += soma_material × dend_delivery_fraction
    axon_material  += soma_material × axon_delivery_fraction
    soma_material  -= (dend_delivery_fraction + axon_delivery_fraction) × soma_material

    // Downstream budgets refilled from soma and astrocyte
    dend_budget    += astro_lactate × dend_fraction
                   + soma_budget × soma_to_dend_fraction
    pre_budget     += astro_lactate × pre_fraction
    post_budget    += astro_lactate × post_fraction
    axon_budget    += soma_budget × soma_to_axon_fraction
                   + astro_lactate × axon_fraction
```

---

## Step 2 — Structural Commits (Parallel, Independent per Compartment)

```
scope NIGHT | step 2:

    // Each compartment commits independently based on its own tag
    // No global AND gate — coherence emerges from shared DAY events
    // COHERENCE BONUS: if all tags SET simultaneously → amplified commit
    all_aligned = (pre_tag > tag_expiry_threshold and
                   post_tag > tag_expiry_threshold and
                   astro_tag > tag_expiry_threshold)
    coherence_bonus = all_aligned ? coherence_factor : 1.0

    // ── PRE COMMIT ──────────────────────────────────────────────────────
    if pre_tag > tag_expiry_threshold:
        Δpre   = min(AZ_expansion_cost,
                     pre_material,
                     pre_budget × pre_structural_fraction)
        pre_structure  += Δpre × coherence_bonus   // STRUCTURE WRITTEN
        pre_material   -= Δpre                     // material consumed
        pre_budget     -= Δpre × structural_ATP_cost
        if Δpre < AZ_expansion_cost:
            queue(pre_deficit → next NIGHT)         // deficit deferred
        // biological basis: RIM + Munc13 incorporation → new docking slots
        //                   VGCC clustering → tighter Ca²⁺-release coupling
        // LTD: passive decay if maintenance not met (see step 3)

    // ── POST COMMIT ─────────────────────────────────────────────────────
    if post_tag > tag_expiry_threshold:
        Δpost  = min(AMPA_insertion_cost,
                     post_material,
                     post_budget × post_structural_fraction)
        post_structure += Δpost × coherence_bonus  // STRUCTURE WRITTEN
        post_material  -= Δpost                    // material consumed
        post_budget    -= Δpost × structural_ATP_cost
        if Δpost < AMPA_insertion_cost:
            queue(post_deficit → next NIGHT)
        // biological basis: CaMKII anchors AMPA receptors into PSD scaffold
        //                   actin polymerization enlarges spine head
        //                   new anchoring slots created — not just slots filled

    // ── DEND COMMIT ─────────────────────────────────────────────────────
    if dend_tag > tag_expiry_threshold:
        Δdend  = min(branch_expansion_cost,
                     dend_material,
                     dend_budget × dend_structural_fraction)
        dend_structure += Δdend × coherence_bonus  // STRUCTURE WRITTEN
        dend_material  -= Δdend
        dend_budget    -= Δdend × structural_ATP_cost
        if Δdend < branch_expansion_cost:
            queue(dend_deficit → next NIGHT)
        // biological basis: mitochondria incorporation → local ATP ceiling raised
        //                   cytoskeletal reinforcement → better bAP propagation
        //                   mRNA pool expanded → more local translation capacity

    // ── SOMA COMMIT ─────────────────────────────────────────────────────
    if soma_tag > tag_expiry_threshold:
        Δsoma  = min(soma_expansion_cost,
                     soma_material,
                     soma_budget × soma_structural_fraction)
        soma_structure += Δsoma                    // STRUCTURE WRITTEN
        soma_material  -= Δsoma
        soma_budget    -= Δsoma × structural_ATP_cost
        // biological basis: ion channel density increase at axon initial segment
        //                   ribosome biogenesis → synthesis ceiling raised
        //                   CREB machinery expansion

    // ── AXON COMMIT ─────────────────────────────────────────────────────
    if axon_tag > tag_expiry_threshold:
        Δaxon  = min(axon_expansion_cost,
                     axon_material,
                     axon_budget × axon_structural_fraction)
        axon_structure += Δaxon                    // STRUCTURE WRITTEN
        axon_material  -= Δaxon
        axon_budget    -= Δaxon × structural_ATP_cost
        if Δaxon < axon_expansion_cost:
            queue(axon_deficit → next NIGHT)
        // biological basis: myelination density increase
        //                   motor protein pool expansion
        //                   microtubule stabilization

    // ── ASTRO COMMIT ────────────────────────────────────────────────────
    if astro_tag > tag_expiry_threshold:
        Δastro = min(process_retraction_cost,
                     astro_material,
                     astro_budget × astro_structural_fraction)
        astro_structure += Δastro × coherence_bonus // STRUCTURE WRITTEN
        astro_material  -= Δastro                   // ECM proteins + cytoskeleton consumed
        astro_budget    -= Δastro × structural_ATP_cost
        if Δastro < process_retraction_cost:
            queue(astro_deficit → next NIGHT)
        // biological basis: process retraction → perisynaptic_distance ↓
        //                   ECM secretion (Glypicans, Thrombospondins) → cleft sealed
        //                   racemase upregulation → D_serine_tonic ↑
        //                   EAAT density increase → clearance ceiling ↑
        // SELF-REINFORCING: astro_structure ↑ → future signals more contained
        //                                     → future D-serine higher
        //                                     → future LTP easier
```

---

## Step 3 — Passive Depotentiation (Resource Conservation)

```
scope NIGHT | step 3:

    // Potentiation is the primary drive.
    // Depotentiation is its shadow — a consequence of finite resources.
    // Structures decay at a baseline rate.
    // Decay is overcome only if maintenance allocation is sufficient.
    // Maintenance draws from what remains AFTER potentiation has taken its share.

    remaining_material = total_material - material_consumed_by_potentiation
    remaining_budget   = total_budget   - budget_consumed_by_potentiation

    maintenance_per_synapse = remaining_material / total_synapse_count

    for each synapse:
        // Structural decay — passive, continuous
        pre_structure  -= structural_decay_rate × Δt_night
        post_structure -= structural_decay_rate × Δt_night
        dend_structure -= structural_decay_rate × Δt_night
        astro_structure -= structural_decay_rate × Δt_night

        // Maintenance allocation — overcomes decay if resources available
        if maintenance_per_synapse >= maintenance_cost:
            pre_structure  += maintenance_pre
            post_structure += maintenance_post
            dend_structure += maintenance_dend
            astro_structure += maintenance_astro
            // decay fully compensated — structure stable

        else:
            // maintenance_per_synapse < maintenance_cost
            // partial compensation only — structure drifts downward
            // THIS IS DEPOTENTIATION BY NEGLECT — no active signal required
            // the synapse is not told to weaken
            // it simply does not receive enough to stay where it is
            pre_structure  += maintenance_per_synapse × pre_fraction
            post_structure += maintenance_per_synapse × post_fraction
            // net: structure slowly declines toward lower baseline

    // LTD material recovery: dismantled proteins returned to pools
    // This enriches the remaining pool and partially benefits other synapses
    for each synapse where net_structure_change < 0:
        recovered = structure_loss × recycling_fraction
        pre_material  += recovered × pre_fraction
        post_material += recovered × post_fraction
        astro_material += recovered × astro_fraction × recycling_fraction
        // biological basis: ubiquitin-proteasome degradation → amino acids recycled
        //                   internalized receptors → endosomal reserve
        //                   dismantled AZ proteins → axonal pool
```

---

## Step 4 — Homeostatic Scaling

```
scope NIGHT | step 4:

    // If soma fired too much overall during DAY — global downscale
    if soma_tag > homeostatic_ceiling:
        scale_factor = homeostatic_ceiling / soma_tag
        for each synapse:
            post_structure *= scale_factor     // STRUCTURE WRITTEN
            pre_structure  *= scale_factor     // STRUCTURE WRITTEN
        // biological basis: global AMPA downscaling during sleep
        //                   relative differences preserved — absolute excitability restored
        // material recovery: scaled-down proteins returned to soma_material
        soma_material += sum(structure_reduction) × recycling_fraction
```

---

## Step 5 — Clear All Traces

```
scope NIGHT | step 5:

    // FAST_TRACEs: already decayed during DAY — confirm zero
    pre_fast_trace   = 0
    post_fast_trace  = 0
    dend_fast_trace  = 0
    soma_fast_trace  = 0
    axon_fast_trace  = 0
    astro_fast_trace = 0

    // POSSIBLE_TAGGING: decayed during DAY — confirm zero
    pre_possible_tagging   = 0
    post_possible_tagging  = 0
    dend_possible_tagging  = 0
    soma_possible_tagging  = 0
    axon_possible_tagging  = 0
    astro_possible_tagging = 0

    // TAGS: explicitly cleared after commit
    // Tags above expiry threshold carry forward to next NIGHT (multi-night consolidation)
    if pre_tag   < tag_expiry_threshold: pre_tag   = 0
    if post_tag  < tag_expiry_threshold: post_tag  = 0
    if dend_tag  < tag_expiry_threshold: dend_tag  = 0
    if soma_tag  < tag_expiry_threshold: soma_tag  = 0
    if axon_tag  < tag_expiry_threshold: axon_tag  = 0
    if astro_tag < tag_expiry_threshold: astro_tag = 0
    // Tags above threshold: partial commit ran, deficit queued,
    // remaining tag persists to next NIGHT for completion
```

---

## Summary of Energy and Material Relations

```
ENERGY FLOW:
    vascular_glucose_supply (FIXED)
        → astro_budget (glycolysis)
            → astro_lactate → pre_budget, post_budget, dend_budget, axon_budget
        → soma_budget (own mitochondria — independent of astrocyte)
            → axon_budget (partial)
            → dend_budget (partial, via organelle delivery)

MATERIAL FLOW:
    soma (CREB synthesis)
        → soma_material
            → dend_material (shipping during DAY NOT_AP + NIGHT)
                → post_material (local delivery to spines)
            → axon_material (shipping during DAY NOT_AP + NIGHT)
                → pre_material (anterograde transport to boutons)
    astrocyte cell body (local synthesis)
        → astro_material
            → D-serine (consumed in DAY)
            → ECM proteins (consumed in NIGHT)
            → process cytoskeleton (consumed in NIGHT)

RECOVERY FLOWS (LTD → returns material to pools):
    post LTD → AMPA receptors → post_material (local reserve)
    pre LTD  → AZ proteins    → pre_material  (axonal pool)
    astro LTD → ECM fragments → astro_material (partial, recycling_fraction)
```

# Flows

## Energy flow

```
VASCULAR SUPPLY
    → ASTROCYTE CELL BODY
        glucose → lactate (glycolysis)
        → astro_budget (local ATP for clearance, D-serine, ECM, process motility)
        → lactate exported to:
            → pre_budget  (ATP for VGCC, vesicle fusion, VATPase)
            → post_budget (ATP for NaK pump, AMPA trafficking, actin)
            → dend_budget (ATP for bAP propagation, local translation)
        
    → SOMA
        soma has own mitochondria — partly self-fueled
        soma_budget (ATP for AP generation, CREB, protein synthesis, shipping)
        → dend_budget top-up (organelle delivery)
        → axon_budget top-up (transport machinery)
```

## Material flow

```
SOMA
    protein synthesis (CREB-driven, peaks in NIGHT)
    → soma_material (receptors, scaffold proteins, organelles, mRNA)
        → dend_material (branch receives proteins + mRNA from soma)
            → post_material (spine receives receptors + actin from branch)
        → axon_material (boutons receive AZ proteins + VGCCs from soma via axon)
            → pre_material (bouton active zone proteins)

ASTROSYNAPSE
    ECM proteins synthesized in astrocyte cell body
    → astro_material (Glypicans, Thrombospondins, serine for D-serine)
        → cleft environment (ECM sealing, D-serine availability)
```
