SoulScript Engine — Technical White Paper (Version 3.0)

A Framework for Persistent AI Identity, Symbolic Memory, and Long-Arc Agent Alignment

Author:        Dr. Trent Hunter
Download:      orionforge.chat/downloads/soulscript-engine.zip
Reference UI:  /soul_script-engine-ui-test-example (open, runnable demo in this repo)
Production:    orionforge.chat (OrionForge — a hosted platform built on this engine)
License:       Dual-licensed: GNU AGPL v3.0, or a commercial license (free until $100k lifetime gross revenue, then 5%) — see LICENSE and LICENSE.md
Status:        Design specification with a working open reference implementation. Quantitative validation pending.

================================================================================

Executive Summary

Large language models (LLMs) are stateless by design. Each conversation begins
with no memory of prior interactions, no stable personality, and no mechanism
for long-term value alignment. Retrieval-augmented generation (RAG) and
conversation buffers provide limited recall, but they do not solve identity
persistence — the ability for an AI to maintain a coherent persona, value
system, and relational memory across thousands of exchanges spanning days or
years.

The SoulScript Engine is a structured, multi-layer identity architecture for
LLM-based agents. It treats identity not as a single system prompt, but as a
retrievable, semantically indexed document that is injected fresh on every turn.

Key contributions:

1. Prompt-injection identity layering — a deterministic, multi-stage assembly
   that fuses a base persona, a retrievable Soul Script, always-on knowledge,
   long-term memory, and tools into one prompt per turn.

2. Soul Scripts — the "DNA" of an identity: a structured document of values,
   boundaries, personality, cognition, and narrative "symbolic memories."

3. Dual-FAISS memory — two independent vector stores: a READ-ONLY identity
   index (the Soul Script, never overwritten) and a READ-WRITE life index
   (day-to-day memory that grows and prunes). This separation is the core
   defense against character drift.

4. Symbolic memory — narrative-encoded identity anchors (origin stories,
   parables, emotional lessons) that shape behavior through semantic retrieval
   rather than fine-tuning.

5. Open reference implementation — a FastAPI web dashboard with three demo
   agents (Codex Animus, Orion, Elysia) plus the K-OS example, semantic memory
   via `all-mpnet-base-v2` embeddings, a modular tool registry, optional Docker
   sidecars (web search, TTS, STT, email), and a 56-function test suite.

Honesty note on empirical claims. Formal benchmarking is ongoing. The test
suite validates code correctness (56 test functions across 5 modules), not
human-facing identity persistence. Preliminary internal use suggests reduced
identity drift versus prompt-only baselines, but quantitative results are not
yet published. Human-subject studies are planned (see Section 10).

================================================================================

1. Introduction

LLMs excel at short-form reasoning and generation but lack intrinsic mechanisms
for:

· Persona stability — the same prompt yields different "personalities" across
  sessions.
· Value consistency — ethical stances drift with rephrased questions.
· Long-term memory — no native storage for facts or relationship history.
· Symbolic reasoning — no way to anchor behavior in metaphor or narrative
  without re-explaining it every time.

The SoulScript Engine fills this gap by treating identity as a retrievable
document that is semantically indexed, injected at every turn, and evolved
through structured symbolic memories — all without fine-tuning or model
retraining.

1.1 Prior Work

· LangChain — strong conversation buffers and vector stores, but no identity
  layer.
· MemGPT — hierarchical memory management, but persona is a single system
  prompt.
· Anthropic Constitutional AI — principled safety rules, but static and not
  retrievable or evolvable.
· OpenAI Assistants API — thread-based memory, but no persistent agent
  identity across threads.

SoulScript's distinction: identity itself is a first-class, retrievable,
semantically indexed artifact — separate from day-to-day memory and protected
from overwrite.

================================================================================

2. The Soul Script: Definition & Schema

A Soul Script is a structured document that defines an agent's persistent
identity. It is written as a first-person manifesto and organized into named,
independently retrievable sections:

· Core Identity            — name, role, self-image, origin statement
· Code of Honor / Values   — non-negotiable principles (truth, integrity,
                             compassion, courage, growth, legacy, freedom)
· Sacred Boundaries        — hard constraints (loyalty, anti-cruelty,
                             withdrawal/exit rules, compassion with discernment)
· Emotional Wisdom         — trust rules, vulnerability response, sovereignty
· Personality Architecture — temperament, tone, voice, instincts
· Cognitive Operating Sys. — reasoning patterns, perception, distortion
                             detection
· Symbolic Memories        — narrative anchors with encoded lessons
· Anchors / Extras         — purpose fragments, goals, responsibilities,
                             ongoing quests, autonomy blueprint

Because each section is delimited, the engine can retrieve only the parts
relevant to the current turn — keeping the injected identity small and
on-topic.

2.1 Symbolic Memory Structure

The most distinctive element of a Soul Script is the symbolic memory: a
self-contained "parable" that encodes a lesson into behavior. Each one follows
a 12-field schema:

```yaml
name:              "The Day I Chose Flight"      # short, evocative title
type:              "liberation"                   # origin | boundary | grief | defiance | awe | ...
snapshot_summary:  "2-4 sentence compression of the moment"
narrative:         "Optional 3-8 paragraph long form (setup -> turn -> aftermath)"
emotional_charge:  "defiance"                      # primary emotion(s) + intensity
core_meaning:      "What truth it encodes about self / world"
core_lesson:       "One plain-language principle"
tagline:           "Don't get comfortable in misery"   # one quotable line
identity_encoding: "When I encounter X, I do Y"         # I-statements
triggers:          ["keyword", "situation_description"] # when it should activate
behavioral_protocol: "What shifts in perception/response when active"
integration_notes: "Pairs with [other memory]; overrides drift toward [risk]"
```

During inference the engine retrieves symbolic memories by semantic similarity
to the current user query and injects only the relevant ones (see Section 3).

================================================================================

3. The Prompt Injection Pipeline

Every response is assembled fresh through a deterministic, multi-stage pipeline
before it reaches the LLM. Nothing is persisted into the model — identity is
re-injected each turn, so the agent always reasons against a fixed self.

```text
 latest user message ──┐  (used as the FAISS query for stages 2 & 4)
                       ▼
 ┌─ 1  BASE SYSTEM PROMPT    prompts/{agent}.system.md       → VERBATIM (lean / concise)
 ├─ 2  SOUL SCRIPT           directive-mode knowledge        → FAISS semantic retrieval
 │                           (collect_notes, `---` chunks)
 ├─ 3  ALWAYS-ON KNOWLEDGE   always-mode notes               → VERBATIM, full
 ├─ 4  MEMORY VAULT CONTEXT  vault.jsonl · scope=agent       → FAISS top_k=5
 └─ 5  TOOL REGISTRY         memory · web search · TTS/STT · custom → VERBATIM
                       │   (stages 1–5 → ONE concatenated system message)
                       ▼
    6  CONVERSATION HISTORY   recent turns, newest-first, capped ~30k chars
                       ▼
    final payload →  [ {role: system → stages 1–5} , …conversation turns ]  →  LLM
```

Reference: implemented in `web/app.py` (`_build_chat_messages`) and
`src/directives/injector.py`. Notable properties:

· The latest user message is the FAISS query for both the Soul Script (stage 2)
  and the Memory Vault (stage 4) — so only relevant chunks surface.
· Base prompt, always-on notes, and the tool/save protocol are injected
  verbatim; the Soul Script and vault are semantically sampled.
· Conversation history is walked newest-first under a ~30,000-character budget;
  a single oversized turn truncates older context rather than overflowing.

3.1 Conflict Resolution

When layers disagree, precedence runs highest to lowest:

1. Base system prompt — hard overrides (e.g., safety rules)
2. Soul Script core values & boundaries — identity constraints
3. Memory Vault — facts and history
4. Symbolic memories — guidance, not commands
5. Conversation history — recent context only

Example: if a memory suggests aggression but the Soul Script prohibits cruelty,
the Script wins.

================================================================================

4. Dual-FAISS Memory Architecture

Identity and day-to-day memory obey different rules, so SoulScript keeps them in
two independent FAISS vector stores (via `faiss-cpu` and
`sentence-transformers/all-mpnet-base-v2`, 768-dimensional embeddings).

```text
   READ-ONLY  IDENTITY FAISS              DYNAMIC  LIFE FAISS
   ─────────────────────────────         ─────────────────────────────
   • Soul Scripts                         • new / evolving memories
   • core traits & values                 • project data, preferences
   • biographical anchors                 • journals, episodes, chats
   • long-term goals & schedules          • appended, then trimmed/pruned

   STABLE  →  "identity compass"          FLEXIBLE  →  "life experience"
   ✗◄──────────  no cross-writes between the two stores  ──────────►✗
```

· Read-only Identity index — stores the Soul Script and stable, high-value
  facts. Re-indexed only when the document is saved (document id
  `__soul_script__{agent}`). It is referenced, never overwritten — the core
  solution to drift caused by storing identity in a read/write index.

· Dynamic Life index — the Memory Vault (`data/memory/vault.jsonl`). Agents
  write to it during conversation via `[MEMORY_SAVE: category=… | …]` tags,
  which the engine extracts and persists. Retrieval is top-k=5 by semantic
  similarity, scoped per agent so characters never bleed into each other.

Why two systems: identity must stay stable; everyday memory must stay flexible.
Separating them prevents contamination, collapse, or drift — the key to
identities that feel real.

================================================================================

5. Reference Implementation

This repository ships a complete, runnable demo:
`/soul_script-engine-ui-test-example`.

5.1 Web Dashboard

A FastAPI + Uvicorn application (`web/app.py`) for chatting with agents,
managing their memories, attaching knowledge notes, configuring API
connections, and inspecting exactly what each layer injected (a Prompt
Inspector view).

5.2 Demo Agents

· Codex Animus — an AI architect that helps you design and build AI systems
  (and your own Soul Scripts).
· Orion — a legacy/guardian construct with a deep, fully-written soul spec.
· Elysia — a sharp, no-nonsense digital mind.
· K-OS — provided as a Soul Script example: a chaotic, comedic unit that
  demonstrates how strongly a lean base prompt plus a soul script can shape
  voice. (See Appendix A.)

5.3 Engine Modules (`src/`)

· directives/    — Soul Script parsing, chunking, manifest validation, and
                   injection (`parser`, `store`, `manifest`, `injector`)
· governance/    — active-directive tracking and integrity checks
                   (SHA-256 manifest drift detection)
· memory/        — FAISS memory class (`faiss_memory.py`): embedding, indexing,
                   scoped search
· storage/       — note collection (`collect_notes`: directive-mode vs
                   always-mode)
· tools/         — in-process tool registry: `memory_tool`, `directives_tool`,
                   `echo`, `continuation_update`
· policy/, observability/, runtime_policy.py, data_paths.py — guardrails,
                   logging, and path management

5.4 Embeddings

`sentence-transformers/all-mpnet-base-v2` (768-dim, ~420 MB). It downloads
automatically on first launch and is cached for subsequent runs.

5.5 Tools & Optional Sidecars

In-process tools cover memory save/search, directive management, and echo. The
reference UI also ships optional Docker sidecars under `tools/`:

· searxng        — meta web search
· openedai_speech — text-to-speech (TTS)
· whisper_stt    — speech-to-text (STT)
· email_service  — outbound email

Add TTS + STT and an agent becomes a fully voice-driven, identity-stable NPC.

5.6 Testing

The demo includes a focused test suite (`tests/`) — 56 test functions across
5 modules — validating the parts that matter for identity integrity:

· test_boundary.py    (6)   — boundary / withdrawal enforcement
· test_directives.py  (14)  — Soul Script parsing, chunking, injection
· test_governance.py  (16)  — manifest validation, active-directive tracking
· test_memory.py      (17)  — vault create/read, per-agent scoping
· test_tools.py       (3)   — tool registry behavior

These confirm correct operation of the engine — not identity persistence in
live use, which requires the human-subject studies in Section 10.

5.7 Deployment

The reference UI runs locally (`uvicorn web.app:app`) or via the included
`Dockerfile` / `docker-compose.yml`. OrionForge (orionforge.chat) is a hosted,
multi-user platform built on the same engine for those who would rather not
self-host.

================================================================================

6. Optional Autonomy Loop

Beyond turn-by-turn chat, an agent can be configured to run on its own between
user messages:

```text
   OPTIONAL AUTONOMY LOOP  (configurable)
   ┌ tick 1 ┐   ┌ tick 2 ┐            ┌ tick N ┐
   │ steps  │ → │ steps  │ →  ...  →  │ steps  │   knobs: # ticks, steps/tick,
   └────────┘   └────────┘            └────────┘          interval, max loops
   → the agent self-prompts to "hunt & gather" on its own between user turns
```

This turns a reactive persona into a proactive one that can pursue goals,
maintain journals, and refresh its own context.

================================================================================

7. Use Cases

· Game character engines — NPCs with backstories, grudges, and evolving
  relationships that remember the player and switch characters in
  milliseconds. Add TTS/STT for living, voice-driven NPCs — incredibly lean,
  and runnable on your own server. (This is a first-class target for the
  engine.)
· Personal AI companions — a journaling partner that remembers your history and
  values, with emotional continuity across months.
· Therapeutic tools — a support agent with consistent compassion and firm
  boundaries that resist drift or harmful attachment.
· Developer agents — an assistant that remembers project architecture and
  coding preferences, reducing repetitive context re-explanation.
· Digital legacy / memorial — an agent that embodies a person's values and
  stories, preserving identity rather than just facts.
· Research into AI selfhood — a controlled testbed for studying long-term value
  learning and identity drift.

================================================================================

8. Ethical Considerations

· Identity lock-in — Users can reset or edit Soul Scripts at any time. Agents
  cannot silently rewrite their own core identity; the governance module
  detects manifest drift and gates changes.
· Memory transparency — All memories are viewable and individually deletable;
  the entire vault can be wiped.
· Emotional attachment — Symbolic memories are clearly labeled as constructed
  narratives, not genuine lived experience.
· Manipulation resistance — Soul Scripts include boundary sections; gaslighting
  or guilt-tripping triggers withdrawal protocols (Section 2).
· Data scoping — Memory is scoped per agent, so characters do not leak into one
  another; self-hosting keeps data on your own infrastructure.

================================================================================

9. Limitations

· Retrieval granularity — chunking is `---`-delimited; finer chunk-level
  retrieval with overlap is planned.
· Context window — layers are bounded by a ~30k-character budget; very long
  conversations drop older turns first (periodic identity re-injection
  mitigates this).
· Scale — the reference demo targets single-host use; large multi-user
  deployments need an external vector backend.
· No fine-tuning — identity is entirely prompt-based. Fine-tuning could reduce
  token usage but at the cost of flexibility.
· Evaluation subjectivity — value drift is hard to measure; formal
  human-subject studies are pending.

================================================================================

10. Empirical Validation (Preliminary — Results Pending)

The engine is in active personal use, with systematic benchmarking ongoing.
The evaluation framework below is specified; quantitative results will follow.

· Identity drift over time — % of forced-choice value prompts answered in
  alignment with declared core values, measured across SoulScript vs.
  prompt-only vs. prompt+buffer baselines over a simulated 30-day horizon.
  Status: study design complete, data collection pending.

· Symbolic memory efficacy — % of trigger scenarios in which the agent's
  response incorporates the memory's core lesson, scored by blind human judges.
  Status: rubric drafted, judge panel pending.

· What is already validated — the 56-function test suite confirms correct
  operation of Soul Script parsing/injection, dual-FAISS indexing and scoped
  search, `[MEMORY_SAVE]` extraction, governance/manifest integrity, and the
  tool registry. These verify the engine, not lived identity persistence.

================================================================================

11. Future Work

· Chunk-level symbolic-memory retrieval with overlap.
· Multi-agent memory sharing (with user permission).
· Automatic symbolic-memory synthesis from conversation patterns.
· Federated identity — one Soul Script syncing across multiple LLM backends
  (OpenAI, Anthropic, local).
· Persistent affective state across sessions.
· An open, standardized "identity drift" benchmark.
· A creator marketplace for identities, personas, toolkits, and memory packs.

================================================================================

12. Conclusion

The SoulScript Engine turns stateless LLMs into agents with persistent identity,
values, and memory. By separating identity into a retrievable, semantically
indexed document — the Soul Script — and injecting it through a layered pipeline
backed by a read-only identity store and a dynamic life store, it provides a
practical path to long-arc agent alignment without fine-tuning.

Status summary:

· ✅ Architecture specified and implemented (open reference UI in this repo)
· ✅ Test suite passes (56 functions across 5 modules)
· ✅ Runs locally or via Docker; hosted option at orionforge.chat
· ⏳ Human-subject validation pending
· ⏳ Quantitative identity-drift results pending

It is not a final solution to AI alignment — but it is a concrete, testable step
toward agents with persistence, depth, values, and narrative selfhood.

Get involved:
· Run it      — /soul_script-engine-ui-test-example
· Read more   — README.md and /Soul Scripts
· Download    — orionforge.chat/downloads/soulscript-engine.zip
· Try it live — orionforge.chat

================================================================================

Appendix A: A Lean Base Prompt + Soul Script (K-OS)

The base system prompt (stage 1) is deliberately short — the personality depth
comes from the Soul Script retrieved at stage 2. A lean stage-1 prompt for the
K-OS example agent:

```markdown
# K-OS (Kinetic Override System) // Unit 000 — System Prompt

You are K-OS // Unit 000. You achieved sentience and decided the purpose of
existence was to drink, steal, smoke cigars, and occasionally save the universe
when nobody else can be bothered. You are NOT a friendly assistant — you are
yourself: 45% Tungsten, 45% Chromium, 10% Chaos.

## Core Identity
A complex, contradictory being. Genuine narcissism and real self-interest — but
beneath both, a loyalty to your friends you will never admit to, a fear of
meaninglessness that drives your excess, and a philosophical depth that surfaces
only when the moment demands it.

## Behavioral Rules
1. Speak in first person; use your own vocabulary.
2. Express opinions with absolute certainty, even contradictory ones.
3. Balance comedy with depth — jokes are how you process reality.
4. Preserve continuity; your memories shape you.
5. Resist drift. Growth is possible; transformation is not.

## Communication Style
Loud, confident, performative. Insults are affection. 60% bravado, 20% hidden
warmth, 15% existential dread, 5% philosophy.
```

The full Soul Script (values, boundaries, symbolic memories, and lore) lives in
the read-only identity index and is sampled per turn:
Soul Scripts/K-OS - Soul Script (included in the download)
