---
schema_version: "1.0"
name: Source Cleanup Audit and Fix
description: Find, verify, and implement worthwhile behavior-preserving source cleanups.
nodes:
  - id: scope
    mode: parallel
    providers:
      - provider: codex
        model: gpt-6-astra
        reasoning: low
        role: executor
  - id: scan.duplication
    mode: parallel
    needs: [scope]
    providers:
      - provider: codex
        model: gpt-6-astra
        reasoning: xhigh
        role: executor
  - id: scan.contracts
    mode: parallel
    needs: [scope]
    providers:
      - provider: codex
        model: gpt-6-astra
        reasoning: xhigh
        role: executor
  - id: report
    mode: parallel
    needs: [scan.duplication, scan.contracts]
    providers:
      - provider: codex
        model: gpt-6-astra
        reasoning: xhigh
        role: executor
  - id: fix
    mode: parallel
    needs: [report]
    providers:
      - provider: codex
        model: gpt-6-astra
        reasoning: xhigh
        role: executor
---

## scope

Map the current project's source code for a cleanup audit. This discovery node
is read-only: do not edit, stage, commit, format, generate files, or run commands
that mutate project state. Return your report as the node output.

1. Read applicable repository guidance and developer/architecture documentation
   when present. Record the current revision and worktree status if Git exists.
2. Identify production source roots, major ownership boundaries, validation
   commands, and relevant test roots. Include authored untracked source; exclude
   dependencies, caches, generated output, vendored code, and run artifacts.
3. Inspect recent changes when available to understand established cleanup
   patterns. They are context, not a restriction to reviewing the latest diff.
4. Give each downstream scanner an explicit source-root list and exclusions.
   Note boundaries that must remain separate and persisted formats to preserve.

Return a concise repository map, scan scope, applicable guidance paths, existing
shared helper owners, and verification entry points. Do not propose a redesign
or inspect secret values.

## scan.duplication

Find source duplication worth cleaning up. Keep the project read-only and return
the complete candidate report as node output. Do not create a separate report file.

Open the repository map: `{{scope.output_path}}`.
Scan only the source roots it identifies, following its exclusions and guidance.

1. Use text or syntax-tree searches to locate repeated algorithms, validation
   rules, naming formats, and wrappers that add no behavior.
2. Trace concrete callers and tests before accepting a candidate. Similar syntax
   alone is insufficient; distinguish shared policy from intentional differences.
3. Identify the narrowest existing owner that could absorb the shared behavior.
   Recommend a new module only when current consumers establish a real boundary.
4. Preserve externally visible behavior, persisted bytes/names, error handling,
   resource ownership, and concurrency semantics. Separate behavior fixes from
   mechanical cleanup proposals.

Return at most eight supported candidates, with stable IDs D1, D2, and so on.
For each, include exact file/line references for the repeated code and callers,
the maintenance cost, intended common rule, intentional differences, smallest
cleanup, affected tests, and an observable acceptance check. Include a short
list of tempting duplicates rejected because their contracts differ. If none
qualify, say so; do not manufacture candidates to fill the list.

## scan.contracts

Find shared contracts with scattered ownership. Keep the project read-only and
return the complete candidate report as node output. Do not create a separate file.

Open the repository map: `{{scope.output_path}}`.
Scan only its source roots and follow the recorded exclusions and guidance.

1. Trace producers and consumers of names, paths, serialized fields, validation
   predicates, and small policy objects across the mapped boundaries.
2. Look for independently reconstructed contracts, redundant representations,
   and shared behavior located under a caller-specific layer.
3. Verify each proposal against current callers and tests. Describe the concrete
   cost or drift risk and why an existing owner or local extraction resolves it.
4. Preserve boundary validation and deliberate differences in defaults, null
   handling, failure signals, cleanup, and resource ownership. Avoid general
   frameworks, speculative reuse, compatibility layers, and style-only proposals.

Return at most eight supported candidates with IDs C1, C2, and so on. For each,
give exact file/line references, producer and consumer paths, the shared contract,
intentional differences, proposed owner, minimal cleanup scope, affected tests,
and an observable acceptance check. Record uncertainty explicitly. Report no
candidates when the evidence does not support useful cleanup.

## report

Verify the proposed cleanups and return a prioritized maintenance report. Keep
the project read-only. The verified report defines the downstream fix node's scope.

Open these complete canonical artifacts:
- Repository map: `{{scope.output_path}}`
- Duplication candidates: `{{scan.duplication.output_path}}`
- Contract candidates: `{{scan.contracts.output_path}}`

Read only the named source locations, their directly affected callers, tests,
and governing guidance. Expand locally only to resolve a specific contradictory
claim; do not start another broad scan. Treat upstream suggestions as candidates
that require verification, not requirements to implement.

1. Merge overlapping proposals and discard unsupported, stylistic, already
   resolved, or overly broad recommendations. Distinguish intentional repetition
   from shared behavior with a clear owner.
2. Verify that each retained cleanup preserves the existing contract and removes
   more maintenance burden than its abstraction introduces.
3. Rank by concrete benefit, scope, and regression risk. Separate independent
   changes and identify dependencies between recommendations.
4. Recommend focused checks for exact formats, boundary inputs, failure behavior,
   and relevant integration paths. Never claim tests ran unless they did.

Return at most eight recommendations using this format for each:

### <priority>. <Action-oriented cleanup title>
- Evidence: exact file/line references and affected callers.
- Reason: the concrete maintenance burden or contract-drift risk.
- Scope and owner: the smallest complete change and where it belongs.
- Preserve: intentional differences and externally observable contracts.
- Validation: existing tests and any additional behavior checks needed.
- Effort/risk: small, medium, or large, with a brief reason and dependencies.

Finish with the recommended first change, rejected candidate IDs with brief
reasons, and verification limits. If none survive verification, return
"No worthwhile cleanup candidates found" with the inspected scope and limits.

## fix

Use write-code skill and implement the verified cleanup recommendations and return a validation report.
Use the complete maintenance report as the canonical implementation scope.

Open these complete canonical artifacts:

- Verified recommendations: `{{report.output_path}}`
- Repository map and guidance paths: `{{scope.output_path}}`

If the report contains no worthwhile cleanup candidates, make no changes and
return that outcome. Otherwise:

1. Read applicable repository guidance and use the write-code skill, including
   clean-code and review-code, when available. Check the current worktree before
   editing and preserve existing user changes. Do not stage or commit changes.
2. Inspect the report's named source locations, affected callers, and tests.
   Expand locally only to resolve a specific implementation question; do not
   start another broad scan. If a recommendation is stale or unsupported,
   explain why it cannot be applied and continue with independent valid items.
3. Implement all retained recommendations in dependency order, starting with the
   highest-priority independent change. Keep each cleanup within its verified
   scope and owner. Preserve public behavior, persisted formats and names,
   boundary validation, error handling, defaults, null semantics, resource
   ownership, and concurrency guarantees.
4. Add or update meaningful contract or regression coverage where needed. Run
   the focused checks identified in the report, then the repository's required
   validation commands. Update documentation only where the changes make it
   inaccurate or materially incomplete.
5. Review the final diff for correctness, regressions, and unintended changes.
   Resolve issues introduced by the cleanup and rerun affected checks. Report
   any remaining failure or unverified contract explicitly; never claim checks
   passed unless they ran successfully.

Return the implemented recommendations and their changed files, any skipped or
blocked recommendations with reasons, validation commands and results, and
remaining risks. Account for every recommendation in the report.

When files changed, finish with an exact `## Generated Files` heading followed
by one concrete workspace-relative path or Markdown link per line. Include only
files verifiably changed during this invocation, with no prose in that section.
Describe deleted files in the summary rather than claiming them as captured files.
