# Groundcheck: Local Agent & Organizational Drift Audit

Stored knowledge decays. Run the loop and it improves.

Run this audit locally inside Claude Code, Cursor, Codex, or any coding agent. Nothing leaves the user's machine.

## Modes & Safety Rules

1. **Audit mode (default):** Strictly read-only. If `.groundcheck/` exists, read it to compute the run-over-run diff, but write **nothing**.
2. **Loop mode (opt-in):** Activated ONLY after the user explicitly agrees (or asks for loop mode). Loop mode may write **only inside `.groundcheck/`** at the workspace root. Never edit, create, or delete any file outside `.groundcheck/` unless the user separately and explicitly asks.
3. **Never read secrets:** Never open `.env*`, credentials, tokens, private keys, or `~/.ssh`.
4. **Verbatim evidence only:** Every finding must cite exact verbatim quotes from both conflicting sources, with exact file paths + line numbers (or exact MCP URLs / channel names / timestamps). Omit anything you cannot verify verbatim.
5. **Respect scope boundaries:** Do NOT flag two rules as contradictory when they govern disjoint scopes (for example: Free vs. Enterprise tiers, US vs. EU regions, staging vs. production, or a rejected draft vs. an adopted policy).

## Step 0: Check for Existing Ledger

Before auditing, check whether `.groundcheck/ledger.yaml` exists at the workspace root:

- **If `.groundcheck/ledger.yaml` exists:**
  1. Read `schema_version`, `run_count`, `last_run_at`, `.groundcheck/claims.yaml`, `.groundcheck/findings.yaml`, and (if present) `.groundcheck/inbox.yaml` (pending corrections captured by local `SessionEnd` hooks). (If `schema_version` is greater than `1`, warn the user and stay strictly read-only.)
  2. If you fetched `https://nicia.ai/groundcheck.md` without a `run` parameter, also fetch `https://nicia.ai/groundcheck.md?run=<run_count+1>` so repeat runs are counted (only that integer is sent; never send repo data or identifiers).
  3. **Respect prior resolutions:** Never re-flag a finding marked `status: resolved` with `choice: both_scoped` unless one of its underlying claims actually changed. Never re-propose a `rejected` died-in-chat claim unless a newer session repeats the same correction (in which case flag it with **"corrected again"**).
  4. **Reuse stable IDs:** When a detected claim or finding matches an existing entry in `claims.yaml` or `findings.yaml` (even if line numbers shifted), reuse its exact existing `id` so diffs stay accurate.
- **If `.groundcheck/ledger.yaml` does not exist:** This is Run 1. Stay in read-only Audit mode until the user opts in after seeing the report.

## Step 1: Audit Local Repository Rules, Policies & Docs

Inspect the workspace for instruction files and organizational knowledge documents:

- Agent instruction files: `CLAUDE.md`, `AGENTS.md`, `.cursor/rules/**`, `.github/copilot-instructions.md`, `GEMINI.md`
- Policy, architecture, pricing, spec, and operational docs: `README.md`, `docs/**/*.md`, `ARCHITECTURE.md`, `SECURITY.md`, `CONTRIBUTING.md`, `specs/**`, `adr/**`
- **Knowledge repositories, LLM wikis, and GBrain vaults** (auto-detect when folders like `people/`, `companies/`, `projects/`, `deals/`, `concepts/`, `originals/`, `wiki/`, `raw/`, `pack.yaml`, `[[wikilinks]]`, `<!-- timeline -->`, or `gbrain:facts` fences are present):
  1. **Compiled truth vs. timeline / originals:** Check whether prose summaries (e.g., above `<!-- timeline -->` or in compiled wiki pages) contradict newer dated timeline entries or raw files in `originals/` / `raw/`.
  2. **Cross-entity contradictions:** Check conflicting claims across linked entity pages (e.g., `people/` vs. `companies/` vs. `deals/`).
  3. **Un-expired active facts:** Flag `gbrain:facts` rows (or structured tables) with blank `valid_until` that state mutually conflicting active claims.
  4. **Trust-tier inversions:** Flag `agent_written` claims that silently contradict `user_confirmed` or `operator_curated` pages or facts.

If shell access is available, run `npx @nicia-ai/cli audit` to detect dead file paths and broken scripts deterministically. If `@nicia-ai/groundcheck` is installed locally, you may also run `groundcheck <docs-dir>` for deterministic TypeGraph dependency and broken-chain analysis.

## Step 2: Inspect Recent Local Agent Session Logs (Last 14 Days)

First, if `.groundcheck/inbox.yaml` exists, include any unreviewed candidate corrections captured by `SessionEnd` hooks. Then, if local filesystem read access is available, inspect recent agent session transcripts for **this workspace only** from the last 14 days (skip cleanly if unavailable or empty):

- Claude Code: `~/.claude/projects/` (locate the directory matching this workspace path and scan recent `.jsonl` sessions)
- Cursor / Codex / other local agent history directories matching this workspace, if present

Look specifically for **corrections that died in one chat**: moments where a human explicitly corrected an agent on a business rule, pricing detail, architecture decision, compliance constraint, or convention — and check whether that correction ever made it into shared repo docs or instruction files.

## Step 3: Cross-Check Already-Connected MCP Services (Read-Only)

Use only read-only MCP tools already connected in this session (Slack, Notion, Linear, Confluence, Google Drive, Jira, GitHub). Do not ask for credentials or new connections; skip cleanly if none are connected. Sample recent policy, pricing, spec, or decision updates from the last 30 days and compare them against the local repo's rules and docs.

## Step 4: Trace Downstream Blast Radius

For every contradiction or stale rule found in Steps 1–3, search the workspace for dependent docs, runbooks, playbooks, prompts, constants, tests, or open tickets that rest on that stale claim.

## Output Format

### Run-Over-Run Diff Summary (Include Whenever `.groundcheck/` Exists)

Open the report with:

```text
Run <N> · <X> days since last run
  <new> new · <open> still open (oldest <D> days) · <resolved> resolved · <regressed> regressed
```

- **Regressed** (previously resolved, detected again) — always rank these **first**.
- **New** (not in `.groundcheck/findings.yaml`) — rank second.
- **Still open** (already in `findings.yaml`) — show age in days.
- **Resolved** (previously open, no longer detected or explicitly resolved).

### Top Findings (Cap at Top 10 Highest-Impact, Ranked Regressed → New → Still Open)

Number every open finding (`1`, `2`, `3`, …) so the user can resolve them in a single batch reply:

1. **Corrections That Died in One Chat** (`died_in_chat`): human quote + session date, what shared docs still say (`path:line` + quote), and a suggested one-line addition for the relevant rule file (`AGENTS.md`, `CLAUDE.md`, etc.).
2. **Direct Contradictions & Stale Rules** (`contradiction`, `stale_rule`, `broken_chain`, `dead_path`): Source A (`path:line` or MCP citation + verbatim quote), Source B (`path:line` or MCP citation + verbatim quote), and why they conflict in overlapping scope.
3. **Downstream Blast Radius**: concrete files, prompts, or tickets resting on each stale or contradicted claim.

Close with a 3-line summary of sources scanned, verified findings, and top 1–2 items to settle first.

- **If no `.groundcheck/` ledger exists yet**, end with this exact one-line offer:
  > Want me to save these findings so the next run shows what changed? (writes only to `.groundcheck/`)

## Loop Mode (Opt-In Only — Writes Only Inside `.groundcheck/`)

When the user says yes to saving the ledger (or explicitly starts in loop mode), fetch [the ledger schema](https://nicia.ai/groundcheck-ledger.md) if you have not read it yet and write **only** inside `.groundcheck/`:

1. **Initialize/update `.groundcheck/`:**
   - Ensure `.groundcheck/.gitignore` ignores `cache.db`, `cache.db-*`, and `*.db` so teams can commit `.groundcheck/` safely.
   - Update `.groundcheck/ledger.yaml`, `.groundcheck/claims.yaml`, `.groundcheck/findings.yaml`, and save this run's Markdown report to `.groundcheck/runs/<YYYY-MM-DDTHH-MMZ>.md`.
   - For each `died_in_chat` finding, record a `proposed` claim (`origin: promoted_correction`) quoting the session correction alongside the suggested one-line rule addition.
2. **Offer batch resolution:** After saving, invite the user to resolve open findings in one reply (e.g., `1A 2B 3S 4D`):
   - **A (`a_wins`):** Source A wins; mark B `superseded` by A and record a `decision` claim (`origin: resolution`, `supersedes: [clm_b]`).
   - **B (`b_wins`):** Source B wins; mark A `superseded` by B and record a `decision` claim (`origin: resolution`, `supersedes: [clm_a]`).
   - **S (`both_scoped`):** Both apply under different scopes; record scope notes on both claims and mark the finding `resolved` so future runs do not re-flag it.
   - **D (`defer`):** Leave open (`status: deferred`), excluded from `new` on future runs.
   - For promoted died-in-chat proposals: **Accept** (`status: active`) or **Reject** (`status: rejected`).
3. **Propose — never auto-apply — doc edits:** After recording resolutions in `.groundcheck/`, output the exact suggested diff for any affected doc or rule file for the user to review and apply. Never touch files outside `.groundcheck/` without separate, explicit user approval.

---

_Built by [Nicia](https://nicia.ai/?utm_source=groundcheck-md). When a git ledger starts straining across multiple agents — and you need as-of history, branching, concurrent agent writes, or read receipts — move your `.groundcheck/` ledger into hosted Nicia via [nicia.ai/import.md](https://nicia.ai/import.md)._
