Skip to content

fix(git-sync): the canonical .gitignore stops reversing the agent's own negations, and a Push reports what it untracked (#2529) - #2595

Merged
vybe merged 22 commits into
devfrom
AndriiPasternak31/issue-2529
Sep 8, 2026
Merged

vybe merged 22 commits into
devfrom
AndriiPasternak31/issue-2529

Conversation

@AndriiPasternak31

Copy link
Copy Markdown
Contributor

Fixes #2529

What was broken

Both writers of an agent's .gitignore appended, and gitignore is last-match-wins. So the canonical _GITIGNORE_PATTERNS block landed below every !negation the agent had written and silently reversed it — after which the per-Push git rm --cached sweep untracked exactly the files those negations were protecting, inside an unrelated sync commit that named none of them.

.env.example was a casualty, and compat check F-004 requires it — so an agent that shipped one lost it on its first Push and then failed its own compatibility contract. The documented escape hatch ("negate in your own .gitignore", #1596/#2036) held only until the next canonical pattern was appended below it.

The fix

The merge is a normalize-and-rebuild into two managed regions, not an append:

[ defaults block ]        <- canonical rules the agent MAY override
[ user region ]           <- the agent's own rules, original order preserved
[ protected floor ]       <- credentials + .trinity/*, the agent may NOT override

Two regions rather than one, because a single hoisted block provably cannot carry both. Hoisting everything would flip every currently-inert !.env in the fleet live in one unattended 15-minute cycle, and would let a user *.sh beat !.trinity/setup.sh (ent#76/#1704 reintroduced, and quietly, since the rm-cached pathspec still exempts the path).

AC-1 is enforced by git itself — with the defaults above the agent's rules, git ls-files -ci no longer lists a path an effective negation covers — so #462's and #1596's purpose (untracking long-committed node_modules/) survives untouched. _GITIGNORE_PROTECTED is a filter over _GITIGNORE_PATTERNS, never a second list; an import-time assertion enforces the subset relation.

Floor membership is decided against services/credential_paths.py — the platform's own answer to "is this secret material" — not against the constant's comment headings. That is how .ssh/ was caught in review: an agent carrying !.ssh had .ssh/id_rsa ignored under the old append-only merge and not ignored under the hoist, and the unattended git add -A would then commit a private key. Reproduced, fixed, pinned.

The rebuild is idempotent by content (cmp gate), so the auto-sync loop has nothing to re-commit, and the 14 bundled templates are regenerated as the merge's own fixed point to keep #1908's byte-identity that #953 depends on.

Acceptance criteria — all 7 met, none deferred

AC Status Where
AC-1 — a Push never untracks an already-tracked path covered by an agent negation ✅ _build_gitignore_merge_command, _build_rm_cached_ignored_command — enforced by git's own ls-files -ci against the rebuilt file
AC-2 — canonical merge preserves agent-authored precedence ✅ two-region rebuild, user region above the floor and below the defaults
AC-3 — !.env.example + !.mcp.json.template in _GITIGNORE_PATTERNS; ALLOWED_NON_CANONICAL empty ✅ git_service.py:1501,1505; tests/unit/test_1908_bundled_template_gitignore.py:148 is now ()
AC-4 — a Push that untracks anything reports the removed paths on API, MCP, UI, commit message ✅ all four, plus a fifth see below
AC-5 — regression: !.env.example + tracked .env.example survives two consecutive Pushes ✅ test_env_example_survives_two_consecutive_pushes
AC-6 — regression: tracked .claude/settings.json under a negation survives a Push ✅ test_claude_settings_json_negation_survives_a_push
AC-7 — guide documents the one-line recovery for already-stripped agents ✅ docs/TRINITY_COMPATIBLE_AGENT_GUIDE.md — "Recovering a file a sync already untracked" (git add -f + a negation)

AC-4 in full — the UI surface is implemented, not deferred. No follow-up issue is needed for it.

  • API response — removed_paths / unignored_paths / shadowed_negations on GitSyncResult (db_models.py) and on the hand-built response dict in routers/git.py. Reported on all four returns including the 409: the index mutation precedes the HTTP call, so a failed Push is exactly as obliged to report it as a successful one.
  • MCP git_sync result — the fields pass through the client verbatim; the tool description now tells the caller to check removed_paths before assuming a sync only added things (src/mcp-server/src/tools/git.ts, pinned by git.test.ts).
  • UI — useGitSync.js names the sweep in the sync toast, in both directions.
  • Commit message — _augment_commit_message (best-effort: git rm --cached only stages).
  • Operator queue — a durable gitignore_untracked entry, the surface that outlives an unattended 15-minute cycle. Routed through the bug: platform operator-queue alert emitters bypass #1632 ingestion caps — skill-not-found is agent-triggerable (flood residual, gates pull default-ON) #1677 budget seam and budgeted rather than exempted, because sync_to_github is reachable from the git_sync MCP tool that an agent-scoped key may call on itself.

All five are gated on GitignoreSweep.changed_tracking (removed or unignored) — the rebuild changes what is in the repo in both directions, and the addition half is already in the remote's history and may need a credential rotated rather than a file restored.

Known residual — reported, not fixed

23 canonical patterns are dir-form, and git does not descend into an excluded directory, so a negation beneath one is inert at any position. Contents-form conversion was costed and rejected: it would force git to stat node_modules/-sized trees on every status. The Push instead reports it as shadowed_negations ("!rule -> deciding managed pattern") rather than failing silently.

Shell hardening (each reproduced first)

  • The strip grep is a real command with an rc<=1 check — a failure inside a process substitution is invisible, and the mv then destroys the user's rules.
  • LC_ALL=C grep -a — a NUL byte otherwise drops the whole user region while exiting 0.
  • Bare + CR strip list, so a CRLF .gitignore normalizes rather than duplicating.

CI direction fixed

test_doc_and_constant_in_sync asserted constant ⊆ doc only — which is exactly how the guide's fence carried !.env.example for months while the constant did not. It is now set equality, so this direction cannot regress.

Verification

Run locally on this branch, output shown:

Suite Result
Every git_service-touching unit test + test_models_centralized (34 files) 815 passed
test_2529_gitignore_precedence.py + the 4 amended guards 225 passed
Frontend unit suite (incl. the new gitSyncSweepToast.spec.js) 2182 passed / 98 files
MCP server suite (node --test) 318 passed, 0 failed
tests/lint_sys_modules.py OK — 140 violations vs baseline 206, no new
test_lint_root_test_placement.py (#1895 guard) 13 passed
enterprise-docs-guard PCRE, run locally against the changed docs OK — no disclosure

Not run: /verify-local (no Dockerfile, compose, requirements, migration, or base-image change in this diff — no new top-level src/backend module, no new os.getenv, so neither the #1033 image-packaging class nor the #1056 config-packaging class is reachable here).

Docs

  • docs/memory/requirements/github.md — new §11.15 Canonical .gitignore Precedence and Sweep Reporting
  • docs/memory/architecture/agent-lifecycle.md — the two-region precedence model and the five report surfaces
  • docs/memory/feature-flows/ — github-sync.md, git-sync-health.md, operating-room.md (the second budgeted emitter), plus the index row in feature-flows.md
  • docs/TRINITY_COMPATIBLE_AGENT_GUIDE.md — the escape hatch and the recovery procedure (AC-7)
  • docs/memory/learnings.md — inverting a precedence order re-decides every conflict at once

🤖 Generated with Claude Code

https://claude.ai/code/session_01TvPBC72QFs1kXSA7YUyiS1

AndriiPasternak31 and others added 21 commits September 7, 2026 19:54
… bug (#2529)

The canonical `_GITIGNORE_PATTERNS` block is appended to the END of an agent's
`.gitignore` on every Push, and git is last-match-wins, so it silently reverses
every `!negation` the agent wrote above it — and `_build_rm_cached_ignored_command`
then untracks the files those negations were protecting.

Two tests, both red against the real builders and real git repos:
  - `.env.example` (compat F-004 requires it) negated by the agent, with an
    unrelated rule after the negation so the win cannot come from being last
  - `.claude/settings.json`, the escape hatch #2036's own rationale offered

TWO consecutive Pushes is the load-bearing shape: on a pre-canonical repo the
file is already gone by the second Push, so a single-Push assertion can pass
with the bug live.

Co-Authored-By: Claude Opus 5 <[email protected]>
…eporting (#2529)

Rule #1: the requirements entry lands BEFORE the implementation. Records the
two-region shape and why one block provably cannot carry both defaults the user
may override and guarantees the user may not; AC-1 rule (b) and why not rule (a);
the dir-form residual with its rejected contents-form alternative and that
alternative's cost; the three report fields across five surfaces and which one
outlives the session; and the decision that `.trinity/operator-queue.json` stays
runtime state rather than a commit every 15 minutes.

Co-Authored-By: Claude Opus 5 <[email protected]>
…egations win (#2529)

The merge is now a normalize-and-rebuild instead of an append: every managed
line is stripped wherever it appears, then the file is written as
[defaults][user region, original order][protected floor], and only written at
all when the computed content differs.

An agent's `!.env.example` / `!.claude/settings.json` now beats a canonical
default without having to be the file's last line. It does NOT beat the floor:
the six credential patterns with their two canonical negations, plus `.trinity/*`
and the eight `!` re-includes derived from `_TRINITY_AUTHORED_PATHS`, sit BELOW
the user region — because a single hoisted block would flip every currently
inert `!.env` in the fleet live in one unattended Push (measured), and would let
a user `*.sh` beat `!.trinity/setup.sh` (trinity-enterprise#76 / #1704, measured).

`!.env.example` and `!.mcp.json.template` join `_GITIGNORE_PATTERNS` at the tail,
where the constant's order becomes exactly the agent guide's fence order.

Shell hardening, each reproduced before it was fixed: the strip grep is a real
command with an explicit rc<=1 check (a failure inside a process substitution is
invisible and the mv then destroys the user's rules); `LC_ALL=C grep -a` (a NUL
byte otherwise drops the whole user region while exiting 0); the strip list
carries every line bare AND CR-suffixed; `[ -e ] || : >` instead of `touch`; and
an import-time reject of empty or newline-bearing managed lines.

Three report probes ride on the two execs the Push already ran — removed,
untracked-before/after, and a `git check-ignore -v` shadow probe whose verdict
comes from the deciding pattern text, never the exit code (check-ignore exits 0
even when a negation decides).

Verified against real git repos: idempotent (byte-identical second run), floor
beats the user's `!.env` and `*.sh`, user negation wins for
`.claude/settings.json`, user rules keep their order, and the dir-form residual
(`content/keep.md` under `content/`) is swept AND reported.

Co-Authored-By: Claude Opus 5 <[email protected]>
`_migrate_workspace_gitignore` returned `None`, so nothing downstream could tell
"5 files pushed" from "5 files pushed, 4 silent deletions" — which is why both
field incidents surfaced two months late. It now returns a `GitignoreSweep`
(removed / unignored / shadowed), and every failure path returns the empty one
so a caller can read the fields unconditionally.

`sync_to_github` attaches it to ALL FOUR returns — 200, 409, non-200 and the
exception path — because the index mutation happens before the HTTP call, so a
conflict is exactly as obliged to report it as a success. The router's
HTTPException keeps only `detail`, so the one-line summary is folded into
`result.message` inside the service rather than special-cased per status code.

Surfaces: the API response (the hand-built router dict drops anything not named,
so all three keys are listed), the `_audit_git` details on both the success and
failure paths (#905), the commit message (best-effort — `git rm --cached` only
stages, and if the auto-sync loop commits first the deletions ride in someone
else's commit, which is exactly what `47efd80` was), and an operator-queue
`gitignore_untracked` entry, which is the only one that outlives the session.

Guards moved with the fix:
- `test_doc_and_constant_in_sync` is now set EQUALITY. Asserting `constant ⊆ doc`
  is how the guide carried `!.env.example` for months while the constant did not.
- `ALLOWED_NON_CANONICAL` shrinks to empty (AC-3): the reviewed delta between the
  guide's fence and the constant no longer exists.
- The 14 bundled templates are regenerated as the merge's own fixed point, which
  is what preserves #1908's byte-identity property that #953 depends on; a flat
  canonical list is no longer its own fixed point, so the #2069 no-drift seed is
  reseeded to block shape and its contract restated.
- `test_ent123`'s hand-written `_GitSyncResult` stand-in gains the three fields
  and a `model_copy` — a closed kwarg list raises TypeError at the very return
  that test asserts on.
- New `test_guide_fence_order_matches_the_constant`: the fence a template author
  copies must produce the file the platform writes, order included.

Co-Authored-By: Claude Opus 5 <[email protected]>
…sync toast (#2529)

Invariant #13: the backend router, the agent server and the MCP tool are three
surfaces of one contract, so `git_sync`'s description now names removed_paths /
unignored_paths / shadowed_negations. No `client.ts` / `server.ts` change is
needed — `run()` JSON-stringifies the client result wholesale and `gitSync`
returns `Promise<unknown>` — but that passthrough is now a pinned regression
test rather than an assumption, because an agent reading only `files_changed`
cannot tell a 5-file push from a 5-file push that also untracked two committed
files.

The toast names the removal count in the same breath as the files pushed, on the
success, no-changes and failure paths alike (the sweep runs before the agent
call, so "nothing to commit" and "the index was mutated" are not mutually
exclusive). Type stays 'success' on a successful sync: the toast host is a
binary success/danger ternary, so anything else paints a completed verb in the
danger token. The durable surface for a removal an operator must act on is the
operator-queue entry, not a 3-second toast.

Verified: `node --import tsx --test src/tools/git.test.ts` 10/10 and
`npx tsc --noEmit` clean in src/mcp-server; `npm run test:unit` 2175/2175 in
src/frontend plus the 5 new specs; raw-color scan unchanged (the composable
carries no colors and is not in the baseline).

Co-Authored-By: Claude Opus 5 <[email protected]>
…port (#2529)

31 tests over REAL git repos, because the defect lives in git's own
last-match-wins and dir-descent semantics, which a mocked container cannot
express. Modelled on `test_2070_trinity_authored_paths.py`'s harness, and the
report is produced by the exact two commands the backend runs — not a second,
test-only code path.

Precedence: `.env.example` and `.claude/settings.json` survive two consecutive
Pushes with an unrelated rule after the negation; corbin's `!**/.env.example` at
nested depth; the defaults block sits above the user rules and the user rules
keep their original order.

The floor: `!.env` / `!.env.production` cannot un-ignore a credential; a user
`*.sh`/`*.yaml`/`*.json` cannot beat `!.trinity/setup.sh` (the R2 regression);
the floor is a total partition of the canonical list; every entry of
`_TRINITY_AUTHORED_PATHS` is protected by derivation, so a tenth authored path
inherits it; `!.env.example` follows `.env.*` in index order.

Mechanics: byte-identical second run with a clean porcelain (the mtime is
deliberately NOT asserted — content-identity is the invariant); a CRLF canonical
copy is stripped while the user's own CRLF line keeps its endings, asserted at
byte level because `str.splitlines()` splits on a bare CR and would hide the
distinction; an unreadable `.gitignore` aborts without writing; a NUL-bearing
file keeps its user region; no empty or newline-bearing managed line; no
line-gluing on a file with no trailing newline.

Reporting: removed/unignored/shadowed each pinned, including the
`git check-ignore -v` exit-0-on-negation trap and the interleaved-stderr blob
(`container_exec_run` does not demux). AC-1 is proved as the universal it is —
`before - after == set(removed)` over a 10-file repo spanning both regions, a
dir-form parent, effective negations and genuine #462/#1596 targets — and
parametrised over both pattern forms, so it cannot pass on a file-form fixture
and certify a guarantee that is false for the 23 dir-form patterns.

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

architecture/agent-lifecycle.md — the Git Sync Health paragraph (the Architecture
Map's owner of git_service.py) gains the precedence sentence in the map's own
"read it first because" voice: a canonical rule appended below an agent's
negation silently reverses it and the sweep then untracks the file, and a
canonical rule hoisted above a platform negation silently reverses that one
instead — which is why there are two managed regions and not one. Plus the
dir-form residual, the rejected contents-form alternative, and the five report
surfaces. The core architecture.md is untouched: no new area, invariant or
topology change, and no schema change.

TRINITY_COMPATIBLE_AGENT_GUIDE.md — AC-7. Section 5 documented no escape hatch
and no recovery at all. It now shows the three-part file, states that a negation
no longer has to be the last line, names what the protected floor refuses and
why, states the honest git limitation that a negation cannot re-include a file
under an excluded directory (inert at any position — and that the sync now says
so via shadowed_negations), and gives the one-line recovery for an
already-stripped file: a negation below the managed block plus `git add -f`.
The canonical fence itself is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
github-sync.md — "Per-Push Gitignore Migration" rewritten for the rebuild shape,
why two regions rather than one hoisted block, that AC-1 is enforced by git
itself once the block sits above the agent's rules, the three report fields with
their honest caveats (unignored is `after - before` against a live container;
the commit message is best-effort because `git rm --cached` only stages), and
the dir-form residual with its rejected contents-form alternative. The sequence
diagram now shows the rebuild, the probes, the operator-queue entry and the
three fields on the response.

git-sync-health.md — §0 gains the region shape and the content-idempotence
contract (the 14 bundled templates are the merge's fixed point, which is what
keeps #1908's byte-identity that #953 depends on); the Testing section gains the
five real-git suites it omitted, including the two #2069 files.

feature-flows.md — Recent Updates row (standing rule: always add one).

.claude/agents/test-runner.md — catalog entry for the 31 new unit tests, the
four amended files, and the frontend/MCP specs; statistics bumped.

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

`test_1677_operator_alert_emitters.py` caught this and it was right. The sibling
`git_bloat` / `sync_failing` emitters are direct `db.create_operator_queue_item`
calls because their cadence is the 60-second platform poller's. This one fires
from `sync_to_github`, and `git_sync` is an MCP tool an agent-scoped key may call
on itself — a repeated `git add -f <ignored>` + sync loop yields a fresh
`removed` set every time against a timestamped, non-idempotent id, so nothing
upstream bounds the volume. That is the `_alert_skill_not_found` (#1410) shape
the budget seam exists for.

So: `create_bounded_alert` with `gitignore_untracked` registered in
`_BUDGETED_ALERT_TYPES`, and `gitignore-untracked-` added to
`_RESERVED_ID_PREFIXES` so an agent cannot pre-create the id and silently
suppress its own alert through the sink's `on_conflict_do_nothing` (the C2
class). The emitter is now async and still swallows everything —
`create_bounded_alert` never raises and returns False when refused, but an
alerting failure must not be able to fail a Push either.

Two tests pin the classification and the payload (path cap at 20, empty sweep
files nothing, a raising sink never reaches the caller).

Co-Authored-By: Claude Opus 5 <[email protected]>
…er (#2529)

The #1677 emitter inventory in operating-room.md said "today
`task_execution_service._alert_skill_not_found`" — it is no longer the only one.
`gitignore_untracked` joins it as agent-influenceable, and the entry states WHY
its `git_bloat`/`sync_failing` siblings stay direct creates: their cadence is the
60-second poller's, which is exactly the influence-not-location distinction #1677
was built on. The reserved-prefix list in the ingestion-caps section was also
three prefixes stale (`db-backup-`, `log-archive-`, `sub-headroom-`); brought to
match the source alongside the new one.

Co-Authored-By: Claude Opus 5 <[email protected]>
…#2529)

Decision 8 of the plan: the coverage frame is the FILE, not the three merge call
sites. Two writers were reasoned about and are now pinned rather than asserted.

`materialize_data_paths` (#1169) appends through the generic
`_build_gitignore_append_command`, i.e. to the END — which after this change is
BELOW the protected floor. Harmless (positive ignores over agent-declared data
directories shadow nothing the floor protects) and self-correcting: they are not
managed lines, so the next merge carries them into the user region with
everything else. What actually matters is that neither writer duplicates them in
either order, because a growing `.gitignore` is exactly what the 15-minute
auto-sync loop would re-commit forever.

And the honest cost of the rebuild: a user who typed a canonical pattern
themselves keeps one copy — ours, in the managed block — so `*.log` /
`!important.log` / `*.log` leaves only the negation below the block, WEAKENING an
ignore they meant. It can never untrack something new, the floor covers the cases
where weakening would be dangerous, and `shadowed_negations` reports the rest.
Documented in the agent guide; now also pinned.

Co-Authored-By: Claude Opus 5 <[email protected]>
Revised criterion 3 as it actually happened: an earlier Push swept four
`.env.example` files — still on disk, gone from the index, and IGNORED, so
nothing re-added them. The issue's follow-up names the second-order property,
"un-ignoring a file does not re-track it": three of four were restored by hand
and one sat untracked for two days.

The test starts from exactly that state and asserts the next Push reports the
file in `unignored_paths` — the report that would have made the sweep a same-day
finding instead of a two-month-old one — and that the same Push's `git add -A`
re-tracks it.

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

`$ignored` is captured before `git rm --cached`, so echoing it before the rm
named files that are still tracked whenever the rm failed — a false alarm on the
operator-queue entry, the one surface whose whole job is to be trusted. Moved
below the rm, so a failed sweep aborts the `&&` chain and reports nothing, which
is what this code did before #2529 anyway. Pinned by a structural test that also
holds the two post-sweep probes below it.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ct (#2529)

`container_exec_run` reads a whole exec output into memory as one blob, and both
probed sets are unbounded in exactly the cases this code exists for. The
untracked probe runs BEFORE the canonical block is written on a pre-canonical
agent, so nothing is ignored yet and `$HOME` answers with every file under
`.local/lib/python3.13/site-packages`, `.npm` and `.cache`. And `$ignored` is
five figures on the #1596 population — an agent with a committed `node_modules/`,
the 44 GB repos those patterns were written for. Both are the migration moment,
fleet-wide, which is the worst time to ship an unbounded read.

So every probe list is `head`-capped in-container at 2000 lines, with two
properties that keep the report honest rather than merely small:

- The cap is `head -n CAP+1` on the two set-difference operands, so truncation
  announces itself; when either side is truncated `unignored_paths` is SUPPRESSED
  rather than computed, because a difference over a truncated operand invents
  entries that are only "new" because the other side was cut off. The field is
  advisory, and a fiction is worse than a gap.
- The removed count is emitted separately and exactly (`wc -l` over the full
  list) into `removed_total`, so a capped list never turns into an undercounted
  "untracked N file(s)" — the number is what an operator acts on. It falls back
  to the list length if the count line is missing or unparseable.

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

`_tagged_output_lines` matches by `startswith`, so a tag that is a prefix of
another silently absorbs its lines — and `removed` vs `removed-count` is one
character away from being exactly that.

Also records the delivery in `.plan/issue-2529-delivery.md` (gitignored): AC-by-AC
coverage for the original seven plus the four revised criteria, the two
structural decisions with the measurements behind them, the three things found
during implementation that the plan did not anticipate, and every verification
command with its actual result.

Co-Authored-By: Claude Opus 5 <[email protected]>
Review found the mirror of this issue's own bug. Hoisting the defaults
block above the user region is only safe for a default the agent may
genuinely override, and `.ssh/` is not one — `credential_paths.py`
classifies `.ssh/id_*` as secret material. It sat in the OVERRIDABLE
region because floor membership was drawn around the constant's
"Credentials — NEVER COMMIT" comment heading, and `.ssh/` lives under
"Instance-specific directories".

Reproduced on the live fleet shape, not argued: an agent whose
`.gitignore` carries `!.ssh` with no `.ssh/` line of its own (every
pre-#2529 Push appended the canonical block BELOW that negation, so
`.ssh/id_rsa` was ignored) comes out of the rebuild with `.ssh/id_rsa`
NOT ignored, and the unattended 15-minute `git add -A` then commits a
private key to the owner's GitHub repo. That is Decision 1's own
`!.env` hazard, one directory over.

Floor membership is now decided against `credential_paths.py` and
pinned both ways: a behavioural regression test that reproduces the
live shape end-to-end (RED without this commit) and a membership
assertion, so adding a credential-bearing pattern to the overridable
region has to be a decision someone makes on purpose.

The 14 bundled templates are regenerated — they are the merge's own
fixed point, so `.ssh/` moves with it.

Co-Authored-By: Claude Opus 5 <[email protected]>
…#2529)

Every reporting surface gated on `sweep.removed`, so the addition half
of the rebuild was exactly as silent as the deletions this issue exists
to end — and the addition is the worse half. A removal is recoverable
from the working tree; a newly un-ignored path is already in the
remote's history and may need a credential rotated rather than a file
restored. The `.ssh/` case in the previous commit produced
`unignored_paths` correctly and reported it through none of the five.

`GitignoreSweep.changed_tracking` (`removed OR unignored`) is now the
single gate for the operator-queue entry, the commit-message body, the
`message` summary line and the toast. `shadowed` is deliberately NOT in
it — standing advice about the file, not a change this Push made, so
including it would file an alert on every Push of every agent that has
a dir-form negation.

An unignored-ONLY entry files at `medium`, not `high`: `unignored` is
`after − before` across two execs against a live container, so a file
the agent's own session creates in that window lands there too, whereas
a removal is a confirmed destructive act. A band that cries wolf stops
being read.

Co-Authored-By: Claude Opus 5 <[email protected]>
…lizes it (#2529)

The recovery snippet told the reader to hand-move the appended line above
the floor markers. Unnecessary: the negation is not a managed line, so the
next merge carries it into the user region automatically, where it already
beats the defaults block. The instruction only invited manual editing
inside a region the merge rewrites.

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

`_with_sweep` populating `GitSyncResult` is only half of AC-4's API half:
`routers/git.py::sync_to_github` hand-builds its response dict and drops
anything not named in it, so a sweep field can be correct on the model and
invisible to every HTTP and MCP caller (the MCP tool is a passthrough over
this dict). The code comment names the hazard; nothing asserted it.

Two tests, both proven RED by mutating the router:

- the success dict must carry every field `_with_sweep` writes, derived by
  BEHAVIOUR (baseline vs populated result) rather than a hardcoded list — a
  hardcoded list is the same "someone must remember" mechanism that loses the
  field. A fourth sweep field forgotten in the dict now fails here.
- a 409 raises `HTTPException`, which keeps only `detail`, so the folded
  summary is the whole structured surface — pinned alongside `removed_paths`
  on the #905 audit row, the durable half. The sweep mutates the index before
  the push, so a failed Push has untracked the files just as surely as a 200.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TvPBC72QFs1kXSA7YUyiS1
Three conflicts, all "both sides added at the same insertion point":

- `operator_queue_service.py` — ent#499 (#2568) added `workspace_problem_report`
  to `_BUDGETED_ALERT_TYPES` and `workspace-problem-` to `_RESERVED_ID_PREFIXES`;
  #2529 adds `gitignore_untracked` / `gitignore-untracked-` to the same two.
  Pure additions, both kept.

  Real interaction, not just a textual merge: ent#499 introduced
  `is_platform_minted`, keyed on `_RESERVED_ID_PREFIXES`. Listing
  `gitignore-untracked-` there therefore ALSO keeps the sweep alert out of the
  agent's own `~/.trinity/operator-queue.json` write-back. That is the correct
  outcome — the sweep alarm is a platform alarm ABOUT the agent, not a loop the
  agent opened and is waiting on — so the prefix comment now records it rather
  than leaving a future reader to rediscover it. Verified by executing the
  predicate against the id `git_service` actually emits.

- `docs/memory/learnings.md`, `docs/memory/feature-flows.md` — newest-first
  lists, both sides prepended an entry. Both kept.

Merged tree re-verified: 2027 passed, 4 skipped across every `git_service`- and
`operator_queue`-touching unit test plus `test_models_centralized`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TvPBC72QFs1kXSA7YUyiS1
@AndriiPasternak31
AndriiPasternak31 requested review from dolho, trinity-ability and vybe and removed request for dolho and trinity-ability September 7, 2026 22:08
@AndriiPasternak31 AndriiPasternak31 self-assigned this Sep 7, 2026
@AndriiPasternak31
AndriiPasternak31 marked this pull request as ready for review September 7, 2026 22:15

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

/review — PR #2595 (AndriiPasternak31/issue-2529 → dev)

Files: 35 (+3318/−891) · Scope: CLEAN — all five ACs addressed, and the two-region split is a better answer than either option the issue proposed ("write canonical above user rules, or re-append the file's negations").

Verified locally: pytest tests/unit/test_2529_gitignore_precedence.py test_1908_bundled_template_gitignore.py test_2069_gitignore_at_creation.py test_github_init_gitignore.py test_ent123_tokenless_clone.py → 225 passed. Partition checked by hand against the real constant: floor order is .env, .env.*, .mcp.json, credentials.json, *.pem, *.key, .ssh/, .trinity/*, !.trinity/…×8, !.env.example, !.mcp.json.template — every exclusion precedes its own negation, which is the property the whole design rests on.

The reasoning I want to record as correct, because a reviewer six months from now will be tempted to "simplify" it:

  • Two regions, not one hoist. A single hoisted block cannot carry both "defaults the agent may override" and "guarantees it may not", and the failure mode of getting that wrong is not cosmetic — a fleet-wide !.env that is inert today becomes live, and the unattended 15-minute git add -A commits the credential file to the owner's own GitHub repo. Deriving the split from _GITIGNORE_PROTECTED inside the one builder, with the import-time subset assert, is what stops the two lists drifting.
  • .ssh/ promoted to the floor after review reproduced it. That is the single most valuable line in the diff.
  • shadowed reads the deciding PATTERN TEXT, never check-ignore's exit code. git check-ignore -v exits 0 even when a negation wins; a reviewer checking rc would have shipped an inverted report. The verification note (.env.example → plain_rc=1, verbose_rc=0) is exactly the evidence that belongs in a comment.
  • Never reimplementing gitignore matching, and assembling the grep | sed | git check-ignore pipeline in-container so agent-controlled .gitignore bytes never reach a backend-side bash -c payload.
  • The four shell details (grep status inspected instead of || true, -a for NUL bytes, CR-suffixed strip entries, [ -e ] || : > instead of touch) each describe a way the user's rules get destroyed. The || true one in particular — status swallowed, block-only temp file, mv succeeds because it needs directory write permission — is the kind of thing that only shows up on a mode-000 file in production.

Critical

None introduced by this PR. But see below — this is the audit where one belongs.

Security gap — pre-existing, and this is the PR to close it in

[S1] .claude/.credentials.json is not in _GITIGNORE_PATTERNS at all (Confidence: 8/10)
src/backend/services/git_service.py:1439-1451 (the .claude/* run)

The canonical list covers .claude/projects/, statsig/, todos/, debug/, sessions/, shell-snapshots/, plugins/, settings.json, remote-settings.json, policy-limits.json, backups/, .last-cleanup — and not .claude/.credentials.json. Grepping the branch, that path appears in exactly two places, neither of them an ignore rule:

  • git_service.py:500 — DEFAULT_PERSISTENT_STATE, i.e. the platform's own list of things that must survive a reset, sitting between .mcp.json and .claude.json;
  • docker/base-image/agent_server/routers/files.py:257 — a denylist, i.e. the platform's own statement that it is secret material.

So the platform believes the file exists and believes it is a credential, and nothing ignores it. If it is present on an agent, the 15-minute auto-sync's git add -A commits Claude Code's OAuth credential store into the owner's GitHub repo. It does not usually exist (Trinity authenticates via CLAUDE_CODE_OAUTH_TOKEN in the environment) — which is why this has not bitten — but "usually absent" is not a control.

This is the same catch as .ssh/, one file over, and the diff's own words are the argument: "it is here because review caught it MISSING." The fix is one line in _GITIGNORE_CREDENTIAL_PATTERNS + _GITIGNORE_PATTERNS, plus python tests/unit/test_1908_bundled_template_gitignore.py --regenerate, which this PR is already running.

[S2] .claude.json sits in the overridable TOP region while its DEFAULT_PERSISTENT_STATE sibling .mcp.json sits in the floor (Confidence: 6/10)

Same list, same block, opposite treatment. .claude.json is Claude Code's user config and can carry mcpServers entries with env/headers; #1705's stated position is that the plugins manifest is committable precisely because .claude.json is not "secret-free". Nothing in #2529 asks for .claude.json to be agent-overridable, so the asymmetry looks like an artifact of the partition rather than a decision. .claude/settings.json staying overridable IS a decision (#2036's hatch, and the issue names it) — worth stating the .claude.json call explicitly either way, since the next person will read the partition as the record of what was considered.

Informational

[I1] _augment_commit_message reproduces the agent-server default with naive local time (Confidence: 7/10)
src/backend/services/git_service.py:2345

subject = message or f"Trinity sync: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"

datetime.now() is the backend container's local clock, and the repo's convention for a stamped string is utc_now_iso() (Invariant #16's write-side lesson, #1474). The value only ever lands in a commit subject so nothing parses it, but the agent server's own default is generated on the agent's clock — so the same fleet now writes two differently-derived "Trinity sync: …" subjects depending on whether the sweep changed tracking. One call to the helper that is already imported in this module.

[I2] The merge exec's leading probe puts an unbounded git ls-files --others under a 10s timeout (Confidence: 6/10)
src/backend/services/git_service.py (_build_gitignore_merge_command, first group)

The head -n CAP+1 does bound it — SIGPIPE stops the walk — and the cap comment names exactly the right population (a pre-canonical agent where nothing is ignored yet, so $HOME answers with all of site-packages/.npm/.cache). Recording it because the failure direction changed: before this PR the merge command was grep/echo only and could not plausibly time out; now a timeout on the probe takes the whole merge with it (the exception path returns the empty sweep and the rebuild never applies), so the #1596 44 GB population is the one where the migration silently does not run. If you want a belt, timeout 5 git ls-files … inside the group would fail the probe alone rather than the merge; not worth it if the SIGPIPE reasoning holds on a real large agent, which is worth one manual check before this reaches the fleet.

[I3] unignored contamination is documented but the field ships to three surfaces (Confidence: 6/10)

The docstring is honest that after − before spans two execs against a live container, so a file the agent's own session creates in that window is reported as newly un-ignored. That is fine for the operator-queue entry and the commit message. It is slightly less fine on the toast (N newly un-ignored and committed), which asserts a causal claim about this Push. Wording it as "N path(s) newly tracked by this sync (may include files the agent just wrote)" would cost nothing and keeps the surface honest at the same level the docstring is.

Clean

  • AC audit: (1) two-region rebuild means an agent negation in the user region beats every TOP pattern — the .claude/settings.json and .env.example incidents both close; (2) canonical order preserved with negations after their exclusions, verified against the real constant; (3) !.env.example + !.mcp.json.template in _GITIGNORE_PATTERNS, ALLOWED_NON_CANONICAL emptied; (4) reported on all four returns of sync_to_github plus the MCP tool description, the toast, the commit message and a durable operator-queue entry; (5) regression tests present and green.
  • The operator-queue routing is the right seam: create_bounded_alert (not a direct create) because git_sync is an MCP tool an agent-scoped key can call on itself, and gitignore-untracked- added to _RESERVED_ID_PREFIXES so an agent cannot pre-create the id of an alarm about itself and silence it through ON CONFLICT DO NOTHING. That is #1677's classification applied correctly rather than by analogy.
  • Injection: every interpolated value goes through shlex.quote; the strip list is grep -vxF (whole-line, fixed-string) and empty/newline entries are rejected at import, so no user rule metacharacter can be caught by accident.
  • _coerce_sweep is justified by a named test rather than added as reflexive defensiveness.
  • Reporting can never fail a Push: every probe group ends in :, the sweep itself stays in the && chain, and _migrate_workspace_gitignore returns the empty sweep on every failure path — so callers read the fields unconditionally.
  • removed_total separate from len(removed) so a capped list never becomes an undercounted claim; and unignored is suppressed outright when either operand truncated, rather than reporting a set difference of two prefixes.

Summary

Critical: 0 introduced · Security gaps: 2 pre-existing (S1 worth closing here) · Informational: 3 · Scope: clean.

Approving. Not blocking on S1 despite its class: it is pre-existing, it needs a file that is normally absent, and holding this PR keeps the silent untracking — a confirmed, twice-observed, currently-active data loss — in the fleet for longer. But this is the canonical-ignore-list audit, S1 is one line plus the --regenerate you are already running, and I'd much rather it land here than as a follow-up nobody files.

@github-actions

github-actions Bot commented Sep 8, 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.

# Conflicts:
#	docs/memory/feature-flows.md
#	docs/memory/learnings.md
@vybe
vybe merged commit 4c5fde2 into dev Sep 8, 2026
28 of 29 checks passed
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown

⚠️ Live-instance suite skipped — merge conflict against dev.

Resolve by merging dev locally and pushing the result; the next nightly re-tests.

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