Skip to content

Before asking, read User Questions.

Rename Refs

Rename one Python symbol/module with preflight and verification. Every source write is journaled by rename_snapshot.py: a post-edit failure restores all-or-nothing — each file the run changed gets its original bytes and a recorded git mv is undone with git mv back, but a file changed outside the run's recorded edits is a conflict, and any conflict keeps every file as it is and is reported; Step 7 lists restored files, conflicts and remaining work. Coverage: definition, __all__ exports, caller imports/calls (fn-rdeps plus line ranges), non-call references (imports, base classes, isinstance targets, callback values, ancestor __init__.py re-exports) in files importing the symbol's module or a re-exporting ancestor package, Sphinx refs in .py/.rst, optional pyDeprecate alias, or hard delete only with exhaustive zero callers.

Interface

  • symbol <old_qname> <new_qname>: function/class/method. qname is bare (MyClass) or qualified (MyClass.method), matched to symbol-local qualified_name. The module-qualified form (module::symbol) is not accepted by find-symbol and returns zero matches. Build <module>::<qualified_name> only for Step 2 fn-rdeps.
  • module <old_module_path> <new_module_path>: dotted paths; rename file and imports.
  • --dry-run: list sites, no edit.
  • --deprecate[=<decorator>]: symbol only; old-name pyDeprecate @deprecated wrapper to new name; pyDeprecate required.
  • --no-deprecate: symbol only; declines the wrapper; no conflict with --remove-if-no-callers.
  • --since <ver> / --removed-in <ver>: decorator versions, default "?".
  • --remove-if-no-callers: symbol only; delete only with exhaustive zero callers, no zero-caller method hint, and no non-call reference.

Reject --deprecate with --remove-if-no-callers before analysis. Static limits: report a getattr(obj, "old_name") search advisory; cross-repo callers require --deprecate plus a SemVer bump for public API.

NOT for: index build ($codemap-py:scan-codebase); query without rename intent ($codemap-py:query-code); non-Python; ABC/Protocol override renames (static imports don't track overrides—review fn-rdeps, then rename overrides explicitly). No --index <path>; use default project index. For monorepo packages, first run $codemap-py:scan-codebase --root <pkg>.

Runtime note

Codex has no bin/ PATH entry or plugin-root variable. Resolve installed root once, substitute PLUGIN_ROOT, retain in reasoning; shell state doesn't persist. Route missing input, stale-index, ambiguous-match, delete/abort, and dry-run/apply/abort questions through User Questions; preserve every feasible choice, wait for valid bound answer before dependent changes.

Workflow

Stop routing follows source edit state, including a deletion or git mv. Before the first source write, any stop ends this invocation; re-invoke only after correcting the reported prerequisite. Never finish a stopped rename by hand with grep, direct edits or a file move, in any language. A placeholder-substitution self-check only retries its block after substituting the named value. After the first source edit, every stop, refused journal command or incomplete verification is a post-edit failure: stop further rename edits, skip the remaining Step 4–6 work, restore through the journal automatically, without a question, then report ⚠ Rename incomplete in Step 7 with the restored files, every conflict and remaining work; never restart an earlier edit step. A failed incremental re-scan does not skip other Step 6 checks: continue available verification and repeat the warning in Step 7; unavailable verification still makes the rename incomplete and restores.

Edit journal (rename_snapshot.py, run from the repository root): Step 1 sets aside a leftover journal and opens this run's with the first two commands below. Immediately before every source write — each direct edit, the Step 3 hard-delete, and the Step 5 git mv for its source path — run the journal before command; immediately after each successful edit run after --file, and after a successful git mv run after --move with both paths. A refused journal command (exit 3) writes nothing: before the first source write it ends the invocation, after one it is a post-edit failure. Step 7 restores an incomplete rename and discards the journal only for a verified one.

"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/rename_snapshot.py" --runtime codex discard --retain
"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/rename_snapshot.py" --runtime codex before
"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/rename_snapshot.py" --runtime codex before --file "<path about to be written>"
"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/rename_snapshot.py" --runtime codex after --file "<path just edited>"
"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/rename_snapshot.py" --runtime codex after --move "<old_file_path>" "<new_file_path>"
"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/rename_snapshot.py" --runtime codex restore --journal "<RETAINED_JOURNAL path>"

1. Parse and check freshness

Check for .py/.pyi files from the repository root (current directory outside Git), excluding .git, .venv, venv and node_modules. If none exist, report ! UNSUPPORTED — rename-refs is Python-only; stop, do not rename by hand and end the invocation before index queries. Then, from the repository root, set aside a leftover journal and open this run's (the first two Edit journal commands); a refused journal command ends the invocation before index queries. Exit 5 from discard --retain means a previous rename left unfinished edits: skip before and index queries, report the RETAINED_JOURNAL path and that a previous rename left unfinished edits, and ask through User Questions: keep as is, or restore it with the restore --journal command (all-or-nothing). Report its restore or CONFLICT lines, then end the invocation.

Accept only the listed flags; reject other -- tokens, symbol-only flags under module, and the incompatible pair. Then run:

PLUGIN_ROOT/bin/codemap-py query find-symbol "<old_ref>" --limit 0

Keep that result for Step 2. Let the engine prepare a missing index or refresh a stale one within its bounded heal cap. Inspect every answer's index.query_complete and index.stale, including each batch item's ok and result.index; a failed query/preparation stops before edits. Only if a query still reports stale: true after bounded preparation (or preparation is disabled), ask through User Questions: Proceed anyway (callers may be incomplete) or Abort (explicitly refresh, then re-invoke $codemap-py:scan-codebase). Record PROCEED_STALE=true in the private run state only for an explicit Proceed anyway answer; otherwise false. Apply this gate when a later query first reports stale evidence too; never infer consent. Missing/unknown freshness or query_complete: false belongs in the blast report and Step 7, never counts as complete or permits hard-delete. Every known site still requires caller preflight.

2. Resolve targets

For symbol, reuse matches; each has {name, qualified_name, type, module, path, start_line, end_line, source}. Use path/lines for edits and qualified_name for exact filtering. Zero: report Symbol '<old_ref>' not found and stop. Multiple: list name/type/module/path, ask selection, wait. Then query:

PLUGIN_ROOT/bin/codemap-py query fn-rdeps "<module>::<qualified_name>"

It returns {qname, called_by:[{caller, module, path, inferred?}], count, index:{query_complete,...}}, plus hint for a method or constructor with zero static callers; inferred: true marks a caller reached only through an inferred receiver type: confirm it in source before rewriting it, and report any unconfirmed one as skipped; Step 3 resolves caller ranges from symbols <module> by exact qualified_name. Read completeness forward-first: index.query_complete, then legacy index.exhaustive only if absent; not complete belongs in the report. A hint means zero static callers is not zero callers — instance calls on a receiver whose class the source does not state (obj.method()), overrides, subclass constructors, and implicit protocol (dunder) calls such as len(x) or x == y are never resolved statically; print it in the report. Also print index.hint, the search for references outside the static AST such as hook-registered callers; it never blocks the rename on its own.

called_by holds call edges only: a subclass base, isinstance target, callback value, plain import or ancestor __init__.py re-export never appears in it. Save the narrowed find-symbol answer and the fn-rdeps answer as find-symbol.json and fn-rdeps.json in a private temporary directory (mktemp -d). Write batch-in.json there holding {"cmd":"list","args":["--limit","0"]} plus one {"cmd":"rdeps","args":["<pkg>"]} for the symbol's module and for each ancestor package (a.b.c → a.b.c, a.b, a): a re-export lives in an ancestor __init__.py, and its users import the package. Resolve the repository root once (git rev-parse --show-toplevel, current directory outside Git). Run every reference helper and grep from that root so repository-relative saved paths resolve correctly. Then list every whole-word old name in the files that call, define or import it:

cd "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" || exit 1
PLUGIN_ROOT/bin/codemap-py query batch "<tmp>/batch-in.json" > "<tmp>/batch.json"
"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/find_module_refs.py" --kind name --name "<old_name>" --files-from-json "<tmp>/fn-rdeps.json" --files-from-json "<tmp>/find-symbol.json" --files-from-json "<tmp>/batch.json"

A non-zero exit from either means reference sites are unknown: stop before any source edit. Each printed path:line:text is a candidate site; comments, docstrings and strings are included, and a same-name symbol imported from another module stays unedited. For a method, only attribute accesses on an instance of its class count. Report the site count with the callers in Step 3.

For module, query:

PLUGIN_ROOT/bin/codemap-py query rdeps "<old_module_path>"

Read completeness identically. Save the pre-rename answer; inventory imported_by, dynamic_imported_by and config_refs separately, including every source location in preflight and Step 6. String imports and mock/config targets require explicit source review; any unresolved old target leaves the migration incomplete.

3. Report and confirm

Print old→new, type/definition (symbol), static caller count/files, Step 4 doc-ref search, and getattr/cross-repo limits. If incomplete: "index non-exhaustive — some callers may not appear above."

Caller count alone never blocks a complete migration. Enumerate and preflight every known caller; save the complete inventory and resolved locations to .reports/codex/codemap-py/rename-refs-blast-<branch>-<YYYY-MM-DD>.md and print its path. <branch> is git branch --show-current | tr '/' '-' (main if empty/detached). Never overwrite: append -2, -3, … until free. The inventory supports confirmation and complete execution; it never permits a partial migration.

For --remove-if-no-callers, before edits: callers found → report count and stop (remove callers first or drop the flag); incomplete/missing completeness → report $codemap-py:scan-codebase required and stop; zero with a hint → report that zero static callers is not proof for a method or constructor, print the hint's search, and stop (delete manually only if it finds no reference); a protocol-method (dunder) hint names no search — Python calls it implicitly, so report it is never deleted on zero callers and stop; complete zero without a hint → first run the non-call reference check, also under --dry-run. fn-rdeps counts call edges only: imports, base classes, isinstance, callback values and re-exports never appear in it. Search every .py/.pyi file outside .git, .venv and node_modules for <old_name> (last dotted part of <old_qname>) as a whole word, at most 50 hits:

grep -rnw --include='*.py' --include='*.pyi' --exclude-dir=.git --exclude-dir=.venv --exclude-dir=node_modules -- "<old_name>" "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" | head -50

Any hit other than the definition's own def/class line → report <N> non-call reference(s) to <old_name> — delete would leave ImportError/NameError and stop. No such hit → ask delete/abort; under --dry-run, record "would delete <old_qname> — no callers, exhaustive" in the dry-run report instead, with no question and no edit. Before deletion, verify start_line names the expected symbol; mismatch aborts. Run the journal before command for the definition file, delete definition plus preceding decorators, record it with after --file, skip Step 4, and continue at Step 6.

Before apply confirmation, resolve every known caller before any source edit: for symbols, query every caller and verify its unique source range and expected imports/calls; for modules, inspect every dependent file and matching import. For a missing, ambiguous or source-mismatched site, stop before any source edit with source unchanged. With the recorded Proceed anyway decision, stale or incomplete metadata alone does not reject a uniquely resolved, source-verified caller; carry the caveat into the blast report and Step 7. Without that decision, unavailable caller coverage stops. Retain these locations for apply; recheck them before mutation. The complete preflight applies to both subcommands regardless of caller count.

For symbols, run PLUGIN_ROOT/bin/codemap-py query symbols "<caller_module>" once per caller module before confirmation, splitting caller at :: and selecting its exact qualified_name. Require exactly one match, the same indexed path, and valid start_line/end_line bounds in the current file. For stale/incomplete coverage under Proceed anyway, parse the dedented current range: require one function/async function/class with the expected name and an expected call to the old symbol, including imported aliases and constructor class names. When the whole-file AST parses, also verify qualified nesting at those bounds; a whole-file syntax failure does not replace the range checks. A source mismatch stops before edits. Save every (caller, module, path, start_line, end_line, current source) row as caller-ranges.json in the private temporary directory only after all callers resolve; read the saved source alongside expected imports/calls before confirmation.

For --dry-run, write would-change sites to .reports/codex/codemap-py/rename-refs-dry-<branch>-<YYYY-MM-DD>.md using the same branch and never-overwrite rule; print path, ask for re-invocation without --dry-run or stop. Otherwise ask apply/abort and stop on abort.

4. Apply symbol edits

  1. At start_line, rename def old_name( / class OldName(...) / class OldName:; for methods, match inside class. Rename @old_name.setter/.deleter too: an orphaned descriptor raises AttributeError at class definition. Rename @typing.overload def old_name( in the file and sibling .pyi; find-symbol omits these.
  2. In package __init__.py, rename quoted old names in __all__.
  3. For each called_by, read its unique row from saved caller-ranges.json without re-querying an index that may refresh after edits. Compare current source at the saved bounds to saved source, allowing only this run's recorded 1:1 substitutions. Missing/duplicate rows or unexpected drift stop apply; report partial state through Steps 6–7, never skip a caller. Within its range, fix each file's module import once, then qualified X.old_name( and bare old_name(. Never bare-replace outside the confirmed range. Use the complete preflight inventory; never skip a known caller. Then, for every file in the Step 2 reference-site list (callers included): find the line bringing the old name in — from <module> import …, a relative import, or from <ancestor package> import … whose __init__.py re-exports it. Another origin is a same-name symbol: leave that file unedited. Origin confirmed: edit that import line once and every listed whole-word occurrence — base classes, isinstance targets, callback values, __all__ strings, re-export lines, annotations, comments and docstrings naming it; for a method, only attribute accesses on its class's instances. A line that cannot be classified stays unedited for Step 6 to report.
  4. Search .py/.rst Sphinx :func:/:class:/:meth:/:mod:/:attr: old-name roles; edit only matching module context.
  5. For --deprecate, after definition rename run PLUGIN_ROOT/bin/gen_deprecation_wrapper.py; insert after new definition. It maps class to @deprecated_class(target=NewName, ...) (keeps isinstance) and function/method to @deprecated(target=new_fn, ...). Missing pyDeprecate makes target import fail; report advisory in Step 6.

5. Apply module edits

  1. For non-git or untracked source, stop before edits and report that tracked-file module moves require Git tracking; never add, commit, or stash automatically. For tracked source, preserve uncommitted user edits and use git mv -- <old_file_path> <new_file_path> after confirming that the source exists, the destination is unoccupied on disk and in the index, and neither path is conflicted. Do not force a move. Prefer indexed path over dotted conversion (which can be wrong under src/ layouts). Package directories (__init__.py) are out of scope: print direct git mv, do not attempt. Run the journal before command for <old_file_path> immediately before the move and after --move "<old_file_path>" "<new_file_path>" once it succeeds.
  2. Rename direct import mypackage.old_name (including as X) and from mypackage.old_name import ..., at line start or indented inside a function, try or if TYPE_CHECKING: block, plus attribute uses after a parent import (mypackage.old_name.func() following import mypackage), which carry no import line naming the module.
  3. Rename same-package __init__.py from .old_name import ... after directory check.
  4. Search full dotted path in pyproject.toml/setup.cfg, editing package/install requirements only; never bare basename.
  5. Rename Sphinx :mod: full paths; basename fallback needs matching module context.

6. Re-scan and verify

PLUGIN_ROOT/bin/codemap-py index --incremental
PLUGIN_ROOT/bin/codemap-py query find-symbol "<old_ref>" --limit 0    # symbol
PLUGIN_ROOT/bin/codemap-py query rdeps "<old_ref>"                     # module

For symbol, find-symbol sees definitions only, never references. Count every whole-word old name still in *.py/*.pyi files: the whole tree for a function or class; for a method, add the three Step 2 --files-from-json arguments, since a bare method name recurs across unrelated classes. With --deprecate, add --alias-in "<definition path>" so the alias stub's own def/class line is not counted:

cd "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" || exit 1
"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/find_module_refs.py" --kind name --name "<old_name>"

Classify each hit: an unedited reference to the renamed symbol (import from its module or a re-exporting package, base, call, isinstance target, callback value, comment or docstring naming it) or a same-name symbol of another origin.

For modules, interpret rdeps <old_ref> with its actual status: exit 3 plus structured error: "module not indexed" for the old module is clean absence only after a successful rescan. Exit 0 with any static/dynamic/config consumer is residual; empty lists still mean the old module is indexed, so inspect its source. Any other error, malformed result or failed rescan makes verification unavailable. Search literal dotted old-module references with identifier boundaries in Python, stubs, documentation and config files from the repository root, excluding VCS, virtualenvs, generated reports/plans, caches and build outputs. Classify every hit by origin: old string imports, mock/config targets and current docs are unresolved and prevent success. Changelog/history hits are advisory, never unresolved; do not rewrite history. Record same-text references to another origin separately.

Before claiming completion, record these results in the saved blast report:

  1. Require a successful rescan, old-definition/importer checks and classified residuals. For symbols, count only find-symbol matches with qualified_name exactly equal to the old reference; a new name containing the old name is not residual. Expect old name absent except deprecated alias.
  2. For symbols, save fn-rdeps <module>::<new_qualified_name> and compare every (caller, path) against saved caller-ranges, including equal total count; only the renamed provider's own qualified prefix and nested members transform. Equal counts alone do not prove identity. For hard-delete, require old definition and all references absent instead.
  3. For modules, save rdeps <new_ref> and compare static importers, dynamic importer locations and config locations to the pre-rename answer. Verify each saved source location names the new module, including relative imports; absent/still-old consumers fail. Review extra identities as newly discovered consumers. For both modes, require complete, fresh post-query metadata only when pre-rename completeness was true; otherwise compare known identities and carry the non-exhaustive caveat without downgrading a fully matched rename.
  4. Using the project's Python environment, import the provider and every inventoried Python consumer module in separate processes, with a 20-second limit per module. For symbols, include modules from the saved reference batch's successful rdeps items as well as call consumers; for modules, include static and dynamic importers, replacing the old provider with the new one. Record every module, command and exit status. Print the new target's test-impact pytest command as advisory only; no covering test or unavailable test-impact is advisory, never blocks success, and no test suite runs automatically.

N is the distinct preflight caller count (module mode: static/dynamic/config consumers). M counts consumers passing identity/source comparison and, for Python consumers, their module's import smoke; config consumers require source-location checks. An unresolved known caller, unedited reference, post-write stop, failed smoke or unavailable required verification means incomplete migration. A non-exhaustive index or missing covering test remains a caveat. Import smoke checks import-time behavior; runtime calls remain outside this bounded check. If re-scan fails, continue available checks and report incomplete verification.

7. Summary

First settle the journal from the repository root. An incomplete migration runs restore automatically, without a question; a verified one runs discard; a run that stopped before its first source write runs neither:

"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/rename_snapshot.py" --runtime codex restore
"PLUGIN_ROOT/bin/python" "PLUGIN_ROOT/bin/rename_snapshot.py" --runtime codex discard

Restore is all-or-nothing: it checks every journaled write first, then puts back every file still holding the run's last recorded edit, deletes a file the run created only while it holds the created bytes, and undoes a git mv with git mv back. Exit 4 means a conflict: with NOTHING_RESTORED, nothing was restored and every file keeps its current bytes; without it, a file changed during the restore, which stopped after its printed lines. Report each CONFLICT line and the RETAINED_JOURNAL path, where the original bytes stay. Exit 3 means restore was unavailable: report its ! line and that the edits remain in place.

For an incomplete migration, report ⚠ Rename incomplete with the restored files, every conflict, the changed files, verified/known caller counts, each unedited reference as file:line, failed or unavailable checks, and next actions. Repeat any re-scan warning. Otherwise, a success line states M/N consumers verified, the residual whole-word count for symbols or literal dotted reference count for modules, each residual's other-origin classification, any history advisory, and the stale/non-exhaustive caveat when applicable; never print an unqualified Renamed. Report renamed pair, files, calls, doc refs, alias path/line when used; always flag getattr literal search, external consumers without alias, skipped callers, and residual hits when applicable.