Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /promptdriven_pdd /pdd /sync_orchestration.py
# pdd/sync_orchestration.py
"""
Orchestrates the complete PDD sync workflow by coordinating operations and
animations in parallel, serving as the core engine for the `pdd sync` command.
"""
import threading
import time
import json
import hashlib
import datetime
import subprocess
import re
import os
from pathlib import Path, PurePosixPath
from typing import Dict, Any, Optional, List, Callable
from dataclasses import asdict, dataclass, field
import tempfile
import sys
import uuid
from .sync_tui import maybe_steer_operation, DEFAULT_STEER_TIMEOUT_S
import click
import logging
logger = logging.getLogger(__name__)
# --- Constants ---
MAX_CONSECUTIVE_TESTS = 3 # Allow up to 3 consecutive test attempts
MAX_TEST_EXTEND_ATTEMPTS = 2 # Allow up to 2 attempts to extend tests for coverage
MAX_CONSECUTIVE_CRASHES = 3 # Allow up to 3 consecutive crash attempts (Bug #157 fix)
MAX_CONSECUTIVE_FIXES = 5 # Allow up to 5 consecutive fix attempts (Issue #1203: only fires when not making progress)
# --- Real PDD Component Imports ---
from .sync_tui import SyncApp
from .operation_log import (
load_operation_log,
create_log_entry,
update_log_entry,
append_log_entry,
log_event,
save_fingerprint,
save_run_report,
clear_run_report,
get_log_path,
get_run_report_path,
get_fingerprint_path,
)
from .sync_determine_operation import (
sync_determine_operation,
get_pdd_file_paths,
AmbiguousModuleError,
RunReport,
SyncDecision,
PDD_DIR,
META_DIR,
SyncLock,
read_run_report,
calculate_sha256,
calculate_current_hashes,
trusted_hash_root_for_paths,
_safe_basename,
is_test_extend_disabled,
)
from .auto_deps_main import auto_deps_main
from .code_generator_main import (
code_generator_main,
PublicSurfaceRegressionError,
TestChurnError,
_verify_public_surface_regression,
)
from .agentic_sync_runner import build_test_churn_hard_failure_from_error
from .context_generator_main import context_generator_main
from .crash_main import crash_main
from .fix_verification_main import fix_verification_main
from .cmd_test_main import cmd_test_main
from .content_selector import PDD_TEST_OUTPUT_NEEDS_REVIEW_MARKER
from .fix_main import fix_main
from .compressed_sync_context import build_compressed_sync_context, metadata as compressed_context_metadata
from .update_main import update_main
from .python_env_detector import detect_host_python_executable
from .get_run_command import get_run_command_for_file
from .pytest_output import extract_failing_files_from_output, _find_project_root
from . import DEFAULT_STRENGTH
from .core.errors import record_core_dump_error
from .core.llm_trace import set_current_operation, pop_last_pair
def _truncate_text(text: str, limit_chars: int) -> str:
if text is None:
return ""
if len(text) <= limit_chars:
return text
return text[:limit_chars] + f"\n... (truncated, {len(text)} total chars)"
def _compose_sync_summary(
*,
success: bool,
operations_completed: List[str],
skipped_operations: List[str],
errors: List[str],
terminal_reason: Optional[str] = None,
) -> str:
"""Compose a truthful, scoped summary line for the sync result.
- No-op success: "No sync operations required; selected target is already synchronized."
- Success with work: "Completed: <ops>" (and "; skipped: <ops>" when applicable)
- Failure: "Step <first> failed: <reason>" using the first error.
When ``terminal_reason`` is provided for an accepted-as-complete decision
(e.g. coverage below target but tests skipped, or test_extend unsupported
for the target language), it is appended so the user understands WHY the
run was accepted instead of seeing only "no operations required". #1103.
The selected-target scoping comes from the caller (sync_main renders this per language).
"""
if not success:
first_err = next((e for e in errors if e), "")
if first_err:
return f"Sync failed: {first_err}"
return "Sync failed."
completed = [op for op in (operations_completed or []) if op]
skipped = [op for op in (skipped_operations or []) if op]
reason = (terminal_reason or "").strip()
if not completed and not skipped:
base = "No sync operations required; selected target is already synchronized."
if reason:
return f"{base} Accepted as complete: {reason}"
return base
parts: List[str] = []
if completed:
parts.append(f"Completed: {', '.join(completed)}")
if skipped:
parts.append(f"skipped: {', '.join(skipped)}")
summary = "; ".join(parts)
if reason:
summary = f"{summary}; accepted as complete: {reason}"
return summary
def _run_fix_operation_test_subprocess(*args: Any, **kwargs: Any) -> Any:
"""subprocess.run for fix-phase test capture; separate symbol so tests can patch reliably."""
return subprocess.run(*args, **kwargs)
# --- Helper Functions ---
# Note: _safe_basename is imported from sync_determine_operation
def _extract_cost_from_result(operation: str, result: tuple) -> float:
"""Extract cost from an operation result tuple at the correct index.
Each operation returns a different tuple format:
- crash/fix/verify: 6-tuple (..., cost, model) — cost at index 4
- generate: 4-tuple (content, was_incremental, cost, model) — cost at index 2
- example/test/test_extend/auto-deps: 3-or-4-tuple (..., cost, model, ...) — cost at index 1
"""
if operation in ('crash', 'fix', 'verify'):
idx = 4
elif operation == 'generate':
idx = 2
else:
idx = 1
if len(result) > idx:
val = result[idx]
if isinstance(val, (int, float)) and not isinstance(val, bool):
return float(val)
return 0.0
def _extract_model_from_result(operation: str, result: tuple) -> str:
"""Extract model name from an operation result tuple at the correct index.
Each operation returns a different tuple format:
- crash/fix/verify: 6-tuple (..., cost, model) — model at index 5
- generate: 4-tuple (content, was_incremental, cost, model) — model at index 3
- example/test/test_extend/auto-deps: 3-or-4-tuple (..., cost, model, ...) — model at index 2
"""
if operation in ('crash', 'fix', 'verify'):
idx = 5
elif operation == 'generate':
idx = 3
else:
idx = 2
if len(result) > idx and isinstance(result[idx], str):
return result[idx]
return 'unknown'
def _fold_test_churn_cost_into_result(
result: Any,
*,
accumulated_cost: float,
accumulated_model: str,
) -> Any:
"""Return ``result`` with prior failed-attempt cost/model folded in.
The test op's return type is ``TestResult`` (a ``NamedTuple``) in
production, but legacy paths and tests may return a ``dict`` (with
``cost``/``model`` keys) or a generic tuple where ``cost`` is at
index 1 and ``model`` at index 2 (matches ``_extract_cost_from_result``
/``_extract_model_from_result`` for the test op).
When the successful retry's model is absent/empty, fall back to the
accumulated model from the last failed attempt so the run report
still attributes the spend correctly. Shapes the helper doesn't
recognize are returned unchanged — the bug is most acute for the
canonical ``TestResult`` shape and we keep behavior conservative
for anything exotic.
"""
# TestResult is a NamedTuple — use ``_replace`` to keep all other
# fields (content/agentic_success/error_message) intact.
if hasattr(result, "_replace") and hasattr(result, "_fields"):
fields = getattr(result, "_fields", ())
updates: Dict[str, Any] = {}
if "cost" in fields:
updates["cost"] = float(getattr(result, "cost", 0.0) or 0.0) + accumulated_cost
if "model" in fields:
current_model = getattr(result, "model", "") or ""
updates["model"] = current_model or accumulated_model or "unknown"
if updates:
return result._replace(**updates)
return result
if isinstance(result, dict):
folded = dict(result)
folded["cost"] = float(folded.get("cost", 0.0) or 0.0) + accumulated_cost
current_model = folded.get("model", "") or ""
folded["model"] = current_model or accumulated_model or "unknown"
return folded
if isinstance(result, tuple) and len(result) >= 3:
cost_idx = 1
model_idx = 2
existing_cost = result[cost_idx] if isinstance(result[cost_idx], (int, float)) and not isinstance(result[cost_idx], bool) else 0.0
existing_model = result[model_idx] if isinstance(result[model_idx], str) else ""
new_cost = float(existing_cost or 0.0) + accumulated_cost
new_model = existing_model or accumulated_model or "unknown"
return result[:cost_idx] + (new_cost, new_model) + result[model_idx + 1:]
return result
def _run_test_op_with_churn_retry(
call: Callable[[Optional[str]], Any],
*,
basename: str,
budget_remaining: float,
) -> Any:
"""Run a `cmd_test_main` call inside a bounded `TestChurnError` repair loop.
The test-op uses the same `PDD_REPAIR_DIRECTIVE` plumbing as the
generate-op architecture-conformance / public-surface loop (#866, #1012),
but caps retries at one extra attempt: churn rewrites rarely converge,
and the directive forces an additive-only edit on the retry.
The ``call`` callable accepts an ``Optional[str]`` repair_directive
argument: attempt 1 receives ``None`` (no in-loop failure yet);
attempt 2 receives the prior ``TestChurnError.repair_directive``.
Callers are expected to forward this to ``cmd_test_main(..., repair_directive=...)``
so the directive flows into the test-generation prompt via the
explicit kwarg rather than ``os.environ`` (#1012, F-G / F-H).
Behavior:
- On each ``TestChurnError`` accumulate ``exc.total_cost`` / ``exc.model_name``
onto the exception (so callers can charge for failed attempts).
- Track the repair directive in a loop-local variable
``pending_repair_directive`` (source of truth for the next
attempt's ``call`` argument). Also write
``os.environ["PDD_REPAIR_DIRECTIVE"]`` so nested PDD CLI
subprocesses spawned by agentic test generation inherit it via
the env (load-bearing for ``code_generator_main``'s own repair
loop in the child process); but this loop ITSELF does not read
the env to drive the call.
- Skip the retry if the remaining budget is already exhausted by the
failed attempt's accumulated cost.
- On exhaustion, emit the structured ``=== test churn threshold exceeded ===``
block to stderr and re-raise the last exception.
- On a successful retry, fold any prior failed-attempt cost (and the
last failed-attempt model when the success response leaves the
model blank) into the returned ``TestResult`` so the sync budget
charges the operator for every attempt.
- Always restore ``PDD_REPAIR_DIRECTIVE`` to its prior value in a
``finally`` block.
- **Stale outer env protection** (#1012, F-G): pop
``PDD_REPAIR_DIRECTIVE`` from the env BEFORE attempt 1 so a stale
outer value (set by the caller's shell, a parent orchestration
layer, or a prior PDD command) cannot leak through env inheritance
into nested subprocesses during attempt 1. The prior value is
restored in ``finally``.
The previous behavior (only the generic ``except`` printed the hard
block) is preserved on exhaustion, so this function is the single
source-of-truth for emitting the diagnostic — the per-operation
``except`` no longer prints it for the test op.
"""
from .agentic_sync_runner import MAX_CONFORMANCE_ATTEMPTS
prev_repair = os.environ.get("PDD_REPAIR_DIRECTIVE")
# Pop the env var BEFORE attempt 1 so any nested PDD CLI subprocess
# spawned by agentic test generation during the first attempt sees a
# CLEAN env. Only failures raised inside THIS loop populate the
# directive for subsequent attempts.
os.environ.pop("PDD_REPAIR_DIRECTIVE", None)
# Loop-local source of truth for the next attempt's call argument.
pending_repair_directive: Optional[str] = None
try:
last_exc: Optional[TestChurnError] = None
last_signature: Optional[tuple] = None
accumulated_cost = 0.0
accumulated_model = ""
for attempt in range(MAX_CONFORMANCE_ATTEMPTS):
try:
result = call(pending_repair_directive)
# Fold prior failed-attempt cost/model into the successful
# retry's result so the caller charges all attempts against
# the sync budget. Mirrors the generate-op repair loop's
# post-success rewrap (see #1015 Codex review) and the
# `one_session_sync` accumulation.
if accumulated_cost > 0:
result = _fold_test_churn_cost_into_result(
result,
accumulated_cost=accumulated_cost,
accumulated_model=accumulated_model,
)
return result
except TestChurnError as exc:
attempt_cost = float(getattr(exc, "total_cost", 0.0) or 0.0)
accumulated_cost += attempt_cost
exc.total_cost = accumulated_cost
exc_model = getattr(exc, "model_name", "") or ""
if exc_model and exc_model != "unknown":
accumulated_model = exc_model
exc.model_name = accumulated_model
signature = (
f"{exc.churn_ratio:.2f}",
str(exc.pre_line_count),
)
# Stop early if the retry produced the identical churn
# signature (no progress is being made).
if last_signature is not None and signature == last_signature:
last_exc = exc
break
last_signature = signature
last_exc = exc
if attempt + 1 >= MAX_CONFORMANCE_ATTEMPTS:
break
# Test-churn retries are unlikely to converge — cap at one
# extra attempt (mirrors the generate-op test-churn branch).
if attempt >= 1:
break
if accumulated_cost >= max(budget_remaining, 0.0):
break
# Record the directive for the next attempt's `call`
# argument (loop-local source of truth) AND set the env
# var so any re-entrant PDD CLI subprocess spawned by
# agentic test generation inherits it.
pending_repair_directive = exc.repair_directive
os.environ["PDD_REPAIR_DIRECTIVE"] = exc.repair_directive
if last_exc is not None:
hard_block = build_test_churn_hard_failure_from_error(last_exc, basename)
print(hard_block, file=sys.stderr)
raise last_exc
# Unreachable: the loop either returns or sets last_exc.
return None
finally:
if prev_repair is None:
os.environ.pop("PDD_REPAIR_DIRECTIVE", None)
else:
os.environ["PDD_REPAIR_DIRECTIVE"] = prev_repair
def _verify_code_surface_after_write(
*,
code_path: Path,
pre_code: str,
basename: str,
language: str,
prompt_path: Path,
operation: str,
) -> Optional[PublicSurfaceRegressionError]:
"""Verify the public surface of ``code_path`` against ``pre_code`` (#1012, P2.A).
Called AFTER a non-generate operation (``crash_main`` /
``fix_verification_main`` / ``fix_main``) writes the code file
directly. The generate-op repair loop only protects
``code_generator_main``; without this gate, downstream operations
can silently regress the public surface that the generate gate
accepted. Returns the ``PublicSurfaceRegressionError`` instance on
detection (so the caller can emit the structured hard-failure
block and record an appropriate error), or ``None`` when the
surface is preserved.
**Contract: crash/fix/verify surface failures are HARD failures.**
On detection this helper restores ``pre_code`` to disk and returns
the typed error WITHOUT triggering any retry. The
``PDD_REPAIR_DIRECTIVE`` repair loop is intentionally NOT applied
here — it only governs the ``generate`` and ``one-session`` paths.
Each crash/fix/verify operation already has its own internal
iterative fix loop (``loop=True``, ``max_attempts=N``); wrapping
them in an outer surface-repair retry would compound retries
(``N × M``) and burn budget while rarely converging. The caller
surfaces the structured hard-failure block plus a clear
"operation failed" exit, and the user fixes the regression
(either by adjusting the prompt or adding a
``BREAKING-CHANGE: remove <symbol>`` opt-out) before re-running.
The contract is mirrored in ``README.md`` so docs and behavior
cannot drift; do not introduce a retry here without updating both.
"""
try:
post_code = code_path.read_text(encoding="utf-8")
except OSError:
post_code = ""
prompt_content = ""
try:
if prompt_path.exists():
prompt_content = prompt_path.read_text(encoding="utf-8")
except OSError:
prompt_content = ""
try:
_verify_public_surface_regression(
existing_code=pre_code,
generated_code=post_code,
prompt_name=f"{basename}_{language}.prompt",
output_path=str(code_path),
language=language,
prompt_content=prompt_content,
)
except PublicSurfaceRegressionError as surface_err:
# Restore the pre-operation code file so the regression does
# not persist on disk. The caller decides what to surface
# (error string + hard-failure block).
try:
code_path.write_text(pre_code, encoding="utf-8")
except OSError:
pass
return surface_err
return None
def _use_agentic_path(language: str, agentic_mode: bool) -> bool:
"""Returns True if we should use agentic path (non-Python OR agentic_mode for Python).
This is used to determine whether to skip iterative LLM loops and delegate
directly to agentic handlers. When agentic_mode is True, Python behaves
like TypeScript/other languages.
"""
return language.lower() != 'python' or agentic_mode
# --- Atomic State Update (Issue #159 Fix) ---
@dataclass
class PendingStateUpdate:
"""Holds pending state updates for atomic commit."""
run_report: Optional[Dict[str, Any]] = None
fingerprint: Optional[Dict[str, Any]] = None
run_report_path: Optional[Path] = None
fingerprint_path: Optional[Path] = None
@dataclass
class FileRollbackSnapshot:
"""Snapshot of a single file before an operation mutates it."""
path: Path
existed: bool
content: Optional[bytes] = None
class AtomicStateUpdate:
"""
Context manager for atomic state updates.
Ensures run_report and fingerprint are both written or neither is written.
This fixes Issue #159 where non-atomic writes caused state desynchronization.
Usage:
with AtomicStateUpdate(basename, language) as state:
state.set_run_report(report_dict, report_path)
state.set_fingerprint(fingerprint_dict, fp_path)
# On successful exit, both files are written atomically
# On exception, neither file is written (rollback)
"""
def __init__(self, basename: str, language: str):
self.basename = basename
self.language = language.lower()
self.pending = PendingStateUpdate()
self._crash_hook: Optional[Callable[[str], None]] = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self._commit()
return False # Don't suppress exceptions
def set_run_report(self, report: Dict[str, Any], path: Path):
"""Buffer a run report for atomic write."""
self.pending.run_report = report
self.pending.run_report_path = path
def set_fingerprint(self, fingerprint: Dict[str, Any], path: Path):
"""Buffer a fingerprint for atomic write."""
self.pending.fingerprint = fingerprint
self.pending.fingerprint_path = path
def _commit(self):
"""Commit the pair through the canonical durable transaction manager.
The run report is deliberately installed before the fingerprint, which
is the completion checkpoint. A durable COMMITTING journal lets the
next process finish both writes after SIGKILL at either rename.
"""
from .sync_core.transaction import PlannedWrite, TransactionManager
pairs = (
(self.pending.run_report_path, self.pending.run_report),
(self.pending.fingerprint_path, self.pending.fingerprint),
)
destinations = [Path(path) for path, data in pairs if path and data is not None]
if not destinations:
return
root = _metadata_checkout_root(*destinations)
manager = TransactionManager(root)
_recover_metadata_transactions(manager, self.basename, self.language)
writes = []
for path, data in pairs:
if path is None or data is None:
continue
relative = Path(path).resolve(strict=False).relative_to(root)
payload = json.dumps(data, indent=2, default=str).encode("utf-8") + b"\n"
writes.append(PlannedWrite(PurePosixPath(relative.as_posix()), payload, "100644"))
transaction_id = _metadata_transaction_prefix(self.basename, self.language) + uuid.uuid4().hex
prepared = manager.prepare(transaction_id, tuple(writes))
if not prepared.no_op:
manager.commit(transaction_id, crash_hook=self._crash_hook)
def _metadata_checkout_root(*paths: Path) -> Path:
"""Return the single checkout root owning metadata destinations."""
roots = set()
for raw_path in paths:
resolved = Path(raw_path).resolve(strict=False)
pdd_dir = next((parent for parent in resolved.parents if parent.name == ".pdd"), None)
if pdd_dir is None:
raise ValueError(f"metadata destination is outside .pdd: {raw_path}")
roots.add(pdd_dir.parent)
if len(roots) != 1:
raise ValueError("metadata destinations belong to different projects")
return roots.pop()
def _metadata_transaction_prefix(basename: str, language: str) -> str:
identity = f"{basename}\0{language.lower()}".encode("utf-8")
return f"legacy-metadata-{hashlib.sha256(identity).hexdigest()[:20]}-"
def _recover_metadata_transactions(manager, basename: str, language: str) -> tuple[str, ...]:
"""Recover only journals owned by this legacy module identity."""
prefix = _metadata_transaction_prefix(basename, language)
recovered = []
for transaction_id in manager.incomplete():
if transaction_id.startswith(prefix):
manager.recover(transaction_id)
recovered.append(transaction_id)
return tuple(recovered)
def recover_incomplete_metadata_transactions(
basename: str,
language: str,
paths: Optional[Dict[str, Path]] = None,
) -> tuple[str, ...]:
"""Recover a crash-interrupted run-report/fingerprint pair before reading it."""
fingerprint_path = get_fingerprint_path(basename, language, paths=paths)
run_report_path = get_run_report_path(basename, language, paths=paths)
root = _metadata_checkout_root(fingerprint_path, run_report_path)
from .sync_core.transaction import TransactionManager
return _recover_metadata_transactions(TransactionManager(root), basename, language)
def _atomic_write_bytes(path: Path, data: bytes) -> None:
"""Write file bytes atomically using temp file + rename."""
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_path = tempfile.mkstemp(
dir=path.parent,
prefix=f".{path.stem}_",
suffix=".tmp",
)
try:
with os.fdopen(fd, "wb") as handle:
handle.write(data)
os.replace(temp_path, path)
finally:
if os.path.exists(temp_path):
try:
os.unlink(temp_path)
except OSError:
pass
class OperationFileRollback:
"""Restores selected files when an operation fails before commit."""
def __init__(self, paths: List[Path]):
self._snapshots: List[FileRollbackSnapshot] = []
seen = set()
for raw_path in paths:
path = Path(raw_path)
if path in seen:
continue
seen.add(path)
if path.exists():
self._snapshots.append(
FileRollbackSnapshot(
path=path,
existed=True,
content=path.read_bytes(),
)
)
else:
self._snapshots.append(FileRollbackSnapshot(path=path, existed=False))
self._committed = False
def commit(self) -> None:
self._committed = True
def restore(self) -> None:
if self._committed:
return
for snapshot in reversed(self._snapshots):
try:
if snapshot.existed:
_atomic_write_bytes(snapshot.path, snapshot.content or b"")
elif snapshot.path.exists():
snapshot.path.unlink()
except OSError as exc:
logger.warning(
"Failed to restore %s after interrupted sync operation: %s",
snapshot.path,
exc,
)
self._committed = True
def _find_auto_deps_architecture_path(prompt_path: Path) -> Optional[Path]:
"""Locate architecture.json that auto-deps may patch for the prompt."""
try:
from .architecture_registry import find_project_root
from .auto_deps_architecture import _find_architecture_record_for_prompt_file
project_root = find_project_root()
record = _find_architecture_record_for_prompt_file(project_root, prompt_path.resolve())
if record is None:
return None
arch_path, _, _ = record
return arch_path
except Exception:
return None
def _build_auto_deps_rollback(prompt_path: Path, temp_output: Path) -> OperationFileRollback:
"""Capture the files auto-deps can mutate before the fingerprint commit."""
rollback_paths = [
prompt_path,
temp_output,
Path("project_dependencies.csv"),
]
arch_path = _find_auto_deps_architecture_path(prompt_path)
if arch_path is not None:
rollback_paths.append(arch_path)
return OperationFileRollback(rollback_paths)
# --- State Management Wrappers ---
def _save_run_report_atomic(report: Dict[str, Any], basename: str, language: str,
atomic_state: Optional['AtomicStateUpdate'] = None,
paths: Optional[Dict[str, Path]] = None):
"""Save a run report to the metadata directory, supporting atomic updates.
Args:
report: The run report dictionary to save.
basename: The module basename.
language: The programming language.
atomic_state: Optional AtomicStateUpdate for atomic writes (Issue #159 fix).
paths: Optional path hints (Issue #1211) routing the file under the
subproject's .pdd/meta when run CWD lives above the subproject.
"""
if atomic_state:
# Buffer for atomic write — resolve via the same project-root-aware
# helper as the direct path so atomic writes don't bypass #1211.
report_file = get_run_report_path(basename, language, paths=paths)
atomic_state.set_run_report(report, report_file)
else:
# Direct write using operation_log
save_run_report(basename, language, report, paths=paths)
def _save_fingerprint_atomic(basename: str, language: str, operation: str,
paths: Dict[str, Path], cost: float, model: str,
atomic_state: Optional['AtomicStateUpdate'] = None,
include_deps_override: Optional[Dict[str, str]] = None):
"""Save fingerprint state after successful operation, supporting atomic updates.
Args:
basename: The module basename.
language: The programming language.
operation: The operation that was performed.
paths: Dictionary of PDD file paths.
cost: The cost of the operation.
model: The model used.
atomic_state: Optional AtomicStateUpdate for atomic writes (Issue #159 fix).
include_deps_override: Pre-captured include deps (Issue #522). Used when
auto-deps may have stripped <include> tags before fingerprint save.
"""
from .sync_core.finalize import canonical_root_for_paths
root = canonical_root_for_paths(paths)
if root is not None:
from .sync_core import (
attestation_signer_from_environment,
finalize_unit,
)
from .sync_core.finalize import lexical_managed_module
protected_base = os.environ.get("PDD_SYNC_PROTECTED_BASE_SHA")
if not protected_base:
raise RuntimeError(
"canonical sync requires PDD_SYNC_PROTECTED_BASE_SHA"
)
try:
module = lexical_managed_module(
root,
Path(paths["prompt"]),
base_ref=protected_base,
head_ref="HEAD",
)
except (OSError, RuntimeError, ValueError) as exc:
raise RuntimeError(
f"trusted canonical finalization failed: {exc}"
) from exc
finalize_unit(
root,
module,
base_ref=protected_base,
head_ref="HEAD",
signer=attestation_signer_from_environment(),
)
return
if atomic_state:
# Buffer for atomic write
from datetime import datetime, timezone
from .sync_determine_operation import calculate_current_hashes, Fingerprint, read_fingerprint
from . import __version__
# Issue #522: Use override deps if provided (captured before auto-deps),
# otherwise fall back to stored deps from previous fingerprint
if include_deps_override is not None:
stored_deps = include_deps_override
else:
prev_fp = read_fingerprint(basename, language, paths=paths)
stored_deps = prev_fp.include_deps if prev_fp else None
current_hashes = calculate_current_hashes(
paths,
stored_include_deps=stored_deps,
dependency_root=trusted_hash_root_for_paths(paths),
)
# If override provided and current extraction found nothing, use the override
if include_deps_override and not current_hashes.get('include_deps'):
current_hashes['include_deps'] = include_deps_override
fingerprint = Fingerprint(
pdd_version=__version__,
timestamp=datetime.now(timezone.utc).isoformat(),
command=operation,
prompt_hash=current_hashes.get('prompt_hash'),
code_hash=current_hashes.get('code_hash'),
example_hash=current_hashes.get('example_hash'),
test_hash=current_hashes.get('test_hash'),
test_files=current_hashes.get('test_files'), # Bug #156
include_deps=current_hashes.get('include_deps'), # Issue #522
)
# Issue #1211: route the atomic fingerprint file through the
# paths-aware helper so subprojects whose .pddrc is below run CWD
# get the file under <subproject>/.pdd/meta, not parent CWD.
fingerprint_file = get_fingerprint_path(basename, language, paths=paths)
atomic_state.set_fingerprint(asdict(fingerprint), fingerprint_file)
else:
# Direct write using operation_log
save_fingerprint(basename, language, operation, paths, cost, model)
def _python_cov_target_for_code_file(code_file: Path) -> str:
"""Return a `pytest-cov` `--cov` target for a Python code file.
- If the file is inside a Python package (directories with `__init__.py`),
returns a dotted module path (e.g., `pdd.sync_orchestration`).
- Otherwise falls back to the filename stem (e.g., `admin_get_users`).
"""
if code_file.suffix != ".py":
return code_file.stem
package_dir: Optional[Path] = None
current = code_file.parent
while (current / "__init__.py").exists():
package_dir = current
parent = current.parent
if parent == current:
break
current = parent
if package_dir:
relative_module = code_file.relative_to(package_dir.parent).with_suffix("")
return str(relative_module).replace(os.sep, ".")
return code_file.stem
def _python_cov_target_for_test_and_code(test_file: Path, code_file: Path, fallback: str) -> str:
"""Choose the best `--cov` target based on how tests import the code.
In some repos, tests add a directory to `sys.path` and import modules by their
filename stem (e.g., `from admin_get_users import ...`) even when the code
also lives under a package (e.g., `backend.functions.admin_get_users`).
Heuristic:
- Prefer the code file stem when the test file imports it directly.
- Otherwise, prefer the dotted module path derived from the package layout.
- Fall back to the provided fallback (usually the basename).
"""
def _imports_module(source: str, module: str) -> bool:
escaped = re.escape(module)
return bool(
re.search(rf"^\s*import\s+{escaped}\b", source, re.MULTILINE)
or re.search(rf"^\s*from\s+{escaped}\b", source, re.MULTILINE)
)
stem = code_file.stem
dotted = _python_cov_target_for_code_file(code_file)
try:
test_source = test_file.read_text(encoding="utf-8", errors="ignore")
except Exception:
test_source = ""
if stem and _imports_module(test_source, stem):
return stem
if dotted and dotted != stem:
if _imports_module(test_source, dotted):
return dotted
if "." in dotted:
parent = dotted.rsplit(".", 1)[0]
# e.g. `from backend.functions import admin_get_users`
if re.search(
rf"^\s*from\s+{re.escape(parent)}\s+import\s+.*\b{re.escape(stem)}\b",
test_source,
re.MULTILINE,
):
return dotted
# e.g. `import backend.functions.admin_get_users`
if re.search(
rf"^\s*import\s+{re.escape(parent)}\.{re.escape(stem)}\b",
test_source,
re.MULTILINE,
):
return dotted
return dotted
return stem or fallback
def _has_coverage_config(project_root: Path) -> bool:
"""Check whether the project already provides coverage.py configuration.
coverage.py discovers config from (in order): .coveragerc, pyproject.toml
[tool.coverage], setup.cfg [coverage:*], tox.ini [coverage:*]. If any of
these exist we leave the project's settings alone.
"""
if (project_root / ".coveragerc").is_file():
return True
for cfg_name in ("pyproject.toml", "setup.cfg", "tox.ini"):
cfg = project_root / cfg_name
if cfg.is_file():
try:
text = cfg.read_text(encoding="utf-8", errors="ignore")
if "tool.coverage" in text or "[coverage:" in text:
return True
except OSError:
pass
return False
def _parse_test_output(output: str, language: str) -> tuple[int, int, float]:
"""
Parse test output to extract passed/failed/coverage.
Args:
output: Combined stdout/stderr from test runner
language: Language name (e.g., 'python', 'typescript', 'go')
Returns:
(tests_passed, tests_failed, coverage)
"""
tests_passed = 0
tests_failed = 0
coverage = 0.0
lang = language.lower()
# Python (pytest)
if lang == 'python':
if 'passed' in output:
passed_match = re.search(r'(\d+) passed', output)
if passed_match:
tests_passed = int(passed_match.group(1))
if 'failed' in output:
failed_match = re.search(r'(\d+) failed', output)
if failed_match:
tests_failed = int(failed_match.group(1))
if 'error' in output:
error_match = re.search(r'(\d+) error', output)
if error_match:
tests_failed += int(error_match.group(1))
coverage_match = re.search(r'TOTAL.*?(\d+)%', output)
if not coverage_match:
coverage_match = re.search(r'(\d+)%\s*$', output, re.MULTILINE)
if not coverage_match:
coverage_match = re.search(r'(\d+(?:\.\d+)?)%(?!\])', output)
if coverage_match:
coverage = float(coverage_match.group(1))
# Jest/Vitest (JavaScript/TypeScript)
elif lang in ('javascript', 'typescript', 'typescriptreact', 'javascriptreact'):
# "Tests: X passed, Y failed" or "Tests: X passed, Y failed, Z total"
match = re.search(r'Tests:\s*(\d+)\s+passed', output)
if match:
tests_passed = int(match.group(1))
match = re.search(r'Tests:.*?(\d+)\s+failed', output)
if match:
tests_failed = int(match.group(1))
# Alternative Mocha-style: "X passing, Y failing"
if tests_passed == 0:
pass_match = re.search(r'(\d+)\s+pass(?:ing)?', output, re.I)
if pass_match:
tests_passed = int(pass_match.group(1))
if tests_failed == 0:
fail_match = re.search(r'(\d+)\s+fail(?:ing)?', output, re.I)
if fail_match:
tests_failed = int(fail_match.group(1))
# Coverage: "All files | XX.XX |"
cov_match = re.search(r'All files[^|]*\|\s*(\d+\.?\d*)', output)
if cov_match:
coverage = float(cov_match.group(1))
# Go
elif lang == 'go':
# Count PASS and FAIL occurrences for individual tests
tests_passed = len(re.findall(r'--- PASS:', output))
tests_failed = len(re.findall(r'--- FAIL:', output))
# Fallback: check for overall PASS/FAIL
if tests_passed == 0 and 'PASS' in output and 'FAIL' not in output:
tests_passed = 1
if tests_failed == 0 and 'FAIL' in output:
tests_failed = 1
# coverage: XX.X% of statements
cov_match = re.search(r'coverage:\s*(\d+\.?\d*)%', output)
if cov_match:
coverage = float(cov_match.group(1))
# Rust (cargo test)
elif lang == 'rust':
# "test result: ok. X passed; Y failed;"
match = re.search(r'(\d+)\s+passed', output)
if match:
tests_passed = int(match.group(1))
match = re.search(r'(\d+)\s+failed', output)
if match:
tests_failed = int(match.group(1))
# Fallback: try generic patterns
else:
pass_match = re.search(r'(\d+)\s+(?:tests?\s+)?pass(?:ed)?', output, re.I)
fail_match = re.search(r'(\d+)\s+(?:tests?\s+)?fail(?:ed)?', output, re.I)
if pass_match:
tests_passed = int(pass_match.group(1))
if fail_match:
tests_failed = int(fail_match.group(1))
return tests_passed, tests_failed, coverage
def _detect_example_errors(output: str) -> tuple[bool, str]:
"""
Detect if example output contains error indicators.
Only detects true crashes/errors:
- Python tracebacks (catches ALL unhandled exceptions)
- ERROR level log messages
Intentionally does NOT detect:
- HTTP status codes (examples may test error responses)
- Individual exception type names (causes false positives, redundant with traceback)
Returns:
(has_errors, error_summary)
"""
error_patterns = [
(r'Traceback \(most recent call last\):', 'Python traceback'),
(r' - ERROR - ', 'Error log message'), # Python logging format
]
errors_found = []
for pattern, description in error_patterns:
if re.search(pattern, output, re.MULTILINE):
errors_found.append(description)
if errors_found:
return True, '; '.join(errors_found)
return False, ''
def _try_auto_fix_import_error(
error_output: str,
code_file: Path,
example_file: Path,
) -> tuple[bool, str]:
"""
Try to automatically fix common import errors before calling expensive agentic fix.
Returns:
(fixed, message): Whether a fix was attempted and what was done.
"""
import re
# Check for ModuleNotFoundError or ImportError
module_not_found = re.search(r"ModuleNotFoundError: No module named ['\"]([^'\"]+)['\"]", error_output)
import_error = re.search(r"ImportError: cannot import name ['\"]([^'\"]+)['\"]", error_output)
if not module_not_found and not import_error:
return False, "No import error detected"
if module_not_found:
missing_module = module_not_found.group(1)
# Split by . to get the top-level package
top_level_package = missing_module.split('.')[0]
# Check if this is the module we're trying to import (local module)
code_module_name = code_file.stem # e.g., "data_validator" from "data_validator.py"
if top_level_package == code_module_name:
# It's trying to import our own generated code - fix the example's sys.path
# Read the example and fix the path manipulation
try:
example_content = example_file.read_text(encoding='utf-8')
code_dir = str(code_file.parent.resolve())
# Look for existing sys.path manipulation
if 'sys.path' in example_content:
# Try to fix the existing path manipulation
# Common pattern: module_path = os.path.abspath(os.path.join(...))
# Replace with correct path
fixed_content = re.sub(
r"module_path\s*=\s*os\.path\.abspath\([^)]+\)",
f"module_path = '{code_dir}'",
example_content
)
if fixed_content != example_content:
example_file.write_text(fixed_content, encoding='utf-8')
return True, f"Fixed sys.path to point to {code_dir}"
# If no existing sys.path, add one at the start after imports
lines = example_content.split('\n')
insert_pos = 0
for i, line in enumerate(lines):
if line.startswith('import ') or line.startswith('from '):
if 'sys' in line or 'os' in line:
insert_pos = i + 1
continue
if line.strip() and not line.startswith('#') and not line.startswith('import') and not line.startswith('from'):
insert_pos = i
break
path_fix = f"\n# Auto-added by pdd to fix import\nimport sys\nsys.path.insert(0, '{code_dir}')\n"
lines.insert(insert_pos, path_fix)
example_file.write_text('\n'.join(lines), encoding='utf-8')
return True, f"Added sys.path.insert(0, '{code_dir}') to example"
except Exception as e:
return False, f"Failed to fix import path: {e}"
else:
# It's an external package - try pip install
try:
result = subprocess.run(
[sys.executable, '-m', 'pip', 'install', top_level_package],
capture_output=True,
text=True,
timeout=120
)
if result.returncode == 0:
return True, f"Installed missing package: {top_level_package}"
else:
return False, f"Failed to install {top_level_package}: {result.stderr}"
except Exception as e:
return False, f"Failed to run pip install: {e}"
return False, "Import error detected but no auto-fix available"
def _get_module_exports(module_path: Path) -> 'set[str] | None':
"""
Extract exported names from a Python module file using AST parsing.
Returns a set of top-level names defined in the module, or None if
the file cannot be parsed (to avoid false positives).
Collects all top-level definitions (functions, classes, assignments,
and re-exported imports). If __all__ is defined, its names are unioned
with the physically defined names — because __all__ only restricts
'from module import *', not explicit imports like 'from module import X'.
"""
import ast
try:
source = module_path.read_text(encoding='utf-8')
except OSError as e:
logger.warning("Cannot read module %s: %s", module_path, e)
return None
try:
tree = ast.parse(source)
except SyntaxError as e:
logger.warning("SyntaxError parsing module %s — module may be broken: %s", module_path, e)
return None
all_names: set[str] | None = None
# Check for __all__ (top-level only — iter_child_nodes is correct here)
for node in ast.iter_child_nodes(tree):
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id == '__all__':
if isinstance(node.value, (ast.List, ast.Tuple)):
all_names = set()
for elt in node.value.elts:
if isinstance(elt, ast.Constant) and isinstance(elt.value, str):
all_names.add(elt.value)
# Handle __all__ += ['extra_name'] patterns
elif isinstance(node, ast.AugAssign):
if isinstance(node.target, ast.Name) and node.target.id == '__all__':
if isinstance(node.value, (ast.List, ast.Tuple)):
if all_names is None:
all_names = set()
for elt in node.value.elts:
if isinstance(elt, ast.Constant) and isinstance(elt.value, str):
all_names.add(elt.value)
# Note: fully dynamic __all__ construction (e.g., list comprehensions) is not supported.
# Use ast.walk() to capture names defined inside try/except, if/else, etc.
# (e.g., conditional imports: try: from fast_json import loads; except: from json import loads)
exports: set[str] = set()
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
exports.add(node.name)
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
exports.add(target.id)
elif isinstance(target, ast.Tuple):
for elt in target.elts:
if isinstance(elt, ast.Name):
exports.add(elt.id)
elif isinstance(node, ast.AnnAssign):
if isinstance(node.target, ast.Name):
exports.add(node.target.id)
elif isinstance(node, ast.ImportFrom):
# Re-exported imports: 'from X import Y' or 'from X import Y as Z'
if node.names:
for alias in node.names:
if alias.name != '*':
exports.add(alias.asname if alias.asname else alias.name)
elif isinstance(node, ast.Import):
# Top-level imports: 'import X' or 'import X as Y'
for alias in node.names:
exports.add(alias.asname if alias.asname else alias.name)
# Union __all__ names with physically defined names, since __all__
# only restricts 'from module import *', not explicit imports.
if all_names:
exports |= all_names
return exports
def _validate_python_imports(
code_file: Path,
) -> list[str]:
"""
Validate that local imports in generated Python code resolve to actual files on disk.
Uses ast.parse() to extract Import/ImportFrom nodes, filters out stdlib and
known third-party packages, then checks whether each remaining local import
corresponds to a .py file next to code_file or an installed package.
Also validates that specific imported names (functions, classes, constants)
actually exist within local modules (Issue #620).
Returns:
List of unresolved import module names (empty if all imports are valid).
"""
import ast
if not code_file.exists():
return []
try:
source = code_file.read_text(encoding='utf-8')
except OSError:
return []
try:
tree = ast.parse(source)
except SyntaxError:
return []
# Collect top-level module names and full dotted paths from import statements.
# Also track specific names imported from each module path (Issue #620).
imported_modules: set[str] = set()
full_import_paths: dict[str, set[str]] = {} # top_level -> {full dotted paths}
import_names: dict[str, set[str]] = {} # full_module_path -> {name1, name2, ...}
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom):
if node.module and node.level == 0: # Skip relative imports
top_level = node.module.split('.')[0]
if top_level != '__future__':
imported_modules.add(top_level)
full_import_paths.setdefault(top_level, set()).add(node.module)
# Capture imported names (skip star imports)
if node.names:
names = {
alias.name for alias in node.names
if alias.name != '*'
}
if names:
import_names.setdefault(node.module, set()).update(names)
elif isinstance(node, ast.Import):
for alias in node.names:
top_level = alias.name.split('.')[0]
imported_modules.add(top_level)
full_import_paths.setdefault(top_level, set()).add(alias.name)
if not imported_modules:
return []
# Filter out stdlib modules
stdlib_modules = sys.stdlib_module_names if hasattr(sys, 'stdlib_module_names') else set()
non_stdlib = imported_modules - stdlib_modules
if not non_stdlib:
return []
# Filter out known third-party packages (check if they're importable)
# A module is considered third-party if it can be found by importlib
import importlib.util
unresolved: list[str] = []
code_dir = code_file.parent
# Pre-compute installed package names for namespace package fallback.
# find_spec() returns None for some namespace packages (e.g., packages installed
# under a different distribution name). packages_distributions() (Python 3.11+)
# maps importable package names to their distribution names.
try:
import importlib.metadata
installed_packages = set(importlib.metadata.packages_distributions().keys())
except Exception:
installed_packages = set()
for module_name in sorted(non_stdlib):
# Check if it exists as a local .py file in the same directory as the code
local_file = code_dir / f"{module_name}.py"
local_package = code_dir / module_name / "__init__.py"
if local_file.exists() or local_package.exists():
# Issue #620: Also validate imported names against module exports.
for full_path in full_import_paths.get(module_name, set()):
target_file: Path | None = None
if full_path == module_name:
# Simple import: "from hackathon_models import X"
if local_file.exists():
target_file = local_file
elif local_package.exists():
target_file = local_package
else:
# Dotted import: "from utils.firebase_admin_init import X"
parts = full_path.split('.')
submodule_file = code_dir / '/'.join(parts[:-1]) / f"{parts[-1]}.py"
submodule_package = code_dir / '/'.join(parts) / "__init__.py"
if submodule_file.exists():
target_file = submodule_file
elif submodule_package.exists():
target_file = submodule_package
else:
# Submodule path doesn't exist on disk
unresolved.append(f"module '{full_path}' not found on disk")
continue
# Validate imported names against the target module's exports
names_to_check = import_names.get(full_path, set())
if not names_to_check or target_file is None:
continue
exports = _get_module_exports(target_file)
if exports is None:
# Parse failure — skip validation to avoid false positives
logger.debug("Skipping name validation for %s (parse failure)", target_file)
continue
for name in sorted(names_to_check):
if name not in exports:
unresolved.append(f"name '{name}' not found in module '{full_path}'")
continue
# Check if it's an installable/importable third-party package
spec = importlib.util.find_spec(module_name)
if spec is not None:
continue
# Fallback: check installed distributions for namespace packages
if module_name in installed_packages:
continue
# Module is neither local nor third-party — it's unresolved
unresolved.append(f"module '{module_name}' not found on disk")
return unresolved
def _validate_typescript_imports(
code_file: Path,
) -> list[str]:
"""
Validate that imports in generated TypeScript/JavaScript code resolve to actual files.
Uses regex to extract ES6 (import ... from '...') and CommonJS (require('...'))
import paths, then checks whether each import resolves to a file on disk.
Skips:
- Node.js built-in modules (fs, path, http, etc.)
- Packages found in node_modules/
Returns:
List of unresolved import paths (empty if all imports are valid).
"""
import re
if not code_file.exists():
return []
try:
source = code_file.read_text(encoding='utf-8')
except Exception:
return []
# Extract import paths from ES6 and CommonJS patterns
import_paths: set[str] = set()
# ES6: import ... from 'path' or import 'path'
for match in re.finditer(r'''(?:import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]|from\s+['"]([^'"]+)['"]\s+import)''', source):
path = match.group(1) or match.group(2)
if path:
import_paths.add(path)
# CommonJS: require('path')
for match in re.finditer(r'''require\s*\(\s*['"]([^'"]+)['"]\s*\)''', source):
import_paths.add(match.group(1))
# Dynamic import: import('path')
for match in re.finditer(r'''import\s*\(\s*['"]([^'"]+)['"]\s*\)''', source):
import_paths.add(match.group(1))
if not import_paths:
return []
# Node.js built-in modules (targets Node.js 20 LTS)
node_builtins = {
'assert', 'async_hooks', 'buffer', 'child_process', 'cluster',
'console', 'constants', 'crypto', 'dgram', 'diagnostics_channel',
'dns', 'domain', 'events', 'fs', 'http', 'http2', 'https',
'inspector', 'module', 'net', 'os', 'path', 'perf_hooks', 'process',
'punycode', 'querystring', 'readline', 'repl', 'stream',
'string_decoder', 'sys', 'test', 'timers', 'tls', 'trace_events',
'tty', 'url', 'util', 'v8', 'vm', 'wasi', 'worker_threads', 'zlib',
}
code_dir = code_file.parent
# Common file extensions for TypeScript/JavaScript
ts_extensions = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']
# Walk up to find project root (where package.json or node_modules lives)
project_root = code_dir
for _ in range(10):
if (project_root / 'package.json').exists() or (project_root / 'node_modules').exists():
break
parent = project_root.parent
if parent == project_root:
break
project_root = parent
node_modules = project_root / 'node_modules'
# Read package.json dependencies as fallback when node_modules doesn't exist
# (common in CI/git-clone environments where npm install hasn't been run).
package_json_deps: set[str] = set()
package_json_path = project_root / 'package.json'
if package_json_path.exists():
try:
import json as _json
pkg = _json.loads(package_json_path.read_text(encoding='utf-8'))
for dep_key in ('dependencies', 'devDependencies', 'peerDependencies'):
package_json_deps.update(pkg.get(dep_key, {}).keys())
except Exception:
pass
unresolved: list[str] = []
for import_path in sorted(import_paths):
# Skip Node.js built-ins (with or without 'node:' prefix)
bare_path = import_path.removeprefix('node:')
if bare_path in node_builtins:
continue
# Relative imports (./foo, ../foo)
if import_path.startswith('.'):
resolved = code_dir / import_path
# Check with various extensions and as directory with index file
found = False
# Exact match (e.g., ./foo.ts)
if resolved.exists() and resolved.is_file():
found = True
if not found:
for ext in ts_extensions:
if (resolved.parent / f"{resolved.name}{ext}").exists():
found = True
break
# Check as directory with index file
if not found and resolved.is_dir():
for ext in ts_extensions:
if (resolved / f"index{ext}").exists():
found = True
break
if not found:
unresolved.append(import_path)
continue
# Path alias imports (@/, ~/, #/)
if import_path.startswith(('@/', '~/', '#/')):
# These rely on tsconfig/webpack aliases — check common src/ resolution
alias_path = import_path[2:] # Strip @/ or ~/ or #/
found = False
# Check common alias roots: src/, app/, lib/
for alias_root in ['src', 'app', 'lib', '.']:
base = project_root / alias_root / alias_path
if base.exists() and base.is_file():
found = True
break
for ext in ts_extensions:
if (base.parent / f"{base.name}{ext}").exists():
found = True
break
if not found and base.is_dir():
for ext in ts_extensions:
if (base / f"index{ext}").exists():
found = True
break
if found:
break
if not found:
unresolved.append(import_path)
continue
# Scoped packages (@org/package)
if import_path.startswith('@') and '/' in import_path:
pkg_name = '/'.join(import_path.split('/')[:2])
if node_modules.exists() and (node_modules / pkg_name).exists():
continue
if pkg_name in package_json_deps:
continue
unresolved.append(import_path)
continue
# Bare module imports (react, next, lodash, etc.)
top_level = import_path.split('/')[0]
if node_modules.exists() and (node_modules / top_level).exists():
continue
if top_level in package_json_deps:
continue
# Neither node_modules nor package.json lists this module
unresolved.append(import_path)
return unresolved
def _try_auto_fix_env_var_error(
error_output: str,
example_file: Path,
) -> tuple[bool, str]:
"""
Try to automatically fix missing environment variable errors before calling expensive agentic fix.
Detects patterns like:
- KeyError: 'BREVO_API_KEY' (from os.environ["VAR"])
- "Set the BREVO_API_KEY environment variable" (explicit error messages)
- ValueError/RuntimeError mentioning env var names (ALL_CAPS_WITH_UNDERSCORES)
Inserts a guard at the top of the example that checks for the env var and exits
gracefully with sys.exit(0) so PDD treats it as non-crash.
Returns:
(fixed, message): Whether a fix was attempted and what was done.
"""
import re
env_var_name = None
# Pattern 1: KeyError: 'VAR_NAME' or KeyError: "VAR_NAME"
key_error_match = re.search(r"KeyError:\s*['\"]([A-Z][A-Z0-9_]+)['\"]", error_output)
if key_error_match:
env_var_name = key_error_match.group(1)
# Pattern 2: "Set the VAR_NAME environment variable"
if not env_var_name:
set_the_match = re.search(r"[Ss]et the ([A-Z][A-Z0-9_]+) environment variable", error_output)
if set_the_match:
env_var_name = set_the_match.group(1)
# Pattern 3: ValueError/RuntimeError mentioning env var names
if not env_var_name:
val_err_match = re.search(
r"(?:ValueError|RuntimeError).*?([A-Z][A-Z0-9_]{2,}(?:_KEY|_TOKEN|_SECRET|_API|_URL|_PASSWORD|_CREDENTIALS))",
error_output,
)
if val_err_match:
env_var_name = val_err_match.group(1)
if not env_var_name:
return False, "No environment variable error detected"
# Skip PDD_PATH — it's always set by the runtime
if env_var_name == "PDD_PATH":
return False, "PDD_PATH is a runtime variable, not an API key"
try:
example_content = example_file.read_text(encoding='utf-8')
# Insert guard near the top, after any existing imports
lines = example_content.split('\n')
insert_pos = 0
for i, line in enumerate(lines):
stripped = line.strip()
if stripped and not stripped.startswith('#') and not stripped.startswith('import ') and not stripped.startswith('from '):
insert_pos = i
break
else:
insert_pos = len(lines)
guard = (
f"\n# Auto-added by pdd: graceful skip for missing env var\n"
f"import os, sys\n"
f"if not os.environ.get(\"{env_var_name}\"):\n"
f" print(\"{env_var_name} not set. Skipping example.\")\n"
f" sys.exit(0)\n"
)
lines.insert(insert_pos, guard)
# Also replace direct os.environ["VAR"] access with os.environ.get("VAR")
fixed_content = '\n'.join(lines)
bracket_pattern = f'os\\.environ\\[[\"\']({re.escape(env_var_name)})[\"\']]'
fixed_content = re.sub(bracket_pattern, f'os.environ.get("{env_var_name}")', fixed_content)
example_file.write_text(fixed_content, encoding='utf-8')
return True, f"Added env var guard for {env_var_name} with sys.exit(0)"
except Exception as e:
return False, f"Failed to fix env var error: {e}"
def _run_example_with_error_detection(
cmd_parts: list[str],
env: dict,
cwd: Optional[str] = None,
timeout: int = 60
) -> tuple[int, str, str]:
"""
Run example file, detecting errors from output.
For server-style examples that block, this runs until timeout
then analyzes output for errors. No errors = success.
Returns:
(returncode, stdout, stderr)
- returncode: 0 if no errors detected, positive if errors found or process failed
"""
import threading
proc = subprocess.Popen(
cmd_parts,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.DEVNULL,
env=env,
cwd=cwd,
start_new_session=True,
)
stdout_chunks = []
stderr_chunks = []
def read_pipe(pipe, chunks):
try:
for line in iter(pipe.readline, b''):
chunks.append(line)
except Exception:
pass
t_out = threading.Thread(target=read_pipe, args=(proc.stdout, stdout_chunks), daemon=True)
t_err = threading.Thread(target=read_pipe, args=(proc.stderr, stderr_chunks), daemon=True)
t_out.start()
t_err.start()
# Wait for process or timeout
try:
proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
t_out.join(timeout=2)
t_err.join(timeout=2)
stdout = b''.join(stdout_chunks).decode('utf-8', errors='replace')
stderr = b''.join(stderr_chunks).decode('utf-8', errors='replace')
combined = stdout + '\n' + stderr
# Check for errors in output
has_errors, error_summary = _detect_example_errors(combined)
# Determine result (check returncode first, then use error detection for signal-killed):
# - Zero exit code → success (trust the exit code)
# - Positive exit code (process failed normally, e.g., sys.exit(1)) → failure
# - Negative exit code (killed by signal, e.g., -9 for SIGKILL) → check output
#
# IMPORTANT: When we kill the process after timeout, returncode is negative
# (the signal number). This is NOT a failure if output has no errors.
if proc.returncode is not None and proc.returncode == 0:
return 0, stdout, stderr # Clean exit = success (trust exit code)
elif proc.returncode is not None and proc.returncode > 0:
return proc.returncode, stdout, stderr # Process exited with error
else:
# Killed by signal (returncode < 0 or None) - use error detection
# Server-style examples may run until timeout, need to check output
if has_errors:
return 1, stdout, stderr # Errors detected in output
return 0, stdout, stderr # No errors, server was running fine
def _create_synthetic_run_report_for_agentic_success(
test_file: Path,
basename: str,
language: str,
*,
atomic_state: Optional['AtomicStateUpdate'] = None,
) -> RunReport:
"""Create a synthetic RunReport when agentic test generation succeeds.
For non-Python languages, the agentic test generation already runs tests
internally. When it reports success, we create a synthetic RunReport to
signal workflow completion without re-running tests.
Args:
test_file: Path to the expected test file (may not exist if agent created elsewhere).
basename: Module basename for the report filename.
language: Programming language.
atomic_state: Optional atomic state for buffered writes.
Returns:
The created RunReport.
"""
timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
# Use actual hash if file exists, otherwise use sentinel value to indicate
# agentic test generation succeeded (differentiates from crash/verify synthetic reports)
if test_file.exists():
test_hash = calculate_sha256(
test_file, trusted_hash_root_for_paths({"test": test_file})
)
else:
# Sentinel value: indicates agentic test success even though expected file path doesn't exist
# The agent may have created tests at a different path (e.g., .test.tsx instead of .tsx)
test_hash = "agentic_test_success"
report = RunReport(
timestamp=timestamp,
exit_code=0,
tests_passed=1, # Synthetic: indicates tests passed
tests_failed=0,
coverage=0.0, # Coverage not available from agentic mode
test_hash=test_hash,
)
# Save the report
# NOTE: Must use _run.json (not _run_report.json) to match read_run_report() in sync_determine_operation.py
# Issue #1211: route via paths-aware helper so subproject meta dir is used.
report_file = get_run_report_path(
basename, language, paths={"test": test_file}
)
if atomic_state:
atomic_state.set_run_report(asdict(report), report_file)
else:
report_file.parent.mkdir(parents=True, exist_ok=True)
report_file.write_text(json.dumps(asdict(report), indent=2))
return report
def _execute_tests_and_create_run_report(
test_file: Path,
basename: str,
language: str,
target_coverage: float = 90.0,
*,
code_file: Optional[Path] = None,
atomic_state: Optional['AtomicStateUpdate'] = None,
test_files: Optional[List[Path]] = None, # Bug #156: Support multiple test files
) -> RunReport:
"""Execute tests and create a RunReport with actual results.
Now supports multiple languages by using get_test_command_for_file()
to determine the appropriate test runner.
Args:
test_file: Primary test file (for backward compat)
test_files: Optional list of all test files to run (Bug #156)
"""
from .get_test_command import get_test_command_for_file
timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
# Bug #156: Use test_files if provided, otherwise just the single test_file
all_test_files = test_files if test_files else [test_file]
# Calculate test file hash for staleness detection (primary file for backward compat)
test_hash = (
calculate_sha256(test_file, trusted_hash_root_for_paths({"test": test_file}))
if test_file.exists()
else None
)
# Bug #156: Calculate hashes for ALL test files
test_file_hashes = {
f.name: calculate_sha256(f, trusted_hash_root_for_paths({"test": f}))
for f in all_test_files
if f.exists()
} if all_test_files else None
# Use clean env without TUI-specific vars
clean_env = os.environ.copy()
for var in ['FORCE_COLOR', 'COLUMNS']:
clean_env.pop(var, None)
try:
lang_lower = language.lower()
# Python: use existing pytest logic with coverage
if lang_lower == "python":
module_name = test_file.name.replace('test_', '').replace('.py', '')
python_executable = detect_host_python_executable()
cov_target = None
if code_file is not None:
cov_target = _python_cov_target_for_test_and_code(test_file, code_file, basename or module_name)
else:
cov_target = basename or module_name
if not cov_target:
cov_target = basename or module_name
# Workaround: litellm>=1.80.11 added pydantic RootModel generics
# (interactions/generated.py) that crash under coverage's import
# hook when --cov targets a dotted submodule (e.g. pdd.my_module).
# Use the top-level package instead; coverage still reports per-file.
# Keep the original target to extract per-module coverage from output.
original_cov_target = cov_target
if "." in cov_target:
cov_target = cov_target.split(".")[0]
# Find project root for proper pytest configuration (Bug fix: infinite fix loop)
# This matches the logic in pytest_output.py to ensure consistent behavior
project_root = _find_project_root(test_file)
# Bug #156: Run pytest on ALL test files
pytest_args = [
python_executable, '-m', 'pytest',
] + [str(f) for f in all_test_files] + [
'-v',
'--tb=short',
f'--cov={cov_target}',
'--cov-report=term-missing'
]
# Set up project root configuration to prevent parent config interference
subprocess_cwd = None
if project_root is not None:
# Add PYTHONPATH to include project root and src/ directory
paths_to_add = [str(project_root)]
src_dir = project_root / "src"
if src_dir.is_dir():
paths_to_add.insert(0, str(src_dir))
existing_pythonpath = clean_env.get("PYTHONPATH", "")
if existing_pythonpath:
paths_to_add.append(existing_pythonpath)
clean_env["PYTHONPATH"] = os.pathsep.join(paths_to_add)
# Add --rootdir and -c /dev/null to prevent parent config discovery
pytest_args.extend([f'--rootdir={project_root}', '-c', '/dev/null'])
subprocess_cwd = str(project_root)
# Add --cov-config with __main__ exclusion only if the project
# has no coverage config of its own. Coverage.py discovers config
# independently of pytest's -c flag, so projects with .coveragerc
# or [tool.coverage] in pyproject.toml are left alone.
_cov_rc_path = None
if project_root is not None and not _has_coverage_config(project_root):
_cov_rc_file = tempfile.NamedTemporaryFile(
mode='w', suffix='.coveragerc', delete=False, prefix='pdd_cov_'
)
_cov_rc_file.write(
"[report]\n"
"exclude_lines =\n"
" if __name__ == .__main__.\n"
" pragma: no cover\n"
)
_cov_rc_file.close()
_cov_rc_path = _cov_rc_file.name
pytest_args.append(f'--cov-config={_cov_rc_path}')
try:
# Build subprocess kwargs - only include cwd if project root was found
subprocess_kwargs = {
'capture_output': True,
'text': True,
'timeout': 300,
'stdin': subprocess.DEVNULL,
'env': clean_env,
'start_new_session': True,
}
if subprocess_cwd is not None:
subprocess_kwargs['cwd'] = subprocess_cwd
result = subprocess.run(pytest_args, **subprocess_kwargs)
finally:
if _cov_rc_path is not None:
try:
os.unlink(_cov_rc_path)
except OSError:
pass
exit_code = result.returncode
stdout = result.stdout + (result.stderr or '')
tests_passed, tests_failed, coverage = _parse_test_output(stdout, language)
# When --cov was collapsed from a dotted module to the package,
# extract per-module coverage instead of using the TOTAL line.
if original_cov_target != cov_target and "." in original_cov_target:
# Convert pdd.agentic_bug_orchestrator → pdd/agentic_bug_orchestrator.py
module_path = original_cov_target.replace(".", "/") + ".py"
module_cov_match = re.search(
rf'^{re.escape(module_path)}\s+\d+\s+\d+\s+(\d+)%',
stdout, re.MULTILINE
)
if module_cov_match:
coverage = float(module_cov_match.group(1))
else:
# Non-Python: use language-appropriate test command
test_cmd = get_test_command_for_file(str(test_file), language)
if test_cmd is None:
# No test command available - return report indicating this
report = RunReport(
timestamp=timestamp,
exit_code=127, # Command not found
tests_passed=0,
tests_failed=0,
coverage=0.0,
test_hash=test_hash,
test_files=test_file_hashes, # Bug #156
)
_save_run_report_atomic(
asdict(report), basename, language, atomic_state,
paths={"test": test_file},
)
return report
effective_cwd = str(test_cmd.cwd) if test_cmd.cwd is not None else str(test_file.parent)
result = subprocess.run(
test_cmd.command,
shell=True,
capture_output=True,
text=True,
timeout=300,
env=clean_env,
cwd=effective_cwd,
stdin=subprocess.DEVNULL,
start_new_session=True
)
exit_code = result.returncode
stdout = (result.stdout or '') + '\n' + (result.stderr or '')
# Parse results based on language
tests_passed, tests_failed, coverage = _parse_test_output(stdout, language)
report = RunReport(
timestamp=timestamp,
exit_code=exit_code,
tests_passed=tests_passed,
tests_failed=tests_failed,
coverage=coverage,
test_hash=test_hash,
test_files=test_file_hashes, # Bug #156
)
except (subprocess.TimeoutExpired, subprocess.CalledProcessError, Exception) as e:
report = RunReport(
timestamp=timestamp,
exit_code=1,
tests_passed=0,
tests_failed=1,
coverage=0.0,
test_hash=test_hash,
test_files=test_file_hashes, # Bug #156
)
_save_run_report_atomic(
asdict(report), basename, language, atomic_state, paths={"test": test_file}
)
return report
def _create_mock_context(**kwargs) -> click.Context:
"""Creates a mock Click context object to pass parameters to command functions."""
ctx = click.Context(click.Command('sync'))
ctx.obj = kwargs
return ctx
def _display_sync_log(
basename: str,
language: str,
verbose: bool = False,
paths: Optional[Dict[str, Path]] = None,
) -> Dict[str, Any]:
"""Displays the sync log for a given basename and language.
`paths` (Issue #1211) routes the log file lookup through the
subproject's .pdd/meta when invoked from a parent CWD.
"""
log_file = get_log_path(basename, language, paths=paths)
if not log_file.exists():
print(f"No sync log found for '{basename}' in language '{language}'.")
return {'success': False, 'errors': ['Log file not found.'], 'log_entries': []}
log_entries = load_operation_log(basename, language, paths=paths)
print(f"--- Sync Log for {basename} ({language}) ---")
if not log_entries:
print("Log is empty.")
return {'success': True, 'log_entries': []}
for entry in log_entries:
timestamp = entry.get('timestamp', 'N/A')
if 'event' in entry:
event = entry.get('event', 'N/A')
print(f"[{timestamp[:19]}] EVENT: {event}")
if verbose and 'details' in entry:
details_str = json.dumps(entry['details'], indent=2)
print(f" Details: {details_str}")
continue
operation = entry.get('operation', 'N/A')
reason = entry.get('reason', 'N/A')
success = entry.get('success')
actual_cost = entry.get('actual_cost')
estimated_cost = entry.get('estimated_cost', 0.0)
duration = entry.get('duration')
if verbose:
print(f"[{timestamp[:19]}] {operation:<12} | {reason}")
decision_type = entry.get('decision_type', 'N/A')
confidence = entry.get('confidence', 'N/A')
model = entry.get('model', 'N/A')
budget_remaining = entry.get('details', {}).get('budget_remaining', 'N/A')
print(f" Decision Type: {decision_type} | Confidence: {confidence}")
if actual_cost is not None:
print(f" Cost: ${actual_cost:.2f} (estimated: ${estimated_cost:.2f}) | Model: {model}")
if duration is not None:
print(f" Duration: {duration:.1f}s | Budget Remaining: ${budget_remaining}")
else:
print(f" Estimated Cost: ${estimated_cost:.2f}")
if 'details' in entry and entry['details']:
details_copy = entry['details'].copy()
details_copy.pop('budget_remaining', None)
if details_copy:
details_str = json.dumps(details_copy, indent=2)
print(f" Details: {details_str}")
else:
status_icon = "✓" if success else "✗" if success is False else "?"
cost_info = ""
if actual_cost is not None:
cost_info = f" | {status_icon} ${actual_cost:.2f} (est: ${estimated_cost:.2f})"
else:
cost_info = f" | Est: ${estimated_cost:.2f}"
duration_info = ""
if duration is not None:
duration_info = f" | {duration:.1f}s"
error_info = ""
if entry.get('error'):
error_info = f" | Error: {entry['error']}"
print(f"[{timestamp[:19]}] {operation:<12} | {reason}{cost_info}{duration_info}{error_info}")
print("--- End of Log ---")
return {'success': True, 'log_entries': log_entries}
def sync_orchestration(
basename: str,
target_coverage: float = 90.0,
language: str = "python",
prompts_dir: str = "prompts",
code_dir: str = "src",
examples_dir: str = "examples",
tests_dir: str = "tests",
max_attempts: int = 3,
budget: float = 10.0,
skip_verify: bool = False,
skip_tests: bool = False,
dry_run: bool = False,
force: bool = False,
strength: float = DEFAULT_STRENGTH,
temperature: float = 0.0,
time_param: float = 0.25,
verbose: bool = False,
quiet: bool = False,
output_cost: Optional[str] = None,
review_examples: bool = False,
local: bool = False,
context_config: Optional[Dict[str, str]] = None,
context_override: Optional[str] = None,
confirm_callback: Optional[Callable[[str, str], bool]] = None,
no_steer: bool = False,
steer_timeout: float = DEFAULT_STEER_TIMEOUT_S,
agentic_mode: bool = False,
compress: bool = False,
evidence: bool = False,
snapshot_context: bool = False,
compressed_context: bool = False,
fresh: bool = False,
) -> Dict[str, Any]:
"""
Orchestrates the complete PDD sync workflow with parallel animation.
``fresh`` (issue #1938 Pillar A): when False (the default), the generate
operation regenerates mature modules surgically (edit-shaped) by driving
``code_generator_main`` with ``force_incremental_flag=True`` so declared
public symbols are preserved instead of being dropped by a full "rebirth"
regeneration. Pass ``fresh=True`` (``pdd sync --fresh``) to restore full
regeneration. ``code_generator_main`` still falls back to full generation
for new/empty modules or when the original prompt cannot be determined.
"""
# Handle None values from CLI (Issue #194) - defense in depth
if target_coverage is None:
target_coverage = 90.0
if budget is None:
budget = 10.0
if max_attempts is None:
max_attempts = 3
# Issue #1711: clear the per-(file, query) include-extraction guard counters
# at the start of every top-level sync run. The counters live on the
# IncludeQueryExtractor class so they survive the fresh instance preprocess.py
# creates each cycle; without an explicit reset here they would also leak
# across separate runs in a long-lived process (e.g. the server running sync
# in-process), falsely tripping the guard on later legitimate runs.
from .include_query_extractor import IncludeQueryExtractor
IncludeQueryExtractor.reset_session()
# Import get_extension at function scope
from .sync_determine_operation import get_extension
if dry_run:
# Issue #1211: best-effort path lookup so the log file resolves
# under the subproject's .pdd/meta even from a parent CWD.
# Only pass `paths` if discovery succeeded, to keep the
# positional-arg shape unchanged for callers/tests that don't
# care about the path hint.
try:
_dry_paths = get_pdd_file_paths(
basename, language, prompts_dir, context_override=context_override
)
except AmbiguousModuleError:
# Issue #1677: surface ambiguity even in dry-run so `pdd sync page
# --dry-run` reports the conflict instead of a misleading generic log.
raise
except Exception:
_dry_paths = None
if _dry_paths:
return _display_sync_log(basename, language, verbose, paths=_dry_paths)
return _display_sync_log(basename, language, verbose)
# --- Initialize State and Paths ---
try:
pdd_files = get_pdd_file_paths(basename, language, prompts_dir, context_override=context_override)
except FileNotFoundError as e:
if "test_config.py" in str(e) or "tests/test_" in str(e):
# Case-insensitive prompt file lookup for fallback
fallback_prompt = Path(prompts_dir) / f"{basename}_{language}.prompt"
if not fallback_prompt.exists():
prompts_dir_path = Path(prompts_dir)
if prompts_dir_path.is_dir():
target_lower = fallback_prompt.name.lower()
for candidate in prompts_dir_path.iterdir():
if candidate.name.lower() == target_lower and candidate.is_file():
fallback_prompt = candidate
break
pdd_files = {
'prompt': fallback_prompt,
'code': Path(f"src/{basename}.{get_extension(language)}"),
'example': Path(f"context/{basename}_example.{get_extension(language)}"),
'test': Path(f"tests/test_{basename}.{get_extension(language)}")
}
if not quiet:
print(f"Note: Test file missing, continuing with sync workflow to generate it")
else:
print(f"Error constructing paths: {e}")
return {
"success": False,
"error": f"Failed to construct paths: {str(e)}",
"summary": f"Failed to construct paths: {str(e)}",
"operations_completed": [],
"errors": [f"Path construction failed: {str(e)}"]
}
except AmbiguousModuleError:
# Issue #1677: an ambiguous bare basename is a hard, actionable error.
# Propagate it (like the dry-run branch above) so the CLI reports the
# conflict via handle_error instead of burying it in a generic
# "Failed to construct paths" result. Generation never starts.
raise
except Exception as e:
print(f"Error constructing paths: {e}")
return {
"success": False,
"error": f"Failed to construct paths: {str(e)}",
"operations_completed": [],
"errors": [f"Path construction failed: {str(e)}"]
}
test_output_needs_review = pdd_files.get("test_output_needs_review")
if test_output_needs_review:
# Issue #1903: the runner exists, but its effective collection path is
# opaque. Continue code/example work while suppressing every test/fix
# write and surface a machine-readable note to the issue-driven parent.
skip_tests = True
print(
f"{PDD_TEST_OUTPUT_NEEDS_REVIEW_MARKER}: "
f"{test_output_needs_review}",
flush=True,
)
try:
# Operation selection must never observe one half of a prior metadata
# commit. Recovery is scoped to this exact module/language identity.
recover_incomplete_metadata_transactions(
basename,
language,
paths=pdd_files,
)
from .sync_core.finalize import preflight_legacy_mutation
preflight_legacy_mutation(pdd_files)
except RuntimeError as exc:
return {
"success": False,
"error": str(exc),
"operations_completed": [],
"errors": [str(exc)],
}
# Shared state for animation (passed to App)
current_function_name_ref = ["initializing"]
stop_event = threading.Event()
current_cost_ref = [0.0]
prompt_path_ref = [str(pdd_files.get('prompt', 'N/A'))]
code_path_ref = [str(pdd_files.get('code', 'N/A'))]
example_path_ref = [str(pdd_files.get('example', 'N/A'))]
tests_path_ref = [str(pdd_files.get('test', 'N/A'))]
prompt_box_color_ref = ["blue"]
code_box_color_ref = ["blue"]
example_box_color_ref = ["blue"]
tests_box_color_ref = ["blue"]
compression_phase_metadata: List[Dict[str, Any]] = []
agentic_fallback_events: List[Dict[str, Any]] = []
# Mutable container for the app reference (set after app creation)
# This allows the worker to access app.request_confirmation()
app_ref: List[Optional['SyncApp']] = [None]
# Progress callback ref for TUI ProgressBar updates during auto-deps
progress_callback_ref: List[Optional[Callable[[int, int], None]]] = [None]
# Track if user has already confirmed overwrite (to avoid asking multiple times)
user_confirmed_overwrite: List[bool] = [False]
def get_confirm_callback() -> Optional[Callable[[str, str], bool]]:
"""Get the confirmation callback from the app if available.
Once user confirms, we remember it so subsequent operations don't ask again.
Fix for Issue #277: In headless mode, we now return a wrapper callback
that uses click.confirm AND sets user_confirmed_overwrite[0] = True,
so subsequent calls auto-confirm instead of prompting repeatedly.
"""
if user_confirmed_overwrite[0]:
# User already confirmed, return a callback that always returns True
return lambda msg, title: True
if app_ref[0] is not None:
def confirming_callback(msg: str, title: str) -> bool:
result = app_ref[0].request_confirmation(msg, title)
if result:
user_confirmed_overwrite[0] = True
return result
return confirming_callback
# Fix #277: In headless mode (app_ref is None), create a wrapper callback
# that sets the flag after confirmation, preventing repeated prompts
if confirm_callback is None:
def headless_confirming_callback(msg: str, title: str) -> bool:
"""Headless mode callback that remembers user confirmation."""
try:
prompt = msg or "Overwrite existing files?"
result = click.confirm(
click.style(prompt, fg="yellow"),
default=True,
show_default=True
)
except (click.Abort, EOFError):
return False
if result:
user_confirmed_overwrite[0] = True
return result
return headless_confirming_callback
return confirm_callback # Fall back to provided callback
def _phase_compressed_context(phase: str, repair_directive: Optional[str] = None) -> Optional[Dict[str, Any]]:
if not compressed_context:
return None
try:
test_paths = [Path(p) for p in pdd_files.get("test_files", [])] if pdd_files.get("test_files") else [pdd_files.get("test")]
package = build_compressed_sync_context(
phase=phase,
prompt_path=pdd_files["prompt"],
code_path=pdd_files.get("code"),
example_path=pdd_files.get("example"),
test_paths=[p for p in test_paths if p],
run_report_path=get_run_report_path(basename, language, paths=pdd_files),
repair_directive=repair_directive,
context_compression=os.environ.get("PDD_CONTEXT_COMPRESSION"),
)
package_dict = asdict(package)
compression_phase_metadata.append(compressed_context_metadata(package_dict))
return package_dict
except Exception as exc:
fallback = {
"enabled": True,
"used": False,
"phase": phase,
"mode": "compressed-sync-context",
"unavailable_reason": str(exc),
}
compression_phase_metadata.append(fallback)
return fallback
def _compression_log_metadata() -> Dict[str, Any]:
return {
"enabled": compressed_context,
"requested": compressed_context,
"used": any(item.get("used") for item in compression_phase_metadata),
"mode": "compressed-sync-context",
"phases": list(compression_phase_metadata),
}
def _agentic_fallback_log_metadata() -> Dict[str, Any]:
from .operation_log import aggregate_agentic_fallback_metadata
return aggregate_agentic_fallback_metadata(
phase_events=agentic_fallback_events,
agentic_sync_mode=agentic_mode,
)
def sync_worker_logic():
"""
The main loop of sync logic, run in a worker thread by Textual App.
"""
operations_completed: List[str] = []
skipped_operations: List[str] = []
errors: List[str] = []
start_time = time.time()
last_model_name: str = "unknown"
operation_history: List[str] = []
consecutive_noop_fixes = 0
operation_rollback: Optional[OperationFileRollback] = None
terminal_reason: Optional[str] = None
MAX_CYCLE_REPEATS = 2
try:
log_event(
basename,
language,
"sync_start",
{"pid": os.getpid()},
invocation_mode="sync",
paths=pdd_files,
compression=_compression_log_metadata(),
agentic_fallback=_agentic_fallback_log_metadata(),
)
except Exception:
# Best-effort logging; sync should proceed even if log setup fails.
pass
# Helper function to print inside worker (goes to RichLog via redirection)
# print() will work if sys.stdout is redirected.
try:
with SyncLock(basename, language):
log_event(basename, language, "lock_acquired", {"pid": os.getpid()}, invocation_mode="sync", paths=pdd_files)
# Issue #1203: track failing-test count across consecutive fix
# operations so the breaker can stay open while the fix loop is
# still making progress (failures strictly decreasing).
prev_fix_failures = None
while True:
budget_remaining = budget - current_cost_ref[0]
if current_cost_ref[0] >= budget:
errors.append(f"Budget of ${budget:.2f} exceeded.")
log_event(basename, language, "budget_exceeded", {
"total_cost": current_cost_ref[0],
"budget": budget
}, invocation_mode="sync", paths=pdd_files)
break
if budget_remaining < budget * 0.2 and budget_remaining > 0:
log_event(basename, language, "budget_warning", {
"remaining": budget_remaining,
"percentage": (budget_remaining / budget) * 100
}, invocation_mode="sync", paths=pdd_files)
decision = sync_determine_operation(
basename,
language,
target_coverage,
budget_remaining,
False,
prompts_dir,
skip_tests,
skip_verify,
context_override,
isolated_replay_or_repair=force or bool(os.environ.get("PDD_REPAIR_DIRECTIVE")),
)
operation = decision.operation
# Interactive steering: allow user to override the recommended operation.
if no_steer:
steered_op = operation
should_abort = False
else:
steered_op, should_abort = maybe_steer_operation(
operation,
decision.reason,
app_ref[0],
quiet,
skip_tests,
skip_verify,
timeout_s=steer_timeout,
)
if should_abort:
errors.append("User aborted sync via steering.")
log_event(basename, language, "steering_abort", {"recommended": operation}, invocation_mode="sync", paths=pdd_files)
break
if steered_op != operation:
log_event(
basename,
language,
"steering_override",
{"recommended": operation, "chosen": steered_op, "reason": decision.reason},
invocation_mode="sync",
paths=pdd_files,
)
operation = steered_op
# Keep decision.operation aligned with the chosen path for downstream logging.
decision.operation = steered_op
log_entry = create_log_entry(
operation=decision.operation,
reason=decision.reason,
invocation_mode="sync",
estimated_cost=decision.estimated_cost,
confidence=decision.confidence,
decision_type=decision.details.get("decision_type", "heuristic") if decision.details else "heuristic",
compression=_compression_log_metadata(),
agentic_fallback=_agentic_fallback_log_metadata(),
)
if decision.details:
log_entry.setdefault('details', {}).update(decision.details)
log_entry.setdefault('details', {})['budget_remaining'] = budget_remaining
operation_history.append(operation)
# Cycle detection logic
if len(operation_history) >= 3:
recent_auto_deps = [op for op in operation_history[-3:] if op == 'auto-deps']
if len(recent_auto_deps) >= 2:
errors.append("Detected auto-deps infinite loop. Force advancing to generate operation.")
log_event(basename, language, "cycle_detected", {"cycle_type": "auto-deps-infinite"}, invocation_mode="sync", paths=pdd_files)
operation = 'generate'
decision.operation = 'generate' # Update decision too
# Skip auto-deps in agentic mode — prompts already have explicit dependencies
if operation == 'auto-deps' and agentic_mode:
log_event(basename, language, "auto_deps_skipped", {
"reason": "auto-deps skipped in agentic mode — prompts have explicit dependencies"
}, invocation_mode="sync", paths=pdd_files)
operation = 'generate'
decision.operation = 'generate'
# Bug #4 fix: Detect crash-verify cycle pattern
# The pattern [crash, verify, crash, verify] or [verify, crash, verify, crash]
# represents 2 iterations of the alternating cycle, so break immediately
if len(operation_history) >= 4:
recent_ops = operation_history[-4:]
if (recent_ops == ['crash', 'verify', 'crash', 'verify'] or
recent_ops == ['verify', 'crash', 'verify', 'crash']):
# Pattern detected - this represents MAX_CYCLE_REPEATS iterations
errors.append(f"Detected crash-verify cycle repeated {MAX_CYCLE_REPEATS} times. Breaking cycle.")
log_event(basename, language, "cycle_detected", {"cycle_type": "crash-verify", "count": MAX_CYCLE_REPEATS}, invocation_mode="sync", paths=pdd_files)
break
# Bug #4 fix: Detect test-fix cycle pattern
# The pattern [test, fix, test, fix] or [fix, test, fix, test]
# represents 2 iterations of the alternating cycle, so break immediately
if len(operation_history) >= 4:
recent_ops = operation_history[-4:]
if (recent_ops == ['test', 'fix', 'test', 'fix'] or
recent_ops == ['fix', 'test', 'fix', 'test']):
# Pattern detected - this represents MAX_CYCLE_REPEATS iterations
errors.append(f"Detected test-fix cycle repeated {MAX_CYCLE_REPEATS} times. Breaking cycle.")
log_event(basename, language, "cycle_detected", {"cycle_type": "test-fix", "count": MAX_CYCLE_REPEATS}, invocation_mode="sync", paths=pdd_files)
break
if operation == 'fix':
consecutive_fixes = 0
for i in range(len(operation_history) - 1, -1, -1):
if operation_history[i] == 'fix':
consecutive_fixes += 1
else:
break
# Issue #1203: a regeneration that mismatches N error
# strings should be able to converge in ~N fix iterations.
# Don't trip the consecutive-fix breaker while the failing
# test count is still strictly decreasing. paths=pdd_files
# (Issue #1211) ensures the correct subproject .pdd/meta
# run report is read in parent-CWD/subproject setups.
current_rr = read_run_report(basename, language, paths=pdd_files)
current_failures = current_rr.tests_failed if current_rr is not None else None
making_progress = (
current_failures is not None
and prev_fix_failures is not None
and current_failures < prev_fix_failures
)
if current_failures is not None:
prev_fix_failures = current_failures
if consecutive_fixes >= MAX_CONSECUTIVE_FIXES and not making_progress:
msg = f"Detected {consecutive_fixes} consecutive fix operations with no progress. Breaking infinite fix loop."
errors.append(msg)
record_core_dump_error(
command="sync",
type="LogicalFailure",
message=msg,
details={
"basename": basename,
"language": language,
"reason": "consecutive_fix_limit",
"consecutive": consecutive_fixes,
"operations_completed": operations_completed,
"skipped_operations": skipped_operations,
"total_cost": current_cost_ref[0],
},
)
break
if operation == 'test':
consecutive_tests = 0
for i in range(len(operation_history) - 1, -1, -1):
if operation_history[i] == 'test':
consecutive_tests += 1
else:
break
if consecutive_tests >= MAX_CONSECUTIVE_TESTS:
msg = f"Detected {consecutive_tests} consecutive test operations. Breaking infinite test loop."
errors.append(msg)
record_core_dump_error(
command="sync",
type="LogicalFailure",
message=msg,
details={
"basename": basename,
"language": language,
"reason": "consecutive_test_limit",
"consecutive": consecutive_tests,
"operations_completed": operations_completed,
"skipped_operations": skipped_operations,
"total_cost": current_cost_ref[0],
},
)
break
# Bug #157 fix: Prevent infinite crash retry loops
if operation == 'crash':
consecutive_crashes = 0
for i in range(len(operation_history) - 1, -1, -1):
if operation_history[i] == 'crash':
consecutive_crashes += 1
else:
break
if consecutive_crashes >= MAX_CONSECUTIVE_CRASHES:
msg = f"Detected {consecutive_crashes} consecutive crash operations. Breaking infinite crash loop."
errors.append(msg)
record_core_dump_error(
command="sync",
type="LogicalFailure",
message=msg,
details={
"basename": basename,
"language": language,
"reason": "consecutive_crash_limit",
"consecutive": consecutive_crashes,
"operations_completed": operations_completed,
"skipped_operations": skipped_operations,
"total_cost": current_cost_ref[0],
},
)
break
if operation == 'test_extend':
# PR auto-heal scope guard (#1403): when test_extend is
# disabled, accept the current state as complete instead
# of appending coverage-driven tests. This is the
# execution-time backstop for the detection-layer guard
# in sync_determine_operation — even if a `pdd sync`
# child re-derives a coverage gap, no unrelated test
# block is written. Accept regardless of coverage
# (the gap is known and intentionally not closed).
if is_test_extend_disabled():
current_rr = read_run_report(basename, language, paths=pdd_files)
log_event(basename, language, "test_extend_skipped", {
"reason": "test_extend disabled by PDD_DISABLE_TEST_EXTEND (PR auto-heal scope guard)",
"coverage": current_rr.coverage if current_rr else None,
"coverage_ok": True
}, invocation_mode="sync", paths=pdd_files)
success = True
break
# Skip test_extend for non-Python languages - code coverage tooling is Python-specific.
# Python always has working coverage tools, so test_extend runs even in agentic mode.
if language.lower() != 'python':
# Bug #573: Check coverage before accepting — don't declare success
# if coverage is below target (e.g. 0.0 from sys.modules stubs)
current_rr = read_run_report(basename, language, paths=pdd_files)
coverage_ok = current_rr is not None and current_rr.coverage >= target_coverage
log_event(basename, language, "test_extend_skipped", {
"reason": f"test_extend not supported for {language} (or agentic_mode), {'accepting' if coverage_ok else 'rejecting'} current state",
"coverage": current_rr.coverage if current_rr else None,
"coverage_ok": coverage_ok
}, invocation_mode="sync", paths=pdd_files)
if not coverage_ok:
current_cov = current_rr.coverage if current_rr else 0.0
errors.append(f"Coverage {current_cov:.1f}% below target {target_coverage:.1f}% after test_extend skip (agentic mode)")
success = coverage_ok
break
# Count test_extend attempts to prevent infinite loop
extend_attempts = sum(1 for op in operation_history if op == 'test_extend')
if extend_attempts >= MAX_TEST_EXTEND_ATTEMPTS:
# Bug #573: Check coverage before accepting — don't declare success
# if coverage is below target after exhausting retries
current_rr = read_run_report(basename, language, paths=pdd_files)
coverage_ok = current_rr is not None and current_rr.coverage >= target_coverage
log_event(basename, language, "test_extend_limit", {
"attempts": extend_attempts,
"max_attempts": MAX_TEST_EXTEND_ATTEMPTS,
"reason": "Max extend attempts reached",
"coverage": current_rr.coverage if current_rr else None,
"coverage_ok": coverage_ok
}, invocation_mode="sync", paths=pdd_files)
if not coverage_ok:
current_cov = current_rr.coverage if current_rr else 0.0
errors.append(f"Coverage {current_cov:.1f}% below target {target_coverage:.1f}% after {extend_attempts} test_extend attempts")
success = coverage_ok
break
if operation in ['all_synced', 'nothing', 'fail_and_request_manual_merge', 'error']:
current_function_name_ref[0] = "synced" if operation in ['all_synced', 'nothing'] else "conflict"
# Emit phase marker for parent process to parse (agentic sync progress tracking)
print(f"PDD_PHASE: {current_function_name_ref[0]}", flush=True)
success = operation in ['all_synced', 'nothing']
# Preserve the decision reason for terminal success states so the
# final summary can surface accepted-as-complete details
# (e.g. coverage skipped, test_extend not supported, unparseable
# coverage). Without this the summary collapses to a generic
# "no operations required" message and the user never sees why
# we accepted the run as complete (#1103).
if operation == 'all_synced' and decision.reason:
terminal_reason = decision.reason
error_msg = None
if operation == 'fail_and_request_manual_merge':
msg = f"Manual merge required: {decision.reason}"
errors.append(msg)
record_core_dump_error(
command="sync",
type="ManualMergeRequired",
message=msg,
details={
"basename": basename,
"language": language,
"operation": operation,
"reason": decision.reason,
"operations_completed": operations_completed,
"skipped_operations": skipped_operations,
"total_cost": current_cost_ref[0],
},
)
error_msg = decision.reason
elif operation == 'error':
msg = f"Error determining operation: {decision.reason}"
errors.append(msg)
record_core_dump_error(
command="sync",
type="DecisionError",
message=msg,
details={
"basename": basename,
"language": language,
"operation": operation,
"reason": decision.reason,
"operations_completed": operations_completed,
"skipped_operations": skipped_operations,
"total_cost": current_cost_ref[0],
},
)
error_msg = decision.reason
update_log_entry(log_entry, success=success, cost=0.0, model='none', duration=0.0, error=error_msg)
append_log_entry(basename, language, log_entry, paths=pdd_files)
break
# Handle skips - save fingerprint with 'skip:' prefix to distinguish from actual execution
# Bug #11 fix: Use 'skip:' prefix so _is_workflow_complete() knows the op was skipped
if operation == 'verify' and (skip_verify or skip_tests):
skipped_operations.append('verify')
print(f"PDD_PHASE: skip:{operation}", flush=True)
update_log_entry(log_entry, success=True, cost=0.0, model='skipped', duration=0.0, error=None)
append_log_entry(basename, language, log_entry, paths=pdd_files)
# Save fingerprint with 'skip:' prefix to indicate operation was skipped, not executed
_save_fingerprint_atomic(basename, language, 'skip:verify', pdd_files, 0.0, 'skipped')
consecutive_noop_fixes = 0
continue
if operation == 'fix' and skip_tests:
skipped_operations.append('fix')
print(f"PDD_PHASE: skip:{operation}", flush=True)
update_log_entry(log_entry, success=True, cost=0.0, model='skipped', duration=0.0, error=None)
append_log_entry(basename, language, log_entry, paths=pdd_files)
# Save fingerprint with 'skip:' prefix to indicate operation was skipped, not executed
_save_fingerprint_atomic(basename, language, 'skip:fix', pdd_files, 0.0, 'skipped')
continue
if operation == 'test' and skip_tests:
skipped_operations.append('test')
print(f"PDD_PHASE: skip:{operation}", flush=True)
update_log_entry(log_entry, success=True, cost=0.0, model='skipped', duration=0.0, error=None)
append_log_entry(basename, language, log_entry, paths=pdd_files)
# Save fingerprint with 'skip:' prefix to indicate operation was skipped, not executed
_save_fingerprint_atomic(basename, language, 'skip:test', pdd_files, 0.0, 'skipped')
consecutive_noop_fixes = 0
continue
if operation == 'crash' and (skip_tests or skip_verify):
skipped_operations.append('crash')
print(f"PDD_PHASE: skip:{operation}", flush=True)
update_log_entry(log_entry, success=True, cost=0.0, model='skipped', duration=0.0, error=None)
append_log_entry(basename, language, log_entry, paths=pdd_files)
# Save fingerprint with 'skip:' prefix to indicate operation was skipped, not executed
_save_fingerprint_atomic(basename, language, 'skip:crash', pdd_files, 0.0, 'skipped')
# FIX: Create a synthetic run_report to prevent infinite loop when crash is skipped
# Without this, sync_determine_operation keeps returning 'crash' because no run_report exists
current_hashes = calculate_current_hashes(
pdd_files,
dependency_root=trusted_hash_root_for_paths(pdd_files),
)
synthetic_report = RunReport(
timestamp=datetime.datetime.now(datetime.timezone.utc).isoformat(),
exit_code=0, # Assume success since we're skipping validation
tests_passed=0,
tests_failed=0,
coverage=0.0,
test_hash=current_hashes.get('test_hash')
)
_save_run_report_atomic(asdict(synthetic_report), basename, language, paths=pdd_files)
consecutive_noop_fixes = 0
continue
current_function_name_ref[0] = operation
# Emit phase marker for parent process to parse (agentic sync progress tracking)
print(f"PDD_PHASE: {operation}", flush=True)
ctx = _create_mock_context(
force=force, strength=strength, temperature=temperature, time=time_param,
verbose=verbose, quiet=quiet, output_cost=output_cost,
review_examples=review_examples, local=local, budget=budget - current_cost_ref[0],
max_attempts=max_attempts, target_coverage=target_coverage,
confirm_callback=get_confirm_callback(),
context=context_override,
agentic_mode=agentic_mode,
)
result = {}
success = False
op_start_time = time.time()
include_deps_override = None # Issue #522: Captured before auto-deps strips tags
test_output_excerpt: Optional[str] = None
operation_rollback = None
from .continuous_sync import canonical_sync_enabled
operation_start = pdd_files.get("prompt") or Path.cwd()
if canonical_sync_enabled(Path(operation_start)):
raise RuntimeError(
"protected canonical sync blocks legacy production mutation; "
"use read-only reporting or trusted finalization until the "
"staged repair executor is enabled"
)
# Issue #159 fix: Use atomic state for consistent run_report + fingerprint writes
set_current_operation(operation)
# Drop any stale LLM trace for this operation key so failure paths only
# attach pairs from the current attempt (success paths do not pop).
pop_last_pair(operation)
with AtomicStateUpdate(basename, language) as atomic_state:
# --- Execute Operation ---
try:
if operation == 'auto-deps':
temp_output = Path(str(pdd_files['prompt']).replace('.prompt', '_with_deps.prompt'))
if operation_rollback is None:
operation_rollback = _build_auto_deps_rollback(
pdd_files['prompt'],
temp_output,
)
original_content = pdd_files['prompt'].read_text(encoding='utf-8')
# Issue #522: Capture include deps BEFORE auto-deps may strip tags
from .sync_determine_operation import extract_include_deps
include_deps_override = extract_include_deps(pdd_files['prompt'])
result = auto_deps_main(
ctx,
prompt_file=str(pdd_files['prompt']),
directory_path=examples_dir,
auto_deps_csv_path=(context_config or {}).get('auto_deps_csv_path'),
output=str(temp_output),
force_scan=False,
progress_callback=progress_callback_ref[0],
# Sync owns canonical fingerprint/run-report
# bookkeeping (the _save_fingerprint_atomic
# call below and the clear_run_report after
# the move). Suppress auto_deps_main's own
# finalization to avoid orphan
# ``.pdd/meta/*_with_deps.json`` files for
# the temp output (issue #989 follow-up).
compress=compress,
_skip_finalization=True,
)
if temp_output.exists():
import shutil
new_content = temp_output.read_text(encoding='utf-8')
if new_content != original_content:
shutil.move(str(temp_output), str(pdd_files['prompt']))
# Issue #989: clear the canonical stale
# ``_run.json`` because the prompt
# content just changed. Mirrors the
# clear after generate (line 2272).
try:
clear_run_report(basename, language, paths=pdd_files)
except Exception:
# Never mask a successful auto-deps
# result on metadata cleanup errors.
pass
else:
temp_output.unlink()
result = (new_content, 0.0, 'no-changes')
elif operation == 'generate':
# Ensure code directory exists before generating
pdd_files['code'].parent.mkdir(parents=True, exist_ok=True)
# Architecture-conformance repair loop (#866). Retry generation when
# the generated code is missing declared interface symbols, injecting
# the repair directive via PDD_REPAIR_DIRECTIVE so the next attempt
# sees the missing-export instruction. Mirrors the loop in
# sync_main.py / agentic_sync_runner.py for parity across all
# `pdd sync` entry points.
from .code_generator_main import (
ArchitectureConformanceError,
PublicSurfaceRegressionError,
)
from .agentic_sync_runner import (
MAX_CONFORMANCE_ATTEMPTS,
build_conformance_hard_failure_from_error,
build_public_surface_hard_failure_from_error,
)
_prev_repair = os.environ.get("PDD_REPAIR_DIRECTIVE")
# Pop the env var BEFORE attempt 1 (#1012,
# F-J) so `code_generator_main` reads a
# CLEAN env on the first try. Without
# this, a stale outer `PDD_REPAIR_DIRECTIVE`
# (set by the caller's shell, a parent
# orchestration layer, or a prior PDD
# command) would be injected into the
# first generation attempt's prompt via
# the `<architecture_repair_directive>`
# block read at code_generator_main.py:1990.
# Only failures raised inside THIS loop
# populate the directive for subsequent
# attempts. The `finally` block below
# restores the prior outer value when
# the loop exits. Mirrors the parallel
# pop in `_run_test_op_with_churn_retry`
# (F-G) and `one_session_sync` (F-I).
os.environ.pop("PDD_REPAIR_DIRECTIVE", None)
try:
last_conform_exc: Optional[Any] = None
last_conform_signature: Optional[tuple] = None
last_conform_kind: Optional[str] = None
conformance_failed_cost = 0.0
conformance_failed_model = ""
for _conform_attempt in range(MAX_CONFORMANCE_ATTEMPTS):
try:
# Use absolute paths to avoid path_resolution_mode mismatch between sync (cwd) and generate (config_base)
result = code_generator_main(ctx, prompt_file=str(pdd_files['prompt'].resolve()), output=str(pdd_files['code'].resolve()), original_prompt_file_path=None, force_incremental_flag=not fresh, output_from_config=True, compress=compress, snapshot_context=snapshot_context, compressed_context=_phase_compressed_context('generate', os.environ.get("PDD_REPAIR_DIRECTIVE")))
last_conform_exc = None
break
except (
ArchitectureConformanceError,
PublicSurfaceRegressionError,
TestChurnError,
) as _conform_exc:
attempt_cost = float(getattr(_conform_exc, "total_cost", 0.0) or 0.0)
conformance_failed_cost += attempt_cost
_conform_exc.total_cost = conformance_failed_cost
exc_model = getattr(_conform_exc, "model_name", "") or ""
if exc_model and exc_model != "unknown":
conformance_failed_model = exc_model
if isinstance(_conform_exc, PublicSurfaceRegressionError):
new_kind = "public_surface"
new_signature = tuple(
[
f"removed:{symbol}"
for symbol in sorted(set(_conform_exc.removed_symbols))
]
+ [
f"signature_changed:{symbol}"
for symbol in sorted(
set(
getattr(
_conform_exc,
"changed_signatures",
[],
)
)
)
]
)
elif isinstance(_conform_exc, TestChurnError):
new_kind = "test_churn"
new_signature = (
f"{_conform_exc.churn_ratio:.2f}",
str(_conform_exc.pre_line_count),
)
else:
new_kind = "architecture"
new_signature = tuple(sorted(set(_conform_exc.missing_symbols)))
if (
last_conform_signature is not None
and new_signature == last_conform_signature
and new_kind == last_conform_kind
):
last_conform_exc = _conform_exc
break
last_conform_signature = new_signature
last_conform_kind = new_kind
last_conform_exc = _conform_exc
if _conform_attempt + 1 >= MAX_CONFORMANCE_ATTEMPTS:
break
if isinstance(_conform_exc, TestChurnError) and _conform_attempt >= 1:
break
if conformance_failed_cost >= max(budget - current_cost_ref[0], 0.0):
break
os.environ["PDD_REPAIR_DIRECTIVE"] = _conform_exc.repair_directive
if last_conform_exc is not None:
# Emit the structured hard-failure block
# (#866 contract: plain CLI path must show the
# same diagnostic the agentic runner emits)
# before re-raising. The generic except below
# converts the exception into an errors.append
# entry, but the structured block has already
# been written to stderr for the user.
if isinstance(last_conform_exc, PublicSurfaceRegressionError):
hard_block = build_public_surface_hard_failure_from_error(
last_conform_exc, basename
)
elif isinstance(last_conform_exc, TestChurnError):
hard_block = build_test_churn_hard_failure_from_error(
last_conform_exc, basename
)
else:
hard_block = build_conformance_hard_failure_from_error(
last_conform_exc, basename
)
print(hard_block, file=sys.stderr)
raise last_conform_exc
if conformance_failed_cost and isinstance(result, tuple) and len(result) >= 4:
result = (
result[0],
result[1],
float(result[2] or 0.0) + conformance_failed_cost,
result[3] or conformance_failed_model or "unknown",
)
finally:
if _prev_repair is None:
os.environ.pop("PDD_REPAIR_DIRECTIVE", None)
else:
os.environ["PDD_REPAIR_DIRECTIVE"] = _prev_repair
# Clear stale run_report so crash/verify is required for newly generated code
clear_run_report(basename, language, paths=pdd_files)
if evidence:
try:
from .evidence_manifest import write_evidence_manifest, validation_from_sync
# Use the current sync result state for evidence
sync_result = {"success": True, "summary": "Generated code from prompt"}
if isinstance(result, tuple) and len(result) >= 3:
sync_result["total_cost"] = result[1]
sync_result["model_name"] = result[2]
elif isinstance(result, dict):
sync_result.update(result)
validation = validation_from_sync(
sync_result,
skip_tests=skip_tests,
skip_verify=skip_verify,
)
write_evidence_manifest(
basename=basename,
language=language,
command="sync",
validation=validation,
pdd_files=pdd_files,
)
except Exception as e:
logger.warning(f"Failed to write evidence manifest: {e}")
# Issue #572: Validate Python imports after generation in agentic mode
if agentic_mode and language.lower() == 'python' and pdd_files['code'].exists():
unresolved = _validate_python_imports(
pdd_files['code'],
)
if unresolved:
error_msg = (
f"Hallucinated imports detected in generated code: "
f"{'; '.join(unresolved)}."
)
errors.append(error_msg)
log_event(basename, language, "import_validation_failed", {
"unresolved_imports": unresolved,
"code_file": str(pdd_files['code']),
}, invocation_mode="sync", paths=pdd_files)
# Issue #624: Validate TypeScript/JavaScript imports after generation in agentic mode
if agentic_mode and language.lower() in ('typescript', 'javascript', 'typescriptreact', 'javascriptreact') and pdd_files['code'].exists():
unresolved = _validate_typescript_imports(
pdd_files['code'],
)
if unresolved:
error_msg = (
f"Hallucinated imports detected in generated code: "
f"{', '.join(unresolved)}. "
f"These modules do not exist on disk or in the project."
)
errors.append(error_msg)
log_event(basename, language, "import_validation_failed", {
"unresolved_imports": unresolved,
"code_file": str(pdd_files['code']),
}, invocation_mode="sync", paths=pdd_files)
elif operation == 'example':
# Ensure example directory exists before generating
pdd_files['example'].parent.mkdir(parents=True, exist_ok=True)
# Use absolute paths to avoid path_resolution_mode mismatch between sync (cwd) and example (config_base)
result = context_generator_main(ctx, prompt_file=str(pdd_files['prompt'].resolve()), code_file=str(pdd_files['code'].resolve()), output=str(pdd_files['example'].resolve()))
elif operation == 'crash':
required_files = [pdd_files['code'], pdd_files['example']]
missing_files = [f for f in required_files if not f.exists()]
if missing_files:
skipped_operations.append('crash')
continue
# Crash handling logic (simplified copy from original)
current_run_report = read_run_report(basename, language, paths=pdd_files)
crash_log_content = ""
# Check for crash condition (either run report says so, or we check manually)
has_crash = False
if current_run_report and current_run_report.exit_code != 0:
has_crash = True
crash_log_content = f"Test execution failed exit code: {current_run_report.exit_code}\n"
elif _use_agentic_path(language, agentic_mode) and language.lower() != 'python':
# Bug #364 fix: For non-Python languages, skip Python-based verification.
# Delegate crash detection and fixing to the agentic handler, which
# uses the correct language-specific run command.
has_crash = True
crash_log_content = f"Language {language} (agentic_mode={agentic_mode}) - delegating crash detection to agentic handler.\n"
else:
# Manual check - run the example to see if it crashes
env = os.environ.copy()
code_dir = pdd_files['code'].resolve().parent
env['PYTHONPATH'] = f"{code_dir}:{env.get('PYTHONPATH', '')}"
# Remove TUI-specific env vars that might contaminate subprocess
for var in ['FORCE_COLOR', 'COLUMNS']:
env.pop(var, None)
# Bug fix: Use sys.executable to match crash_main's Python interpreter
# and do NOT set cwd - inherit from pdd invocation directory
# to match crash_main behavior. Setting cwd to example's parent breaks imports.
example_path = str(pdd_files['example'].resolve())
cmd_parts = [sys.executable, example_path]
# Use error-detection runner that handles server-style examples
returncode, stdout, stderr = _run_example_with_error_detection(
cmd_parts,
env=env,
timeout=60
)
class ExampleResult:
def __init__(self, rc, out, err):
self.returncode = rc
self.stdout = out
self.stderr = err
ex_res = ExampleResult(returncode, stdout, stderr)
if ex_res.returncode != 0:
has_crash = True
crash_log_content = f"Example failed exit code: {ex_res.returncode}\nSTDOUT:\n{ex_res.stdout}\nSTDERR:\n{ex_res.stderr}\n"
if "SyntaxError" in ex_res.stderr:
crash_log_content = "SYNTAX ERROR DETECTED:\n" + crash_log_content
else:
# No crash - for Python, run real tests to get actual coverage.
# For non-Python, save synthetic report (no coverage tools).
if language.lower() == 'python' and pdd_files['test'].exists():
_execute_tests_and_create_run_report(
pdd_files['test'],
basename,
language,
target_coverage,
code_file=pdd_files.get("code"),
atomic_state=atomic_state,
test_files=pdd_files.get('test_files'),
)
else:
test_hash = (
calculate_sha256(
pdd_files['test'],
trusted_hash_root_for_paths(pdd_files),
)
if pdd_files['test'].exists()
else None
)
report = RunReport(
datetime.datetime.now(datetime.timezone.utc).isoformat(),
exit_code=0,
tests_passed=1,
tests_failed=0,
coverage=0.0,
test_hash=test_hash
)
_save_run_report_atomic(asdict(report), basename, language, atomic_state=atomic_state, paths=pdd_files)
skipped_operations.append('crash')
continue
if has_crash:
# Try auto-fix for common import errors before expensive agentic call
auto_fixed, auto_fix_msg = _try_auto_fix_import_error(
crash_log_content,
pdd_files['code'],
pdd_files['example']
)
if not auto_fixed:
# Try auto-fix for missing environment variable errors
auto_fixed, auto_fix_msg = _try_auto_fix_env_var_error(
crash_log_content,
pdd_files['example']
)
if auto_fixed:
log_event(basename, language, "auto_fix_attempted", {"message": auto_fix_msg}, invocation_mode="sync", paths=pdd_files)
# Retry running the example after auto-fix
retry_returncode, retry_stdout, retry_stderr = _run_example_with_error_detection(
cmd_parts,
env=env,
timeout=60
)
if retry_returncode == 0:
# Auto-fix worked! Save run report and continue
log_event(basename, language, "auto_fix_success", {"message": auto_fix_msg}, invocation_mode="sync", paths=pdd_files)
if language.lower() == 'python' and pdd_files['test'].exists():
_execute_tests_and_create_run_report(
pdd_files['test'], basename, language, target_coverage,
code_file=pdd_files.get("code"), atomic_state=atomic_state,
test_files=pdd_files.get('test_files'),
)
else:
test_hash = (
calculate_sha256(
pdd_files['test'],
trusted_hash_root_for_paths(pdd_files),
)
if pdd_files['test'].exists()
else None
)
report = RunReport(
datetime.datetime.now(datetime.timezone.utc).isoformat(),
exit_code=0, tests_passed=1, tests_failed=0, coverage=0.0,
test_hash=test_hash
)
_save_run_report_atomic(asdict(report), basename, language, atomic_state=atomic_state, paths=pdd_files)
result = (True, 0.0, 'auto-fix')
success = True
actual_cost = 0.0
model_name = 'auto-fix'
# Update crash_log_content for logging
crash_log_content = f"Auto-fixed: {auto_fix_msg}"
# Fix for issue #430: Save fingerprint and track operation completion before continuing
operations_completed.append('crash')
_save_fingerprint_atomic(basename, language, 'crash', pdd_files, 0.0, 'auto-fix', atomic_state=atomic_state, include_deps_override=include_deps_override)
continue # Skip crash_main, move to next operation
else:
# Auto-fix didn't fully work, update error log and proceed
crash_log_content = f"Auto-fix attempted ({auto_fix_msg}) but still failing:\nRETRY STDOUT:\n{retry_stdout}\nRETRY STDERR:\n{retry_stderr}\n"
Path("crash.log").write_text(crash_log_content)
# Snapshot pre-operation code so the
# public-surface gate (#1012, P2.A)
# can verify crash_main's rewrite
# did not regress public symbols.
try:
_crash_pre_code = pdd_files['code'].read_text(encoding="utf-8")
except OSError:
_crash_pre_code = ""
try:
# For non-Python languages (or agentic mode), set max_attempts=0 to skip iterative loop
# and go directly to agentic fallback
effective_max_attempts = 0 if _use_agentic_path(language, agentic_mode) else max_attempts
result = crash_main(ctx, prompt_file=str(pdd_files['prompt']), code_file=str(pdd_files['code']), program_file=str(pdd_files['example']), error_file="crash.log", output=str(pdd_files['code']), output_program=str(pdd_files['example']), loop=True, max_attempts=effective_max_attempts, budget=budget - current_cost_ref[0], strength=strength, temperature=temperature)
except Exception as e:
print(f"Crash fix failed: {e}")
skipped_operations.append('crash')
continue
# Post-operation public-surface gate
# (#1012, P2.A). crash_main writes
# the code file directly; without
# this check it could silently
# regress the surface that the
# generate gate accepted.
_crash_surface_exc = _verify_code_surface_after_write(
code_path=pdd_files['code'],
pre_code=_crash_pre_code,
basename=basename,
language=language,
prompt_path=pdd_files['prompt'],
operation='crash',
)
if _crash_surface_exc is not None:
from .agentic_sync_runner import (
build_public_surface_hard_failure_from_error,
)
hard_block = build_public_surface_hard_failure_from_error(
_crash_surface_exc, basename
)
print(hard_block, file=sys.stderr)
# Charge the failed helper's cost
# against the budget (#1012, P3.A)
# — without this, expensive
# crash_main spend that produced
# a regressing rewrite goes
# un-billed.
if isinstance(result, tuple):
current_cost_ref[0] += _extract_cost_from_result(
'crash', result
)
errors.append(
f"crash operation regressed public surface — refusing to continue. "
f"Add a `BREAKING-CHANGE:` directive to the prompt to opt out, "
f"or fix the prompt/code to preserve the public symbols. "
f"Details: {_crash_surface_exc}"
)
skipped_operations.append('crash')
# Terminate the operation loop
# (#1012, P3.A): a surface
# regression is a contract
# violation, not a transient
# failure. `continue` would let
# `sync_determine_operation`
# re-select the same op next
# iteration and spin
# indefinitely on deterministic
# bad output.
break
elif operation == 'verify':
if not pdd_files['example'].exists():
skipped_operations.append('verify')
continue
# For non-Python languages (or agentic mode), set max_attempts=0 to skip iterative loop
# and go directly to agentic fallback
effective_max_attempts = 0 if _use_agentic_path(language, agentic_mode) else max_attempts
# Snapshot pre-operation code so the
# public-surface gate (#1012, P2.A) can
# verify the verify-op's rewrite did
# not regress public symbols.
try:
_verify_pre_code = pdd_files['code'].read_text(encoding="utf-8")
except OSError:
_verify_pre_code = ""
result = fix_verification_main(ctx, prompt_file=str(pdd_files['prompt']), code_file=str(pdd_files['code']), program_file=str(pdd_files['example']), output_results=f"{basename.replace('/', '_')}_verify_results.log", output_code=str(pdd_files['code']), output_program=str(pdd_files['example']), loop=True, verification_program=str(pdd_files['example']), max_attempts=effective_max_attempts, budget=budget - current_cost_ref[0], strength=strength, temperature=temperature, compressed_context=_phase_compressed_context('verify'), agentic_fallback_events=agentic_fallback_events)
_verify_surface_exc = _verify_code_surface_after_write(
code_path=pdd_files['code'],
pre_code=_verify_pre_code,
basename=basename,
language=language,
prompt_path=pdd_files['prompt'],
operation='verify',
)
if _verify_surface_exc is not None:
from .agentic_sync_runner import (
build_public_surface_hard_failure_from_error,
)
hard_block = build_public_surface_hard_failure_from_error(
_verify_surface_exc, basename
)
print(hard_block, file=sys.stderr)
# Charge the failed helper's cost
# (#1012, P3.A).
if isinstance(result, tuple):
current_cost_ref[0] += _extract_cost_from_result(
'verify', result
)
errors.append(
f"verify operation regressed public surface — refusing to continue. "
f"Add a `BREAKING-CHANGE:` directive to the prompt to opt out, "
f"or fix the prompt/code to preserve the public symbols. "
f"Details: {_verify_surface_exc}"
)
skipped_operations.append('verify')
# Terminate the operation loop
# (#1012, P3.A): a surface
# regression is a contract
# violation. The verify op has no
# consecutive-operation guard, so
# `continue` would let
# `sync_determine_operation`
# re-select it and spin
# indefinitely on deterministic
# bad output.
break
elif operation == 'test':
pdd_files['test'].parent.mkdir(parents=True, exist_ok=True)
# Use merge=True when test file exists to preserve fixes and append new tests
# instead of regenerating from scratch (which would overwrite fixes)
test_file_exists = pdd_files['test'].exists()
# Wrap `cmd_test_main` in the test-churn repair loop so
# `TestChurnError` thrown by `_verify_test_churn` round-trips
# through `PDD_REPAIR_DIRECTIVE` (mirrors the generate-op loop;
# #1012). The helper restores the previous env value on exit
# and prints the hard-failure block on exhaustion before
# re-raising — keep the generic `except` below clear of any
# duplicate print.
result = _run_test_op_with_churn_retry(
lambda _repair_directive: cmd_test_main(ctx, prompt_file=str(pdd_files['prompt']), code_file=str(pdd_files['code']), output=str(pdd_files['test']), language=language, coverage_report=None, existing_tests=[str(pdd_files['test'])] if test_file_exists else None, target_coverage=target_coverage, merge=test_file_exists, strength=strength, temperature=temperature, repair_directive=_repair_directive, compressed_context=_phase_compressed_context('test', _repair_directive)),
basename=basename,
budget_remaining=budget - current_cost_ref[0],
)
# Always run real tests to get accurate pass/fail counts.
# sync_determine_operation needs real tests_failed to recommend 'fix'.
if pdd_files['test'].exists():
_execute_tests_and_create_run_report(
pdd_files['test'],
basename,
language,
target_coverage,
code_file=pdd_files.get("code"),
atomic_state=atomic_state,
test_files=pdd_files.get('test_files'), # Bug #156
)
elif operation == 'test_extend':
# Extend existing tests to improve coverage
# Uses existing_tests and merge=True to add more test cases
pdd_files['test'].parent.mkdir(parents=True, exist_ok=True)
if pdd_files['test'].exists():
existing_test_path = str(pdd_files['test'])
# Same test-churn repair loop as the plain `test`
# op so coverage-extension regenerations also get
# one bounded retry under `PDD_REPAIR_DIRECTIVE`.
result = _run_test_op_with_churn_retry(
lambda _repair_directive: cmd_test_main(
ctx,
prompt_file=str(pdd_files['prompt']),
code_file=str(pdd_files['code']),
output=str(pdd_files['test']),
language=language,
coverage_report=None,
existing_tests=[existing_test_path],
target_coverage=target_coverage,
merge=True,
strength=strength,
temperature=temperature,
repair_directive=_repair_directive,
compressed_context=_phase_compressed_context('test_extend', _repair_directive),
),
basename=basename,
budget_remaining=budget - current_cost_ref[0],
)
# Always run real tests for accurate pass/fail counts.
_execute_tests_and_create_run_report(
pdd_files['test'],
basename,
language,
target_coverage,
code_file=pdd_files.get("code"),
atomic_state=atomic_state,
test_files=pdd_files.get('test_files'), # Bug #156
)
else:
# No existing test file, fall back to regular test generation.
# Pre-existing file is empty so the churn gate would not
# trip (`_compute_test_churn_ratio` returns 0 for an empty
# pre), but wrap in the same helper for symmetry and so the
# `PDD_REPAIR_DIRECTIVE` env var is still cleaned up.
result = _run_test_op_with_churn_retry(
lambda _repair_directive: cmd_test_main(ctx, prompt_file=str(pdd_files['prompt']), code_file=str(pdd_files['code']), output=str(pdd_files['test']), language=language, coverage_report=None, existing_tests=None, target_coverage=target_coverage, merge=False, strength=strength, temperature=temperature, repair_directive=_repair_directive, compressed_context=_phase_compressed_context('test', _repair_directive)),
basename=basename,
budget_remaining=budget - current_cost_ref[0],
)
# Always run real tests for accurate pass/fail counts.
if pdd_files['test'].exists():
_execute_tests_and_create_run_report(
pdd_files['test'],
basename,
language,
target_coverage,
code_file=pdd_files.get("code"),
atomic_state=atomic_state,
test_files=pdd_files.get('test_files'), # Bug #156
)
elif operation == 'fix':
error_file_path = Path("fix_errors.log")
# Capture errors using language-appropriate test command
try:
from .get_test_command import get_test_command_for_file
test_cmd = get_test_command_for_file(str(pdd_files['test']), language)
# Use clean env without TUI-specific vars
clean_env = os.environ.copy()
for var in ['FORCE_COLOR', 'COLUMNS']:
clean_env.pop(var, None)
if test_cmd:
# Run language-appropriate test command
if language.lower() == 'python' and not agentic_mode:
# Use pytest directly for Python
python_executable = detect_host_python_executable()
# Bug #156: Run pytest on ALL matching test files
test_files = pdd_files.get('test_files', [pdd_files['test']])
pytest_args = [python_executable, '-m', 'pytest'] + [str(f) for f in test_files] + ['-v', '--tb=short']
# Bug fix: Find project root for proper pytest configuration
# This matches the fix in _execute_tests_and_create_run_report()
project_root = _find_project_root(pdd_files['test'])
# Set up subprocess kwargs
subprocess_kwargs = {
'capture_output': True,
'text': True,
'timeout': 300,
'stdin': subprocess.DEVNULL,
'env': clean_env,
'start_new_session': True
}
if project_root is not None:
# Add PYTHONPATH to include project root and src/ directory
paths_to_add = [str(project_root)]
src_dir = project_root / "src"
if src_dir.is_dir():
paths_to_add.insert(0, str(src_dir))
existing_pythonpath = clean_env.get("PYTHONPATH", "")
if existing_pythonpath:
paths_to_add.append(existing_pythonpath)
clean_env["PYTHONPATH"] = os.pathsep.join(paths_to_add)
# Add --rootdir and -c /dev/null to prevent parent config discovery
pytest_args.extend([f'--rootdir={project_root}', '-c', '/dev/null'])
subprocess_kwargs['cwd'] = str(project_root)
test_result = _run_fix_operation_test_subprocess(pytest_args, **subprocess_kwargs)
else:
fix_cwd = str(test_cmd.cwd) if test_cmd.cwd is not None else str(pdd_files['test'].parent)
# Use shell command for non-Python
test_result = _run_fix_operation_test_subprocess(
test_cmd.command,
shell=True,
capture_output=True, text=True, timeout=300,
stdin=subprocess.DEVNULL, env=clean_env,
cwd=fix_cwd,
start_new_session=True
)
error_content = f"Test output:\n{test_result.stdout}\n{test_result.stderr}"
if getattr(test_result, "returncode", 0) != 0:
# Capture for core dump / sync step records
test_output_excerpt = _truncate_text(error_content, 5 * 1024)
else:
# No test command available - trigger agentic fallback with context
error_content = f"No test command available for {language}. Please run tests manually and provide error output."
test_output_excerpt = _truncate_text(error_content, 5 * 1024)
except Exception as e:
error_content = f"Test execution error: {e}"
test_output_excerpt = _truncate_text(error_content, 5 * 1024)
error_file_path.write_text(error_content)
# Bug #156 fix: Parse pytest output to find actual failing files
# and pass the correct file to fix_main
failing_files = extract_failing_files_from_output(error_content)
unit_test_file_for_fix = str(pdd_files['test']) # Default to tracked file
if failing_files:
# Try to resolve the failing file paths
test_dir = pdd_files['test'].parent
tracked_file_name = pdd_files['test'].name
# Check if the tracked file is among the failures
tracked_in_failures = any(
Path(ff).name == tracked_file_name for ff in failing_files
)
if not tracked_in_failures:
# Failures are in a different file - use the first failing file
for ff in failing_files:
# Try to resolve the path relative to test directory
ff_path = Path(ff)
if ff_path.is_absolute() and ff_path.exists():
unit_test_file_for_fix = str(ff_path)
break
else:
# Try to find it in the test directory
candidate = test_dir / ff_path.name
if candidate.exists():
unit_test_file_for_fix = str(candidate)
break
# Also try the path as-is relative to cwd
if ff_path.exists():
unit_test_file_for_fix = str(ff_path.resolve())
break
# For non-Python languages (or agentic mode), set max_attempts=0 to skip iterative loop
# and go directly to agentic fallback
effective_max_attempts = 0 if _use_agentic_path(language, agentic_mode) else max_attempts
# Bug #360 fix: output_test must match the actual failing file so the fix
# is written to the correct file, not always the primary test file.
# Without this, fix_main tests/writes the primary file (already fixed)
# while the secondary file retains the failure, causing an infinite loop.
output_test_for_fix = unit_test_file_for_fix
# Bug #360 fix (part 2): Pass ALL test files to fix_main so that
# fix_error_loop runs them together. This detects test isolation
# failures that only manifest when multiple test files interact.
test_files_for_fix = [str(f) for f in pdd_files.get('test_files', [pdd_files['test']])]
# Snapshot pre-operation code so the
# public-surface gate (#1012, P2.A) can
# verify fix_main's rewrite did not
# regress public symbols.
try:
_fix_pre_code = pdd_files['code'].read_text(encoding="utf-8")
except OSError:
_fix_pre_code = ""
_ctx_obj = ctx.obj if ctx and ctx.obj else {}
result = fix_main(
ctx,
prompt_file=str(pdd_files['prompt']),
code_file=str(pdd_files['code']),
unit_test_file=unit_test_file_for_fix,
error_file=str(error_file_path),
output_test=output_test_for_fix,
output_code=str(pdd_files['code']),
output_results=f"{basename.replace('/', '_')}_fix_results.log",
loop=True,
verification_program=str(pdd_files['example']),
max_attempts=effective_max_attempts,
budget=budget - current_cost_ref[0],
auto_submit=(not local),
strength=strength,
temperature=temperature,
test_files=test_files_for_fix,
compress_test_context=bool(_ctx_obj.get("compress_test_context")),
context_compression=_ctx_obj.get("context_compression"),
compression_fallback=_ctx_obj.get("compression_fallback"),
compressed_context=_phase_compressed_context('fix'),
agentic_fallback_events=agentic_fallback_events,
)
_fix_surface_exc = _verify_code_surface_after_write(
code_path=pdd_files['code'],
pre_code=_fix_pre_code,
basename=basename,
language=language,
prompt_path=pdd_files['prompt'],
operation='fix',
)
if _fix_surface_exc is not None:
from .agentic_sync_runner import (
build_public_surface_hard_failure_from_error,
)
hard_block = build_public_surface_hard_failure_from_error(
_fix_surface_exc, basename
)
print(hard_block, file=sys.stderr)
# Charge the failed helper's cost
# (#1012, P3.A).
if isinstance(result, tuple):
current_cost_ref[0] += _extract_cost_from_result(
'fix', result
)
errors.append(
f"fix operation regressed public surface — refusing to continue. "
f"Add a `BREAKING-CHANGE:` directive to the prompt to opt out, "
f"or fix the prompt/code to preserve the public symbols. "
f"Details: {_fix_surface_exc}"
)
skipped_operations.append('fix')
# Terminate the operation loop
# (#1012, P3.A): surface regression
# is a contract violation; let the
# sync exit cleanly rather than
# spin.
break
elif operation == 'update':
result = update_main(ctx, input_prompt_file=str(pdd_files['prompt']), modified_code_file=str(pdd_files['code']), input_code_file=None, output=str(pdd_files['prompt']), use_git=True, strength=strength, temperature=temperature)
else:
errors.append(f"Unknown operation {operation}")
result = {'success': False}
# Result parsing
if isinstance(result, dict):
success = result.get('success', False)
current_cost_ref[0] += result.get('cost', 0.0)
elif isinstance(result, tuple) and len(result) >= 3:
if operation == 'test':
# For agentic test generation (non-Python languages), trust the
# agentic_success flag (4th element) since the agent may create
# test files with different extensions or at different paths.
# Only fall back to file existence check for Python (non-agentic mode).
agentic_success_flag = result.agentic_success if hasattr(result, 'agentic_success') else (result[3] if len(result) >= 4 else None)
if agentic_success_flag is not None:
# Agentic mode was used - trust the agent's success report
success = agentic_success_flag
else:
# Non-agentic mode (Python) - check if file exists
success = pdd_files['test'].exists()
# Issue #1072: Extract error message from TestResult
error_msg = result.error_message if hasattr(result, 'error_message') else (result[4] if len(result) >= 5 else "")
if not success and error_msg:
errors.append(f"Agentic test generation failed: {error_msg}")
else:
success = bool(result[0])
# Issue #1072: Extract error message from crash/fix result[1]
if not success and len(result) >= 2 and result[1]:
errors.append(str(result[1]))
cost = _extract_cost_from_result(operation, result)
current_cost_ref[0] += cost
else:
success = result is not None
except click.Abort:
if operation_rollback is not None:
operation_rollback.restore()
errors.append(f"Operation '{operation}' was cancelled (user declined or non-interactive environment)")
success = False
except Exception as e:
if operation_rollback is not None:
operation_rollback.restore()
# NOTE: TestChurnError no longer prints the structured
# hard-failure block here. Both the generate-op repair
# loop and `_run_test_op_with_churn_retry` already emit
# `=== test churn threshold exceeded ===` before
# re-raising, so printing it again would duplicate the
# diagnostic in stderr.
error_msg = str(e) if str(e) else type(e).__name__
errors.append(f"Exception during '{operation}': {error_msg}")
exc_cost = float(getattr(e, "total_cost", 0.0) or 0.0)
exc_model = getattr(e, "model_name", "") or "unknown"
if exc_cost:
current_cost_ref[0] += exc_cost
result = {
"success": False,
"cost": exc_cost,
"model": exc_model,
}
success = False
# Log update
duration = time.time() - op_start_time
actual_cost = 0.0
model_name = "unknown"
# Issue #1072: Extract cost/model regardless of success/failure
if isinstance(result, dict):
actual_cost = result.get('cost', 0.0)
model_name = result.get('model', 'unknown')
elif isinstance(result, tuple) and len(result) >= 3:
actual_cost = _extract_cost_from_result(operation, result)
model_name = _extract_model_from_result(operation, result)
if success:
last_model_name = str(model_name)
operations_completed.append(operation)
# Don't save the fingerprint for a no-op fix (zero cost, empty/unknown
# model) — the loop may be about to abort this as a logical failure, and
# persisting "fix completed" state before that check is detected would
# leave stale metadata behind.
_model_name_lower_check = str(model_name).strip().lower()
_is_noop_fix = (
operation == 'fix'
and actual_cost == 0.0
and _model_name_lower_check in ['', 'none', 'unknown', 'n/a']
)
if not _is_noop_fix:
_save_fingerprint_atomic(basename, language, operation, pdd_files, actual_cost, str(model_name), atomic_state=atomic_state, include_deps_override=include_deps_override)
if operation_rollback is not None:
operation_rollback.commit()
update_log_entry(
log_entry,
success=success,
cost=actual_cost,
model=model_name,
duration=duration,
error=errors[-1] if errors and not success else None,
compression=_compression_log_metadata(),
agentic_fallback=_agentic_fallback_log_metadata(),
)
if not success:
if test_output_excerpt:
log_entry.setdefault("details", {})["test_output_excerpt"] = test_output_excerpt
# Attach last LLM prompt/response pair (best-effort) for failed operations.
pair = pop_last_pair(operation)
if pair:
log_entry.setdefault("details", {})["llm_trace"] = pair
append_log_entry(basename, language, log_entry, paths=pdd_files)
if operation == 'fix':
model_name_lower = str(model_name).strip().lower()
if actual_cost == 0.0 and model_name_lower in ['', 'none', 'unknown', 'n/a']:
consecutive_noop_fixes += 1
else:
consecutive_noop_fixes = 0
else:
consecutive_noop_fixes = 0
if consecutive_noop_fixes >= 2:
msg = f"Detected {consecutive_noop_fixes} consecutive no-op fix operations. Breaking loop."
errors.append(msg)
record_core_dump_error(
command="sync",
type="LogicalFailure",
message=msg,
details={
"basename": basename,
"language": language,
"reason": "consecutive_noop_fix_limit",
"consecutive": consecutive_noop_fixes,
"operations_completed": operations_completed,
"skipped_operations": skipped_operations,
"total_cost": current_cost_ref[0],
},
)
log_event(basename, language, "cycle_detected", {"cycle_type": "noop-fix", "count": consecutive_noop_fixes}, invocation_mode="sync", paths=pdd_files)
break
# Post-operation checks (simplified)
if success and operation == 'crash':
if _use_agentic_path(language, agentic_mode) and language.lower() != 'python':
# Bug #364 fix: For non-Python languages, trust the agentic result.
# Python needs real coverage measurement (commit 86fe07dc1 missed this).
# Save a successful RunReport so sync_determine_operation advances.
test_hash = (
calculate_sha256(
pdd_files['test'],
trusted_hash_root_for_paths(pdd_files),
)
if pdd_files['test'].exists()
else None
)
report = RunReport(
datetime.datetime.now(datetime.timezone.utc).isoformat(),
exit_code=0,
tests_passed=1,
tests_failed=0,
coverage=0.0,
test_hash=test_hash
)
_save_run_report_atomic(asdict(report), basename, language, atomic_state=atomic_state, paths=pdd_files)
else:
# Re-run example to verify crash fix worked (Python only)
try:
# Use clean env without TUI-specific vars
clean_env = os.environ.copy()
for var in ['FORCE_COLOR', 'COLUMNS']:
clean_env.pop(var, None)
# Bug fix: Use sys.executable to ensure same Python interpreter as
# crash_main (fix_code_loop.py:477). When both venv and conda are
# active, PATH lookup for 'python' may resolve to a different
# interpreter, causing infinite crash loops.
# Bug fix: Do NOT set cwd - inherit from pdd invocation directory
# to match crash_main behavior. Setting cwd to example's parent breaks imports.
example_path = str(pdd_files['example'].resolve())
cmd_parts = [sys.executable, example_path]
# Use error-detection runner that handles server-style examples
returncode, stdout, stderr = _run_example_with_error_detection(
cmd_parts,
env=clean_env,
timeout=60
)
# Include test_hash for staleness detection
test_hash = (
calculate_sha256(
pdd_files['test'],
trusted_hash_root_for_paths(pdd_files),
)
if pdd_files['test'].exists()
else None
)
report = RunReport(datetime.datetime.now(datetime.timezone.utc).isoformat(), returncode, 1 if returncode==0 else 0, 0 if returncode==0 else 1, 100.0 if returncode==0 else 0.0, test_hash=test_hash)
_save_run_report_atomic(asdict(report), basename, language, atomic_state=atomic_state, paths=pdd_files)
except Exception as e:
# Bug #8 fix: Don't silently swallow exceptions - log them and mark as error
error_msg = f"Post-crash verification failed: {e}"
errors.append(error_msg)
log_event(basename, language, "post_crash_verification_failed", {"error": str(e)}, invocation_mode="sync", paths=pdd_files)
if success and operation == 'verify':
if _use_agentic_path(language, agentic_mode) and language.lower() != 'python':
test_hash = (
calculate_sha256(
pdd_files['test'],
trusted_hash_root_for_paths(pdd_files),
)
if pdd_files['test'].exists()
else None
)
report = RunReport(
datetime.datetime.now(datetime.timezone.utc).isoformat(),
exit_code=0,
tests_passed=1,
tests_failed=0,
coverage=0.0,
test_hash=test_hash
)
_save_run_report_atomic(asdict(report), basename, language, atomic_state=atomic_state, paths=pdd_files)
if success and operation == 'fix':
# Re-run tests to update run_report after successful fix
# This prevents infinite loop by updating the state machine
if _use_agentic_path(language, agentic_mode) and language.lower() != 'python':
# Bug #364 fix: For non-Python languages, trust the agentic result.
# The agentic fix handler already verified tests pass.
# Python needs real coverage measurement (commit 86fe07dc1 missed this).
test_hash = (
calculate_sha256(
pdd_files['test'],
trusted_hash_root_for_paths(pdd_files),
)
if pdd_files['test'].exists()
else None
)
report = RunReport(
datetime.datetime.now(datetime.timezone.utc).isoformat(),
exit_code=0,
tests_passed=1,
tests_failed=0,
coverage=0.0,
test_hash=test_hash
)
_save_run_report_atomic(asdict(report), basename, language, atomic_state=atomic_state, paths=pdd_files)
elif pdd_files['test'].exists():
_execute_tests_and_create_run_report(
pdd_files['test'],
basename,
language,
target_coverage,
code_file=pdd_files.get("code"),
atomic_state=atomic_state,
test_files=pdd_files.get('test_files'), # Bug #156
)
if not success:
if operation_rollback is not None:
operation_rollback.restore()
if not errors:
msg = f"Operation '{operation}' failed."
errors.append(msg)
record_core_dump_error(
command="sync",
type="OperationFailed",
message=msg,
details={
"basename": basename,
"language": language,
"operation": operation,
"operations_completed": operations_completed,
"skipped_operations": skipped_operations,
"total_cost": current_cost_ref[0],
},
)
break
except BaseException as e:
if operation_rollback is not None:
operation_rollback.restore()
errors.append(f"An unexpected error occurred in the orchestrator: {type(e).__name__}: {e}")
# Log the full traceback for debugging
import traceback
traceback.print_exc()
finally:
try:
log_event(basename, language, "lock_released", {"pid": os.getpid(), "total_cost": current_cost_ref[0]}, invocation_mode="sync", paths=pdd_files)
except: pass
# Return result dict
if errors:
record_core_dump_error(
command="sync",
type="SyncFailed",
message="Sync terminated with errors (non-exception failure).",
details={
"basename": basename,
"language": language,
"errors": errors,
"operations_completed": operations_completed,
"skipped_operations": skipped_operations,
"total_cost": current_cost_ref[0],
"model_name": last_model_name,
},
)
return {
'success': not errors,
'operations_completed': operations_completed,
'skipped_operations': skipped_operations,
'total_cost': current_cost_ref[0],
'total_time': time.time() - start_time,
'final_state': {
p: {'exists': f.exists(), 'path': str(f)}
for p, f in pdd_files.items()
if p != 'test_files' and isinstance(f, Path)
},
'needs_review': test_output_needs_review,
'errors': errors,
'error': "; ".join(errors) if errors else None,
'summary': _compose_sync_summary(
success=not errors,
operations_completed=operations_completed,
skipped_operations=skipped_operations,
errors=errors,
terminal_reason=terminal_reason,
),
'model_name': last_model_name,
'compression': {
'enabled': compressed_context,
'requested': compressed_context,
'used': any(item.get('used') for item in compression_phase_metadata),
'mode': 'compressed-sync-context',
'phases': compression_phase_metadata,
},
'agentic_fallback': _agentic_fallback_log_metadata(),
}
# Detect headless mode (no TTY, CI environment, or quiet mode)
headless = quiet or not sys.stdout.isatty() or os.environ.get('CI')
if headless:
# Set PDD_FORCE to also skip API key prompts in headless mode
os.environ['PDD_FORCE'] = '1'
# Run worker logic directly without TUI in headless mode
if not quiet:
print(f"Running sync in headless mode (CI/non-TTY environment)...")
result = sync_worker_logic()
# No TUI app, so no worker_exception to check
worker_exception = None
else:
# Instantiate and run Textual App
app = SyncApp(
basename=basename,
budget=budget,
worker_func=sync_worker_logic,
function_name_ref=current_function_name_ref,
cost_ref=current_cost_ref,
prompt_path_ref=prompt_path_ref,
code_path_ref=code_path_ref,
example_path_ref=example_path_ref,
tests_path_ref=tests_path_ref,
prompt_color_ref=prompt_box_color_ref,
code_color_ref=code_box_color_ref,
example_color_ref=example_box_color_ref,
tests_color_ref=tests_box_color_ref,
stop_event=stop_event,
progress_callback_ref=progress_callback_ref
)
# Store app reference so worker can access request_confirmation
app_ref[0] = app
result = app.run()
# Show exit animation if not quiet
from .sync_tui import show_exit_animation
show_exit_animation()
worker_exception = app.worker_exception
# Check for worker exception that might have caused a crash (TUI mode only)
if not headless and worker_exception is not None:
print(f"\n[Error] Worker thread crashed with exception: {worker_exception}", file=sys.stderr)
if hasattr(app, 'captured_logs') and app.captured_logs:
print("\n[Captured Logs (last 20 lines)]", file=sys.stderr)
for line in app.captured_logs[-20:]: # Print last 20 lines
print(f" {line}", file=sys.stderr)
import traceback
# Use trace module to print the stored exception's traceback if available
if hasattr(worker_exception, '__traceback__'):
traceback.print_exception(type(worker_exception), worker_exception, worker_exception.__traceback__, file=sys.stderr)
if result is None:
return {
"success": False,
"total_cost": current_cost_ref[0],
"model_name": "",
"error": "Sync process interrupted or returned no result.",
"summary": "Sync interrupted: app exited without result.",
"operations_completed": [],
"errors": ["App exited without result"]
}
return result
if __name__ == '__main__':
# Example usage
Path("./prompts").mkdir(exist_ok=True)
Path("./src").mkdir(exist_ok=True)
Path("./examples").mkdir(exist_ok=True)
Path("./tests").mkdir(exist_ok=True)
Path("./prompts/my_calculator_python.prompt").write_text("Create a calculator.")
PDD_DIR.mkdir(exist_ok=True)
META_DIR.mkdir(exist_ok=True)
result = sync_orchestration(basename="my_calculator", language="python", quiet=True)
print(json.dumps(result, indent=2))
# pdd/sync_orchestration.py
"""
Orchestrates the complete PDD sync workflow by coordinating operations and
animations in parallel, serving as the core engine for the `pdd sync` command.
"""
import threading
import time
import json
import hashlib
import datetime
import subprocess
import re
import os
from pathlib import Path, PurePosixPath
from typing import Dict, Any, Optional, List, Callable
from dataclasses import asdict, dataclass, field
import tempfile
import sys
import uuid
from .sync_tui import maybe_steer_operation, DEFAULT_STEER_TIMEOUT_S
import click
import logging
logger = logging.getLogger(__name__)
# --- Constants ---
MAX_CONSECUTIVE_TESTS = 3 # Allow up to 3 consecutive test attempts
MAX_TEST_EXTEND_ATTEMPTS = 2 # Allow up to 2 attempts to extend tests for coverage
MAX_CONSECUTIVE_CRASHES = 3 # Allow up to 3 consecutive crash attempts (Bug #157 fix)
MAX_CONSECUTIVE_FIXES = 5 # Allow up to 5 consecutive fix attempts (Issue #1203: only fires when not making progress)
# --- Real PDD Component Imports ---
from .sync_tui import SyncApp
from .operation_log import (
load_operation_log,
create_log_entry,
update_log_entry,
append_log_entry,
log_event,
save_fingerprint,
save_run_report,
clear_run_report,
get_log_path,
get_run_report_path,
get_fingerprint_path,
)
from .sync_determine_operation import (
sync_determine_operation,
get_pdd_file_paths,
AmbiguousModuleError,
RunReport,
SyncDecision,
PDD_DIR,
META_DIR,
SyncLock,
read_run_report,
calculate_sha256,
calculate_current_hashes,
trusted_hash_root_for_paths,
_safe_basename,
is_test_extend_disabled,
)
from .auto_deps_main import auto_deps_main
from .code_generator_main import (
code_generator_main,
PublicSurfaceRegressionError,
TestChurnError,
_verify_public_surface_regression,
)
from .agentic_sync_runner import build_test_churn_hard_failure_from_error
from .context_generator_main import context_generator_main
from .crash_main import crash_main
from .fix_verification_main import fix_verification_main
from .cmd_test_main import cmd_test_main
from .content_selector import PDD_TEST_OUTPUT_NEEDS_REVIEW_MARKER
from .fix_main import fix_main
from .compressed_sync_context import build_compressed_sync_context, metadata as compressed_context_metadata
from .update_main import update_main
from .python_env_detector import detect_host_python_executable
from .get_run_command import get_run_command_for_file
from .pytest_output import extract_failing_files_from_output, _find_project_root
from . import DEFAULT_STRENGTH
from .core.errors import record_core_dump_error
from .core.llm_trace import set_current_operation, pop_last_pair
def _truncate_text(text: str, limit_chars: int) -> str:
if text is None:
return ""
if len(text) <= limit_chars:
return text
return text[:limit_chars] + f"\n... (truncated, {len(text)} total chars)"
def _compose_sync_summary(
*,
success: bool,
Xet Storage Details
- Size:
- 208 kB
- Xet hash:
- 636d52b1bf2bfa59e5e681dc513b3f4b5d04eb6e69bd06898e9132df475a3a23
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.