Skip to content

Codemap-py capability contract — v1

Single source of truth-claims for the six codemap-py skills, shared by both runtime rosters (claude-skills/, codex-skills/). Under the Parity requirements section below, runtime skills may differ in invocation syntax and tool bindings but must not differ in truth claims — inputs, outputs, exit codes, completeness metadata, or caveats. tests/integration/test_skill_parity.py diffs both rosters against this file; a runtime skill that adds an undocumented capability, drops a documented one, or states a stronger/weaker guarantee than listed here fails parity.

The Shared exit-code contract and Parity requirements sections below define CLI outcomes and skill parity. integration-contract.md defines the integration protocol.

Shared exit-code contract

All six skills' underlying CLI calls (scan-index, scan-query, codemap-py integrate) obey:

Exit Meaning Output
0 valid success, incl. valid empty/disconnected result requested text or JSON
1 valid request cannot complete — index/domain/fs/runtime failure bounded structured error, no traceback
2 invalid command syntax, option, value, or malformed batch input one bounded usage/JSON error
3 requested module/symbol not indexed — distinct from valid empty result parseable JSON error on stdout
127 no eligible CPython interpreter, incl. invalid CODEMAP_PYTHON or untested future minor empty stdout, one actionable stderr line

A skill's own pre-flight shell logic (e.g. an unsupported-flag check before the CLI is even invoked) may take a shortcut exit path; that shortcut is skill-local UX, not a redefinition of the underlying CLI's exit-code contract above. Both rosters' shortcut paths must reach the same decision (reject vs proceed) for the same input, even if the intermediate exit code differs from 2.

Completeness metadata (shared vocabulary)

Every scan-query result JSON carries an index block; all six skills interpret it identically:

  • index.method — technique used (static-ast, import-graph, index-lookup, ast-flags).
  • index.not_covered — list of what the method structurally misses; non-empty → surface as a scope caveat, never fill the gap by re-querying codemap.
  • index.hint — actionable alternative when deeper coverage is needed.
  • index.confidence: "exact" — exact within the reported method and scope; does not override freshness, completeness or truncation limits.
  • index.degraded — count of modules that failed to parse; >0 → some edges may be missing.
  • query_complete (forward field) / exhaustive (legacy alias, one deprecation cycle) — direction-scoped completeness: true → result authoritative for that query's direction, stop querying/grepping; false → check degraded_files, untracked_py, stale before filling gaps.
  • completeness_reason — slug of the highest-priority reducer that made the answer incomplete (ok when complete; may be absent on a compact complete answer).
  • remedies — present only when query_complete is false, in the full and the compact block: one {reason, remedy} record per active reducer (every reducer, not only the first), in veto-priority order, so the first reason equals completeness_reason. remedy is a fixed one-line action naming no file, module, symbol or path; note carries the same remedy text. A collision remedy names the fix: exclude the unwanted copy or order src_roots, then run a full scan.
  • dynamic_sites — present only when the query's search set holds a non-literal dynamic call, in the full and the compact block, whether or not the answer is complete: {count, modules, scope, check}. count is the number of import_module/__import__ calls and getattr calls on an indexed module whose module or attribute argument the scanner cannot resolve; modules is how many modules hold them; scope is module for a module-local query (deps, symbols: the queried module only) and index for every other query (all indexed modules); check is one fixed sentence naming no file, module, symbol or path. It never changes query_complete, completeness_reason, note or remedies; surface it as a caveat that those call sites may reach modules or attributes the answer does not show.
  • stale — index older than source; skills that self-heal (bounded inline scan-index --incremental) report whether the heal ran or was skipped (change set over cap, git unavailable).

Consumers may skip re-querying only when completeness is exhaustive/query_complete: true.

Skill: scan-codebase

Purpose: build/refresh the Python structural JSON index (import graph + blast-radius metrics

  • symbol table) at .cache/codemap/<project>.json (or $CODEMAP_INDEX_DIR/<project>.json).

Inputs: [--root <path>] [--incremental]. No target/symbol arguments — whole-project scan.

Outputs: index JSON on disk; terminal summary (N modules indexed, M degraded); no stdout JSON payload for programmatic consumption (that is query-code's job).

Exit codes: 0 success (including empty-Python-project index); 1 scanner failure (scan-index internal error); 2 unsupported flag rejected before the scanner runs.

Completeness metadata: post-scan summary reports degraded module count only — no per-file list at this skill's surface (obtainable via query-code once indexed).

Caveats:

  • Python only — non-.py/.pyi files never parsed, never silently counted as indexed.
  • --root <path> names the index after basename(path), distinct from the default git-root index; queries against the default index will not see a custom-root index unless invoked consistently with the same --root.
  • Zero-Python project: index writes but is empty; downstream queries return no results, not an error.
  • --incremental with no prior index falls back to a full scan (informational, not a failure).

NOT for: querying an existing index (query-code); integration health/wiring (integration).

Skill: query-code

Purpose: read-only structural queries over the index — module deps/rdeps/central/coupled/path, symbol-level source extraction, function call graph (fn-deps/fn-rdeps/fn-central/fn-blast), and the extended quality/coverage/test-graph query family (mock-rdeps, undocumented, uncovered, import-types, xrefs, dead-symbols, dead-modules, subprocess-deps(-rdeps), fixture-rdeps/fixture-graph, coverage/coverage-gap, diff-impact).

Inputs: one subcommand + target (<module>, <qname> as module::symbol, or none for central/coupled); shared modifiers --top N, --exclude-tests, --limit N, --with-imports.

Outputs: JSON on stdout for every subcommand (never prose-only); the skill wrapper renders it into the per-command table format documented in each roster's SKILL.md (list/pair/fenced-code/etc. per subcommand — rendering choice is runtime-specific, not a truth claim).

Entry-point references: dead-symbols and dead-modules count an entry point declared in the root pyproject.toml ([project.scripts], [project.gui-scripts], [project.entry-points.<group>], pytest11 included) as a reference to its target: dead-symbols skips the target symbol and any class enclosing it, dead-modules skips the target module. Generic config-file references stay ignored by dead-modules. [tool.poetry.scripts], setup.cfg and setup.py entry points, and pyproject.toml files below the project root are not read.

Possibly-public hint: a dead-symbols or dead-modules finding that sits where code outside the scanned project can import it carries possibly_public: true, and the payload then carries one fixed possibly_public_check text. The hint never removes a finding and never changes counts. For dead-symbols it marks symbols of a top-level module or a package __init__.py that declares no __all__. For dead-modules it marks a top-level module, a package __init__.py, and any module that declares __all__. The index sees only this project, so before deleting a marked finding confirm that no downstream project or documented API uses it. An unmarked finding is not proof of safety: a module reached only by a plugin mechanism the index does not read carries no hint.

Resolved dynamic references: rdeps lists dynamic_imported_by rows for string-literal import_module/__import__ calls (including a bare import_module imported from importlib) and, with a via slug, for two resolved forms: via: "constant" for import_module(CONST) where CONST is a module-level string constant bound once, unconditionally and not shadowed (the row's line is the constant's line), and via: "lazy_getattr" for a PEP 562 lazy-import map (a module-level dict of attribute name to module path, or to a (module path, attribute) pair, that a module-level __getattr__ reads and imports from). Relative paths resolve against __name__, __package__ or a literal package argument. The index also records, per module, getattr_refs ({target: "module::attr", line}) for getattr(<imported module>, "attr") with a literal or constant attribute name whose base is an indexed module. None of these forms adds a direct_imports edge or changes rdep_count, and dead-symbols/dead-modules do not read them. A call of these forms with an unresolvable argument is counted in dynamic_sites (§Completeness metadata), never dropped.

Inferred call edges: index call edges may carry inferred: <rule>. An inferred edge links a method call to the method of a class the source states for its receiver: a constructor assignment, an annotation (including Optional[C], C | None and string annotations), an instance attribute set from either, super(), a class-qualified call through an imported class, or an inherited self.method(). The receiver must be an indexed class and the method is found in its hierarchy before any unindexed base; anything else stays unresolved. Inferred edges are lower-confidence than recorded edges but are counted as callers by fn-rdeps, fn-deps, fn-blast and function-level test-impact, so dead-symbols reports fewer dead methods. Receivers from function return values, containers, unannotated parameters, other objects' attributes and module-level variables are not inferred. fn-rdeps shows the marker per caller: a called_by row carries inferred: true when every edge that makes that symbol a caller is inferred, a row with any recorded edge keeps its historic keys, and no row carries inferred: false. No other verb shows it: fn-deps, fn-blast and test-impact count inferred edges without marking them, so a consumer must not promise per-edge visibility there. The per-module index fields typed_calls and class_bases are additive and internal.

Complete-query paths are caller-repo-relative, never Skill-relative; do not re-query/read/grep merely to re-derive the complete structural fact. An edit may still need source and its named test/oracle to establish runtime behavior.

Exit codes: 0 success incl. valid empty result (e.g. path → null with reason: "no-import-path"); 1 index/runtime failure; 2 bad subcommand/flag; 3 requested module/symbol not indexed; a query requiring a newer index generation than what's on disk exits with a "requires vN+ index" message (upgrade path: re-run auto-build or scan-codebase). Every target-resolution failure (target not found or not indexed, module where a function is required, name resolving to candidates) carries rejected_target in its JSON error, so it is told apart from an exit-1 index/runtime failure by that key, not by message text.

Completeness metadata: full shared vocabulary above applies; this is the primary skill where query_complete/exhaustive, not_covered, degraded, and confidence are consumed.

Caveats:

  • Skip Codemap when an exact file and symbol are supplied for a localized edit and no caller, dependency, blast-radius, test-impact, import, or source-slice fact remains unresolved. A lifecycle boundary—callback/hook, cancellation/exception, scheduling/cleanup, or state transfer—leaves source scope unresolved: inspect source and the named test/oracle, then query fn-rdeps for caller or fn-deps for callee responsibility. An explicit structural query or tool requirement overrides this skip; otherwise choose the smallest complete query.
  • Auto-builds/refreshes a missing or stale index unless SCAN_NO_AUTOBUILD=1 is set, in which case a missing index is a hard refusal (exit non-zero) rather than a silent skip.
  • Direction matters: rdeps = callers/blast-radius, deps = forward imports — swapping them is the most common misuse and is called out explicitly to both rosters.
  • For requests for test modules that directly import a module, use rdeps <module> and filter/report test modules; reserve test-impact <target> for transitive affected-test selection.
  • Test-impact lives at two levels and both are supported — this is a routing split, not a dead zone. The test-impact <target> subcommand of this skill answers a one-off structural question; the test-impact skill runs the full workflow (index ensure, JSON parse, pytest command, not_covered caveat). A roster's NOT-for line defers the workflow to that skill and never removes the subcommand from this skill's own surface; both rosters must state that split rather than imply the subcommand is unavailable.
  • Symbol staleness: stale: true + empty source → fall back to a file read; stale: false + empty → source genuinely unavailable, re-scan required.
  • Result truncation at 20 items is a real cap, not an exhaustive list, unless --limit 0 is passed.

NOT for: index rebuild (scan-codebase); rename intent (rename-refs); non-Python repos.

Skill: test-impact

Purpose: identify the minimal static test set for a changed function/module or the union of working-tree Python changes (no test execution); emits a ready-to-run pytest command.

Inputs: [<module::symbol | module>] [--no-mocks]. Function-level (module::symbol) does BFS over the reverse call graph; module-level (bare module) does BFS over the reverse import graph. Both include tests that mock the target (mock_patches) unless --no-mocks is passed. Omitted target queries diff-impact for tracked staged and unstaged Python changes against HEAD (untracked excluded); len(changed_modules) + len(unmapped_files) > 1 selects the whole-change union. Zero/one changed file or unavailable diff analysis asks for a concrete target, retaining original flags; failed diff analysis is never an empty result.

Outputs: single-target JSON with test_files, pytest_cmd, via_call/via_mock breakdown and index; rendered with target-only scope and other-changed-module count (or count unknown). Whole-change analysis uses summarize_test_impact.py --diff-impact: test_impact.test_files, test_impact.total, test_impact.pytest_cmd, index, unmapped_files and changed_modules[].errors, scoped to working-tree changes, without invented call/mock counts. With --no-mocks, test_impact_union.py batches all changed modules and their changed symbols from the original diff, fails on any failed query, and adds diff_index, batch index and target_caveats. Render affected tests, host-quoted pytest command and all completeness/coverage caveats; test_files is authoritative for other shells.

Exit codes: 0 success including total == 0 (valid "no tests found" result, not an error); 1 index build/query failure or non-JSON output from the underlying query; 2 no target supplied and the interactive clarification path is unavailable (non-interactive runtime); 127 propagated from a missing interpreter at the scan-query binary boundary.

Completeness metadata: index.query_complete: false or index.stale: true is caveated on both empty and nonempty outputs independently of not_covered; missing signals stay absent, and completeness_reason may be absent on compact complete answers. Surface index.not_covered (dynamic dispatch, hook callbacks, string-dispatch callers — same blind spot as fn-blast); this static limitation is never closed by grepping. Whole-change unions always retain that limitation, unmapped files and module errors, even on the question route; failed subqueries may be omitted without listed errors, so never claim complete coverage. Mock-excluding unions retain both diff/batch metadata and every target caveat.

Caveats:

  • Accepts one explicit symbol/module per invocation; multiple space-separated tokens use only the first — the discarded remainder must be surfaced, never silently dropped. Omitted-target whole-change routing is the separate union mode.
  • Underlying JSON may carry non-JSON prefix/suffix noise on some model tiers — the truth claim is "test-impact returns exactly the JSON payload's test_files/pytest_cmd fields," and a runtime that can't parse it must fail loudly (re-run/rebuild suggestion), never guess.

NOT for: enumerating all callers of a function (query-code fn-blast); running the identified tests (identifies, does not execute).

Skill: rename-refs

Purpose: rename of a Python symbol or module with preflight and verification across statically discoverable sites — definition, __all__ re-exports, import call sites (via fn-rdeps/rdeps + symbol line-range narrowing), Sphinx docstring cross-refs (:func:/:class:/:meth:/:mod:/:attr:) — with optional deprecated-alias (--deprecate) or hard-delete (--remove-if-no-callers) behavior. A post-edit failure restores the run's journaled edits all-or-nothing and undoes a recorded git mv; a file changed outside the run's recorded edits is a conflict, and any conflict restores nothing, keeping every file as it is and reporting it. A journal left by an interrupted run stops the next run before any index query, with an offer to restore it.

Inputs: symbol <old_qname> <new_qname> [--dry-run] [--deprecate[=<decorator>]] [--since <ver>] [--removed-in <ver>] [--remove-if-no-callers] or module <old_module_path> <new_module_path> [--dry-run]. 1:1 renames only.

Outputs: in-place source edits (unless --dry-run); a blast-radius/confirmation report before any edit; a re-scan-and-verify pass after edits; a final summary (files changed, call sites updated, docstring refs updated, advisories for out-of-scope hits).

Exit codes: 0 rename applied and verified (or dry-run report written); 1 index missing/ staleness abort, symbol not found, or scan-index re-verify failure; 2 invalid subcommand/flag or conflicting flags (--deprecate + --remove-if-no-callers); 3 zero matches for the target symbol/module (distinct from a valid "renamed with zero callers" outcome, which is 0).

Completeness metadata: inspect every query's query_complete/stale metadata (legacy exhaustive only when query_complete is absent). Explicit recorded Proceed anyway permits uniquely resolved, source-verified known callers with stale/incomplete metadata; preserve that caveat in the blast report and summary. --remove-if-no-callers still refuses unless the caller count is both 0 and exhaustive, and refuses a zero-caller method/constructor hint (instance calls, overrides, subclass constructors and implicit protocol calls are unresolved statically). Post-query metadata must be complete/fresh when pre-rename evidence was exhaustive; otherwise compare known identities and preserve the non-exhaustive caveat.

Caveats (static-analysis hard limits — not fixable by this skill, must be surfaced, never silently missed):

  • getattr(obj, "old_name") string-bound dispatch — not statically tracked; grep advisory emitted.
  • Cross-repo callers — out of scope; recommend --deprecate + semver bump for public APIs.
  • ABC/Protocol subclass overrides — not tracked by static import analysis; must be reviewed and renamed manually via fn-rdeps inspection.
  • Caller count alone never blocks migration. Save the full caller/source inventory before confirmation and edits; missing, ambiguous or source-mismatched sites stop with source unchanged. Apply from saved caller ranges without re-querying after edits, allowing only recorded substitutions. Completion requires a successful rescan, old-target/residual checks, consumer identity/source comparisons and separate provider/consumer import processes bounded to 20 seconds per module. History references and the suggested test-impact pytest command are advisory; tests never run automatically. Unresolved references or failed/unavailable required checks leave migration incomplete; success reports verified/known consumer counts and residual classifications.

NOT for: building the index (scan-codebase); querying without rename intent (query-code); non-Python files; 1:N symbol splits; package-directory rename (use git mv directly). No --index <path> override — always operates against the default project index.

Skill: integration

Purpose: runtime adapter over the codemap-py integrate pinned CLI surface — audit, plan, source-wire, locally sync, and demonstrate the supported consumer set. Full contract: integration-contract.md (this directory) — this entry only states the skill-level truth claims that must hold identically across both runtime adapters.

Inputs: one mode — audit [--runtime {claude,codex,both}] [--json] [--since YYYY-MM-DD] / plan [--runtime ...] [--consumers <csv>] [--source {local-candidate,release}] [--out <artifact>] / apply --plan <artifact> --approve <sha256> / sync --source {local-candidate,release} --plan <artifact> --approve <sha256> [--runtime ...] / demo [--runtime ...].

Outputs: audit → schema-versioned evidence report (provider/consumer versions, roots, managed blocks, shared-index identity, runtime logs, usage, findings, and non-executable remediation); plan → a report artifact (never mutates); apply/sync → mutation + verification result + journal entry; demo → audit output + one representative structural smoke query, recording protocol/version/evidence; never claims a plain-vs-structural comparison, token savings, or current-session activation.

Exit codes: audit exits 0 for completed pass or warn, 1 for completed fail or a required runtime/filesystem probe failure, and 2 for invalid syntax, runtime, date, or selection. plan remains zero-write and uses 0 for a completed artifact or 2 for bad syntax.

Completeness metadata: audit distinguishes observed, not-observed, and legacy-flat runtime logs; reports split_index_roots, index_stale_or_unknown, and index_degraded only from bounded read-only evidence; and never infers runtime identity or refresh provenance for legacy records.

Caveats: --approve is valid only with an explicit mutation mode, a saved plan artifact, and the displayed SHA-256; it never authorizes new targets, remote publication, git/marketplace mutation, or deletion. Both runtime adapters target the same closed consumer set (see integration-contract.md) — neither adapter may invoke the other host runtime's model.

NOT for: structural queries (query-code); explicit standalone index rebuild outside of a side-effect build during plan/sync bring-up.

Skill: debrief-coding

Purpose: read-only diagnostic/usage report over local codemap telemetry (.cache/codemap/logs/ JSONL) — subcommand distribution, timing (queries and index refreshes separately), static blind-spot slugs, error patterns, skill-invocation counts, session timelines, and the module-overlap proxy with its structural_search subset (a shape match, not a guard-chain leak rate) across legacy flat and recursive runtime shards. Missing Grep/Glob scope remains unknown, never presumed recursive; new records retain search path and producer-observed file/directory scope. Standalone Bash grep/rg searches get the same producer-observed scope from the full command; pipelines and other ambiguous commands do not, and their recursive-looking searches outside own-file inspection stay unknown: truncated command spelling cannot establish directory scope.

Inputs: [--since <YYYY-MM-DD>] [--session <id>] [--anonymize] [--output <path>].

Outputs: a markdown report, default .reports/codemap/debrief-<YYYY-MM-DD>.md; explicit and default report paths stay within the project root, resolve relative paths from that root, and append -2, -3, … when occupied; with --anonymize, pseudonymized copies under .cache/codemap/export/ are read instead of raw logs; directory input preserves claude/, codex/, and direct/ topology and the report never includes the reversibility salt.

Exit codes (statistics helper): 0 one JSON object on stdout (including zero matching records after filtering); 1 no telemetry only when stderr starts with No codemap telemetry found, otherwise a helper crash; 2 bad flag, missing value, invalid --since date, output outside the project, or oversized telemetry; 3 anonymize.py or join_avoidance.py exceeded its time cap, with the scratch copy already removed; 4 requested anonymization failed, so debrief stopped without a report. Report writing is a later skill step, outside the helper's exit codes.

Completeness metadata: not index-completeness in the query sense — this skill reports its own data-completeness caveats explicitly: "session not found in <file>" when a --session filter matches zero records in one log layer (expected when that layer never logged the session, not a data-loss condition); "scripted/polluted records excluded: N" when benchmark/test-suite noise is filtered from organic-usage stats.

Caveats: telemetry is sharded per session (cli_<session>.jsonl, skills_<session>.jsonl, tools_<session>.jsonl) below claude/, codex/, or direct/; older flat shards remain readable as unattributed legacy evidence. Aggregate every matching shard, never just one glob. Refresh provenance is explicit for new records (missing_index_explicit, claude_prompt_background, query_self_heal, explicit_scan, or direct_cli); legacy records remain unknown.

NOT for: validating codemap installation health (integration audit); building/querying the structural index (scan-codebase/query-code).

Parity requirements

  • Both runtime rosters expose exactly these six skill names — no extra, none missing.
  • A parity test rejects: a missing skill, a stale command/subcommand name, a runtime-specific filesystem path presented as if portable, or a truth claim in one roster that contradicts (is strictly stronger or weaker than) the corresponding entry in this file.
  • Runtime-specific latitude: invocation syntax (/codemap-py:<skill> vs $codemap-py:<skill>), tool bindings (Claude Bash/Read/Write/Skill/AskUserQuestion vs Codex's resolved plugin-root path convention), and result-injection/wording differences within the latitude this section defines.
  • Every runtime-specific instruction in a roster's SKILL.md must have an executable or inspection oracle behind it — no unverifiable prose claim about what a command does.