# chameleon architecture > *"Code that blends in."* This document describes how chameleon works as built. It is the reference for the bootstrap pipeline, the hook stack, the MCP tool surface, the enforcement and review gate, the profile schema, the state stores, and the security model. It tracks engine version **4.10.0** and profile **schema version 8**. When the code and this document disagree, the code is right; please file an issue. ## Contents - [Purpose and honest boundary](#purpose-and-honest-boundary) - [Vocabulary](#vocabulary) - [System overview](#system-overview) - [Repository layout](#repository-layout) - [The profile](#the-profile) - [Bootstrap and refresh pipeline](#bootstrap-and-refresh-pipeline) - [Language tiers](#language-tiers) - [Production-ref derivation](#production-ref-derivation) - [Cluster signature function](#cluster-signature-function) - [Canonical selection](#canonical-selection) - [Conventions derivation](#conventions-derivation) - [Cross-file indexes](#cross-file-indexes) - [Hook stack](#hook-stack) - [MCP server (chameleon-mcp)](#mcp-server-chameleon-mcp) - [Enforcement](#enforcement) - [The review gate and trust path](#the-review-gate-and-trust-path) - [Trust model](#trust-model) - [Atomicity, locking, and crash safety](#atomicity-locking-and-crash-safety) - [State stores](#state-stores) - [The advisor daemon](#the-advisor-daemon) - [Security model](#security-model) - [Performance characteristics](#performance-characteristics) - [Configuration and environment](#configuration-and-environment) - [Versioning and schema migrations](#versioning-and-schema-migrations) - [What stays human](#what-stays-human) - [Glossary](#glossary) --- ## Purpose and honest boundary chameleon gives the model deep knowledge of *your* repo's conventions: not a list of pre-known framework patterns, but the patterns your team actually wrote. It clusters AST and statistical signals from the codebase, captures the idioms an AST cannot infer through `/chameleon-teach`, and injects archetype-keyed guidance on every edit. **North star:** a machine review gate good enough that human review moves from mandatory to on-demand for the change classes the engine provably covers. chameleon does not certify correctness, and no amount of static AST plus statistics ever will. What it does is cover the review classes it covers well, reserve human eyes for the classes it cannot, and give a team lead the evidence to trust that split. **What the gate covers, deterministically and per-repo calibrated:** structural and convention conformance, hallucinated imports and symbols, hardcoded secrets, supply-chain red flags in manifests and lockfiles, and cross-file symbol-existence breaks. On top of that it runs an advisory LLM judge at PR-review and turn-end that reads the diff for logic-delta regressions (a removed guard, a dropped await, an inverted condition). **What stays human, always:** business-logic correctness, novel security flaws (authorization logic, IDOR, complex injection, crypto design), and architectural judgment. The LLM judge helps on these; it is not a principal engineer, so it advises and never gates alone. Anything in an unsupported language, below a sample-size threshold, or in a file class the engine does not verify goes to a human regardless of gate color. See [What stays human](#what-stays-human) for the full list. **Supported stacks:** TypeScript / JavaScript, Ruby, and Python as first-class languages, plus Go, Rust, Java, C# and PHP at the extraction tier. Claude Code only. The core is framework-agnostic: it learns each repo's conventions from the repo's own structure (clustering, naming, signatures), so it works on any framework, not just well-known ones. Where a framework has strong, well-known conventions, chameleon adapts for deeper, framework-aware guidance: Rails for Ruby; Django, DRF, Flask, and FastAPI for Python; and Next.js and NestJS for TypeScript / JavaScript. The TS framework layer is lighter than the Rails/Django ones (framework detection, naming roles, and framework-specific anti-hallucination guidance, rather than the full guard/contract derivation), but it is no longer absent. Five more languages are supported one tier down: Go, Rust, Java, C#, PHP. See [Language tiers](#language-tiers) for what each tier gets and why the split exists. The three first-class languages each have a dedicated parser: the TypeScript extractor uses the TypeScript Compiler API, the Ruby extractor uses Prism, and the Python extractor uses libcst (bundled with the plugin, so Python repos need nothing extra installed). All three also parse in-process through tree-sitter, which is the default backend; the dump scripts are the fallback, kept because they need no Python-side parser at all (`CHAMELEON_TREE_SITTER=0` reverts to them). Python framework awareness keys on filename conventions (`models.py`/`views.py`/`serializers.py` → cross-app role archetypes) and the web-layer directory (`routes/`, `blueprints/`), with decorators and base classes captured for finer discrimination. --- ## Vocabulary Five user-facing terms carry the whole model: - **profile** the team's conventions captured in `.chameleon/`, committed to git. - **archetype** a category of file with shared patterns (controller, service, hook, component, worker). - **idiom** a team-specific rule or banned pattern that an AST cannot infer. - **refresh** automated re-analysis (`/chameleon-refresh`). - **trust** per-user approval of a committed profile (`/chameleon-trust`). Internal terms (`canonical`, `witness`, `normative shape`, `content_signal`, `cluster signature`, `recency weight`) appear in this document and the code, not in user-facing copy. The context tag is neutral: ``, with no importance framing, so it never competes with other plugins' framing. --- ## System overview chameleon has two halves: the **engine** (one plugin, shipped to every user) and the **profile** (per-repo data, committed to each repo). The engine carries no repo-specific knowledge; the profile carries no code. ``` +--------------------------------------------------------------------------+ | Engine (the chameleon plugin) | | | | Hooks (subprocess-per-call, fail-open) Skills (static prose) | | - session-start (SessionStart) - using-chameleon (auto) | | - preflight-and-advise (PreToolUse) - 14 user-invocable /commands| | - peer-skill-advise (PreToolUse) | | - posttool-recorder (PostToolUse) | | - posttool-verify (PostToolUse) | | - callout-detector (UserPromptSubmit) | | - stop-backstop (Stop / SubagentStop) | | | | | v | | MCP server (chameleon-mcp, FastMCP, stdio) -- 21 tools | | | | | +---------------+----------------+ | | v v | | AST extractors Bootstrap / refresh pipeline | | - tree-sitter, in-process (default) detect -> discover -> parse -> | | * TS/JS, Ruby, Python cluster -> canonical -> conventions | | * Go, Rust, Java, C#, PHP -> atomic commit | | (declarative specs) | | - dump-script fallback: | | ts_dump.mjs / prism_dump.rb / libcst_dump.py | +--------------------------------------------------------------------------+ Per-repo, committed to git: Per-user, local only (never committed): /.chameleon/ ~/.local/share/chameleon/ profile.json, archetypes.json, index.db (repo registry) canonicals.json, conventions.json, / rules.json, idioms.md, principles.md, drift.db, .trust, conventions.md (memory-channel mirror), config.json, *index*.json, ... .pause_until, prodtree/, markers ``` The engine talks to the model only through hooks. Hooks call the MCP server, the MCP server reads the profile, and the result is injected as a `` block. The model never has to call an MCP tool by hand, though the same tools are available to it and to the `/chameleon-*` skills. chameleon ships one auto-fired skill (`using-chameleon`) and fourteen user-invocable slash commands (14 commands); the full list is in the [README](../README.md#slash-commands). A per-user **advisor daemon** (POSIX only) is an optional performance layer that holds the profile in memory and answers hot-path hook lookups over a unix socket. It is never load-bearing: every hook falls back to an in-process lookup if the daemon is absent. See [The advisor daemon](#the-advisor-daemon). --- ## Repository layout ``` chameleon/ ├── .claude-plugin/ │ └── marketplace.json # marketplace entry (source: ./plugin) ├── plugin/ # the installable plugin surface — what a marketplace install copies │ ├── .claude-plugin/ │ │ └── plugin.json # plugin manifest (version anchor) │ ├── .mcp.json # launches chameleon-mcp via uvx │ ├── hooks/ │ │ ├── hooks.json # hook registrations │ │ ├── run-hook.cmd # cross-platform polyglot dispatcher │ │ ├── _resolve-python.sh # interpreter resolution ladder (>=3.11) │ │ ├── session-start │ │ ├── preflight-and-advise │ │ ├── peer-skill-advise │ │ ├── posttool-recorder │ │ ├── posttool-verify │ │ ├── callout-detector │ │ └── stop-backstop │ ├── skills/ │ │ ├── using-chameleon/ # auto-fired foundation skill │ │ └── chameleon-*/ # 14 user-invocable slash commands │ ├── agents/ # code-scout, pattern-reviewer, recall-lens, │ │ # verifier, web-researcher │ ├── mcp/ │ │ ├── pyproject.toml # Python package (requires-python >=3.11) │ │ ├── uv.lock, package.json # committed locks │ │ ├── typescript-checksums.json # build-time SHA-256 manifest (not verified at runtime) │ │ └── chameleon_mcp/ # the Python package (see below) │ │ ├── extractors/ │ │ │ └── treesitter/ # in-process backend + lang/specs.py (the │ │ │ # declarative specs for Go/Rust/Java/C#/PHP) │ │ └── knowledge/ # taxonomy.json (541 concepts) + its loader │ │ # and the scored framework detector │ ├── scripts/ # runtime scripts shipped with the plugin │ │ ├── ts_dump.mjs # TypeScript AST extractor (Node) │ │ ├── prism_dump.rb # Ruby AST extractor (Prism) │ │ ├── libcst_dump.py # Python AST extractor (libcst) │ │ ├── chameleon-merge-driver.sh # git merge driver for .chameleon │ │ └── setup.sh # prerequisite check + dependency warm-up │ └── bin/ │ └── chameleon-statusline.sh # status line (<100ms budget) ├── chromatophore/ # the Rust extraction engine, NOT shipped in the │ # plugin, built separately, carries its own gates ├── scripts/ # dev-only tooling (not shipped) │ ├── bump-version.sh # keeps six manifests in sync │ └── ... ├── tests/ # unit/, journey/, effectiveness/, qa_*.py └── docs/ # architecture.md, install.md, qa-team.md ``` The Python package (`plugin/mcp/chameleon_mcp/`) is the brain. The load-bearing modules: `server.py` (FastMCP tool registry), `tools.py` (tool implementations), `hook_helper.py` (the hook dispatch entry point and all gate logic), `bootstrap/` (the derivation pipeline), `extractors/` (language dispatch), `language_support.py` (the per-language tier declaration everything else reads), `knowledge/` (the compiled-in taxonomy, its loader, and the scored framework detector), `profile/` (schema, loader, config, trust), `conventions.py` and `lint_engine.py` (convention derivation and linting), `enforcement.py` and `enforcement_calibration.py` (the block gate and its calibration), `judge.py` and friends (the advisory review layer), and the cross-file index modules (`symbol_index.py`, `calls_index.py`, `function_catalog.py`, `symbol_signatures.py`). --- ## The profile A profile is a directory of committed artifacts plus a set of per-user local files. The committed half is what makes conventions team-shared and reviewable in a PR. ### Committed artifacts (`/.chameleon/`) All JSON artifacts carry `schema_version`, `engine_min_version`, and a `generation` counter. They are written together inside one atomic transaction. | File | Contents | |---|---| | `COMMITTED` | Sentinel written last; loaders refuse the profile without it. | | `profile.json` | Manifest: repo_id, language, source, archetype count, workspace block, tool-config sources, `derivation_source` provenance. | | `archetypes.json` | Per-archetype cluster facts: id, size, path pattern, content signal, top-level node kinds, export shape, optional sub-buckets, summary. | | `canonicals.json` | Per-archetype canonical: the witness (path + sha hint), normative shape (AST query + callable signatures), normative idioms (comments), and the secret/injection/poisoning scan verdicts. | | `conventions.json` | Per-archetype derived conventions (imports, naming, error handling, body shape, doc coverage, test pairing, inheritance and method calls for Ruby, class contract, key exports) plus repo-level layering. | | `principles.md` | Data-backed prose principles generated from conventions. | | `conventions.md` | The CLAUDE.md-channel mirror: the rendered conventions block PLUS the principles sections and a TEAM IDIOMS gist section (one `- name: first-sentence directive` line per active idiom, rendered from the `idioms/` store), for wiring into Claude's memory channel via a one-line `.claude/rules/chameleon-conventions.md`, `CLAUDE.local.md`, or a `CLAUDE.md` import (init offers all three, consent-gated; none edits an existing file by default). Rewritten by bootstrap/refresh, re-synced by teach/unteach after every conventions.json or idioms.md mutation, self-healed from disk on a noop refresh when missing or older-format; absent when nothing renders. Kill switch `CHAMELEON_CONVENTIONS_MD=0`. Motive: memory-channel delivery measured 100% rule adherence vs 40% for the same content as a hook advisory (results-published/migration-ab-2026-07-11.md). Because the mirror is the complete session-conventions content, a wired import lets SessionStart skip its duplicate hook injection (`CHAMELEON_MEMORY_CHANNEL_DEDUP`). (Pre-3.4.0 this also let the Stop idiom-review interrupt render mirror-carried idioms as gists via `CHAMELEON_STOP_IDIOM_GIST`; that interrupt is gone — idiom review is now the async job's idiom lens, see [Turn-end advisories](#turn-end-advisories-on-by-default-never-block).) | | `rules.json` | Tool-derived rules keyed by source: prettier, tsconfig compiler options, eslint, editorconfig, rubocop. | | `idioms/` | The idiom store: one schema-validated JSON file per idiom (`core/idiom_store.py`, schema `chameleon-idiom-1`), the single source of idiom truth. Each record carries a slug, title, body, scope, status (`active`/`deprecated`), and source (`taught`/`auto`/`learned`). Per-file storage keeps git merges trivial and scopes the injection scan to one idiom. `core/idiom_store.py` is the only reader/writer. | | `idioms.md` | A generated *view* of the `idioms/` store (rendered by `regenerate_views`), not a source of truth. A first run writes an empty template; a legacy hand-authored `idioms.md` migrates into the store on the next teach (`migrate_idioms_md`, `records_from_markdown`). Kept for human review and PR diffs. | | `idiom-candidates/` | The self-learning miner's never-auto-adopted proposals: one `.json` per candidate with an evidence trail. Deliberately **not** part of the trust-hashed surface (`_HASHED_ARTIFACTS`) — hashing unreviewed output would arm the trust gate on the miner itself. A candidate becomes a real idiom only through the same `/chameleon-teach` path a hand-taught idiom uses. See [Self-learning idiom miner](#self-learning-idiom-miner). | | `profile.summary.md` | Human-readable summary for PR review and the trust prompt. | | `enforcement.json` | Per-rule block-calibration verdict (`{rule: {active, fp_rate, sampled, flagged}}`; the two calibration-exempt security rules also carry `exempt_reason: "security-rule"` and are active regardless of this artifact). | | `exports_index.json`, `reverse_index.json` | Symbol export map and its inverse importer graph. TS/JS + Python (`REVERSE_INDEXED_LANGUAGES`). | | `function_catalog.json` | Per-function name, shape, and body-hash for the duplication prefilter. All three languages. | | `calls_index.json` | Deterministic caller -> callee edges for the judge. All three languages. | | `symbol_signatures.json` | Per-callable signature and body span for forward-definition hydration. All three languages (declared types TS only). | | `constant_index.json` | Ruby-only: per-constant reverse index mapping constant references to their defining class, backing the cross-file call-site analysis. | | `counterexamples.json` | Per-archetype off-pattern counterexample: a real instance of a taught discouraged import, paired with the witness at edit time as a "do NOT write it this way" example. Built at teach time and bootstrap/refresh; drop-stale. | | `renames.json` | User archetype-rename overlay (written only when a rename map exists). | | `config.json` | Operator-managed: `production_ref`, `auto_refresh`, `enforcement`, `trust`, `canonical_ref`. Read, never produced, by bootstrap. | ### Per-user local state (`~/.local/share/chameleon/`) Overridable with `CHAMELEON_PLUGIN_DATA`. Never committed, never exfiltrated. | Path | Contents | |---|---| | `index.db` | SQLite registry of every repo this user has bootstrapped. | | `/drift.db` | Per-edit confidence history, override audit, decision log, finding ledger. | | `/.trust` | Per-user trust grant for this repo. | | `/.pause_until` | `/chameleon-pause-15m` expiry (line 1) + HMAC `sig=` line; with the per-user key available an unsigned/forged marker is ignored, so a live pre-4.0.1 marker stops suppressing after upgrade. | | `/.session_disabled.` | HMAC-signed per-session disable marker. | | `/prodtree/` | Materialized production-branch worktrees (swept after use). | | `/.intent..ndjson` | Captured intent tokens and digests (never raw prose). | | `/review_ledger.ndjson`, `session_attestations.ndjson` | HMAC-signed review and attestation records. | | `/findings_ledger.json` | The canonical turn-end Finding-lifecycle ledger (`review_ledger.py`): one row per finding `match_key`, walking `pending`/`delivered`/`addressed`/`resurfaced`/`shelved`/`expired`. Local, not committed. See [Turn-end advisories](#turn-end-advisories-on-by-default-never-block). | | `/cross_reverse_index.json` | Monorepo cross-workspace import edges (deliberately off the trust-hashed profile surface). | The Bash exec log lives separately under `${TMPDIR:-/tmp}/.chameleon_exec_log//` (mode 0700), and the HMAC key under `~/.claude/hooks/.exec_hmac.key` (mode 0600, overridable with `CHAMELEON_HMAC_KEY_PATH`). --- ## Bootstrap and refresh pipeline `/chameleon-init` calls `chameleon_lifecycle(action="bootstrap_repo", ...)`; `/chameleon-refresh` calls `chameleon_lifecycle(action="refresh_repo", ...)`. Both delegate to the same orchestrator, which runs once for the repo root and once per detected monorepo workspace. Before the pipeline runs, the tool wrapper applies three guards: it refuses an unsafe root (a temp-dir or world-writable directory, override `CHAMELEON_ALLOW_TMP_REPO=1`), warns on a non-git parent with git children, and sweeps orphaned transaction directories from crashed prior runs. When a `production_ref` lock exists it resolves the ref and materializes a worktree to analyze (see [Production-ref derivation](#production-ref-derivation)). The pipeline stages, in order: 1. **Workspace detection.** Detect pnpm/yarn/lerna/turbo/nx workspaces and monorepo layouts; fan out to each workspace root. 2. **Tool-config read.** Read eslint, prettier, tsconfig, rubocop, editorconfig. 3. **Language detect.** Select the extractor, first match wins. TypeScript wins on a `tsconfig.json`, or a `package.json` naming `typescript`/`ts-node`/`vite`, or a bounded scan of `.ts`/`.tsx` files. Ruby wins on a `Gemfile` or any `*.gemspec`. Python wins on a project marker (`pyproject.toml`, `setup.py`, `setup.cfg`, `requirements.txt`, `manage.py`, `Pipfile`, `tox.ini`) or, absent all of them, any `*.py` file in the tree. No supported signal yields `failed_unsupported_language`. 4. **Discovery and exclusion.** Enumerate candidate source files, excluding generated, vendored, and test directories from the canonical pool. A post-exclusion ceiling of 200k files raises `TooManyFilesError`; large repos pass an explicit `paths_glob`. 5. **AST parse.** Run the extractor over the candidates. A missing language toolchain degrades to a typed report naming the actual missing toolchain (`failed_node_unavailable` for TS, `failed_ruby_unavailable` for Ruby, `failed_python_unavailable` for Python, with a generic `failed_extractor_unavailable` fallback), not a crash. A corpus that parsed too poorly degrades to `failed_extractor_degraded`. 6. **Clustering.** Group files by their [cluster signature](#cluster-signature-function), then run loose-merge, shape-fuzzy-merge, and sub-bucket-split passes. Generated files are skipped here. 7. **Canonical selection.** For each dense cluster, pick the witness that passes all [security scans](#canonical-selection). Sparse clusters never reach this stage. 8. **Archetype assembly and naming.** Build archetype and canonical entries, derive the normative AST query, and propose archetype names. 9. **Conventions derivation.** Re-read members for declarations and derive per-archetype conventions; merge taught competing imports from the prior profile. 10. **Rules assembly.** Convert tool configs to `rules.json`. 11. **Idiom store carry-forward.** The `.chameleon/idioms/` store is idiom truth and is carried forward untouched; its `idioms.md` and conventions.md views are re-rendered from it. A first run writes an empty template; a legacy hand-authored `idioms.md` is migrated into the store on the next teach. 12. **Atomic commit.** Write every artifact and index, fsync, write the `COMMITTED` sentinel last, and flock-serialize the directory rename. See [Atomicity](#atomicity-locking-and-crash-safety). 13. **Drift baseline.** Record the post-commit baseline, best-effort. ### Extractors and limits Two backends, one `ParsedFile` contract. The in-process tree-sitter path is the default and the only path for the five spec-driven languages; the dump scripts below are the fallback for the first-class three and the path a missing grammar or an ABI mismatch falls back to. The tree-sitter walker mirrors the same ceilings (`TS_MAX_AST_NODES`, `TS_MAX_CALL_SITES`, `TS_MAX_CALLABLE_SIGNATURES` in `_thresholds.py`), so the bounds below hold either way. The three dump-script extractors are long-lived subprocesses fed file paths on stdin, emitting NDJSON on stdout, read under a 600-second wall-clock timeout. They are spawned from a neutral working directory with the interpreter's startup-injection environment scrubbed so they never load repo-controlled startup code: Ruby drops `RUBYOPT`/`RUBYLIB`; TypeScript pops `NODE_OPTIONS` (so a poisoned `--require` cannot preload code) and sets `NODE_PATH`/`CHAMELEON_NODE_MODULES` itself; Python drops `PYTHONPATH`/`PYTHONSTARTUP`. Per-file ceilings are application-level, enforced inside the extractor: `MAX_AST_NODES` (50,000 for TS and Ruby; 165,000 for Python, because libcst CST nodes are roughly 3.3x denser and an equal ceiling would unfairly drop equivalent Python files), `MAX_FILE_SIZE = 1_000_000` bytes, `MAX_PARSE_DIAGNOSTICS = 20`, `MAX_CALLABLE_SIGNATURES`, and `MAX_CALL_SITES`. A symlink is refused; an oversize or too-broken file is skipped and marked so the partial corpus stays visible. There is no OS-level RSS or CPU rlimit and no `--max-old-space-size`; the bound is the node/byte ceilings plus the wall clock. The TypeScript toolchain is provisioned at first use, not vendored. The first `/chameleon-init` on a TS repo runs `npm ci`/`npm install` into a per-user, version-scoped directory under the data dir. `plugin/mcp/typescript-checksums.json` is a SHA-256 manifest generated by `scripts/generate-typescript-checksums.sh` (dev tooling, repo root). It is a build-time integrity reference only; it is **not** cryptographically verified on the extraction hot path. --- ## Language tiers Chameleon supports eight languages at two depths, and the split is declared as data in `chameleon_mcp/language_support.py` rather than left to be inferred from which lists a language appears in. `/chameleon-doctor` and `docs/language-support-matrix.md` both read the tier from that one place, and `tests/unit/test_language_support.py` pins the declaration against the real wiring. The split exists to prevent one specific failure. A language wired into the extractor but not into the lint engine derives archetypes, conventions and signatures perfectly well while every lint rule silently returns nothing, and that silence is indistinguishable from "your code is clean". Naming the tier turns an invisible absence into a stated one. | | First-class (TS/JS, Ruby, Python) | Extraction (Go, Rust, Java, C#, PHP) | |---|:--:|:--:| | Archetypes, canonical witness | yes | yes | | Callable signatures, imports | yes | yes | | Conventions | yes | the language-agnostic sections only (see below) | | Secret + eval-sink detection | yes | yes | | Per-edit lint rules | yes | no | | Reverse/exports index (`query_symbol_importers`, removed-export checks) | yes | no | | Graded cross-file call edges | yes | same-file edges only | An extraction-tier language is a declarative `LanguageSpec` in `extractors/treesitter/lang/specs.py`: node kinds and grammar field names, which `spec_driven.build` turns into the same table object the walker calls for the first-class three. Adding one is data, not code, and `tests/unit/test_spec_driven_lang.py` validates each spec against its LOADED grammar, so a spec naming a node the grammar does not have fails in CI rather than matching nothing. `_spec_driven_extractor_classes()` splices them into `EXTRACTORS` between Ruby and Python: after TS/Ruby because those carry equally strong markers, before Python because `PythonExtractor.can_handle` claims any repo holding a single `.py` file. Detection requires a build MANIFEST (`go.mod`, `Cargo.toml`, `pom.xml`/`build.gradle`, `global.json`, `composer.json`) plus real source, so one vendored `.go` file does not make a repo Go, and `_resolve_first_class_precedence` hands a match back to a first-class language that outranks it, so a PyO3 crate's `pyproject.toml` beside its `Cargo.toml` still profiles as Python. `CHAMELEON_TREE_SITTER=0` turns off the in-process backend. The first-class three fall back to their dump scripts; the extraction tier has no fallback, so a repo it claims stops at `failed_extractor_unavailable` with an error naming the switch, rather than silently profiling as something else. **Which conventions actually derive at the extraction tier.** The sections keyed off the parsed shape run for every language: repo-wide preferred imports, `callable_signatures`, `body_shape`, and the path-only file-naming half of `naming`. The sections that dispatch on language do not: identifier `naming` and `doc_coverage` both re-read file bytes through language-specific scanners that return nothing for an unknown language, and `error_handling`, `inheritance`, `method_calls`, `required_guards`, `class_contract` and `key_exports` are each gated on the first-class three. So an extraction-tier archetype carries a shape and a witness, and absent guidance rather than wrong guidance. **Two languages in one repo.** Bootstrap binds one extractor, and therefore one primary language, per profile. Everything else the repo genuinely contains is picked up as a *secondary corpus* (`_secondary_language_files`, kill switch `CHAMELEON_CROSS_LANGUAGE_INDEX=0`): each secondary language must clear the same manifest-plus-source bar a primary does, its files go through the same `discover_files` filters (gitignore, vendor, symlink, containment), and the sampling cap is split evenly across the languages present before it is round-robined across directories, so a package-per-directory Go monorepo beside one Ruby service cannot starve Ruby to zero. Secondary files reach clustering and canonical selection (so a second language derives its own archetypes and witness), plus `calls_index.json` and `symbol_signatures.json`. They do NOT reach `extract_all_conventions`, which takes one repo-wide language, and they do NOT reach `function_catalog.json`: a cataloged function records no language, so a Go `ParseOrder` and a TypeScript `parseOrder` would pair as a reuse lead no reuse can ever join. The calls index is built once per language and merged, so each corpus is graded by its own resolver instead of the primary's. --- ## Production-ref derivation Bootstrap and refresh derive the profile from the repo's **production branch tree**, not the checked-out working tree, whenever a production lock exists. The lock is `production_ref` in `config.json` (a branch name; resolution prefers `origin/` over the local branch). This means the profile reflects the production line no matter which feature branch a teammate has checked out. Lock precedence, highest first: 1. **Explicit** `chameleon_lifecycle(action="bootstrap_repo", params={"production_ref": ...})`, the init skill's confirmed answer. Always wins, always persisted. 2. **Persisted** `production_ref` in `config.json`. 3. **Auto-detection** (init and the refresh migration): the remote's declared default branch (`refs/remotes/origin/HEAD`), then an origin branch named `production`/`prod`, then `main`/`master`/`trunk`. Auto-locking requires the answer to be unambiguous **and** origin-backed; a local-only repo keeps working-tree derivation and the skill asks rather than silently flipping semantics. An explicit `"production_ref": null` is a durable opt-out that auto-detection never overrides. Mechanics: the locked ref's tip is resolved from local objects, the tree is materialized with `git worktree add --detach` under `//prodtree/-`, and the whole pipeline runs against that tree. Materialization passes `-c core.hooksPath=` so the repo's post-checkout hook never runs: a derivation that promises static analysis must never execute repo-controlled code. Worktrees from crashed runs are swept at the next prepare, skipping any whose creating PID is still alive. The orchestrator splits the **analysis root** (the materialized tree) from the **write/identity root** (the real checkout): the profile dir, repo_id, drift baseline, and prior idioms all bind to the real checkout, and persisted paths are repo-relative so artifacts apply one-to-one. `profile.json` records `derivation_source` (`{mode, branch, ref, sha}`) as provenance. **Default-on fetch.** When a locked branch is origin-backed, refresh (manual and auto) runs one bounded, non-interactive `git fetch origin ` *before* resolving the tip, so derivation sees the genuinely latest production. The fetch is hardened against argument injection: the branch name is validated before it reaches argv, credential helpers and SSH prompts are disabled, and a stuck transfer is killed by process group. It self-suppresses under `CI`, never runs on a hook hot path, and fails open to the last-fetched ref with a classified reason. Kill switch: `CHAMELEON_FETCH_PRODUCTION_REF=0` or config `auto_refresh.fetch_production_ref=false`. Tuning: `CHAMELEON_PRODUCTION_REF_FETCH_TIMEOUT_SECONDS` (default 10) and `CHAMELEON_PRODUCTION_REF_FETCH_BACKOFF_HOURS` (default 6, applied only after an auth or branch-gone failure). **Staleness for a pinned repo is the tip SHA, not mtimes.** If the recorded `derivation_source.sha` equals the current tip, refresh is a `noop` (feature churn is irrelevant). If the tip moved, refresh re-derives from the new tree. The SessionStart auto-refresh has a matching trigger, and a `[🦎 chameleon: production drift]` banner surfaces the pending staleness. `get_drift_status` carries a `production_ref` block (derived_sha, tip_sha, tip_moved, commits_ahead). Every failure mode (no git, no origin, unresolvable ref, worktree-add failure) degrades to working-tree derivation with a note in the envelope. The lock is best-effort, never a new hard dependency. `canonical_ref` is orthogonal: `production_ref` governs what analysis derives *from*; `canonical_ref` redirects which committed `.chameleon` snapshot the hooks *read*. --- ## Cluster signature function An archetype is a named cluster of files that share a structural signature. The signature `sig: file -> ClusterKey` is computed in a single AST pass. The `ClusterKey` dataclass declares seven fields for shape and JSON compatibility, but one of them is degenerate by construction, so the **live discriminating signature is six dimensions**: 1. **`path_pattern_bucket`** the depth- and monorepo-aware path glob, with the file extension appended during clustering. 2. **`content_signal_match`** the first-200-byte lexical directive (`use_client`, `use_server`, a shebang, a TS pragma, or none). 3. **`top_level_node_kinds`** the set of top-level AST node kinds, stored as a sorted, deduplicated set (order- and multiplicity-insensitive, to agree with the runtime lint conformance check). 4. **`default_export_kind`** the kind of the default export, or none. 5. **`named_export_count_bucket`** bucketed named-export count (0, 1, 2-4, 5-9, 10+). 6. **`jsx_present`** whether JSX appears anywhere in the file. The seventh declared field, `import_module_set_hash`, is hardcoded to the empty string. The exact import set was the single largest source of over-fragmentation (it made each service its own cluster), so it was dropped in schema v8; import conventions are derived separately. The field survives only for the dataclass and JSON shape. After exact-key clustering, three passes refine the result: a loose merge of sparse clusters by Jaccard overlap, a shape-fuzzy merge of near-identical clusters, and a sub-bucket split that records `sub_buckets` when one archetype spans varied concerns. **Stability obligations.** Running `/chameleon-refresh` twice on the same input produces a byte-identical profile (idempotence). Adding or removing a single file does not flip canonical selection unless that file *is* the new canonical. The profile-wide invalidation lever is `CURRENT_SCHEMA_VERSION`, not a separate signature-function version. --- ## Canonical selection A canonical is the reference example for an archetype. It is **trichotomized** so the engine is explicit about what part of the example is normative: - **Witness** the actual file (path plus xxhash64 sha hint). It has the team's real idioms and also its idiosyncrasies. - **Normative shape** the AST query the archetype must match, plus the consensus callable signatures. - **Normative idioms** prose annotations (leading comments and any taught idioms) that capture intent. The canonical excerpt injected at edit time is a **witness, not a template**: match its shape and idioms, not its specific business logic. Selection walks the cluster's eligible members sorted by `(demoted, -recency_weight, -typicality, path)`. **Demotion is the top-priority key**: it pushes structural non-representatives below their concrete siblings regardless of how recently they were committed, a Rails `application_*.rb` abstract base, an imports-only NestJS `@Module` aggregator, and a migration whose `ActiveRecord::Migration[x.y]` version is behind the cluster's current one. Below it, **recency weight** decays smoothly off each file's **last git commit time**: a single `git log` walk per bootstrap builds a `{path: commit_epoch}` map, and the weight is the full multiplier (2.0) for a just-committed file, halving its boost above 1.0 every `CANONICAL_RECENCY_HALF_LIFE_DAYS` (default 45). Commit time survives a fresh clone's uniform mtimes, so a recently committed minority idiom outranks the legacy majority, the exact case a mid-migration repo needs; a commit ahead of the clock (cross-machine skew) is clamped to most-recent, never penalized. When git is unavailable or a file is untracked, the weight falls back to the legacy mtime step (2.0 within 90 days, else 1.0); `CHAMELEON_CANONICAL_GIT_RECENCY=0` forces that fallback. **Typicality** (closeness to the cluster's most common AST shape) breaks a same-commit tie, then the path string decides. The first member that passes all three security scans wins. If none pass, the cluster is flagged `clusters_with_only_failing_canonicals` so the gap is visible rather than silently shipping a poisoned example. The three scans, run during selection: - **Secret scan** runs `detect-secrets` when available plus a deterministic regex set (AWS, GitHub, GitLab, AI keys, Stripe, Slack, Google, GCP service accounts, Azure, private keys, high-entropy hex). Any hit excludes the file. - **Injection scan** flags instruction-shaped prose ("you must", "ignore previous instructions", literal `` or `` tags) so a committed file cannot smuggle a prompt into the model's context. - **Poisoning scan** flags dangerous code shapes: raw SQL string concatenation, `eval`/`exec` calls, `subprocess(shell=True)`, and security-context weak hash or insecure random. Supply-chain checks are not part of canonical selection; they run only at tool time (see [The review gate](#the-review-gate-and-trust-path)). --- ## Conventions derivation Beyond the cluster signature, bootstrap derives per-archetype conventions into `conventions.json`. Each section is gated on its own sample-size floor and, where applicable, a 0.60 dominance frequency: a convention is the archetype's norm only when the clear majority of its members share it. Sections that do not clear their gate stay empty. All thresholds live in `_thresholds.py`. Sections also vary by language, and an empty section can mean either "no norm cleared the gate" or "no arm exists for this language". `extract_all_conventions` takes one repo-wide language, so a polyglot repo's secondary corpus reaches clustering but never this pass at all. See [Language tiers](#language-tiers) for which sections an extraction-tier language gets and which it does not. - **`naming`** dominant identifier casing (Ruby methods/classes/constants), TypeScript interface prefix, and the dominant file-basename casing and suffix. The file-naming convention is block-eligible under calibration. - **`import_ordering`** the dominant external-versus-relative grouping order (advisory NIT; competes with deterministic formatters, so low impact). - **`error_handling`** the archetype's error-handling shape at 0.60 (TS try/catch fraction; Rails controller-base `rescue_from`). Feeds a principle. - **`body_shape`** percentiles of branch count, nesting depth, line span, and parameter count, from a thicker witness pool. Branch count and nesting are the primary outlier signal; line span and parameter count never trigger alone. Advisory only. - **`doc_coverage`** the fraction of public declarations with a leading doc comment. Surfaced as a NIT. - **`test_pairing`** the fraction of source files with a paired test at the derived path. Advisory only and never block-eligible: too many files legitimately lack a test for the near-zero-FP gate to keep a block rule active. - **`callable_signatures`** the consensus positional shape of callable names an archetype shares (a name must appear in at least two members). Used only at PR-review with the LLM judge; no per-edit arity lint. - **`inheritance`** Ruby and Python: the archetype's dominant base class (a Rails controller's `ApplicationController`, a Django model cohort's `models.Model`). **`method_calls`** Ruby-only: shared DSL macro calls. - **`required_guards`** Ruby controllers: the shared `before_action` guard symbols, accounting for `skip_before_action` and scoping. Advisory, because Rails authz is routinely inherited. - **`class_contract`** the archetype's required class-body shape (base, macros, decorators, required methods). - **`layering`** the cross-cluster import-edge multiset, from which the engine derives forbidden-upward edges only for directional, unanimous pairs, plus a static cycle report. Advisory. --- ## Cross-file indexes Six committed index artifacts make the cross-file checks possible without re-parsing callers on the hot path. All key on repo-relative paths, are byte-reproducible, are hashed into the trust SHA, and fail open to "no facts" (never a crash, never a fabricated claim) on any corruption. - **`exports_index.json`** (TS/JS + Python): each source path to the set of names it exports. A file with `export * from` is marked open and skipped by the phantom-symbol check, since barrel files are the dominant false-positive source. - **`reverse_index.json`** (TS/JS + Python): the inverse view, exported-name to the files that import it by name plus the import line. Backs the edit-time blast-radius advisory and the cross-file symbol-existence check (a name that was exported is gone and an indexed importer still references it). - **`function_catalog.json`** (the PRIMARY language only, whatever it is): per function, the name, kind, arity, and two body hashes (plain and parameter-normalized). The body hash drops the name line, collapses whitespace, and hashes the rest, but only for bodies past a minimum length. No body text is stored. This is the cheap candidate-narrowing layer for cross-file duplication; the LLM caller judges equivalence against real bodies. Deliberately the one index that skips a polyglot repo's secondary corpus: a cataloged function carries no language, and candidates pair on name-token overlap plus arity, so a Go `ParseOrder` and a TypeScript `parseOrder` would match and cost a reviewer spawn on a pair no reuse can ever join. - **`calls_index.json`** (every language in the repo, primary and secondary): callee file to callable name to recorded caller rows. Built once per language and merged, because the builder binds one module resolver for the whole index: a mixed file list resolved every secondary file's import specifiers under the primary's rules and silently lost every cross-file grade. Partitions are disjoint (one extension maps to one language) and an edge is recorded only when caller and callee are in the same build, so the merge is a plain union. It stores exactly five deterministic grades and never name-only repo-wide matches (the false-positive bulk): - `same_file` a bare call to a same-file callable, or a `this.`/`self.` call to a same-file class member. The only grade an extraction-tier language reaches: each graded cross-file edge below needs a per-language resolver, and the five specs have none. (`self`, `this`, `$this`, `self::` and `static::` are each declared per spec, so the intra-class edge is recorded.) - `import` (TS and Python) a call of a named import matched on its local binding and recorded under the exported name, where the callee exists in the target's closed export set. - `constant_receiver` (Ruby only) `Const.method` where `Const` resolves to exactly one defining class and the member is class-level. - `typed_property` (TS only) `this..()` where the property's declared type (a constructor parameter-property or typed field) resolves to a class that records the method as a member — the dependency-injection call shape (NestJS/Angular constructor injection). Any resolution gap (generics, unions, untyped fields, open barrel exports) yields no edge. - `module_attribute` (Python only) `mod.func()` where `mod` is a submodule bound by `from pkg import mod` resolving to a real in-repo module file, and the member is a callable defined in that file — the Python analog of `typed_property`/`constant_receiver`. Each entry carries an honest `total` and a `truncated` flag so a capped count reads as a lower bound, not an undercount. Like every protocol artifact (see [Atomicity](#atomicity-locking-and-crash-safety)), a failed rebuild drops the old copy rather than carrying it forward: stale caller facts fed to the judge are worse than none. - **`symbol_signatures.json`** (every language in the repo, primary and secondary): per callable, the parameter shape, declared types (TypeScript and Python; Ruby has no static types), and body span, for the judge's forward-definition hydration. - **`constant_index.json`** (Ruby only): each referenced constant to its defining class, so a `Const.method` call site resolves to exactly one class for the cross-file blast-radius and call-site checks. The primary consumer is the turn-end correctness judge, which renders a bounded caller-facts block (including multi-hop transitive callers) for the callables a diff changed. Absence of an edge is never evidence of dead code; the facts block says so explicitly. The same artifacts back `get_callers`, `query_symbol_importers`, `get_crossfile_context`, and `get_duplication_candidates`. A seventh index lives outside the committed profile: the monorepo **cross-workspace existence index**, `cross_reverse_index.json` (default on, kill switch `CHAMELEON_CROSSWS_INDEX=0`). `build_reverse_index` runs per workspace, so a file in package B importing from package A over a `@scope/a`-style specifier is invisible to A's own reverse index, and a removed export a sibling package still imports goes unseen. At bootstrap and refresh each workspace captures the cross-package import specifiers its own reverse index drops, and the coordinator join resolves each `@scope/pkg` specifier to the sibling workspace's file through a `package.json`-name map with a fail-closed name-in-exports confirmation. The resolved edges are written to the plugin data dir (`//cross_reverse_index.json`), deliberately **off the trust-hashed profile surface**: materializing a coordinator profile to host it would create a new trust anchor and arm the security-deny floor on previously ungoverned root files. Its consumer is a Stop-time advisory (never a deny) that flags an export the turn removed which a sibling workspace still imports, confirmed by a live presence re-check on the importer. TypeScript/JS and Python both resolve. Each candidate carries the language that captured it, so the coordinator pools every workspace's candidates into one list and resolves each by its own rules: JS extension probing plus `package.json` `main` for one, dotted module paths against an import-name map for the other. Python's map is keyed on the IMPORT name (the directory a sibling writes in `from my_lib.core import x`), not the distribution name in `pyproject.toml`, which is routinely spelled differently (`my-lib`) and would resolve almost nothing. Ruby has no static export surface and the extraction-tier languages have no reverse index, so neither contributes edges. --- ## Hook stack Seven hook scripts are wired across six Claude Code events (PreToolUse and PostToolUse are each registered twice; `stop-backstop` is reused for Stop and SubagentStop). All registrations route through `run-hook.cmd