Chapters
On this page
DOC-04 / Technical reference · Chapter 08
Memory and learning of the Synedre OS harness
This chapter describes the three-level memory architecture of Synedre (reflex, Zettelkasten, pgvector), the associated indexing automata and the learning cycle based on capitalisation of errors and successes.
Memory & Learning
This page describes how the agentic harness stores information (three memory levels), retrieves relevant content (semantic recall via vector similarity) and capitalises on errors and successes by converting them into reusable rules (scars → learning → lessons loop).
1. Three-Level Memory
The system distinguishes three memory tiers of increasing granularity and write discipline.
┌────────────────────────────────────────────────────────────────────┐
│ LEVEL 1 — Reflexes │
│ Loaded in EVERY session. Hard rules, experience feedback, │
│ references. Strict, one line per entry in the index. │
├────────────────────────────────────────────────────────────────────┤
│ LEVEL 2 — Doctrine (Zettelkasten) │
│ The "why": decisions, doctrine, concepts. Exploratory. │
│ Draft zone = free deposit; consolidated zone = validated │
│ only upon explicit operator decision. │
├────────────────────────────────────────────────────────────────────┤
│ LEVEL 3 — Semantic Index │
│ 1024-dimension vectors (cosine HNSW) covering everything above │
│ + database tables. RAG recall. │
└────────────────────────────────────────────────────────────────────┘
Level 1 — Reflexes (automatic loading)
- An index file lists all active entries; details are spread across thematic files (feedback, user preferences, project references).
- These files are injected into the context of every session without explicit recall: this is the "reflex" memory.
- Reserved for genuinely impactful doctrines — each entry fits on one line (approximately 200 characters maximum).
Level 2 — Zettelkasten Doctrine (Obsidian Vault)
- The Vault is organised into sub-folders:
permanent(consolidated notes),inbox(drafts),moc(concept maps),dailyandfleeting(ephemeral notes). - Inter-note links use wikilink syntax. YAML frontmatter carries the
typeandstatusfields. - Promotion rule: the
inboxzone is the AI's free deposit area; thepermanentzone is never modified without an explicit operator instruction. No automatic merge inbox → permanent or inbox → reflexes is permitted — a programmatic safeguard enforces this.
Level 3 — Semantic Index (pgvector)
- Vectors are stored in the mother-ship's central database, in a dedicated embeddings table.
- Vector index of type HNSW cosine, dimension 1024 (model
mistral-embed). - A composite uniqueness constraint on
(source type, source identifier)guarantees the absence of duplicates.
2. Indexing
Two automated processes feed levels 2 and 3 respectively. Their roles are distinct and complementary:
- The structural indexing engine populates the Vault's relational table (structured search, hub interface).
- The semantic indexing engine populates the vector table (RAG recall by similarity).
2.1 Structural Indexing Engine → Vault Relational Table
- Traverses all Vault sub-folders (
permanent,inbox,moc,daily,fleeting). - Parses the YAML frontmatter of each note and extracts wikilinks.
- Incremental synchronisation: compares each file's modification date against the value recorded in the database. UPSERT on path conflict; deletion of orphaned entries whose source file no longer exists.
- Indexed columns: path, type, title, tags, full frontmatter, body, outgoing links, size, timestamps.
- Available flags:
--force(re-indexes everything),--stats(counts by type without writing). - Schedule: every 15 minutes. Idempotent.
2.2 Semantic Indexing Engine → Vector Table
Computes embeddings via the mistral-embed model (1,024 dimensions) and inserts them into the database via UPSERT.
Covered sources:
| Source Type | Indexed Content |
|---|---|
| Scar | Entries from the incident table with a populated description field — scar/victory separation performed in application memory |
| Victory | Entries from the incident table qualified as kind='victory' |
| Reflex | Files from the reflex memory zone (excluding the index file) |
| Doctrine Note | Vault sub-folders (permanent, inbox, moc, daily, fleeting) |
| Doctrine | Active entries from the doctrine table |
| Worksite | Worksite table |
| Agent | Agent table |
| Drill | Exercise (drill) table |
| Conduct | Active entries from the conduct table |
| Iteration | ReAct triplets (reason / action / observation) from the task iteration table |
- Deduplication: a SHA-256 hash of the content is computed per chunk; if the pair
(source type, source identifier)already exists with the same hash, the chunk is skipped. - Chunking: one file = one chunk (MVP); truncated at 16,000 characters. Smart chunking is planned for a later phase.
- Batch processing: 50 inputs per Mistral API call.
- Immediate re-indexing of a scar: when a scar is recorded during a ReAct loop, the reflex engine triggers an inline unit re-indexing — the scar becomes queryable via RAG without waiting for the nightly sync.
- Schedule: full incremental sync daily (all sources, no full rebuild). Inline unit re-indexing remains active in parallel for immediate RAG availability.
Note on other scheduled automated processes: additional nightly or weekly maintenance loops complete the cycle — structural indexing (every 15 min), nightly learning consolidation loop, pattern detection (weekly), skill proposal monitoring (hourly), memory metrics (morning), monthly consolidation. Each is idempotent and logged.
Recall RAG — Memory Retrieval Engine
The memory retrieval engine allows an agent to find, among all indexed knowledge, the fragments most relevant to a text query. It exposes a search skill invocable in natural language and relies on three complementary ranking modes.
Processing Pipeline
Every query follows the pipeline below:
- The text query is submitted to the retrieval engine, which selects the ranking mode according to configuration.
- Raw results are filtered by scope, then re-ranked by importance and recency.
- The recall counter of each served fragment is incremented in a non-blocking manner (except in diagnostic mode).
- The top-K results are returned with their provenance.
Search Modes
- Semantic mode: the query is transformed into a dense vector (1024 dimensions) via an external embedding model. Ranking is performed by cosine distance between this vector and stored embeddings.
- Lexical mode: words of at least 3 characters and short alphanumeric identifiers are extracted. An OR query is built and evaluated via a full-text index prepared and stored in the database. No call to an external service is required for this mode.
- Hybrid mode (default): both rankings are merged by Reciprocal Rank Fusion (RRF, k=60). A document's score is the sum of
1/(60 + rank)across both rankings. A document absent from one mode receives 0 for that mode without penalising the other.
Re-ranking by Importance and Recency
When re-ranking is enabled (default behaviour), the engine over-fetches k×3 candidates. For scars, a composite score is computed:
score = similarity × (1 + importance/10) × exp(-age_days / 365)
A recent scar of maximum importance is thus boosted by a factor of ~2, while an old, low-importance scar is penalised by a factor of ~0.4. The final top-K is extracted after this re-ranking.
Search Scopes
The user may restrict the search to one or more source families: iterations, scars, victories, memorised notes, doctrine, projects, agents, steering exercises, or the full corpus. A special source family groups the five sub-types of permanent Vault notes.
Anti-Forgetting Telemetry
Each served scar has its recall counter incremented and its last-recall timestamp updated. This mechanism feeds the archiving policy: only scars whose counter has remained at zero are eligible for purging by the nightly loop. The operation is non-blocking; a failure does not interrupt the response.
Validity Before Ranking
Before entering the ranking, each document is verified in the database: doctrines must be active, scars and victories must be present and not superseded. A stale document in the index therefore does not consume a slot in the top-K. The content remains a snapshot: an active rule may have been rewritten since its last embedding.
Result Provenance
Each result carries provenance metadata: source type, identifier, location, and validity status. The status conventions are as follows:
- Active doctrines: status
active. - Non-superseded scars: status
not_superseded, verified in the database. - Working notes (incoming, ephemeral, daily, navigation cards): status
draftas a precaution. - Consolidated permanent notes: status
consolidated(a storage classification, not a validation proof). - Free memory and uncontrolled sources: status
unverified. - A status field in a note's frontmatter (
draft,deprecated,superseded,archived) takes precedence. Deprecated notes remain readable with their label, without implicit promotion.
Shared Injection
The memory pre-flight module maintains, in the excerpts transmitted to each agent (Claude, Codex, Antigravity), the status and source of each fragment. The knowledge graph is not activated automatically in this pipeline.
Command-Line Options
--k <integer>: number of desired final results.--mode lex|sem|hybrid: ranking mode (default:hybrid).--scope <scope>: source family filter.--json: machine-readable output.--no-bump: disables telemetry (useful for read-only diagnostics).--context-path <file>/--context-command <command>: enables fusion with the knowledge graph (see next section).
Score Interpretation
In semantic mode: a score above 0.75 indicates strong relevance; between 0.65 and 0.75, satisfactory relevance; below 0.65, manual validation is recommended. In hybrid mode, RRF scores typically fall below 0.1 — only the relative rank is meaningful, not absolute thresholds.
Pre-Project Hook
An automatic hook, triggered before any project skeleton is created, extracts the title of the artefact to be created and runs a hybrid search over the four closest results. If the embedding service is unavailable (rate limit reached), lexical mode takes over. Results are injected into the diagnostic pipeline before creation, in a non-blocking manner. The objective is to avoid reinventing a scar, doctrine, or project already known — semantic search catching the cases that the linear index would have missed.
Recall Evaluation — Non-Regression Harness
A non-regression harness verifies that changes made to the retrieval engine do not degrade search quality as measured on a golden dataset.
Principle
The golden dataset associates each query with a set of expected documents (identified by their reference in the index). The harness invokes the retrieval engine in read-only mode (the recall counter is never mutated), computes three aggregated metrics, and compares them against the frozen baseline. A result is considered a match if the expected reference is a substring of the returned identifier (case-insensitive) — making it robust to path prefixes and compound formats.
Metrics
| Metric | Definition |
|---|---|
recall@k |
Proportion of expected documents present in the top-K, averaged across all queries. |
mrr@10 |
Reciprocal of the rank of the first relevant document in the top-10 (0 if absent), averaged across all queries. |
top1_accuracy |
Fraction of queries for which the first result matches an expected document. |
Cadence and Rate-Limit Handling
A delay of 1.3 seconds is observed between each embedding call (semantic and hybrid modes). In the event of a rate-limit response, exponential backoff is applied for up to five attempts. Lexical mode does not call any external service and is subject to no cadence constraint.
Commands and Exit Codes
| Command / option | Effect | Exit code |
|---|---|---|
| (no option) | Regression gate: compares current metrics against the baseline; fails if regression exceeds the tolerance. | 0 or 1 |
--baseline |
Freezes the baseline by running the full hybrid mode. | 0 |
--mode-sweep |
Compares all three modes (lexical, semantic, hybrid) for informational purposes, without a regression gate. | 0 |
--tol <float> |
Regression tolerance (default: 0.05). | — |
--json |
Machine-readable output. | — |
| (baseline absent) | Warning and immediate exit. | 2 |
Knowledge Graph — Contextual Recall Experiment
This feature is a bounded experiment, reversible at any time, whose decision for permanent deployment is conditioned on measurable criteria. It aims to evaluate whether structural proximity — "which fragments are two hops or fewer from the artefact I am about to modify?" — improves recall beyond what semantic similarity and lexical search provide.
Graph Structure
The graph relies on three dedicated tables:
- Node table: eight node types closed by an integrity constraint — hook, event, scar, doctrine, note, project, path, command.
- Edge table: eight relationship types closed by constraint; each edge carries an origin (derived automatically or set manually), a non-null proof, and a confidence level. Manual edges are never overwritten or pruned by the automatic build process.
- Comparison log table: records, for each hook call in shadow mode, what the graph would have proposed compared to keyword search.
Graph Construction
The build process uses only deterministic extractors: analysis of hook configuration files, hook headers, doctrines, structural links between notes, and hook bodies for protection relationships. No language model is involved in extraction: an edge produced by an LLM would shift the hallucination risk into the graph itself.
Neighbourhood Query
For a given artefact (file path or command), the engine performs an undirected recursive traversal up to depth 2, excluding edges of type "supersedes". The confidence of a path is the product of the confidences of its edges.
Path resolution normalises paths from different directory layouts to a common key, without reading file contents.
Each traversal result carries the evidence for the chosen route (relationship type, proof, origin, confidence, node identifiers) as well as the hop count. The route is selected by minimum distance then maximum confidence — both criteria apply to the same route, not to different routes.
Note: Confidence reflects the quality of automatic extraction, not a probability of truth of the node contents.
Controlled Fusion at Recall Time
When a file or command context is supplied to the retrieval engine, neighbouring doctrines and scars identified by the graph are added to the candidate pool. Validity and scope checks apply normally. Both rankings (textual and structural) are then merged by RRF. Only sources already indexed in the retrieval engine are served; graph notes are excluded from fusion because their identifiers may be homonymous.
Without a supplied context, without any admissible neighbour, or in the event of a graph failure, the textual ranking is preserved unchanged. The graph connection is read-only, limited to depth 2, and subject to a maximum traversal timeout of 300 ms; any failure is reported on the diagnostic channel without interrupting recall.
Example of a read-only contextual search:
python3 -m <recall-module> --mode hybrid --scope doctrine --context-path <context-file> --no-bump --json "<query>"
Shadow Mode
A local environment variable activates shadow mode: the scar injection engine logs what the graph would have proposed, without injecting anything into the live pipeline. The operation is limited to 300 ms and fails silently.
Decision Criteria (go / no-go)
The final verdict relies on an evaluation harness of 10 manually ground-truthed cases. The pass condition (go) is:
- graph recall@5 ≥ semantic recall@5 + 0.15, or union recall@5 ≥ semantic recall@5 + 0.20;
- and median latency (p50) < 150 ms.
Initial measurement (D0): graph 0.03 / semantic 0.30 / union 0.30, p50 7.5 ms → no-go as-is.
Identified structural cause: protection edges only capture hooks that test a command string; hooks that test a state (presence of a merge marker, file content) are invisible in the graph. Furthermore, only a small number of hooks cite a scar in their header. The final decision will be made after one week of shadow-mode data collection.
Non-Regression Checks
A SQL test suite executes SELECT statements against in-memory fixtures (literal values in common table expressions) within a read-only transaction. No schema is created, no business data is written. Any mutation that disables the activity filter or misaligns the returned route and its confidence level must cause these tests to fail.
Lexical non-regression checks on the 36-query golden dataset confirmed full stability before and after the graph was introduced (recall@10: 0.5417; MRR@10: 0.2534; top-1: 0.1389). On a hybrid sample of 6 cases, recall@10: 0.8333 and MRR@10: 0.5139, also stable. On the 10 cases of the graph evaluation dataset, standalone hybrid recall and contextualised recall are identical (0.3167), confirming the absence of any overall gain — hence the decision to limit fusion to explicit context only, with no new automatic injection.
Learning Loop: Errors, Checks, Suggestions, Lessons
This is the core of knowledge capitalization. A resolved error (or a reproducible success) becomes structured data, then a concrete suggestion, then — after human validation — a rule loaded into all future sessions.
The general flow is as follows:
- A ReAct workstream produces a resolved error or a reproducible success.
- The event is recorded in the lesson registry and immediately indexed in vector memory. An AI model evaluates its importance and determines whether the lesson is actionable.
- The learning engine transforms actionable lessons into concrete suggestions (before/after format) and places them in a queue.
- A human operator validates, rejects, or modifies each suggestion via the dashboard.
- Applied suggestions are recorded in an audit log and propagated to their destination (orchestrator directive, configuration, persistent memory, skill, etc.).
- The loop is closed: the rule is active from the next session onward.
The Lesson Registry
The lesson registry is the single source of truth for knowledge capitalization. Each entry represents either a resolved failure or a reproducible success. The key columns are:
- Lesson identifier, agent involved, error type, description, root cause, correcting agent, severity, resolution status, registration date.
- Entry kind (
kind): distinguishes failures, raw scars, wins, and a few legacy categories (bug, convention, pattern). - The lesson itself (
check_added): for a failure, what was added to prevent recurrence; for a win, the pattern to reproduce. - Importance score (integer): computed by an AI model at registration time, via the AI routing system. Non-blocking — if the model is unavailable, the score is zero and a nightly process will back-fill it. A high score doubles the lesson's weight in recalls.
- Actionability flag (
learnable): the entry gate for the learning engine. Only lessons marked as actionable feed suggestion generation.
To record a win, the dedicated skill is invoked, which goes through the entity layer — never through raw SQL. The tags field must be supplied as a literal PostgreSQL array (syntax "{a,b,c}"), not as an application-level list.
The Learning Engine: From Lesson to Suggestion
The learning engine scans the lesson registry and generates suggestions to submit for human validation. Its five-step pipeline:
- Retrieval: actionable lessons not yet processed are loaded, sorted by descending importance then by date, with a per-run limit.
- PII scrubbing: a PII filter sanitizes each lesson before passing it to the model. The model output is itself re-filtered before insertion, as a defense-in-depth measure.
- LLM generation: the model receives the filtered lesson and produces a structured suggestion in JSON format.
- Suggestion format: the suggestion includes a destination type, an explanatory text, a before state, and an after state (diff).
- Queue insertion with
pendingstatus. The operation is idempotent and rate-limited.
The six possible destinations for a suggestion are:
| Destination | Meaning |
|---|---|
| Orchestrator directive | Rule to add or modify in the agent's main configuration |
| Technical configuration | Hook, permission, or environment parameter |
| Persistent memory | Level-1 note activated from the next session onward |
| Conceptual inbox | New Zettelkasten note (concept or doctrine) |
| Agent skill | Creation or improvement of an invocable skill |
| Tool or automated workstream | New workstream or automation to integrate into the system |
Tracking Tables and Human Validation
The suggestion queue, the audit log, and the validation statuses are managed by three distinct structures:
- Queue: each suggestion has an identifier, a link to the source lesson, the destination type, the text, the before/after diff, the status, and the creation date.
- Statuses:
pending→applied,refused, ormodified. - Audit log: records each validation action (who, when, diff snapshot).
Validation is exclusively human, via the dashboard: one view lists pending suggestions, an apply action switches the status and writes the entry to the log, and a reject or modify action is also available. The engine only proposes — it never applies anything on its own.
Post-Workstream Lessons
At workstream closure, the /apprendre skill (Academy agent) triggers an in-depth retrospective analysis. It loads a full audit bundle: workstream metadata, works, tasks, the last thirty task iterations, associated scars, and execution log excerpts (truncated to stay within the context limit).
A guard checks workstream maturity: fewer than three completed works causes the skill to refuse analysis (overridable with an explicit flag).
The model produces an analysis in five sections:
- Gap between estimated and actual token usage
- Top 3 recurring errors
- Top 3 patterns to standardize
- One candidate doctrine
- One tool to create
The output is placed in the document inbox in draft format (with revision metadata). Promotion to permanent memory or reflexes is always manual — an operator moves the file after review, in accordance with the three-level memory doctrine.
The analysis engine has a primary path (via the agent binary, with read-only restricted tools, two attempts) and a fallback path (via the AI provider API, three attempts with exponential backoff), activated only if the binary is absent or if an explicit flag requests it.
Patterns → Skills Pipeline
A second operational pipeline, separate from the lessons → suggestions loop, transforms recurring patterns observed in ReAct iterations into proposals for invocable skills.
The flow is as follows:
- Completed task iterations are scanned every week (Sunday at 04:00 UTC).
- The pattern detector passes a batch of recent iterations to an AI model, which identifies patterns present in at least three tasks and warranting a dedicated skill.
- For each proposal: if a skill or proposal with the same identifier already exists (pending, validated, or refused), it is skipped. Otherwise, a new proposal is inserted with
pendingstatus, along with the source iteration identifiers and the justification text produced by the model. - An hourly monitor alerts the founder if the number of pending proposals exceeds a threshold (default: 10). It also produces statistics: totals by status, average validation time, validations per agent, additions in the last hour. Alerts are routed through the system's email facade.
- Human validation is performed via a dedicated dashboard page. A validated proposal is promoted to a natively invocable skill.
Not to be confused: a second pattern-detection skeleton exists in the codebase but is currently inactive — its own internal documentation states this explicitly. It is the detector described above that actually feeds the skill proposal queue.
Other Related Loop Automations
Several nightly or periodic automations operate around the learning loop.
Nightly Consolidation (10 Features)
A nightly consolidation automation runs every night at 04:00 UTC. It covers ten features (F1–F5, F7–F11 — no F6). Cross-cutting guard: never automatic integration from the inbox to permanent memory; simulation mode is the default behavior. The provider and model for each feature are resolved dynamically from the AI routing system.
- F1 — Repeated lessons: compares the day's lessons against vector memory (cosine similarity ≥ 0.85 over the eleven nearest neighbors); if at least two similar occurrences exist in the past, a promotion draft is placed in the document inbox.
- F2 — Transcript compaction: parses the day's session logs (up to 30 sessions; files containing secrets are skipped), passes them to the AI model, extracts 3 to 5 durable facts (decision, delivery, lesson, observation), and records them in the daily journal. In simulation mode: no LLM call is made.
- F3 — Morning summary: morning summary email via the system's email facade. Skipped if no draft or daily journal was produced.
- F4 — Documentation drift: checks canonical pricing tiers in the pricing file; scans obsolete patterns defined in a dedicated configuration file (thresholds: ≥ 3 occurrences in ≥ 2 files); identifies heavily numeric Markdown tables (≥ 6 rows, > 50% numeric content) and recommends migration to the database. Results are placed in the inbox.
- F5 — Nightly reflection: for each active agent, the top twenty resolved lessons are passed to the model, which produces three introspective questions and three abstractions placed in the inbox. In simulation mode: counts eligible agents without making an LLM call.
- F7 — Forgetting curve: archives (status
resolved=2) lessons older than 180 days with no recall. No deletion — the operation is reversible. Archived lessons become invisible to semantic recall. - F8 — Workstream proactivity / emails: scans workstreams with external contacts (statuses: paused, planning, discovery, development), auto-links emails by sender, reconstructs the full thread, and classifies each workstream as
archive-refused,act-now,awaiting-them, orno-action-needed. - F9 — Workstream obsolescence audit: scans paused or planning-stage workstreams with no activity beyond a configurable threshold, computes obsolescence signals, classifies via LLM as
still-relevant,maybe-obsolete, orarchive-recommended. Non-still-relevantverdicts surface in the morning email for operator decision. - F10 — Persona drift audit: self-gated to the 1st of the month. Measures the gap between agents' current configuration and their reference persona, persists the drift history, and flags the top-3 most-drifted agents in the morning email.
- F11 — Daily cost per agent: aggregates the previous day's costs, compares them to the seven-day average per agent, and sends an email alert if the deviation exceeds 20%.
Lesson Qualification
A qualification automation classifies lessons that have not yet been categorized. The AI model returns a category, a reclassified severity, an actionability flag, tags, a confidence score, and a rationale. These fields are mapped column by column into the registry.
Note: the actionability flag produced by this automation is not written directly to the corresponding column — it is serialized as a prefix in the rationale field in the form
learnable:true|false. It is the main learning engine that handles the definitive write of this flag.
Level-1 Memory Hygiene and Consolidation
A monthly pipeline (1st of the month, 00:00 UTC, with overlap-prevention locking) ensures the hygiene of the level-1 persistent memory. It breaks down into four sequential steps, halting on the first failure:
- Environment validation: checks Python dependencies and required paths, executed in an isolated subprocess. If this step fails, the pipeline stops without executing the subsequent steps.
- Dead link detection: scans links in the main memory file. This step runs even in simulation mode and may write reports to disk.
- Obsolete file archiving: moves files from obsolete or decommissioned categories to an off-repository archive destination, and removes the corresponding reference from the main memory file.
- Deduplication: identifies and processes identical files by SHA-256 hash.
A structured report is produced at each run (per step: OK status, duration, any error, plus an overall summary).
The required environment variables are the memory directory and the archive destination. If either is missing, the pipeline fails at step 1.
Flags and exit codes:
| Flag | Effect |
|---|---|
| (none) | Full pipeline, live writes |
--dry-run |
Steps 3 and 4 in simulation; step 2 always runs and may write reports |
--validate-only |
Stops after step 1 |
| Exit code | Meaning |
|---|---|
0 |
Full pipeline OK (or --validate-only OK) |
1 |
Environment validation failed — no step executed |
2 |
Fatal error in a step — pipeline halted |
3 |
Simulation mode completed (informational, no changes made) |
A runnable non-regression quiz verifies the actual system state across sixteen checks spread over four modules: script and dependency presence, runtime behavior (--validate-only → exit 0; --dry-run → exit 3 or 0), report presence and conformance, and reference documentation conformance. This quiz must be run after any modification to the pipeline. It accepts a --verbose flag.
Important: the training document associated with this pipeline is hard-read by four quiz checks. Deleting it without updating the quiz would cause the score to drop below 100% and return an error code.
Memory Observability
A daily automation (06:00 UTC) collects metrics on persistent memory: file count, size in kilobytes, line count of the main memory file, dead links, and orphaned links. These metrics are retained over a rolling 90-day history. Alerts are emitted in the monitoring system if thresholds are exceeded. The automation accepts --json and --dry-run flags.
User Model Recall
Semantic vector recall is not the only memory channel. A separate module loads the structured user model from a dedicated table (JSONB dimensions) to inject it into agent briefings — this is a targeted, non-vector recall.
The available slices are:
- Direct slices: communication style, schedule, profile, skills, history, preferences, strictly private data.
- Composite
coreslice: aggregates communication style, cognitive preferences, and meeting schedule, calibrated for briefing injection (under 1,000 tokens). It never includes strictly private data.
The API exposes a retrieval function by slice (returns a dictionary) and a ready-to-inject formatting function (returns text). From the command line:
python3 -m <user-recall-module> --slice core [--json|--format-briefing]
Nightly Maintenance Loop
This layer orchestrates, every night, the self-repair of the documentation and the system health assessment. The orchestrator inspects documentation fidelity, measures overall health, mechanically repairs dead references, triggers gated regeneration of derived chapters, then pushes a sanitized snapshot to synedre.com.
The pipeline executes in the following order:
- Perceive — the drift detector inspects the gap between documentation and code.
- Coverage — the blind-spot detector identifies undocumented areas.
- Repair — the dead-reference fixer mechanically processes invalid links.
- Regenerate — gated deep rewriting of chapters is triggered if necessary.
- Propose — a staging cycle prepares drafts before publication.
- Publish documentation — automatic publication after verification (leaks, drift, editorial compliance).
- Re-perceive — a second drift measurement is performed after publication, so that the health assessment reflects the post-regeneration state rather than the state at the start of the night.
- Health assessment — aggregation of five vital dimensions of the system.
- Publish snapshot — best-effort push to synedre.com.
The cron is configured at 05:00 UTC daily, via the central scheduling envelope.
Nightly Loop Orchestrator
The orchestrator constitutes the single entry point of the loop. It enforces several global safeguards:
- Database kill-switch: if the entry corresponding to this orchestrator in the automaton configuration table carries the inactive status, execution stops silently.
- Overlap-prevention lock: a temporary lock file records the PID of the current process. If that PID is still alive at startup, the loop is cancelled to prevent a double run.
- Semantic return codes: codes 1 and 2 respectively signal a detected drift and a critical health state — these are statuses, not fatal failures. The loop only terminates with a real error if a sub-step actually fails.
- Daily report: at the end of the loop, an idempotent record is inserted into the morning summary table, with a recap of each step.
- Double drift measurement: the drift detector runs a second time after publication, just before the health assessment, so that the assessment reflects the actual post-regeneration state.
Available flags:
| Flag | Effect |
|---|---|
| (none) | Full execution in production mode. |
--dry-run |
All sub-steps receive simulation mode; the kill-switch is bypassed. |
--no-deep |
Skips the deep rewriting step. |
--deep-max N |
Hard cap on the number of chapters processed in depth (default: 4). |
--deep-budget-sec N |
Time budget in seconds for deep rewriting (default: 4,500 s = 75 min); no new chapter is started beyond this budget. |
Health Assessment Module
This component aggregates five vital dimensions into an idempotent snapshot per execution date, visible in the morning dashboard.
| Dimension | What is measured | Critical threshold |
|---|---|---|
| Proprioception | Documentation drift table | At least one chapter in dead-ref state |
| Coverage | Documentation coverage table | At least one uncovered unit |
| Debt | Automaton backlog | At least one open P0-priority item |
| Learning | Scar KPI view | Refresh more than 3 days overdue |
| Automatons | Cron error table + active automaton registry (mothership scope) | At least one mothership-scope automaton unintentionally disabled |
Automaton scope: only automatons belonging to the mothership scope and marked active are taken into account in this assessment. An intentionally disabled automaton or one belonging to a distinct client scope does not degrade the global metric.
Note authored by the Guardian agent: the Health Guardian reads the vital indicators and drafts a care note in three sentences maximum (in English). This note is robust to agent unavailability (it is simply absent if the agent does not respond) and is stored in the JSONB field of the global snapshot under the dedicated key.
Available flags: --dry-run (display without writing), --no-voice (metrics only, without drafted note). Return codes: 0 = ok, 1 = warning, 2 = critical.
Public Snapshot Synchronization Module
This component reads in read-only mode the latest health and drift snapshots produced by the preceding modules, sanitizes them (removal of IP addresses, internal paths, and client identifiers), then pushes a JSON snapshot to the synedre.com database.
Safeguards:
- No writes on the mothership side: reading is strictly read-only.
- Idempotent migration: the destination table is created automatically on the first run if it does not exist.
- UPSERT on date: one snapshot per day only.
- In the event of an error when pushing to synedre.com, return code 2 is emitted and the error is logged, but the nightly loop continues (best-effort mode).
The snapshot exposes overall and per-dimension health (scores, statuses, sanitized summaries), the list of drifted chapters, and the Guardian note. This data feeds the maintenance dashboard on synedre.com.
Flags: --dry-run (prints the JSON without any remote write). Return codes: 0 = ok, 1 = read error, 2 = push error.
Unified AI Facade
Every call to an artificial intelligence provider within the Synedre ecosystem routes through a centralized facade. This doctrine ensures that routing, billing, and resilience are managed in a single place. Two canonical functions are exposed:
embed(text, *, provider="auto", model=None) -> list[float]
complete(mission, *, context="", provider="auto", model=None,
json_output=False, timeout=90,
api_key=None, meter_tag=None) -> str | dict | None
Database-Driven Routing
When provider="auto" is specified, the facade consults a routing table in the database. This table contains a global fallback row and per-feature rows, merged at call time. Switching providers amounts to a database update — no redeployment is required. If the database is unreachable or empty, default values are applied.
Available providers and models:
| Usage | Valid providers | Default model |
|---|---|---|
| Embedding | Mistral, Voyage, OpenAI | mistral-embed / voyage-3 / text-embedding-3-small |
| Completion | Claude (Anthropic), Mistral, OpenAI | claude-haiku-4-5 / mistral-large-latest / gpt-4o-mini |
Completion Paths
Claude provider (Anthropic) — two billing paths coexist:
- Direct API path: if the provider API key is present (via parameter or environment variable), the call is made directly to the Anthropic API. This path is intended for client contexts where billing is separate. It includes three attempts with exponential backoff on transient errors, as well as usage tracking (tokens, estimated cost) by billing tag.
- Internal CLI path: in the absence of a direct API key, the call routes through the Gauss agent (codename: Gauss), whose neutral persona is suited to internal use cases.
Mistral provider — direct HTTP call, temperature 0.0, three attempts on transient errors (429 and server errors). Permanent client errors (4xx except 429) are not retried.
OpenAI provider — direct HTTP call to the OpenAI completion API.
Usage Traceability
Each completion via the Anthropic direct API is recorded in a dedicated table (provider, model, billing tag, input/output tokens, estimated cost in USD). This mechanism is fail-soft: a traceability error does not block the main call. It enables per-client rebilling via the meter_tag field.
Robust JSON Parsing
In json_output=True mode, the facade attempts in sequence: direct parsing, stripping of Markdown code fences, then extraction via regular expression. This fallback chain makes structured output robust against formatting variations across models.
API Keys
No key values are documented here. Keys are read exclusively from environment variables, carried by files ignored by the version control system. The variables concerned cover the Mistral, Voyage, OpenAI, and Anthropic providers, as well as the database password. The environment initialization function parses these files at startup and injects them into the process environment without exposing them.
Mistral is the canonical embedding provider, selected for European data sovereignty reasons.
Database Connection
All Python automatons connect to the mothership central database via a dedicated database container, exposed on a non-standard port on the host side. The connection explicitly specifies the application schema in order to isolate Synedre tables from the PostgreSQL public schema. Credentials (database name, user, password) are carried by the environment variables described in the previous section and are never hardcoded.
Component Summary Table
The following table lists all active and experimental components of the memory and learning layer, their nature, and their role in the architecture.
| Component | Nature | Role |
|---|---|---|
| Note Indexer | Periodic task (15 min) | Traverses the Vault and indexes each note into the relational knowledge registry. |
| Vector Synchronizer | Periodic task (05:40) + inline trigger | Computes and stores vector representations (1024 dimensions) for all sources; incremental nightly update and on-demand recomputation during a ReAct session. |
| Retrieval Engine | RAG | Lexical, semantic, and hybrid search (rank fusion, coefficient 60); returns the K most relevant results after re-ranking and relevance score update. |
| Retrieval Evaluation Harness | Quality assurance | Measures recall@k, MRR@10, and top-1 precision against a frozen golden dataset; blocks any regression relative to the reference baseline. |
| Pre-Scaffold Hook | PreToolUse hook | Triggers a hybrid retrieval (top 4) before a scaffold skeleton is created; non-blocking. |
| Nightly Maintenance Orchestrator | Periodic task (05:00) | Coordinates the full maintenance loop: state inspection, coverage check, repair, regeneration, proposal, documentation publishing, re-inspection, and final housekeeping. |
| Health Check | Diagnostic | Evaluates five health dimensions of the system and records the result in the health registry and the daily journal. |
| Public Snapshot Synchronizer | Synchronization | Produces a sanitized snapshot (health + drift) and pushes it to the synedre.com public VPS. |
| AI Facade | Facade | Single entry point for embed and complete calls; routes requests according to the AI routing table; supports two paths to the primary model (direct API and CLI); logs per-request consumption. |
| Learning Engine | Engine | Transforms scars marked as learnable into structured suggestions pending human validation. |
| Post-Scaffold Retrospective | Feedback | Generates a lesson after each scaffold and deposits it in the Vault inbox (default model via interactive terminal; fallback to a lightweight alternative model). |
| Nightly Consolidator | Periodic task (04:00) | Consolidates ten long-term memory features (F1–F5, F7–F11); runs in simulation mode by default. |
| Skill Proposal Detector | Weekly task (Sun. 04:00) | Analyzes repeated iteration patterns and creates new skill proposals via the LLM; functional component in production. |
| Proposal Monitor | Hourly task | Alerts the founder when the number of pending skill proposals exceeds a configurable threshold. |
| Pattern Detector (MVP) | Weekly task (Sun. 03:00) | Scans and logs patterns without creating proposals; inactive skeleton, distinct from the proposal detector above. |
| Scar Qualifier | LLM | Assigns each scar a proposed error type, severity level, confidence score, and reasoning; prefixes learnable scars. |
| Monthly Vault Hygiene | Monthly task | Detects dead links, archives obsolete notes, and deduplicates by SHA-256 fingerprint; produces a structured monthly report. |
| Memory Metrics | Periodic task (6h) | Computes Vault metrics, retains them over 90 days, and generates alerts on anomaly detection. |
| User Retrieval | Contextual retrieval | Leverages the multi-dimensional user model (stored in JSONB) to produce personalized briefings for agents. |
| Knowledge Graph | Experimental | Builds a deterministic graph queryable within two hops; includes an evaluation harness and a ghost-mode report. Go/no-go planned for September 2026. |
Data Registries
| Registry | Role |
|---|---|
| Scar Registry | Lessons (failures and wins), importance, learnable status. |
| Vector Registry | Indexed vector representations (HNSW, cosine similarity). |
| Zettelkasten Registry | Vault notes indexed in the relational model. |
| Skill Proposal Registry | LLM-generated proposals pending human validation. |
| Native Skill Registry | Validated and activated skills (promotion target for proposals). |
| Learning Suggestion Registry | LLM suggestions pending validation before application. |
| Learning Audit Log | Trace of each validated and applied suggestion. |
| Memory Metrics Time Series | 90-day history of Vault indicators. |
| User Model | Multi-dimensional profile (JSONB) feeding retrieval briefings. |
| Health Registry | Daily snapshots per dimension (five dimensions + global score). |
| Sanitized Public Snapshot | Daily health and drift snapshot, synchronized to the public VPS. |
| AI Routing Table | Single source of truth for per-feature routing (embedding provider, completion provider, model, additional parameters in JSONB). |
| AI Consumption Log | Per-request recording of API consumption (provider, model, billing label, input/output tokens, cost in USD) — basis for per-tenant chargebacks. |
| Golden Evaluation Dataset | Reference dataset for the retrieval evaluation harness. |
| Retrieval Baseline | Frozen metrics (recall@k, MRR, top-1) serving as the non-regression gate. |
User Interfaces
- Skill Validation Dial — Hub interface allowing the founder to approve or reject automatically generated new skill proposals.
- Memory Interface — enables browsing and querying the Vault from the Hub.
- Learning Interface — manually triggers a structured learning suggestion.
- Win Recording Interface — records a positive lesson in the scar registry.