# repo-context-ledger

Adopt this skill: https://proskills.md/skills/other/gviiisen-repo-context-ledger-skills-repo-context-ledger

Page: https://proskills.md/skills/other/gviiisen-repo-context-ledger-skills-repo-context-ledger
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/repo-context-ledger/SKILL.md
size: 11265
sha: bd8df7821e461bc57839f1a11b4738aa937ff311
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/SKILL.md

````text
---
name: repo-context-ledger
description: Record every behavior-changing feature addition, fix, and adjustment as durable, evidence-based repository knowledge, then use that ledger to continue accurately across AI windows, tools, Git collaboration, and pull requests. Use the deterministic runtime to route bounded context, isolate private drafts, publish verified change records, refresh stable feature knowledge, and keep native Codex, Claude, Cursor, Copilot, Grok, and other Agent entry points aligned without asking the user to run bookkeeping commands.
---

# Repo Context Ledger

Turn behavior-changing feature work into durable, code-verified repository knowledge. Git-tracked Packs, specs, and completed Changes form the feature change ledger; cross-window and cross-Agent continuation are capabilities built on that shared source. Private vendor Memory is never read or synchronized.

## First decide what is new — without a Ledger call

Judge new facts/effects from the current request, loaded conversation, known task and inspected code, not similar wording. Do this mentally: no classifier command, extra document, or automatic Git/Markdown rescan.

- Routine question/recheck/operation with sufficient context: answer or execute the authorized request normally, without a new Ledger lifecycle. Do not skip a requested recheck or infer permission to repeat side effects.
- Same known unfinished task: keep its session/epoch and background; add only new changes, findings, decisions and checks. Same-window "continue" does not require resume or a new session.
- Similar work with new behavior/inputs/paths: reuse the method, not a previous pass. Keep a suitable unfinished task; after publication create a new change record and reference relevant history. Independent deliverables stay separate.
- Missing identity/background: query only what is missing. Paused tasks and actual handovers need resume; lifecycle writes still validate ownership/epoch. Resolve stale state rather than guessing.

Proceed when scope/identity are clear, without announcing a classification checklist. Reuse results only while relevant code, inputs, environment and acceptance phase remain valid. Changed conditions and time-sensitive safety checks need fresh verification; never relabel an old pass as new. Investigate uncertain code boundaries.

## Runtime

Resolve this Skill directory. Its runtime is `scripts/ledger.py`. After initialization use the repository entry:

```text
python .context-ledger/ledger.py <command>
```

Use `python3` when needed. `--repo` is optional; discovery walks upward to the nearest `.context-ledger/config.json` and stops at nested Git boundaries.

In `runtime.mode: global`, that entry is a small forwarder to the Codex Skill under `CODEX_HOME/skills` (or the user's `.codex/skills`); configuration and records remain repository-local. If the entry is absent, invoke this installed Skill's runtime with explicit `--repo <project>`. Never initialize or copy an old runtime just to execute a command. See [global-runtime.md](references/global-runtime.md) only for runtime installation/migration.

## Plan only when routing is needed

When the decision above leaves task identity or required context unresolved, run:

```text
python .context-ledger/ledger.py plan --query "<user request>" --tool <agent>
```

Follow the returned `workflow-plan-v1` mode and `next_action`:

- `readonly`: load bounded context only; never create a session.
- `small-fix`: start one short session, edit the known boundary, verify, finish.
- `ordinary-change`: route the Pack/spec, start one session, implement, verify, refresh stable knowledge, finish.
- `resume`: resume only one uniquely selected accessible session and keep its new epoch.

Automatic classification is guidance, not permission. If `requires_confirmation` is true, clarify the workflow or select a session; never guess. `start --workflow readonly|resume` must fail. `context` returns the same nested Workflow Plan, and `resume --query` uses the same owned-session route.

## Non-negotiable safety

- Never read, pause, resume, checkpoint, finish, invalidate, or expose another principal's private task unless an explicit unexpired grant permits that exact access.
- Never message, delegate to, steer, or interrupt another user-owned Agent task unless the user explicitly requests cross-task coordination.
- The ledger isolates documentation sessions only. It does not lock, copy, merge, or coordinate source-code edits; leave code conflicts to the host Agent and Git.
- Read only Context Bundle `required_reads` initially. Never recursively load `docs/ai`, `docs/specs`, or `docs/changes`. This is a starting route, not a cap: expand through every behavior-relevant caller, implementation, configuration, persistence, permission, concurrency, retry, test, and external boundary.
- Prefer code and executed verification over specs, specs over Packs, and Git-tracked knowledge over private Agent Memory.
- Do not create a handoff for read-only analysis, questions, or formatting-only work.
- Do not ask the user to run ledger bookkeeping commands.
- One bounded logical request gets one session and one completed Change. Archive once, but update the same draft when meaningful facts emerge. Before a context/window switch, and after a changed diagnosis, key decision, or relevant failed approach, preserve the useful explanation while it is fresh. Use private checkpoints for continuation, not a new Change per step; do not combine unrelated requests or independently deliverable work just to reduce record counts.

## Change lifecycle

1. Keep the session ID and epoch from start/resume; use `status` only when this task's identity or state needs resolving. Pass `--session` on lifecycle writes; never guess or absorb another task.
2. Follow an existing accepted plan. Run context/focus only for missing or changed background, not again for every ordinary-work turn. A known code boundary needs no repeated broad routing.
3. Start once when behavior will change and there is no suitable unfinished task: `start --title "<title>" --feature <feature> --workflow <small-fix|ordinary-change> --tool <agent>`. Reuse only a genuinely related task; never reopen a completed record to hide a new change.
4. Implement after verifying the routed boundary in code. Context docs guide where to look; they never justify reading too little code.
5. Choose acceptance goals before verification. Reads, searches, file/configuration generation, preparation, and authorized deployment use ordinary tools, not a verify wrapper per operation. Run acceptance through `verify` once when first needed; do not run it bare and repeat it just for a Ledger entry. Group related checks with an existing reviewed project script/preset, preserving step results and failure exit codes. Keep pre-deployment and post-deployment goals separate. Independent checks may run concurrently only without shared mutable resources; use direct argv, not nested shell strings.
6. Prefer an exact repository preset when configured. If `PRESET_TRUST_REQUIRED` appears, review it and repeat with its exact printed `--trust-digest`; never trust without reviewing. Ordinary operations and useful diagnostic observations belong in the same draft as such, not fabricated managed check results. Never replay a deployment, authorization, migration, or trade to obtain missing logging. See [verification-presets.md](references/verification-presets.md) for grouping and the optional tested script example.
7. A single-session small fix lets `finish` collect evidence. With parallel sessions or a broad dirty tree, run `evidence --path` for this task's paths only.
8. Refresh the related Pack and spec when their facts or dependencies changed. Update only the draft's new differences and correct superseded assumptions; retain useful earlier reasoning rather than rewriting unchanged background. A small-fix form still explains each meaningful change, its file/symbol references, and documentation rationale. Only Updated is generated; share common boundaries and verification rather than repeating them.
9. Remove unresolved template placeholders and finish once the bounded request is actually complete, not at every intermediate reply: `finish --spec <spec>`, or `--no-spec --reason "<why no stable behavior exists>"`. Keep a returned continuation epoch on every resumed write.

Read [production-workflow.md](references/production-workflow.md) for large repositories, verification concurrency, PR baselines, coverage gates, and derived-index timing. Read [writing-quality.md](references/writing-quality.md) before editing an evidence-v1 draft.

Small is a known low-risk boundary, not a line count. Independent behavior changes, permissions, persistence, money, concurrency, public contracts, or uncertain impact need ordinary investigation and records. Expand the same draft when scope grows; preserve its notes and evidence, rather than finishing early or starting over. `finish --dry-run` is optional; do not make it a mandatory extra step or loop through it while still writing. Before finish, reconcile meaningful diff changes against the record; passing structural checks is not proof of complete business explanations.

## Initialize or upgrade

Run `init --dry-run`, review the exact plan, then run the same `init` only when its scope is correct. Preserve prose outside managed markers and all existing completed history. Confirm `adapters check`, `manifest check`, and `doctor`. See [document-model.md](references/document-model.md) for legacy layouts and where facts belong.

## Cross-window continuation

Before switching Agents or windows, run `checkpoint --summary "<state>" --next "<action>"`; use `pause` only when suspending the task. In the new window run `plan --query "continue <keywords>"`, then its explicit resume action. Resume increments the epoch; it does not create a replacement session.

"Continue" inside the same active window is not a handover. If the task and current epoch are already known, continue directly; resume only for an actual handover, paused task, or state recovery.

If several sessions are close matches, choose an explicit session. If only foreign work overlaps, use committed Pack/spec/Change guidance. Private unfinished state does not travel with clone, pull, or another computer.

## Integration and recovery

- Use `doctor` first for bounded read-only diagnosis. It never deletes locks or mutates Packs/sessions.
- At PR/integration time run `policy --base <ref>` for aggregate delta-based checks. Use `audit --history --policy as-recorded --fail-on unresolved` only for controlled historical/release audits, never to unblock an unrelated session.
- After merge, run `sync --derived` once on the configured default branch. Do not hand-edit generated indexes.
- Keep unfinished drafts private. Publish only through `finish`; never persist secrets or machine-specific absolute paths.

## Runtime development

Edit `src/repo_context_ledger/runtime.py.tmpl` and its ordered source fragments, not generated runtimes. Run `python scripts/build_runtime.py` and `python scripts/build_runtime.py --check`; `.context-ledger/ledger.py` and the Skill runtime must remain byte-identical standalone files.
````

## File: skills/repo-context-ledger/scripts/ledger.py
size: 355666
sha: 1d84b22070dfbb543100c3191cbf255bfd0d9c3b
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/scripts/ledger.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/scripts/ledger.py

## File: skills/repo-context-ledger/references/document-model.md
size: 13629
sha: 822f6daacdd74ba523d2873c197725d7c6e265a8
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/references/document-model.md

````text
# Document model

Use three layers of repository knowledge.

New records use `Quality profile: evidence-v1`. Their language and detail metadata come from `.context-ledger/config.json`; legacy documents remain valid and are not rewritten automatically. Use [writing-quality.md](writing-quality.md) for evidence, language, and purpose-specific form rules.

## `docs/ai/`: repository orientation

Store information that applies across features: repository purpose, major modules, shared architecture, environment conventions, and navigation guidance. Keep it concise and link to stable feature specs.

`docs/ai/context-manifest.json` is a derived, machine-readable route index. It lists Context Packs, stable specs, tracked entry paths, source commits, and recent handoffs. Rebuild it from source documents; never treat manual edits to the manifest as canonical knowledge.

### `docs/ai/context-packs/`: minimal feature loading

Keep one compact Context Pack per feature or bounded subsystem. Use it as the first document loaded after a context switch. Record the minimum load order, entry points, contracts, boundaries, verification, stable-spec links, and tracked-file fingerprints.

Context Packs route an agent to current truth; they do not replace stable specs. Refresh a pack after its tracked files change. Strict validation treats changed or missing fingerprints as stale context.

`context --query` is a router over current Context Packs and private sessions available to the current principal. It prefers exact feature, title, tracked path, and path-token matches, excludes superseded/archived Packs from Required reads, penalizes stale fingerprints, and returns one `context-bundle-v1` with a primary Pack, linked specs, selection reason, optional PR baseline, and an optional bounded Resume Capsule for a unique owned active/paused match. It does not rank every Markdown file by word count or persist the Capsule as another document. A reverse index shortlists expensive fingerprint checks while a cheap all-Pack metadata scan remains as a correctness safety net. Pack parsing and file digests may be cached only below Git metadata; cache loss or corruption rebuilds from current files. The Context Manifest may accelerate discovery when it matches live Packs; live Pack metadata remains authoritative because feature branches may defer derived-index updates. Two current Packs may track the same shared file; an explicit `Superseded by` or non-current status makes a Pack cold and ineligible for routing.

`doctor` is a read-only health projection, not a fourth knowledge layer. Its `doctor-v1` report aggregates runtime/configuration, adapters, Manifest, private-state integrity, Pack freshness and lifecycle, local links, and feature-branch derived-file safety. Shared tracked files produce an overlap warning only: the runtime never infers semantic replacement from file overlap. A Pack becomes cold only through explicit non-current status or explicit lineage. Repair suggestions are plans, not mutations.

Use a compact navigation form: `Read first`, `Read if needed`, and `Do not load by default`. Context Packs have a configurable maximum line count.

## `docs/specs/`: current feature truth

Create one document per durable feature, interface, or bounded subsystem. Describe:

- purpose and user-visible behavior;
- entry points and important code paths;
- data flow and external contracts;
- invariants, boundaries, failure modes, and non-goals;
- verification commands;
- related historical changes.

Update this layer when the current implementation changes. Do not append chronological notes to the narrative; the managed related-changes block provides history.

Use a current-state form: concrete path/symbol ownership, input → flow → persistence/dependency → output, boundaries, and reliable verification commands. Never copy a handoff's chronological narration into a spec.

## `docs/changes/`: chronological handoffs

Create one document per behavior-changing task. Explain intent, the actual change, touched code paths, risks, verification, and documentation impact. Completed handoffs remain immutable except for corrections.

Store and index history by month:

```text
docs/changes/README.md
docs/changes/YYYY/MM/README.md
docs/changes/YYYY/MM/<individual-change>.md
```

The root history index lists months only. Each monthly index lists that month's individual changes, preventing a single document from growing without bound.

Each task reserves a unique timestamp/actor/token publication path plus `Handoff ID`, `Session ID`, `Actor`, and `Branch` metadata. The handoff ID is also the lifecycle session ID. While active or paused, the content remains a private draft; only a successful `finish` publishes the completed file.

Use a chronological evidence form: Before/After behavior, path/symbol responsibilities, invariants, failure/recovery, deliberate non-changes, documentation impact, open questions, Git-derived changed paths, and verification executed by the runtime.

Paused drafts keep `Status: paused`, a resume summary, the next action, base commit, and dirty paths. In a Git repository, the task-session map and draft files live under worktree Git metadata. State schema v8 stores each private draft reference, reserved publication path, feature, status, owner principal, continuation epoch/tool, expiring grants, and update time. In a non-Git directory, the fallback lives under `.context-ledger/sessions/`. Agents use `status` and lifecycle commands rather than editing state directly.

An active handoff may also carry `Checkpointed`, `Checkpoint actor`, `Resume summary`, and `Next step`. A checkpoint preserves the task as active so another Agent window using the same human principal can continue it without pretending to import the previous tool's private Memory. The principal is a pseudonymous hash of a configured local identity or OS account, not the Agent tool name and not a Git-tracked secret.

Keyword resume searches active and paused sessions available to that principal. A unique match produces a bounded Resume Capsule on demand; `resume` keeps the same task session, changes the continuation tool, increments its epoch, and requires that epoch on later lifecycle writes. This prevents a stale pre-resume window from writing without first reloading current state. The Capsule is initial navigation, not proof of complete context: the Agent must continue into every caller, implementation, configuration, persistence, permission, concurrency, retry, test, or external boundary that can affect behavior.

Another principal cannot see private Capsule fields or mutate the session by default. It may learn only that a matching foreign scope exists, then use committed Git context. With explicit user authorization, an expiring `read-only` grant exposes only the Capsule, `fork` creates a new recipient-owned child session while preserving the source, and `transfer` changes ownership only after the source is paused and the recipient accepts it. These checks provide logical workflow isolation; filesystem and OS permissions remain the actual security boundary.

When exactly one active or paused session matches an operation, the CLI may infer it for compatibility. When multiple sessions match, it must fail and require `--session <id>`; it must never guess. In a Git worktree with another registered session, evidence capture also requires repeated explicit `--path` values and records only those changed paths. Verification holds the repository write lock only while binding the target session and while appending the completed result, not while the external command runs.

`finish` is a session-scoped publication gate. It validates the selected draft, its recorded evidence paths, explicit specs, and only the relevant fingerprints inside Packs recorded by that session. Foreign dirty paths and unrelated stale Packs remain visible to repository-wide checks but cannot block or contaminate this session's publication. Run `check --strict --coverage` as an integration or PR gate after parallel work settles.

Task-session isolation covers ledger bookkeeping only. The runtime does not copy, lock, merge, claim, or coordinate source files. Native adapters prohibit contacting, steering, pausing, or interrupting another user-owned task unless the user explicitly requested cross-task coordination; source conflicts remain the responsibility of the host Agent and Git.

## Native adapters

Keep Agent-specific entry files thin. `AGENTS.md`, `CLAUDE.md`, Cursor rules, and GitHub Copilot instructions route tools to the same manifest, Context Packs, specs, and handoffs; they do not duplicate feature truth. Preserve prose outside managed markers.

Private vendor Memory is a non-authoritative cache. When it conflicts with the repository, use this precedence: current code and executed tests, verified stable specs, Context Packs, change history, then private Memory.

## README summaries

The runtime owns only content between `repo-context-ledger` markers. Root and detected module READMEs retain human-authored content outside those markers. Generated blocks link readers and agents to current context and recent changes.

Monthly indexes and managed README blocks are derived data. With the default team policy, feature branches do not regenerate them. After merge, run `sync --derived` on the default branch to rebuild the same result from committed handoffs, specs, and Context Packs. This keeps concurrent pull requests from repeatedly conflicting in shared summaries.

Context Packs record both a source commit and a base branch/commit. `team-check` compares a working branch with its base, detects overlapping code paths and feature handoffs, rejects derived-index edits on feature branches, and reports packs created against an outdated base. `check --coverage` separately classifies Git paths through validated repository-relative globs, requires changed production paths to appear in handoff evidence, requires a changed stable spec or explicit exception, and verifies that each production path is tracked by a Context Pack that was actually refreshed. An unrelated changed Pack never satisfies coverage.

## Migration rules

- Reuse an existing `docs/specs/` or equivalent stable documentation area when it already serves this purpose.
- Preserve existing files and prose.
- Prefer adding indexes and managed blocks over reorganizing a mature repository.
- Recognize mature `docs/changes/YYYY-MM/...` trees as a legacy monthly layout. Reuse an existing `YYYY-MM/index.md` without rewriting its human content, group nested handoffs at that month root, and do not create per-date or per-feature indexes. Delete a stale generated index only when its full content is reproducible from current sibling records; preserve ambiguous files.
- Treat nested Git repositories and worktrees as module-discovery boundaries.
- Configure exceptional paths in `.context-ledger/config.json` instead of duplicating documents.
- Re-running `init` migrates v2 shared `.active-handoff` and context state into private v3 workspace state after the new state is safely written.
- Upgrading to v0.4 adds the quality policy and templates without changing existing record language, format, filenames, or content. Strict evidence checks apply only to documents marked `evidence-v1`.
- Upgrading to v0.5 adds the Context Manifest, native adapter configuration, checkpoint metadata, and optional Git-diff coverage gate. It preserves existing semantic documents and user prose.
- Upgrading to v0.5.1 adds default Coverage path classes and related-Pack validation. Existing v5 configuration remains valid; rerunning `init` persists the new default glob policy without rewriting historical records.
- Upgrading to v0.5.2 migrates the single active pointer and paused stack into v6 task sessions, shortens `verify` lock scope, and refreshes native adapters with a no-unsolicited-cross-task-contact rule. Historical handoffs are preserved.
- Upgrading to v0.5.3 migrates registered active or paused handoffs from formal history into v7 private drafts, reserves their original publication paths, and leaves completed and legacy history unchanged. A validated `finish` atomically publishes one completed change and removes only that session's draft.
- Upgrading to v0.5.4 makes evidence and finish session-scoped in shared worktrees. Foreign dirty paths and stale Packs no longer contaminate or block another task, while repository-wide strict and coverage checks remain available for integration.
- Upgrading to v0.5.9 persists a bounded `context` budget, returns `context-plan-v1` Required reads plus cold-history metadata, and adds merge-base `check --changed-since` validation. Existing Packs, specs, completed changes, session drafts, and full-check behavior remain unchanged.
- Upgrading to v0.5.10 migrates private state to v8, adds principal ownership, continuation epochs/tools, bounded `context-plan-v2` Resume Capsules, keyword resume across active/paused work, and explicit expiring read-only/fork/transfer grants. Existing drafts are bound conservatively when their Actor matches the current Git actor; completed history and Git evidence rules remain unchanged.
- Upgrading to v0.6.0 returns `context-bundle-v1`, adds a disposable Git-metadata router cache, bounded reverse-index fingerprint candidates, optional `context --baseline`, and selected-Pack evidence filtering. Existing Packs, specs, Changes, private sessions, ownership, and Git sharing rules remain unchanged; no production data or private Capsule body is added to the cache benchmark or committed records.
````

## File: skills/repo-context-ledger/references/global-runtime.md
size: 2574
sha: 6072d0b9041d826e4ddb2d3e03aad29784c55d80
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/references/global-runtime.md

```text
# Reusing the global runtime

Default repositories keep a standalone bundled runtime. On a workstation that explicitly chooses a single globally installed Codex Skill, `init --runtime global --dry-run` previews a normal initialization with a small forwarding entry; the corresponding init applies it. Review all planned writes first. Existing `runtime.mode` is preserved by subsequent init calls; `--runtime bundled` explicitly restores a bundled copy.

The saved setting is `"runtime": {"mode": "global"}` in `.context-ledger/config.json`. The project entry `.context-ledger/ledger.py` resolves `CODEX_HOME/skills/repo-context-ledger/scripts/ledger.py`, or the user's `.codex/skills` when CODEX_HOME is unset. No user-specific absolute path is committed. CODEX_HOME must be absolute; a missing target or a target inside the calling repository fails closed, without downloading or falling back to an old runtime. Other editors can use the same entry on this machine if that global installation exists; a fresh clone/CI machine must install it or choose bundled mode.

The forwarding entry supplies its own repository root even when invoked from another directory; an explicit global `--repo` argument still takes precedence. Global updates take effect on the next command. This shares executable code, not repository configuration, presets, permissions, principal identity, drafts, caches, or completed history. Agents must still reload updated Skill instructions in a new turn/window; updating a file does not rewrite already-loaded conversation context.

For a mature repository that must keep all documentation and task state unchanged, avoid an unrestricted init merely to replace the runtime. Back up the existing installation outside skill-discovery directories. Update only the runtime mode, forwarding entry, and reviewed Agent entry instructions, preserving configuration values and all history/state. Remove a project-local Skill directory only after confirming that it actually is a duplicate Skill, not `.context-ledger` configuration or documentation. A stale instruction that actively requires a shared active-handoff pointer must be explicitly retired during migration; leave the historical pointer and records themselves intact.

Verify forwarding with `--version`, read-only status, and adapter checks. Compare the existing documentation and state before/after, and do not commit the consuming project unless requested. Global mode is intentionally opt-in: a pinned bundled version remains useful for CI and collaborators who do not share this workstation.
```

## File: skills/repo-context-ledger/references/production-workflow.md
size: 14391
sha: e66c3bb00008d2edf50101dd44b1ac42680e61ae
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/references/production-workflow.md

````text
# Production-scale context and validation

Use this reference in repositories where accumulated Packs, specs, and completed changes make broad context loading or full local audits expensive.

## Judge the delta before lifecycle work

First judge new facts/effects from the current request and loaded task context. Do not run a classifier command, scan Git again, or write a classification document for every reply. Routine follow-ups with adequate context use ordinary tools, not a fresh lifecycle. A known unfinished task receives only its new delta and useful findings; retain existing background and methods, and do not finish it merely because one reply ends. New behavior after completion needs a new record, even if the task sounds similar; never rewrite completed history. Operational facts may require an update, but code preparation, questions and identical status rechecks do not each need a new Change.

Run `plan --query "<user request>" --tool <agent>` only when task identity or a required route is missing. Its read-only `workflow-plan-v1` result selects a mode and structured next action; honor requires_confirmation. A paused task or real handover uses resume and its new epoch; a same-window continue on a known active task does not. Reuse only results still valid for the relevant code, inputs, environment and acceptance phase; time-sensitive safety checks stay fresh. This is Agent guidance, not a new semantic-deduplication engine or test-result cache.

Examples for reviewing the guidance:

| Request and known state | Expected decision |
| --- | --- |
| "再看一下刚才的日志"; task and log location already known | Perform the requested read normally; no plan/start/finish or synthetic new verification entry. |
| "继续刚才的修复"; same active window, session and epoch known | Continue that draft, adding new facts only; no resume/epoch bump. |
| "另一个接口也修同样的问题" | Reuse the method, inspect the new interface boundary, and record its actual delta; do not recycle the old pass. |
| New behavioral correction after the earlier task was published | Start a new record and reference relevant background; leave the completed record unchanged. |
| "继续公告抓取" in a fresh window with unknown session | Route the keywords; resume only the uniquely permitted task, or resolve ambiguity. |
| Repeat deployment request or changed authorization/environment | Respect the explicit request and safety gates; similarity neither authorizes a side effect nor justifies skipping required checks. |

These examples document the expected Agent decisions; deterministic runtime tests alone do not prove that a model will always choose them.

## Context Bundle is the initial read boundary

Run:

```text
python .context-ledger/ledger.py context --query "<task>"
```

The runtime returns one `context-bundle-v1` with one current primary Pack, bounded Required reads, cold-history summaries, the configured character budget, an optional PR baseline, and—when one owned private task matches—a bounded Resume Capsule. Superseded or archived Packs are never eligible as Required reads. A disposable cache below Git metadata reuses Pack parsing and tracked-file digests; it never replaces current Pack/code verification and never enters Git.

Run `doctor --format json` as a scheduled or release health observation, not on every edit. It groups Pack debt and caps detail items so a large repository does not emit one line per stale file. Treat warnings and repairable findings as planned maintenance; errors identify broken deterministic contracts. Doctor is strictly read-only and never refreshes fingerprints, changes Pack status, rewrites lineage, repairs links, or cleans private sessions.

- Read Required reads in order.
- Do not recursively read `docs/ai`, `docs/specs`, or `docs/changes`.
- Treat completed Change bodies as cold history. ID/title/feature/date/summary/evidence metadata is not permission to load a body.
- Open a completed Change only when the user asks for historical reasoning, a Required Pack cites it for a named reason, or the unresolved question cannot be answered from current code/specs.
- If more context is needed, state the unresolved question before opening another document. Always expand into behavior-relevant callers, implementations, configuration, persistence, permissions, concurrency, retries, tests, and external APIs. The budget limits only the initial route; it never limits necessary code investigation.

Use `--format json` when a native Agent integration needs the exact Bundle, budget, baseline, cache state, and local timing metrics. At PR time, add `--baseline origin/main`; an unresolved ref remains an explicit warning rather than silently pretending a delta was loaded.

## Resume without replaying a long chat

When a user starts a fresh Agent window and supplies earlier task keywords, route them before broad code or documentation search:

```text
python .context-ledger/ledger.py context --query "continue <task keywords>" --tool <agent>
```

The router searches only active/paused sessions available to the current principal. A unique match receives an on-demand Resume Capsule containing the checkpoint summary, next action, bounded implementation evidence paths, last verification, Git position, Pack, warnings, previous tool, and continuation epoch. The Capsule is private state, not a new Markdown document and not a copy of the previous conversation.

Continue the same Ledger session with `resume --query ... --tool ...`. This increments its epoch; pass that epoch to every later lifecycle write so a stale window fails instead of overwriting the newer continuation. Ambiguous matches require an explicit session ID.

Another principal gets no Capsule by default—only a minimal overlap signal—and cannot mutate the source task. An explicit expiring grant may provide read-only Capsule access, create a recipient-owned fork, or transfer a paused task. Git-tracked Packs, specs, and completed Changes remain readable to every collaborator through normal Git workflows.

The ownership boundary is logical workflow isolation. Anyone with unrestricted access to the same filesystem can inspect Git metadata, so OS accounts and repository permissions remain the security boundary. Private sessions also do not travel to a different clone or computer.

## Keep validation proportional to the change

Use the existing session-scoped `finish` gate for local task completion. It validates the selected draft and related Pack/spec evidence only.

For a small single-session fix, avoid a separate `evidence` command; `finish` captures the bounded dirty set. After code is stable, launch checks concurrently only when they do not share a database, port, generated directory, or mutable fixture. Refresh the Pack and spec while those checks run, then wait for every `verify` process to record before `finish`. Verification commands may append concurrently through short lock phases, but an Agent must not hand-edit the private draft at the same time.

Use ordinary tools for reads, searches, file generation, preparation, and authorized deployment. Select managed verification by acceptance goal, not by helper-script count. Run a required acceptance script through verify at first execution; do not rerun it simply to log it. Group checks with the same goal using an existing reviewed project script, preserving failed and not-run substeps. Pre-deployment, authorization, and post-deployment boundaries stay ordered and separate; no hard invocation quota justifies dropping a check or replaying a state-changing action. Meaningful operational facts still belong in the same draft, clearly distinguished from managed verification.

Keep one session open for the complete logical request, including its tests and documentation. Do not finish the code and then open a second session just to update the same request's README. Archive once, but preserve meaningful progress in the same private draft when a diagnosis changes, a key decision is made, or a failed approach reveals an important boundary. Before switching windows, checkpoint the result and next step without replacing the reasoning in the draft. Do not log every command or delay publication across unrelated later user requests.

`start --workflow small-fix` uses the existing evidence-v1 headings with nine authoring prompts: intent, Before/After, change explanations, invariants, failure/recovery, unchanged scope, documentation rationale, and uncertainty. Explain what each meaningful change does and why, citing its exact repository-relative file/symbol; coupled files can share an explanation and refer to common boundaries and verification. Only the documentation `Updated` list is generated from scoped evidence, never its `Reason` or the change explanation. There is no fixed limit on change items. Auto evidence includes changed README and native instruction Markdown, but these remain non-production Coverage paths. Generated runtime/configuration files are still filtered. A broad dirty tree or multiple sessions requires explicit task-scoped evidence; a single session alone never proves all dirty changes belong to it.

New short records carry `Record format: small-fix-explained-v1`. The gate rejects path-only explanations and missing implementation-path references (all evidence paths if none are implementation), but it cannot prove business semantics or detect every omitted change inside one file. Review the actual diff against the record. If multiple independent behaviors, high-risk boundaries, or uncertainty appear, expand this same draft to `Workflow: ordinary-change` and `Detail: standard`, preserving its format marker, decisions, and checks. Do not replace the session or erase evidence to make it fit the short form. Historical completed records are preserved; older unfinished short forms need explanations before publication.

Use optional `finish --dry-run` with the same session/epoch/spec arguments when the closeout requirements are uncertain. It uses real preparation and validation, reports draft, verification, spec, and related Pack problems together where inputs can safely be resolved, and returns 0 when ready or 2 when invalid. It does not lock, save router caches, update drafts/specs, publish history, or change ownership. An invalid path, inaccessible session, or missing scoped evidence still stops before unsafe inspection. A successful preview is a point-in-time check, not a reservation; actual finish revalidates. Do not add this preview to every small task or poll it after every field edit.

Use `--timings` before the command when diagnosing lifecycle overhead. It emits one `private-command-timings-v1` JSON object to stderr and never persists machine paths or timing data in Git. `finish` validates outside the write lock, rechecks a bounded input signature under the lock, publishes atomically, and regenerates derived indexes afterward. A draft, evidence file, Pack, spec, or publication target that changes during preparation causes `finish` to fail closed and preserve the session.

For repeated project checks, prefer reviewed `verification.presets` over shell strings assembled by each Agent. Presets store executable arguments as JSON arrays, may constrain the repository-relative working directory and platform, and are executed only after an explicit `verify --preset <name>`. Keep one-off commands direct. See [verification-presets.md](verification-presets.md) for the schema and safe Windows/Linux examples.

Before a pull request, use a merge-base delta:

```text
python .context-ledger/ledger.py check --strict --coverage --changed-since origin/main
```

This checks changed handoffs, specs, Packs, Markdown links, adapter drift, directly related current Packs/specs, and Coverage without letting unrelated historical debt block the pull request. A source change that makes its related Pack stale still fails. Coverage accepts private task evidence or a spec exception only from a session whose recorded evidence intersects the changed implementation paths.

Keep the full audit explicit:

```text
python .context-ledger/ledger.py check --strict --coverage
```

Run it for scheduled repository health work, controlled integration, or release readiness. Do not run it merely to finish an unrelated parallel task.

## Configuration

The `context` object in `.context-ledger/config.json` controls the hard initial budget:

```json
{
  "max_required_files": 3,
  "max_linked_specs": 2,
  "max_change_summaries": 3,
  "max_total_characters": 30000,
  "show_close_candidates": 0
}
```

Keep the default unless a measured repository need justifies a larger budget. Increasing the budget is not a substitute for smaller Context Packs or clearer feature boundaries.

## Knowledge growth

- Keep one short completed Change per behavior-changing task; its body remains cold by default.
- Keep one current Pack per durable feature or bounded subsystem, not one Pack per fix.
- `pack --file` declares validity dependencies: changing one requires code-informed Pack review and a fresh fingerprint. Use `pack --reference <path>` for optional reading links whose contents do not determine this Pack's correctness. They live in Reading references, are checked for broken links, and neither invalidate fingerprints on content edits nor satisfy Coverage. Never move a real behavior dependency there to get a green check.
- Existing `--file` dependencies are never automatically demoted. Refreshing without `--file` retains the full list; supplying any `--file` still explicitly replaces it. A path cannot be both tracked and a reading reference. Review both the code boundary and Pack prose before explicitly changing dependency roles. Optional references are read only for a named question, never as an instruction to load every linked file.
- Reading references currently use simple local Markdown links. Paths with Markdown delimiters (brackets, parentheses, backticks, a fragment marker, or newlines) are rejected before writing instead of emitting a broken link; ordinary spaces are supported. Remove obsolete reading links from the Pack when their targets move, then review the new path.
- Update specs only when current behavior, contracts, boundaries, or navigation truth changes.
- Regenerate shared indexes on the default branch rather than every feature branch.
````

## File: skills/repo-context-ledger/references/verification-presets.md
size: 6176
sha: 00a8b086b90d66bbccd8e667421733e9c9da4392
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/references/verification-presets.md

````text
# Verification presets

Use a verification preset for a stable acceptance goal that multiple Agents or sessions will verify repeatedly. Routine reads, searches, file/configuration generation, and deployment preparation use ordinary tools; they do not each need a Ledger wrapper. A one-off acceptance check can use direct `verify -- <executable> <arguments>`. Record exploratory observations in the draft without inventing managed verification results.

## Configuration

Presets live in the Git-tracked `.context-ledger/config.json` and are never executed automatically:

```json
{
  "verification": {
    "presets": {
      "python-unit": {
        "argv": ["python", "-B", "-m", "unittest", "discover", "-s", "tests"],
        "cwd": ".",
        "timeout": 600,
        "sensitive": false,
        "platforms": ["windows", "linux", "darwin"]
      },
      "go-announcement-worker": {
        "argv": ["go", "test", "./..."],
        "cwd": "services/announcement-worker",
        "timeout": 900,
        "sensitive": false,
        "platforms": ["windows", "linux", "darwin"]
      },
      "windows-worker-script": {
        "argv": ["powershell.exe", "-NoProfile", "-NonInteractive", "-File", "scripts/verify-worker.ps1"],
        "cwd": ".",
        "timeout": 900,
        "sensitive": false,
        "platforms": ["windows"]
      }
    }
  }
}
```

Run one explicitly. The first attempt stops before execution and prints the preset's normalized digest:

```text
python .context-ledger/ledger.py verify --session <id> --preset python-unit
ERROR: ... repeat with --trust-digest sha256:<digest>
python .context-ledger/ledger.py verify --session <id> --preset python-unit --trust-digest sha256:<digest>
```

An explicit `--timeout` overrides the preset timeout. An explicit `--sensitive` can strengthen a non-sensitive preset; it cannot make a preset configured as sensitive persist its command or output.

## Safety and portability

- `argv` is passed directly to `subprocess.run(..., shell=False)`. Each JSON element is one argument, so spaces do not require shell escaping.
- `cwd` is relative to the repository and cannot escape it. The directory must exist when the preset runs.
- `platforms` contains one or more of `windows`, `linux`, and `darwin`; a mismatched machine fails before execution.
- PowerShell presets must use `-File` with a reviewed script. `-Command`, encoded command strings, `cmd.exe`, and shell `-c` strings are rejected.
- Do not store secrets, tokens, local absolute paths, or environment-specific values in a preset. `sensitive: true` protects verification evidence, not the Git-tracked configuration itself.
- Review a preset after cloning, pulling, changing branches, or receiving configuration changes. Trust requires the exact digest printed by the runtime, is scoped to the current local principal, and is stored outside Git. A changed preset has a new digest and stops again before execution. Initialization, context routing, and `finish` never auto-run it.
- Prefer checked-in Python, PowerShell, Bash, or project-native scripts when a check needs pipes, conditionals, environment setup, or several commands.

## Agent behavior

Before assembling a repeated verification command, check whether a preset exactly represents the required test. Do not substitute a narrower preset for a broader claimed check, invent a preset merely to avoid understanding the project, or run every configured preset by default. Independent presets may run concurrently only when they do not share mutable services, ports, databases, generated directories, or fixtures.

## One acceptance goal, one invocation

1. Identify the behavior and safety boundary being accepted. Reuse the current session and existing project checks; do not repeat plan/status/focus merely for the next helper command.
2. Run that acceptance script through verify when it is first needed, not bare first and a second time for logging. Prefer an existing script; only when a small wrapper is justified, adapt `assets/verify-change.py` from this Skill to the project's scripts directory. Its empty CHECKS list deliberately fails until configured with reviewed, named direct argv arrays. It executes serially, stops on failure or timeout, and marks remaining checks not-run.
3. Inspect the aggregate exit code and substep results before continuing. Optional `ledger-step: <short-name> <passed|failed|not-run>` output is retained as a bounded, redacted summary (up to 16 annotations; extra annotations are explicitly counted as omitted). These are script-reported steps, not separate trusted attestations; the managed result still comes from the actual process exit code. Sensitive verification suppresses the step summary with the rest of the output.

For example, a permission-fix acceptance script can check directory access, execution as the service user, and the existing startup guard. File preparation is not a fourth verification goal. Keep required pre-deployment checks before deployment and post-deployment acceptance afterward; never combine across authorization boundaries or replay deployment/trading actions to repair missing logging. An already executed external observation may be documented as an observation, not relabeled as a managed pass. Rerun only a safe check whose result genuinely needs refreshing.

A small fix commonly needs one or two acceptance invocations, but this is not a hard quota. Different safety boundaries or changed inputs can require more. The goal is fewer wrappers and no duplicate execution, not fewer tests or lost failure details.

## Distinguish script time from Ledger time

For a slow invocation, use `--timings verify ...`. The private stderr report keeps `verification_command_ms` for the actual subprocess, adds `verification_prepare_ms` and `verification_record_ms`, and reports total `ledger_overhead_ms` outside the subprocess. `lock_wait_ms` is included within overhead, not additional time to sum again. Python interpreter startup precedes this measurement. Metrics contain no command arguments or repository paths and are not stored in the handoff. Do not infer real deployment speed from a synthetic small-file benchmark.
````

## File: skills/repo-context-ledger/references/writing-quality.md
size: 6078
sha: fb756583af341e6bbdc0f4d45524ab7e19619b0b
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/references/writing-quality.md

````text
# Evidence-first writing quality

Apply this standard only to records with `Quality profile: evidence-v1`. Preserve legacy records unless the task explicitly upgrades them.

## Language

- Honor `Language` metadata: `en`, `zh-CN`, or `auto`.
- For `auto`, follow the predominant language of nearby repository documentation; if no pattern exists, follow the user's language.
- Keep paths, symbols, commands, protocol fields, error text, and identifiers in their source form. Do not translate them.
- Use one primary natural language per document. Quote another language only when it is part of an interface or evidence.

## Evidence rules

- Derive changed paths from the ledger evidence block and `git diff`, not memory.
- Cite concrete paths in backticks. Add the relevant class, function, route, job, or configuration key when known.
- Separate inspected fact from inference. Write `Unknown` or an open question when evidence is missing.
- Record only commands actually executed through `ledger.py verify`. Never convert an intended check into a reported result.
- Avoid unsupported claims such as “all edge cases are covered,” “fully compatible,” or “tests pass” without attached evidence.
- Reject vague standalone text such as “updated relevant files,” “fixed the logic,” or “修改了相关代码.” Replace it with an observable behavior, path, and boundary.

## Purpose-specific forms

### Handoff: chronological change evidence

- State intent and acceptance outcome.
- Describe observable `Before` and `After` behavior.
- Map changed paths and symbols to their responsibility and actual change.
- Record invariants, failure/recovery behavior, and what deliberately did not change.
- Keep verification results in the managed checks block.
- List documentation updated, or write `None — <reason>`.
- Preserve unresolved uncertainty under Open questions.

For a new `--workflow small-fix` draft, the runtime replaces the repeated path table with a free-form change explanation and generates only the `Updated` documentation list. Fill the nine authoring prompts with task-specific facts, including what each meaningful change does and why, its repository-relative file/symbol references, and why documentation changed or remains correct. Coupled files may share one explanation; boundaries and recorded verification may be referenced rather than restated. There is no fixed number of change items or artificial word cap. A changed-path list is not a change explanation, and "no documentation path changed" does not explain why no update is needed.

The `small-fix-explained-v1` record marker adds mechanical checks for prose beyond a path list and references to every implementation evidence path (or every evidence path when no implementation path exists). File/symbol references must use the exact repository-relative evidence path; a shared basename is ambiguous. These checks cannot prove the correctness of the explanation or detect every omitted behavior change in one file. Reconcile the actual diff against the record before finish; expand the same draft to ordinary work if there are independent behavior changes, high-risk boundaries, or uncertainty.

Archive once does not mean write only at the end. Preserve a changed diagnosis, key design decision, rejected approach that explains a boundary, or useful failure cause in the same private draft when discovered. An optional Decisions section can hold such notes; shared Verification already retains executed attempts. Before switching context, checkpoint the current result and next step without overwriting the reasoning already in the body. Do not record every command, duplicate raw logs, or keep irrelevant troubleshooting noise. Preserve uncertainty instead of converting it into confirmed behavior during final cleanup.

Example for one coupled fix:

```markdown
## Code paths

- `src/service.py::VALUE` reads `src/defaults.py::DEFAULT` so the exported value and shared default cannot drift. The import contract and verification below apply to both files.

## Documentation updates

Updated: Generated from scoped documentation paths at finish.
Reason: The usage guide states this default, so its example must match the corrected value; installation steps remain unchanged.
```

If the record grows beyond a known small boundary, expand its explanations and set `Workflow: ordinary-change` and `Detail: standard` in the same draft. Retain its existing sections, decisions, format marker, and managed checks. Do not start a replacement session or remove evidence to get past a gate. Existing completed records without the new marker keep their historical validation contract; old unfinished path-only short drafts must add explanations before publication.

### Stable spec: current truth

- Describe the merged behavior as it exists now; do not narrate the implementation history.
- Map entry points and ownership, then show input → processing → persistence/dependency → output.
- State contracts, permissions, validation, concurrency/idempotency rules, failure modes, and recovery only when they apply.
- Link history through the managed related-changes block instead of copying handoff prose.

### Context Pack: minimal loading route

- Keep it shorter than the configured maximum.
- Separate `Read first`, `Read if needed`, and `Do not load by default`.
- Track the smallest sufficient set of validity dependencies. Optional navigation can use `pack --reference` and Reading references; it does not count toward Coverage. Do not demote a real dependency merely to avoid stale warnings. Do not turn the pack into a second spec.
- Prefer navigation facts, boundaries, and reliable diagnostic commands over implementation narration.

## Detail levels

- `concise`: record the minimum evidence needed to resume safely.
- `standard`: cover the main flow, contracts, failure behavior, and focused verification.
- `detailed`: add justified secondary flows and operational boundaries; do not repeat source code.

More detail never relaxes the requirement for concrete evidence.
````

## File: skills/repo-context-ledger/assets/context-pack-template.md
size: 1393
sha: a02ca86207aa8adca01409893a9f886a7be73e43
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/assets/context-pack-template.md

```text
# {{TITLE}} context pack

Status: current
Feature: {{FEATURE}}
Aliases: none
Quality profile: evidence-v1
Language: {{LANGUAGE}}
Detail: {{DETAIL}}
Source commit: {{SOURCE_COMMIT}}
Base branch: {{BASE_BRANCH}}
Base commit: {{BASE_COMMIT}}
Last refreshed: {{REFRESHED}}

## Purpose

TODO: Explain the feature or subsystem in two or three evidence-based sentences.

## Load order

- Read first: TODO: List the minimum paths required for the main flow.
- Read if needed: TODO: List conditional paths and when they become relevant.
- Do not load by default: TODO: Name adjacent areas that are normally out of scope.

## Entry points and code map

| Path / symbol | Role |
| --- | --- |
| `TODO:path-or-symbol` | TODO: State why a fresh session needs it. |

## Contracts and boundaries

- Invariants and contracts: TODO: Record confirmed rules only.
- Failure / recovery: TODO: Record relevant failure paths and recovery.
- Non-goals: TODO: State adjacent behavior outside this feature.

## Verification

TODO: Record reliable commands in backticks and state what each command proves; do not claim a result here.

<!-- repo-context-ledger:pack-specs:start -->
## Stable context

- No linked stable specs yet.
<!-- repo-context-ledger:pack-specs:end -->

<!-- repo-context-ledger:pack-files:start -->
## Tracked file fingerprints

- No tracked files yet.
<!-- repo-context-ledger:pack-files:end -->
```

## File: skills/repo-context-ledger/assets/handoff-template.md
size: 1767
sha: 9da963085a197c12c96417e884209d200cc145a2
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/assets/handoff-template.md

```text
# {{TITLE}}

Status: active
Feature: {{FEATURE}}
Quality profile: evidence-v1
Language: {{LANGUAGE}}
Detail: {{DETAIL}}
Scope: {{SCOPE}}
Handoff ID: {{HANDOFF_ID}}
Session ID: {{SESSION_ID}}
Actor: {{ACTOR}}
Branch: {{BRANCH}}
Started: {{STARTED}}
Completed:
Paused:
Resumed:
Checkpointed:
Checkpoint actor:
Base commit: {{BASE_COMMIT}}
Dirty paths: none
Resume summary:
Next step:
Specs: none
Spec exception:

## Intent

TODO: State the requested outcome, why it matters, and the observable acceptance result.

## Changed behavior

Before: TODO: Describe the observable behavior before this change.

After: TODO: Describe the observable behavior after this change.

## Code paths

| Path / symbol | Responsibility | Actual change |
| --- | --- | --- |
| `TODO:path-or-symbol` | TODO: State its role in the flow. | TODO: State what changed here. |

## Boundaries and risks

- Invariant: TODO: State behavior that must remain true.
- Failure / recovery: TODO: State failure handling and recovery, or why it does not apply.
- Not changed: TODO: State adjacent behavior deliberately left unchanged.

## Verification

Record checks with `ledger.py verify`; do not type claimed results manually.

<!-- repo-context-ledger:checks:start -->
- No verification recorded yet.
<!-- repo-context-ledger:checks:end -->

## Documentation updates

Updated: TODO: List documentation paths in backticks, or write `None — <reason>`.

Reason: TODO: Explain why those documents changed or why no documentation applies.

## Open questions

TODO: Record unresolved facts or write `None.` Never present an inference as confirmed behavior.

<!-- repo-context-ledger:evidence:start -->
## Git change evidence

- Evidence has not been captured yet.
<!-- repo-context-ledger:evidence:end -->
```

## File: skills/repo-context-ledger/assets/project-context-template.md
size: 594
sha: 8c826683a1a390ecf895e440d99e15f63eaa129a
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/assets/project-context-template.md

```text
# Project context

Quality profile: evidence-v1
Language: {{LANGUAGE}}
Detail: {{DETAIL}}

## Repository purpose

TODO: Summarize what this repository delivers and who uses it, separating confirmed facts from unknowns.

## Architecture map

TODO: List major modules, their responsibilities, and important dependency directions.

## Shared boundaries

TODO: Record cross-cutting invariants, security boundaries, data ownership, and operational constraints.

## Navigation

- Stable feature context: [`{{SPECS_INDEX}}`]({{SPECS_INDEX}})
- Change history: [`{{CHANGES_INDEX}}`]({{CHANGES_INDEX}})
```

## File: skills/repo-context-ledger/assets/spec-template.md
size: 1290
sha: fa92febe7a29aee381d1664aaa481e1cfac99511
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/assets/spec-template.md

```text
# {{TITLE}}

Status: current
Quality profile: evidence-v1
Language: {{LANGUAGE}}
Detail: {{DETAIL}}
Last reviewed: {{DATE}}

## Purpose and behavior

TODO: Describe the current merged user-visible or system-visible behavior without narrating history.

## Entry points and code map

| Path / symbol | Ownership and role |
| --- | --- |
| `TODO:path-or-symbol` | TODO: State its responsibility in the feature. |

## Data flow and contracts

- Input: TODO: Describe accepted input and validation.
- Flow: TODO: Describe processing and important dependency direction.
- Persistence / dependencies: TODO: Describe durable state and external contracts.
- Output: TODO: Describe observable output and errors.

## Boundaries and failure modes

- Invariants: TODO: Record rules that must remain true.
- Permissions / concurrency: TODO: Record authorization, idempotency, and concurrency rules when applicable.
- Failure / recovery: TODO: Record failure behavior and recovery.
- Non-goals: TODO: State what this feature does not own.

## Verification

TODO: List reliable commands in backticks and state what each command verifies. Do not report an unexecuted result.

<!-- repo-context-ledger:changes:start -->
## Related changes

- No recorded changes yet.
<!-- repo-context-ledger:changes:end -->
```

## File: skills/repo-context-ledger/assets/verify-change.py
size: 2216
sha: 5e9b4a65f9146d66c83ebe49668c5fd9fb2e7012
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/assets/verify-change.py

```text
#!/usr/bin/env python3
"""Optional project-owned acceptance script: configure existing checks before use.

Copy only when several checks share one acceptance goal; prefer existing project scripts.
Run once through ledger.py verify (or an existing preset). This is not a deployment runner.
Use sys.executable for Python and direct argument arrays for Go/Rust/PowerShell -File.
Keep authorization boundaries and pre/post-deployment checks in their original phases.
"""

from pathlib import Path
import re
import subprocess
import sys

ROOT = Path(__file__).resolve().parents[1]  # For a copy in <project>/scripts/.
CHECKS = []  # (short-name, [executable, argument, ...]); empty configuration fails closed.
TIMEOUT_SECONDS = 300

def run_checks(checks, root, timeout=TIMEOUT_SECONDS):
    if not checks or not 1 <= len(checks) <= 16:
        raise ValueError("Configure 1-16 named acceptance checks, not deployment operations.")
    seen = set()
    for name, argv in checks:
        if (not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_-]{0,31}", name)
                or name in seen or not isinstance(argv, list) or not argv
                or any(not isinstance(arg, str) or not arg for arg in argv)):
            raise ValueError("Checks need unique short names and nonempty direct argv arrays.")
        seen.add(name)
    for index, (name, argv) in enumerate(checks):
        try:
            result = subprocess.run(argv, cwd=root, shell=False, timeout=timeout)
            code = result.returncode
        except subprocess.TimeoutExpired:
            print(f"ERROR: {name} timed out", file=sys.stderr)
            code = 124
        except OSError:
            print(f"ERROR: {name} could not start", file=sys.stderr)
            code = 127
        print(f"ledger-step: {name} {'passed' if code == 0 else 'failed'}", flush=True)
        if code:
            for pending, _ in checks[index + 1:]:
                print(f"ledger-step: {pending} not-run", flush=True)
            return 1
    return 0

if __name__ == "__main__":
    try:
        raise SystemExit(run_checks(CHECKS, ROOT))
    except ValueError as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        raise SystemExit(2)
```

## File: skills/repo-context-ledger/agents/openai.yaml
size: 279
sha: 228681854f650fff28038149309799feadee231d
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/skills/repo-context-ledger/agents/openai.yaml

```text
interface:
  display_name: "Repo Context Ledger"
  short_description: "Record feature changes and relay verified context"
  default_prompt: "Use $repo-context-ledger to record this feature change as verified repository knowledge and preserve it for future AI windows and tools."
```

## File: README.md
upstream: https://github.com/gviiisen/repo-context-ledger/blob/main/README.md

````text
# Repo Context Ledger — Feature Change Ledger & Cross-Agent Context Relay

[English](README.md) | [简体中文](README.zh-CN.md)

[![skills.sh](https://skills.sh/b/gviiisen/repo-context-ledger)](https://skills.sh/gviiisen/repo-context-ledger)

> Automatically record every behavior-changing feature update, then let Codex, Cursor, or Claude continue from the right code, decisions, and boundaries.

Repo Context Ledger is an open, repository-level feature change ledger for AI coding. After a feature is added, fixed, or behaviorally adjusted, it preserves what changed, why it changed, where the implementation lives, which boundaries must remain stable, and how the result was verified.

Those verified records become durable context for Codex, Claude, Cursor, GitHub Copilot, Grok, and other coding agents. A fresh window or a different tool can follow a focused route into the relevant code and continue without replaying a long chat or rediscovering the feature from scratch.

Use it for AI feature change tracking, software change documentation, AI context management, Codex context management, Cursor context switching, Claude context management, and cross-agent development handoffs. The change ledger is the knowledge source; cross-session and cross-tool continuation are capabilities built on top of it.

Install it with the standard Agent Skills CLI:

```bash
npx skills@latest add gviiisen/repo-context-ledger --skill repo-context-ledger
```

You make ordinary coding requests. The AI owns the documentation lifecycle.

Before any lifecycle command, the Agent can ask the read-only Workflow Plan whether the request is understanding work, a small fix, an ordinary change, or a continuation. The plan reuses the bounded context router, explains its decision, and asks for clarification instead of guessing when intent is ambiguous.

## Why it exists

AI-assisted changes are easy to implement but hard to preserve as durable repository knowledge. Without a feature-level record, the reason for a fix, its code path, verification evidence, and important boundaries remain trapped in a chat or must be rediscovered from a large diff and codebase.

The same gap becomes more visible when work moves to a fresh window or another coding agent. The next agent must reconstruct the feature from scratch, and implementation details or important constraints can be lost between sessions.

Repo Context Ledger records each behavior-changing feature addition, repair, and adjustment, then turns that verified history into a small, durable map of the repository:

- where a feature lives;
- how its code path works;
- which contracts and edge cases must remain stable;
- what changed, why it changed, and how it was verified;
- which project and module README summaries need refreshing.

## What it maintains

- `docs/ai/`: concise repository-wide orientation for fresh AI sessions.
- `docs/ai/context-manifest.json`: generated feature-to-context routes for machine discovery.
- `docs/ai/context-packs/`: minimal feature context, load order, boundaries, tests, and tracked-file fingerprints.
- `docs/specs/`: current feature behavior, code maps, contracts, and boundaries.
- `docs/changes/`: chronological implementation and repair handoffs, grouped as `YYYY/MM/<change>.md` with a small monthly index.
- Private branch/worktree state: independent active and paused drafts are stored under Git metadata and are never committed; only completed changes enter formal history.
- Root and module `README.md` files: generated navigation blocks without rewriting human prose.
- `AGENTS.md`, `CLAUDE.md`, Cursor rules, and `.github/copilot-instructions.md`: thin native adapters that route coding agents to the same ledger.
- `.context-ledger/writing-quality.md`: local evidence, language, and record-form rules available to every AI tool.

## Compatibility

The core skill follows the open Agent Skills `SKILL.md` format. It is designed for Codex, Claude Code, Cursor, GitHub Copilot, Grok, and other agents that support Agent Skills or repository instruction files.

Initialized repositories also receive plain instruction files, so tools without native Skill discovery can follow the same workflow. Native discovery and exact installation locations vary by product.

See [COMPATIBILITY.md](COMPATIBILITY.md) for supported Python/platform and CLI schema guarantees, and [MIGRATIONS.md](MIGRATIONS.md) for upgrade rules.

## Install

Clone this repository or download a release, then install the directory `skills/repo-context-ledger` in your AI tool.

### Codex

Ask Codex:

> Use `$skill-installer` to install the `skills/repo-context-ledger` skill from `https://github.com/gviiisen/repo-context-ledger`.

For repository-scoped use, copy or link the skill directory to:

```text
.agents/skills/repo-context-ledger/
```

### Claude Code

Copy or link `skills/repo-context-ledger` to either the personal or project skill directory:

```text
~/.claude/skills/repo-context-ledger/
.claude/skills/repo-context-ledger/
```

### Cursor

Import this GitHub repository from Cursor's Skills/Rules settings, or copy the skill to:

```text
~/.agents/skills/repo-context-ledger/
.agents/skills/repo-context-ledger/
```

### GitHub Copilot

Install the Skill through a compatible Agent Skills client, or let an initialized repository's `.github/copilot-instructions.md` route Copilot to the ledger. The runtime preserves existing Copilot prose outside its managed block.

## Common usage examples

After installation and one-time repository initialization, talk to your coding Agent normally. You do not need to run Ledger lifecycle commands yourself.

| Situation | What you can say | What the Agent does |
| --- | --- | --- |
| Understand an existing feature | `Explain how withdrawal review works and where its boundaries are.` | Routes to the most relevant Pack and spec, then inspects the necessary code without creating a task session. |
| Implement or fix behavior | `Fix duplicate withdrawal notifications.` | Creates a private task session, loads bounded context, expands through affected code and tests, verifies the result, and publishes one completed Change record. |
| Continue in a fresh window | `Continue announcement API rate limiting.` | Finds your matching active or paused session, generates a Resume Capsule, and continues the same Ledger session rather than starting over. |
| Switch AI tools | Open Cursor after Codex and say `Continue announcement API rate limiting.` | Uses the same vendor-neutral repository context and your principal-owned private session, while revalidating code and stale warnings. |
| Temporarily switch tasks | `Pause this work, fix the login timeout, then let me return later.` | Checkpoints the current task and starts an independent private session, so their handoff drafts do not overwrite each other. |
| Hand work to a teammate | `Transfer this paused task to principal p-…` or request a read-only/fork grant. | Creates an explicit expiring grant. Without one, another principal can use committed Packs, specs, and Changes but cannot read or mutate your private draft. |

The routed files are a starting map, not a limit. The Agent must still read additional callers, implementations, configuration, persistence, permissions, concurrency, retries, tests, and external boundaries whenever they can affect the requested behavior.

## Tutorial

### 1. Initialize a repository once

Open the target project with your AI coding tool and ask:

> Use repo-context-ledger to initialize this repository.

The agent first previews the exact operation list with `init --dry-run`, then applies the same plan with `init`. It creates the documentation structure, private workspace state, and durable agent instructions without overwriting existing documentation.

For a manual preview, run:

```text
python path/to/ledger.py --repo path/to/repository init --dry-run
```

The output is a compact plan, not a full diff. It does not create a lock, repository file, or private session-state 
````
