Buckets:
import fnmatch
import glob
import os
import re
import time
import traceback
from dataclasses import asdict
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import click
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich import print as rprint
# Relative imports from the pdd package
from . import DEFAULT_STRENGTH, DEFAULT_TIME
from .construct_paths import (
_is_known_language,
construct_paths,
_extract_prefix_from_prompts_dir,
_find_pddrc_file,
_get_relative_basename,
_load_pddrc_config,
get_extension
)
from .sync_determine_operation import get_pdd_file_paths, AmbiguousModuleError
from .operation_log import get_run_report_path
from .architecture_include_validation import print_architecture_include_validation_warnings
from .compressed_sync_context import build_compressed_sync_context, metadata as compressed_context_metadata
from .sync_orchestration import sync_orchestration
from .sync_tui import DEFAULT_STEER_TIMEOUT_S
from .template_expander import expand_template
from .core.errors import record_core_dump_error
# Blocklist of characters that are dangerous in shell contexts or malformed as paths.
# Everything else is allowed — frameworks use [], (), +, @, dots, unicode, etc.
DANGEROUS_BASENAME_CHARS = re.compile(r'[;|&$`><!\'"~{}*?#\\%\s\x00-\x1f\x7f]')
# All languages from language_format.csv that produce code|test|example outputs.
# Used for prompt discovery when scanning for available language variants.
SUPPORTED_SYNC_LANGUAGES = [
'python', 'java', 'cpp', 'javascript', 'ruby', 'php', 'swift', 'go',
'rust', 'kotlin', 'typescript', 'typescriptreact', 'csharp', 'shell',
'bash', 'fish', 'zsh', 'powershell', 'perl', 'r', 'matlab', 'lua',
'haskell', 'scala', 'groovy', 'dart', 'fsharp', 'assembly', 'fortran',
'cobol', 'lisp', 'prolog', 'erlang', 'clojure', 'julia', 'elixir',
'pascal', 'vbscript', 'coffeescript', 'objective-c', 'scheme', 'tcl',
'd', 'ada', 'nim', 'ocaml', 'lean', 'agda', 'javascriptreact',
'svelte', 'vue', 'solidity', 'zig', 'mojo', 'verilog', 'systemverilog',
]
def _validate_basename(basename: str) -> None:
"""Raises UsageError if the basename is invalid."""
if not basename:
raise click.UsageError("BASENAME cannot be empty.")
if any(seg in (".", "..") for seg in basename.split("/")):
raise click.UsageError("Path traversal ('..' or '.') is not allowed in BASENAME.")
if basename.startswith("/"):
raise click.UsageError("Absolute paths not allowed in BASENAME.")
if basename.endswith("/") or "//" in basename:
raise click.UsageError("Malformed path in BASENAME.")
match = DANGEROUS_BASENAME_CHARS.search(basename)
if match:
raise click.UsageError(
f"Basename '{basename}' contains dangerous character '{match.group()}'."
)
def _python_first_sorted(lang_to_path: Dict[str, Path]) -> Dict[str, Path]:
"""Return lang-to-path dict with Python first (if present), then sorted alphabetically."""
if 'python' in lang_to_path:
result: Dict[str, Path] = {'python': lang_to_path['python']}
for k in sorted(lang_to_path.keys()):
if k != 'python':
result[k] = lang_to_path[k]
return result
return dict(sorted(lang_to_path.items()))
def _get_extension_safe(language: str) -> str:
"""Get file extension with fallback for when PDD_PATH is not set."""
try:
return get_extension(language)
except (ValueError, FileNotFoundError):
# Fallback to built-in mapping
builtin_ext_map = {
'python': 'py', 'javascript': 'js', 'typescript': 'ts', 'java': 'java',
'typescriptreact': 'tsx', 'javascriptreact': 'jsx',
'cpp': 'cpp', 'c': 'c', 'go': 'go', 'ruby': 'rb', 'rust': 'rs',
}
return builtin_ext_map.get(language.lower(), '')
def _relative_basename_for_context(basename: str, context_config: Dict[str, Any]) -> str:
"""Return basename relative to a context's most specific path or prompt prefix."""
matches = []
for path_pattern in context_config.get('paths', []):
pattern_base = path_pattern.rstrip('/**').rstrip('/*')
if fnmatch.fnmatch(basename, path_pattern) or \
basename.startswith(pattern_base + '/') or \
basename == pattern_base:
relative = _get_relative_basename(basename, path_pattern)
matches.append((len(pattern_base), relative))
defaults = context_config.get('defaults', {})
prompts_dir = defaults.get('prompts_dir', '')
if prompts_dir:
prefix = _extract_prefix_from_prompts_dir(prompts_dir)
if prefix and (basename == prefix or basename.startswith(prefix + '/')):
relative = basename[len(prefix) + 1 :] if basename != prefix else basename.split('/')[-1]
matches.append((len(prefix), relative))
if not matches:
return basename
matches.sort(key=lambda item: item[0], reverse=True)
return matches[0][1]
def _normalize_prompts_root(prompts_dir: Path) -> Path:
"""
Resolve prompts_dir to an absolute path relative to the project root.
This function takes a potentially relative prompts_dir path (e.g., "prompts/backend")
and resolves it to an absolute path using the .pddrc location as the project root.
Note: This function previously stripped subdirectories after "prompts" which was
incorrect for context-specific prompts_dir values. Fixed in Issue #253.
"""
prompts_root = Path(prompts_dir)
pddrc_path = _find_pddrc_file()
if pddrc_path and not prompts_root.is_absolute():
prompts_root = pddrc_path.parent / prompts_root
return prompts_root
def _case_insensitive_prompt_lookup(path: Path) -> Path:
"""Return the actual file path with correct casing, or the original if no match.
Searches the immediate parent directory only. Callers that need recursive
nested-subdirectory resolution use ``_find_prompt_file()`` in
``sync_determine_operation`` (for ``get_pdd_file_paths``) or
``_resolve_prompt_path_from_architecture`` (for architecture.json). Keeping
this helper narrow-scope preserves context isolation for
``_find_prompt_in_contexts``.
"""
if path.exists():
return path
parent = path.parent
if parent.is_dir():
target_lower = path.name.lower()
for candidate in parent.iterdir():
if candidate.is_file() and candidate.name.lower() == target_lower:
return candidate
return path
def _find_prompt_in_contexts(basename: str) -> Optional[Tuple[str, Path, str]]:
"""
Search for a prompt file across all contexts using outputs.prompt.path templates.
This enables finding prompts when the basename alone doesn't match context path patterns.
For example, 'credit_helpers' can find 'prompts/backend/utils/credit_helpers_python.prompt'
if the backend-utils context has outputs.prompt.path configured.
Args:
basename: The base name for the prompt file (e.g., 'credit_helpers')
Returns:
Tuple of (context_name, prompt_path, language) if found, None otherwise
"""
pddrc_path = _find_pddrc_file()
if not pddrc_path:
return None
try:
config = _load_pddrc_config(pddrc_path)
except Exception:
return None
# Resolve paths relative to .pddrc location, not CWD
pddrc_parent = pddrc_path.parent
contexts = config.get('contexts', {})
for context_name, context_config in contexts.items():
if context_name == 'default':
continue
defaults = context_config.get('defaults', {})
outputs = defaults.get('outputs', {})
prompt_config = outputs.get('prompt', {})
prompt_template = prompt_config.get('path')
if not prompt_template:
# No template — try scanning prompts_dir directly (Issue #1165).
prompts_dir_val = defaults.get('prompts_dir', '')
if prompts_dir_val:
resolved_dir = pddrc_parent / prompts_dir_val
if resolved_dir.is_dir():
detected = _detect_languages(basename, resolved_dir)
if detected:
lang, path = next(iter(detected.items()))
return (context_name, path, lang)
continue
context_basename = _relative_basename_for_context(basename, context_config)
parts = context_basename.split('/') if context_basename else ['']
name_part = parts[-1]
category = '/'.join(parts[:-1]) if len(parts) > 1 else ''
dir_prefix = f"{category}/" if category else ''
# Try each language
for lang in SUPPORTED_SYNC_LANGUAGES:
ext = _get_extension_safe(lang)
template_context = {
'name': name_part,
'category': category,
'dir_prefix': dir_prefix,
'ext': ext,
'language': lang,
}
expanded_path = expand_template(prompt_template, template_context)
# Guard: if the template doesn't use {name}, only match if the context
# name matches the basename (i.e., this is the module's own context).
if '{name}' not in prompt_template:
if context_name != basename:
continue
# Resolve relative to .pddrc location, not CWD
prompt_path = pddrc_parent / expanded_path
prompt_path = _case_insensitive_prompt_lookup(prompt_path)
if prompt_path.exists():
return (context_name, prompt_path, lang)
return None
def _extract_prompts_base_dir(prompt_template: str) -> Optional[str]:
"""
Extract the base prompts directory from a template path.
For example:
- "prompts/frontend/{category}/{name}_{language}.prompt" -> "prompts/frontend"
- "prompts/backend/utils/{name}_{language}.prompt" -> "prompts/backend/utils"
- "{name}_{language}.prompt" -> None (no fixed prefix)
"""
# Find the first placeholder
first_placeholder = prompt_template.find('{')
if first_placeholder == -1:
# No placeholders, return parent directory
return str(Path(prompt_template).parent)
if first_placeholder == 0:
# Template starts with placeholder, no fixed prefix
return None
# Get the part before the first placeholder
prefix = prompt_template[:first_placeholder]
# Remove trailing slash if present
prefix = prefix.rstrip('/')
# If prefix ends with a partial path segment, get the parent
if prefix and not prefix.endswith('/'):
# e.g., "prompts/frontend/" -> "prompts/frontend"
return prefix
return prefix if prefix else None
def _detect_languages_with_context(basename: str, prompts_dir: Path, context_name: Optional[str] = None) -> Dict[str, Path]:
"""
Detects all available languages for a given basename, optionally using context config.
If context_name is provided and has outputs.prompt.path configured, uses template-based
discovery. Otherwise falls back to directory scanning.
When context_name is provided but template expansion fails (e.g., missing category),
falls back to recursive glob search in the context's prompts directory.
Returns:
Dict mapping normalized language names to their prompt file paths.
E.g., {'typescriptreact': Path('prompts/frontend/app/sales/page_TypescriptReact.prompt')}
"""
if context_name:
pddrc_path = _find_pddrc_file()
if pddrc_path:
try:
config = _load_pddrc_config(pddrc_path)
# Resolve paths relative to .pddrc location, not CWD
pddrc_parent = pddrc_path.parent
contexts = config.get('contexts', {})
context_config = contexts.get(context_name, {})
defaults = context_config.get('defaults', {})
outputs = defaults.get('outputs', {})
prompt_config = outputs.get('prompt', {})
prompt_template = prompt_config.get('path')
if prompt_template:
context_basename = _relative_basename_for_context(basename, context_config)
parts = context_basename.split('/') if context_basename else ['']
name_part = parts[-1]
category = '/'.join(parts[:-1]) if len(parts) > 1 else ''
dir_prefix = f"{category}/" if category else ''
found_lang_to_path: Dict[str, Path] = {}
# If the template has no {language} placeholder, it's a
# static path — all languages would resolve to the same
# file. Infer the single language from the filename suffix
# instead of iterating (avoids duplicate syncs).
if '{language}' not in prompt_template and '{ext}' not in prompt_template:
full_path = pddrc_parent / prompt_template
if full_path.exists():
stem = full_path.stem # e.g. "action_engine_Python"
lang_suffix = stem.rsplit('_', 1)[-1].lower()
if _is_known_language(lang_suffix):
found_lang_to_path[lang_suffix] = full_path
else:
# Unrecognised suffix — default to python
found_lang_to_path['python'] = full_path
if found_lang_to_path:
return _python_first_sorted(found_lang_to_path)
else:
for lang in SUPPORTED_SYNC_LANGUAGES:
ext = _get_extension_safe(lang)
template_context = {
'name': name_part,
'category': category,
'dir_prefix': dir_prefix,
'ext': ext,
'language': lang,
}
expanded_path = expand_template(prompt_template, template_context)
# Resolve relative to .pddrc location, not CWD
full_path = pddrc_parent / expanded_path
full_path = _case_insensitive_prompt_lookup(full_path)
if full_path.exists():
found_lang_to_path[lang] = full_path
if found_lang_to_path:
return _python_first_sorted(found_lang_to_path)
# Template expansion didn't find files - fallback to recursive glob
# This handles cases where basename alone doesn't provide category info
# e.g., pdd sync --basename page --context frontend
prompts_base_dir = _extract_prompts_base_dir(prompt_template)
if prompts_base_dir:
prompts_base_path = pddrc_parent / prompts_base_dir
if prompts_base_path.is_dir():
# Recursively search for {basename}_*.prompt files
# Escape glob metacharacters in name_part (e.g., [id] -> [[]id])
escaped_name = glob.escape(name_part)
pattern = f"**/{escaped_name}_*.prompt"
for prompt_file in prompts_base_path.glob(pattern):
stem = prompt_file.stem
if stem.startswith(f"{name_part}_"):
potential_language = stem[len(name_part) + 1:]
# Normalize language name (e.g., TypescriptReact -> typescriptreact)
normalized_lang = potential_language.lower()
if normalized_lang not in found_lang_to_path:
try:
if _is_known_language(potential_language):
if potential_language.lower() != 'llm':
found_lang_to_path[normalized_lang] = prompt_file
except ValueError:
# PDD_PATH not set - use common languages
common_languages = {"python", "javascript", "java", "cpp", "c", "go", "rust", "typescript", "typescriptreact", "javascriptreact"}
if normalized_lang in common_languages:
found_lang_to_path[normalized_lang] = prompt_file
if found_lang_to_path:
return _python_first_sorted(found_lang_to_path)
except Exception:
pass
# Fallback to original directory scanning
return _detect_languages(basename, prompts_dir)
def _detect_languages(basename: str, prompts_dir: Path) -> Dict[str, Path]:
"""
Detects all available languages for a given basename by finding
matching prompt files in the prompts directory.
Excludes runtime languages (LLM) as they cannot form valid development units.
Supports subdirectory basenames like 'core/cloud':
- For basename 'core/cloud', searches in prompts/core/ for cloud_*.prompt files
- The stem comparison only uses the filename part ('cloud'), not the path ('core/cloud')
Returns:
Dict mapping language names to their prompt file paths.
E.g., {'python': Path('prompts/my_module_python.prompt')}
"""
lang_to_path: Dict[str, Path] = {}
if not prompts_dir.is_dir():
return {}
# For subdirectory basenames, extract just the name part for stem comparison
if '/' in basename:
name_part = basename.rsplit('/', 1)[1] # 'cloud' from 'core/cloud'
dir_part = basename.rsplit('/', 1)[0] # 'core' from 'core/cloud'
else:
name_part = basename
dir_part = ''
# Determine glob pattern based on whether prompts_dir already includes the subdirectory
# Case 1: prompts_dir='prompts/frontend/types', basename='frontend/types/foo'
# -> prompts_dir already contains dir_part, use just name_part
# Case 2: prompts_dir='prompts', basename='core/cloud'
# -> prompts_dir doesn't contain dir_part, use full basename
# Use path parts comparison to avoid false positives (e.g., 'end' matching 'backend')
dir_parts = Path(dir_part).parts if dir_part else ()
if dir_parts and prompts_dir.parts[-len(dir_parts):] == dir_parts:
# Escape glob metacharacters (e.g., brackets in [id]) so they're treated as literals
pattern = f"{glob.escape(name_part)}_*.prompt"
else:
pattern = f"{glob.escape(basename)}_*.prompt"
# Search root first, then subdirectories if not found (supports prompts
# in context-specific subdirs like prompts/src/services/).
matches = list(prompts_dir.glob(pattern))
if not matches:
# When the basename is directory-prefixed (e.g. ``core/cloud``) we
# mirror the same dir-aware matching the root-level glob uses: if
# ``prompts_dir`` already ends with the prefix, search just for
# ``name_part`` recursively; otherwise require the full
# ``dir_part/name_part`` so we don't false-match unrelated files
# like ``other/cloud_*.prompt`` in sibling subtrees.
if dir_parts and prompts_dir.parts[-len(dir_parts):] != dir_parts:
recursive_pattern = (
f"**/{glob.escape(dir_part)}/{glob.escape(name_part)}_*.prompt"
)
else:
recursive_pattern = f"**/{glob.escape(name_part)}_*.prompt"
recursive_matches = list(prompts_dir.glob(recursive_pattern))
# Collision detection: warn if same basename found in multiple subdirs
if len(recursive_matches) > 1:
dirs = {str(m.parent) for m in recursive_matches}
if len(dirs) > 1:
# Use rich console output (consistent with other CLI warnings
# in this module). ``warnings.warn`` is wrong here because
# Python deduplicates / silences warnings by default and the
# stack-trace formatting is noisy in CLI context.
rprint(
f"[yellow]Warning: Prompt '{name_part}' found in multiple "
f"subdirectories: {sorted(dirs)}. Using first match: "
f"{recursive_matches[0]}[/yellow]"
)
matches = recursive_matches
for prompt_file in matches:
# stem is the filename without extension (e.g., 'cloud_python')
stem = prompt_file.stem
# Ensure the file starts with the exact name part followed by an underscore
if stem.startswith(f"{name_part}_"):
potential_language = stem[len(name_part) + 1 :]
# Normalize language to lowercase for case-insensitive matching
# (e.g., "Python" from "task_model_Python.prompt" -> "python")
normalized_language = potential_language.lower()
try:
if _is_known_language(potential_language):
# Exclude runtime languages (LLM) as they cannot form valid development units
if normalized_language != 'llm':
lang_to_path[normalized_language] = prompt_file
except ValueError:
# PDD_PATH not set (likely during testing) - assume language is valid
# if it matches common language patterns
common_languages = {"python", "javascript", "java", "cpp", "c", "go", "rust", "typescript"}
if normalized_language in common_languages:
lang_to_path[normalized_language] = prompt_file
# Explicitly exclude 'llm' even in test scenarios
return _python_first_sorted(lang_to_path)
def _auto_submit_example(
basename: str,
language: str,
pdd_files: Dict[str, Path],
ctx: click.Context,
) -> None:
"""Submit example to cloud after successful one-session sync."""
import asyncio
import os
import requests
from .core.cloud import CloudConfig, get_cloud_request_timeout
from .get_jwt_token import get_jwt_token
from .preprocess import preprocess
quiet = ctx.obj.get("quiet", False)
if os.environ.get("PDD_FORCE_LOCAL", "").strip().lower() in {"1", "true", "yes", "on"}:
return
# Skip auto-submit inside cloud executors. Interactive Device Flow auth
# cannot complete in a headless Cloud Run / Cloud Functions environment
# and the asyncio JWT call blocks for the full auth timeout (~5 min) before
# giving up — pure overhead that pushes successful syncs past their cap.
if CloudConfig.is_running_in_cloud():
return
# Bound the JWT auth call as a safety net so a wedged Device Flow cannot
# eat the rest of the sync indefinitely. Cache hits and refresh-token
# renewals (the common case) return in well under a second; only an
# honest first-time interactive Device Flow needs minutes for the user
# to visit GitHub and authorise. Defaulting to 5 min keeps interactive
# auth working while still catching truly hung cases. Defensive parse:
# a malformed env value (e.g. `PDD_AUTO_SUBMIT_AUTH_TIMEOUT_S=abc`)
# falls back to the 300s default rather than crashing a successful
# sync via the outer warning path.
try:
auth_timeout_s = float(os.environ.get("PDD_AUTO_SUBMIT_AUTH_TIMEOUT_S", "300"))
except (TypeError, ValueError):
auth_timeout_s = 300.0
try:
# The lower-level async auth helper checks JWT cache before it knows
# which Firebase audience is expected. Infer PDD_ENV from PDD_CLOUD_URL
# first so staging/prod cache validation cannot reuse the wrong token.
CloudConfig.ensure_default_env()
jwt_token = asyncio.run(asyncio.wait_for(
get_jwt_token(
firebase_api_key=os.environ.get("NEXT_PUBLIC_FIREBASE_API_KEY"),
github_client_id=os.environ.get("GITHUB_CLIENT_ID"),
app_name="PDD Code Generator",
),
timeout=auth_timeout_s,
))
except (asyncio.TimeoutError, TimeoutError):
if not quiet:
rprint(
"[yellow]Skipping example submission: auth did not complete "
f"within {auth_timeout_s:.0f}s[/yellow]"
)
return
prompt_content = pdd_files["prompt"].read_text(encoding="utf-8")
processed_prompt = preprocess(prompt_content, recursive=False, double_curly_brackets=True)
code_content = pdd_files["code"].read_text(encoding="utf-8")
payload: Dict[str, Any] = {
"command": "fix",
"searchInput": prompt_content,
"input": {
"prompts": [{"content": processed_prompt, "filename": pdd_files["prompt"].name}],
"code": [{"content": code_content, "filename": pdd_files["code"].name}],
},
"output": {
"code": [{"content": code_content, "filename": pdd_files["code"].name}],
},
"metadata": {
"title": f"Auto-submitted fix for {basename}",
"description": "Automatically submitted successful one-session sync",
"language": language,
"framework": "",
"tags": ["auto-fix", "one-session", "example"],
"isPublic": True,
"price": 0.0,
},
}
# Add example if it exists
if pdd_files["example"].exists():
payload["input"]["example"] = [{
"content": pdd_files["example"].read_text(encoding="utf-8"),
"filename": pdd_files["example"].name,
}]
# Add test if it exists
if pdd_files["test"].exists():
test_content = pdd_files["test"].read_text(encoding="utf-8")
payload["input"]["test"] = [{"content": test_content, "filename": pdd_files["test"].name}]
payload["output"]["test"] = [{"content": test_content, "filename": pdd_files["test"].name}]
headers = {"Authorization": f"Bearer {jwt_token}", "Content-Type": "application/json"}
response = requests.post(
CloudConfig.get_endpoint_url("submitExample"),
json=payload,
headers=headers,
timeout=get_cloud_request_timeout(),
)
if response.status_code == 200:
if not quiet:
rprint("[bold green]Successfully submitted example[/bold green]")
else:
if not quiet:
rprint(f"[bold red]Failed to submit example: {response.text}[/bold red]")
def sync_main(
ctx: click.Context,
basename: str,
max_attempts: Optional[int],
budget: Optional[float],
skip_verify: bool,
skip_tests: bool,
target_coverage: float,
dry_run: bool,
no_steer: bool = False,
steer_timeout: Optional[float] = None,
agentic_mode: bool = False,
one_session: bool = False,
compress: bool = False,
evidence: bool = False,
snapshot_context: bool = False,
compressed_context: bool = False,
fresh: bool = False,
) -> Tuple[Dict[str, Any], float, str]:
"""
CLI wrapper for the sync command. Handles parameter validation, path construction,
language detection, and orchestrates the sync workflow for each detected language.
Args:
ctx: The Click context object.
basename: The base name for the prompt file.
max_attempts: Maximum number of fix attempts. If None, uses .pddrc value or default (3).
budget: Maximum total cost for the sync process. If None, uses .pddrc value or default (20.0).
skip_verify: Skip the functional verification step.
skip_tests: Skip unit test generation and fixing.
target_coverage: Desired code coverage percentage.
dry_run: If True, analyze sync state without executing operations.
Returns:
A tuple containing the results dictionary, total cost, and primary model name.
"""
console = Console()
start_time = time.time()
# Issue #1711: reset the per-(file, query) include-extraction guard counters
# at the shared top-level sync entry point. sync_main() dispatches to either
# sync_orchestration() (which also resets) or, for one_session=True, directly
# to run_one_session_sync() (which does not). Resetting here covers BOTH
# branches so the class-level counters never leak across top-level sync runs
# in a long-lived process (e.g. the server running one-session sync more than
# once), which would otherwise falsely raise RepeatedRetrievalQueryError.
from .include_query_extractor import IncludeQueryExtractor
IncludeQueryExtractor.reset_session()
# 1. Retrieve global parameters from context
strength = ctx.obj.get("strength", DEFAULT_STRENGTH)
temperature = ctx.obj.get("temperature", 0.0)
time_param = ctx.obj.get("time", DEFAULT_TIME)
verbose = ctx.obj.get("verbose", False)
force = ctx.obj.get("force", False)
quiet = ctx.obj.get("quiet", False)
output_cost = ctx.obj.get("output_cost", None)
review_examples = ctx.obj.get("review_examples", False)
local = ctx.obj.get("local", False)
context_override = ctx.obj.get("context", None)
# Default values for max_attempts, budget, target_coverage when not specified via CLI or .pddrc
DEFAULT_MAX_ATTEMPTS = 3
DEFAULT_BUDGET = 20.0
DEFAULT_TARGET_COVERAGE = 90.0
# 2. Validate inputs (basename only - budget/max_attempts validated after config resolution)
_validate_basename(basename)
# Validate CLI-specified values if provided (not None)
# Note: max_attempts=0 is valid (skips LLM loop, goes straight to agentic mode)
if budget is not None and budget <= 0:
raise click.BadParameter("Budget must be a positive number.", param_hint="--budget")
if max_attempts is not None and max_attempts < 0:
raise click.BadParameter("Max attempts must be a non-negative integer.", param_hint="--max-attempts")
# 3. Try template-based prompt discovery first (uses outputs.prompt.path from .pddrc)
template_result = _find_prompt_in_contexts(basename)
discovered_context = None
if template_result:
discovered_context, discovered_prompt_path, first_lang = template_result
prompts_dir_raw = discovered_prompt_path.parent
pddrc_path = _find_pddrc_file()
if pddrc_path and not prompts_dir_raw.is_absolute():
prompts_dir = pddrc_path.parent / prompts_dir_raw
else:
prompts_dir = prompts_dir_raw
# Use context override if not already set
if not context_override:
context_override = discovered_context
if not quiet:
rprint(f"[dim]Found prompt via template in context: {discovered_context}[/dim]")
# 4. Fallback: Use construct_paths in 'discovery' mode to find the prompts directory.
if not template_result:
try:
initial_config, _, _, _ = construct_paths(
input_file_paths={},
force=False,
quiet=True,
command="sync",
command_options={"basename": basename},
context_override=context_override,
)
prompts_dir_raw = initial_config.get("prompts_dir", "prompts")
pddrc_path = _find_pddrc_file()
if pddrc_path and not Path(prompts_dir_raw).is_absolute():
prompts_dir = pddrc_path.parent / prompts_dir_raw
else:
prompts_dir = Path(prompts_dir_raw)
except Exception as e:
rprint(f"[bold red]Error initializing PDD paths:[/bold red] {e}")
raise click.Abort()
# 5. Detect all languages for the given basename
# Use context_override (CLI --context value) instead of discovered_context
# because discovered_context is None when template discovery fails
# Returns Dict[str, Path] mapping language -> prompt file path
lang_to_path = _detect_languages_with_context(basename, prompts_dir, context_name=context_override)
if not lang_to_path:
# Check if this basename has only LLM template files (not syncable).
# Use the same basename/dir_part logic as _detect_languages() to avoid
# false positives from recursive globs matching unrelated subdirectories.
if '/' in basename:
name_part = basename.rsplit('/', 1)[1]
dir_part = basename.rsplit('/', 1)[0]
else:
name_part = basename
dir_part = ''
dir_parts = Path(dir_part).parts if dir_part else ()
if dir_parts and prompts_dir.parts[-len(dir_parts):] == dir_parts:
llm_pattern = f"{glob.escape(name_part)}_[Ll][Ll][Mm].prompt"
else:
llm_pattern = f"{glob.escape(basename)}_[Ll][Ll][Mm].prompt"
llm_files = list(prompts_dir.glob(llm_pattern)) if prompts_dir.is_dir() else []
if llm_files:
if not quiet:
rprint(f"[dim]Skipping '{basename}': only LLM template files found (not syncable)[/dim]")
return {"overall_success": True, "results_by_language": {}, "total_cost": 0.0, "primary_model": ""}, 0.0, ""
raise click.UsageError(
f"No prompt files found for basename '{basename}' in directory '{prompts_dir}'.\n"
f"Expected files with format: '{basename}_<language>.prompt'"
)
# 5. Handle --dry-run mode separately
if dry_run:
if not quiet:
rprint(Panel(f"Displaying sync analysis for [bold cyan]{basename}[/bold cyan]", title="PDD Sync Dry Run", expand=False))
print_architecture_include_validation_warnings(quiet=quiet, verbose=verbose)
for lang, prompt_file_path in lang_to_path.items():
if not quiet:
rprint(f"\n--- Log for language: [bold green]{lang}[/bold green] ---")
# prompt_file_path is now the correct discovered path from lang_to_path
try:
resolved_config, _, _, _ = construct_paths(
input_file_paths={"prompt_file": str(prompt_file_path)},
force=True, # Always use force=True in log mode to avoid prompts
quiet=True,
command="sync",
command_options={"basename": basename, "language": lang},
context_override=context_override,
)
code_dir = resolved_config.get("code_dir", "src")
tests_dir = resolved_config.get("tests_dir", "tests")
examples_dir = resolved_config.get("examples_dir", "examples")
except Exception:
# Fallback to default paths if construct_paths fails
code_dir = str(prompts_dir.parent / "src")
tests_dir = str(prompts_dir.parent / "tests")
examples_dir = str(prompts_dir.parent / "examples")
sync_orchestration(
basename=basename,
language=lang,
prompts_dir=str(prompt_file_path.parent), # Use discovered path's parent
code_dir=str(code_dir),
examples_dir=str(examples_dir),
tests_dir=str(tests_dir),
dry_run=True,
verbose=verbose,
quiet=quiet,
context_override=context_override,
no_steer=no_steer,
steer_timeout=steer_timeout if steer_timeout is not None else DEFAULT_STEER_TIMEOUT_S,
agentic_mode=agentic_mode,
compress=compress,
fresh=fresh,
evidence=evidence,
snapshot_context=snapshot_context,
)
return {}, 0.0, ""
# 6. Main Sync Workflow
# Determine display values for summary panel (use CLI values or defaults for display)
display_budget = budget if budget is not None else DEFAULT_BUDGET
display_max_attempts = max_attempts if max_attempts is not None else DEFAULT_MAX_ATTEMPTS
if not quiet and display_budget < 1.0:
console.log(f"[yellow]Warning:[/] Budget of ${display_budget:.2f} is low. Complex operations may exceed this limit.")
print_architecture_include_validation_warnings(quiet=quiet, verbose=verbose)
if not quiet:
summary_panel = Panel(
f"Basename: [bold cyan]{basename}[/bold cyan]\n"
f"Languages: [bold green]{', '.join(lang_to_path.keys())}[/bold green]\n"
f"Budget: [bold yellow]${display_budget:.2f}[/bold yellow]\n"
f"Max Attempts: [bold blue]{display_max_attempts}[/bold blue]",
title="PDD Sync Starting",
expand=False,
)
rprint(summary_panel)
aggregated_results: Dict[str, Any] = {"results_by_language": {}}
total_cost = 0.0
primary_model = ""
overall_success = True
# remaining_budget will be set from resolved config on first language iteration
remaining_budget: Optional[float] = None
for lang, prompt_file_path in lang_to_path.items():
if not quiet:
rprint(f"\n[bold]🚀 Syncing for language: [green]{lang}[/green]...[/bold]")
# Check budget exhaustion (after first iteration when remaining_budget is set)
if remaining_budget is not None and remaining_budget <= 0:
if not quiet:
rprint(f"[yellow]Budget exhausted. Skipping sync for '{lang}'.[/yellow]")
overall_success = False
aggregated_results["results_by_language"][lang] = {"success": False, "error": "Budget exhausted"}
record_core_dump_error(
command="sync",
type="BudgetExhausted",
message="Budget exhausted. Skipping remaining languages.",
details={
"basename": basename,
"language": lang,
"remaining_budget": remaining_budget,
"total_cost_so_far": total_cost,
},
)
continue
try:
# prompt_file_path is now the correct discovered path from lang_to_path
command_options = {
"basename": basename,
"language": lang,
"target_coverage": target_coverage,
"time": time_param,
}
# Only pass values if explicitly set by user (not CLI defaults)
# This allows .pddrc values to take precedence when user doesn't pass CLI flags
if max_attempts is not None:
command_options["max_attempts"] = max_attempts
if budget is not None:
command_options["budget"] = budget
if strength != DEFAULT_STRENGTH:
command_options["strength"] = strength
if temperature != 0.0: # 0.0 is the CLI default for temperature
command_options["temperature"] = temperature
# Use force=True for path discovery - actual file writes happen in sync_orchestration
# which will handle confirmations via the TUI's confirm_callback
resolved_config, _, _, resolved_language = construct_paths(
input_file_paths={"prompt_file": str(prompt_file_path)},
force=True, # Always force during path discovery
quiet=True,
command="sync",
command_options=command_options,
context_override=context_override,
)
# Extract all parameters directly from the resolved configuration
# Priority: CLI value > .pddrc value > hardcoded default
final_strength = resolved_config.get("strength", strength)
final_temp = resolved_config.get("temperature", temperature)
# For target_coverage, max_attempts and budget: CLI > .pddrc > hardcoded default
# If CLI value is provided (not None), use it. Otherwise, use .pddrc or default.
# Issue #194: target_coverage was not being handled consistently with the others
if target_coverage is not None:
final_target_coverage = target_coverage
else:
final_target_coverage = resolved_config.get("target_coverage") or DEFAULT_TARGET_COVERAGE
if max_attempts is not None:
final_max_attempts = max_attempts
else:
final_max_attempts = resolved_config.get("max_attempts") or DEFAULT_MAX_ATTEMPTS
if budget is not None:
final_budget = budget
else:
final_budget = resolved_config.get("budget") or DEFAULT_BUDGET
# Validate the resolved values
# Note: max_attempts=0 is valid (skips LLM loop, goes straight to agentic mode)
if final_budget <= 0:
raise click.BadParameter("Budget must be a positive number.", param_hint="--budget")
if final_max_attempts < 0:
raise click.BadParameter("Max attempts must be a non-negative integer.", param_hint="--max-attempts")
# Initialize remaining_budget from first resolved config if not set yet
if remaining_budget is None:
remaining_budget = final_budget
# Update ctx.obj with resolved values so sub-commands inherit them
ctx.obj["strength"] = final_strength
ctx.obj["temperature"] = final_temp
code_dir = resolved_config.get("code_dir", "src")
tests_dir = resolved_config.get("tests_dir", "tests")
examples_dir = resolved_config.get("examples_dir", "examples")
if one_session:
if skip_tests or skip_verify:
raise click.UsageError(
"--one-session cannot be combined with --skip-tests or --skip-verify; "
"these flags are not supported in one-session mode."
)
from .one_session_sync import run_one_session_sync
from .sync_determine_operation import (
sync_determine_operation,
)
# Get file paths for this module
pdd_files = get_pdd_file_paths(
basename, resolved_language,
str(prompt_file_path.parent),
context_override=context_override,
)
from .sync_core.finalize import preflight_legacy_mutation
preflight_legacy_mutation(
{"prompt": Path(pdd_files.get("prompt") or Path.cwd())}
)
# Check fingerprint — skip if module is already fully synced
_one_session_skipped = False
if not force:
decision = sync_determine_operation(
basename, resolved_language,
final_target_coverage,
remaining_budget or final_budget,
log_mode=True,
prompts_dir=str(prompt_file_path.parent),
context_override=context_override,
isolated_replay_or_repair=force or bool(os.environ.get("PDD_REPAIR_DIRECTIVE")),
)
if decision.operation == "nothing":
if not quiet:
rprint(
f"[dim]{basename} is already synced (fingerprint unchanged), skipping.[/dim]"
)
sync_result = {
"success": True,
"total_cost": 0.0,
"model_name": "",
"operations_completed": [],
"errors": [],
"summary": (
"No sync operations required; selected target "
"is already synchronized."
),
}
_one_session_skipped = True
if not _one_session_skipped:
# Phase 1: Run pdd generate to create the code file
pre_cost = 0.0
pre_model = ""
_generate_ran = False
compression_phase_metadata: List[Dict[str, Any]] = []
def _one_session_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,
resolved_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 None
if not pdd_files["code"].exists() or force:
from .code_generator_main import (
code_generator_main,
ArchitectureConformanceError,
PublicSurfaceRegressionError,
TestChurnError,
)
from .agentic_sync_runner import (
MAX_CONFORMANCE_ATTEMPTS,
build_conformance_hard_failure_from_error,
build_public_surface_hard_failure_from_error,
build_test_churn_hard_failure_from_error,
)
if not quiet:
rprint("[dim]Running pdd generate...[/dim]")
pdd_files["code"].parent.mkdir(parents=True, exist_ok=True)
# Architecture-conformance repair loop (#866). Retry
# generation when conformance fails, injecting the
# repair directive via PDD_REPAIR_DIRECTIVE so the
# next attempt sees the missing-export instruction.
# The plain `pdd sync <module>` path runs in-process,
# so we mutate os.environ directly and restore it after.
import os as _os
_prev_repair = _os.environ.get("PDD_REPAIR_DIRECTIVE")
# Pop the env var BEFORE attempt 1 (#1012, F-I)
# 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.
_os.environ.pop("PDD_REPAIR_DIRECTIVE", None)
try:
last_exc: Optional[Any] = None
last_signature: Optional[Tuple[str, ...]] = None
last_kind: Optional[str] = None
for _attempt in range(MAX_CONFORMANCE_ATTEMPTS):
try:
gen_result = code_generator_main(
ctx,
prompt_file=str(pdd_files["prompt"].resolve()),
output=str(pdd_files["code"].resolve()),
original_prompt_file_path=None,
# Surgical (edit-shaped) regeneration by
# default for mature modules; --fresh
# (fresh=True) restores full regeneration
# (#1938 Pillar A). code_generator_main
# still falls back to full generation for
# new/empty modules or when the original
# prompt can't be determined.
force_incremental_flag=not fresh,
language=resolved_language,
# output is .pddrc-derived (get_pdd_file_paths uses
# context config), so let front-matter override it.
output_from_config=True,
snapshot_context=snapshot_context,
compressed_context=_one_session_compressed_context(
"generate",
_os.environ.get("PDD_REPAIR_DIRECTIVE"),
),
)
last_exc = None
break
except (
ArchitectureConformanceError,
PublicSurfaceRegressionError,
TestChurnError,
) as exc:
attempt_cost = float(
getattr(exc, "total_cost", 0.0) or 0.0
)
pre_cost += attempt_cost
exc.total_cost = pre_cost
exc_model = getattr(exc, "model_name", "") or ""
if exc_model and exc_model != "unknown":
pre_model = exc_model
if isinstance(exc, PublicSurfaceRegressionError):
new_kind = "public_surface"
new_signature = tuple(
[f"removed:{symbol}" for symbol in sorted(set(exc.removed_symbols))]
+ [
f"signature_changed:{symbol}"
for symbol in sorted(
set(getattr(exc, "changed_signatures", []))
)
]
)
elif isinstance(exc, TestChurnError):
new_kind = "test_churn"
new_signature = (
f"{exc.churn_ratio:.2f}",
str(exc.pre_line_count),
)
else:
new_kind = "architecture"
new_signature = tuple(
sorted(set(exc.missing_symbols))
)
if (
last_signature is not None
and new_signature == last_signature
and new_kind == last_kind
):
# Stuck on identical symbol set — abort.
last_exc = exc
break
last_signature = new_signature
last_kind = new_kind
last_exc = exc
if _attempt + 1 >= MAX_CONFORMANCE_ATTEMPTS:
break
if isinstance(exc, TestChurnError) and _attempt >= 1:
break
if (
remaining_budget is not None
and pre_cost >= remaining_budget
):
break
if not quiet:
if isinstance(exc, PublicSurfaceRegressionError):
failure_label = "Public surface regression"
elif isinstance(exc, TestChurnError):
failure_label = "Test churn threshold exceeded"
else:
failure_label = "Architecture conformance failed"
rprint(
f"[yellow]{failure_label}; "
f"retrying generation with repair directive "
f"(signature: {', '.join(new_signature) or '<none>'}).[/yellow]"
)
_os.environ["PDD_REPAIR_DIRECTIVE"] = exc.repair_directive
if last_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 original click.UsageError.
import sys as _sys
if isinstance(last_exc, PublicSurfaceRegressionError):
hard_block = build_public_surface_hard_failure_from_error(
last_exc, basename
)
elif isinstance(last_exc, TestChurnError):
hard_block = build_test_churn_hard_failure_from_error(
last_exc, basename
)
else:
hard_block = build_conformance_hard_failure_from_error(
last_exc, basename
)
print(hard_block, file=_sys.stderr)
raise last_exc
finally:
if _prev_repair is None:
_os.environ.pop("PDD_REPAIR_DIRECTIVE", None)
else:
_os.environ["PDD_REPAIR_DIRECTIVE"] = _prev_repair
# code_generator_main returns (content, was_incremental, cost, model)
pre_cost += gen_result[2] if gen_result and len(gen_result) > 2 else 0.0
pre_model = gen_result[3] if gen_result and len(gen_result) > 3 else pre_model
_generate_ran = True
elif not quiet:
rprint("[dim]Code file exists, skipping generate.[/dim]")
if not pdd_files["code"].exists():
# Generate failed — don't proceed
sync_result = {
"success": False,
"total_cost": pre_cost,
"model_name": "",
"operations_completed": [],
"errors": ["Code generation failed"],
"summary": "Step generate failed: Code generation failed",
}
else:
# Phase 2: Hand off to one-session agent for example + crash + verify + test
one_session_result = run_one_session_sync(
basename=basename,
language=resolved_language,
pdd_files=pdd_files,
project_root=Path.cwd(),
target_coverage=final_target_coverage,
budget=max(remaining_budget - pre_cost, 0.0),
verbose=verbose,
quiet=quiet,
)
# Merge costs from both phases
one_session_result["total_cost"] = pre_cost + one_session_result.get("total_cost", 0.0)
one_session_result["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,
}
# Surface the pre-generate phase in operations_completed and
# summary so the Details column doesn't under-report when the
# generate phase actually ran in one-session mode.
if _generate_ran and one_session_result.get("success"):
existing_ops = list(one_session_result.get("operations_completed") or [])
if "generate" not in existing_ops:
one_session_result["operations_completed"] = ["generate"] + existing_ops
existing_summary = one_session_result.get("summary") or ""
if "generate" not in existing_summary:
merged_ops = ", ".join(one_session_result["operations_completed"])
one_session_result["summary"] = (
f"One-session sync complete (operations: {merged_ops})"
)
sync_result = one_session_result
# Post-sync: save fingerprint so next sync sees files as up-to-date
if one_session_result.get("success"):
from .operation_log import save_fingerprint
save_fingerprint(
basename, resolved_language, "fix",
pdd_files, one_session_result.get("total_cost", 0.0),
one_session_result.get("model_name", "unknown") or pre_model or "unknown",
)
# Post-sync: auto-submit example to cloud on success
if one_session_result.get("success") and not local:
try:
_auto_submit_example(basename, resolved_language, pdd_files, ctx)
except Exception as e:
if not quiet:
rprint(f"[yellow]Warning: Example submission failed: {e}[/yellow]")
else:
sync_result = sync_orchestration(
basename=basename,
language=resolved_language,
prompts_dir=str(prompt_file_path.parent), # Use discovered path's parent
code_dir=str(code_dir),
examples_dir=str(examples_dir),
tests_dir=str(tests_dir),
budget=remaining_budget,
max_attempts=final_max_attempts,
skip_verify=skip_verify,
skip_tests=skip_tests,
target_coverage=final_target_coverage,
strength=final_strength,
temperature=final_temp,
time_param=time_param,
force=force,
quiet=quiet,
verbose=verbose,
output_cost=output_cost,
review_examples=review_examples,
evidence=evidence,
compress=compress,
fresh=fresh,
local=local,
context_config=resolved_config,
context_override=context_override,
no_steer=no_steer,
steer_timeout=steer_timeout if steer_timeout is not None else DEFAULT_STEER_TIMEOUT_S,
agentic_mode=agentic_mode,
snapshot_context=snapshot_context,
compressed_context=compressed_context,
)
# Post-sync: auto-submit example to cloud on success (multi-step path)
if sync_result.get("success") and not local:
try:
pdd_files = get_pdd_file_paths(
basename, resolved_language,
str(prompt_file_path.parent),
context_override=context_override,
)
_auto_submit_example(basename, resolved_language, pdd_files, ctx)
except Exception as e:
if not quiet:
rprint(f"[yellow]Warning: Example submission failed: {e}[/yellow]")
lang_cost = sync_result.get("total_cost", 0.0)
total_cost += lang_cost
remaining_budget -= lang_cost
if sync_result.get("model_name"):
primary_model = sync_result["model_name"]
if not sync_result.get("success", False):
overall_success = False
aggregated_results["results_by_language"][lang] = sync_result
except AmbiguousModuleError:
# Issue #1677: an ambiguous bare basename is an actionable user error, not
# an "unexpected" per-language failure. Propagate it so the sync command
# surfaces the conflict (and the list of valid path-qualified choices)
# through handle_error, consistent with the dry-run path.
raise
except Exception as e:
if not quiet:
rprint(
f"[bold red]An unexpected error occurred during sync for '{lang}' "
f"({type(e).__name__}):[/bold red] {e}"
)
if verbose:
console.print_exception(show_locals=True)
# Issue #1714 (Bug 2): record a core dump so pdd_cloud can harvest the
# real exception type, stage, and traceback instead of surfacing an
# opaque "An unexpected error occurred during sync". Mirrors the
# budget-exhaustion handler above.
record_core_dump_error(
command="sync",
type=type(e).__name__,
message=str(e),
details={
"basename": basename,
"language": lang,
"stage": "sync_orchestration",
},
traceback_text=traceback.format_exc(),
)
exc_cost = float(getattr(e, "total_cost", 0.0) or 0.0)
exc_model = getattr(e, "model_name", "") or ""
if exc_cost:
total_cost += exc_cost
if remaining_budget is not None:
remaining_budget -= exc_cost
if exc_model and exc_model != "unknown":
primary_model = exc_model
overall_success = False
aggregated_results["results_by_language"][lang] = {
"success": False,
"error": str(e),
"total_cost": exc_cost,
"model_name": exc_model,
}
# 7. Final Summary Report
if not quiet:
elapsed_time = time.time() - start_time
final_table = Table(title="PDD Sync Complete", show_header=True, header_style="bold magenta")
final_table.add_column("Language", style="cyan", no_wrap=True)
final_table.add_column("Status", justify="center")
final_table.add_column("Cost (USD)", justify="right", style="yellow")
final_table.add_column("Details")
for lang, result in aggregated_results["results_by_language"].items():
status = "[green]Success[/green]" if result.get("success") else "[red]Failed[/red]"
cost_str = f"${result.get('total_cost', 0.0):.4f}"
# Prompt forbids "No details." / "None" placeholders in this column
# (sync_main_python.prompt §11). Pick the first truthy candidate
# whose string form is not a forbidden literal, then fall back to a
# status-scoped phrase so the row never carries a placeholder.
forbidden = {"none", "no details.", "no details"}
candidates = (result.get("summary"), result.get("error"))
details = next(
(
str(value)
for value in candidates
if value is not None and str(value).strip()
and str(value).strip().lower() not in forbidden
),
None,
)
if details is None:
details = (
"No sync operations required; selected target is already synchronized."
if result.get("success")
else "Step failed"
)
final_table.add_row(lang, status, cost_str, str(details))
rprint(final_table)
summary_text = (
f"Total time: [bold]{elapsed_time:.2f}s[/bold] | "
f"Total cost: [bold yellow]${total_cost:.4f}[/bold yellow] | "
f"Overall status: {'[green]Success[/green]' if overall_success else '[red]Failed[/red]'}"
)
rprint(Panel(summary_text, expand=False))
aggregated_results["overall_success"] = overall_success
aggregated_results["total_cost"] = total_cost
aggregated_results["primary_model"] = primary_model
language_compression = [
result["compression"]
for result in aggregated_results["results_by_language"].values()
if isinstance(result, dict) and isinstance(result.get("compression"), dict)
]
aggregated_results["compression"] = {
"enabled": compressed_context,
"requested": compressed_context,
"used": any(item.get("used") for item in language_compression),
"mode": "compressed-sync-context",
"languages": language_compression,
}
from .operation_log import aggregate_agentic_fallback_metadata
aggregated_results["agentic_fallback"] = aggregate_agentic_fallback_metadata(
language_results=aggregated_results["results_by_language"].values(),
agentic_sync_mode=agentic_mode,
)
return aggregated_results, total_cost, primary_model
import fnmatch
import glob
import os
import re
import time
import traceback
from dataclasses import asdict
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import click
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich import print as rprint
# Relative imports from the pdd package
from . import DEFAULT_STRENGTH, DEFAULT_TIME
from .construct_paths import (
_is_known_language,
construct_paths,
_extract_prefix_from_prompts_dir,
_find_pddrc_file,
_get_relative_basename,
_load_pddrc_config,
get_extension
)
from .sync_determine_operation import get_pdd_file_paths, AmbiguousModuleError
from .operation_log import get_run_report_path
from .architecture_include_validation import print_architecture_include_validation_warnings
from .compressed_sync_context import build_compressed_sync_context, metadata as compressed_context_metadata
from .sync_orchestration import sync_orchestration
from .sync_tui import DEFAULT_STEER_TIMEOUT_S
from .template_expander import expand_template
from .core.errors import record_core_dump_error
# Blocklist of characters that are dangerous in shell contexts or malformed as paths.
# Everything else is allowed — frameworks use [], (), +, @, dots, unicode, etc.
DANGEROUS_BASENAME_CHARS = re.compile(r'[;|&$`><!\'"~{}*?#\\%\s\x00-\x1f\x7f]')
# All languages from language_format.csv that produce code|test|example outputs.
# Used for prompt discovery when scanning for available language variants.
SUPPORTED_SYNC_LANGUAGES = [
'python', 'java', 'cpp', 'javascript', 'ruby', 'php', 'swift', 'go',
'rust', 'kotlin', 'typescript', 'typescriptreact', 'csharp', 'shell',
'bash', 'fish', 'zsh', 'powershell', 'perl', 'r', 'matlab', 'lua',
'haskell', 'scala', 'groovy', 'dart', 'fsharp', 'assembly', 'fortran',
'cobol', 'lisp', 'prolog', 'erlang', 'clojure', 'julia', 'elixir',
'pascal', 'vbscript', 'coffeescript', 'objective-c', 'scheme', 'tcl',
'd', 'ada', 'nim', 'ocaml', 'lean', 'agda', 'javascriptreact',
'svelte', 'vue', 'solidity', 'zig', 'mojo', 'verilog', 'systemverilog',
]
def _validate_basename(basename: str) -> None:
"""Raises UsageError if the basename is invalid."""
if not basename:
raise click.UsageError("BASENAME cannot be empty.")
if any(seg in (".", "..") for seg in basename.split("/")):
raise click.UsageError("Path traversal ('..' or '.') is not allowed in BASENAME.")
if basename.startswith("/"):
raise click.UsageError("Absolute paths not allowed in BASENAME.")
if basename.endswith("/") or "//" in basename:
raise click.UsageError("Malformed path in BASENAME.")
match = DANGEROUS_BASENAME_CHARS.search(basename)
if match:
raise click.UsageError(
f"Basename '{basename}' contains dangerous character '{match.group()}'."
)
def _python_first_sorted(lang_to_path: Dict[str, Path]) -> Dict[str, Path]:
"""Return lang-to-path dict with Python first (if present), then sorted alphabetically."""
if 'python' in lang_to_path:
result: Dict[str, Path] = {'python': lang_to_path['python']}
for k in sorted(lang_to_path.keys()):
if k != 'python':
result[k] = lang_to_path[k]
return result
return dict(sorted(lang_to_path.items()))
def _get_extension_safe(language: str) -> str:
"""Get file extension with fallback for when PDD_PATH is not set."""
try:
return get_extension(language)
except (ValueError, FileNotFoundError):
# Fallback to built-in mapping
builtin_ext_map = {
'python': 'py', 'javascript': 'js', 'typescript': 'ts', 'java': 'java',
'typescriptreact': 'tsx', 'javascriptreact': 'jsx',
'cpp': 'cpp', 'c': 'c', 'go': 'go', 'ruby': 'rb', 'rust': 'rs',
}
return builtin_ext_map.get(language.lower(), '')
def _relative_basename_for_context(basename: str, context_config: Dict[str, Any]) -> str:
"""Return basename relative to a context's most specific path or prompt prefix."""
matches = []
Xet Storage Details
- Size:
- 70 kB
- Xet hash:
- 02b67195b8d8becbaab7134869f89beaa90c804a21562c8c56c1f9f370a722c6
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.