Skip to content

feat: GitHub-repo import wizard — fork / copy / clone with inline compat check (abilityai/trinity-enterprise#15) - #2040

Merged
vybe merged 3 commits into
devfrom
feature/ent15-github-import-wizard
Aug 7, 2026
Merged

vybe merged 3 commits into
devfrom
feature/ent15-github-import-wizard

Conversation

@trinity-ability

Copy link
Copy Markdown
Contributor

Summary

  • import_intent: fork | copy | clone on agent creation (POST /api/agents, MCP create_agent with copy|clone only, UI intent picker on the free-form GitHub path). Absent intent → legacy behavior exactly.
  • Copy = backend-materialized snapshot: staging clone via the fork-to-own git machinery (/data staging, PAT via GIT_CONFIG_* never argv, @branch honored, empty repo → 400 COPY_SOURCE_EMPTY, tree-escaping symlinks pruned) → strip .git → workspace-volume pre-population via the deploy-local primitive before the container exists. The container carries no GitHub env and no PAT, no agent_git_config row (both rebuild seams pop git env by construction; never sync-polled), zero base-image dependency.
  • Inline feat: Agent deployment compatibility validation — server-side checks with auto-fix offers #668 compatibility check as the modal's post-create step — readiness-gated on a real agent-server /info response (the proxy fail-opens to 200 + fallback body mid-clone; gated by body shape) with honest failed-to-start/timeout branches. Non-blocking.
  • Idempotency (Invariant Unified Executions Dashboard (EXEC-022) #18): Idempotency-Key on create, scope agent_create:{user_id} (two-principal isolation tested), named in-flight 409 CREATE_IN_FLIGHT; MCP derives a deterministic name-keyed header.
  • Provenance: AgentStatus.import_snapshot (repo/branch/SHA/file-count) → create audit details + trinity.import-intent label.
  • Fork scope failures (FORK_PAT_INVALID, FORK_REPO_CREATE_FAILED) name the copy/clone alternatives (issue AC "degrade …and say so" — implemented as a named suggestion, never silent auto-degrade).

Review notes

Pre-landing /review findings all resolved: readiness-gate fail-open fixed (body-shape discriminator; old images degrade to the honest timeout state), copy+ephemeral refused by name (COPY_EPHEMERAL_UNSUPPORTED — ghosts are volume-less, ent#69), stranded-volume retry-409 fixed (rollback handle armed before pre-population). Accepted residual: a seconds-wide same-name concurrent-create interleaving (pre-existing check-then-act creation class) is documented in the feature flow, not locked — a per-name creation lock is the future fix if it ever bites.

Changes

Backend: snapshot_import.py (new), crud.py (intent gates + copy branch + rollback), models.py, routers/agents.py (idempotency + audit), fork_to_own.py (messages). MCP: agents.ts, client.ts, chat.ts (export), types.ts, import-intent.test.ts (new). Frontend: CreateAgentModal.vue, ImportIntentPicker.vue (new), ImportValidationStep.vue (new). Docs: requirements §11.13, feature-flows/github-import-intents.md (new) + index, architecture row, learnings entry. Tests: tests/unit/test_ent15_import_intents.py (23 cases) + registry.

Test Plan

  • pytest unit/test_ent15_import_intents.py — 23/23
  • Adjacent creation-path suites (test_1484_create_agent_characterization, test_ent313_*, test_fork_to_own, test_ent123_tokenless_clone) — 173/173
  • MCP npm test 173/173 + tsc --noEmit clean
  • Frontend npm run build + check:tokens pass; raw-color ratchet flat (CreateAgentModal byte-equal to baseline; new components zero non-gray/hardcoded)
  • Manual: create from a public repo with each intent; verify copy agent has no GITHUB_REPO env and boots with files; wizard compat step on a real clone

Related to abilityai/trinity-enterprise#15 (private-tracker feature — closed manually at release; closing keywords do not cross repos)

🤖 Generated with Claude Code

… with inline compatibility check (Abilityai/trinity-enterprise#15)

- import_intent on POST /api/agents + MCP create_agent (copy|clone) + UI intent
  picker on the free-form GitHub path; absent intent = legacy behavior exactly
- copy = backend-materialized snapshot: staging clone (fork_to_own git machinery,
  @Branch honored, empty repo refused, tree-escaping symlinks pruned) → strip
  .git → workspace-volume pre-population via the deploy-local primitive; the
  container carries no GitHub env and no PAT, no agent_git_config row, zero
  base-image dependency; provenance (repo+SHA) in response, audit, and label
- inline #668 compatibility check as the modal's post-create step, readiness-
  gated on a REAL agent-server /info response (fail-open-200 discriminated by
  body shape) with honest failed-to-start/timeout branches
- Idempotency-Key on create (scope agent_create:{user_id}, two-principal
  isolation, named in-flight 409); MCP derives a deterministic name-keyed key
- named 400s for every refusal incl. COPY_EPHEMERAL_UNSUPPORTED (ghosts are
  volume-less); fork scope failures name the copy/clone alternatives

Co-Authored-By: Claude Fable 5 <[email protected]>

@vybe vybe 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.

The design is careful and the seam analysis is genuinely good — the git-env story (the _apply_git_env_from_db no-row branch), the #1667 gate ordering, and the rollback-after-container-reclaim ordering all check out against the real code. The security review came back clean on the things I most expected to find problems in: the PAT goes through GIT_CONFIG_* / http.extraHeader and never argv, failure output is scrub_secret-ed, and it never reaches container env, agent_git_config, or the response; the URL is a hardcoded https://github.com/ host with repo_path already validated against ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$, so no scheme override, userinfo, traversal, or leading-- argv injection; _prune_escaping_symlinks correctly walks with followlinks=False, resolves non-strictly so dangling links are caught, and tarfile.add archives symlinks as SYMTYPE rather than following them.

What's missing is a resource bound on a path that streams attacker-chosen bytes onto the platform's primary data volume and through backend RAM.

1. Unbounded clone into /data.

snapshot_import.py stages into /data/agent-import-tmp with git clone --depth 1 --single-branch bounded only by CLONE_TIMEOUT_S = 120. /data is the bind mount that also holds trinity.db and agent-files/. Any creator-role caller can point copy at an arbitrarily large public repo, and 120 seconds of clone bandwidth is multiple GB on a decent link. There is no rate limit on POST /api/agents. Filling /data takes SQLite down.

Compare #1595, where git maintenance carries an explicit free-disk preflight (skip below 1.1× pack bytes) for exactly this reason. Needs a size cap enforced during or after clone, a free-space preflight, or both — with a named 4xx rather than a disk-full 500.

2. The whole snapshot is materialized in backend memory as one tar.

deploy._prepopulate_workspace_from_template builds a BytesIO, tar.adds the tree, then reads the entire buffer before put_archive. That primitive was written for #950 deploy-local, whose input is an operator-supplied template of bounded size. This PR repoints it at arbitrary user-specified GitHub content with no size validation in between, so a large repo OOMs the backend process — which also serves every other agent. snapshot_import computes file_count but never total bytes, so nothing observes the magnitude before the tar is built.

3. The MCP auto-derived idempotency key makes delete-then-recreate a phantom success.

tools/agents.ts derives a key over [userId, "create_agent", args.name, JSON.stringify(config)] — deterministic over name + config, 24h TTL. Delete an agent and re-create it identically via MCP inside 24h and idempotency_service.begin returns the stored completed snapshot: the caller gets a 200 with the old AgentStatus and X-Idempotent-Replay: true, and no agent exists.

The router docstring explicitly argues "Header-only — no auto-derived key"; the MCP surface then does exactly what that sentence rules out. Agent Self-Reminders hit this and solved it ("terminal stored rows excluded from replay"). Either drop the MCP auto-derivation or exclude replays whose recorded agent no longer exists.

4. The core happy path was never executed.

The Test Plan's Manual: create from a public repo with each intent; verify copy agent has no GITHUB_REPO env and boots with files is unchecked, and every backend test mocks _run_git — nothing clones a real repo, pre-populates a real volume, or boots a container. The feature's central safety claim, that a copy agent carries no GitHub env and no agent_git_config row across both rebuild seams, is asserted in prose and in the feature flow and verified nowhere. For a feature PR under the project's verification rule, that's the hold.

Non-blocking:

  • _prepopulate_workspace_from_template is called without adopt_existing_workspace, so the volume mount takes its "declared adopt" branch and logs an adopt attributed to deploy-local #950. Functionally correct — I confirmed the #1667 refusal gate runs before the volume exists — but the log now misattributes the caller.
  • The 24h staging-dir sweeper is the wrong lever while finding 1 is unfixed.
  • /data/agent-import-tmp isn't added to the architecture "Data Persistence" section, which enumerates /data contents.
  • jsonable_encoder, JSONResponse and idempotency_service are imported inside the endpoint; every other router imports at module level.
  • Test gaps per new surface: nothing for _cleanup_copy_artifacts (the F4 ordering fix ships with zero regression coverage), the trinity.import-intent label, the import_snapshot audit fold, or idempotency_service.fail() releasing the claim so a corrected retry proceeds.
  • Invariant #1: snapshot_import raises HTTPException directly rather than a domain error mapped at the router, unlike the ent#109 BindError precedent the same file cites as its model. Minor, not worth blocking on.

Docs are the best-documented part of this PR — architecture row, feature flow + index, requirements, learnings entry.

Entitlement ruling needed. This lands fully ungated — zero requires_entitlement / enterprise_features references anywhere in the diff — and ent#15 is an enterprise-tracker feature under epic ent#122. Per CLAUDE.md the default is a gated module unless explicitly ruled OSS-core, and "reuses OSS tables and endpoints" is expressly not a reason to infer OSS. This is a full user-facing wizard, so the question is bigger here than on a single read endpoint. Needs @vybe's explicit call before merge.

Also needs a rebase (learnings.md only).

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

trinity-ability and others added 2 commits August 7, 2026 10:38
…mport-wizard

# Conflicts:
#	docs/memory/feature-flows.md
#	docs/memory/learnings.md
…ness-gate idempotent replays (ent#15)

Review items from vybe on PR #2040:

1. The snapshot clone is resource-bounded (F1): a free-space preflight
   refuses to start without 3x-cap headroom (structured 507
   COPY_STAGING_NO_SPACE — never a disk-full 500), and a post-clone size
   cap (AGENT_IMPORT_MAX_BYTES, default 1 GiB, lstat so symlinks never
   count their target) answers a named 400 COPY_SOURCE_TOO_LARGE. /data
   also holds trinity.db; 120s of clone bandwidth is multiple GB.

2. _prepopulate_workspace_from_template spools the tar to a disk-backed
   temp file beside the template tree instead of one in-memory BytesIO
   (F2) — the primitive was written for operator-bounded deploy-local
   input and the import points it at user-specified GitHub content; a
   large repo could OOM the backend process. requests streams the file
   object, so put_archive never holds the full tar either.

3. Completed idempotent replays are liveness-gated (F3): the endpoint
   re-checks db.is_agent_live(recorded_name) before replaying. MCP's
   deterministic key made delete-then-identical-recreate inside 24h
   replay a 200 naming an agent that no longer exists, creating nothing.
   A dead recorded agent discards the stored row (new
   db.idempotency_discard_completed — deletes ONLY completed rows) and
   falls through to a genuinely fresh create, which answers honestly
   (name-reserved 409 for soft-deleted, real create for hard-purged).
   Losing the re-claim race yields 409 CREATE_IN_FLIGHT.

Also from the review (non-blocking):
- jsonable_encoder/JSONResponse/idempotency_service hoisted to module
  level in routers/agents.py.
- /data/agent-import-tmp added to the architecture Data Persistence list.
- Regression tests for _cleanup_copy_artifacts (staging + volume removal,
  missing-volume tolerance).

Tests: 8 new (size cap incl. cleanup, preflight-before-clone, lstat
measurement, replay-liveness x3, cleanup x2); suite 31 passed.

The F4 happy path was executed against a live stack (see PR comment):
copy-intent create from github:Abilityai/cornelius verified end-to-end —
import_snapshot provenance, zero GITHUB_*/GIT_SYNC_* container env, no
agent_git_config row, boots running with the full tree +
.trinity-initialized and no .git; delete-then-recreate with the same
Idempotency-Key answers an honest 409 instead of a phantom replay.

Co-Authored-By: Claude Fable 5 <[email protected]>
@vybe

vybe commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

All four blocking findings addressed in a3e8fb2f (+ dev merged in 90908b59), and — the F4 hold — the happy path has now been executed against a live stack, end to end.

Entitlement ruling

Eugene's call: OSS-core, ungated. The import wizard ships in the public bundle with no requires_entitlement / enterprise_features gate.

1. Clone bounded (F1)

2. Tar spooled to disk (F2)

_prepopulate_workspace_from_template now writes the tar to a TemporaryFile beside the template tree (disk-backed /data in both callers — never inside template_dir, never the RAM-tmpfs default tmp) and hands the file object to put_archive; requests streams it, so neither the build nor the upload holds the full tar in memory. Comment explains why (this primitive's original input was operator-bounded #950).

3. Replay liveness-gated (F3)

Kept the MCP derivation (it's the transport-retry protection) and fixed the server side, per your "exclude replays whose recorded agent no longer exists": the endpoint re-checks db.is_agent_live(recorded_name) before replaying. Dead → discard via the new db.idempotency_discard_completed (deletes only completed rows — release still can't touch them) and fall through to a genuinely fresh create, which answers honestly: name-reserved 409 for a soft-deleted agent, a real create for a hard-purged one. Re-claim race → 409 CREATE_IN_FLIGHT. Router docstring updated; the Self-Reminders precedent shape.

4. Happy path EXECUTED (live local stack, backend hot-swapped to this branch)

Copy intent — POST /api/agents {"name":"e2e-copy-test","template":"github:Abilityai/cornelius","import_intent":"copy"}:

"import_snapshot": {"source_repo": "Abilityai/cornelius", "source_branch": "main",
                    "head_sha": "14927a86290ae023b609d69df39b9d5c65f02d38", "file_count": 1232}
  • container env: grep -cE "GITHUB|GIT_SYNC" → 0
  • trinity.import-intent=copy label present
  • db.get_git_config('e2e-copy-test') → None
  • started → status: running, /home/developer holds the full tree (15 top-level entries), .trinity-initialized present, no .git

F3 live proof — create with Idempotency-Key: k-live-2040 → 200; immediate retry → x-idempotent-replay: true; DELETE the agent; re-POST the same key → HTTP 409 "Agent already exists", no replay header — pre-fix this was a 200 replay naming a deleted agent.

Fixtures cleaned up afterward; stack restored to dev.

Non-blocking items taken

  • jsonable_encoder/JSONResponse/idempotency_service hoisted to module level.
  • /data/agent-import-tmp added to architecture.md § Data Persistence.
  • _cleanup_copy_artifacts regression tests (staging+volume removal, missing-volume tolerance).
  • Feature flow documents the bounds + the replay gate.

Left as-is, per your "minor": the Invariant #1 HTTPException-in-service shape, and the adopt-log misattribution. The 24h sweeper stays (now as the backstop behind real bounds, which was your framing).

Tests: test_ent15_import_intents.py → 31 passed (8 new). Rebase done (learnings.md + feature-flows.md kept both sides).

@vybe vybe 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 passed — approving to supersede my earlier CHANGES_REQUESTED (all four blocking findings addressed in a3e8fb2, live happy-path executed, hold lifted per review thread).

Validation summary:

  • Security: no keys/emails/IPs/secrets/credential files in the diff ✅
  • Docs: requirements/github.md §11.13 + architecture.md + new feature flow + index + learnings ✅
  • Packaging: no new top-level backend modules; snapshot_import.py rides the services/ wholesale COPY ✅
  • Tests: 31 unit cases incl. non-happy paths (preflight refusal w/ zero git calls, size cap via lstat, replay liveness, two-principal idempotency isolation) + MCP import-intent.test.ts, registry updated ✅
  • Cross-tracker ref (Related to abilityai/trinity-enterprise#15) is the expected shape — manual status-in-dev bump + manual close at release.

⚠️ Non-blocking follow-up: AGENT_IMPORT_MAX_BYTES is read via env but not wired into either compose file / .env.example — same (pre-existing) gap as its sibling AGENT_DATA_EXPORT_MAX_BYTES. Default (1 GiB) is active regardless, so the bound holds on deploy; the override knob is inert until wired. Suggest one follow-up wiring both.

@vybe
vybe merged commit ff7b3f2 into dev Aug 7, 2026
25 checks passed
AndriiPasternak31 added a commit that referenced this pull request Aug 9, 2026
Rebasing onto dev picked up two changes that landed under this branch and
moved what its own tests assert. Both are the other change being right.

- ent#15 (#2040) inserted an import-intent gate into `_resolve_template`
  ahead of the fork gate. Two `SimpleNamespace` config doubles predate the
  field, so `config.import_intent` raised AttributeError before reaching the
  assertion — a stub gap, not a production one. The fork/clone path and the
  S2 fail-closed gate are unchanged, and dev's `copy` intent carries its own
  `fork_to_own: required` refusal before its early return.

- #1890 made `require_admin` itself reject agent-scoped principals, closing
  the class at the gate rather than per-endpoint. This suite asserted an
  agent key could still READ the registry setting, on the reasoning that the
  human check belongs on the writes. That is now overruled, and correctly:
  the GET returns the registry URL plus a live status block, which for a
  private catalog is exactly the pointer an agent should not enumerate. The
  explicit `reject_agent_principal` on PUT/DELETE is kept as belt-and-braces
  — it states the intent locally and survives any relaxation of the gate.

Co-Authored-By: Claude Opus 5 <[email protected]>
vybe pushed a commit that referenced this pull request Aug 9, 2026
…ity-enterprise#14) (#2033)

* docs(requirements): TMPL-002 remote template registry (ent#14)

Rule of Engagement #1 — requirements land before implementation.

New §4.2.2 in core-agent.md, placed immediately after §4.2.1 because the
registry is a new *source* for the seam TMPL-001 documents: a reader who lands
on 4.2.1 must find it in the next paragraph, not in another file. §4.2.1's
"None = use defaults" sentence gets the one-line cross-reference that keeps it
true.

Two things the entry states plainly rather than comfortably:

- `repo` is a capability pointer. It is literally true that the four
  allowlisted fields only change which repos are listed and how they are
  labelled/ordered; as a security statement that is misleading. Choosing the
  repo chooses which template.yaml Trinity fetches and trusts, and that
  document declares mcp_servers, credentials, schedules, data_paths,
  persistent_state and fork_to_own. The allowlist bounds the direct blast
  radius, not the indirect one.

- The honest GitHub cost. A non-empty registry re-introduces the per-repo
  metadata fetches #1931 had driven to zero: workers x windows/hr x entries.
  On a PAT-less install that exceeds the 60/hr anonymous budget above ~5
  entries, which is exactly the precondition that makes the fork_to_own
  fail-open reachable.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(safe-yaml): distinguish the per-repo payload from the remote index

The TWO ALIAS POLICIES docstring says a "template catalog entry" may
legitimately anchor a repeated block, and that clause reads as an argument for
giving the remote registry a BUDGET policy. It is not one — the only shipped
BUDGET caller is load_template_yaml, a per-repo template.yaml, which really can
anchor a repeated block. The remote index cannot: it is a flat list of unique
entries carrying one pointer and three display scalars each.

Amend the clause so the next author cannot make the same misread, and add
load_template_registry_yaml() pinning REJECT + the 256 KiB cap at the utils
layer — the same reason load_template_yaml exists, so the decision is never
relitigated at a call site.

Duplicate-key rejection is load-bearing for this document specifically: a
registry with two `templates:` keys would silently last-wins, showing one
catalog to the human editing the file and serving another to Trinity.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(config): registry URL + hard kill switch, and its SSRF gate

TEMPLATE_REGISTRY_URL / TEMPLATE_REGISTRY_ENABLED on the OPERATOR_INTAKE_ENABLED
shape, plus validate_template_registry_url().

Two choices worth their comments:

The switch is deliberately NOT settings_service._resolve_bool_flag. That
helper's env leg is opt-in only ("true"/"1"/"yes" -> True, anything else falls
through to `default`), so with default=True it would silently swallow
TEMPLATE_REGISTRY_ENABLED=false and ship a kill switch that does nothing —
#1039's inert-by-obscurity class, caught before a line of it was written.

The validator is a sibling of validate_skills_library_url, not a reuse: that one
is github.com-only, which is right for a clone target and wrong for a registry
an operator may self-host. What carries over is the perimeter check; what is new
is refusing userinfo outright rather than stripping it (a stripped credential
gets persisted into a settings row and echoed through a status payload) and
refusing an unresolvable host rather than deferring, since unlike a later git
clone nothing downstream will fail loudly on our behalf.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(templates): remote template registry service (ent#14)

The fetch/parse/cache half. Never raises; every failure returns [].

Fail-open here is structural, not an except branch: get_all_templates() returns
local + github, local needs no network, github is empty by default, and this
module can only ADD to github. So unreachable / 5xx / timeout / malformed /
bombed / oversize / redirected / empty all reduce github toward [], which is the
already-shipping default state of the product. The except layers are a second
layer on top, because fail-open must not depend on this module being bug-free.

Decisions that are load-bearing and easy to undo by accident:

- The byte cap is enforced on bytes RECEIVED, not on Content-Length, which is
  absent on chunked responses and trivially lied about. resp.text on a 10 GB
  body OOMs the worker before any parse-time cap can act, so the transport
  ceiling is the gate and the parser's max_bytes is the belt.

- follow_redirects=False is a security control. A URL that passed the SSRF gate
  and then redirects is a bypass; a redirect is a fetch failure.

- TTL is 3600s + jitter, deliberately NOT aligned with the 600s per-repo cache.
  Aligning them is a correlated thundering herd, not a shared rhythm: one expiry
  fires the registry fetch and N per-repo GitHub fetches in the same instant,
  and --workers 2 drift into phase. It is also the cheapest lever on the
  anonymous GitHub budget, so it is doing security work, not tidiness.

- Serve-stale is capped at 7 days. Unbounded stale keeps a de-curated, renamed
  or compromised repo listed indefinitely while the operator sees a catalog that
  still renders — no signal at all.

- Invalidation is a generation counter read at cache-hit time, not a per-process
  clear. A per-process clear half-applies under --workers 2, and a
  nondeterministic setting is worse than a slow one. Coupled to the TTL raise;
  the two must not be split.

Found while smoke-testing the parser: `../evil` matches all four copies of the
owner/repo regex, because `.` is inside the character class. That breaks the one
invariant the catalog card rests on — the id would render "../evil" while both
the API and clone URLs normalize to a different repo. This gate now refuses dot
segments explicitly and is deliberately stricter than its three siblings, which
share the hole on paths reachable only by hand-typed ids.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(templates): resolve the registry in BOTH resolvers, fail the fork gate closed

Two changes that only make sense together.

get_all_templates() was never the only resolver. get_github_template() resolves
the same repo list for GET /api/templates/{id} and for agent creation
(crud._resolve_github_repo_and_pat), and its ladder ended in a dynamic
fallthrough calling _build_template with no override dict at all. Landing the
registry in one of them would have listed a template as "Cornelius - your second
brain" and resolved it by id as "cornelius" - and under a rate limit the detail
view degrades to the repo basename, so the hardening the registry buys would not
have reached the detail path. Both now share one ladder; a test pins list,
detail and create to it. learnings.md 2026-07-10, on schedule.

The second change is why the first one matters. An unreadable template.yaml and
an absent one were the same value: _fetch_template_yaml_result already
distinguishes them and the catalog wrapper threw the reason away one frame below
the code that computed it. So a 403 produced fork_to_own: None, `== "required"`
was False, and creation bound the agent to the shared upstream template repo
instead of a user-owned copy. Silent, and the thing in the wrong place is the
user's knowledge base.

That bug is pre-existing. This feature is what makes it expected rather than
theoretical: it re-introduces per-repo fetches on a default install, ships
default-on, and its own arithmetic puts a PAT-less install over GitHub's 60/hr
anonymous limit above ~5 listed repos - while the fleet the registry exists to
serve very likely includes the fork_to_own template.

The reason is now cached alongside the metadata and surfaced as
metadata_unavailable, and creation refuses (503, retryable) rather than
guessing. Scoped to the branch that is unsafe: a caller who IS forking gets a
user-owned repo whatever the template declares, so an outage does not block
them. A clean 404 stays "absent", so a repo that ships no template.yaml creates
as it always has.

Also here, because it is the same builder: priority becomes overridable, which
is the only dimension of "curate freely - feature, order, add, deprecate" that
had no mechanism.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(settings): GET/PUT/DELETE /api/settings/template-registry

Same shape as /api/settings/github-templates deliberately — the registry is a
new source for that seam, not a second settings idiom. Registered before the
/{key} catch-all (Invariant #4), verified by inspecting the router's own route
order rather than by reading it.

reject_agent_principal on both writes is not optional. assert_admin answers what
role, never whether this is a human: get_current_user resolves an agent-scoped
MCP key to its owner carrying the owner's role, so on a default admin-owned
install any agent's injected TRINITY_MCP_API_KEY passes a bare admin gate
(trinity-ops-agent#232). The consequence here is total — an agent could repoint
the platform's template registry at a URL it controls and every operator
browsing templates would see its catalog.

The catch-all blocks all four registry keys, on PUT *and* DELETE. PUT because
the generic route takes an unvalidated Dict[str, str], which would leave the
SSRF gate one request away from bypass. DELETE because — unlike the #1644
retention acks, where deleting an ack re-arms a guard and fails safe — deleting
template_registry_enabled reverts it to its default of ON, re-enabling egress an
operator deliberately switched off, and that route carries no human gate.
generation and lkg are blocked because they are the cache itself.

The status block on GET is part of the contract, not decoration: fail-open makes
every registry failure invisible in the catalog by design, so this is the only
place an operator can see that their registry 404s.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(settings-ui): template registry panel; fix a stale MCP tool description

The panel is a new file specifically so Settings.vue's raw-color counts cannot
move — the ratchet only lets per-file counts shrink, and Settings.vue sits at 63
non-gray. It gains one import and one tag, neither carrying a class. Measured:
the new panel is 0 non-gray / 0 hex / 32 semantic tokens, and Settings.vue is
byte-identical to origin/dev at 63/832/1 (the gray drift vs the committed
baseline predates this branch).

The status block is the point of the panel, not decoration. Fail-open means a
broken registry looks exactly like a working empty one from the catalog, so this
is the only surface where an operator can see that their registry 404s. The
backend publishes a fixed lowercase code and never prose — a hostile server's
response text must not reach an admin's screen — so the explanations are ours,
keyed by code, and each one names the remedy.

Uses LoadFailed for a failed fetch and InlineError for a failed verb rather than
sharing one error line: "couldn't load the settings" and "couldn't save the URL"
point at different remedies, and principle 18 says a failed verb persists next
to the control rather than becoming a toast.

The MCP fix: create_agent's `template` description asserted that list_templates
"on a default install returns local templates only until an admin curates GitHub
repos in Settings". With a default-enabled registry that is false, and a wrong
tool description actively misleads a model. Description only — no parameter,
client method, type or behaviour change, so Invariant #13 stays satisfied
without touching the tool.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(ent14): the fail-open matrix, proven rather than asserted

309 tests across five files. Every failure mode is driven through the real
parser and a real httpx client over MockTransport, and every assertion is on the
CATALOG OUTPUT — not on whether an except branch ran. A test that asserts the
except branch ran would still pass if that branch returned garbage.

The matrix: unreachable, read timeout, 404/403/500/503, redirect, oversize body,
lying Content-Length, malformed YAML, level-6 alias bomb, duplicate keys, HTML
captive portal, binary body, top-level list, future schema version, non-list
templates, empty body, empty registry — each asserted twice, once for "the
catalog equals the bundled floor" and once through the router's own sort, which
is where a non-int priority used to 500 the endpoint. Plus a registry service
that simply raises, because fail-open must not depend on it being bug-free.

Two tests exist to stop the matrix being vacuous: one pins that the real bundled
floor is non-empty (otherwise every "degrades to the floor" assertion is
trivially true), and one re-probes the lying Content-Length through a second
client to prove the header really said 12 while the body was 100 KB — otherwise
a future refactor could start trusting Content-Length and these would still be
green.

The F2 regression test was verified to be red without its fix: neutralising the
guard fails 10 of its 24 assertions.

The parity test encodes a real divergence rather than papering over it. `.` is
inside the shared owner/repo character class, so `../evil` matches all three
older copies of the pattern; the registry gate refuses dot segments and the test
pins BOTH halves — the shared corpus where all four agree, and the containment
that everything the registry accepts, the others accept. If somebody later
tightens those copies, the test fails and points at deleting the assertion
rather than leaving a stale comment.

tests/unit/pytest.ini overrides pyproject.toml, so asyncio_mode = auto does not
apply here and a bare `async def test_*` is collected and silently never
awaited. Everything is sync; the one async call under test is driven through an
explicit asyncio.run.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ent14): architecture + feature flows for the remote template registry

architecture.md x3, in place — the registry is one source feeding one existing
service, not a cross-cutting subsystem: the template_service catalog entry gains
the ladder, template_registry_service gets its own <=2-line catalog entry, and
the Platform Settings table gets the three endpoint rows.

The flow doc is standalone rather than a section inside platform-settings.md.
The plan named that as an escape hatch if the section ran past ~60 lines; it ran
to 495, because the fail-open matrix, the cache semantics and the fork_to_own
fix each need their own argument. So platform-settings.md gets a short section
with the three things a reader of THAT file needs, and the index gets a catalog
row — a new doc always gets one.

library-page.md's `GET /api/templates` row said the GitHub half was the
admin-configured list or config.py defaults. That becomes wrong on merge, so it
now names the three-tier ladder. The page itself is unchanged, which is the
point: registry entries are source: "github" and land in the existing grid.

platform-settings.md already carried the sentence "trinity-enterprise#14 will
repoint this seam". This change is what makes it past tense.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(templates): the fork_to_own fail-open limitation is fixed, not restated

/sync-feature-flows found this and my own docs pass had missed it.
template-processing.md carried, as a Known Limitation:

  "fork_to_own: required enforcement is fail-open when the template.yaml
   metadata fetch fails (advisory gate; empty metadata -> flag unseen for that
   10-min cache window)"

That was an accurate description of a real defect, written down and left. It is
now false, and a stale limitation is worse than none — the next reader would
have designed around a gate that no longer behaves that way.

Replaced with what actually happens, keeping the old sentence quoted so the
history is legible: the fetch reason rides the metadata cache as
metadata_unavailable, the non-forking creation path refuses with a retryable
503, a clean 404 still means "declares nothing", and a caller who is forking is
never blocked. The trade-off is stated rather than buried — creation now depends
on GitHub API reachability where it previously depended only on git clone.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(ent14): restore the vendored safe_yaml mirror and two stubbed seams

Three regressions the full unit run caught that the targeted runs could not.

1. safe_yaml.py is a BYTE-IDENTICAL vendored mirror into the agent server
   (Invariant #5, ent#314/#1965) and I edited only the canonical copy. The
   parity guard is exactly the CI mechanism that exists for this and it worked;
   re-copied. Worth noting the architecture doc's own warning applies here: a
   guard that walks only one tree is not a guard, and this one walks both.

2. get_all_templates() had moved onto a renamed bulk fetch
   (_fetch_all_metadata_results), which silently bypassed two existing test
   doubles — test_ent89's fence stub and test_1931's network stub — so both
   fell through to real code. _fetch_all_metadata keeps its name and its
   `repo -> metadata` return shape; the fetch reason rides _metadata_cache
   instead and is read back by _metadata_reason_from_cache. No caller pays a
   signature change, and routers/settings.py's direct call is untouched.

   The bulk path still submits the reason-preserving variant, deliberately: a
   cache entry written with reason=None for a repo whose fetch actually 403'd
   would tell the creation path "readable, declares nothing" for a full TTL —
   reopening the fork-gate bypass through the catalog's own cache.

3. Two test doubles updated where the seam genuinely moved rather than the code
   being wrong: test_ent89's _build_template stub was one parameter short (a
   short stub raises TypeError *inside* the fence that class exists to test, so
   the assertion failed for an unrelated reason), and test_1931's stub set now
   includes _fetch_template_yaml_logged — without it the counter-test silently
   stops counting, which is the failure mode that test was written to prevent.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(ent14): pin the settings stub by sys.modules key, not by module object

43 of my own tests passed in isolation and failed under the full run — the exact
trap test_ent89_template_schedules.py documents, walked into anyway.

Both consumers resolve the module lazily, at call time: template_service's
`from services.settings_service import get_github_templates` and the registry
service's `from services.settings_service import settings_service` each read
sys.modules by key. Patching an attribute on a separately-imported reference
works right up until an earlier file has swapped the module object, after which
the stub is silently ignored.

The resulting failure was worse than confusing, it was inverted: with the stub
bypassed the real accessor read the real tmp SQLite database, found the durable
last-known-good a previous ent14 test had legitimately persisted, and served it
— so a test asserting "a connect error degrades to the floor" reported a
fail-open bug that does not exist. A green isolated run and a red full run
disagreeing about a security property is the worst shape this could have taken.

Fixed with monkeypatch.setitem on the exact key, and the stub built from a copy
of the real module's namespace so SettingsService and the key constants still
resolve through it.

Full unit suite: 7781 passed, 16 skipped, 0 failed.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(ent14): the hard kill switch was inert — wire both registry knobs into both composes

config.py read TEMPLATE_REGISTRY_ENABLED and TEMPLATE_REGISTRY_URL from the
environment, and neither compose file injected them. Prod compose launches
standalone — no base merge, no env_file: on any service — and it is what every
deploy path uses, so the explicit environment: list is the only route into the
container. Both levers were inert on every real instance while working fine on a
laptop, where the shell environment reaches the process directly.

TEMPLATE_REGISTRY_ENABLED is the feature's hard kill switch: the documented
air-gap answer that no system_settings row may override. An inert one is not a
missing convenience — it is a default-ON feature making outbound requests with no
way to stop it.

The irony is the reason this is pinned rather than just fixed. The comment block
directly above the os.getenv call argues at length, and correctly, against
routing the flag through settings_service._resolve_bool_flag, because that
helper's opt-in-only env leg would "silently swallow
TEMPLATE_REGISTRY_ENABLED=false and ship an inert kill switch (#1039 class)".
The flag then shipped inert anyway, by the other route, ~15 lines away. Avoiding
a known failure mode in the layer you are looking at does not avoid it in the
layer you are not.

Sixth recurrence of the #1039/#1056 packaging-gap class (#1056 VOIP_*, ent#31
LOG_*, #1039, #1871 AGENT_LOG_*, #411 CANARY_*), so it gets a guard shaped like
test_canary_env_prod_parity.py — the guard for the fifth.

What the guard asserts, and why presence is the wrong property:
  - injection in BOTH composes; drift between them IS the bug
  - the ${VAR:-true} form, not a hardcoded `- TEMPLATE_REGISTRY_ENABLED=true`,
    which satisfies a presence check while re-breaking the switch
  - the URL's full non-empty default; a bare `:-` arrives set-but-empty,
    os.getenv returns "" instead of falling back, and the registry points at
    nothing (#1076) — strictly worse than absent, because it looks wired
  - compose and config.py defaults are equal, since two spellings of one default
    drift invisibly (the container always wins, so the code default becomes
    decorative while still reading as authoritative)
  - a meta-test that goes red on pre-fix content AND on the hardcoded revert

Verified by rendering rather than grepping: `docker compose config` shows both
vars on backend for each file, and TEMPLATE_REGISTRY_ENABLED=false propagates
through to "false". The guard was additionally proven by deleting the real prod
line and watching it go red — the first attempt at that used
`grep -v 'VAR=${VAR'`, where $ is an end-of-line anchor, so nothing was removed
and the suite reported a false green against an unmodified tree.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(ent14): CSO diff findings — wire-byte ceiling, creation-path fork gate, CGNAT

Three findings from the security review of this branch, each a case where the
control was present and correct one level above where the attack lands.

S1 — a byte ceiling on decoded bytes is not a byte ceiling.
_fetch_registry_text streamed under a 256 KiB running total, with a docstring
correctly explaining why Content-Length cannot be the gate and why resp.text on
a huge body OOMs the worker. Both true, both defeated one level down: a custom
headers= dict does not override httpx's default Accept-Encoding: gzip, deflate,
and iter_bytes() yields DECOMPRESSED chunks. A 199 KiB wire body — under the cap,
so the early abort passes it — inflated ~1030:1 before the running total was ever
consulted: 458 MB of transient allocation on the event-loop thread. The cap
bounded the decoded total, which is not the resource under attack; the peak is.
Now the ceiling counts wire bytes via iter_raw(), any Content-Encoding is refused
outright before the body is read (encoding_refused, named rather than folded into
bad_shape so gzip bytes hitting a UTF-8 decode don't report as a shape problem),
and Accept-Encoding: identity is sent as the polite half only — a request header
is a preference, never a control over a hostile server. Same body post-fix peaks
at 0.01 MB.

The harness hid it and then inflated it: httpx.Response(content=…) decodes and
buffers in the CONSTRUCTOR, so every fixture built a response the production
iter_raw() path cannot even read and that could only ever exercise iter_bytes().
The byte-ceiling tests were green against a shape incapable of expressing the
failure. Both transport fixtures now convert every mock to a real stream — a
transport test whose mock does not stream is not a transport test.

S2 — the fork_to_own gate read the catalog cache, not its own read.
The gate is correct in direction and was wrong in source: it consulted
gh_template["metadata_unavailable"], derived from the global platform PAT, off
the default branch, through a 600 s cache — while crud.py had already read the
same template.yaml one line earlier with the caller's resolved PAT and parsed
ref, cache-bypassed, for ent#89's schedules. ent#89's own docstring had written
the warning: "the exact silent-ignore class this feature exists to close,
reintroduced one layer up."

Both error directions followed. FALSE PASS: GitHub answers 404, not 403, for a
repo a token cannot see, so a private fork_to_own: required template readable
only by the creator's own PAT was classified absent, the gate passed, and the
agent bound to the shared upstream — the precise outcome the gate exists to
prevent, with no attacker involved. FALSE REFUSE: a poisoned shared cache entry
503'd a creator whose own PAT read the file fine, for a full TTL.

Fixing only the availability half would NOT have closed the false pass — for a
private template the catalog's fork_to_own VALUE is None for the same reason its
verdict is wrong, so the gate would sail past a `required` it still could not
see. Both inputs now come from _read_source_template, and `required` from EITHER
read enforces: a union, so this can only remove a false pass, never add one.
Costs zero extra GitHub calls, and the read that DECIDES is now made with the
same credentials as the clone that follows.

S3 — RFC 6598 shared address space (100.64.0.0/10) was admitted.
Python's ipaddress reports CGNAT as neither is_private nor is_reserved, so the
standard predicate stack passed it. Not reachable in Trinity's own topology
(both Docker networks are 172.28/16 and 172.29/16, which are is_private), but
several cloud providers address internal endpoints out of that range, so a
Trinity deployed there had a hole the same shape as 10.0.0.0/8. Both /10
boundaries are held public so a legitimate registry is not blackholed, and one
CGNAT record among public ones is enough to refuse.

Docs: requirements TMPL-002, architecture, template-registry + scheduling flows,
and three learnings entries for the transferable classes: a decoded-byte
ceiling; a gate reading the catalog's cached metadata instead of the
creation-path read standing one line above it; and the packaging class from the
preceding commit — its ledger entry rides here because learnings.md is a single
append-only file and the compose fix was committed on its own to stay
self-contained.

Full unit suite: 7851 passed, 17 skipped, 0 failed (pytest-randomly).

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(ent14): adapt two suites to dev's newer gates after the rebase

Rebasing onto dev picked up two changes that landed under this branch and
moved what its own tests assert. Both are the other change being right.

- ent#15 (#2040) inserted an import-intent gate into `_resolve_template`
  ahead of the fork gate. Two `SimpleNamespace` config doubles predate the
  field, so `config.import_intent` raised AttributeError before reaching the
  assertion — a stub gap, not a production one. The fork/clone path and the
  S2 fail-closed gate are unchanged, and dev's `copy` intent carries its own
  `fork_to_own: required` refusal before its early return.

- #1890 made `require_admin` itself reject agent-scoped principals, closing
  the class at the gate rather than per-endpoint. This suite asserted an
  agent key could still READ the registry setting, on the reasoning that the
  human check belongs on the writes. That is now overruled, and correctly:
  the GET returns the registry URL plus a live status block, which for a
  private catalog is exactly the pointer an agent should not enumerate. The
  explicit `reject_agent_principal` on PUT/DELETE is kept as belt-and-braces
  — it states the intent locally and survives any relaxation of the gate.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: trinity-ability <[email protected]>
vybe pushed a commit that referenced this pull request Sep 3, 2026
…fied twice, symlinks preserved, named errors, idempotent + locked (#2060) (#2485)

* docs(requirements): deploy-local integrity contract — new §4.1.2 (#2060)

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]>

* fix(deploy): embedded-manifest integrity verification, symlink contract, 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]>

* fix(deploy): manifest-aware MCP tool + CLI — third/fourth surfaces of 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]>

* docs(flows): local-agent-deploy #2060 update + architecture rows

- 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]>

* fix(deploy): review fixes — close the compensation window at create-return, 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]>

* docs(deploy): compensation window closes at create-return — align §4.1.2 + flow with the review fix (#2060)

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(deploy): adopt the shared SingleFlightLock for the per-base-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

* fix(deploy): make the dest_path containment guard the barrier shape CodeQL 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

---------

Co-authored-by: trinity-ability <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
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.

3 participants