Buckets:

download
raw
41.7 kB
from __future__ import annotations import os import re import sys import click from pathlib import Path from typing import Optional, Tuple, Dict, Any, List, Union from rich.console import Console # Relative imports for internal modules from ..context_generator_main import context_generator_main from ..track_cost import track_cost from ..operation_log import log_operation from ..core.errors import handle_error from ..evidence_manifest import ( grounding_kwargs_from_ctx, resolve_generate_output_paths, resolve_test_output_paths, write_evidence_manifest, ) from ..prompt_gate import maybe_run_workflow_prompt_gate from ..user_story_tests import cache_story_prompt_links, generate_user_story # Initialize console console = Console(file=sys.stdout) # Lazily imported in generate() to avoid heavy imports at module load time. # Exposed at module scope so tests can patch it safely. code_generator_main = None _DEFAULT_CODE_GENERATOR_MAIN = None _GITHUB_ISSUE_RE = re.compile( r"^(?:https?://)?(?:www\.)?github\.com/([^/]+)/([^/]+)/issues/(\d+)(?:[/?#].*)?$" ) def _mark_command_failed(ctx: click.Context) -> None: """Mark handled command exceptions so the cli result-callback exits nonzero. Mirrors ``pdd.commands.analysis._mark_command_failed`` (#1895): a command that returns ``None`` on a handled error is otherwise treated as "no results" by ``process_commands`` and the process exits 0. """ if isinstance(getattr(ctx, "obj", None), dict): ctx.obj["_command_failed"] = True def _estimate_mode_active(ctx: click.Context) -> bool: """Return whether the global dry-run cost estimate mode is active.""" return bool((ctx.obj or {}).get("estimate")) or os.getenv("PDD_ESTIMATE", "").lower() in { "1", "true", "yes", "on", } def _is_estimate_only_result(exception: Exception) -> bool: """Identify llm_invoke.EstimateOnlyResult without importing llm_invoke eagerly.""" return ( exception.__class__.__name__ == "EstimateOnlyResult" and isinstance(getattr(exception, "estimate", None), dict) ) def _estimate_result_tuple(exception: Exception) -> Tuple[Dict[str, Any], float, str]: """Convert EstimateOnlyResult into the normal command return tuple.""" payload = getattr(exception, "payload", None) or getattr(exception, "estimate", {}) model = str(payload.get("model") or "unknown") if isinstance(payload, dict) else "unknown" return payload, 0.0, model def _strip_prompt_language_suffix(path: Path) -> Optional[str]: stem = path.stem for suffix in _prompt_target_extensions(path): if stem.endswith(suffix): return stem[: -len(suffix)] return None def _prompt_target_extensions(path: Path) -> Dict[str, str]: return { "_python": ".py", "_Python": ".py", "_typescript": ".ts", "_TypeScript": ".ts", "_typescriptreact": ".tsx", "_TypeScriptReact": ".tsx", "_javascript": ".js", "_JavaScript": ".js", } def _estimate_output_path_hint(prompt_file: Optional[str], output: Optional[str]) -> Optional[str]: """Best-effort existing target file hint for output-token estimation.""" if output: output_path = Path(output) if output_path.is_file(): return str(output_path) if not prompt_file: return None prompt_path = Path(prompt_file) basename = _strip_prompt_language_suffix(prompt_path) if not basename: return None suffix_to_extension = _prompt_target_extensions(prompt_path) extension = next( ( target_extension for prompt_suffix, target_extension in suffix_to_extension.items() if prompt_path.stem.endswith(prompt_suffix) ), ".py", ) candidates: List[Path] = [] parts = prompt_path.parts if "pdd" in parts and "prompts" in parts: try: prompts_index = parts.index("prompts") rel_dir = Path(*parts[prompts_index + 1 : -1]) repo_prefix = Path(*parts[:prompts_index]) candidates.append(repo_prefix / rel_dir / f"{basename}{extension}") except (TypeError, ValueError): pass candidates.extend( [ prompt_path.with_name(f"{basename}{extension}"), prompt_path.parent.parent / "src" / f"{basename}{extension}", prompt_path.parent.parent / f"{basename}{extension}", ] ) for candidate in candidates: try: if candidate.is_file(): return str(candidate) except OSError: continue return None def _maybe_run_prompt_gate( *, output_files: Tuple[str, ...] | List[str], prompt_checkup: Optional[str], no_prompt_checkup: bool, project_root: Optional[str], quiet: bool, dry_run: bool = False, interactive: bool = False, apply: bool = False, ) -> tuple[bool, int]: """Run the prompt gate; return ``(should_continue, exit_code)``.""" if dry_run and not interactive: return True, 0 root = Path(project_root or Path.cwd()).resolve() return maybe_run_workflow_prompt_gate( output_files, cli_prompt_checkup=prompt_checkup, no_prompt_checkup=no_prompt_checkup, project_root=root, quiet=quiet, interactive=interactive, apply=apply, dry_run=dry_run, ) def _enforce_prompt_gate_or_exit( *, output_files: Tuple[str, ...] | List[str], prompt_checkup: Optional[str], no_prompt_checkup: bool, project_root: Optional[str], quiet: bool, dry_run: bool = False, interactive: bool = False, apply: bool = False, ) -> None: """Raise ``click.Exit`` when strict prompt checkup blocks downstream work.""" should_continue, exit_code = _maybe_run_prompt_gate( output_files=output_files, prompt_checkup=prompt_checkup, no_prompt_checkup=no_prompt_checkup, project_root=project_root, quiet=quiet, dry_run=dry_run, apply=apply, interactive=interactive, ) if not should_continue: raise click.exceptions.Exit(exit_code) class GenerateCommand(click.Command): """ Custom command class to handle the conditional requirement of PROMPT_FILE. PROMPT_FILE is required unless --template is specified. """ def format_usage(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: """ Custom usage formatter to indicate PROMPT_FILE is conditionally required. """ # We rely on standard formatting but this class exists to satisfy # specific help text requirements if needed in the future. super().format_usage(ctx, formatter) @click.command(cls=GenerateCommand, name="generate") @click.argument( "prompt_file", required=False, type=click.UNPROCESSED, ) # UNPROCESSED to allow GitHub URLs @click.option("--template", help="Use a template instead of a prompt file.") @click.option("-e", "--env", multiple=True, help="Set environment variables (KEY=VALUE or KEY).") @click.option("--output", help="Specify where to save the generated code.") @click.option("--original-prompt", type=click.Path(exists=True), help="Original prompt file for incremental generation.") @click.option("--incremental", is_flag=True, help="Use incremental patching.") @click.option( "--experimental-prd", is_flag=True, help=( "Opt in to experimental Incremental PRD Mode for a PRD file or " "GitHub issue. Requires --incremental." ), ) @click.option( "--dry-run", is_flag=True, help="Preview incremental PRD propagation without writing files.", ) @click.option("--unit-test", type=click.Path(exists=True), help="Path to a unit test file for TDD.") @click.option("--exclude-tests", is_flag=True, help="Do not automatically include test files.") @click.option("--skip-prompts", is_flag=True, help="Skip prompt generation in agentic architecture mode (prompts are generated by default).") @click.option("--output-dir", default=None, help="Safe repo-relative target subdirectory for agentic or incremental generation.") @click.option( "--force-single", is_flag=True, default=False, help="Force single-project generation even if PRD is complex (skip complexity check).", ) @click.option( "--no-github-state", is_flag=True, help="Disable GitHub issue comments/state for agentic modes.", ) @click.option( "--project-root", "project_root", type=click.Path(file_okay=False, dir_okay=True, exists=True, resolve_path=True), default=None, help=( "Explicit project-root override. Use the given path as the resolved " "project root instead of walking up from cwd. Useful when the cwd is " "a self-contained pdd project nested inside an unrelated outer git repo. " "Only valid in agentic-issue mode and --incremental --experimental-prd " "mode; passing it on a standard prompt-file invocation is rejected." ), ) @click.option( "--evidence", is_flag=True, default=False, help="Write a machine-readable evidence manifest for this run.", ) @click.option( "--snapshot-context", is_flag=True, default=False, help=( "Write replayable expanded prompt context artifacts (single prompt-file " "generation only; not global/agentic sync). Use pdd replay on the " "snapshot manifest under .pdd/evidence/runs/." ), ) @click.option( "--compress", is_flag=True, default=False, help=( "Use AST-based compression for Python includes when expanding the " "prompt (few-shot context reduction)." ), ) @click.option( "--prompt-checkup", type=click.Choice(["warn", "strict"]), default=None, help="Automatic prompt checkup after creating or modifying .prompt files.", ) @click.option( "--no-prompt-checkup", is_flag=True, default=False, help="Disable automatic prompt checkup for this run.", ) @click.option( "--interactive", "interactive", is_flag=True, default=False, help="With --prompt-checkup: run interactive per-finding repair on changed prompts.", ) @click.option( "--apply", "apply", is_flag=True, default=False, help="With --interactive: write approved low-risk repairs to the prompt files.", ) @click.pass_context @log_operation(operation="generate", clears_run_report=True, updates_fingerprint=True) @track_cost def generate( ctx: click.Context, prompt_file: Optional[str], template: Optional[str], env: Tuple[str, ...], output: Optional[str], original_prompt: Optional[str], incremental: bool, experimental_prd: bool, dry_run: bool, unit_test: Optional[str], exclude_tests: bool, skip_prompts: bool, output_dir: Optional[str], force_single: bool, no_github_state: bool, project_root: Optional[str], evidence: bool, snapshot_context: bool, compress: bool, prompt_checkup: Optional[str], no_prompt_checkup: bool, interactive: bool, apply: bool, ) -> Optional[Tuple[str, float, str]]: """ Create runnable code from a prompt file. """ # Defer imports to avoid circular dependencies global code_generator_main, _DEFAULT_CODE_GENERATOR_MAIN from ..code_generator_main import code_generator_main as _code_generator_main if _DEFAULT_CODE_GENERATOR_MAIN is None: _DEFAULT_CODE_GENERATOR_MAIN = _code_generator_main if code_generator_main is None or code_generator_main is _DEFAULT_CODE_GENERATOR_MAIN: code_generator_main = _code_generator_main # Try to import template registry try: from ..template_registry import load_template except ImportError: load_template = None try: # 1. Validate Mutex: Template vs Prompt File if template and prompt_file: raise click.UsageError("Cannot specify both PROMPT_FILE and --template.") if not template and not prompt_file: raise click.UsageError("Missing argument 'PROMPT_FILE' or option '--template'.") # 2. Resolve Template if used target_prompt_file = prompt_file if template: if load_template is None: raise click.UsageError("Template support is not available in this installation.") try: template_meta = load_template(template) target_prompt_file = template_meta.get("path") if not target_prompt_file: raise click.UsageError(f"Template '{template}' not found.") except FileNotFoundError: raise click.UsageError(f"Failed to load template '{template}'") except Exception as e: raise click.UsageError(f"Error resolving template '{template}': {str(e)}") verbose = ctx.obj.get("verbose", False) if ctx.obj else False quiet = ctx.obj.get("quiet", False) if ctx.obj else False estimate_mode = _estimate_mode_active(ctx) is_github_issue = bool(prompt_file and _GITHUB_ISSUE_RE.match(prompt_file.strip())) has_code_generation_options = bool( output or original_prompt or env or template or unit_test or exclude_tests ) is_prd_like_file = bool( prompt_file and Path(prompt_file).suffix.lower() in {".md", ".markdown", ".txt", ".rst", ".adoc"} ) if experimental_prd and not incremental: raise click.UsageError("--experimental-prd requires --incremental.") if snapshot_context and (is_github_issue or experimental_prd): raise click.UsageError("--snapshot-context is only supported for prompt-file generation.") if experimental_prd and has_code_generation_options: raise click.UsageError( "--experimental-prd cannot be combined with code-generation " "options such as --output, --original-prompt, --template, " "--env, --unit-test, or --exclude-tests." ) if ( incremental and not experimental_prd and prompt_file and ( is_github_issue or (is_prd_like_file and not has_code_generation_options) ) ): raise click.UsageError( "Incremental PRD propagation is experimental and now requires " "--experimental-prd. Use `pdd generate --incremental " "--experimental-prd <prd-file-or-issue-url>`." ) is_incremental_prd = bool( incremental and experimental_prd and prompt_file and ( is_github_issue or (is_prd_like_file and not has_code_generation_options) ) ) if experimental_prd and not is_incremental_prd: raise click.UsageError( "--experimental-prd expects a GitHub issue URL or a PRD-like " "file (.md, .markdown, .txt, .rst, .adoc)." ) if is_incremental_prd: if estimate_mode: raise click.UsageError("Estimate mode currently supports standard prompt-file `generate` only.") from .. import DEFAULT_STRENGTH, DEFAULT_TIME from ..agentic_architecture import run_incremental_architecture obj = ctx.obj or {} success, message, cost, model, output_files = run_incremental_architecture( prd_source=prompt_file, dry_run=dry_run, verbose=verbose, quiet=quiet, use_github_state=not no_github_state, target_dir=output_dir, # Forward the global model knobs (--strength / --temperature # / --time) so user-specified values are not silently ignored # for `pdd --strength X generate --incremental ...`. strength=obj.get("strength", DEFAULT_STRENGTH), temperature=obj.get("temperature", 0.0), time=obj.get("time", DEFAULT_TIME), project_root=project_root, ) if not quiet: if success: click.echo(click.style(f"Success: {message}", fg="green")) else: click.echo(click.style(f"Failed: {message}", fg="red")) if output_files: label = "Would change files" if dry_run else "Output files" click.echo(f"{label}: {', '.join(output_files)}") if evidence and success: write_evidence_manifest( command="pdd generate", prompt_file=prompt_file, output_files=output_files if not dry_run else (), model=model, cost_usd=cost, temperature=obj.get("temperature", 0.0), **grounding_kwargs_from_ctx(ctx.obj), ) if success: _enforce_prompt_gate_or_exit( output_files=output_files, prompt_checkup=prompt_checkup, no_prompt_checkup=no_prompt_checkup, project_root=project_root, quiet=quiet, dry_run=dry_run, interactive=interactive, apply=apply, ) else: _mark_command_failed(ctx) return (message, cost, model) if success else None if dry_run: raise click.UsageError( "--dry-run is only supported with --incremental " "--experimental-prd PRD/GitHub issue mode." ) # Detect GitHub issue URL -> agentic architecture mode if is_github_issue: if estimate_mode: raise click.UsageError("Estimate mode currently supports standard prompt-file `generate` only.") from ..agentic_architecture import run_agentic_architecture success, message, cost, model, output_files = run_agentic_architecture( issue_url=prompt_file, verbose=verbose, quiet=quiet, use_github_state=not no_github_state, skip_prompts=skip_prompts, target_dir=output_dir, force_single=force_single, project_root=project_root, ) if not quiet: if success: click.echo(click.style(f"Success: {message}", fg="green")) else: click.echo(click.style(f"Failed: {message}", fg="red")) if output_files: click.echo(f"Output files: {', '.join(output_files)}") if evidence and success: write_evidence_manifest( command="pdd generate", output_files=output_files, model=model, cost_usd=cost, temperature=(ctx.obj or {}).get("temperature", 0.0), basename="agentic-generate", **grounding_kwargs_from_ctx(ctx.obj), ) if success: _enforce_prompt_gate_or_exit( output_files=output_files, prompt_checkup=prompt_checkup, no_prompt_checkup=no_prompt_checkup, project_root=project_root, quiet=quiet, interactive=interactive, apply=apply, ) else: _mark_command_failed(ctx) return (message, cost, model) if success else None if project_root: raise click.UsageError( "--project-root is only supported in agentic-issue mode " "(GitHub issue URL) or --incremental --experimental-prd mode." ) # Validate file path (not a URL, must exist and not be a directory) if prompt_file and not template: p = Path(prompt_file) if not p.exists(): raise click.UsageError(f"Invalid value for 'PROMPT_FILE': Path '{prompt_file}' does not exist.") if p.is_dir(): raise click.UsageError(f"Invalid value for 'PROMPT_FILE': Path '{prompt_file}' is a directory.") # 3. Parse and Set Environment Variables env_vars: Dict[str, str] = {} for item in env: if "=" in item: key, value = item.split("=", 1) env_vars[key] = value else: # Docker-style fallback: read from current env if item in os.environ: env_vars[item] = os.environ[item] # Update os.environ for the duration of this command # This allows the code generator and template expansion to see these values os.environ.update(env_vars) # 4. Call Code Generator force_was_present = False original_force = None output_hint_was_present = False original_output_hint = None incremental_module = None original_incremental_func = None had_incremental_func = False try: if estimate_mode and isinstance(ctx.obj, dict): force_was_present = "force" in ctx.obj original_force = ctx.obj.get("force") ctx.obj["force"] = True output_hint_was_present = "estimate_output_path_hint" in ctx.obj original_output_hint = ctx.obj.get("estimate_output_path_hint") output_path_hint = _estimate_output_path_hint(target_prompt_file, output) if output_path_hint: ctx.obj["estimate_output_path_hint"] = output_path_hint else: ctx.obj.pop("estimate_output_path_hint", None) try: import importlib incremental_module = importlib.import_module("pdd.code_generator_main") had_incremental_func = hasattr( incremental_module, "incremental_code_generator_func", ) original_incremental_func = getattr( incremental_module, "incremental_code_generator_func", None, ) def _estimate_skip_incremental(*_args: Any, **_kwargs: Any) -> Tuple[None, bool, float, str]: return None, False, 0.0, "estimate" incremental_module.incremental_code_generator_func = _estimate_skip_incremental except Exception: incremental_module = None generated_code, is_incremental, cost, model = code_generator_main( ctx=ctx, prompt_file=target_prompt_file, output=output, original_prompt_file_path=original_prompt, force_incremental_flag=incremental, env_vars=env_vars if env_vars else None, unit_test_file=unit_test, exclude_tests=exclude_tests, snapshot_context=snapshot_context, compress=compress, ) except Exception as exception: if _is_estimate_only_result(exception): return _estimate_result_tuple(exception) raise finally: if estimate_mode and isinstance(ctx.obj, dict): if force_was_present: ctx.obj["force"] = original_force else: ctx.obj.pop("force", None) if output_hint_was_present: ctx.obj["estimate_output_path_hint"] = original_output_hint else: ctx.obj.pop("estimate_output_path_hint", None) if estimate_mode and incremental_module is not None: if had_incremental_func: incremental_module.incremental_code_generator_func = original_incremental_func else: try: delattr(incremental_module, "incremental_code_generator_func") except AttributeError: pass if evidence: ctx_obj = ctx.obj or {} resolved_outputs = ( [output] if output else resolve_generate_output_paths( target_prompt_file, context_override=ctx_obj.get("context"), force=ctx_obj.get("force", False), quiet=ctx_obj.get("quiet", True), ) ) write_evidence_manifest( command="pdd generate", prompt_file=target_prompt_file, output_files=resolved_outputs, model=model, cost_usd=cost, temperature=ctx_obj.get("temperature", 0.0), compress=compress, **grounding_kwargs_from_ctx(ctx_obj), context_snapshot=ctx_obj.get("context_snapshot"), ) return generated_code, cost, model except (click.Abort, click.exceptions.Exit, click.UsageError, click.BadArgumentUsage, click.FileError, click.BadParameter): raise except Exception as e: if _is_estimate_only_result(e): return _estimate_result_tuple(e) quiet = ctx.obj.get("quiet", False) if ctx.obj else False handle_error(e, "generate", quiet) return None @click.command("example") @click.argument("prompt_file", type=click.Path(exists=True, dir_okay=False)) @click.argument("code_file", type=click.Path(exists=True, dir_okay=False)) @click.option( "--output", type=click.Path(writable=True), default=None, help="Specify where to save the generated example code (file or directory).", ) @click.option( "--format", type=click.Choice(["code", "md"], case_sensitive=False), default="code", show_default=True, help=( "Output format. 'code' (default) honors any suffix supplied on --output verbatim " "and only synthesizes the language extension when --output has no suffix. 'md' forces " "a .md suffix on the resolved output path." ), ) @click.pass_context @log_operation(operation="example", clears_run_report=True, updates_fingerprint=True) @track_cost def example( ctx: click.Context, prompt_file: str, code_file: str, output: Optional[str], format: str, ) -> Optional[Tuple[str, float, str]]: """Generate example code for a given prompt and implementation.""" try: example_code, total_cost, model_name = context_generator_main( ctx=ctx, prompt_file=prompt_file, code_file=code_file, output=output, format=format, ) return example_code, total_cost, model_name except click.Abort: raise except Exception as exception: if _is_estimate_only_result(exception): return _estimate_result_tuple(exception) handle_error(exception, "example", (ctx.obj or {}).get("quiet", False)) raise click.exceptions.Exit(1) from exception @click.command(name="test") @click.argument("args", nargs=-1) @click.option("--manual", is_flag=True, help="Use manual mode with explicit file arguments.") @click.option("--timeout-adder", type=float, default=0.0, help="Additional seconds to add to each step's timeout (Agentic mode).") @click.option("--no-github-state", is_flag=True, help="Disable GitHub issue comment-based state persistence (Agentic mode).") @click.option("--clean-restart", is_flag=True, help="Discard saved agentic test state and start from step 1 (Agentic mode).") @click.option("--output", help="Specify where to save the generated test file.") @click.option("--language", help="Specify the programming language.") @click.option("--coverage-report", type=click.Path(exists=True), help="Path to the coverage report file.") @click.option("--existing-tests", type=click.Path(exists=True), multiple=True, help="Path(s) to existing unit test file(s).") @click.option("--target-coverage", type=float, default=90.0, help="Desired code coverage percentage.") @click.option("--merge", is_flag=True, help="Merge new tests with existing test file.") @click.option( "--issue", default=None, help=( "Issue source for story generation: a GitHub issue/PR URL, an issue " "number, or a path to a local issue markdown file. The story is " "authored from the issue, independent of the prompt." ), ) @click.option( "--from-story", "from_story", default=None, type=click.Path(exists=True, dir_okay=False), help=( "Generate deterministic pytest regression tests from a story__*.md " "file. Execution of generated tests is offline and LLM-free." ), ) @click.option( "--evidence", is_flag=True, default=False, help="Write a machine-readable evidence manifest for this run.", ) @click.pass_context @log_operation(operation="test", updates_run_report=True) @track_cost def test( ctx: click.Context, args: Tuple[str, ...], manual: bool, timeout_adder: float, no_github_state: bool, clean_restart: bool, output: Optional[str], language: Optional[str], coverage_report: Optional[str], existing_tests: Tuple[str, ...], target_coverage: float, merge: bool, issue: Optional[str], from_story: Optional[str], evidence: bool, ) -> Optional[Tuple[Any, float, str]]: """ Generate or enhance unit tests, or link story prompt metadata. Supports five modes: 1. Agentic UI Test Generation: pdd test <GITHUB_ISSUE_URL> 2. Manual Unit Test Generation: pdd test --manual PROMPT_FILE CODE_OR_EXAMPLE_FILE 3. Story Generation: pdd test --issue <url|number|issue.md> prompts/upload_python.prompt 4. Story Metadata Linking: pdd test user_stories/story__my_story.md 5. Story Regression Generation: pdd test --from-story user_stories/story__my_story.md """ from ..cmd_test_main import cmd_test_main from ..agentic_test import run_agentic_test try: estimate_mode = _estimate_mode_active(ctx) if from_story: if args: raise click.UsageError("--from-story does not accept positional arguments.") if manual or issue: raise click.UsageError("--from-story cannot be combined with --manual or --issue.") if estimate_mode: raise click.UsageError("Estimate mode currently supports `generate` only.") from ..story_test_generation import generate_story_regression_test try: generated = generate_story_regression_test(from_story, output=output) except (ValueError, FileNotFoundError) as exc: # #1889: surface malformed-story / missing-contract failures as a # clean, nonzero-exit ClickException instead of swallowing them # via handle_error + return None (which exits 0 and hides the # failure from CI). No traceback is shown; the message is # preserved verbatim. raise click.ClickException(str(exc)) from exc obj = ctx.obj or {} if not obj.get("quiet", False): action = "generated" if generated.changed else "already current" console.print( "[bold green]Story regression test " f"{action}:[/bold green] {generated.test_file}" ) result_dict = { "success": True, "message": "Story regression test generated.", **generated.as_dict(), } if evidence: write_evidence_manifest( command="pdd test --from-story", output_files=[generated.test_file], model="deterministic", cost_usd=0.0, validation={"story_regression": "generated"}, basename=generated.story_id, ) return result_dict, 0.0, "deterministic" if not args: raise click.UsageError("Missing arguments. See 'pdd test --help'.") is_url = bool(_GITHUB_ISSUE_RE.match(args[0].strip())) if clean_restart and (manual or not is_url): raise click.UsageError("--clean-restart can only be used with an agentic GitHub issue URL.") # Story metadata linking: pdd test story__my_story.md if (len(args) == 1 and not manual and Path(args[0]).suffix.lower() == ".md" and Path(args[0]).name.startswith("story__")): if estimate_mode: raise click.UsageError("Estimate mode currently supports `generate` only.") story_path = Path(args[0]) obj = ctx.obj or {} success, message, cost, model, linked_prompts = cache_story_prompt_links( story_file=str(story_path), prompts_dir=os.environ.get("PDD_PROMPTS_DIR"), strength=obj.get("strength", 0.2), temperature=obj.get("temperature", 0.0), time=obj.get("time", 0.25), verbose=obj.get("verbose", False), ) if not obj.get("quiet", False): if success: console.print(f"[bold green]Story metadata updated:[/bold green] {message}") else: console.print(f"[bold red]Story metadata update failed:[/bold red] {message}") if linked_prompts: console.print(f"Linked prompts: {', '.join(linked_prompts)}") result_dict = { "success": success, "message": message, "story_file": str(story_path), "linked_prompts": linked_prompts, } if evidence and success: write_evidence_manifest( command="pdd test", output_files=[story_path], model=model, cost_usd=cost, validation={"detect_stories": "passed"}, basename=story_path.stem, ) return result_dict, cost, model # Story generation: pdd test prompt1.prompt [prompt2.prompt ...] if not manual and args and all(Path(arg).suffix.lower() == ".prompt" for arg in args): if estimate_mode: raise click.UsageError("Estimate mode currently supports `generate` only.") obj = ctx.obj or {} story_prompt_args = [str(Path(arg)) for arg in args] success, message, cost, model, generated_story_file, linked_prompts = generate_user_story( prompt_files=story_prompt_args, issue=issue, output=output, stories_dir=os.environ.get("PDD_USER_STORIES_DIR"), prompts_dir=os.environ.get("PDD_PROMPTS_DIR"), strength=obj.get("strength", 0.2), temperature=obj.get("temperature", 0.0), time=obj.get("time", 0.25), verbose=obj.get("verbose", False), ) if not obj.get("quiet", False): if success: console.print(f"[bold green]Story generated:[/bold green] {message}") else: console.print(f"[bold red]Story generation failed:[/bold red] {message}") if linked_prompts: console.print(f"Linked prompts: {', '.join(linked_prompts)}") if not success: raise click.ClickException(message) result_dict = { "success": success, "message": message, "story_file": generated_story_file, "linked_prompts": linked_prompts, } if evidence and success: write_evidence_manifest( command="pdd test", prompt_file=story_prompt_args[0], output_files=[generated_story_file], model=model, cost_usd=cost, validation={"detect_stories": "passed"}, ) return result_dict, cost, model if is_url and not manual: if estimate_mode: raise click.UsageError("Estimate mode currently supports `generate` only.") # Agentic Mode if len(args) != 1: raise click.UsageError("Agentic mode requires exactly one argument (the GitHub issue URL).") issue_url = args[0] verbose = ctx.obj.get("verbose", False) if ctx.obj else False quiet = ctx.obj.get("quiet", False) if ctx.obj else False success, message, cost, model, changed_files = run_agentic_test( issue_url=issue_url, verbose=verbose, quiet=quiet, timeout_adder=timeout_adder, use_github_state=not no_github_state, clean_restart=clean_restart, ) if success: console.print(f"[bold green]Agentic test generation completed:[/bold green] {message}") if changed_files: console.print(f"Changed files: {', '.join(changed_files)}") else: console.print(f"[bold red]Agentic test generation failed:[/bold red] {message}") raise click.exceptions.Exit(1) result_dict = { "success": success, "message": message, "changed_files": changed_files } if evidence: write_evidence_manifest( command="pdd test", output_files=changed_files, model=model, cost_usd=cost, validation={"unit_tests": "not_available"}, basename="agentic-test", ) return result_dict, cost, model else: # Manual Mode if len(args) != 2: raise click.UsageError("Manual mode requires exactly two arguments: PROMPT_FILE and CODE_OR_EXAMPLE_FILE.") prompt_file = args[0] code_file = args[1] strength = ctx.obj.get("strength") if ctx.obj else None temperature = ctx.obj.get("temperature") if ctx.obj else None try: test_result = cmd_test_main( ctx=ctx, prompt_file=prompt_file, code_file=code_file, output=output, language=language, coverage_report=coverage_report, existing_tests=existing_tests, target_coverage=target_coverage, merge=merge, strength=strength, temperature=temperature, manual=manual ) except Exception as exception: if _is_estimate_only_result(exception): return _estimate_result_tuple(exception) raise if evidence: ctx_obj = ctx.obj or {} resolved_outputs = ( [output] if output else resolve_test_output_paths( prompt_file, code_file, language=language, context_override=ctx_obj.get("context"), force=ctx_obj.get("force", False), quiet=ctx_obj.get("quiet", True), ) ) write_evidence_manifest( command="pdd test", prompt_file=prompt_file, output_files=resolved_outputs, model=test_result.model, cost_usd=test_result.cost, validation={"unit_tests": "not_available"}, ) return test_result.content, test_result.cost, test_result.model except (click.Abort, click.exceptions.Exit, click.ClickException, click.UsageError, click.BadArgumentUsage, click.FileError, click.BadParameter): raise except Exception as e: if _is_estimate_only_result(e): return _estimate_result_tuple(e) quiet = ctx.obj.get("quiet", False) if ctx.obj else False # #1889: mark the command failed so the cli result-callback exits # nonzero. A bare `return None` is treated as "no results" (results is # None -> normalized_results == []) by process_commands, so the None # never triggers the nonzero-exit path and CI silently sees exit 0. # This mirrors the #1895 convention for `detect --stories`. _mark_command_failed(ctx) handle_error(e, "test", quiet) return None
from __future__ import annotations
import os
import re
import sys
import click
from pathlib import Path
from typing import Optional, Tuple, Dict, Any, List, Union
from rich.console import Console
# Relative imports for internal modules
from ..context_generator_main import context_generator_main
from ..track_cost import track_cost
from ..operation_log import log_operation
from ..core.errors import handle_error
from ..evidence_manifest import (
grounding_kwargs_from_ctx,
resolve_generate_output_paths,
resolve_test_output_paths,
write_evidence_manifest,
)
from ..prompt_gate import maybe_run_workflow_prompt_gate
from ..user_story_tests import cache_story_prompt_links, generate_user_story
# Initialize console
console = Console(file=sys.stdout)
# Lazily imported in generate() to avoid heavy imports at module load time.
# Exposed at module scope so tests can patch it safely.
code_generator_main = None
_DEFAULT_CODE_GENERATOR_MAIN = None
_GITHUB_ISSUE_RE = re.compile(
r"^(?:https?://)?(?:www\.)?github\.com/([^/]+)/([^/]+)/issues/(\d+)(?:[/?#].*)?$"
)
def _mark_command_failed(ctx: click.Context) -> None:
"""Mark handled command exceptions so the cli result-callback exits nonzero.
Mirrors ``pdd.commands.analysis._mark_command_failed`` (#1895): a command
that returns ``None`` on a handled error is otherwise treated as "no
results" by ``process_commands`` and the process exits 0.
"""
if isinstance(getattr(ctx, "obj", None), dict):
ctx.obj["_command_failed"] = True
def _estimate_mode_active(ctx: click.Context) -> bool:
"""Return whether the global dry-run cost estimate mode is active."""
return bool((ctx.obj or {}).get("estimate")) or os.getenv("PDD_ESTIMATE", "").lower() in {
"1", "true", "yes", "on",
}
def _is_estimate_only_result(exception: Exception) -> bool:
"""Identify llm_invoke.EstimateOnlyResult without importing llm_invoke eagerly."""
return (
exception.__class__.__name__ == "EstimateOnlyResult"
and isinstance(getattr(exception, "estimate", None), dict)
)
def _estimate_result_tuple(exception: Exception) -> Tuple[Dict[str, Any], float, str]:
"""Convert EstimateOnlyResult into the normal command return tuple."""
payload = getattr(exception, "payload", None) or getattr(exception, "estimate", {})
model = str(payload.get("model") or "unknown") if isinstance(payload, dict) else "unknown"
return payload, 0.0, model
def _strip_prompt_language_suffix(path: Path) -> Optional[str]:
stem = path.stem
for suffix in _prompt_target_extensions(path):
if stem.endswith(suffix):
return stem[: -len(suffix)]
return None
def _prompt_target_extensions(path: Path) -> Dict[str, str]:
return {
"_python": ".py",
"_Python": ".py",
"_typescript": ".ts",
"_TypeScript": ".ts",
"_typescriptreact": ".tsx",
"_TypeScriptReact": ".tsx",
"_javascript": ".js",
"_JavaScript": ".js",
}
def _estimate_output_path_hint(prompt_file: Optional[str], output: Optional[str]) -> Optional[str]:
"""Best-effort existing target file hint for output-token estimation."""
if output:
output_path = Path(output)
if output_path.is_file():
return str(output_path)
if not prompt_file:
return None

Xet Storage Details

Size:
41.7 kB
·
Xet hash:
a79eb8bb83605354a6e6b7178a33168896f8d5ab2750ed5d66b497a1f4ddd200

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.