Skip to content

fix(deploy): deploy-local integrity contract — embedded manifest verified twice, symlinks preserved, named errors, idempotent + locked (#2060) - #2485

Merged
vybe merged 8 commits into
devfrom
trinity-ability/issue-2060
Sep 3, 2026
Merged

vybe merged 8 commits into
devfrom
trinity-ability/issue-2060

Conversation

@trinity-ability

@trinity-ability trinity-ability commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

deploy_local_agent (the archive path) could deploy an agent that was not the agent on disk and still answer status: "success" — pruned .claude/skills/, dereferenced or fatal symlinks, opaque 500s naming no file. Nothing in the round trip compared what landed against what was packaged. This PR ships the integrity contract:

  • Embedded manifest, verified twice. The caller computes .trinity-manifest.json from the disk tree ({path, sha256 | link_target}) and the tar carries it as an ordinary member. The backend verifies it post-extract (before any side effect) and post-copy into /data/deployed-templates/<version>; any drift is a fail-closed 400 MANIFEST_DRIFT naming missing / altered / extra / link_mismatch paths. Embedding (not a request field) is load-bearing: a 5000-entry manifest as a tool argument would blow the same output-token ceiling as the archive and recreate the bug one level up.
  • Layered requiredness. The MCP tool's execute() sets require_manifest: true in tool code (not a model-controlled parameter) → no manifest = 400 MANIFEST_REQUIRED carrying the generation snippet. The raw HTTP API defaults to false so the shipped PyPI CLI and the abilities plugin keep working — a legacy manifest-less deploy still succeeds but answers verified: false + a warning (flipping status would make every legacy deploy report failure after succeeding; the shipped CLI hard-fails on status != "success"). The in-repo CLI computes and injects the manifest in-memory and sets the flag.
  • Symlink contract. In-root links are preserved end to end (copytree(symlinks=True) → deployed-template dir → prepop tar → workspace volume); dangling in-root links are preserved with a named warning (links to runtime-created content//data/ are legitimate); escaping/absolute targets stay refused before extraction, per member, naming path + target. extractall pinned to filter='tar' (Py3.14 flips the default).
  • Every rejection names the path and the rule, with observed + limit on every cap. Caps: MAX_FILES 1000 → 10000 (a Cornelius-class KB agent exceeds 1000 members), new MAX_EXTRACTED_SIZE 500 MB summed pre-extraction (closes the gzip-bomb hole), manifest read cap 5 MB. macOS ._* AppleDouble members are skipped with a warning; COPYFILE_DISABLE=1 documented.
  • Evidence-bearing response. DeployLocalResponse gains verified, files_expected, files_deployed, symlinks_deployed, and compatibility_hard_count (a post-create feat: Agent deployment compatibility validation — server-side checks with auto-fix offers #668 STATIC-only report, fail-open, never blocks).
  • Idempotency + concurrency. POST /api/agents/deploy-local accepts Idempotency-Key (Invariant Unified Executions Dashboard (EXEC-022) #18; scope agent_deploy:{user_id}, mirroring agent_create incl. the feat: GitHub-repo import wizard — fork / copy / clone with inline compat check (abilityai/trinity-enterprise#15) #2040-F3 staleness branch — a retried slow deploy no longer forks my-agent-2 AND -3). The MCP tool derives a deterministic key over its args. A per-base-name lock (agent:deploy_op:{base}, 409 DEPLOY_IN_PROGRESS) closes the concurrent same-version-name race — built on the shared SingleFlightLock (bug: hand-rolled Redis single-flight locks — 7 divergent copies; system_seed_service releases with an unconditional tokenless delete #1920), registered in agent_runtime_state.EXEMPT_KEYSPACES.
  • Residue + compensation (deploy-local persists an archive whose .mcp.json failed validation, and the create path consumes it #2006 class): mid-copy failures are cleaned and named (TEMPLATE_COPY_FAILED replaces the opaque shutil.Error 500); the prepopulated workspace volume is removed on failure (label + unattached double-guard); an attached pre-existing volume is a 409 WORKSPACE_VOLUME_IN_USE, never a put_archive into a mounted volume; a previous version stopped by the deploy is restarted on any failed deploy, with the compensation window closing at create_agent_fn return (one base name must never run two live versions).

Honesty note (from the plan, §0): manifest verification is accident-proof, not adversary-proof. It kills every observed silent-failure class (tooling / transit drift). A passing incomplete deploy now requires editing both the tar and the manifest commands consistently — deliberate evasion, visible in the calling transcript, out of a bug's scope. The tool argument also stays token-bound (~100–200 KB of base64 per turn), so large agents must deploy via the turn-bypassing transports that already exist (trinity CLI, curl from bash with an MCP key). Removing the payload from the turn entirely is the follow-up below.

Scope split — acceptance criteria carried by follow-ups

Two of the issue's ten ACs are deliberately not in this PR; each has its own issue so nothing is lost when #2060 closes:

AC Carried by Why cut here
AC 1 — the archive no longer rides the model turn (direct-upload staged handle) abilityai/trinity-enterprise#469 A transport arm on its own PR; the manifest contract is transport-agnostic by construction and lands first so the upload path inherits it unchanged.
AC 7 — redeploy-in-place; version-forking becomes opt-in (F5) abilityai/trinity-enterprise#470 Touches crud adopt semantics (#1667 single-adopt guard) and the .trinity-initialized startup marker; a product-shape change, not a correctness fix. The AC 9 "redeploy over a running agent with accumulated data/" regression test moves with it.

AC 3 deviation, stated: on the raw HTTP API a manifest-less deploy keeps status: "success" with verified: false (rationale above). Every MCP-tool deploy is manifest-required, so the AC holds on the surface the issue is about.

Changes

  • src/backend/services/agent_service/deploy.py — manifest parse/verify, symlink contract, caps, named errors, compensation, per-base-name SingleFlightLock
  • src/backend/routers/agents.py — Idempotency-Key on POST /api/agents/deploy-local
  • src/backend/models.py — DeployManifestEntry; DeployLocalRequest.require_manifest; evidence fields on DeployLocalResponse
  • src/backend/services/agent_runtime_state.py — agent:deploy_op: registered in EXEMPT_KEYSPACES
  • src/mcp-server/src/tools/agents.ts (+ agents.deploy.test.ts) — require_manifest set in tool code, deterministic idempotency key, rewritten description (manifest snippet, caps, macOS note, honest token ceiling → CLI)
  • src/cli/trinity_cli/commands/deploy.py — computes + injects the manifest in-memory, sets require_manifest
  • Tests: tests/unit/test_2060_deploy_integrity.py (new, 1100 lines: drift matrix, symlink matrix incl. dangling + escaping chains, caps, AppleDouble, pruned archive must fail naming the missing paths, altered-sha + extra-file drift, compensation incl. create_agent_fn raise, lock contention/release, router idempotency + staleness), tests/unit/test_2006_deploy_residue.py (updated), tests/test_deploy_local.py (integration cases added)
  • Docs: requirements §4.1.2 (new), feature-flows/local-agent-deploy.md, architecture.md rows, flows index

No DB change → no SQLite migration and no Alembic revision needed. docker/base-image/** untouched — symlink preservation is entirely backend-side (the prepop tar.add already preserves links), so no Invariant #5 obligation.

Test plan

  • pytest tests/unit — full suite green on the rebased branch (incl. test_2060_deploy_integrity.py, test_1920_no_hand_rolled_single_flight.py, test_1560_agent_redis_key_parity.py, test_models_centralized.py)
  • npm test in src/mcp-server — 285/285 incl. agents.deploy.test.ts; tsc --noEmit clean
  • /verify-local (real images, isolated stack, real agent) — pass; tests/integration 70 passed / 13 skipped / 2 deselected; tests/test_deploy_local.py 19/19 against the kept stack (details in the verification comment below)
  • Manual: deploy an agent with a symlinked .claude/skills/x -> ../shared/x via the in-repo CLI → verified: true, link present in the workspace; re-run the tar with an extra --exclude → 400 MANIFEST_DRIFT naming the missing paths

Follow-ups filed

Fixes #2060

🤖 Generated with Claude Code

https://claude.ai/code/session_01GJdf1sDRofuPxKf8cmwRh1

trinity-ability and others added 7 commits September 2, 2026 10:12
Rule #1 (requirements before implementation): the embedded-manifest
integrity contract, layered requiredness, the accident-proof-not-
adversary-proof honesty note (token-bound tool argument; CLI escape),
the symlink decision matrix, the security-vs-drift layering rule, caps,
idempotency scope + per-base-name deploy lock, evidence response fields,
and the residue/compensation guarantees.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ct, caps + compensation (#2060)

deploy_local_agent silently deployed incomplete agents: the archive rides
the calling model's own turn and nothing compared what landed against what
was on disk — a pruned-but-well-formed archive deployed status:"success".

- Embedded .trinity-manifest.json (computed from the disk tree, shipped
  inside the archive) verified POST-EXTRACT (before any side effect;
  extras are drift) AND POST-COPY (before the .env credentials merge).
  Fail-closed 400 MANIFEST_DRIFT naming missing/altered/extra/
  link-mismatched paths (capped lists + counts); recovery text directs at
  rebuild-without-excludes / the CLI, never at pruning the manifest.
  MANIFEST_REQUIRED (flag set, no manifest — carries the generation
  snippet) and MANIFEST_INVALID (5 MB read cap, entry bounds, dup/
  traversal/self-listing) complete the taxonomy.
- Symlink contract: copytree(symlinks=True) preserves in-root links end to
  end (previously silently dereferenced); dangling in-root links preserved
  with a named warning (previously an opaque shutil.Error 500 + partial-dir
  residue); escape refusals unchanged and regression-pinned;
  extractall(filter='tar') pinned ahead of the Py3.14 default flip.
- Caps: MAX_FILES 1000→10000; new MAX_EXTRACTED_SIZE 500 MB from member
  headers pre-extraction (gzip-bomb hole); observed+limit on every cap
  rejection; macOS AppleDouble ._* members skipped with a warning.
- Evidence-bearing response: verified / files_expected / files_deployed /
  symlinks_deployed + fail-open #668 STATIC compatibility_hard_count
  (unavailable → None + warning, never 0, never a failed deploy).
- Idempotency-Key on POST /api/agents/deploy-local (scope
  agent_deploy:{user_id}, mirrors agent_create incl. the #2040-F3
  staleness branch; in-flight → 409 DEPLOY_IN_FLIGHT) — an un-keyed
  transport retry forked twice (my-agent-2 AND my-agent-3). Per-base-name
  agent:deploy_op: SETNX lock (fail-open, 409 DEPLOY_IN_PROGRESS),
  registered in agent_runtime_state.EXEMPT_KEYSPACES.
- Residue + compensation (#2006 class): dest_created assigned BEFORE the
  rmtree/copytree pair so a mid-copy failure is cleaned (named 500
  TEMPLATE_COPY_FAILED); failed deploys reclaim the prepopulated workspace
  volume (label + unattached double-guard, #1581 shape) and restart the
  previous version they stopped (incl. create_agent_fn raise); stale
  prepop volume: unattached → remove-and-recreate (put_archive overlays,
  never prunes), attached/unknowable → 409 WORKSPACE_VOLUME_IN_USE;
  catch-all 500 gains code DEPLOY_FAILED.

Security layering preserved: containment/link/member-type validation stays
strictly PRE-extraction in _validate_tar_member; only manifest drift
verification runs post-extract.

TDD: tests/unit/test_2060_deploy_integrity.py written RED-first against
the pre-fix base (44 of 49 failed; the 5 passers are deliberate regression
/ static pins). Live-stack e2e classes appended to tests/test_deploy_local.py
for the FULL verify stage.

Co-Authored-By: Claude Fable 5 <[email protected]>
… the #2060 contract

MCP tool (Invariant #13): description rewritten with the embedded-manifest
generation snippet (same excludes as the tar command, writes
.trinity-manifest.json INTO the agent dir), the COPYFILE_DISABLE=1 macOS
note, the caps, and the HONEST token-bound payload ceiling directing large
agents at the trinity CLI / curl from bash. execute() sets
require_manifest: true in tool CODE (not a model-controlled parameter) and
derives a deterministic Idempotency-Key over
[userId, tool, name, archive] via deriveMcpIdempotencyKey + extraHeaders —
same-args-only by design (a rebuilt tar is deliberately a new deploy).
Response interface carries the new evidence fields. New
agents.deploy.test.ts pins body/require_manifest, key determinism, and the
description contract (5 tests; suite 201 pass, tsc clean).

CLI (fourth consumer): computes the manifest during its existing archive
walk (git ls-files + walk modes; symlinks stored as link entries with
link_target, files with sha256), injects it into the tar IN-MEMORY (never
mutates the user's source dir), sends require_manifest: true, and prints
the verified/counts evidence + compatibility hard-finding count +
warnings.

Co-Authored-By: Claude Fable 5 <[email protected]>
- local-agent-deploy.md: manifest workflow (Step 0 snippet consistent with
  the tar excludes beside it), post-extract/post-copy verification steps,
  deploy lock, dest_created-before-copy, stale-volume hygiene, compat
  gate, compensation, refreshed error-code/size-limit tables, security
  layering + honesty notes, refreshed stale line refs (agents.ts block
  moved 556-643 → 744+).
- feature-flows.md: dated #2060 row + index one-liner.
- architecture.md: POST /api/agents/deploy-local added to the Agents
  endpoint table (pre-existing gap) with the integrity-contract summary;
  agents.ts MCP tools row touched.

Co-Authored-By: Claude Fable 5 <[email protected]>
…eturn, name the NUL-path refusal, strict require_manifest read, shared lock-release predicate (#2060)

Four review findings fixed in place:

1. Compensation over-restart: once create_agent_fn RETURNS, the new version
   is live — a failure past that point (realistically only response
   construction; the compat gate is fully fail-open) must not restart the
   previous version alongside it, or one base name runs two live versions
   (the F5 double-run hazard: both fire schedules). previous_stopped_name is
   now cleared at create-return; the restart-on-create-raise path is
   unchanged. Pinned by
   test_late_failure_after_create_does_not_restart_previous.

2. NUL byte in a manifest path escaped the named 400: os.path.lexists raises
   ValueError("embedded null byte") during verification, landing as the
   catch-all 500 DEPLOY_FAILED instead of MANIFEST_INVALID. Refused at parse
   with every other bad shape; new nul-byte parametrize case.

3. require_manifest read strictly (body.require_manifest) instead of
   getattr-with-default: DeployLocalRequest owns the field (default False)
   and the router is the only production caller — a duck-typed body missing
   it should fail loudly, not silently un-require verification. The two test
   harness body stubs now model the field.

4. Deploy-lock release uses the shared redis_breaker_util.lock_token_matches
   predicate (#1919: one ownership comparison for hand-rolled single-flight
   locks; carries the bytes belt if client decoding config ever drifts).

Co-Authored-By: Claude Fable 5 <[email protected]>
…1.2 + flow with the review fix (#2060)

Co-Authored-By: Claude Fable 5 <[email protected]>
…name deploy lock (#2060)

The branch forked before #1920 consolidated the SETNX single-flight idiom
onto `redis_breaker_util.SingleFlightLock`, so its hand-rolled
`set(nx=True, ex=...)` + GET-then-DELETE release now trips
`tests/unit/test_1920_no_hand_rolled_single_flight.py`. Adopt the primitive
instead of allowlisting: same key (`agent:deploy_op:{base_name}`), same TTL,
same fail-open on Redis down, same 409 `DEPLOY_IN_PROGRESS` on contention —
but the token/compare-and-delete logic now lives in one place. The
`_deploy_lock_client` seam is kept as the site binding the primitive's
injected-client contract asks for (and the unit tests monkeypatch).

Docs: requirements §4.1.2, the feature flow (6c + changelog dated to the
landing), and architecture.md's SingleFlightLock consumer/site lists name
the adoption.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01GJdf1sDRofuPxKf8cmwRh1
@trinity-ability

Copy link
Copy Markdown
Contributor Author

Local verification (Docker on)

Ran /verify-local on this branch (worktree trinity-ability/issue-2060, rebased on dev @ c348cf97) — real prod images built and booted on an isolated stack, real agent exercised, then the integration suite, then tests/test_deploy_local.py against the kept stack.

Stage Result
build + import main in the built backend image OK
agent base-image build + import agent_server OK
boot + /health OK
agent-exercise (real local:test-echo agent reaches /health) OK
integration (tests/integration, 2 known-false-fails deselected) 70 passed, 13 skipped, 2 deselected
tests/test_deploy_local.py vs the kept stack 19 passed — incl. TestDeployLocalIntegrity2060::test_symlinked_agent_deploys_verified_and_boots (symlinked agent deploys verified: true and reaches /health)
pytest tests/unit (full, run separately) 13,497 passed; 2 order-dependent test_1081_physical_meter flips pass in isolation and on dev

Two things surfaced that are not this branch:

  • test: test_2467_turn_integrity fleet-list case is a time bomb — hardcoded started_at aged out of get_fleet_executions' default 24h window #2486 — test_2467_turn_integrity::test_fleet_list_returns_turn_integrity is a time bomb (hardcoded started_at aged out of get_fleet_executions' default 24 h window at 2026-09-02T10:00Z); it reds pytest tests/unit on pristine dev too, so the verify unit stage was run separately and the in-harness unit stage skipped.
  • verify-local harness: on Docker Desktop 27.3.1 a docker network connect/disconnect on the running backend drops its ephemeral host-port forward, so the global-mode agent stage could not reach the backend it had just booted. Patched the skill script to re-publish (restart + re-resolve) after both operations; fix is in the .claude submodule, not this PR.

No DB change, no Alembic revision, docker/base-image/** untouched.

…odeQL proves (#2060)

CodeQL raised 10 py/path-injection alerts on the PR, every flow request
body → base_name → version_name → dest_path → {copytree, the post-copy
manifest walk: lexists/is_symlink/readlink/is_file/sha256}. The #950 guard
already normalizes dest_path and refuses an escape, but its condition
(`!= base and not startswith(...)`) leaves the fall-through branch unproven,
so the sanitizer never applied and the new post-copy sinks surfaced it.
Rewrite it in the `not startswith(...) or == base` form that
`_remove_partial_deploy` uses and documents as the recognized barrier —
identical accept/reject set, no behavior change; the pre-existing guard
simply becomes visible to the analysis that the new manifest walk exposed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01GJdf1sDRofuPxKf8cmwRh1
@trinity-ability

Copy link
Copy Markdown
Contributor Author

CodeQL: the 10 py/path-injection alerts all flowed request body → base_name → version_name → dest_path and were caught by the pre-existing #950 containment guard, whose condition shape (!= base and not startswith) the analyzer does not recognise as a barrier. b3507931 rewrites it in the not startswith or == base form _remove_partial_deploy already uses (identical accept/reject set, no behaviour change). Re-analysis: 0 open alerts.

@obasilakis obasilakis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/validate-pr: APPROVE

The integrity contract is correctly layered — security checks pre-extraction, drift checks post-extract and post-copy — and fail-closed on every rejection path. All 27 checks pass; security greps clean (the only hit is the trinity_mcp_x test fixture in agents.deploy.test.ts). Docs complete: requirements §4.1.2, three architecture rows, flow doc, flows index, EXEMPT_KEYSPACES registration.

I traced the three properties that carry the whole PR:

  • Fail-closed — drift raises 400 MANIFEST_DRIFT before any side effect (deploy.py step 4a, pinned by test_drift_refused_before_any_side_effect and test_post_extract_verification_precedes_version_side_effects); parse defects give 400 MANIFEST_INVALID; unknowable volume attachment refuses with 409 (_attached_volume_names_sync returns None → refuse, test_prepop_unknown_attachment_fails_closed). The only deliberate fail-opens are _compatibility_hard_count (evidence gathering, where None ≠ 0) and the extras walk, noted below.
  • Lock release — finally: _release_deploy_lock(deploy_lock) in deploy_local_agent_logic; release_if_owned() never raises; 600 s TTL backstop; deploy_lock stays None when acquire raises 409, so a contender can't release a foreign lock. Fail-open confirmed at redis_breaker_util.py:57-65.
  • "Verified twice" is genuinely two checks, not one repeated — post-extract over the temp tree with check_extras=True, post-copy over /data/deployed-templates/<version> with check_extras=False, and the second is ordered before the .env credentials merge (test_post_copy_verification_precedes_credentials_merge). Different subjects, same manifest; the second catches copytree/symlink-dereference drift the first structurally cannot see.

Warnings

  • Scope vs. auto-close — the one item needing a human decision. Fixes #2060 will close a P1 bug whose own title clause "archive rides the LLM turn" (AC 1) is deferred to abilityai/trinity-enterprise#469, with AC 7 deferred to #470. The follow-ups exist but live in the private tracker, invisible from the public issue. Either accept the split deliberately, or drop the closing keyword and close #2060 by hand once the remainder lands.
  • AC 3 deviation (disclosed). Raw HTTP require_manifest defaults False, so a manifest-less deploy still answers status: "success" with verified: false. The reasoning holds (the shipped PyPI CLI hard-fails on non-success, and the MCP tool sets the flag in tool code), but the abilities-plugin deploy path stays unverified until an external-repo follow-up lands.
  • No test asserts the deploy lock is released when the deploy fails. TestCompensation exercises failure paths but never checks fake.deleted; release on success is asserted at test_2060_deploy_integrity.py:928. Structurally safe via finally — just untested, and Redis-down (fail-open) is likewise uncovered.

Suggestions

  • deploy.py::_walk_tree_entries uses a bare os.walk (default onerror=None), so an unreadable subdirectory silently yields no extra findings for that subtree. That's the only fail-open left in verification; onerror=raise closes it (missing and altered files are already fail-closed via direct stat).
  • tar.getmembers() runs before the new MAX_EXTRACTED_SIZE header-sum check, so enumerating a gzip bomb still decompresses-and-discards the full stream. CPU and time burn only — no disk write, so bounded.
  • While local-agent-deploy.md is already being edited, it could adopt the canonical ## Side Effects / ## Related Flows headings (it currently has the domain-equivalent ## Error Codes / ## Related Documentation).

Findings produced by /validate-pr (Claude Code).

@vybe
vybe merged commit 7907286 into dev Sep 3, 2026
27 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.

4 participants