[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M759SSHDPF2MCHZZSAVDC1D4":3,"skill-same:01M759SSHDPF2MCHZZSAVDC1D4":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":32,"ownerDescription":33,"updatedAt":34,"install":35,"resources":48},"01M759SSHDPF2MCHZZSAVDC1D4","debugging",null,"Use when encountering any bug, test failure, solver issue, or unexpected behavior, before proposing fixes","harmoniqs\u002Famicode","harmoniqs","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F199011497?v=4","01M759PQCJ9Y093EC5HC3344DW","Harmoniqs","01M759PQD5S85W68FZKV3XD1X0",7,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Fskills\u002Fdebugging\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: debugging\ndescription: Use when encountering any bug, test failure, solver issue, or unexpected behavior, before proposing fixes\nagents: []\nsurface: public\n---\n\n# Systematic Debugging\n\n## Overview\n\nRandom fixes waste time and create new bugs. Quick patches mask underlying issues.\n\n**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.\n\n**Violating the letter of this process is violating the spirit of debugging.**\n\n## The Iron Law\n\n```\nNO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST\n```\n\nIf you haven't completed Phase 1, you cannot propose fixes.\n\n## When to Use\n\nUse for ANY technical issue:\n- Test failures\n- Bugs in production\n- Unexpected behavior\n- Performance problems\n- Build failures\n- Integration issues\n\n**Solver and optimizer issues:**\n- Stagnation: cost not decreasing over iterations, optimizer stuck at local minimum\n- Constraint violation: dynamics constraints not satisfied, trajectory drifting\n- Integrator divergence: NaN\u002FInf appearing in trajectories, timestep too large\n- Infeasibility: optimizer reports problem infeasible, conflicting constraints\n\n**Use this ESPECIALLY when:**\n- Under time pressure (emergencies make guessing tempting)\n- \"Just one quick fix\" seems obvious\n- You've already tried multiple fixes\n- Previous fix didn't work\n- You don't fully understand the issue\n\n**Don't skip when:**\n- Issue seems simple (simple bugs have root causes too)\n- You're in a hurry (rushing guarantees rework)\n- Manager wants it fixed NOW (systematic is faster than thrashing)\n\n## Quantum-Specific Sanity Checks\n\nBefore diving into debugging quantum optimal control code, verify these fundamentals:\n\n1. **Hamiltonian Hermiticity** - Is $H = H^\\dagger$? Non-Hermitian generators produce non-unitary propagators.\n2. **Control bounds** - Are controls within physically realizable bounds? Check `a_bounds` in the trajectory.\n3. **Time grid resolution** - Is $\\Delta t$ small enough for the dynamics? If $\\|H\\| \\cdot \\Delta t \\gg 1$, the integrator may diverge.\n4. **Operator dimensions** - Are all operators, states, and trajectories dimensionally consistent? Mismatched Hilbert space dimensions cause silent errors.\n5. **Basis ordering** - Is the computational basis consistent between the Hamiltonian, initial state, and target gate?\n6. **Embedded operator subspace** - For `EmbeddedOperator`, is the computational subspace correctly specified?\n\n## Solver Diagnosis Patterns\n\n### Stagnation (cost plateau)\n- **Symptoms:** Cost decreases initially then flatlines; optimizer runs to max iterations without convergence.\n- **Common causes:** Poor initial guess, insufficient control authority, local minimum, objective landscape too flat.\n- **Investigation:** Plot cost vs iteration. Check gradient norms (near-zero = stuck). Try different initial trajectories. Verify objective is correctly formulated.\n\n### Constraint Violation (dynamics drift)\n- **Symptoms:** `dynamics` constraint violation remains large; trajectory does not satisfy equations of motion.\n- **Common causes:** Integrator mismatch (BilinearIntegrator vs SplineIntegrator), timestep too large, incorrect Hamiltonian coupling structure.\n- **Investigation:** Check constraint violation magnitude at each timestep. Verify the integrator matches the control parameterization. Use `duration(pulse)` not `sum(get_timesteps)` for duration checks.\n\n### Integrator Divergence (NaN\u002FInf)\n- **Symptoms:** NaN or Inf values appear in state or control trajectories mid-solve.\n- **Common causes:** Timestep too large for operator norms, stiff dynamics, numerical overflow in matrix exponential.\n- **Investigation:** Reduce $\\Delta t$. Check $\\|H\\| \\cdot \\Delta t$. Examine which timestep first produces NaN. Verify no division by zero in custom objectives.\n\n### The Vacuous Solve (silent control-drop) — 2026-10, measured\n- **Symptoms:** The solver consumes thousands of iterations, the variables MOVE (extracted\n  knots differ from the seed), but the internal objective\u002Ffidelity is **bit-identical to the\n  seed value across every option, setting, and formulation change** (max_iter, mu_strategy,\n  member count). Post-solve quality is entirely explained by regularizer drift.\n- **Common causes:** The problem's dynamics integrator never received the controls — template\n  integrator auto-resolution silently resolving to a control-free path (Piccolo 2.2.0\n  measured: `SplineIntegrator` auto-wiring left the objective constant); or reading a STALE\n  `fidelity(qtraj)` (the construction-time ODE solution) that masks movement in the other\n  direction.\n- **Investigation:** Evaluate the objective at the SEED and assert the post-solve value has\n  MOVED (a descent method cannot end where it started, bit-identical). Pass integrators\n  explicitly. Verify extracted solutions through independent scorers, never the problem's\n  internal readouts. Provenance: harmoniqs\u002Fdiraq-esr-realism 2026-10-23 overnight §4.\n\n### The Silent Edit (no-op transformations) — six measured instances\n- **Symptoms:** An edit reports success but behavior never changes; archaeology shows the\n  pattern never matched (trailing comma, already-replaced form, reverted block). Worst case:\n  stacked no-ops make the file's edit history untrustworthy and force a clean rewrite.\n- **Common causes:** `str.replace`\u002F`sed` succeed on no-match by design; kwargs that miss\n  their consumer get swallowed; later edits revert earlier ones through shared patterns;\n  LLM memory of what landed is not evidence.\n- **Investigation\u002FPrevention:** Every programmatic edit ASSERTS its pattern matched\n  (`assert old in s`) and the critical line is grep-verified after the write; multi-edit\n  confusion resolves by rewriting clean with git as arbiter; numbers are never hand-copied\n  between files when a formula can be evaluated (machine-pinned literals, rtol ≤ 1e-9).\n  Provenance: six instances in harmoniqs\u002Fdiraq-esr-realism loops 4–10.\n\n### The Silent OOM (death right after initialization)\n- **Symptoms:** A process dies immediately after \"optimizer initialization complete\" with no\n  error in any log — the OOM killer SIGKILLs without a traceback.\n- **Common causes:** Dense interior-point Hessians over unitary trajectories scale as\n  (2·d²·N)² — a 36-dim member block at N=21 needs ~25 GB. Member counts are memory decisions.\n- **Investigation:** Compute the Hessian memory before launching; prefer small-d blocks.\n  Check `dmesg`\u002Fjournalctl for oom-kill records where readable.\n\n### Background process death at harness boundaries\n- **Symptoms:** `nohup … &` jobs are gone by the next interaction; logs end mid-init.\n- **Cause:** Sandboxed tool environments reap the process group when the call returns.\n- **Fix:** `setsid nohup … &` detaches the session (measured both ways, 2026-10-23).\n\n### Infeasibility (conflicting constraints)\n- **Symptoms:** Solver reports \"infeasible\" or \"locally infeasible\"; no solution found.\n- **Common causes:** Control bounds too tight for the target gate, conflicting time and fidelity constraints, target gate unreachable in given time.\n- **Investigation:** Relax bounds and re-solve to identify which constraint is binding. Check if the target is achievable with unconstrained controls. Verify gate time is sufficient.\n\n## The Four Phases\n\nYou MUST complete each phase before proceeding to the next.\n\n### Phase 1: Root Cause Investigation\n\n**BEFORE attempting ANY fix:**\n\n1. **Read Error Messages Carefully**\n   - Don't skip past errors or warnings\n   - They often contain the exact solution\n   - Read stack traces completely\n   - Note line numbers, file paths, error codes\n\n2. **Reproduce Consistently**\n   - Can you trigger it reliably?\n   - What are the exact steps?\n   - Does it happen every time?\n   - If not reproducible, gather more data, don't guess\n\n3. **Check Recent Changes**\n   - What changed that could cause this?\n   - Git diff, recent commits\n   - New dependencies, config changes\n   - Environmental differences\n\n4. **Gather Evidence in Multi-Component Systems**\n\n   **WHEN system has multiple components (optimizer, integrator, objective, constraints):**\n\n   **BEFORE proposing fixes, add diagnostic instrumentation:**\n   ```\n   For EACH component boundary:\n     - Log what data enters component\n     - Log what data exits component\n     - Verify environment\u002Fconfig propagation\n     - Check state at each layer\n\n   Run once to gather evidence showing WHERE it breaks\n   THEN analyze evidence to identify failing component\n   THEN investigate that specific component\n   ```\n\n   **Example (quantum control pipeline):**\n   ```julia\n   # Layer 1: Problem setup\n   println(\"=== Hamiltonian dimensions: $(size(H_drift)) ===\")\n   println(\"=== Number of controls: $(length(a_labels)) ===\")\n\n   # Layer 2: Trajectory\n   println(\"=== Trajectory timesteps: $(length(times)) ===\")\n   println(\"=== Control bounds: $(a_bounds) ===\")\n\n   # Layer 3: Integrator\n   println(\"=== Integrator type: $(typeof(integrator)) ===\")\n   println(\"=== Max ||H||*dt: $(maximum(norms .* dts)) ===\")\n\n   # Layer 4: Optimizer output\n   println(\"=== Final cost: $(result.objective) ===\")\n   println(\"=== Constraint violation: $(result.constraint_violation) ===\")\n   ```\n\n   **This reveals:** Which layer fails (setup OK, integrator OK, optimizer diverges)\n\n5. **Trace Data Flow**\n\n   **WHEN error is deep in call stack:**\n\n   See `root-cause-tracing.md` in this directory for the complete backward tracing technique.\n\n   **Quick version:**\n   - Where does bad value originate?\n   - What called this with bad value?\n   - Keep tracing up until you find the source\n   - Fix at source, not at symptom\n\n### Phase 2: Pattern Analysis\n\n**Find the pattern before fixing:**\n\n1. **Find Working Examples**\n   - Locate similar working code in same codebase\n   - What works that's similar to what's broken?\n\n2. **Compare Against References**\n   - If implementing pattern, read reference implementation COMPLETELY\n   - Don't skim - read every line\n   - Understand the pattern fully before applying\n\n3. **Identify Differences**\n   - What's different between working and broken?\n   - List every difference, however small\n   - Don't assume \"that can't matter\"\n\n4. **Understand Dependencies**\n   - What other components does this need?\n   - What settings, config, environment?\n   - What assumptions does it make?\n\n### Phase 3: Hypothesis and Testing\n\n**Scientific method:**\n\n1. **Form Single Hypothesis**\n   - State clearly: \"I think X is the root cause because Y\"\n   - Write it down\n   - Be specific, not vague\n\n2. **Test Minimally**\n   - Make the SMALLEST possible change to test hypothesis\n   - One variable at a time\n   - Don't fix multiple things at once\n\n3. **Verify Before Continuing**\n   - Did it work? Yes, proceed to Phase 4\n   - Didn't work? Form NEW hypothesis\n   - DON'T add more fixes on top\n\n4. **When You Don't Know**\n   - Say \"I don't understand X\"\n   - Don't pretend to know\n   - Ask for help\n   - Research more\n\n### Phase 4: Implementation\n\n**Fix the root cause, not the symptom:**\n\n1. **Create Failing Test Case**\n   - Simplest possible reproduction\n   - Automated test if possible\n   - One-off test script if no framework\n   - MUST have before fixing\n   - Use the `tdd` skill for writing proper failing tests\n\n2. **Implement Single Fix**\n   - Address the root cause identified\n   - ONE change at a time\n   - No \"while I'm here\" improvements\n   - No bundled refactoring\n\n3. **Verify Fix**\n   - Test passes now?\n   - No other tests broken?\n   - Issue actually resolved?\n\n4. **If Fix Doesn't Work**\n   - STOP\n   - Count: How many fixes have you tried?\n   - If \u003C 3: Return to Phase 1, re-analyze with new information\n   - **If >= 3: STOP and question the architecture (step 5 below)**\n   - DON'T attempt Fix #4 without architectural discussion\n\n5. **If 3+ Fixes Failed: Question Architecture**\n\n   **Pattern indicating architectural problem:**\n   - Each fix reveals new shared state\u002Fcoupling\u002Fproblem in different place\n   - Fixes require \"massive refactoring\" to implement\n   - Each fix creates new symptoms elsewhere\n\n   **STOP and question fundamentals:**\n   - Is this pattern fundamentally sound?\n   - Are we \"sticking with it through sheer inertia\"?\n   - Should we refactor architecture vs. continue fixing symptoms?\n\n   **Discuss with your human partner before attempting more fixes**\n\n   This is NOT a failed hypothesis - this is a wrong architecture.\n\n## Red Flags - STOP and Follow Process\n\nIf you catch yourself thinking:\n- \"Quick fix for now, investigate later\"\n- \"Just try changing X and see if it works\"\n- \"Add multiple changes, run tests\"\n- \"Skip the test, I'll manually verify\"\n- \"It's probably X, let me fix that\"\n- \"I don't fully understand but this might work\"\n- \"Pattern says X but I'll adapt it differently\"\n- \"Here are the main problems: [lists fixes without investigation]\"\n- Proposing solutions before tracing data flow\n- **\"One more fix attempt\" (when already tried 2+)**\n- **Each fix reveals new problem in different place**\n\n**ALL of these mean: STOP. Return to Phase 1.**\n\n**If 3+ fixes failed:** Question the architecture (see Phase 4, step 5)\n\n## Your Human Partner's Signals You're Doing It Wrong\n\n**Watch for these redirections:**\n- \"Is that not happening?\" - You assumed without verifying\n- \"Will it show us...?\" - You should have added evidence gathering\n- \"Stop guessing\" - You're proposing fixes without understanding\n- \"Ultrathink this\" - Question fundamentals, not just symptoms\n- \"We're stuck?\" (frustrated) - Your approach isn't working\n\n**When you see these:** STOP. Return to Phase 1.\n\n## Common Rationalizations\n\n| Excuse | Reality |\n|--------|---------|\n| \"Issue is simple, don't need process\" | Simple issues have root causes too. Process is fast for simple bugs. |\n| \"Emergency, no time for process\" | Systematic debugging is FASTER than guess-and-check thrashing. |\n| \"Just try this first, then investigate\" | First fix sets the pattern. Do it right from the start. |\n| \"I'll write test after confirming fix works\" | Untested fixes don't stick. Test first proves it. |\n| \"Multiple fixes at once saves time\" | Can't isolate what worked. Causes new bugs. |\n| \"Reference too long, I'll adapt the pattern\" | Partial understanding guarantees bugs. Read it completely. |\n| \"I see the problem, let me fix it\" | Seeing symptoms != understanding root cause. |\n| \"One more fix attempt\" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |\n\n## Quick Reference\n\n| Phase | Key Activities | Success Criteria |\n|-------|---------------|------------------|\n| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |\n| **2. Pattern** | Find working examples, compare | Identify differences |\n| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |\n| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |\n\n## When Process Reveals \"No Root Cause\"\n\nIf systematic investigation reveals issue is truly environmental, timing-dependent, or external:\n\n1. You've completed the process\n2. Document what you investigated\n3. Implement appropriate handling (retry, timeout, error message)\n4. Add monitoring\u002Flogging for future investigation\n\n**But:** 95% of \"no root cause\" cases are incomplete investigation.\n\n## Supporting Techniques\n\nThese techniques are part of systematic debugging and available in this directory:\n\n- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger\n- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause\n\n**Related skills:**\n- **tdd** - For creating failing test case (Phase 4, Step 1)\n- **test** - For running Julia package tests to verify fixes\n\n## Real-World Impact\n\nFrom debugging sessions:\n- Systematic approach: 15-30 minutes to fix\n- Random fixes approach: 2-3 hours of thrashing\n- First-time fix rate: 95% vs 40%\n- New bugs introduced: Near zero vs common\n","# Systematic Debugging\n\n## Overview\n\nRandom fixes waste time and create new bugs. Quick patches mask underlying issues.\n\n**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.\n\n**Violating the letter of this process is violating the spirit of debugging.**\n\n## The Iron Law\n\n```\nNO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST\n```\n\nIf you haven't completed Phase 1, you cannot propose fixes.\n\n## When to Use\n\nUse for ANY technical issue:\n- Test failures\n- Bugs in production\n- Unexpected behavior\n- Performance problems\n- Build failures\n- Integration issues\n\n**Solver and optimizer issues:**\n- Stagnation: cost not decreasing over iterations, optimizer stuck at local minimum\n- Constraint violation: dynamics constraints not satisfied, trajectory drifting\n- Integrator divergence: NaN\u002FInf appearing in trajectories, timestep too large\n- Infeasibility: optimizer reports problem infeasible, conflicting constraints\n\n**Use this ESPECIALLY when:**\n- Under time pressure (emergencies make guessing tempting)\n- \"Just one quick fix\" seems obvious\n- You've already tried multiple fixes\n- Previous fix didn't work\n- You don't fully understand the issue\n\n**Don't skip when:**\n- Issue seems simple (simple bugs have root causes too)\n- You're in a hurry (rushing guarantees rework)\n- Manager wants it fixed NOW (systematic is faster than thrashing)\n\n## Quantum-Specific Sanity Checks\n\nBefore diving into debugging quantum optimal control code, verify these fundamentals:\n\n1. **Hamiltonian Hermiticity** - Is $H = H^\\dagger$? Non-Hermitian generators produce non-unitary propagators.\n2. **Control bounds** - Are controls within physically realizable bounds? Check `a_bounds` in the trajectory.\n3. **Time grid resolution** - Is $\\Delta t$ small enough for the dynamics? If $\\|H\\| \\cdot \\Delta t \\gg 1$, the integrator may diverge.\n4. **Operator dimensions** - Are all operators, states, and trajectories dimensionally consistent? Mismatched Hilbert space dimensions cause silent errors.\n5. **Basis ordering** - Is the computational basis consistent between the Hamiltonian, initial state, and target gate?\n6. **Embedded operator subspace** - For `EmbeddedOperator`, is the computational subspace correctly specified?\n\n## Solver Diagnosis Patterns\n\n### Stagnation (cost plateau)\n- **Symptoms:** Cost decreases initially then flatlines; optimizer runs to max iterations without convergence.\n- **Common causes:** Poor initial guess, insufficient control authority, local minimum, objective landscape too flat.\n- **Investigation:** Plot cost vs iteration. Check gradient norms (near-zero = stuck). Try different initial trajectories. Verify objective is correctly formulated.\n\n### Constraint Violation (dynamics drift)\n- **Symptoms:** `dynamics` constraint violation remains large; trajectory does not satisfy equations of motion.\n- **Common causes:** Integrator mismatch (BilinearIntegrator vs SplineIntegrator), timestep too large, incorrect Hamiltonian coupling structure.\n- **Investigation:** Check constraint violation magnitude at each timestep. Verify the integrator matches the control parameterization. Use `duration(pulse)` not `sum(get_timesteps)` for duration checks.\n\n### Integrator Divergence (NaN\u002FInf)\n- **Symptoms:** NaN or Inf values appear in state or control trajectories mid-solve.\n- **Common causes:** Timestep too large for operator norms, stiff dynamics, numerical overflow in matrix exponential.\n- **Investigation:** Reduce $\\Delta t$. Check $\\|H\\| \\cdot \\Delta t$. Examine which timestep first produces NaN. Verify no division by zero in custom objectives.\n\n### The Vacuous Solve (silent control-drop) — 2026-10, measured\n- **Symptoms:** The solver consumes thousands of iterations, the variables MOVE (extracted\n  knots differ from the seed), but the internal objective\u002Ffidelity is **bit-identical to the\n  seed value across every option, setting, and formulation change** (max_iter, mu_strategy,\n  member count). Post-solve quality is entirely explained by regularizer drift.\n- **Common causes:** The problem's dynamics integrator never received the controls — template\n  integrator auto-resolution silently resolving to a control-free path (Piccolo 2.2.0\n  measured: `SplineIntegrator` auto-wiring left the objective constant); or reading a STALE\n  `fidelity(qtraj)` (the construction-time ODE solution) that masks movement in the other\n  direction.\n- **Investigation:** Evaluate the objective at the SEED and assert the post-solve value has\n  MOVED (a descent method cannot end where it started, bit-identical). Pass integrators\n  explicitly. Verify extracted solutions through independent scorers, never the problem's\n  internal readouts. Provenance: harmoniqs\u002Fdiraq-esr-realism 2026-10-23 overnight §4.\n\n### The Silent Edit (no-op transformations) — six measured instances\n- **Symptoms:** An edit reports success but behavior never changes; archaeology shows the\n  pattern never matched (trailing comma, already-replaced form, reverted block). Worst case:\n  stacked no-ops make the file's edit history untrustworthy and force a clean rewrite.\n- **Common causes:** `str.replace`\u002F`sed` succeed on no-match by design; kwargs that miss\n  their consumer get swallowed; later edits revert earlier ones through shared patterns;\n  LLM memory of what landed is not evidence.\n- **Investigation\u002FPrevention:** Every programmatic edit ASSERTS its pattern matched\n  (`assert old in s`) and the critical line is grep-verified after the write; multi-edit\n  confusion resolves by rewriting clean with git as arbiter; numbers are never hand-copied\n  between files when a formula can be evaluated (machine-pinned literals, rtol ≤ 1e-9).\n  Provenance: six instances in harmoniqs\u002Fdiraq-esr-realism loops 4–10.\n\n### The Silent OOM (death right after initialization)\n- **Symptoms:** A process dies immediately after \"optimizer initialization complete\" with no\n  error in any log — the OOM killer SIGKILLs without a traceback.\n- **Common causes:** Dense interior-point Hessians over unitary trajectories scale as\n  (2·d²·N)² — a 36-dim member block at N=21 needs ~25 GB. Member counts are memory decisions.\n- **Investigation:** Compute the Hessian memory before launching; prefer small-d blocks.\n  Check `dmesg`\u002Fjournalctl for oom-kill records where readable.\n\n### Background process death at harness boundaries\n- **Symptoms:** `nohup … &` jobs are gone by the next interaction; logs end mid-init.\n- **Cause:** Sandboxed tool environments reap the process group when the call returns.\n- **Fix:** `setsid nohup … &` detaches the session (measured both ways, 2026-10-23).\n\n### Infeasibility (conflicting constraints)\n- **Symptoms:** Solver reports \"infeasible\" or \"locally infeasible\"; no solution found.\n- **Common causes:** Control bounds too tight for the target gate, conflicting time and fidelity constraints, target gate unreachable in given time.\n- **Investigation:** Relax bounds and re-solve to identify which constraint is binding. Check if the target is achievable with unconstrained controls. Verify gate time is sufficient.\n\n## The Four Phases\n\nYou MUST complete each phase before proceeding to the next.\n\n### Phase 1: Root Cause Investigation\n\n**BEFORE attempting ANY fix:**\n\n1. **Read Error Messages Carefully**\n   - Don't skip past errors or warnings\n   - They often contain the exact solution\n   - Read stack traces completely\n   - Note line numbers, file paths, error codes\n\n2. **Reproduce Consistently**\n   - Can you trigger it reliably?\n   - What are the exact steps?\n   - Does it happen every time?\n   - If not reproducible, gather more data, don't guess\n\n3. **Check Recent Changes**\n   - What changed that could cause this?\n   - Git diff, recent commits\n   - New dependencies, config changes\n   - Environmental differences\n\n4. **Gather Evidence in Multi-Component Systems**\n\n   **WHEN system has multiple components (optimizer, integrator, objective, constraints):**\n\n   **BEFORE proposing fixes, add diagnostic instrumentation:**\n   ```\n   For EACH component boundary:\n     - Log what data enters component\n     - Log what data exits component\n     - Verify environment\u002Fconfig propagation\n     - Check state at each layer\n\n   Run once to gather evidence showing WHERE it breaks\n   THEN analyze evidence to identify failing component\n   THEN investigate that specific component\n   ```\n\n   **Example (quantum control pipeline):**\n   ```julia\n   # Layer 1: Problem setup\n   println(\"=== Hamiltonian dimensions: $(size(H_drift)) ===\")\n   println(\"=== Number of controls: $(length(a_labels)) ===\")\n\n   # Layer 2: Trajectory\n   println(\"=== Trajectory timesteps: $(length(times)) ===\")\n   println(\"=== Control bounds: $(a_bounds) ===\")\n\n   # Layer 3: Integrator\n   println(\"=== Integrator type: $(typeof(integrator)) ===\")\n   println(\"=== Max ||H||*dt: $(maximum(norms .* dts)) ===\")\n\n   # Layer 4: Optimizer output\n   println(\"=== Final cost: $(result.objective) ===\")\n   println(\"=== Constraint violation: $(result.constraint_violation) ===\")\n   ```\n\n   **This reveals:** Which layer fails (setup OK, integrator OK, optimizer diverges)\n\n5. **Trace Data Flow**\n\n   **WHEN error is deep in call stack:**\n\n   See `root-cause-tracing.md` in this directory for the complete backward tracing technique.\n\n   **Quick version:**\n   - Where does bad value originate?\n   - What called this with bad value?\n   - Keep tracing up until you find the source\n   - Fix at source, not at symptom\n\n### Phase 2: Pattern Analysis\n\n**Find the pattern before fixing:**\n\n1. **Find Working Examples**\n   - Locate similar working code in same codebase\n   - What works that's similar to what's broken?\n\n2. **Compare Against References**\n   - If implementing pattern, read reference implementation COMPLETELY\n   - Don't skim - read every line\n   - Understand the pattern fully before applying\n\n3. **Identify Differences**\n   - What's different between working and broken?\n   - List every difference, however small\n   - Don't assume \"that can't matter\"\n\n4. **Understand Dependencies**\n   - What other components does this need?\n   - What settings, config, environment?\n   - What assumptions does it make?\n\n### Phase 3: Hypothesis and Testing\n\n**Scientific method:**\n\n1. **Form Single Hypothesis**\n   - State clearly: \"I think X is the root cause because Y\"\n   - Write it down\n   - Be specific, not vague\n\n2. **Test Minimally**\n   - Make the SMALLEST possible change to test hypothesis\n   - One variable at a time\n   - Don't fix multiple things at once\n\n3. **Verify Before Continuing**\n   - Did it work? Yes, proceed to Phase 4\n   - Didn't work? Form NEW hypothesis\n   - DON'T add more fixes on top\n\n4. **When You Don't Know**\n   - Say \"I don't understand X\"\n   - Don't pretend to know\n   - Ask for help\n   - Research more\n\n### Phase 4: Implementation\n\n**Fix the root cause, not the symptom:**\n\n1. **Create Failing Test Case**\n   - Simplest possible reproduction\n   - Automated test if possible\n   - One-off test script if no framework\n   - MUST have before fixing\n   - Use the `tdd` skill for writing proper failing tests\n\n2. **Implement Single Fix**\n   - Address the root cause identified\n   - ONE change at a time\n   - No \"while I'm here\" improvements\n   - No bundled refactoring\n\n3. **Verify Fix**\n   - Test passes now?\n   - No other tests broken?\n   - Issue actually resolved?\n\n4. **If Fix Doesn't Work**\n   - STOP\n   - Count: How many fixes have you tried?\n   - If \u003C 3: Return to Phase 1, re-analyze with new information\n   - **If >= 3: STOP and question the architecture (step 5 below)**\n   - DON'T attempt Fix #4 without architectural discussion\n\n5. **If 3+ Fixes Failed: Question Architecture**\n\n   **Pattern indicating architectural problem:**\n   - Each fix reveals new shared state\u002Fcoupling\u002Fproblem in different place\n   - Fixes require \"massive refactoring\" to implement\n   - Each fix creates new symptoms elsewhere\n\n   **STOP and question fundamentals:**\n   - Is this pattern fundamentally sound?\n   - Are we \"sticking with it through sheer inertia\"?\n   - Should we refactor architecture vs. continue fixing symptoms?\n\n   **Discuss with your human partner before attempting more fixes**\n\n   This is NOT a failed hypothesis - this is a wrong architecture.\n\n## Red Flags - STOP and Follow Process\n\nIf you catch yourself thinking:\n- \"Quick fix for now, investigate later\"\n- \"Just try changing X and see if it works\"\n- \"Add multiple changes, run tests\"\n- \"Skip the test, I'll manually verify\"\n- \"It's probably X, let me fix that\"\n- \"I don't fully understand but this might work\"\n- \"Pattern says X but I'll adapt it differently\"\n- \"Here are the main problems: [lists fixes without investigation]\"\n- Proposing solutions before tracing data flow\n- **\"One more fix attempt\" (when already tried 2+)**\n- **Each fix reveals new problem in different place**\n\n**ALL of these mean: STOP. Return to Phase 1.**\n\n**If 3+ fixes failed:** Question the architecture (see Phase 4, step 5)\n\n## Your Human Partner's Signals You're Doing It Wrong\n\n**Watch for these redirections:**\n- \"Is that not happening?\" - You assumed without verifying\n- \"Will it show us...?\" - You should have added evidence gathering\n- \"Stop guessing\" - You're proposing fixes without understanding\n- \"Ultrathink this\" - Question fundamentals, not just symptoms\n- \"We're stuck?\" (frustrated) - Your approach isn't working\n\n**When you see these:** STOP. Return to Phase 1.\n\n## Common Rationalizations\n\n| Excuse | Reality |\n|--------|---------|\n| \"Issue is simple, don't need process\" | Simple issues have root causes too. Process is fast for simple bugs. |\n| \"Emergency, no time for process\" | Systematic debugging is FASTER than guess-and-check thrashing. |\n| \"Just try this first, then investigate\" | First fix sets the pattern. Do it right from the start. |\n| \"I'll write test after confirming fix works\" | Untested fixes don't stick. Test first proves it. |\n| \"Multiple fixes at once saves time\" | Can't isolate what worked. Causes new bugs. |\n| \"Reference too long, I'll adapt the pattern\" | Partial understanding guarantees bugs. Read it completely. |\n| \"I see the problem, let me fix it\" | Seeing symptoms != understanding root cause. |\n| \"One more fix attempt\" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |\n\n## Quick Reference\n\n| Phase | Key Activities | Success Criteria |\n|-------|---------------|------------------|\n| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |\n| **2. Pattern** | Find working examples, compare | Identify differences |\n| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |\n| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |\n\n## When Process Reveals \"No Root Cause\"\n\nIf systematic investigation reveals issue is truly environmental, timing-dependent, or external:\n\n1. You've completed the process\n2. Document what you investigated\n3. Implement appropriate handling (retry, timeout, error message)\n4. Add monitoring\u002Flogging for future investigation\n\n**But:** 95% of \"no root cause\" cases are incomplete investigation.\n\n## Supporting Techniques\n\nThese techniques are part of systematic debugging and available in this directory:\n\n- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger\n- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause\n\n**Related skills:**\n- **tdd** - For creating failing test case (Phase 4, Step 1)\n- **test** - For running Julia package tests to verify fixes\n\n## Real-World Impact\n\nFrom debugging sessions:\n- Systematic approach: 15-30 minutes to fix\n- Random fixes approach: 2-3 hours of thrashing\n- First-time fix rate: 95% vs 40%\n- New bugs introduced: Near zero vs common\n",{"name":5,"agents":24,"surface":25,"description":7},[],"public","main","bf84fdd4c1494800695bd5881702b3118dbf98be","packages\u002Fextension\u002Fskills\u002Fdebugging",2,"https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode","https:\u002F\u002Fgithub.com\u002Fharmoniqs","harmoniqs.ai","research tools, for researchers, by reseachers","2026-11-12 14:46:24",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add harmoniqs\u002Famicode --skill debugging",{"tool":41,"command":42},"bunx","bunx skills add harmoniqs\u002Famicode --skill debugging",{"tool":44,"command":45},"pnpm","pnpm dlx skills add harmoniqs\u002Famicode --skill debugging","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Fskills\u002Fdebugging\u002FSKILL.md",true,[49,55],{"path":50,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":53,"sourceHtmlUrl":54},"defense-in-depth.md","REFERENCE","参考文档",3649,"https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Fskills\u002Fdebugging\u002Fdefense-in-depth.md",{"path":56,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":57,"sourceHtmlUrl":58},"root-cause-tracing.md",5314,"https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Fskills\u002Fdebugging\u002Froot-cause-tracing.md",[60,67,74,80,87,94],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M759XGHEQRJ1GWZTPRFF9Z1W","malformed","Frontmatter that parses as YAML but is missing the required name field.","https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Ftest\u002Ffixtures\u002Fskill-drift\u002Fskills\u002Fmalformed\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M759XDVQ1PYPMT876X8J21TQ","duplicated","Second skill carrying the duplicated frontmatter name.","https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Ftest\u002Ffixtures\u002Fskill-drift\u002Fskills\u002Fdup-two\u002FSKILL.md",[],[],{"skillNo":75,"name":69,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M759XBZYBHF38JDWSRHAC6E1","First skill carrying the duplicated frontmatter name.","https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Ftest\u002Ffixtures\u002Fskill-drift\u002Fskills\u002Fdup-one\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M759XAQBSP29BKTTXR1WF2D7","drifted","A skill whose API claims have drifted from the fixture packages.","https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Ftest\u002Ffixtures\u002Fskill-drift\u002Fskills\u002Fdrifted\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M759X8CNBPVK98C6M45D0QMB","clean","A clean skill whose every extracted claim resolves against the fixture packages.","https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Ftest\u002Ffixtures\u002Fskill-drift\u002Fskills\u002Fclean\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M759X73H6N2G0VDH8CJ5TF11","broken-paths","A skill with a broken relative link and a broken cited package path.","https:\u002F\u002Fgithub.com\u002Fharmoniqs\u002Famicode\u002Fblob\u002Fmain\u002Fpackages\u002Fextension\u002Ftest\u002Ffixtures\u002Fskill-drift\u002Fskills\u002Fbroken-paths\u002FSKILL.md",[],[]]