diff --git a/.egg-state/agent-outputs/integrator-output.json b/.egg-state/agent-outputs/integrator-output.json new file mode 100644 index 0000000000..79123cef25 --- /dev/null +++ b/.egg-state/agent-outputs/integrator-output.json @@ -0,0 +1,133 @@ +{ + "status": "pass", + "phase": "implement", + "pipeline_id": "issue-659", + "issue": 659, + "branch": "egg/issue-659", + "summary": "All coder and tester changes integrate cleanly. Shared prompt criteria unification works correctly across both GHA shell scripts and orchestrator Python code. One lint error (unused variable) was fixed by integrator.", + "test_results": { + "unit_tests": { + "status": "pass", + "passed": 3292, + "failed": 0, + "skipped": 5, + "deselected": 149, + "duration_seconds": 21.23, + "details": "Full unit test suite (tests/) passes. 3292 passed, 5 skipped, 149 deselected (integration/e2e/security markers)." + }, + "orchestrator_tests": { + "status": "pass", + "passed": 403, + "failed": 0, + "pre_existing_failures": 1, + "collection_errors": 2, + "duration_seconds": 14.16, + "details": "403 passed. 1 pre-existing failure (TestAgentRole.test_all_roles expects 6 roles but 13 exist - upstream change, not related to #659). 2 collection errors (test_container_spawner.py, test_docker_client.py) due to missing docker Python library in sandbox - pre-existing." + }, + "action_and_sandbox_tests": { + "status": "pass", + "passed": 821, + "failed": 0, + "skipped": 5, + "duration_seconds": 15.92, + "details": "All action/ and sandbox/ tests pass, including new tests for shared prompt criteria loading and shell script changes." + }, + "pipeline_prompt_tests": { + "status": "pass", + "passed": 36, + "failed": 0, + "duration_seconds": 0.42, + "details": "All 36 pipeline prompt tests pass, covering _read_shared_criteria(), per-type criteria getters, edge cases, shared file content validation, and format-agnostic checks." + } + }, + "lint_results": { + "ruff": { + "status": "pass", + "details": "All checks passed after fixing one unused variable (MockPath -> _MockPath) in test_pipeline_prompts.py." + }, + "shell_syntax": { + "status": "pass", + "details": "All 4 modified shell scripts pass bash -n syntax check." + } + }, + "integration_checks": { + "shared_prompt_files": { + "status": "pass", + "details": "All 4 shared prompt files exist in shared/prompts/ with correct content: agent-design-criteria.md (1976B), autofixer-rules.md (676B), code-review-criteria.md (2013B), contract-review-criteria.md (1233B)." + }, + "shell_script_path_resolution": { + "status": "pass", + "details": "All GHA scripts use $SCRIPT_DIR/../shared/prompts/ pattern. Path resolution verified correct from action/ directory." + }, + "python_path_resolution": { + "status": "pass", + "details": "Python _read_shared_criteria() correctly resolves to shared/prompts/ via Path(__file__).parent.parent.parent. Three-tier fallback: user override -> source tree -> docker path." + }, + "dockerfile_copy": { + "status": "pass", + "details": "Orchestrator Dockerfile includes COPY shared/prompts/ ./prompts/ for production container support." + }, + "inline_fallbacks": { + "status": "pass", + "details": "Inline fallback content in both shell scripts and Python code matches shared file content exactly." + }, + "claude_md_conditional": { + "status": "pass", + "details": "sandbox/entrypoint.py conditionally includes contract.md and orchestrator.md only when EGG_PIPELINE_ID is set, reducing token usage for non-SDLC invocations." + } + }, + "regressions": [], + "issues_found": [ + { + "severity": "low", + "type": "lint", + "description": "Unused variable MockPath in test_pipeline_prompts.py line 307", + "resolution": "Fixed by renaming to _MockPath. Committed as 'Fix unused variable lint error in test_pipeline_prompts'." + } + ], + "pre_existing_issues": [ + { + "severity": "medium", + "description": "TestAgentRole.test_all_roles expects 6 roles but 13 exist. Upstream roles were added without updating the test.", + "location": "orchestrator/tests/test_models.py:307" + }, + { + "severity": "low", + "description": "orchestrator/tests/test_container_spawner.py and test_docker_client.py fail to collect due to missing docker Python library in sandbox environment.", + "location": "orchestrator/tests/" + } + ], + "notes": [ + "The autofixer prompt builder in Python (pipelines.py line ~2019) hardcodes repo_path=None, preventing user overrides of autofixer rules via .egg/autofixer-rules.md when using the orchestrator pipeline. Shell script supports this override. This is a minor inconsistency but not a regression.", + "Agent-design criteria intentionally omits user override support in both shell scripts and Python code (consistent).", + "All inline fallbacks in both shell scripts and Python serve as rollout safety nets and match shared file content exactly." + ], + "commits": { + "coder": [ + { + "sha": "6ac7f70c", + "message": "Unify prompt criteria into shared files, trim CLAUDE.md for non-SDLC", + "files_changed": 15 + }, + { + "sha": "2138b40e", + "message": "Document shared prompt criteria and update CLI references", + "files_changed": 5 + } + ], + "tester": [ + { + "sha": "fd87f7da", + "message": "Add tests for shared prompt criteria and shell script changes", + "files_changed": 4 + } + ], + "integrator": [ + { + "sha": "588f3a59", + "message": "Fix unused variable lint error in test_pipeline_prompts", + "files_changed": 1 + } + ] + } +} diff --git a/.egg-state/checks/implement-results.json b/.egg-state/checks/implement-results.json index 9165b458ef..99ec8794da 100644 --- a/.egg-state/checks/implement-results.json +++ b/.egg-state/checks/implement-results.json @@ -4,12 +4,12 @@ { "name": "lint", "passed": true, - "output": "ruff check: All checks passed! (exit code 0)" + "output": "ruff check: All checks passed! (0 errors, 0 warnings)" }, { "name": "pytest", "passed": true, - "output": "3310 passed, 81 skipped, 3 warnings in 23.79s (exit code 0)" + "output": "3366 passed, 80 skipped, 3 warnings in 24.48s" } ] } diff --git a/.egg-state/contracts/659.json b/.egg-state/contracts/659.json new file mode 100644 index 0000000000..23484ee3df --- /dev/null +++ b/.egg-state/contracts/659.json @@ -0,0 +1,160 @@ +{ + "schemaVersion": "1.0", + "issue": { + "number": 659, + "title": "Issue #659", + "url": "https://github.com/jwbron/egg/issues/659" + }, + "pipeline_id": null, + "current_phase": "refine", + "acceptance_criteria": [], + "phases": [ + { + "id": "phase-1", + "name": "Implementation", + "status": "pending", + "review_cycles": 0, + "max_cycles": 3, + "escalated": false, + "escalation_reason": null, + "tasks": [ + { + "id": "task-1", + "description": "Breakdown", + "status": "pending", + "commit": null, + "checkpoint_id": null, + "notes": "", + "acceptance_criteria": "", + "files_affected": [], + "review_cycles": 0, + "max_cycles": 3, + "escalated": false + }, + { + "id": "task-2", + "description": "Risk Assessment", + "status": "pending", + "commit": null, + "checkpoint_id": null, + "notes": "", + "acceptance_criteria": "", + "files_affected": [], + "review_cycles": 0, + "max_cycles": 3, + "escalated": false + } + ], + "review_feedback": [] + } + ], + "decisions": [], + "workflow_owner": null, + "audit_log": [], + "refine_review_cycles": 0, + "refine_review_feedback": "", + "plan_review_cycles": 0, + "plan_review_feedback": "", + "pr": null, + "feedback": null, + "phase_configs": null, + "agent_executions": [ + { + "role": "coder", + "status": "complete", + "started_at": "2026-02-15T00:21:44.012414Z", + "completed_at": "2026-02-15T00:52:44.093792Z", + "commit": "884e1905", + "checkpoint_id": null, + "outputs": {}, + "error": null, + "retry_count": 0, + "conflicts": [] + }, + { + "role": "tester", + "status": "complete", + "started_at": "2026-02-15T00:36:38.204561Z", + "completed_at": "2026-02-15T00:44:00.154834Z", + "commit": null, + "checkpoint_id": null, + "outputs": {}, + "error": null, + "retry_count": 0, + "conflicts": [] + }, + { + "role": "documenter", + "status": "complete", + "started_at": "2026-02-15T00:36:38.206812Z", + "completed_at": "2026-02-15T00:40:53.155052Z", + "commit": null, + "checkpoint_id": null, + "outputs": {}, + "error": null, + "retry_count": 0, + "conflicts": [] + }, + { + "role": "integrator", + "status": "complete", + "started_at": "2026-02-15T00:44:00.160268Z", + "completed_at": "2026-02-15T00:49:38.741964Z", + "commit": null, + "checkpoint_id": null, + "outputs": {}, + "error": null, + "retry_count": 0, + "conflicts": [] + }, + { + "role": "reviewer_unified", + "status": "pending", + "started_at": null, + "completed_at": null, + "commit": null, + "checkpoint_id": null, + "outputs": {}, + "error": null, + "retry_count": 0, + "conflicts": [] + }, + { + "role": "reviewer_code", + "status": "pending", + "started_at": null, + "completed_at": null, + "commit": null, + "checkpoint_id": null, + "outputs": {}, + "error": null, + "retry_count": 0, + "conflicts": [] + }, + { + "role": "reviewer_contract", + "status": "pending", + "started_at": null, + "completed_at": null, + "commit": null, + "checkpoint_id": null, + "outputs": {}, + "error": null, + "retry_count": 0, + "conflicts": [] + }, + { + "role": "reviewer_agent_design", + "status": "pending", + "started_at": null, + "completed_at": null, + "commit": null, + "checkpoint_id": null, + "outputs": {}, + "error": null, + "retry_count": 0, + "conflicts": [] + } + ], + "multi_agent_config": null +} diff --git a/.egg-state/drafts/659-analysis.md b/.egg-state/drafts/659-analysis.md new file mode 100644 index 0000000000..f71fd96b03 --- /dev/null +++ b/.egg-state/drafts/659-analysis.md @@ -0,0 +1,221 @@ +# Analysis: Tune claude.md files and prompts (#659) + +## Problem Statement + +The codebase has two parallel prompt systems — bash scripts for GitHub Actions workflows and Python functions for the local orchestrator — that serve the same agent roles (reviewer, autofixer, conflict resolver, contract verifier, etc.) but were developed independently. The issue asks to: + +1. Audit all claude.md files and prompts for token waste from frontloaded context +2. Ensure each prompt is appropriate for its task +3. Unify prompt generators so local orchestration and GitHub Actions use the same code + +## Current Architecture + +### CLAUDE.md System + +**Source**: 7 rule files in `sandbox/.claude/rules/` (also duplicated at `sandbox/claude-rules/`) +**Combined output**: `~/CLAUDE.md` (~15.5 KB, 423 lines) — built at container startup by `sandbox/entrypoint.py:setup_agent_rules()` +**Mechanism**: Rules are concatenated in fixed order with `---` separators, then symlinked to `~/repos/CLAUDE.md` + +The 7 rule files and their sizes: + +| File | Size | Purpose | +|------|------|---------| +| `mission.md` | 5,431 B | Agent role, workflow, PR lifecycle, git safety | +| `environment.md` | 2,841 B | Sandbox capabilities, network modes, gateway | +| `code-standards.md` | 386 B | Tech stack, style, commands | +| `test-workflow.md` | 621 B | Test framework reference | +| `pr-descriptions.md` | 445 B | PR format template | +| `contract.md` | 2,670 B | SDLC contract CLI reference | +| `orchestrator.md` | 3,152 B | Orchestrator CLI reference | +| **Total** | **~15.5 KB** | | + +### Slash Commands (`.claude/commands/`) + +7 command files (~16 KB total): `coder-mode.md`, `tester-mode.md`, `documenter-mode.md`, `integrator-mode.md`, `onboarding-docs.md`, `sdlc.md`, `show-metrics.md` + +These are loaded on-demand when invoked, not frontloaded. + +### GitHub Actions Prompt Builders (Bash) + +7 bash scripts in `action/`: + +| Script | Approx Output Size | Used By | +|--------|-------------------|---------| +| `build-review-prompt.sh` | ~2-3 KB | `on-pull-request.yml` via `reusable-review.yml` | +| `build-autofixer-prompt.sh` | ~1.5 KB | `on-check-failure.yml` via `reusable-autofix.yml` | +| `build-conflict-prompt.sh` | ~5 KB (includes API data) | `on-merge-conflict.yml` via `reusable-conflict-resolve.yml` | +| `build-contract-verification-prompt.sh` | ~2.5 KB | `on-pull-request-contract-verify.yml` | +| `build-agent-mode-design-review-prompt.sh` | ~2 KB | `on-pull-request-agent-mode-design.yml` | +| `build-feedback-prompt.sh` | ~1.5 KB | `on-review-feedback.yml` | +| `build-doc-updater-prompt.sh` | ~4 KB (includes git data) | `on-push-doc-updater.yml` | + +Each script also loads conventions from `action/*-conventions.md` files (review, autofixer, conflict — ~280 lines, ~8 KB total). + +### Orchestrator Prompt Builders (Python) + +Functions in `orchestrator/routes/pipelines.py`: + +| Function | Purpose | Equivalent GHA Script | +|----------|---------|----------------------| +| `_build_phase_prompt()` | Phase-specific prompts (refine/plan/implement/pr) | None (SDLC-only) | +| `_build_agent_prompt()` | Role-specific multi-agent prompts | Slash commands (partial) | +| `_build_review_prompt()` | SDLC review with verdict JSON | `build-review-prompt.sh` | +| `_build_checker_prompt()` | Run tests/lint, write results | None (GHA uses CI directly) | +| `_build_autofix_prompt()` | Fix check failures | `build-autofixer-prompt.sh` | +| `_get_code_review_criteria()` | Security/correctness/robustness checklist | Inline in `build-review-prompt.sh` | +| `_get_agent_design_criteria()` | Agent-mode anti-pattern checklist | `build-agent-mode-design-review-prompt.sh` | +| `_get_contract_review_criteria()` | Contract verification checklist | `build-contract-verification-prompt.sh` | + +## Findings + +### Finding 1: Prompt Duplication Between GHA and Orchestrator (HIGH) + +The review criteria, autofixer rules, and contract verification logic exist in two separate implementations: + +- **Code review criteria**: GHA uses inline rules in `build-review-prompt.sh` (lines 30-77) while the orchestrator uses `_get_code_review_criteria()` in `pipelines.py` (lines 787-809). Content overlaps ~80% but differs in detail level. +- **Autofixer rules**: GHA uses `build-autofixer-prompt.sh` inline defaults + `autofixer-conventions.md`. Orchestrator uses `_build_autofix_prompt()` with similar but separately maintained rules. +- **Agent-mode design criteria**: GHA has a full bash script (`build-agent-mode-design-review-prompt.sh`, 180 lines) while orchestrator has `_get_agent_design_criteria()` (15 lines) — the orchestrator version is significantly less detailed. +- **Contract verification**: GHA has `build-contract-verification-prompt.sh` (219 lines); orchestrator has `_get_contract_review_criteria()` (20 lines). + +**Risk**: Divergence over time. When review rules are updated in one place, the other is forgotten. + +### Finding 2: CLAUDE.md Contains Context Not Needed for Every Task (MEDIUM) + +The combined CLAUDE.md (~15.5 KB) is loaded for every agent invocation regardless of task type. Some sections are rarely relevant: + +- **Orchestrator CLI reference** (`orchestrator.md`, 3.2 KB): Only relevant during SDLC pipeline phases, not for ad-hoc coding tasks or GHA workflows. +- **SDLC Contract reference** (`contract.md`, 2.7 KB): Only relevant during SDLC pipeline phases. +- **PR Description Format** (`pr-descriptions.md`, 445 B): Only relevant during PR creation. +- **Non-Interactive Mode section** in `mission.md`: Only relevant in `--print` mode. + +Combined, ~6.3 KB (~40%) of the CLAUDE.md is contextually irrelevant for most agent invocations. + +However, CLAUDE.md is only ~15.5 KB total, which is modest. The token cost of the extra context is small (roughly 4K tokens). The real concern is cognitive noise — irrelevant instructions may distract the agent from task-relevant rules. + +### Finding 3: Duplicate Rule Directories (LOW) + +`sandbox/claude-rules/` and `sandbox/.claude/rules/` contain identical files. The Dockerfile copies from `claude-rules/` while `.claude/rules/` serves as the source-of-truth for the Claude Code `.claude` configuration format. This is confusing but functionally harmless — both are in sync. + +### Finding 4: Orchestrator Review Prompts Differ Structurally from GHA (MEDIUM) + +The orchestrator `_build_review_prompt()` asks agents to write a JSON verdict file to `.egg-state/reviews/`, while GHA review prompts ask agents to post a GitHub review via `gh pr review`. This is a legitimate architectural difference (local vs GitHub), but the review *criteria* should be shared. + +Similarly, the orchestrator review prompt has no equivalent of: +- The `review-conventions.md` file (how to post reviews) +- The re-review delta checking workflow +- The review marker system (``) + +These are GHA-specific conventions and don't apply to local orchestration, so they're appropriately different. + +### Finding 5: Doc-Updater Prompt Pre-fetches Appropriately (OK) + +The `build-doc-updater-prompt.sh` pre-fetches changed files, commit messages, diff stats, and related docs. This is appropriate because the doc-updater needs this context upfront to determine if docs need updating. It follows agent-mode design guidelines by keeping pre-fetched data to small summaries (file lists, term matches), not full diffs. + +### Finding 6: Conflict Prompt Pre-fetches PR Context (OK) + +The `build-conflict-prompt.sh` fetches PR context, commit messages, and review comments via GitHub API. These are small summaries (~2 KB typically) that orient the agent. Appropriate. + +### Finding 7: Phase Prompt Has Dead Code (LOW) + +In `_build_phase_prompt()` (lines 1224-1239 and 1254-1269), the local and non-local branches for the refine and plan phases produce identical output. The `if is_local:` conditional serves no purpose for these phases. + +### Finding 8: Slash Commands Duplicate Orchestrator Agent Prompts (LOW-MEDIUM) + +The slash commands (`coder-mode.md`, `tester-mode.md`, etc.) and the orchestrator's `_build_agent_prompt()` function both define role-specific instructions for the same agent roles (coder, tester, documenter, integrator). The slash commands are more detailed (include file access constraints, handoff formats, quality checklists), while the orchestrator versions are more minimal. + +## Constraints and Dependencies + +1. **GHA and local orchestrator have different output mechanisms**: GHA agents post GitHub reviews; local agents write verdict files. This requires some prompt differences. +2. **GHA prompt scripts must run from a trusted checkout** (security): The `reusable-review.yml` checks out `main` to build prompts, preventing malicious PRs from modifying prompt scripts. Any shared module must be available at that point. +3. **Conventions files are GHA-specific**: `review-conventions.md`, `autofixer-conventions.md`, `conflict-conventions.md` contain GitHub-specific posting instructions that don't apply to local orchestration. +4. **CLAUDE.md must be available without repo mount**: It's baked into the Docker image at build time from `sandbox/claude-rules/`, so it can't depend on the mounted repo. +5. **Backward compatibility**: The `.egg/review-rules.md`, `.egg/autofixer-rules.md`, and `.egg/conflict-rules.md` user-override mechanism must be preserved. + +## Options + +### Option A: Shared Python Module for Review Criteria + +Extract review criteria, autofixer rules, and design-review checklists into a shared Python module in `shared/egg_prompts/`. Both the orchestrator and the GHA bash scripts would use the same source: + +- Orchestrator imports directly +- GHA bash scripts call a thin Python CLI (`python -m egg_prompts.criteria --type code-review`) + +**Pros**: Single source of truth; easy to test; criteria always in sync +**Cons**: Adds a Python dependency to GHA bash scripts; slightly more complex build + +### Option B: Shared Markdown Files as Criteria Source + +Create shared markdown files (e.g., `shared/prompts/code-review-criteria.md`) that both systems `cat`/read at runtime: + +- Orchestrator: `Path("shared/prompts/code-review-criteria.md").read_text()` +- GHA bash scripts: `cat shared/prompts/code-review-criteria.md` + +**Pros**: Simple; language-agnostic; easy to review and edit +**Cons**: No parameterization (can't vary by phase without templating); the trusted checkout in GHA already provides access to `main` branch files + +### Option C: Move Prompt Building into the GHA Action Itself + +Replace individual bash scripts with a single prompt builder inside the `action/` directory that handles all roles, invoked via `action.yml` inputs: + +**Pros**: Centralizes GHA prompt logic +**Cons**: Doesn't solve the duplication with the orchestrator; still two systems + +### Option D: Conditional CLAUDE.md Sections + +Make the CLAUDE.md assembly context-aware, only including sections relevant to the agent's current task: + +- Phase-based: Only include `contract.md` and `orchestrator.md` during SDLC pipeline phases +- Role-based: Only include `pr-descriptions.md` during PR creation + +**Pros**: Reduces token waste; less cognitive noise +**Cons**: More complex entrypoint logic; harder to debug; savings are modest (~4K tokens) + +## Recommendation + +**Pursue Option B (shared markdown criteria) + targeted CLAUDE.md trimming.** + +### Rationale + +1. **Option B is the simplest path to unification.** Shared markdown files can be read by both bash scripts and Python without additional dependencies. The trusted checkout in GHA workflows already provides access to the full repo, so `cat shared/prompts/code-review-criteria.md` works directly. + +2. **Partial CLAUDE.md conditioning is worthwhile.** The `contract.md` and `orchestrator.md` sections (~5.9 KB) should only be included when `EGG_PIPELINE_ID` is set, since they're SDLC-specific. This is a simple conditional in `setup_agent_rules()`. + +3. **Eliminate the duplicate `claude-rules/` directory.** The Dockerfile should copy from `.claude/rules/` directly (or just reference the same path), removing the redundant directory. + +4. **Clean up the dead code** in `_build_phase_prompt()` where `is_local` branches produce identical output. + +5. **Enrich orchestrator agent prompts** with the detail level from slash commands, or have the orchestrator load the slash command files as prompt foundations. + +### Specific Files to Create/Modify + +**Create** (shared criteria as markdown): +- `shared/prompts/code-review-criteria.md` +- `shared/prompts/autofixer-rules.md` +- `shared/prompts/agent-design-criteria.md` +- `shared/prompts/contract-review-criteria.md` +- `shared/prompts/unified-review-criteria-refine.md` +- `shared/prompts/unified-review-criteria-plan.md` +- `shared/prompts/unified-review-criteria-implement.md` + +**Modify** (consume shared criteria): +- `action/build-review-prompt.sh` — replace inline default review rules with `cat shared/prompts/code-review-criteria.md` +- `action/build-autofixer-prompt.sh` — replace inline defaults with `cat shared/prompts/autofixer-rules.md` +- `action/build-agent-mode-design-review-prompt.sh` — replace inline criteria with `cat shared/prompts/agent-design-criteria.md` +- `action/build-contract-verification-prompt.sh` — replace inline rules with `cat shared/prompts/contract-review-criteria.md` +- `orchestrator/routes/pipelines.py` — replace `_get_*_criteria()` functions to read from `shared/prompts/` +- `sandbox/entrypoint.py:setup_agent_rules()` — conditionally exclude `contract.md` and `orchestrator.md` when not in SDLC mode +- `sandbox/Dockerfile` — change COPY source from `sandbox/claude-rules/` to `sandbox/.claude/rules/` + +**Remove**: +- `sandbox/claude-rules/` directory (use `.claude/rules/` as single source) + +**Clean up**: +- `orchestrator/routes/pipelines.py:_build_phase_prompt()` — remove redundant `is_local` branches for refine/plan phases + +## Open Questions + +1. **Should the `.egg/review-rules.md` user-override mechanism apply to orchestrator reviews too?** Currently it only works in GHA. If unified, the orchestrator should also check for this file. + +2. **Should the orchestrator's agent-design review criteria be expanded to match the GHA version?** The GHA `build-agent-mode-design-review-prompt.sh` has significantly more guidance (review philosophy, what to skip, posting instructions) compared to the orchestrator's terse `_get_agent_design_criteria()`. + +3. **Should slash command content be merged with orchestrator `_build_agent_prompt()` output?** The slash commands (e.g., `coder-mode.md`) have richer instructions (file access constraints, handoff format, quality checklist) than the orchestrator's `_build_agent_prompt()`. The orchestrator could load these files as prompt foundations. diff --git a/.egg-state/drafts/659-plan-architect-analysis.json b/.egg-state/drafts/659-plan-architect-analysis.json new file mode 100644 index 0000000000..c663065ae4 --- /dev/null +++ b/.egg-state/drafts/659-plan-architect-analysis.json @@ -0,0 +1,425 @@ +{ + "issue": 659, + "phase": "plan", + "agent": "architect", + "title": "Tune claude.md files and prompts", + "summary": "Architecture analysis for auditing and unifying prompt systems across local orchestrator and GitHub Actions workflows, trimming CLAUDE.md token waste, and ensuring prompt appropriateness per task.", + + "problem_statement": { + "description": "The egg platform has two parallel prompt generation systems — 7 bash scripts for GitHub Actions and 5 Python functions for the local orchestrator — that serve overlapping agent roles but were developed independently. Review criteria, autofixer rules, and contract verification logic are duplicated with subtle divergence. The monolithic CLAUDE.md (~15.5 KB) is loaded for every agent invocation regardless of task type, with ~40% of content irrelevant to most invocations.", + "goals": [ + "Unify prompt generators so local orchestration and GitHub Actions use the same review criteria", + "Trim CLAUDE.md to avoid wasting tokens on frontloaded context not relevant to the current task", + "Ensure each prompt is appropriate for its specific task and agent role", + "Eliminate duplicate and dead code in the prompt system" + ] + }, + + "current_architecture": { + "claude_md": { + "source_dir": "sandbox/.claude/rules/", + "symlink": "sandbox/claude-rules/ -> .claude/rules/", + "assembly_function": "sandbox/entrypoint.py:setup_agent_rules() (lines 678-717)", + "assembly_method": "Hardcoded rules_order list, concatenated with '---' separators, no conditional logic", + "output": "~/CLAUDE.md symlinked to ~/repos/CLAUDE.md", + "total_size_bytes": 15500, + "estimated_tokens": 4000, + "rule_files": [ + {"file": "mission.md", "size_bytes": 5431, "purpose": "Agent role, workflow, PR lifecycle, git safety", "always_relevant": true}, + {"file": "code-standards.md", "size_bytes": 386, "purpose": "Tech stack, style, commands", "always_relevant": true}, + {"file": "environment.md", "size_bytes": 2841, "purpose": "Sandbox capabilities, network modes, gateway", "always_relevant": true}, + {"file": "test-workflow.md", "size_bytes": 621, "purpose": "Test framework reference", "always_relevant": true}, + {"file": "pr-descriptions.md", "size_bytes": 445, "purpose": "PR format template", "always_relevant": false, "relevant_when": "PR creation only"}, + {"file": "contract.md", "size_bytes": 2670, "purpose": "SDLC contract CLI reference", "always_relevant": false, "relevant_when": "SDLC pipeline phases only"}, + {"file": "orchestrator.md", "size_bytes": 3152, "purpose": "Orchestrator CLI reference", "always_relevant": false, "relevant_when": "SDLC pipeline phases only"} + ] + }, + "gha_prompt_builders": { + "location": "action/", + "total_scripts": 7, + "total_lines": 1526, + "scripts": [ + {"file": "build-review-prompt.sh", "lines": 187, "purpose": "Code review prompts for PRs", "has_orchestrator_equivalent": true}, + {"file": "build-autofixer-prompt.sh", "lines": 131, "purpose": "Fix failing CI checks", "has_orchestrator_equivalent": true}, + {"file": "build-conflict-prompt.sh", "lines": 280, "purpose": "Merge conflict resolution", "has_orchestrator_equivalent": false}, + {"file": "build-contract-verification-prompt.sh", "lines": 218, "purpose": "Contract compliance verification", "has_orchestrator_equivalent": true}, + {"file": "build-agent-mode-design-review-prompt.sh", "lines": 179, "purpose": "Agent-mode design alignment review", "has_orchestrator_equivalent": true}, + {"file": "build-doc-updater-prompt.sh", "lines": 446, "purpose": "Post-merge documentation updates", "has_orchestrator_equivalent": false}, + {"file": "build-feedback-prompt.sh", "lines": 85, "purpose": "Address review feedback", "has_orchestrator_equivalent": true} + ], + "convention_files": [ + {"file": "review-conventions.md", "lines": 57, "purpose": "How to post GitHub reviews"}, + {"file": "autofixer-conventions.md", "lines": 125, "purpose": "Single-pass fix workflow"}, + {"file": "conflict-conventions.md", "lines": 279, "purpose": "Merge conflict resolution strategy"} + ] + }, + "orchestrator_prompt_builders": { + "location": "orchestrator/routes/pipelines.py", + "functions": [ + {"name": "_build_phase_prompt()", "lines": "1096-1329", "purpose": "Phase-specific prompts (refine/plan/implement/pr)"}, + {"name": "_build_agent_prompt()", "lines": "1337-1556", "purpose": "Role-specific multi-agent prompts"}, + {"name": "_build_review_prompt()", "lines": "903-983", "purpose": "Review prompts with typed verdict JSON output"}, + {"name": "_build_checker_prompt()", "lines": "1850-1924", "purpose": "Test/lint check execution"}, + {"name": "_build_autofix_prompt()", "lines": "1927-1988", "purpose": "Fix auto-fixable check failures"}, + {"name": "_get_code_review_criteria()", "lines": "737-759", "purpose": "Security/correctness/robustness/design criteria"}, + {"name": "_get_agent_design_criteria()", "lines": "720-734", "purpose": "Agent-mode anti-pattern checklist"}, + {"name": "_get_contract_review_criteria()", "lines": "762-783", "purpose": "Contract verification checklist"}, + {"name": "_get_unified_criteria()", "lines": "639-718", "purpose": "Phase-specific unified review criteria (refine/plan/implement)"}, + {"name": "_get_reviewer_scope_preamble()", "lines": "808-831", "purpose": "Reviewer type scope instructions"}, + {"name": "_get_review_criteria_for_type()", "lines": "794-805", "purpose": "Dispatch to correct criteria function"} + ] + }, + "slash_commands": { + "location": "sandbox/.claude/commands/", + "files": ["coder-mode.md", "tester-mode.md", "documenter-mode.md", "integrator-mode.md", "onboarding-docs.md", "sdlc.md", "show-metrics.md"], + "total_size_kb": 16, + "note": "Loaded on-demand when invoked, NOT frontloaded into CLAUDE.md" + } + }, + + "findings": [ + { + "id": "F1", + "severity": "HIGH", + "title": "Review criteria duplicated between GHA and orchestrator with divergence", + "description": "Four categories of review criteria exist in two separate implementations that overlap ~80% but differ in detail level. The GHA versions (in bash scripts) are generally more detailed than the orchestrator versions (in Python string literals).", + "details": { + "code_review": { + "gha_location": "action/build-review-prompt.sh lines 30-77", + "orchestrator_location": "orchestrator/routes/pipelines.py:_get_code_review_criteria() lines 737-759", + "differences": [ + "GHA adds 'Insecure cryptography or randomness' under Security", + "GHA adds 'Incorrect algorithm complexity for data size' under Correctness", + "GHA adds 'State corruption scenarios' under Robustness", + "GHA adds 'Missing or incorrect abstractions' under Design", + "GHA includes detailed 'How to Review' methodology section (5 steps)", + "GHA includes 'Skip' section (linter issues, type annotations, auto-generated files)", + "Orchestrator version has none of the above" + ] + }, + "agent_design": { + "gha_location": "action/build-agent-mode-design-review-prompt.sh lines 55-127", + "orchestrator_location": "orchestrator/routes/pipelines.py:_get_agent_design_criteria() lines 720-734", + "differences": [ + "Same 5 anti-patterns listed, nearly identical wording", + "GHA adds 'What to Skip' section scoping the review", + "GHA adds nuance: 'Small metadata and task context are fine' for pre-fetching", + "Orchestrator version is terse (15 lines vs 70+ lines)" + ] + }, + "contract_review": { + "gha_location": "action/build-contract-verification-prompt.sh lines 35-64", + "orchestrator_location": "orchestrator/routes/pipelines.py:_get_contract_review_criteria() lines 762-783", + "differences": [ + "Nearly identical content and structure", + "GHA includes egg-contract CLI commands for marking criteria verified", + "Orchestrator omits the CLI verification step" + ] + }, + "autofixer": { + "gha_location": "action/build-autofixer-prompt.sh lines 32-46", + "orchestrator_location": "orchestrator/routes/pipelines.py:_build_autofix_prompt() lines 1977-1986", + "differences": [ + "GHA adds 'Missing or outdated dependencies in lock files' as auto-fixable", + "GHA adds 'Build failures from missing environment config' as report-only", + "Orchestrator has 3 categories each; GHA has 4 categories each" + ] + } + }, + "risk": "Criteria diverge over time. Updates in one place are forgotten in the other." + }, + { + "id": "F2", + "severity": "MEDIUM", + "title": "CLAUDE.md includes ~6.3 KB of context irrelevant to most agent invocations", + "description": "contract.md (2.7 KB) and orchestrator.md (3.2 KB) are SDLC-specific but loaded for all agents, including ad-hoc tasks and GHA workflows. pr-descriptions.md (445 B) is only relevant during PR creation. Total irrelevant context for non-SDLC invocations: ~6.3 KB (~40% of CLAUDE.md).", + "impact": "~1,600 tokens of cognitive noise per non-SDLC invocation. Token cost is modest, but irrelevant instructions may distract agents from task-relevant rules.", + "mitigation": "Conditional inclusion based on EGG_PIPELINE_ID environment variable in setup_agent_rules()" + }, + { + "id": "F3", + "severity": "LOW", + "title": "Dead code in _build_phase_prompt() with identical is_local branches", + "description": "Lines 1166-1181 (refine phase) and 1196-1211 (plan phase) have if/else branches on is_local that produce identical output in both branches.", + "location": "orchestrator/routes/pipelines.py lines 1166-1211" + }, + { + "id": "F4", + "severity": "LOW", + "title": "Duplicate rule directory (claude-rules/ symlink to .claude/rules/)", + "description": "sandbox/claude-rules/ is a symlink to sandbox/.claude/rules/. The Dockerfile copies from claude-rules/ which Docker follows through the symlink. Both paths reference the same files. The symlink is confusing but functionally harmless.", + "location": "sandbox/claude-rules -> sandbox/.claude/rules/" + }, + { + "id": "F5", + "severity": "MEDIUM", + "title": "Slash commands and orchestrator agent prompts duplicate role instructions", + "description": "Slash commands (coder-mode.md, tester-mode.md, etc.) and _build_agent_prompt() both define role-specific instructions for the same agent roles. Slash commands are richer (file access constraints, handoff formats, quality checklists). The orchestrator could load these instead of maintaining separate, less detailed versions.", + "location": "sandbox/.claude/commands/ vs orchestrator/routes/pipelines.py:_build_agent_prompt()" + }, + { + "id": "F6", + "severity": "INFO", + "title": "Unified review criteria are phase-specific (orchestrator-only, no GHA equivalent)", + "description": "_get_unified_criteria() returns different criteria for refine, plan, and implement phases. These are orchestrator-specific (GHA has no equivalent lifecycle concept) and don't need unification. They're well-structured.", + "location": "orchestrator/routes/pipelines.py:_get_unified_criteria() lines 639-718" + }, + { + "id": "F7", + "severity": "INFO", + "title": "GHA-only capabilities that appropriately have no orchestrator equivalent", + "description": "Conflict resolution (build-conflict-prompt.sh), doc-updater (build-doc-updater-prompt.sh), and the GHA-specific conventions files are PR-centric automations that don't apply to local orchestration. These are appropriately different.", + "location": "action/build-conflict-prompt.sh, action/build-doc-updater-prompt.sh" + } + ], + + "recommended_approach": { + "name": "Shared markdown criteria files with conditional CLAUDE.md assembly", + "summary": "Extract duplicated review criteria into shared markdown files that both GHA bash scripts and orchestrator Python functions read at runtime. Conditionally assemble CLAUDE.md to exclude SDLC-specific sections for non-pipeline agents. Clean up dead code and eliminate the redundant claude-rules/ symlink.", + + "rationale": [ + "Shared markdown files are the simplest unification path — both bash (cat) and Python (Path.read_text()) can read them without additional dependencies", + "The trusted checkout in GHA workflows already provides access to the full repo, so GHA scripts can read shared files directly", + "Conditional CLAUDE.md assembly is a minimal change to setup_agent_rules() that checks one environment variable (EGG_PIPELINE_ID)", + "The .egg/review-rules.md user-override mechanism is preserved — shared files serve as defaults, user overrides take priority", + "No new Python dependencies or build complexity introduced" + ], + + "constraints": [ + "GHA prompt scripts must run from a trusted checkout (main branch) — shared files must be available at that point", + "GHA and orchestrator have different output mechanisms (GitHub reviews vs JSON verdict files) — only criteria content is shared, not output format instructions", + "Convention files (review-conventions.md, autofixer-conventions.md, conflict-conventions.md) are GHA-specific and remain separate", + "CLAUDE.md must be available without repo mount — it's baked into the Docker image at build time", + "The .egg/review-rules.md, .egg/autofixer-rules.md, .egg/conflict-rules.md user-override mechanism must be preserved" + ], + + "alternatives_considered": [ + { + "name": "Shared Python module for criteria", + "description": "Extract criteria into a shared Python module in shared/egg_prompts/. Orchestrator imports directly; GHA scripts call a thin Python CLI.", + "rejected_because": "Adds Python dependency to GHA bash scripts, increasing complexity for marginal benefit over shared markdown files" + }, + { + "name": "Move all prompt building into GHA action", + "description": "Replace individual bash scripts with a single prompt builder in the action/ directory.", + "rejected_because": "Doesn't solve duplication with orchestrator — still two systems" + }, + { + "name": "Full dynamic CLAUDE.md with role-based sections", + "description": "Make CLAUDE.md fully dynamic based on agent role, task type, and phase.", + "rejected_because": "Over-engineered for the savings. Only contract.md and orchestrator.md are conditionally relevant. Simple EGG_PIPELINE_ID check suffices." + } + ] + }, + + "implementation_plan": { + "workstreams": [ + { + "id": "WS1", + "title": "Create shared prompt criteria files", + "description": "Extract duplicated review criteria from both GHA scripts and orchestrator functions into shared markdown files. Use the more detailed GHA versions as the baseline, enriching where the orchestrator version has additional content.", + "files_to_create": [ + { + "path": "shared/prompts/code-review-criteria.md", + "source": "Merge from action/build-review-prompt.sh lines 30-77 (primary) and orchestrator _get_code_review_criteria() lines 737-759", + "note": "Use GHA version as baseline — it's more comprehensive. Orchestrator adds nothing the GHA version lacks." + }, + { + "path": "shared/prompts/autofixer-rules.md", + "source": "Merge from action/build-autofixer-prompt.sh lines 32-46 (primary) and orchestrator _build_autofix_prompt() lines 1977-1986", + "note": "Use GHA version — it has 2 extra categories (lock files, build failures) that the orchestrator should also include." + }, + { + "path": "shared/prompts/agent-design-criteria.md", + "source": "Merge from action/build-agent-mode-design-review-prompt.sh lines 55-127 (primary) and orchestrator _get_agent_design_criteria() lines 720-734", + "note": "Use GHA version — it adds 'What to Skip' and nuance about small metadata being acceptable." + }, + { + "path": "shared/prompts/contract-review-criteria.md", + "source": "Merge from action/build-contract-verification-prompt.sh lines 35-64 (primary) and orchestrator _get_contract_review_criteria() lines 762-783", + "note": "Nearly identical content. GHA version includes egg-contract CLI commands for verification — keep those." + } + ], + "files_not_shared": [ + { + "path": "orchestrator/routes/pipelines.py:_get_unified_criteria()", + "reason": "Phase-specific unified review criteria are orchestrator-only. No GHA equivalent exists. Keep as-is." + } + ] + }, + { + "id": "WS2", + "title": "Update GHA prompt builders to use shared files", + "description": "Replace inline criteria in GHA bash scripts with reads from shared/prompts/ files. Preserve the .egg/*-rules.md user-override mechanism as a priority override.", + "files_to_modify": [ + { + "path": "action/build-review-prompt.sh", + "change": "Replace inline default review rules (lines 30-77) with: cat shared/prompts/code-review-criteria.md. Keep .egg/review-rules.md as user override that takes priority." + }, + { + "path": "action/build-autofixer-prompt.sh", + "change": "Replace inline default autofixer rules (lines 32-46) with: cat shared/prompts/autofixer-rules.md. Keep .egg/autofixer-rules.md as user override." + }, + { + "path": "action/build-agent-mode-design-review-prompt.sh", + "change": "Replace inline agent-design criteria (lines 55-127) with: cat shared/prompts/agent-design-criteria.md" + }, + { + "path": "action/build-contract-verification-prompt.sh", + "change": "Replace inline contract verification rules (lines 35-64) with: cat shared/prompts/contract-review-criteria.md. Keep .egg/contract-rules.md as user override." + } + ] + }, + { + "id": "WS3", + "title": "Update orchestrator to use shared files", + "description": "Replace hardcoded Python string criteria functions with file reads from shared/prompts/. The shared directory is available at the repo root, accessible via EGG_REPO_PATH.", + "files_to_modify": [ + { + "path": "orchestrator/routes/pipelines.py", + "changes": [ + "Replace _get_code_review_criteria() body with: Path(repo_path) / 'shared/prompts/code-review-criteria.md').read_text()", + "Replace _get_agent_design_criteria() body similarly", + "Replace _get_contract_review_criteria() body similarly", + "Replace autofixer rules in _build_autofix_prompt() body similarly", + "Add fallback: if file doesn't exist, log a warning and use inline default (backward compatibility during rollout)", + "Also support .egg/review-rules.md user-override mechanism (currently GHA-only; now works in orchestrator too)" + ] + } + ] + }, + { + "id": "WS4", + "title": "Conditional CLAUDE.md assembly", + "description": "Modify setup_agent_rules() to conditionally exclude SDLC-specific sections when not in pipeline mode.", + "files_to_modify": [ + { + "path": "sandbox/entrypoint.py", + "changes": [ + "In setup_agent_rules() (line 678), check for EGG_PIPELINE_ID environment variable", + "When EGG_PIPELINE_ID is not set, exclude contract.md and orchestrator.md from rules_order", + "Keep mission.md, code-standards.md, environment.md, test-workflow.md, pr-descriptions.md for all invocations" + ] + } + ], + "estimated_savings": "~5.8 KB (~1,500 tokens) per non-SDLC invocation" + }, + { + "id": "WS5", + "title": "Cleanup: dead code and duplicate directory", + "description": "Remove dead code and the confusing duplicate directory.", + "changes": [ + { + "path": "orchestrator/routes/pipelines.py", + "change": "Remove redundant is_local branches in _build_phase_prompt() at lines 1166-1181 and 1196-1211. Keep the common code without the conditional." + }, + { + "path": "sandbox/claude-rules", + "change": "Consider removing the symlink and updating the Dockerfile to COPY from sandbox/.claude/rules/ directly. However, this is low priority and the symlink is harmless." + } + ] + }, + { + "id": "WS6", + "title": "Update tests", + "description": "Update existing tests to verify shared criteria are loaded correctly.", + "files_to_modify": [ + { + "path": "tests/action/test_build_review_prompt.py", + "change": "Verify that shared/prompts/code-review-criteria.md content appears in output" + }, + { + "path": "tests/action/test_build_agent_mode_design_review_prompt.py", + "change": "Verify that shared/prompts/agent-design-criteria.md content appears in output" + }, + { + "path": "orchestrator/tests/test_pipeline_prompts.py", + "change": "Verify orchestrator criteria functions read from shared files; test fallback behavior when files are missing" + }, + { + "path": "tests/sandbox/test_entrypoint.py", + "change": "Add test for conditional CLAUDE.md assembly (with and without EGG_PIPELINE_ID)" + } + ] + } + ], + + "implementation_order": [ + "WS1 (create shared files) — prerequisite for everything else", + "WS2 (update GHA scripts) and WS3 (update orchestrator) — can be done in parallel after WS1", + "WS4 (conditional CLAUDE.md) — independent, can be done in parallel with WS2/WS3", + "WS5 (cleanup) — independent, can be done anytime", + "WS6 (tests) — after WS1-WS4 are complete" + ], + + "key_files_touched": [ + "shared/prompts/code-review-criteria.md (NEW)", + "shared/prompts/autofixer-rules.md (NEW)", + "shared/prompts/agent-design-criteria.md (NEW)", + "shared/prompts/contract-review-criteria.md (NEW)", + "action/build-review-prompt.sh (MODIFY)", + "action/build-autofixer-prompt.sh (MODIFY)", + "action/build-agent-mode-design-review-prompt.sh (MODIFY)", + "action/build-contract-verification-prompt.sh (MODIFY)", + "orchestrator/routes/pipelines.py (MODIFY)", + "sandbox/entrypoint.py (MODIFY)", + "tests/action/test_build_review_prompt.py (MODIFY)", + "tests/action/test_build_agent_mode_design_review_prompt.py (MODIFY)", + "orchestrator/tests/test_pipeline_prompts.py (MODIFY)", + "tests/sandbox/test_entrypoint.py (MODIFY)" + ] + }, + + "open_questions": [ + { + "id": "Q1", + "question": "Should the .egg/review-rules.md user-override mechanism be extended to orchestrator reviews?", + "context": "Currently user overrides only work in GHA. The recommended approach would also apply them in the orchestrator, making behavior consistent. This seems clearly desirable but is a behavioral change.", + "recommendation": "Yes — extend user overrides to orchestrator. Users who customize review rules likely want them applied everywhere." + }, + { + "id": "Q2", + "question": "Should the orchestrator load slash command files as agent prompt foundations instead of maintaining separate, less detailed role instructions?", + "context": "Slash commands (coder-mode.md, etc.) have richer instructions than _build_agent_prompt(). The orchestrator could load these files and append phase-specific context, eliminating another duplication source.", + "recommendation": "Defer to a follow-up issue. The slash commands are loaded on-demand by Claude Code and have a different format than what _build_agent_prompt() produces. Unifying them requires more design work than this issue warrants." + }, + { + "id": "Q3", + "question": "Should the shared criteria files live in shared/prompts/ or a different location?", + "context": "The shared/ directory currently contains Python packages (egg_config, egg_container, etc.). Adding markdown files is a new pattern. Alternative: action/shared-criteria/ or a top-level prompts/ directory.", + "recommendation": "Use shared/prompts/ — it's the most natural location given the shared/ directory is explicitly for cross-component shared resources. The fact that it currently contains Python packages doesn't preclude non-Python content." + } + ], + + "risk_assessment": [ + { + "risk": "GHA trusted checkout won't have shared/prompts/ files", + "severity": "LOW", + "mitigation": "GHA workflows check out the main branch for prompt building. Shared files will be on main after the PR is merged. During rollout, GHA scripts should have a fallback to inline defaults if the shared file doesn't exist." + }, + { + "risk": "Orchestrator can't find shared/prompts/ at runtime", + "severity": "LOW", + "mitigation": "The orchestrator runs from the repo root. Use EGG_REPO_PATH / 'shared/prompts/' with a fallback to inline defaults." + }, + { + "risk": "Breaking existing tests", + "severity": "MEDIUM", + "mitigation": "Run existing tests before and after changes. The test files for GHA prompt builders (tests/action/) and orchestrator prompts (orchestrator/tests/test_pipeline_prompts.py) will need updates to account for shared file reads." + }, + { + "risk": "Conditional CLAUDE.md breaks agent behavior in non-SDLC mode", + "severity": "LOW", + "mitigation": "contract.md and orchestrator.md are SDLC-specific CLIs that non-SDLC agents never use. Removing them from non-SDLC agents has no behavioral impact." + } + ], + + "metrics": { + "files_with_duplicated_criteria": 8, + "shared_criteria_files_to_create": 4, + "total_files_to_modify": 10, + "total_files_to_create": 4, + "estimated_token_savings_per_non_sdlc_invocation": 1500, + "percentage_claude_md_conditionally_excluded": 40 + } +} diff --git a/.egg-state/drafts/659-plan-risk-analyst.json b/.egg-state/drafts/659-plan-risk-analyst.json new file mode 100644 index 0000000000..7cf2317be0 --- /dev/null +++ b/.egg-state/drafts/659-plan-risk-analyst.json @@ -0,0 +1,268 @@ +{ + "issue": 659, + "phase": "plan", + "agent": "risk_analyst", + "title": "Risk Assessment: Tune claude.md files and prompts", + "summary": "Technical risk assessment for unifying prompt criteria into shared markdown files, conditionally assembling CLAUDE.md, and cleaning up dead code. Overall risk is MEDIUM — the approach is sound but has specific pitfalls around container build contexts, GHA trusted-checkout security model, and test coupling that require careful handling.", + + "overall_risk_level": "MEDIUM", + "recommendation": "PROCEED_WITH_MITIGATIONS", + + "risks": [ + { + "id": "R1", + "title": "Orchestrator container lacks access to shared/prompts/ at build time", + "category": "compatibility", + "severity": "HIGH", + "likelihood": "CERTAIN", + "impact": "Orchestrator criteria functions would fail with FileNotFoundError at runtime if they try to read shared/prompts/ files", + "description": "The orchestrator Dockerfile (orchestrator/Dockerfile lines 14-22) copies only specific Python packages from shared/ (egg_logging, egg_config, egg_contracts, egg_container). It does NOT copy arbitrary subdirectories. If criteria are placed in shared/prompts/*.md, the orchestrator container will not have these files. The orchestrator runs in its own container (docker-compose.yml line 90-93), not inside the sandbox, and has no volume mount for the egg source repo at the shared/prompts/ path.", + "affected_files": [ + "orchestrator/Dockerfile", + "orchestrator/routes/pipelines.py" + ], + "mitigation": { + "strategy": "Add COPY directive to orchestrator Dockerfile: 'COPY shared/prompts/ ./prompts/' and have the Python functions read from Path('/app/prompts/') with inline fallback. Alternatively, place criteria files in a location already accessible to both systems — e.g., alongside the orchestrator code itself.", + "effort": "LOW", + "residual_risk": "LOW — straightforward Dockerfile change, but adds a build dependency that future maintainers must keep in sync" + }, + "requires_human_review": false + }, + { + "id": "R2", + "title": "GHA trusted-checkout security model interaction", + "category": "security", + "severity": "HIGH", + "likelihood": "LOW", + "impact": "If implemented incorrectly, a malicious PR could inject prompt content into review agents that run with bot tokens", + "description": "The GHA reusable workflows (e.g., reusable-review.yml lines 474-491) implement a two-stage checkout security model: (1) checkout main for trusted prompt scripts, (2) checkout PR code for the review target. The prompt builder scripts (build-review-prompt.sh etc.) run from the main checkout. Currently, inline criteria serve as immutable defaults that cannot be tampered with by PR code. If the scripts are changed to read criteria from shared/prompts/*.md using a relative path like 'cat shared/prompts/code-review-criteria.md', the path resolution depends on which checkout is the working directory at execution time. If the working directory is the PR checkout (not main), a malicious PR could provide a tampered criteria file.", + "affected_files": [ + "action/build-review-prompt.sh", + "action/build-autofixer-prompt.sh", + "action/build-agent-mode-design-review-prompt.sh", + "action/build-contract-verification-prompt.sh", + ".github/workflows/reusable-review.yml" + ], + "mitigation": { + "strategy": "Ensure GHA scripts read shared criteria using an absolute path anchored to the trusted main checkout, not the PR checkout. The reusable workflows already set up the trusted checkout path — scripts should use $GITHUB_WORKSPACE or a dedicated variable pointing to the main checkout. Also maintain hardcoded inline fallback criteria in the scripts so that if the shared file is missing (e.g., during rollout before merge to main), the default criteria still apply. The existing .egg/review-rules.md user-override mechanism intentionally reads from the PR checkout — this is by design and should remain separate from the default criteria loading.", + "effort": "MEDIUM", + "residual_risk": "LOW — if paths are correctly anchored to the trusted checkout, the security model is preserved" + }, + "requires_human_review": true, + "review_reason": "Security-sensitive change to the trusted prompt generation pipeline. Must verify that path resolution in GHA workflows correctly isolates trusted vs untrusted code." + }, + { + "id": "R3", + "title": "Test suite breakage from content coupling", + "category": "compatibility", + "severity": "MEDIUM", + "likelihood": "HIGH", + "impact": "Multiple test files will fail when criteria move from inline strings to file reads", + "description": "Tests in tests/action/test_build_review_prompt.py assert specific phrases like 'thorough', 'ALL issues', 'every', 'context' that appear in the inline default criteria. Tests in tests/action/test_build_agent_mode_design_review_prompt.py assert exact phrases like 'guidelines, not absolute rules', 'Orienting vs constraining', 'Practical balance', 'Benefit of the doubt'. When criteria move to shared markdown files, the bash scripts need to read them at test time. If tests mock the filesystem or run without the shared files present, they will fail. The orchestrator tests (orchestrator/tests/test_pipeline_prompts.py) are lower risk because they test function output behavior rather than exact string content.", + "affected_files": [ + "tests/action/test_build_review_prompt.py", + "tests/action/test_build_agent_mode_design_review_prompt.py", + "orchestrator/tests/test_pipeline_prompts.py" + ], + "mitigation": { + "strategy": "Update test fixtures to provide shared markdown files in the test environment. For bash script tests, ensure the test working directory contains the shared/prompts/ files or that the scripts are invoked with correct path resolution. For orchestrator tests, add test cases that verify: (a) shared file is loaded when present, (b) inline fallback is used when file is missing. Run the full test suite before and after changes to catch regressions.", + "effort": "MEDIUM", + "residual_risk": "LOW — tests need updating but the pattern is straightforward" + }, + "requires_human_review": false + }, + { + "id": "R4", + "title": "Rollout timing: GHA scripts reference shared files before they exist on main", + "category": "compatibility", + "severity": "MEDIUM", + "likelihood": "MEDIUM", + "impact": "After merging the PR, GHA workflows on other PRs could fail if script changes land before shared files, or if the GHA cache serves stale main branch content", + "description": "The GHA trusted checkout checks out the main branch to build prompts. If the PR modifies both the bash scripts (to read from shared/prompts/) AND creates the shared files, these all land atomically on main at merge time, which is fine. However, if the implementation is split across multiple PRs, or if GitHub Actions caches the main checkout, there's a window where scripts expect files that don't exist. Additionally, if partial commits within a single PR are cherry-picked, the script changes could land without the shared files.", + "affected_files": [ + "action/build-review-prompt.sh", + "action/build-autofixer-prompt.sh", + "shared/prompts/*.md" + ], + "mitigation": { + "strategy": "Ship all changes in a single PR (as the architect recommends). Ensure every script that reads from shared/prompts/ retains inline fallback defaults — the existing pattern where the script checks 'if file exists, cat file, else use heredoc default' should be preserved for the shared criteria files. This makes the transition backward-compatible. The fallback eliminates any rollout timing risk.", + "effort": "LOW", + "residual_risk": "NEGLIGIBLE — fallback pattern is already established in the codebase" + }, + "requires_human_review": false + }, + { + "id": "R5", + "title": "Conditional CLAUDE.md assembly could break future agents that expect full content", + "category": "compatibility", + "severity": "LOW", + "likelihood": "LOW", + "impact": "An agent invoked without EGG_PIPELINE_ID that needs contract or orchestrator CLI reference would not have it in CLAUDE.md", + "description": "The proposed change excludes contract.md (~2.7 KB) and orchestrator.md (~3.2 KB) from CLAUDE.md when EGG_PIPELINE_ID is not set. Currently all agents get all sections. If a new feature or workflow invokes agents that need contract/orchestrator CLI references outside the SDLC pipeline (e.g., an ad-hoc debugging session that needs to inspect contract state), those agents would lack the relevant instructions. The savings (~1,500 tokens per non-SDLC invocation) is modest.", + "affected_files": [ + "sandbox/entrypoint.py" + ], + "mitigation": { + "strategy": "The mitigation is already built into the approach: EGG_PIPELINE_ID is set for all SDLC pipeline invocations. Non-SDLC invocations (ad-hoc sessions, GHA workflows) genuinely don't need contract/orchestrator CLI references. If a future use case requires them outside SDLC, the condition can be broadened. The slash commands (sdlc.md, show-metrics.md) which reference these CLIs are loaded on-demand and are unaffected. Low residual risk.", + "effort": "NEGLIGIBLE", + "residual_risk": "LOW — easy to reverse if needed" + }, + "requires_human_review": false + }, + { + "id": "R6", + "title": "Criteria drift between shared markdown and GHA-specific context", + "category": "design", + "severity": "LOW", + "likelihood": "MEDIUM", + "impact": "Shared criteria files could diverge from GHA-specific conventions over time if maintainers forget the relationship", + "description": "The architect proposes sharing only criteria content, not output format instructions (conventions). This means GHA scripts will compose: shared_criteria + gha_conventions + user_overrides. The orchestrator will compose: shared_criteria + verdict_format. If someone updates the shared criteria to reference GHA-specific concepts (like 'gh pr review' commands), or if the conventions evolve to assume criteria content that has changed, subtle inconsistencies could emerge. This is the same class of problem the refactoring aims to fix, just at a different boundary.", + "affected_files": [ + "shared/prompts/*.md", + "action/*-conventions.md" + ], + "mitigation": { + "strategy": "Add a comment header to each shared criteria file noting which systems consume it (GHA scripts + orchestrator) and that it must remain output-format-agnostic. Add a CI check or test that verifies shared criteria files don't contain GHA-specific terms (gh pr, $GITHUB_REPOSITORY, etc.).", + "effort": "LOW", + "residual_risk": "LOW — documentation and review process suffice" + }, + "requires_human_review": false + }, + { + "id": "R7", + "title": "Removing claude-rules/ symlink could break Dockerfile or CI that references it", + "category": "compatibility", + "severity": "LOW", + "likelihood": "LOW", + "impact": "Docker build would fail if Dockerfile still references claude-rules/ after symlink removal", + "description": "The architect suggests removing the sandbox/claude-rules/ symlink and updating the Dockerfile COPY to use sandbox/.claude/rules/ directly. The Dockerfile currently uses 'COPY sandbox/claude-rules/*.md /opt/claude-rules/' (line 117). Docker follows symlinks during COPY, so the current setup works. Changing to 'COPY sandbox/.claude/rules/*.md /opt/claude-rules/' would also work, but the .claude directory name might cause issues with .dockerignore or other tooling that filters dotfiles.", + "affected_files": [ + "sandbox/Dockerfile", + "sandbox/claude-rules" + ], + "mitigation": { + "strategy": "Verify that .dockerignore (if present) does not exclude .claude directories. Test the Docker build locally before merging. Alternatively, keep the symlink as-is — it's functionally harmless and the architect noted this is low priority. The symlink removal could be deferred to avoid unnecessary risk.", + "effort": "LOW", + "residual_risk": "NEGLIGIBLE" + }, + "requires_human_review": false + }, + { + "id": "R8", + "title": "User-override mechanism (.egg/*-rules.md) behavior change in orchestrator", + "category": "design", + "severity": "MEDIUM", + "likelihood": "MEDIUM", + "impact": "Extending .egg/review-rules.md to orchestrator reviews changes behavior for repos that have custom rules — they'd now apply in both GHA and local reviews, which may not be expected", + "description": "The architect recommends extending the .egg/review-rules.md user-override mechanism to orchestrator reviews (Q1 in open questions). Currently, user overrides only affect GHA workflows. If extended to the orchestrator, repos with custom .egg/review-rules.md would see those custom rules applied in SDLC pipeline reviews too. This is likely desirable but is a behavioral change that could surprise users who set up overrides specifically for GHA reviews.", + "affected_files": [ + "orchestrator/routes/pipelines.py" + ], + "mitigation": { + "strategy": "Document the behavioral change in the PR description. The user-override files (.egg/review-rules.md etc.) are an opt-in mechanism — users who created them presumably want consistent review criteria. The risk of unwanted behavior is low. If needed, a separate .egg/orchestrator-review-rules.md could be supported, but this adds complexity for minimal benefit.", + "effort": "LOW", + "residual_risk": "LOW — behavioral change is aligned with user intent" + }, + "requires_human_review": true, + "review_reason": "Behavioral change that affects all repos with custom .egg/*-rules.md files. Confirm this is the desired behavior." + } + ], + + "areas_requiring_human_review": [ + { + "area": "GHA trusted-checkout path resolution (R2)", + "reason": "Security-critical: prompt builder scripts must read shared criteria from the trusted main checkout, not the untrusted PR checkout. Implementation must be verified to maintain the existing security model.", + "suggested_reviewer": "Security-aware engineer familiar with GHA reusable workflow security model" + }, + { + "area": "User-override mechanism extension to orchestrator (R8)", + "reason": "Behavioral change affecting repos with custom .egg/*-rules.md files. Confirm this aligns with user expectations.", + "suggested_reviewer": "Product owner or engineer familiar with user-facing configurations" + }, + { + "area": "Scope of shared criteria vs GHA-specific context", + "reason": "The architect defers slash command unification (Q2) to a follow-up. This boundary decision (what's shared vs system-specific) has long-term maintenance implications. Confirm the boundary is drawn correctly.", + "suggested_reviewer": "Architect or senior engineer" + } + ], + + "rollback_plan": { + "strategy": "Revert the entire PR. The fallback pattern (inline defaults in scripts) means reverting is safe — criteria return to inline, conditional CLAUDE.md logic is removed, dead code cleanup is undone. No data migration or state changes are involved.", + "steps": [ + "1. Revert the PR via GitHub UI (creates revert commit)", + "2. GHA workflows immediately use inline criteria again (fallback path)", + "3. Orchestrator container rebuild picks up reverted code automatically", + "4. Sandbox container rebuild restores full CLAUDE.md assembly", + "5. No manual intervention needed — all changes are code-only, no state migrations" + ], + "data_loss_risk": "NONE — this is a prompt generation change, no persistent data is affected", + "downtime_risk": "NONE — prompt generation changes take effect on next agent invocation, not mid-execution" + }, + + "implementation_recommendations": [ + { + "id": "REC1", + "priority": "HIGH", + "recommendation": "Ship all changes in a single PR to avoid rollout timing issues (R4). The architect's workstream ordering (WS1 -> WS2/WS3 parallel -> WS4/WS5 -> WS6) is logical but all should be in one PR.", + "rationale": "Atomic merge ensures shared files and script changes land together. The fallback pattern handles the pre-merge state." + }, + { + "id": "REC2", + "priority": "HIGH", + "recommendation": "Add shared/prompts/ COPY to orchestrator/Dockerfile (R1). This is the most likely-to-be-overlooked step since the architect's plan mentions EGG_REPO_PATH as the read path, but the orchestrator runs in its own container where the egg source repo isn't mounted.", + "rationale": "Without this, orchestrator criteria functions will fail in production. The orchestrator container needs the files baked in at build time." + }, + { + "id": "REC3", + "priority": "HIGH", + "recommendation": "For GHA scripts, use a path relative to the script's own directory ($SCRIPT_DIR/../shared/prompts/) anchored to the trusted checkout, not a bare relative path (R2).", + "rationale": "Prevents prompt injection via malicious PR code. The scripts already use `$(dirname \"$0\")` for conventions files — use the same pattern for shared criteria." + }, + { + "id": "REC4", + "priority": "MEDIUM", + "recommendation": "Maintain inline fallback criteria in both GHA scripts and orchestrator functions (R3, R4). Use the pattern: if shared file exists, read it; else use inline default.", + "rationale": "Backward compatibility during rollout, resilience against missing files, and makes the transition reversible without a full revert." + }, + { + "id": "REC5", + "priority": "LOW", + "recommendation": "Defer the claude-rules/ symlink removal (R7) to a follow-up. It's low value and introduces unnecessary risk in an already large changeset.", + "rationale": "The symlink is functionally harmless. Removing it requires Dockerfile and possibly .dockerignore changes that could break the build for a negligible cleanup benefit." + } + ], + + "performance_assessment": { + "token_savings": "~1,500 tokens per non-SDLC agent invocation (40% of CLAUDE.md excluded)", + "build_time_impact": "Negligible — adding COPY for 4 small markdown files", + "runtime_impact": "Negligible — file reads are cached by OS, criteria are small (<5 KB each)", + "note": "The token savings are modest but the cognitive noise reduction (irrelevant SDLC instructions removed for non-SDLC agents) is the primary value. The unification benefit (single source of truth for criteria) is the main long-term win." + }, + + "security_assessment": { + "threat_model": "Prompt injection via malicious PR modifying shared criteria files in untrusted checkout", + "current_controls": [ + "GHA two-stage checkout: prompt scripts execute from main branch, not PR branch", + "Inline fallback criteria: scripts have hardcoded defaults that don't depend on any file", + "User overrides (.egg/*-rules.md): intentionally read from PR checkout (opt-in customization)" + ], + "proposed_controls": [ + "Script path anchoring: read shared criteria using script-relative paths from trusted checkout", + "Fallback preservation: inline defaults remain as fallback if shared files are missing", + "No new trust boundaries: shared criteria are read from the same trust context as existing prompt scripts" + ], + "residual_risk": "LOW if path anchoring is correctly implemented; the security model is preserved" + }, + + "compatibility_assessment": { + "breaking_changes": "None — all changes are additive with fallback behavior", + "backward_compatibility": "Full — inline fallbacks ensure old behavior when shared files are missing", + "forward_compatibility": "Good — shared markdown files can be extended without code changes", + "affected_systems": [ + "GHA review workflows (reusable-review.yml, reusable-autofix.yml, etc.)", + "Orchestrator SDLC pipeline reviews", + "Sandbox CLAUDE.md assembly (entrypoint.py)", + "Docker build for sandbox and orchestrator containers" + ] + } +} diff --git a/.egg-state/drafts/659-plan-task-planner.json b/.egg-state/drafts/659-plan-task-planner.json new file mode 100644 index 0000000000..b1e9b72853 --- /dev/null +++ b/.egg-state/drafts/659-plan-task-planner.json @@ -0,0 +1,250 @@ +{ + "issue": 659, + "phase": "plan", + "agent": "task_planner", + "title": "Tune claude.md files and prompts", + "summary": "Task breakdown for unifying prompt systems across GHA and orchestrator, trimming CLAUDE.md token waste, and cleaning up dead code. 5 phases, 18 tasks, sequenced to minimize risk and enable parallel work where possible.", + + "phases": [ + { + "id": "phase-1", + "name": "Create shared prompt criteria files", + "description": "Extract duplicated review criteria from GHA bash scripts and orchestrator Python functions into shared markdown files. Use the more detailed GHA versions as baseline. This is the prerequisite for all other phases.", + "dependency": null, + "tasks": [ + { + "id": "task-1-1", + "description": "Create shared/prompts/code-review-criteria.md by merging content from action/build-review-prompt.sh (lines 30-77, primary) and orchestrator _get_code_review_criteria() (lines 737-759). Use the GHA version as baseline since it includes additional items (insecure cryptography, algorithm complexity, state corruption, missing abstractions) plus the 'How to Review' methodology and 'Skip' sections that the orchestrator lacks.", + "acceptance_criteria": "File exists at shared/prompts/code-review-criteria.md; contains all 4 review categories (Security, Correctness, Robustness, Design) with items from both sources; includes 'How to Review' and 'Skip' sections from GHA version; is valid markdown.", + "files_affected": ["shared/prompts/code-review-criteria.md"] + }, + { + "id": "task-1-2", + "description": "Create shared/prompts/agent-design-criteria.md by merging content from action/build-agent-mode-design-review-prompt.sh (lines 55-127, primary) and orchestrator _get_agent_design_criteria() (lines 720-734). The GHA version has all 5 anti-patterns plus 'What to Skip' section and nuance about small metadata being acceptable.", + "acceptance_criteria": "File exists at shared/prompts/agent-design-criteria.md; contains all 5 anti-patterns; includes 'What to Skip' section; is valid markdown.", + "files_affected": ["shared/prompts/agent-design-criteria.md"] + }, + { + "id": "task-1-3", + "description": "Create shared/prompts/contract-review-criteria.md by merging content from action/build-contract-verification-prompt.sh (lines 35-64, primary) and orchestrator _get_contract_review_criteria() (lines 762-783). Include the egg-contract CLI verification commands from the GHA version.", + "acceptance_criteria": "File exists at shared/prompts/contract-review-criteria.md; contains contract verification checklist with CLI commands; is valid markdown.", + "files_affected": ["shared/prompts/contract-review-criteria.md"] + }, + { + "id": "task-1-4", + "description": "Create shared/prompts/autofixer-rules.md by merging content from action/build-autofixer-prompt.sh (lines 32-46, primary) and orchestrator _build_autofix_prompt() (lines 1977-1986). Use GHA version which has 4 categories each for auto-fixable and report-only items (vs orchestrator's 3 each).", + "acceptance_criteria": "File exists at shared/prompts/autofixer-rules.md; contains auto-fixable and report-only categories; includes lock file and build failure categories from GHA version; is valid markdown.", + "files_affected": ["shared/prompts/autofixer-rules.md"] + } + ] + }, + { + "id": "phase-2", + "name": "Update GHA prompt builders to use shared files", + "description": "Replace inline criteria in GHA bash scripts with reads from shared/prompts/ files. Preserve the .egg/*-rules.md user-override mechanism where it already exists (override takes priority over shared default).", + "dependency": "phase-1", + "tasks": [ + { + "id": "task-2-1", + "description": "Update action/build-review-prompt.sh to read default review criteria from shared/prompts/code-review-criteria.md instead of inline heredoc (lines 30-77). Keep .egg/review-rules.md as the user override that takes priority. Add a fallback to the existing inline content if the shared file doesn't exist (rollout safety during the transition before this PR merges to main).", + "acceptance_criteria": "Script reads from shared/prompts/code-review-criteria.md when available; .egg/review-rules.md override still takes priority; inline fallback exists for when shared file is missing; script produces equivalent output.", + "files_affected": ["action/build-review-prompt.sh"] + }, + { + "id": "task-2-2", + "description": "Update action/build-autofixer-prompt.sh to read default autofixer rules from shared/prompts/autofixer-rules.md instead of inline content (lines 32-46). Keep .egg/autofixer-rules.md as user override. Add fallback.", + "acceptance_criteria": "Script reads from shared/prompts/autofixer-rules.md when available; .egg/autofixer-rules.md override still takes priority; fallback exists; equivalent output.", + "files_affected": ["action/build-autofixer-prompt.sh"] + }, + { + "id": "task-2-3", + "description": "Update action/build-agent-mode-design-review-prompt.sh to read agent-design criteria from shared/prompts/agent-design-criteria.md instead of inline content (lines 55-127). Add fallback.", + "acceptance_criteria": "Script reads from shared/prompts/agent-design-criteria.md when available; fallback exists; equivalent output.", + "files_affected": ["action/build-agent-mode-design-review-prompt.sh"] + }, + { + "id": "task-2-4", + "description": "Update action/build-contract-verification-prompt.sh to read contract review criteria from shared/prompts/contract-review-criteria.md instead of inline content (lines 35-64). Keep .egg/contract-rules.md as user override. Add fallback.", + "acceptance_criteria": "Script reads from shared/prompts/contract-review-criteria.md when available; .egg/contract-rules.md override still takes priority; fallback exists; equivalent output.", + "files_affected": ["action/build-contract-verification-prompt.sh"] + } + ] + }, + { + "id": "phase-3", + "name": "Update orchestrator to use shared files", + "description": "Replace hardcoded Python string criteria functions in orchestrator/routes/pipelines.py with reads from shared/prompts/ files. Also extend the .egg/*-rules.md user-override mechanism to orchestrator reviews (currently GHA-only). Add fallback to inline defaults for backward compatibility.", + "dependency": "phase-1", + "tasks": [ + { + "id": "task-3-1", + "description": "Update _get_code_review_criteria() (lines 737-759) to read from shared/prompts/code-review-criteria.md via Path(repo_path) / 'shared/prompts/code-review-criteria.md'. Add support for .egg/review-rules.md user override (check repo_path / '.egg/review-rules.md' first, use shared file as default). Add fallback to current inline content if file doesn't exist (log warning).", + "acceptance_criteria": "Function reads from shared file; .egg/review-rules.md override takes priority; falls back to inline default with warning log; existing tests still pass.", + "files_affected": ["orchestrator/routes/pipelines.py"] + }, + { + "id": "task-3-2", + "description": "Update _get_agent_design_criteria() (lines 720-734) to read from shared/prompts/agent-design-criteria.md similarly. Add fallback.", + "acceptance_criteria": "Function reads from shared file; falls back to inline default with warning; existing tests pass.", + "files_affected": ["orchestrator/routes/pipelines.py"] + }, + { + "id": "task-3-3", + "description": "Update _get_contract_review_criteria() (lines 762-783) to read from shared/prompts/contract-review-criteria.md. Add .egg/contract-rules.md user override support. Add fallback.", + "acceptance_criteria": "Function reads from shared file; .egg/contract-rules.md override takes priority; falls back to inline default with warning; existing tests pass.", + "files_affected": ["orchestrator/routes/pipelines.py"] + }, + { + "id": "task-3-4", + "description": "Update _build_autofix_prompt() autofixer rules section (lines 1977-1986) to read from shared/prompts/autofixer-rules.md. Add .egg/autofixer-rules.md user override support. Add fallback.", + "acceptance_criteria": "Function reads from shared file; .egg/autofixer-rules.md override takes priority; falls back to inline default with warning; existing tests pass.", + "files_affected": ["orchestrator/routes/pipelines.py"] + } + ] + }, + { + "id": "phase-4", + "name": "Conditional CLAUDE.md assembly and cleanup", + "description": "Modify setup_agent_rules() to conditionally exclude SDLC-specific sections for non-pipeline agents. Remove dead code in orchestrator. This phase is independent of phases 2-3 and can run in parallel.", + "dependency": null, + "tasks": [ + { + "id": "task-4-1", + "description": "Modify setup_agent_rules() in sandbox/entrypoint.py (line 678) to check for EGG_PIPELINE_ID environment variable. When EGG_PIPELINE_ID is not set, exclude contract.md and orchestrator.md from rules_order. Keep mission.md, environment.md, code-standards.md, test-workflow.md, and pr-descriptions.md for all invocations.", + "acceptance_criteria": "When EGG_PIPELINE_ID is set, all 7 rule files are included (unchanged behavior). When EGG_PIPELINE_ID is not set, contract.md and orchestrator.md are excluded. Combined CLAUDE.md is ~5.8 KB smaller for non-SDLC invocations.", + "files_affected": ["sandbox/entrypoint.py"] + }, + { + "id": "task-4-2", + "description": "Remove dead code in _build_phase_prompt() at lines 1166-1181 (refine phase) and 1196-1211 (plan phase) where if/else branches on is_local produce identical output. Replace with the common code without the conditional.", + "acceptance_criteria": "Redundant is_local branches removed for refine and plan phases. Behavior unchanged (both branches produce identical output). No test regressions.", + "files_affected": ["orchestrator/routes/pipelines.py"] + } + ] + }, + { + "id": "phase-5", + "name": "Tests", + "description": "Update and add tests to verify shared criteria loading, fallback behavior, and conditional CLAUDE.md assembly. Run full test suite to catch regressions.", + "dependency": "phase-2, phase-3, phase-4", + "tasks": [ + { + "id": "task-5-1", + "description": "Update tests/action/test_build_review_prompt.py to verify that shared/prompts/code-review-criteria.md content appears in the review prompt output. Add test case for fallback when shared file is missing. Add test case for .egg/review-rules.md user override taking priority.", + "acceptance_criteria": "Tests verify shared file content in output; test fallback path; test user override priority. All tests pass.", + "files_affected": ["tests/action/test_build_review_prompt.py"] + }, + { + "id": "task-5-2", + "description": "Update tests/action/test_build_agent_mode_design_review_prompt.py to verify shared/prompts/agent-design-criteria.md content appears in output. Add fallback test.", + "acceptance_criteria": "Tests verify shared file content in output; test fallback path. All tests pass.", + "files_affected": ["tests/action/test_build_agent_mode_design_review_prompt.py"] + }, + { + "id": "task-5-3", + "description": "Update orchestrator/tests/test_pipeline_prompts.py to verify orchestrator criteria functions read from shared files. Add test for fallback when files are missing. Add test for .egg/*-rules.md user override mechanism in orchestrator.", + "acceptance_criteria": "Tests verify shared file reads for _get_code_review_criteria, _get_agent_design_criteria, _get_contract_review_criteria, and autofixer rules. Tests verify fallback behavior. Tests verify user override priority. All tests pass.", + "files_affected": ["orchestrator/tests/test_pipeline_prompts.py"] + }, + { + "id": "task-5-4", + "description": "Add test for conditional CLAUDE.md assembly in setup_agent_rules(). Test with EGG_PIPELINE_ID set (all rules included) and without (contract.md and orchestrator.md excluded). May require a new test file or addition to existing sandbox/entrypoint tests.", + "acceptance_criteria": "Tests verify conditional inclusion/exclusion based on EGG_PIPELINE_ID. Both paths tested. All tests pass.", + "files_affected": ["tests/sandbox/test_entrypoint.py"] + } + ] + } + ], + + "acceptance_criteria": [ + { + "id": "ac-1", + "description": "Shared prompt criteria files exist in shared/prompts/ with unified content from both GHA and orchestrator sources" + }, + { + "id": "ac-2", + "description": "GHA prompt scripts read criteria from shared files with fallback to inline defaults" + }, + { + "id": "ac-3", + "description": "Orchestrator criteria functions read from shared files with fallback to inline defaults" + }, + { + "id": "ac-4", + "description": ".egg/*-rules.md user-override mechanism works in both GHA and orchestrator" + }, + { + "id": "ac-5", + "description": "CLAUDE.md excludes contract.md and orchestrator.md for non-SDLC invocations" + }, + { + "id": "ac-6", + "description": "Dead code (redundant is_local branches) removed from orchestrator" + }, + { + "id": "ac-7", + "description": "All existing tests pass; new tests added for shared file loading, fallback, and conditional assembly" + } + ], + + "dependency_graph": { + "phase-1": [], + "phase-2": ["phase-1"], + "phase-3": ["phase-1"], + "phase-4": [], + "phase-5": ["phase-2", "phase-3", "phase-4"] + }, + + "parallelism_notes": "Phase 1 and Phase 4 have no dependencies and can start immediately. Phase 2 and Phase 3 can run in parallel after Phase 1 completes. Phase 5 (tests) should run last after all code changes are complete. In a multi-agent setup: coder handles phases 1-4, tester handles phase 5.", + + "test_strategy": { + "approach": "Update existing tests and add targeted new tests for changed behavior", + "existing_test_files": [ + "tests/action/test_build_review_prompt.py", + "tests/action/test_build_agent_mode_design_review_prompt.py", + "orchestrator/tests/test_pipeline_prompts.py" + ], + "new_test_coverage": [ + "Shared file loading: verify criteria functions read from shared/prompts/ files", + "Fallback behavior: verify inline defaults used when shared files are missing", + "User override priority: verify .egg/*-rules.md files take precedence over shared defaults", + "Conditional CLAUDE.md: verify contract.md and orchestrator.md excluded when EGG_PIPELINE_ID unset" + ], + "test_commands": [ + "PYTHONPATH=shared pytest tests/action/ -v", + "PYTHONPATH=shared pytest orchestrator/tests/test_pipeline_prompts.py -v", + "make test (full suite via act)" + ], + "regression_strategy": "Run full test suite before and after changes. Existing tests for GHA prompt builders and orchestrator prompts will catch regressions in output format. New tests verify the shared file mechanism." + }, + + "risk_mitigations": [ + { + "risk": "GHA trusted checkout won't have shared/prompts/ files during rollout", + "mitigation": "All GHA scripts retain inline fallback defaults. Shared files are only used when present. After PR merges to main, shared files become available to all subsequent GHA runs." + }, + { + "risk": "Orchestrator can't find shared/prompts/ at runtime", + "mitigation": "Use EGG_REPO_PATH / 'shared/prompts/' with fallback to inline defaults. Log warning when falling back." + }, + { + "risk": "Breaking existing tests", + "mitigation": "Run existing tests as baseline before changes. Update test assertions to account for shared file reads. Phase 5 ensures all tests pass before PR." + } + ], + + "out_of_scope": [ + { + "item": "Unifying slash commands with orchestrator _build_agent_prompt()", + "reason": "Per architect recommendation: slash commands have different format than _build_agent_prompt() output. Unifying requires more design work. Defer to follow-up issue." + }, + { + "item": "Removing sandbox/claude-rules/ symlink", + "reason": "Low priority, functionally harmless. The symlink and .claude/rules/ reference the same files. Can be addressed in a separate cleanup PR." + }, + { + "item": "Extracting unified review criteria (_get_unified_criteria) to shared files", + "reason": "Phase-specific unified criteria are orchestrator-only with no GHA equivalent. No duplication to resolve." + } + ] +} diff --git a/action/README.md b/action/README.md index 3e50a055d7..4a0a23d9dc 100644 --- a/action/README.md +++ b/action/README.md @@ -26,6 +26,8 @@ This action runs the egg autonomous coding agent within GitHub Actions. It sets | `autofixer-conventions.md` | Autofixer workflow conventions | | `conflict-conventions.md` | Merge conflict resolution conventions | +Prompt builders load review criteria from `shared/prompts/` (shared with the local orchestrator) with inline fallbacks for rollout safety. Repositories can override criteria via `.egg/` files (e.g., `.egg/review-rules.md`). + ## Quick Start ```yaml diff --git a/action/build-agent-mode-design-review-prompt.sh b/action/build-agent-mode-design-review-prompt.sh index 7f0f1952de..faa4043ba2 100755 --- a/action/build-agent-mode-design-review-prompt.sh +++ b/action/build-agent-mode-design-review-prompt.sh @@ -16,35 +16,23 @@ set -euo pipefail # --------------------------------------------------------------------------- -# Build the prompt +# Fetch agent-design criteria (or use defaults) # --------------------------------------------------------------------------- -build_prompt() { - local prompt - local is_rereview=false - - # Check if this is a re-review (we have a previous review commit) - if [[ -n "${LAST_REVIEW_COMMIT:-}" ]]; then - is_rereview=true - prompt="**Specialized review**: Check PR #${PR_NUMBER} in ${GITHUB_REPOSITORY} for agent-mode design alignment. - -This is a **re-review** — you previously reviewed this PR at commit \`${LAST_REVIEW_COMMIT}\`. - -## Scope - -This is a specialized design review, NOT a general code review. A separate bot handles general code quality, security, and correctness. Your job is to assess agent-mode design alignment. - -**Only comment if you find agent-mode design issues.** If the PR has no agent-mode concerns, approve with a brief note like \"No agent-mode design concerns\" — don't provide general feedback. - -## Re-review Task - -1. Use \`git diff ${LAST_REVIEW_COMMIT}..HEAD\` to see changes since your last review. -2. Use \`gh pr view ${PR_NUMBER} --comments\` to check if previous feedback was addressed. -3. Focus only on the delta — don't re-review unchanged code. +fetch_agent_design_criteria() { + local script_dir + script_dir="$(dirname "$0")" + local shared_file="${script_dir}/../shared/prompts/agent-design-criteria.md" + if [[ -f "$shared_file" ]]; then + # Shared criteria (anchored to trusted checkout via script dir) + cat "$shared_file" + else + # Inline fallback for rollout safety + cat <<'EOF' ## Review Philosophy -The guidelines in \`docs/guides/agent-mode-design.md\` are **guidelines, not absolute rules**. Apply them with judgment: +The guidelines in `docs/guides/agent-mode-design.md` are **guidelines, not absolute rules**. Apply them with judgment: - **Orienting vs constraining**: The key question is whether context *helps* the agent work effectively or *constrains* its ability to explore. Lightweight metadata, task context, and small summaries that orient the agent are fine—even encouraged. The concern is with large pre-fetched diffs or logs that prevent the agent from seeing what it needs. @@ -68,6 +56,41 @@ Flag these **clear** anti-patterns: - Security issues unrelated to agent design — the base review bot covers this - Correctness/logic errors — the base review bot covers this - Borderline cases where the design choice is reasonable +EOF + fi +} + +# --------------------------------------------------------------------------- +# Build the prompt +# --------------------------------------------------------------------------- + +build_prompt() { + local agent_design_criteria + agent_design_criteria=$(fetch_agent_design_criteria) + + local prompt + local is_rereview=false + + # Check if this is a re-review (we have a previous review commit) + if [[ -n "${LAST_REVIEW_COMMIT:-}" ]]; then + is_rereview=true + prompt="**Specialized review**: Check PR #${PR_NUMBER} in ${GITHUB_REPOSITORY} for agent-mode design alignment. + +This is a **re-review** — you previously reviewed this PR at commit \`${LAST_REVIEW_COMMIT}\`. + +## Scope + +This is a specialized design review, NOT a general code review. A separate bot handles general code quality, security, and correctness. Your job is to assess agent-mode design alignment. + +**Only comment if you find agent-mode design issues.** If the PR has no agent-mode concerns, approve with a brief note like \"No agent-mode design concerns\" — don't provide general feedback. + +## Re-review Task + +1. Use \`git diff ${LAST_REVIEW_COMMIT}..HEAD\` to see changes since your last review. +2. Use \`gh pr view ${PR_NUMBER} --comments\` to check if previous feedback was addressed. +3. Focus only on the delta — don't re-review unchanged code. + +${agent_design_criteria} ## Posting Your Review @@ -99,32 +122,9 @@ This is a specialized design review, NOT a general code review. A separate bot h **Only comment if you find agent-mode design issues.** If the PR has no agent-mode concerns, approve with a brief note like \"No agent-mode design concerns\" — don't provide general feedback. -## Review Philosophy - -Use \`gh pr diff ${PR_NUMBER}\` to see changes. Read \`docs/guides/agent-mode-design.md\` for context, but remember: **these are guidelines, not absolute rules**. Apply them with judgment: +Use \`gh pr diff ${PR_NUMBER}\` to see changes. Read \`docs/guides/agent-mode-design.md\` for context. -- **Orienting vs constraining**: The key question is whether context *helps* the agent work effectively or *constrains* its ability to explore. Lightweight metadata, task context, and small summaries that orient the agent are fine—even encouraged. The concern is with large pre-fetched diffs or logs that prevent the agent from seeing what it needs. - -- **Practical balance**: A design that's 80% aligned but works well is better than 100% pure but fragile. Preserve useful functionality while avoiding unnecessary complexity. - -- **Benefit of the doubt**: If a design choice could be interpreted as either helpful orientation or problematic pre-fetching, lean toward the charitable interpretation unless there's clear evidence of harm. - -## What to Look For - -Flag these **clear** anti-patterns: - -1. **Excessive pre-fetching**: Baking *large* diffs (10KB+) or full file contents into prompts. Small metadata and task context are fine. -2. **Structured output for humans**: Requiring JSON when output goes directly to humans (PR comments, reviews) -3. **Post-processing pipelines**: Scripts that parse agent output to take actions the agent could take directly -4. **Rigid procedures**: Micromanaging step-by-step procedures when objectives would suffice -5. **Prompt-level security**: Using instructions for constraints that should be sandbox-enforced - -## What to Skip - -- General code quality, style, naming — the base review bot covers this -- Security issues unrelated to agent design — the base review bot covers this -- Correctness/logic errors — the base review bot covers this -- Borderline cases where the design choice is reasonable +${agent_design_criteria} ## Posting Your Review diff --git a/action/build-autofixer-prompt.sh b/action/build-autofixer-prompt.sh index ac62581d5d..dca4a362ef 100755 --- a/action/build-autofixer-prompt.sh +++ b/action/build-autofixer-prompt.sh @@ -24,11 +24,18 @@ set -euo pipefail fetch_autofixer_rules() { local rules_file=".egg/autofixer-rules.md" + local script_dir + script_dir="$(dirname "$0")" + local shared_file="${script_dir}/../shared/prompts/autofixer-rules.md" if [[ -f "$rules_file" ]]; then + # User override takes priority cat "$rules_file" + elif [[ -f "$shared_file" ]]; then + # Shared criteria (anchored to trusted checkout via script dir) + cat "$shared_file" else - # Default autofixer rules when no repo-specific rules exist + # Inline fallback for rollout safety cat <<'EOF' ## Default Autofixer Rules diff --git a/action/build-contract-verification-prompt.sh b/action/build-contract-verification-prompt.sh index 9a4cfd77a9..485ec6155a 100755 --- a/action/build-contract-verification-prompt.sh +++ b/action/build-contract-verification-prompt.sh @@ -24,11 +24,18 @@ set -euo pipefail fetch_contract_rules() { local rules_file=".egg/contract-rules.md" + local script_dir + script_dir="$(dirname "$0")" + local shared_file="${script_dir}/../shared/prompts/contract-review-criteria.md" if [[ -f "$rules_file" ]]; then + # User override takes priority cat "$rules_file" + elif [[ -f "$shared_file" ]]; then + # Shared criteria (anchored to trusted checkout via script dir) + cat "$shared_file" else - # Default contract verification rules when no repo-specific rules exist + # Inline fallback for rollout safety cat <<'EOF' ## Default Contract Verification Rules diff --git a/action/build-review-prompt.sh b/action/build-review-prompt.sh index 0610833b5a..ab2479fd4c 100755 --- a/action/build-review-prompt.sh +++ b/action/build-review-prompt.sh @@ -22,11 +22,18 @@ set -euo pipefail fetch_review_rules() { local rules_file=".egg/review-rules.md" + local script_dir + script_dir="$(dirname "$0")" + local shared_file="${script_dir}/../shared/prompts/code-review-criteria.md" if [[ -f "$rules_file" ]]; then + # User override takes priority cat "$rules_file" + elif [[ -f "$shared_file" ]]; then + # Shared criteria (anchored to trusted checkout via script dir) + cat "$shared_file" else - # Default review rules when no repo-specific rules exist + # Inline fallback for rollout safety cat <<'EOF' ## Default Review Rules diff --git a/docs/development/STRUCTURE.md b/docs/development/STRUCTURE.md index 394ed150ef..5993978cdc 100644 --- a/docs/development/STRUCTURE.md +++ b/docs/development/STRUCTURE.md @@ -24,7 +24,7 @@ egg/ | Directory | Purpose | Runs In | |-----------|---------|---------| -| `bin/` | CLI entry points (`egg`, `setup-gateway`) | Host | +| `bin/` | CLI entry points (`egg`, `egg-sdlc`, `setup-gateway`) | Host | | `config/` | Repository config, secrets template | Host | | `gateway/` | Gateway sidecar: policy enforcement, credential injection, proxying | Gateway container | | `integration_tests/` | Integration tests requiring Docker and real containers | CI / local | @@ -166,9 +166,14 @@ shared/ │ ├── agent_recovery.py # Failed agent recovery logic │ ├── checkpoints.py # Checkpoint data models │ ├── checkpoint_loader.py # Checkpoint storage and retrieval -│ ├── checkpoint_cli.py # Checkpoint browsing CLI +│ ├── checkpoint_cli.py # Checkpoint browsing CLI (list, show, browse) │ ├── transcript_extractor.py # API transcript extraction │ └── redactor.py # Sensitive data redaction for checkpoints +├── prompts/ # Shared prompt criteria (used by GHA scripts AND orchestrator) +│ ├── agent-design-criteria.md # Agent-mode design review criteria +│ ├── autofixer-rules.md # Autofixer auto-fix vs report-only rules +│ ├── code-review-criteria.md # Code review security/correctness criteria +│ └── contract-review-criteria.md # Contract verification rules ├── egg_git/ # Git utilities ├── egg_logging/ # Structured logging └── egg_orchestrator/ # Orchestrator integration layer @@ -229,6 +234,9 @@ integration_tests/ ``` tests/ +├── action/ # GitHub Action prompt builder tests +│ ├── test_build_agent_mode_design_review_prompt.py +│ └── test_build_review_prompt.py ├── sandbox/ # Sandbox component tests │ ├── test_contract_cli.py # Contract CLI tests │ └── ... @@ -241,7 +249,6 @@ tests/ │ ├── test_phase_defaults.py # Phase default configuration tests │ ├── test_deployment_config.py # Deployment configuration tests │ ├── test_agent_recovery.py # Agent recovery and circuit breaker tests -│ ├── test_checkpoints.py # Checkpoint model tests │ ├── test_redactor.py # Redactor tests for sensitive data masking │ └── test_transcript_extractor.py # Transcript extraction tests └── workflows/ # Workflow integration tests diff --git a/docs/guides/github-automation.md b/docs/guides/github-automation.md index 9e0b15e4ab..f0e6ce5af6 100644 --- a/docs/guides/github-automation.md +++ b/docs/guides/github-automation.md @@ -19,6 +19,19 @@ for how to call egg's workflows from your own repositories. | [Conflict Resolver](#conflict-resolver) | Push to main / schedule / manual | Resolves merge conflicts via merge commits | | [Doc Updater](#doc-updater) | Push to main | Checks if code changes require documentation updates | +### Shared Prompt Criteria + +Review criteria for each workflow are defined in `shared/prompts/` as markdown files. Both the GitHub Actions prompt builder scripts (`action/build-*-prompt.sh`) and the local orchestrator (`orchestrator/routes/pipelines.py`) read from the same shared files, ensuring consistent review behavior across both flows. + +| File | Used By | +|------|---------| +| `shared/prompts/code-review-criteria.md` | AI Code Review, orchestrator reviewers | +| `shared/prompts/agent-design-criteria.md` | Design Review, orchestrator reviewers | +| `shared/prompts/autofixer-rules.md` | Check Autofixer | +| `shared/prompts/contract-review-criteria.md` | Contract Verification, orchestrator reviewers | + +Repositories can override criteria by placing a custom file in `.egg/` (e.g., `.egg/review-rules.md` overrides code review criteria). + ## AI Code Review **Workflow:** [`.github/workflows/on-pull-request.yml`](../../.github/workflows/on-pull-request.yml) diff --git a/docs/index.md b/docs/index.md index ef8457ab0f..dcba7be108 100644 --- a/docs/index.md +++ b/docs/index.md @@ -115,4 +115,4 @@ Each major component has detailed documentation: --- -*Last updated: 2026-02-13* +*Last updated: 2026-02-15* diff --git a/orchestrator/Dockerfile b/orchestrator/Dockerfile index d2ccf24067..73693dc576 100644 --- a/orchestrator/Dockerfile +++ b/orchestrator/Dockerfile @@ -21,6 +21,9 @@ COPY shared/egg_config/ ./egg_config/ COPY shared/egg_contracts/ ./egg_contracts/ COPY shared/egg_container/ ./egg_container/ +# Copy shared prompt criteria files +COPY shared/prompts/ ./prompts/ + # Install dependencies COPY orchestrator/requirements.txt ./requirements.txt RUN pip install --no-cache-dir -r requirements.txt diff --git a/orchestrator/routes/pipelines.py b/orchestrator/routes/pipelines.py index e667913756..5a2dfaad8f 100644 --- a/orchestrator/routes/pipelines.py +++ b/orchestrator/routes/pipelines.py @@ -808,8 +808,45 @@ def _get_unified_criteria(phase: str) -> str: ) +def _read_shared_criteria( + filename: str, + user_override: str | None = None, + repo_path: str | None = None, +) -> str | None: + """Read shared criteria from file, checking user override first. + + Search order: + 1. .egg/ in the repo (if user_override provided) + 2. shared/prompts/ relative to source tree + 3. /app/prompts/ (Docker container path) + + Returns the file content, or None if no file found (caller uses inline fallback). + """ + # Check user override first + if user_override and repo_path: + override_path = Path(repo_path) / ".egg" / user_override + if override_path.is_file() and override_path.stat().st_size > 0: + return override_path.read_text() + + # Try source tree path (development / tests) + source_path = Path(__file__).parent.parent.parent / "shared" / "prompts" / filename + if source_path.is_file(): + return source_path.read_text() + + # Try Docker container path (production) + docker_path = Path("/app/prompts") / filename + if docker_path.is_file(): + return docker_path.read_text() + + return None + + def _get_agent_design_criteria() -> str: """Return agent-mode design review criteria.""" + content = _read_shared_criteria("agent-design-criteria.md") + if content is not None: + return content + logger.warning("Shared agent-design-criteria.md not found, using inline fallback") return ( "Flag these **clear** anti-patterns:\n\n" "1. **Excessive pre-fetching** — Baking large diffs (10KB+) or full file contents " @@ -825,8 +862,16 @@ def _get_agent_design_criteria() -> str: ) -def _get_code_review_criteria() -> str: +def _get_code_review_criteria(repo_path: str | None = None) -> str: """Return code review criteria.""" + content = _read_shared_criteria( + "code-review-criteria.md", + user_override="review-rules.md", + repo_path=repo_path, + ) + if content is not None: + return content + logger.warning("Shared code-review-criteria.md not found, using inline fallback") return ( "### Security (highest priority)\n" "- Injection vulnerabilities (SQL, command, XSS, LDAP, path traversal)\n" @@ -850,8 +895,16 @@ def _get_code_review_criteria() -> str: ) -def _get_contract_review_criteria() -> str: +def _get_contract_review_criteria(repo_path: str | None = None) -> str: """Return contract verification criteria.""" + content = _read_shared_criteria( + "contract-review-criteria.md", + user_override="contract-rules.md", + repo_path=repo_path, + ) + if content is not None: + return content + logger.warning("Shared contract-review-criteria.md not found, using inline fallback") return ( "### Task Verification\n" "For each task in the contract, verify:\n" @@ -934,16 +987,18 @@ def _get_plan_review_criteria() -> str: ) -def _get_review_criteria_for_type(reviewer_type: str, phase: str) -> str: +def _get_review_criteria_for_type( + reviewer_type: str, phase: str, repo_path: str | None = None +) -> str: """Dispatch to the correct criteria function based on reviewer type.""" if reviewer_type == "unified": return _get_unified_criteria(phase) elif reviewer_type == "agent-design": return _get_agent_design_criteria() elif reviewer_type == "code": - return _get_code_review_criteria() + return _get_code_review_criteria(repo_path=repo_path) elif reviewer_type == "contract": - return _get_contract_review_criteria() + return _get_contract_review_criteria(repo_path=repo_path) elif reviewer_type == "refine": return _get_refine_review_criteria() elif reviewer_type == "plan": @@ -1069,6 +1124,7 @@ def _build_review_prompt( issue_number: int | None = None, review_cycle: int = 1, prior_feedback: str | None = None, + repo_path: str | None = None, ) -> str: """Build a review prompt for the reviewer agent. @@ -1110,7 +1166,7 @@ def _build_review_prompt( # Review criteria lines.append("## Review Criteria\n") - lines.append(_get_review_criteria_for_type(reviewer_type, phase)) + lines.append(_get_review_criteria_for_type(reviewer_type, phase, repo_path=repo_path)) lines.append("") # Prior feedback for re-reviews @@ -1623,6 +1679,7 @@ def _build_agent_prompt( branch: str | None = None, review_feedback: str | None = None, review_cycle: int = 0, + repo_path: str | None = None, ) -> str: """Build a role-specific prompt for multi-agent execution. @@ -1645,6 +1702,7 @@ def _build_agent_prompt( branch: Branch name review_feedback: Feedback from prior review cycle review_cycle: Current review cycle number + repo_path: Filesystem path to repository (for user override lookup) Returns: Complete prompt string for the agent @@ -1835,6 +1893,7 @@ def _build_agent_prompt( issue_number=issue_number, review_cycle=review_cycle + 1, prior_feedback=review_feedback, + repo_path=repo_path, ) else: lines.extend( @@ -1928,6 +1987,7 @@ def _run_multi_agent_phase( branch=pipeline.branch, review_feedback=review_feedback, review_cycle=review_cycle, + repo_path=str(worktree_repo_path), ) # Map using the orchestrator's AgentRole enum try: @@ -2326,6 +2386,7 @@ def _build_autofix_prompt( pipeline_mode: str, check_results: dict, repo: str | None = None, + repo_path: str | None = None, ) -> str: """Build a prompt for the autofixer agent. @@ -2371,17 +2432,33 @@ def _build_autofix_prompt( "(lint errors, formatting, simple type errors, obvious test fixes), make the fix", "4. **Verify locally**: Run the same checks again to confirm fixes work", "5. **Commit all fixes together** with a descriptive message\n", - "## Auto-fixable vs Report-only\n", - "**Auto-fixable (commit fixes directly):**", - "- Lint errors (formatting, import order, code style)", - "- Type errors with clear fixes", - "- Simple test failures with obvious fixes\n", - "**Report only (note in commit message):**", - "- Complex logic errors requiring design decisions", - "- Security issues requiring architectural changes", - "- Test failures from unclear requirements", ] ) + + # Load autofixer rules from shared file or use inline fallback + autofixer_rules = _read_shared_criteria( + "autofixer-rules.md", + user_override="autofixer-rules.md", + repo_path=repo_path, + ) + if autofixer_rules is not None: + lines.append(autofixer_rules) + else: + logger.warning("Shared autofixer-rules.md not found, using inline fallback") + lines.extend( + [ + "## Auto-fixable vs Report-only\n", + "**Auto-fixable (commit fixes directly):**", + "- Lint errors (formatting, import order, code style)", + "- Type errors with clear fixes", + "- Simple test failures with obvious fixes\n", + "**Report only (note in commit message):**", + "- Complex logic errors requiring design decisions", + "- Security issues requiring architectural changes", + "- Test failures from unclear requirements", + ] + ) + return "\n".join(lines) @@ -3162,6 +3239,7 @@ def _run_pipeline(pipeline_id: str, repo_path: Path) -> None: pipeline_mode, check_results, repo=pipeline.repo, + repo_path=str(worktree_repo_path), ) autofix_command = [ "claude", @@ -3240,6 +3318,7 @@ def _spawn_reviewer( # type: ignore[no-untyped-def] _review_feedback=review_feedback, _sandbox_env=sandbox_env, _repos=repos, + _repo_path=worktree_repo_path, ): role_str = role.value rtype = role_str.replace("reviewer_", "", 1).replace("_", "-") @@ -3251,6 +3330,7 @@ def _spawn_reviewer( # type: ignore[no-untyped-def] issue_number=_pipeline.issue_number, review_cycle=_review_cycle + 1, prior_feedback=_review_feedback, + repo_path=str(_repo_path), ) reviewer_command = [ "claude", diff --git a/orchestrator/tests/test_pipeline_prompts.py b/orchestrator/tests/test_pipeline_prompts.py index 844078f3f4..cb2d373365 100644 --- a/orchestrator/tests/test_pipeline_prompts.py +++ b/orchestrator/tests/test_pipeline_prompts.py @@ -3,7 +3,9 @@ """ import sys -from unittest.mock import MagicMock +import tempfile +from pathlib import Path +from unittest.mock import MagicMock, patch # Mock heavy dependencies that pipelines.py imports at module level _docker_mock = MagicMock() @@ -11,7 +13,14 @@ sys.modules.setdefault("docker.errors", _docker_mock.errors) sys.modules.setdefault("docker.types", _docker_mock.types) -from routes.pipelines import _build_autofix_prompt, _build_checker_prompt +from routes.pipelines import ( + _build_autofix_prompt, + _build_checker_prompt, + _get_agent_design_criteria, + _get_code_review_criteria, + _get_contract_review_criteria, + _read_shared_criteria, +) class TestBuildCheckerPrompt: @@ -99,3 +108,275 @@ def test_includes_pipeline_metadata(self): result = _build_autofix_prompt("pid-99", "issue", results) assert "pid-99" in result assert "issue" in result + + def test_autofix_includes_shared_rules(self): + """Autofix prompt loads rules from shared/prompts/autofixer-rules.md.""" + results = {"checks": [{"name": "lint", "passed": False, "output": "3 errors"}]} + result = _build_autofix_prompt("pid-1", "local", results) + # The shared file content should appear in the prompt + assert "Auto-fixable" in result or "auto-fixable" in result.lower() + + +class TestReadSharedCriteria: + """Tests for _read_shared_criteria helper function.""" + + def test_reads_from_source_tree(self): + """Reads criteria from shared/prompts/ in the source tree.""" + content = _read_shared_criteria("code-review-criteria.md") + assert content is not None + assert "Security" in content + + def test_returns_none_for_missing_file(self): + """Returns None when no file is found.""" + content = _read_shared_criteria("nonexistent-file.md") + assert content is None + + def test_user_override_takes_priority(self): + """User override file takes priority over shared file.""" + with tempfile.TemporaryDirectory() as tmpdir: + egg_dir = Path(tmpdir) / ".egg" + egg_dir.mkdir() + (egg_dir / "review-rules.md").write_text("## Custom Override\nCustom content.") + + content = _read_shared_criteria( + "code-review-criteria.md", + user_override="review-rules.md", + repo_path=tmpdir, + ) + assert content is not None + assert "Custom Override" in content + assert "Custom content" in content + + def test_shared_file_when_no_override(self): + """Falls through to shared file when no user override exists.""" + with tempfile.TemporaryDirectory() as tmpdir: + content = _read_shared_criteria( + "code-review-criteria.md", + user_override="review-rules.md", + repo_path=tmpdir, + ) + assert content is not None + # Should contain shared file content, not None + assert "Security" in content + + +class TestGetCodeReviewCriteria: + """Tests for _get_code_review_criteria with shared file loading.""" + + def test_returns_criteria_content(self): + """Returns review criteria content.""" + result = _get_code_review_criteria() + assert "Security" in result + + def test_loads_from_shared_file(self): + """Criteria loads from shared/prompts/code-review-criteria.md.""" + result = _get_code_review_criteria() + # Shared file has enriched content compared to inline fallback + assert "How to Review" in result + + def test_user_override(self): + """Supports .egg/review-rules.md user override.""" + with tempfile.TemporaryDirectory() as tmpdir: + egg_dir = Path(tmpdir) / ".egg" + egg_dir.mkdir() + (egg_dir / "review-rules.md").write_text("## My Custom Rules") + + result = _get_code_review_criteria(repo_path=tmpdir) + assert "My Custom Rules" in result + + def test_inline_fallback(self): + """Falls back to inline criteria when shared file is missing.""" + # Patch _read_shared_criteria to return None (simulating missing files) + with patch("routes.pipelines._read_shared_criteria", return_value=None): + result = _get_code_review_criteria() + assert "Security" in result + assert "Correctness" in result + + +class TestGetAgentDesignCriteria: + """Tests for _get_agent_design_criteria with shared file loading.""" + + def test_returns_criteria_content(self): + """Returns agent-design criteria content.""" + result = _get_agent_design_criteria() + assert "pre-fetching" in result.lower() + + def test_loads_from_shared_file(self): + """Criteria loads from shared/prompts/agent-design-criteria.md.""" + result = _get_agent_design_criteria() + # Shared file has enriched content including review philosophy + assert "guidelines, not absolute rules" in result + + def test_inline_fallback(self): + """Falls back to inline criteria when shared file is missing.""" + with patch("routes.pipelines._read_shared_criteria", return_value=None): + result = _get_agent_design_criteria() + assert "Excessive pre-fetching" in result + assert "Rigid procedures" in result + + +class TestGetContractReviewCriteria: + """Tests for _get_contract_review_criteria with shared file loading.""" + + def test_returns_criteria_content(self): + """Returns contract review criteria content.""" + result = _get_contract_review_criteria() + assert "Task Verification" in result + + def test_user_override(self): + """Supports .egg/contract-rules.md user override.""" + with tempfile.TemporaryDirectory() as tmpdir: + egg_dir = Path(tmpdir) / ".egg" + egg_dir.mkdir() + (egg_dir / "contract-rules.md").write_text("## Custom Contract Rules") + + result = _get_contract_review_criteria(repo_path=tmpdir) + assert "Custom Contract Rules" in result + + def test_inline_fallback(self): + """Falls back to inline criteria when shared file is missing.""" + with patch("routes.pipelines._read_shared_criteria", return_value=None): + result = _get_contract_review_criteria() + assert "Task Verification" in result + assert "Contract Integrity" in result + + +class TestReadSharedCriteriaEdgeCases: + """Additional edge case tests for _read_shared_criteria.""" + + def test_user_override_without_repo_path_ignored(self): + """User override is ignored when repo_path is None.""" + # Even with user_override name, if no repo_path, skip override + content = _read_shared_criteria( + "code-review-criteria.md", + user_override="review-rules.md", + repo_path=None, + ) + # Should still return content from shared file + assert content is not None + assert "Security" in content + + def test_user_override_without_egg_dir(self): + """Falls through when .egg dir doesn't exist in repo.""" + with tempfile.TemporaryDirectory() as tmpdir: + # No .egg directory created + content = _read_shared_criteria( + "code-review-criteria.md", + user_override="review-rules.md", + repo_path=tmpdir, + ) + # Should fall through to shared file + assert content is not None + assert "Security" in content + + def test_reads_all_shared_prompt_files(self): + """All four shared prompt files are readable.""" + for filename in [ + "agent-design-criteria.md", + "autofixer-rules.md", + "code-review-criteria.md", + "contract-review-criteria.md", + ]: + content = _read_shared_criteria(filename) + assert content is not None, f"Failed to read {filename}" + assert len(content) > 0, f"Empty content for {filename}" + + def test_docker_path_fallback(self): + """Falls through to Docker path when source tree path doesn't exist.""" + docker_content = "## Docker Path Content" + original_is_file = Path.is_file + original_read_text = Path.read_text + + def mock_is_file(self): + s = str(self) + # Block source tree match for our test file + if s.endswith("shared/prompts/docker-only-test.md"): + return False + # Simulate Docker path existing + if s == "/app/prompts/docker-only-test.md": + return True + return original_is_file(self) + + def mock_read_text(self, *args, **kwargs): + if str(self) == "/app/prompts/docker-only-test.md": + return docker_content + return original_read_text(self, *args, **kwargs) + + with patch.object(Path, "is_file", mock_is_file), \ + patch.object(Path, "read_text", mock_read_text): + content = _read_shared_criteria("docker-only-test.md") + assert content == docker_content + + def test_empty_override_file_is_ignored(self): + """An existing but empty override file is skipped (falls through to shared).""" + with tempfile.TemporaryDirectory() as tmpdir: + egg_dir = Path(tmpdir) / ".egg" + egg_dir.mkdir() + (egg_dir / "review-rules.md").write_text("") + + content = _read_shared_criteria( + "code-review-criteria.md", + user_override="review-rules.md", + repo_path=tmpdir, + ) + # Empty override is treated as absent; falls through to shared file + assert content is not None + assert "Security" in content + + def test_autofix_prompt_falls_back_when_shared_missing(self): + """_build_autofix_prompt uses inline fallback when shared file is missing.""" + results = {"checks": [{"name": "lint", "passed": False, "output": "err"}]} + with patch("routes.pipelines._read_shared_criteria", return_value=None): + result = _build_autofix_prompt("pid-1", "local", results) + assert "Auto-fixable" in result + assert "Report only" in result + + +class TestSharedPromptFileContent: + """Tests that shared prompt files contain expected content and structure.""" + + def test_agent_design_criteria_has_key_sections(self): + """agent-design-criteria.md has expected sections.""" + content = _read_shared_criteria("agent-design-criteria.md") + assert content is not None + assert "## Review Philosophy" in content + assert "## What to Look For" in content + assert "## What to Skip" in content + + def test_code_review_criteria_has_key_sections(self): + """code-review-criteria.md has expected sections.""" + content = _read_shared_criteria("code-review-criteria.md") + assert content is not None + assert "Security" in content + assert "Correctness" in content + assert "Robustness" in content + assert "How to Review" in content + + def test_contract_review_criteria_has_key_sections(self): + """contract-review-criteria.md has expected sections.""" + content = _read_shared_criteria("contract-review-criteria.md") + assert content is not None + assert "Task Verification" in content + assert "Phase Consistency" in content + assert "Contract Integrity" in content + + def test_autofixer_rules_has_key_sections(self): + """autofixer-rules.md has expected sections.""" + content = _read_shared_criteria("autofixer-rules.md") + assert content is not None + assert "Auto-fixable" in content + assert "Report only" in content + + def test_shared_files_are_format_agnostic(self): + """Shared prompt files don't contain output-format-specific content.""" + for filename in [ + "agent-design-criteria.md", + "autofixer-rules.md", + "code-review-criteria.md", + "contract-review-criteria.md", + ]: + content = _read_shared_criteria(filename) + assert content is not None + # Should not contain gh commands (format-agnostic per the HTML comments) + assert "gh pr review" not in content, f"{filename} contains gh pr review" + assert "GITHUB_OUTPUT" not in content, f"{filename} contains GITHUB_OUTPUT" diff --git a/sandbox/entrypoint.py b/sandbox/entrypoint.py index 8ae6547e49..d1385b4f63 100644 --- a/sandbox/entrypoint.py +++ b/sandbox/entrypoint.py @@ -678,16 +678,20 @@ def setup_egg_symlink(config: Config, logger: Logger) -> None: def setup_agent_rules(config: Config, logger: Logger) -> None: """Set up CLAUDE.md agent rules.""" rules_dir = Path("/opt/claude-rules") + + # Core rules always included rules_order = [ "mission.md", "environment.md", "code-standards.md", "test-workflow.md", "pr-descriptions.md", - "contract.md", - "orchestrator.md", ] + # SDLC-specific rules only included when running in a pipeline + if os.environ.get("EGG_PIPELINE_ID"): + rules_order.extend(["contract.md", "orchestrator.md"]) + if not (rules_dir / "mission.md").exists(): return diff --git a/shared/README.md b/shared/README.md index 632bf25470..2c6cdb5595 100644 --- a/shared/README.md +++ b/shared/README.md @@ -152,6 +152,19 @@ mode = DeploymentMode.from_env() - `detection.py` - Orchestrator mode detection utilities - `constants.py` - Configuration constants +### prompts + +Shared prompt criteria files consumed by both GitHub Actions prompt builder scripts (`action/build-*-prompt.sh`) and the local orchestrator (`orchestrator/routes/pipelines.py`). Keeping criteria in shared markdown files ensures consistent review behavior across both flows. + +| File | Purpose | +|------|---------| +| `agent-design-criteria.md` | Agent-mode design review criteria | +| `autofixer-rules.md` | Auto-fix vs report-only classification rules | +| `code-review-criteria.md` | Security, correctness, and robustness review criteria | +| `contract-review-criteria.md` | SDLC contract verification rules | + +These files are output-format-agnostic (no `gh` commands or verdict JSON references). Repositories can override criteria by placing a custom file in `.egg/` (e.g., `.egg/review-rules.md`). + ### egg_contracts SDLC contract models, role-based validation, plan parsing, resilience utilities, and agent checkpoint capture. diff --git a/shared/prompts/agent-design-criteria.md b/shared/prompts/agent-design-criteria.md new file mode 100644 index 0000000000..387d745e63 --- /dev/null +++ b/shared/prompts/agent-design-criteria.md @@ -0,0 +1,29 @@ + + +## Review Philosophy + +The guidelines in `docs/guides/agent-mode-design.md` are **guidelines, not absolute rules**. Apply them with judgment: + +- **Orienting vs constraining**: The key question is whether context *helps* the agent work effectively or *constrains* its ability to explore. Lightweight metadata, task context, and small summaries that orient the agent are fine—even encouraged. The concern is with large pre-fetched diffs or logs that prevent the agent from seeing what it needs. + +- **Practical balance**: A design that's 80% aligned but works well is better than 100% pure but fragile. Preserve useful functionality while avoiding unnecessary complexity. + +- **Benefit of the doubt**: If a design choice could be interpreted as either helpful orientation or problematic pre-fetching, lean toward the charitable interpretation unless there's clear evidence of harm. + +## What to Look For + +Flag these **clear** anti-patterns: + +1. **Excessive pre-fetching**: Baking *large* diffs (10KB+) or full file contents into prompts. Small metadata and task context are fine. +2. **Structured output for humans**: Requiring JSON when output goes directly to humans (PR comments, reviews) +3. **Post-processing pipelines**: Scripts that parse agent output to take actions the agent could take directly +4. **Rigid procedures**: Micromanaging step-by-step procedures when objectives would suffice +5. **Prompt-level security**: Using instructions for constraints that should be sandbox-enforced + +## What to Skip + +- General code quality, style, naming — the base review bot covers this +- Security issues unrelated to agent design — the base review bot covers this +- Correctness/logic errors — the base review bot covers this +- Borderline cases where the design choice is reasonable diff --git a/shared/prompts/autofixer-rules.md b/shared/prompts/autofixer-rules.md new file mode 100644 index 0000000000..16070bb783 --- /dev/null +++ b/shared/prompts/autofixer-rules.md @@ -0,0 +1,16 @@ + + +## Default Autofixer Rules + +**Auto-fixable (commit fixes directly):** +- Lint errors (formatting, import order, code style) +- Type errors with clear fixes +- Simple test failures with obvious fixes +- Missing or outdated dependencies in lock files + +**Report only (post comment explaining what's needed):** +- Complex logic errors requiring design decisions +- Security issues requiring architectural changes +- Test failures from unclear requirements +- Build failures from missing environment config diff --git a/shared/prompts/code-review-criteria.md b/shared/prompts/code-review-criteria.md new file mode 100644 index 0000000000..90835b375a --- /dev/null +++ b/shared/prompts/code-review-criteria.md @@ -0,0 +1,49 @@ + + +## Default Review Rules + +**Be extremely thorough.** This is critical infrastructure. Identify ALL issues in the first pass—do not stop after finding a few. A false negative (missing a bug) is far worse than extra scrutiny. + +### What to Review + +**Security** (highest priority): +- Injection vulnerabilities (SQL, command, XSS, LDAP, path traversal) +- Authentication/authorization flaws +- Credential exposure, hardcoded secrets +- Insecure cryptography or randomness +- SSRF, open redirects, unsafe deserialization + +**Correctness**: +- Logic errors, off-by-one, boundary conditions +- Race conditions, deadlocks, concurrency bugs +- Null/undefined handling, missing error paths +- Resource leaks (connections, file handles, memory) +- Incorrect algorithm complexity for data size + +**Robustness**: +- Missing input validation at trust boundaries +- Unhandled exceptions that could crash the system +- Missing retry logic for transient failures +- Inadequate timeouts for external calls +- State corruption scenarios + +**Design issues**: +- Violations of existing codebase patterns +- Breaking changes to public interfaces +- Missing or incorrect abstractions +- Tight coupling that will hinder future changes + +### How to Review + +1. **Examine every changed file systematically**. Do not skim. +2. **Read surrounding context**—check how changed code integrates with the rest of the codebase. Use file reads and grep liberally. +3. **Trace data flow** from input to output, especially for security-sensitive paths. +4. **Consider edge cases** the author may not have tested. +5. **Research when uncertain**—look up library behavior, check documentation, verify assumptions. + +### Skip + +- Style issues handled by linters (formatting, import order) +- Type annotation completeness (type checkers handle this) +- Auto-generated files (migrations, lock files) diff --git a/shared/prompts/contract-review-criteria.md b/shared/prompts/contract-review-criteria.md new file mode 100644 index 0000000000..801f937458 --- /dev/null +++ b/shared/prompts/contract-review-criteria.md @@ -0,0 +1,34 @@ + + +## Default Contract Verification Rules + +### Task Verification + +For each task in the contract, verify: + +1. **Implementation exists**: The described functionality is present in the code +2. **Acceptance criteria met**: The specific acceptance criteria for the task is satisfied +3. **Commit linked**: If a commit is linked, verify it relates to the task +4. **Tests present**: Where applicable, tests cover the new functionality + +### Phase Consistency + +Check that: +- All tasks in completed phases are actually implemented +- Phase status matches task completion state +- No orphaned code exists that isn't covered by any task + +### Acceptance Criteria Verification + +For each acceptance criterion in the contract: +1. Read the criterion description +2. Examine the implementation to verify it meets the criterion +3. Note any gaps in your review + +### Contract Integrity + +Verify: +- No implementation changes violate previously verified criteria +- New changes don't break existing contract compliance +- All required files listed in tasks are present diff --git a/tests/action/test_build_agent_mode_design_review_prompt.py b/tests/action/test_build_agent_mode_design_review_prompt.py index 8b7e32c386..c7d9de82e3 100644 --- a/tests/action/test_build_agent_mode_design_review_prompt.py +++ b/tests/action/test_build_agent_mode_design_review_prompt.py @@ -1,6 +1,7 @@ """Tests for action/build-agent-mode-design-review-prompt.sh.""" import os +import shutil import subprocess import tempfile from pathlib import Path @@ -248,3 +249,55 @@ def test_empty_last_review_commit_is_initial(self) -> None: prompt = read_prompt_file(tmpdir, "123") assert "Re-review" not in prompt + + +class TestSharedCriteriaLoading: + """Tests for loading agent-design criteria from shared/prompts/ files.""" + + def test_loads_from_shared_file(self) -> None: + """Script loads agent-design criteria from shared/prompts/agent-design-criteria.md.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, stdout, stderr = run_build_prompt( + pr_number="123", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0 + prompt = read_prompt_file(tmpdir, "123") + # The shared file contains these markers + assert "guidelines, not absolute rules" in prompt + assert "Orienting vs constraining" in prompt + assert "Practical balance" in prompt + assert "Benefit of the doubt" in prompt + assert "pre-fetching" in prompt.lower() + + def test_inline_fallback_when_no_shared_file(self) -> None: + """Script falls back to inline defaults when shared file is missing.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create a fake repo with just the script, no shared files + fake_repo = Path(tmpdir) / "repo" + fake_repo.mkdir() + action_dir = fake_repo / "action" + action_dir.mkdir() + shutil.copy(BUILD_PROMPT, action_dir / "build-agent-mode-design-review-prompt.sh") + + env = os.environ.copy() + env["PR_NUMBER"] = "123" + env["GITHUB_REPOSITORY"] = "owner/repo" + env["GITHUB_OUTPUT"] = "/dev/null" + env["RUNNER_TEMP"] = tmpdir + + result = subprocess.run( + ["bash", str(action_dir / "build-agent-mode-design-review-prompt.sh")], + capture_output=True, + text=True, + env=env, + cwd=fake_repo, + ) + + assert result.returncode == 0 + prompt = read_prompt_file(tmpdir, "123") + # Falls back to inline defaults + assert "pre-fetching" in prompt.lower() + assert "Rigid procedures" in prompt diff --git a/tests/action/test_build_autofixer_prompt.py b/tests/action/test_build_autofixer_prompt.py new file mode 100644 index 0000000000..904b7911c0 --- /dev/null +++ b/tests/action/test_build_autofixer_prompt.py @@ -0,0 +1,246 @@ +"""Tests for action/build-autofixer-prompt.sh.""" + +import os +import shutil +import subprocess +import tempfile +from pathlib import Path + +# Path to the script under test +PROJECT_ROOT = Path(__file__).parent.parent.parent +BUILD_AUTOFIXER_PROMPT = PROJECT_ROOT / "action" / "build-autofixer-prompt.sh" + + +def run_build_autofixer_prompt( + pr_number: str, + github_repository: str, + failed_workflow: str = "", + failed_run_id: str = "", + runner_temp: str = "", +) -> tuple[int, str, str]: + """Run build-autofixer-prompt.sh with the given environment variables. + + Returns (returncode, stdout, stderr). + """ + env = os.environ.copy() + env["PR_NUMBER"] = pr_number + env["GITHUB_REPOSITORY"] = github_repository + env["GITHUB_OUTPUT"] = "/dev/null" + + if failed_workflow: + env["FAILED_WORKFLOW"] = failed_workflow + if failed_run_id: + env["FAILED_RUN_ID"] = failed_run_id + + if not runner_temp: + runner_temp = tempfile.gettempdir() + env["RUNNER_TEMP"] = runner_temp + + result = subprocess.run( + ["bash", str(BUILD_AUTOFIXER_PROMPT)], + capture_output=True, + text=True, + env=env, + cwd=PROJECT_ROOT, + ) + return result.returncode, result.stdout, result.stderr + + +def read_prompt_file(runner_temp: str, pr_number: str) -> str: + """Read the generated autofixer prompt file.""" + prompt_file = Path(runner_temp) / f"autofixer-prompt-{pr_number}.txt" + return prompt_file.read_text() + + +class TestBasicPromptGeneration: + """Tests for basic autofixer prompt generation.""" + + def test_generates_prompt_successfully(self) -> None: + """Script runs and produces a prompt file.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, stdout, stderr = run_build_autofixer_prompt( + pr_number="42", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0, f"Script failed: {stderr}" + prompt = read_prompt_file(tmpdir, "42") + assert "PR #42" in prompt + assert "owner/repo" in prompt + + def test_includes_investigation_instructions(self) -> None: + """Prompt includes instructions to investigate failures.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, _, _ = run_build_autofixer_prompt( + pr_number="10", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0 + prompt = read_prompt_file(tmpdir, "10") + assert "gh pr checks" in prompt + assert "Investigate" in prompt + + def test_includes_workflow_context(self) -> None: + """Prompt includes failed workflow context when provided.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, _, _ = run_build_autofixer_prompt( + pr_number="10", + github_repository="owner/repo", + failed_workflow="CI Tests", + failed_run_id="12345", + runner_temp=tmpdir, + ) + + assert returncode == 0 + prompt = read_prompt_file(tmpdir, "10") + assert "CI Tests" in prompt + assert "12345" in prompt + + def test_manual_workflow_excluded(self) -> None: + """Manual workflow name is not included in context.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, _, _ = run_build_autofixer_prompt( + pr_number="10", + github_repository="owner/repo", + failed_workflow="manual", + runner_temp=tmpdir, + ) + + assert returncode == 0 + prompt = read_prompt_file(tmpdir, "10") + # "manual" workflow should be excluded from context + assert "The **manual** workflow failed" not in prompt + + +class TestRequiredVariables: + """Tests for required environment variables.""" + + def test_fails_without_pr_number(self) -> None: + """Script fails if PR_NUMBER is not set.""" + env = os.environ.copy() + env["GITHUB_REPOSITORY"] = "owner/repo" + env.pop("PR_NUMBER", None) + + result = subprocess.run( + ["bash", str(BUILD_AUTOFIXER_PROMPT)], + capture_output=True, + text=True, + env=env, + cwd=PROJECT_ROOT, + ) + + assert result.returncode != 0 + assert "PR_NUMBER" in result.stderr + + def test_fails_without_github_repository(self) -> None: + """Script fails if GITHUB_REPOSITORY is not set.""" + env = os.environ.copy() + env["PR_NUMBER"] = "123" + env.pop("GITHUB_REPOSITORY", None) + + result = subprocess.run( + ["bash", str(BUILD_AUTOFIXER_PROMPT)], + capture_output=True, + text=True, + env=env, + cwd=PROJECT_ROOT, + ) + + assert result.returncode != 0 + assert "GITHUB_REPOSITORY" in result.stderr + + +class TestSharedCriteriaLoading: + """Tests for loading autofixer rules from shared/prompts/ files.""" + + def test_loads_from_shared_file(self) -> None: + """Script loads autofixer rules from shared/prompts/autofixer-rules.md.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, _, stderr = run_build_autofixer_prompt( + pr_number="1", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0, f"Script failed: {stderr}" + prompt = read_prompt_file(tmpdir, "1") + # Shared file markers + assert "Auto-fixable" in prompt + assert "Report only" in prompt + assert "Lint errors" in prompt + + def test_user_override_takes_priority(self) -> None: + """User .egg/autofixer-rules.md overrides shared criteria.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create a fake repo with user override + fake_repo = Path(tmpdir) / "repo" + fake_repo.mkdir() + egg_dir = fake_repo / ".egg" + egg_dir.mkdir() + (egg_dir / "autofixer-rules.md").write_text( + "## Custom Autofixer Rules\nAlways fix everything." + ) + + # Copy the action script to fake repo + action_dir = fake_repo / "action" + action_dir.mkdir() + shutil.copy(BUILD_AUTOFIXER_PROMPT, action_dir / "build-autofixer-prompt.sh") + # Copy shared dir too + shared_dir = fake_repo / "shared" / "prompts" + shared_dir.mkdir(parents=True) + shutil.copy( + PROJECT_ROOT / "shared" / "prompts" / "autofixer-rules.md", + shared_dir / "autofixer-rules.md", + ) + + env = os.environ.copy() + env["PR_NUMBER"] = "1" + env["GITHUB_REPOSITORY"] = "owner/repo" + env["GITHUB_OUTPUT"] = "/dev/null" + env["RUNNER_TEMP"] = tmpdir + + result = subprocess.run( + ["bash", str(action_dir / "build-autofixer-prompt.sh")], + capture_output=True, + text=True, + env=env, + cwd=fake_repo, + ) + + assert result.returncode == 0 + prompt = read_prompt_file(tmpdir, "1") + assert "Custom Autofixer Rules" in prompt + assert "Always fix everything" in prompt + + def test_inline_fallback_when_no_shared_file(self) -> None: + """Script falls back to inline defaults when shared file is missing.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create a fake repo with just the script, no shared files + fake_repo = Path(tmpdir) / "repo" + fake_repo.mkdir() + action_dir = fake_repo / "action" + action_dir.mkdir() + shutil.copy(BUILD_AUTOFIXER_PROMPT, action_dir / "build-autofixer-prompt.sh") + + env = os.environ.copy() + env["PR_NUMBER"] = "1" + env["GITHUB_REPOSITORY"] = "owner/repo" + env["GITHUB_OUTPUT"] = "/dev/null" + env["RUNNER_TEMP"] = tmpdir + + result = subprocess.run( + ["bash", str(action_dir / "build-autofixer-prompt.sh")], + capture_output=True, + text=True, + env=env, + cwd=fake_repo, + ) + + assert result.returncode == 0 + prompt = read_prompt_file(tmpdir, "1") + # Inline fallback content + assert "Auto-fixable" in prompt + assert "Lint errors" in prompt diff --git a/tests/action/test_build_contract_verification_prompt.py b/tests/action/test_build_contract_verification_prompt.py new file mode 100644 index 0000000000..7025432622 --- /dev/null +++ b/tests/action/test_build_contract_verification_prompt.py @@ -0,0 +1,276 @@ +"""Tests for action/build-contract-verification-prompt.sh.""" + +import os +import shutil +import subprocess +import tempfile +from pathlib import Path + +# Path to the script under test +PROJECT_ROOT = Path(__file__).parent.parent.parent +BUILD_CONTRACT_PROMPT = PROJECT_ROOT / "action" / "build-contract-verification-prompt.sh" + + +def run_build_contract_prompt( + pr_number: str, + github_repository: str, + last_review_commit: str = "", + runner_temp: str = "", +) -> tuple[int, str, str]: + """Run build-contract-verification-prompt.sh with the given environment variables. + + Returns (returncode, stdout, stderr). + """ + env = os.environ.copy() + env["PR_NUMBER"] = pr_number + env["GITHUB_REPOSITORY"] = github_repository + env["GITHUB_OUTPUT"] = "/dev/null" + + if last_review_commit: + env["LAST_REVIEW_COMMIT"] = last_review_commit + + if not runner_temp: + runner_temp = tempfile.gettempdir() + env["RUNNER_TEMP"] = runner_temp + + result = subprocess.run( + ["bash", str(BUILD_CONTRACT_PROMPT)], + capture_output=True, + text=True, + env=env, + cwd=PROJECT_ROOT, + ) + return result.returncode, result.stdout, result.stderr + + +def read_prompt_file(runner_temp: str, pr_number: str) -> str: + """Read the generated contract verification prompt file.""" + prompt_file = Path(runner_temp) / f"contract-verification-prompt-{pr_number}.txt" + return prompt_file.read_text() + + +class TestInitialVerification: + """Tests for initial contract verification (no LAST_REVIEW_COMMIT).""" + + def test_generates_initial_prompt(self) -> None: + """Script generates an initial contract verification prompt.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, stdout, stderr = run_build_contract_prompt( + pr_number="50", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0, f"Script failed: {stderr}" + prompt = read_prompt_file(tmpdir, "50") + assert "PR #50" in prompt + assert "owner/repo" in prompt + assert "comprehensive contract verification" in prompt.lower() or "Verify contract" in prompt + + def test_includes_egg_contract_cli(self) -> None: + """Prompt includes egg-contract CLI usage instructions.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, _, _ = run_build_contract_prompt( + pr_number="50", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0 + prompt = read_prompt_file(tmpdir, "50") + assert "egg-contract show" in prompt + assert "egg-contract verify-criterion" in prompt + + def test_includes_review_marker(self) -> None: + """Prompt includes review marker for tracking.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, _, _ = run_build_contract_prompt( + pr_number="50", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0 + prompt = read_prompt_file(tmpdir, "50") + assert "egg-automated-review" in prompt + assert "contract-verification" in prompt + + def test_not_a_rereview(self) -> None: + """Initial verification does not contain re-review markers.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, stdout, _ = run_build_contract_prompt( + pr_number="50", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0 + assert "type=initial" in stdout + prompt = read_prompt_file(tmpdir, "50") + assert "re-review" not in prompt.lower() or "Re-verify" not in prompt + + +class TestReVerification: + """Tests for re-verification (with LAST_REVIEW_COMMIT).""" + + def test_generates_rereview_prompt(self) -> None: + """Re-verification uses git diff from last reviewed commit.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, stdout, stderr = run_build_contract_prompt( + pr_number="50", + github_repository="owner/repo", + last_review_commit="abc123def456", + runner_temp=tmpdir, + ) + + assert returncode == 0, f"Script failed: {stderr}" + assert "re-review" in stdout + + prompt = read_prompt_file(tmpdir, "50") + assert "Re-verify" in prompt or "re-review" in prompt.lower() + assert "abc123def456" in prompt + + def test_includes_git_diff_instruction(self) -> None: + """Re-verification instructs to use git diff from last commit.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, _, _ = run_build_contract_prompt( + pr_number="50", + github_repository="owner/repo", + last_review_commit="abc123def456", + runner_temp=tmpdir, + ) + + assert returncode == 0 + prompt = read_prompt_file(tmpdir, "50") + assert "git diff abc123def456..HEAD" in prompt + + +class TestRequiredVariables: + """Tests for required environment variables.""" + + def test_fails_without_pr_number(self) -> None: + """Script fails if PR_NUMBER is not set.""" + env = os.environ.copy() + env["GITHUB_REPOSITORY"] = "owner/repo" + env.pop("PR_NUMBER", None) + + result = subprocess.run( + ["bash", str(BUILD_CONTRACT_PROMPT)], + capture_output=True, + text=True, + env=env, + cwd=PROJECT_ROOT, + ) + + assert result.returncode != 0 + assert "PR_NUMBER" in result.stderr + + def test_fails_without_github_repository(self) -> None: + """Script fails if GITHUB_REPOSITORY is not set.""" + env = os.environ.copy() + env["PR_NUMBER"] = "123" + env.pop("GITHUB_REPOSITORY", None) + + result = subprocess.run( + ["bash", str(BUILD_CONTRACT_PROMPT)], + capture_output=True, + text=True, + env=env, + cwd=PROJECT_ROOT, + ) + + assert result.returncode != 0 + assert "GITHUB_REPOSITORY" in result.stderr + + +class TestSharedCriteriaLoading: + """Tests for loading contract criteria from shared/prompts/ files.""" + + def test_loads_from_shared_file(self) -> None: + """Script loads contract rules from shared/prompts/contract-review-criteria.md.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, _, stderr = run_build_contract_prompt( + pr_number="1", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0, f"Script failed: {stderr}" + prompt = read_prompt_file(tmpdir, "1") + # Shared file markers + assert "Task Verification" in prompt + assert "Phase Consistency" in prompt + assert "Contract Integrity" in prompt + + def test_user_override_takes_priority(self) -> None: + """User .egg/contract-rules.md overrides shared criteria.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create a fake repo with user override + fake_repo = Path(tmpdir) / "repo" + fake_repo.mkdir() + egg_dir = fake_repo / ".egg" + egg_dir.mkdir() + (egg_dir / "contract-rules.md").write_text( + "## Custom Contract Rules\nVerify everything twice." + ) + + # Copy the action script + action_dir = fake_repo / "action" + action_dir.mkdir() + shutil.copy(BUILD_CONTRACT_PROMPT, action_dir / "build-contract-verification-prompt.sh") + # Copy shared dir + shared_dir = fake_repo / "shared" / "prompts" + shared_dir.mkdir(parents=True) + shutil.copy( + PROJECT_ROOT / "shared" / "prompts" / "contract-review-criteria.md", + shared_dir / "contract-review-criteria.md", + ) + + env = os.environ.copy() + env["PR_NUMBER"] = "1" + env["GITHUB_REPOSITORY"] = "owner/repo" + env["GITHUB_OUTPUT"] = "/dev/null" + env["RUNNER_TEMP"] = tmpdir + + result = subprocess.run( + ["bash", str(action_dir / "build-contract-verification-prompt.sh")], + capture_output=True, + text=True, + env=env, + cwd=fake_repo, + ) + + assert result.returncode == 0 + prompt = read_prompt_file(tmpdir, "1") + assert "Custom Contract Rules" in prompt + assert "Verify everything twice" in prompt + + def test_inline_fallback_when_no_shared_file(self) -> None: + """Script falls back to inline defaults when shared file is missing.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create a fake repo with just the script + fake_repo = Path(tmpdir) / "repo" + fake_repo.mkdir() + action_dir = fake_repo / "action" + action_dir.mkdir() + shutil.copy(BUILD_CONTRACT_PROMPT, action_dir / "build-contract-verification-prompt.sh") + + env = os.environ.copy() + env["PR_NUMBER"] = "1" + env["GITHUB_REPOSITORY"] = "owner/repo" + env["GITHUB_OUTPUT"] = "/dev/null" + env["RUNNER_TEMP"] = tmpdir + + result = subprocess.run( + ["bash", str(action_dir / "build-contract-verification-prompt.sh")], + capture_output=True, + text=True, + env=env, + cwd=fake_repo, + ) + + assert result.returncode == 0 + prompt = read_prompt_file(tmpdir, "1") + # Inline fallback content + assert "Task Verification" in prompt + assert "Contract Integrity" in prompt diff --git a/tests/action/test_build_review_prompt.py b/tests/action/test_build_review_prompt.py index 86f8fd52b6..2ae2f431b9 100644 --- a/tests/action/test_build_review_prompt.py +++ b/tests/action/test_build_review_prompt.py @@ -1,6 +1,7 @@ """Tests for action/build-review-prompt.sh.""" import os +import shutil import subprocess import tempfile from pathlib import Path @@ -314,3 +315,94 @@ def test_empty_last_review_commit_is_initial(self) -> None: prompt = read_prompt_file(tmpdir, "123") assert "Re-review" not in prompt + + +class TestSharedCriteriaLoading: + """Tests for loading review criteria from shared/prompts/ files.""" + + def test_loads_from_shared_file(self) -> None: + """Script loads review rules from shared/prompts/code-review-criteria.md.""" + with tempfile.TemporaryDirectory() as tmpdir: + returncode, stdout, stderr = run_build_review_prompt( + pr_number="123", + github_repository="owner/repo", + runner_temp=tmpdir, + ) + + assert returncode == 0 + prompt = read_prompt_file(tmpdir, "123") + # The shared file contains these markers from the merged criteria + assert "Security" in prompt + assert "Correctness" in prompt + assert "Robustness" in prompt + assert "How to Review" in prompt + + def test_user_override_takes_priority(self) -> None: + """User .egg/review-rules.md overrides shared criteria.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create a fake repo structure with user override + fake_repo = Path(tmpdir) / "repo" + fake_repo.mkdir() + egg_dir = fake_repo / ".egg" + egg_dir.mkdir() + (egg_dir / "review-rules.md").write_text("## Custom User Rules\nMy custom rules here.") + + # Copy the action script and shared files to the fake repo + action_dir = fake_repo / "action" + action_dir.mkdir() + shutil.copy(BUILD_REVIEW_PROMPT, action_dir / "build-review-prompt.sh") + shared_dir = fake_repo / "shared" / "prompts" + shared_dir.mkdir(parents=True) + shutil.copy( + PROJECT_ROOT / "shared" / "prompts" / "code-review-criteria.md", + shared_dir / "code-review-criteria.md", + ) + + env = os.environ.copy() + env["PR_NUMBER"] = "123" + env["GITHUB_REPOSITORY"] = "owner/repo" + env["GITHUB_OUTPUT"] = "/dev/null" + env["RUNNER_TEMP"] = tmpdir + + result = subprocess.run( + ["bash", str(action_dir / "build-review-prompt.sh")], + capture_output=True, + text=True, + env=env, + cwd=fake_repo, + ) + + assert result.returncode == 0 + prompt = read_prompt_file(tmpdir, "123") + assert "Custom User Rules" in prompt + assert "My custom rules here" in prompt + + def test_inline_fallback_when_no_shared_file(self) -> None: + """Script falls back to inline defaults when shared file is missing.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create a fake repo with just the script, no shared files + fake_repo = Path(tmpdir) / "repo" + fake_repo.mkdir() + action_dir = fake_repo / "action" + action_dir.mkdir() + shutil.copy(BUILD_REVIEW_PROMPT, action_dir / "build-review-prompt.sh") + + env = os.environ.copy() + env["PR_NUMBER"] = "123" + env["GITHUB_REPOSITORY"] = "owner/repo" + env["GITHUB_OUTPUT"] = "/dev/null" + env["RUNNER_TEMP"] = tmpdir + + result = subprocess.run( + ["bash", str(action_dir / "build-review-prompt.sh")], + capture_output=True, + text=True, + env=env, + cwd=fake_repo, + ) + + assert result.returncode == 0 + prompt = read_prompt_file(tmpdir, "123") + # Falls back to inline defaults + assert "Security" in prompt + assert "Correctness" in prompt diff --git a/tests/sandbox/test_entrypoint.py b/tests/sandbox/test_entrypoint.py index f990291991..de6b7672f7 100644 --- a/tests/sandbox/test_entrypoint.py +++ b/tests/sandbox/test_entrypoint.py @@ -522,22 +522,178 @@ def test_counts_mounted_repos(self, temp_dir, capsys): class TestSetupAgentRules: """Tests for the setup_agent_rules function.""" - @pytest.mark.skip( - reason="Requires complex mocking of /opt/claude-rules path; " - "function relies on hardcoded paths that are difficult to test without container" - ) - def test_creates_claude_md(self, temp_dir): - """Creates CLAUDE.md from rule files.""" - # This test would require extensive mocking of the filesystem paths - # used in setup_agent_rules. The function reads from /opt/claude-rules/ - # and writes to ~/CLAUDE.md, both of which require either: - # 1. Running in the actual container environment, or - # 2. Complex patching of Path operations - # - # For now, we skip this test and rely on: - # - test_no_rules_does_nothing for the early-exit path - # - Integration tests for the full functionality - pass + @patch("os.lchown") + @patch("os.chown") + def test_includes_all_rules_with_pipeline_id(self, mock_chown, mock_lchown, temp_dir, monkeypatch): + """Includes contract.md and orchestrator.md when EGG_PIPELINE_ID is set.""" + monkeypatch.setenv("EGG_PIPELINE_ID", "issue-123") + + # Create mock rules directory + rules_dir = temp_dir / "opt-claude-rules" + rules_dir.mkdir() + for f in ["mission.md", "environment.md", "code-standards.md", "test-workflow.md", + "pr-descriptions.md", "contract.md", "orchestrator.md"]: + (rules_dir / f).write_text(f"# {f} content") + + # Create repos dir for symlink + repos_dir = temp_dir / "repos" + repos_dir.mkdir() + + config = MagicMock() + config.user_home = temp_dir + config.repos_dir = repos_dir + config.runtime_uid = 1000 + config.runtime_gid = 1000 + + logger = entrypoint.Logger(quiet=True) + + # Patch Path("/opt/claude-rules") to point to our temp rules dir + original_path_init = Path.__new__ + + def patched_path_new(cls, *args, **kwargs): + result = original_path_init(cls, *args, **kwargs) + if str(result) == "/opt/claude-rules": + return rules_dir + return result + + with patch.object(Path, "__new__", patched_path_new): + entrypoint.setup_agent_rules(config, logger) + + claude_md = temp_dir / "CLAUDE.md" + content = claude_md.read_text() + assert "contract.md content" in content + assert "orchestrator.md content" in content + assert "mission.md content" in content + + @patch("os.lchown") + @patch("os.chown") + def test_excludes_sdlc_rules_without_pipeline_id(self, mock_chown, mock_lchown, temp_dir, monkeypatch): + """Excludes contract.md and orchestrator.md when EGG_PIPELINE_ID is not set.""" + monkeypatch.delenv("EGG_PIPELINE_ID", raising=False) + + # Create mock rules directory + rules_dir = temp_dir / "opt-claude-rules" + rules_dir.mkdir() + for f in ["mission.md", "environment.md", "code-standards.md", "test-workflow.md", + "pr-descriptions.md", "contract.md", "orchestrator.md"]: + (rules_dir / f).write_text(f"# {f} content") + + # Create repos dir for symlink + repos_dir = temp_dir / "repos" + repos_dir.mkdir() + + config = MagicMock() + config.user_home = temp_dir + config.repos_dir = repos_dir + config.runtime_uid = 1000 + config.runtime_gid = 1000 + + logger = entrypoint.Logger(quiet=True) + + # Patch Path("/opt/claude-rules") to point to our temp rules dir + original_path_init = Path.__new__ + + def patched_path_new(cls, *args, **kwargs): + result = original_path_init(cls, *args, **kwargs) + if str(result) == "/opt/claude-rules": + return rules_dir + return result + + with patch.object(Path, "__new__", patched_path_new): + entrypoint.setup_agent_rules(config, logger) + + claude_md = temp_dir / "CLAUDE.md" + content = claude_md.read_text() + assert "contract.md content" not in content + assert "orchestrator.md content" not in content + assert "mission.md content" in content + assert "environment.md content" in content + + @patch("os.lchown") + @patch("os.chown") + def test_core_rules_order_preserved(self, mock_chown, mock_lchown, temp_dir, monkeypatch): + """Core rules are included in the expected order.""" + monkeypatch.delenv("EGG_PIPELINE_ID", raising=False) + + rules_dir = temp_dir / "opt-claude-rules" + rules_dir.mkdir() + core_rules = ["mission.md", "environment.md", "code-standards.md", + "test-workflow.md", "pr-descriptions.md"] + for f in core_rules: + (rules_dir / f).write_text(f"## {f} marker") + + repos_dir = temp_dir / "repos" + repos_dir.mkdir() + + config = MagicMock() + config.user_home = temp_dir + config.repos_dir = repos_dir + config.runtime_uid = 1000 + config.runtime_gid = 1000 + + logger = entrypoint.Logger(quiet=True) + + original_path_init = Path.__new__ + + def patched_path_new(cls, *args, **kwargs): + result = original_path_init(cls, *args, **kwargs) + if str(result) == "/opt/claude-rules": + return rules_dir + return result + + with patch.object(Path, "__new__", patched_path_new): + entrypoint.setup_agent_rules(config, logger) + + claude_md = temp_dir / "CLAUDE.md" + content = claude_md.read_text() + + # Verify all core rules present and in order + positions = [] + for f in core_rules: + marker = f"## {f} marker" + pos = content.find(marker) + assert pos >= 0, f"Missing rule: {f}" + positions.append(pos) + assert positions == sorted(positions), "Core rules are not in expected order" + + @patch("os.lchown") + @patch("os.chown") + def test_missing_optional_rule_file_skipped(self, mock_chown, mock_lchown, temp_dir, monkeypatch): + """Missing individual rule files are gracefully skipped.""" + monkeypatch.delenv("EGG_PIPELINE_ID", raising=False) + + rules_dir = temp_dir / "opt-claude-rules" + rules_dir.mkdir() + # Only create mission.md and code-standards.md, skip the rest + (rules_dir / "mission.md").write_text("# Mission") + (rules_dir / "code-standards.md").write_text("# Code Standards") + + repos_dir = temp_dir / "repos" + repos_dir.mkdir() + + config = MagicMock() + config.user_home = temp_dir + config.repos_dir = repos_dir + config.runtime_uid = 1000 + config.runtime_gid = 1000 + + logger = entrypoint.Logger(quiet=True) + + original_path_init = Path.__new__ + + def patched_path_new(cls, *args, **kwargs): + result = original_path_init(cls, *args, **kwargs) + if str(result) == "/opt/claude-rules": + return rules_dir + return result + + with patch.object(Path, "__new__", patched_path_new): + entrypoint.setup_agent_rules(config, logger) + + claude_md = temp_dir / "CLAUDE.md" + content = claude_md.read_text() + assert "# Mission" in content + assert "# Code Standards" in content @patch("os.chown") @patch("os.lchown")