Buckets:
import logging
import os
import re
import warnings
import base64
import subprocess
from typing import Any, List, Optional, Tuple, Union
import traceback
from pathlib import Path, PurePosixPath
from rich.console import Console
from rich.panel import Panel
from rich.markup import escape
from rich.traceback import install
from .firecrawl_cache import get_firecrawl_cache
from pdd.path_resolution import get_default_resolver
from pdd.sync_core.includes import include_paths
install()
console = Console()
logger = logging.getLogger(__name__)
# Maximum iterations for the non-recursive convergence loop.
# Diamond includes converge quickly; true cycles never converge.
_MAX_INCLUDE_ITERATIONS = 50
_DEBUG_EVENTS: List[str] = []
def _is_debug() -> bool:
return str(os.getenv("PDD_PREPROCESS_DEBUG", "")).lower() in ("1", "true", "yes", "on")
def _is_quiet_mode() -> bool:
return os.getenv("PDD_QUIET") == "1"
def _is_context_audit_no_query_fallback() -> bool:
"""Return True when context audit must defer semantic query fallbacks."""
return os.getenv("PDD_CONTEXT_AUDIT_NO_QUERY_FALLBACK") == "1"
def _warn_selector_fallback(
file_path: str,
mode: str,
error: Exception,
*,
selectors: str | None = None,
) -> None:
"""Emit a UserWarning when compression/selector fails and full content is used."""
selector_detail = f" for select={selectors}" if selectors else ""
if isinstance(error, ImportError):
message = (
f"ContentSelector not importable{selector_detail} in {file_path}: {error}. "
"Falling back to full content."
)
else:
message = (
f"ContentSelector failed{selector_detail} in {file_path} (mode={mode}): {error}. "
"Falling back to full content."
)
warnings.warn(message, UserWarning, stacklevel=4)
from pdd.compression_reporting import record_compression_fallback
record_compression_fallback(message)
if not _is_quiet_mode():
console.print(f"[yellow]Warning: {message}[/yellow]")
def _query_fallback_extract(full_path, fallback_query, snapshot_recorder):
"""Shared ``select=`` → ``query=`` fallback extraction (Issue #1711).
Used by all three selector-failure routes in ``process_include_tags``
(ImportError, SelectorError, and the generic selector/compression failure).
Returns the extracted content on success, or ``None`` when there is no
``query=`` to fall back to or the extraction failed for a non-guard reason
(recorded as a ``[query_include failed: ...]`` placeholder in the snapshot).
``RepeatedRetrievalQueryError`` — the per-``(file, query)`` session guard — is
intentionally NOT caught here: it propagates so a stuck retrieval loop fails
fast instead of silently continuing on degraded include content. Centralizing
the re-raise in a single helper (rather than copying ``except
RepeatedRetrievalQueryError: raise`` into each branch) stops a future edit
from re-introducing the swallow on one of the fallback paths.
"""
if not fallback_query:
return None
from pdd.include_query_extractor import (
IncludeQueryExtractor,
RepeatedRetrievalQueryError,
)
try:
extracted = IncludeQueryExtractor().extract(
file_path=full_path, query=fallback_query
)
except RepeatedRetrievalQueryError:
raise
except Exception as inner_e:
if snapshot_recorder is not None:
placeholder = f"[query_include failed: {inner_e}]"
snapshot_recorder.record_include(
source_path=full_path,
content=placeholder,
query=fallback_query,
output=placeholder,
)
return None
if snapshot_recorder is not None:
snapshot_recorder.record_include(
source_path=full_path,
content=extracted,
query=fallback_query,
output=extracted,
)
return extracted
def _dbg(msg: str) -> None:
if _is_debug():
console.print(f"[dim][PPD][preprocess][/dim] {escape(msg)}")
_DEBUG_EVENTS.append(msg)
def _write_debug_report() -> None:
if _is_debug():
output_file = os.getenv("PDD_PREPROCESS_DEBUG_FILE")
if output_file:
try:
with open(output_file, "w", encoding="utf-8") as fh:
fh.write("Preprocess Debug Report\n\n")
for line in _DEBUG_EVENTS:
fh.write(line + "\n")
console.print(f"[green]Debug report written to:[/green] {output_file}")
except Exception as e:
# Report the error so users know why the log file wasn't written
console.print(f"[yellow]Warning: Could not write debug report to {output_file}: {e}[/yellow]")
else:
console.print("[dim]Debug mode enabled but PDD_PREPROCESS_DEBUG_FILE not set (output shown in console only)[/dim]")
def _looks_like_user_intent_path(path: str) -> bool:
"""Heuristic: distinguish a real include path from a parser false positive.
`<include>` / `<include-many>` / backtick-include regexes can match literal
tag syntax that appears inside an already-included source file's docstrings,
regex strings, or comments (e.g. `pdd/preprocess.py` is itself routinely
included by prompts and contains literal `<include>...</include>` examples).
Production callers do a two-pass preprocess(recursive=True) → expand vars →
preprocess(recursive=False), and the literal tags from the first pass's
expanded source then look like first-iteration matches in the second pass —
so the iteration gate alone cannot suppress them.
A real user-intent include path:
* is non-empty after stripping whitespace
* fits on a single line (no embedded newlines)
* is reasonably short (≤ 256 chars; real paths rarely exceed this)
* doesn't start with comment or tag punctuation (`#`, `//`, `/*`, `*`, `<`)
* contains at least one path-y character — `/`, `\\`, `.`, or `$` (for
`${VAR}` placeholders). Bare-word strings like "path" — common in
docstring examples — get filtered out.
Returning False here suppresses the FileNotFound console warning, the
`_failed` tracking, and the trailing unresolved-include warning for the
given path. Anything legitimately resembling a path still passes through.
"""
if not path:
return False
if "\n" in path:
return False
if len(path) > 256:
return False
stripped = path.strip()
if not stripped:
return False
if stripped.startswith(("#", "//", "/*", "*", "<")):
return False
if not any(c in stripped for c in "/\\.$"):
return False
# Real include paths don't contain whitespace inside the path itself.
# Natural-language fragments like "in a docstring)." or "set from the
# original prompt" pass the punctuation check above (because of the `.`)
# but are clearly parser-artifact prose, not paths.
if any(c.isspace() for c in stripped):
return False
return True
def _extract_fence_spans(text: str) -> List[Tuple[int, int]]:
"""Return list of (start, end) spans for fenced code blocks (``` or ~~~).
The spans are [start, end) indices in the original text.
"""
spans: List[Tuple[int, int]] = []
try:
fence_re = re.compile(
r"(?m)^[ \t]*([`~]{3,})[^\n]*\n[\s\S]*?\n[ \t]*\1[ \t]*(?:\n|$)"
)
for m in fence_re.finditer(text):
spans.append((m.start(), m.end()))
except Exception:
pass
return spans
def _extract_inline_code_spans(text: str) -> List[Tuple[int, int]]:
"""Return list of (start, end) spans for inline code (backticks)."""
spans: List[Tuple[int, int]] = []
try:
for m in re.finditer(r"(?<!`)(`++)([^\n]*?)\1", text):
spans.append((m.start(), m.end()))
except Exception:
pass
return spans
def _extract_code_spans(text: str) -> List[Tuple[int, int]]:
"""Markdown literal spans, shared with canonical dependency discovery.
Expansion and ``pdd.sync_core.includes`` must classify a directive the
same way. Keeping a second scanner here meant a fence closed by a longer
delimiter run expanded a literal, and an invalid mixed-delimiter fence
suppressed a real include, while the dependency graph disagreed on both.
"""
from .sync_core.includes import markdown_literal_spans
return markdown_literal_spans(text)
def _is_inside_any_span(idx: int, spans: List[Tuple[int, int]]) -> bool:
for s, e in spans:
if s <= idx < e:
return True
return False
def _intersects_any_span(start: int, end: int, spans: List[Tuple[int, int]]) -> bool:
for s, e in spans:
if start < e and end > s:
return True
return False
def _scan_risky_placeholders(text: str) -> Tuple[List[Tuple[int, str]], List[Tuple[int, str]]]:
"""Scan for risky placeholders outside code fences.
Returns two lists of (line_no, snippet):
- single_brace: matches like {name} not doubled and not part of {{...}}
- template_brace: `${...}` occurrences (which include single { ... })
"""
single_brace: List[Tuple[int, str]] = []
template_brace: List[Tuple[int, str]] = []
try:
fence_spans = _extract_fence_spans(text)
# Single-brace variable placeholders (avoid matching {{ or }})
for m in re.finditer(r"(?<!\{)\{([A-Za-z_][A-Za-z0-9_]*)\}(?!\})", text):
if not _is_inside_any_span(m.start(), fence_spans):
line_no = text.count("\n", 0, m.start()) + 1
single_brace.append((line_no, m.group(0)))
# JavaScript template placeholders like ${...}
for m in re.finditer(r"\$\{[^\}]++\}", text):
if not _is_inside_any_span(m.start(), fence_spans):
line_no = text.count("\n", 0, m.start()) + 1
template_brace.append((line_no, m.group(0)))
except Exception:
pass
return single_brace, template_brace
def compute_user_intent_paths(text: str) -> set:
"""Extract the set of paths that appear inside `<include>`, `<include-many>`,
and `\\`\\`\\`<...>\\`\\`\\`` tags in the given text.
Recognises every grammar `process_include_tags` accepts:
* body form: `<include>path</include>`
* `path=` attribute on body form: `<include path="path">...</include>`
* self-closing form: `<include path="path" />`
plus `<include-many>...</include-many>` (comma/newline-separated paths) and
backtick includes (`\\`\\`\\`<path>\\`\\`\\``).
Production callers run preprocess in two passes (recursive=True, then
`_expand_vars`, then recursive=False). Pass 2's input contains content from
pass 1's expansions, including any literal `<include>...</include>` syntax
that was inside an expanded `.py` source's docstrings or regex strings.
Pass 2 cannot, on its own, distinguish those parser artifacts from real
user-intent includes that appear textually identical.
The fix: callers pre-compute this set from the ORIGINAL prompt (before
any expansion) and pass it to pass 2 via the `_user_intent_paths`
parameter on `preprocess()`. Pass 2 only emits warnings for paths in the
set, suppressing the false positives.
To accommodate `<include>${VAR}</include>` includes whose paths only
materialize after `_expand_vars`, callers should union the result of
`compute_user_intent_paths(original_prompt)` with the result of
`compute_user_intent_paths(_expand_vars(original_prompt, env_vars))`.
"""
return include_paths(text)
def preprocess(
prompt: Union[str, Any],
recursive: bool = False,
double_curly_brackets: bool = True,
exclude_keys: Optional[List[str]] = None,
compress: bool = False,
examples_dir: str = "examples/",
tests_dir: str = "tests/",
_seen: Optional[set] = None,
_failed: Optional[List[str]] = None,
_user_intent_paths: Optional[set] = None,
snapshot_recorder: Optional[Any] = None,
exclude: Optional[List[str]] = None,
) -> str:
if exclude_keys is None:
exclude_keys = exclude
try:
# Some tests patch template loading to return mock objects with .format().
# In that case preprocessing is not applicable; return as string.
if not isinstance(prompt, str):
return str(prompt)
if not prompt:
console.print("[bold red]Error:[/bold red] Empty prompt provided")
return ""
if _seen is None:
_seen = set()
# Track include paths that the include processors actually failed to expand,
# so the unresolved-include warning fires only for real failures — not for
# `[File not found: ...]` text that appears in documentation or spec content.
if _failed is None:
_failed = []
_DEBUG_EVENTS.clear()
_dbg(
f"Start preprocess(recursive={recursive}, double_curly={double_curly_brackets}, "
f"exclude_keys={exclude_keys}, compress={compress}, examples_dir={examples_dir}, tests_dir={tests_dir})"
)
_dbg(f"Initial length: {len(prompt)} characters")
if not _is_quiet_mode():
console.print(Panel("Starting prompt preprocessing", style="bold blue"))
prompt = process_backtick_includes(
prompt,
recursive,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
_seen=_seen,
_failed=_failed,
_user_intent_paths=_user_intent_paths,
snapshot_recorder=snapshot_recorder,
)
_dbg("After backtick includes processed")
prompt = process_xml_tags(
prompt,
recursive,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
_seen=_seen,
_failed=_failed,
_user_intent_paths=_user_intent_paths,
snapshot_recorder=snapshot_recorder,
)
_dbg("After XML-like tags processed")
if double_curly_brackets:
prompt = double_curly(prompt, exclude_keys)
_dbg("After double_curly execution")
# Scan for risky placeholders remaining outside code fences
singles, templates = _scan_risky_placeholders(prompt)
if singles:
_dbg(f"WARNING: Found {len(singles)} single-brace placeholders outside code fences (examples):")
for ln, frag in singles[:5]:
_dbg(f" line {ln}: {frag}")
if templates:
_dbg(f"INFO: Found {len(templates)} template literals ${{...}} outside code fences (examples):")
for ln, frag in templates[:5]:
_dbg(f" line {ln}: {frag}")
# Surface include paths that the processors actually failed to expand,
# so missing dependency context is a visible signal, not silent corruption
# (#616). Tracking direct failures (not regex-scanning the final prompt)
# avoids false positives on documentation/spec text that mentions the
# `[File not found: ...]` marker as an example. Skipped on recursive passes.
if not recursive:
seen_in_warning: set[str] = set()
for unresolved in _failed:
unresolved = unresolved.strip()
if not unresolved or unresolved in seen_in_warning:
continue
# Defensive filter: only re-apply the path-shape heuristic when
# the caller didn't supply `_user_intent_paths`. With an
# authoritative set, anything that reached `_failed` already
# passed the user-intent gate, so re-filtering here would
# spuriously suppress legitimate extensionless paths
# (Makefile, Dockerfile, LICENSE).
if _user_intent_paths is None and not _looks_like_user_intent_path(unresolved):
continue
seen_in_warning.add(unresolved)
msg = (
f"Unresolved include in preprocessed prompt: {unresolved}. "
"Generated code may be missing dependency context. Check that "
"example_output_path in .pddrc matches where example files are "
"written (default: 'examples/')."
)
# If the file exists at the context↔examples swap location, name it.
try:
_parts = Path(unresolved).parts
if _parts and _parts[0] in ("context", "examples"):
_alt_root = "examples" if _parts[0] == "context" else "context"
_alt_path = Path(_alt_root, *_parts[1:])
if _alt_path.exists():
msg += f" Found at: {_alt_path}."
except Exception:
pass
logger.warning(msg)
if not _is_quiet_mode():
console.print(f"[bold yellow]Warning:[/bold yellow] {msg}")
_dbg(f"WARNING: {msg}")
# Don't trim whitespace that might be significant for the tests
if not _is_quiet_mode():
console.print(Panel("Preprocessing complete", style="bold green"))
_dbg(f"Final length: {len(prompt)} characters")
_write_debug_report()
return prompt
except (RecursionError, ValueError) as e:
if "Circular include" in str(e) or isinstance(e, RecursionError):
raise
raise
except Exception as e:
from pdd.compression_reporting import CompressionFallbackError
if isinstance(e, CompressionFallbackError):
raise
# Issue #1711: a stuck retrieval loop must fail fast with the guard's
# actionable message. The best-effort "return the partial prompt" path
# below would otherwise swallow it and let sync continue on degraded
# include content — defeating the guard.
from pdd.include_query_extractor import RepeatedRetrievalQueryError
if isinstance(e, RepeatedRetrievalQueryError):
raise
console.print(f"[bold red]Error during preprocessing:[/bold red] {str(e)}")
console.print(Panel(traceback.format_exc(), title="Error Details", style="red"))
_dbg(f"Exception: {str(e)}")
_write_debug_report()
# Best-effort behavior: return the (partially) processed prompt instead of raising,
# so the CLI and callers can continue with whatever was produced before the error.
return prompt
def get_file_path(file_name: str) -> str:
resolver = get_default_resolver()
relpath = Path(file_name)
if relpath.is_absolute():
return str(relpath)
normalized = PurePosixPath(os.path.normpath(file_name).replace(os.sep, "/"))
resolved = resolver.resolve_include(normalized.as_posix())
cwd_candidate = resolver.cwd / normalized
if resolved == cwd_candidate:
return os.path.join("./", normalized.as_posix())
try:
resolved.relative_to(resolver.cwd)
except ValueError:
pass
else:
# A nested source checkout must not shadow a missing active-project file.
return os.path.join("./", normalized.as_posix())
return str(resolved)
def _compressed_include_with_fallback_or_raw(
raw_content: str,
file_path: str,
*,
selectors: Optional[List[str]] = None,
expand_dependencies: bool = False,
) -> str:
"""Apply compressed include transform; return raw content when compression fails."""
try:
from pdd.content_selector import apply_compressed_include_with_fallback
return apply_compressed_include_with_fallback(
raw_content,
file_path=file_path,
selectors=selectors,
expand_dependencies=expand_dependencies,
)
except Exception as exc:
_warn_selector_fallback(file_path, "compressed", exc, selectors=",".join(selectors or []) or None)
return raw_content
def _process_nested_includes(
content: str,
_seen: set,
_failed: Optional[List[str]],
_user_intent_paths: Optional[set],
compress: bool = False,
examples_dir: str = "examples/",
tests_dir: str = "tests/",
snapshot_recorder: Optional[Any] = None,
) -> str:
"""Resolve include syntax from included content while preserving the include stack."""
nested_user_intent_paths = _user_intent_paths if _user_intent_paths is not None else set()
content = process_backtick_includes(
content,
recursive=False,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
_seen=_seen,
_failed=_failed,
_user_intent_paths=nested_user_intent_paths,
snapshot_recorder=snapshot_recorder,
)
content = process_include_tags(
content,
recursive=False,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
_seen=_seen,
_failed=_failed,
_user_intent_paths=nested_user_intent_paths,
snapshot_recorder=snapshot_recorder,
)
content = process_include_many_tags(
content,
recursive=False,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
_seen=_seen,
_failed=_failed,
_user_intent_paths=nested_user_intent_paths,
snapshot_recorder=snapshot_recorder,
)
return content
def process_backtick_includes(
text: str,
recursive: bool,
compress: bool = False,
examples_dir: str = "examples/",
tests_dir: str = "tests/",
_seen: Optional[set] = None,
_failed: Optional[List[str]] = None,
_user_intent_paths: Optional[set] = None,
snapshot_recorder: Optional[Any] = None,
) -> str:
if _seen is None:
_seen = set()
# More specific pattern that doesn't match nested > characters
pattern = r"```<([^>]*+)>```"
def replace_include(match):
file_path = match.group(1).strip()
try:
full_path = get_file_path(file_path)
resolved = os.path.realpath(full_path)
if resolved in _seen:
raise ValueError(f"Circular include detected: {file_path} is already in the include chain")
console.print(f"Processing backtick include: [cyan]{full_path}[/cyan]")
with open(full_path, 'r', encoding='utf-8') as file:
content = file.read()
child_seen = _seen | {resolved}
if recursive:
content = preprocess(
content,
recursive=True,
double_curly_brackets=False,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
_seen=child_seen,
_failed=_failed,
_user_intent_paths=_user_intent_paths,
snapshot_recorder=snapshot_recorder,
)
else:
content = _process_nested_includes(
content,
_seen=child_seen,
_failed=_failed,
_user_intent_paths=_user_intent_paths,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
snapshot_recorder=snapshot_recorder,
)
if snapshot_recorder is not None:
snapshot_recorder.record_include(
source_path=full_path,
content=content,
include_depth=len(_seen),
)
_dbg(f"Included via backticks: {file_path} (len={len(content)})")
return f"```{content}```"
except FileNotFoundError:
_dbg(f"Missing backtick include: {file_path}")
# First pass (recursive=True): leave the tag so a later env expansion can resolve it
if recursive:
return match.group(0)
# iterations > 0 means the match originated from content expanded earlier;
# don't warn or track those (parser false positives from included source).
if iterations > 0:
return match.group(0)
# Two-pass flow: when caller supplied `_user_intent_paths`, gate
# authoritatively on that set; otherwise fall back to the path-shape
# heuristic to filter parser artifacts in single-pass mode. (See
# the matching comment in `process_include_tags.replace_include`
# for the rationale on extensionless filenames.)
if _user_intent_paths is not None:
if file_path not in _user_intent_paths:
return match.group(0)
else:
if not _looks_like_user_intent_path(file_path):
return match.group(0)
if not _is_quiet_mode():
console.print(f"[bold red]Warning:[/bold red] File not found: {file_path}")
if _failed is not None:
_failed.append(file_path)
return f"```[File not found: {file_path}]```"
except ValueError as e:
if "Circular include" in str(e):
raise
console.print(f"[bold red]Error processing include:[/bold red] {str(e)}")
_dbg(f"Error processing backtick include {file_path}: {e}")
if recursive:
return match.group(0)
return f"```[Error processing include: {file_path}]```"
except OSError as e:
_dbg(f"OSError processing backtick include {file_path}: {e}")
return match.group(0)
except Exception as e:
console.print(f"[bold red]Error processing include:[/bold red] {str(e)}")
_dbg(f"Error processing backtick include {file_path}: {e}")
if recursive:
return match.group(0)
return f"```[Error processing include: {file_path}]```"
prev_text = ""
current_text = text
iterations = 0
while prev_text != current_text:
if iterations >= _MAX_INCLUDE_ITERATIONS:
raise ValueError("Circular include detected: maximum include depth exceeded")
prev_text = current_text
current_text = re.sub(pattern, replace_include, current_text, flags=re.DOTALL)
iterations += 1
return current_text
def process_xml_tags(
text: str,
recursive: bool,
compress: bool = False,
examples_dir: str = "examples/",
tests_dir: str = "tests/",
_seen: Optional[set] = None,
_failed: Optional[List[str]] = None,
_user_intent_paths: Optional[set] = None,
snapshot_recorder: Optional[Any] = None,
) -> str:
if _seen is None:
_seen = set()
# If the caller supplied an explicit user-intent set, use it directly
# (covers the production two-pass flow where pass 2 sees expanded source).
# Otherwise snapshot the user-intent <include-many> paths from the input
# text so a literal `<include-many>...</include-many>` string inside an
# expanded `<include>`'s content can't be treated as user intent on the
# subsequent process_include_many_tags pass.
if _user_intent_paths is not None:
user_intent_many_paths: Optional[set] = _user_intent_paths
elif _failed is not None:
user_intent_many_paths = set()
for m in re.finditer(r'<include-many(?:\s[^>]*+)?>(.*?)</include-many>', text, flags=re.DOTALL):
inner = m.group(1)
for raw in [s.strip() for part in inner.splitlines() for s in part.split(',')]:
if raw:
user_intent_many_paths.add(raw)
else:
user_intent_many_paths = None
text = process_pdd_tags(text)
text = process_include_tags(
text,
recursive,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
_seen=_seen,
_failed=_failed,
_user_intent_paths=_user_intent_paths,
snapshot_recorder=snapshot_recorder,
)
text = process_include_many_tags(
text,
recursive,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
_seen=_seen,
_failed=_failed,
_user_intent_paths=user_intent_many_paths,
snapshot_recorder=snapshot_recorder,
)
text = process_shell_tags(text, recursive, snapshot_recorder=snapshot_recorder)
text = process_web_tags(text, recursive, snapshot_recorder=snapshot_recorder)
return text
def _parse_attrs(attr_str: str) -> dict:
if not attr_str:
return {}
attrs = {}
# Simple attribute parser: key="value" or key='value'
for match in re.finditer(r'(\w+)\s*=\s*["\']([^"\']*)["\']', attr_str):
attrs[match.group(1)] = match.group(2)
# Boolean attributes (e.g., <include optional>path</include>)
# This keeps the include tag syntax ergonomic without requiring key="true".
if "optional" not in attrs and re.search(r'(?<![A-Za-z0-9_])optional(?![A-Za-z0-9_])', attr_str):
attrs["optional"] = "true"
if "expand" not in attrs and re.search(r'(?<![A-Za-z0-9_])expand(?![A-Za-z0-9_])', attr_str):
attrs["expand"] = "true"
return attrs
def _include_expand_dependencies(attrs: dict) -> bool:
"""Return True when an include tag requests dependency expansion."""
expand_val = attrs.get("expand")
if expand_val is None:
return False
return str(expand_val).strip().lower() not in {"", "0", "false", "no", "off"}
def process_include_tags(
text: str,
recursive: bool,
compress: bool = False,
examples_dir: str = "examples/",
tests_dir: str = "tests/",
_seen: Optional[set] = None,
_failed: Optional[List[str]] = None,
_user_intent_paths: Optional[set] = None,
snapshot_recorder: Optional[Any] = None,
) -> str:
if _seen is None:
_seen = set()
# Support both <include>path</include> and <include path="path" attrs... />
pattern = r'<include(?P<attrs>\s[^>]*+)?>(?P<content>.*?)</include>|<include(?P<attrs_self>\s[^>]*?)/>'
def replace_include(match):
attrs_str = match.group('attrs') or match.group('attrs_self') or ""
attrs = _parse_attrs(attrs_str)
# Content between tags (used as path for bare <include>path</include>)
content = match.group('content') if match.group('content') is not None else ""
file_path = attrs.get('path') or content.strip()
if not file_path:
return match.group(0)
file_path = file_path.strip()
# Handle query attribute — semantic LLM extraction
# When both select= and query= are present, prefer select= (deterministic)
# and only fall back to query= if select fails.
query = attrs.get('query')
selectors_str = attrs.get('select')
if query and selectors_str:
_dbg(f"Both select= and query= on <include> for {file_path}; preferring select=")
query = None # Will be used as fallback below if select fails
if query:
if recursive:
return match.group(0)
try:
from pdd.include_query_extractor import (
IncludeQueryExtractor,
RepeatedRetrievalQueryError,
)
except ImportError:
console.print("[yellow]Warning: pdd.include_query_extractor not found. Cannot perform semantic query.[/yellow]")
error_msg = f"[Error: pdd.include_query_extractor not found. Cannot query from {file_path}]"
if snapshot_recorder is not None:
snapshot_recorder.record_include(
source_path=file_path,
content=error_msg,
query=query,
output=error_msg,
)
return error_msg
try:
resolved_path = get_file_path(file_path)
extractor = IncludeQueryExtractor()
extracted = extractor.extract(file_path=resolved_path, query=query)
if snapshot_recorder is not None:
snapshot_recorder.record_include(
source_path=resolved_path,
content=extracted,
query=query,
output=extracted,
)
return extracted
except RepeatedRetrievalQueryError:
# Issue #1711: a stuck retrieval loop must fail fast with the
# guard's actionable message. Swallowing it into a placeholder
# (as the broad handler below does) would let sync silently
# continue on degraded include content instead of stopping.
raise
except Exception as e:
console.print(f"[bold red]Error in semantic query:[/bold red] {e}")
error_msg = f"[Error in semantic query from {file_path}: {e}]"
if snapshot_recorder is not None:
snapshot_recorder.record_include(
source_path=resolved_path,
content=error_msg,
query=query,
output=error_msg,
)
return error_msg
try:
full_path = get_file_path(file_path)
resolved = os.path.realpath(full_path)
if resolved in _seen:
raise ValueError(f"Circular include detected: {file_path} is already in the include chain")
# Automatic mode detection based on context compression settings
mode = attrs.get('mode', 'full')
if mode == "full":
compression = (os.environ.get("PDD_CONTEXT_COMPRESSION") or "").lower()
modes = [m.strip() for m in compression.split(",") if m.strip()]
# Check for test/all mode or legacy test context compression
if "all" in modes or "test" in modes or os.environ.get("PDD_COMPRESS_TEST_CONTEXT") == "1":
if file_path.startswith(tests_dir):
mode = "test_interface"
# Check for examples/all mode or legacy examples compression
if mode == "full" and ("all" in modes or "examples" in modes or os.environ.get("PDD_COMPRESS_EXAMPLES") == "1"):
if file_path.startswith(examples_dir):
mode = "interface"
# Check for contracts/all mode
if mode == "full" and ("all" in modes or "contracts" in modes):
if any(file_path.endswith(ext) for ext in (".prompt", ".md", ".markdown", ".rst")):
mode = "contracts"
if attrs.get("mode") is None and mode == "full" and compress:
mode = "compressed"
ext = os.path.splitext(file_path)[1].lower()
image_extensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.heic']
if ext in image_extensions:
console.print(f"Processing image include: [cyan]{full_path}[/cyan]")
from PIL import Image
import io
import pillow_heif
pillow_heif.register_heif_opener()
MAX_DIMENSION = 1024
with open(full_path, 'rb') as file:
img = Image.open(file)
img.load() # Force loading the image data before the file closes
if img.width > MAX_DIMENSION or img.height > MAX_DIMENSION:
img.thumbnail((MAX_DIMENSION, MAX_DIMENSION))
console.print(f"Image resized to {img.size}")
# Handle GIFs: convert to a static PNG of the first frame
if ext == '.gif':
img.seek(0)
img = img.convert("RGB")
img_format = 'PNG'
mime_type = 'image/png'
elif ext == '.heic':
img_format = 'JPEG'
mime_type = 'image/jpeg'
else:
img_format = 'JPEG' if ext in ['.jpg', '.jpeg'] else 'PNG'
mime_type = f'image/{img_format.lower()}'
# Save the (potentially resized and converted) image to an in-memory buffer
buffer = io.BytesIO()
img.save(buffer, format=img_format)
content = buffer.getvalue()
encoded_string = base64.b64encode(content).decode('utf-8')
return f"data:{mime_type};base64,{encoded_string}"
else:
if not _is_quiet_mode():
console.print(f"Processing XML include: [cyan]{full_path}[/cyan]")
with open(full_path, 'r', encoding='utf-8') as file:
content = file.read()
# Apply selectors if any
selectors_str = attrs.get('select')
lines_str = attrs.get('lines')
expand_dependencies = _include_expand_dependencies(attrs)
if selectors_str or lines_str or mode != 'full' or expand_dependencies:
selectors = []
if selectors_str:
from pdd._selector_parse import parse_selectors_string
selectors.extend(parse_selectors_string(selectors_str))
if lines_str:
selectors.append(f"lines:{lines_str}")
if mode == "compressed":
raw_include_content = content
content = _compressed_include_with_fallback_or_raw(
raw_include_content,
full_path,
selectors=selectors,
expand_dependencies=expand_dependencies,
)
else:
try:
from pdd.compression_reporting import (
CompressionFallbackError,
record_compression_applied,
)
from pdd.content_selector import ContentSelector, SelectorError
original_content = content
selector = ContentSelector()
content = selector.select(
content=content,
selectors=selectors,
file_path=full_path,
mode=mode,
expand_dependencies=expand_dependencies,
)
if content != original_content:
if selectors_str:
record_compression_applied(
full_path, f"select:{selectors_str}"
)
elif mode != "full":
record_compression_applied(full_path, mode)
except CompressionFallbackError:
raise
except ImportError as e:
fallback_query = attrs.get('query')
if fallback_query and _is_context_audit_no_query_fallback():
_dbg(f"Deferred query fallback during context audit for {file_path}")
return match.group(0)
# Issue #1711: _query_fallback_extract re-raises the
# session guard (fail fast); only non-guard failures
# fall through to the full-content fallback below.
extracted = _query_fallback_extract(full_path, fallback_query, snapshot_recorder)
if extracted is not None:
return extracted
_warn_selector_fallback(file_path, mode, e, selectors=selectors_str)
except SelectorError as e:
fallback_query = attrs.get('query')
if fallback_query and _is_context_audit_no_query_fallback():
_dbg(f"Deferred query fallback during context audit for {file_path}")
return match.group(0)
# Issue #1711: _query_fallback_extract re-raises the
# session guard (fail fast); only non-guard failures
# fall through to the full-content fallback below.
extracted = _query_fallback_extract(full_path, fallback_query, snapshot_recorder)
if extracted is not None:
return extracted
_warn_selector_fallback(file_path, mode, e, selectors=selectors_str)
except Exception as e:
fallback_strategy = os.environ.get("PDD_COMPRESSION_FALLBACK", "full").lower()
if fallback_strategy == "error":
raise CompressionFallbackError(str(e)) from e
fallback_query = attrs.get('query')
if fallback_query and _is_context_audit_no_query_fallback():
_dbg(f"Deferred query fallback during context audit for {file_path}")
return match.group(0)
# Issue #1711: _query_fallback_extract re-raises the
# session guard (fail fast); only non-guard failures
# fall through to the full-content fallback below.
extracted = _query_fallback_extract(full_path, fallback_query, snapshot_recorder)
if extracted is not None:
return extracted
_warn_selector_fallback(file_path, mode, e, selectors=selectors_str)
if recursive:
child_seen = _seen | {resolved}
content = preprocess(
content,
recursive=True,
double_curly_brackets=False,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
_seen=child_seen,
_failed=_failed,
_user_intent_paths=_user_intent_paths,
snapshot_recorder=snapshot_recorder,
)
else:
child_seen = _seen | {resolved}
content = _process_nested_includes(
content,
_seen=child_seen,
_failed=_failed,
_user_intent_paths=_user_intent_paths,
compress=compress,
examples_dir=examples_dir,
tests_dir=tests_dir,
snapshot_recorder=snapshot_recorder,
)
if snapshot_recorder is not None:
snapshot_recorder.record_include(
source_path=full_path,
content=content,
include_depth=len(_seen),
)
_dbg(f"Included via XML tag: {file_path} (len={len(content)})")
return content
except FileNotFoundError:
_dbg(f"Missing XML include: {file_path}")
# First pass (recursive=True): leave the tag so a later env expansion can resolve it.
if recursive:
return match.group(0)
# iterations > 0 means this match originated from content already expanded on
# an earlier pass (e.g. literal <include> syntax inside a .py docstring/regex
# string). User-intended includes were resolved on iteration 0, so suppress
# both the console warning and the failed-include tracking for these.
if iterations > 0:
return match.group(0)
optional_val = attrs.get("optional")
if optional_val is not None:
truthy = str(optional_val).strip().lower() not in {"", "0", "false", "no", "off"}
if truthy:
# Optional missing files are silent: no console warning, no
# "[File not found: ...]" marker, no entry in _failed.
return ""
# Suppress matches that came from inside an already-expanded source
# file's docstrings/regex/comments. Two-tier gating:
#
# * Caller supplied `_user_intent_paths` (production two-pass flow,
# pre-computed from the ORIGINAL prompt via
# `compute_user_intent_paths()`): use the set as the authoritative
# gate. Skip the path-shape heuristic entirely so legitimate
# extensionless includes (Makefile, Dockerfile, LICENSE) still
# fail loudly when they're missing and the user authored them.
#
# * No `_user_intent_paths`: fall back to the path-shape heuristic
# to filter the obvious parser artifacts (multi-word fragments,
# lines starting with `#`, paths without any path-y character).
# This gate is conservative — it suppresses some valid filenames
# like bare `Makefile`, but in single-pass callers the only
# known false-positive source is parser artifacts in expanded
# content, so that tradeoff is acceptable for back-compat.
if _user_intent_paths is not None:
if file_path not in _user_intent_paths:
return match.group(0)
else:
if not _looks_like_user_intent_path(file_path):
return match.group(0)
if not _is_quiet_mode():
console.print(f"[bold red]Warning:[/bold red] File not found: {file_path}")
if _failed is not None:
_failed.append(file_path)
return f"[File not found: {file_path}]"
except ValueError as e:
if "Circular include" in str(e):
raise
console.print(f"[bold red]Error processing include:[/bold red] {str(e)}")
_dbg(f"Error processing XML include {file_path}: {e}")
if recursive:
return match.group(0)
return f"[Error processing include: {file_path}]"
except OSError as e:
_dbg(f"OSError processing XML include {file_path}: {e}")
return match.group(0)
except Exception as e:
from pdd.compression_reporting import CompressionFallbackError
from pdd.include_query_extractor import RepeatedRetrievalQueryError
if isinstance(e, CompressionFallbackError):
raise
# Issue #1711: the session guard re-raised from a select= query fallback
# must keep propagating. This broad handler would otherwise turn it into
# an "[Error processing include]" placeholder and let sync continue.
if isinstance(e, RepeatedRetrievalQueryError):
raise
console.print(f"[bold red]Error processing include:[/bold red] {str(e)}")
_dbg(f"Error processing XML include {file_path}: {e}")
if recursive:
return match.group(0)
return f"[Error processing include: {file_path}]"
prev_text = ""
current_text = text
iterations = 0
while prev_text != current_text:
if iterations >= _MAX_INCLUDE_ITERATIONS:
raise ValueError("Circular include detected: maximum include depth exceeded")
prev_text = current_text
code_spans = _extract_code_spans(current_text)
def replace_include_with_spans(match):
if _intersects_any_span(match.start(), match.end(), code_spans):
return match.group(0)
return replace_include(match)
current_text = re.sub(pattern, replace_include_with_spans, current_text, flags=re.DOTALL)
iterations += 1
return current_text
def process_pdd_tags(text: str) -> str:
pattern = r'<pdd>(?:(?!</pdd>)[\s\S])*+</pdd>'
# Replace pdd tags with an empty string first
processed = re.sub(pattern, '', text, flags=re.DOTALL)
# If there was a replacement and we're left with a specific test case, handle it specially
if processed == "This is a test" and text.startswith("This is a test <pdd>"):
return "This is a test "
return processed
def process_shell_tags(text: str, recursive: bool, snapshot_recorder: Optional[Any] = None) -> str:
pattern = r'<shell>((?:(?!</shell>)[\s\S])*+)</shell>'
def replace_shell(match):
command = match.group(1).strip()
if recursive:
# Defer execution until after env var expansion
return match.group(0)
console.print(f"Executing shell command: [cyan]{escape(command)}[/cyan]")
_dbg(f"Shell tag command: {command}")
try:
# Configurable timeout to prevent hanging shell commands
try:
shell_timeout = int(os.environ.get("PDD_SHELL_TIMEOUT", "30"))
except Exception:
shell_timeout = 30
timeout_arg = None if shell_timeout <= 0 else shell_timeout
result = subprocess.run(
command,
shell=True,
check=True,
capture_output=True,
text=True,
timeout=timeout_arg,
)
if snapshot_recorder is not None:
snapshot_recorder.record_shell(
command=command,
stdout=result.stdout,
stderr=result.stderr,
exit_code=result.returncode,
timeout=timeout_arg,
)
return result.stdout
except subprocess.CalledProcessError as e:
# Do not re-raise: replace the <shell> tag with an inline error so preprocessing
# completes and callers (sync/generate/etc.) continue; tests expect this behavior.
stdout = (e.stdout or "").strip()
stderr = (e.stderr or "").strip()
combined_output = " ".join(part for part in (stdout, stderr) if part)
error_msg = (
f"Command '{command}' returned non-zero exit status {e.returncode}."
+ (f" Output: {combined_output}" if combined_output else "")
)
console.print(f"[bold red]Error:[/bold red] {error_msg}")
_dbg(f"Shell command error: {error_msg}")
if snapshot_recorder is not None:
snapshot_recorder.record_shell(
command=command,
stdout=e.stdout or "",
stderr=e.stderr or "",
exit_code=e.returncode,
timeout=timeout_arg,
)
return f"Error: {error_msg}"
except subprocess.TimeoutExpired as e:
# Replace the <shell> tag with a visible timeout marker instead of hanging
error_msg = f"Command '{e.cmd}' timed out after {e.timeout} seconds."
console.print(f"[bold red]Error:[/bold red] {error_msg}")
_dbg(f"Shell command timeout: {error_msg}")
if snapshot_recorder is not None:
snapshot_recorder.record_shell(
command=command,
stdout=e.stdout or "",
stderr=e.stderr or "",
exit_code=124,
timeout=e.timeout,
)
return error_msg
except Exception as e:
console.print(f"[bold red]Error executing shell command:[/bold red] {str(e)}")
_dbg(f"Shell execution exception: {e}")
if snapshot_recorder is not None:
snapshot_recorder.record_shell(
command=command,
stdout="",
stderr=str(e),
exit_code=-1,
timeout=timeout_arg,
)
return f"[Shell execution error: {str(e)}]"
code_spans = _extract_code_spans(text)
def replace_shell_with_spans(match):
if _intersects_any_span(match.start(), match.end(), code_spans):
return match.group(0)
return replace_shell(match)
return re.sub(pattern, replace_shell_with_spans, text, flags=re.DOTALL)
def process_web_tags(text: str, recursive: bool, snapshot_recorder: Optional[Any] = None) -> str:
pattern = r'<web>((?:(?!</web>)[\s\S])*+)</web>'
def replace_web(match):
url = match.group(1).strip()
if recursive:
# Defer network operations until after env var expansion
return match.group(0)
# Get cache instance
cache = get_firecrawl_cache()
# Check cache first
cached_content = cache.get(url)
if cached_content is not None:
console.print(f"Using cached content for: [cyan]{url}[/cyan]")
if snapshot_recorder is not None:
snapshot_recorder.record_web(
url=url,
content=cached_content,
fetcher="firecrawl_cache",
status=200,
)
return cached_content
console.print(f"Scraping web content from: [cyan]{url}[/cyan]")
_dbg(f"Web tag URL: {url}")
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError
try:
try:
from firecrawl import Firecrawl
except ImportError:
try:
from firecrawl import FirecrawlApp as Firecrawl
except ImportError:
_dbg("firecrawl import failed; package not installed")
error_msg = f"[Error: firecrawl-py package not installed. Cannot scrape {url}]"
if snapshot_recorder is not None:
snapshot_recorder.record_web(url=url, content=error_msg, fetcher="error", status=None)
return error_msg
api_key = os.environ.get('FIRECRAWL_API_KEY')
if not api_key:
console.print("[bold yellow]Warning:[/bold yellow] FIRECRAWL_API_KEY not found in environment")
_dbg("FIRECRAWL_API_KEY not set")
error_msg = f"[Error: FIRECRAWL_API_KEY not set. Cannot scrape {url}]"
if snapshot_recorder is not None:
snapshot_recorder.record_web(url=url, content=error_msg, fetcher="error", status=None)
return error_msg
app = Firecrawl(api_key=api_key)
# firecrawl-py v4 renamed scrape_url() -> scrape(). Fall back to
# the legacy name for older SDKs (v2/v3 still ship FirecrawlApp).
scrape_fn = getattr(app, 'scrape', None) or getattr(app, 'scrape_url', None)
if scrape_fn is None:
_dbg("firecrawl client exposes neither scrape() nor scrape_url()")
error_msg = f"[Error: firecrawl-py client missing scrape API. Cannot scrape {url}]"
if snapshot_recorder is not None:
snapshot_recorder.record_web(url=url, content=error_msg, fetcher="error", status=None)
return error_msg
# Firecrawl SDK has historically had a bug where it passed timeout
# (ms) to requests.post() which expects seconds, so timeout=30000
# becomes 30000s (~8hrs). Wrap in a thread with a hard 30s
# client-side deadline regardless of SDK version.
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(scrape_fn, url, formats=['markdown'], timeout=30000)
response = future.result(timeout=30)
# Handle both dict response (new API) and object response (legacy)
content = None
if isinstance(response, dict) and 'markdown' in response:
_dbg(f"Web scrape returned markdown (len={len(response['markdown'])})")
content = response['markdown']
elif hasattr(response, 'markdown'):
_dbg(f"Web scrape returned markdown (len={len(response.markdown)})")
content = response.markdown
if content:
# Cache the result for future use
cache.set(url, content)
if snapshot_recorder is not None:
snapshot_recorder.record_web(
url=url,
content=content,
fetcher="firecrawl",
status=200,
)
return content
else:
console.print(f"[bold yellow]Warning:[/bold yellow] No markdown content returned for {url}")
_dbg("Web scrape returned no markdown content")
error_msg = f"[No content available for {url}]"
if snapshot_recorder is not None:
snapshot_recorder.record_web(url=url, content=error_msg, fetcher="firecrawl", status=200)
return error_msg
except FuturesTimeoutError:
console.print(f"[bold yellow]Warning:[/bold yellow] Web scrape timed out after 30s for {url}")
_dbg(f"Web scrape timeout for {url}")
error_msg = f"[Web scraping timed out for {url}]"
if snapshot_recorder is not None:
snapshot_recorder.record_web(url=url, content=error_msg, fetcher="error", status=None)
return error_msg
except Exception as e:
console.print(f"[bold red]Error scraping web content:[/bold red] {str(e)}")
_dbg(f"Web scraping exception: {e}")
error_msg = f"[Web scraping error: {str(e)}]"
if snapshot_recorder is not None:
snapshot_recorder.record_web(url=url, content=error_msg, fetcher="error", status=None)
return error_msg
code_spans = _extract_code_spans(text)
def replace_web_with_spans(match):
if _intersects_any_span(match.start(), match.end(), code_spans):
return match.group(0)
return replace_web(match)
return re.sub(pattern, replace_web_with_spans, text, flags=re.DOTALL)
def process_include_many_tags(
text: str,
recursive: bool,
compress: bool = False,
examples_dir: str = "examples/",
tests_dir: str = "tests/",
_seen: Optional[set] = None,
_failed: Optional[List[str]] = None,
_user_intent_paths: Optional[set] = None,
snapshot_recorder: Optional[Any] = None,
) -> str:
"""Process <include-many> blocks whose inner content is a comma- or newline-separated
list of file paths (typically provided via variables after env expansion).
Supports `optional` attribute: <include-many optional="true">...</include-many>.
When optional, missing files are silently skipped (no console warning, no marker,
no entry in `_failed`). Use this for tag bodies that derive from optional ${VAR}
placeholders that may not be bound.
`_user_intent_paths` is a set of paths captured from the ORIGINAL prompt text
before any <include> expansion. When supplied, FileNotFound warnings only fire
for paths in the set — protecting against false positives when an expanded
include's source contains literal `<include-many>...</include-many>` syntax in
a docstring or regex string.
"""
if _seen is None:
_seen = set()
pattern = r'<include-many(?P<attrs>\s[^>]*+)?>(?P<inner>.*?)</include-many>'
def replace_many(match):
attrs = _parse_attrs(match.group('attrs') or "")
inner = match.group('inner')
if recursive:
# Wait for env expansion to materialize the list
return match.group(0)
optional_val = attrs.get("optional")
is_optional = (
optional_val is not None
and str(optional_val).strip().lower() not in {"", "0", "false", "no", "off"}
)
# Split by newlines or commas
raw_items = [s.strip() for part in inner.splitlines() for s in part.split(',')]
paths = [p for p in raw_items if p]
contents: list[str] = []
for p in paths:
try:
full_path = get_file_path(p)
console.print(f"Including (many): [cyan]{full_path}[/cyan]")
with open(full_path, 'r', encoding='utf-8') as fh:
raw_content = fh.read()
content = (
_compressed_include_with_fallback_or_raw(
raw_content,
full_path,
)
if compress
else raw_content
)
contents.append(content)
if snapshot_recorder is not None:
snapshot_recorder.record_include(
source_path=full_path,
content=content,
include_depth=len(_seen),
)
_dbg(f"Included (many): {p}")
except FileNotFoundError:
_dbg(f"Missing include-many: {p}")
if is_optional:
continue
# Two-tier gating (mirrors `process_include_tags`):
# * caller-supplied `_user_intent_paths`: authoritative gate.
# * no `_user_intent_paths`: path-shape heuristic fallback.
if _user_intent_paths is not None:
if p not in _user_intent_paths:
continue
else:
if not _looks_like_user_intent_path(p):
continue
if not _is_quiet_mode():
console.print(f"[bold red]Warning:[/bold red] File not found: {p}")
if _failed is not None:
_failed.append(p)
contents.append(f"[File not found: {p}]")
except Exception as e:
console.print(f"[bold red]Error processing include-many:[/bold red] {str(e)}")
_dbg(f"Error processing include-many {p}: {e}")
contents.append(f"[Error processing include: {p}]")
return "\n".join(contents)
code_spans = _extract_code_spans(text)
def replace_many_with_spans(match):
if _intersects_any_span(match.start(), match.end(), code_spans):
return match.group(0)
return replace_many(match)
return re.sub(pattern, replace_many_with_spans, text, flags=re.DOTALL)
def double_curly(
text: str,
exclude_keys: Optional[List[str]] = None,
exclude: Optional[List[str]] = None,
) -> str:
if exclude_keys is None:
exclude_keys = exclude if exclude is not None else []
if not _is_quiet_mode():
console.print("Doubling curly brackets...")
_dbg("double_curly invoked")
# Protect ${IDENT} placeholders so we can safely double braces, then restore
# them as ${{IDENT}} to avoid PromptTemplate interpreting {IDENT}.
protected_vars: List[str] = []
def _protect_var(m):
protected_vars.append(m.group(0))
return f"__PDD_VAR_{len(protected_vars)-1}__"
text = re.sub(r"\$\{[A-Za-z_][A-Za-z0-9_]*\}", _protect_var, text)
# First, protect any existing double curly braces
text = re.sub(r'\{\{([^{}]*+)\}\}', r'__ALREADY_DOUBLED__\1__END_ALREADY__', text)
# Process excluded keys
for key in exclude_keys:
pattern = r'\{(' + re.escape(key) + r')\}'
text = re.sub(pattern, r'__EXCLUDED__\1__END_EXCLUDED__', text)
# Double remaining single brackets
text = text.replace("{", "{{").replace("}", "}}")
# Restore excluded keys
text = re.sub(r'__EXCLUDED__((?:(?!__END_EXCLUDED__).)*+)__END_EXCLUDED__', r'{\1}', text)
# Restore already doubled brackets
text = re.sub(r'__ALREADY_DOUBLED__((?:(?!__END_ALREADY__).)*+)__END_ALREADY__', r'{{\1}}', text)
# Restore protected ${IDENT} placeholders as ${{IDENT}}
def _restore_var(m):
idx = int(m.group(1))
if 0 <= idx < len(protected_vars):
original = protected_vars[idx] # e.g., ${FOO}
try:
inner = re.match(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}", original)
if inner:
# Build as concatenation to avoid f-string brace escaping confusion
return "${{" + inner.group(1) + "}}" # -> ${{FOO}}
except Exception:
pass
return original
return m.group(0)
text = re.sub(r"__PDD_VAR_(\d+)__", _restore_var, text)
# Special handling for code blocks
code_block_pattern = r'```([\w \t\r\f\v]*)\n((?:(?!```)[\s\S])*)```'
def process_code_block(match):
lang = match.group(1).strip()
code = match.group(2)
if lang.lower() in ['json', 'javascript', 'typescript', 'js', 'ts', 'python', 'py']:
lines = code.split('\n')
processed_lines = []
for line in lines:
if '{{' in line and '}}' in line:
processed_lines.append(line)
else:
processed_line = line
if '{' in line and '}' in line:
processed_line = processed_line.replace("{", "{{").replace("}", "}}")
processed_lines.append(processed_line)
processed_code = '\n'.join(processed_lines)
return f"```{lang}\n{processed_code}```"
return match.group(0)
# Process code blocks
text = re.sub(code_block_pattern, process_code_block, text, flags=re.DOTALL)
return text
import logging
import os
import re
import warnings
import base64
import subprocess
from typing import Any, List, Optional, Tuple, Union
import traceback
from pathlib import Path, PurePosixPath
from rich.console import Console
from rich.panel import Panel
from rich.markup import escape
from rich.traceback import install
from .firecrawl_cache import get_firecrawl_cache
from pdd.path_resolution import get_default_resolver
from pdd.sync_core.includes import include_paths
install()
console = Console()
logger = logging.getLogger(__name__)
# Maximum iterations for the non-recursive convergence loop.
# Diamond includes converge quickly; true cycles never converge.
_MAX_INCLUDE_ITERATIONS = 50
_DEBUG_EVENTS: List[str] = []
def _is_debug() -> bool:
return str(os.getenv("PDD_PREPROCESS_DEBUG", "")).lower() in ("1", "true", "yes", "on")
def _is_quiet_mode() -> bool:
return os.getenv("PDD_QUIET") == "1"
def _is_context_audit_no_query_fallback() -> bool:
"""Return True when context audit must defer semantic query fallbacks."""
return os.getenv("PDD_CONTEXT_AUDIT_NO_QUERY_FALLBACK") == "1"
def _warn_selector_fallback(
file_path: str,
mode: str,
error: Exception,
*,
selectors: str | None = None,
) -> None:
"""Emit a UserWarning when compression/selector fails and full content is used."""
selector_detail = f" for select={selectors}" if selectors else ""
if isinstance(error, ImportError):
message = (
f"ContentSelector not importable{selector_detail} in {file_path}: {error}. "
"Falling back to full content."
)
else:
message = (
f"ContentSelector failed{selector_detail} in {file_path} (mode={mode}): {error}. "
"Falling back to full content."
)
warnings.warn(message, UserWarning, stacklevel=4)
from pdd.compression_reporting import record_compression_fallback
record_compression_fallback(message)
if not _is_quiet_mode():
console.print(f"[yellow]Warning: {message}[/yellow]")
def _query_fallback_extract(full_path, fallback_query, snapshot_recorder):
"""Shared ``select=`` → ``query=`` fallback extraction (Issue #1711).
Used by all three selector-failure routes in ``process_include_tags``
(ImportError, SelectorError, and the generic selector/compression failure).
Returns the extracted content on success, or ``None`` when there is no
``query=`` to fall back to or the extraction failed for a non-guard reason
(recorded as a ``[query_include failed: ...]`` placeholder in the snapshot).
``RepeatedRetrievalQueryError`` — the per-``(file, query)`` session guard — is
intentionally NOT caught here: it propagates so a stuck retrieval loop fails
fast instead of silently continuing on degraded include content. Centralizing
the re-raise in a single helper (rather than copying ``except
RepeatedRetrievalQueryError: raise`` into each branch) stops a future edit
from re-introducing the swallow on one of the fallback paths.
"""
if not fallback_query:
return None
from pdd.include_query_extractor import (
IncludeQueryExtractor,
RepeatedRetrievalQueryError,
)
try:
extracted = IncludeQueryExtractor().extract(
file_path=full_path, query=fallback_query
)
except RepeatedRetrievalQueryError:
raise
except Exception as inner_e:
if snapshot_recorder is not None:
placeholder = f"[query_include failed: {inner_e}]"
snapshot_recorder.record_include(
source_path=full_path,
content=placeholder,
Xet Storage Details
- Size:
- 67.6 kB
- Xet hash:
- 0a12c8e133622c4939238b5ecfc817d35607c56dd5ac4df8d2a6db5b95f3cdc3
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.