{
  "markdown": "# CodeLedger\n\n---\n\n> **What problem are we solving?**\n>\n> **The Problem** — AI coding agents waste 40–60% of their context window on irrelevant files. Every session starts cold. Institutional knowledge lives in people's heads and disappears when they leave. There is no risk signal before a merge.\n>\n> **The Solution** — CodeLedger is a deterministic context control plane for software development. It scores every file in a repository, selects only what the current task requires, captures outcomes, and promotes successful patterns into reusable institutional memory.\n>\n> **The Intelligence Layer** — The Task Intelligence Engine does not start from zero. It is seeded from day one with a curated ontology pack of golden patterns — distilled from peer organizations and leading engineering teams at organizations including Google, SAP, and Salesforce. As your team uses CodeLedger, your own earned patterns layer on top, making the system progressively more tailored to your codebase, your conventions, and your standards.\n>\n> **The Principle** — No cloud. No training pipeline. No behavior change required. Engineering management installs it once. Every developer and every AI agent benefits automatically — from collective intelligence on day one, and from your own institutional memory from day two onward.\n>\n> *Logs are history. Ledger is intelligence.*\n\n---\n\n\nCodeLedger turns every coding action into a persistent, compounding asset.\n\nWithout CodeLedger:\n- Context is lost between agents\n- Every task starts from scratch\n- Failures repeat\n\nWith CodeLedger:\n- Context persists across sessions and agents\n- Success patterns compound\n- Engineering becomes measurable and auditable\n\nThis is not another AI tool. This is a **Context Control Plane** for your repo.\n\nWorks with: **Claude Code** | **Cursor** | **Codex** | **GitHub Copilot** | **Gemini CLI** | Any CLI-based agent\n\n---\n\n## What happens when you use CodeLedger?\n\n1. You run a task\n2. CodeLedger selects context deterministically\n3. The outcome is recorded\n4. Future tasks improve automatically\n\nOver time, your repo builds its own intelligence layer.\n\n---\n\n## The Two-Loop Model\n\nCodeLedger helps in two ways:\n\n**⚡ Now** — Assembles the minimal context needed for your current task. Fewer irrelevant files, fewer retries, faster execution.\n\n**💎 Next** — Captures what worked and builds reusable memory so future tasks start smarter. Successful patterns compound into institutional knowledge.\n\n```\n⚡ Now                          💎 Next\nSelect context → Execute →      Record evidence → Promote patterns →\n                                Future tasks start smarter\n```\n\n---\n\n## AI Agent Integration (MCP)\n\nCodeLedger includes an MCP server that gives Claude, Cursor, and Windsurf direct access to your repo's memory:\n\n```bash\ncodeledger mcp start     # Launch MCP server (stdio transport)\ncodeledger mcp status    # Check readiness + connection instructions\n```\n\n**Tools available to agents:**\n- `query_ledger` — Search for verified patterns before coding\n- `get_active_context` — Get the task-specific context bundle\n- `record_interaction` — Report outcomes for memory compounding\n\n> MCP integration requires Team or Enterprise tier. See [Feature Tiers](#feature-tiers).\n\n---\n\n## Engineering Dashboard\n\nGenerate a repo-local engineering dashboard from your Context Ledger:\n\n```bash\ncodeledger dashboard build    # Generate static HTML dashboard\ncodeledger dashboard open     # Open in browser (no server needed)\n```\n\nThe dashboard shows: system health, integrity signals, quality metrics, pattern reuse intelligence, and estimated engineering value — all derived from real execution evidence.\n\n> Full dashboard requires Team or Enterprise tier. Individual tier receives a placeholder with teaser stats.\n\n---\n\n## Semantic Merge Verification\n\nPrevent silent merge failures where code compiles but types or config are semantically broken:\n\n```bash\ncodeledger merge-check --save-baseline    # Before parallel work\ncodeledger merge-check --verify           # After pulling a merge\ncodeledger merge-check                    # Quick health check\n```\n\nCatches removed types with active importers, config fields accessed but missing from defaults, and name collisions across packages.\n\n---\n\n## Feature Tiers\n\n| Feature | Individual (Free) | Team | Enterprise |\n|---------|:-:|:-:|:-:|\n| Context selection + scanning | ✅ | ✅ | ✅ |\n| Prompt coaching (automatic) | ✅ | ✅ | ✅ |\n| CI enforcement (`ci check --json`) | ✅ | ✅ | ✅ |\n| Local evidence + pattern capture | ✅ | ✅ | ✅ |\n| Semantic merge verification | ✅ | ✅ | ✅ |\n| **Full Engineering Dashboard** | 🔒 | ✅ | ✅ |\n| **MCP Server** (AI agent memory) | 🔒 | ✅ | ✅ |\n| **Team coordination** (claims, leases) | 🔒 | ✅ | ✅ |\n| **Pattern sync** (GitHub mirror) | 🔒 | ✅ | ✅ |\n| **Provenance** (causal traceability) | 🔒 | 🔒 | ✅ |\n| **Audit export** (SIEM-ready) | 🔒 | 🔒 | ✅ |\n\n```bash\ncodeledger features           # See what's available at your tier\ncodeledger upgrade            # Explore Team / Enterprise\n```\n\n---\n\n## Why this matters\n\nCodeLedger is built on a local-first Context Ledger:\n\n- Append-only memory of engineering activity\n- Outcome-linked learning (what worked vs what failed)\n- Cross-agent continuity\n- Deterministic context selection\n\nYour repo becomes an evolving system — not just code.\n\n---\n\n### Get CodeLedger\n\n**[Download Latest Release](https://github.com/codeledgerECF/codeledger/releases/latest)** · `npm install -g @codeledger/cli` · [Getting Started Guide](GETTING-STARTED.md) · [CLI Command Reference](https://github.com/codeledgerECF/codeledger/blob/main/docs/CLI_COMMAND_REFERENCE.md)\n\n```bash\nnpm install -g @codeledger/cli   # or download the zip from Releases\ncd your-project\ncodeledger ready\ngit add .codeledger/bin/ .gitignore\ngit commit -m \"chore: init codeledger\"\n./.codeledger/bin/codeledger task --task \"Fix null handling in user service\"\ncodeledger task --task \"Fix null handling in user service\"\n# Your agent now has .codeledger/active-bundle.md with the right context\n```\n\nYour agent reads the right files first. Every time.\n\nFor browser/cloud sessions, the committed `.codeledger/bin/` runtime package is what gets executed. `codeledger ready` initializes the repo, scans it, and deploys the canonical standalone build so the checked-in runtime matches the version you tested locally. Inside a vendored repo, `./.codeledger/bin/codeledger <command>` is the easiest interactive entry point.\n\n### Truth Control Plane\n\nOnce a repo is initialized, CodeLedger can reconcile reality across drift, outcomes, snapshots, handoffs, and release state:\n\n```bash\ncodeledger drift --history --verify-integrity\ncodeledger outcome --json --verify-integrity\ncodeledger harvest --preview --verify-integrity\ncodeledger context-handoff --target codex --verify-integrity\ncodeledger snapshot --verify-integrity\ncodeledger time-travel --to <snapshot-id> --verify-integrity\ncodeledger reality-check --verify-integrity\n```\n\nThese commands extend CodeLedger's existing verification and memory systems. They do not create a separate ledger or memory store.\n\n### What Happens After Install\n\nInstalling CodeLedger gives you the CLI. To use it in a project, initialize that project:\n\n```bash\ncodeledger init\n```\n\nThat sets up CodeLedger inside the repo by creating:\n- `.codeledger/` for project-local cache, bundles, sessions, and runtime data\n- `.codeledger/bin/` for the vendored standalone runtime\n- `.claude/hooks.json` for automatic integration\n- updates to `CLAUDE.md` so agents know how to use the context bundle\n\nYour normal flow after install is:\n\n1. Install CodeLedger\n```bash\nnpm install -g @codeledger/cli\n```\n\n2. Go to your project\n```bash\ncd your-project\n```\n\n3. Initialize and scan CodeLedger in that repo\n```bash\ncodeledger ready\n```\n\n4. Commit the vendored runtime if you want browser/cloud support\n```bash\ngit add .codeledger/bin/ .gitignore\ngit commit -m \"chore: initialize codeledger\"\n```\n\n5. Start using it\n```bash\ncodeledger ready --task \"your task here\"\n```\n\n## 🌐 Beyond CodeLedger\n\nCodeLedger is just the beginning.\n\nIt’s built on **ContextECF** — a broader context infrastructure approach for making AI systems **deterministic, auditable, and cumulative** instead of probabilistic and forgetful.\n\nAt the core is a simple idea:\n\n> Every interaction with AI should make the system smarter, more reliable, and more accountable over time.\n\n---\n\n## 🧠 What This Means (In Practice)\n\nWhile you’re using CodeLedger for development, the same foundation extends to:\n\n- 🧑‍💻 Engineering → Shared memory across agents, verified execution, no rework  \n- 📊 Decision-making → Faster, context-rich executive decisions  \n- 🗂️ Knowledge → Institutional memory that doesn’t disappear  \n- 🤖 AI agents → Coordinated, governed, and trustworthy systems  \n- 💬 Communication → Smarter meetings, better alignment  \n- 📈 Revenue → Relationship intelligence and proactive insights  \n- 🔐 Governance → Built-in auditability and compliance  \n\n---\n\n## 🚀 Why It Matters\n\nMost AI tools:\n- Recompute context every time  \n- Lose what they learned  \n- Can’t prove what happened  \n\nContextECF + CodeLedger:\n- Remember  \n- Verify  \n- Compound value over time  \n\nWhat you’re building isn’t just output.\n\n> You’re building a **long-term context asset** for yourself — and potentially your entire organization.\n\n---\n\n## 🤝 Share This\n\nIf CodeLedger is helping you, it’s worth a quick share with:\n\n- CTO / VP Engineering  \n- Platform / DevEx teams  \n- AI / Data leaders  \n\n---\n\n## 🏢 About\n\n**Intelligent Context AI Inc** is the creator of CodeLedger and ContextECF.\n\nIf your team is exploring AI at scale, agent systems, or enterprise context management:\n\n📩 customersuccess@intelligentcontext.ai  \n📞 916-753-7432  \n\n---\n\n> CodeLedger helps you capture truth in code.  \n> ContextECF helps you scale that truth across the enterprise.\n\nImportant:\n- You do not need to keep a separate CodeLedger folder elsewhere on your machine.\n- The long-lived project state lives inside each repo in `.codeledger/`.\n- The global install is just the CLI entry point.\n- For browser/cloud environments, the committed `.codeledger/bin/` runtime is what makes CodeLedger portable.\n\n---\n\n## Why CodeLedger?\n\nAI coding agents are powerful, but on real codebases they waste time, tokens, and accuracy because they lack **targeted context**. CodeLedger fixes that — deterministically.\n\n**No embeddings. No cloud. No telemetry. Fully local at runtime. Fully deterministic.**\n\n| Pain Point (Without CodeLedger) | Feature (With CodeLedger) | How It Works | Benefit |\n|:-|:-|:-|:-|\n| Agent reads 30-50 files before finding the right ones | **Deterministic file selection** | Scores every file across multiple weighted signals and selects the top-ranked set within a token budget | Agent starts with the right files from the first turn |\n| Irrelevant context burns tokens and degrades model accuracy | **Bounded token budgets** | Stop-rule algorithm packs files greedily until the budget is full; `--expand` doubles when you need more | 60-99% context reduction — pay only for what matters |\n| Agent edits files in package A when the task is in package B | **Monorepo scope restriction** (`--scope`) + **Auto-scope inference** | Constrains candidate generation to specified path prefixes. Auto-detects service names in the task (e.g., \"fix auth for api-gateway\") and scopes automatically — no `--scope` flag needed | No cross-package pollution; bundles stay focused |\n| Compound tasks (\"fix auth and add tests\") miss half the files | **Task decomposition** | Splits compound tasks into sub-clauses and unions the discovery results | Every clause gets its own file discovery pass |\n| Agent doesn't know which tests to run after a change | **Blast radius annotation** (`--blast-radius`) | Traces direct dependents, transitive dependents, and impacted test files for each bundle file via the dependency graph | Agent knows exactly what to test and what might break |\n| Hard to tell if the bundle actually covers the task | **Confidence scoring with actionable UX** | Assesses keyword coverage, score distribution, and reason diversity; suggests improvements when confidence is low | Low-confidence bundles come with specific \"try this\" guidance |\n| No visibility into files that almost made the cut | **Near-miss explanation** (`--near-misses`) | Reports the top N excluded files with scores, ranks, budget gaps, and keyword suggestions | Refine your task description or bump budget with precision |\n| \"Add a new endpoint\" tasks lack structural examples | **Pattern exemplars** | Detects creation-intent tasks and includes sibling files from the same directory as structural templates | Agent sees how existing endpoints are built before writing new ones |\n| Bundle scores feel like a black box | **Explain mode** (`--explain`) | Shows the per-file scoring breakdown for every selected file | Full transparency into why each file was chosen |\n| Agent loses context after compaction or long sessions | **Session continuity** (`session-progress`, `session-summary`) | Writes ground-truth snapshots from git (commits, changed files, remaining bundle files) before compaction; session-end recall/precision metrics | Re-orient after compaction without redoing work |\n| Mid-session learning can't feed back into context | **Mid-session refine** (`refine --learned \"...\"`) | Re-scores the bundle with new learned context, extra keywords (`--add-keywords`), and file exclusions (`--drop`); recomputes all derived metadata | Bundle evolves as the agent learns, without starting over |\n| Manually figuring out which files changed on the current branch | **Branch-aware scoring** (`--branch-aware`) | Detects uncommitted and branch-diffed files and boosts their scores automatically | Work-in-progress files float to the top |\n| Config files, type definitions, and contracts get missed | **Surface-aware auto-inclusion** | Automatically includes config files, type definitions, and API contracts that match task keywords | Critical context files never fall through the cracks |\n| Agent reads files in random order, missing structural context | **Architectural layer ordering** (`--layer-order`) | Sorts bundle files by architectural layer (types, models, services, routes, tests) | Agent reads contracts before implementations, just like a human would |\n| Only works on TypeScript/JavaScript repos | **Language-agnostic scanning** | Built-in language registry for 42 file extensions across 15 language families. Python and Go get full deep support (import resolution, test conventions, keyword extraction). Any language works out of the box | Polyglot and multi-language monorepos just work |\n| Co-changed files missing from the bundle | **Shadow Files** | Mines git history to find files that commonly change together and expands the bundle accordingly | Cross-cutting companions (types ↔ tests, schema ↔ migration) included automatically |\n| Agent introduces architectural violations that linters miss | **Review Intelligence** | 5 invariant modules detect missing runtime validation (P1), unguarded outbound HTTP (P1), helper bypass (P2). Baselines, inline suppressions, disposition tracking | Catches architectural risks — not just syntax issues — deterministically |\n| Token estimates are wildly inaccurate across languages | **Language-aware token calibration** | Uses per-language token/line rates (TypeScript 3.5, Python 3.2, Java 4.5, etc.) instead of a flat 4.0 | Budgets are accurate; no over- or under-packing |\n| Task type doesn't influence which files are prioritized | **Task-type inference** | Auto-detects bug fix, feature add, refactor, test update, or config task and adjusts scoring weights accordingly | Bug fixes emphasize error infrastructure; test tasks heavily prioritize test files |\n| TODO/FIXME markers scattered across the codebase are invisible | **TODO/FIXME awareness** | Scans selected files for TODO, FIXME, HACK, XXX markers and surfaces counts in the bundle | Agent sees open work items in the files it's about to edit |\n| No way to compare agent performance with vs. without context | **A/B benchmarking** (`compare`) | Runs the same task twice — once with CodeLedger context, once without — and diffs test pass rate, iterations, token usage, and time | Quantified proof that context selection works |\n| Agent gets stuck in test-fail-edit-retry loops | **Loop detection & circuit-breaker** | Detects repeated test failures, file edit loops, and command retries from the event ledger with configurable thresholds | Stuck agents get a clear signal to change approach |\n| Agent edits files outside the task's scope | **Scope contract enforcement** | Derives allowed file paths from bundle + dependency neighbors; warns or blocks out-of-scope edits | Haphazard changes caught before they land |\n| Multiple agents edit the same files concurrently | **Cross-session conflict zones** | Detects file overlap between active sessions and warns before edits begin | Merge conflicts prevented before they happen |\n| Refreshed bundles re-surface already-resolved files | **Commit-aware bundle invalidation** | Marks bundled files as \"addressed\" when committed; suggests refresh when staleness >= 75% | No re-review parroting — agents move forward |\n| Task objective drifts mid-session without detection | **Intent governance** (`intent`) | Tracks structured task contracts (objective, scope, constraints) with deterministic Jaccard-based drift scoring across 7 fields | Scope creep detected and flagged automatically |\n| Rate limit or crash loses all work-in-progress | **Checkpoint bundles** (`checkpoint`) | Incremental snapshots of bundle state + git HEAD + changed files; restore to resume | Work survives interruptions |\n| No visibility across concurrent agent sessions | **Multi-agent shared summary** (`shared-summary`) | Cross-session overlap matrix, per-session metrics, hotspot detection | Orchestrators see the full picture |\n\n## Install\n\n```bash\n# Recommended: install globally\nnpm install -g @codeledger/cli\n\n# Or use without installing\nnpx @codeledger/cli --version\n\n# Or install as a dev dependency\nnpm install --save-dev @codeledger/cli\n```\n\nVerify it works:\n\n```bash\ncodeledger --version\n```\n\nSee **[GETTING-STARTED.md](GETTING-STARTED.md)** for the full 5-step setup guide, configuration, and troubleshooting.\nFor a command-by-command walkthrough with example output, see the **[CLI Command Reference](https://github.com/codeledgerECF/codeledger/blob/main/docs/CLI_COMMAND_REFERENCE.md)**.\n\n### Alternative: Download from GitHub Releases\n\n**[Download the latest release](https://github.com/codeledgerECF/codeledger/releases/latest)** — extract the zip, then drag `install.sh` into your terminal and press Enter. The installer uses the bundled package from the zip, so the installed wrapper version matches the release. The wrapper then fetches the matching hardened binary from the GitHub release unless your environment already provides it.\n\n## Best For\n\n| Repo Profile | Source Files | Impact |\n|-------------|-------------|--------|\n| Large monolith or service | 500 – 5,000 | **Highest.** Cuts straight to the 10-25 files that matter. |\n| Mid-size application | 100 – 500 | **High.** Sweet spot for tight-budget precision. |\n| Multi-package monorepo | 1,000 – 50,000+ | **High.** Auto-scope inference detects service names in your task automatically. |\n| Small project | 20 – 100 | **Moderate.** Still useful for churn-based prioritization. |\n\n**Rule of thumb:** If your agent regularly reads more than 25 files before making its first edit, CodeLedger will help.\n\n## How It Works\n\n1. **Scans** your repo (dependency graph, git churn, test mappings, content index)\n2. **Ranks** candidate files with deterministic local signals\n3. **Selects** the most relevant files within a token budget\n4. **Delivers** a context bundle your agent reads immediately\n\nSame task + same repo state = same file rankings and content. Every time.\n\nUse `codeledger activate --task \"...\" --explain` to see behavior-level reasons\nfor a specific bundle without exposing protected implementation details.\n\n## Installation Note\n\nAfter a new release, `npm install -g @codeledger/cli` automatically fetches the hardened platform binary from GitHub Releases. For the first ~10 minutes following a release, the binary may still be uploading. The installer retries automatically with backoff — this is expected behavior, not an error.\n\nIf you see \"Binary pending\" messages during install, simply wait. The installer handles the timing automatically and will complete within a few minutes.\n\n## Quick Start\n\n```bash\ncd your-project\ncodeledger init\n```\n\nThat's it. Start your agent and describe your task in plain English. The hooks will:\n1. Extract your intent and scan the repo automatically\n2. Score every file across multiple weighted signals\n3. Select the most relevant files within a token budget\n4. Write a context bundle for your agent to read\n\nNo commands to memorize. Context is ready when your agent starts.\n\nInside an initialized repo, prefer:\n\n```bash\n./.codeledger/bin/codeledger <command>\n```\n\nThat repo-local wrapper prefers a newer global `codeledger` install on your machine and falls back to the vendored standalone runtime in browser, CI, and container environments.\n\n## Agent Integration\n\n### Claude Code (Zero Setup)\n\nCodeLedger ships with Claude Code hooks. Just run `codeledger init` and start Claude Code — `init` warms the repo index, and the SessionStart hook handles activation automatically.\n\n| Hook | When | What |\n|------|------|------|\n| **SessionStart** | Session opens | Scans repo, generates bundle |\n| **PreToolUse** | Before edit/write | Checks activation freshness and warns on CodeLedger reservation conflicts; managed installs may block |\n| **PreCompact** | Before compression | Saves progress snapshot to survive compaction |\n| **Stop** | Session ends | Shows recall/precision metrics |\n\nNo commands to remember. Context is ready when your agent starts.\n\nSee the public [Claude Code hook example](https://github.com/codeledgerECF/codeledger/blob/main/examples/claude-code-hooks.json) for the hook configuration.\n\n### Cursor / Codex / Other Agents\n\nAfter `codeledger init`, your agent reads the `CLAUDE.md` instructions and `.codeledger/active-bundle.md` for context. Hook-aware environments refresh automatically for new meaningful tasks. In local non-hook environments, the repo-local ambient wrappers now apply the same rule before handoff:\n\n```bash\n./.codeledger/bin/codex \"your new task\"\n./.codeledger/bin/claude \"your new task\"\n```\n\nAcknowledgement-only follow-ups like `Yes please` do not refresh context. If you need to trigger the rule directly, use:\n\n```bash\n./.codeledger/bin/codeledger auto-refresh --prompt \"your new task\"\n```\n\nFor plugin-first, mid-session retrieval, ask CodeLedger for refreshed context before using raw search:\n\n```bash\n./.codeledger/bin/codeledger broker refresh --task \"implement the related feature\" --json\n```\n\nThat returns the active bundle, top-ranked files, and bundle delta for the task shift. Use `rg` or manual file search only if the broker result is insufficient.\nHuman-readable broker output also includes matched runtime patterns with ranking reasons like lifecycle status, confidence, reuse count, promotion state, merge count, and the most recent promotion rationale.\n\nFor session-aware inspection during the same run:\n\n```bash\n./.codeledger/bin/codeledger broker current --json\n./.codeledger/bin/codeledger broker timeline --limit 10 --json\n```\n\n`codeledger scan` ends with a compact executive summary, grouped policy recommendations, and suggested next commands. Use `codeledger scan --full-policy` when you want the full override list instead of the compact default view.\n`codeledger memory patterns` shows promoted runtime patterns along with trust basis and promotion state for quick inspection.\n`codeledger memory activity` gives one compact view of active learning proposals plus harvested runtime outcomes.\n\nFor relevance-managed architectural memory:\n\n```bash\ncodeledger memory status\ncodeledger memory explain --id <artifact-id>\ncodeledger memory inject --task \"Fix auth regression\" --paths \"src/auth/login.ts\"\ncodeledger memory compact --dry-run\ncodeledger memory prune --dry-run\n```\n\nPolicy memory is stored under `.codeledger/memory/policy-artifacts.json` and keeps HOT/WARM/COLD/ARCHIVED artifacts deterministic, compact, and auditable.\n`codeledger memory inject` builds the bounded task-start injection bundle that sits on top of DRS: HOT is eligible, not automatically injected.\n\nTask-start injection is driven by a deterministic taxonomy classifier. Before injection, CodeLedger classifies the task into one primary type such as `bug_fix`, `auth_change`, `migration`, `infra_change`, `dependency_change`, `api_change`, `ui_change`, `docs_only`, or `unknown`. It also emits secondary tags like `high_risk`, `shared_core`, `auth_sensitive`, `schema_sensitive`, `customer_visible`, and `incident_related`, plus a confidence score, risk level, complexity, and evidence trace.\n\nIf you need repo-specific tuning, add `.codeledger/taxonomy.yaml`:\n\n```yaml\noverrides:\n  paths:\n    \"services/legacy/**\":\n      boost:\n        refactor: 0.5\n      add_tags:\n        - high_risk\n  keywords:\n    \"decommission\":\n      set_type: migration\n      weight: 1.5\n```\n\nThis lets you bias classification deterministically without changing the global defaults.\n\n## CLI Commands\n\n```bash\n# ── Getting Started ───────────────────────────────────────────\ncodeledger init [--force]                # Set up .codeledger/ with config and scenarios\ncodeledger doctor                        # Integration health check (config, hooks, index, ledger)\n\n# ── Context Selection (daily use) ─────────────────────────────\ncodeledger scan                          # Build repo index (dep graph, churn, test map)\ncodeledger bundle --task \"…\"             # Generate a deterministic context bundle\n  --scope \"src/auth/,src/api/\"           #   Restrict to path prefixes (monorepo-friendly)\n  --near-misses                          #   Show files that almost made the cut\n  --blast-radius                         #   Annotate dependents and impacted tests\n  --explain                              #   Dump per-file scoring breakdown\n  --expand                               #   Double the token budget\n  --layer-order                          #   Sort files by architectural layer\ncodeledger activate --task \"…\"           # Scan-if-stale + bundle + write active-bundle.md\n  --scope --branch-aware                 #   Same flags as bundle, plus branch awareness\n  --near-misses --blast-radius --explain #   All diagnostic flags supported\ncodeledger refine --learned \"…\"          # Re-score with new context mid-session\n  --drop \"file1.ts,file2.ts\"             #   Remove specific files\n  --add-keywords \"pool,cache\"            #   Inject new search terms\n\nCommand-driven activation is now deterministic:\n- CodeLedger now uses a single ambient activation policy table for task-bearing commands\n- pre-refresh commands such as `codeledger context --task \"...\"`, `codeledger broker refresh --task \"...\"`, `codeledger memory inject --task \"...\"`, `codeledger complete-check --task \"...\"`, and `codeledger audit --task \"...\"` establish or refresh task context in the background before they run\n- command-managed commands such as `codeledger task`, `codeledger codex`, `codeledger claude`, `codeledger preflight`, `codeledger bundle`, `codeledger manifest`, `codeledger verify`, and `codeledger activate` establish task context themselves, so the CLI avoids duplicate activation in the same invocation\n- help, version, and status-style commands do not trigger ambient activation\n- `codeledger activate --task \"...\"` remains the explicit/manual fallback and power-user entrypoint\n\nGitHub Copilot support is available through the existing generic task runtime:\n- `codeledger task --agent copilot --agent-bin \"<copilot-compatible command>\" --task \"...\"`\n- for GitHub-hosted Copilot coding agent sessions, use CodeLedger to prepare and verify context around the agent with `bundle` and `verify`\n\nMulti-agent repo coordination is now repo-native:\n- `codeledger claim <paths...>` records active file or directory claims before edits happen\n- `codeledger preflight-edit <path>` checks a target path against active claims and policy before you modify it\n- `codeledger leases`, `codeledger release`, and `codeledger coordination` expose active leases, stale claims, and overlap summaries\n- validation records bind decisions to commit hash, repo fingerprint, session ID, and claimed scopes\n\nProduct promise:\n- Git tells you after two agents collided. CodeLedger tells you before they do.\n\n# ── Session Management ────────────────────────────────────────\ncodeledger session-init                  # Initialize a new session (returns session ID)\ncodeledger sessions                      # List active sessions and file overlaps\ncodeledger session capsule               # Write a durable coding session capsule\ncodeledger session-progress              # Write ground-truth progress snapshot\ncodeledger session-summary               # Show session-end recall/precision metrics\ncodeledger session-cleanup               # Clean up a session's state files\ncodeledger checkpoint create             # Save work-in-progress snapshot\ncodeledger checkpoint restore --id …    # Resume from a checkpoint\ncodeledger checkpoint list               # List available checkpoints\ncodeledger shared-summary                # Cross-session coordination summary\ncodeledger context pack --task \"…\"       # Build reviewer-ready context pack artifacts\ncodeledger review coordinator            # Normalize reviewer output into a judgment artifact\ncodeledger negative-space record         # Record reviewed noise/false-positive evidence\ncodeledger value receipt --session <id>  # Write an evidence-backed value receipt\n\n# ── Intent Governance ─────────────────────────────────────────\ncodeledger intent init --objective \"…\"   # Create a structured task contract\ncodeledger intent show                   # Display drift score and per-field distances\ncodeledger intent set --objective \"…\"    # Update contract fields mid-session\ncodeledger intent ack                    # Acknowledge drift (reset or accept)\n\n# ── CI / Enterprise Governance ────────────────────────────────\ncodeledger setup-ci                      # Generate CI workflow + policy file\n  --provider github|gitlab|circleci|azure #  CI provider (default: github)\n  --mode observe|warn|block              #   Set enforcement level (default: warn)\n  --output <dir>                         #   Custom workflow directory\ncodeledger manifest --task \"…\"           # Generate deterministic context manifest\ncodeledger sign-manifest --in … --out …  # Sign a manifest with HMAC-SHA256\ncodeledger policy --print                # Show resolved policy for current repo\ncodeledger verify --task \"…\"             # CI enforcement: evaluate policy, emit artifacts\n  --explain                              #   Show richer reasoning and repo-standard examples\n  --json                                 #   Machine-readable output for CI/AI agents\n  --invariant <name>                     #   Narrow to one invariant module\n\n# ── API Server & Compliance ──────────────────────────────────\ncodeledger serve                         # Start HTTP API server (default: port 7400)\n  --port 7400                            #   GET /health, /drift, /outcome, /reality-check, /metrics, /provenance, /policy\n                                         #   GET /architecture-health/*, /broker/timeline, /broker/current\n                                         #   POST /verify, /bundle, /harvest, /snapshot, /time-travel, /context-handoff\n                                         #   POST /broker/resolve, /broker/validation, /broker/neighborhood,\n                                         #        /broker/evidence, /broker/completion, /broker/preamble, /broker/refresh\n                                         #   Use `codeledger serve --help` for the full endpoint list\ncodeledger audit-export                  # Export ledger to JSON, CSV, or JSON Lines\n  --format json|csv|jsonl                #   SIEM-compatible output\n  --output <path>                        #   Write to file (default: stdout)\n  --table runs|events|bundles|coverage   #   Filter to one table\n  --raw                                  #   Opt into privileged raw export; default output is sanitized\ncodeledger provenance trace --task \"…\"   # Trace provenance for one task\ncodeledger provenance export --json      # Export provenance graph (sanitized by default)\n\n# ── Cowork (Knowledge Mode) ──────────────────────────────────\ncodeledger cowork-start --intent \"…\"     # Scan workspace + generate context bundle\ncodeledger cowork-refresh --intent \"…\"   # Re-run selection with updated intent\ncodeledger cowork-snapshot               # Write progress snapshot for continuity\ncodeledger cowork-stop                   # Finalize session + print summary\n\n# ── Benchmarking ──────────────────────────────────────────────\ncodeledger run --scenario …              # Execute a single benchmark scenario\ncodeledger compare --scenario …          # A/B comparison: with vs without CodeLedger\ncodeledger share [--format twitter]      # Generate shareable result snippet\ncodeledger clean                         # Remove orphaned worktrees\n```\n\n## Benchmark Results\n\n| Metric | Without CodeLedger | With CodeLedger | Delta |\n|--------|-------------------|-----------------|-------|\n| Tests Passed | 78% | 94% | **+16%** |\n| Iterations | 4 | 2 | **-50%** |\n| Files Changed | 17 | 9 | **-47%** |\n| Time to Finish | 6m 12s | 3m 40s | **-41%** |\n| Token Usage | 28k | 18k | **-36%** |\n\n*Example results from a mid-sized Node.js service.*\n\n### Selector Quality (CI-Enforced)\n\n| Budget | Avg Recall | Avg Precision |\n|--------|-----------|---------------|\n| **Tight** (10 files) | 100% | 62.5% |\n| **Default** (25 files) | 100% | -- |\n\n## How the Scoring Works\n\nCodeLedger uses a multi-stage candidate pipeline and a ten-signal scorer:\n\n**Candidate Generation:**\nMulti-stage pipeline combining keyword analysis, graph traversal, test pairing, and git history signals.\n\n**Scoring:**\nDeterministic weighted combination of positive and negative signals, configurable in `.codeledger/config.json`.\n\n**Post-Selection Enrichment:**\n- Confidence assessment with actionable suggestions\n- Pattern exemplars for creation-intent tasks\n- Near-miss explanation with budget gap analysis\n- Blast radius annotation with impacted test discovery\n- Architectural layer ordering\n- TODO/FIXME marker surfacing\n- Task-type inference (bug fix, feature, refactor, test, config)\n- Scope contract derivation (bundle files + dependency neighbors)\n- Commit-aware invalidation (addressed files marked as stale)\n- Shadow file annotations (temporal co-commit companions with boost reasons)\n- Intent drift scoring (objective/scope/constraint change detection)\n\nRun `codeledger bundle --task \"…\" --explain` to see per-file selection reasons\nfor a specific task.\n\n## Review Intelligence\n\n`codeledger verify` includes **Review Intelligence** — a repository-aware architectural verification layer that catches risks linters and SAST tools miss. Runs automatically with zero configuration:\n\n- **Runtime validation** — catches typed routes without runtime input validation (P1)\n- **Outbound I/O safety** — flags HTTP calls without timeouts (P1)\n- **Repository drift** — detects bypass of sanctioned helpers/wrappers (P2)\n- **Repo-standard discovery** — automatically finds and recommends helpers already used in your repo\n- **AI repair loop** — structured JSON output lets AI agents patch and re-verify\n\nFindings support baselines (`--update-baseline`), inline suppressions (`// codeledger: ignore <rule>`), and dispositions (new/baselined/suppressed). CI blocks only on **new** P0/P1 findings.\n\n## Agent Governance\n\nCodeLedger extends beyond context selection into **deterministic agent governance** — three containment layers that keep agents productive without requiring LLM judgment:\n\n**Context Containment** — what the agent sees:\n- Deterministic scoring, bounded budgets, intent-tracked bundles\n\n**Execution Containment** — what the agent does:\n- Scope contracts prevent out-of-scope edits\n- Loop detection catches stuck agents before they waste tokens\n- Cross-session conflict zones prevent concurrent agents from colliding\n- Intent drift scoring flags when the task objective has changed\n\n**Quality Containment** — what the agent produces:\n- Commit-aware invalidation prevents re-review parroting\n- Checkpoint bundles enable resume after interruption\n- Multi-agent shared summaries give orchestrators full visibility\n\nAll governance features are **deterministic** — numeric thresholds, pattern matching, and set distance calculations. No LLM reasoning. No probabilistic language. Fully auditable.\n\n## Architecture: Open Surface, Closed Engine\n\n```\n┌──────────────────────────────────────────────────────┐\n│  PUBLIC (MIT License)                                │\n│  CLI · Types · Repo Scanner · Harness · Report       │\n│  Hooks · Config · Scenarios · Quality Tests          │\n├──────────────────────────────────────────────────────┤\n│  PROTECTED (CodeLedger Core License)                 │\n│  Scoring Engine · Selection Algorithm · Confidence   │\n│  Shipped as platform-specific hardened binaries      │\n│  Runtime local by default · No source telemetry      │\n└──────────────────────────────────────────────────────┘\n```\n\nThe CLI wrapper, benchmarking harness, types, and repo scanning are fully open — inspect them, contribute improvements, build trust. The protected engine ships as platform-specific hardened binaries to protect the IP while keeping runtime behavior local and inspectable through public receipts.\n\nUse `codeledger about`, `codeledger doctor`, and command-specific `--explain`\noutput to inspect behavior, health, and evidence without exposing protected\nimplementation internals.\n\n## Share Your Results\n\n```bash\ncodeledger share                        # Markdown summary\ncodeledger share --format twitter       # Copy-pasteable tweet\ncodeledger share --format linkedin      # LinkedIn post\ncodeledger share --clipboard            # Copy to clipboard\n```\n\n## Privacy\n\n- **Installation** may use npm and GitHub Releases to fetch the wrapper and matching hardened binary\n- **After install**, analysis runs on your local machine\n- Runtime analysis makes zero source-code telemetry calls by default\n- Collects zero telemetry\n- Your source code never leaves your machine\n- No account required\n- Uninstall at any time\n\n## Contributing\n\nThe scoring engine is closed, but there are many ways to contribute:\n\n- **Bug reports** — file issues with reproduction steps\n- **Feature requests** — propose new CLI commands, output formats, or agent integrations\n- **Documentation** — improve guides, examples, and troubleshooting\n- **Benchmark scenarios** — suggest new task/repo combinations for testing\n- **Agent adapters** — add support for new AI coding tools\n\nSee the public [contribution guide](https://github.com/codeledgerECF/codeledger/blob/main/CONTRIBUTING.md) for details.\n\n## Prerequisites\n\n| Requirement | Minimum | Check |\n|-------------|---------|-------|\n| Node.js | v20+ | `node -v` |\n| npm | v9+ | `npm -v` |\n| Git | v2.15+ | `git --version` |\n\n## Tiers\n\n| | **Individual (Free)** | **Team** | **Organization** |\n|---|---|---|---|\n| **Who** | Solo devs, personal projects, OSS | Dev teams (>1 developer), commercial | Engineering orgs, enterprise, regulated |\n| **Context selection** | Full (multi-signal, Shadow Files, auto-scope) | Same | Same |\n| **Agent governance** | Full (scope, loops, intent, checkpoints) | Same | Same |\n| **Review Intelligence** | Full (5 invariant modules) | Same | Same |\n| **Multi-session coordination** | — | Conflict zones, shared summary | Same |\n| **CI enforcement** | — | `setup-ci` for 4 CI providers | Same |\n| **Audit & compliance** | — | — | Audit export (JSON/CSV/JSONL), manifest signing |\n| **Deployment** | Local CLI | Local CLI | + Docker, Helm, AWS, Terraform |\n| **API server** | — | — | `codeledger serve` |\n| **Policy cascading** | — | — | Org → repo policy resolution |\n| **Enterprise platform** | — | — | [ContextECF](https://timetocontext.co) |\n| **Price** | Free | [Contact us](mailto:team@codeledger.dev) | [Contact us](mailto:team@codeledger.dev) |\n\nStart free. Tier up when your team — or your compliance team — needs more.\n\n## License\n\n- **Plugin (CLI, types, repo, harness, report):** [MIT](LICENSE)\n- **Downloaded hardened binary:** [CodeLedger Core License](LICENSE-CORE) — free for individuals and OSS, commercial use requires a license\n\n## Links\n\n- [Getting Started Guide](GETTING-STARTED.md)\n- [Public Architecture Overview](ARCHITECTURE_OVERVIEW.md)\n- [Release Notes](RELEASE_NOTES.md)\n- [CodeLedger](https://codeledger.dev)\n- [npm: @codeledger/cli](https://www.npmjs.com/package/@codeledger/cli)\n- [ContextECF Enterprise](https://timetocontext.co)\n\n## Philosophy\n\nLarge context windows are not the answer.\n\n**Smarter context selection is.**\n\n---\n\n<sub>**CodeLedger** is produced by Intelligent Context AI, Inc. [timetocontext.co](https://timetocontext.co) · [codeledger.dev](https://codeledger.dev)</sub>\n",
  "bytes": 41333,
  "sha": "1d6d74d6cb31d0cb684d7870bfecabe3b9089706fb2c7b70f388b17f5e0d7898",
  "repo_slug": "codeledgerecf/codeledger",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_codeledgerecf_codeledger_85175d59/readme"
}