/shipwright:duplication-scan runs instead · from shipwright
Scans a repository for semantically duplicate or near-duplicate code patterns using judgment-driven comparison, tracks findings across runs in a PatrolFinding ledger, and reports stabilized patterns. Requires --repo flag. Read-only — no code changes.
This skill never runs in Claude Code
It ships in shipwright at skills/, but /shipwright:duplication-scan (a command, or a skill Claude Code finds first) has the same name: typing it, or Claude choosing it, runs that one instead.
Survey the codebase for emerging, unnamed duplicate or near-duplicate logic —
the same responsibility implemented independently in two or more places — weight
candidates by how actively their files are being edited, and track them across
multiple weekly runs in the task store's PatrolFinding ledger before proposing anything. This skill makes
no code changes — it reads and reports only.
Scope note — how this differs from entropy-scan: entropy-scan is stateless
and deterministic — it checks a fixed set of named rules from references/principles.md,
each with an explicit **Detection:** instruction, and every run stands alone.
duplication-scan is the opposite shape: there is no named rule to check against.
It relies on judgment — an LLM reading and comparing the purpose and structure of
code across files and services — to notice duplication that a deterministic checker
can't name in advance. Because a single pass of judgment-driven comparison is noisy
and prone to one-off false positives, this skill never proposes anything from a
single run: it persists what it finds as PatrolFinding rows and only
promotes a candidate once it has recurred, with a stable shape, across multiple runs
(Rule of Three — see Steps 6-7). Static clone-detection tools (jscpd, SonarQube CPD)
are explicitly not used here — they only catch textual/token clones; this skill's
job is to catch semantic duplication that shares no lines at all (e.g. three
independently-written retry-with-backoff implementations).
--repo org/repo is required. This skill scans exactly one repo per run (the
duplication-patrol system cron queues one task per repo). If --repo is missing
or not in org/repo form, print this usage error and stop without scanning:
--repo is required.
Usage: /shipwright:duplication-scan --repo org/repo [--summary] [--dry-run]
Work in a worktree of that repo (never edit the repos/ checkout directly) and run
the survey against it. Note the checked-out commit (git rev-parse HEAD) — it is
recorded with the run. The cron id used with the recorder below is
duplication-patrol. See the system-cron contract in docs/task-store.md.
Flags:
--summary — print counts to stdout; skip writing docs/patrols/duplication.md
(findings and the run record are still written)--dry-run — run the full scan (survey, churn-weighting, fingerprinting, counter
updates) but write nothing: no findings upsert, no run record, no docs file, no
PR. Print what would have been written instead. The legacy import is also skipped
(the legacy file is left untouched).See references/decisions-registry.md for the shared decisions-registry pattern this
mirrors — the generic entry schema, ownership, and consumption contract that
docs/duplication-decisions.md is one concrete instance of.
docs/duplication-decisions.md in the project root. This is the only
registry path: never read or write a decisions file under .claude/shipwright/.entropy-scan uses for a missing .claude/shipwright/principles.md
override. Print: "No duplication-decisions.md found — no suppressions configured."
and continue to Step 2 with an empty suppression list. This is expected on every
run until a sibling task adds that file — it is not an error.This suppression list is consulted twice later: once loosely during the survey (Step 3, to avoid wasting effort re-describing a pattern already accepted as debt) and once authoritatively before promotion (Step 7, which is the actual gate).
The ledger lives in the task store as PatrolFinding rows keyed by
(cronId = duplication-patrol, repo, fingerprint). Read prior state through the
cron-run recorder:
bun ${CLAUDE_PLUGIN_ROOT}/scripts/cron-run-recorder.ts prior \
--cron duplication-patrol --repo {org/repo} \
--legacy-shape consolidation-ledger
It prints {latest, findings, imported} JSON (read-only). findings are the repo's
PatrolFinding rows (all pages already followed): each has fingerprint, status
(tracking | ready_to_propose), firstSeen, lastSeen, occurrenceCount,
history, and a detail object holding description, files, notes,
consecutive_stable_runs, occurrence_count and proposed_shape.
One-time legacy import. This is the only step that touches the old agent-local
ledger (state/consolidation-ledger.json). When the store has no prior run for this
repo and the legacy file holds candidates for it, the recorder returns them under
imported, already filtered to this repo (other repos' entries are ignored). Treat
imported.findings as the prior ledger for this run, and log
Imported {N} legacy duplication candidates for {repo}. The recorder posts them
to the store and deletes the legacy file only after the record call in Step 8
succeeds, so a failed run leaves the file in place for a retry. After the import, no
step of this skill reads or writes that file again.
findings and imported are empty, the ledger is empty — a normal first
run, not an error.max(occurrenceCount, detail.occurrence_count) (an imported entry carries its
legacy count in detail.occurrence_count). consecutive_stable_runs, files,
description, notes, and the latest observation come from detail.This is explicitly not an AST/token clone scan. Do not run or emulate jscpd, SonarQube CPD, or a diff-based similarity tool. Instead:
plugins/shipwright/, and — when scanning a target project rather than this repo
itself — its own source layout). Favor breadth over exhaustive depth: sample
representative files across each service/package rather than reading every file
in full.detail and history in Step 8 and is
what future runs compare against to judge shape stabilityoccurrence_count over unrelated runs. When in
doubt, leave it out — a real duplication will keep showing up on its own in
future runs.For each candidate's involved files, compute a recency/frequency signal from git history:
git log -1 --format=%cd --date=relative -- <file>
git log --since="90 days ago" --oneline -- <file> | wc -l
Rank candidates churn-first (most recently/frequently touched first) — this is a prioritization signal for the report and for triage effort, not a filter. A dormant candidate is still tracked in the ledger; it just surfaces lower in ordering and is less urgent, since files nobody is editing don't suffer from the "update the same logic in two places" pain this skill exists to catch.
The fingerprint is the join key between this run's candidates and the ledger's prior entries. Getting this wrong means the stabilization counter (Step 6) never accumulates correctly, so keep it conservative and deterministic:
sha256(normalized_description + "|" + sorted_files.join(",")).candidates map from Step 2.
occurrence_count: 1, consecutive_stable_runs: 0, status: "tracking",
and this run's single observation as its detail. The store sets
firstSeen/lastSeen and the history entry.Important limitation to keep in mind: because the fingerprint includes the involved file list, a candidate whose set of duplicated files changes materially between runs (e.g. a third occurrence appears in a new file, or one occurrence gets renamed/moved) will not match the prior fingerprint and will instead register as a new candidate. This is a deliberate conservative tradeoff for the first version — it undercounts recurrence rather than risking a false match that corrupts an unrelated candidate's counters. Note this explicitly when reporting so a human reviewing the ledger understands why a pattern might appear to "reset." Expect to revisit this matching strategy after a few real runs.
For every fingerprint match found in Step 5:
occurrence_count by 1 (prior effective count from Step 2 plus one; the store's occurrenceCount is bumped by the same upsert).** A fingerprint match is by
definition a recurrence of the same description + file set, so the raw count
always goes up.consecutive_stable_runs. Compare this
run's candidate description/structure notes (from Step 3) against the ledger
entry's most recently recorded history entry:
consecutive_stable_runs by 1.consecutive_stable_runs
to 0. Note this only fires on an existing fingerprint match — since the
fingerprint (Step 5) is keyed on the description text, a change large enough
to alter the generic description itself (e.g. "retry with exponential
backoff" becoming "retry with a fixed delay and no backoff") would already
produce a different fingerprint and register as a new candidate in Step 5,
never reaching this branch. What lands here instead is a matched fingerprint
(same generic description, same files) whose recorded "why they look like the
same responsibility" reasoning has drifted — e.g. the description still reads
"retry a flaky network call with backoff" but this run's notes show the
backoff calculation changed from exponential-with-jitter to a hardcoded fixed
delay, a structural change not reflected in the (still-accurate-enough)
generic description. Rule of Three applies to the shape stabilizing, not
just the raw count — a candidate that keeps reappearing but keeps changing
shape is not ready to propose a single canonical replacement for, because
there's no settled target shape yet to propose.history when the
upsert lands (Step 8) — prior history entries are never rewritten.detail.files, detail.description, detail.notes to this run's
observation (the store's history retains the full trail), and
detail.occurrence_count / detail.consecutive_stable_runs to the new values.ready_to_proposeFor every candidate (new or matched) after Step 6's updates, evaluate promotion:
status: "ready_to_propose" only if all of the
following hold:
occurrence_count >= 3consecutive_stable_runs >= 2status: "ready_to_propose" on the finding.status stays "tracking" — it is silently tracked,
not listed in the docs file. This is the core "watch, don't act immediately" behavior this
system exists to implement: a candidate can sit at occurrence_count: 5 with
consecutive_stable_runs: 0 indefinitely (kept reappearing, but never in a
settled shape) and it will never be promoted until its shape stabilizes for two
consecutive runs.ready_to_propose entry that becomes newly suppressed (a
suppression was added since it was promoted) should be demoted back to
"tracking" — the decisions registry is authoritative and always re-checked
fresh each run, never cached from a prior promotion decision.Skip all of this under --dry-run (print what would be written instead).
docs/patrols/duplication.md (readable only)Build the file from the patterns that are open after Step 7 — the ready_to_propose
findings only. Tracking-but-not-yet-stable patterns stay in the store and never appear
in the file. The file is a human-readable list: per pattern a short title, why the
instances look like the same responsibility, the involved file paths, and the proposed
canonical shape. It carries no fingerprints, counters, sightings tables, run
history, resolved items or timestamps — all machine state lives in the task store, all
numbers in the run record. Order by churn (Step 4), highest first. It is capped at 150
lines: build it with renderPatrolDoc from
${CLAUDE_PLUGIN_ROOT}/scripts/check-patrol-docs.ts (one item per pattern; overflow
becomes a pointer line to the fix tasks).
Validate and detect material change against the repo's current file:
bun ${CLAUDE_PLUGIN_ROOT}/scripts/check-patrol-docs.ts {candidate.md} docs/patrols/duplication.md
It prints { violations, materiallyChanged } and exits non-zero on violations. If
there are violations, fix the candidate and re-run; never commit a file that fails.
If materiallyChanged is false (including a timestamp-only change or a pure
reorder), write nothing and open no PR — the unchanged file opens no PR. When it
is true, commit the file on a docs branch (docs/duplication-patrol-{YYYYMMDD})
in the repo's worktree and open a docs PR (first run gh label create shipwright --description "Opened by a Shipwright agent" --color 4F8EF7 --force, then gh pr create ... --label shipwright), using the same docs-PR
path as /shipwright:test-readiness (reuse an existing open docs PR for the patrol
rather than opening a second one). The file is skipped under --summary.
Write a result file (e.g. /tmp/duplication-result-{ts}.json) and post it:
bun ${CLAUDE_PLUGIN_ROOT}/scripts/cron-run-recorder.ts record \
--cron duplication-patrol --repo {org/repo} --commit {HEAD sha} \
--result /tmp/duplication-result-{ts}.json \
--legacy-shape consolidation-ledger
The result file is { "outcome": "ok" | "no_op", "metrics": {...}, "findings": [...] }:
findings: one { fingerprint, status, detail } per candidate observed this
run (new or matched), with status tracking or ready_to_propose and
detail = { description, files, notes, consecutive_stable_runs, occurrence_count, proposed_shape }.
The store upserts them: new fingerprints get occurrenceCount 1, continued ones
+1, lastSeen updates, and a history entry is appended. Prior findings not
observed this run are simply not sent — they stay in the store unchanged (a single
miss is not evidence of resolution, so never delete or decay them). When Step 2
returned imported, the recorder posts those legacy findings first.metrics: numeric counts for this run — new, matched, promoted,
ready_to_propose, tracking, suppressed, docs_pr (1 if a docs PR was opened).outcome: no_op when nothing was observed and nothing changed, else ok.The recorder posts exactly one run per invocation. If the scan itself fails
part-way, record the run with { "outcome": "failed", "metrics": {} } and stop.
--summary still records the run and findings (only the docs file is skipped), so
the next run's counters stay correct.
Always print a summary to stdout after the scan:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DUPLICATION SCAN COMPLETE — {org/repo}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
New candidates tracked this run: {N}
Candidates promoted this run: {N} (ready_to_propose)
Total tracked, not yet ready: {N} (status: tracking, in the store)
Suppressed by decisions registry: {N}
{docs PR opened: " Docs PR: {url}" | no material change: " docs/patrols/duplication.md unchanged — no PR."}
{If zero candidates are ready: " ✓ No candidates ready to propose yet — {N} still accumulating stability."}
{If --dry-run: "Dry run — nothing written."}
{Else if --summary: "Summary only — docs file not written; findings and run still recorded."}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
--repo org/repo is required. One repo per run; missing flag is a usage error.docs/patrols/duplication.md (via a docs PR, only on material change) and,
through the recorder, the task store's findings and run record. Nothing is
written in --dry-run mode.PatrolFinding rows. The
legacy agent-local ledger file is only ever read through the one-time import in
Step 2.git log calls are read-only history
inspection for churn-weighting.duplication-fix skill's job. It only writes findings and the run record.docs/patrols/duplication.md on its first observed occurrence — the
occurrence_count >= 3 AND consecutive_stable_runs >= 2 gate in Step 7 is not
optional and does not have a "confidence override."docs/duplication-decisions.md.--dry-run mutates nothing. No docs file, no PR, no findings, no run record.plugins/shipwright/, .claude/shipwright/ (read-only), the repo's
docs/patrols/ file, and the task store through the recorder.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub app-vitals/shipwright --plugin shipwright27 skills in this plugin
/agent-readinessScore one repo against the agent-readiness catalogue (docs/readiness.md) with the deterministic scorer, post one ReadinessSnapshot and record one run. Requires --repo org/repo. No model judgment, no task creation, no repo files./canary-executionCross-cutting contract for the test-readiness pipeline. Defines how canary-eligible test code runs in two modes — `local` (boot dependencies inline, hit localhost) and `canary` (skip the boot, hit a deployed `TEST_TARGET_URL`) — via a dedicated entry point separate from the local smoke runner. Specifies eligibility rules (read-only or self-cleaning, smoke/E2E only, critical/high tier only, zero DB-dependent tests) and the deploy-gate budget (<60s wall time). Referenced by the inventory, system-design, migration, and roadmap skills.
/Other plugins' skills for the same job