I Made My AI Agent Fix Its Own Copy-Paste ![rw-book-cover](https://img.youtube.com/vi/ubhVleOpLQ0/maxresdefault.jpg) ๐Ÿ”— **Source:** [I Made My AI Agent Fix Its Own Copy-Paste](https://www.youtube.com/watch?v=ubhVleOpLQ0) > [!note]+ Document Notes > tags: [ai-coding-agents, code-duplication-detection, php-static-analysis, developer-tooling, agentic-workflows] > author: Scott Keck-Warren > source: PHP Architect (YouTube) > reference: https://www.youtube.com/watch?v=ubhVleOpLQ0 > date created: 2026-08-15 > > > [!info] Generated analysis โ€” not the author's words. Sections below are machine-written > > from the captured source. Only text inside `> [!quote]` blocks is verbatim from the author. > > Do not quote or attribute any other line to the named author. > > # ๐Ÿท๏ธ Title: I Made My AI Agent Fix Its Own Copy-Paste (jscpd + Mago) > <!-- deep-read:sections start --> ## ๐Ÿงญ Table of Contents - [๐Ÿ“ Summary](#-summary) - [๐Ÿ“– Main Content](#-main-content) - [๐Ÿ—’๏ธ Notes](#๏ธ-notes) - [๐Ÿ“š References](#-references) - [๐Ÿ—ฃ๏ธ Paraphrase](#๏ธ-paraphrase) - [๐Ÿ“ฐ Newsletter](#-newsletter) - [โœ… Action Items](#-action-items) - [๐Ÿงช Hypotheses](#-hypotheses) - [๐Ÿ“Š Methodology](#-methodology) - [โ“ Questions](#-questions) - [๐Ÿ”ฎ Future Research](#-future-research) - [๐Ÿ’ก Implications](#-implications) - [๐Ÿง  Learning Styles Assessment](#-learning-styles-assessment) - [๐Ÿ“Š Accessibility Assessment](#-accessibility-assessment) - [๐ŸŒ DEIB Assessment](#-deib-assessment) - [โœ… Logical Validity](#-logical-validity) - [๐Ÿ›ก๏ธ DARVO Analysis](#-darvo-analysis) - [๐ŸŽฏ Conclusion](#-conclusion) ### ๐Ÿ”— References - [jscpd (GitHub)](https://github.com/kucherenko/jscpd) โ€” copy/paste detector for source code, 223+ formats - [jscpd.dev](https://jscpd.dev/) โ€” official docs - [Mago (Carthage Software)](https://mago.carthage.software/) โ€” Rust-based PHP toolchain (lint + analyze) - [PHP Architect YouTube channel](https://www.youtube.com/@Phparch) ## ๐Ÿ“ Summary - **What happened.** Scott Keck-Warren (PHP Architect) demonstrates pairing two fast, near-instant developer tools โ€” jscpd (a language-agnostic copy/paste detector) and Mago (a Rust-powered PHP static-analysis toolchain) โ€” inside an AI coding agent's edit loop, so the agent self-checks its own output for duplication and correctness before a human ever reviews the diff. - **Why it matters.** AI agents readily produce large volumes of working but repetitive code (the same validation block, the same fetch-and-guard pattern, the same try/catch wrapper, copy-pasted across controllers or models). That duplication is a maintenance liability โ€” one bug now has to be fixed in N places โ€” and it silently erodes review quality because reviewers stop reading carefully once code "looks like it works." - **Key stakeholders.** Individual PHP developers using agentic coding tools (Claude Code, Cursor, or any agent that can run shell commands); engineering teams responsible for code-review throughput and maintainability; tooling maintainers (jscpd's Andrey Kucherenko; the Mago/Carthage Software team) building agent-aware developer tooling. - **Risks and tradeoffs.** Over-aggressive duplication thresholds produce false positives (two short, coincidentally similar constructors) that waste agent cycles "fixing" non-problems; forcing premature abstraction on code that will legitimately diverge later creates worse coupling than the original duplication. Slow tooling defeats the entire premise โ€” a check that takes minutes gets run rarely, by which point the agent has already buried the problem under thousands more lines. - **Bottom line.** Speed is the load-bearing property: jscpd and Mago are fast enough to run after every single agent edit, which is what makes an automated "check your own work" loop viable at all. The tools catch *mechanical* problems (duplication, type mismatches, dead code, style) fast and cheaply, freeing human review time for the one thing tools can't judge โ€” whether the feature is the right feature. ## ๐Ÿ“– Main Content - **The problem framing.** LLM coding agents excel at turning a short prompt into thousands of lines of code, but volume isn't the same as originality. A large share of agent output is the same ~100-line pattern repeated with trivial variation (e.g., a record-fetch-or-404 guard duplicated near-identically across six model classes). Without a fast feedback loop, this duplication reaches the human reviewer already baked into the codebase. - **jscpd (JavaScript Copy/Paste Detector), despite the name, is language-agnostic** โ€” it works by tokenizing source rather than parsing each language's full grammar, so it covers PHP, Python, Go, and dozens of other languages without per-language configuration. It requires no install (run via npx-style invocation) or can be installed globally for frequent use. Pointed at a directory, it reports a duplicated-tokens percentage plus the exact file/line pairs where clones live. - **The `--threshold` flag turns a report into a guard rail.** Set a maximum tolerable duplication percentage; jscpd exits non-zero when the run crosses it (the video's example: 13.44% duplication against a threshold of 5 triggers a non-zero exit). A non-zero exit code is the signal an agent or CI pipeline needs โ€” it's binary, scriptable, and doesn't require an LLM to interpret prose output. - **Config lives in `jscpd.json`** at the project root so every run โ€” human or agent โ€” uses identical settings. The `reporters` option controls output shape: `console` (the table format), `html` (a browsable clickable report), and `json` (machine-readable, for feeding into other tooling or an agent's own reasoning). - **Worked duplication example.** Two controllers each fetch a record and guard against a missing result โ€” same shape, only the model name swapped. jscpd flags this as a clone. The fix is extracting the shared behavior into one place (the video's example calls it something like a shared "record responder"), so each controller delegates instead of repeating the guard clause. The payoff: when a user finds a bug in that logic, it's fixed once instead of in every duplicated copy. - **Mago covers the failure mode jscpd can't see: correctness, not repetition.** Mago is a Rust-written static-analysis toolchain for PHP, fast enough to run on every edit. `mago lint` checks style consistency; `mago analyze` builds a semantic model of the code and catches type errors, dead code, and logic that structurally cannot work โ€” e.g., a function that claims an `int` return type but actually returns a string. Together, jscpd (duplication) and Mago (correctness/style) cover two distinct, complementary failure modes of AI-generated code. - **Wiring it into an agentic loop.** The pattern is a small `check.sh` script that runs jscpd and Mago's two subcommands in sequence with `set -e`, so the script exits non-zero the moment any one of the three checks fails โ€” that failure signal is what an agent (Claude Code, Cursor, or any agent that can execute shell commands) needs to know it must fix something before moving on. The script gets wired either as a post-edit hook or as a plain instruction in the agent's configuration ("run check after every change and fix what it reports"). For Claude Code specifically, the presenter describes adding a corresponding section to `.claude/settings.json`. In practice: the agent sees duplication cross 5%, extracts the repeated block, and moves on โ€” all before a human looks at the diff. - **Why speed is the actual mechanism, not a nice-to-have.** The video's central causal claim: a check that takes two minutes gets run once a day at best, and by then the agent has already produced another few thousand lines on top of the original problem. Because jscpd and Mago both run in seconds, they're cheap enough to run on *every* iteration โ€” and running on every iteration, not occasionally, is what actually keeps an agent's output on track. - **Caveats and calibration.** jscpd will flag coincidental matches (e.g., two short constructors that happen to line up) as clones โ€” the fix is raising the minimum-tokens or minimum-lines thresholds until trivial matches stop triggering. Not all duplication is bad: two functions that look alike today may need to diverge tomorrow, and forcing a shared abstraction prematurely can create worse coupling than the duplication it replaced โ€” the tools see mechanically, not contextually, so a human override is sometimes warranted. Thresholds should be project-specific and adjusted over time: a greenfield project might hold at 3%, a legacy codebase might need to start around 15% and ratchet down over months as debt is paid off. The presenter's framing throughout: these are guard rails, not a substitute for review โ€” they exist to free human review capacity for judgment calls (is this even the right feature?) that tooling can't make. ### ๐Ÿ—’๏ธ Notes #### โฑ๏ธ [00:00:01](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=1) Cold open โ€” the AI-agent duplication problem - Agents readily hand back thousands of lines that look like a win until you notice the same validation block, fetch pattern, or try/catch wrapper repeated across multiple files. - Framing claim: "that doesn't mean it's all unique code" โ€” volume of output is not a proxy for quality or originality. - The proposed fix: a fast feedback loop so the agent catches duplication itself, before a human ever sees the diff. #### โฑ๏ธ [00:00:51](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=51) Channel intro + tool pairing announced - Host: Scott Keck-Warren, PHP Architect YouTube channel. - Two tools introduced: jscpd (copy/paste detection) and Mago (Rust-powered PHP static analysis / linting). #### โฑ๏ธ [00:01:13](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=73) jscpd mechanics - Language-agnostic despite the "JavaScript" in the name โ€” works via tokenization, not per-language parsing. - No-install or global-install usage; point at a directory; reports a duplicated-tokens percentage plus file/line locations. #### โฑ๏ธ [00:01:50](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=110) Threshold flag and jscpd.json config - `--threshold` turns a report into an enforceable gate: crossing it exits non-zero. - Worked number: 13.44% duplication vs. a threshold of 5 โ†’ non-zero exit, which is the signal an agent/CI needs. - `jscpd.json` centralizes settings so every run is consistent; `reporters` option = console / html / json output modes. #### โฑ๏ธ [00:02:29](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=149) Worked duplication example - Two controllers, same fetch-and-guard shape, only the model name differs โ€” flagged as a clone. - Fix: extract shared behavior into one place; each controller now delegates; a bug fix now applies once instead of N times. #### โฑ๏ธ [00:03:00](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=180) Sponsor segment - Cloud-infrastructure orchestration sponsor read (CLI-driven Kubernetes deployment across AWS/Azure/GCP, positioned against unmanaged Docker/Kubernetes/Terraform complexity). Sponsor name is garbled in the auto-generated transcript ("Displace" / "displace.te") and not independently verified โ€” do not cite the sponsor's actual name or URL from this source without confirming it against the video itself. #### โฑ๏ธ [00:03:40](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=220) Mago overview - Rust-written PHP static-analysis toolchain, fast enough to run on every edit. - `mago lint` = style consistency; `mago analyze` = semantic model, catches type errors, dead code, logic that can't work (e.g., declared `int` return that actually hands back a string). - Positioned as complementary to jscpd: duplication vs. correctness/style are two distinct failure modes. #### โฑ๏ธ [00:04:20](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=260) Wiring into the agentic loop - `check.sh` runs jscpd + Mago's two subcommands with `set -e` so any single failure returns non-zero. - Wired as a post-edit hook, or as a plain agent instruction ("run check after every change and fix what it reports"). - For Claude Code specifically: a corresponding section added to `.claude/settings.json`. - Result loop: agent sees duplication cross 5%, extracts the repeated block, moves on โ€” before a human reviews. #### โฑ๏ธ [00:05:00](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=300) Why speed is the mechanism - A 2-minute check gets run once a day (if that); by then the agent has piled another ~3,000 lines on top. - jscpd and Mago run in seconds, which is what makes "check after every iteration" actually viable. #### โฑ๏ธ [00:05:30](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=330) Caveats: false positives and premature abstraction - Coincidental matches (short constructors that happen to align) get flagged โ€” raise minimum tokens/lines to quiet trivial matches. - Not all duplication is bad; forcing early abstraction on code that will legitimately diverge can create worse coupling than the duplication it "fixes." - The tools see mechanically, not contextually โ€” a human override is sometimes the right call. #### โฑ๏ธ [00:06:02](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=362) Threshold calibration is per-project - Greenfield service: hold around 3%. - Legacy codebase: may need to start around 15%, then ratchet down over months. - Framing: pick a number you can actually pass today, then tighten it over time โ€” guard rails, not a replacement for review. #### โฑ๏ธ [00:06:27](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=387) Recap - jscpd: fast, language-agnostic, reports duplication % and clone locations; use `--threshold` to fail the build. - Extract flagged clones into a shared method/trait/service so fixes happen once. - Pair jscpd with Mago to cover duplication and correctness together. - `check.sh` run after every edit turns both tools into an immediate feedback loop for the agent. #### โฑ๏ธ [00:06:56](https://www.youtube.com/watch?v=ubhVleOpLQ0?t=416) Outro and CTA - Asks viewers for their worst AI-agent duplication "war stories" in the comments. - Standard like/share/subscribe close; sign-off as Scott Keck-Warren, PHP Architect channel. ## ๐Ÿ“š References - [jscpd (GitHub) โ€” Kucherenko](https://github.com/kucherenko/jscpd) - [jscpd.dev โ€” official docs](https://jscpd.dev/) - [Mago โ€” Carthage Software](https://mago.carthage.software/) - [PHP Architect YouTube channel](https://www.youtube.com/@Phparch) - [PHP Architect โ€” Community Corner: JSCPD with Andrey Kucherenko](https://www.phparch.com/podcast/community-corner-jscpd-with-andrey-kucherenko/) โ€” companion podcast interview with jscpd's creator, useful primary-source cross-reference for jscpd's design intent around AI-agent workflows ## ๐Ÿ—ฃ๏ธ Paraphrase - **Opening:** Agents make it trivially easy to get 5,000 lines of working code, but "working" hides repetition โ€” the same guard clauses and boilerplate copy-pasted across files, which turns into a maintenance burden and a review that no longer catches real problems. - **jscpd section:** A token-based, language-agnostic scanner reports what percentage of a codebase is duplicated and exactly where; a threshold flag converts that report into a pass/fail signal an agent or CI can act on without a human reading prose output. - **Worked example:** Two near-identical controller methods are exactly what the tool is built to catch โ€” the fix is a shared extraction, not a manual rewrite of each copy. - **Mago section:** Duplication detection alone doesn't tell you if the code is *right*. A Rust-based PHP analyzer running on every edit catches type mismatches, dead code, and unreachable logic โ€” the correctness half of the equation. - **Integration section:** The actual payoff comes from chaining both tools into a single fail-fast script the agent must run after every change, wired either as a hook or as a standing instruction. - **Speed argument:** None of this works if the checks are slow โ€” slow checks get skipped, and by the time they'd run, the damage has already compounded. - **Caveats:** The tools are blunt instruments โ€” they need tuning against false positives, they can't judge whether an abstraction is premature, and they don't replace human review of whether the feature itself is right. ## ๐Ÿ“ฐ Newsletter Found a genuinely useful pattern for anyone running AI coding agents against PHP (or any) codebases: pair jscpd (a fast, language-agnostic copy/paste detector) with Mago (a Rust-powered PHP static analyzer) inside a single `check.sh` your agent runs after every edit. jscpd catches the "same 100 lines with the model name swapped" problem that agents produce constantly; Mago catches the type errors and dead code jscpd can't see. The insight that generalizes past PHP: the whole scheme only works because both tools run in seconds โ€” a two-minute check gets skipped, a two-second check becomes a real feedback loop. If your team runs agentic coding sessions and hasn't wired a fast self-check hook into the loop yet, this is a 15-minute watch worth the time. Video: [I Made My AI Agent Fix Its Own Copy-Paste (jscpd + Mago)](https://www.youtube.com/watch?v=ubhVleOpLQ0), PHP Architect / Scott Keck-Warren. ## โœ… Action Items #### DevRel - Developer advocacy: build a short demo/talk showing a fast pre-commit or agent-hook duplication+lint check as a concrete "responsible AI coding" pattern for conference/meetup content. - Education: publish a companion tutorial pairing jscpd + a language's native static analyzer (Mago for PHP; equivalents for other ecosystems) as a reusable agent-hook recipe. - Developer experience: template a starter `check.sh` + config (jscpd.json equivalent) that teams can drop into a new agentic-coding repo. - Developer marketing: not applicable โ€” no product/campaign angle in this source. - Community management: solicit and curate the "worst AI-duplication war story" thread the video explicitly invites, as a low-effort community engagement hook. - Internal/external/cross-project: share the fail-fast `check.sh` pattern across teams running Claude Code / Cursor / other shell-capable agents so the hook convention is consistent. #### OSPO - Policy & Governance: not applicable to this source โ€” no contribution-policy content discussed. - License Compliance: not applicable โ€” not discussed. - Security Management: adjacent but not discussed directly; Mago's `analyze` step (type/logic correctness) is a natural place to eventually fold in security-relevant static checks, worth flagging for a future OSPO tooling review. - Software Inventory: not applicable โ€” not discussed. - Developer Support: document the post-edit-hook pattern (jscpd + Mago + `set -e`) as a supported internal recipe for teams standing up agentic workflows. - Community Engagement: not applicable โ€” not discussed. - Strategic Alignment: not applicable โ€” not discussed. #### Community - Maintainers: consider recommending a duplication-detection + static-analysis gate as a baseline expectation for projects that accept AI-agent-generated contributions. - Contributors: not applicable โ€” no contributor-onboarding content in this source. - Sponsors: not applicable โ€” not discussed. - Ecosystem: cross-project value in standardizing on fast (seconds-not-minutes) pre-merge checks specifically because agent-generated PRs are now common enough to need this as a default, not an opt-in. #### WordPress *Note on relevance: this video does not mention WordPress. The tools discussed (jscpd, Mago) are general-purpose/PHP-ecosystem tools, not WordPress-specific. The items below extrapolate plausible applications to WordPress Core and plugin development โ€” since Core, Core plugins, and much of the wp.org ecosystem are PHP codebases where AI-agent contributions are increasingly common โ€” rather than reflecting anything stated in the source.* - Core: evaluate wiring jscpd + a PHP static analyzer (Mago, or existing PHPCS/PHPStan tooling) into the AI-assisted-contribution review path as a fast pre-review gate, given Core's stated interest in responsible AI tooling. - CLI: a `check.sh`-style wrapper (duplication + static analysis + non-zero exit) maps directly onto WP-CLI's existing scaffold/test tooling conventions; worth prototyping as a `wp scaffold` addition for plugin/theme starter kits. - Documentation: document the "fast, agent-run, fail-fast checklist script" pattern in Core's or Meta's contributor-facing AI-tooling guidance, since it's a concrete, low-effort recommendation for anyone using agentic coding tools against wp.org codebases. - Other WordPress subteams (Core Performance, Core AI, Core Program Team, Mobile, Playground, Community, Training, Marketing, Support, Design, Photos, TV, Polyglots, Accessibility, Meta, Hosting, Tide, Openverse, Themes, Plugins): not applicable โ€” no content in this source connects to these subteams' work. #### The WPOCC - Not applicable to this source โ€” the video does not discuss The WPOCC, WordPress governance, or community funding structures; it's a general PHP-tooling tutorial with no WordPress-specific content. ### FAIR - Not applicable to this source โ€” no discussion of governance, provenance, or funding covenants. ## ๐Ÿงช Hypotheses - H1: Repositories that wire a sub-5-second duplication+lint check into an AI agent's post-edit loop will show measurably lower duplicated-token percentage over time than repositories relying on periodic (daily/weekly) manual or CI-only checks, because agents self-correct before duplication compounds. - H2: Teams that set a `--threshold` gate at a level the current codebase can already pass (rather than an aspirational target) will sustain the practice longer (measured by consecutive weeks without threshold overrides/disables) than teams that set an initially-failing threshold. - H3: For a fixed volume of AI-agent-generated PHP code, pairing a duplication detector with a type/logic static analyzer (Mago-style) will catch a materially different, largely non-overlapping set of defects than either tool alone โ€” i.e., the two failure modes (repetition vs. incorrectness) are statistically close to independent. - H4: Check scripts that exceed roughly 30โ€“60 seconds of wall-clock time will see agent/developer compliance (frequency of invocation) drop sharply compared to sub-10-second scripts, consistent with the video's "2-minute check runs once a day" claim. - H5: Legacy codebases that start duplication thresholds high (e.g., ~15%) and ratchet down on a fixed cadence (e.g., quarterly) will reach a target threshold (e.g., 5%) with fewer disruptive large refactor PRs than codebases that impose the target threshold immediately. ## ๐Ÿ“Š Methodology - H1/H4 (adoption vs. check latency): instrument CI/agent-hook logs across a sample of repositories to correlate check runtime with invocation frequency and duplication-percentage trend over a fixed window (e.g., 90 days); would need repos with and without the fast-hook pattern as a comparison group. - H2 (threshold-setting behavior): survey or repo-mine a sample of projects using jscpd's `--threshold` flag; classify initial threshold as "passing" vs. "aspirational" at time of adoption, then track whether/when the check gets disabled or overridden. - H3 (independent failure modes): run both jscpd and a static analyzer against a corpus of AI-agent-authored PHP commits; compute the overlap between flagged locations to test independence. - H5 (ratchet strategy): compare refactor-PR size distributions between projects that step thresholds down incrementally versus projects that impose a stricter target immediately, controlling for codebase size and duplication baseline. ## โ“ Questions - How does the false-positive rate of token-based duplication detection (jscpd) scale with a codebase's use of legitimately similar-but-divergent patterns (e.g., CRUD scaffolding), and is minimum-token/minimum-line tuning sufficient to control it at scale? - Does wiring `mago analyze`'s type/logic checks into the same agent loop as duplication detection change *what kind* of duplication agents produce (e.g., pushing agents toward correct-but-still-duplicated code, since analyze doesn't penalize repetition)? - What's the actual compliance rate when a check is "wired as an instruction" (agent told to run it) versus a true hook (mechanically enforced) โ€” does the video's recommended pattern hold up when agents are under context pressure and skip steps? - At what duplication percentage does forcing an abstraction genuinely start producing worse code than tolerating the duplication, and can that threshold be estimated per-codebase rather than guessed? - Is there a meaningful difference in outcomes between a human writing check.sh once versus an agent being asked to write its own guard-rail script (a more self-referential/self-policing pattern)? ## ๐Ÿ”ฎ Future Research - Empirical study of duplication-percentage trends in AI-agent-authored PHP repositories before and after adopting a fast post-edit hook, ideally across multiple teams/organizations. - Comparative benchmarking of jscpd against other duplication detectors (e.g., PMD CPD) specifically on AI-agent-generated code, since agent duplication patterns (near-identical boilerplate with minor parameter swaps) may differ systematically from human-authored duplication (copy-paste-and-forget). - Investigation into whether static analyzers like Mago should ship agent-specific output modes (structured JSON diagnostics tuned for LLM consumption) versus human-readable terminal output, and whether that changes agent fix-rate or fix-quality. - Longitudinal tracking of threshold-ratchet strategies (start high, tighten over time) in legacy codebases to establish evidence-based default ratchet schedules. ## ๐Ÿ’ก Implications - **Practice:** The fast-feedback-hook pattern (duplication detector + static analyzer + fail-fast script, wired to run after every agent edit) is a low-cost, immediately actionable practice any team using agentic coding tools can adopt this week โ€” it requires no new tooling purchase, only wiring two existing free/open tools into an existing agent's hook or instruction surface. - **Policy:** Teams and organizations formalizing "AI-assisted contribution" policies (relevant to any OSPO or open-source project accepting agent-generated PRs) have a concrete, cheap gate to require โ€” duplication threshold + static-analysis pass โ€” as a baseline before human review time is spent. - **Security:** Indirect but real โ€” Mago's `analyze` step catching "logic that can't work" (e.g., type mismatches) closes a class of AI-hallucinated-code bugs before they reach review, though the video does not claim or demonstrate security-vulnerability detection specifically. - **Education:** A clean, teachable example of "guard rails, not gatekeeping" โ€” useful for teaching newer developers (and teams skeptical of agentic coding) that agent output quality is manageable with lightweight, fast automated checks rather than requiring line-by-line manual review of every AI-generated diff. - **Funding models:** Not directly discussed; tools involved (jscpd, Mago) are open source, so the practice has no vendor lock-in or budget barrier to adoption โ€” worth noting as a factor in why this pattern is realistic for solo developers and small teams, not just well-funded orgs. ## ๐Ÿง  Learning Styles Assessment - Reading level estimate: approximately Flesch-Kincaid Grade 9โ€“10 (technical vocabulary โ€” "token-based," "semantic model," "non-zero exit code" โ€” offset by short, direct sentences and a conversational tutorial register typical of a YouTube dev-tools explainer). #### ๐Ÿ‘€ Visual learners - Present: on-screen terminal output showing jscpd's duplication table and the worked before/after controller-refactor code example (described verbally in the transcript, implying screen-share visuals in the video itself). - Improve: an architecture diagram showing the check.sh flow (edit โ†’ jscpd โ†’ mago lint โ†’ mago analyze โ†’ pass/fail โ†’ agent continues/fixes) would make the loop concept immediately legible without needing to track the verbal explanation. #### ๐Ÿ”Š Aural learners - Present: the video itself is narrated screen-share tutorial content, well suited to aural learners as delivered. - Improve: a standalone audio-only walkthrough/podcast cut (the presenter already runs a companion podcast) would let this content work without the visual terminal demonstrations. #### ๐Ÿ—ฃ๏ธ Verbal learners - Present: clear analogies ("a report that fails your build is the guard rail"; "guard rails, not a replacement for review") and defined terms (threshold, reporter, semantic model). - Improve: an explicit glossary or on-screen term callouts for jscpd/Mago-specific vocabulary (tokens, clones, reporters) would help viewers unfamiliar with either tool. #### ๐Ÿงฉ Kinesthetic learners - Present: the check.sh pattern is inherently a "try it yourself" recipe โ€” concrete commands and config a viewer can replicate immediately. - Improve: a companion repo or gist with the actual jscpd.json, check.sh, and settings.json snippets referenced but not fully shown on-screen would let viewers reproduce the setup without transcribing terminal output. #### ๐Ÿง  Logical learners - Present: clear causal chain (slow checks โ†’ skipped checks โ†’ compounding duplication) and a before/after worked example. - Improve: a decision table (duplication % range โ†’ recommended threshold โ†’ recommended action) would formalize the "greenfield 3%, legacy 15%, ratchet down" guidance into something directly actionable. #### ๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ Social learners - Present: the explicit prompt for viewers to share "war stories" in the comments creates a built-in discussion hook. - Improve: a structured discussion prompt (e.g., "share your jscpd.json threshold and why") would generate more comparable, useful community discussion than an open-ended prompt. #### ๐Ÿง˜โ€โ™€๏ธ Solitary learners - Present: the content is fully self-contained and reproducible without needing a cohort or live session. - Improve: a self-check quiz ("what would jscpd flag in this snippet?") would let solitary learners verify understanding without needing to run the tools themselves. #### ๐ŸŒฟ Naturalistic learners - Present: not directly present โ€” no ecosystem/environmental framing in the source. - Improve: a "codebase health" framing (duplication and technical debt as an ecosystem that compounds or degrades over time, much like the video's own legacy-vs-greenfield threshold framing) would give naturalistic learners a hook, though this would be an added frame rather than something in the source. ## ๐Ÿ“Š Accessibility Assessment #### Screen reader semantics - Present: standard YouTube video structure with title and description; no additional information available on in-video captions/chapters from the transcript alone. - Improve: published video chapters (YouTube chapter markers) matching the topic shifts identified in this analysis (intro, jscpd, worked example, Mago, integration, caveats, recap) would materially improve screen-reader and non-visual navigation of the content. #### Keyboard navigation - Present: not applicable to video content directly โ€” standard YouTube player keyboard controls apply. - Improve: not applicable โ€” outside the source's or creator's direct control beyond platform defaults. #### Contrast and readability - Present: unknown from transcript alone โ€” cannot assess on-screen terminal/code contrast without visual review of the video. - Improve: cannot assess without visual review; flagging for reviewer if a full accessibility audit of the video is needed. #### Text resizing and reflow - Present: not applicable โ€” video content, not text/web content. - Improve: not applicable. #### Media and captions - Present: this document was built from a captured transcript, confirming captions/transcript exist for the video. - Improve: the auto-generated transcript contains clear errors (tool names "jscpd"/"Mago" rendered as "JS CPD"/"MO"/"MGO"; the host's name "Keck-Warren" rendered as "Kekwarren"/"Kekin"; the sponsor name is garbled beyond recovery) โ€” creator-provided or corrected captions would substantially improve accessibility and searchability for viewers relying on captions/transcripts. #### Forms and interactions - Present: not applicable โ€” no forms or interactive elements in video content. - Improve: not applicable. #### Standards reference - Media and captions gap maps to WCAG 2.2 AA 1.2.2 (Captions, Prerecorded) โ€” captions exist but contain accuracy errors that would benefit from creator review against the source audio. ## ๐ŸŒ DEIB Assessment #### Cultural breadth - Present: no international/multi-region framing in this source โ€” single presenter, single tooling ecosystem (PHP). - Improve: not applicable to this content type โ€” a tool tutorial doesn't require geographic/cultural breadth to be complete; noting absence rather than a gap. #### Inclusive language - Present: plain, jargon-defined technical language throughout ("threshold," "reporters," "semantic model" are each explained on first use). - Improve: none identified โ€” language is already accessible for its target technical audience. #### Neurodiversity support - Present: consistent structure (tool โ†’ mechanism โ†’ worked example โ†’ integration โ†’ caveats โ†’ recap) that repeats predictably. - Improve: the video's stated chapter/topic structure isn't reflected in visible on-screen chapter markers (per available data); adding them would help viewers who benefit from predictable, navigable chunking. #### Representation - Present: single presenter (Scott Keck-Warren); the video also credits the two tools' respective communities (jscpd, Mago/Carthage Software) by name. - Improve: not applicable โ€” a solo tutorial format doesn't inherently require broader representation to be complete. #### Psychological safety - Present: respectful, non-alarmist framing of AI-agent-generated duplication ("it's so easy... it might even feel like a win" โ€” treats the problem as a normal consequence of the tooling, not a developer failing) and the comments prompt is framed as lighthearted ("war stories") rather than shaming. - Improve: none identified โ€” the tone throughout is collegial and blame-free toward both developers and the AI tooling itself. ## โœ… Logical Validity #### Strong reasoning - Causal chain (~5:00โ€“5:22 mark): "a check that takes 2 minutes is a check that you'll run once a day... jscpd and Mago scan in seconds... running them on every iteration is what keeps the AI on track" โ€” a clear, testable causal claim linking check latency to check-frequency to outcome quality. Strength: specific, falsifiable, and consistent with known human/agent behavior around friction and compliance. - Analogical reasoning (worked example, ~2:29): the two-controller duplication example is a concrete, minimal instance that generalizes cleanly to the abstract claim about AI-generated boilerplate โ€” a well-chosen illustrative case rather than a strawman or cherry-picked edge case. - Calibrated claims (~5:30โ€“6:27): the caveats section explicitly limits the tools' own claims ("the tools only see in black and white," "not a replacement for review"), which strengthens overall credibility by avoiding overclaiming what automated checks can do. #### Fallacies - None identified. The video stays within its stated technical scope, qualifies its claims (thresholds are per-project, not universal; duplication isn't always bad), and does not make appeals to authority, urgency, or fear beyond ordinary tutorial framing ("maintenance nightmare," "drains the life out of you" are hyperbolic but flagged as rhetorical color, not load-bearing argument). #### Tone of voice - Conversational, practitioner-to-practitioner tutorial tone throughout; direct address to the viewer ("you," "your agent"); mild hyperbole for relatability ("drains the life out of you") balanced by concrete technical specificity (exact percentages, exact flag names, exact file names) that keeps the content grounded rather than purely promotional. ## ๐Ÿ›ก๏ธ DARVO Analysis - Not applicable to this source. DARVO (Denyโ€“Attackโ€“Reverse Victim and Offender) analysis applies to interpersonal or institutional conflict/accountability narratives; this is a technical tutorial with no accusation, denial, or victim/offender framing present. ## ๐ŸŽฏ Conclusion - **Bottom line:** Pairing a fast, language-agnostic duplication detector (jscpd) with a fast PHP-specific static analyzer (Mago) inside a single fail-fast script that an AI coding agent runs after every edit turns "review the agent's output" into "the agent reviews itself, fast enough that it actually happens." The mechanism that makes this work isn't the specific tools โ€” it's that both run in seconds, which is the only way a self-check loop survives contact with an agent's iteration speed. - **Practical next steps:** (1) Install jscpd and a project-appropriate static analyzer; (2) set an initially-passing `--threshold` rather than an aspirational one; (3) write a `check.sh` with `set -e` chaining both tools; (4) wire it as a post-edit hook or explicit agent instruction; (5) revisit and ratchet the threshold down on a fixed cadence as the codebase's duplication debt is paid down. ## ๐Ÿ”„ Refactor Appendix โ€” I Made My AI Agent Fix Its Own Copy-Paste (jscpd + Mago) > Density: 2โ€“5 Literature atoms (H3), 0โ€“3 Permanent candidates (H4). > Defaults: 3 Literature, 1 Permanent. Resonance filter: if you can't > articulate in one line why a claim matters, drop it. > > Konik claim-header rules: present tense, declarative, โ‰ค10 words when > possible, searchable, unique, mirrors annotation focus if present. > > Atomicity: one declarative sentence per atom. "and"/"also" โ†’ split. > > Tag pool: #bmf ยท #addendum ยท #xref ยท #articleseed ยท #storystem ยท #share ยท #aphorisms ### ๐Ÿ“š Literature Atoms (H3) #### [H1] Check speed determines whether agents actually self-correct > [!quote] ID:rw_ubhVleOpLQ0_h1 > "A check that takes 2 minutes is a check that you'll run once a day, if that, and by then the agent has buried your problem under another 3,000 lines." **Context & use**: - ~5:00โ€“5:22 in the video, immediately after the Mago/jscpd integration explanation. - Core mechanism claim of the whole video โ€” everything else (thresholds, hooks, config) is downstream of this being true. **Tags**: #xref #aphorisms **Highlight**: [view highlight](readwise://ubhVleOpLQ0_h1) <!-- atomicity: 1 idea โœ“ --> #### [H2] Threshold flag converts a duplication report into a build gate > [!quote] ID:rw_ubhVleOpLQ0_h2 > "If the duplication comes back at 13.44% against a threshold of five, the process exits with a non-zero status... which is exactly what an agent or a CI pipeline needs to know that something went wrong." **Context & use**: - ~1:50โ€“2:12 in the video, explaining jscpd's `--threshold` flag. - Establishes the general pattern (report โ†’ binary pass/fail signal) that recurs with Mago later. **Tags**: #xref **Highlight**: [view highlight](readwise://ubhVleOpLQ0_h2) <!-- atomicity: 1 idea โœ“ --> #### [H3] Duplication detection and static analysis catch independent failure modes > [!quote] ID:rw_ubhVleOpLQ0_h3 > "JavaScript copypaste detector tells you if your code is repeated, but it says nothing about whether the code is right." **Context & use**: - ~3:40, the transition point from jscpd to Mago. - Grounds Hypothesis H3 (independence of duplication vs. correctness defects) directly in the source. **Tags**: #xref #articleseed **Highlight**: [view highlight](readwise://ubhVleOpLQ0_h3) <!-- atomicity: 1 idea โœ“ --> ### ๐Ÿง  Permanent Candidates (H4) #### [P1] Automated guard rails should be scoped to what tools can mechanically verify **Claim** (one sentence, Courtney's voice): Automated code-quality checks earn a place in an agent's edit loop only when they're fast enough to run on every iteration and scoped to mechanically-verifiable problems, leaving judgment calls for human review. **Evidence pointer**: [[#H1]] **Scope & conditions**: Holds for any automated gate (linting, duplication, type-checking) wired into a fast iteration loop โ€” human, agent, or CI. Breaks down if the "mechanically-verifiable" scope creeps into judgment calls (e.g., "is this the right abstraction," "is this the right feature") that the tool can't actually assess โ€” the video explicitly warns against exactly this overreach. **Links** (โ‰ฅ1 with annotation): - [[Fast feedback loops]] โ€” because extends a general software-engineering principle (tight iteration loops improve output quality) into the agentic-coding context specifically. - [[Guard rails vs. gatekeeping]] โ€” because contrasts on scope: a guard rail catches mechanical problems fast; gatekeeping would try to adjudicate judgment calls the tool isn't equipped for. <!-- atomicity: 1 idea โœ“ --> ### โœ๏ธ Fleeting Queue - [F1] Look into whether Mago's `analyze` output format is structured enough (JSON mode) to feed directly into an agent's context without a parsing step โ€” worth checking Mago's docs. #xref - [F2] The "start high, ratchet down" threshold strategy for legacy codebases parallels error-budget/SLO ratcheting in reliability engineering โ€” possible cross-domain analogy worth a short post. #articleseed ### โ†’ Things 3 (max 2 actions) - [ ] Evaluate wiring a jscpd + Mago-equivalent (PHPStan/PHPCS if Mago isn't adopted) fail-fast check into any WordPress plugin repos using agentic coding tools โ€” dev-outpost, dev-link-extension-for-xfn, dev-post-formats-for-block-themes, dev-post-kinds-for-indieweb #things - [ ] Watch the companion PHP Architect "Community Corner: JSCPD with Andrey Kucherenko" podcast episode for the tool-creator's own framing of the AI-agent use case #things <!-- deep-read:sections end --> ๐Ÿ“„ **Full text:** [[Full Document Contents/Articles/I Made My AI Agent Fix Its Own Copy-Paste.md|I Made My AI Agent Fix Its Own Copy-Paste by YouTube]] ## Highlights - that. If the duplication comes back at 13.44% against a threshold of five, the process exits with a non-zero status was exa which is exactly what an agent or a CI pipeline needs to know that something went wrong. To make sure you're using the same setting for each run, you can create ajcpd.json in your project route. So all those settings can live in one place. The reporter options controls the output. Console prints the table you saw. HTML writes a browsable report you can click through. And JSON gives you a machine ([View Highlight](https://read.readwise.io/read/01m02x0qyh1pp5w782vkjzsc2z)) - Note: Threshold flag converts a duplication report into a build gate. - Tags: atom/literature/h2 - and Terraform. Let our automation free you to focus on your core business without losing control over your infrastructure. Get started at displace.te and discover how the right tools can eliminate the need for a full DevOps team. So JavaScript copypaste detector tells you if your code is repeated, but it says nothing about whether the code is right. That's why we reach for MGO. MGO is a static analysis tool chain for PHP written in Rust, which makes it fast enough to run on every single edit. I covered it in depth in a separate video, so here's a short ([View Highlight](https://read.readwise.io/read/01m02x0ya8yxkyrnc9ja8zbs62)) - Note: Duplication detection and static analysis catch independent failure modes. - Tags: atom/literature/h3 - you have to look at the code. For clawed code, Claude adds the following section to the clawed settings.json file. None of this works if the tools are slow. A check that takes 2 minutes is a check that you'll run once a day, if that, and by then the agent has buried your problem under another 3,000 lines. JavaScript copy paste detector and mgo scan in seconds because they before you notice they've even started. You can run them on every iteration and running them on every iteration is what keeps the AI on track. That all being said, there are a few things to keep in mind. JavaScript ([View Highlight](https://read.readwise.io/read/01m02x0jke2vbdysav2xahbcy6)) - Note: Core mechanism claim: check speed determines whether agents actually self-correct. - Tags: atom/literature/h1, aphorisms - that reports duplication percentage and clone locations. Use the threshold option to fail the build when the duplication gets too high. Extract flag clones into a shared method, trait or service, so fixes happen once. Pair JavaScript copy paste detector with MGO so you can cover duplication and correctness at the same time. A check.sh the agent runs after every edit turns both tools into an immediate feedback. So I have to ask, what's the most absurd pile of duplicate code an agent has ever handed you? Drop your war stories in the ([View Highlight](https://read.readwise.io/read/01m02x139yn4ste5zcc0qt6zqz)) - Note: Recap: the two-tool pairing pattern condensed into the video's own summary language. - Tags: atom/literature/h1