Repository navigation
fix(deploy): deploy-local integrity contract — embedded manifest verified twice, symlinks preserved, named errors, idempotent + locked (#2060) - #2485
Conversation
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
Local verification (Docker on)Ran
Two things surfaced that are not this branch:
No DB change, no Alembic revision, |
…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
|
CodeQL: the 10 |
obasilakis
left a comment
There was a problem hiding this comment.
/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_DRIFTbefore any side effect (deploy.pystep 4a, pinned bytest_drift_refused_before_any_side_effectandtest_post_extract_verification_precedes_version_side_effects); parse defects give 400MANIFEST_INVALID; unknowable volume attachment refuses with 409 (_attached_volume_names_syncreturnsNone→ refuse,test_prepop_unknown_attachment_fails_closed). The only deliberate fail-opens are_compatibility_hard_count(evidence gathering, whereNone≠ 0) and the extras walk, noted below. - Lock release —
finally: _release_deploy_lock(deploy_lock)indeploy_local_agent_logic;release_if_owned()never raises; 600 s TTL backstop;deploy_lockstaysNonewhen acquire raises 409, so a contender can't release a foreign lock. Fail-open confirmed atredis_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>withcheck_extras=False, and the second is ordered before the.envcredentials 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 #2060will close a P1 bug whose own title clause "archive rides the LLM turn" (AC 1) is deferred toabilityai/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_manifestdefaultsFalse, so a manifest-less deploy still answersstatus: "success"withverified: 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.
TestCompensationexercises failure paths but never checksfake.deleted; release on success is asserted attest_2060_deploy_integrity.py:928. Structurally safe viafinally— just untested, and Redis-down (fail-open) is likewise uncovered.
Suggestions
deploy.py::_walk_tree_entriesuses a bareos.walk(defaultonerror=None), so an unreadable subdirectory silently yields noextrafindings for that subtree. That's the only fail-open left in verification;onerror=raisecloses it (missing and altered files are already fail-closed via direct stat).tar.getmembers()runs before the newMAX_EXTRACTED_SIZEheader-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.mdis already being edited, it could adopt the canonical## Side Effects/## Related Flowsheadings (it currently has the domain-equivalent## Error Codes/## Related Documentation).
Findings produced by /validate-pr (Claude Code).
Summary
deploy_local_agent(the archive path) could deploy an agent that was not the agent on disk and still answerstatus: "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:.trinity-manifest.jsonfrom 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 400MANIFEST_DRIFTnamingmissing/altered/extra/link_mismatchpaths. 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.execute()setsrequire_manifest: truein tool code (not a model-controlled parameter) → no manifest = 400MANIFEST_REQUIREDcarrying the generation snippet. The raw HTTP API defaults tofalseso the shipped PyPI CLI and the abilities plugin keep working — a legacy manifest-less deploy still succeeds but answersverified: false+ a warning (flippingstatuswould make every legacy deploy report failure after succeeding; the shipped CLI hard-fails onstatus != "success"). The in-repo CLI computes and injects the manifest in-memory and sets the flag.copytree(symlinks=True)→ deployed-template dir → prepop tar → workspace volume); dangling in-root links are preserved with a named warning (links to runtime-createdcontent//data/are legitimate); escaping/absolute targets stay refused before extraction, per member, naming path + target.extractallpinned tofilter='tar'(Py3.14 flips the default).observed+limiton every cap. Caps:MAX_FILES1000 → 10000 (a Cornelius-class KB agent exceeds 1000 members), newMAX_EXTRACTED_SIZE500 MB summed pre-extraction (closes the gzip-bomb hole), manifest read cap 5 MB. macOS._*AppleDouble members are skipped with a warning;COPYFILE_DISABLE=1documented.DeployLocalResponsegainsverified,files_expected,files_deployed,symlinks_deployed, andcompatibility_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).POST /api/agents/deploy-localacceptsIdempotency-Key(Invariant Unified Executions Dashboard (EXEC-022) #18; scopeagent_deploy:{user_id}, mirroringagent_createincl. 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 forksmy-agent-2AND-3). The MCP tool derives a deterministic key over its args. A per-base-name lock (agent:deploy_op:{base}, 409DEPLOY_IN_PROGRESS) closes the concurrent same-version-name race — built on the sharedSingleFlightLock(bug: hand-rolled Redis single-flight locks — 7 divergent copies; system_seed_service releases with an unconditional tokenless delete #1920), registered inagent_runtime_state.EXEMPT_KEYSPACES..mcp.jsonfailed validation, and the create path consumes it #2006 class): mid-copy failures are cleaned and named (TEMPLATE_COPY_FAILEDreplaces the opaqueshutil.Error500); the prepopulated workspace volume is removed on failure (label + unattached double-guard); an attached pre-existing volume is a 409WORKSPACE_VOLUME_IN_USE, never aput_archiveinto a mounted volume; a previous version stopped by the deploy is restarted on any failed deploy, with the compensation window closing atcreate_agent_fnreturn (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 (
trinityCLI,curlfrom 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:
.trinity-initializedstartup marker; a product-shape change, not a correctness fix. The AC 9 "redeploy over a running agent with accumulateddata/" regression test moves with it.AC 3 deviation, stated: on the raw HTTP API a manifest-less deploy keeps
status: "success"withverified: 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-nameSingleFlightLocksrc/backend/routers/agents.py—Idempotency-KeyonPOST /api/agents/deploy-localsrc/backend/models.py—DeployManifestEntry;DeployLocalRequest.require_manifest; evidence fields onDeployLocalResponsesrc/backend/services/agent_runtime_state.py—agent:deploy_op:registered inEXEMPT_KEYSPACESsrc/mcp-server/src/tools/agents.ts(+agents.deploy.test.ts) —require_manifestset 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, setsrequire_manifesttests/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_fnraise, lock contention/release, router idempotency + staleness),tests/unit/test_2006_deploy_residue.py(updated),tests/test_deploy_local.py(integration cases added)feature-flows/local-agent-deploy.md,architecture.mdrows, flows indexNo DB change → no SQLite migration and no Alembic revision needed.
docker/base-image/**untouched — symlink preservation is entirely backend-side (the prepoptar.addalready 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 testinsrc/mcp-server— 285/285 incl.agents.deploy.test.ts;tsc --noEmitclean/verify-local(real images, isolated stack, real agent) — pass;tests/integration70 passed / 13 skipped / 2 deselected;tests/test_deploy_local.py19/19 against the kept stack (details in the verification comment below).claude/skills/x -> ../shared/xvia the in-repo CLI →verified: true, link present in the workspace; re-run the tar with an extra--exclude→ 400MANIFEST_DRIFTnaming the missing pathsFollow-ups filed
import_agent_data(Agent runtime data volumes: declared data paths with snapshot/restore and portable export #1169)trinityplugin's deploy skill must adopt the manifest snippet +COPYFILE_DISABLE=1note (external repo, not in this PR).envvalue quoting at the deploy merge is bug(credentials): .env quote-escaping is write-only — a credential containing a double quote round-trips corrupted #2023's family (PR fix(credentials): make the .env quote encoding reversible (#2023) #2030) — deliberately not touchedFixes #2060
🤖 Generated with Claude Code
https://claude.ai/code/session_01GJdf1sDRofuPxKf8cmwRh1