{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Claude Code & Skills\r\n",
    "\r\n",
    "*Module 6*\r\n",
    "\r\n",
    "This module shifts from basic configuration to advanced repository operations. It focuses on the practical judgment needed to explore large codebases without exhausting the context window, manage divergent exploration paths through forking, and make reliable file modifications when automated edits are ambiguous.\r\n",
    "\r\n",
    "**Lab notebook:** [Module6_Complete.ipynb](lab_files/Module6_Complete.ipynb)\r\n",
    "\r\n",
    "## 1. Navigating Unfamiliar Codebases\r\n",
    "\r\n",
    "An architect must build understanding incrementally. Loading entire directories up front creates attention dilution: the model has too much low-signal text in context and starts missing the facts that matter.\r\n",
    "\r\n",
    "- **Glob pattern matching:** use `Glob` to find files by name or extension patterns, such as `**/*.test.tsx` or `**/*.config.ts`, rather than reading full directories.\r\n",
    "- **Content-based search:** use `Grep` to locate function entry points, exported names, error messages, and constants across the codebase.\r\n",
    "- **Flow tracing:** identify an exported name with `Read`, then use `Grep` to find all callers and trace usage through wrapper modules.\r\n",
    "- **Targeted reading:** use `Read` only after `Glob` or `Grep` has narrowed the candidate files.\r\n",
    "\r\n",
    "```incremental discovery pattern\r\n",
    "Goal: understand an authentication failure without flooding context.\r\n",
    "\r\n",
    "1. Glob: \"**/*.config.ts\" to map configuration files.\r\n",
    "2. Grep: \"Invalid Token\" to locate the error source.\r\n",
    "3. Read: inspect the matching source file and identify the exported function.\r\n",
    "4. Grep: search for that exported function to find all callers.\r\n",
    "5. Read: inspect only the caller files needed to understand the flow.\r\n",
    "```\r\n",
    "\r\n",
    "## 2. Reliable Modifications\r\n",
    "\r\n",
    "Production modifications must be deterministic. Claude Code should prefer the smallest reliable edit, then escalate to a full-file replacement only when the targeted edit is ambiguous.\r\n",
    "\r\n",
    "- **The `Edit` tool:** preferred for targeted changes using unique text matching. It is more token-efficient and lower risk than full-file writes.\r\n",
    "- **The fallback pattern:** if `Edit` fails because the target text appears multiple times, use `Read` to load the full content, modify the intended block with complete context, then use `Write` to replace the file.\r\n",
    "- **Verification:** after a fallback write, run the narrowest relevant test or linter command.\r\n",
    "\r\n",
    "```edit fallback pattern\r\n",
    "1. Attempt Edit against unique anchor text.\r\n",
    "2. If the anchor appears multiple times, stop and Read the full file.\r\n",
    "3. Identify the intended block by surrounding function/component names.\r\n",
    "4. Modify the full file content locally.\r\n",
    "5. Use Write to replace the file.\r\n",
    "6. Run the smallest relevant verification command.\r\n",
    "```\r\n",
    "\r\n",
    "## 3. Session State Strategy: Resume, Fork, Fresh Start\r\n",
    "\r\n",
    "Architects must decide which session history best matches the current goal.\r\n",
    "\r\n",
    "### 3a. Resuming Sessions\r\n",
    "\r\n",
    "Use `claude --resume <session-id>` to continue a specific investigation thread across work sessions. Running `claude --resume` with no argument opens an interactive session picker so you can choose which past session to continue.\r\n",
    "\r\n",
    "```bash\r\n",
    "# Resume a specific session by its ID\r\n",
    "claude --resume 550e8400-e29b-41d4-a716-446655440000\r\n",
    "\r\n",
    "# No argument: opens an interactive picker of recent sessions\r\n",
    "claude --resume\r\n",
    "```\r\n",
    "\r\n",
    "### 3b. Fork-Based Exploration\r\n",
    "\r\n",
    "Use `claude --resume <session-id> --fork-session` to create independent branches from a shared analysis baseline. Each fork gets its own new session ID, leaving the original untouched. This is ideal for comparing two refactoring approaches or two testing strategies without losing the initial setup. In the Agent SDK, the equivalent option is `forkSession`.\r\n",
    "\r\n",
    "```bash\r\n",
    "# After shared discovery identifies the auth flow, fork the\r\n",
    "# baseline session twice -- each fork gets its own session ID:\r\n",
    "claude --resume 550e8400-e29b-41d4-a716-446655440000 --fork-session\r\n",
    "claude --resume 550e8400-e29b-41d4-a716-446655440000 --fork-session\r\n",
    "\r\n",
    "# Agent SDK equivalent: pass forkSession: true when resuming.\r\n",
    "```\r\n",
    "\r\n",
    "### 3c. Fresh-Start Rebuild\r\n",
    "\r\n",
    "When a session is filled with stale tool results, dead-end exploration, or old assumptions, start a new session. The first message should be a handoff summary that re-grounds the model efficiently.\r\n",
    "\r\n",
    "```handoff summary, first message of the new session\r\n",
    "Current state:\r\n",
    "- \"Invalid Token\" is raised in auth/token.ts by validateAccessToken.\r\n",
    "- The login route calls validateAccessToken directly; API middleware calls it through requireAuth.\r\n",
    "- Decision: preserve public API shape and fix validation at the shared boundary.\r\n",
    "\r\n",
    "Next step:\r\n",
    "Add the missing issuer check and run the auth middleware test file.\r\n",
    "```\r\n",
    "\r\n",
    "> **Tip.** Architect Tip for the Exam Decision rule: **resume** when the prior context is still accurate; **fork** when comparing divergent approaches from one shared baseline; **fresh-start** when stale context would mislead the next implementation step.\r\n",
    "\r\n",
    "## 4. Repository Governance\r\n",
    "\r\n",
    "Persistent instructions provide universal standards without bloating every prompt.\r\n",
    "\r\n",
    "- **User-level settings (`~/`) are not shared.** They are useful for personal defaults, not team standards.\r\n",
    "- **Project-level `CLAUDE.md`** is the primary vehicle for repository-wide team standards.\r\n",
    "- **Directory-level `CLAUDE.md`** scopes rules to one subtree when a package or app has different conventions.\r\n",
    "- **Path-scoped rules** in `.claude/rules/` use glob patterns in YAML frontmatter to load conventions only when matching files are edited.\r\n",
    "\r\n",
    "*.claude/rules/test-conventions.md*\r\n",
    "```markdown\r\n",
    "---\r\n",
    "paths: [\"**/*.test.tsx\"]\r\n",
    "---\r\n",
    "# Test File Conventions\r\n",
    "- Use existing fixtures before creating new mocks.\r\n",
    "- Prefer user-visible assertions over implementation details.\r\n",
    "- Run the nearest test file after modifying test helpers.\r\n",
    "```\r\n",
    "\r\n",
    "> **Tip.** Architect Tip Path-scoped rules are ideal for cross-cutting conventions like `**/*.test.tsx` because they apply by file pattern rather than directory boundary.\r\n",
    "\r\n",
    "### 4a. Advanced Configuration: Modular Memory\r\n",
    "\r\n",
    "Large repositories should not put every convention into one giant `CLAUDE.md`. Use `@import` to keep instructions modular and reviewable.\r\n",
    "\r\n",
    "*CLAUDE.md*\r\n",
    "```markdown\r\n",
    "# CLAUDE.md\r\n",
    "\r\n",
    "@import .claude/memory/testing.md\r\n",
    "@import .claude/memory/security.md\r\n",
    "@import .claude/memory/release-process.md\r\n",
    "```\r\n",
    "\r\n",
    "After editing memory files, run `/memory` in Claude Code to verify which instructions and imported files are loaded for the current working directory.\r\n",
    "\r\n",
    "## 5. Slash Commands: Project vs. Personal Scope\r\n",
    "\r\n",
    "Slash commands are reusable prompts invoked by name. Where the command file lives determines who can use it.\r\n",
    "\r\n",
    "- **Project-scoped commands (`.claude/commands/`):** committed to version control and shared with the whole team. A file named `review.md` in this directory becomes the team's `/review` command, carrying the team's review checklist prompt.\r\n",
    "- **Personal commands (`~/.claude/commands/`):** available in every project on your machine but never shared with teammates.\r\n",
    "\r\n",
    "*.claude/commands/review.md*\r\n",
    "```markdown\r\n",
    "Review the current diff against our team standards:\r\n",
    "1. Security: input validation, authorization checks, secret handling.\r\n",
    "2. Tests: new behavior has coverage; no skipped or deleted tests.\r\n",
    "3. Regressions: public API shape and error contracts are unchanged.\r\n",
    "Report findings as a numbered list with file paths.\r\n",
    "```\r\n",
    "\r\n",
    "> **Tip.** Architect Tip for the Exam Decision rule: team workflow → project scope (`.claude/commands/`); personal experiment → user scope (`~/.claude/commands/`).\r\n",
    "\r\n",
    "## 6. Agent Skills: Progressive Disclosure\r\n",
    "\r\n",
    "Skills should minimize token load until Claude actually needs the detail. Use the three-level system:\r\n",
    "\r\n",
    "- **Level 1, frontmatter:** keep `description` focused on what the skill does and when to use it. This trigger text sits in the system prompt.\r\n",
    "- **Level 2, `SKILL.md` body:** use standard headers such as `Steps`, `Examples`, and `Troubleshooting`.\r\n",
    "- **Level 3, linked files:** place high-signal supporting docs in `references/` and link to them from `SKILL.md`.\r\n",
    "\r\n",
    "*SKILL.md*\r\n",
    "```markdown\r\n",
    "---\r\n",
    "name: pr-reviewer\r\n",
    "description: Use when reviewing pull requests for security, test coverage, and regression risk. Do not use for writing new features.\r\n",
    "context: fork\r\n",
    "allowed-tools: Read, Grep, Glob\r\n",
    "argument-hint: [pr-number-or-branch]\r\n",
    "---\r\n",
    "\r\n",
    "# PR Reviewer\r\n",
    "\r\n",
    "## Steps\r\n",
    "1. Inspect the diff.\r\n",
    "2. Identify correctness, security, and test risks.\r\n",
    "3. Return machine-parseable findings.\r\n",
    "\r\n",
    "## Examples\r\n",
    "See references/review-examples.md.\r\n",
    "\r\n",
    "## Troubleshooting\r\n",
    "If the diff is too large, request a narrower file set.\r\n",
    "```\r\n",
    "\r\n",
    "Three frontmatter keys deserve special attention:\r\n",
    "\r\n",
    "- **`context: fork`:** runs the skill in an isolated sub-agent context, so verbose output does not pollute the main conversation. Use this for codebase-analysis or brainstorming skills that generate long intermediate output.\r\n",
    "- **`allowed-tools`:** restricts which tools the skill may use during execution — for example, limiting a skill to file writes only.\r\n",
    "- **`argument-hint`:** prompts the developer for the required parameters when the skill is invoked without arguments.\r\n",
    "\r\n",
    "Keep the scoping distinction sharp: skills are on-demand, task-specific capabilities, while `CLAUDE.md` carries always-loaded universal standards.\r\n",
    "\r\n",
    "Lab checkpoint: use the `skill-creator` skill to review custom skills for vague descriptions, missing trigger conditions, missing `Steps`, or absent `references/` links.\r\n",
    "\r\n",
    "### 6a. User-Scoped Skill Variants\r\n",
    "\r\n",
    "Team skills belong in the project repository. Personal productivity variants belong in `~/.claude/skills/` under a **different name** from the team skill, so they do not alter shared behavior for teammates.\r\n",
    "\r\n",
    "```skill locations\r\n",
    "Project skill:\r\n",
    ".claude/skills/pr-reviewer/SKILL.md\r\n",
    "\r\n",
    "Personal variant:\r\n",
    "~/.claude/skills/alexa-pr-reviewer/SKILL.md\r\n",
    "```\r\n",
    "\r\n",
    "Use this when you want stricter personal review preferences, local aliases, or private workflow notes without changing the repository standard.\r\n",
    "\r\n",
    "## 7. The Interview Pattern\r\n",
    "\r\n",
    "In unfamiliar domains, start by forcing Claude to interview before implementation. The goal is to surface hidden design constraints, such as cache invalidation, failure modes, data retention, or rollout requirements, before code is written.\r\n",
    "\r\n",
    "```interview prompt\r\n",
    "Before proposing or implementing a solution, ask 2-3 clarifying questions.\r\n",
    "Focus on cache invalidation, failure handling, and compatibility risks.\r\n",
    "After I answer, summarize the decision constraints and then implement the smallest viable change.\r\n",
    "```\r\n",
    "\r\n",
    "Use this pattern for ambiguous feature work, domain-specific systems, and changes with reliability implications. Do not use it for tiny, fully specified single-file fixes.\r\n",
    "\r\n",
    "## 8. Session Context Isolation for CI Review\r\n",
    "\r\n",
    "The Claude session that generated code is less effective at reviewing it because it carries the same assumptions, exploratory dead ends, and self-justifications that led to the patch. Automated review should use an independent Claude instance with only the diff, repo rules, and review schema.\r\n",
    "\r\n",
    "```ci review command\r\n",
    "claude -p \"Review this PR for correctness, security, and missing tests.\" \\\r\n",
    "  --output-format json \\\r\n",
    "  --json-schema .claude/schemas/pr-review-findings.schema.json\r\n",
    "```\r\n",
    "\r\n",
    "Use the JSON findings to post inline PR comments. Keep the generation session and the review session isolated.\r\n",
    "\r\n",
    "**Deduplicate across runs.** When re-running the review after new commits land on the branch, include the prior findings in context and instruct Claude to report only new or still-unaddressed issues, so reviewers are not flooded with duplicates. Likewise, provide the existing test files as context so test generation does not duplicate scenarios that are already covered.\r\n",
    "\r\n",
    "## 9. Plan Mode vs. Direct Execution\r\n",
    "\r\n",
    "Use Plan Mode when the task has architectural implications, multiple implementation approaches, or multi-file modifications. Use direct execution for well-understood, single-file bug fixes with clear scope.\r\n",
    "\r\n",
    "- **Plan Mode:** suited for refactors, unfamiliar code paths, migration work, and changes where you need to compare approaches before editing.\r\n",
    "- **Explore subagent:** during planning, use it to isolate verbose discovery output and return only summaries to the main session, preserving context for decisions.\r\n",
    "- **Direct execution:** suited for a narrow bug fix where the target file, expected change, and verification command are already clear.\r\n",
    "- **Context recovery with `/compact`:** when extended exploration fills the context window with verbose discovery output, run `/compact` to condense the conversation and reduce context usage before continuing implementation.\r\n",
    "\r\n",
    "```plan mode decision examples\r\n",
    "Use Plan Mode:\r\n",
    "- \"Trace auth token validation and compare two fix approaches.\"\r\n",
    "- \"Refactor all checkout tests to a new fixture system.\"\r\n",
    "\r\n",
    "Use Direct Execution:\r\n",
    "- \"Fix this typo in one error message.\"\r\n",
    "- \"Add a missing import in this single test file.\"\r\n",
    "```\r\n",
    "\r\n",
    "## Lab Exercise: Incremental Codebase Understanding\r\n",
    "\r\n",
    "**Lab notebook:** [Module6_Self_Driven_Lab.ipynb](lab_files/Module6_Self_Driven_Lab.ipynb)\r\n",
    "\r\n",
    "**Objective:** master built-in tool selection and the fallback modification pattern.\r\n",
    "\r\n",
    "1. **Structural mapping:** use `Glob` to find all configuration files matching `**/*.config.ts`.\r\n",
    "2. **Entry point search:** use `Grep` to find every instance of `\"Invalid Token\"` and identify where authentication logic is defined.\r\n",
    "3. **Tracing and reading:** use `Read` to inspect the source file found by `Grep`, identify the exported function, then use `Grep` again to find all callers.\r\n",
    "4. **The fallback move:** attempt to use `Edit` to add a line where the target anchor text appears multiple times. Observe the failure, then use `Read` to get the full file content and `Write` to replace it reliably.\r\n",
    "5. **Divergent approaches:** use `claude --resume <session-id> --fork-session` twice to create two branches from the shared baseline, one per candidate fix for the authentication bug. Resume each forked session to verify its fix independently.\r\n",
    "6. **Skill review:** use the `skill-creator` skill to audit a custom skill for vague descriptions, missing trigger conditions, missing `Steps`, and whether supporting docs belong in `references/`.\r\n",
    "7. **Personal skill variant:** create a user-scoped variant in `~/.claude/skills/` with a unique name, then document how it differs from the team skill without changing project files.\r\n",
    "8. **Interview pattern:** prompt Claude to ask 2-3 clarifying questions before implementation, specifically probing cache invalidation, failure modes, and compatibility risks.\r\n",
    "9. **CI review isolation:** run an independent `claude -p` review with `--output-format json` and `--json-schema`, then map findings to inline PR comments.\r\n",
    "\r\n",
    "> **Tip.** Architect Tip for the Exam Tool choice is part of architecture. `Glob` maps structure, `Grep` finds behavior, `Read` builds local understanding, `Edit` handles unique targeted changes, and `Read` + `Write` is the deterministic fallback when targeted matching is ambiguous.\r\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}