Skip to content

feat(systems): first-run seed of a default system manifest (trinity-enterprise#124) - #1764

Merged
dolho merged 2 commits into
devfrom
feature/ent124-default-system-seed
Jul 24, 2026
Merged

dolho merged 2 commits into
devfrom
feature/ent124-default-system-seed

Conversation

@vybe

@vybe vybe commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Summary

First-run seed of a default system manifest (abilityai/trinity-enterprise#124): on a genuinely fresh install, Trinity now auto-deploys a bundled starter fleet once, right after first-time setup — the multi-agent generalization of the Cornelius seeder (ent#107), driven through the resilient deploy path (ent#125).

  • Deploy orchestration extracted to the service layer (Invariant Fix: Add missing Docker labels to system agent container #1, feat: system-emitted agent.task.completed/failed events at execution terminal (async caller report-back) #1578 precedent): the full pipeline moved verbatim from routers/systems.py::deploy_system into services/system_service.py::deploy_manifest(); the router is now a thin HTTP wrapper (status=="failed" → 500 JSONResponse; everything else — 400 parse, strict-abort status codes, dry-run — passes through unchanged). The default create_agent_fn lazily resolves the routers/agents facade (not crud), preserving agent_created WS broadcasts on every deploy path.
  • New services/system_seed_service.py: ensure_first_run_seeded() (both call sites: setup-completion background task + lifespan safety-net with a strong task ref) resolves a persisted first-run verdict (first_run_fresh, computed once BEFORE Cornelius provisions; cornelius_seeded=="true" forces not-fresh) and runs both seeders under that one decision — without this, the first seeder's own agents poison every later pass's freshness count (a failed fleet deploy could never retry; a failed Cornelius would self-mark seeded after the fleet lands).
  • Idempotency & safety: durable default_system_seeded flag + default_system_seed_info diagnostics JSON; SETNX lock (system_seed:provision, fail-open); existence backstop — any already-reserved {system}-{short} name converges the flag without deploying (the deploy path suffixes name collisions instead of 409ing, so a fail-open lock race would otherwise double-seed). Flag policy: deployed/partial → set (a partial fleet must never be re-deployed — suffix duplicates); failed (0 created)/exception → not set (retry-safe).
  • Operator control: TRINITY_DEFAULT_SYSTEM_MANIFEST env — path to a private distribution manifest, or disabled/none/off/0/false to skip (no flag burn; set-but-empty ⇒ bundled, the Voice DOA on compose deploys: empty VOICE_MODEL from compose shadows code default → Gemini 'model is required' #1076 compose class). An explicitly-set-but-unreadable override fails loudly (ERROR + operator-queue alert) and never silently falls back. Partial/failed seeds also raise one deterministic-id operator alert (platform-path direct DB create, bug: operator-queue create path has no rate limit or size caps — flooding/operator-fatigue surface (blocking pull default-ON) #1632-exempt).
  • Bundled fleet config/manifests/default-system.yaml: the in-tree acme trio (local:scout/sage/scribe) deployed as the coherent team its CLAUDE.md content assumes (name acme, shared folders, full-mesh) — no schedules (zero-credential installs must not accumulate failing crons), no prompt: (never mutates platform-wide trinity_prompt). Content is data: ent#137's curated public fleet swaps the manifest, not the mechanism. Baked into the backend image AND dir-mounted in both compose files (the dev ./src/backend:/app mount shadows image COPYs — the mount is load-bearing locally).
  • CI insurance: the e2e stack sets the disabled sentinel explicitly to keep its zero-agent baseline (learnings 2026-07-08).
  • ent#125's partial-deploy warning no longer points at refactor: Split routers/processes.py (1018 lines) #124 for converge support (converge remains deferred under epic ent#122; the seeder sidesteps it by never re-deploying).

Design notes for review

  • Auto-seed vs opt-in (flagged by the independent strategy review): ent#124's stated direction is silent auto-seed; the opt-in UI install path is its sibling ent#126. With zero credentials the seeded agents idle until a platform key/subscription is configured (they use use_platform_api_key=1, so an install whose setup configured ANTHROPIC_API_KEY works immediately). The disabled sentinel is the opt-out.
  • Fresh-install footprint: trinity-system + Cornelius + 3 starters (cpu/memory are limits, not reservations). Documented in requirements §16.5.1.
  • An ent#107-era install (Cornelius seeded, even with all agents since deleted) upgrading to this version gets no starter fleet — pinned by test.

Changes

  • src/backend/services/system_service.py — deploy_manifest() + _failure_reason + _default_create_agent_fn (moved/new)
  • src/backend/routers/systems.py — deploy endpoint thinned to the HTTP wrapper
  • src/backend/services/system_seed_service.py — new seeder + orchestrator
  • src/backend/services/cornelius_agent_service.py — optional precomputed fresh verdict (legacy behavior when None)
  • src/backend/main.py, src/backend/routers/setup.py — call sites → ensure_first_run_seeded()
  • config/manifests/default-system.yaml — bundled starter manifest
  • docker/backend/Dockerfile, docker-compose.yml, docker-compose.prod.yml, .env.example, .github/workflows/frontend-e2e.yml — packaging + env + CI sentinel
  • docs/memory/requirements/roadmap.md (§16.5.1), docs/memory/architecture.md, feature flows (system-manifest.md, cornelius-default-agent.md)
  • src/backend/services/operator_queue_service.py — system-seed- added to the bug: operator-queue create path has no rate limit or size caps — flooding/operator-fatigue surface (blocking pull default-ON) #1632 reserved id prefixes (an agent can't pre-create-and-silence the seed alerts)
  • Tests: tests/unit/test_ent124_default_system_seed.py (30 new), test_ent125_resilient_system_deploy.py (patch targets migrated to the service), test_ent107_cornelius_seed.py (+3 fresh-param tests), test_setup_operator_profile.py (call-site binding migrated), tests/registry.json

Review provenance

Full pipeline ran: /autoplan (independent strategy + engineering voices; 25-decision audit trail) → /implement → adversarial diff review. All HIGH/MEDIUM review findings fixed in this PR: stale setup-test bindings; a never-raises hole on the admin lookup + an unbelted orchestrator call (the strong task ref would have suppressed the only diagnostic); seed alerts made un-silenceable via the reserved-prefix guard; a parse-broken override now alerts instead of silently retrying every boot; a crash-interrupted partial fleet detected by the converge backstop now alerts too. Known accepted residuals (LOW): a truly simultaneous fail-open lock race can still suffix-duplicate (boot-scoped); system_service raising HTTPException is a documented verbatim-move tradeoff.

Test Plan

  • pytest tests/unit/test_ent124_default_system_seed.py tests/unit/test_ent125_resilient_system_deploy.py tests/unit/test_ent107_cornelius_seed.py tests/unit/test_setup_operator_profile.py — 66 passed
  • Broader slice tests/unit -k "system or cornelius or setup" — 97 passed, 4 skipped
  • Real bundled manifest validated through the executor's own parser; every local: template it references asserted to exist in-tree (learnings 2026-07-23 blank-agent trap)
  • Compose files YAML-validated; touched modules compile + unused-import clean
  • Manual: fresh-stack boot seeds acme-scout/acme-sage/acme-scribe after setup completes (needs a wiped local stack — not run against the live dev stack)

Refs abilityai/trinity-enterprise#124 (private-tracker feature — closed manually at release, closing keywords don't cross repos)

🤖 Generated with Claude Code

Eugene Vyborov and others added 2 commits July 24, 2026 14:17
…oard skill + P-37 catalog entry

Co-Authored-By: Claude Fable 5 <[email protected]>
…nterprise#124)

On a genuinely fresh install, auto-deploy a bundled starter fleet once,
right after first-time setup — the multi-agent generalization of the
Cornelius seeder (ent#107), driven through the resilient deploy path
(ent#125).

- Extract the deploy orchestration verbatim from routers/systems.py into
  services/system_service.py::deploy_manifest (Invariant #1; router is a
  thin HTTP wrapper). Default create_agent_fn lazily resolves the
  routers/agents ws-broadcasting facade so agent_created broadcasts are
  preserved on every deploy path.
- New services/system_seed_service.py: ensure_first_run_seeded() resolves
  a PERSISTED first-run verdict (first_run_fresh — computed once BEFORE
  Cornelius provisions; cornelius_seeded forces not-fresh) and runs both
  seeders under that one decision, closing the cross-pass count-poisoning
  bug. Durable default_system_seeded flag + seed-info JSON, SETNX lock,
  reserved-name existence backstop (the deploy path suffixes collisions
  instead of 409ing), flag policy deployed/partial=set failed/error=retry,
  operator-queue alerts (system-seed-* ids, #1632 reserved prefix) on
  partial/failed/error/unreadable-override/interrupted-converge.
- cornelius_agent_service.ensure_seeded gains an optional precomputed
  fresh verdict (legacy count when None).
- Bundled config/manifests/default-system.yaml: the in-tree acme trio
  (local:scout/sage/scribe) as the coherent team its content assumes —
  no schedules, no prompt. TRINITY_DEFAULT_SYSTEM_MANIFEST env override /
  disable sentinels; baked into the image AND dir-mounted in both compose
  files (the dev src mount shadows image COPYs). e2e stack pins the
  disabled sentinel to keep its zero-agent baseline.

Refs trinity-enterprise#124 (closed manually at release — closing
keywords don't cross repos).

Co-Authored-By: Claude Fable 5 <[email protected]>
@vybe
vybe requested a review from AndriiPasternak31 as a code owner July 24, 2026 12:39
@dolho

dolho commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

/review Report

Branch: feature/ent124-default-system-seed → dev (merge-base bc546b66)
Files Changed: 23 (+1669 / −354)
Scope: CLEAN — the diff is the seeder, the service extraction it needs, packaging, docs, tests. Nothing unrelated rode along.
Plan Completion: acceptance items from the PR body all traceable to code. deploy_manifest extraction (system_service.py:748), seeder (system_seed_service.py), both call sites (main.py:427, setup.py:142), bundled manifest, packaging in all four files, reserved-prefix guard (operator_queue_service.py:107). The one UNVERIFIABLE item is the author's own unchecked box — fresh-stack boot never run.

Critical Findings (block merge)

None. No new endpoints, no raw SQL, no unparameterized input, no credential path. _failure_reason sanitizes at the exit point and _sanitized_reason reuses it rather than re-deriving, so the seeder's alert text inherits PAT redaction. The two duplicate-prevention layers (SETNX lock + name-reservation backstop) are genuinely independent.

Informational Findings

[I1] Correctness: the persisted first-run verdict never re-validates, so every non-flag-burning skip path becomes a delayed trigger (Confidence: 8/10)
File: src/backend/services/system_seed_service.py:159 and :96

Evidence — the verdict is computed once and stored forever:

stored = db.get_setting_value(_FRESH_VERDICT_KEY, None)
if stored is not None:
    return stored == "true"

and the disable sentinel returns before the freshness check, deliberately not burning the flag:

# 2. Operator disable sentinel. Deliberately does NOT set the flag —
#    un-setting the sentinel on a still-fresh install seeds normally.
if override_raw.lower() in _DISABLE_SENTINELS:
    return self._skip(result, "disabled", ...)

Issue: first_run_fresh is written on the first ensure_first_run_seeded() call — which happens at setup completion even when seeding is disabled or the manifest is missing. It is never recomputed. Three skip paths intentionally leave default_system_seeded unset, and each one therefore arms a seed that fires at an arbitrary later date:

  • disabled sentinel — operator sets it at install, runs the platform for months, later drops the env var (or ships a compose change that stops passing it). Next boot: verdict still "true" → starter fleet deploys into an established fleet.
  • manifest_unavailable — the likeliest one locally: without the new ./config/manifests bind mount the seed skips flagless every boot; the user builds their real fleet; a later compose update adds the mount → 3 surprise agents.
  • failed (0 created) — retry-safe by design, but the retry window is unbounded.

The existence backstop doesn't help: it only matches acme-scout/acme-sage/acme-scribe, and a user's own agents have different names. So the module's central promise — "do NOT surprise an established install with a heavy container" — has a hole in exactly the states the design chose not to flag.

Why it's not trivially fixable: re-checking count_non_system_agents() == 0 at deploy time is precisely the poisoning the persisted verdict exists to prevent (Cornelius's own agent would flip the count). A correct fix needs the count to be attributable — e.g. persist the agent count alongside the verdict and, at seed time, require that the current non-system agents are a subset of {Cornelius} ∪ {manifest final names}; or scope the retry (only while count_non_system_agents() <= agents_this_orchestrator_created).

Suggestion: fix, or file the follow-up and say so in the docstring — right now the docstring reads as though the flag policy fully covers this.

[I2] Observability: the honest-status alert fails silently (Confidence: 9/10)
File: src/backend/services/system_seed_service.py:432

except Exception as e:
    logger.debug("Seed operator alert failed (non-fatal): %s", e)

The operator-queue alert is the only channel telling an operator the fleet seeded partially. create_item raises ValueError on several belt conditions (#1632) and can fail on DB error — and that failure lands at DEBUG, invisible at default level. The partial-deploy logger.warning above it survives, so this isn't total blindness, but the converge-path partial (:243) has no accompanying log — there, a failed alert means the interrupted fleet is entirely silent. Suggest WARNING, and a log line on the converge-partial branch.

[I3] Robustness: blind lock release can delete another worker's lock (Confidence: 7/10)
File: src/backend/services/system_seed_service.py:466, :475
_acquire_lock fails open (returns True on Redis error without setting the key); _release_lock then issues an unconditional r.delete(_PROVISION_LOCK_KEY) in the finally. A worker that failed open can delete the real holder's lock mid-deploy. The codebase already has the right pattern for this — monitoring:leader does own-lease-only refresh (#1464). Impact is small because the existence backstop is the real duplicate guard, but a value-token guard on release would cost two lines.

[I4] Test gap: the CI insurance has never executed (Confidence: 10/10)
File: .github/workflows/frontend-e2e.yml:145
The TRINITY_DEFAULT_SYSTEM_MANIFEST=disabled sentinel protects the e2e zero-agent baseline — and the e2e job is skipping on this PR (label-gated), so that line has never run. The workflow comment is admirably honest that Cornelius stays un-seeded here "only by timing," which means the baseline is one workflow refactor away from breaking with a confusing symptom. Worth one ui-labelled run before merge, since the seeder's whole job is to create containers in the environment that asserts none exist.

[I5] Alert dedup is permanent across all statuses (Confidence: 8/10)
File: src/backend/services/system_seed_service.py:420
create_item maps item["id"] → request_id with ON CONFLICT (agent_name, request_id) DO NOTHING, so system-seed-override-unreadable can be created exactly once ever — including after an operator clears it via Clear All without fixing the override. For the one-shot seed statuses that's correct; for override-unreadable, which recurs every boot, "alert once and never again" may not be the intent. Retention (90d) eventually frees it. Flagging only because the docstring says "at most one open row per kind," and the row need not be open to suppress.

[I6] Stale type hint on the facade (Confidence: 9/10)
File: src/backend/routers/agents.py:106 — request: Request, while the underlying _create_agent_internal is correctly Optional[Request] = None (crud.py:1629) and the seeder now passes request=None through this facade. Runtime-safe (verified: request is never dereferenced in the create path), but the hint now lies about the contract the seeder depends on.

Clean Categories

  • SQL & data safety — no raw SQL; all writes via db.set_setting / existing accessors. No migration (system_settings KV).
  • Auth boundaries — no new endpoints; the router keeps require_role. The seeder is a boot/background path with no request principal, and builds its User from the admin row, matching the Cornelius precedent (cornelius_agent_service.py:114).
  • Credential exposure — _failure_reason applies sanitize_text(redact_url_userinfo(...)); _sanitized_reason delegates to it rather than re-implementing. Alert context carries a path and names only. .env.example uses no real value.
  • Verbatim-move fidelity — I diffed steps 1–12 line by line: parse/validate 400s, dry-run shape, strict abort with the original status code, prompt-after-create, created_map scoping, the five best-effort config phases, start_all_agents. The only deltas are the documented ones (catch-all moved into the service; failed→500 wrap left in the router) and the create_agent_fn seam. Behavior for POST /api/systems/deploy is unchanged.
  • WS broadcast preservation — _default_create_agent_fn resolves the routers/agents facade, not crud, so agent_created still fires on the seed path. Lazy call-time import avoids the cycle. This was easy to get wrong.
  • Enum/value completeness — system-seed- added to _RESERVED_ID_PREFIXES; checked the other consumers of that tuple, nothing else keys off it. SystemDeployResponse.status gains no new value.
  • Manifest validity — full-mesh is in valid_presets (system_service.py:133); local:scout/sage/scribe all exist in config/agent-templates/; no schedules: and no prompt:, matching the stated rationale.
  • Packaging — Dockerfile COPY + bind mount in both compose files; the dev ./src/backend:/app shadowing problem is real and the mount is the right fix.
  • Frontend — no changes.

Verification performed

  • Merge-base diff read in full; system_seed_service.py read end to end.
  • Confirmed get_user_by_username returns Optional[Dict] (db/users.py:70), so the admin_row.get(...) in the User build is safe — this would otherwise have made the seeder fail 100% of the time behind a caught exception.
  • Confirmed count_non_system_agents excludes soft-deleted and system rows (db/agents.py:371).
  • Confirmed create_operator_queue_item(agent_name, item) signature and the id→request_id mapping.
  • CI: all 17 required checks green, including pytest head × 3 seeds, schema-parity, regression diff, enterprise-docs-guard, gitleaks. e2e skipped (see I4).
  • Not run: the unchecked manual item — fresh-stack boot actually seeding acme-*. I did not wipe a stack to verify it.

Summary

  • Critical: 0
  • Informational: 6 — I1 is the one worth a decision before merge; I2/I3 are cheap hardening; I4 is a CI run; I5/I6 are notes.
  • Scope: clean. The service extraction is the right call and was executed faithfully — that's the part that could have quietly broken the existing deploy endpoint, and it didn't.

Durable lesson worth adding to docs/memory/learnings.md (not written — wrong branch checked out): a persisted one-shot verdict must be paired with re-validation at action time; otherwise every skip path that deliberately avoids burning the completion flag becomes a delayed trigger that fires when the skip condition is removed.

🤖 Reviewed with /review (Claude Opus 4.8)

@dolho
dolho merged commit 38bda3e into dev Jul 24, 2026
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants