Chapters

DOC-04 / Technical reference · Chapter 04

Data model for worksites, jobs and tasks

This chapter describes the Synedre OS data hierarchy — worksites, jobs and tasks — along with the associated Python entities, statuses, scopes and fields that allow the Atlas orchestrator to drive all development work without any state outside the database.

Worksites, jobs & tasks

Purpose

The Synedre OS harness organises all development work into a hierarchy persisted in the database — 1 worksite = N jobs = N tasks — so that the Atlas orchestrator and agents can create, track, parallelise and close work without any state held outside the database. This page documents the data model, the Python entity API that manipulates it, the mandatory seven-step creation procedure, the multi-session locking mechanism, and status cascades (including the resolution of a paused job via a bis-job).

1. Data model

1.1 Hierarchy

Three levels nest within one another: a worksite contains N jobs, each job contains N tasks. Three Python entity classes wrap these tables; two auxiliary entities manage session locks and inter-task dependencies respectively.

Conceptual entity Role Primary key
Worksite Top-level container grouping a set of related jobs id_chantier
Job Development unit assigned to an agent id_travail
Task Atomic action composing a job id_tache
Auto-explode run log Audit trace of a single invocation of the automatic expansion pipeline id_run
Session lock Exclusive lock per worksite and per owner kind (id_chantier, owner_kind)
Task dependency Edge in the intra-job DAG (blocked task → blocking task) id_dep

Migration note: the worksite and job tables retain a prefix inherited from a previous generation, while the task and lock tables use a more recent prefix. This heterogeneity is a known technical debt; do not correct it without a dedicated worksite.

1.2 Statuses

Canonical statuses are split by level to prevent cross-level validation errors.

Worksite statuses: planning, dev, test, paused, done, cancelled.

Job statuses: discovery, planning, dev, paused, review, done, cancelled.

A union alias of both sets is retained for backward compatibility with certain existing modules. All new code must use the set specific to the relevant level.

The shared validation method accepts a status_set parameter so that each entity routes to its own enum: the worksite entity passes the worksite set, the job entity passes the job set.

Database constraints: PostgreSQL CHECK constraints have been placed on the status columns of the worksite and job tables. The enum is enforced at both the database and code levels. A raw SQL INSERT with an out-of-enum status will be rejected by PostgreSQL.

Task statuses: todo, doing, done, paused, cancelled — distinct vocabulary, with no CHECK constraint in the database at this time.

Canonical priorities are: P0, P1, P2, P3.

1.3 Scopes

The scope field discriminates the synchronisation perimeter (monolith vs OSS) and conditions certain validations. The database is the authoritative source over any documentation.

Worksite scopes (nullable column, CHECK constraint in the database):

  • synedre
  • codemyshop-oss
  • codemyshop-enterprise
  • tenant
  • business
  • juridique
  • negociation
  • conseil

Warning: the docstring of the skeleton-based creation method lists only the first five scopes. The database permits three additional ones (juridique, negociation, conseil), added for Atlas intents. The database is authoritative.

Task scopes (column validated in code and by an identical DB CHECK):

  • synedre-internal
  • codemyshop-oss
  • codemyshop-enterprise
  • tenant-single
  • tenant-multi
  • infra
  • doctrine

An invalid task scope raises a ValueError at entity creation time, before any database access.

1.4 Notable fields

At the worksite level, the most important fields are:

  • Mission letter (mission_letter, text): structured mission letter, corresponding to step 2 of the creation doctrine.
  • Pre-production test plan (preprod_test_plan, text): accepts Markdown or YAML v2; the presence of a version: key triggers automatic QA.
  • Closure command (ship_command, varchar 255): exact command to execute at delivery, for example ./ship <tenant> for a client or ./deploy synedre-os for the mother ship.
  • Auto-explode kill-switch (auto_explode, boolean, default true): disables automatic discovery→implementation expansion for this worksite.
  • Autonomous mode (mode_auto, boolean): the agent executes without validating each action.
  • AI cost ceiling (max_cost_eur, numeric): maximum budget per worksite (null = unlimited).
  • Client identifier (client_id): reference to the client registry, or NULL for an internal worksite.

At the job level, notable fields include:

  • agent_codename, agent_prompt: assigned agent and its working prompt.
  • zone_perimeter, exit_criteria: intervention perimeter and exit criteria.
  • context_json, decisions_json, discoveries_json: cumulative context JSON blobs.
  • depends_on_travail_id: inter-job dependency graph with cycle detection (see §1.7).
  • resolves_travail_id: core of the bis-job pattern (see §6).
  • conduite_slug, current_cue_position: current position within a scripted conduite.
  • contract_dto, mode_auto, repo_paths: interface contract, local autonomy, affected repository paths.

At the task level, notable fields include:

  • assignee_codename: agent assigned to this task.
  • estimated_tokens, recommended_model: budget and recommended model.
  • position: display order within the list.
  • last_test_result, actual_tokens, actual_cost_usd: result of the last test, actual consumption.
  • started_at, finished_at: lifecycle timestamps.
  • Visual intent (visual_intent, visual_url): URL of the expected visual render and URL of the post-deployment capture — NULL indicates a non-visual task. These fields feed the automatic visual verification pipeline after deployment.

1.5 Agent recruitment — per-worksite persistence

Agent recruitment on a worksite (step 3 of the doctrine) is persisted in a dedicated table, distinct from the task assignment field which only carries the assignment of an isolated action.

Column Role
id_assignment (int, PK) Assignment identifier
id_chantier (int) Concerned worksite (foreign key)
agent_codename (varchar) Recruited agent
role (varchar) production / lead_production / validation / lead_validation
position (int) Display order
date_assigned / date_unassigned (timestamptz) Recruitment lifecycle
notes (text) Recruitment justification

This table is what the task→job cascade mechanism queries to determine whether a validation (QA) team is present: a count of agents whose role is validation or lead_validation greater than zero switches the cascade to a QA cycle instead of a simple status advancement (see §5).

1.6 Auto-explode run log

A log entity persists an audit trace for each invocation of the pipeline that transforms the decisions of a discovery job into implementation jobs (phases A, B, C). One row corresponds to one invocation.

The row is created with status pending at the start of the pipeline, then updated at the end:

Status Meaning
pending Run in progress
success Implementation jobs created
validation_failed LLM plan rejected by validation
llm_failed LLM API error
killswitched One of the three kill-switches halted execution

Key fields include the JSON plan produced by the LLM, the number of jobs created, token counters and cost in euros, as well as the dry_run and force flags. Entries are retained for 90 days (configurable). A global daily quota is configured in YAML: if the number of invocations in the last 24 hours exceeds it, the expansion is marked killswitched without raising an error. The run history is accessible from the list skill in the dashboard.

1.7 Task→task dependencies — intra-job DAG

An N:M dependency mechanism manages a directed acyclic graph (DAG) within a job. Not to be confused with inter-job dependencies (carried by the depends_on_travail_id column of the job): these two mechanisms operate at distinct levels.

Semantics: a blocked task cannot start until its blocking task is done. Strong business constraint: both tasks must belong to the same job — a cross-job dependency raises a dedicated application error (no SQL trigger).

Operation Method
Add a dependency add_dep(blocked, blocker)
List dependencies for a job list_deps_for_travail(id) — JOIN with blocking/blocked titles
List blockers for a task list_blockers_for_tache(id)
Check whether a task is unblocked is_tache_unblocked(id)
Remove a dependency remove_dep(blocked, blocker) — idempotent

Cycle prevention: a depth-first search (DFS) from the blocking task through the existing graph detects any path to the blocked task before the INSERT. A maximum depth guard (100 levels) protects against corrupted DAGs.

A blocker with status cancelled is considered resolved in the unblocking check, in order to avoid deadlock situations where a cancelled task would indefinitely prevent its dependants from starting.

The is_tache_unblocked method is used by selective autonomous mode to launch a task only if all its blockers are resolved.

Atomic creation of a worksite

The worksite creation method exposed by the project management engine is the sole canonical path for instantiating a worksite. It atomically inserts the worksite, its first travail, and at least one task, thereby preventing the creation of orphaned worksites (with no associated travail) or orphaned travaux (with no task).

Signature

create_with_skeleton(
    codename, title, *,
    first_travail: dict,
    first_tache: dict | None = None,      # deprecated — backward compatibility
    first_taches: list[dict] | None = None,  # preferred (doctrine v3)
    client_id: str | None = None,
    priority: str = "P2",
    scope: str | None = None,
    current_focus: str | None = None,
    notes: str | None = None,
) -> dict

The first_travail dictionary accepts the following fields: codename, title, and optionally priority, current_phase, current_task, next_action, blockers.

Each entry in first_taches must include at minimum title and assignee_codename, and optionally priority, estimated_tokens, estimated_h, description, position, recommended_model, scope, visual_intent, visual_url.

Blocking validations

All validations are accumulated before the first INSERT and raise an error if any one of them fails:

  1. Codename format — strict kebab-case: lowercase letters, digits and hyphens, between 4 and 64 characters (regex ^[a-z0-9][a-z0-9\-]{2,62}[a-z0-9]$).
  2. Codename uniqueness — an existence check is performed; a codename cannot be reused.
  3. Valid priority — must belong to {P0, P1, P2, P3}.
  4. Valid initial travail — codename and title must be non-empty.
  5. At least one task — either first_tache or first_taches is mandatory; providing both simultaneously is an error.
  6. Known assignee — each assignee_codename must correspond to an active agent in the agent registry.
  7. ≥ 2 distinct assignees if the scope is of tenant type (doctrine v3) — the set of assignees must contain at least two distinct codenames, otherwise creation is rejected.

Non-blocking warnings: the absence of estimated_tokens on a task generates a warning but does not prevent creation — an automatic estimator will fill in the missing value.

Atomicity and rollback

All inserts are executed within a single transaction (BEGIN … COMMIT). If any INSERT fails, the entire transaction is rolled back: it is impossible to obtain a worksite without a travail, or a travail without a task. Travaux and tasks reference their parent via a subquery on the worksite codename, ensuring correct foreign key resolution in insertion order within the same transaction.

Token estimation and recommended model

If recommended_model is not provided for a task, the engine computes it automatically according to the following logic:

Priority P0 or repeated failures (≥2 iterations failed)  → <high-capacity-model>
estimated_tokens ≥ 8,000 (or absent)                     → <high-capacity-model>
estimated_tokens ≥ 1,500                                 → <mid-tier-model>
otherwise                                                   → <lightweight-model>

Outside the skeleton, when a task is created in isolation without estimated_tokens, the estimation engine automatically evaluates the token volume from the content, then recomputes the recommended model and updates the database row.

Attached skills and tools

After insertion, the skeleton attaches the optional skills and tools declared per task. An unknown skill or tool does not cause a failure: it generates a warning and a pending validation proposal, allowing the registry to be enriched incrementally without blocking creation.

Return structure

{
  "id_chantier": int,
  "id_travail": int,
  "id_tache": int,           // backward compat — first in the list
  "id_taches": [int, ...],   // doctrine v3
  "codenames": {
    "chantier": str,
    "travail": str,
    "tache_title": str,
    "tache_titles": [str, ...]
  },
  "warnings": [str, ...]
}

Command-line interface

python3 -m <worksite-management-module> --create-with-skeleton [--json-file <path>]
# without --json-file: the JSON payload is read from standard input

A verification hook monitors direct SQL INSERTs on the worksite, travail, and task tables performed outside this facade and emits a warning if such a practice is detected.

This section focuses on --create-with-skeleton and the locking mechanisms. The engine exposes additional verbs (--list, --show, --list-travaux, --create-travail, --update, --close, --resolve, …) — refer to the built-in help for the complete list.

7-step procedure — worksite creation

Mandatory rule: no worksite may be created without following these steps in order. For worksites triggered by email, the dedicated facade executes steps 0a through 4 under constraint (rejection if the attachment scan fails or if fewer than two agents are recruited). It stops at the atomic skeleton creation (step 4) and performs neither step 2 (drafting the mission brief: the facade generates only generic task titles of the form @agent — analysis…) nor step 5 (post-skeleton update of the mission fields, scope, test plan, and delivery command). These two steps must be performed manually after the facade call.

Step Action Mechanism
0a Read the email request verbatim Via the inbox API or the message read command
0b Extract and scan attachments before any reading The attachment scanner analyzes each file; a verdict other than clean triggers an immediate block
1 Audit of available agents Query the active agent registry (codename, alias, role, group)
2 Draft the mission brief Structure: OBJECTIVE / CONTEXT / SCOPE / DELIVERABLES / CONSTRAINTS / DOCTRINE, based on content read in steps 0a/0b
3 Explicit recruitment ≥ 2 distinct agents if the scope is of tenant type
4 Atomic creation via skeleton See previous section
5 Post-skeleton update Mission brief + scope + preprod test plan + delivery command, via named UPDATE on the codename

Email-based creation facade

The email processing facade follows the internal flow below (the step numbers displayed on screen by the script correspond to its own internal numbering, distinct from the doctrinal numbering 0a→5 described above):

--id <email-id>
  STEP 1  Retrieve the message via the inbox API
  STEP 2  Extract attachments + scan
             → attachment not "clean" → BLOCK, exit code 2
  STEP 3  Summarize the request (title, priority, scope)
  STEP 4  List active agents + recruitment
             → fewer than 2 distinct agents → BLOCK, exit code 3
  STEP 5  Build payload (1 task/agent, generic titles) + "-init" travail
             → call create_with_skeleton(**payload)
             = DOCTRINAL step 4 (no mission brief UPDATE, no doctrinal step 5)

Exit codes: 2 = non-clean attachment, 3 = fewer than 2 agents, 4 = validation error. The --dry-run option displays the payload without performing any INSERT.

Two distinct ≥ 2 agent checks: the facade always requires at least 2 agents — an unconditional check, independent of the scope. The create_with_skeleton method applies its own ≥ 2 validation only if the scope starts with tenant. The default scope tenant aligns the facade's blocking message but does not condition its internal check.

Note: the facade creates a single -init travail in the discovery phase. The transition to implementation travaux remains manual or goes through the automatic travail explosion mechanism (see the dedicated section).

Test plan and delivery command fields (step 5)

These two fields are mandatory for any non-trivial worksite. In their absence, the update cascade emits a non-blocking warning, but the validation lead cannot activate the "READY TO SHIP" banner. If the test plan is provided in YAML v2 format (with the version: prefix), the cascade automatically triggers a background Playwright QA session. This behavior can be disabled via a dedicated environment variable.

Multi-session locking

The worksite locking mechanism allows N different worksites to be opened in parallel (N terminals or workers) while preventing the same session from opening the same worksite twice. It is a collision-prevention net, not an ergonomic blocker.

Data model

  • The lock table uses a composite primary key (worksite identifier, owner type) where the type is either user (interactive session) or worker (agent subprocess).
  • Both types may coexist on the same worksite; each type only contests its own slot.
  • The owner type is detected via a dedicated environment variable, with fallback to process hierarchy inspection.
  • The session identifier is resolved in this order: session variable > transcript fingerprint > pid/user/host combination.

TTL and acquisition

The lock time-to-live is 30 minutes of inactivity. Acquisition attempts an INSERT with conflict resolution: it succeeds only if the session identifier matches the existing lock or if the lock has expired (last activity > 30 minutes). On conflict, the operation returns {acquired: false, owner: {...}}.

The lock is acquired automatically when the worksite context is opened. On refusal, a ChantierLockedError exception is raised and intercepted by the command facade. An environment kill-switch allows the mechanism to be entirely disabled. In compatibility mode (table absent), the lock is always granted.

Verbs and lifecycle

Operation Description CLI option
Active lock inventory Lists all live locks --locks
Release own lock Conditional DELETE on (worksite + type + session), idempotent --release <codename>
Claim another's lock (same type) Evicts the previous owner and assigns the lock to the caller --force-claim <codename>
Keep lock alive Updates the last-activity timestamp — (called internally)

Three release safety nets ensure no lock remains blocked indefinitely:

  1. Session-end hook — triggered automatically on interactive session close, releases the lock immediately.
  2. TTL cron — runs every 5 minutes and deletes locks whose last activity exceeds 30 minutes. Idempotent, always exits 0, silent if the database is unreachable or the table is absent. This is the true safeguard against crashes, kill -9, and SSH disconnections.
  3. Manual --force-claim — last resort if neither of the two preceding mechanisms has yet fired.

5. Status Cascades

Entity updates are overloaded to propagate terminal statuses from one level to the next. The cascade is limited to one step per level: each step re-triggers its own cascade.

task.update(status='done'/'cancelled')
   └─ cascade to job
        if ALL tasks in the job are done/cancelled AND ≥1 done:
        ├─ QA team present on the project?
        │   (agent with role 'validation' or 'lead_validation' in the project team)
        │   YES → QA cycle executed:
        │          global verdict pass? → job moves to 'done'
        │          otherwise → fix tasks created, job stays in 'dev' (NO bump)
        │   NO → direct bump: job moves to 'done'

job.update(status='done'/'cancelled')
   └─ cascade resolve-paused      (on 'done' only) → §6
   └─ cascade to project
        if ALL jobs in the project are done/cancelled AND ≥1 done
        → project moves to status 'test'  (= preprod, manual review)
   └─ bug detector                (on 'done', non-blocking)

⚠️ The task → job bump is NOT systematically direct. If the project has a QA team — at least one agent with the validation or lead_validation role in the project team (cf §1.5) — the cascade delegates to the QA cycle instead of bumping immediately: the job only moves to done if the global verdict is positive; otherwise fix tasks are created and the job remains active. The direct bump occurs only when no QA team is present. An exception raised during the QA cycle is fail-safe (logged, no bump).

The final test → done transition remains manual (validation act after ./ship), never cascaded.

5.1 Discovery-only guard / auto-explode

The cascade toward the project does not promote to test status if all completed jobs are in the discovery phase: without this guard, a project automatically created from an incoming email (with a single initial analysis job) would enter preprod review as soon as the analysis finished, before any implementation jobs existed.

In that case, an automatic discovery → implementation explosion mechanism may trigger. It is gated by three successive kill-switches:

  1. An environment variable allowing global deactivation of auto-explode;
  2. A database flag on the project itself (auto_explode = FALSE);
  3. A global YAML configuration flag.

If any one of these three guards blocks, the project remains in planning for manual review. Each invocation of the explode is audited in a dedicated log via a tracking entity whose possible statuses are:

  • killswitched — one of the three guards blocked;
  • success — implementation jobs were created;
  • validation_failed — the plan proposed by the model was rejected.

5.2 Native SQL cascade (incoming emails)

Independently of the application-level cascades described above, a native database trigger propagates the transition to done state at the SQL layer, invisibly from the application layer.

Its behavior: when a project transitions to done for the first time, it automatically marks as resolved (with a timestamp) all incoming emails attached to that project that are not already resolved or flagged as spam.

Practical consequence: marking a project done automatically resolves associated incoming emails, without a single line of application code. This behavior should be kept in mind when debugging an email that transitioned to resolved apparently on its own.


6. Resolve-paused — companion-job pattern

When a job is set to paused (blocked), a companion job is created holding a reference to the blocked job. When the companion moves to done, an automatic resolution mechanism clears the blocked job before the cascade to the project — because it modifies the count of the project's terminal jobs.

Effects triggered when the companion job moves to done:

  1. The blocked job moves to done (via a direct update that bypasses cascade recursion);
  2. The blocked job's todo tasks are bulk-cancelled;
  3. A symmetric audit trail entry is added to the decisions_json field of both the companion AND the blocked job.

Applied guards:

Condition Behavior
No resolve reference (inherited path) silent no-op
Blocked job belongs to a different project ValueError — cross-project resolution forbidden
Blocked job is already done idempotent no-op
Blocked job itself references the companion (A↔B cycle) ValueError — cycle forbidden
Orphaned FK reference (job not found) warn + skip
Blocked job status ∉ {paused, dev, planning} warn + skip

Associated database constraints: partial index on the resolve reference column, CHECK constraint forbidding self-reference (resolves_job_id <> id_job), foreign key with ON DELETE SET NULL.

The ./project --resolve --dry-run command exposes this pattern in simulation mode.


7. Pitfalls & invariants

  • Multi-line columns and SQL reads. Certain text fields (mission brief, notes, preprod test plan, current focus, next action, current task) contain newline characters. Reads targeting these columns must use a CSV extraction mode rather than standard SQL reading, or risk silent truncation. Reuse this pattern for any new read of these columns.
  • The field registry must follow the DDL. Adding a column to the database without adding it to the field registry of the corresponding entity renders any update to that column silently inoperative. This pitfall has already been encountered on several columns discovered after the fact.
  • Split status sets. The set of valid statuses for a project differs from that of a job. A review status valid for a job is out-of-enum for a project. Always pass the correct set during validation. Never use the general canonical status set for level-specific code.
  • CHECK constraints in the database. Status CHECK constraints exist in the database for projects and jobs. A direct INSERT with an arbitrary (out-of-enum) status will fail — including in test migration scripts.
  • Project scope: the database is authoritative. When in doubt about the allowed values for a project's scope, always check the database constraint rather than the Python docstring.
  • Visual fields on tasks. Tasks have optional visual intent and visual URL fields (NULL = non-visual task). A post-deployment verification pipeline checks that the visual intent is rendered. Do not omit these columns from the task entity field registry, or the pitfall described above will apply.
  • Database credentials. Database connection credentials are read from environment variables in the root .env file. They must never appear in plaintext in the code or in the database.
  • Two dependency mechanisms coexist. Job → job dependencies (reference column on the job) and intra-job task → task dependencies (N:M DAG via a dedicated dependency table) are distinct, non-interchangeable mechanisms. The cross-job constraint for task→task dependencies is enforced at the application layer: corrupting it via direct SQL will not be caught by a trigger.
  • The explode audit log is not a queue. Auto-explode audit log entries are passive: the pipeline creates and updates them itself; nothing consumes them. Do not use them to trigger or restart an explode.