# Git Progress Tracking Strategy

## Goal

Use Git as an optional runtime evidence layer for Omnius agent sessions. When a project already has Git, Omnius should track its own mutations with the same discipline a careful implementer uses manually: baseline status, scoped diffs, changed-file summaries, verifier results after changes, and recovery artifacts.

This should not replace todos, workboard cards, or verifier gates. Git becomes a concrete backing signal for what changed, who changed it, whether it is verified, and what can be safely summarized to the user.

## Implementation Status

Phase 0 and the context-exposure part of Phase 1 are wired in the orchestrator runtime:

- `GitProgressState` captures baseline Git status, current dirty/untracked state, changed paths since the run baseline, touched pre-existing dirty files, and owned-scope warnings.
- `AgenticRunner` initializes Git progress at run start and refreshes it after confirmed file or mutating-shell changes.
- The active context frame now includes a first-class `git_state` section, plus next-action-contract hints for safe Git evidence commands.
- Summaries are persisted to `.omnius/git-progress/latest.json`, session checkpoints, debug tool events, and trajectory logs.

Still deliberately not implemented: auto-init, auto-commit, stash/reset/checkout/clean behavior, patch-bundle rollback, and per-sub-agent worktrees.

## Non-Goals

- Do not auto-commit by default.
- Do not hide, stash, reset, checkout, or discard user changes without explicit approval.
- Do not require Git for Omnius to operate.
- Do not make Git the source of truth for todo state.
- Do not wholesale replace the current mutation contract with branches or worktrees.

## Runtime Principles

1. Preserve user work first.
   Omnius must treat pre-existing dirty files as user-owned unless the session explicitly mutates them under an active contract.

2. Observe before changing.
   At session start, capture repo root, current branch, HEAD, dirty files, untracked files, ignored state summary, and whether the repo has an upstream.

3. Attribute agent mutations.
   After each mutating tool call, record changed paths, diff stat, name-status, and whether the mutation was inside the current owned-file scope.

4. Verify after relevant mutation.
   Git evidence can support completion, but it cannot replace live verifier evidence. A clean or expected diff is not proof that the build passes.

5. Keep recovery cheap.
   Persist patch bundles and file hashes for Omnius-authored changes so the user can inspect or request rollback of agent changes without touching unrelated dirty work.

6. Make the UI compact.
   Surface changed-file counts, last checkpoint, dirty status, and verifier freshness in the TUI without dumping full diffs into the main transcript.

## Proposed Runtime State

```ts
export interface GitProgressState {
  enabled: boolean;
  available: boolean;
  repoRoot: string | null;
  branch: string | null;
  head: string | null;
  baselineDirtyPaths: string[];
  baselineUntrackedPaths: string[];
  sessionId: string;
  sessionRef?: string;
  checkpoints: GitCheckpoint[];
  lastChangeSet?: GitChangeSet;
}

export interface GitChangeSet {
  turn: number;
  actor: "main" | "sub_agent" | "runtime";
  owner?: string;
  toolName: string;
  changedPaths: string[];
  addedPaths: string[];
  deletedPaths: string[];
  renamedPaths: Array<{ from: string; to: string }>;
  diffStat: string;
  nameStatus: string;
  outsideOwnedScope: string[];
  verifierCommand?: string;
  verifierFreshAfterChange: boolean;
}

export interface GitCheckpoint {
  id: string;
  turn: number;
  kind: "baseline" | "patch_bundle" | "commit" | "worktree_merge";
  head: string | null;
  patchPath?: string;
  commitSha?: string;
  changedPaths: string[];
  verifierCommand?: string;
  verifierPassed?: boolean;
}
```

## Behavior

### 1. Repository Detection

At agentic run startup:

- Run `git rev-parse --show-toplevel`.
- If it succeeds, set `GitProgressState.enabled = true`.
- Capture `git status --porcelain=v1 -z`, `git branch --show-current`, and `git rev-parse HEAD`.
- Mark all existing dirty and untracked files as baseline user state.
- Store the baseline in the run trajectory and debug artifacts.

If Git is unavailable or the project is not a repo:

- Keep Omnius fully functional.
- Record `GitProgressState.enabled = false`.
- Offer an opt-in strategy note in the trajectory: `git init available, not performed`.

### 2. Optional Auto-Init

Omnius may initialize Git only when explicitly enabled by config or user consent:

- `OMNIUS_GIT_AUTO_INIT=1`
- or a future setting such as `agent.git.autoInit = true`
- or a direct user command

Auto-init must:

- run only in the project root Omnius is operating on;
- create an initial baseline commit only when requested;
- otherwise keep an uncommitted initialized repo and record that no baseline commit exists;
- never add ignored files unless the user asks.

### 3. Mutation Tracking

After every file mutation and shell command classified as mutating:

- Re-run `git status --porcelain=v1 -z`.
- Compute changed paths relative to the captured baseline.
- Compute `git diff --stat` and `git diff --name-status`.
- For untracked files, include path and size metadata.
- Compare changed paths to mutation contract `owned_files`.
- Emit a typed runtime event:
  - `git_progress_change_detected`
  - `git_progress_scope_warning`
  - `git_progress_checkpoint_created`
  - `git_progress_verifier_fresh`
  - `git_progress_completion_blocked`

Git telemetry should be attached to:

- todo evidence for the active leaf;
- workboard card evidence;
- end-of-run trajectory;
- debug artifacts.

### 4. Checkpoints

Initial implementation should prefer patch bundles over commits:

- Save `git diff --binary` to `.omnius/git-snapshots/<session>/<turn>.patch`.
- Save metadata JSON with turn, actor, tool, changed paths, verifier state, and owned scope.
- Never apply or reverse patches automatically.

Optional checkpoint commits can be a later opt-in:

- create branch `omnius/<session-id>`;
- commit only Omnius-authored changes;
- include verifier state in commit message trailers;
- never commit baseline user dirt unless explicitly included.

### 5. Sub-Agent Strategy

For sub-agents, Git should improve isolation without requiring every task to become a separate branch immediately.

Phase 1:

- main runner records per-sub-agent changed paths;
- mutation contracts enforce owned files;
- sub-agent completion summaries are backed by diff stats and verifier freshness;
- parent completion is never satisfied by sub-agent `task_complete` alone.

Phase 2:

- assign each sub-agent a patch bundle namespace;
- require sub-agent output to include patch evidence for its owned files;
- detect conflicting changes before merging into the parent run state.

Phase 3:

- optionally use `git worktree` per sub-agent when repo size and task scope justify it;
- merge with normal Git conflict detection;
- surface conflicts as workboard cards instead of letting the model guess.

### 6. Completion Gate

Before accepting `task_complete`, Omnius should check:

- every open todo leaf is complete or explicitly blocked;
- no active mutation contract has unverified changes;
- final verifier passed live after the last relevant mutation;
- Git changed paths are summarized;
- outside-owned-scope changes are either approved or unresolved;
- baseline user dirty files were not silently modified unless they were in scope.

If blocked, the message should include:

- changed paths since baseline;
- paths outside the active owned scope;
- last verifier command;
- last verifier turn;
- required next action.

### 7. TUI Surface

Add a compact Git state presenter near the existing bottom status area:

- branch and dirty count;
- Omnius-authored changed-file count;
- last checkpoint id or patch bundle turn;
- last verifier freshness marker;
- warning marker if an agent changed files outside owned scope.

The detailed diff stays in a modal, debug artifact, or command output, not in the main status row.

## Implementation Phases

### Phase 0: Observe-Only Git Telemetry

- Add Git detector to the orchestrator runtime.
- Capture baseline repo state at session start.
- Record post-mutation `status`, `diff --stat`, and `name-status`.
- Add trajectory/debug artifact output.
- No commits, no branches, no auto-init.

### Phase 1: Diff-Aware Todo And Workboard Evidence

- Attach changed paths and diff stat to active leaf todo evidence.
- Mirror Git change sets into workboard cards.
- Show owner, active leaf, changed-file count, and verifier freshness in the TUI.
- Block completion when Git says files changed after the last accepted verifier.

### Phase 2: Patch Bundle Checkpoints

- Write `.omnius/git-snapshots/<session>/<turn>.patch` after agent mutations.
- Add metadata JSON and retention policy.
- Add a read-only inspection command for checkpoint history.
- Do not auto-apply rollback.

### Phase 3: Opt-In Auto-Init And Checkpoint Commits

- Add config for `git.autoInit`, `git.checkpointCommits`, and `git.commitMessageTemplate`.
- Support initialized repos without baseline commits.
- Support optional `omnius/<session>` checkpoint branches.
- Keep default behavior non-committing.

### Phase 4: Sub-Agent Worktree Integration

- Create per-sub-agent worktrees only when enabled.
- Use owned-file contracts to limit merge inputs.
- Convert merge conflicts into explicit workboard cards.
- Require parent verifier pass after merged sub-agent changes.

## Tests

Add orchestrator tests for:

- repo detection with clean, dirty, and untracked baselines;
- non-Git projects continuing without Git state;
- post-mutation changed path attribution;
- pre-existing dirty user files not counted as Omnius-authored unless touched;
- completion blocked when changed files exist after last verifier;
- patch bundle creation and metadata contents;
- outside-owned-scope change warning;
- sub-agent diff evidence not satisfying parent completion;
- opt-in auto-init guarded by config.

Add CLI/TUI tests for:

- Git status presenter renders compactly;
- dirty count updates on refresh;
- warning marker appears for outside-owned-scope changes;
- no full diff is dumped into the status row.

## First Concrete Slice

Implement Phase 0 and part of Phase 1:

1. Add `git-progress.ts` in `packages/orchestrator/src`.
2. Capture baseline in `AgenticRunner` at run start.
3. Call a post-mutation Git refresh from the same path that invalidates verifier evidence.
4. Add Git change summaries to trajectory/debug artifacts.
5. Surface changed-file count and verifier freshness in the TUI status model.
6. Add tests using temporary Git repos.

This gives Omnius immediate visibility into agent-caused changes without changing user workflow or introducing risky write behavior.
