Skip to content

Architecture

AncientOS is the canonical system identity. The assistant name is configurable, with Luna as default; Discord, Terminal and Web are transports. See the identity model for preference scope and migration boundaries.

AncientOS intent boundary

AncientOS separates the operator's current directive from language supplied as context before any natural-language capability router runs. Negated actions, future or hypothetical instructions, examples, quotations, code blocks, and pasted report, log, or transcript content cannot select a capability. Quoted or supplied text may be used as an operand only after an independent current directive selects a route.

The original transport request remains the observed evidence. The shared boundary derives bounded directive evidence and safe reason metadata without granting execution or approval authority. Ambiguous scope fails closed to conversation or clarification. Lich and the existing governed execution paths remain the authority boundary.

The bounded directive_text is authoritative for downstream capability selection. The original request is retained only for audit lineage and advisory plan context. High-confidence development-planning arbitration runs after explicit governance, approval, and pending-continuation handling but before narrow financial and broad runtime-status inspection. Capability names and entities discussed inside a development diagnosis do not independently select their domain.

Governed development delegation

Concise human intent is preserved as a durable objective and planned against live repository evidence. Detailed LegionCommander plans are immutable, content-addressed artifacts reviewed separately from implementation authority. Codex receives a concise artifact reference, and its canonical provider adapter rejects complete final instructions over 20,000 Python Unicode code points immediately before launch. See docs/governed_development_delegation.md.

Capability availability truth

Rubick registration and declared wiring are static architecture facts, not claims that Luna can use a capability now. Oracle's shared read-only projection combines those facts with fresh configuration, dependency, runtime, route, transport, and existing Lich authority evidence for a requested operation. See Capability Availability and Reachability Truth. The contract remains model-agnostic and model-portable: inference inventory is one evidence adapter, not a special authority or a separate availability model.

Current Strategic Architecture

AncientOS is the governed cognition kernel for personal AI continuity. It is transport-neutral, provider-neutral, capability-first, and governance-first. It is independent of any single model, provider, interface, hardware location, or transport.

AncientOS uses an operating-system architecture: the kernel owns shared authority and lifecycle primitives; applications and domains request governed capabilities; transports carry requests; providers and execution lanes perform bounded work only through kernel contracts. “Operating system” is an architectural responsibility model, not a claim that AncientOS replaces Linux, Docker, or the host service manager.

Public-facing shorthand: "AncientOS lets your AI relationship move with you."

Exact deferred work can survive transport and process boundaries through governed continuations. Continuation selection is not authority; current identity, readiness, scope, action hash, and separate Lich approval are revalidated before an exactly-once resume claim.

The constitutional architecture reference is AncientOS Kernel Specification v1.0. This page summarizes and expands that specification for human orientation.

AncientOS v3 Architecture preserves historical application-platform design context. Current terminology defines Chen as the governed mutation orchestration layer; live behavior is documented in Durable Governed Actions.

Kernel services for governance, capability reasoning, runtime routing, memory, evidence, operational awareness, repository reasoning, and bounded execution exist to make that continuity trustworthy, inspectable, portable, and human-controlled. They are not meant to turn AncientOS into an enterprise compliance platform, an AGI project, an autonomous agent swarm, or a Discord bot.

The conversational assistant has a configurable name, defaulting to Luna, and uses the AncientOS kernel. Discord, Web and the terminal TUI are transports for that kernel; they do not own routing, governance, memory, provider selection, or execution semantics.

Current taxonomy:

  • Kernel services: Rubick, Oracle, Keeper, Beastmaster, LifeVault, Lich, Zeus, Meepo, Clockwerk, Io, LegionCommander, Roshan, Invoker, Tinker, TrollWarlord, Creep, Kunkka, and Nyx provide reusable AncientOS kernel capability. They protect continuity, trust, evidence, routing, execution boundaries, durable governed observation continuity, objective coordination, and operator legibility. Clockwerk governs time; Io governs continuity.
  • Kernel primitives: governance, capability registry, provider selection, routing/arbitration, memory authority, artifacts, ledgers, evidence, repository reasoning, knowledge graph reasoning, policy, replay/provenance, and operational awareness.
  • Chen governed mutation orchestration: Chen provides the common proposal, approval, execution, evidence, receipt, and rollback lifecycle for capabilities that change system state. It does not become readiness, approval, or evidence authority.
  • Domains: Media, Home, Infrastructure, Finance, Publishing, Knowledge, and future domain packages implement domain-specific logic behind Chen or other governed app surfaces. Media Manager is the first active Chen domain.
  • Applications/workflows: Luna, Naga-Siren, Prophet, X-feed-worker, Keeper Console, and future domain packages consume kernel services through governed contracts. Applications may own workflow-specific state, views, and domain artifacts, but they do not own kernel authority.
  • Providers/adapters: Ollama, xAI/Grok, OpenAI-compatible APIs, Anthropic, Codex, Claude Code, X API, GitHub, MCP providers, UCP commerce providers, and search/browser providers expose implementation surfaces behind governed contracts. Providers are replaceable infrastructure, not identity or authority.
  • Interfaces/transports: Discord, terminal TUI, CLI, Web, Android, and future desktop/mobile clients carry requests and render results without owning kernel semantics. Transports are replaceable surfaces, not continuity.

Core rule: capability visibility is not authority. Observation, planning, and recommendation do not imply permission to execute. Coordination proposals are also not execution authority. MCP and UCP descriptors are external interoperability metadata, not AncientOS authority sources.

Layered model: Transports enter -> Kernel governs -> Chen orchestrates mutation -> Domains implement -> Providers execute bounded work -> Evidence returns. The Semantic Router classifies intent and routes requests into the appropriate kernel, Chen, domain, or interface surface. Luna remains the conversation and interface layer. External services such as Bitmagnet, Plex, qBittorrent, and provider APIs are adapters behind governed contracts, not kernel concepts.

Architecture distinction:

Concern Meaning
Cognition continuity The durable relationship layer: memory, identity, reasoning style, trust, context, and operator alignment across infrastructure changes.
Governance The approval, policy, audit, rollback, and fail-closed machinery that keeps continuity trustworthy.
Workflow orchestration Chen coordinates multi-step app/domain flows through governed capabilities and adapters without owning approval, policy, audit, or replay authority.
Domain logic Domain packages implement subject-specific logic such as Media, Home, Infrastructure, Finance, Publishing, and Knowledge.
Execution Bounded lanes that may perform work only through explicit authority, validation, and replayable artifacts.
Transport Discord, CLI, web, mobile, and future interfaces that relay interaction without owning cognition.
Provider/model abstraction Replaceable intelligence backends behind governed inference roles and capability/provider contracts.

Continuity primitives:

Primitive Architectural owner
Memory continuity LifeVault is the logical memory continuity layer. It preserves durable context, source provenance, promotion status, supersession/deprecation state, and archive lifecycle independently of storage backends.
Posture continuity Rubick preserves controllable behavior, prompt/profile posture, cognitive modes, and continuity-safe runtime configuration.
Transition continuity Meepo revalidates approved state transitions and fails closed on drift.
Governance continuity Rubick, Meepo, Lich language, ledgers, and Zeus supervision preserve stable trust boundaries.
Interaction continuity Luna and transport adapters preserve the relationship across Discord, terminal TUI, CLI, web, mobile, and future clients.
Execution continuity Roshan, Tinker, and Invoker preserve bounded, replayable execution paths across executor/provider changes.

Canonical vocabulary for AncientOS, Luna, app/workflow packages, provider lanes, transports, and external tool boundaries lives in Canonical Terminology. Architecture docs should use that page when distinguishing the AncientOS governed kernel from Luna's Discord interface, other app/workflow packages, transport surfaces, and executor providers.

Canonical kernel invariants, service ownership, application boundaries, provider/capability posture, memory, transport, repository knowledge, and prohibited drift are defined in AncientOS Kernel Specification v1.0.

AncientOS v3 application-platform doctrine, Chen domain lifecycle, domain manifests, domain registry visibility, and the v2-to-Chen-domain migration path are defined in AncientOS v3 Architecture.

Canonical Objective to Loop lifecycle doctrine, authority boundaries, Oracle review posture, Zeus evidence, Lich approval, Clockwerk scheduling, LegionCommander/Creep dispatch, loop traces, and LifeVault retention are defined in Governance Kernel. Architecture pages should link there rather than duplicating lifecycle authority tables.

The kernel-service/application interaction model lives in AncientOS App And Component Boundary Model. It defines application lifecycle, capability requests, permissioning, state ownership, provider boundaries, transport boundaries, and kernel service interaction rules without adding runtime app registration or enforcement.

Era 6A introduces an interoperability protocol scaffold documented in Interoperability Protocol Layer. MCP is an external tool/context protocol that can describe AncientOS capabilities only through Rubick-owned mappings. Inbound MCP providers remain disabled and untrusted until explicitly registered through Rubick and classified through Lich governance. UCP is represented only as inert commerce-intent models; it does not add checkout, payment, purchasing, or merchant mutation authority. Future governed execution through either protocol requires Rubick capability registration, Lich approval classification, Zeus evidence artifacts, replay boundaries, and fail-closed validation.

Era 7C adds Gap Intelligence for the support hierarchy above execution. It can explain missing or weak objective, skill, capability, and governance coverage and rank advisory roadmap candidates, but it cannot create anything, plan autonomously, mutate roadmaps, invoke providers, or change lifecycle state.

Era 6A.5 adds the descriptor-only MCP export bridge:

Rubick Capability Registry -> MCP Export Bridge -> Descriptor Catalog -> Future MCP Server

The bridge and catalog are read-only interoperability surfaces. They do not start a server, open a network transport, register external MCP providers, or invoke AncientOS capabilities.

Eras 6A.7 through 6A.9 add the governed planning substrate that sits between read-only MCP discovery and any future execution phase:

Discovery -> Authorization -> Approval Packet -> Execution Plan -> STOP
flowchart LR D[Read-only MCP discovery] A[Authorization] P[Immutable approval packet] E[Governed execution plan] S[Stop before execution] D --> A --> P --> E --> S A --> R[Rubick metadata] A --> L[Lich required authority] A --> Z[Zeus evidence requirements]

Authorization answers what approval, evidence, governance path, and replay boundary would be required. Approval packets are deterministic future-Lich inputs. Execution plans list verification steps only and always set execution_performed = false. This substrate introduces no provider invocation, Rubick capability execution, network path, filesystem mutation, or commerce path.

Era 6B adds an opt-in governed read-only MCP execution lane:

Discovery -> Authorization -> Approval Packet -> Execution Plan
-> Invocation Candidate -> Lich Gate -> Zeus Evidence Gate
-> Read-Only Executor Facade -> Evidence Receipt

The lane is disabled by default with mcp_read_only_execution_enabled = false. When disabled, tools/call remains a discovery-only refusal. When enabled, it can execute only the allowlisted Era 6D.1 real capability inspect_disk_space, and only after requester identity, session context, execution-eligible trust, read-only intent, execute_read_only authority, Rubick registration, provider registration, authorization, approval packet, execution plan, Lich gate, Zeus evidence gate, executor policy, provider allowlist, and receipt generation all pass.

Era 6D.1 binds inspect_disk_space to the exact Rubick provider provider_beastmaster_inspect_disk_space and Beastmaster's registered disk_overview read-only probe. MCP arguments cannot change the provider, command, or path. Receipts include sanitized disk-space output and governance attribution, while omitting secrets, credentials, raw environment dumps, and host data outside the intended disk-space result.

Era 6D.2 adds a local operator validation harness at app/interoperability/mcp_validation_harness/. It is an inspection harness, not an authority surface: it runs pure scenario functions and an optional local CLI to show discovery output, requester identity, session context, intent, trust, authority, authorization, approval packet, execution plan, invocation candidate, Lich gate, Zeus evidence gate, execution result or refusal, and receipt data for the existing inspect_disk_space lane. Fake-provider execution is the default. Real Beastmaster provider execution requires an explicit --allow-real-provider flag. The harness adds no new capabilities, public HTTP transport, network calls, Discord routing, mutating execution, commerce execution, arbitrary shell execution, or filesystem writes by default.

Era 6F.3 adds app/interoperability/skill_validation_harness/, a local advisory validation harness for skill intelligence. It validates skill lists, host awareness health and fitness, MCP governance health, overlap reports, gap reports, recommendation reports, missing-capability cases, dormant-capability cases, and no-implemented-capability cases. It renders deterministic JSON or human-readable summaries and explicitly performs no provider invocation, execution, lifecycle mutation, capability mutation, automatic optimization, promotion, deprecation, or retirement.

Era 6G.1 adds app/interoperability/mcp_client_compat/, a local MCP-client-shaped compatibility harness. It validates profile-shaped transcripts for generic MCP clients, Claude Desktop-shaped clients, Cursor-shaped clients, VS Code-shaped clients, and OpenAI MCP-shaped clients without installing, launching, authenticating to, or networking with those clients. This is compatibility testing of transcript shapes only. Live Claude/Cursor/VS Code validation remains a separate future integration track.

Era 7A adds app/interoperability/conversational_intake/, a rule-based transport-neutral intake layer that converts operator text or object input into governed objective, skill, capability, proposal, and next-step structures. It sits before MCP enablement, lifecycle governance, portfolio review, and skill intelligence. It does not call LLMs, invoke providers, execute MCP tools, apply MCP enablement, mutate lifecycle or objective state, approve work, or add Discord-specific behavior.

Era 7B adds app/interoperability/objective_governance/, a metadata-only governance layer above skills:

Objective -> Skill -> Capability -> Provider -> Execution

Objectives explain why skills and capabilities exist. The layer supports objective records, success criteria, objective-skill mappings, objective-capability mappings, unresolved bindings, explicit lifecycle transition simulation, portfolio aggregation, intelligence assessments, validation, deterministic reports, and advisory recommendations. It does not create autonomous goals, plan work, execute capabilities, invoke providers, apply MCP enablement, mutate lifecycle state, add real capabilities, or depend on Discord or any transport.

Era 6E.1 adds the governed MCP capability enablement path at app/interoperability/mcp_enablement/. The entrypoint prepare_mcp_enablement_request(...) is transport-neutral: Discord, CLI, web, mobile, tests, and future transports may submit text or object requests, but no transport may directly enable MCP tools or mutate the MCP allowlist.

Enablement is distinct from execution. The path parses a target capability_id, checks Rubick capability and provider registration, classifies read-only, mutating, commerce, and network authority, includes validation simulation evidence when supplied, generates a Rubick/Lich/Zeus approval packet, produces an enablement plan, and emits a receipt. It defaults to dry_run=true, apply=false, approval_state=pending, and enablement_performed=false.

Unknown capabilities produce proposal-only refusals. Mutating capabilities, commerce capabilities, network capabilities, missing providers, failed validation simulation, pending approval, and missing explicit apply all fail closed. A governed allowlist or registry-surface update may occur only for an already registered, provider-backed, read-only capability when the approval packet is approved, apply=true, and dry_run=false. Rubick owns capability and provider truth, Lich owns approval and classification, and Zeus owns evidence expectations.

This does not create general protocol execution authority. Mutating execution, commerce execution, UCP execution, filesystem mutation, network mutation, write-capable providers, arbitrary shell commands, Docker mutation, Git mutation, Keeper mutation, LifeVault mutation, Naga mutation, and Discord routing changes remain outside the MCP lane. The MCP server uses a read-only executor facade and provider adapter allowlist rather than direct Rubick, Beastmaster, shell, or network calls.

Era 6E.2 adds MCP capability lifecycle governance at app/interoperability/mcp_lifecycle/. It is transport-neutral and provider-neutral: it models lifecycle state, observations, reviews, promotion/deprecation/retirement proposals, simulations, dormancy reviews, reports, and receipts without invoking providers or adding new capabilities.

Lifecycle transitions are explicit and fail closed. Each transition requires a known requester, trust classification, authority scope, approval packet, evidence references, and target state. Simulations can answer what would happen if a capability were suspended, promoted, deprecated, retired, or reviewed for dormancy, but simulations do not change state.

Dormancy governance follows a human-review policy. AncientOS tracks last successful execution metadata and recommends review after 90 days of no successful execution. It does not auto-disable dormant capabilities. Dormancy recommendations always keep human_review_required=true and auto_disable_allowed=false; suspend, disable, retire, and archive require separate human-approved lifecycle transitions. Retired records are archived, not deleted, so receipts, attribution, trust metadata, evidence, and history remain available for audit.

Era 6E.3 adds MCP capability portfolio governance at app/interoperability/mcp_portfolio/. It is a visibility and reporting layer over Rubick capability/export catalog data and MCP lifecycle models. It builds portfolio health reports, risk reports, dormancy reports, review backlogs, redundancy findings, advisory recommendations, and deterministic JSON snapshots without invoking providers, adding transports, depending on Discord, or mutating lifecycle state.

Portfolio recommendations are advisory only. A dormant capability at 90+ days unused creates review_required, not disablement. A capability at 180+ days unused creates stale_review_required, still requiring human review. High-risk enabled capabilities, missing evidence, stale approvals, repeated failures, repeated refusals, unreviewed enabled capabilities, and redundant capabilities enter review backlog reports. Promotion, suspension, deprecation, disablement, and retirement candidates remain candidates until a separate human-approved lifecycle transition occurs.

Rubick remains the source of truth for capability and provider registration. MCP lifecycle governance remains the state and approval model. MCP portfolio governance is transport-neutral operator visibility across those model inputs; it adds no new capabilities, no execution paths, no provider invocation, and no automatic suspension, disablement, deprecation, or retirement.

Era 6F.1 adds the skill registry at app/interoperability/skill_registry/. It introduces a metadata hierarchy:

Skill -> Capability -> Provider -> Execution

Skills represent durable governed purposes and typed contracts. Capabilities remain Rubick-owned implementation units. Providers remain implementation metadata beneath capabilities. Execution remains available only through separately governed execution lanes. The skill registry can map one skill to many capabilities, one capability to many skills, providers to skills, dependencies between skills, and unresolved future bindings. It can validate the graph, render deterministic reports, surface portfolio and dormancy summaries under parent skills, and generate advisory recommendations.

Skill recommendations are not lifecycle authority. They do not promote, retire, optimize, rewrite, or execute skills or capabilities. SkillOpt informs the reusable-artifact and validation-gate shape only; SkillOps-like practice informs typed contracts and skill ecosystem graph thinking only.

Era 6F.2 adds skill intelligence at app/interoperability/skill_intelligence/. It is an advisory layer over the skill registry, skill graph, validation results, and optional capability portfolio reports. It classifies skill health, computes 0-100 fitness scores, detects skill overlap, identifies gaps, labels strategic importance, ranks fitness, emits recommendations, and renders deterministic JSON and human-readable reports.

Fitness scoring considers implemented capability count, unresolved bindings, capability portfolio health, dormancy, evidence completeness, review backlog, failure/refusal signals when supplied, risk level, and validation warnings. Overlap analysis compares shared capabilities, providers, domain, tags, and purpose/description keywords. Gap analysis covers no implemented capabilities, only unresolved bindings, missing providers, high strategic importance with low fitness, contract outputs without validation signals, failure modes without mitigation notes, and enabled skills without executable capabilities. Strategic labels are foundational, operational, governance, integration, experimental, and deprecated.

Skill intelligence is not SkillOpt autonomy. It borrows skill fitness and recommendation concepts only. It adds no execution authority, MCP capability, provider invocation, Rubick mutation, lifecycle mutation, automatic optimization, automatic promotion, automatic deprecation, automatic retirement, Discord dependency, or transport dependency.

Layered AncientOS Topology

flowchart TD A[AncientOS governed cognition kernel] A --> L[Luna interactive cognition interface] A --> V[LifeVault memory continuity] A --> R[Rubick continuity posture control plane] A --> K[Keeper objective and task coordination] A --> B[Beastmaster host/runtime awareness] A --> M[Meepo transition integrity infrastructure] A --> O[Oracle evidence and state explanation] A --> G[Lich approval and Zeus evidence governance] A --> X[Roshan / Tinker / Invoker bounded execution paths] L --> T[Transports: Discord / terminal TUI / CLI / Web / Android / future clients] X --> P[Providers and models: Codex / Claude Code / Ollama / xAI / OpenAI-compatible / Anthropic] T --> P2[Provider adapters: X API / GitHub / search-browser providers]

Rubick governs posture, capability, repository, and relationship reasoning. Keeper coordinates objectives and tasks. Oracle explains facts, evidence, risk, and recommendations. Beastmaster observes host/runtime state. LifeVault preserves long-term memory continuity. Lich owns approval boundaries, and Zeus owns evidence expectations and replay governance. Luna expresses interactive cognition through transport adapters. Roshan, Tinker, Invoker, and Creep handle bounded execution paths only after governance. Providers and models are replaceable infrastructure; transports are replaceable interaction surfaces.

LifeVault is the logical continuity authority for memory. pgvector/Postgres, SQLite, files, artifact directories, append-only audits, and future databases are storage or replay surfaces behind LifeVault. Discord history, Oracle reports, Rubick records, Meepo transition packets, and provider outputs may be evidence for memory proposals, but they do not become durable memory until reviewed and promoted through LifeVault.

The symbolic Dota-style names are intentional cognitive anchors for humans. Architecture documentation should preserve names such as Rubick, Meepo, Roshan, Invoker, TrollWarlord, Tinker, Creep, Zeus, Oracle, Clockwerk, Io, Kunkka, Lich, and Nyx while pairing them with canonical technical classifications such as ancientos_core_component, ancientos_app, provider_adapter, or interface_transport.

Canonical Boundary Summary

AncientOS is the persistent governed cognition kernel around AI relationships. It preserves memory, trust, identity, reasoning style, governance, and operational alignment across replaceable models, providers, and transports. Luna is the default configurable assistant name over the kernel, not the kernel itself. Naga-Siren, Prophet, X-feed-worker, Keeper Console, and future domain packages are applications or workflows that consume kernel services. Discord and terminal TUI are transports/rendering adapters.

Rubick, Oracle, Keeper, Beastmaster, LifeVault, Lich, Zeus, Meepo, Clockwerk, Io, LegionCommander, Roshan, Invoker, TrollWarlord, Tinker, Creep, Kunkka, and Nyx are AncientOS kernel services, components, or lanes. Rubick is the continuity, capability, repository, and relationship reasoning control plane. Keeper owns objectives, tasks, planning records, and preflight signals. Oracle owns evidence synthesis and review. Beastmaster owns host/runtime awareness. LifeVault owns memory authority. Lich owns approval and governance gates. Zeus owns evidence expectations and replay governance. Meepo protects transition integrity. Execution lanes may act only under explicit governed authority.

Ollama, xAI/Grok, OpenAI-compatible APIs, Anthropic, Codex, Claude Code, X API, GitHub, MCP providers, search/browser providers, and other adapters are providers behind governed contracts, not independent authority sources. Tinker is the local executor provider lane for implementation work and remains bound by Lich, Zeus, Rubick, and Roshan boundaries.

External repos and tools are treated as patterns, references, integrations, or provider candidates unless AncientOS explicitly adopts them under a governed contract. The preferred strategy is to wrap or adapt external tools behind deterministic, artifact-backed, auditable contracts; avoid premature forks; preserve provider interchangeability; and fork only when AncientOS intentionally decides to maintain a divergent codebase.

This section is taxonomy-only. Existing modules, services, commands, Docker keys, API routes, database paths, and environment variables retain historical Luna names until a future mechanical rename phase.

Component Classification

Symbolic name Canonical classification Technical role
Rubick AncientOS kernel service continuity, capability, repository, and relationship reasoning control plane
Meepo AncientOS core component transition integrity infrastructure
Roshan AncientOS core component governed execution lane
Invoker AncientOS core component safe self-development lane
TrollWarlord AncientOS core component promotion / commit engine
Tinker AncientOS core component and local provider lane local executor provider/lane
Creep AncientOS core component executor component worker
Zeus AncientOS kernel service evidence expectations, replay governance, and constitutional supervision
Oracle AncientOS kernel service evidence synthesis, operational awareness, and state interpretation
Keeper AncientOS kernel service objectives, task coordination, planning records, and preflight context
Beastmaster AncientOS kernel service host and runtime awareness
LifeVault AncientOS kernel service durable memory authority
Clockwerk AncientOS kernel service approved scheduling and time-window visibility
Io AncientOS kernel service durable governed watch/tether continuity and typed observation invocation
LegionCommander AncientOS kernel lane bounded task graph and dispatch planning after governance
Kunkka AncientOS core component candidate navigation / workflow routing candidate
Lich AncientOS kernel service approval / confirmation / governance gate
Nyx AncientOS core component candidate preflight / interception safety candidate
Luna Default configurable assistant name conversational presentation over the kernel
Chen AncientOS governed mutation orchestration layer proposal, approval, execution, evidence, receipt, and rollback lifecycle coordination
Media Manager Chen domain media domain readiness and planning, currently read-only with future approval-gated actions
Naga-Siren AncientOS app/workflow governed publishing workflow
Keeper Console AncientOS app/interface manual task-management UI over Keeper
X-feed-worker AncientOS app/workflow feed ingestion / service workflow
Prophet AncientOS app read-only prediction-market intelligence, advisory recommendation, and manual-review proposal workflow

Transport-Neutral Runtime Kernel

app/runtime/kernel.py implements the AncientOS Runtime Kernel. It owns message-processing order independently of Discord. app/bot.py is only the Discord ingress and lifecycle shell: it receives an event, asks app/runtime/discord_adapter.py to construct a RuntimeMessageEnvelope, calls the kernel, and asks the adapter to render the returned payloads.

Module Authority Explicit non-authority
app/runtime/contracts.py transport-neutral envelopes and route result types Discord objects, execution decisions
app/runtime/kernel.py first-class runtime entrypoint and pipeline ownership Discord imports, message sending, direct execution
app/runtime/pipeline.py ordered runtime stages and governed preemption order transport-specific rendering, autonomous loops
app/runtime/commands.py legacy command compatibility routing Discord objects, parser loosening, hidden execution
app/runtime/context.py channel/user/session context helpers execution authority
app/runtime/state_policy.py allowed runtime cognition fields, forbidden fields, expiry, clear rules chat memory, secrets, execution authority
app/runtime/state_store.py scoped deterministic runtime cognition persistence Discord objects, unbounded transcripts, hidden loops
app/runtime/intent_memory.py active objective, bounded pending intent, route confidence, last route decision inferring intent beyond stored evidence
app/runtime/clarification_state.py unresolved clarification records and deterministic answer resolution free-form intent guessing
app/runtime/workflow_state.py active workflow summary, next safe suggested action, pending governance branch executing workflow steps
app/runtime/state_inspection.py plain-English state and pending-work summaries mutation or approval
app/runtime/discord_adapter.py Discord envelope extraction and send/edit rendering runtime decisions, governance decisions
app/runtime/observability.py trace payload normalization and runtime identity business logic, routing, governance decisions
app/runtime/rendering.py Discord-safe chunking and approval handoff rendering planning, execution, confirmation mutation
app/inference/contracts.py transport-neutral inference request/response contracts and role names Discord objects, routing authority, execution decisions
app/inference/client.py bounded luna-inference HTTP client with fail-closed errors direct Ollama/OpenWebUI ownership, unsafe fallback
app/inference/policy.py deterministic role/tier/structured-output policy model-owned governance or execution
app/inference/roles.py named inference role registry subsystem-specific model semantics
app/interoperability/objective_governance/* objective metadata, objective-skill-capability mapping, lifecycle simulation, portfolio reports, intelligence, validation, and recommendations execution, provider invocation, MCP enablement apply, lifecycle mutation, autonomous goals, automatic planning, automatic promotion, automatic retirement, Discord or transport dependency
app/interoperability/gap_intelligence/* advisory objective, skill, capability, governance, recommendation, priority, and JSON snapshot reports execution, provider invocation, lifecycle mutation, capability creation, skill creation, objective creation, autonomous planning, roadmap mutation, Discord or transport dependency
app/interoperability/skill_intelligence/* advisory skill health, fitness, overlap, gap, strategic importance, and recommendations execution, provider invocation, Rubick mutation, lifecycle mutation, automatic optimization, automatic promotion, automatic deprecation, Discord or transport dependency
app/interoperability/conversational_intake/* deterministic operator text/object intake into governed proposals and next-step recommendations Discord behavior, LLM calls, provider invocation, MCP enablement apply, lifecycle mutation, objective mutation, automatic approval, execution
app/routing/governed_preemption.py TrollWarlord governed commit canonicalization and preemption orchestration generic commit inference, shell/file authority
app/routing/governance_interceptor.py governance-preview interception and persisted investigation attachment executing mitigations or collapsing intent
app/routing/operational_router.py deterministic plain-English operational route selection and clarification direct execution or approval
app/routing/conversational_router.py tools-bypass/chat fallback composition governed execution

Runtime pipeline stages:

flowchart TD D[Discord adapter] --> E[RuntimeMessageEnvelope] E --> S[author/self skip] S --> G[TrollWarlord governed preemption] G --> T[task ingest and drafting surfaces] T --> K[Keeper surface] K --> C[explicit command compatibility] C --> X[x-feed ignore gate] X --> M[governed runtime cognitive state] M --> O[plain-English operational routing] O --> P[explicit plan/delegate compatibility] P --> I[governance preview interception] I --> R[luna-router compatibility] R --> F[operational cognition/tools/chat fallback] F --> Y[RuntimeDispatchResult] Y --> A[Discord adapter render]

Plain-English operational routing is deterministic and bounded. Clear operator requests such as planning cleanup, delegating a read-only inspection, listing pending confirmations, or showing task state map to explicit modes. Ambiguous requests such as "do the thing", "proceed", "fix it", or "run that" ask a clarifying question unless existing pending confirmation context makes the meaning deterministic. Clarification happens before action; Luna does not guess, loosen parsers, or fall through into unsafe execution.

Architectural inspection requests also route through this deterministic layer. Questions such as "What capabilities do you currently have?", "What roadmap stage are we in?", "What should we work on next?", "What architectural debt remains?", and "What still depends on Discord?" are handled by app/architecture/*. The response is a read-only report. It cannot mutate roadmap state, approve work, create execution plans, enqueue tasks, or bypass governance preview.

Governed Architectural Awareness Layer

app/architecture/* provides bounded architectural self-awareness for AncientOS/Luna. It synthesizes capability evidence, roadmap era state, dependency readiness, subsystem boundaries, governance layers, runtime coupling, drift warnings, and advisory next-step recommendations.

Module Responsibility Explicit non-authority
app/architecture/evidence.py evidence references and provenance labels deciding truth without evidence
app/architecture/capability_registry.py evidence-backed capability registry advertising docs-only aspirations as available capabilities
app/architecture/roadmap_state.py deterministic era and milestone state automatically completing roadmap items
app/architecture/dependency_graph.py prerequisite and readiness evaluation executing dependency work
app/architecture/architecture_inventory.py subsystem, coupling, governance, and debt inventory mutating runtime topology
app/architecture/drift_detection.py bounded warnings for mismatch or ambiguity automatic reconciliation
app/architecture/next_step_synthesis.py advisory safest-next-step synthesis planning or execution authority
app/architecture/rendering.py human-readable summaries and reports adapter-specific rendering or hidden loops

Governed Coordination Cognition Layer

app/coordination/* represents operational coordination as a governed, inspectable, replay-safe substrate. It is the transition from Oracle understanding operational state to AncientOS synthesizing bounded coordination proposals.

Module Responsibility Explicit non-authority
app/coordination/workflow_state.py canonical workflow-state snapshots and file-backed JSON loading hidden state, workflow execution
app/coordination/dependency_reasoning.py dependency chains, degradation propagation, approval bottlenecks, replay-invalid chains, validation blockers resolving dependencies or mutating state
app/coordination/sequencing.py governance-aware next-step proposals and deterministic prioritization execution, self-approval, background planning loops
app/coordination/capability_composition.py ontology-backed capability composition and unsafe-chain warnings invoking capabilities
app/coordination/simulation.py bounded replay-safe comparison of coordination paths runtime simulation authority or state mutation
app/coordination/bottleneck_analysis.py governance friction and recovery proposal surfaces remediation authority
app/coordination/policy.py advisory authority contract and constitutional coordination-risk warnings enforcement authority
app/coordination/topology.py inspectable workflow/dependency topology reconstruction invented operational history
app/coordination/coordination_reports.py transport-neutral report schemas interface-owned semantics
app/coordination/evidence.py replay hashes and deterministic evidence serialization truth promotion without evidence

Coordination reports include workflow-state, dependency coordination, coordination proposal, capability composition, coordination simulation, governance friction, operational recovery, and coordination risk surfaces. They are renderable by Oracle and future adapters, but they cannot execute, self-authorize, recursively spawn workflows, bypass governance, or mutate runtime state.

Awareness is not autonomy. The layer can answer bounded architectural questions, but it cannot start work, approve work, mutate state, run tools, repair drift, or treat its recommendations as authority. "Next step" output is explicitly advisory, includes dependency rationale, and declares no execution authority.

Capability evidence model:

  • Verified capability claims require direct runtime evidence or test evidence.
  • Document-only claims are treated as derived evidence.
  • Roadmap aspirations are separated from verified capabilities.
  • Missing or ambiguous evidence fails closed.
  • Evidence labels remain inspectable in rendered reports.

Dependency reasoning model:

  • Roadmap era readiness is computed from fixed prerequisite relationships.
  • A dependency is satisfied only when the prerequisite era is marked complete in the bounded registry.
  • Unknown eras and missing prerequisites fail closed.
  • Readiness reports explain satisfied and missing dependencies without mutating roadmap state.

Architectural drift semantics:

  • Drift detection produces warnings only.
  • Ambiguous evidence, docs/runtime mismatches, and blocked aspirations do not rewrite registries or documentation.
  • Reconciliation remains a human-governed documentation or code change.

Anti-patterns avoided:

  • Hidden planning loops behind architectural questions.
  • Treating roadmap cognition as execution authority.
  • Treating docs as canonical truth without runtime or test evidence.
  • Inferring unverified capabilities from aspirations.
  • Allowing architecture summaries to depend on Discord transport objects.
  • Automatically correcting drift or completing milestones.

Runtime Cognitive State Layer

The Runtime Cognitive State layer gives Luna bounded operational continuity across messages without implementing vague chat memory. It stores only small scoped records needed for deterministic routing and inspection:

  • active objective
  • unresolved clarification
  • pending intent
  • active workflow summary
  • pending governance branch
  • recent route decision
  • current bounded scope
  • route and clarification confidence
  • last safe suggested next step

This state is owned by app/runtime/*, scoped by channel/user/session, and persisted through deterministic JSON in app/runtime/state_store.py when a runtime store is configured. It is transport-neutral: records do not contain Discord objects, message logs, raw transcripts, secrets, credentials, or unbounded history.

Operational cognition state differs from chat memory:

Operational cognition state Chat memory anti-pattern
bounded fields with an allowlist arbitrary remembered conversation
scoped channel/user/session records global hidden personalization
deterministic expiry and reset indefinite retention
auditable route and clarification facts opaque inferred intent
context for routing/proposals only authority to execute

Expiry and clear rules are explicit. New records receive a deterministic TTL. Stale records are cleared on load. Reset this thread's runtime state clears the current runtime scope. Forget the pending task clears pending clarification and intent records for the current scope while leaving unrelated scopes untouched.

Clarification continuity is bounded. When Luna asks a clarifying question, the question, expected answer type, original ambiguous request, and candidate interpretations are stored until expiry, reset, cancellation, or deterministic resolution. Answers resolve only when they map to exactly one candidate.

Proceed/yes/do-it safety semantics:

  • Proceed does not execute work. It may continue only when exactly one safe pending continuation exists, and the continuation still routes through normal governed plan/delegate preview paths.
  • Proceed with no unique safe pending continuation asks for clarification.
  • Do it behaves like a bounded continuation request and clarifies when more than one pending action exists.
  • Yes does not approve governance-sensitive work unless the existing explicit confirmation flow owns the approval context.
  • Runtime state is never an authority source for Lich, TrollWarlord, Oracle, Keeper, Roshan, Kunkka, governance preview, or confirmation bypass.

Authority ownership:

Authority Owner
Pipeline ordering RuntimeKernel / app/runtime/pipeline.py
Discord object access app/runtime/discord_adapter.py and app/bot.py lifecycle shell
Runtime cognitive state app/runtime/state_store.py and state-specific runtime modules
Governed commit canonicalization TrollWarlord through app/routing/governed_preemption.py
Approval and confirmation state Lich / Commander confirmation registry
Planner and delegate previews LegionCommander under governance interception
Dangerous-operation containment Roshan validation and escalation contracts
Keeper task surface Keeper handlers, called as a runtime stage
Conversational fallback Runtime pipeline only after governed stages decline

Anti-patterns avoided:

  • Discord transport owning execution semantics.
  • Discord-owned cognition or planner/delegate branching.
  • Phrase-specific governed commit handlers outside TrollWarlord normalization.
  • Backup files counting as live runtime identity candidates.
  • Generic chat fallback before governed and operational routes decline.
  • Vague chat memory, unbounded conversation logs, and secret-bearing state.
  • Runtime state as execution authority or approval bypass.
  • Hidden loops, autonomous execution, or unrestricted shell/file/network access.

Runtime identity scans regular .py files only. Timestamped bot snapshots have been removed from source control; Git retains their history. Regression fixtures continue to verify that backups and bytecode do not inflate counts.

Oracle Visibility Layer

Oracle is the read-only AncientOS kernel service for operational visibility and evidence synthesis in app/oracle/*. It aggregates governed artifacts, bounded runtime summaries, Rubick evidence, Beastmaster evidence when supplied, and Governed Architectural Awareness reports into operator-facing visibility.

Oracle does not mutate state, execute tools, stage files, commit, bypass Lich, escalate through Underlord, orchestrate runtime services, or launch background loops. It emits deterministic visibility reports for humans while existing execution, approval, validation, and remediation paths remain authoritative.

Oracle reports separate verified facts, inferred readiness, warnings, and advisory recommendations. Missing or ambiguous evidence fails closed with warnings. Oracle is not a source of truth; it renders bounded evidence from governed sources.

Governed Inference Substrate

app/inference/* centralizes eligible Luna text inference through luna-inference. Runtime routing, governance preview, Lich, TrollWarlord, Keeper, confirmations, Oracle policy, and execution decisions remain outside model control.

Named roles include:

  • conversational_reply
  • operational_clarification
  • architecture_summary
  • oracle_synthesis
  • route_explanation
  • draft_generation
  • bounded_reasoning
  • memory_fact_extraction
  • task_intent_classification
  • embedding_generation
  • retrieval_query_embedding
  • memory_fact_embedding
  • architecture_evidence_embedding

Each role has deterministic policy: allowed tiers, structured-output requirements, advisory-only semantics, and fail-closed behavior for disallowed roles or unavailable luna-inference. Structured-output roles must parse and validate their expected shape before the output is accepted.

Governed embedding roles use the same policy and observability substrate as text inference. Embedding requests are transport-neutral contracts, are checked against explicit embedding roles, and route through the governed inference client. Disallowed embedding roles fail closed before HTTP. Missing embedding service configuration or invalid vectors produce explicit degraded responses; callers must treat that as unavailable evidence preparation, not permission to call a backend directly.

Compatibility wrappers such as run_model_attempt, call_ollama, and call_openwebui remain for legacy callers, but eligible chat, task-intent, and fact-extraction traffic now delegates to the governed inference client. The wrappers do not silently fall back to direct model services when luna-inference fails.

Inference and embedding output cannot approve, execute, mutate, stage files, commit, bypass governance, or choose execution authority. Text output may only produce bounded summaries, clarifications, or structured proposals that remain subject to the normal deterministic and governed pipeline. Embedding output may only prepare retrieval or memory evidence.

Retrieval remains evidence input, not authority. Query, memory-fact, and architecture-evidence embeddings may influence what evidence is surfaced for a human or deterministic subsystem to inspect, but retrieval results cannot approve actions, mutate memory by themselves, bypass Oracle read-only limits, or expand runtime/file/shell/network authority.

Residual model-call debt:

  • Broader retrieval callers should continue migrating to the governed embedding roles as they are introduced. Memory fact embedding traffic now uses the governed inference client instead of direct /api/embeddings calls.

Anti-patterns avoided:

  • direct subsystem-owned chat model calls
  • model-owned governance
  • model-owned execution
  • hidden unsafe fallback to direct Ollama/OpenWebUI
  • unstructured autonomous reasoning loops

Planner to execution flow

flowchart TD U[User request] --> P[LegionCommander planner] P --> L[Lich review] L -->|allow| E[Executor or creep worker] L -->|require confirmation| C[Confirmation gate] C --> E E --> V[Validation] V --> R[Discord result]

Creep job lifecycle

stateDiagram-v2 [*] --> queued queued --> running running --> completed running --> failed running --> waiting_for_confirmation waiting_for_confirmation --> running

Keeper

See the detailed Keeper architecture page: Keeper Architecture

Keeper Lifecycle

See the runtime state flow: Keeper Lifecycle

Discord session context

Discord chat requests include a bounded per-channel or per-thread session window before the current user turn. See Session Context.

Natural AncientOS/Luna context

Natural questions about AncientOS/Luna roadmap, architecture, state, limitations, capabilities, live system, or checkpoints use deterministic intent matching. When matched, Discord asks luna-tools to read the fixed context index and one fixed allowlisted source file. The retrieved text is bounded and injected only into the current model request.

Discord does not perform direct filesystem reads, accept user-provided paths, write files, mutate memory, or route through shell for this context path. See Natural Context Retrieval (includes Phase 6C Core Runtime Context Tools + Phase 6D Operational Awareness Layer).

Current Operational Architecture

graph TD U[User in Discord] --> D[discord-luna] D --> I[Intent Detection] I -->|roadmap/system question| T[luna-tools governed retrieval] T --> C[Authoritative Context Files] C --> D D --> L[luna-inference] L --> O[Ollama] D -->|governed execution requests| G[luna-interop] G --> P[Patch Plans / Validation / Rollback] P --> X[Tinker Local Execution]

Current Execution Reality

Luna now operates through governed artifact flows instead of direct autonomous execution.

Current implemented capabilities: - bounded Discord session context - governed operational memory - natural-language self-context retrieval - governed live Tinker bridge - sandboxed mutation capability - patch-aware structured editing - rollback-aware execution receipts - validation contracts and review artifacts

Current blocked capabilities: - arbitrary shell execution - unrestricted filesystem access - recursive autonomous execution - unrestricted network operations - uncontrolled self-modification - Discord-owned execution semantics

The system remains intentionally fail-closed and governance-first.

Operational Awareness (Phase 6D)

Additive read-only layer in context_retrieval provides deterministic health, container, repo, update, limitation, source, and degraded-state summaries. All gated behind natural language intent detection, bounded, request-scoped, using only luna-tools governed reads from fixed docs. No new authority; fully compatible with existing Tinker governance.

Intent detection now uses expanded deterministic term groups with explicit self-state priority (runtime, operational, continuity, state, checkpoint) so that Luna/SER6BUZZ/self queries reliably win over generic completion. Clock awareness, tools, limitations, operational state, and recent activity now route correctly to governed sources.

Task Continuity Layer (Phase 6E)

Further additive extension for coherent cross-session continuity: current task, latest checkpoint, capabilities/skills awareness, recent activity (success vs degraded). Uses only existing fixed allowlisted sources (current_task, checkpoint.md, luna_capabilities.md). Deterministic intent classification, bounded, fail-closed, request-scoped. Preserves all governance, rollback, and thin-transport properties. No write authority or autonomous loops introduced.

Phase 6F Structured Operational Inventories

Canonical governed maps (GOVERNED_TOOLS, GOVERNED_SKILLS, etc.) plus deterministic renderers (tools_inventory_summary, operational_state_summary, runtime_clock_summary, etc.) provide structured, bounded answers instead of raw prose. All inventories are static, auditable, and sourced from allowlisted governed documents only.

Current Architecture Status: Governed Operational Intelligence

Luna has moved beyond simple retrieval-backed self-description into a layered governed cognition stack.

Current implemented layers:

  • Governed runtime registry
  • Operational awareness context
  • Task continuity context
  • Governed operational intent routing
  • Structured operational inventories
  • Governed action intelligence
  • Governed multi-step plan state
  • Governed workflow cognition
  • Multi-workflow arbitration
  • Coordination kernel
  • Governed simulation engine
  • Governed policy engine
  • Branch evaluation and safest-path selection

The system remains non-autonomous. These layers reason about workflows, policies, simulations, rollback readiness, validation needs, governance cost, and safest paths, but they do not execute actions automatically.

graph TD U[User / Discord] --> D[Thin Discord Transport] D --> R[Governed Intent Router] R --> G[Runtime Registry] R --> P[Governed Plan State] R --> W[Workflow Cognition] W --> A[Workflow Arbitration] A --> C[Coordination Kernel] C --> PE[Policy Engine] C --> SE[Simulation Engine] SE --> B[Branch Evaluation] B --> S[Semantic Response Renderer] S --> D PE -. denies .-> X[Unsafe Authority] SE -. forecasts .-> Y[Rollback / Validation / Review Needs]

Core boundary: AncientOS can support reasoning about operational futures under governance constraints, including through the Luna interface, but execution remains gated, explicit, and non-automatic.

Documentation Drift Detection

AncientOS includes a deterministic, read-only documentation drift checker for the architecture and master roadmap documents. The checker reports required strategic architecture terms, stale language, missing files, bounded recommendations, and future-facing consumer contracts as structured JSON.

This substrate is intentionally observational. Oracle may later surface drift visibility to humans, and Zeus may later use the report for constitutional review recommendations, but neither role is implemented by the checker. Remediation remains governed: humans review proposals, Lich approves mutations, Kunkka applies deterministic patches only after approval, Roshan validates, and Underlord is involved only for paid escalation paths.

Governed Entity Cognition Architecture (Phase 8E Extension)

AncientOS extends portable personal AI continuity with governed entity cognition and persistent semantic continuity. This is a strict extension, not a replacement, of existing layers.

1. AncientOS Core (Authoritative)

  • Bounded deterministic runtime
  • Governed execution lanes and providers (Invoker, Tinker, Roshan, Commander, Kunkka, Codex) behind Lich approval
  • Capability manifests
  • Selector / proposal layers
  • Artifact lineage and audit logs
  • All execution remains approval-gated and replayable

2. Entity Cognition Layer (Derived)

  • Entity registry (people, systems, projects, decisions, incidents, capabilities)
  • Relationship edges with evidence/provenance links
  • Semantic provenance tracking
  • Entity timelines and state summaries
  • Semantic deltas and entity revisions
  • Derived Markdown export generation
  • All surfaces are projections of canonical artifacts

3. Human Cognitive Surface (Presentation Only)

  • Obsidian-compatible Markdown vault
  • Backlinks and readable summaries
  • Local-first inspection and navigation
  • Versionable, discardable, and fully regeneratable
  • Never treated as source of truth

4. Governance Boundary (Enforced)

  • Capability visibility ≠ authority
  • Semantic summary ≠ truth
  • Markdown view ≠ source of truth
  • Proposal ≠ approval
  • Approval ≠ execution until bounded executor applies validated operation
  • Semantic provenance must accompany every derived surface

5. Anti-Patterns / Prohibited Directions

  • Markdown-as-authority
  • Autonomous uncontrolled background agents
  • Opaque memory mutation
  • Direct entity graph writes bypassing governance
  • Electron-first architecture
  • SaaS dependency for core memory or cognition
  • Unrestricted self-modification
  • Hidden semantic drift
  • Unreplayable cognition transforms

This layered model ensures AncientOS remains: - governed - deterministic-first - artifact-backed - replayable - transport-neutral - bounded execution - offline-safe - fail-closed - approval-gated

while adding persistent semantic continuity through derived, inspectable surfaces.

Engineering Maturity Layer (Phase 13)

The cognition stack is sophisticated but the surrounding engineering surface has trailed it. Phase 13 adds the boring, load-bearing infrastructure that keeps the governed-cognition guarantees provably true at the implementation level — not just the architectural level.

Concurrency correctness

claim_next_queued_job previously did SELECT-then-UPDATE without a transaction or rowcount check. Two creep workers could both observe the same queued row and both proceed to execute it, producing duplicate artifacts that broke the replay/lineage contract. The function now uses BEGIN IMMEDIATE to acquire SQLite's RESERVED lock before reading, then asserts cursor.rowcount == 1 on the UPDATE and rolls back otherwise. Combined with WAL journaling, a 30 s busy_timeout, and synchronous=NORMAL, the claim becomes atomic under any plausible worker count.

sequenceDiagram participant W1 as Worker A participant W2 as Worker B participant DB as SQLite (WAL) W1->>DB: BEGIN IMMEDIATE W2->>DB: BEGIN IMMEDIATE (blocks) W1->>DB: SELECT queued LIMIT 1 W1->>DB: UPDATE -> running (rowcount=1) W1->>DB: COMMIT DB-->>W2: lock released W2->>DB: SELECT queued LIMIT 1 DB-->>W2: (none / different row) W2->>DB: ROLLBACK

Regression test: tests/test_claim_job_atomicity.py.

Centralized configuration

app/config.py exposes CONFIG, a frozen LunaConfig dataclass loaded once at import time. The worker consumes this typed configuration; bot.py and other modules still read environment variables directly. Centralization is partial, and a field in CONFIG does not prove that every runtime consumer uses it.

describe_config() returns a redacted dict suitable for health endpoints or audit logs — tokens, passwords, and API keys are reported as <set>/<unset> only.

Structured logging

Worker stdout previously emitted [creep-worker] claimed ... print lines. It now uses logging.getLogger("creep_worker") with the format LEVEL | ISO8601 | logger | message. The same shape will be adopted by bot.py modules during their extraction.

Engineering safety perimeter

  • .pre-commit-config.yaml rejects committed .bak* snapshots and new raw print() calls in app/.
  • .github/workflows/ci.yml runs compileall, pytest, pyright (non-blocking), pre-commit, and a docs-touched check on PRs.
  • scripts/cleanup_bak_files.py is a legacy manual utility; its apply path can delete after an archive failure and must not be used pending bounded retirement or repair. It is not an automatic maintenance loop.
  • CONTRIBUTING.md documents the branch-instead-of-bak-file workflow.

Wave 2 — Schema, observability, and DB ergonomics

The second wave extends Phase 13 with three additive systems:

Schema migration framework. app/migrations/ introduces a tiny in-house runner that discovers m_*.py modules, applies any not already recorded in schema_migrations, and stores each application with a timestamp and duration. Migrations are pure-Python callables; they are inherently idempotent (CREATE/ALTER guards) so the framework is defense-in-depth, not a single point of failure. _db() invokes the runner on every connection; warm databases incur a single EXCLUDE lookup. Baseline migrations (m_0001_baseline, m_0002_job_indexes) record schema fingerprints and add composite indexes for the hot job-claim path.

Runtime stats endpoint. app/runtime_stats.py aggregates job counts by status and executor, recent throughput (1 h and 24 h windows), stale-running detection (5 min and 30 min), schema migration history, SQLite file metadata and pragma snapshot, and a redacted config view. The bot's existing health server gains a new GET /stats endpoint returning this snapshot as JSON. python -m app.stats_cli provides the same view from the shell, with a --json flag for machine consumption.

graph LR A[curl :8000/stats] --> H[LunaHealthHandler] C[python -m app.stats_cli] --> R H --> R[runtime_stats.collect_runtime_stats] R --> J[(jobs table)] R --> M[(schema_migrations)] R --> P[SQLite PRAGMAs] R --> CFG[describe_config redacted]

Database ergonomics. db_conn() is a context manager that wraps _db() and guarantees connection closure even on exceptions. New code uses with db_conn() as conn:; existing try/finally call sites are grandfathered. The bot's module logger (luna_bot) now matches the worker's format so a unified log shape is available across services for new logging call sites.

Wave 3 — Typed boundaries and bug excavation

The third wave makes the wave 1 typed model and wave 2 migration framework load-bearing.

Typed Job model wired into the worker hot path. claim_next_queued_job and get_job now construct their return dicts via Job.from_claim_row / Job.from_full_row instead of indexing the raw SQLite row by integer position. The dataclass uses dict(zip(JOB_FULL_COLUMNS, row)) so column order is enforced by name, not by index.

Bug fix: get_job channel/parent shift. While wiring the typed model we discovered that get_job had been mapping row[1] to both objective_id and channel_id, and row[2] to parent_message_id — meaning every caller that read job["channel_id"] got the objective id instead, and every caller that read job["parent_message_id"] got the channel id. The typed model makes that shift structurally impossible: a missing or shifted column raises ValueError at the boundary. Regression test: tests/test_job_model.py::test_from_full_row_preserves_channel_id_and_parent_message_id.

This is the canonical example of why the engineering-maturity layer matters to the cognition stack: a quiet schema-shift bug in the lookup path is exactly the kind of failure that erodes AncientOS/Luna replay/audit guarantees without ever raising an exception.

Migration 0003 — canonical jobs schema. The historical inline CREATE TABLE IF NOT EXISTS + stacked ALTER TABLE ADD COLUMN blocks for the jobs, builder_objectives, and delegated_task_lifecycle tables are now codified in app/migrations/m_0003_canonical_jobs_schema.py. The inline calls in _db() remain as defense-in-depth, but the migration is the canonical schema reference and the obvious place for future column additions.

app/job_lifecycle.py import surface. The creep worker now imports claim_next_queued_job, complete_job, fail_job, update_heartbeat, update_job_progress, get_job, and get_job_status from app/job_lifecycle.py — a focused module re-exporting only the job-lifecycle API. Function bodies still live in bot.py (a full move would require extracting _db() first), but new code now has a stable, focused import target instead of pulling in the entire Discord bot module.

graph TD W[creep worker] --> JL[app.job_lifecycle] JL --> B[app.bot] B --> DB[(SQLite)] B --> M[app.migrations] B --> JM[app.job_model] JL -. future move .-> NEW[app.db + app.job_lifecycle]

Wave 4 — Physical module extraction

The wave-3 import surface (app/job_lifecycle.py) was a thin shim re-exporting from app/bot.py. Wave 4 makes the extraction physical: function bodies actually move out of bot.py.

app/db.py owns SQLite access. The connection factory (_db), context manager (db_conn), timestamp helper (now_ts), and the DATA_DIR / DB_PATH constants moved out of bot.py into a focused module. The new _db() body is 12 lines instead of 100+, because the inline CREATE TABLE / ALTER TABLE blocks for jobs, builder_objectives, and delegated_task_lifecycle are now codified in m_0003_canonical_jobs_schema.py and applied via the migration runner. The schema bootstrap order is now: SessionContextManager.ensure_schemaensure_self_improvement_schemaapply_pending_migrations.

app/job_lifecycle.py owns job state transitions. The bodies of claim_next_queued_job, update_job_progress, complete_job, fail_job, get_job, get_job_status, and classify_job_status moved here. Each function imports its dependencies from app.db and app.job_model only — no Discord, no governance kernel, no inference router. The creep worker can now run with app/bot.py essentially absent from its dependency graph.

Lazy cross-callbacks. complete_job and fail_job historically called mark_delegated_task_job_completed / mark_delegated_task_job_failed in bot.py. Those callbacks are now imported lazily inside the functions themselves, which breaks the circular dependency and means a callback failure cannot mask the underlying job state transition.

bot.py is now a re-export shim for these names. All previous public symbols (_db, db_conn, now_ts, DATA_DIR, DB_PATH, claim_next_queued_job, complete_job, fail_job, get_job, get_job_status, classify_job_status, update_job_progress) remain importable from app.bot for back-compat. New code should import from app.db or app.job_lifecycle directly.

graph LR W[creep worker] JL[app.job_lifecycle] DB[app.db] JM[app.job_model] MIG[app.migrations] CFG[app.config] B[app.bot] W --> JL W --> CFG JL --> DB JL --> JM JL -. lazy callback .-> B DB --> MIG B --> JL B --> DB B -. discord .-> X[Discord transport]

The arrow from bot.py to job_lifecycle.py is now the re-export shim; the arrow in the opposite direction is a lazy import that activates only when a callback fires. Cycles are broken, and the worker's dependency graph no longer crosses into the Discord transport.

Line accounting. bot.py shrank from 7,620 → 7,367 lines (-253). The four new modules total ~624 lines — larger because each function moved here also acquired a proper docstring and the migration framework absorbed ~100 lines of inline DDL that used to live in _db(). The governing module (bot.py) became smaller; the total code became slightly larger but is now organized along responsibility lines.

Bounded scope

Phase 13 is intentionally additive. It introduces no new execution authority, no new governance bypass, and no new external dependency inside the running container. Every artifact added is either developer tooling (CI, pre-commit, scripts) or read-only runtime configuration. The governance and replay properties of every other layer are unchanged.

Runtime truth model

AncientOS status is a composition of related but distinct facts:

  • architectural state defines components, capabilities, ownership, and dependency relationships;
  • policy and authority state defines what a named actor, capability, or execution lane may do;
  • configuration state records whether a specific integration or endpoint is configured;
  • runtime availability records whether a component or dependency is presently usable;
  • live operational evidence records current observations, timestamps, and evidence hashes;
  • discovery state records known repositories separately from currently permitted or indexed files; and
  • cognition state records the inert, request-scoped reasoning packages resolved after capability selection.

These categories do not override each other globally. Live evidence has priority for current claims within the evidence scope, while canonical architecture and policy remain authoritative within their own scopes. A configured integration is not necessarily reachable; an unavailable source is not an observed zero; and a source that was not queried is neither healthy nor unhealthy.

Broad AncientOS/ser6buzz status requests resolve through the transport-neutral runtime inspection stage. The current bounded bundle resolves Rubick capability IDs, invokes independently governed Beastmaster memory and disk observations, inspects the Rubick and architecture registries, records tools-gateway configuration separately, and performs bounded governed file discovery. Each datum carries a category, scope, source identity, source state, and freshness; live observations additionally preserve timestamps and evidence hashes.

Partial source failure produces partial status, not global failure. Fail-closed means that unavailable evidence or authority is never claimed as available. It does not erase verified facts from independent sources. Scoped authority limitations also remain scoped during synthesis and rendering: direct model shell authority may be prohibited while a separately governed host-inspection capability is available.

Capability resolution remains upstream of cognition resolution. Cognition explains operational semantics; live evidence represents current operational truth. Cognition packages cannot contain current runtime state, approve work, change policy, or alter capability availability.

The governed-action boundary also exposes a request-local prepared-action and execution-preflight projection. It reuses canonical capability truth and exact Lich bindings to describe what an existing governed executor would require, without creating an approval or invoking that executor. Keeper creation and allowlisted Home Assistant light state are supported preparation families; meeting action candidates can seed Keeper parameters as evidence only. Host service restart remains unsupported because no bounded governed restart executor is registered. A future execution path must rerun preflight and require approved_ready where Lich applies; approval alone is never treated as operational readiness. See Capability taxonomy.

The legacy CURRENT FOCUS and CHECKPOINT context labels represent bounded task-continuity documents only. Reader failures are source failures, not focus or checkpoint values, and these labels do not participate in canonical broad runtime health synthesis.

Governed financial-data provider

OpenBB ODP is an isolated external provider behind canonical AncientOS capabilities. Luna never receives arbitrary OpenBB URLs or a raw OpenBB MCP tool catalog. Shared semantic routing selects a Rubick capability, Lich evaluates the read-only external observation, the allowlisted AncientOS adapter calls the internal OpenBB REST service, and provider-attributed results become Zeus-style evidence before capability-driven cognition and transport-neutral rendering.

The initial slice covers OpenBB readiness, equity quote/history/profile, fundamentals, selected metrics, bounded multi-symbol comparison, and ETF information. TMX and Yahoo Finance are the installed no-credential providers. Direct model network authority remains prohibited; network access is encapsulated by the governed OpenBB provider. No brokerage, order, portfolio, credential mutation, trading, or prediction-market capability is added. See Governed OpenBB financial-data provider for deployment, evidence, boundedness, and licensing details.

The X provider and credential boundary keeps the verified owner-account OAuth1 signer inside x-feed-worker and returns only redacted identity/readiness snapshots to AncientOS. OAuth2 remains exclusive to the bookmark worker, billing is unverified, and every destructive X operation remains disabled.

Governed artifact materialization (roadmap, 99416a07401a)

Capability

  • Governed artifact materialization produces reviewed documentation updates for artifact, materialization, bundle, lineage, lich, confirmation.
  • Materialized content is generated from deterministic templates, not copied from the operator prompt.

Governance Model

  • The roadmap artifact remains bounded to approved documentation roots.
  • Governance metadata records target selection, content digest, and materialization lineage.
  • Replay metadata preserves the selected target, content hash, and intent classification.

Execution Flow

  • LegionCommander classifies the objective into artifact intents.
  • The materializer selects a bounded documentation target for each intent.
  • confirmation_runner queues artifact_execute only after Lich approval.
  • artifact_patch_safe writes the approved bundle and records worker result metadata.

Safety Boundaries

  • Runtime code execution policy is not broadened by artifact materialization.
  • Source, test, script, generated API, secret, absolute, and traversal paths remain denied.
  • Architecture impact is limited to the governed artifact lane and its audit metadata.

Current Limitations

  • Generated prose is intentionally template-bounded and does not infer unobserved implementation details.
  • Ambiguous equal-score targets fail closed for human repair instead of guessing.

Future Roadmap

  • Track follow-up milestones as explicit documentation artifacts instead of runtime code changes.

Luna pending-approvals workflow

The pending-approvals workflow is a transport-neutral view over the durable composed Lich service. Lich remains the sole approval authority. Its projection distinguishes unavailable from empty, classifies plan review and implementation authorization separately, and supplies independently bound exact decision controls. Discord and Web TUI consume that representation without owning state or governance semantics; Oracle consumes a minimized read-only view without controls. Successful review does not cascade into authorization or execution.

Governed artifact materialization (roadmap, 0d7502af4462)

Capability

  • Governed artifact materialization produces reviewed documentation updates for artifact, materialization, lineage, lich, confirmation, approval.
  • Materialized content is generated from deterministic templates, not copied from the operator prompt.

Governance Model

  • The roadmap artifact remains bounded to approved documentation roots.
  • Governance metadata records target selection, content digest, and materialization lineage.
  • Replay metadata preserves the selected target, content hash, and intent classification.

Execution Flow

  • LegionCommander classifies the objective into artifact intents.
  • The materializer selects a bounded documentation target for each intent.
  • confirmation_runner queues artifact_execute only after Lich approval.
  • artifact_patch_safe writes the approved bundle and records worker result metadata.

Safety Boundaries

  • Runtime code execution policy is not broadened by artifact materialization.
  • Source, test, script, generated API, secret, absolute, and traversal paths remain denied.
  • Architecture impact is limited to the governed artifact lane and its audit metadata.

Current Limitations

  • Generated prose is intentionally template-bounded and does not infer unobserved implementation details.
  • Ambiguous equal-score targets fail closed for human repair instead of guessing.

Future Roadmap

  • Track follow-up milestones as explicit documentation artifacts instead of runtime code changes.