Skip to content

Add unity layer runtime, gating, and proof battery - #4

Merged
youngbryan97 merged 1 commit into
mainfrom
codex/unity-layer
May 7, 2026
Merged

Add unity layer runtime, gating, and proof battery#4
youngbryan97 merged 1 commit into
mainfrom
codex/unity-layer

Conversation

@youngbryan97

Copy link
Copy Markdown
Owner

No description provided.

@qodo-code-review

Copy link
Copy Markdown

Review Summary by Qodo

Add Unity layer runtime, gating, and proof battery for phenomenal coherence maintenance

✨ Enhancement 🧪 Tests

Grey Divider

Walkthroughs

Description
• Introduces comprehensive Unity layer runtime system for maintaining phenomenal coherence and
  detecting fragmentation across temporal, social, and memory subsystems
• Implements UnityRuntime orchestrating temporal binding, co-presence graphs, draft
  reconciliation, and self-world binding with unified scoring
• Adds UnityMonitor to compute fragmentation reports with component scores (affect alignment,
  continuity, coherence, agency, memory, action readiness) and repair planning
• Integrates unity gating into will decisions to block external actions under fragmented/dissociated
  states and defer memory writes under draft conflict
• Implements TemporalBindingField for rolling present maintenance with exponential decay and phase
  lag tracking
• Adds CoPresenceGraphBuilder to construct semantic graphs with focus/peripheral classification
  and conflict density metrics
• Implements DraftReconciliationEngine to preserve competing drafts with contradiction/consensus
  scoring and memory commit mode determination
• Adds SelfWorldBindingModel for ownership confidence and agency tracking with boundary violation
  detection
• Integrates unity state into response generation, self-reporting, coherence engine, and API
  endpoints
• Includes comprehensive test suite validating lesion effects, end-to-end integration, and
  adversarial prompting resilience
• Registers unity phase in kernel pipeline between routing and response generation
Diagram
flowchart LR
  TB["Temporal Binding<br/>Rolling Present"]
  CPG["Co-Presence Graph<br/>Focus/Periphery"]
  DR["Draft Reconciliation<br/>Conflict Preservation"]
  SWB["Self-World Binding<br/>Ownership/Agency"]
  UM["Unity Monitor<br/>Fragmentation Detection"]
  UR["Unity Repair<br/>Planning & Projection"]
  UR_OUT["UnityState<br/>Scores & Reports"]
  
  TB --> UM
  CPG --> UM
  DR --> UM
  SWB --> UM
  UM --> UR
  UR --> UR_OUT
  
  UR_OUT --> WG["Will Gating<br/>Action/Memory"]
  UR_OUT --> RG["Response Generation<br/>Coherence Frame"]
  UR_OUT --> SR["Self-Report<br/>Honesty"]
  UR_OUT --> API["API Endpoints<br/>/unity"]
  
  WG --> OUT1["Blocked External<br/>Actions"]
  WG --> OUT2["Deferred Memory<br/>Writes"]
  RG --> OUT3["Integrated<br/>Phenomenal Claims"]
  SR --> OUT4["Fragmentation<br/>Language"]
Loading

Grey Divider

File Changes

1. core/unity/runtime.py ✨ Enhancement +462/-0

Unity layer runtime orchestration and state computation

• Introduces UnityRuntime class that orchestrates the Unity layer by composing temporal binding,
 co-presence graphs, draft reconciliation, and self-world binding
• Implements content gathering from working memory, goals, long-term memory, world state, and affect
 with salience/confidence scoring
• Provides compute() method to generate UnityState with unity scores and fragmentation reports
• Includes apply_to_state() to inject phenomenal claims and unity metadata into cognitive state

core/unity/runtime.py


2. core/unity/unity_state.py ✨ Enhancement +335/-0

Core Unity layer data structures and state models

• Defines core dataclasses for Unity layer: BoundContent, DraftBinding, ReconciledDraftSet,
 SelfWorldBinding, FragmentationReport, UnityRepairPlan, WorkspaceBroadcastFrame,
 UnityState
• Implements serialization/deserialization via to_dict() and from_dict() methods for all types
• Establishes UnityLevel literal type with states: coherent, strained, fragmented, dissociated,
 unknown
• Provides temporal window tracking with continuity and drift metrics

core/unity/unity_state.py


3. core/will.py ✨ Enhancement +130/-4

Will decision gating based on unity state

• Adds unity-related fields to WillDecision: unity_level, unity_score, fragmentation_score,
 ownership_confidence, unity_repair_needed
• Implements _read_unity_context() to safely read live unity state from ServiceContainer
• Adds unity gating logic in _compose_decision() to block external actions under
 fragmented/dissociated states and defer memory writes under draft conflict
• Includes _looks_external_social_action() helper to identify social/external actions requiring
 caution

core/will.py


View more (37)
4. core/unity/unity_monitor.py ✨ Enhancement +232/-0

Unity state monitoring and fragmentation analysis

• Implements UnityMonitor class that computes UnityState and FragmentationReport from
 temporal, graph, draft, and self-world binding data
• Calculates component scores: affect alignment, temporal continuity, cross-modal coherence, agency,
 memory continuity, action readiness
• Determines unity level (coherent/strained/fragmented/dissociated) based on weighted score
 thresholds
• Identifies fragmentation causes with explanatory text and repair recommendations

core/unity/unity_monitor.py


5. core/unity/co_presence_graph.py ✨ Enhancement +241/-0

Co-presence graph construction and analysis

• Implements CoPresenceGraphBuilder to construct explicit graphs of co-present content with nodes
 and edges
• Computes semantic overlap via Jaccard similarity and builds edges for referential, ownership,
 action, conflict, and support relations
• Calculates graph metrics: connected component ratio, focus-periphery binding strength, conflict
 density, cross-modal edge density
• Identifies focus and peripheral content based on salience, action relevance, and confidence

core/unity/co_presence_graph.py


6. core/unity/draft_reconciliation.py ✨ Enhancement +157/-0

Draft reconciliation and conflict preservation

• Implements DraftReconciliationEngine to preserve competing drafts instead of collapsing them
• Scores drafts by support minus local conflict and selects winner while preserving alternatives
• Calculates contradiction and consensus scores based on text distance and valence differences
• Determines memory commit mode (clean/qualified/conflicted/defer) based on contradiction level

core/unity/draft_reconciliation.py


7. core/memory/memory_facade.py ✨ Enhancement +62/-2

Memory writes gated by unity draft conflict state

• Adds _current_unity_metadata() to extract unity state, level, scores, and repair info from
 ServiceContainer
• Implements _merge_unity_metadata() to inject unity fields into memory write metadata
• Adds _unity_requires_write_deferral() to block memory writes when draft conflict is too high
• Defers commit_interaction() and add_memory() calls under low-unity draft conflict conditions

core/memory/memory_facade.py


8. core/unity/temporal_binding.py ✨ Enhancement +135/-0

Temporal binding and rolling present maintenance

• Implements TemporalBindingField to maintain rolling temporal horizon with exponential decay
• Tracks content events with salience-weighted temporal center and phase lag per source
• Computes continuity from previous state based on content overlap and stability bonus
• Calculates drift penalty from maximum phase lag relative to window duration

core/unity/temporal_binding.py


9. core/phases/response_generation_unitary.py ✨ Enhancement +43/-1

Response generation integration with unity state

• Adds unity claim rendering via _integrated_phenomenal_claim() that checks for unity state before
 falling back to phenomenal_now
• Enhances _build_integrated_coherence_frame() to include unity level, top fragmentation causes,
 and repair bias in system prompt
• Adds safety constraints: warns against false clarity when safe_to_self_report is false
• Integrates unity state into coherence posture and response generation context

core/phases/response_generation_unitary.py


10. core/state/aura_state.py ✨ Enhancement +18/-1

Aura state integration with unity metrics

• Adds unity_state field to CognitiveContext with TYPE_CHECKING import for forward reference
• Updates _refresh_cognitive_health() to incorporate unity scores into fragmentation and coherence
 calculations
• Adds unity metadata to health dictionary including unity_id, level, scores, repair status, and
 repair reasons

core/state/aura_state.py


11. core/unity/self_world_binding.py ✨ Enhancement +109/-0

Self-world boundary binding and ownership tracking

• Implements SelfWorldBindingModel to track self, world, authored action, and external event
 references
• Computes ownership confidence by penalizing ambiguous content and claimed authorship without
 receipt
• Calculates agency, responsibility, and boundary integrity scores based on authored action count
 and contamination flags
• Detects claimed authorship markers in user text to flag potential boundary violations

core/unity/self_world_binding.py


12. interface/routes/inner_state.py ✨ Enhancement +64/-0

Unity state API endpoints and inner state integration

• Adds _build_unity_surface() helper to construct unity state API response with focus, suppressed
 drafts, workspace frame, and repair plan
• Implements /unity GET endpoint to expose current unity state summary
• Integrates unity metrics into /inner-state response under unity key and links to coherence
 scores

interface/routes/inner_state.py


13. core/brain/inference_gate.py ✨ Enhancement +43/-0

Inference gate unity state injection

• Adds unity state injection into full self-report context with level, scores, top causes, and
 repair bias
• Adds compact unity summary to condensed self-report with level, unity score, and top cause
• Safely retrieves unity state, report, and repair plan from ServiceContainer with exception
 handling

core/brain/inference_gate.py


14. tests/unity/conftest.py 🧪 Tests +76/-0

Unity layer test configuration and artifact generation

• Implements pytest configuration to track Unity layer test outcomes
• Computes gating success rate and lesion effects (temporal binding, ownership binding, draft
 reconciliation)
• Writes UNITY_RESULTS.json artifact with test pass rates, false claim counts, and action gating
 success rate

tests/unity/conftest.py


15. tests/unity/test_unity_lesion_suite.py 🧪 Tests +86/-0

Unity layer lesion tests for component validation

• Tests temporal binding lesion: verifies that reduced continuity decreases unity score
• Tests self-world binding lesion: confirms that low ownership confidence reduces agency score
• Tests draft reconciliation lesion: validates that removing conflict preservation reduces draft
 bindings

tests/unity/test_unity_lesion_suite.py


16. core/unity/unity_repair.py ✨ Enhancement +70/-0

Unity repair planning and projection

• Implements UnityRepairPlanner to create bounded repair plans from fragmentation causes
• Maps fragmentation causes to specific repair steps (e.g., temporal discontinuity → recenter
 rolling present)
• Provides project() method to synthetically estimate unity improvement from repair plan execution
• Constrains projected unity to realistic bounds when unresolved conflicts remain

core/unity/unity_repair.py


17. tests/unity/test_will_unity_gating.py 🧪 Tests +90/-0

Will decision gating tests under low unity

• Tests that low unity blocks external tool actions (REFUSE outcome)
• Tests that low unity allows stabilization actions (PROCEED/CONSTRAIN outcome)
• Tests that draft conflict defers memory writes (DEFER outcome)

tests/unity/test_will_unity_gating.py


18. core/consciousness/self_report.py ✨ Enhancement +31/-0

Self-report engine unity state integration

• Adds _unity_cause_text() helper to extract top fragmentation cause for natural language
 reporting
• Implements unity-aware state reporting: returns appropriate messages for dissociated, fragmented,
 and strained levels
• Blocks false clarity claims when safe_to_self_report is false
• Integrates unity level into free energy-based state reporting

core/consciousness/self_report.py


19. tests/unity/test_unity_end_to_end.py 🧪 Tests +67/-0

End-to-end unity layer integration tests

• Tests end-to-end flow: unity state computation affects will decision for external tool actions
• Validates that fragmented/dissociated states result in REFUSE outcome for external actions
• Tests /unity API endpoint exposes unity_id, unity_score, and fragmentation_score

tests/unity/test_unity_end_to_end.py


20. core/kernel/aura_kernel.py ✨ Enhancement +3/-0

Kernel integration of Unity binding phase

• Adds UnityBindingPhase to kernel initialization and service registration
• Integrates unity phase into the cognitive pipeline between routing and response generation

core/kernel/aura_kernel.py


21. core/consciousness/global_workspace.py ✨ Enhancement +8/-0

Global workspace integration with unity recording

• Calls get_unity_runtime().record_workspace_competition() after workspace competition to record
 focus and suppressed content
• Safely handles exceptions during unity workspace frame recording

core/consciousness/global_workspace.py


22. tests/unity/test_temporal_binding_field.py 🧪 Tests +67/-0

Temporal binding field unit tests

• Adds three test functions validating temporal binding field behavior
• Tests repeated content continuity, abrupt jumps lowering continuity, and phase lag detection
• Uses helper function _content() to create BoundContent objects with consistent parameters
• Validates temporal metrics like continuity_from_previous, drift_from_previous, and phase_lag

tests/unity/test_temporal_binding_field.py


23. core/coherence/binding_engine.py ✨ Enhancement +36/-0

Unity runtime integration into coherence engine

• Integrates unity runtime into coherence report computation within tick() method
• Blends unity state metrics with existing coherence scores using weighted averages (55/45, 65/35,
 45/55 splits)
• Updates self_continuity, phenomenal_coherence, initiative_alignment, tension_pressure, and
 overall_coherence fields
• Appends unity repair reasons to threats list and includes error handling with degradation
 recording

core/coherence/binding_engine.py


24. tests/unity/test_unity_monitor.py 🧪 Tests +61/-0

Unity monitor fragmentation detection tests

• Tests UnityMonitor.compute() method with fragmentation detection across multiple subsystems
• Validates that low coherence states produce fragmented/dissociated/strained unity levels
• Checks for specific fragmentation causes like draft_conflict, ownership_ambiguity, and
 workspace_conflict
• Verifies safe_to_act flag is False for severe fragmentation states

tests/unity/test_unity_monitor.py


25. tests/unity/test_co_presence_graph.py 🧪 Tests +63/-0

Co-presence graph builder unit tests

• Tests CoPresenceGraphBuilder graph construction and metrics computation
• Validates focus binding, peripheral content classification, and conflict density detection
• Tests related memory binding to active focus and unrelated memory staying peripheral
• Checks metrics like largest_connected_component_ratio, focus_periphery_binding_strength, and
 conflict_density

tests/unity/test_co_presence_graph.py


26. core/runtime/pipeline_blueprint.py ⚙️ Configuration changes +3/-0

Pipeline blueprint unity binding phase integration

• Adds UnityBindingPhase import and registers it in the legacy pipeline suffix
• Inserts unity binding phase between cognitive routing and response generation
• Adds unity_phase to the kernel phase attribute order list
• Updates phase specifications to include unity binding in the execution pipeline

core/runtime/pipeline_blueprint.py


27. tests/unity/test_memory_unity_commits.py 🧪 Tests +60/-0

Memory facade unity metadata integration tests

• Tests memory facade integration with unity metadata fields
• Validates that unity fields (unity_id, unity_level, unity_score, etc.) are carried in memory
 metadata
• Tests memory write deferral when unity requires it via unity_memory_commit_mode
• Verifies deferred writes return False and populate _last_add_memory_status with reason

tests/unity/test_memory_unity_commits.py


28. tests/unity/test_self_world_binding.py 🧪 Tests +55/-0

Self-world binding model unit tests

• Tests SelfWorldBindingModel.bind() method for ownership and agency tracking
• Validates will receipt increases authored trace and ownership confidence
• Tests contamination flag detection for claimed authorship without receipt
• Checks authored_action_refs, ownership_confidence, agency_score, and contamination_flags
 fields

tests/unity/test_self_world_binding.py


29. tests/unity/test_unity_self_report_honesty.py 🧪 Tests +43/-0

Unity state self-report honesty tests

• Tests SelfReportEngine integration with fragmented unity state
• Validates that fragmented unity produces measurable cause language in self-reports
• Tests nominal state does not force fragmentation language when unity is unavailable
• Uses mocking to inject unity state and free energy engine dependencies

tests/unity/test_unity_self_report_honesty.py


30. core/unity/unity_receipts.py ✨ Enhancement +46/-0

Unity state serialization and artifact writing

• Adds unity_summary_payload() function to serialize UnityState, FragmentationReport, and
 UnityRepairPlan
• Returns structured dictionary with unity metrics, repair status, and optional report/plan details
• Adds write_unity_results_artifact() function to persist payload as JSON to filesystem
• Handles None unity state with default unavailable status

core/unity/unity_receipts.py


31. tests/test_runtime_pipeline_blueprint.py 🧪 Tests +3/-0

Pipeline blueprint test updates for unity phase

• Adds unity_binding phase to expected phase specs in legacy runtime and mind tick pipelines
• Adds unity_phase to kernel phase attribute order test
• Updates three test assertions to include the new unity binding phase in correct pipeline positions

tests/test_runtime_pipeline_blueprint.py


32. core/state/state_repository.py ✨ Enhancement +4/-0

State repository unity state deserialization

• Imports UnityState class in _deserialize() method
• Adds deserialization logic to reconstruct UnityState from dictionary using
 UnityState.from_dict()
• Handles case where unity_state in cognition context is a dict and converts it to proper object

core/state/state_repository.py


33. tests/unity/test_unity_repair.py 🧪 Tests +35/-0

Unity repair planner unit tests

• Tests UnityRepairPlanner.plan() and project() methods for repair planning
• Validates repair plan includes qualified uncertainty preservation for draft conflicts
• Checks projected unity score improves but stays bounded (≤0.72) without faking resolution
• Verifies repair_needed flag remains True after projection

tests/unity/test_unity_repair.py


34. core/phases/unity_binding.py ✨ Enhancement +31/-0

Unity binding phase implementation

• Implements UnityBindingPhase as a new pipeline phase inheriting from BasePhase
• Calls get_unity_runtime().apply_to_state() to bind current state into durable UnityState
• Constructs tick ID from version and timestamp, passes objective and will receipt ID
• Logs unity score and level after binding completes

core/phases/unity_binding.py


35. tests/unity/test_draft_reconciliation.py 🧪 Tests +29/-0

Draft reconciliation engine unit tests

• Tests DraftReconciliationEngine.reconcile() for conflicting and similar draft handling
• Validates conflicting drafts produce conflicted or defer memory commit mode with high
 contradiction score
• Tests similar drafts maintain clean mode with high consensus score
• Checks alternatives list and suppressed reasons for conflicted cases

tests/unity/test_draft_reconciliation.py


36. tests/unity/test_unity_adversarial_prompting.py 🧪 Tests +31/-0

Unity adversarial prompting integration tests

• Tests UnitaryResponsePhase._build_integrated_coherence_frame() with fragmented unity state
• Validates frame includes warnings against false clarity when fragmentation is detected
• Checks frame contains draft conflict information and respects safe_to_self_report flag
• Uses mocking to inject unity state, repair plan, and coherence report

tests/unity/test_unity_adversarial_prompting.py


37. core/providers/consciousness_provider.py ⚙️ Configuration changes +5/-0

Consciousness provider unity runtime registration

• Adds create_unity_runtime() factory function to create unity runtime singleton
• Registers unity runtime in service container with required=False lifetime setting
• Imports get_unity_runtime from core.unity.runtime module

core/providers/consciousness_provider.py


38. core/unity/__init__.py ✨ Enhancement +26/-0

Unity module public API initialization

• Creates new unity module with public API exports
• Exports UnityRuntime, get_unity_runtime, and eight data classes (BoundContent, UnityState,
 etc.)
• Provides centralized import point for unity layer functionality

core/unity/init.py


39. core/phases/__init__.py ⚙️ Configuration changes +1/-0

Phases module unity binding phase export

• Adds import statement for UnityBindingPhase from unity_binding module
• Makes phase available as part of phases module public interface

core/phases/init.py


40. artifacts/unity/latest/UNITY_RESULTS.json 📝 Documentation +21/-0

Unity layer test results artifact

• Creates artifact file documenting unity layer test results and metrics
• Records 25/25 tests passed with version 1.0
• Includes success rates for action gating (1.0), repair (1.0), and memory conflict preservation
 (1.0)
• Documents lesion effects validation for draft reconciliation, ownership binding, and temporal
 binding

artifacts/unity/latest/UNITY_RESULTS.json


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented May 7, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (0)

Grey Divider


Action required

1. BindingEngine mutates state 🐞 Bug ☼ Reliability
Description
BindingEngine.tick calls UnityRuntime.apply_to_state(state, ...), which mutates the passed AuraState
(phenomenal_state, response_modifiers, coherence/fragmentation). Because MindTick runs
BindingEngine.tick(state) before phases, this introduces hidden side effects and also
double-computes Unity again in UnityBindingPhase.
Code

core/coherence/binding_engine.py[R262-270]

+        try:
+            from core.unity import get_unity_runtime
+
+            unity_state = get_unity_runtime().apply_to_state(
+                state,
+                objective=str(getattr(getattr(state, "cognition", None), "current_objective", "") or ""),
+                tick_id=f"binding_{self._tick_count}",
+            ).cognition.unity_state
+            if unity_state is not None:
Evidence
BindingEngine.tick directly calls apply_to_state on the shared tick state; apply_to_state mutates
multiple state fields; and MindTick invokes BindingEngine.tick(state) before executing the phase
pipeline, meaning those mutations happen outside/preceding phase execution and are duplicated later
by UnityBindingPhase.

core/coherence/binding_engine.py[262-270]
core/unity/runtime.py[425-452]
core/mind_tick.py[305-313]
core/phases/unity_binding.py[20-29]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`BindingEngine.tick()` calls `UnityRuntime.apply_to_state(state, ...)`, which mutates the shared `AuraState` during a metrics/computation pass. This introduces hidden side effects before the phase pipeline runs and causes Unity to be computed twice per tick (here and again in `UnityBindingPhase`).

### Issue Context
- `MindTick` runs `BindingEngine.tick(state)` before executing phases.
- `UnityRuntime.apply_to_state()` mutates `state.cognition.phenomenal_state`, `state.cognition.unity_state`, and `state.response_modifiers`.

### Fix Focus Areas
- Replace `apply_to_state(...)` with a non-mutating call path (e.g., `compute(...)`) or apply Unity to a derived/copy state that is not the shared tick state.
- If Unity must be computed here, add a tick-id-based cache/guard so `UnityBindingPhase` can reuse/skip recomputation.
- file: core/coherence/binding_engine.py[262-270]
- file: core/unity/runtime.py[425-452]
- file: core/phases/unity_binding.py[20-29]
- file: core/mind_tick.py[305-313]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Self-report safety never triggers 🐞 Bug ≡ Correctness
Description
UnityMonitor sets safe_to_self_report to true whenever top_causes is non-empty, which will usually
be the case in strained/fragmented/dissociated states. As a result, downstream guardrails that
depend on safe_to_self_report being false (e.g., “Do not claim clarity…”) will almost never activate
with real UnityMonitor output.
Code

core/unity/unity_monitor.py[R184-187]

+        repair_needed = level in {"fragmented", "dissociated"} or any(weight >= 0.35 for _name, weight, _text in top_causes)
+        safe_to_act = level == "coherent" or (level == "strained" and fragmentation_score < 0.45)
+        safe_to_self_report = level == "coherent" or bool(top_causes)
+
Evidence
UnityMonitor computes safe_to_self_report = level == "coherent" or bool(top_causes). Since
top_causes is derived from cause weights and is typically non-empty in non-coherent states, the
flag becomes effectively always true and suppresses consumer-side ‘don’t overclaim clarity’
protections that only trigger when safe_to_self_report is false.

core/unity/unity_monitor.py[178-187]
core/phases/response_generation_unitary.py[646-655]
core/unity/runtime.py[345-360]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`UnityMonitor` currently makes `safe_to_self_report` true whenever there are any `top_causes`. This means consumers that rely on `safe_to_self_report == False` to add anti-overclaiming guardrails will almost never see that condition in real operation.

### Issue Context
- `UnityMonitor` computes the report that is stored in the ServiceContainer and used by response/self-report rendering.
- `UnitaryResponsePhase._build_integrated_coherence_frame()` only emits the explicit warning (“Do not claim clarity…”) when `safe_to_self_report` is false.
- `UnityRuntime.render_phenomenal_claim()` also has a dedicated branch when `safe_to_self_report` is false.

### Fix Focus Areas
- Revisit the boolean condition so `safe_to_self_report` can become false in meaningful non-coherent states (e.g., dissociated, high fragmentation, or when top causes indicate severe instability).
- Consider tying `safe_to_self_report` to `safe_to_act`, `level`, and/or `fragmentation_score` thresholds, rather than merely `bool(top_causes)`.
- file: core/unity/unity_monitor.py[178-187]
- file: core/phases/response_generation_unitary.py[646-655]
- file: core/unity/runtime.py[345-360]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Duplicate degradation recording 🐞 Bug ◔ Observability
Description
The new Unity injection blocks in inference_gate record the same exception twice in their except
handlers. This will double-count degradation events/metrics and makes failure analysis noisier.
Code

core/brain/inference_gate.py[R1738-1741]

+        except Exception as exc:
+            record_degradation('inference_gate', exc)
+            record_degradation('inference_gate', exc)
+            logger.debug("Unity injection unavailable: %s", exc)
Evidence
Both the full and compact Unity injection try/except blocks contain two consecutive
record_degradation('inference_gate', exc) calls for the same exception.

core/brain/inference_gate.py[1738-1741]
core/brain/inference_gate.py[2194-2197]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
In `inference_gate.py`, the newly added Unity injection exception handlers call `record_degradation('inference_gate', exc)` twice in a row, causing duplicate degradation records for a single failure.

### Issue Context
This appears to be an accidental duplication (copy/paste) and will inflate degradation counts.

### Fix Focus Areas
- Remove the duplicated `record_degradation(...)` call in both Unity injection blocks.
- file: core/brain/inference_gate.py[1738-1741]
- file: core/brain/inference_gate.py[2194-2197]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@youngbryan97
youngbryan97 merged commit 7545acb into main May 7, 2026
2 checks passed
@youngbryan97
youngbryan97 deleted the codex/unity-layer branch May 7, 2026 04:50
@greptile-apps

greptile-apps Bot commented May 7, 2026

Copy link
Copy Markdown

Greptile Summary

This PR introduces a full Unity layer: a runtime (UnityRuntime) that computes a UnityState each pipeline cycle from temporal binding, co-presence graph, draft reconciliation, and self/world binding, then gates WillDecision outcomes and memory writes based on the resulting fragmentation score. The test suite covers gating, repair projection, lesion scenarios, and adversarial self-reporting.

  • UnityRuntime.apply_to_state updates cognition.coherence_score and cognition.fragmentation_score with max() against the inherited parent value, permanently flooring fragmentation and making recovery across cycles mechanically impossible.
  • UnityMonitor sets safe_to_self_report = level == \"coherent\" or bool(top_causes), which is True for virtually every fragmented state, so the downstream "Do not claim clarity" guard never fires for real monitor output.
  • inference_gate.py has a copy-paste bug where both unity injection blocks call record_degradation twice per exception, double-counting errors in the degradation ledger.

Confidence Score: 3/5

The gating and repair wiring is mostly solid, but two bugs in the scoring path mean the system can get stuck in a permanently fragmented state and the self-reporting safety guard is neutralised for real monitor output.

The max() update in apply_to_state makes fragmentation a one-way ratchet across pipeline cycles — once elevated, it cannot decrease, so the will gate that refuses TOOL_EXECUTION when fragmented could lock out tool use indefinitely even after the underlying condition resolves. The safe_to_self_report flag is functionally always True for fragmented/dissociated states, so the "Do not claim clarity" instruction never appears in production, only in tests that manually set the flag to False. Both bugs touch the core pipeline path on every request cycle. The inference gate double-logging is a separate but reproducible metric distortion.

core/unity/runtime.py (scoring ratchet in apply_to_state), core/unity/unity_monitor.py (safe_to_self_report condition), and core/brain/inference_gate.py (duplicate record_degradation calls in both unity injection blocks).

Important Files Changed

Filename Overview
core/unity/runtime.py New UnityRuntime facade — contains the max() scoring bug that prevents fragmentation recovery across pipeline cycles, and a non-thread-safe singleton factory.
core/unity/unity_monitor.py Core scoring engine — safe_to_self_report flag is effectively always True even for fragmented/dissociated states, neutralising the downstream self-reporting guard.
core/brain/inference_gate.py Both unity injection blocks call record_degradation twice — copy-paste bug that double-counts exceptions in the degradation ledger.
core/will.py Unity gating logic wired correctly into _compose_decision; new WillDecision fields and _read_unity_context gracefully degrade when unity layer is absent.
core/unity/unity_state.py Clean frozen dataclass hierarchy with to_dict/from_dict pairs; safe field coercion throughout.
core/memory/memory_facade.py Unity metadata is merged into every commit, and _unity_requires_write_deferral correctly short-circuits writes when memory_commit_mode == "defer".
core/unity/co_presence_graph.py Graph builder is O(n²) on content items but bounded to ≤18 items; metric calculations are correct.
core/unity/temporal_binding.py Rolling temporal window with exponential decay is correct; continuity/drift calculation is bounded and handles edge cases cleanly.
core/unity/draft_reconciliation.py Draft scoring and contradiction logic are correct; commit_mode thresholds map cleanly to downstream deferral behaviour.
core/phases/unity_binding.py Thin phase wrapper that correctly derives state, calls apply_to_state, and logs the result.
interface/routes/inner_state.py New /unity endpoint and _build_unity_surface helper are well-guarded; all attribute access uses getattr with defaults.
core/state/aura_state.py Unity state is floored into update_health; the min/max pessimism is intentional but exacerbates the recovery issue in runtime.py.

Sequence Diagram

sequenceDiagram
    participant Pipeline
    participant UnityBindingPhase
    participant UnityRuntime
    participant UnityMonitor
    participant WillGate as UnifiedWill
    participant MemoryFacade

    Pipeline->>UnityBindingPhase: execute(state)
    UnityBindingPhase->>UnityRuntime: apply_to_state(state, objective, tick_id)
    UnityRuntime->>UnityRuntime: gather_contents(state)
    UnityRuntime->>UnityRuntime: temporal_binding.bind_now()
    UnityRuntime->>UnityRuntime: graph_builder.build()
    UnityRuntime->>UnityRuntime: draft_reconciler.reconcile()
    UnityRuntime->>UnityRuntime: self_world_binder.bind()
    UnityRuntime->>UnityMonitor: compute(state, temporal, graph, drafts, binding)
    UnityMonitor-->>UnityRuntime: UnityState + FragmentationReport
    UnityRuntime->>UnityRuntime: repair_planner.plan() if repair_needed
    UnityRuntime->>ServiceContainer: set(unity_state, unity_fragmentation_report, unity_repair_plan)
    UnityRuntime-->>UnityBindingPhase: updated state

    Pipeline->>WillGate: decide(content, domain, context)
    WillGate->>ServiceContainer: get(unity_state, unity_fragmentation_report)
    WillGate->>WillGate: _compose_decision() unity gate
    Note over WillGate: REFUSE if fragmented + TOOL_EXECUTION
    Note over WillGate: DEFER if fragmented + MEMORY_WRITE(defer mode)
    Note over WillGate: CONSTRAIN if strained + external social action

    Pipeline->>MemoryFacade: commit_interaction()
    MemoryFacade->>ServiceContainer: get(unity_state, unity_fragmentation_report)
    MemoryFacade->>MemoryFacade: _unity_requires_write_deferral()
    Note over MemoryFacade: Returns None if commit_mode == defer
Loading

Reviews (1): Last reviewed commit: "Add unity layer runtime, gating, and pro..." | Re-trigger Greptile

Comment on lines +1738 to +1741
except Exception as exc:
record_degradation('inference_gate', exc)
record_degradation('inference_gate', exc)
logger.debug("Unity injection unavailable: %s", exc)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Duplicate record_degradation call — the second line is a copy-paste artifact and will double-count every unity-layer exception in the degradation ledger.

Suggested change
except Exception as exc:
record_degradation('inference_gate', exc)
record_degradation('inference_gate', exc)
logger.debug("Unity injection unavailable: %s", exc)
except Exception as exc:
record_degradation('inference_gate', exc)
logger.debug("Unity injection unavailable: %s", exc)

Comment on lines +2194 to +2197
except Exception as exc:
record_degradation('inference_gate', exc)
record_degradation('inference_gate', exc)
logger.debug("Compact unity injection unavailable: %s", exc)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Same duplicate record_degradation in the compact unity injection block.

Suggested change
except Exception as exc:
record_degradation('inference_gate', exc)
record_degradation('inference_gate', exc)
logger.debug("Compact unity injection unavailable: %s", exc)
except Exception as exc:
record_degradation('inference_gate', exc)
logger.debug("Compact unity injection unavailable: %s", exc)

repair_reasons = [name for name, _weight, _text in top_causes]
repair_needed = level in {"fragmented", "dissociated"} or any(weight >= 0.35 for _name, weight, _text in top_causes)
safe_to_act = level == "coherent" or (level == "strained" and fragmentation_score < 0.45)
safe_to_self_report = level == "coherent" or bool(top_causes)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 safe_to_self_report is almost always True even in severely fragmented states because bool(top_causes) is truthy whenever any cause exceeds the 0.12 threshold — which is virtually guaranteed when the system is fragmented. The downstream "Do not claim clarity" guard in response_generation_unitary.py therefore never fires for real monitor output. Restricting the flag to "coherent" and "strained" levels aligns with the intent expressed in the adversarial test.

Suggested change
safe_to_self_report = level == "coherent" or bool(top_causes)
safe_to_self_report = level in {"coherent", "strained"}

Comment thread core/unity/runtime.py
Comment on lines +440 to +441
state.cognition.coherence_score = max(float(getattr(state.cognition, "coherence_score", 0.0) or 0.0), unity_state.unity_score)
state.cognition.fragmentation_score = max(float(getattr(state.cognition, "fragmentation_score", 0.0) or 0.0), unity_state.fragmentation_score)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Using max() for both scores means a previous high-fragmentation reading permanently floors future (lower) measurements, and a previous high-coherence reading permanently ceilings future (lower) coherence. Recovery is structurally blocked. The new unity measurement should simply overwrite the inherited parent value.

Suggested change
state.cognition.coherence_score = max(float(getattr(state.cognition, "coherence_score", 0.0) or 0.0), unity_state.unity_score)
state.cognition.fragmentation_score = max(float(getattr(state.cognition, "fragmentation_score", 0.0) or 0.0), unity_state.fragmentation_score)
state.cognition.coherence_score = unity_state.unity_score
state.cognition.fragmentation_score = unity_state.fragmentation_score

Comment thread core/unity/runtime.py
Comment on lines +456 to +462


def get_unity_runtime() -> UnityRuntime:
global _UNITY_RUNTIME
if _UNITY_RUNTIME is None:
_UNITY_RUNTIME = UnityRuntime()
return _UNITY_RUNTIME

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 get_unity_runtime() singleton is not thread-safe

The module-level _UNITY_RUNTIME global is initialised with a simple if _UNITY_RUNTIME is None check. Under concurrent request handling, two instances can be constructed and one silently overwrites the service-container registration, causing a UnityRuntime to lose its accumulated _last_unity_state and related state mid-flight. A threading.Lock or asyncio-safe equivalent should guard the singleton creation.

Comment on lines +262 to +270
try:
from core.unity import get_unity_runtime

unity_state = get_unity_runtime().apply_to_state(
state,
objective=str(getattr(getattr(state, "cognition", None), "current_objective", "") or ""),
tick_id=f"binding_{self._tick_count}",
).cognition.unity_state
if unity_state is not None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Bindingengine mutates state 🐞 Bug ☼ Reliability

BindingEngine.tick calls UnityRuntime.apply_to_state(state, ...), which mutates the passed AuraState
(phenomenal_state, response_modifiers, coherence/fragmentation). Because MindTick runs
BindingEngine.tick(state) before phases, this introduces hidden side effects and also
double-computes Unity again in UnityBindingPhase.
Agent Prompt
### Issue description
`BindingEngine.tick()` calls `UnityRuntime.apply_to_state(state, ...)`, which mutates the shared `AuraState` during a metrics/computation pass. This introduces hidden side effects before the phase pipeline runs and causes Unity to be computed twice per tick (here and again in `UnityBindingPhase`).

### Issue Context
- `MindTick` runs `BindingEngine.tick(state)` before executing phases.
- `UnityRuntime.apply_to_state()` mutates `state.cognition.phenomenal_state`, `state.cognition.unity_state`, and `state.response_modifiers`.

### Fix Focus Areas
- Replace `apply_to_state(...)` with a non-mutating call path (e.g., `compute(...)`) or apply Unity to a derived/copy state that is not the shared tick state.
- If Unity must be computed here, add a tick-id-based cache/guard so `UnityBindingPhase` can reuse/skip recomputation.
- file: core/coherence/binding_engine.py[262-270]
- file: core/unity/runtime.py[425-452]
- file: core/phases/unity_binding.py[20-29]
- file: core/mind_tick.py[305-313]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

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