import re from pathlib import Path from afk_developer.backends.registry import BackendRegistry from afk_developer.config import Config from afk_developer.grillme.spec_model import TaskIntent, TaskSpec from afk_developer.planner.task_model import ( DiscoveryContract, TaskNode, TaskPlan, TaskPriority, TaskStatus, ) from afk_developer.utils import extract_json def decompose_task(spec: TaskSpec, config: Config) -> TaskPlan: content = _build_context(spec) is_analysis = spec.intent == TaskIntent.ANALYZE is_debug = spec.intent == TaskIntent.DEBUG system_prompt = """You are an expert software engineering task planner. Your job is to decompose a coding goal into an ordered list of concrete, actionable tasks. CRITICAL RULES: 1. EVERY non-infrastructure task MUST list at least one dependency. A task like "implement X" without any dependencies is almost always wrong — it should depend on the setup/bootstrap task at minimum. 2. The first task should ALWAYS be an infrastructure task: initializing the project, installing dependencies, configuring the test framework and linter. 3. Tasks form a DAG (directed acyclic graph). Later tasks depend on earlier ones. No circular dependencies. 4. Think carefully: "What must exist before this task can start?" Each task should be: - Small enough for a single AI coding agent to complete in one session - Specific about which files to create/modify - Given a unique ID slug (e.g. "init-project", "create-user-model", "add-auth-middleware") - Marked `read_only: true` only when it exclusively inspects existing code, runs verification, or reports findings and intentionally makes no versioned file changes. A brownfield baseline audit is normally read-only. All other tasks must set `read_only: false`. - Assigned a priority following this strict order: * "critical_bug" — broken CI, broken app, security issues (do first) * "infrastructure" — project init, dependency install, test/lint config, CI config (do first) * "tracer_bullet" — thin end-to-end slice of the simplest case to validate approach * "feature" — regular feature implementation work * "polish" — improvements, quick wins, UX cleanup * "refactor" — code restructuring without behavior changes (do last) Output a JSON object with the following structure: { "tasks": [ { "id": "string", "title": "string (short imperative phrase)", "description": "string (detailed instructions for the agent, including target files)", "hypothesis": "string (ONE sentence: what this task assumes will make it pass; for a read-only task, the finding you expect)", "contract_command": "string (executable acceptance test run from the project root after review; exit 0 = satisfied; use {python} for the target interpreter; empty ONLY if no runnable test can be written)", "dependencies": ["string (task_id that must complete first)", ...], "evidence_gated_by": ["read-only discovery task ID whose source conclusion must be supported before mutation"], "accepts_not_applicable_dependencies": false, "estimated_effort": "small|medium|large", "priority": "critical_bug|infrastructure|tracer_bullet|feature|polish|refactor", "read_only": false, "required_artifacts": ["project-relative/nonempty.file"], "acceptance_criteria": ["deterministic condition that proves this task is complete"], "disallow_unscoped_pytest": false, "evidence_roots": ["absolute external path", ...] "discovery_contract": { "cache_key": "explicit-shared-key-only-when-siblings-share-identical-discovery", "questions": ["bounded local question"], "input_paths": ["exact/project-relative.py"], "allowed_output_paths": ["exact/project-relative.py"], "exclusions": ["explicit local discovery boundary"] } "red_regression_test_files": ["tests/new_regression_test.py"] } ] }""" if is_analysis: system_prompt += "\n\nThis is a READ-ONLY analysis task. All tasks should explore/examine/summarize existing code without making any changes. Fan out analysis across subdirectories or modules when possible." elif is_debug: system_prompt += "\n\nThis is a debug/fix task. The first task MUST be diagnosing the issue (reading logs, examining the error, locating root cause). Fix tasks follow after diagnosis." system_prompt += ( "\n\nWhen the goal names an external corpus, fixture directory, or other immutable " "evidence location, include every required absolute external path in each dependent " "task's evidence_roots. Do not list the target project directory as evidence." ) system_prompt += ( "\n\nUse discovery_contract only for a mutating task that has a concrete risk of repeating " "local source discovery across retries. It must name exact project-relative input files, " "bounded questions, exact allowed output paths, and exclusions. Omit it for ordinary tasks. " "Assign the same non-empty cache_key to sibling tasks only when they ask identical questions " "over identical declared inputs; never infer cache reuse from similar prose." ) system_prompt += ( "\n\nFor a deliberate TDD red-first task, use red_regression_test_files only when the task " "creates new focused pytest files that must fail until its direct dependent repair runs. " "Those paths must be exact tests/*.py files. The task may modify only those test files; the " "reviewer will require each named file to fail in isolation while the remaining pytest suite " "and lint pass. Do not use this field for ordinary regression tests. Never instruct the worker " "to run git commit: AFK owns staging commits and merges after review." ) system_prompt += ( "\n\nFor every mutating task, list each concrete versioned deliverable in " "required_artifacts using exact project-relative POSIX file paths, and provide bounded, " "deterministic acceptance_criteria. Required artifacts must be real non-empty files, not " "directories, ignored corpus/build outputs, caches, or empty placeholders. Read-only tasks " "normally have no required artifacts. Set disallow_unscoped_pytest true whenever the task " "must use only focused test files or markers, or must not run pytest at all. Documentation-" "only tasks that prohibit pytest must set it true so deterministic review skips pytest." ) system_prompt += ( "\n\nFor an implementation task that may proceed only after a paired source-discovery task " "establishes a deterministic contract, list that discovery task in evidence_gated_by as well " "as dependencies. A trusted insufficient conclusion then prevents speculative implementation. " "For a read-only release/audit task that should run after such an intentionally skipped implementation, " "set accepts_not_applicable_dependencies: true. Do not use either field for ordinary code dependencies." ) system_prompt += ( "\n\nEvery task must state its hypothesis in exactly one sentence before it can be " "dispatched: the claim the attempt rests on (for a mutating task) or the finding it " "expects to establish (for a read-only task). Hypotheses already refuted on the campaign " "ledger will be sent back to you rather than dispatched." ) system_prompt += ( "\n\nEvery mutating task is dispatchable only with an executable acceptance test attached: " "set contract_command to one shell command, run from the project root after deterministic " "review, that exits 0 exactly when the task's acceptance criteria hold (for example " '{python} -m pytest tests/test_feature.py -q, or {python} -c "..." asserting a fact about ' "the repository). If you cannot write such a test, leave it empty; the task will then be " "returned to a human instead of dispatched to a worker." ) system_prompt += ( "\n\nIMPORTANT: Return ONLY valid JSON. No markdown formatting, no trailing commas." ) last_error = None for attempt in range(config.max_retries): try: response = ( BackendRegistry(config) .get_reasoner() .complete( system_prompt=system_prompt, user_prompt=content, temperature=0.0, ) ) config.record_usage(response.usage, role="reasoner") result = extract_json(response.content) raw_tasks = result.get("tasks", []) tasks = [ TaskNode( id=t.get("id", f"task-{i}"), title=t.get("title", ""), description=t.get("description", ""), hypothesis=str(t.get("hypothesis", "")).strip()[:300], contract_command=str(t.get("contract_command", "")).strip()[:1_000], dependencies=_dependencies_with_evidence_gates(t), evidence_gated_by=t.get("evidence_gated_by", []), accepts_not_applicable_dependencies=bool( t.get("accepts_not_applicable_dependencies", False) ), estimated_effort=t.get("estimated_effort", "medium"), priority=_parse_priority(t.get("priority", "feature")), read_only=is_analysis or bool(t.get("read_only", False)), required_artifacts=t.get("required_artifacts", []), acceptance_criteria=t.get("acceptance_criteria", []), disallow_unscoped_pytest=bool(t.get("disallow_unscoped_pytest", False)), evidence_roots=_task_evidence_roots(spec, t), discovery_contract=_parse_discovery_contract(t.get("discovery_contract")), red_regression_test_files=t.get("red_regression_test_files", []), status=TaskStatus.PENDING, ) for i, t in enumerate(raw_tasks) ] _remove_unbacked_evidence_gates(tasks) return TaskPlan( project_name=spec.project_name, goal=spec.goal, intent=spec.intent.value, tasks=tasks, ) except Exception as e: last_error = e if attempt < config.max_retries - 1: system_prompt = _make_stricter_prompt(system_prompt) raise RuntimeError( f"Failed to decompose task after {config.max_retries} attempts: {last_error}" ) def _dependencies_with_evidence_gates(task: dict) -> list[str]: """Preserve the DAG invariant that every evidence gate is also a dependency.""" dependencies = task.get("dependencies", []) evidence_gates = task.get("evidence_gated_by", []) return list(dict.fromkeys([*dependencies, *evidence_gates])) def _parse_discovery_contract(value: object) -> DiscoveryContract | None: """Accept only the explicit structured opt-in emitted by the planner.""" if value is None: return None if not isinstance(value, dict): raise ValueError("discovery_contract must be an object when provided") return DiscoveryContract.model_validate(value) def _remove_unbacked_evidence_gates(tasks: list[TaskNode]) -> None: """Downgrade local discovery gates to ordinary DAG dependencies. An evidence gate requires a durable packet rooted in approved external evidence. Local source inspection is still a valuable prerequisite, but it cannot create that packet and must not deadlock its dependent repair. """ task_by_id = {task.id: task for task in tasks} for task in tasks: task.evidence_gated_by = [ source_id for source_id in task.evidence_gated_by if task_by_id[source_id].evidence_roots ] def _make_stricter_prompt(original: str) -> str: return ( original + "\n\nCRITICAL: The previous JSON was invalid. Ensure NO trailing commas and valid JSON syntax." ) def _parse_priority(value: str) -> TaskPriority: try: return TaskPriority(value) except ValueError: return TaskPriority.FEATURE _ABSOLUTE_PATH_PATTERN = re.compile(r"(?:(?:[A-Za-z]:[\\/])|/)[^\s,;\]\[(){}\"']+") def _task_evidence_roots(spec: TaskSpec, raw_task: dict) -> list[str]: """Return declared and request-derived external evidence roots for one task.""" candidates = [*raw_task.get("evidence_roots", [])] for text in (spec.goal, raw_task.get("description", "")): candidates.extend(_ABSOLUTE_PATH_PATTERN.findall(text)) target_dir = spec.project_dir.resolve() roots: list[str] = [] seen: set[str] = set() for value in candidates: if not isinstance(value, str) or not value: continue path = Path(value.rstrip(".")).resolve() if not path.exists(): continue try: path.relative_to(target_dir) except ValueError: key = str(path).casefold() if key not in seen: roots.append(str(path)) seen.add(key) return roots def _discover_existing_structure(project_dir) -> str: """Return a concise file tree of Python source files in the project.""" from pathlib import Path base = Path(project_dir) if not base.exists(): return "" lines: list[str] = [] for p in sorted(base.rglob("*.py")): if any(part.startswith(".") for part in p.parts): continue if "__pycache__" in p.parts or ".egg-info" in p.parts: continue rel = p.relative_to(base) try: first_line = ( p.read_text(encoding="utf-8").splitlines()[0] if p.stat().st_size < 50000 else "" ) except Exception: first_line = "" indent = " " * (len(rel.parts) - 1) lines.append(f"{indent}{rel}") if first_line and first_line.startswith(('"""', "'''", "#")): lines[-1] += f" — {first_line.strip('#').strip().strip('"').strip()[:80]}" return "\n".join(lines[:60]) def _build_context(spec: TaskSpec) -> str: parts = [f"PROJECT: {spec.project_name}"] parts.append(f"PROJECT DIRECTORY: {spec.project_dir}") parts.append(f"GOAL: {spec.goal}") if spec.intent != TaskIntent.ANALYZE: parts.append(f"LANGUAGE: {spec.language or 'unknown'}") parts.append(f"FRAMEWORK: {spec.framework or 'none'}") parts.append(f"TEST FRAMEWORK: {spec.test_framework or 'none'}") if spec.constraints: parts.append(f"CONSTRAINTS: {', '.join(spec.constraints)}") if spec.additional_context: parts.append(f"ADDITIONAL CONTEXT: {spec.additional_context}") parts.append(f"EXISTING FILES: {spec.auto_detected.existing_files_count}") parts.append(f"EXISTING TEST FILES: {spec.auto_detected.existing_tests_count}") if spec.auto_detected.existing_files_count > 0: tree = _discover_existing_structure(spec.project_dir) if tree: parts.append(f"\nEXISTING PROJECT STRUCTURE:\n{tree}") if spec.linter: parts.append(f"LINTER TO CONFIGURE: {spec.linter}") if spec.test_framework: parts.append(f"TEST FRAMEWORK TO CONFIGURE: {spec.test_framework}") is_new_project = spec.auto_detected.existing_files_count == 0 parts.append( "\nIMPORTANT: This is a NEW project with zero existing files. " "Your FIRST task must be an 'infrastructure' priority task to initialize the project " "(create project files, install dependencies, configure linter and test framework). " "All subsequent tasks MUST declare this init task as a dependency." if is_new_project else "\nIMPORTANT: This project ALREADY has existing code. Your FIRST task MUST read and " "understand the existing modules before making changes. Read key source files and run " "the existing tests to understand what's already built. Subsequent tasks must build " "on the existing architecture, not create duplicate modules." ) return "\n".join(parts)