Skip to content

feat(git): reset-to-main-preserve-state operation (S3, #384) - #400

Merged
vybe merged 13 commits into
Abilityai:mainfrom
AndriiPasternak31:AndriiPasternak31/reset-preserve-state
Apr 22, 2026
Merged

vybe merged 13 commits into
Abilityai:mainfrom
AndriiPasternak31:AndriiPasternak31/reset-preserve-state

Conversation

@AndriiPasternak31

Copy link
Copy Markdown
Contributor

Summary

Ships §S3 of the git-improvements proposal — a first-class recovery path for
agents stuck in the parallel-history deadlock (P2/P3). Consumes the
persistent-state allowlist primitive from #383 / PR #394 (S4) rather than
reimplementing it.

  • Backend: POST /api/agents/{name}/git/reset-to-main-preserve-state
    (owner-only). Guardrail: refuses with 409 agent_busy if the agent
    currently has in-progress activities (activity service check).
  • Agent-server primitives: new routers/snapshot.py with
    POST /api/agent-server/snapshot (tarball response; optional
    .trinity/backup/<ts>/ copy) and POST /api/agent-server/restore
    (multipart with JSON-array paths). Both pure functions
    (build_snapshot, restore_from_tar) reject traversal / absolute
    paths.
  • Compose routine in agent_server/routers/git.py:
    1. Read allowlist via _read_persistent_state() (S4).
    2. Snapshot matching files to .trinity/backup/<iso-ts>/ with manifest.
    3. git fetch origin main + git reset --hard origin/main.
    4. Overlay snapshot back.
    5. Commit with the spec's exact message Adopt main baseline, preserve state.
    6. git push --force-with-lease origin HEAD:<working-branch>.
      Guardrails: 409 no_git_config / no_remote_main.
  • Tests: 16 new unit tests (mirror + drift-detect pattern like the
    existing S4 tests). Plus tests/git-sync/s3_reset_preserve.sh
    reproducing the proposal's pure-git regression from
    /tmp/trinity-repro/s3_fix_verified.sh. Opt-in integration test in
    tests/test_reset_preserve_state_integration.py.

The UI wiring (third modal button) belongs to #385 / PR #395 and is
intentionally out of scope here.

Stacking

Stacked on #394 (S4, issue #383). Marked draft until #394 merges.
Once it does, rebase onto upstream/main with
git rebase --onto upstream/main <S4-head-sha> AndriiPasternak31/reset-preserve-state
and flip out of draft.

Test plan

  • pytest tests/unit/test_reset_preserve_state_*.py → 20 passed
  • pytest tests/unit/test_persistent_state_*.py tests/unit/test_git_pull_branch.py → 23 passed (no S4 regressions)
  • ./tests/git-sync/s3_reset_preserve.sh → S3 pure-git regression: OK
  • ruff check on edited files → 0 new errors (4 pre-existing F841s untouched)
  • mypy --strict on the new compose routine → 0 new errors
  • cd src/mcp-server && npm run build → tsc exit 0
  • Integration test against a live stack — skipped (no Docker available in this workspace); opt-in via TRINITY_API_URL / TRINITY_TEST_TOKEN / TRINITY_GIT_TEST_AGENT

Closes #384
Refs #381

🤖 Generated with Claude Code

@AndriiPasternak31

Copy link
Copy Markdown
Contributor Author

Rebased onto main (now at 21403b1) — mergeable: CLEAN.

Used the approach documented in the PR description: git rebase --onto upstream/main 3ebb65b HEAD to drop the S4 persistent-state commit (now merged in #394 as 21f2de4) and replay the 13 S3-specific commits on top of current main.

Conflicts resolved:

  • docker/base-image/agent_server/routers/git.py (imports block) — kept upstream's S2/S5/S7 imports (uuid, ..utils.git_conflict, Optional) AND my S3 imports (.files._read_persistent_state, .snapshot.build_snapshot/restore_from_tar, Callable). Union-merged the typing import line.
  • docs/memory/feature-flows/github-sync.md — upstream added S7/S5/S2 rows above; appended my S3 reset-preserve-state row after them.
  • docs/memory/feature-flows.md — inserted my Reset-preserve-state operation (S3) #384 S3 row at its 2026-04-18 chronological position, below the two 2026-04-19 rows.
  • docs/memory/requirements.md — upstream took §§11.3/11.4/11.5; moved my reset-preserve-state entry to §11.6.
  • docs/memory/project_index.json — kept upstream's last_updated: 2026-04-19 (tighter than mine); union-merged features.implemented: kept github_pat_auto_propagation + git_reset_preserve_state.

12 commits on top of main. Draft status is lifted (S4 dependency merged). Ready for review.

@AndriiPasternak31
AndriiPasternak31 marked this pull request as ready for review April 19, 2026 13:26
Andrii Pasternak and others added 13 commits April 22, 2026 10:08
Add two pure-function primitives that the reset-preserve-state routine
will compose:

- `build_snapshot(home_dir, paths)` walks /home/developer, selects files
  matching any allowlist glob (S4 persistent-state patterns), and returns
  a tar blob plus the list of captured paths. Traversal/absolute patterns
  in the allowlist are silently skipped.
- `restore_from_tar(home_dir, tar_bytes, paths)` extracts a tar back into
  /home/developer, enforcing the same allowlist and rejecting entries
  whose names are absolute or contain `..` segments. Returns (restored,
  skipped) so the caller can audit.

Both are wrapped by thin FastAPI endpoints (`/api/agent-server/snapshot`,
`/api/agent-server/restore`). The snapshot endpoint optionally writes a
copy to `.trinity/backup/<dir>/snapshot.tar` when `backup_dir` is given.
The restore endpoint accepts a JSON-encoded `paths` form field so the
allowlist is explicit in every call.

Tests follow the project convention (see `test_git_pull_branch.py`,
`test_persistent_state_reader.py`): mirror the pure functions host-side
and drift-detect via a source-match assertion. 10 tests cover empty
allowlist no-ops, the S4 default patterns, path-traversal rejection on
both sides, and round-trip snapshot→restore.

Refs Abilityai#381
Part of Abilityai#384

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ai#384)

Compose the snapshot + restore primitives into the recovery operation
the git-improvements proposal calls out as §S3. The routine:

1. Reads the persistent-state allowlist via `_read_persistent_state()`
   from Abilityai#383 / S4 — does NOT reimplement the reader.
2. Snapshots every matching file to `.trinity/backup/<iso-ts>/` with a
   manifest, so the destructive reset is always recoverable from inside
   the container even if the push later fails.
3. `git fetch origin main` + `git reset --hard origin/main` to adopt the
   template baseline.
4. Overlays the snapshot back to restore instance-specific state.
5. Commits `Adopt main baseline, preserve state` — the exact message
   §S3 specifies.
6. `git push --force-with-lease origin HEAD:<working-branch>` — the
   lease keeps this safe against the P5 clobber scenario even though
   the broader --force swap belongs to Abilityai#382 / S7.

Two guardrails live in this layer:
  - `no_git_config` — refuse if `.git` is missing or no origin remote.
  - `no_remote_main` — refuse if origin doesn't have main.

Both surface as HTTP 409 with an `X-Conflict-Type` header so the backend
can map them to operator-readable messages. The "agent currently running
a task" guardrail sits in the backend layer (next commit) because this
server has no view of the activity service.

Tests (6 new): drift-detect the compose routine's signature; cover the
two guardrails; pin the empty-allowlist-is-safe-no-op invariant; exercise
the full snapshot→reset→overlay→commit happy path; verify the push step
uses --force-with-lease. All tests drive a real tmpdir with a bare-origin
fixture reproducing the parallel-history scenario from the proposal.

Refs Abilityai#381
Part of Abilityai#384

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rd (S3, Abilityai#384)

Backend surface for the recovery operation added to the agent-server in
the previous commit:

- `services/git_service.py::reset_to_main_preserve_state(agent_name)`
  proxies `POST /api/agents/{name}/git/reset-to-main-preserve-state` to
  the agent-server endpoint, and adds one guard that can only live at
  this layer: reject if the agent currently has in-progress activities
  (chat, schedule, tool-call, collaboration). The activity service is a
  backend-only view, so the agent-server cannot check this itself.

- `routers/git.py` adds the `POST .../git/reset-to-main-preserve-state`
  endpoint, scoped to `OwnedAgentByName` so only the agent's owner or an
  admin can trigger a destructive reset. Normalises the service's error
  dict into HTTP responses:
    - 409 `X-Conflict-Type: agent_busy | no_git_config | no_remote_main`
    - 500 for unexpected agent-server failures (push_failed, etc.)
    - 200 with `{success: true, snapshot_dir, files_preserved,
      commit_sha, working_branch}` on success.

Tests (4 new, 10 total with the agent-server ones): mock the activity
service and httpx client to verify the guard short-circuits before any
HTTP call, the happy-path proxy call shape, conflict-header surfacing,
and the unexpected-status → proxy_failed fallback.

The helper in `_load_git_service` installs mocks directly in sys.modules
(rather than using patch.dict) so the function's lazy import of
`services.activity_service` still resolves to the mock at call time.

Refs Abilityai#381
Part of Abilityai#384

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
In-repo mirror of /tmp/trinity-repro/s3_fix_verified.sh. Pure git + bash
— no Trinity stack, no Python, no network. Lets anyone confirm the
shell-level mechanics of reset-preserve-state still work after a refactor
without bringing up Docker.

Reproduces the parallel-history scenario from the proposal (same commit
title, different SHAs, upstream advances with a conflicting change) and
asserts the remote `trinity/demo/abc` ends with origin/main's baseline
plus the worker's workspace state and the spec's exact commit message.

Refs Abilityai#381
Part of Abilityai#384

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…#384)

Opt-in integration test that hits the endpoint on a running Trinity
stack. Skipped unless TRINITY_API_URL / TRINITY_TEST_TOKEN /
TRINITY_GIT_TEST_AGENT are set — so CI and the default pytest run don't
need Docker or a pre-configured test agent.

Asserts the response falls in the defined contract surface — either a
200 with snapshot_dir/commit_sha/working_branch, or a 409 with an
X-Conflict-Type header in the known set (agent_busy, no_git_config,
no_remote_main). Anything else indicates a regression.

A second test verifies that unauthenticated requests are rejected before
any git work happens.

Refs Abilityai#381
Part of Abilityai#384

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…lityai#384)

- architecture.md: new "Git Recovery" section with the endpoint row and
  its three 409 X-Conflict-Type variants.
- feature-flows/github-sync.md: revision-history entry for S3 covering
  the agent-server primitives, the compose routine, the allowlist
  consumer contract from S4, and the test matrix.

Refs Abilityai#381
Part of Abilityai#384

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…i#384)

Ruff doesn't recognise flake8-wemake-python-styleguide codes and emitted
a warning. The lazy import is intentional (explained in the comment) and
ruff's own rules don't flag it, so no suppression is needed.

Refs Abilityai#384

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ai#384)

Addresses two mypy --strict errors introduced by the new compose
routine:

- `_git` now returns `subprocess.CompletedProcess[str]` (text=True).
- `reset_to_main_preserve_state_impl` returns `dict[str, object]`
  instead of a bare `dict`.

Rest of agent_server/routers/git.py remains untyped (140 pre-existing
strict errors out of scope for Abilityai#384).

Refs Abilityai#384

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…nts (Abilityai#384)

One-line row in the Entry Points table so the top-of-file index reflects
the new recovery endpoint alongside pull/sync/status/config.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ityai#384)

Document the new recovery operation as its own section in the existing
GitHub Sync flow (rather than a standalone file — S3 is an enhancement
to the sync feature, not a separate system).

Covers:
- Purpose (parallel-history deadlock and why pull/force aren't safe)
- Full API contract with all three 409 X-Conflict-Type variants
- Sequence diagram showing the backend agent-busy guard + agent-server
  compose routine (snapshot → fetch → reset → overlay → commit → push)
- Five guardrails in execution order
- Primitives table mapping each helper to its source file
- Code reference map (tests, regression script, integration test)
- Explicit non-goals (UI, auto-sync, branch-ownership) with the PRs
  that own them

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…lityai#384)

One-line entry under Recent Updates pointing at the github-sync.md flow
where the full S3 recovery operation is documented.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…yai#384)

New requirement §11.3 with status, description, key features, endpoint,
and flow-doc link. Sits under "GitHub Integration" alongside Sync and
Repository Initialization.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ilityai#384)

Project index JSON gains the new feature slug under features.implemented;
bumps last_updated to 2026-04-18.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@vybe
vybe force-pushed the AndriiPasternak31/reset-preserve-state branch from 15e9be7 to e46f58a Compare April 22, 2026 09:09
@vybe
vybe merged commit 75f7a22 into Abilityai:main Apr 22, 2026
@AndriiPasternak31
AndriiPasternak31 deleted the AndriiPasternak31/reset-preserve-state branch April 25, 2026 17:59
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.

Reset-preserve-state operation (S3)

3 participants