"""Acceptance-profile configuration command. Extracted verbatim from the `acceptance-profile` Click command in `cli.py` (Session 1 of the refactor-handoffs plan, docs/refactor-handoffs/01-file-splits.md, Task 5 stretch). Zero behavior change. Defines its own `click.command` (registered onto `main` from cli.py) rather than decorating `main` directly, mirroring Task 2's campaign_cli.py pattern. Names resolved from cli.py's own module namespace (`console`, `_load_plan`, `_save_plan`) are accessed via `import afk_developer.cli as cli` (function-body-local, to avoid a circular import since cli.py imports this module at module level) so existing test monkeypatches on `afk_developer.cli.X` keep working unchanged. """ from pathlib import Path import click from afk_developer.config import Config from afk_developer.evidence import EvidencePacketError, normalize_evidence_roots from afk_developer.planner.task_model import ( ENABLED_ACCEPTANCE_PROFILES, AcceptanceProfile, TaskFailureKind, TaskLifecyclePhase, TaskPlan, TaskStatus, ) from afk_developer.recovery import RecoveryAction def _configure_acceptance_profile( plan: TaskPlan, *, task_ids: tuple[str, ...], profile: AcceptanceProfile, evidence_roots: tuple[Path, ...], project_dir: Path, ) -> list[str]: """Apply human-selected profile state before the selected tasks can mutate code.""" if not task_ids: raise click.UsageError("Specify at least one explicit --task-id.") duplicate_ids = sorted({task_id for task_id in task_ids if task_ids.count(task_id) > 1}) if duplicate_ids: raise click.UsageError(f"Duplicate task ID(s): {', '.join(duplicate_ids)}.") if profile not in ENABLED_ACCEPTANCE_PROFILES: raise click.UsageError( f"Acceptance profile '{profile.value}' is registered but unavailable until its " "trusted verifier specification is implemented." ) if not project_dir.is_dir(): raise click.UsageError(f"Saved project directory does not exist: {project_dir}.") task_by_id = {task.id: task for task in plan.tasks} unknown_ids = [task_id for task_id in task_ids if task_id not in task_by_id] if unknown_ids: available = ", ".join(sorted(task_by_id)) raise click.UsageError( f"Unknown task ID(s): {', '.join(unknown_ids)}. Available tasks: {available}." ) selected = [task_by_id[task_id] for task_id in task_ids] read_only_evidence_setup = profile is AcceptanceProfile.NONE and bool(evidence_roots) if read_only_evidence_setup and any(not task.read_only for task in selected): raise click.UsageError( "Profile 'none' may use --evidence-root only for explicit read-only tasks." ) try: normalized_roots = ( normalize_evidence_roots( [str(root) for root in evidence_roots], project_dir=project_dir ) if profile is AcceptanceProfile.CORPUS_RAW_OUTPUT or read_only_evidence_setup else [] ) except EvidencePacketError as exc: raise click.UsageError(str(exc)) from exc started = [ task.id for task in selected if not _acceptance_profile_is_mutable(task) and not (read_only_evidence_setup and _read_only_evidence_roots_are_mutable(task)) ] if started: raise click.UsageError( "Acceptance profiles and evidence roots are human-approved before mutation and " f"cannot change after a task starts: {', '.join(started)}." ) for task in selected: reset_preflight_block = _is_unstarted_acceptance_preflight_block(task) reset_read_only_evidence_block = ( read_only_evidence_setup and _read_only_evidence_roots_are_mutable(task) ) task.acceptance_profile = profile task.evidence_roots = list(normalized_roots) task.evidence_packet_id = "" task.evidence_revision = None task.evidence_fingerprint = "" task.validator_finding_ids = [] task.validator_finding_fingerprint = "" task.validator_findings = [] task.semantic_repair_fingerprints = [] task.recovery_action = RecoveryAction.NONE if reset_preflight_block or reset_read_only_evidence_block: task.status = TaskStatus.PENDING task.lifecycle_phase = TaskLifecyclePhase.PLANNED task.blocked_reason = "" task.failure_kind = None task.failure_detail = "" task.retry_count = 0 return [task.id for task in selected] def _acceptance_profile_is_mutable(task) -> bool: """Return whether a human may still amend a task's acceptance configuration. An acceptance preflight can stop a task before an agent call, branch mutation, or declared file change. Such a stop is a safe correction point, not a completed start. Every other non-planned state remains immutable. """ if ( task.status is TaskStatus.PENDING and task.lifecycle_phase is TaskLifecyclePhase.PLANNED and not task.attempts and not task.files_created ): return True return _is_unstarted_acceptance_preflight_block(task) def _is_unstarted_acceptance_preflight_block(task) -> bool: """Recognize the narrow no-mutation acceptance-preflight recovery state.""" return ( task.status is TaskStatus.ESCALATED and task.lifecycle_phase is TaskLifecyclePhase.ESCALATED and task.failure_kind in { TaskFailureKind.ACCEPTANCE_POLICY_REJECTED, TaskFailureKind.VALIDATOR_MISSING_EVIDENCE, } and not task.attempts and not task.files_created ) def _read_only_evidence_roots_are_mutable(task) -> bool: """Permit a human to attach roots after a read-only evidence-access failure. This is not an acceptance-profile amendment for a mutating task: the task has made no source changes, remains unprofiled, and only needs a human to make its external read-only source available to the existing tool surface. """ return ( task.read_only and task.acceptance_profile is AcceptanceProfile.NONE and not task.evidence_roots and not task.files_created and task.status is TaskStatus.ESCALATED and task.lifecycle_phase is TaskLifecyclePhase.ESCALATED and task.failure_kind is TaskFailureKind.RESEARCH_INSUFFICIENT ) @click.command("acceptance-profile") @click.argument("project_name") @click.option( "--task-id", "task_ids", multiple=True, required=True, help="Explicit saved-plan task ID to configure; may be supplied more than once.", ) @click.option( "--profile", type=click.Choice([profile.value for profile in AcceptanceProfile], case_sensitive=False), required=True, help="Human-selected acceptance profile. Only none and corpus_raw_output are enabled initially.", ) @click.option( "--evidence-root", "evidence_roots", type=click.Path(path_type=Path), multiple=True, help="Existing external source directory approved by a human for the selected tasks.", ) @click.pass_context def acceptance_profile( ctx: click.Context, project_name: str, task_ids: tuple[str, ...], profile: str, evidence_roots: tuple[Path, ...], ) -> None: """Configure human-approved acceptance state for explicit saved-plan tasks.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] loaded = cli._load_plan(config, project_name) if loaded is None: raise click.UsageError(f"No saved plan found for '{project_name}'.") ( plan, saved_project_dir, saved_linter, saved_test_framework, saved_lint_mode, saved_max_auto_resume_passes, ) = loaded project_dir = Path(saved_project_dir).resolve() if saved_project_dir else Path.cwd().resolve() selected_ids = _configure_acceptance_profile( plan, task_ids=task_ids, profile=AcceptanceProfile(profile), evidence_roots=evidence_roots, project_dir=project_dir, ) cli._save_plan( config, plan, project_dir=project_dir, linter=saved_linter, test_framework=saved_test_framework, lint_mode=saved_lint_mode, max_auto_resume_passes=saved_max_auto_resume_passes, ) if profile == AcceptanceProfile.NONE.value: cli.console.print( f"[green]Removed acceptance profiles from:[/green] {', '.join(selected_ids)}" ) else: cli.console.print( f"[green]Configured {profile} for:[/green] {', '.join(selected_ids)} " f"with {len(evidence_roots)} approved evidence root(s)." )