{
  "markdown": "# Weavatrix Refactor JS\n\n[![CI](https://github.com/Weavatrix/weavatrix-refactor-js/actions/workflows/ci.yml/badge.svg)](https://github.com/Weavatrix/weavatrix-refactor-js/actions/workflows/ci.yml)\n[![npm](https://img.shields.io/npm/v/weavatrix-refactor-js.svg)](https://www.npmjs.com/package/weavatrix-refactor-js)\n[![MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n\nPart of the [Weavatrix ecosystem](https://weavatrix.com/ecosystem). This repository preserves the explicit JavaScript refactoring line.\n\n> This is the JavaScript refactoring engine of Weavatrix, continued as\n> `weavatrix-refactor-js`. The\n> [`weavatrix-refactor`](https://www.npmjs.com/package/weavatrix-refactor)\n> package ships the native Rust MCP host built on\n> [weavatrix-rust](https://github.com/Weavatrix/weavatrix-rust) and the\n> `weavatrix-edit` / `weavatrix-refactor-plan` / `weavatrix-worktree` crates.\n> This package continues that version line: `weavatrix-refactor@0.1.5` was the\n> last JavaScript release under the old name, and `weavatrix-refactor-js@0.1.6`\n> picks up from it. Install `weavatrix-refactor-js`, or pin\n> `weavatrix-refactor@0.1.5`, to stay on the JavaScript implementation.\n\nEvidence-backed, transactional refactoring for coding agents.\n\n`weavatrix-refactor-js` is the write-capable member of the JavaScript family. It\ncombines the complete read-only `weavatrix-js` code-intelligence MCP with 11\nrefactoring tools that can prove a change, preview it against the current\nworking tree, apply it atomically, refresh the graph, and roll it back.\n\n> **Engine boundary:** this package hosts the `weavatrix-js` engine. It does not\n> use the native `weavatrix-rust` engine, and installing both packages does not\n> silently upgrade this one's analysis layer. Its state lives in\n> `~/.weavatrix-refactor-js`, kept separate from the Rust host's so the two\n> never share a lock, a token store, or a rollback journal.\n\nIt is substantially more than a rename wrapper:\n\n- semantic JS/TS rename through the bundled language server;\n- SQL table and field rename with schema-aware evidence;\n- strict graph-plus-lexical rename for Python, Rust, Go, Java, C#, and Solidity;\n- several related JS/TS renames merged into one atomic transaction;\n- signature, symbol-body, import, bulk-replace, move, and delete-safety workflows;\n- byte-exact file hashes, `before` text, provenance, uncertainty, and graph revision in every applyable plan;\n- stale-tree detection, repository locking, rollback bundles, and automatic rollback after a mid-write failure;\n- architecture and cycle projection before structural moves;\n- post-change blast-radius and verification tools inherited from the core.\n\n## Why this is a separate package\n\nThe MIT `weavatrix-js` core is physically read-only: its published artifact has no\nrepository source-write path. This package is the explicit write\nboundary. Installing it and selecting its `refactor` profile makes the `edit`\ncapability visible; without this package, the server cannot modify source.\n\nThe split is a safety property, not packaging cosmetics:\n\n```text\nweavatrix-js core       weavatrix-refactor-js                 repository\nread-only evidence  ->  plan + preview + confirmation  ->  atomic write\ngraph / LSP / audit     hashes / provenance / rollback     refreshed graph\n```\n\n## Architecture\n\nThe implementation is a ports-and-adapters system with one-way boundaries:\n\n```text\nedit-plan model  <-  filesystem / lock / token adapters\n       ^                         ^\n       |                         |\nplan engines     ->  preview / apply / rollback workflows  ->  MCP adapter\n```\n\n- **Model** validates the frozen `weavatrix.edit-plan.v1` envelope and applies\n  byte-exact edits as pure string transformations.\n- **Platform adapters** own real-path containment, atomic replacement,\n  repository locks, single-use tokens, and durable rollback bundles.\n- **Plan engines** compute rename, signature, symbol, import, move, delete, and\n  bulk-replace evidence without owning the write workflow.\n- **Application workflows** bind a preview to the current repository, issue and\n  consume confirmation tokens, apply under a lock, and restore on failure.\n- **MCP adapter** composes the 11 refactor tools with the read-only\n  `weavatrix-js` catalog and exposes one stdio server.\n\nThe checked-in strict architecture contract enforces zero runtime cycles,\nfiles no longer than 300 lines, and functions no longer than 100 lines. It has\nno exceptions or ratchet baseline.\n\n## What makes the refactor workflow different\n\nAn ordinary editor rename answers: \"Which text edits should I make now?\"\nWeavatrix Refactor also answers:\n\n| Question | Evidence returned |\n| --- | --- |\n| Is this the exact symbol? | Stable graph symbol id plus parser/LSP selection range |\n| Which references are proven? | Per-edit provenance: `EXACT_LSP`, `RESOLVED`, `EXTRACTED`, or `LEXICAL_EXACT` |\n| What was not proven? | Explicit `uncertainReferences`, `notModified`, warnings, and `PARTIAL` completeness |\n| Which files were even looked at? | The rename session seeds every graph-declared reference plus every indexed file whose text contains the identifier; anything it could not open is named and forces `PARTIAL` |\n| Did the tree change after preview? | File sha256 plus exact `before` text rechecked under the write lock |\n| Can several renames partially succeed? | No. Related renames are conflict-checked and applied as one transaction |\n| What happens after a disk/write failure? | Already-written files are restored; a durable rollback bundle remains |\n| Will a move worsen architecture? | Projected runtime cycles, boundary violations, improvements, and blast radius |\n| Did the refactor preserve behavior-shaped structure? | Refreshed graph plus `verified_change` caller/import/reference conservation |\n\nThe system fails closed when proof is insufficient. It never upgrades an\n`INFERRED` edge into an applyable edit and never hides an ambiguous reference.\n\n## The complete rename workflow\n\n`rename_symbol` and `rename_related_symbols` are complete operations, not\n`PLANNED`-only helpers. Each method owns both phases.\n\n### 1. Preview\n\nCall the rename method normally:\n\n```json\n{\n  \"symbol\": \"src/users.ts#getUser@12\",\n  \"new_name\": \"getCustomer\"\n}\n```\n\nThe method computes the rename, validates every plan file against the working\ntree, and returns `PREVIEW_OK` with a short-lived `confirmToken`. Preview never\nwrites source and does not require the environment write gate.\n\n### 2. Apply through the same method\n\nRepeat the same operation inputs and add the confirmation:\n\n```json\n{\n  \"symbol\": \"src/users.ts#getUser@12\",\n  \"new_name\": \"getCustomer\",\n  \"mode\": \"apply\",\n  \"confirm_token\": \"<token from preview>\"\n}\n```\n\nThe tool recomputes the deterministic plan, verifies that the token belongs to\nthat plan and repository, takes the repository lock, rechecks hashes and\n`before` text, writes a rollback bundle, and applies every edit bottom-up.\n\nThe same contract applies to a coordinated set:\n\n```json\n{\n  \"renames\": [\n    {\"symbol\": \"src/api.ts#getUser@8\", \"new_name\": \"getCustomer\"},\n    {\"symbol\": \"src/api.ts#getOrder@20\", \"new_name\": \"getPurchase\"}\n  ]\n}\n```\n\n`rename_related_symbols` detects overlapping edits, chains, swaps, shadowing\nrisk, and per-sub-rename failure before it issues a token. Apply is one atomic\nmulti-file operation.\n\n## Refactoring tools\n\n### Complete write workflows\n\n| Tool | What it actually does |\n| --- | --- |\n| `rename_symbol` | Cross-language preview/confirm/apply rename. Dispatches to exact JS/TS LSP, SQL schema, or strict graph+lexical backends; returns honest backend completeness and every uncovered reference. |\n| `rename_related_symbols` | Coordinates up to 50 JS/TS symbol renames in one shared language-server session and one atomic edit plan. Detects conflicts, chains, swaps, snapshot drift, and any failed sub-rename before writing. |\n| `apply_edit_plan` | Generic two-phase executor for `weavatrix.edit-plan.v1` envelopes from the other tools or `weavatrix-online`. Preview issues a plan-bound token; apply writes atomically with rollback. |\n| `rollback_last_apply` | Restores the latest pre-apply bundle. Refuses if post-apply files drifted; retries converge after an incomplete restore. |\n\n### Proven plan producers\n\n| Tool | What it actually does |\n| --- | --- |\n| `change_signature` | Adds or removes a JS/TS function or method parameter. Performs byte-exact declaration and call-argument surgery; spread calls and value-requiring additions remain explicit uncertainty. |\n| `edit_symbol` | Uses the indexed parser range for `replace_symbol_body`, `insert_before_symbol`, or `insert_after_symbol`. JS/TS output is parse-gated; line endings and UTF-16 coordinates are preserved. |\n| `bulk_replace` | Two-stage, occurrence-selective replacement over indexed files. First returns stable occurrence ids; the second call accepts chosen ids or an exact expected count and emits a hash-bound plan. Literal mode is the default; regex replacements use real capture expansion. |\n| `organize_imports` | Removes only provably unused named JS/TS imports. Default and namespace imports stay uncertain; side-effect imports are untouched; sorting is deliberately left to the formatter. |\n\nThese plans are applied with `apply_edit_plan`, using the same preview, token,\natomic-write, and rollback protocol as rename.\n\n### Structural review and safety tools\n\n| Tool | What it actually does |\n| --- | --- |\n| `move_file` | Builds a JS/TS relocate review: rewrites importer specifiers and the moved file's own relative imports, then projects architecture effects. File renaming itself remains an explicit editor/agent action, so this is intentionally not an apply envelope. |\n| `move_symbol` | Projects a declaration move without inventing byte edits. Reports introduced/removed runtime cycles, target-file dependencies, architecture violations or improvements, and blast radius. |\n| `delete_readiness` | Returns `safe: true`, `false`, or `UNPROVEN` with known references, dynamic/reflection risks, confidence, and the declaration span. Exported symbols are capped at `UNPROVEN`; deletion is never automated. |\n\n## Language and proof matrix\n\n| Surface | Backend | Applyable provenance | Completeness contract |\n| --- | --- | --- | --- |\n| JavaScript / TypeScript rename | Bundled TypeScript language server | `EXACT_LSP` | `COMPLETE` only when every file that could mention the symbol was opened in the rename session and proven; any candidate left out forces `PARTIAL` |\n| SQL table rename | Schema-aware SQL scanner across SQL and host files | `EXTRACTED` / `LEXICAL_EXACT` | Reports every skipped or ambiguous reference |\n| SQL field rename | Definition-safe SQL backend | Proven definition edits only | Usages remain `UNPROVEN` rather than guessed |\n| Python / Rust / Go / Java / C# / Solidity rename | Indexed graph references plus exact lexical location on the recorded line | `EXTRACTED` / `LEXICAL_EXACT` | Always `PARTIAL`; ambiguous lines are never edited |\n| JS/TS signature and imports | Parser plus graph call/reference evidence | `EXTRACTED` / `RESOLVED` | Explicitly partial where graph reach cannot prove absence |\n| Symbol-anchored edit | Indexed parser ranges for every indexed language | `EXTRACTED` | JS/TS parse gate; other languages retain the parser-range evidence boundary |\n\n## Edit-plan proof envelope\n\nEvery applyable plan uses `weavatrix.edit-plan.v1`. Its load-bearing fields are:\n\n- operation and graph revision;\n- repository-relative target paths only;\n- sha256 of every target file;\n- exact 1-based line and UTF-16 character ranges;\n- exact `before` and `after` text;\n- per-edit provenance;\n- `uncertainReferences`, `notModified`, warnings, and completeness.\n\nThe applier additionally protects against:\n\n- absolute paths, traversal, `.git` casing/trailing-dot tricks, NTFS streams, and escaping symlinks/junctions;\n- non-UTF-8 or oversized files;\n- overlapping edits, stale ranges, lone surrogates, and edits that split surrogate pairs;\n- two writers interleaving in the same repository;\n- token reuse, expiry, repository mismatch, or plan mismatch;\n- partial writes and incomplete rollback.\n\n`createdAt` is provenance metadata and is the only field excluded from the\nconfirmation fingerprint. This allows a rename method to recompute the same\nplan on its apply call; every executable field remains token-bound.\n\n## Result states agents can act on\n\n| State | Meaning |\n| --- | --- |\n| `PREVIEW_OK` | Every hash and `before` text matches; a single-use token was issued. |\n| `PREVIEW_BLOCKED` | The generated plan does not match the current tree; nothing can be applied. |\n| `WRITE_GATE_CLOSED` | The server was not deliberately started with source edits enabled. |\n| `APPLIED` | Every planned edit was written and the rollback bundle is available. |\n| `STALE` | The working tree changed between preview and the locked apply check; nothing was written. |\n| `TOKEN_UNKNOWN` / `TOKEN_EXPIRED` / `TOKEN_*_MISMATCH` | Confirmation is absent, consumed, expired, or belongs to another plan/repository. |\n| `REPO_BUSY` | Another apply or rollback currently owns the repository lock. |\n| `ROLLED_BACK` | A failed apply or explicit rollback restored the original files. |\n| `ROLLBACK_INCOMPLETE` | Restoration was blocked for named files; the durable bundle remains retryable. |\n| `INVALID_PLAN` | Schema, path, range, encoding, overlap, or provenance validation failed before writing. |\n| `INVALID_ARGS` | A required argument was missing or the wrong type; the offending names are listed. Nothing was planned. |\n\nPlanner-specific states such as `NOT_FOUND`, `NO_CHANGE`, `CONFLICT`,\n`BLOCKED`, `UNPROVEN`, and `NOT_SUPPORTED` remain visible instead of being\ncollapsed into a generic failure.\n\n## The three write gates\n\nRepository source changes require all three:\n\n1. `weavatrix-refactor-js` is installed and the `refactor` profile selects `edit`;\n2. the server starts with `WEAVATRIX_ALLOW_SOURCE_EDITS=1`;\n3. the apply call presents a valid, unexpired, single-use token bound to the\n   exact plan and repository.\n\nPreview and every read-only analysis remain available while the environment\ngate is closed.\n\n## End-to-end change proof\n\nThe package includes all 34 read-only core tools in the same MCP server. A\nstrong refactor session can therefore stay in one evidence chain:\n\n1. `inspect_symbol`, `context_bundle`, or `get_dependents` identifies the exact target;\n2. `rename_symbol`, `change_signature`, `move_symbol`, or another refactor tool previews the change;\n3. the write workflow applies atomically;\n4. the next graph call auto-refreshes changed files and reverse importers;\n5. `verified_change` compares callers, imports, and references against the merge base;\n6. `change_impact`, `verify_architecture`, `coverage_map`, `run_audit`, and `find_duplicates` inspect the consequences.\n\nUseful inherited surfaces include:\n\n- architecture maps and navigation: `module_map`, `query_graph`, `shortest_path`, `context_bundle`;\n- impact and proof: `change_impact`, `get_dependents`, `prepare_change`, `verified_change`;\n- health: `run_audit`, `find_dead_code`, `find_duplicates`, `coverage_map`, `hot_path_review`;\n- contracts: `list_endpoints`, `trace_endpoint`, `trace_api_contract`;\n- target architecture: `get_architecture_contract`, `verify_architecture`, `explain_architecture_violation`;\n- repository control: `open_repo`, `rebuild_graph`, `graph_diff`, `list_known_repos`.\n\nSee the [weavatrix-js README](https://github.com/Weavatrix/weavatrix-js)\nfor the complete JavaScript host catalog.\n\n## Run it\n\nStart the merged read-only-plus-refactor MCP server for one repository:\n\n```bash\nnpx -y weavatrix-refactor-js <repoRoot>\n```\n\nFor an MCP client, the minimal configuration is:\n\n```json\n{\n  \"mcpServers\": {\n    \"weavatrix\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"weavatrix-refactor-js\", \"/absolute/path/to/repository\"]\n    }\n  }\n}\n```\n\nOn Windows, use `npx.cmd` when the client does not resolve command shims.\nWith no environment override, every analysis and preview tool works but source\nwrites fail closed. Add `\"env\": {\"WEAVATRIX_ALLOW_SOURCE_EDITS\": \"1\"}` only\nfor a session in which apply and rollback are deliberately authorized.\n\nApplications that already host `weavatrix-js` can compose the same extension:\n\n```js\nimport {startMcpServer} from 'weavatrix-js/mcp-runtime'\nimport {refactorExtension} from 'weavatrix-refactor-js/extension'\n\nawait startMcpServer({\n  defaultCapabilities: 'refactor',\n  loadExtensions: async () => [refactorExtension()],\n})\n```\n\nThe exported extension registers tools and the `refactor` capability profile;\nit does not silently open the write gate.\n\n## Scope and honest limits\n\n- Related multi-symbol rename is currently JS/TS-only.\n- `move_file` cannot rename the file through `apply_edit_plan`; it is a review\n  plan because file relocation has different filesystem semantics.\n- `move_symbol` is a topology/architecture dry-run, not byte-edit synthesis.\n- Graph+lexical language backends cannot prove reference completeness and stay\n  `PARTIAL` even when every known reference was located.\n- `delete_readiness` never auto-deletes, and public/exported APIs cannot receive\n  an automatic clean verdict.\n- Tests, typechecking, runtime checks, and human review remain the release\n  authority. Weavatrix supplies bounded evidence; it does not fabricate proof.\n\n## Package boundary\n\n| Package | License | Responsibility |\n| --- | --- | --- |\n| `weavatrix-js` | MIT | Read-only JavaScript graph, analysis, evidence, architecture, and verification |\n| `weavatrix-refactor-js` | MIT | Proven refactor plans, transactional writes, and rollback |\n| `weavatrix-online` | MIT | Explicit public network connector and remote plan/evidence workflows |\n\nThe refactor package extends the legacy JavaScript core only through\n`weavatrix-js/extension-api` and `weavatrix-js/analysis-kit`; it does not copy\nor relicense that core. The canonical `weavatrix` package is the native Rust\nengine and is not this JavaScript extension host.\n\n## License\n\nMIT.\n",
  "bytes": 18046,
  "sha": "a22c957746b8927a56ec904f0b57a351e6778cc1e25b987dc4e3bb66aad933bd",
  "repo_slug": "sergii-ziborov/weavatrix-refactor-js",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_sergii_ziborov_weavatrix_refac_9a080af2/readme"
}