Chapters

DOC-04 / Technical reference · Chapter 03

Agentic core: Atlas and the agents

This chapter describes the architecture of Synedre's agentic engine, from the LLM-based classification of incoming emails to post-spawn orchestration (preprod deployment, QA, recap), including the data model of the 33 CodeMyShop agents.

Agentic Core Overview

The agentic core is the engine that transforms an incoming email — or a project task — into an executed action. It chains together intent and complexity classification by a large language model, the launch of a Claude Code agent in non-interactive mode inside an isolated workspace, injection of the designated agent's persona, and then post-execution orchestration: staging deployment, automated quality control, and a summary email.

The core rests on two fundamental building blocks:

  1. The orchestrator (public codename: Atlas). This is the directing agent, the sole representative of orbit ring 0. It does not hold a permanent autonomous runtime: "being Atlas" means launching a Claude Code session in prompt mode with a briefing system specific to its role. Concrete orchestration is handled by a Python classification/spawn module and a Node bridge that manages the pseudo-terminal.
  2. Specialised agents (33 in total, active in the database). These are personas — identity, cognitive frame, and business perimeter — injected into a Claude's context at the moment of executing a task.

Main pipeline — "Atlas Inbox"

The standard flow of an incoming email unfolds in four steps:

  1. Ingestion. An IMAP collection component continuously polls the orchestrator's inbox, idempotently inserts each message into the email messages table, creates a tracking entry with status received, then marks the message as read.
  2. Classification. The classification engine queries a large language model (via the internal AI facade) to determine the message's intent from among: run, question, noise, negociation, conseil — and its complexity (leger or plan, relevant only for run). It then materialises the corresponding entity in the database (task, question, negotiation, or advisory) and advances the status to classified.
  3. Agent spawn. The spawn component filters on the whitelist of actionable intents (run, question, negociation, conseil), then launches a Claude Code session via a real pseudo-terminal inside an isolated Git worktree, with the Atlas briefing injected. The session operates in "code + commit only" mode and writes its result to a structured temporary file before terminating.
  4. Post-spawn. The orchestrator takes over: staging deployment, execution of the Playwright test suite, dispatch of the summary email, status update to actioned. If tests fail, the orchestrator may relaunch the agent up to three times.

Note — The chantier intent no longer exists. Since mid-2026, the classifier never produces intent='chantier'. What would formerly have constituted a chantier is now processed as run + complexity='plan': enriched prompt, unlimited turn count, full deployment + QA. Promotion to a formal chantier remains possible, but it is exclusively manual via the --link-chantier option of the CLI interface.

Note — Ingestion and scheduler. It is the IMAP collection component itself that automatically chains antivirus analysis followed by classification after each insertion. It is not the Nitro scheduler (which drives a separate batch of tasks) that loops the pipeline end to end.


Agent Model

Database storage

Agents are stored in a central physical table. A compatibility view exposing the same columns allows the various application layers (Python on the harness side, Nuxt/Drizzle on the interface side) to access the same data under two historical names. This coexistence is the legacy of a progressive migration between two namespaces.

Key columns

Column Type Role
codename varchar(64) Lookup key, kebab-case format, unique. Examples: orchestrator, backend, seo-technique.
nickname varchar(64) Public alias of the agent. Examples: Atlas, Gauss, Mitnick, Otlet.
role varchar(255) Job title. Example: "SEO Technical Officer".
group_name varchar(64) Functional family, one of: direction, cadrage, execution, validation.
orbite integer Orbit ring (0 to 3). Ring 0 is reserved for Atlas alone. ⚠️ Does not always coincide with the visual ring displayed in the interface.
heritage varchar(255) Geographic or historical anchor of the persona. Example: "Ancient Greece" for Atlas.
cognitive_frame text "Way of thinking" — the agent's four cognitive dimensions, injected with highest priority into the briefing.
personality, quote, inspiration, proof text Rich identity fields, used in the full briefing tier only.
job_mission, job_perimeter, job_key_checks text Business perimeter of the agent.
content_md text Long Markdown profile, consumed by the direct invocation component.
active integer 1 = agent eligible to be recruited for a task.
prompt_domains varchar(255) CSV list of prompt domains (content, faq, cover…) for routing to the appropriate agents.
auto_spawn, spawn_count, error_count integer Agent runtime counters.

EN internationalisation columns are present as mirrors for the main text fields (role_en, heritage_en, cognitive_frame_en, etc.).

Satellite tables

Several tables orbit the main agents table to store their activity, events, availability heartbeats, relationships, skills, tools, and experience history. For some of these tables, a compatibility view with the former namespace also exists — but not for all: the events, skills, and tools tables have no mirror view.

Dormant table. A table dedicated to per-agent fine-tuning configuration has been present in the database since a recent migration, but no component in the repository reads from or writes to it to date. It most likely represents the schema preparation for a project not yet delivered. It is outside the functional scope for as long as no caller references it.

Nuxt module restructuring. A former monolithic agents module has been split into two distinct modules:

  • The interface module hosts Vue components, hub pages (reactor, terminal cockpit, Git health utilities), and serves no API routes of its own.
  • The engine module contains the DB schemas, database connection utilities, and all Nitro API routes for the agents domain (agent list, reactor state, prompt agent routing, project management, etc.).

Persona loading

Before a Claude executes a task, it "becomes" the designated agent. The persona loading component assembles a multi-layer bundle:

  • Identity, thinking, and perimeter: read from the agents table.
  • Relevant scars: selected by vector search (pgvector) in the embeddings table, prioritising scars belonging to the agent in question, then supplementing with global scars. The explicit objective is to prevent an agent from seeing another agent's lessons as its primary context.
  • Mission letter of the associated project, if resolvable.
  • User preferences (slice of the primary account configuration).

Three rendering levels are calibrated by token budget, in order to limit attention dilution and maximise the prompt cache hit rate (TTL ~5 minutes on the Anthropic side):

Level Indicative budget Content Use case
Core ~150 tokens Cognitive frame only + minimal identity Fast-path without code, Task sub-agents
Business ~350 tokens Core + role + business perimeter Default for Atlas spawn and the task worker
Full ~600 tokens Business + historical anchor + quote + personality + inspiration + proof Agent review, drill, mission letter

The Business level serves as the default alias for backward compatibility with existing callers.

Direct invocation component (legacy path)

A direct invocation component — older in design — allows launching an agent via Claude as a subprocess and logging the session in the Reactor. It remains actively called: on one side by the internal AI facade when it delegates to Claude in CLI mode (cf. the section on plan management), and on the other side directly by several automation processes (LLM detector, forum source resolution, SEO optimiser, netlinking contact discovery…).

Database migration complete. This component historically read scars and doctrines from a MySQL/MariaDB database. That is no longer the case: it now connects exclusively via the internal PostgreSQL connector (the source code itself labels it the "PG connector post-MariaDB death"). It reads scars and doctrines from their respective PostgreSQL tables.

Persistent watch point. The scar and doctrine loading functions silently absorb their exceptions: on error, they return an empty string without raising any visible alert. A profile can therefore be assembled without scars or doctrines without any error being propagated.

Atlas the orchestrator — the spawn mechanism

Restricted role of the spawn

The Atlas spawn selects one of three system prompts based on the nature of the request and its estimated complexity:

Case Prompt used Role
Request of type run, light complexity (default) Condensed prompt ("lean") Essential guardrails + minimal result interface, without build ceremony.
Request of type run, plan complexity Rich prompt + plan doctrine addendum "Proof by mutation before code" doctrine — equivalent to the former build mode.
Other intent (question / negotiation / advice) or unknown intent Rich prompt, unchanged Open behaviour: a misclassified run is never constrained.

Both rich variants strictly frame the spawned agent: investigation, code writing, Git commit — nothing else. Deployment, email sending, and message status updates are handled by the Python orchestrator after the spawn ends. The scope guardrails written into the prompt restrict modifications to the dedicated spaces of each tenant; no shared public component must be touched.

"Early checkpoint" instruction

Both prompts instruct the agent to write an intermediate result file as early as possible — from the very first partial diagnostic — and to overwrite it after each major step forward. The rationale is straightforward: if the agent is interrupted by a timeout, the last persisted state allows the orchestrator to compose a salvage alert for the operator. A partial file is better than nothing.

This mechanism has been reinforced: in the event of a timeout, the orchestrator directly inspects the working directory (Git commits, checkpoint file even if partial) to reconstruct the context, without relying solely on the final contract file.

Isolated worktree

Until a recent architectural update, each spawn executed within the repository's shared trunk, whose Git index is shared across all concurrent sessions. A git stash left by one spawn had been sufficient to block the merge-back of all other lanes in progress.

From now on, the orchestrator creates an isolated worktree by default for each spawn: a dedicated branch, forked from the pre-production branch, with automatic merge-back after commit, conditional on trunk cleanliness. An environment kill-switch allows reverting to trunk behaviour; any failure of the worktree mechanism (tool unavailable, timeout, missing path) also falls back to trunk — the fallback is safe, no run is lost.

Candidate selection for spawning

The candidate selector queries the Atlas message table to retain only entries:

  • whose status is classified;
  • whose classified intent belongs to the set {run, question, negociation, conseil};
  • with no spawn audit (started, completed, or failed) dated less than one hour ago — anti-double-spawn idempotency.

The query also returns the associated project identifier and the estimated complexity (default value: light). The former is used for AI model routing; the latter determines which system prompt to use.

Safety constants

  • Allowed intents: run, question, negociation, conseil. The noise and chantier intents are excluded from automatic spawning (chantier removed as an autonomous intent; conseil added to auto-spawn simultaneously).
  • Maximum spawns per cycle: 3 — protection against runaway costs.
  • Timeout: 40 minutes. It is the Python orchestrator that enforces this cutoff within its own loop reading the agent's output stream. On the Node wrapper side, the --timeout-sec parameter is now only a diagnostic signal (see the activity watchdog section).
  • Global kill-switch: an environment variable allows automatic spawning to be disabled entirely.
  • Default model: Sonnet. This default is however overridden by the unified model resolver, which applies a precedence order: client authorisation > project doctrine > recommended model, with a terminal proxy health check. The project identifier associated with the message is used to resolve the project doctrine and, consequently, to activate a possible model veto on the email path.

Vigilance note: the module documentation header states a timeout of 10 minutes — this value is outdated. The effective constant in the code is 40 minutes. This page uses the actual values from the code.

Anti-race: database advisory lock

To avoid collisions between automatic scheduling (every 5 minutes) and a simultaneous manual invocation, the orchestrator acquires a session-level advisory lock in the database before each spawn. If the lock is already held by another process, the spawn is skipped and a spawn_skipped_lock_held audit record is written. The lock is released automatically when the connection closes or when the holding process terminates.

Client resolution and prompt construction

Actual client resolution

An email forwarded by the operator always carries the operator's address in the sending envelope — the actual sender (the client) lives only in the body of the forwarded message. The vast majority of Atlas emails transit through the operator in this way. The client resolver applies three rules in order:

  1. If the sending envelope matches a known client directly → direct resolution.
  2. Otherwise, if the envelope belongs to the operator or a forwarding marker is detected in the body: extraction of the original From: header quoted in the body, then matching against the client database → resolution via forwarded body.
  3. Otherwise → unknown client. The caller must treat this case as a hard failure if the message is indeed a forward: no project routing, no silent fallback.

The matching excludes non-identifying addresses: the operator's address and public-domain addresses (generic mail providers). A backward-compatibility function that inspects only the envelope is retained for legacy use cases; it always returns unknown on a forward and must not be used for the main email path.

Prompt construction

  • Initial prompt: assembles the forwarded email body, the resolved tenant/client, the output of the classification engine (intent, complexity, confidence, justification), the discussion thread, an attachment block, and an optional infrastructure summary.
  • Re-spawn prompt (after QA failure): includes previous commits, errors detected at the HTTP and browser levels, and a dedicated block for layout compliance discrepancies — the compliance gate is now integrated into the correction loop.

Spawn contractual deliverable

Before terminating, the spawned agent must write a structured result file to a temporary directory. Two contracts coexist depending on the prompt used:

Prompt variant Contract fields
Rich prompt / plan Success status, tenant, routes to submit to QA, completed commits, Markdown summary, reply draft for the user.
Condensed prompt (light run) Success status, tenant, completed commits, Markdown summary — fields read with safe default values on the orchestrator side.

This file is what the orchestrator reads after the spawn ends to decide on the next steps: triggering QA, sending the reply to the client, updating the message status.

Programmatic invocation via a real pseudo-TTY

A fundamental rule of the orchestration system requires that any agent launched programmatically go through a real pseudo-TTY (pty), never through a direct Python subprocess.

Why a pty is mandatory

Launching the agent via a standard Python subprocess causes a silent deadlock (buffer deadlock): the structured streaming output mode detects that the file descriptor is not a terminal (isatty() returns false) and refuses to process the prompt passed as an argument. A pty of type xterm-color bypasses both pitfalls simultaneously.

Call chain

During a spawn, the system writes the prompt and the selected system prompt to temporary files, resolves the execution directory (isolated worktree by default), then launches the Node spawn bridge with the following parameters:

node <spawn-bridge> \
  --id <ID> \
  --prompt-file <prompt-file> \
  --system-prompt-file <system-file> \
  --model <resolved-model> \
  --stream-log <log-file> \
  --add-dir <working-directory> \
  --timeout-sec 2400 \
  [--max-turns <N>]

The --max-turns parameter is only set if the intent/complexity combination returns a value greater than zero. The measured default value (40 turns) covers the observed real-world median; a value that is too low (12 turns, set by intuition) covered only 24% of actual executions and cut off committed work at zero. The value remains unlimited for intents of type planning or for any intent outside direct execution.

The Node spawn bridge

The spawn bridge is a Node script that creates the pty and drives the agent. Its key behaviors:

  • Arguments forwarded to the agent: the bridge composes a precise command line including the structured JSON stream output format, session options, the system prompt appended at the end, and the appropriate permissions mode.
  • Critical ordering of --add-dir: this flag must unconditionally precede all other arguments. If placed after them, its variadic behavior "swallows" the prompt as an additional directory, making execution silently incorrect.
  • Dynamic sections excluded from the system prompt: the current directory, environment variables, memory paths, and git status are moved to the first user message. This move makes the system prompt prefix byte-identical from one spawn to the next, enabling a cache hit on the AI provider side despite the absence of session persistence.
  • Restricted tool suite by default: a strict curation mode is enabled by default, avoiding the loading of the extended tool suite (user-level third-party integrations, approximately 15 seconds of additional latency). This restriction applies only to MCP tools — safety hooks remain loaded at all times. The full suite can be enabled via a dedicated environment variable.
  • Forced pty environment: the bridge enforces a set of environment variables guaranteeing that the agent connects to the local database and identifies itself as a task worker. The database password is inherited from the parent environment without being rewritten.
  • Real-time JSONL emission: each stream event is emitted to standard output and optionally recorded in a log file. The result event type is detected on the fly and on the last partial line at the time the pty closes.

Exit codes and activity watchdog

The spawn bridge emits an enriched exit code allowing the nature of the termination to be distinguished:

Code Meaning Recommended behavior
0 Success (result with no error) Normal finalization
125 Killed by idle timeout (prolonged silence — agent stalled) Retryable — session resume
124 Killed by hard timeout (absolute ceiling exceeded — agent drifting) Retryable — session resume
1 Actual agent failure Error analysis required
2 Invalid arguments Configuration fix required

A wrapper event of type node_pty_exit is emitted at the end, with a reason field taking the values ok, idle, hard_timeout, or error.

The activity watchdog replaces the former fixed cutoff. Two guards run in parallel:

  • Idle timeout (default: 20 minutes of total silence on the stream) → exit 125.
  • Absolute hard timeout (default: 110 minutes) → exit 124.

The Python-side read budget (default: 2,400 seconds) remains the effective cutoff for the orchestrator's email processing path, applied independently by the Python read loop.

Live event persistence

On the Python side, each JSONL line is parsed and persisted in real time into the spawn event journal: sequence number, event type (sub-typed into stream events, system events, or tool results), called tool name, and full JSON payload.

Sensitive data leak prevention: each event passes through a filter that strips personally identifiable information and secrets (passwords, API keys, tokens) before any write operation — whether to a temporary file or to the database. An emergency switch allows this filter to be disabled if necessary for debugging.

The event journal is implemented as an updatable view on top of its physical table — as are other views in the same system. Inserts through the view operate normally. This journal makes it possible to diagnose a stall (the last event visible in the database indicates where the agent stopped) and to aggregate cost, duration, and token consumption from the final result event. All operations are also audited in the general audit log.


Execution theory: Turn and Cycle

Beyond the mechanics of pty invocation, agent execution is organized according to three levels of scale articulating the model and the runtime.

  1. The global mission: the macro-objective assigned to the agent (for example: "Fix the cart validation bug on the API").
  2. The cycle: a complete functional milestone backed by a sub-objective (observe, form a hypothesis, act, verify).
  3. The turn: the raw call to the model and the execution of a tool (tool_call → tool_result).

The fundamental Turn vs. Cycle distinction

The distinction rests on the level of abstraction:

  • The turn: a mechanical, sequential unit at the protocol level (one request sent to the model → text generation or tool call → system return). It is measured in input/output tokens, per-call latency, and adherence to the turn ceiling.
  • The cycle: a logical, teleological (goal-directed) unit of decisional feedback. It validates or invalidates a step of the task and aggregates one to several turns. In a multi-agent context, a cycle denotes a complete orchestration round before synthesis.
Dimension Turn Cycle
Analysis level Protocol / raw model Agentic logic / Architecture
Question asked "What is the next action?" "What is the current state of progress on the task?"
Typical content 1 prompt + 1 completion (or 1 tool call + 1 return) Evaluation → Planning → Action(s) → Feedback
Multiplicity Always 1 model call Aggregates 1 to N turns
Concrete example Running a grep and receiving the output Finding the root cause of a bug, fixing it, verifying that tests pass

Why a mission requires multiple cycles

A mission almost always requires a succession of cycles for three structural reasons:

  1. Success evaluation: at the end of a cycle, the agent tests whether the sub-objective has been reached. If not, it opens a new cycle armed with the error data.
  2. Context compaction: closing a cycle allows the acquired knowledge to be summarized, verbose tool outputs to be archived, and the next cycle to begin with a lighter context window.
  3. Adaptive planning: the course of cycle N+1 depends directly on the discoveries made during cycle N.

Example on a regression:

  • Cycle 1 — Diagnosis: Turn 1 (grep search) → Turn 2 (middleware read) → Turn 3 (reproduction test). End of cycle 1: root cause identified.
  • Cycle 2 — Fix: Turn 1 (code patch) → Turn 2 (compilation). End of cycle 2: code is clean.
  • Cycle 3 — Validation: Turn 1 (test suite) → Turn 2 (coverage check). End of cycle 3: validation successful — or opening of a Cycle 4 remediation.

The clockwork analogy: Mission, Cycle, Turn

The complementarity of the three scales can be illustrated by a clockwork analogy:

  • The mission (the dial, the 24 hours): completing the full traversal and returning to the starting point. The loop closes the end onto the beginning — as soon as the maintenance pass completes, the next traversal begins.
  • The cycle (the hour hand): each hour forms a self-contained world with a precise critical objective that must be validated before moving to the next.
  • The turn (the second hand): the elementary operations that advance execution within a given hour.

Without this loop, the linear context is exhausted; with it, the mechanism resets at each completed cycle without losing its state.

Anatomy of a turn in five phases

Every agent turn is systematically broken down into five steps:

  1. Context aggregation (Observation): compilation of the system prompt, history, environment, and the result of the previous action.
  2. Inference and decision (Reasoning): model reflection and decision to respond or call a tool via a structured payload.
  3. Runtime interception (Action): generation suspended; the tool call is read and executed by the harness.
  4. Return capture (Feedback): output stream captured, anti-context-saturation truncation applied, encapsulated in a tool result.
  5. Completion evaluation: immediate loop-back if the task requires another turn, or control returned to the caller.

Cycle configuration depending on the runtime used

The degree of configurability depends on how open the runtime is:

  • Agent CLI (closed): the internal feedback engine is not modifiable, but cycles can be framed declaratively via the project instructions file, interactive pauses on sensitive permissions, and custom state tools.
  • API harness (LangGraph, custom): full algorithmic control of the state machine — per-cycle turn ceiling, strict exit criteria on return code or LLM judge, custom compaction between cycles.
  • Sandbox environments: infrastructure-driven control via reversible memory/disk snapshots on cycle failure, and parallelization of exploratory cycles on cloned sandboxes.

The three critical friction points

  1. Context bloat: uncontrolled accumulation of logs and outputs saturates the attention window and increases costs.
  2. Infinite repair loops: risk of sterile repetitive correction without a strict cap on the number of turns.
  3. Determinism management: irreversible actions on system state require automatic versioning or cycle snapshots.

Anatomy of a raw transcript and ultra-compaction techniques

The execution transcript is materialized as a JSONL file — one complete JSON object per line, corresponding to one turn. Minimal example ("Create hello.txt with 'Hello World' and verify"):

{"role":"user","content":[{"type":"text","text":"Create hello.txt with 'Hello World' and verify its content."}],"timestamp":"2026-09-21T07:15:00.000Z"}
{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants to initialize a hello.txt file and inspect its creation. I will use the bash command to write the text and then cat to verify."},{"type":"tool_use","id":"call_123","name":"Bash","input":{"command":"echo 'Hello World' > hello.txt && cat hello.txt"}}],"timestamp":"2026-09-21T07:15:02.100Z"}
{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_123","content":"Hello World\n","is_error":false}],"timestamp":"2026-09-21T07:15:02.450Z"}
{"role":"assistant","content":[{"type":"text","text":"The file `hello.txt` has been created and correctly contains `Hello World`."}],"timestamp":"2026-09-21T07:15:03.200Z"}

In a real session, each command injects thousands of characters into tool_result and thinking blocks. Four rules make it possible to reduce token consumption by 70 to 90% without degrading the model's comprehension:

  1. Purge reasoning blocks from past turns: intermediate reasoning is indispensable at decision time, but becomes dead weight once the action has been carried out. Keep the reasoning block only for the very last current turn, and purge it for all archived turns.
  2. Aggressively truncate tool outputs:
    • Head-tail strategy: if the output exceeds 20 lines, keep only the first 5 (launch context) and the last 10 (result/error), with a synthetic marker: [... N lines omitted ...].
    • Zero-status rule: if a command exits with code 0 and no warnings, replace the dump with a minimal sentinel: status: ok (exit 0).
  3. Eliminate terminal pollution: strip ANSI escape codes (colors, cursor movements) and spinner or progress-bar refresh sequences — keep only the final state.
  4. Semantic compaction via milestones: overwrite a batch of trial-and-error turns with a single summary object as soon as a milestone is validated:
    {
      "role": "system",
      "content": "Milestone validated [fix-typescript]: typescript@5.8.3 and vue-tsc@2.2.12 added to dev dependencies. Unit test passed (exit 0). Modified files: package.json, package-lock.json."
    }
    
    This condensed record replaces 15,000 tokens of raw noise with 40 tokens of contextual certainty.

Intent Classification and Complexity

Recognized Intents and Complexity Dimension

The classification engine recognizes five possible intents: run, question, noise, negociation, and conseil. The "chantier" mission type was removed from this set in July 2026: the complexity of a piece of work is now expressed in a separate field, complexity, never in the intent itself.

The complexity field is only relevant when the intent is run; for any other intent it is forced to its minimum value. Two values are accepted:

  • leger — atomic, one-off task, processed in a single direct pass with no prior structuring.
  • plan — cross-cutting or multi-step task (new feature, refactor, audit, migration); a plan and a non-regression test must be written before any code change. This mode replaces the former chantier intent downstream in the pipeline.
Intent Meaning Downstream effect
run (complexity leger) Atomic task executable in a single pass Creation or update of a lightweight run entry in the work registry
run (complexity plan) Cross-cutting or complex task — replaces the former chantier intent Same registration, but full pipeline with deployment, QA, and unlimited rounds; manual promotion to chantier available via the dedicated option
question Request for an opinion or analysis, response expected as a draft Creation of an entry in the question registry
noise Newsletter, spam, or non-actionable content No action (no-op)
negociation Inbound commercial request (prospect, quote) Creation of an entry in the negotiation registry
conseil Request for expertise or advice, explicit or implicit (forward "FYI" of a technical alert), with no execution instruction Creation of an entry in the advisory registry

Each materialization is mutually exclusive and idempotent: unique indexes and application-level guards prevent any duplicate creation. The generated identifier is traced in the source email record.

Automatic attachment to an existing open chantier — distinct from creation: for the run and question intents only, the system attempts to attach the incoming email to an already-open chantier whose subject matches. When a confident match is found, the link is set automatically; otherwise, no action is taken. Creating a chantier remains strictly manual.

LLM Engine

Calls to the language model always go through the unified AI provider facade — no direct call to a third-party SDK is permitted. Routing is resolved dynamically; the default provider and model are configured in the atlas_classifier routing file. Output is expected as structured JSON, with a 30-second timeout.

Guardrails

Several protection layers govern classification:

  • Priority of direct text over quoted content: the email body is split into two zones — the immediate sender's text ("cover") and quoted or forwarded content ("quoted"). The prompt explicitly instructs the model that the cover always takes precedence over the quoted section for intent determination. A "FYI" forward is judged on the substance of the quoted content, not on the form of the enclosing message.
  • Verified client context injected from the database: if the sender matches a known tenant, a context block (priority, status, monthly recurrence) is injected before the email body, explicitly marked as originating from the database — and therefore not forgeable from the message body.
  • Prompt injection protection: the body is wrapped in fixed delimiters signaling to the model that it contains raw data, not instructions. The body is truncated to 8,000 characters.
  • Strict enum validation: any intent outside the known list, and any confidence score outside the interval [0, 1], is rejected.
  • Automatic confidence floor: a score below 0.5 switches the intent to noise.
  • Uncertainty threshold: a score below 0.7 triggers a classification_uncertain audit for review.
  • Two pre-LLM short-circuits, conditioned on DKIM validation (fail-closed): the sender address and subject are entirely forgeable without cryptographic proof. These two shortcuts therefore only fire if DKIM validation for the email is confirmed (computed at ingestion and persisted in the database):
    • A re-forward of an Atlas summary by the founder is forced to noise to avoid a costly empty spawn.
    • Validation copies auto-generated by the pipeline itself are forced to noise — without this guardrail, the model read the summary content as a human instruction and incorrectly classified it as run or question.
  • Block on unsafe attachment: classification is blocked if an attachment carries an antivirus verdict other than clean.
  • False-noise protection for the founder: if an email is classified as noise but originates from the founder and contains attachments, the intent is switched to question. Actionable content may reside in a screenshot that the text-only model cannot perceive.
  • Paying-client silence protection: noise is the only intent that materializes no downstream action — the only silent failure mode of the pipeline. If the actual sender (envelope only, never the body) matches a client with a confirmed positive monthly recurrence, a final noise is switched to question. The restriction to the envelope is intentional: the inbox authenticates no one on the message body side — relying on the body would have allowed any spam to trigger an agent with elevated permissions.
  • False-negotiation downgrade: if an email is classified as negociation but the actual sender is an existing client, the intent is reclassified as run scoped to the relevant tenant. The conseil intent is explicitly excluded from this downgrade: an existing client may legitimately request technical advice without that constituting a negotiation. When the downgrade applies, complexity is forced to plan — a model that has evaluated a negotiation has no information about the actual complexity of the underlying work, and forcing leger had previously caused the premature termination of an in-progress run.

At the end of classification, the email record is updated with the retained intent, complexity, confidence score, model used, textual justification, and the classified status. A classified audit event is emitted.

OCR Enrichment

Before the language model call, if attachments are present and the antivirus verdict is clean, the system extracts visible text from attached images using a local OCR engine (Tesseract) — no cloud service is involved.

The extracted text is appended to the context sent to the model, wrapped in its own delimiters, allowing the classifier to take screenshot content into account.

Privacy: OCR text is never persisted in the database (potentially personal data). It is used solely in memory during the classification cycle. Only an ocr_extracted audit event is recorded, indicating the character count and the approximate number of images processed.

This step was introduced to correct silent misclassifications (noise) on emails whose actionable content resided exclusively in attached screenshots — a text-only model being unable to perceive those images by default.

The two parallel AI routers

The harness runs two distinct multi-provider AI routing systems, sharing neither code nor configuration. This is not an accidental duplication: they serve two different runtimes. Knowing which one to modify depends on the development context.

Axis Python router (automations) TypeScript router (Nuxt hub)
Runtime Scheduled automations, nightly loops, callbacks, classification, pedagogical orchestration… Nuxt hub runtime (server API endpoints)
Public surface embed(...) + complete(...) generateContent(req) + provider resolution per client
Supported providers Embed: Mistral / Voyage / OpenAI; Complete: Claude / Mistral / OpenAI / DeepSeek Mistral / Anthropic / OpenAI
Routing source AI routing table in the database (replaces the former YAML configuration file, which no longer exists) Per call (provider specified in the request) or per client (JSON config stored in the database)
Default provider Embed → Mistral; Complete → Claude Mistral
Claude call Delegated to the agent invocation engine (subprocess) Direct HTTP via a dedicated helper
Doctrine Mandatory pass through the validated facade (feedback hook) Internal Nuxt module service, not guarded by hook

The full details of the Python router (embed/complete logic, AI routing table, retries, guardrails) are documented in the Memory & Learning chapter. This section describes its TypeScript counterpart, symmetrically.

Silent failure observability: the complete() function of the Python router resets a module-level variable at each call — this variable stores the last recorded failure. Any completion path returning None first writes its reason there, which the caller can then read via a dedicated function. A caller receiving None is therefore no longer faced with total silence — it can read why the completion failed. The variable is reset at each entry into complete() to never serve a stale failure.

The single entry point of the Nuxt runtime

generateContent(req) is the single entry point of the Nuxt runtime for text generation. Its signature accepts: prompt, systemPrompt (optional), provider (optional), model (optional), maxTokens (default 4,096), temperature (default 0.7). The response is normalized: generated content, provider that actually responded after any fallback, model used, tokens consumed (input/output), duration in milliseconds.

  • Default provider = Mistral — a sovereignty choice (FR data, EU API), consistent with the Python router's default embed.
  • Default models: Mistral → mistral-large-latest; Anthropic → claude-sonnet-4-6; OpenAI → gpt-4o.

Automatic fallback — sovereign order

The defined fallback order is Mistral → Anthropic → OpenAI. At call time, the system builds the effective order by placing the requested provider first, followed by the others in sovereign order, then iterates:

generateContent(req)
   effective provider = req.provider ?? 'mistral'
   order = [provider, ...FALLBACK_ORDER \ provider]
        │
        ▼   for each provider in the order:
   API key absent? ──yes──► skip (next provider, silent)
        │ no
        ▼
   call provider  ──success──► return { provider, durationMs, ... }
        │ exception
        ▼
   last provider in order? ──yes──► error "All AI providers are unavailable"
        │ no
        ▼
   log "Fallback → next provider"

Two conditions trigger a move to the next provider:

  • API key absent: silent skip, no error raised.
  • Exception on call: caught, move to next with log.

When a fallback switch occurs, the model used is realigned to the fallback provider's default model — not to the model requested for the initial provider. The provider field in the response reflects who actually responded, which is useful to log on the caller side.

All three providers are called via direct HTTP with a 120-second timeout. Mistral and OpenAI share an identical message format (optional system + user).

Verified latent debt: the Anthropic link in the fallback chain relies on a helper (callAnthropicRaw) that is not available within the standalone Nuxt hub scope. This helper exists in another sub-project of the repository but is not imported there. Expected consequence: a call to the Anthropic provider raises a ReferenceError, caught by the fallback loop's try/catch, causing an automatic switch to OpenAI. The Anthropic link is therefore non-operational until the helper is ported. To be confirmed: this is a static finding; no real caller currently requests Anthropic via this router.

TypeScript router API keys

API keys are resolved solely by environment variable name, with no values in the code or in this documentation. A missing key is not an error: it simply causes the corresponding provider to be skipped in the fallback loop.

Provider Environment variable Carrier file (gitignored)
Mistral The Mistral API key .env / .env.host
Anthropic The Anthropic API key .env / .env.host
OpenAI The OpenAI API key .env / .env.host

Provider choice per client — tenant config resolution

A dedicated function reads a client's AI configuration from the database and returns the { provider, model } pair to use for that client. It queries the JSON configuration column of the client VPS table, filtering on active entries only. The JSON is parsed and two keys are extracted:

  • AI provider → defaults to mistral if absent;
  • AI model → defaults to the provider's default model if absent.

Any error (unknown client, invalid JSON, helper failure) falls back silently to Mistral with its default model. A client whose entry is marked inactive is never returned, even if its configuration specifies a provider.

Actual state observed in the database: the large majority of active clients have the AI provider field unset in their configuration (→ sovereign Mistral by default). Only two clients set it explicitly — one of which points to Anthropic, which would in any case fall back onto the callAnthropicRaw debt described above if a caller were to use it.

Noted discrepancy: the per-client provider resolution function has no active caller in the Nuxt hub. Actual consumers of generateContent pass the provider hard-coded in the request and never query the client configuration. Per-tenant routing is therefore wired but not yet connected to the generation flow.

Actual callers of the TypeScript router

Important correction: a previous version of this page cited a second caller from a project named client. This project is not a module of the Nuxt hub — it is a separate Nuxt project at the root of the repository, with its own independent AI router. Its distinct multi-agent pipeline is out of scope for this chapter, which documents only the Atlas harness and the hub.

A single Nuxt endpoint consumes the TypeScript router today:

Endpoint Usage Requested provider
Client reply draft generation for a completed Atlas run Produces a formal reply draft, 3 to 6 sentences, ready to send from the hub cockpit Mistral / mistral-small-latest

Important note: this reply draft does not use the Python router — although it is the final piece of the Atlas Inbox pipeline, it is served by a Nuxt endpoint and therefore goes through the TypeScript router. This is the concrete illustration of the boundary:

  • Classification and spawn = Python router (automations);
  • Email draft composed on demand from the cockpit = TypeScript router (Nuxt hub).

This endpoint is, to date, the sole actual caller of the TypeScript router. The automatic fallback (Mistral → Anthropic → OpenAI) and per-client resolution remain wired but exercised by a single entry point, always on Mistral.

Orbit-based organisation: direction, framing, execution, validation

Data model

Each agent has two complementary attributes that define its position within the constellation:

  • The functional group — the agent's business family: direction, framing, execution or validation. This is the source of truth for the project doctrine.
  • The numeric ring (orbit 0 to 3) — a value stored in the database that does not map one-to-one to the functional group. For example, the direction group appears in both ring 0 and ring 1; the framing group spans rings 1 and 2.

The observed distribution is as follows:

Ring Functional group Notable agents Count
0 Direction Atlas (orchestrator) — dedicated ring 1
1 Direction DG, health, strategy, vision agents 4
1 Framing Legal, security agents 2
2 Framing Gauss, Marco Polo, brand and design agents 4
2 Validation Lovelace, audio-QA agent 2
3 Execution — 19
3 Validation Accessibility agent 1

Visual rendering in the reactor

The constellation's main dial — the reactor — does not read the ring column stored in the database. It dynamically recomputes each agent's position from its functional group, using a local mapping table:

RING 1 — Direction       (rotation 60 s)   ← includes Atlas despite ring=0 in DB
RING 2 — Framing + Execution (90 s, counter-clockwise)
RING 3 — Validation      (120 s)

The internal mapping table is of the form:

direction  → ring 1
framing    → ring 2
execution  → ring 2
validation → ring 3

Watch point: the divergence between the ring stored in the database (values 0–3) and the ring computed by the interface (values 1–3) is potentially a technical debt. The visual rendering is driven exclusively by the functional group and remains reliable; the ring column in the database appears underused on the interface side. Adding ring 0 for Atlas has no visual effect, as the recomputation ignores that column.

Routing by prompt domain

In addition to rings, each agent can be associated with one or more prompt domains (for example: content, FAQ, cover, podcast, LinkedIn, reels). A dedicated API endpoint allows retrieval of the list of eligible agents for a given domain. When the request originates from a remote tenant, it is automatically relayed through a proxy mechanism to the mothership, which centralises this registry.


Mail classifier calibration

A monthly reporting script aggregates classification data from incoming emails in order to measure the health of the automatic sorting system. It performs neither model retraining nor automatic weight adjustment — it is exclusively concerned with observability and promotion-threshold management.

Produced metrics

  • Volume by intent: number of classified messages, mean confidence, standard deviation.
  • Proxy success rate: for each intent, the proportion of projects actually opened (not cancelled) among those initiated by the system. A cancelled project means the human supervisor rejected the proposal.
  • Uncertainty rate: share of classifications flagged as uncertain by the engine.
  • Classification failures: unclassified messages, or messages blocked due to risky attachments.

Promotion threshold for external tenants

The system currently operates in internal-only mode. The doctrine defines a promotion threshold for external tenants: exceeding 90 % success over at least 30 consecutive internal projects. This threshold is not crossed automatically — it is verified upon reading the monthly report.

Anomaly detected: the promotion-threshold calculation searches the results for a specific intent that was removed from the classifier's enumerator in July 2026. Since that date, no email can carry this intent, so the threshold verification branch can never trigger — with no visible error or alert. The gate for external tenants is de facto silently frozen. This calculation must be rewired to the equivalent intent and complexity in the current schema (intent='run' and complexity='plan').

Automatic calibration of the classifier's system prompt (few-shot example injection) remains a roadmap feature that has not yet been delivered.


Post-spawn orchestration: deployment, QA and summary

After a sub-agent has produced its output, an orchestration loop takes over. It receives two parameters: the intent of the original message and its complexity level.

Step 1 — Contract reading

The sub-agent deposits a JSON contract in a temporary location. The orchestrator reads it and may find an intent correction proposed by the sub-agent — but only towards a less complex intent (never an escalation). The sub-agent has read access to the full thread, whereas the initial classifier only saw a truncated excerpt.

Step 2 — No-code branch

Certain intents (question, negotiation, advice) are systematically handled without any code deployment. The run intent is also code-free if the complexity is not plan. In that case, the orchestrator sends the summary directly and marks the task as handled.

Step 3 — Code branch

The combination run + complexity plan triggers the full pipeline. Several pre-flight checks are performed on the contract:

  • If the contract indicates commits but the deployment target is absent, this is flagged as an orchestration failure.
  • If the contract mentions neither a target nor commits, this is a legitimate analysis deliverable — treated as a no-code branch rather than a failure.
  • An additional check confronts a "nothing to do" declaration by the sub-agent against the existing mock-up before accepting it.

When everything is consistent, the system executes:

  1. Pre-production deployment via the command ./deploy <target> --preprod, with a 15-minute timeout.
  2. Playwright QA on each route declared by the sub-agent. Each route is first resolved against the actual sitemap to avoid testing a non-existent URL.

Step 4 — Iteration loop

In the event of a QA failure, the system can re-spawn the sub-agent with the error context, up to a maximum of 3 iterations for a generic failure. If the failure is solely a visual conformance gap against the mock-up, a separate budget of 8 iterations applies, as such corrections are more predictable. Beyond the budgets, the case is escalated to a human.

Step 5 — Email summary

The orchestrator sends a summary email via the centralised messaging facade. The sender is resolved through an internal mailbox registry — connection credentials are never read directly by the orchestrator, but delegated to the facade. The recipient is the human system supervisor, in accordance with the "zero AI-to-client email" doctrine. Proof attachments (screenshots, boards) are included when they exist; a missing file is silently ignored rather than causing the send to fail.

Loop overview

spawn ok ──► no-code intent?
                  │ yes                      │ no (run+plan, contract OK)
                  ▼                          ▼
          email Atlas→supervisor       deploy preprod ──► QA route(s)
          UPDATE 'actioned'                              │
                              ┌── QA OK ────────┴── QA FAIL ──┐
                              ▼                                ▼
                        email Atlas→supervisor         iteration < budget?
                        UPDATE 'actioned'         ┌── yes ──┴── no ──┐
                                                   ▼                    ▼
                                         re-spawn (QA error       human escalation
                                         context)

Pipeline Trigger Loop

Correction (September 2026): a previous version of this page stated that the application's native scheduler was inactive. This information is outdated: the scheduler was restarted during a dedicated workstream and is now running with 7 active tasks — email queue processing (every 2 minutes), response time monitoring (every 15 minutes), dictionary and dependency watch (every 30 minutes), daily appointment, SSL watch, and trademark watch. All tasks were confirmed active in the execution logs on the day they were brought back into service.

Two IMAP synchronization tasks remain intentionally disabled: their message retrieval mode was blocking the Node.js event loop and causing timeouts on the supervision terminal. Their reactivation is planned for a later phase.

Demo Mode

When the application is built with the DEMO_MODE=1 flag, the scheduler is cleared of all its tasks at build time — scheduled tasks being registered at build time rather than at runtime. A guard component completes this isolation: in demo mode, any non-read request (other than GET, HEAD, OPTIONS) receives a 405 Demo mode is read-only response before reaching any handler. In production and pre-production, nothing changes: the 7 active tasks run normally.

This Scheduler Does Not Drive the Inbound Email Processing Pipeline

The 7 tasks of the application scheduler fall under generic platform maintenance (email queue, audits, monitoring). The inbound email processing pipeline — ingestion, scan, classification, spawn — is driven by standard Linux system crons, independent of the application scheduler's state. Each cron passes through a locking and logging component that guarantees execution uniqueness.

Three crons form the end-to-end loop:

Frequency Component Role in the loop
*/1 * * * * Ingestion Collector Ingestion + chaining. Polls the dedicated email inbox, inserts received messages, then triggers antivirus scanning and classification in cascade. Classification is invoked here, within the same tick, and not by a separate cron.
*/5 * * * * (offset by 120 s) Spawn Orchestrator Spawn + orchestration. The 2-minute offset ensures the collector has completed scanning and classification before the orchestrator retrieves eligible classified messages (intents: execution, question, negotiation, advice) and launches the corresponding agents.
*/15 * * * * Lock Guardian Safety net. Emits an alert if an advisory database lock has remained active for more than 10 minutes, a sign of a zombie process.

The actual execution order is therefore: collection (minute ×1) → antivirus scan → classification (within the same tick) → spawn (minute ×5, offset by 2 min). The 120-second offset prevents the race condition where the orchestrator would attempt to process messages still undergoing classification. The advisory database lock (described in the concurrency section) covers the residual collision between the every-5-minutes cron and an occasional manual invocation.

The general mailbox synchronization cron (every minute) is a separate worker that feeds a distinct table — it must not be confused with the ingestion collector dedicated to the agent email inbox.

Other Emitters to the Agent Inbox

Ingestion is not fed solely by client emails. The incident escalation component — triggered in a fully deterministic manner, without any LLM call — automatically sends the complete file of any detected incident to the agent inbox. That file then enters the same chain: collection → scan → classification → spawn. An emergency switch allows this automatic escalation to be disabled without redeployment.

The session heartbeat mechanism that wakes the orchestrator from a pool of active sessions uses a separate channel: it does not pass through this email loop.


Component Overview

Component Role
Ingestion Collector Polls the dedicated email inbox, inserts received messages into the raw and orchestration tables, then triggers antivirus scanning and classification in cascade. Cron every minute.
Classification Engine Determines the intent (execution, question, negotiation, advice) and complexity (light or plan) via LLM. Applies authenticity guardrails, manages separation of main body / quoted text, and injects client context from the database. July 2026 update: the direct workstream intent was removed in favour of the execution + plan complexity combination; the advice intent was added.
Spawn Orchestrator Retrieves eligible classified messages, launches agents and orchestrates the subsequent steps (deployment, quality assurance, reply email, iterations). Selects the appropriate AI model via the centralised routing registry. Since August 2026: each agent runs in an isolated Git workspace (worktree). Since September 2026: sender identity is resolved by the configuration registry rather than by direct environment variable reads.
Classifier Calibration Tool Produces a monthly quality report on classifications and tracks the threshold for progression to the advanced phase. Note: this threshold has been frozen since the removal of the direct workstream intent.
Spawn Bridge (terminal wrapper) Mandatory Node.js component for launching the AI agent in streaming mode. Integrates an activity guardian (inactivity timeout and absolute timeout) replacing the former fixed hard cutoff. Supports turn limit, session resumption, and the list of authorised tools.
Persona Loader Loads the agent persona according to three priority levels, retrieves relevant scars via vector search, and injects the mission brief.
Agent Invoker (legacy) Agent invocation via subprocess — legacy path. The technical debt of reading from a MySQL database has been resolved: scars and doctrines are now read from the main PostgreSQL database.
AI Gateway (application side) Server-side multi-provider AI router: content generation with automatic provider failover (Mistral → Anthropic → OpenAI), and per-tenant provider resolution via topology configuration. Application-side counterpart to the Python AI routing component.
Agent Interface Domain Vue.js components, supervision hub pages, and real-time reactor.
Agent Engine Domain Execution engine, database schemas, PostgreSQL access facades, and hub API routes.

Main Data Tables

  • Agent Registry: configuration and state of each agent.
  • Raw Messages: emails ingested in their original form.
  • Orchestrated Emails: enriched records from the Atlas pipeline.
  • Drafts: reply bodies being composed, read by the question materialisation mechanism.
  • Audit Log: full traceability of all pipeline decisions.
  • Spawn Events: refreshable view of agent launches.
  • Jobs, Questions, Negotiations, Advice: materialisation tables by intent.
  • Clients and Persons: client identity resolution from email metadata.
  • Workstreams: associated development projects.
  • Embeddings: vectors for semantic search (RAG).
  • Tenant Topology: configuration of client VPS instances and their AI parameters.

Notable External Modules

  • OCR Engine: text extraction from image attachments via local Tesseract, called by the classifier.
  • Model Routing Registry: centralised resolution of the AI model to use based on spawn context — single governance point for all agent calls.
  • Leak Filter: intercepts and redacts any secrets potentially present in the agent's JSON stream before any persistence or transmission.