Chapters
On this page
DOC-04 / Technical reference · Chapter 07
Inbox hub and Atlas Inbox: two distinct IMAP pipelines
This chapter describes the two IMAP collection pipelines of Synedre — the personal mailbox feeding `ps_ac_inbox_emails` and the agentic CodeMyShop mailbox feeding the Atlas workflow — along with their classification rules and associated security doctrines.
Overview — two distinct messaging pipelines
The system embeds two mailboxes and two email storage spaces that have no direct relationship with each other. This is the primary source of confusion; keep it in mind above all else.
| Pipeline "Inbox hub" | Pipeline "Atlas Inbox" | |
|---|---|---|
| IMAP mailbox | Main contact mailbox (shared hosting) | CodeMyShop agentic mailbox (shared hosting) |
| Target storage | Hub reception table (raw messages + classification) | Raw message table + agentic workflow table |
| Active collector | Python IMAP synchronisation script (sole live path) | Python IMAP polling script (unread messages) |
| Legacy implementation | Nuxt endpoint POST /api/bo/inbox/sync → 410 Gone; Nitro scheduled task outside the live path |
No Nuxt facade — direct Python poll |
| Classification | Static heuristic (sender domain → category) | LLM, intent among 6 possible values |
| Purpose | Triage and display in the hub (client bugs, MRR, priority) | Trigger actions: run, project, question, negotiation, advice |
| User interface | Hub inbox dial + skill /inbox |
Runs, negotiations, etc. dials |
The global flow diagram is as follows:
Main contact mailbox (shared IMAP)
│
│ cron */1 — Python synchronisation collector
│ (SOLE active collector since 2026-05-23 —
│ read-only connection, SINCE -7d search)
▼
Hub reception table ◄── ON CONFLICT (imap_id) DO UPDATE … COALESCE
(classification: client category / priority / MRR / spam)
│
▼ skill /inbox, dial /hub
[DISABLED] Nuxt endpoint POST /api/bo/inbox/sync
Disabled 2026-05-23 (was saturating the application event loop)
CodeMyShop agentic mailbox (shared IMAP)
│ cron */1 — Python collector (SEARCH UNSEEN)
▼
Raw message table ──1:1──► Agentic workflow table (status='received')
│
├─ attachments detected → antivirus scan + heuristics
│ └─ security indicator: safe / unsafe
▼
LLM classifier → detected intent
│
┌─────────┬──────────┼───────────┬──────────────┐
run question project negotiation advice / noise
Pipeline "Inbox hub" — main contact mailbox
A single active collector
This hub reception table has only one feed path wired in production: the Python IMAP synchronisation collector. The legacy Nuxt facade is permanently out of service.
-
Active Python collector — direct IMAP poll of the main contact mailbox, via the internal connection facade (read-only mode). Searches UIDs from the last 7 days, from most recent to oldest. Insertion uses an
ON CONFLICT (imap_id) DO UPDATEstrategy to prevent duplicates. Launched by cron*/1 * * * *via the internal cron wrapper. This collector replaces the legacy Nitro scheduled task. -
Legacy implementation — neutralised: the Nuxt endpoint
POST /api/bo/inbox/syncnow returns 410 Gone and no longer imports the corresponding Nitro task. The old path, still referenced by an original shell script, had been disabled on 2026-05-23 because it was saturating the application event loop on IMAP timeouts, causing hub unavailability and database connection errors. The corresponding cron line is commented out in the crontab:# [DISABLED 2026-05-23 — hub down, IMAP/DB timeout saturating the event loop] # */5 … <script-inbox-sync-shell>
There are therefore not two co-active paths: one live path (Python collector) and one dead path (Nuxt facade / shell script). The skill /inbox-direct (emergency IMAP fallback, read-only) never touches the hub reception table in order to avoid any double-insertion.
True insertion detection: the RETURNING clause distinguishes a true insertion (inserted = true) from a backfill on a duplicate (false, counted separately as a duplicate).
Heuristic classification (without LLM)
The classification function takes only the sender address as input (not the subject) and applies two successive rules:
- Matching the sender against an internal table of known client domains (exact address or domain) → assigns a client name, a priority, and an MRR value.
- Otherwise, detection of spam indicators in the address (newsletter, noreply, no-reply, mailer-daemon, postmaster, notifications@, updates@, marketing@) → marks the email as spam.
The status set at insertion is either spam or new. The message body is extracted in multipart-aware mode (text/plain and text/html parts), explicitly ignoring parts marked as attachments. Both bodies are persisted in full, without truncation. On re-synchronisation of an already known email, the ON CONFLICT … DO UPDATE strategy only backfills bodies if they are empty (COALESCE) — the existing classification is never overwritten.
Attachments: not captured by the active flow. The Python collector persists no attachments — parts marked Content-Disposition: attachment are explicitly ignored. Attachment storage belonged to the disabled legacy Nuxt facade; in the current state, the hub attachment table is no longer fed by this pipeline.
The legacy Nuxt implementation (
sync.ts) remains present in the repository but has not been executed since 2026-05-23. Do not treat it as a reference source.
Messaging credentials management
The active collector does not read IMAP connection variables directly: it delegates to an internal connection facade that resolves the credentials of the main contact mailbox. These values reside solely in the host environment file (never in the git repository), which is the authoritative source.
Several system components read IMAP password variables under slightly different names depending on their development history. In case of doubt about the canonical name, the host environment file is authoritative and defines the actual mapping. The IMAP server and login user remain common to all components.
Hub reception table structure
| Column | Type | Role |
|---|---|---|
| Internal identifier | integer PK | Auto-incremented primary key |
| IMAP identifier | varchar UNIQUE | Deduplication key — target of ON CONFLICT |
| Sender (address, name), subject | varchar | Header metadata |
| Reception date | timestamptz | |
| Client name, priority, MRR | varchar / int | Populated by heuristic classification |
| Bug indicators (flag, keyword, AI severity, AI summary) | smallint / varchar / text | Bug triage; flag set to 0 at initial insertion |
| Archive path | varchar | Reference to the archived .eml file (not written by the active flow) |
| Status | varchar | new, spam, … |
| Internal annotations | varchar / timestamptz / text | Processing, processing date, free-form notes |
| Project link | integer FK | Association with an existing project |
| Text body, HTML body | text | Full body, untruncated |
| Creation / update timestamps | timestamptz | Written at each insertion or update |
The associated API endpoints (under the inbox directory of the hub application) cover: paginated list, message detail, partial update, attachment list, project association, and the synchronisation endpoint (disabled, 410).
Atlas Inbox Processing Pipeline
This pipeline automatically chains three steps within a single verification cycle: reception, attachment analysis, and classification. All three steps are triggered sequentially without human intervention.
3.1 Reception — the message collector
A collector runs continuously (one-minute cycle) and orchestrates the complete pipeline on each pass. An exclusive lock mechanism ensures that only one instance runs at a time: if a previous cycle is still active, the new pass is silently ignored. A separate watchdog process detects and releases orphaned locks (every fifteen minutes).
Sequence of a reception cycle:
- Acquisition of the exclusive lock — silent abort if already held.
- Connection to the inbox via the mandatory email facade (see §3.5) — any direct connection to the IMAP protocol is architecturally blocked.
- Search for unread messages, capped at 50 messages per cycle (configurable).
- Retrieval of each message body in peek mode — the "read" flag is set only after successful insertion into the database, guaranteeing idempotency: a message that was not inserted remains "unread" even after a post-retrieval crash.
- Insertion of the message into the email messages table (deduplication by message identifier: a duplicate is silently ignored). The body is truncated at reasonable thresholds to prevent overflow.
- Insertion of a tracking row into the Atlas workflow table with status
received. - Automatic chaining: if the message contains attachments, antivirus analysis is launched before classification (scan-first doctrine); classification is then triggered in all cases.
- Append-only audit: only a truncated hash (8 characters) of the sender address is logged — no personal data in plaintext.
Internal loop-prevention guard: messages whose sender is the Atlas inbox itself, or whose subject contains an internal tracking system identifier, are marked as read and ignored without insertion. This rule protects against self-send loops observed in production.
All database access goes through a dedicated internal adapter. Large message bodies are passed via a temporary file to work around shell argument size limits.
Command-line invocation:
python3 -m <atlas-collector> # full cycle
python3 -m <atlas-collector> --dry-run # read without insertion
python3 -m <atlas-collector> --max 10 # limit to 10 messages
3.2 Attachment analysis — the antivirus scanner
When a message contains attachments, the scanner is called before any classification. It proceeds through several steps:
- Retrieval of message metadata (message identifier, presence of attachments) via a join between the workflow table and the raw messages table.
- Full re-download of the message from the IMAP inbox in read-only mode.
- Extraction of each attachment part to an isolated temporary directory, with path-traversal protection.
- Pre-scan rejection: any attachment whose extension belongs to a list of dangerous executable types (
.exe,.scr,.bat,.cmd,.com,.vbs,.js,.jar,.msi,.dmg,.deb,.rpm,.ps1) or whose size exceeds 25 MB is immediately blocked with verdictblocked. - Antivirus analysis of each retained file via the security facade (Mitnick agent, see §5).
- The global verdict is
attachments_safe = 1only if at least one file was scanned and none is flagged as suspicious, infected, or rejected. - In the event of a negative verdict: status
failedand quarantine move to an isolated directory. - Persistence of the scan verdict (JSON structure) and audit trace.
3.3 Classification — the intent engine
Once reception and antivirus analysis are complete, the classification engine determines the intent of the message and triggers the appropriate downstream materialization.
Scan-first guard (blocking)
If a message contains attachments and the antivirus verdict is available and negative (attachments_safe = 0), classification is refused and a classify_blocked_unsafe_attachments audit event is emitted. Tolerance: an absent verdict (message with no attachment, or scan not yet performed) allows classification to proceed.
Prompt injection protection
The message body is transmitted to the language model with several active protections:
- The body is wrapped in explicit delimiter markers that distinguish it from system instructions.
- An explicit warning instructs the model that the delimited content is email data, not an instruction.
- The body is truncated to a maximum of 8,000 characters before transmission.
- Output is constrained by a strict enumeration of valid intents — any out-of-scope hallucination is rejected by validation.
- The scope and recipient are never derived from the message body.
Pre-LLM short-circuit — internal re-forward
When an incoming message is identified as a re-forward of a summary issued by Atlas itself (founder sender + subject starting with Fwd: [Atlas] or equivalent), the intent is forced to noise using a rule model (rule:self_forward, confidence 1.0) before any call to the language model. This rule avoids a costly spawn (approximately $1.70 and ~10 minutes of processing observed in production on an Atlas self-summary).
Local OCR enrichment
After a positive antivirus verdict is validated, if image attachments are present, a local OCR engine (Tesseract) is triggered. The extracted text is added to the prompt context between dedicated markers. Two doctrine rules apply:
- OCR text is never persisted to the database (in-memory use only — protection of personal data potentially present in images).
- OCR is triggered after antivirus validation — never on an attachment that has not yet been analyzed.
Language model call
The AI provider configuration (provider and target model) is resolved dynamically via the internal AI routing table (atlas_classifier entry). Default: provider mistral, model mistral-small-latest. The call is made with a 30-second timeout and a constrained JSON output.
Validation and thresholds
The raw model output is validated: the intent must belong to the authorized enumeration and confidence must be between 0 and 1. A confidence threshold of 0.7 triggers a classification_uncertain audit event. Furthermore, any classification with a confidence below 0.5 is automatically floored to the noise intent, regardless of the audit threshold.
Post-LLM guards — two override rules
- Founder false negative with attachment: if the model classifies the message as
noise, the message originates from a founder re-forward and attachments are present, the intent is switched toquestion— actionable content is likely contained in an image that the language model alone cannot interpret. Audit event:noise_override_founder_attachment. - Existing client re-routed: if the intent is
negociationorconseilbut the sender matches an active tenant in the database (verified by email domain), the intent is requalified asrunscoped to that tenant. Unknown prospects remain asnegociation. Audit event:existing_client_guard.
Persistence
The result is persisted in the Atlas workflow table: classified intent, confidence score, identifier of the model used, textual justification, status classified.
Intents and downstream materialization
Six intents are recognized: run, chantier, question, noise, negociation, conseil. Each intent materializes at most one row in a dedicated table, in an idempotent manner.
| Intent | Action | Target table | Deduplication | Tracked link |
|---|---|---|---|---|
run |
UPSERT | Runs table (source='atlas-inbox', trigger='email', tenant scope if re-routed by the client guard) |
Unique constraint on (reference type, reference id) for source atlas-inbox |
id_run_linked |
question |
UPSERT | Questions table (status='pending') |
Same constraint | id_question_linked |
negociation |
INSERT | Negotiations table (status='nouveau') |
Guard on already-present link | id_negociation_linked |
conseil |
INSERT | Advisory table (status='received') |
Guard on already-present link | id_conseil_linked |
chantier |
Manual draft via --link-chantier |
Chantiers table (status='draft') |
— | id_chantier_linked |
noise |
Total no-op | — | — | — |
For the negociation and conseil intents, the company is derived from the sender domain, except for generic domains (gmail.com, outlook.com, laposte.net, etc.) for which no derivation is performed.
Special case — chantier intent
Unlike other intents, the creation of a chantier is not automatic at the end of classification. The system leaves the message in the classified state with intent chantier. Draft chantier creation is triggered manually via the command line, after human review. This choice is intentional and consistent with the 7-step procedure doctrine.
Command-line invocation:
python3 -m <atlas-classifier> --id-atlas-email 42
python3 -m <atlas-classifier> --all-pending
python3 -m <atlas-classifier> --reclassify <id>
python3 -m <atlas-classifier> --link-chantier <id>
python3 -m <atlas-classifier> --report-uncertain
3.4 Atlas workflow table structure
The Atlas workflow table centralizes the processing state of each incoming message. It includes in particular:
- A primary identifier and a foreign key to the raw messages table.
- Classification fields: intent, confidence score, identifier of the model used, textual justification, current status.
- The antivirus verdict (JSON structure) and the attachment safety flag.
- Links to downstream materialized entities (chantier, run, question, negotiation, advisory).
- A token block for the email-based authorization pipeline (ship-via-email): single-use token, issuance and consumption timestamps, consumer identity, reference message identifier.
- Provenance fields (
source_type/source_metadatain JSON) distinguishing a message received via automatic IMAP collection from a manual re-forward — information used by the loop-prevention short-circuit described in §3.3.
A forensic audit log, in append-only mode, records each significant action with its type, actor, JSON metadata, and timestamp. This log never contains personal data in plaintext: only hashes, identifiers, error codes, and metrics.
3.5 Email facade guard
This guard is a technical mechanism, not a simple convention. It is an interception hook wired into the development agent, which activates on every attempted shell command execution.
Mechanism:
- The hook reads the command from its standard input and applies only to shell-type calls.
- An allowlist explicitly authorizes approved email components: the facade email client, the inbox synchronizer, the direct connector, and the SASU inbox connector. Any command referencing one of these components (full name or short name) is allowed through.
- For all other commands, a scan detects the presence of direct email access patterns: imports of standard IMAP or SMTP libraries, SSL connection constructors, direct sends, MIME constructors, as well as unauthorized alternative facades (
send_immediate,send_email_quick). - Any match results in a hard block with an error message displayed to the agent; the absence of a match allows the command through.
This guard structurally blocks any bypass attempt — inline Python code, ad hoc scripts outside the allowlist, direct calls to networking libraries. It was introduced after a production incident in which a non-facade send function left messages invisible in the Sent folder and corrupted the encoding of accented characters when passing through the shell.
Spawn and ship are two distinct components, outside the scope of this section:
- The spawn engine (5-minute cycle) triggers a headless agent for the
chantierandquestionintents only — thenoise,run, and other intents do not trigger a spawn via this mechanism.- The ship-via-email pipeline generates a single-use authorization token, sends a confirmation email via the facade, then performs a triple anti-spoofing check (sender allowlist + DKIM + message match + atomic token consumption) before executing the deployment.
Manual Attachment Extraction
A command-line tool allows attachments to be extracted from an IMAP email by targeting a message through its universal identifier (Message-ID) rather than its position in the mailbox.
node <attachment-extractor> <message-id> [output-directory]
The tool loads its configuration from environment files: IMAP host, login credentials, and IMAP password (with a fallback mechanism to SMTP variables if the IMAP variables are not defined). The output directory is created automatically in a temporary area if no path is provided. The MIME parser is multipart-aware and performs binary writes to preserve byte integrity.
Policy: extracted files must never be opened or analysed before the antivirus scan has returned a
cleanverdict (see the AV scan section below). The inbox search skill lists attachments without extracting them in order to uphold this scan-first principle.
Outbound Email Façade
A single façade centralises all professional email sending. Direct calls to the SMTP transport layer are forbidden outside this façade — no bypass is tolerated.
Draft → Validation → Send Cycle
The workflow follows three mandatory, sequential steps:
--draft ──► writes the draft (status='draft') to the drafts directory
└─► AUTOMATICALLY sends a validation copy to the operator (never to the client)
--list ──► lists pending drafts
--preview --draft-id <ref> ──► displays the full draft for review
--validate --draft-id <ref> ──► (re)sends the validation copy to the operator
--send --draft-id <ref> ──► sends to the client + copy stored in the IMAP Sent folder
(use the textual reference, not a positional number)
Façade Arguments
| Flag | Effect |
|---|---|
--to / --cc (repeatable or CSV) / --subject |
Recipients and message subject |
--body |
Inline message body |
--body-file |
Body from a UTF-8 file (recommended — avoids inline escaping issues) |
--markdown |
The Markdown body is converted to HTML before sending (systematic behaviour) |
--html |
Body already in HTML |
--attachment (repeatable) |
Attachments; immediate failure if a file is missing |
--delivery-kind interface|non-interface |
Classifies any delivery announced to a client; required at send time |
--interface-proof <capture.png> |
Designates the annotated screenshot of an interface delivery; it must also be displayed in the body |
--draft-id <ref> |
Targets an existing draft for sending, preview, or revalidation |
--draft requires --to, --subject, and at least one of: --body or --body-file.
Enforced format: --plain / --no-markdown is rejected. The façade systematically converts the body to HTML before sending, including historical drafts. The canonical HTML signature, which carries the logo, is automatically appended to every send.
Delivery proof: any wording implying an external delivery (including "is now available") must be classified. An interface-type delivery is rejected without an annotated PNG or JPG screenshot explicitly designated via --interface-proof, attached and displayed in the body immediately below the reply. An attachment alone is not sufficient. Any reply threaded to an existing conversation must include at least one verbatim quote from that thread; --no-quote is only for acknowledgements or explicitly assumed deferrals.
Automatic Validation Copy (Show-Before-Send)
On every --draft call, the façade automatically sends a validation copy to the operator with a subject prefixed [TO VALIDATE → <recipient>]. The client email does not go out at this stage — a console message states this explicitly. An anti-loop guard prevents this copy from being sent if the recipient is already the validation mailbox.
This is the implementation of the show-before-send policy: --draft and --send are never chained automatically; the operator validates the received copy before any --send.
Before displaying the draft, the façade queries the editorial tone engine to recall the appropriate register for the recipient — best-effort behaviour, never blocking.
Actual Send and Archiving in Sent Folder
The send command transmits the message via SMTP and then deposits a copy in the IMAP Sent folder. The façade tries several candidate folder names in order (Sent Messages, Sent, Envoyés, etc.) and only declares the copy successful after an explicit OK status from the IMAP server. A rejection by all folders raises a non-blocking warning — the SMTP email remains sent. The HTML signature is appended automatically at send time.
SMTP and IMAP Configuration
The façade reads its configuration from the environment at startup. Required parameters cover: SMTP host and port (port 465 for SMTP over SSL), SMTP authentication credentials, sender address, and IMAP host and credentials. A startup check lists any missing variables if the configuration is incomplete.
Mandatory Antivirus Scan Before Opening (P0)
The antivirus scan engine is managed by the Mitnick agent via the dedicated skill. No extracted attachment is opened or analysed before a clean verdict has been returned. Online analysis (third-party cloud services) is excluded for client data confidentiality reasons. Any bypass is forbidden.
Analysis Layers
- Raw executable rejection: a list of high-risk extensions (
.exe,.dll,.so,.bat,.cmd,.ps1,.sh,.vbs,.js,.jar,.msi) immediately produces aninfectedverdict without further analysis. - ClamAV: the signature scanner is invoked in fail-fast mode. If a signature is found, the verdict is immediately
infected. If the ClamAV binary is absent from the system, the error is surfaced explicitly along with the installation command. - PDF heuristics: a regex analysis targeting known dangerous markers (
/JavaScript,/OpenAction,/Launch,/EmbeddedFile, etc.) is performed on the first 4 MB of the file. A positive signal produces asuspiciousverdict. - Office macros: macro-enabled file extensions are inspected via
olevba(best-effort) for auto-execution patterns or system call invocations. A positive signal produces asuspiciousverdict. - Archives: archive formats are not unpacked; they systematically receive a
suspiciousverdict and require manual review.
Clean marker: on a final clean verdict, a JSON marker file (containing the SHA-256 hash and timestamp) is written atomically to a subdirectory of the attachment, with restrictive permissions. Downstream processes operate in fail-close mode on the absence of this marker: no marker = not yet scanned, access blocked.
Verdict Table
| Verdict | Meaning | CLI Exit Code |
|---|---|---|
clean |
No signal detected — opening authorised | 0 |
suspicious |
Static signals detected — sandbox recommended | 1 |
infected |
ClamAV signature or executable — DO NOT OPEN | 2 |
error |
Scan impossible (ClamAV unavailable, file missing) | 3 |
The scanner is invocable from the command line with a --json option for structured output and a --dir option to scan an entire directory. The exit code reflects the worst verdict among the analysed files. The Atlas pipeline consumes this scanner to qualify attachments; if attachments not qualified as safe are present, the classifier refuses to execute.
Policy — Zero Direct Client Communication (P0)
The system never communicates directly with clients; all external communication must transit through the human operator.
The technical safeguards enforcing this policy are:
- The email façade never sends to the client during a
--draft: it writes a draft and sends a[TO VALIDATE → …]copy to the operator. Only the--send --draft-id <ref>command, triggered after explicit validation, delivers the message to the client. - An active guard hook monitors all Bash commands and blocks any attempt to use the SMTP or IMAP transport layer outside the authorised façades. This safeguard makes the façade technically non-bypassable.
- The Atlas classifier never derives the recipient or scope from an email body (anti-injection protection). Reply drafts remain in
pendingstatus until human validation. - Formal address forms are systematic for all external contacts. Appointments are proposed via a self-service booking link — no hard-coded time slot is ever included in an email.
Active Scheduled Tasks
| Frequency | Pipeline |
|---|---|
| Every minute | Inbox synchronisation to the email hub (sole live collector) |
| Every minute | Atlas polling — ingestion of new emails into the processing pipeline |
| Every 15 minutes | Atlas lock watchdog — releases orphaned locks |
| Every 5 minutes (offset start of 2 min) | Headless agentic spawn — chantier and question intents only (hard-coded allowlist) |
Disabled task: the legacy synchronisation script using the Nuxt hub HTTP façade has been commented out in the crontab since May 2026. It caused event-loop saturation in the hub due to cascading IMAP and database timeouts. It was replaced by the external Python synchronisation worker. Do not re-enable it without fixing the root cause of the saturation.
Known Pitfalls
- Two distinct tables, no join possible. The hub inbox table (key: numeric IMAP identifier) is entirely separate from the Atlas pipeline tables (key: account + Message-ID). These two worlds do not intersect.
\Seenflag set after INSERT on the Atlas side: a crash between the fetch and the insertion leaves the email unread, and therefore reprocessed on the next cycle. Idempotency is ensured by anON CONFLICTconstraint in the database.- Mandatory
PEEKon Atlas fetch to avoid marking the email as read prematurely before the insertion is confirmed. --markdownrecommended for all client emails. Always prefer--body-fileover inline--body.- Scan-first is non-negotiable: opening an attachment before a
cleanverdict constitutes a P0-level architectural debt. - Docstring / reality gap: the Atlas poller documents a 5-minute frequency but actually runs every minute.
- Email anti-loop: the operator address intentionally forwards to the Atlas mailbox. Only the Atlas mailbox is filtered as a self-sender. Do not add the operator address to the self-sender list.
chantierintent: the classifier does not create a chantier automatically — this is an explicit CLI action (--link-chantier). This prevents the creation of orphaned chantiers without a mission statement.