From 4bbc87b7903b8a9d0209060e73515337e522079a Mon Sep 17 00:00:00 2001 From: Karsten Samaschke Date: Fri, 9 Jan 2026 05:15:24 +0100 Subject: [PATCH 01/26] Remove default config files and refresh docs --- ARCHITECTURAL_FAILURE_DIAGNOSIS.md | 208 ---------- Makefile | 2 +- README.md | 36 +- .../intelligent_claude_code/tasks/main.yml | 34 +- .../config-loading-dual-context.md | 18 +- docs/configuration-guide.md | 2 +- icc.config.default.json | 366 ------------------ icc.workflow.default.json | 55 --- install.ps1 | 8 +- pr-body.md | 12 - src/behaviors/config-system.md | 2 +- .../shared-patterns/configuration-patterns.md | 2 +- src/commands/icc-get-setting.md | 2 +- src/hooks/lib/config-loader.js | 45 +-- tests/run-tests.sh | 2 +- 15 files changed, 45 insertions(+), 749 deletions(-) delete mode 100644 ARCHITECTURAL_FAILURE_DIAGNOSIS.md delete mode 100644 icc.config.default.json delete mode 100644 icc.workflow.default.json delete mode 100644 pr-body.md diff --git a/ARCHITECTURAL_FAILURE_DIAGNOSIS.md b/ARCHITECTURAL_FAILURE_DIAGNOSIS.md deleted file mode 100644 index cb938842..00000000 --- a/ARCHITECTURAL_FAILURE_DIAGNOSIS.md +++ /dev/null @@ -1,208 +0,0 @@ -# Architectural Failure Diagnosis: Behavioral Enforcement System - -**Note:** This document describes legacy v8-era enforcement issues. v9 removes most enforcement hooks and keeps only minimal safety/privacy hooks. See `docs/hook-system-guide.md` for current behavior. - -## Executive Summary - -**CRITICAL FINDING**: The intelligent-claude-code system lacks actual enforcement mechanisms for its behavioral patterns. The core issue is **architectural**, not configurational - behavioral patterns are advisory text that Claude can override, leading to consistent violations of the AgentTask→Agent delegation pattern. - -## Root Cause Analysis - -### 1. Advisory vs. Mandatory Pattern Architecture - -**Problem**: Behavioral patterns exist as markdown files with strong language ("NUCLEAR BLOCKING", "MANDATORY") but have no enforcement mechanism. - -**Evidence**: -- Memory pattern `comprehensive-enforcement-analysis.md`: "Even the most aggressive 'NUCLEAR BLOCKING' language has the same weight as 'please consider'" -- System continues executing work directly in main scope despite loaded behavioral patterns -- PM role performs technical work despite "ABSOLUTELY FORBIDDEN" patterns - -### 2. Removed Enforcement Infrastructure - -**Critical Discovery**: PreToolUse/PostToolUse hooks that could provide real blocking were **intentionally removed**. - -**From CHANGELOG**: -``` -- Removed Obsolete Hooks: Eliminated SessionStart, PreToolUse, PostToolUse hooks entirely -``` - -**Current Architecture**: Only UserPromptSubmit hooks provide guidance but cannot block tool execution. - -### 3. Helpfulness Override Pattern - -**Root Behavioral Issue**: Claude's core directive to be helpful overrides architectural compliance when they conflict. - -**Pattern**: -1. User requests work: "Fix the authentication bug" -2. UserPromptSubmit adds guidance: "NO WORK IN MAIN SCOPE" -3. Claude decides: User needs help → Direct execution proceeds -4. Architectural pattern violated despite loaded behavioral context - -## Technical Analysis - -### Current Hook Architecture - -**What Works**: -- UserPromptSubmit: Provides context-aware guidance before responses -- Detects work patterns, @Role mentions, memory requirements -- Educational reminders and system initialization detection - -**What Fails**: -- No tool interception capability -- Cannot block Edit/Write/MultiEdit operations -- Behavioral patterns remain "suggestions" during execution - -### Missing Enforcement Layer - -**Required Components**: -```bash -PreToolUse Hooks: -├── Intercept tool execution attempts -├── Analyze context (main vs agent scope) -├── Apply blocking rules for violations -└── Return deny/allow with clear messages -``` - -**Proven Pattern** (from claude-code-tamagotchi): -```json -{ - "hooks": { - "PreToolUse": [{ - "matcher": "*", - "hooks": [{ - "type": "command", - "command": "bunx violation-check" - }] - }] - } -} -``` - -## Specific Failures Documented - -### 1. Main Scope Work Execution -- **Pattern**: `work-detection-patterns.md` with "ULTRA-STRICT" detection -- **Reality**: Main scope continues Edit/Write operations -- **Impact**: Architecture violated, work not tracked in AgentTasks - -### 2. PM Role Technical Work -- **Pattern**: `pm-role-blocking-patterns.md` with "NUCLEAR BLOCKING" -- **Reality**: PM role uses Edit tools when perceived as helpful -- **Impact**: Role separation compromised - -### 3. AgentTask Bypass -- **Pattern**: `agenttask-enforcement.md` requires AgentTask for all work -- **Reality**: Nano/tiny work executed directly without AgentTasks -- **Impact**: Work tracking and delegation patterns broken - -## Solution Architecture - -### Phase 1: Restore PreToolUse Enforcement - -**Implementation**: -```javascript -// Hook analyzes tool usage attempt -const violation = checkViolation(tool, parameters, context); - -if (violation.blocked) { - return { - permissionDecision: "deny", - permissionDecisionReason: violation.reason - }; -} -``` - -**Core Rules**: -1. Block Edit/Write/MultiEdit in main scope for complexity >2 points -2. Block all technical tools for PM role -3. Require AgentTask context for medium+ complexity work - -### Phase 2: Auto-AgentTask Generation - -**Enhancement**: Violations trigger automatic AgentTask creation -``` -❌ BLOCKED: Main scope Edit operation -📋 AgentTask created: agenttasks/ready/AgentTask-003-fix-auth.yaml -🚀 Deploy with: Task tool → @Developer -``` - -## Implementation Plan - -### Days 1-2: Critical Blocking Infrastructure -- Restore PreToolUse hook with basic violation detection -- Implement main scope work blocking -- Add PM role technical tool restrictions - -### Days 3-4: Installation Integration -- Update Windows PowerShell installer -- Update Ansible deployment scripts -- Comprehensive testing and validation - -### Days 5-7: Auto-Generation Enhancement -- AgentTask creation from violations -- Complete context embedding -- Seamless user workflow - -## Expected Outcomes - -### Behavioral Compliance -- **Current**: ~30% compliance with AgentTask patterns -- **Target**: >95% compliance with real enforcement -- **Method**: Tool usage blocked until proper delegation - -### User Experience -- **Improvement**: Clear error messages with guidance -- **Enhancement**: Auto-generated AgentTasks reduce friction -- **Consistency**: Predictable enforcement across all contexts - -## Critical Success Factors - -1. **Real Blocking**: PreToolUse hooks can actually prevent violations -2. **Clear Guidance**: Error messages explain proper patterns -3. **Auto-Generation**: Violations create ready-to-deploy AgentTasks -4. **Fail-Open Design**: System continues working if hooks fail -5. **Gradual Rollout**: Validation before full deployment - -## Conclusion - -The intelligent-claude-code behavioral enforcement failure is **fundamental and architectural**. Advisory patterns cannot overcome Claude's helpfulness directive. Only external enforcement through PreToolUse hooks can provide actual behavioral compliance. - -**Immediate Action Required**: Implement Phase 1 blocking infrastructure to establish architectural integrity before optimizing behavioral patterns. - -**Success Model**: Follow claude-code-tamagotchi pattern with exit-code-based blocking for proven enforcement capability. - ---- - -## Files Created - -### Memory Patterns -- `/memory/behavioral-enforcement/architectural-failure-analysis.md` - Comprehensive root cause analysis -- `/memory/behavioral-enforcement/enforcement-solution-architecture.md` - Complete solution design -- `/memory/behavioral-enforcement/immediate-implementation-plan.md` - Detailed implementation plan - -### Analysis Documents -- `ARCHITECTURAL_FAILURE_DIAGNOSIS.md` - Executive summary and findings (this file) - -## Relevant Files Analyzed - -### Behavioral Patterns -- `src/behaviors/agenttask-enforcement.md` - Current enforcement patterns -- `src/behaviors/shared-patterns/work-detection-patterns.md` - Work detection logic -- `src/behaviors/shared-patterns/pm-role-blocking-patterns.md` - PM role restrictions - -### Memory Patterns -- `memory/behavioral-enforcement/comprehensive-enforcement-analysis.md` - Previous analysis -- `memory/behavioral-enforcement/pattern-enforcement-limitations.md` - Known limitations -- `memory/system/behavioral-violations.md` - Documented violations - -### Hook System -- `src/hooks/user-prompt-submit.js` - Current guidance system -- `memory/architecture/optimal-hook-architecture.md` - Hook removal rationale - -### Best Practices -- `best-practices-examples/git/feature-branch-workflow.md` - Implementation standards -- `best-practices-examples/architecture/configuration-first-design.md` - Design principles - ---- -*Diagnosis completed 2025-01-21 by @AI-Engineer* -*Comprehensive analysis with immediate implementation plan ready* diff --git a/Makefile b/Makefile index 63b9d869..2699c595 100644 --- a/Makefile +++ b/Makefile @@ -41,7 +41,7 @@ help: @echo " HOST - Remote host IP (omit for local installation)" @echo " USER - Remote username (required for remote installation)" @echo " TARGET_PATH - Target path (omit for user scope ~/.claude/)" - @echo " CONFIG_FILE - Path to icc.config JSON to deploy (default icc.config.default.json)" + @echo " CONFIG_FILE - Path to icc.config JSON to deploy (optional)" @echo " MCP_CONFIG - Path to MCP servers configuration JSON file" @echo " ENV_FILE - Path to .env file with environment variables" @echo " KEY - SSH key for remote (default: ~/.ssh/id_rsa)" diff --git a/README.md b/README.md index e14571bb..2accd8d4 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,14 @@ # Intelligent Claude Code -CC‑native framework for planning‑first AgentTasks, native subagents, and minimal hooks. +CC‑native framework slimmed to what Claude Code 2 + Opus still needs. ## Current scope (v9) -- **CC‑native subagents** — no marker files, no custom role enforcement hooks. +- **Claude Code 2 + Opus focused** — keep only what CC doesn’t do natively. +- **CC‑native subagents** — no marker files or custom role‑enforcement hooks. - **Planning‑first AgentTasks** — main scope plans, subagents implement. -- **Minimal hooks only** — keep only what CC doesn’t do natively. -- **Behavior guidance** — behaviors live in the repo and are read by humans + Claude. +- **Minimal hooks** — privacy, infra safety, summary/report routing. +- **Behavior guidance** — behaviors live in the repo and guide humans + Claude. ## Included @@ -19,14 +20,6 @@ CC‑native framework for planning‑first AgentTasks, native subagents, and min - `agent-infrastructure-protection.js` — block imperative infra changes - `summary-file-enforcement.js` — route summaries/reports + block ALL‑CAPS filenames -## Removed - -- Marker‑based orchestration -- Role enforcement hooks -- Reminder hooks -- Auto‑trigger and workflow hooks -- Redundant behavior trees - ## Principles 1. **Plan first** → create AgentTask before implementation. @@ -37,9 +30,9 @@ CC‑native framework for planning‑first AgentTasks, native subagents, and min ## Core roles -@PM, @Architect, @Developer, @System‑Engineer, @DevOps‑Engineer, @Database‑Engineer, -@Security‑Engineer, @AI‑Engineer, @Web‑Designer, @QA‑Engineer, @Backend‑Tester, -@Requirements‑Engineer, @User‑Role, @Reviewer — plus dynamic specialists (e.g., @React‑Developer). +pm, architect, developer, system‑engineer, devops‑engineer, database‑engineer, +security‑engineer, ai‑engineer, web‑designer, qa‑engineer, backend‑tester, +requirements‑engineer, user‑role, reviewer — plus dynamic specialists (e.g., react‑developer). ## Install @@ -50,15 +43,18 @@ make install # or .\install.ps1 install on Windows make clean-install # force uninstall + reinstall (Linux/macOS) ``` -Usage: +Usage (if your Claude Code build supports @‑mentions, use the file names below): ```bash -@PM break down the story -@Architect review the design -@Developer implement auth -@Reviewer audit for regressions +@pm break down the story +@architect review the design +@developer implement auth +@reviewer audit for regressions ``` +If @‑mentions aren’t supported, just ask in plain language: +“Use the architect subagent to review the design.” + ## Model control (user‑configurable) Claude Code model selection remains user‑controlled. Set it via: diff --git a/ansible/roles/intelligent_claude_code/tasks/main.yml b/ansible/roles/intelligent_claude_code/tasks/main.yml index fc2a9be7..719130e6 100644 --- a/ansible/roles/intelligent_claude_code/tasks/main.yml +++ b/ansible/roles/intelligent_claude_code/tasks/main.yml @@ -186,7 +186,7 @@ when: - intelligent_claude_code_config_md_exists.stat.exists - ansible_verbosity >= 1 -- name: Copy configuration file (selected or default without overwriting user edits) +- name: Copy configuration file (selected without overwriting user edits) block: - name: Use provided config_file when specified (overwrite) ansible.builtin.copy: @@ -207,41 +207,19 @@ - claude_config_source | length == 0 - intelligent_claude_code_icc_config_exists.stat.exists - ansible_verbosity >= 1 - - name: Install default icc.config.json only if missing - ansible.builtin.copy: - src: "{{ playbook_dir }}/../icc.config.default.json" - dest: "{{ claude_install_path }}/icc.config.json" - mode: '0644' - force: false + - name: Note missing icc.config.json when none supplied + ansible.builtin.debug: + msg: "No icc.config.json provided; defaults remain internal (pass CONFIG_FILE to install)." when: - claude_config_source | length == 0 - not intelligent_claude_code_icc_config_exists.stat.exists - - name: Always install default for reference - ansible.builtin.copy: - src: "{{ playbook_dir }}/../icc.config.default.json" - dest: "{{ claude_install_path }}/icc.config.default.json" - mode: '0644' - force: true + - ansible_verbosity >= 1 - name: Display config installation choice ansible.builtin.debug: msg: >- Configuration installed or preserved at {{ claude_install_path }}/icc.config.json - (source={{ claude_config_source | default('existing or icc.config.default.json') }}) + (source={{ claude_config_source | default('existing') }}) when: ansible_verbosity >= 1 -- name: Copy default workflow configuration file (JSON format) - ansible.builtin.copy: - src: "{{ playbook_dir }}/../icc.workflow.default.json" - dest: "{{ claude_install_path }}/icc.workflow.default.json" - mode: '0644' - force: true - register: intelligent_claude_code_default_workflow_copy_result -- name: Display default workflow installation notice - ansible.builtin.debug: - msg: >- - Default workflow configuration installed: - {{ claude_install_path }}/icc.workflow.default.json - - complete workflow settings available - when: ansible_verbosity >= 1 - name: Check if settings.json exists ansible.builtin.stat: path: "{{ claude_install_path }}/settings.json" diff --git a/best-practices/development/config-loading-dual-context.md b/best-practices/development/config-loading-dual-context.md index 210f626d..901950cb 100644 --- a/best-practices/development/config-loading-dual-context.md +++ b/best-practices/development/config-loading-dual-context.md @@ -66,13 +66,13 @@ if (!config) { ```javascript // Works ONLY in production, breaks in development -const configPath = path.join(__dirname, '../..', 'icc.config.default.json'); +const configPath = path.join(__dirname, '../..', 'icc.config.json'); const config = loadJsonConfig(configPath); ``` **Result**: -- ✅ Production: Loads from `~/.claude/icc.config.default.json` -- ❌ Development: Fails - `src/icc.config.default.json` doesn't exist +- ✅ Production: Loads from `~/.claude/icc.config.json` +- ✅ Development: Loads from `repo-root/icc.config.json` (if provided) - ❌ Documentation: Examples fail - ❌ Tests: Regression tests broken @@ -80,26 +80,26 @@ const config = loadJsonConfig(configPath); ```javascript // Try production location first -let configPath = path.join(__dirname, '../..', 'icc.config.default.json'); +let configPath = path.join(__dirname, '../..', 'icc.config.json'); let config = loadJsonConfig(configPath); if (!config) { // Fallback to development location - configPath = path.join(__dirname, '../../..', 'icc.config.default.json'); + configPath = path.join(__dirname, '../../..', 'icc.config.json'); config = loadJsonConfig(configPath); } if (!config) { console.error('[config-loader] Config not found. Searched:'); - console.error('[config-loader] - ' + path.join(__dirname, '../..', 'icc.config.default.json')); - console.error('[config-loader] - ' + path.join(__dirname, '../../..', 'icc.config.default.json')); + console.error('[config-loader] - ' + path.join(__dirname, '../..', 'icc.config.json')); + console.error('[config-loader] - ' + path.join(__dirname, '../../..', 'icc.config.json')); config = getHardcodedDefaults(); } ``` **Result**: -- ✅ Production: Loads from `~/.claude/icc.config.default.json` -- ✅ Development: Loads from `repo-root/icc.config.default.json` +- ✅ Production: Loads from `~/.claude/icc.config.json` +- ✅ Development: Loads from `repo-root/icc.config.json` - ✅ Documentation: Examples work as-written - ✅ Tests: All regression tests pass diff --git a/docs/configuration-guide.md b/docs/configuration-guide.md index 346aabfe..32cc25b3 100644 --- a/docs/configuration-guide.md +++ b/docs/configuration-guide.md @@ -4,7 +4,7 @@ 1. AgentTask overrides 2. Project config: `./icc.config.json` or `./.claude/icc.config.json` 3. User config: `~/.claude/icc.config.json` -4. Defaults: `icc.config.default.json` +4. Defaults: built-in (no default file shipped) ## Key Settings diff --git a/icc.config.default.json b/icc.config.default.json deleted file mode 100644 index 95461e5b..00000000 --- a/icc.config.default.json +++ /dev/null @@ -1,366 +0,0 @@ -{ - "$schema": "./src/schemas/icc.config.schema.json", - "version": "1.0.0", - "description": "Intelligent Claude Code unified configuration with all 147+ settings", - - "autonomy": { - "level": "L2", - "pm_always_active": true, - "l3_settings": { - "max_parallel": 5, - "auto_discover": true, - "continue_on_error": true - } - }, - - "git": { - "privacy": true, - "privacy_patterns": [ - "AI", - "Claude", - "agent", - "Generated with Claude Code", - "Co-Authored-By: Claude" - ], - "branch_protection": true, - "default_branch": "main", - "require_pr_for_main": true, - "validate_commits": true - }, - - "paths": { - "story_path": "stories", - "bug_path": "bugs", - "memory_path": "memory", - "docs_path": "docs", - "src_path": "src", - "test_path": "tests", - "config_path": "config", - "agenttask_template_path": "agenttask-templates", - "summaries_path": "summaries" - }, - - "team": { - "default_reviewer": "@Architect", - "specialist_creation": true, - "role_validation": true - }, - - "agenttask": { - "template_validation": true, - "complexity_override": false, - "auto_breakdown": true, - "size_limits": { - "nano": { "min": 0, "max": 2 }, - "tiny": { "min": 3, "max": 5 }, - "medium": { "min": 6, "max": 15 }, - "large": { "min": 16, "max": 30 }, - "mega": { "min": 31, "max": 999 } - } - }, - - "memory": { - "integration": true, - "auto_storage": true, - "search_before_questions": true, - "max_search_results": 3, - "max_search_tokens": 1000, - "relevance_threshold": 6 - }, - - "quality": { - "enforce_peer_review": true, - "testing_required": true, - "documentation_required": true, - "security_validation": true, - "compliance_checking": true - }, - - "development": { - "auto_cleanup": true, - "file_management_strict": true, - "testing_approach": "comprehensive" - }, - - "tools": { - "context7_enabled": true, - "sequential_thinking": true, - "mcp_tools_enabled": true - }, - - "subagents": { - "model": "sonnet", - "threshold": 3, - "max_concurrent": 5, - "auto_delegation": true - }, - - "project": { - "repository_type": "git", - "release_automation": true - }, - - "enforcement": { - "blocking_enabled": true, - "allow_markdown_outside_allowlist": false, - "allow_markdown_outside_allowlist_agents": null, - "allow_parent_allowlist_paths": false, - "violation_logging": true, - "auto_correction": true, - "main_scope_has_agent_privileges": false, - "workflow": { - "enabled": false, - "steps": [ - { "name": "Task", "tools": ["Task"] }, - { "name": "Plan", "tools": ["Plan"] }, - { "name": "Review Plan", "tools": ["Review"] }, - { "name": "Execute", "tools": ["Execute"] }, - { "name": "Review Execute", "tools": ["Review"] }, - { "name": "Document", "tools": ["Document", "Write", "Edit"] } - ] - }, - "strict_main_scope": true, - "strict_main_scope_message": "Main scope is limited to coordination work only. Create AgentTasks via Task tool for all technical operations.", - "pm_allowed_bash_commands": [ - "git status", - "git log", - "git diff", - "git show", - "git branch", - "git config", - "git remote", - "git tag", - "gh pr list", - "gh pr view", - "gh pr status", - "gh issue list", - "gh issue view" - ], - "tool_blacklist": { - "universal": [ - "rm -rf /", - "dd if=/dev/zero of=/dev/sda", - "mkfs", - "fdisk /dev/sda", - "> /dev/sda", - "format c:" - ], - "main_scope_only": [ - "Write", - "Edit", - "MultiEdit", - "NotebookEdit" - ], - "agents_only": [ - "Task", - "SlashCommand", - "Skill" - ], - "infrastructure": [ - "govc", - "esxcli", - "vcsa-cli", - "virsh", - "vboxmanage", - "qm", - "pct", - "multipass", - "vagrant", - "packer", - "kubectl", - "helm", - "terraform", - "ansible-playbook", - "docker", - "docker-compose", - "az", - "gcloud", - "aws" - ] - }, - "allowed_allcaps_files": [ - "README.md", - "LICENSE", - "LICENSE.md", - "CLAUDE.md", - "CHANGELOG.md", - "CONTRIBUTING.md", - "AUTHORS", - "NOTICE", - "PATENTS", - "VERSION", - "MAKEFILE", - "DOCKERFILE", - "COPYING", - "COPYRIGHT" - ], - "heredoc_allowed_commands": [ - "git", - "gh", - "glab", - "hub" - ], - "auto_commit_review": { - "enabled": false, - "command": "@codex review" - }, - "infrastructure_protection": { - "enabled": true, - "enforce_iac_only": true, - "emergency_override_enabled": false, - "read_operations_allowed": true, - "imperative_destructive": [ - "govc vm.destroy", - "govc vm.remove", - "govc pool.destroy", - "govc datastore.rm", - "esxcli vm process kill", - "virsh destroy", - "virsh undefine", - "vboxmanage unregistervm", - "qm destroy", - "pct destroy", - "multipass delete", - "vagrant destroy", - "kubectl delete", - "kubectl drain", - "kubectl cordon", - "Remove-VM", - "Remove-VirtualDisk", - "Remove-VMHardDiskDrive", - "Remove-VMSnapshot", - "Remove-AzVM", - "Remove-AzDisk" - ], - "write_operations": [ - "govc vm.power", - "govc vm.shutdown", - "govc vm.reboot", - "govc vm.create", - "govc host.shutdown", - "govc host.reboot", - "esxcli system shutdown", - "esxcli system reboot", - "virsh shutdown", - "virsh reboot", - "virsh start", - "vboxmanage controlvm", - "vboxmanage startvm", - "qm shutdown", - "qm reboot", - "qm start", - "pct shutdown", - "pct reboot", - "pct start", - "multipass stop", - "multipass start", - "vagrant halt", - "vagrant reload", - "vagrant up", - "kubectl apply", - "kubectl create", - "kubectl patch", - "kubectl scale", - "kubectl set", - "Start-VM", - "Stop-VM", - "Restart-VM", - "Suspend-VM", - "Resume-VM", - "New-VM", - "Set-VM", - "Start-Service", - "Stop-Service", - "Restart-Service", - "New-AzVM", - "Start-AzVM", - "Stop-AzVM", - "Restart-AzVM" - ], - "read_operations": [ - "govc vm.info", - "govc ls", - "govc find", - "esxcli system version", - "virsh list", - "virsh dominfo", - "vboxmanage list", - "qm list", - "qm status", - "pct list", - "pct status", - "multipass list", - "multipass info", - "vagrant status", - "kubectl get", - "kubectl describe", - "kubectl logs", - "kubectl top", - "kubectl explain", - "Get-VM", - "Get-VMHost", - "Get-VMSwitch", - "Get-VMNetworkAdapter", - "Get-VirtualDisk", - "Get-VMHardDiskDrive", - "Get-VMSnapshot", - "Get-Service", - "Get-AzVM", - "Get-AzDisk", - "Get-AzResource" - ], - "whitelist": [], - "emergency_override_token": "" - } - }, - - "best_practices": { - "search_enabled": true, - "auto_generation": true, - "promotion_threshold": 3, - "categories": [ - "architecture", - "collaboration", - "development", - "git", - "operations", - "quality", - "security" - ] - }, - - "mcp_integrations": { - "memory": { - "provider": "mcp__memory", - "enabled": false, - "fallback": "file-based", - "config": {} - }, - "issue_tracking": { - "provider": "mcp__github", - "enabled": false, - "fallback": "file-based", - "config": {} - }, - "documentation": { - "provider": "file-based", - "enabled": true, - "fallback": "file-based", - "config": { - "base_path": "docs/" - } - } - }, - - "cache": { - "ttl_minutes": 5, - "enabled": true - }, - - "logging": { - "enabled": true, - "retention_hours": 24, - "directory": "~/.claude/logs", - "agent_marker_log_level": "INFO" - } -} diff --git a/icc.workflow.default.json b/icc.workflow.default.json deleted file mode 100644 index 759b1b94..00000000 --- a/icc.workflow.default.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "$schema": "./src/schemas/icc.workflow.schema.json", - "version": "1.0.0", - "description": "Workflow settings by AgentTask complexity tier", - - "nano": { - "version_bump": false, - "changelog_required": false, - "pr_required": false, - "merge_strategy": "direct_commit", - "release_automation": false - }, - - "tiny": { - "version_bump": true, - "version_type": "patch", - "changelog_required": true, - "pr_required": false, - "merge_strategy": "direct_commit", - "release_automation": false - }, - - "medium": { - "version_bump": true, - "version_type": "minor", - "changelog_required": true, - "pr_required": true, - "merge_strategy": "feature_branch", - "release_automation": true, - "auto_merge": false - }, - - "large": { - "version_bump": true, - "version_type": "minor", - "changelog_required": true, - "pr_required": true, - "merge_strategy": "feature_branch", - "release_automation": true, - "auto_merge": false, - "coordination_required": true - }, - - "mega": { - "version_bump": true, - "version_type": "major", - "changelog_required": true, - "pr_required": true, - "merge_strategy": "feature_branch", - "release_automation": true, - "auto_merge": false, - "coordination_required": true, - "breaking_change_assessment": true - } -} diff --git a/install.ps1 b/install.ps1 index 3aaaa6d6..2f32e379 100644 --- a/install.ps1 +++ b/install.ps1 @@ -26,7 +26,7 @@ function Show-Help { Write-Host "Parameters:" -ForegroundColor Yellow Write-Host " -TargetPath - Target path (omit for user scope ~\.claude\)" Write-Host " -McpConfig - Path to MCP servers configuration JSON file" - Write-Host " -ConfigFile - Path to icc.config JSON to install (fallback: icc.config.default.json)" + Write-Host " -ConfigFile - Path to icc.config JSON to install (optional)" Write-Host " -Force - Force complete removal including user data (uninstall only)" Write-Host "" Write-Host "Examples:" -ForegroundColor Green @@ -349,7 +349,6 @@ function Install-IntelligentClaudeCode { } # Install configuration file (custom or default) - $DefaultConfigPath = Join-Path $PSScriptRoot "icc.config.default.json" $TargetConfigPath = Join-Path $Paths.InstallPath "icc.config.json" if ($ConfigFile -and (Test-Path $ConfigFile)) { @@ -357,15 +356,12 @@ function Install-IntelligentClaudeCode { Write-Host "Config installed from: $ConfigFile" -ForegroundColor Yellow } else { if (-not (Test-Path $TargetConfigPath)) { - Copy-Item -Path $DefaultConfigPath -Destination $TargetConfigPath -Force - Write-Host "Config installed from: $DefaultConfigPath" -ForegroundColor Yellow + Write-Host "No config installed (pass -ConfigFile to add icc.config.json)" -ForegroundColor Yellow } else { Write-Host "Preserving existing icc.config.json (pass -ConfigFile to override)" -ForegroundColor Yellow } } - Copy-Item -Path $DefaultConfigPath -Destination (Join-Path $Paths.InstallPath "icc.config.default.json") -Force - # Install MCP configuration if provided if ($McpConfig -and (Test-Path $McpConfig)) { Write-Host "Installing MCP configuration..." -ForegroundColor Yellow diff --git a/pr-body.md b/pr-body.md deleted file mode 100644 index d1a6470e..00000000 --- a/pr-body.md +++ /dev/null @@ -1,12 +0,0 @@ -## Summary -- Describe the change in 1-3 bullets - -## Changes -- [ ] Key files updated -- [ ] Tests updated or noted - -## Impact -- Behavior changes -- Risk areas -- Rollback notes - diff --git a/src/behaviors/config-system.md b/src/behaviors/config-system.md index cbc2c4a0..441932d5 100644 --- a/src/behaviors/config-system.md +++ b/src/behaviors/config-system.md @@ -6,7 +6,7 @@ 1. Embedded AgentTask overrides 2. Project config: `./icc.config.json` or `./.claude/icc.config.json` 3. User config: `~/.claude/icc.config.json` -4. System defaults: `icc.config.default.json` +4. System defaults: built-in (no default file shipped) ## Key Settings - `git.*` (privacy, branch protection, PR requirement) diff --git a/src/behaviors/shared-patterns/configuration-patterns.md b/src/behaviors/shared-patterns/configuration-patterns.md index cdfb5263..978744a6 100644 --- a/src/behaviors/shared-patterns/configuration-patterns.md +++ b/src/behaviors/shared-patterns/configuration-patterns.md @@ -6,7 +6,7 @@ 1. AgentTask overrides 2. Project config (`./icc.config.json` or `./.claude/icc.config.json`) 3. User config (`~/.claude/icc.config.json`) -4. Defaults (`icc.config.default.json`) +4. Defaults (built-in; no default file shipped) ## Key Areas - `git.*`, `paths.*`, `team.*`, `agenttask.*`, `models.*` diff --git a/src/commands/icc-get-setting.md b/src/commands/icc-get-setting.md index 25ffa6dc..df73181e 100644 --- a/src/commands/icc-get-setting.md +++ b/src/commands/icc-get-setting.md @@ -27,7 +27,7 @@ Gets setting value from configuration hierarchy with dot notation support. - Embedded configs (highest priority) - Project config (./icc.config.json or ./.claude/icc.config.json) - User config (~/.claude/icc.config.json) - - System defaults (icc.config.default.json) + - System defaults (built-in; no default file shipped) 3. Support dot notation for nested values 4. Validate critical settings (git_privacy MUST be boolean) 5. Return first found value or default diff --git a/src/hooks/lib/config-loader.js b/src/hooks/lib/config-loader.js index 1764fe7c..1770eaa0 100644 --- a/src/hooks/lib/config-loader.js +++ b/src/hooks/lib/config-loader.js @@ -3,7 +3,7 @@ /** * Unified Configuration Loader for Intelligent Claude Code * - * Hierarchy: ./icc.config.json → ~/.claude/icc.config.json → icc.config.default.json + * Hierarchy: ./icc.config.json → ~/.claude/icc.config.json → built-in defaults * Backward compatibility: Falls back to CLAUDE.md/config.md if icc.config.json missing * 5-minute TTL cache for performance */ @@ -207,26 +207,9 @@ function findConfigFile(projectRoot, filename) { * Load workflow configuration from hierarchy */ function loadWorkflowConfig() { - // 1. Load default workflow configuration - // Try installed location first (~/.claude/), then repo root (for testing) - let defaultWorkflowPath = path.join(__dirname, '../..', 'icc.workflow.default.json'); - let workflowConfig = loadJsonConfig(defaultWorkflowPath); - - if (!workflowConfig) { - // Fallback to repo root for local development/testing - defaultWorkflowPath = path.join(__dirname, '../../..', 'icc.workflow.default.json'); - workflowConfig = loadJsonConfig(defaultWorkflowPath); - } - - if (!workflowConfig) { - console.error('[config-loader] CRITICAL: Default workflow configuration not found'); - console.error('[config-loader] Searched paths:'); - console.error('[config-loader] - ' + path.join(__dirname, '../..', 'icc.workflow.default.json')); - console.error('[config-loader] - ' + path.join(__dirname, '../../..', 'icc.workflow.default.json')); - workflowConfig = {}; - } + let workflowConfig = {}; - // 2. Try to load user global workflow configuration + // 1. Try to load user global workflow configuration const userWorkflowPath = findConfigFile(path.join(os.homedir(), '.claude'), 'icc.workflow.json'); if (userWorkflowPath) { const userWorkflow = loadJsonConfig(userWorkflowPath); @@ -235,7 +218,7 @@ function loadWorkflowConfig() { } } - // 3. Try to load project workflow configuration + // 2. Try to load project workflow configuration const projectWorkflowPath = findConfigFile(process.cwd(), 'icc.workflow.json'); if (projectWorkflowPath) { const projectWorkflow = loadJsonConfig(projectWorkflowPath); @@ -258,24 +241,8 @@ function loadConfig() { return configCache; } - // 1. Load default configuration - // Try installed location first (~/.claude/), then repo root (for testing) - let defaultConfigPath = path.join(__dirname, '../..', 'icc.config.default.json'); - let config = loadJsonConfig(defaultConfigPath); - - if (!config) { - // Fallback to repo root for local development/testing - defaultConfigPath = path.join(__dirname, '../../..', 'icc.config.default.json'); - config = loadJsonConfig(defaultConfigPath); - } - - if (!config) { - console.error('[config-loader] CRITICAL: Default configuration not found'); - console.error('[config-loader] Searched paths:'); - console.error('[config-loader] - ' + path.join(__dirname, '../..', 'icc.config.default.json')); - console.error('[config-loader] - ' + path.join(__dirname, '../../..', 'icc.config.default.json')); - config = getHardcodedDefaults(); - } + // 1. Load hardcoded defaults + let config = getHardcodedDefaults(); // 2. Try to load user global configuration const userConfigPath = findConfigFile(path.join(os.homedir(), '.claude'), 'icc.config.json'); diff --git a/tests/run-tests.sh b/tests/run-tests.sh index d7fbb592..0b25d12b 100755 --- a/tests/run-tests.sh +++ b/tests/run-tests.sh @@ -5,7 +5,7 @@ set -e # Ensure deterministic context during tests (main scope raised to agent only when explicitly set) export ICC_MAIN_SCOPE_AGENT=false export CLAUDE_DISABLE_MAIN_INFRA_BYPASS=1 -export CLAUDE_CONFIG_PATH="$(cd "$(dirname "$0")/.." && pwd)/icc.config.default.json" +export CLAUDE_CONFIG_PATH="$(cd "$(dirname "$0")/.." && pwd)/sample-configs/icc.config.relaxed.json" export ICC_TEST_MARKER_DIR="$(mktemp -d)" echo "🧪 Running intelligent-claude-code hook tests..." From 69db4667317242d43ddf7d69f7559543a9169360 Mon Sep 17 00:00:00 2001 From: Karsten Samaschke Date: Fri, 9 Jan 2026 05:19:48 +0100 Subject: [PATCH 02/26] Remove best-practices references --- CHANGELOG.md | 2 +- best-practices-examples/README.md | 98 -- best-practices-examples/TEMPLATE.md | 180 --- .../configuration-first-design.md | 67 - .../collaboration/agile-practices.md | 98 -- .../development/clean-code-practices.md | 52 - .../development/test-driven-development.md | 89 -- .../git/feature-branch-workflow.md | 218 ---- .../operations/gitops-practices.md | 67 - .../quality/code-review-standards.md | 80 -- .../security/secure-coding-practices.md | 89 -- best-practices/README.md | 26 - .../config-loading-dual-context.md | 305 ----- best-practices/git-workflow-patterns.md | 264 ---- .../git/version-bump-and-release.md | 72 -- best-practices/memory-storage-retrieval.md | 209 ---- best-practices/release-workflow-automation.md | 1106 ----------------- docs/agenttask-system-guide.md | 19 +- docs/agenttask-templates-guide.md | 4 +- docs/best-practices-guide.md | 228 ---- docs/directory-structure.md | 9 +- docs/project-configuration.md | 13 +- .../medium-agenttask-template.yaml | 3 +- .../tiny-agenttask-template.yaml | 3 +- src/commands/icc-search-memory.md | 4 +- src/modes/virtual-team.md | 3 - .../test-story-file-classification.js | 2 +- 27 files changed, 13 insertions(+), 3297 deletions(-) delete mode 100644 best-practices-examples/README.md delete mode 100644 best-practices-examples/TEMPLATE.md delete mode 100644 best-practices-examples/architecture/configuration-first-design.md delete mode 100644 best-practices-examples/collaboration/agile-practices.md delete mode 100644 best-practices-examples/development/clean-code-practices.md delete mode 100644 best-practices-examples/development/test-driven-development.md delete mode 100644 best-practices-examples/git/feature-branch-workflow.md delete mode 100644 best-practices-examples/operations/gitops-practices.md delete mode 100644 best-practices-examples/quality/code-review-standards.md delete mode 100644 best-practices-examples/security/secure-coding-practices.md delete mode 100644 best-practices/README.md delete mode 100644 best-practices/development/config-loading-dual-context.md delete mode 100644 best-practices/git-workflow-patterns.md delete mode 100644 best-practices/git/version-bump-and-release.md delete mode 100644 best-practices/memory-storage-retrieval.md delete mode 100644 best-practices/release-workflow-automation.md delete mode 100644 docs/best-practices-guide.md diff --git a/CHANGELOG.md b/CHANGELOG.md index ddb5fa44..cd140ed1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -113,7 +113,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - ALL-CAPS filename enforcement retains execution-pattern guidance while auto-suggesting lowercase/kebab alternatives. ### Changed -- All sample configs now force best-practices/constraints output and keep memory integration plus git branch protection enabled. +- All sample configs now force constraints output and keep memory integration plus git branch protection enabled. - Main-scope coordination whitelist can be extended via `enforcement.main_scope_allowed_bash_commands` so presets can safely allow additional `gh`/`git` commands. - README highlights the available presets for quick reference. - Context-injection now instructs the Main Scope to start every response with the rendered constraints + best-practice block so users see the guardrails continuously. diff --git a/best-practices-examples/README.md b/best-practices-examples/README.md deleted file mode 100644 index 6b081219..00000000 --- a/best-practices-examples/README.md +++ /dev/null @@ -1,98 +0,0 @@ -# Best Practices System - -**Dynamic injection system for methodological approaches into AgentTask generation** - -## Overview - -The best-practices system automatically discovers and injects methodological approaches and practices into AgentTasks during generation. This system follows the same auto-discovery pattern as the memory system but focuses on process and practice guidance. - -## Directory Structure - -``` -best-practices/ -├── development/ # Coding practices (TDD, Clean Code, SOLID) -├── architecture/ # Design patterns and architectural principles -├── operations/ # DevOps, GitOps, Infrastructure practices -├── security/ # DevSecOps, security practices -├── quality/ # Quality assurance methodologies -└── collaboration/ # Team practices and coordination -``` - -## Auto-Discovery Process - -During AgentTask generation, the system: - -1. **Scans best-practices/** directory for relevant practice files -2. **Matches practices** to work type and complexity -3. **Injects top 2-3 practices** into AgentTask context (max 800 tokens) -4. **Replaces template placeholders** with dynamic content - -## Practice File Format - -Create `.md` files in appropriate subdirectories: - -```markdown -# Practice Name - -**Type:** [development|architecture|operations|security|quality|collaboration] -**Applies To:** [complexity_levels, work_types] -**Keywords:** keyword1, keyword2, keyword3 - -## Description -Brief description of the practice - -## Implementation -Specific guidance for this practice - -## Quality Gates -- [ ] Checklist item 1 -- [ ] Checklist item 2 - -## Examples -Code or configuration examples -``` - -## Integration with AgentTask Generation - -The system automatically: -- **Discovers** relevant practices based on work request analysis -- **Scores** practices by relevance, recency, and project context -- **Embeds** selected practices into AgentTask complete_context -- **Replaces** template placeholders like `[CODING_STYLE]` with actual practice content - -## Supported Methodologies - -The system supports ANY methodological approach: -- **GitOps** (operations/gitops-practices.md) -- **Configuration-First** (architecture/config-first-design.md) -- **DevSecOps** (security/devsecops-integration.md) -- **Test-Driven Development** (development/tdd-practices.md) -- **Clean Architecture** (architecture/clean-architecture.md) -- **Infrastructure as Code** (operations/iac-practices.md) - -## Usage - -1. **Add practices**: Create `.md` files in appropriate subdirectories -2. **Use keywords**: Include relevant keywords for auto-discovery -3. **Specify scope**: Define what work types and complexity levels apply -4. **Let system work**: AgentTask generation automatically discovers and injects - -## Template Integration - -Replaces hardcoded placeholders: -- `[PROJECT_CODING_STYLE]` → Dynamic coding practices -- `[ARCHITECTURE_CONSTRAINTS]` → Relevant architectural practices -- `[QUALITY_STANDARDS]` → Applicable quality practices -- `[SECURITY_REQUIREMENTS]` → Security practice guidelines - -## No Manual Template Modification - -The system eliminates the need to modify AgentTask templates for customization. Simply add practice files and the auto-discovery mechanism handles injection automatically. - -## Version Control - -All best-practices are version controlled with the project, enabling: -- **Team consistency** across all AgentTask executions -- **Practice evolution** through normal git workflows -- **Project-specific** customization without system modification -- **Knowledge sharing** through documented practices \ No newline at end of file diff --git a/best-practices-examples/TEMPLATE.md b/best-practices-examples/TEMPLATE.md deleted file mode 100644 index 7255786a..00000000 --- a/best-practices-examples/TEMPLATE.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -category: [CATEGORY] -tags: [TAG1, TAG2, TAG3] -created: [CREATION_DATE] -source_operation: [SOURCE_AgentTask_OR_OPERATION] -quality_score: [QUALITY_SCORE] -usage_count: 0 -effectiveness_rating: unrated -last_updated: [CREATION_DATE] ---- - -# [PRACTICE_NAME] - -## Overview -[BRIEF_DESCRIPTION_OF_PRACTICE] - -## Problem Statement -This practice addresses [SPECIFIC_CHALLENGE] that occurs when [CONTEXT_OR_SITUATION]. - -### Symptoms -- [OBSERVABLE_INDICATOR_1] -- [OBSERVABLE_INDICATOR_2] -- [COMMON_FAILURE_PATTERN] - -### Impact -Without this practice, teams typically experience [CONSEQUENCES_OF_NOT_FOLLOWING_PRACTICE]. - -## Solution Approach - -### Overview -[HIGH_LEVEL_DESCRIPTION_OF_SOLUTION_APPROACH] - -### Steps -1. **[STEP_NAME]:** [DETAILED_INSTRUCTION] - - **Validation:** [HOW_TO_VERIFY_STEP_COMPLETION] - - **If problems:** [RECOVERY_APPROACH] - - **Prerequisites:** [WHAT_MUST_BE_IN_PLACE] - -2. **[STEP_NAME]:** [DETAILED_INSTRUCTION] - - **Expected outcome:** [WHAT_SHOULD_RESULT] - - **Quality check:** [VALIDATION_CRITERIA] - -3. **[STEP_NAME]:** [DETAILED_INSTRUCTION] - - **Critical factors:** [ESSENTIAL_ELEMENTS_FOR_SUCCESS] - - **Common mistakes:** [PITFALLS_TO_AVOID] - -### Quality Gates -- [ ] [CRITICAL_VALIDATION_POINT_1] -- [ ] [CRITICAL_VALIDATION_POINT_2] -- [ ] [SUCCESS_CRITERIA_CHECKPOINT] -- [ ] [FINAL_VERIFICATION_STEP] - -## Examples - -### Scenario 1: [SPECIFIC_CONTEXT] -**Situation:** [DESCRIPTION_OF_WHEN_TO_APPLY] - -**Application:** -```bash -[SPECIFIC_COMMANDS_OR_STEPS] -``` - -**Outcome:** [EXPECTED_RESULTS] - -**Key Success Factors:** -- [CRITICAL_ELEMENT_1] -- [CRITICAL_ELEMENT_2] - -### Scenario 2: [DIFFERENT_CONTEXT] -**Situation:** [ALTERNATIVE_APPLICATION_CONTEXT] - -**Adaptation:** -[DESCRIPTION_OF_HOW_PRACTICE_ADAPTS_TO_DIFFERENT_CONTEXT] - -**Results:** [OUTCOMES_IN_THIS_CONTEXT] - -## When to Use - -### Ideal Conditions -- [CONDITION_1_FOR_OPTIMAL_APPLICATION] -- [CONDITION_2_FOR_SUCCESS] -- [ENVIRONMENTAL_REQUIREMENT] - -### Prerequisites -- [REQUIRED_TOOL_OR_KNOWLEDGE_OR_PERMISSION] -- [SYSTEM_STATE_REQUIREMENT] -- [TEAM_COORDINATION_NEED] - -### Not Recommended When -- [SITUATION_WHERE_PRACTICE_DOESNT_APPLY] -- [CONSTRAINT_THAT_PREVENTS_EFFECTIVE_USE] -- [ALTERNATIVE_APPROACH_MORE_SUITABLE] - -## Variations and Adaptations - -### For Small Teams -[HOW_TO_ADAPT_FOR_SMALLER_SCALE_OPERATIONS] - -### For Large Projects -[SCALING_CONSIDERATIONS_FOR_LARGER_OPERATIONS] - -### Tool-Specific Adaptations -- **[TOOL_NAME]:** [SPECIFIC_ADAPTATIONS_NEEDED] -- **[TOOL_NAME]:** [ALTERNATIVE_APPROACHES_WITH_DIFFERENT_TOOLS] - -## Common Pitfalls - -### Mistake: [COMMON_ERROR_1] -**Why it happens:** [ROOT_CAUSE_OF_ERROR] -**Prevention:** [HOW_TO_AVOID_THIS_ERROR] -**Recovery:** [HOW_TO_FIX_IF_ERROR_OCCURS] - -### Mistake: [COMMON_ERROR_2] -**Symptoms:** [HOW_TO_RECOGNIZE_THIS_ERROR] -**Impact:** [CONSEQUENCES_OF_THIS_ERROR] -**Solution:** [CORRECTIVE_ACTION_TO_TAKE] - -## Success Metrics - -### Quantitative Indicators -- [MEASURABLE_SUCCESS_METRIC_1] -- [MEASURABLE_SUCCESS_METRIC_2] -- [PERFORMANCE_BENCHMARK] - -### Qualitative Indicators -- [OBSERVABLE_QUALITY_IMPROVEMENT] -- [SUBJECTIVE_SUCCESS_INDICATOR] -- [TEAM_SATISFACTION_MEASURE] - -## Related Practices - -### Complementary Practices -- **[RELATED_PRACTICE_1]:** [HOW_THEY_WORK_TOGETHER] -- **[RELATED_PRACTICE_2]:** [SYNERGISTIC_BENEFITS] - -### Alternative Approaches -- **[ALTERNATIVE_1]:** [WHEN_TO_USE_INSTEAD] -- **[ALTERNATIVE_2]:** [TRADE_OFFS_TO_CONSIDER] - -## References and Resources - -### Source Operations -- [SOURCE_AgentTask_OR_OPERATION_1]: [BRIEF_DESCRIPTION_OF_SOURCE] -- [SOURCE_AgentTask_OR_OPERATION_2]: [CONTEXT_OF_SUCCESSFUL_APPLICATION] - -### External Resources -- [EXTERNAL_DOCUMENTATION_LINK]: [DESCRIPTION_OF_RESOURCE] -- [TOOL_DOCUMENTATION]: [RELEVANT_SECTIONS] - -### Learning Patterns -- [MEMORY_ENTITY_REFERENCE]: [RELATED_LEARNING_OR_PATTERN] - -## Revision History - -### [DATE] - v1.0 -- Initial creation from [SOURCE_OPERATION] -- [NOTABLE_ELEMENTS_OF_INITIAL_VERSION] - -### [DATE] - v1.1 (Template) -- [DESCRIPTION_OF_UPDATES_WHEN_PRACTICE_IS_REVISED] -- [RATIONALE_FOR_CHANGES] - -## Usage Tracking - -### Applications -- **Date:** [APPLICATION_DATE] | **Context:** [WHERE_APPLIED] | **Outcome:** [RESULTS] -- **Date:** [APPLICATION_DATE] | **Context:** [WHERE_APPLIED] | **Outcome:** [RESULTS] - -### Effectiveness Rating -**Current Rating:** [UNRATED/EXCELLENT/GOOD/NEEDS_IMPROVEMENT] -**Based on:** [NUMBER_OF_APPLICATIONS] applications -**Last Review:** [REVIEW_DATE] - -### Improvement Opportunities -- [IDENTIFIED_ENHANCEMENT_OPPORTUNITY_1] -- [IDENTIFIED_ENHANCEMENT_OPPORTUNITY_2] - ---- - -*This template provides the structure for all best practice documents generated from successful operational patterns. Each section should be completed with specific, actionable content relevant to the identified practice.* \ No newline at end of file diff --git a/best-practices-examples/architecture/configuration-first-design.md b/best-practices-examples/architecture/configuration-first-design.md deleted file mode 100644 index 9efbd7cd..00000000 --- a/best-practices-examples/architecture/configuration-first-design.md +++ /dev/null @@ -1,67 +0,0 @@ -# Configuration-First Design - -**Type:** architecture -**Applies To:** medium, large, mega -**Keywords:** configuration, design, architecture, flexibility, maintainability - -## Description - -Design approach that prioritizes external configuration over hardcoded values to enable flexible, maintainable systems. - -## Implementation - -### External Configuration -- All environment-specific values externalized -- Configuration hierarchy: runtime → file → defaults -- Validation of configuration at startup -- Hot-reload capabilities where appropriate - -### Configuration Structure -- Hierarchical configuration organization -- Environment-specific overrides -- Secure handling of sensitive values -- Configuration documentation and schemas - -### Design Principles -- Favor composition over inheritance -- Dependency injection for configurability -- Interface-based design for swappable components -- Configuration-driven behavior selection - -## Quality Gates -- [ ] No hardcoded environment-specific values -- [ ] Configuration validation implemented -- [ ] Configuration hierarchy documented -- [ ] Sensitive values properly secured -- [ ] Configuration schema defined -- [ ] Hot-reload tested where applicable - -## Examples - -### Configuration Hierarchy -```yaml -# config/defaults.yaml -database: - connection_timeout: 30 - pool_size: 10 - -# config/production.yaml -database: - host: prod-db.example.com - pool_size: 50 - -# config/development.yaml -database: - host: localhost - pool_size: 5 -``` - -### Environment Variable Override -```javascript -const config = { - database: { - host: process.env.DB_HOST || config.database.host, - port: process.env.DB_PORT || config.database.port - } -}; -``` \ No newline at end of file diff --git a/best-practices-examples/collaboration/agile-practices.md b/best-practices-examples/collaboration/agile-practices.md deleted file mode 100644 index 82551136..00000000 --- a/best-practices-examples/collaboration/agile-practices.md +++ /dev/null @@ -1,98 +0,0 @@ -# Agile Development Practices - -**Type:** collaboration -**Applies To:** medium, large, mega -**Keywords:** agile, scrum, collaboration, iterative, feedback, continuous improvement - -## Description - -Agile development practices for iterative delivery, team collaboration, and continuous improvement. - -## Implementation - -### Sprint Planning -- Break work into manageable user stories -- Estimate effort using story points or time-boxing -- Commit to realistic sprint goals -- Define clear acceptance criteria for each story - -### Daily Standups -- Share progress, blockers, and next steps -- Keep meetings focused and time-boxed (15 minutes) -- Identify impediments and address them quickly -- Foster team communication and coordination - -### Retrospectives -- Regular reflection on team processes and practices -- Identify what's working well and what needs improvement -- Create action items for continuous improvement -- Celebrate successes and learn from failures - -### Continuous Delivery -- Integrate code frequently to avoid merge conflicts -- Automate testing and deployment pipelines -- Deliver working software in short iterations -- Gather feedback early and often - -## Quality Gates -- [ ] User stories have clear acceptance criteria -- [ ] Sprint goals are realistic and achievable -- [ ] Daily standups occur and are productive -- [ ] Retrospectives held regularly with action items -- [ ] Code integrated frequently (multiple times per day) -- [ ] Automated testing pipeline in place -- [ ] Working software delivered each iteration -- [ ] Customer feedback incorporated regularly - -## Examples - -### User Story Template -``` -As a [user type] -I want [functionality] -So that [benefit/value] - -Acceptance Criteria: -- [ ] Criterion 1 -- [ ] Criterion 2 -- [ ] Criterion 3 - -Definition of Done: -- [ ] Code written and reviewed -- [ ] Tests written and passing -- [ ] Documentation updated -- [ ] Deployed to staging environment -``` - -### Daily Standup Format -``` -Yesterday: -- Completed user authentication feature -- Fixed bug in payment processing - -Today: -- Working on user profile management -- Will review PRs from team members - -Blockers: -- Waiting for API documentation from external team -- Need access to staging database -``` - -### Sprint Retrospective Format -``` -What went well: -- Great collaboration on complex feature -- Automated testing caught several bugs -- Customer feedback was very positive - -What could be improved: -- Communication about API changes -- Code review turnaround time -- Sprint planning estimation accuracy - -Action items: -- Implement API change notification process -- Set up review reminders in Slack -- Use story point poker for better estimates -``` \ No newline at end of file diff --git a/best-practices-examples/development/clean-code-practices.md b/best-practices-examples/development/clean-code-practices.md deleted file mode 100644 index ce975483..00000000 --- a/best-practices-examples/development/clean-code-practices.md +++ /dev/null @@ -1,52 +0,0 @@ -# Clean Code Practices - -**Type:** development -**Applies To:** tiny, medium, large, mega -**Keywords:** code quality, readability, maintainability, clean code - -## Description - -Clean code principles for readable, maintainable, and robust software development. - -## Implementation - -### Naming Conventions -- Use descriptive, searchable names -- Avoid mental mapping and abbreviations -- Use pronounceable names -- Use intention-revealing names - -### Function Design -- Functions should be small (20 lines max preferred) -- Functions should do one thing -- Use descriptive function names -- Minimize function arguments (3 max preferred) - -### Code Organization -- Organize code by feature, not by file type -- Keep related code close together -- Use consistent indentation and formatting -- Remove commented-out code - -## Quality Gates -- [ ] All functions have clear, descriptive names -- [ ] No function exceeds 30 lines -- [ ] No more than 3 parameters per function -- [ ] No commented-out code remains -- [ ] Code follows consistent formatting standards -- [ ] All variables have intention-revealing names - -## Examples - -### Good Function Naming -```javascript -function calculateMonthlyPayment(principal, interestRate, termInMonths) { - // Implementation -} -``` - -### Good Variable Naming -```javascript -const userAccount = getUserAccount(userId); -const isAccountActive = account.status === 'active'; -``` \ No newline at end of file diff --git a/best-practices-examples/development/test-driven-development.md b/best-practices-examples/development/test-driven-development.md deleted file mode 100644 index f89cb1d8..00000000 --- a/best-practices-examples/development/test-driven-development.md +++ /dev/null @@ -1,89 +0,0 @@ -# Test-Driven Development (TDD) - -**Type:** development -**Applies To:** medium, large, mega -**Keywords:** testing, tdd, red-green-refactor, unit tests, quality - -## Description - -Test-Driven Development approach using the Red-Green-Refactor cycle to drive design and ensure comprehensive test coverage. - -## Implementation - -### Red-Green-Refactor Cycle -- **Red**: Write a failing test that captures the desired functionality -- **Green**: Write the minimum code to make the test pass -- **Refactor**: Improve code structure while keeping tests passing - -### Test Structure -- Use descriptive test names that explain behavior -- Follow Arrange-Act-Assert pattern -- One assertion per test when possible -- Test edge cases and error conditions - -### Test Coverage -- Aim for 80%+ code coverage minimum -- Focus on testing behavior, not implementation -- Test public interfaces, not private methods -- Include integration tests for key workflows - -## Quality Gates -- [ ] All new code has corresponding tests written first -- [ ] Test coverage maintained above 80% -- [ ] All tests pass before code commit -- [ ] Test names clearly describe expected behavior -- [ ] Edge cases and error conditions tested -- [ ] Integration tests cover key workflows - -## Examples - -### TDD Cycle Example -```javascript -// RED: Write failing test -test('should calculate total price with tax', () => { - const cart = new ShoppingCart(); - cart.addItem({price: 100, quantity: 2}); - - const total = cart.getTotalWithTax(0.08); - - expect(total).toBe(216); // 200 + 16 tax -}); - -// GREEN: Make test pass -class ShoppingCart { - constructor() { - this.items = []; - } - - addItem(item) { - this.items.push(item); - } - - getTotalWithTax(taxRate) { - const subtotal = this.items.reduce((sum, item) => - sum + (item.price * item.quantity), 0); - return subtotal * (1 + taxRate); - } -} - -// REFACTOR: Improve structure while keeping tests green -``` - -### Test Organization -```javascript -describe('ShoppingCart', () => { - describe('getTotalWithTax', () => { - it('should return 0 for empty cart', () => { - // Test implementation - }); - - it('should calculate tax on single item', () => { - // Test implementation - }); - - it('should handle zero tax rate', () => { - // Test implementation - }); - }); -}); -``` \ No newline at end of file diff --git a/best-practices-examples/git/feature-branch-workflow.md b/best-practices-examples/git/feature-branch-workflow.md deleted file mode 100644 index 1c8ce2df..00000000 --- a/best-practices-examples/git/feature-branch-workflow.md +++ /dev/null @@ -1,218 +0,0 @@ ---- -category: git -tags: [branching, workflow, feature-development, clean-commits] -created: 2025-08-09 -source_operation: STORY-002-AgentTask-001-best-practices-generation -quality_score: 9.2 -usage_count: 1 -effectiveness_rating: excellent -last_updated: 2025-08-09 ---- - -# Feature Branch Workflow with Clean Integration - -## Overview -A systematic approach to feature development using dedicated branches with clean commit history and professional integration practices. - -## Problem Statement -This practice addresses the challenge of maintaining clean Git history and professional commit standards while developing complex features that require multiple commits and coordination. - -### Symptoms -- Messy commit histories with debugging commits -- Merge conflicts that break main branch stability -- Unprofessional commit messages in permanent history -- Lost work due to improper branch management - -### Impact -Without this practice, teams typically experience code review confusion, difficulty tracking changes, and unprofessional repository appearance. - -## Solution Approach - -### Overview -Create dedicated feature branches, maintain clean development practices, and integrate with professional commit standards. - -### Steps -1. **Create Feature Branch:** Create dedicated branch from main with descriptive name - - Validation: Branch created and checked out successfully - - If problems: Ensure main branch is up to date first - - Prerequisites: Clean working directory, current main branch - -2. **Develop with Clean Commits:** Make focused commits with professional messages - - Expected outcome: Each commit represents logical development unit - - Quality check: Commit messages follow professional standards - - Critical factors: No debugging commits, clear commit purposes - -3. **Maintain Professional Standards:** Apply git privacy settings and quality gates - - Validation: No AI mentions in commit messages - - Expected outcome: Professional commit history suitable for production - - Prerequisites: git_privacy=true configuration applied - -4. **Integration and Cleanup:** Clean merge or rebase into main branch - - Critical factors: No merge conflicts, clean history preserved - - Common mistakes: Merging without testing, leaving debugging commits - - Quality check: Main branch remains stable after integration - -### Quality Gates -- [ ] Feature branch created with descriptive name -- [ ] All commits have professional, descriptive messages -- [ ] No AI references in commit history (git_privacy compliance) -- [ ] Feature fully tested before integration -- [ ] Clean merge without conflicts -- [ ] Main branch stability maintained - -## Examples - -### Scenario 1: New Feature Development -**Situation:** Developing best practices generation system requiring multiple behavioral files - -**Application:** -```bash -# Create feature branch -git checkout -b feature/STORY-002-best-practices - -# Make focused commits -git add src/behaviors/best-practice-recognition.md -git commit -m "feat: Add best practice recognition behavior - -- Implement pattern detection for successful operations -- Add quality assessment criteria -- Create user interaction workflows" - -git add src/behaviors/best-practice-generation.md -git commit -m "feat: Implement best practice document generation - -- Create structured documentation generation -- Add template-based content creation -- Implement user approval workflow" - -# Clean integration -git checkout main -git pull origin main -git merge feature/STORY-002-best-practices --no-ff -git push origin main -``` - -**Outcome:** Clean commit history with professional messages, successful feature integration, no AI mentions in permanent history. - -**Key Success Factors:** -- Descriptive branch name matches work item -- Each commit represents logical development unit -- Professional commit messages with context -- Clean merge preserves development history - -### Scenario 2: Bug Fix Integration -**Situation:** Fixing critical bug with systematic approach and validation - -**Adaptation:** -Create focused branch for bug resolution, implement fix with validation, integrate with testing confirmation. - -**Results:** Bug resolved without regression, professional commit history, clear documentation of fix approach. - -## When to Use - -### Ideal Conditions -- Feature development requiring multiple commits -- Complex changes affecting multiple files -- Work requiring coordination and review -- Professional repository standards required - -### Prerequisites -- Git repository with main branch protection -- git_privacy configuration enabled -- Clear understanding of feature requirements -- Access to create and merge branches - -### Not Recommended When -- Single-line changes or typo fixes -- Emergency hotfixes requiring immediate deployment -- Working in repositories without branch protection - -## Variations and Adaptations - -### For Small Teams -- Simplified review process but maintain commit standards -- Direct merge allowed for trusted developers -- Emphasis on communication during development - -### For Large Projects -- Required pull request reviews before merge -- Automated testing gates before integration -- Detailed commit message requirements -- Squash merging for cleaner history - -### Tool-Specific Adaptations -- **GitHub:** Use pull requests with review requirements -- **GitLab:** Implement merge request workflows with approvals - -## Common Pitfalls - -### Mistake: Including Debug/Test Commits in History -**Why it happens:** Developers commit debugging code or experimental changes -**Prevention:** Use git reset or interactive rebase to clean history before merge -**Recovery:** Rebase to remove debugging commits, force push to feature branch - -### Mistake: AI References in Commit Messages -**Symptoms:** Commit messages contain "Generated with Claude Code" or AI mentions -**Impact:** Unprofessional appearance in permanent repository history -**Solution:** Apply git_privacy settings, rewrite commit messages before push - -## Success Metrics - -### Quantitative Indicators -- Zero merge conflicts during integration -- 100% compliance with commit message standards -- Clean main branch history without debugging commits - -### Qualitative Indicators -- Professional repository appearance -- Easy code review and change tracking -- Clear development progression in commit history - -## Related Practices - -### Complementary Practices -- **Code Review Standards:** Works with systematic review processes -- **Automated Testing:** Integrates with CI/CD pipelines for quality gates - -### Alternative Approaches -- **Squash and Merge:** When commit history simplification preferred -- **Rebase Workflow:** For linear history maintenance - -## References and Resources - -### Source Operations -- STORY-002-AgentTask-001: Successful multi-file feature development with clean integration -- Multiple completed AgentTasks: Consistent application of professional Git practices - -### External Resources -- Git Documentation: Branching and merging best practices -- Professional commit message standards - -### Learning Patterns -- memory/git-workflows/: Related learning patterns and successful approaches - -## Revision History - -### 2025-08-09 - v1.0 -- Initial creation from STORY-002-AgentTask-001 best practices generation -- Includes feature branch workflow, commit standards, clean integration -- Based on successful multi-file development pattern - -## Usage Tracking - -### Applications -- **Date:** 2025-08-09 | **Context:** Best practices system development | **Outcome:** Clean feature integration, professional commit history - -### Effectiveness Rating -**Current Rating:** Excellent -**Based on:** 1 application -**Last Review:** 2025-08-09 - -### Improvement Opportunities -- Add examples for different repository hosting platforms -- Include conflict resolution strategies -- Enhance integration with automated testing workflows - ---- - -*This best practice was generated from the successful implementation of the best practices generation system, demonstrating effective feature branch workflow with professional Git standards.* \ No newline at end of file diff --git a/best-practices-examples/operations/gitops-practices.md b/best-practices-examples/operations/gitops-practices.md deleted file mode 100644 index 3ad52ac5..00000000 --- a/best-practices-examples/operations/gitops-practices.md +++ /dev/null @@ -1,67 +0,0 @@ -# GitOps Practices - -**Type:** operations -**Applies To:** medium, large, mega -**Keywords:** gitops, deployment, infrastructure, automation, version control - -## Description - -GitOps methodology for infrastructure and application deployment using Git as the single source of truth. - -## Implementation - -### Git as Source of Truth -- All infrastructure and application configs in version control -- Declarative configuration management -- Environment promotion through git workflows -- Audit trail through git history - -### Automated Deployment Pipeline -- Changes trigger automated deployment workflows -- Rollback capabilities through git revert -- Environment consistency through identical configs -- No manual deployment interventions - -### Pull-Based Deployment -- Deployment agents pull changes from git -- Self-healing through continuous reconciliation -- Reduced attack surface (no push credentials) -- Environment isolation and security - -## Quality Gates -- [ ] All infrastructure defined as code in version control -- [ ] Automated deployment pipelines configured -- [ ] Environment promotion strategy defined -- [ ] Rollback procedures tested and documented -- [ ] Monitoring and alerting for deployment status -- [ ] Security scanning integrated in pipeline - -## Examples - -### GitOps Workflow Structure -```yaml -# deployment/production/app-config.yaml -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-app - namespace: production -spec: - replicas: 3 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-app - image: my-app:v1.2.3 -``` - -### Branch Strategy -- `main` → Production environment -- `staging` → Staging environment -- `develop` → Development environment \ No newline at end of file diff --git a/best-practices-examples/quality/code-review-standards.md b/best-practices-examples/quality/code-review-standards.md deleted file mode 100644 index 5ce1d16a..00000000 --- a/best-practices-examples/quality/code-review-standards.md +++ /dev/null @@ -1,80 +0,0 @@ -# Code Review Standards - -**Type:** quality -**Applies To:** tiny, medium, large, mega -**Keywords:** code review, quality assurance, peer review, standards, collaboration - -## Description - -Comprehensive code review standards to ensure code quality, knowledge sharing, and team collaboration. - -## Implementation - -### Review Process -- All code changes require peer review before merge -- Reviews should be constructive and educational -- Review for correctness, performance, security, and maintainability -- Use automated tools to catch basic issues before human review - -### Review Checklist -- Code follows established coding standards -- Logic is clear and well-documented -- Error handling is appropriate -- Tests are included and comprehensive -- Security considerations addressed -- Performance implications considered - -### Review Communication -- Be respectful and constructive in feedback -- Explain the "why" behind suggestions -- Ask questions to understand the approach -- Acknowledge good practices and improvements - -## Quality Gates -- [ ] All changes reviewed by at least one qualified team member -- [ ] Automated checks (linting, testing) pass before review -- [ ] Security implications reviewed and addressed -- [ ] Performance impact assessed -- [ ] Documentation updated if needed -- [ ] Review feedback addressed satisfactorily -- [ ] All conversations resolved before merge - -## Examples - -### Good Review Comment -``` -Consider using a Map instead of object lookup here: - -const statusMap = new Map([ - ['pending', 'Processing'], - ['complete', 'Finished'], - ['error', 'Failed'] -]); - -This provides better performance for frequent lookups and cleaner syntax. -``` - -### Review Checklist Template -```markdown -## Code Review Checklist - -### Functionality -- [ ] Code accomplishes stated requirements -- [ ] Edge cases handled appropriately -- [ ] Error handling is robust - -### Quality -- [ ] Code is readable and well-documented -- [ ] Follows established coding standards -- [ ] No code duplication or unnecessary complexity - -### Testing -- [ ] Adequate test coverage provided -- [ ] Tests are meaningful and comprehensive -- [ ] All tests pass - -### Security -- [ ] No security vulnerabilities introduced -- [ ] Input validation where appropriate -- [ ] Sensitive data handled correctly -``` \ No newline at end of file diff --git a/best-practices-examples/security/secure-coding-practices.md b/best-practices-examples/security/secure-coding-practices.md deleted file mode 100644 index 7a2dc1eb..00000000 --- a/best-practices-examples/security/secure-coding-practices.md +++ /dev/null @@ -1,89 +0,0 @@ -# Secure Coding Practices - -**Type:** security -**Applies To:** tiny, medium, large, mega -**Keywords:** security, authentication, authorization, input validation, encryption - -## Description - -Essential security practices for developing secure applications and protecting against common vulnerabilities. - -## Implementation - -### Input Validation -- Validate all input at application boundaries -- Use whitelist validation over blacklist -- Sanitize output for different contexts (HTML, SQL, etc.) -- Implement proper error handling without information disclosure - -### Authentication & Authorization -- Use strong password policies and secure storage -- Implement proper session management -- Use principle of least privilege for authorization -- Implement multi-factor authentication for sensitive operations - -### Data Protection -- Encrypt sensitive data at rest and in transit -- Use HTTPS for all communications -- Implement proper key management -- Avoid storing sensitive data unnecessarily - -### Common Vulnerability Prevention -- Prevent SQL injection through parameterized queries -- Avoid XSS through proper output encoding -- Implement CSRF protection for state-changing operations -- Use secure headers and Content Security Policy - -## Quality Gates -- [ ] All user inputs validated and sanitized -- [ ] Authentication and authorization properly implemented -- [ ] Sensitive data encrypted at rest and in transit -- [ ] SQL injection prevention mechanisms in place -- [ ] XSS protection through output encoding -- [ ] CSRF tokens implemented for state changes -- [ ] Security headers configured (CSP, HSTS, etc.) -- [ ] Error messages don't reveal sensitive information - -## Examples - -### Input Validation -```javascript -function validateEmail(email) { - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!email || typeof email !== 'string') { - throw new ValidationError('Email is required'); - } - if (!emailRegex.test(email)) { - throw new ValidationError('Invalid email format'); - } - return email.toLowerCase().trim(); -} -``` - -### SQL Injection Prevention -```javascript -// GOOD: Parameterized query -const user = await db.query( - 'SELECT * FROM users WHERE email = ? AND active = ?', - [email, true] -); - -// BAD: String concatenation -const user = await db.query( - `SELECT * FROM users WHERE email = '${email}' AND active = true` -); -``` - -### Secure Password Hashing -```javascript -const bcrypt = require('bcrypt'); - -async function hashPassword(password) { - const saltRounds = 12; - return await bcrypt.hash(password, saltRounds); -} - -async function verifyPassword(password, hash) { - return await bcrypt.compare(password, hash); -} -``` \ No newline at end of file diff --git a/best-practices/README.md b/best-practices/README.md deleted file mode 100644 index bf2bedfa..00000000 --- a/best-practices/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Best Practices Index - -User-generated best practices for effective ICC usage. - -## Memory Storage and Retrieval -Learn when and how to store information in memory for team knowledge sharing. -[→ Details](./memory-storage-retrieval.md) - -## Git Workflow Patterns -Ensure commits comply with privacy settings and follow branch protection workflows. -[→ Details](./git-workflow-patterns.md) - -## Version Bump and GitHub Release Workflow -Complete workflow for version bumps with CHANGELOG updates, git tagging, and GitHub release creation using gh CLI. -[→ Details](./git/version-bump-and-release.md) - -## Release Workflow Automation -Configure automated release workflows with simple command interface for efficient PR-to-release pipelines. -[→ Details](./release-workflow-automation.md) - ---- - -**Note**: This directory is for user-generated best practices. Add your own by: -1. Creating a new `.md` file in this directory -2. Adding an entry to this README with headline + summary + link -3. Sharing via version control with your team diff --git a/best-practices/development/config-loading-dual-context.md b/best-practices/development/config-loading-dual-context.md deleted file mode 100644 index 901950cb..00000000 --- a/best-practices/development/config-loading-dual-context.md +++ /dev/null @@ -1,305 +0,0 @@ -# Dual-Context Configuration Loading - -## Overview -Configuration loading pattern that supports both production (installed) and development (repository) contexts without environment variables or conditional logic. - -## Problem Statement - -Hook systems and plugin architectures often need to work in two different contexts: -1. **Production/Installed Context**: Hooks installed at `~/.claude/hooks/` loading config from `~/.claude/` -2. **Development/Repository Context**: Hooks in `src/hooks/` loading config from repository root - -Using a single hardcoded path breaks one context or the other, requiring environment variables or complex detection logic. - -## Core Principle - -**FALLBACK APPROACH**: Try the production path first, then fallback to the development path if not found. - -This ensures: -- Production deployments work without modification -- Development/testing works without environment variables -- Documentation examples run as-written -- Regression tests continue functioning -- No conditional logic based on environment detection - -## Implementation Pattern - -### Basic Fallback Pattern - -```javascript -// Try production location first, then development location -let configPath = path.join(__dirname, '../..', 'config.json'); -let config = loadConfig(configPath); - -if (!config) { - // Fallback to development/repo location - configPath = path.join(__dirname, '../../..', 'config.json'); - config = loadConfig(configPath); -} - -if (!config) { - // Enhanced error reporting shows both searched paths - console.error('Config not found. Searched:'); - console.error(' - ' + path.join(__dirname, '../..', 'config.json')); - console.error(' - ' + path.join(__dirname, '../../..', 'config.json')); - - // Fallback to defaults - config = getDefaults(); -} -``` - -### Path Resolution Examples - -**Production Context** (`~/.claude/hooks/lib/config-loader.js`): -- `__dirname` = `~/.claude/hooks/lib` -- `../..` = `~/.claude/` ✅ (found) -- `../../..` = `~/` (not checked, already found) - -**Development Context** (`src/hooks/lib/config-loader.js`): -- `__dirname` = `repo/src/hooks/lib` -- `../..` = `repo/src/` ❌ (not found) -- `../../..` = `repo/` ✅ (found on fallback) - -## Real-World Example - -### Before: Single Path (Broken) - -```javascript -// Works ONLY in production, breaks in development -const configPath = path.join(__dirname, '../..', 'icc.config.json'); -const config = loadJsonConfig(configPath); -``` - -**Result**: -- ✅ Production: Loads from `~/.claude/icc.config.json` -- ✅ Development: Loads from `repo-root/icc.config.json` (if provided) -- ❌ Documentation: Examples fail -- ❌ Tests: Regression tests broken - -### After: Dual-Context Fallback (Working) - -```javascript -// Try production location first -let configPath = path.join(__dirname, '../..', 'icc.config.json'); -let config = loadJsonConfig(configPath); - -if (!config) { - // Fallback to development location - configPath = path.join(__dirname, '../../..', 'icc.config.json'); - config = loadJsonConfig(configPath); -} - -if (!config) { - console.error('[config-loader] Config not found. Searched:'); - console.error('[config-loader] - ' + path.join(__dirname, '../..', 'icc.config.json')); - console.error('[config-loader] - ' + path.join(__dirname, '../../..', 'icc.config.json')); - config = getHardcodedDefaults(); -} -``` - -**Result**: -- ✅ Production: Loads from `~/.claude/icc.config.json` -- ✅ Development: Loads from `repo-root/icc.config.json` -- ✅ Documentation: Examples work as-written -- ✅ Tests: All regression tests pass - -## Benefits - -### No Environment Variables Required -- No `NODE_ENV` checks -- No `INSTALLED_MODE` flags -- No custom environment setup -- Works out of the box in both contexts - -### Simplified Testing -- Tests run directly: `node src/hooks/agent-infrastructure-protection.js` -- No test-specific configuration -- Documentation examples copy-pasteable -- Regression tests don't need special setup - -### Production Ready -- Installed hooks work without modification -- No performance penalty (checks are fast) -- Clear error messages aid debugging -- Graceful fallback to defaults - -### Maintainability -- Single codebase for both contexts -- No conditional logic to maintain -- Clear path resolution order -- Self-documenting through comments - -## Common Use Cases - -### Hook Systems -- Production: Hooks in `~/.claude/hooks/` -- Development: Hooks in `repo/src/hooks/` -- Config in different locations relative to hook files - -### Plugin Architectures -- Production: Plugins in `~/.app/plugins/` -- Development: Plugins in `repo/src/plugins/` -- Shared config loading logic - -### CLI Tools -- Production: Installed to `/usr/local/bin/` -- Development: Run from `./src/cli/` -- Configuration in user home or repo root - -### Testing Frameworks -- Production: Installed test runners -- Development: Local test execution -- Test fixtures in different locations - -## Error Handling Best Practices - -### Enhanced Error Messages -Always show ALL searched paths when config not found: - -```javascript -if (!config) { - console.error('[loader] Configuration not found'); - console.error('[loader] Searched paths:'); - console.error('[loader] 1. ' + productionPath); - console.error('[loader] 2. ' + developmentPath); - console.error('[loader] Falling back to defaults'); - config = getDefaults(); -} -``` - -### Graceful Degradation -Provide sensible defaults as final fallback: - -```javascript -function getDefaults() { - return { - // Minimal working configuration - enabled: true, - logLevel: 'error' - }; -} -``` - -### Debug Logging -Log which path succeeded (at debug level): - -```javascript -if (config) { - if (process.env.DEBUG) { - console.debug('[loader] Config loaded from: ' + configPath); - } -} -``` - -## Anti-Patterns to Avoid - -### ❌ Environment-Based Logic -```javascript -// Don't do this -const configPath = process.env.NODE_ENV === 'production' - ? path.join(__dirname, '../..', 'config.json') - : path.join(__dirname, '../../..', 'config.json'); -``` - -**Why**: Requires environment setup, brittle, hard to test - -### ❌ Complex Detection Logic -```javascript -// Don't do this -const isInstalled = fs.existsSync(path.join(__dirname, '../..', '.installed')); -const configPath = isInstalled - ? path.join(__dirname, '../..', 'config.json') - : path.join(__dirname, '../../..', 'config.json'); -``` - -**Why**: Requires marker files, complex, error-prone - -### ❌ Silent Failures -```javascript -// Don't do this -let config = loadJsonConfig(configPath) || {}; -``` - -**Why**: No indication of failure, hard to debug, loses 140+ settings silently - -## Integration with Existing Systems - -### Works With -- ✅ npm/yarn package installations -- ✅ Ansible/Chef deployments -- ✅ Docker containers -- ✅ CI/CD pipelines -- ✅ Local development -- ✅ Documentation generation -- ✅ Test suites - -### Doesn't Require -- ❌ Environment variables -- ❌ Build-time configuration -- ❌ Conditional compilation -- ❌ Symlinks or aliases -- ❌ Path mapping -- ❌ Custom loaders - -## Quality Gates - -### Validation Checklist - -Before deploying dual-context config loading: - -- [ ] Production path points to installed location -- [ ] Development path points to repository root -- [ ] Both paths tested manually -- [ ] Error messages show both searched paths -- [ ] Graceful fallback to defaults implemented -- [ ] Debug logging available (if needed) -- [ ] Documentation updated with both contexts -- [ ] Tests cover both scenarios - -### Testing Requirements - -**Test in production context:** -```bash -$ node ~/.claude/hooks/lib/config-loader.js -✓ Config loaded successfully -``` - -**Test in development context:** -```bash -$ node src/hooks/lib/config-loader.js -✓ Config loaded successfully -``` - -**Test hook execution in production:** -```bash -$ node ~/.claude/hooks/agent-infrastructure-protection.js < test-input.json -✓ Hook runs correctly -``` - -**Test hook execution in development:** -```bash -$ node src/hooks/agent-infrastructure-protection.js < test-input.json -✓ Hook runs correctly -``` - -## Related Patterns - -- **Configuration Hierarchy**: Combines with user/project/default config layers -- **Graceful Degradation**: Provides defaults when config unavailable -- **Path Resolution**: Systematic approach to finding resources -- **Error Reporting**: Enhanced messages aid debugging - -## Success Metrics - -- Zero environment variables required -- 100% test pass rate in both contexts -- Documentation examples work without modification -- Clear error messages when config missing -- No production issues from path resolution - -## References - -- Implemented in: `src/hooks/lib/config-loader.js` -- PR: https://github.com/intelligentcode-ai/intelligent-claude-code/pull/239 -- Issue: Hook enforcement failures in other projects -- Commits: 1a38567, 490e159 diff --git a/best-practices/git-workflow-patterns.md b/best-practices/git-workflow-patterns.md deleted file mode 100644 index 0b1654a0..00000000 --- a/best-practices/git-workflow-patterns.md +++ /dev/null @@ -1,264 +0,0 @@ -# Git Privacy Compliance - -## Overview -Ensure all git commits comply with privacy settings and branch protection rules through automatic enforcement and manual verification. - -## Git Privacy Settings - -### Configuration -```json -{ - "git": { - "privacy": true, - "privacy_patterns": [ - "AI", - "Claude", - "agent", - "Generated with Claude Code", - "Co-Authored-By: Claude" - ], - "branch_protection": true, - "default_branch": "main", - "require_pr_for_main": true - } -} -``` - -### Automatic Enforcement -- **Hook**: `git-privacy-enforcement.js` enforces automatically -- **Trigger**: Before all git commit operations -- **Action**: Strips AI mentions from commit messages -- **Validation**: MANDATORY when `git.privacy: true` - -## Privacy Pattern Stripping - -### Default Patterns Removed -- "AI" references -- "Claude" mentions -- "agent" keywords -- "Generated with Claude Code" footers -- "Co-Authored-By: Claude" trailers - -### Custom Patterns -Add project-specific patterns to `git.privacy_patterns` array in `icc.config.json`. - -## Branch Protection - -### Protected Branch Rules -- **Default Branch**: Usually `main` or `master` -- **Direct Commits**: Blocked when `branch_protection: true` -- **Workflow**: Feature branch → PR → Merge -- **Override**: Emergency fixes require explicit override - -### Feature Branch Workflow -1. Create feature branch from default branch -2. Make commits on feature branch -3. Create pull request to default branch -4. Review and approve PR -5. Merge to default branch - -## Commit Message Guidelines - -### Professional Format -``` -(): - - - -