diff --git a/.agents/skills/README.md b/.agents/skills/README.md new file mode 100644 index 0000000..d339f94 --- /dev/null +++ b/.agents/skills/README.md @@ -0,0 +1,17 @@ +# Skills + +Reusable project skills for the FastAPI/Python AI service. + +- `api-design`: FastAPI route and schema design. +- `database-schema`: Postgres schema guidance. +- `docker`: Docker and Compose guidance. +- `fastapi-python-arch`: Python/FastAPI architecture guidance. +- `git-commit`: Logical local commits. +- `migration-guide`: Alembic/schema migration guidance. +- `planning`: Structured planning interview. +- `pytest-guide`: Python test patterns. +- `resolve-reviews`: GitHub PR review handling. +- `security-checklist`: Security review checklist. +- `systematic-debugging`: Root-cause debugging workflow. +- `test`: Smallest useful test/check selection. +- `write-pr`: Push and open PR. diff --git a/.agents/skills/api-design/SKILL.md b/.agents/skills/api-design/SKILL.md new file mode 100644 index 0000000..891538e --- /dev/null +++ b/.agents/skills/api-design/SKILL.md @@ -0,0 +1,23 @@ +--- +name: api-design +description: FastAPI API design guide for routes, request/response schemas, status codes, and error behavior. +--- + +# FastAPI API Design + +Use this when adding or reviewing API endpoints. + +## Rules + +- Keep routes resource-oriented and versionable when a public contract exists. +- Put request/response shapes in Pydantic models when they are reused or non-trivial. +- Return explicit status codes for create/delete/error paths. +- Keep external AI/provider calls behind a service function, not inside route handlers. +- Do not change an API contract without updating matching docs or examples if they exist. + +## Checks + +```bash +python -m py_compile main.py +python -c "from main import app; assert app" +``` diff --git a/.agents/skills/database-schema/SKILL.md b/.agents/skills/database-schema/SKILL.md new file mode 100644 index 0000000..7494902 --- /dev/null +++ b/.agents/skills/database-schema/SKILL.md @@ -0,0 +1,18 @@ +--- +name: database-schema +description: Postgres schema guidance for this Python service. Use only when DB tables or persistence are actually being added. +--- + +# Database Schema Guide + +This repo currently has no application DB layer. Do not add schema tooling until a real persistence requirement exists. + +## Defaults When Needed + +- Postgres for local/dev parity. +- Alembic for migrations if SQLAlchemy is introduced. +- `snake_case` table and column names. +- `created_at` and `updated_at` timestamps on durable domain tables. +- Explicit indexes for frequent lookup predicates only. + +Keep schema changes in the same PR as the code that uses them. diff --git a/.agents/skills/docker/SKILL.md b/.agents/skills/docker/SKILL.md new file mode 100644 index 0000000..b0a4be2 --- /dev/null +++ b/.agents/skills/docker/SKILL.md @@ -0,0 +1,19 @@ +--- +name: docker +description: Docker and Docker Compose guide for this FastAPI/Python service. +--- + +# Docker Guide + +Use the existing `compose.yml` before adding new Docker files. + +## Compose + +- Keep app containers out of dev compose unless explicitly requested. +- Prefer official images with pinned tags. +- Add healthchecks for stateful services. +- Use volumes only for data that must persist between restarts. + +## Dockerfile + +Add a Dockerfile only when deployment or app-container local dev needs it. If added, copy dependency manifests before source files for cache efficiency. diff --git a/.agents/skills/fastapi-python-arch/SKILL.md b/.agents/skills/fastapi-python-arch/SKILL.md new file mode 100644 index 0000000..b3892f0 --- /dev/null +++ b/.agents/skills/fastapi-python-arch/SKILL.md @@ -0,0 +1,22 @@ +--- +name: fastapi-python-arch +description: Architecture guide for this Python/FastAPI service. +--- + +# FastAPI + Python Architecture + +Keep the app boring until requirements force structure. + +## Current Shape + +- `main.py` owns the FastAPI app. +- `requirements.txt` pins runtime dependencies. +- `compose.yml` owns local backing services only. + +## When Adding Code + +- Keep route handlers thin. +- Move reusable provider/model/business logic into plain Python modules. +- Use Pydantic models at trust boundaries. +- Do not add packages for small stdlib jobs. +- Add the smallest runnable check for non-trivial logic. diff --git a/.agents/skills/git-commit/SKILL.md b/.agents/skills/git-commit/SKILL.md new file mode 100644 index 0000000..0f219c1 --- /dev/null +++ b/.agents/skills/git-commit/SKILL.md @@ -0,0 +1,59 @@ +--- +name: git-commit +description: Split working tree changes into logical commits following this project's convention (` :: <한글 요약>`), auto-detect Git Flow (warn before committing directly to develop/main), and commit without pushing. +compatibility: Requires git +--- + +## Step 1 — Inspect Changes + +```bash +git status --short +git diff +git diff --staged +``` + +If there are no changes (staged or unstaged), report that and exit. + +## Step 2 — Git Flow Check + +```bash +git branch --show-current +``` + +If the current branch is `main`, `master`, or `develop`, warn the user before committing directly and ask for confirmation. Prefer committing on a feature/fix branch. + +## Step 3 — Group Into Logical Commits + +Read the diff and group changed files by concern (one feature, one fix, one config change, etc.). If the working tree mixes unrelated concerns, split into multiple commits using targeted `git add ` instead of `git add -A`. Do not bundle unrelated changes into a single commit just for convenience. + +## Step 4 — Write Commit Messages + +Format (see `AGENTS.md`): + +``` + :: <한글 요약> +``` + +- `type`: `feat`, `fix`, `refactor`, `chore`, `docs`, `test`, `style`, `perf` 중 하나 +- 요약은 한글로, 무엇을 했는지 간결하게 + +Example: `feat :: JWT 인증 필터 추가`, `fix :: API 키 조회 NPE 수정` + +**어트리뷰션 주의**: 커밋 메시지에 "Co-Authored-By", "Generated by Codex" 같은 트레일러나 서명을 추가하지 않는다. 커밋 작성자는 로컬 `git config user.name`/`user.email`(사용자 본인 계정)을 그대로 따른다 — 별도로 identity를 바꾸지 않는다. + +## Step 5 — Commit + +```bash +git add +git commit -m " :: <한글 요약>" +``` + +여러 그룹이 있으면 그룹마다 반복. **`git push`는 실행하지 않는다** — 푸시는 `write-pr` 스킬 또는 사용자가 직접 수행한다. + +## Step 6 — Report + +생성된 커밋 목록을 보여준다: + +```bash +git log --oneline -n <생성한 커밋 수> +``` \ No newline at end of file diff --git a/.agents/skills/migration-guide/SKILL.md b/.agents/skills/migration-guide/SKILL.md new file mode 100644 index 0000000..13df052 --- /dev/null +++ b/.agents/skills/migration-guide/SKILL.md @@ -0,0 +1,18 @@ +--- +name: migration-guide +description: Migration guide for future DB changes in this Python service. +--- + +# Migration Guide + +Use only after persistence exists. + +## Order + +1. Add or update SQLAlchemy models. +2. Add Alembic migration. +3. Update service/repository code. +4. Add or update tests. +5. Verify upgrade and downgrade when downgrade is supported. + +Do not rely on auto-generated migrations without reading the generated SQL. diff --git a/.agents/skills/planning/SKILL.md b/.agents/skills/planning/SKILL.md new file mode 100644 index 0000000..cbcca73 --- /dev/null +++ b/.agents/skills/planning/SKILL.md @@ -0,0 +1,11 @@ +--- +name: planning +argument-hint: [instructions] +description: Conduct an in-depth structured interview with the user to uncover non-obvious requirements, tradeoffs, and constraints, then produce a detailed implementation spec file. +--- + +Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. After I respond to each question, provide your evaluation and recommended answer. + +Ask the questions one at a time. + +If a question can be answered by exploring the codebase, explore the codebase instead. diff --git a/.agents/skills/pytest-guide/SKILL.md b/.agents/skills/pytest-guide/SKILL.md new file mode 100644 index 0000000..d01e098 --- /dev/null +++ b/.agents/skills/pytest-guide/SKILL.md @@ -0,0 +1,27 @@ +--- +name: pytest-guide +description: Pytest and FastAPI TestClient guidance for this repo. +--- + +# Pytest Guide + +Use pytest only when tests exist or the change needs a real regression check. + +## Patterns + +- Use plain `assert`. +- Use FastAPI `TestClient` for endpoint behavior. +- Keep fixtures local until shared setup is repeated. +- Mock external provider calls at the module boundary. + +## Minimal Example + +```python +from fastapi.testclient import TestClient +from main import app + + +def test_health(): + client = TestClient(app) + assert client.get("/health").json() == {"status": "ok"} +``` diff --git a/.agents/skills/resolve-reviews/SKILL.md b/.agents/skills/resolve-reviews/SKILL.md new file mode 100644 index 0000000..4080c63 --- /dev/null +++ b/.agents/skills/resolve-reviews/SKILL.md @@ -0,0 +1,18 @@ +--- +name: resolve-reviews +description: Fetch PR review comments, apply valid fixes, and reply with what changed. +compatibility: Requires git and gh. +--- + +# Resolve Reviews + +## Steps + +1. Resolve current PR with `gh pr view --json number,url`. +2. Fetch inline comments with `gh api repos/{owner}/{repo}/pulls/{number}/comments`. +3. Classify each comment as valid, invalid, or needs clarification. +4. Apply valid fixes only. +5. Run the smallest relevant checks. +6. Commit, push, and reply to the review comment with the commit hash. + +Do not resolve threads or dismiss comments unless explicitly asked. diff --git a/.agents/skills/security-checklist/SKILL.md b/.agents/skills/security-checklist/SKILL.md new file mode 100644 index 0000000..db46a12 --- /dev/null +++ b/.agents/skills/security-checklist/SKILL.md @@ -0,0 +1,20 @@ +--- +name: security-checklist +description: Security checklist for Python/FastAPI changes. +--- + +# Security Checklist + +- No secrets committed outside `.env.example`. +- No API keys, tokens, or passwords logged. +- External inputs validated with Pydantic or explicit checks. +- Provider responses treated as untrusted data. +- Network calls have clear error handling. +- CORS/auth changes are reviewed explicitly. + +Useful searches: + +```bash +rg -n "password|secret|token|api[_-]?key|sk-" . +rg -n "print\\(|logger\\..*token|logger\\..*secret" . +``` diff --git a/.agents/skills/systematic-debugging/SKILL.md b/.agents/skills/systematic-debugging/SKILL.md new file mode 100644 index 0000000..d2a618f --- /dev/null +++ b/.agents/skills/systematic-debugging/SKILL.md @@ -0,0 +1,280 @@ +--- +name: systematic-debugging +description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes +--- + +# Systematic Debugging + +## Overview + +Random fixes waste time and create new bugs. Quick patches mask underlying issues. + +**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure. + +**Violating the letter of this process is violating the spirit of debugging.** + +## The Iron Law + +``` +NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST +``` + +If you haven't completed Phase 1, you cannot propose fixes. + +## When to Use + +Use for ANY technical issue: +- Test failures +- Bugs in production +- Unexpected behavior +- Performance problems +- Build failures +- Integration issues + +**Use this ESPECIALLY when:** +- Under time pressure (emergencies make guessing tempting) +- "Just one quick fix" seems obvious +- You've already tried multiple fixes +- Previous fix didn't work +- You don't fully understand the issue + +**Don't skip when:** +- Issue seems simple (simple bugs have root causes too) +- You're in a hurry (rushing guarantees rework) +- Manager wants it fixed NOW (systematic is faster than thrashing) + +## The Four Phases + +You MUST complete each phase before proceeding to the next. + +### Phase 1: Root Cause Investigation + +**BEFORE attempting ANY fix:** + +1. **Read Error Messages Carefully** + - Don't skip past errors or warnings + - They often contain the exact solution + - Read stack traces completely + - Note line numbers, file paths, error codes + +2. **Reproduce Consistently** + - Can you trigger it reliably? + - What are the exact steps? + - Does it happen every time? + - If not reproducible → gather more data, don't guess + +3. **Check Recent Changes** + - What changed that could cause this? + - Git diff, recent commits + - New dependencies, config changes + - Environmental differences + +4. **Gather Evidence in Multi-Component Systems** + + **WHEN system has multiple components (CI → build → signing, API → service → database):** + + **BEFORE proposing fixes, add diagnostic instrumentation:** + ``` + For EACH component boundary: + - Log what data enters component + - Log what data exits component + - Verify environment/config propagation + - Check state at each layer + + Run once to gather evidence showing WHERE it breaks + THEN analyze evidence to identify failing component + THEN investigate that specific component + ``` + + **Example (multi-layer system):** + ```bash + # Layer 1: Workflow + echo "=== Secrets available in workflow: ===" + echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}" + + # Layer 2: Build script + echo "=== Env vars in build script: ===" + env | grep IDENTITY || echo "IDENTITY not in environment" + + # Layer 3: Signing script + echo "=== Keychain state: ===" + security list-keychains + security find-identity -v + + # Layer 4: Actual signing + codesign --sign "$IDENTITY" --verbose=4 "$APP" + ``` + + **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗) + +5. **Trace Data Flow** + + **WHEN error is deep in call stack:** + + See `references/root-cause-tracing.md` in this directory for the complete backward tracing technique. + + **Quick version:** + - Where does bad value originate? + - What called this with bad value? + - Keep tracing up until you find the source + - Fix at source, not at symptom + +### Phase 2: Pattern Analysis + +**Find the pattern before fixing:** + +1. **Find Working Examples** + - Locate similar working code in same codebase + - What works that's similar to what's broken? + +2. **Compare Against References** + - If implementing pattern, read reference implementation COMPLETELY + - Don't skim - read every line + - Understand the pattern fully before applying + +3. **Identify Differences** + - What's different between working and broken? + - List every difference, however small + - Don't assume "that can't matter" + +4. **Understand Dependencies** + - What other components does this need? + - What settings, config, environment? + - What assumptions does it make? + +### Phase 3: Hypothesis and Testing + +**Scientific method:** + +1. **Form Single Hypothesis** + - State clearly: "I think X is the root cause because Y" + - Write it down + - Be specific, not vague + +2. **Test Minimally** + - Make the SMALLEST possible change to test hypothesis + - One variable at a time + - Don't fix multiple things at once + +3. **Verify Before Continuing** + - Did it work? Yes → Phase 4 + - Didn't work? Form NEW hypothesis + - DON'T add more fixes on top + +4. **When You Don't Know** + - Say "I don't understand X" + - Don't pretend to know + - Ask for help + - Research more + +### Phase 4: Implementation + +**Fix the root cause, not the symptom:** + +1. **Create Failing Test Case** + - Simplest possible reproduction + - Automated test if possible + - One-off test script if no framework + - MUST have before fixing + +2. **Implement Single Fix** + - Address the root cause identified + - ONE change at a time + - No "while I'm here" improvements + - No bundled refactoring + +3. **Verify Fix** + - Test passes now? + - No other tests broken? + - Issue actually resolved? + +4. **If Fix Doesn't Work** + - STOP + - Count: How many fixes have you tried? + - If < 3: Return to Phase 1, re-analyze with new information + - **If ≥ 3: STOP and question the architecture (step 5 below)** + - DON'T attempt Fix #4 without architectural discussion + +5. **If 3+ Fixes Failed: Question Architecture** + + **Pattern indicating architectural problem:** + - Each fix reveals new shared state/coupling/problem in different place + - Fixes require "massive refactoring" to implement + - Each fix creates new symptoms elsewhere + + **STOP and question fundamentals:** + - Is this pattern fundamentally sound? + - Are we "sticking with it through sheer inertia"? + - Should we refactor architecture vs. continue fixing symptoms? + + **Discuss with your human partner before attempting more fixes** + + This is NOT a failed hypothesis - this is a wrong architecture. + +## Red Flags - STOP and Follow Process + +If you catch yourself thinking: +- "Quick fix for now, investigate later" +- "Just try changing X and see if it works" +- "Add multiple changes, run tests" +- "Skip the test, I'll manually verify" +- "It's probably X, let me fix that" +- "I don't fully understand but this might work" +- "Pattern says X but I'll adapt it differently" +- "Here are the main problems: [lists fixes without investigation]" +- Proposing solutions before tracing data flow +- **"One more fix attempt" (when already tried 2+)** +- **Each fix reveals new problem in different place** + +**ALL of these mean: STOP. Return to Phase 1.** + +**If 3+ fixes failed:** Question the architecture (see Phase 4.5) + +## Common Rationalizations + +| Excuse | Reality | +|----------------------------------------------|-------------------------------------------------------------------------| +| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. | +| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. | +| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. | +| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. | +| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. | +| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. | +| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. | +| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. | + +## Quick Reference + +| Phase | Key Activities | Success Criteria | +|-----------------------|--------------------------------------------------------|-----------------------------| +| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY | +| **2. Pattern** | Find working examples, compare | Identify differences | +| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis | +| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass | + +## When Process Reveals "No Root Cause" + +If systematic investigation reveals issue is truly environmental, timing-dependent, or external: + +1. You've completed the process +2. Document what you investigated +3. Implement appropriate handling (retry, timeout, error message) +4. Add monitoring/logging for future investigation + +**But:** 95% of "no root cause" cases are incomplete investigation. + +## Supporting Techniques + +These techniques are part of systematic debugging and available in this directory: + +- **`references/root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger +- **`references/defense-in-depth.md`** - Add validation at multiple layers after finding root cause +- **`references/condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling + +## Real-World Impact + +From debugging sessions: +- Systematic approach: 15-30 minutes to fix +- Random fixes approach: 2-3 hours of thrashing +- First-time fix rate: 95% vs 40% +- New bugs introduced: Near zero vs common diff --git a/.agents/skills/systematic-debugging/references/condition-based-waiting.md b/.agents/skills/systematic-debugging/references/condition-based-waiting.md new file mode 100644 index 0000000..70994f7 --- /dev/null +++ b/.agents/skills/systematic-debugging/references/condition-based-waiting.md @@ -0,0 +1,115 @@ +# Condition-Based Waiting + +## Overview + +Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI. + +**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes. + +## When to Use + +```dot +digraph when_to_use { + "Test uses setTimeout/sleep?" [shape=diamond]; + "Testing timing behavior?" [shape=diamond]; + "Document WHY timeout needed" [shape=box]; + "Use condition-based waiting" [shape=box]; + + "Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"]; + "Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"]; + "Testing timing behavior?" -> "Use condition-based waiting" [label="no"]; +} +``` + +**Use when:** +- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`) +- Tests are flaky (pass sometimes, fail under load) +- Tests timeout when run in parallel +- Waiting for async operations to complete + +**Don't use when:** +- Testing actual timing behavior (debounce, throttle intervals) +- Always document WHY if using arbitrary timeout + +## Core Pattern + +```typescript +// ❌ BEFORE: Guessing at timing +await new Promise(r => setTimeout(r, 50)); +const result = getResult(); +expect(result).toBeDefined(); + +// ✅ AFTER: Waiting for condition +await waitFor(() => getResult() !== undefined); +const result = getResult(); +expect(result).toBeDefined(); +``` + +## Quick Patterns + +| Scenario | Pattern | +|----------|---------| +| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` | +| Wait for state | `waitFor(() => machine.state === 'ready')` | +| Wait for count | `waitFor(() => items.length >= 5)` | +| Wait for file | `waitFor(() => fs.existsSync(path))` | +| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` | + +## Implementation + +Generic polling function: +```typescript +async function waitFor( + condition: () => T | undefined | null | false, + description: string, + timeoutMs = 5000 +): Promise { + const startTime = Date.now(); + + while (true) { + const result = condition(); + if (result) return result; + + if (Date.now() - startTime > timeoutMs) { + throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`); + } + + await new Promise(r => setTimeout(r, 10)); // Poll every 10ms + } +} +``` + +See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session. + +## Common Mistakes + +**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU +**✅ Fix:** Poll every 10ms + +**❌ No timeout:** Loop forever if condition never met +**✅ Fix:** Always include timeout with clear error + +**❌ Stale data:** Cache state before loop +**✅ Fix:** Call getter inside loop for fresh data + +## When Arbitrary Timeout IS Correct + +```typescript +// Tool ticks every 100ms - need 2 ticks to verify partial output +await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition +await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior +// 200ms = 2 ticks at 100ms intervals - documented and justified +``` + +**Requirements:** +1. First wait for triggering condition +2. Based on known timing (not guessing) +3. Comment explaining WHY + +## Real-World Impact + +From debugging session (2025-10-03): +- Fixed 15 flaky tests across 3 files +- Pass rate: 60% → 100% +- Execution time: 40% faster +- No more race conditions diff --git a/.agents/skills/systematic-debugging/references/defense-in-depth.md b/.agents/skills/systematic-debugging/references/defense-in-depth.md new file mode 100644 index 0000000..e248335 --- /dev/null +++ b/.agents/skills/systematic-debugging/references/defense-in-depth.md @@ -0,0 +1,122 @@ +# Defense-in-Depth Validation + +## Overview + +When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks. + +**Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible. + +## Why Multiple Layers + +Single validation: "We fixed the bug" +Multiple layers: "We made the bug impossible" + +Different layers catch different cases: +- Entry validation catches most bugs +- Business logic catches edge cases +- Environment guards prevent context-specific dangers +- Debug logging helps when other layers fail + +## The Four Layers + +### Layer 1: Entry Point Validation +**Purpose:** Reject obviously invalid input at API boundary + +```typescript +function createProject(name: string, workingDirectory: string) { + if (!workingDirectory || workingDirectory.trim() === '') { + throw new Error('workingDirectory cannot be empty'); + } + if (!existsSync(workingDirectory)) { + throw new Error(`workingDirectory does not exist: ${workingDirectory}`); + } + if (!statSync(workingDirectory).isDirectory()) { + throw new Error(`workingDirectory is not a directory: ${workingDirectory}`); + } + // ... proceed +} +``` + +### Layer 2: Business Logic Validation +**Purpose:** Ensure data makes sense for this operation + +```typescript +function initializeWorkspace(projectDir: string, sessionId: string) { + if (!projectDir) { + throw new Error('projectDir required for workspace initialization'); + } + // ... proceed +} +``` + +### Layer 3: Environment Guards +**Purpose:** Prevent dangerous operations in specific contexts + +```typescript +async function gitInit(directory: string) { + // In tests, refuse git init outside temp directories + if (process.env.NODE_ENV === 'test') { + const normalized = normalize(resolve(directory)); + const tmpDir = normalize(resolve(tmpdir())); + + if (!normalized.startsWith(tmpDir)) { + throw new Error( + `Refusing git init outside temp dir during tests: ${directory}` + ); + } + } + // ... proceed +} +``` + +### Layer 4: Debug Instrumentation +**Purpose:** Capture context for forensics + +```typescript +async function gitInit(directory: string) { + const stack = new Error().stack; + logger.debug('About to git init', { + directory, + cwd: process.cwd(), + stack, + }); + // ... proceed +} +``` + +## Applying the Pattern + +When you find a bug: + +1. **Trace the data flow** - Where does bad value originate? Where used? +2. **Map all checkpoints** - List every point data passes through +3. **Add validation at each layer** - Entry, business, environment, debug +4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it + +## Example from Session + +Bug: Empty `projectDir` caused `git init` in source code + +**Data flow:** +1. Test setup → empty string +2. `Project.create(name, '')` +3. `WorkspaceManager.createWorkspace('')` +4. `git init` runs in `process.cwd()` + +**Four layers added:** +- Layer 1: `Project.create()` validates not empty/exists/writable +- Layer 2: `WorkspaceManager` validates projectDir not empty +- Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests +- Layer 4: Stack trace logging before git init + +**Result:** All 1847 tests passed, bug impossible to reproduce + +## Key Insight + +All four layers were necessary. During testing, each layer caught bugs the others missed: +- Different code paths bypassed entry validation +- Mocks bypassed business logic checks +- Edge cases on different platforms needed environment guards +- Debug logging identified structural misuse + +**Don't stop at one validation point.** Add checks at every layer. diff --git a/.agents/skills/systematic-debugging/references/root-cause-tracing.md b/.agents/skills/systematic-debugging/references/root-cause-tracing.md new file mode 100644 index 0000000..6e6cfb0 --- /dev/null +++ b/.agents/skills/systematic-debugging/references/root-cause-tracing.md @@ -0,0 +1,170 @@ +# Root Cause Tracing + +## Overview + +Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom. + +**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source. + +## When to Use + +```dot +digraph when_to_use { + "Bug appears deep in stack?" [shape=diamond]; + "Can trace backwards?" [shape=diamond]; + "Fix at symptom point" [shape=box]; + "Trace to original trigger" [shape=box]; + "BETTER: Also add defense-in-depth" [shape=box]; + + "Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"]; + "Can trace backwards?" -> "Trace to original trigger" [label="yes"]; + "Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"]; + "Trace to original trigger" -> "BETTER: Also add defense-in-depth"; +} +``` + +**Use when:** +- Error happens deep in execution (not at entry point) +- Stack trace shows long call chain +- Unclear where invalid data originated +- Need to find which test/code triggers the problem + +## The Tracing Process + +### 1. Observe the Symptom +``` +Error: git init failed in /Users/jesse/project/packages/core +``` + +### 2. Find Immediate Cause +**What code directly causes this?** +```typescript +await execFileAsync('git', ['init'], { cwd: projectDir }); +``` + +### 3. Ask: What Called This? +```typescript +WorktreeManager.createSessionWorktree(projectDir, sessionId) + → called by Session.initializeWorkspace() + → called by Session.create() + → called by test at Project.create() +``` + +### 4. Keep Tracing Up +**What value was passed?** +- `projectDir = ''` (empty string!) +- Empty string as `cwd` resolves to `process.cwd()` +- That's the source code directory! + +### 5. Find Original Trigger +**Where did empty string come from?** +```typescript +const context = setupCoreTest(); // Returns { tempDir: '' } +Project.create('name', context.tempDir); // Accessed before beforeEach! +``` + +## Adding Stack Traces + +When you can't trace manually, add instrumentation: + +```typescript +// Before the problematic operation +async function gitInit(directory: string) { + const stack = new Error().stack; + console.error('DEBUG git init:', { + directory, + cwd: process.cwd(), + nodeEnv: process.env.NODE_ENV, + stack, + }); + + await execFileAsync('git', ['init'], { cwd: directory }); +} +``` + +**Critical:** Use `console.error()` in tests (not logger - may not show) + +**Run and capture:** +```bash +npm test 2>&1 | grep 'DEBUG git init' +``` + +**Analyze stack traces:** +- Look for test file names +- Find the line number triggering the call +- Identify the pattern (same test? same parameter?) + +## Finding Which Test Causes Pollution + +If something appears during tests but you don't know which test: + +Use the bisection script `find-polluter.sh` in the scripts directory: + +```bash +./scripts/find-polluter.sh '.git' 'src/**/*.test.ts' +``` + +Runs tests one-by-one, stops at first polluter. See script for usage. + +## Real Example: Empty projectDir + +**Symptom:** `.git` created in `packages/core/` (source code) + +**Trace chain:** +1. `git init` runs in `process.cwd()` ← empty cwd parameter +2. WorktreeManager called with empty projectDir +3. Session.create() passed empty string +4. Test accessed `context.tempDir` before beforeEach +5. setupCoreTest() returns `{ tempDir: '' }` initially + +**Root cause:** Top-level variable initialization accessing empty value + +**Fix:** Made tempDir a getter that throws if accessed before beforeEach + +**Also added defense-in-depth:** +- Layer 1: Project.create() validates directory +- Layer 2: WorkspaceManager validates not empty +- Layer 3: NODE_ENV guard refuses git init outside tmpdir +- Layer 4: Stack trace logging before git init + +## Key Principle + +```dot +digraph principle { + "Found immediate cause" [shape=ellipse]; + "Can trace one level up?" [shape=diamond]; + "Trace backwards" [shape=box]; + "Is this the source?" [shape=diamond]; + "Fix at source" [shape=box]; + "Add validation at each layer" [shape=box]; + "Bug impossible" [shape=doublecircle]; + "NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white]; + + "Found immediate cause" -> "Can trace one level up?"; + "Can trace one level up?" -> "Trace backwards" [label="yes"]; + "Can trace one level up?" -> "NEVER fix just the symptom" [label="no"]; + "Trace backwards" -> "Is this the source?"; + "Is this the source?" -> "Trace backwards" [label="no - keeps going"]; + "Is this the source?" -> "Fix at source" [label="yes"]; + "Fix at source" -> "Add validation at each layer"; + "Add validation at each layer" -> "Bug impossible"; +} +``` + +**NEVER fix just where the error appears.** Trace back to find the original trigger. + +## Stack Trace Tips + +**In tests:** Use `console.error()` not logger - logger may be suppressed +**Before operation:** Log before the dangerous operation, not after it fails +**Include context:** Directory, cwd, environment variables, timestamps +**Capture stack:** `new Error().stack` shows complete call chain + +## Real-World Impact + +From debugging session (2025-10-03): +- Found root cause through 5-level trace +- Fixed at source (getter validation) +- Added 4 layers of defense +- 1847 tests passed, zero pollution +- diff --git a/.agents/skills/systematic-debugging/scripts/find-polluter.sh b/.agents/skills/systematic-debugging/scripts/find-polluter.sh new file mode 100644 index 0000000..700612b --- /dev/null +++ b/.agents/skills/systematic-debugging/scripts/find-polluter.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Bisection script to find which test creates unwanted files/state +# Usage: ./find-polluter.sh +# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts' + +set -e + +if [ $# -ne 2 ]; then + echo "Usage: $0 " + echo "Example: $0 '.git' 'src/**/*.test.ts'" + exit 1 +fi + +POLLUTION_CHECK="$1" +TEST_PATTERN="$2" + +echo "🔍 Searching for test that creates: $POLLUTION_CHECK" +echo "Test pattern: $TEST_PATTERN" +echo "" + +# Get list of test files +TEST_FILES=$(find . -path "$TEST_PATTERN" | sort) +if [ -z "$TEST_FILES" ]; then + TOTAL=0 +else + TOTAL=$(printf '%s\n' "$TEST_FILES" | wc -l | tr -d ' ') +fi + +echo "Found $TOTAL test files" +echo "" + +COUNT=0 +for TEST_FILE in $TEST_FILES; do + COUNT=$((COUNT + 1)) + + # Skip if pollution already exists + if [ -e "$POLLUTION_CHECK" ]; then + echo "⚠️ Pollution already exists before test $COUNT/$TOTAL" + echo " Skipping: $TEST_FILE" + continue + fi + + echo "[$COUNT/$TOTAL] Testing: $TEST_FILE" + + # Run the test + pytest "$TEST_FILE" > /dev/null 2>&1 || true + + # Check if pollution appeared + if [ -e "$POLLUTION_CHECK" ]; then + echo "" + echo "🎯 FOUND POLLUTER!" + echo " Test: $TEST_FILE" + echo " Created: $POLLUTION_CHECK" + echo "" + echo "Pollution details:" + ls -la "$POLLUTION_CHECK" + echo "" + echo "To investigate:" + echo " pytest $TEST_FILE # Run just this test" + echo " cat $TEST_FILE # Review test code" + exit 1 + fi +done + +echo "" +echo "✅ No polluter found - all tests clean!" +exit 0 diff --git a/.agents/skills/test/SKILL.md b/.agents/skills/test/SKILL.md new file mode 100644 index 0000000..d8e0ce3 --- /dev/null +++ b/.agents/skills/test/SKILL.md @@ -0,0 +1,19 @@ +--- +name: test +description: Run the smallest useful Python check or test command and report results. +--- + +# Test Skill + +## Selection + +- If a specific pytest target is obvious, run it. +- If tests exist, run `pytest`. +- If no tests exist, run: + +```bash +.venv/bin/python -m py_compile main.py +.venv/bin/python -c "from main import app; assert app" +``` + +Use `python` instead of `.venv/bin/python` only when `.venv` is unavailable. diff --git a/.agents/skills/write-pr/SKILL.md b/.agents/skills/write-pr/SKILL.md new file mode 100644 index 0000000..ece4340 --- /dev/null +++ b/.agents/skills/write-pr/SKILL.md @@ -0,0 +1,63 @@ +--- +name: write-pr +description: Push the current branch, generate a PR title/body from commits since the base branch following this project's convention (no prefix, Korean title), attach best-matching labels if any exist, and open the GitHub PR. +compatibility: Requires git and gh (GitHub CLI) +--- + +## Step 1 — Determine Base Branch + +Default base branch is `develop`. Confirm it exists: + +```bash +git fetch origin +git rev-parse --verify origin/develop +``` + +If `develop` doesn't exist, ask the user which base branch to target. + +## Step 2 — Push Current Branch + +```bash +git branch --show-current +git push -u origin +``` + +If the current branch is `develop` or `main`, stop and ask the user — a PR from the base branch itself doesn't make sense. + +## Step 3 — Collect Commits Since Base + +```bash +git log origin/develop..HEAD --oneline +``` + +If there are no commits ahead of base, report that and exit. + +## Step 4 — Compose Title and Body + +**PR 제목**: 접두어 없이 한글 문장으로 (`[FEAT]`, `feat:` 같은 접두어 금지). 커밋들의 핵심 변경사항을 한 문장으로 요약. + +예: `JWT 인증 필터 추가` + +**PR 본문**: 커밋 목록을 바탕으로 변경 사항을 bullet로 정리하고, 관련 이슈가 있으면 `Closes #<번호>` 형식으로 연결. + +**어트리뷰션 주의**: 본문에 "Generated by Codex" 같은 서명이나 트레일러를 추가하지 않는다. + +## Step 5 — Labels (best-effort) + +```bash +gh label list +``` + +변경 내용과 매칭되는 라벨이 저장소에 이미 존재하면 붙인다. 매칭되는 라벨이 없으면 라벨 없이 진행 — 임의로 새 라벨을 만들지 않는다. + +## Step 6 — Open PR + +```bash +gh pr create --base develop --title "<한글 제목>" --body "<본문>" +``` + +라벨이 있으면 `--label