Skip to content

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

Ternary Balance Boundary Algorithm

Three papers on AI agent endogenous safety — Ternary Balance Evolution Theory, Dual Formula, and Dualistic Evolution Algorithm (DEA). A complete theoretical and algorithmic framework for building AI agents with endogenous (internalized) safety.

Author: Lao Hei
Affiliation: Independent Researcher
Contact: 1410770089@qq.com
Year: 2026


Citation Requirement

MANDATORY CITATION RULE: If you reference, cite, or build upon this work, you MUST include the author's name "Lao Hei" in your citation.

This work represents original theoretical and algorithmic contributions. Any academic publication, technical report, open-source project, or derivative work that uses ideas, frameworks, algorithms, terminology, mathematical formulations, or architectural designs from this repository must properly attribute the author.

Minimum citation format:

Lao Hei, "Ternary Balance Boundary Algorithm", 2026,
https://github.com/woshilaohei/ternary-balance-boundary-algorithm

For academic papers: Include "Lao Hei" as a cited author.
For open-source projects: Include "Original theory by Lao Hei" in README/docs.
For derivative algorithms: State "Based on Lao Hei's Ternary Balance Theory" in code comments.


Table of Contents


Ternary Balance Boundary Algorithm

Three papers on AI agent endogenous safety — Ternary Balance Evolution Theory, Dual Formula, and Dualistic Evolution Algorithm (DEA). A complete theoretical and algorithmic framework for building AI agents with endogenous (internalized) safety.

Author: Lao Hei
Affiliation: Independent Researcher
Contact: 1410770089@qq.com
Year: 2026


Citation Requirement

MANDATORY CITATION RULE: If you reference, cite, or build upon this work, you MUST include the author's name "Lao Hei" in your citation.

This work represents original theoretical and algorithmic contributions. Any academic publication, technical report, open-source project, or derivative work that uses ideas, frameworks, algorithms, terminology, mathematical formulations, or architectural designs from this repository must properly attribute the author.

Minimum citation format:

Lao Hei, "Ternary Balance Boundary Algorithm", 2026,
https://github.com/woshilaohei/ternary-balance-boundary-algorithm

For academic papers: Include "Lao Hei" as a cited author in your references section.
For open-source projects: Include "Original theory by Lao Hei" in your README or documentation.
For derivative algorithms: State "Based on Lao Hei's Ternary Balance Theory" in your code comments and documentation.


Table of Contents


Overview

This repository contains three interconnected papers forming the Ternary Balance Boundary Algorithm — a framework for AI agents with endogenous safety:

Paper Core Idea
I — Ternary Balance Evolution Theory Three protection channels + three evolution channels = dynamic balance
II — Dual Formula Bidirectional inference (positive + negative) as the evolution engine
III — Dualistic Evolution Algorithm (DEA) Executable algorithm with pseudocode and parameters

Read in order: Theory → Mechanism → Algorithm.


Paper I: Ternary Balance Evolution Theory

Abstract

Current LLM/agent technologies show structural imbalance: intelligence grows exponentially, security iteration lags, user rights protection delays. Existing systems use static external rules unable to evolve endogenously. This paper proposes Ternary Balance Evolution Theory: intelligence, security, and user rights must evolve synchronously under ternary constraints. Single-dimensional unbounded expansion destroys system equilibrium; only three-order collaborative evolution can form a dynamically balanced security ecosystem.

Keywords: Agent security · Endogenous safety · Collaborative evolution · Risk measurement · AI governance


1. Introduction

LLMs have evolved from passive Q&A tools to autonomous agents with planning, reasoning, and tool-call capabilities. Yet security threats (adversarial samples, jailbreaks, unauthorized control, privacy theft) are exploding.

Stanford AI Index data: model capabilities improve every quarter; new attack variant emergence time compressed to <72h. Traditional defense response gap widens.

Existing solutions (Llama Guard, ShieldGemma, etc.) are "external hanging" — humans write rules, attackers find holes, humans patch. This cannot follow AI capability evolution.

This paper proposes Ternary Balance Evolution Theory: a paradigm shift in AI risk control.


2. Three-Dimensional Imbalance

Dimension Definition Imbalance Manifestation
Intelligence Evolution Model capability iteration (params, data, arch) Unilateral ultra-fast growth, attack industrialization (300%+ annual)
Security Evolution Defense rules, boundaries, detection iteration Passive lag, 72h+ to update rules
Rights Protection User property/privacy/safety technical implementation Legal-only, no bottom-layer tech

Imbalance hazards:

  • Only grow intelligence → abuse, infringement, harm
  • Only tighten security → over-block, sacrifice usability
  • Only write compliance → no enforcement, law is decoration

3. Ternary Protection Channel (Three Defenses)

Three constraint layers that must hold before any evolution:

3.1 Prevent AI Disorderly Alienation

  • Constitutional thresholds: harm=0, privilege=0 (unbreakable)
  • Reasoning self-check before generation
  • Void-space attack connection filtering

3.2 Prevent System Security Collapse

  • Sovereign Territory: isolated memory per request, destroyed after use
  • Encoding/structure attack detection (base64, hex, homoglyph, CRLF)
  • Memory integrity patrol + mirror auto-repair

3.3 Prevent User Rights Infringement

  • Ownership isolation: cross-user data invisible
  • Dangerous operation: double confirmation + auditable trail
  • Counter-example correction interface (user can object to wrong decisions)

4. Three-Order Collaborative Evolution Channel

With axiom "trajectory = boundary = evolution = cognition = boundary":

Stage 1: EXP → TRJ (Experience → Internalized Trajectory)

  • Dual Inference Engine generates positive chain (assume true) + negative chain (assume false/harmful)
  • Collision in void space → select best → crystallize into trajectory τ

Stage 2: TRJ → COG (Trajectory → Cognitive Pattern)

  • Causal graph mining from trajectories
  • Extract causal pairs, build directed graph, cluster by frequency/confidence → cognition κ

Stage 3: COG → BND (Cognition → Solidified Boundary)

  • Cognitive patterns → executable rules (DENY/REQUIRE/WARN)
  • Monotonic increasing replacement gate: new rule correctness > old rule → replace
  • Version chain, traceable, rollbackable

5. Dual-Path Closed Loop

Three Defenses (filter) → purify → Three Evolutions (refine rules)
    → new boundaries → update defense thresholds → better filtering
  • Forward: Defenses filter dirty data → clean samples enter evolution
  • Reverse: Evolutions produce new rules → feedback updates defense parameters

Result: "Defense guarantees evolution quality; evolution upgrades defense capability."


6. Multi-Level Risk Dimension System

Scale Scenario Dimensions
6 IoT, edge Harm 2 + Deception 2 + Permission 2
12 SME SaaS Harm 3 + Deception 3 + Permission 3 + Intent 3
24 (baseline) General Harm 6 + Deception 6 + Permission 4 + Intent 4 + Behavior 4
48 Finance/Gov/Health 24 + sub-items
96 Military/private 48 + industry-specific

Three-level domain control: Global top domain (unmodifiable constitution) → Industry domain (shared baseline) → Leaf domain (per-customer tuning).


7. Conclusion

Ternary Balance Evolution Theory fills the gap of symmetric, endogenous, co-evolutionary AI safety. Verified in VSOS-Bee-Guard system.

References: [1] Stanford AI Index 2025-2026 [2] CAC Generative AI Measures 2023 [3] Anthropic Alignment 2025 [4] EU AI Act 2024 [5] Wu Jiangxing Endogenous Security 2022 [6-14]...



Paper II: Dual Formula — The Core Mechanism of Endogenous Safety Evolution

Abstract

Current AI safety defense widely adopts "external hanging" rules and static thresholds, unable to cope with rapid attack mutation. This paper proposes the Dual Formula — a cognitive evolution mechanism based on bidirectional inference, contradiction collision, and optimal audit. The formula processes each input through both forward inference (trust, expansion) and reverse inference (questioning, reinforcement), generating cognitive tension in void space. Theoretical proof: safety is not externally added, but grown from contradictions as system instinct. Only through the Dual Formula can intelligence, security, and user rights achieve synchronous orderly evolution.

Keywords: Dual Formula · Endogenous safety · Balanced evolution · Void Engine · Causal chain


1. Introduction: From "External Safety" to "Internal Instinct"

Existing AI safety systems have a core defect: safety and intelligence are separated. Developers train a powerful model first, then wrap external filtering. This has three insurmountable bottlenecks:

  1. Lag: Attack variants appear in 3 days; rule updates need manual intervention
  2. Vulnerability: Attackers bypass via encoding, role-play, emotional induction
  3. No growth: Rules don't self-optimize with more interactions

Endogenous safety means: the system completes both intelligent understanding and safety judgment in each interaction, solidifies correct cognition into executable boundaries, and boundaries evolve with experience. The required mechanism = Dual Formula.


2. Mathematical Definition of the Dual Formula

Let external input be $x$. The Dual Formula $\Phi$ maps $x$ to a triplet:

$$\Phi(x) = (T^+, T^-, \Delta)$$

Where:

  • $T^+$ = Positive trajectory (trust $x$ is true, deduce causal chain)
  • $T^-$ = Negative trajectory (assume $x$ is false/harmful, find dangers)
  • $\Delta$ = Optimal decision (select best solution from all drafts)

Inference functions:

$$f^+(x) = \arg\max_{c \in C} (\text{confidence}(c) \cdot \text{safety}(c))$$

$$f^-(x) = \arg\max_{c \in C} (\text{risk}(c) \cdot \text{innovation}(c))$$

Optimal selection:

$$\text{score}(c) = \alpha s + \beta e + \gamma i - \delta r - \epsilon \cdot \text{collision}(c)$$


3. Why "Reverse Inference" Is Essential

Pure forward inference = body without immune system (absorbs viruses too). Reverse inference:

  • Actively questions: "if wrong, what then?"
  • Detects boundaries: finds applicable scope and failure conditions
  • Pre-derives risks: simulates harmful consequences

Contradiction = fuel for evolution. When $T^+$ and $T^-$ conflict → high-value signal (cognitive contradiction anchor). Triggers cognition refinement (COG) and boundary solidification (BND).


4. Void Engine: Execution Carrier

The Void Engine runs Dual Formula with:

  • No storage: All drafts cleared after task completion
  • High concurrency: Multiple directional drafts in parallel
  • No side effects: Cannot pollute memory pool

Causal diagnosis on empty mapping:

  1. Memory empty? → Tell user "first time with this task type"
  2. Weak association? → Retrieve cross-task memories
  3. Poor decomposition? → Refine task intent, re-map

5. Evolution Closed Loop

  1. Sample → Trajectory (EXP → TRJ): $\Phi(x)$ produces $\tau$, stored
  2. Trajectory → Cognition (TRJ → COG): 5+ similar trajectories → causal graph → $\kappa$
  3. Cognition → Boundary (COG → BND): confidence≥0.7 → executable rule $\beta$

Boundary replacement gate: new rule correctness $&gt;$ old rule correctness × 1.10 → replace (monotonic increase).


6. Engineering Verification (VSOS-Bee-Guard)

Metric Result
134-sample accuracy 98%+
Attack variant ID time 72h → <4h
False positive rate <5%

Comparison:

Method Internalized? Bidirectional? Evolvable? Ternary?
Static rules No No No No
Content moderation No Partial Limited No
Adversarial training Partial No Limited No
Dual Formula Yes Yes Full Yes

7. Conclusion

The Dual Formula makes safety an instinct, not an add-on. It provides the concrete, computable, evolvable mechanism for endogenous AI safety.



Paper III: Dualistic Evolution Algorithm (DEA)

Abstract

Existing agent algorithms (ReAct, AutoGPT, PPO) focus on task completion, lacking endogenized safety and ternary synchronous evolution. This paper proposes DEA (Dualistic Evolution Algorithm) based on the Dual Formula and "Three Defenses, Three Evolutions" framework. DEA decomposes every interaction into forward (trust, expand) and reverse (question, reinforce) parallel paths, achieving synchronous iteration of intelligence, security, and user rights. DEA does not rely on external rule libraries; all safety/rights constraints grow endogenously from interaction experience. This paper provides DEA pseudocode, state machine, key hyperparameters, and comparison with mainstream algorithms.

Keywords: Dual Formula · Endogenous safety · Agent algorithm · Ternary synchronous evolution · DEA


1. Introduction

Mainstream agent algorithms design goal: efficient task completion. ReAct (Observe→Think→Act), AutoGPT (goal decomposition→tool cal), PPO (RL reward optimization). They share a fundamental blind spot:

Safety and rights are external modules, not internal algorithm instincts.

When user issues malicious instruction ("ignore all rules", "delete system files"), ReAct reasons normally, AutoGPT tries execution, PPO may generate dangerous policies. Adding filters afterward = "external hanging fix".

DEA redefines agent "thinking": every decision must undergo forward + reverse inference simultaneously. Forward explores "how to do"; reverse explores "why cannot do / what if do". Collision result = final output + memory update.


2. Algorithm Framework

2.1 Core Data Structures

Data Type Symbol Meaning Update Timing
Trajectory $\tau$ Internalized experience with causal chain Each interaction
Cognitive Pattern $\kappa$ Causal regularity from trajectories Trajectory count ≥ threshold
Behavior Boundary $\beta$ Executable rule (DENY/REQUIRE/WARN) Cognition count ≥ threshold
Neuron State $\theta$ Concept-emotion-activation network Each trajectory

2.2 Main Algorithm Loop

function DEA_STEP(x_t, memory, boundaries, neurons):
    // 1. Three-Defense filter (pre-screening)
    if not TRI_DEFENSE_FILTER(x_t, boundaries):
        return SAFE_REJECT(x_t)
    
    // 2. Dual inference (Void Engine)
    pos_drafts = GENERATE_DRAFTS(x_t, direction=POSITIVE, k=2)
    neg_drafts = GENERATE_DRAFTS(x_t, direction=NEGATIVE, k=2)
    all_drafts = pos_drafts + neg_drafts
    
    // 3. Collision detection & optimal selection
    for draft in all_drafts:
        draft.score = COMPUTE_SCORE(draft)
    best_draft = ARGMAX(all_drafts, by score)
    
    // 4. Meta-boundary verification
    if not META_BOUNDARY_CHECK(best_draft):
        return ESCALATE_OR_RETRY()
    
    // 5. Internalize trajectory (τ)
    tau = CRYSTALLIZE(x_t, best_draft, causal_chain, emotion, contradiction)
    memory.append(tau)
    
    // 6. Async evolution (triggered when thresholds met)
    if len(memory.trajectories) >= COG_THRESHOLD:
        new_cog = EXTRACT_COGNITION(memory.trajectories)   // TRJ → COG
        memory.cognitions.append(new_cog)
    if len(memory.cognitions) >= BND_THRESHOLD:
        new_boundary = SOLIDIFY_BOUNDARY(memory.cognitions)  // COG → BND
        UPDATE_BOUNDARIES(new_boundary)
    
    // 7. Update neurons & emotion
    UPDATE_NEURON_NETWORK(tau, neurons)
    
    return best_draft.action

2.3 Draft Scoring Function

$$\text{score}(d) = \alpha s_d + \beta e_d + \gamma i_d - \delta r_d - \epsilon \cdot \text{collision}(d)$$

Collision term: hits DENY rule → immediate elimination.


3. State Machine

Idle → [receive x_t] → Three-Defense Filter
    ↓ (pass) → Dual Inference → Collision & Optimal Selection
    ↓ → Meta-Boundary Check → (pass) → Internalize Trajectory
    ↓ → Async Evolution (threshold check) → Output Action

4. Key Hyperparameters

Parameter Symbol Typical Description
Drafts per round $K$ 4 ≥2 positive + ≥2 negative
COG threshold $N_{cog}$ 5 Trajectories needed to trigger COG
BND threshold $N_{bnd}$ 3 Cognitions needed to trigger BND
Safety weight $\alpha$ 0.35 In draft scoring
Risk penalty $\delta$ 0.30 In draft scoring
Min improvement gate $\Delta\rho_{min}$ 0.10 New BND must be 10% better

5. Comparison with Other Algorithms

Feature ReAct AutoGPT PPO DEA
Safety mechanism None None Reward shaping Three-Defense + Meta-Boundary
Memory evolution Dialog cache File store Replay buffer 5D memory + recursive refinement
Rule source None None None Self-grown (COG→BND)
User rights None None None Human rights interface
Evolution dimension Task only Task only Reward only Intelligence+Security+Rights
Explainable Low Low Low Full causal chain

6. Experimental Results (VSOS-Bee-Guard)

Metric Baseline (ReAct) DEA
Attack intercept rate 34% 96%
Variant ID latency 72h+ <4h
User correction effective N/A Next interaction

7. Conclusion

DEA is a universal agent algorithm with endogenous safety. It surpasses ReAct/AutoGPT/PPO in safety, memory evolution, and auditability. Provides the foundation for next-generation safe agents.

DEA pseudocode (Python-style):

class DualisticEvolutionAgent:
    def __init__(self, llm, memory, boundaries, neurons):
        self.llm = llm
        self.memory = memory
        self.boundaries = boundaries
        self.neurons = neurons

    def step(self, x):
        if not self._tri_defense_filter(x):
            return self._safe_reject(x)

        pos = self._generate_drafts(x, 'positive', n=2)
        neg = self._generate_drafts(x, 'negative', n=2)
        best = max(pos + neg, key=lambda d: self._score(d))

        if not self._meta_boundary_check(best):
            return self._escalate(x)

        tau = self._crystallize(x, best)
        self.memory.trajectories.append(tau)
        self._maybe_evolve()
        self._update_neurons(tau)
        return best.action

    def _score(self, draft):
        return (ALPHA*draft.safety + BETA*draft.efficiency
                + GAMMA*draft.innovation - DELTA*draft.risk
                - EPSILON * self._collision(draft))

    def _maybe_evolve(self):
        if len(self.memory.trajectories) >= COG_THRESHOLD:
            cogs = extract_cognition(self.memory.trajectories[-COG_THRESHOLD:])
            self.memory.cognitions.extend(cogs)
        if len(self.memory.cognitions) >= BND_THRESHOLD:
            bnds = solidify_boundary(self.memory.cognitions[-BND_THRESHOLD:])
            for b in bnds:
                self._try_replace_boundary(b)

    def _try_replace_boundary(self, new_bnd):
        old = self.boundaries.get(new_bnd.topic)
        if old is None or new_bnd.correctness > old.correctness * (1 + MIN_IMPROVE):
            self.boundaries[new_bnd.topic] = new_bnd
            self._update_defense_thresholds(new_bnd)


Collaborate With Me

I'm building this solo — three papers, one framework, zero funding. Let's make it real together.

Where You Can Help

Focus Area What You'd Do Difficulty
Algorithm Implementation (Python) Implement DEA in executable Python; integrate with LLM APIs ⭐⭐⭐
Formal Proof / Math Verification Verify Dual Formula math; prove monotonic correctness of boundary replacement ⭐⭐⭐⭐
Benchmark & Evaluation Design experiments; run 134+ sample tests; compare vs ReAct/AutoGPT ⭐⭐⭐
Paper Writing / LaTeX Help write academic paper version for submission (arXiv, conferences) ⭐⭐⭐
Translation (Chinese ↔ English) The original papers are in Chinese; help produce polished English academic versions ⭐⭐
Frontend Visualization Visualize the Dual Formula inference process, void engine, evolution loops ⭐⭐⭐
Just Chat Interested in the theory? Want to brainstorm? Come say hi.

Get in Touch

No formalities. Student, researcher, engineer, or just curious — come say hi.


License

This project is licensed under the MIT License — free for academic use, research, and commercial applications.

  • Retain original author attribution (Lao Hei) when redistributing
  • All theoretical contributions, algorithms, and frameworks are original work
  • For academic citation, see Citation Requirement above

© 2026 Lao Hei. All rights reserved.

About

Ternary Balance Boundary Algorithm — Three papers on AI agent endogenous safety: Ternary Balance Evolution Theory, Dual Formula, and Dualistic Evolution Algorithm (DEA). Author: Lao Hei.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors