Buckets:

download
raw
175 kB
""" Unit tests for architecture_sync module. Tests bidirectional sync between architecture.json and prompt file metadata tags. """ import hashlib import inspect import json import tempfile import textwrap from pathlib import Path import pytest from pdd.architecture_sync import ( _contract_summary_is_empty, _extract_contract_summary, _find_renamed_prompt_file, _infer_filepath, _infer_module_tags, _resolve_sync_paths, filepath_to_prompt_filename, generate_tags_from_architecture, get_architecture_entry_for_prompt, has_pdd_tags, normalize_architecture_filenames, parse_prompt_tags, register_untracked_prompts, sync_prompts_to_architecture, sync_all_prompts_to_architecture, update_architecture_from_prompt, validate_dependencies, validate_architecture_modules, validate_interface_structure, ) def _repository_architecture_entry(filename: str) -> dict: """Return a real repository architecture entry for prompt-contract checks.""" repo_root = Path(__file__).resolve().parent.parent entries = json.loads((repo_root / "architecture.json").read_text(encoding="utf-8")) return next(entry for entry in entries if entry["filename"] == filename) def test_mock_contract_validation_real_prompt_interface_is_parseable(): """XML-safe memory sentinels must preserve the real security gate contract.""" repo_root = Path(__file__).resolve().parent.parent prompt = repo_root / "pdd" / "prompts" / "mock_contract_validation_python.prompt" tags = parse_prompt_tags(prompt.read_text(encoding="utf-8")) assert "interface_parse_error" not in tags assert tags["interface"] is not None signatures = { function["name"]: function["signature"] for function in tags["interface"]["module"]["functions"] } assert "source_path: str = '<memory>'" in signatures["extract_query_fields"] assert "source_path: str = '<memory>'" in signatures["extract_mock_fields"] assert _repository_architecture_entry("mock_contract_validation_python.prompt")["interface"] == tags["interface"] def test_sync_orchestration_real_prompt_contract_matches_runtime(): """The orchestration prompt and architecture expose only runtime arguments.""" from pdd.sync_orchestration import sync_orchestration repo_root = Path(__file__).resolve().parent.parent prompt = repo_root / "pdd" / "prompts" / "sync_orchestration_python.prompt" tags = parse_prompt_tags(prompt.read_text(encoding="utf-8")) declared_signature = tags["interface"]["module"]["functions"][0]["signature"] runtime_parameters = list(inspect.signature(sync_orchestration).parameters) assert "one_session" not in declared_signature assert "one_session" not in runtime_parameters assert runtime_parameters[-2:] == ["compressed_context", "fresh"] architecture_signature = _repository_architecture_entry( "sync_orchestration_python.prompt" )["interface"]["module"]["functions"][0]["signature"] assert "one_session" not in architecture_signature assert architecture_signature.endswith( "compressed_context: bool = False, fresh: bool = False) -> Dict[str, Any]" ) # --- Test parse_prompt_tags --- def test_parse_tags_with_all_fields(): """Test parsing prompt with reason, interface, and dependencies.""" content = """ <pdd-reason>Provides unified LLM invocation</pdd-reason> <pdd-interface> { "type": "module", "module": { "functions": [ {"name": "llm_invoke", "signature": "(...)", "returns": "Dict"} ] } } </pdd-interface> <pdd-dependency>path_resolution_python.prompt</pdd-dependency> <pdd-dependency>construct_paths_python.prompt</pdd-dependency> % Rest of prompt content... """ result = parse_prompt_tags(content) assert result['reason'] == 'Provides unified LLM invocation' assert result['interface'] is not None assert result['interface']['type'] == 'module' assert len(result['interface']['module']['functions']) == 1 assert result['dependencies'] == [ 'path_resolution_python.prompt', 'construct_paths_python.prompt' ] def test_include_query_extractor_prompt_metadata_tags_parse(): """Regression for malformed closing tags generated in prompt metadata.""" repo_root = Path(__file__).resolve().parent.parent prompt_path = repo_root / "pdd" / "prompts" / "include_query_extractor_python.prompt" result = parse_prompt_tags(prompt_path.read_text(encoding="utf-8")) assert result['reason'] == ( "Handles semantic extraction from files using LLMs with persistent caching " "for reproducibility." ) assert result['interface'] is not None assert result['interface']['type'] == 'module' assert 'interface_parse_error' not in result assert result['dependencies'] == [ 'llm_invoke_python.prompt', 'load_prompt_template_python.prompt', 'preprocess_python.prompt', 'path_resolution_python.prompt', ] def test_user_story_tests_architecture_metadata_matches_prompt(): """Architecture metadata must not keep stale duplicate user_story_tests entries.""" repo_root = Path(__file__).resolve().parent.parent prompt_path = repo_root / "pdd" / "prompts" / "user_story_tests_python.prompt" architecture_path = repo_root / "architecture.json" prompt_tags = parse_prompt_tags(prompt_path.read_text(encoding="utf-8")) prompt_functions = { fn["name"]: fn for fn in prompt_tags["interface"]["module"]["functions"] if fn["name"] in { "generate_user_story", "run_user_story_tests", "run_user_story_fix", } } architecture = json.loads(architecture_path.read_text(encoding="utf-8")) entries = [ entry for entry in architecture if entry.get("filename") == "user_story_tests_python.prompt" and entry.get("filepath") == "pdd/user_story_tests.py" ] assert len(entries) == 1 arch_functions = { fn["name"]: fn for fn in entries[0]["interface"]["module"]["functions"] if fn["name"] in prompt_functions } assert arch_functions == prompt_functions def test_parse_tags_lenient_missing_fields(): """Test lenient parsing with missing tags (only reason present).""" content = """ <pdd-reason>Only reason tag present</pdd-reason> % Rest of prompt without interface or dependencies """ result = parse_prompt_tags(content) assert result['reason'] == 'Only reason tag present' assert result['interface'] is None assert result['dependencies'] == [] def test_parse_tags_only_dependencies(): """Test parsing with only dependency tags.""" content = """ <pdd-dependency>dep1.prompt</pdd-dependency> <pdd-dependency>dep2.prompt</pdd-dependency> """ result = parse_prompt_tags(content) assert result['reason'] is None assert result['interface'] is None assert result['dependencies'] == ['dep1.prompt', 'dep2.prompt'] def test_parse_tags_accepts_bare_basename_dependency(): """Bare basename dependency tags are kept for later architecture normalization.""" content = "<pdd-dependency>api</pdd-dependency>" result = parse_prompt_tags(content) assert result['dependencies'] == ['api'] def test_parse_tags_after_yaml_front_matter(): """PDD metadata immediately after YAML front matter should be parsed.""" content = """--- name: pdd/example language: Python --- <pdd-dependency>dep1.prompt</pdd-dependency> <pdd-reason>Front matter prompt</pdd-reason> # Role Prompt body. """ result = parse_prompt_tags(content) assert result['reason'] == 'Front matter prompt' assert result['dependencies'] == ['dep1.prompt'] assert result['has_dependency_tags'] is True def test_parse_tags_malformed_xml(): """Test lenient parsing with malformed XML (unclosed tag).""" content = "<pdd-reason>Unclosed tag without ending" result = parse_prompt_tags(content) # Lenient parser (recover=True) actually extracts content from malformed XML # This is better than returning None - it extracts what it can assert result['reason'] == 'Unclosed tag without ending' assert result['interface'] is None assert result['dependencies'] == [] def test_parse_tags_invalid_json_in_interface(): """Test lenient parsing with invalid JSON in interface tag.""" content = """ <pdd-reason>Valid reason</pdd-reason> <pdd-interface> {invalid json here, missing quotes} </pdd-interface> """ result = parse_prompt_tags(content) # Reason should parse, interface should be None (lenient) assert result['reason'] == 'Valid reason' assert result['interface'] is None assert result['dependencies'] == [] def test_parse_tags_after_leading_percent_preamble(): """Leading % prompt prose must not hide real PDD tags that follow.""" content = """% You are an expert TypeScript engineer. <pdd-reason>Reason after leading percent line</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": []}}</pdd-interface> <pdd-dependency>types_TypeScript.prompt</pdd-dependency> % Requirements """ result = parse_prompt_tags(content) assert result["reason"] == "Reason after leading percent line" assert result["interface"] is not None assert result["interface"]["type"] == "module" assert result["dependencies"] == ["types_TypeScript.prompt"] def test_parse_tags_after_multiple_percent_and_blank_preamble_lines(): """Multiple leading %/blank lines before tags should still parse correctly.""" content = """% First preamble line % Second preamble line <pdd-reason>Still visible</pdd-reason> <pdd-dependency>dep.prompt</pdd-dependency> % Body """ result = parse_prompt_tags(content) assert result["reason"] == "Still visible" assert result["dependencies"] == ["dep.prompt"] def test_parse_tags_after_leading_include_header(): """Leading XML-style include lines before the first real tag must remain parseable.""" content = """<include>context/python_preamble.prompt</include> <pdd-reason>Reason after include header</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": []}}</pdd-interface> <pdd-dependency>dep.prompt</pdd-dependency> % Body """ result = parse_prompt_tags(content) assert result["reason"] == "Reason after include header" assert result["interface"] is not None assert result["interface"]["type"] == "module" assert result["dependencies"] == ["dep.prompt"] def test_parse_tags_after_leading_erb_comment_header(): """Leading ERB-style prompt comments must not hide real PDD metadata tags.""" content = """<%-- NOTE: multi-line prompt comment before metadata tags. --%> <pdd-reason>Reason after ERB comment</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": []}}</pdd-interface> <pdd-dependency>dep.prompt</pdd-dependency> % Body """ result = parse_prompt_tags(content) assert result["reason"] == "Reason after ERB comment" assert result["interface"] is not None assert result["interface"]["type"] == "module" assert result["dependencies"] == ["dep.prompt"] def test_validate_architecture_modules_returns_route_shaped_result(): """Validation helper should produce the same dict shape the route exposes.""" modules = [ { "filename": "core_python.prompt", "filepath": "core.py", "description": "Core module", "reason": "Handles core logic", "dependencies": ["dep_python.prompt"], "priority": 1, }, { "filename": "dep_python.prompt", "filepath": "dep.py", "description": "Dependency module", "reason": "Supports core logic", "dependencies": [], "priority": 2, }, ] result = validate_architecture_modules(modules) assert result == { "valid": True, "errors": [], "warnings": [], } def test_agentic_architecture_primary_workflow_dependency_chain_is_registered(): """Every primary Step 1-13 prompt must satisfy architecture dependencies.""" architecture_path = Path(__file__).resolve().parents[1] / "architecture.json" modules = json.loads(architecture_path.read_text(encoding="utf-8")) filenames = [ "agentic_arch_step1_analyze_prd_LLM.prompt", "agentic_arch_step2_analyze_LLM.prompt", "agentic_arch_step3_research_LLM.prompt", "agentic_arch_step4_data_model_LLM.prompt", "agentic_arch_step5_design_LLM.prompt", "agentic_arch_step6_research_deps_LLM.prompt", "agentic_arch_step7_generate_LLM.prompt", "agentic_arch_step8_pddrc_LLM.prompt", "agentic_arch_step9_prompts_LLM.prompt", "agentic_arch_step10_completeness_LLM.prompt", "agentic_arch_step11_sync_LLM.prompt", "agentic_arch_step12_deps_LLM.prompt", "agentic_arch_step13_fix_LLM.prompt", ] workflow = { module["filename"]: module for module in modules if module.get("filename") in filenames } assert set(workflow) == set(filenames) assert validate_architecture_modules(list(workflow.values())) == { "valid": True, "errors": [], "warnings": [], } def test_shared_python_preamble_is_registered_architecture_context(): """A real shared context include must not become a missing module edge.""" root = Path(__file__).resolve().parents[1] modules = json.loads((root / "architecture.json").read_text(encoding="utf-8")) preamble = next( module for module in modules if module.get("filename") == "context/python_preamble.prompt" ) assert preamble["filepath"] == "context/python_preamble.prompt" assert (root / preamble["filepath"]).is_file() assert preamble["interface"] == {"type": "config", "config": {"keys": []}} assert not any( error["type"] == "missing_dependency" and "context/python_preamble.prompt" in error["modules"] for error in validate_architecture_modules(modules)["errors"] ) def _registered_external_context_template() -> dict: """Return the single immutable architecture row for the shared preamble.""" return { "reason": "Provides shared Python generation conventions for prompt templates.", "description": ( "Human-maintained context template included by Python prompt modules to " "define package, typing, import, error-handling, and preservation conventions." ), "dependencies": [], "priority": 98, "filename": "context/python_preamble.prompt", "filepath": "context/python_preamble.prompt", "tags": ["config", "context", "python", "template"], "interface": {"type": "config", "config": {"keys": []}}, } def test_sync_all_skips_registered_external_context_templates(tmp_path): """The exact preamble include needs no prompts-root shadow copy.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() architecture_path = tmp_path / "architecture.json" architecture_path.write_text( json.dumps( [_registered_external_context_template()] ), encoding="utf-8", ) result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=architecture_path, dry_run=True, ) assert result["success"] is True assert result["errors"] == [] assert result["skipped_count"] == 1 @pytest.mark.parametrize( ("field", "value"), ( ("filename", "context/missing.prompt"), ("filename", "context/../prompts/escape.prompt"), ("filepath", "context/missing.prompt"), ("description", "Mutated context metadata"), ("tags", ["config", "context", "python"]), ("interface", {"type": "config", "config": {"keys": ["mutated"]}}), ), ) def test_external_context_exception_rejects_noncanonical_or_mutated_rows( tmp_path, field, value ): """Only the exact registered preamble row may skip generated-prompt sync.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() architecture_path = tmp_path / "architecture.json" context = _registered_external_context_template() context[field] = value architecture_path.write_text(json.dumps([context]), encoding="utf-8") validation = validate_architecture_modules([context]) result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=architecture_path, dry_run=True, ) assert validation["valid"] is False assert any( error["type"] == "invalid_external_context_template" for error in validation["errors"] ) assert result["success"] is False assert result["skipped_count"] == 0 assert result["errors"] def test_sync_prompts_to_architecture_updates_selected_prompts_and_validates(tmp_path): """Single-prompt sync should normalize prompt paths, write changes, and validate.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() architecture_path = tmp_path / "architecture.json" (prompts_dir / "core_python.prompt").write_text( "\n".join( [ "<pdd-reason>New core reason</pdd-reason>", "<pdd-dependency>dep_python.prompt</pdd-dependency>", ] ), encoding="utf-8", ) architecture_path.write_text( json.dumps( [ { "filename": "core_python.prompt", "filepath": "core.py", "description": "Core module", "reason": "Old reason", "dependencies": [], "priority": 1, }, { "filename": "dep_python.prompt", "filepath": "dep.py", "description": "Dependency module", "reason": "Dependency reason", "dependencies": [], "priority": 2, }, ] ), encoding="utf-8", ) result = sync_prompts_to_architecture( filenames=["prompts/core_python.prompt"], prompts_dir=prompts_dir, architecture_path=architecture_path, dry_run=False, ) updated_arch = json.loads(architecture_path.read_text(encoding="utf-8")) assert result["success"] is True assert result["updated_count"] == 1 assert result["skipped_count"] == 0 assert result["validation"]["valid"] is True assert result["errors"] == [] assert updated_arch[0]["reason"] == "New core reason" assert updated_arch[0]["dependencies"] == ["dep_python.prompt"] def test_sync_prompts_to_architecture_normalizes_basename_dependency_tags(tmp_path): """Path-aware architecture sync should resolve stale basename dependency tags.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() (prompts_dir / "src").mkdir() architecture_path = tmp_path / "architecture.json" (prompts_dir / "src" / "worker_app_Python.prompt").write_text( "\n".join( [ "<pdd-reason>Worker app</pdd-reason>", "<pdd-dependency>config_python.prompt</pdd-dependency>", "<pdd-dependency>services/lifecycle_Python.prompt</pdd-dependency>", ] ), encoding="utf-8", ) architecture_path.write_text( json.dumps( [ { "filename": "src/worker_app_Python.prompt", "filepath": "src/worker_app.py", "description": "Worker app", "reason": "Old", "dependencies": [], "priority": 1, }, { "filename": "src/config_Python.prompt", "filepath": "src/config.py", "description": "Config", "reason": "Config", "dependencies": [], "priority": 2, }, { "filename": "src/services/lifecycle_Python.prompt", "filepath": "src/services/lifecycle.py", "description": "Lifecycle", "reason": "Lifecycle", "dependencies": [], "priority": 3, }, ] ), encoding="utf-8", ) result = sync_prompts_to_architecture( filenames=["src/worker_app_Python.prompt"], prompts_dir=prompts_dir, architecture_path=architecture_path, dry_run=False, ) updated_arch = json.loads(architecture_path.read_text(encoding="utf-8")) assert result["success"] is True assert result["validation"]["valid"] is True assert updated_arch[0]["dependencies"] == [ "src/config_Python.prompt", "src/services/lifecycle_Python.prompt", ] def test_update_architecture_from_prompt_normalizes_bare_dependency_tag(tmp_path): """Bare dependency tags should resolve instead of clearing existing deps.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() architecture_path = tmp_path / "architecture.json" (prompts_dir / "app_python.prompt").write_text( "<pdd-dependency>api</pdd-dependency>", encoding="utf-8", ) architecture_path.write_text( json.dumps( [ { "filename": "app_python.prompt", "filepath": "pdd/app.py", "description": "App", "reason": "App", "dependencies": ["api_python.prompt"], "priority": 1, }, { "filename": "api_python.prompt", "filepath": "pdd/api.py", "description": "API", "reason": "API", "dependencies": [], "priority": 2, }, ] ), encoding="utf-8", ) result = update_architecture_from_prompt( "app_python.prompt", prompts_dir=prompts_dir, architecture_path=architecture_path, dry_run=False, ) updated_arch = json.loads(architecture_path.read_text(encoding="utf-8")) assert result["success"] is True assert updated_arch[0]["dependencies"] == ["api_python.prompt"] def test_sync_prompts_to_architecture_dry_run_preserves_architecture_file(tmp_path): """Dry-run should report changes without rewriting architecture.json.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() architecture_path = tmp_path / "architecture.json" (prompts_dir / "core_python.prompt").write_text( "<pdd-reason>Changed in dry run</pdd-reason>", encoding="utf-8", ) original_architecture = json.dumps( [ { "filename": "core_python.prompt", "filepath": "core.py", "description": "Core module", "reason": "Original reason", "dependencies": [], "priority": 1, } ] ) architecture_path.write_text(original_architecture, encoding="utf-8") result = sync_prompts_to_architecture( filenames=["core_python.prompt"], prompts_dir=prompts_dir, architecture_path=architecture_path, dry_run=True, ) assert result["success"] is True assert result["updated_count"] == 1 assert result["validation"]["valid"] is True assert architecture_path.read_text(encoding="utf-8") == original_architecture def test_sync_prompts_to_architecture_reports_sync_errors_without_crashing(tmp_path): """Missing prompt files should be surfaced in the shared result structure.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() architecture_path = tmp_path / "architecture.json" architecture_path.write_text( json.dumps( [ { "filename": "core_python.prompt", "filepath": "core.py", "description": "Core module", "reason": "Core reason", "dependencies": [], "priority": 1, } ] ), encoding="utf-8", ) result = sync_prompts_to_architecture( filenames=["missing_python.prompt"], prompts_dir=prompts_dir, architecture_path=architecture_path, dry_run=False, ) assert result["success"] is False assert result["updated_count"] == 0 assert result["validation"]["valid"] is True assert result["errors"] == [ "missing_python.prompt: Prompt file not found: missing_python.prompt" ] def test_update_architecture_from_prompt_parses_tags_after_leading_percent_preamble(tmp_path): """Architecture sync should update entries when prompts start with % preamble lines.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() architecture_path = tmp_path / "architecture.json" (prompts_dir / "lib_db_TypeScript.prompt").write_text( """% You are an expert TypeScript engineer. <pdd-reason>Updated from prompt tags</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": [{"name": "getDb", "signature": "(): Database", "returns": "db"}]}}</pdd-interface> <pdd-dependency>types_TypeScript.prompt</pdd-dependency> % Body """, encoding="utf-8", ) architecture_path.write_text( json.dumps( [ { "filename": "lib_db_TypeScript.prompt", "filepath": "lib/db.ts", "description": "db", "reason": "Old reason", "dependencies": [], "priority": 1, } ] ), encoding="utf-8", ) result = update_architecture_from_prompt( "lib_db_TypeScript.prompt", prompts_dir=prompts_dir, architecture_path=architecture_path, dry_run=True, ) assert result["success"] is True assert result["updated"] is True assert result["changes"]["reason"]["new"] == "Updated from prompt tags" assert result["changes"]["dependencies"]["new"] == ["types_TypeScript.prompt"] def test_update_architecture_from_prompt_parses_tags_after_leading_include_header(tmp_path): """Architecture sync should update entries when prompts start with include headers.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() architecture_path = tmp_path / "architecture.json" (prompts_dir / "agentic_split_python.prompt").write_text( """<include>context/python_preamble.prompt</include> <pdd-reason>Updated from include-first prompt tags</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": [{"name": "run_agentic_split", "signature": "(target_file)", "returns": "tuple"}]}}</pdd-interface> <pdd-dependency>agentic_split_orchestrator_python.prompt</pdd-dependency> % Body """, encoding="utf-8", ) architecture_path.write_text( json.dumps( [ { "filename": "agentic_split_python.prompt", "filepath": "pdd/agentic_split.py", "description": "agentic split", "reason": "Old reason", "dependencies": [], "priority": 1, } ] ), encoding="utf-8", ) result = update_architecture_from_prompt( "agentic_split_python.prompt", prompts_dir=prompts_dir, architecture_path=architecture_path, dry_run=True, ) assert result["success"] is True assert result["updated"] is True assert result["changes"]["reason"]["new"] == "Updated from include-first prompt tags" assert result["changes"]["dependencies"]["new"] == [ "agentic_split_orchestrator_python.prompt" ] def test_sync_prompts_to_architecture_prefers_nearest_cwd_project(tmp_path, monkeypatch): """Default path resolution should target the nearest ancestor with prompts/architecture.""" repo_root = tmp_path / "repo" repo_root.mkdir() (repo_root / ".git").mkdir() root_prompts = repo_root / "prompts" root_prompts.mkdir() (root_prompts / "root_python.prompt").write_text( "<pdd-reason>Updated root reason</pdd-reason>", encoding="utf-8", ) (repo_root / "architecture.json").write_text( json.dumps( [ { "filename": "root_python.prompt", "filepath": "root.py", "description": "Root module", "reason": "Original root reason", "dependencies": [], "priority": 1, } ] ), encoding="utf-8", ) nested_root = repo_root / "apps" / "nested" nested_root.mkdir(parents=True) nested_prompts = nested_root / "prompts" nested_prompts.mkdir() (nested_prompts / "nested_python.prompt").write_text( "<pdd-reason>Updated nested reason</pdd-reason>", encoding="utf-8", ) (nested_root / "architecture.json").write_text( json.dumps( [ { "filename": "nested_python.prompt", "filepath": "nested.py", "description": "Nested module", "reason": "Original nested reason", "dependencies": [], "priority": 1, } ] ), encoding="utf-8", ) monkeypatch.chdir(nested_root) result = sync_prompts_to_architecture(dry_run=False) root_arch = json.loads((repo_root / "architecture.json").read_text(encoding="utf-8")) nested_arch = json.loads((nested_root / "architecture.json").read_text(encoding="utf-8")) assert result["success"] is True assert result["updated_count"] == 1 assert root_arch[0]["reason"] == "Original root reason" assert nested_arch[0]["reason"] == "Updated nested reason" def test_resolve_sync_paths_uses_nested_architecture_with_ancestor_prompts(tmp_path, monkeypatch): """Nested architecture.json files can use an ancestor prompts directory.""" repo_root = tmp_path / "repo" backend = repo_root / "backend" / "functions" (repo_root / ".git").mkdir(parents=True) (repo_root / "prompts").mkdir() backend.mkdir(parents=True) (backend / "architecture.json").write_text("[]", encoding="utf-8") monkeypatch.chdir(backend) prompts_dir, architecture_path = _resolve_sync_paths(None, None) assert prompts_dir.resolve() == (repo_root / "prompts").resolve() assert architecture_path.resolve() == (backend / "architecture.json").resolve() def test_nested_sync_architecture_scopes_ancestor_prompt_registration(tmp_path, monkeypatch): """No-arg nested sync must not auto-register unrelated ancestor prompts.""" repo_root = tmp_path / "repo" backend = repo_root / "backend" / "functions" prompts_dir = repo_root / "prompts" (repo_root / ".git").mkdir(parents=True) backend.mkdir(parents=True) (prompts_dir / "backend").mkdir(parents=True) (prompts_dir / "unrelated_python.prompt").write_text( "<pdd-reason>Unrelated module</pdd-reason>", encoding="utf-8", ) (prompts_dir / "backend" / "worker_python.prompt").write_text( "<pdd-reason>Updated backend worker</pdd-reason>", encoding="utf-8", ) architecture_path = backend / "architecture.json" architecture_path.write_text( json.dumps( [ { "filename": "backend/worker_python.prompt", "filepath": "worker.py", "description": "Backend worker", "reason": "Old backend worker", "dependencies": [], "priority": 1, } ] ), encoding="utf-8", ) monkeypatch.chdir(backend) result = sync_prompts_to_architecture(dry_run=False) arch_data = json.loads(architecture_path.read_text(encoding="utf-8")) assert result["success"] is True assert result["updated_count"] == 1 assert result["registered"] == [] assert [module["filename"] for module in arch_data] == [ "backend/worker_python.prompt" ] assert arch_data[0]["reason"] == "Updated backend worker" def test_sync_prompts_to_architecture_dry_run_reports_registrations(tmp_path, monkeypatch): """Dry-run should expose prompt registrations that a real run would write.""" (tmp_path / ".git").mkdir() prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() (prompts_dir / "new_python.prompt").write_text( "<pdd-reason>New module</pdd-reason>", encoding="utf-8", ) (tmp_path / "architecture.json").write_text("[]", encoding="utf-8") monkeypatch.chdir(tmp_path) result = sync_prompts_to_architecture(dry_run=True) assert result["success"] is True assert result["registered"] == ["new_python.prompt"] def test_resolve_sync_paths_does_not_escape_nested_project_root(tmp_path, monkeypatch): """A nested project without prompts/ must not borrow a parent project's prompts.""" outer = tmp_path / "outer" inner = outer / "inner" outer.mkdir() inner.mkdir() (outer / "prompts").mkdir() (outer / "architecture.json").write_text("[]", encoding="utf-8") (inner / ".git").mkdir() (inner / "architecture.json").write_text("[]", encoding="utf-8") monkeypatch.chdir(inner) prompts_dir, architecture_path = _resolve_sync_paths(None, None) assert prompts_dir.resolve() == (inner / "prompts").resolve() assert architecture_path.resolve() == (inner / "architecture.json").resolve() def test_sync_prompts_to_architecture_falls_back_to_repo_root_from_nested_cwd(tmp_path, monkeypatch): """If no nearer prompts/architecture exist, default resolution should fall back to repo root.""" repo_root = tmp_path / "repo" repo_root.mkdir() (repo_root / ".git").mkdir() root_prompts = repo_root / "prompts" root_prompts.mkdir() (root_prompts / "root_python.prompt").write_text( "<pdd-reason>Updated root reason</pdd-reason>", encoding="utf-8", ) (repo_root / "architecture.json").write_text( json.dumps( [ { "filename": "root_python.prompt", "filepath": "root.py", "description": "Root module", "reason": "Original root reason", "dependencies": [], "priority": 1, } ] ), encoding="utf-8", ) nested_cwd = repo_root / "apps" / "nested" / "src" nested_cwd.mkdir(parents=True) monkeypatch.chdir(nested_cwd) result = sync_prompts_to_architecture(dry_run=False) root_arch = json.loads((repo_root / "architecture.json").read_text(encoding="utf-8")) assert result["success"] is True assert result["updated_count"] == 1 assert root_arch[0]["reason"] == "Updated root reason" def test_parse_tags_double_brace_escaped_json(): """Test parsing interface with double-brace escaping (used in LLM prompts for Python .format()).""" content = """ <pdd-reason>Fixes validation errors in architecture.json</pdd-reason> <pdd-interface> {{ "type": "module", "module": {{ "functions": [ {{"name": "fix_architecture", "signature": "(current_architecture: str, step7_output: str)", "returns": "str"}} ] }} }} </pdd-interface> <pdd-dependency>agentic_arch_step7_validate_LLM.prompt</pdd-dependency> """ result = parse_prompt_tags(content) # Should successfully parse double-brace escaped JSON assert result['reason'] == 'Fixes validation errors in architecture.json' assert result['interface'] is not None assert result['interface']['type'] == 'module' assert result['interface']['module']['functions'][0]['name'] == 'fix_architecture' assert result['dependencies'] == ['agentic_arch_step7_validate_LLM.prompt'] assert result.get('interface_parse_error') is None def test_parse_tags_empty_content(): """Test parsing empty content.""" result = parse_prompt_tags("") assert result['reason'] is None assert result['interface'] is None assert result['dependencies'] == [] def test_parse_tags_no_pdd_tags(): """Test parsing content without any PDD tags.""" content = """ % This is a regular prompt file % with no PDD metadata tags Your goal is to implement... """ result = parse_prompt_tags(content) assert result['reason'] is None assert result['interface'] is None assert result['dependencies'] == [] # --- Test update_architecture_from_prompt --- def test_update_architecture_from_prompt_success(): """Test successful update of architecture entry from prompt.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # Create test prompt file with tags prompt_file = prompts_dir / "test_module_python.prompt" prompt_file.write_text(""" <pdd-reason>Updated reason from prompt</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": []}}</pdd-interface> <pdd-dependency>dependency1.prompt</pdd-dependency> """) # Create test architecture.json arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "test_module_python.prompt", "filepath": "pdd/test_module.py", "reason": "Old reason", "description": "Test module", "dependencies": [], "priority": 1, "tags": ["module"], "interface": None } ] arch_file.write_text(json.dumps(arch_data, indent=2)) # Update from prompt result = update_architecture_from_prompt( "test_module_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False ) # Check result assert result['success'] is True assert result['updated'] is True assert 'reason' in result['changes'] assert result['changes']['reason']['old'] == 'Old reason' assert result['changes']['reason']['new'] == 'Updated reason from prompt' # Verify architecture.json was updated updated_arch = json.loads(arch_file.read_text()) assert updated_arch[0]['reason'] == 'Updated reason from prompt' assert updated_arch[0]['interface'] == {"type": "module", "module": {"functions": []}} assert updated_arch[0]['dependencies'] == ['dependency1.prompt'] def test_update_architecture_from_prompt_dry_run(): """Test dry run mode doesn't write to architecture.json.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() prompt_file = prompts_dir / "test_module_python.prompt" prompt_file.write_text("<pdd-reason>New reason</pdd-reason>") arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "test_module_python.prompt", "filepath": "pdd/test.py", "reason": "Old reason", "description": "Test", "dependencies": [], "priority": 1, "tags": [] } ] original_content = json.dumps(arch_data, indent=2) arch_file.write_text(original_content) # Dry run result = update_architecture_from_prompt( "test_module_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=True ) assert result['success'] is True assert result['updated'] is True # Verify architecture.json NOT modified assert arch_file.read_text() == original_content def test_update_architecture_from_prompt_missing_file(): """Test error when prompt file doesn't exist.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" arch_file.write_text("[]") result = update_architecture_from_prompt( "nonexistent.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['success'] is False assert 'not found' in result['error'].lower() def test_update_architecture_from_prompt_no_entry(): """Test error when no architecture entry exists for prompt.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() prompt_file = prompts_dir / "orphan.prompt" prompt_file.write_text("<pdd-reason>Test</pdd-reason>") arch_file = tmppath / "architecture.json" arch_file.write_text("[]") # Empty architecture result = update_architecture_from_prompt( "orphan.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['success'] is False assert 'no architecture entry' in result['error'].lower() def test_sync_preserves_other_fields(): """Test that sync only updates specified fields (reason, interface, dependencies).""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() prompt_file = prompts_dir / "test.prompt" prompt_file.write_text("<pdd-reason>Updated reason</pdd-reason>") arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "test.prompt", "filepath": "pdd/test.py", "reason": "Old reason", "description": "Original description", "dependencies": [], "priority": 42, "tags": ["module", "python"], "interface": None } ] arch_file.write_text(json.dumps(arch_data, indent=2)) # Update update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) # Verify other fields preserved updated = json.loads(arch_file.read_text()) assert updated[0]['filename'] == "test.prompt" assert updated[0]['filepath'] == "pdd/test.py" assert updated[0]['description'] == "Original description" assert updated[0]['priority'] == 42 assert updated[0]['tags'] == ["module", "python"] # --- Test sync_all_prompts_to_architecture --- def test_sync_all_prompts_to_architecture(): """Test syncing all prompts to architecture.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # Create multiple prompts (prompts_dir / "module1.prompt").write_text("<pdd-reason>Module 1</pdd-reason>") (prompts_dir / "module2.prompt").write_text("<pdd-reason>Module 2</pdd-reason>") (prompts_dir / "module3.prompt").write_text("% No tags") # Create architecture arch_file = tmppath / "architecture.json" arch_data = [ {"filename": "module1.prompt", "filepath": "m1.py", "reason": "Old 1", "description": "D1", "dependencies": [], "priority": 1, "tags": []}, {"filename": "module2.prompt", "filepath": "m2.py", "reason": "Old 2", "description": "D2", "dependencies": [], "priority": 2, "tags": []}, {"filename": "module3.prompt", "filepath": "m3.py", "reason": "Old 3", "description": "D3", "dependencies": [], "priority": 3, "tags": []}, ] arch_file.write_text(json.dumps(arch_data, indent=2)) # Sync all result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['success'] is True assert result['updated_count'] == 2 # module1 and module2 have tags assert len(result['results']) == 3 def test_sync_all_prompts_to_architecture_only_files_scopes_update_pass(): """only_files must scope the per-module UPDATE pass, not just registration. Regression for the pre-checkup gate (PR #1327 / issue #1293): passing only_files={touched prompt} must NOT rewrite an unrelated module's architecture.json entry from its prompt, because the gate commits the file and would otherwise sweep repo-wide drift into a feature PR. Greg's exact reproduction: only_files={'a_python.prompt'} updated both a and b before the fix (updated_count == 2). """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # Both prompts carry tags that differ from the stale arch entries, so a # full-scan sync WOULD rewrite both. The scope filter must spare b. (prompts_dir / "a_python.prompt").write_text("<pdd-reason>Fresh A</pdd-reason>") (prompts_dir / "b_python.prompt").write_text("<pdd-reason>Fresh B</pdd-reason>") arch_file = tmppath / "architecture.json" arch_data = [ {"filename": "a_python.prompt", "filepath": "a.py", "reason": "Stale A", "description": "DA", "dependencies": [], "priority": 1, "tags": []}, {"filename": "b_python.prompt", "filepath": "b.py", "reason": "Stale B", "description": "DB", "dependencies": [], "priority": 2, "tags": []}, ] arch_file.write_text(json.dumps(arch_data, indent=2)) b_before = {m["filename"]: m for m in json.loads(arch_file.read_text())}["b_python.prompt"] result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=arch_file, only_files={"a_python.prompt"}, ) assert result["success"] is True # Exactly one module updated — the in-scope one (not "skip everything"). assert result["updated_count"] == 1 synced = {m["filename"]: m for m in json.loads(arch_file.read_text())} # Touched prompt actually synced from its prompt file... assert synced["a_python.prompt"]["reason"] == "Fresh A" # ...and the unrelated entry is left exactly as it was (no leak). assert synced["b_python.prompt"] == b_before assert synced["b_python.prompt"]["reason"] == "Stale B" def test_sync_all_prompts_to_architecture_only_files_none_full_scan(): """only_files=None (default) preserves the full-scan behavior for both prompts.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() (prompts_dir / "a_python.prompt").write_text("<pdd-reason>Fresh A</pdd-reason>") (prompts_dir / "b_python.prompt").write_text("<pdd-reason>Fresh B</pdd-reason>") arch_file = tmppath / "architecture.json" arch_data = [ {"filename": "a_python.prompt", "filepath": "a.py", "reason": "Stale A", "description": "DA", "dependencies": [], "priority": 1, "tags": []}, {"filename": "b_python.prompt", "filepath": "b.py", "reason": "Stale B", "description": "DB", "dependencies": [], "priority": 2, "tags": []}, ] arch_file.write_text(json.dumps(arch_data, indent=2)) result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=arch_file, ) assert result["success"] is True assert result["updated_count"] == 2 synced = {m["filename"]: m for m in json.loads(arch_file.read_text())} assert synced["a_python.prompt"]["reason"] == "Fresh A" assert synced["b_python.prompt"]["reason"] == "Fresh B" # --- Test validate_dependencies --- def test_validate_dependencies_valid(): """Test validation of valid dependencies.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # Create dependency files (prompts_dir / "dep1.prompt").write_text("test") (prompts_dir / "dep2.prompt").write_text("test") result = validate_dependencies( ["dep1.prompt", "dep2.prompt"], prompts_dir=prompts_dir ) assert result['valid'] is True assert result['missing'] == [] assert result['duplicates'] == [] def test_validate_dependencies_missing(): """Test validation detects missing dependencies.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() (prompts_dir / "exists.prompt").write_text("test") result = validate_dependencies( ["exists.prompt", "missing.prompt"], prompts_dir=prompts_dir ) assert result['valid'] is False assert "missing.prompt" in result['missing'] assert "exists.prompt" not in result['missing'] def test_validate_dependencies_duplicates(): """Test validation detects duplicate dependencies.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() (prompts_dir / "dep.prompt").write_text("test") result = validate_dependencies( ["dep.prompt", "dep.prompt", "dep.prompt"], prompts_dir=prompts_dir ) assert result['valid'] is False assert "dep.prompt" in result['duplicates'] # --- Test validate_interface_structure --- def test_validate_interface_structure_module_valid(): """Test validation of valid module interface.""" interface = { "type": "module", "module": { "functions": [ {"name": "func1", "signature": "(...)", "returns": "str"} ] } } result = validate_interface_structure(interface) assert result['valid'] is True assert result['errors'] == [] def test_validate_interface_structure_cli_valid(): """Test validation of valid CLI interface.""" interface = { "type": "cli", "cli": { "commands": [ {"name": "cmd1", "description": "Test command"} ] } } result = validate_interface_structure(interface) assert result['valid'] is True def test_validate_interface_structure_entrypoint_valid(): """Test validation of valid entrypoint interface.""" interface = { "type": "entrypoint", "entrypoint": {}, } result = validate_interface_structure(interface) assert result['valid'] is True assert result['errors'] == [] def test_validate_interface_structure_invalid_type(): """Test validation detects invalid type.""" interface = { "type": "invalid_type", "module": {"functions": []} } result = validate_interface_structure(interface) assert result['valid'] is False assert len(result['errors']) > 0 assert 'invalid type' in result['errors'][0].lower() def test_validate_interface_structure_missing_nested_key(): """Test validation detects missing nested key.""" interface = { "type": "module" # Missing 'module' key } result = validate_interface_structure(interface) assert result['valid'] is False assert any('missing' in err.lower() for err in result['errors']) def test_validate_interface_structure_missing_functions(): """Test validation detects missing functions in module.""" interface = { "type": "module", "module": {} # Missing 'functions' key } result = validate_interface_structure(interface) assert result['valid'] is False assert any('functions' in err.lower() for err in result['errors']) # --- Test helper functions --- def test_has_pdd_tags_with_tags(): """Test detection of PDD tags in content.""" content = """ <pdd-reason>Test</pdd-reason> Rest of content """ assert has_pdd_tags(content) is True def test_has_pdd_tags_no_tags(): """Test detection when no tags present.""" content = "Regular prompt content without tags" assert has_pdd_tags(content) is False def test_get_architecture_entry_for_prompt(): """Test retrieving architecture entry by prompt filename.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) arch_file = tmppath / "architecture.json" arch_data = [ {"filename": "test.prompt", "reason": "Test module"}, {"filename": "other.prompt", "reason": "Other module"} ] arch_file.write_text(json.dumps(arch_data)) entry = get_architecture_entry_for_prompt( "test.prompt", architecture_path=arch_file ) assert entry is not None assert entry['filename'] == "test.prompt" assert entry['reason'] == "Test module" def test_get_architecture_entry_for_prompt_not_found(): """Test retrieving non-existent architecture entry.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) arch_file = tmppath / "architecture.json" arch_file.write_text("[]") entry = get_architecture_entry_for_prompt( "nonexistent.prompt", architecture_path=arch_file ) assert entry is None def test_generate_tags_from_architecture_all_fields(): """Test generating tags from complete architecture entry.""" arch_entry = { "reason": "Test module for validation", "interface": { "type": "module", "module": {"functions": []} }, "dependencies": ["dep1.prompt", "dep2.prompt"] } tags = generate_tags_from_architecture(arch_entry) assert '<pdd-reason>Test module for validation</pdd-reason>' in tags assert '<pdd-interface>' in tags assert '<pdd-dependency>dep1.prompt</pdd-dependency>' in tags assert '<pdd-dependency>dep2.prompt</pdd-dependency>' in tags def test_generate_tags_from_architecture_partial(): """Test generating tags from partial architecture entry.""" arch_entry = { "reason": "Only reason field", "dependencies": [] } tags = generate_tags_from_architecture(arch_entry) assert '<pdd-reason>Only reason field</pdd-reason>' in tags assert '<pdd-interface>' not in tags assert '<pdd-dependency>' not in tags def test_generate_tags_from_architecture_empty(): """Test generating tags from empty architecture entry.""" arch_entry = {} tags = generate_tags_from_architecture(arch_entry) assert tags == "" # --- Test reverse direction (architecture.json → prompt generation) --- def test_reverse_direction_tag_injection(): """Test that tags are injected when generating new prompts.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) # Create architecture.json arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "new_module.prompt", "filepath": "pdd/new_module.py", "reason": "This is a new module", "description": "New module for testing", "dependencies": ["dep1.prompt", "dep2.prompt"], "priority": 1, "tags": ["module"], "interface": { "type": "module", "module": { "functions": [ {"name": "test_func", "signature": "()", "returns": "None"} ] } } }] arch_file.write_text(json.dumps(arch_data, indent=2)) # Simulate prompt generation: create content without tags generated_content = "% New Module Prompt\n\nYour goal is to implement..." # Check that content doesn't have tags assert not has_pdd_tags(generated_content) # Get architecture entry entry = get_architecture_entry_for_prompt( "new_module.prompt", architecture_path=arch_file ) assert entry is not None # Generate tags tags = generate_tags_from_architecture(entry) # Inject tags (simulating what code_generator_main does) final_content = tags + '\n\n' + generated_content # Verify tags were injected assert has_pdd_tags(final_content) assert '<pdd-reason>This is a new module</pdd-reason>' in final_content assert '<pdd-interface>' in final_content assert '<pdd-dependency>dep1.prompt</pdd-dependency>' in final_content assert '<pdd-dependency>dep2.prompt</pdd-dependency>' in final_content # Verify original content is preserved assert 'Your goal is to implement' in final_content def test_reverse_direction_preserve_existing_tags(): """Test that existing tags are NOT overwritten (preserve manual edits).""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) # Create architecture.json with one reason arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "existing.prompt", "filepath": "pdd/existing.py", "reason": "Architecture reason", "description": "Test", "dependencies": [], "priority": 1, "tags": [] }] arch_file.write_text(json.dumps(arch_data, indent=2)) # Content already has manually edited tags existing_content = """<pdd-reason>Manually edited reason</pdd-reason> % Module Prompt Your goal is to implement...""" # Should detect existing tags assert has_pdd_tags(existing_content) # Should NOT inject tags because they already exist entry = get_architecture_entry_for_prompt( "existing.prompt", architecture_path=arch_file ) if not has_pdd_tags(existing_content): tags = generate_tags_from_architecture(entry) final_content = tags + '\n\n' + existing_content else: final_content = existing_content # Verify original tags preserved (not overwritten with architecture.json version) assert '<pdd-reason>Manually edited reason</pdd-reason>' in final_content assert 'Architecture reason' not in final_content def test_reverse_direction_no_architecture_entry(): """Test that no tags are injected if no architecture entry exists.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) # Empty architecture.json arch_file = tmppath / "architecture.json" arch_file.write_text("[]") # Prompt content content = "% Orphan Prompt\n\nNo architecture entry exists..." # Try to get architecture entry entry = get_architecture_entry_for_prompt( "orphan.prompt", architecture_path=arch_file ) assert entry is None # Should not inject any tags if entry and not has_pdd_tags(content): tags = generate_tags_from_architecture(entry) final_content = tags + '\n\n' + content else: final_content = content # Verify no tags added assert not has_pdd_tags(final_content) assert final_content == content def test_reverse_direction_partial_tags(): """Test injection with partial architecture data (only some fields).""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) # Architecture with only reason (no interface or dependencies) arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "partial.prompt", "filepath": "pdd/partial.py", "reason": "Only has reason field", "description": "Test", "dependencies": [], "priority": 1, "tags": [] }] arch_file.write_text(json.dumps(arch_data, indent=2)) # Get entry and generate tags entry = get_architecture_entry_for_prompt( "partial.prompt", architecture_path=arch_file ) tags = generate_tags_from_architecture(entry) # Should only have reason tag assert '<pdd-reason>Only has reason field</pdd-reason>' in tags assert '<pdd-interface>' not in tags assert '<pdd-dependency>' not in tags # --- Test has_dependency_tags flag --- def test_parse_tags_has_dependency_tags_true(): """Test that has_dependency_tags is True when dependency tags are present.""" content = """ <pdd-reason>Test module</pdd-reason> <pdd-dependency>dep1.prompt</pdd-dependency> """ result = parse_prompt_tags(content) assert result['has_dependency_tags'] is True assert result['dependencies'] == ['dep1.prompt'] def test_parse_tags_has_dependency_tags_false(): """Test that has_dependency_tags is False when no dependency tags present.""" content = """ <pdd-reason>Test module</pdd-reason> % No dependency tags here """ result = parse_prompt_tags(content) assert result.get('has_dependency_tags', False) is False assert result['dependencies'] == [] def test_parse_tags_empty_dependency_tag(): """Test that has_dependency_tags is True even for empty dependency tag.""" content = """ <pdd-reason>Test module</pdd-reason> <pdd-dependency></pdd-dependency> """ result = parse_prompt_tags(content) # has_dependency_tags should be True (tag exists even if empty) assert result['has_dependency_tags'] is True # But dependencies list should be empty (no valid content) assert result['dependencies'] == [] # --- Test dependency clearing behavior --- def test_dependencies_preserved_when_no_pdd_dependency_tags(): """architecture.json dependencies are not cleared when prompt has no <pdd-dependency> tags. Reason/interface-only updates must not wipe dependencies (include-based deps may exist). """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() prompt_file = prompts_dir / "test.prompt" prompt_file.write_text(""" <pdd-reason>Updated reason only</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": []}}</pdd-interface> % No pdd-dependency tags """) arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "test.prompt", "filepath": "pdd/test.py", "reason": "Old reason", "description": "Test", "dependencies": ["old_dep1.prompt", "old_dep2.prompt"], "priority": 1, "tags": [] }] arch_file.write_text(json.dumps(arch_data, indent=2)) result = update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['success'] is True assert result['updated'] is True assert 'dependencies' not in result.get('changes', {}) updated = json.loads(arch_file.read_text()) assert updated[0]['dependencies'] == ["old_dep1.prompt", "old_dep2.prompt"] assert updated[0]['reason'] == "Updated reason only" def test_dependencies_cleared_when_empty_pdd_dependency_tags_present(): """Explicit empty <pdd-dependency> tags clear dependencies in architecture.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() prompt_file = prompts_dir / "test.prompt" prompt_file.write_text(""" <pdd-reason>Module with dependencies removed</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": []}}</pdd-interface> <pdd-dependency></pdd-dependency> % Empty dependency tag = user cleared deps """) arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "test.prompt", "filepath": "pdd/test.py", "reason": "Old reason", "description": "Test", "dependencies": ["old_dep1.prompt", "old_dep2.prompt"], "priority": 1, "tags": [] }] arch_file.write_text(json.dumps(arch_data, indent=2)) result = update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['success'] is True assert result['updated'] is True assert 'dependencies' in result['changes'] assert result['changes']['dependencies']['old'] == ['old_dep1.prompt', 'old_dep2.prompt'] assert result['changes']['dependencies']['new'] == [] updated = json.loads(arch_file.read_text()) assert updated[0]['dependencies'] == [] def test_no_dependency_clearing_for_legacy_prompt(): """Test that prompts without ANY PDD tags don't clear dependencies.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # Legacy prompt without ANY PDD tags prompt_file = prompts_dir / "legacy.prompt" prompt_file.write_text(""" % Legacy prompt without PDD tags Your goal is to implement... """) # Architecture has dependencies arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "legacy.prompt", "filepath": "pdd/legacy.py", "reason": "Legacy module", "description": "Test", "dependencies": ["should_not_be_cleared.prompt"], "priority": 1, "tags": [] }] arch_file.write_text(json.dumps(arch_data, indent=2)) # Sync result = update_architecture_from_prompt( "legacy.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) # Verify: no updates (legacy prompt has no PDD tags) assert result['success'] is True assert result['updated'] is False # No changes made assert 'dependencies' not in result['changes'] # Verify architecture.json NOT modified updated = json.loads(arch_file.read_text()) assert updated[0]['dependencies'] == ["should_not_be_cleared.prompt"] def test_dependency_add_and_remove(): """Test adding and removing dependencies in sequence.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" prompt_file = prompts_dir / "test.prompt" # Initial state: no dependencies in architecture arch_data = [{ "filename": "test.prompt", "filepath": "pdd/test.py", "reason": "Test", "description": "Test", "dependencies": [], "priority": 1, "tags": [] }] arch_file.write_text(json.dumps(arch_data, indent=2)) # Step 1: Add dependencies via prompt prompt_file.write_text(""" <pdd-reason>Test</pdd-reason> <pdd-dependency>dep1.prompt</pdd-dependency> <pdd-dependency>dep2.prompt</pdd-dependency> """) result = update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['updated'] is True updated = json.loads(arch_file.read_text()) assert set(updated[0]['dependencies']) == {'dep1.prompt', 'dep2.prompt'} # Step 2: Remove one dependency prompt_file.write_text(""" <pdd-reason>Test</pdd-reason> <pdd-dependency>dep1.prompt</pdd-dependency> """) result = update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['updated'] is True updated = json.loads(arch_file.read_text()) assert updated[0]['dependencies'] == ['dep1.prompt'] # Step 3: Remove ALL dependencies — explicit empty <pdd-dependency> tags prompt_file.write_text(""" <pdd-reason>Test</pdd-reason> <pdd-dependency></pdd-dependency> % Cleared via empty dependency tags """) result = update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['updated'] is True updated = json.loads(arch_file.read_text()) assert updated[0]['dependencies'] == [] # --- Test interface JSON parse error reporting --- def test_interface_parse_error_reported(): """Test that JSON parse errors in interface are reported in warnings.""" content = """ <pdd-reason>Valid reason</pdd-reason> <pdd-interface> {invalid json - missing quotes and colons} </pdd-interface> """ result = parse_prompt_tags(content) assert result['reason'] == 'Valid reason' assert result['interface'] is None # Failed to parse assert 'interface_parse_error' in result assert 'Invalid JSON' in result['interface_parse_error'] def test_interface_parse_error_in_sync_result(): """Test that interface parse errors appear in sync warnings.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # Create prompt with invalid JSON in interface prompt_file = prompts_dir / "test.prompt" prompt_file.write_text(""" <pdd-reason>Valid reason</pdd-reason> <pdd-interface> {this is not valid JSON} </pdd-interface> """) arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "test.prompt", "filepath": "pdd/test.py", "reason": "Old reason", "description": "Test", "dependencies": [], "priority": 1, "tags": [], "interface": {"type": "module", "module": {"functions": []}} }] arch_file.write_text(json.dumps(arch_data, indent=2)) result = update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) # Should succeed but with warnings assert result['success'] is True assert 'warnings' in result assert len(result['warnings']) > 0 assert any('Invalid JSON' in w for w in result['warnings']) # --- Test interface update scenarios --- def test_interface_update_from_none_to_value(): """Test updating interface from None to a value.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() prompt_file = prompts_dir / "test.prompt" prompt_file.write_text(""" <pdd-reason>Test</pdd-reason> <pdd-interface> {"type": "module", "module": {"functions": [{"name": "test", "signature": "()", "returns": "None"}]}} </pdd-interface> """) arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "test.prompt", "filepath": "pdd/test.py", "reason": "Test", "description": "Test", "dependencies": [], "priority": 1, "tags": [], "interface": None # Start with no interface }] arch_file.write_text(json.dumps(arch_data, indent=2)) result = update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['updated'] is True assert 'interface' in result['changes'] assert result['changes']['interface']['old'] is None updated = json.loads(arch_file.read_text()) assert updated[0]['interface'] is not None assert updated[0]['interface']['type'] == 'module' def test_interface_update_changes_detected(): """Test that interface changes are properly detected.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # New interface with additional function prompt_file = prompts_dir / "test.prompt" prompt_file.write_text(""" <pdd-reason>Test</pdd-reason> <pdd-interface> { "type": "module", "module": { "functions": [ {"name": "func1", "signature": "()", "returns": "None"}, {"name": "func2", "signature": "(x: int)", "returns": "int"} ] } } </pdd-interface> """) arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "test.prompt", "filepath": "pdd/test.py", "reason": "Test", "description": "Test", "dependencies": [], "priority": 1, "tags": [], "interface": { "type": "module", "module": { "functions": [ {"name": "func1", "signature": "()", "returns": "None"} ] } } }] arch_file.write_text(json.dumps(arch_data, indent=2)) result = update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['updated'] is True assert 'interface' in result['changes'] updated = json.loads(arch_file.read_text()) funcs = updated[0]['interface']['module']['functions'] assert len(funcs) == 2 assert any(f['name'] == 'func2' for f in funcs) def test_interface_no_update_when_same(): """Test that no update occurs when interface is identical.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() interface_json = {"type": "module", "module": {"functions": []}} prompt_file = prompts_dir / "test.prompt" prompt_file.write_text(f""" <pdd-reason>Same reason</pdd-reason> <pdd-interface> {json.dumps(interface_json)} </pdd-interface> """) arch_file = tmppath / "architecture.json" arch_data = [{ "filename": "test.prompt", "filepath": "pdd/test.py", "reason": "Same reason", "description": "Test", "dependencies": [], "priority": 1, "tags": [], "interface": interface_json }] arch_file.write_text(json.dumps(arch_data, indent=2)) result = update_architecture_from_prompt( "test.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) # No changes should be detected assert result['success'] is True assert result['updated'] is False assert result['changes'] == {} # --- Test edge cases --- def test_whitespace_in_tags(): """Test that whitespace in tags is properly handled.""" content = """ <pdd-reason> Reason with leading and trailing whitespace </pdd-reason> <pdd-dependency> dep1.prompt </pdd-dependency> <pdd-dependency> dep2.prompt </pdd-dependency> """ result = parse_prompt_tags(content) assert result['reason'] == 'Reason with leading and trailing whitespace' assert 'dep1.prompt' in result['dependencies'] assert 'dep2.prompt' in result['dependencies'] def test_special_characters_in_reason(): """Test that special characters in reason are handled.""" content = """ <pdd-reason>Module for &amp; handling "special" <characters></pdd-reason> """ result = parse_prompt_tags(content) # XML entities should be decoded assert result['reason'] is not None assert 'special' in result['reason'] def test_multiline_interface_json(): """Test parsing of multiline prettified JSON in interface.""" content = """ <pdd-interface> { "type": "module", "module": { "functions": [ { "name": "complex_func", "signature": "(arg1: str, arg2: int, arg3: Optional[Dict] = None) -> Tuple[bool, str]", "returns": "Tuple[bool, str]", "sideEffects": [ "Logs to file", "Updates cache", "Sends notification" ] } ] } } </pdd-interface> """ result = parse_prompt_tags(content) assert result['interface'] is not None assert result['interface']['type'] == 'module' funcs = result['interface']['module']['functions'] assert len(funcs) == 1 assert funcs[0]['name'] == 'complex_func' assert len(funcs[0]['sideEffects']) == 3 def test_concurrent_updates_different_modules(): """Test that updating different modules doesn't interfere.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # Create two prompts (prompts_dir / "module1.prompt").write_text("<pdd-reason>Module 1 Updated</pdd-reason>") (prompts_dir / "module2.prompt").write_text("<pdd-reason>Module 2 Updated</pdd-reason>") arch_file = tmppath / "architecture.json" arch_data = [ {"filename": "module1.prompt", "filepath": "m1.py", "reason": "Old 1", "description": "D1", "dependencies": [], "priority": 1, "tags": []}, {"filename": "module2.prompt", "filepath": "m2.py", "reason": "Old 2", "description": "D2", "dependencies": [], "priority": 2, "tags": []}, ] arch_file.write_text(json.dumps(arch_data, indent=2)) # Update module1 result1 = update_architecture_from_prompt( "module1.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) # Update module2 result2 = update_architecture_from_prompt( "module2.prompt", prompts_dir=prompts_dir, architecture_path=arch_file ) assert result1['success'] and result1['updated'] assert result2['success'] and result2['updated'] # Verify both were updated correctly final = json.loads(arch_file.read_text()) m1 = next(m for m in final if m['filename'] == 'module1.prompt') m2 = next(m for m in final if m['filename'] == 'module2.prompt') assert m1['reason'] == 'Module 1 Updated' assert m2['reason'] == 'Module 2 Updated' def test_sync_all_with_mixed_prompts(): """Test sync_all with mix of prompts with and without tags.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # Prompt with all tags (prompts_dir / "full.prompt").write_text(""" <pdd-reason>Full module</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": []}}</pdd-interface> <pdd-dependency>dep.prompt</pdd-dependency> """) # Prompt with only reason (prompts_dir / "partial.prompt").write_text("<pdd-reason>Partial</pdd-reason>") # Prompt with no tags (prompts_dir / "legacy.prompt").write_text("% No tags") # Prompt not in architecture (prompts_dir / "orphan.prompt").write_text("<pdd-reason>Orphan</pdd-reason>") arch_file = tmppath / "architecture.json" arch_data = [ {"filename": "full.prompt", "filepath": "f.py", "reason": "Old", "description": "F", "dependencies": [], "priority": 1, "tags": []}, {"filename": "partial.prompt", "filepath": "p.py", "reason": "Old", "description": "P", "dependencies": ["old_dep.prompt"], "priority": 2, "tags": []}, {"filename": "legacy.prompt", "filepath": "l.py", "reason": "Legacy", "description": "L", "dependencies": ["should_keep.prompt"], "priority": 3, "tags": []}, ] arch_file.write_text(json.dumps(arch_data, indent=2)) result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=arch_file ) assert result['success'] is True final = json.loads(arch_file.read_text()) full = next(m for m in final if m['filename'] == 'full.prompt') partial = next(m for m in final if m['filename'] == 'partial.prompt') legacy = next(m for m in final if m['filename'] == 'legacy.prompt') # Full should have all updates assert full['reason'] == 'Full module' assert full['dependencies'] == ['dep.prompt'] assert full['interface'] is not None # Partial: reason updated; dependencies unchanged (no <pdd-dependency> in prompt) assert partial['reason'] == 'Partial' assert partial['dependencies'] == ['old_dep.prompt'] # Legacy should be unchanged (no PDD tags) assert legacy['reason'] == 'Legacy' assert legacy['dependencies'] == ['should_keep.prompt'] # --- Test JSON trailing comma handling --- def test_interface_json_trailing_comma(): """Test that JSON with trailing comma fails gracefully.""" content = """ <pdd-interface> { "type": "module", "module": { "functions": [ {"name": "func1", "signature": "()", "returns": "None"}, ] } } </pdd-interface> """ result = parse_prompt_tags(content) # Should fail to parse due to trailing comma assert result['interface'] is None assert 'interface_parse_error' in result # --- Regression tests for issue #550: corrupted dependency values --- def test_parse_tags_rejects_multiline_dependency(): """Dependency containing newlines (prompt content blob) must be rejected. Regression for issue #550: pdd change step 10 wrote the entire prompt file content as a dependency string when it confused example tags with real ones. """ corrupted_dep = "` tags:\n - Extract from `<include>` directives\n - Only include .prompt files\nllm_invoke_python.prompt" content = f"<pdd-dependency>{corrupted_dep}</pdd-dependency>" result = parse_prompt_tags(content) assert result['dependencies'] == [], ( "Multiline dependency value should be rejected" ) def test_parse_tags_rejects_dependency_over_100_chars(): """Dependency longer than 100 chars must be rejected. Regression for issue #550: the corrupted value was hundreds of characters long. """ long_dep = "a" * 101 + ".prompt" content = f"<pdd-dependency>{long_dep}</pdd-dependency>" result = parse_prompt_tags(content) assert result['dependencies'] == [], ( "Dependency value over 100 chars should be rejected" ) def test_parse_tags_rejects_dependency_not_ending_in_prompt(): """Dependency not ending in .prompt must be rejected.""" content = "<pdd-dependency>some_python_file.py</pdd-dependency>" result = parse_prompt_tags(content) assert result['dependencies'] == [], ( "Non-.prompt dependency should be rejected" ) def test_parse_tags_accepts_valid_dependency_alongside_corrupted(): """Valid .prompt dependency is kept even when another dep is corrupted. Regression for issue #550: architecture.json had one corrupted dep and one valid dep (path_resolution_python.prompt). The valid one must be preserved. """ corrupted = "` tags:\n - Extract from includes\nllm_invoke_python.prompt" content = ( f"<pdd-dependency>{corrupted}</pdd-dependency>\n" "<pdd-dependency>path_resolution_python.prompt</pdd-dependency>" ) result = parse_prompt_tags(content) assert result['dependencies'] == ['path_resolution_python.prompt'] # --- Regression tests for _sanitize_architecture_dependencies --- def test_sanitize_architecture_dependencies_removes_corrupted_dep(): """_sanitize_architecture_dependencies cleans corrupted deps from architecture.json. Regression for issue #550: after step 10 writes a corrupted dependency, the sanitizer must strip it so Dev Units validation passes. """ import json import tempfile from pathlib import Path from pdd.agentic_change_orchestrator import _sanitize_architecture_dependencies corrupted_dep = "` tags:\n - Extract from `<include>` directives\nllm_invoke_python.prompt" arch_data = [ { "filename": "agentic_change_step10_architecture_update_LLM.prompt", "dependencies": [corrupted_dep, "path_resolution_python.prompt"], } ] with tempfile.TemporaryDirectory() as tmpdir: arch_path = Path(tmpdir) / "architecture.json" arch_path.write_text(json.dumps(arch_data, indent=2)) _sanitize_architecture_dependencies(Path(tmpdir)) result = json.loads(arch_path.read_text()) assert result[0]["dependencies"] == ["path_resolution_python.prompt"] def test_sanitize_architecture_dependencies_leaves_valid_deps_untouched(): """_sanitize_architecture_dependencies must not modify clean architecture.json.""" import json import tempfile from pathlib import Path from pdd.agentic_change_orchestrator import _sanitize_architecture_dependencies arch_data = [ { "filename": "llm_invoke_python.prompt", "dependencies": ["path_resolution_python.prompt", "construct_paths_python.prompt"], } ] with tempfile.TemporaryDirectory() as tmpdir: arch_path = Path(tmpdir) / "architecture.json" arch_path.write_text(json.dumps(arch_data, indent=2)) _sanitize_architecture_dependencies(Path(tmpdir)) result = json.loads(arch_path.read_text()) assert result[0]["dependencies"] == [ "path_resolution_python.prompt", "construct_paths_python.prompt", ] def test_sanitize_architecture_dependencies_no_file_is_noop(): """_sanitize_architecture_dependencies must not crash if no architecture.json.""" import tempfile from pathlib import Path from pdd.agentic_change_orchestrator import _sanitize_architecture_dependencies with tempfile.TemporaryDirectory() as tmpdir: _sanitize_architecture_dependencies(Path(tmpdir)) # should not raise def test_sanitize_architecture_interfaces_preserves_existing_params(): """Step 10 post-check should preserve params dropped by a direct architecture edit.""" from pdd.agentic_change_orchestrator import _sanitize_architecture_interfaces previous_architecture = [ { "filename": "orchestrator_python.prompt", "filepath": "pdd/orchestrator.py", "interface": { "type": "module", "module": { "functions": [ { "name": "run_agentic_e2e_fix_orchestrator", "signature": "(issue_url, issue_content, use_github_state, protect_tests)", "returns": "Dict", } ] }, }, } ] current_architecture = [ { "filename": "orchestrator_python.prompt", "filepath": "pdd/orchestrator.py", "interface": { "type": "module", "module": { "functions": [ { "name": "run_agentic_e2e_fix_orchestrator", "signature": "(issue_url, issue_content, use_github_state, ci_retries = 3, skip_ci = False)", "returns": "Dict", } ] }, }, } ] with tempfile.TemporaryDirectory() as tmpdir: arch_path = Path(tmpdir) / "architecture.json" arch_path.write_text(json.dumps(current_architecture, indent=2)) warnings = _sanitize_architecture_interfaces(Path(tmpdir), previous_architecture) result = json.loads(arch_path.read_text()) signature = result[0]["interface"]["module"]["functions"][0]["signature"] assert "protect_tests" in signature assert "ci_retries" in signature assert "skip_ci" in signature assert any("protect_tests" in warning for warning in warnings) # --- Tests for issue #566: parse_prompt_tags must ignore tags inside code fences --- def test_parse_tags_ignores_fenced_example_prefers_real_tag(): """Tags inside code fences must be ignored; real tag in header is extracted. Regression for issue #566: parse_prompt_tags() used to scan the entire file, picking up example tags in code fences as real metadata. Fix: only parse content before the first % section marker. Real tags are always declared in the header (before any % section); examples live in the body sections. """ content = """<pdd-reason>Real reason for this module</pdd-reason> % Examples Here is an example of how to use pdd-reason: ```xml <pdd-reason>Example reason shown in docs</pdd-reason> ``` """ result = parse_prompt_tags(content) # The real tag (in header) should be extracted, not the fenced example assert result['reason'] == 'Real reason for this module', ( f"Expected 'Real reason for this module' but got '{result['reason']}' — " "parser is extracting example tags from inside code fences" ) def test_parse_tags_ignores_all_tag_types_in_fences(): """All pdd-* tag types inside code fences must be ignored. Regression for issue #566: the actual prompt file agentic_change_step10_architecture_update_LLM.prompt has example <pdd-reason>, <pdd-interface>, and <pdd-dependency> tags inside code fences that get incorrectly extracted. """ content = """<pdd-reason>Real module reason</pdd-reason> <pdd-interface>{"type": "module", "module": {"functions": []}}</pdd-interface> <pdd-dependency>real_dep.prompt</pdd-dependency> % Examples Here are examples of how to format the tags in your output: ```xml <pdd-reason>The reason for this module's existence</pdd-reason> <pdd-interface> { "type": "module", "module": { "functions": [ {"name": "example_func", "signature": "()", "returns": "None"} ] } } </pdd-interface> <pdd-dependency>example_dep.prompt</pdd-dependency> <pdd-dependency>another_example.prompt</pdd-dependency> ``` """ result = parse_prompt_tags(content) assert result['reason'] == 'Real module reason' assert result['interface'] is not None assert result['interface']['type'] == 'module' # Only the real dependency should be extracted, not the fenced examples assert result['dependencies'] == ['real_dep.prompt'], ( f"Expected ['real_dep.prompt'] but got {result['dependencies']} — " "parser is extracting example dependencies from inside code fences" ) def test_parse_tags_returns_empty_when_all_tags_in_fences(): """When ALL pdd-* tags are inside code fences, parser should return empty results. Regression for issue #566: the step10 prompt file has no real top-level tags, only examples inside code fences. The parser should return None/empty for all fields, not extract the fenced examples as real metadata. """ content = """ % This prompt instructs the LLM how to generate architecture tags. Your output should follow this structure: ```xml <pdd-reason>Describe the module's purpose</pdd-reason> <pdd-interface> { "type": "module", "module": { "functions": [ {"name": "my_func", "signature": "(arg: str)", "returns": "str"} ] } } </pdd-interface> <pdd-dependency>some_module.prompt</pdd-dependency> ``` Make sure to include all relevant tags. """ result = parse_prompt_tags(content) assert result['reason'] is None, ( f"Expected None but got '{result['reason']}' — " "parser extracted a reason from inside a code fence" ) assert result['interface'] is None, ( "Parser extracted an interface from inside a code fence" ) assert result['dependencies'] == [], ( f"Expected [] but got {result['dependencies']} — " "parser extracted dependencies from inside a code fence" ) def test_parse_tags_ignores_inline_backtick_references(): """Inline backtick references in body prose must not be extracted as tags. Regression for issue #566: inline backtick references like `<pdd-reason>` in instructional body text get recovered by lxml as actual XML elements with garbled text content, corrupting the extracted metadata. Fix: only parse the header (before first % section). Instructional prose with inline backtick references lives in body sections, never in the header. """ content = """<pdd-reason>Real reason value</pdd-reason> % Instructions Generate a `<pdd-reason>` tag with the module's purpose. Also generate `<pdd-interface>` and `<pdd-dependency>` tags. """ result = parse_prompt_tags(content) # Only the real header tag should be extracted, not the backtick references assert result['reason'] == 'Real reason value', ( f"Expected 'Real reason value' but got '{result['reason']}' — " "parser is confused by inline backtick references in body" ) # Inline backtick references to interface/dependency should not produce results assert result['interface'] is None assert result['dependencies'] == [] def test_parse_tags_extracts_real_tags_adjacent_to_fences(): """Real tags in the header are extracted even when fenced examples exist in body. Ensures the fix doesn't over-strip — real tags declared in the header (before the first % section) must still be extracted correctly, while fenced example tags in body sections are ignored. """ content = """<pdd-reason>Reason at top</pdd-reason> <pdd-dependency>real_dep.prompt</pdd-dependency> % Examples ```xml <pdd-reason>Fenced example reason</pdd-reason> <pdd-dependency>fenced_dep.prompt</pdd-dependency> ``` """ result = parse_prompt_tags(content) assert result['reason'] == 'Reason at top', ( f"Expected 'Reason at top' but got '{result['reason']}'" ) assert result['dependencies'] == ['real_dep.prompt'], ( f"Expected ['real_dep.prompt'] but got {result['dependencies']} — " "parser should only extract real header dependencies, not fenced examples" ) def test_parse_tags_real_world_step10_prompt_pattern(): """Regression test matching the actual step10 prompt file structure. The file agentic_change_step10_architecture_update_LLM.prompt has NO real top-level pdd-* tags — only instructional examples inside code fences. The parser must return empty results for this pattern. This directly reproduces the bug reported in issue #566. """ content = """% Architecture Update Step You are updating the architecture.json file for a PDD project. % Instructions For each module, generate the following tags: ```xml <pdd-reason>Brief description of why this module exists</pdd-reason> ``` For interfaces, use this format: ```xml <pdd-interface> { "type": "module", "module": { "functions": [ {"name": "parse_prompt_tags", "signature": "(prompt_content: str)", "returns": "Dict[str, Any]"} ] } } </pdd-interface> ``` For dependencies, list each one: ```xml <pdd-dependency>path_resolution_python.prompt</pdd-dependency> <pdd-dependency>construct_paths_python.prompt</pdd-dependency> ``` % Important: Only include dependencies that are actually used. """ result = parse_prompt_tags(content) # No real tags exist outside code fences — all fields should be empty assert result['reason'] is None, ( f"Expected None but got '{result['reason']}' — " "step10 prompt pattern: parser extracted example reason from code fence" ) assert result['interface'] is None, ( "step10 prompt pattern: parser extracted example interface from code fence" ) assert result['dependencies'] == [], ( f"Expected [] but got {result['dependencies']} — " "step10 prompt pattern: parser extracted example dependencies from code fences" ) def test_parse_tags_ignores_tilde_fenced_tags(): """Tags inside tilde-style code fences (~~~) must also be ignored. The _extract_fence_spans utility in preprocess.py recognizes both backtick and tilde fences. The fix for parse_prompt_tags should be consistent. """ content = """<pdd-reason>Real reason outside tilde fence</pdd-reason> % Examples ~~~xml <pdd-reason>Tilde-fenced example reason</pdd-reason> <pdd-dependency>tilde_fenced_dep.prompt</pdd-dependency> ~~~ """ result = parse_prompt_tags(content) assert result['reason'] == 'Real reason outside tilde fence', ( f"Expected 'Real reason outside tilde fence' but got '{result['reason']}' — " "parser is extracting tags from inside tilde code fences" ) assert result['dependencies'] == [], ( f"Expected [] but got {result['dependencies']} — " "parser is extracting dependencies from inside tilde code fences" ) # --- Tests for auto-rename and auto-register features --- def test_find_renamed_prompt_file_finds_step_file(): """_find_renamed_prompt_file returns renamed path when exactly one step-numbered variant exists.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) # step5_design exists on disk but step4_design does not (prompts_dir / 'agentic_arch_step5_design_LLM.prompt').write_text('content') result = _find_renamed_prompt_file('agentic_arch_step4_design_LLM.prompt', prompts_dir) assert result is not None assert result.name == 'agentic_arch_step5_design_LLM.prompt' def test_find_renamed_prompt_file_no_match(): """_find_renamed_prompt_file returns None when no similarly-named file exists.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) # No files at all result = _find_renamed_prompt_file('agentic_arch_step4_design_LLM.prompt', prompts_dir) assert result is None def test_find_renamed_prompt_file_ambiguous(): """_find_renamed_prompt_file returns None when multiple step-number variants exist.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) (prompts_dir / 'agentic_arch_step5_design_LLM.prompt').write_text('content') (prompts_dir / 'agentic_arch_step6_design_LLM.prompt').write_text('content') result = _find_renamed_prompt_file('agentic_arch_step4_design_LLM.prompt', prompts_dir) assert result is None def test_find_renamed_prompt_file_no_step_pattern(): """_find_renamed_prompt_file returns None for filenames without step number pattern.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) (prompts_dir / 'cli_detector_python.prompt').write_text('content') result = _find_renamed_prompt_file('cli_detector_python.prompt', prompts_dir) assert result is None def test_update_uses_renamed_file(): """update_architecture_from_prompt auto-renames arch.json entry and syncs from the found file.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) arch_path = Path(tmp) / 'architecture.json' # Disk has step5 but arch.json references step4 step5_content = '<pdd-reason>Design step 5</pdd-reason>\n% body' (prompts_dir / 'agentic_arch_step5_design_LLM.prompt').write_text(step5_content) arch_data = [ { 'filename': 'agentic_arch_step4_design_LLM.prompt', 'filepath': 'prompts/agentic_arch_step4_design_LLM.prompt', 'reason': 'Old reason', 'dependencies': [], 'priority': 1, } ] arch_path.write_text(json.dumps(arch_data, indent=2) + '\n') result = update_architecture_from_prompt( 'agentic_arch_step4_design_LLM.prompt', prompts_dir=prompts_dir, architecture_path=arch_path, ) assert result['success'] is True # Should have updated filename and reason updated_arch = json.loads(arch_path.read_text()) assert updated_arch[0]['filename'] == 'agentic_arch_step5_design_LLM.prompt' assert updated_arch[0]['filepath'] == 'prompts/agentic_arch_step5_design_LLM.prompt' assert updated_arch[0]['reason'] == 'Design step 5' def test_update_uses_renamed_file_dry_run(): """update_architecture_from_prompt dry_run does not write changes.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) arch_path = Path(tmp) / 'architecture.json' (prompts_dir / 'agentic_arch_step5_design_LLM.prompt').write_text( '<pdd-reason>Design step 5</pdd-reason>\n% body' ) arch_data = [ { 'filename': 'agentic_arch_step4_design_LLM.prompt', 'filepath': 'prompts/agentic_arch_step4_design_LLM.prompt', 'reason': 'Old reason', 'dependencies': [], 'priority': 1, } ] original_text = json.dumps(arch_data, indent=2) + '\n' arch_path.write_text(original_text) result = update_architecture_from_prompt( 'agentic_arch_step4_design_LLM.prompt', prompts_dir=prompts_dir, architecture_path=arch_path, dry_run=True, ) assert result['success'] is True # File should be unchanged in dry_run mode assert arch_path.read_text() == original_text def test_infer_filepath_python(): """_infer_filepath returns pdd/<module>.py for _python.prompt files.""" assert _infer_filepath('cli_detector_python.prompt') == 'pdd/cli_detector.py' def test_infer_filepath_path_aware_pascal_python(): """_infer_filepath reverses path-aware PascalCase Python prompt names.""" assert ( _infer_filepath('src/workers/runtime/gemini_cli_Python.prompt') == 'src/workers/runtime/gemini_cli.py' ) assert ( _infer_filepath('src/clients/__init___Python.prompt') == 'src/clients/__init__.py' ) def test_infer_filepath_path_aware_legacy_lowercase_python(): """_infer_filepath keeps path-qualified legacy lowercase Python prompts path-aware.""" assert ( _infer_filepath('src/workers/runtime/gemini_cli_python.prompt') == 'src/workers/runtime/gemini_cli.py' ) def test_infer_filepath_path_aware_typescript_react(): """_infer_filepath reverses path-aware TypeScriptReact prompt names.""" assert ( _infer_filepath('app/sheet/[id]/page_TypeScriptReact.prompt') == 'app/sheet/[id]/page.tsx' ) def test_infer_filepath_llm(): """_infer_filepath returns prompts/<filename> for _LLM.prompt files.""" assert _infer_filepath('agentic_arch_step5_design_LLM.prompt') == 'prompts/agentic_arch_step5_design_LLM.prompt' def test_infer_module_tags_python(): """_infer_module_tags returns ['module', 'python'] for _python.prompt files.""" assert _infer_module_tags('cli_detector_python.prompt') == ['module', 'python'] assert _infer_module_tags('src/workers/runtime/gemini_cli_Python.prompt') == ['module', 'python'] def test_infer_module_tags_llm(): """_infer_module_tags returns ['llm'] for _LLM.prompt files.""" assert _infer_module_tags('agentic_arch_step5_design_LLM.prompt') == ['llm'] def test_register_untracked_prompts_adds_entry(): """register_untracked_prompts registers a prompt with PDD tags not in arch.json.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) arch_path = Path(tmp) / 'architecture.json' # cli_detector_python.prompt has PDD tags but no arch.json entry (prompts_dir / 'cli_detector_python.prompt').write_text( '<pdd-reason>Detects CLI invocation context</pdd-reason>\n% body' ) # Already-registered module (prompts_dir / 'existing_python.prompt').write_text( '<pdd-reason>Existing module</pdd-reason>\n% body' ) arch_data = [ { 'filename': 'existing_python.prompt', 'filepath': 'pdd/existing.py', 'reason': 'Existing module', 'dependencies': [], 'priority': 1, } ] arch_path.write_text(json.dumps(arch_data, indent=2) + '\n') result = register_untracked_prompts(prompts_dir=prompts_dir, architecture_path=arch_path) assert 'cli_detector_python.prompt' in result['registered'] assert 'existing_python.prompt' not in result['registered'] # Verify written to arch.json updated = json.loads(arch_path.read_text()) filenames = [m['filename'] for m in updated] assert 'cli_detector_python.prompt' in filenames # Check inferred fields cli_entry = next(m for m in updated if m['filename'] == 'cli_detector_python.prompt') assert cli_entry['filepath'] == 'pdd/cli_detector.py' assert cli_entry['reason'] == 'Detects CLI invocation context' assert 'python' in cli_entry['tags'] def test_register_untracked_prompts_adds_include_first_entry(): """Auto-registration must not skip prompts whose header starts with <include>.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) arch_path = Path(tmp) / 'architecture.json' (prompts_dir / 'commands_modify_python.prompt').write_text( '<include>context/python_preamble.prompt</include>\n\n' '<pdd-reason>Modify commands</pdd-reason>\n' '<pdd-dependency>split_main_python.prompt</pdd-dependency>\n' '% body\n' ) arch_path.write_text(json.dumps([], indent=2) + '\n') result = register_untracked_prompts(prompts_dir=prompts_dir, architecture_path=arch_path) assert 'commands_modify_python.prompt' in result['registered'] updated = json.loads(arch_path.read_text()) entry = next(m for m in updated if m['filename'] == 'commands_modify_python.prompt') assert entry['reason'] == 'Modify commands' assert entry['dependencies'] == ['split_main_python.prompt'] def test_register_untracked_prompts_uses_nested_pddrc_generate_output_path(tmp_path): """Nested .pddrc prompt contexts should own auto-register filepath inference.""" prompts_dir = tmp_path / "prompts" commands_dir = prompts_dir / "commands" src_runtime_dir = prompts_dir / "src" / "workers" / "runtime" commands_dir.mkdir(parents=True) src_runtime_dir.mkdir(parents=True) arch_path = tmp_path / "architecture.json" (tmp_path / ".pddrc").write_text( """ version: "1.0" contexts: commands: paths: ["pdd/commands/**", "prompts/commands/**"] defaults: prompts_dir: "prompts/commands" generate_output_path: "pdd/commands/" pdd_cli: paths: ["pdd/**", "prompts/**"] defaults: prompts_dir: "prompts" generate_output_path: "pdd" """, encoding="utf-8", ) (commands_dir / "foo_python.prompt").write_text( "<pdd-reason>Foo command</pdd-reason>\n% body\n", encoding="utf-8", ) (src_runtime_dir / "gemini_cli_python.prompt").write_text( "<pdd-reason>Gemini runtime</pdd-reason>\n% body\n", encoding="utf-8", ) arch_path.write_text("[]\n", encoding="utf-8") result = register_untracked_prompts( prompts_dir=prompts_dir, architecture_path=arch_path, ) assert set(result["registered"]) == { "commands/foo_python.prompt", "src/workers/runtime/gemini_cli_python.prompt", } updated = json.loads(arch_path.read_text(encoding="utf-8")) entries = {entry["filename"]: entry for entry in updated} assert entries["commands/foo_python.prompt"]["filepath"] == "pdd/commands/foo.py" assert ( entries["src/workers/runtime/gemini_cli_python.prompt"]["filepath"] == "src/workers/runtime/gemini_cli.py" ) def test_register_skips_file_without_tags(): """register_untracked_prompts skips prompt files with no PDD tags.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) arch_path = Path(tmp) / 'architecture.json' # No PDD tags (prompts_dir / 'bare_module_python.prompt').write_text('% Just a body, no tags\n') arch_path.write_text(json.dumps([], indent=2) + '\n') result = register_untracked_prompts(prompts_dir=prompts_dir, architecture_path=arch_path) assert 'bare_module_python.prompt' not in result['registered'] assert 'bare_module_python.prompt' in result['skipped'] # Arch.json should remain empty assert json.loads(arch_path.read_text()) == [] def test_register_untracked_prompts_dry_run(): """register_untracked_prompts dry_run does not write to arch.json.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) arch_path = Path(tmp) / 'architecture.json' (prompts_dir / 'cli_detector_python.prompt').write_text( '<pdd-reason>Detects CLI</pdd-reason>\n% body' ) arch_path.write_text(json.dumps([], indent=2) + '\n') result = register_untracked_prompts( prompts_dir=prompts_dir, architecture_path=arch_path, dry_run=True ) assert 'cli_detector_python.prompt' in result['registered'] # File should be unchanged assert json.loads(arch_path.read_text()) == [] def test_sync_all_auto_registers_before_syncing(): """sync_all_prompts_to_architecture registers untracked files and handles renamed files.""" with tempfile.TemporaryDirectory() as tmp: prompts_dir = Path(tmp) arch_path = Path(tmp) / 'architecture.json' # Disk: step5_design exists, cli_detector exists (prompts_dir / 'agentic_arch_step5_design_LLM.prompt').write_text( '<pdd-reason>Design step</pdd-reason>\n% body' ) (prompts_dir / 'cli_detector_python.prompt').write_text( '<pdd-reason>Detects CLI</pdd-reason>\n% body' ) (prompts_dir / 'existing_python.prompt').write_text( '<pdd-reason>Existing updated</pdd-reason>\n% body' ) # arch.json: step4_design (stale name), existing (registered), no cli_detector arch_data = [ { 'filename': 'agentic_arch_step4_design_LLM.prompt', 'filepath': 'prompts/agentic_arch_step4_design_LLM.prompt', 'reason': 'Old design', 'dependencies': [], 'priority': 1, }, { 'filename': 'existing_python.prompt', 'filepath': 'pdd/existing.py', 'reason': 'Old reason', 'dependencies': [], 'priority': 2, }, ] arch_path.write_text(json.dumps(arch_data, indent=2) + '\n') result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=arch_path, ) assert result['success'] is True # Check registered field is present assert 'registered' in result assert 'cli_detector_python.prompt' in result['registered'] # Verify arch.json has all three modules updated = json.loads(arch_path.read_text()) filenames = [m['filename'] for m in updated] assert 'cli_detector_python.prompt' in filenames assert 'agentic_arch_step5_design_LLM.prompt' in filenames assert 'agentic_arch_step4_design_LLM.prompt' not in filenames assert 'existing_python.prompt' in filenames # --- Tests for Issue #825: Parameter-drop bug in interface sync --- def test_interface_sync_drops_existing_params_when_adding_new(): """ Bug reproduction (Issue #825): When a prompt's <pdd-interface> adds new parameters to a function but omits an existing one, the existing parameter is silently dropped because update_architecture_from_prompt does a full replacement instead of merging. This test should FAIL on buggy code (full replacement) and PASS once merge logic is added. """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() # Existing architecture.json has protect_tests in the signature arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "orchestrator_python.prompt", "filepath": "pdd/orchestrator.py", "reason": "Orchestrates e2e fix", "description": "Orchestrator module", "dependencies": [], "priority": 1, "tags": ["module", "python"], "interface": { "type": "module", "module": { "functions": [ { "name": "run_agentic_e2e_fix_orchestrator", "signature": "(issue_url, issue_content, use_github_state, protect_tests)", "returns": "Dict" } ] } } } ] arch_file.write_text(json.dumps(arch_data, indent=2)) # New prompt adds ci_retries and skip_ci but OMITS protect_tests # (simulating the LLM rewriting the tag without preserving all params) prompt_file = prompts_dir / "orchestrator_python.prompt" new_interface = { "type": "module", "module": { "functions": [ { "name": "run_agentic_e2e_fix_orchestrator", "signature": "(issue_url, issue_content, use_github_state, ci_retries=3, skip_ci=False)", "returns": "Dict" } ] } } prompt_file.write_text( f'<pdd-reason>Orchestrates e2e fix</pdd-reason>\n' f'<pdd-interface>{json.dumps(new_interface)}</pdd-interface>\n' f'\n% Module Prompt\n' ) # Run the sync result = update_architecture_from_prompt( "orchestrator_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False ) assert result['success'] is True # Read the updated architecture.json updated_arch = json.loads(arch_file.read_text()) updated_sig = updated_arch[0]['interface']['module']['functions'][0]['signature'] # The merged signature MUST contain protect_tests (existing param) # AND the new params ci_retries, skip_ci assert 'protect_tests' in updated_sig, ( f"Existing parameter 'protect_tests' was silently dropped! " f"Got signature: {updated_sig}" ) assert 'ci_retries' in updated_sig, ( f"New parameter 'ci_retries' missing from signature: {updated_sig}" ) assert 'skip_ci' in updated_sig, ( f"New parameter 'skip_ci' missing from signature: {updated_sig}" ) def test_interface_sync_preserves_existing_params_on_merge(): """ Happy path: new interface adds parameters while the existing ones are also present in the new tag. All should be preserved. """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "mod_python.prompt", "filepath": "pdd/mod.py", "reason": "Test module", "description": "Test", "dependencies": [], "priority": 1, "tags": ["module"], "interface": { "type": "module", "module": { "functions": [ { "name": "do_thing", "signature": "(a, b, c)", "returns": "str" } ] } } } ] arch_file.write_text(json.dumps(arch_data, indent=2)) # New tag has all existing params + new one new_interface = { "type": "module", "module": { "functions": [ { "name": "do_thing", "signature": "(a, b, c, d=None)", "returns": "str" } ] } } prompt_file = prompts_dir / "mod_python.prompt" prompt_file.write_text( f'<pdd-interface>{json.dumps(new_interface)}</pdd-interface>\n' f'\n% Prompt\n' ) result = update_architecture_from_prompt( "mod_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False ) assert result['success'] is True updated_arch = json.loads(arch_file.read_text()) sig = updated_arch[0]['interface']['module']['functions'][0]['signature'] assert sig == "(a, b, c, d=None)" def test_interface_sync_warns_on_param_drop(): """ When the new interface tag would remove a parameter that existed in the old signature, the result should include a warning. """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "mod_python.prompt", "filepath": "pdd/mod.py", "reason": "Test", "description": "Test", "dependencies": [], "priority": 1, "tags": ["module"], "interface": { "type": "module", "module": { "functions": [ { "name": "process", "signature": "(x, y, z)", "returns": "bool" } ] } } } ] arch_file.write_text(json.dumps(arch_data, indent=2)) # New tag drops 'z' parameter new_interface = { "type": "module", "module": { "functions": [ { "name": "process", "signature": "(x, y)", "returns": "bool" } ] } } prompt_file = prompts_dir / "mod_python.prompt" prompt_file.write_text( f'<pdd-interface>{json.dumps(new_interface)}</pdd-interface>\n' f'\n% Prompt\n' ) result = update_architecture_from_prompt( "mod_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False ) assert result['success'] is True # Should have a warning about the dropped parameter warnings = result.get('warnings', []) warning_text = ' '.join(warnings).lower() assert 'z' in warning_text or 'drop' in warning_text or 'removed' in warning_text, ( f"Expected a warning about dropped parameter 'z', got warnings: {warnings}" ) def test_interface_sync_via_sync_all_preserves_params(): """ Same bug via sync_all_prompts_to_architecture entry point: existing parameters must be preserved when new ones are added. """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "worker_python.prompt", "filepath": "pdd/worker.py", "reason": "Worker module", "description": "Worker", "dependencies": [], "priority": 1, "tags": ["module"], "interface": { "type": "module", "module": { "functions": [ { "name": "run_worker", "signature": "(queue, max_retries, timeout)", "returns": "None" } ] } } } ] arch_file.write_text(json.dumps(arch_data, indent=2)) # Prompt adds verbose param but omits timeout new_interface = { "type": "module", "module": { "functions": [ { "name": "run_worker", "signature": "(queue, max_retries, verbose=False)", "returns": "None" } ] } } prompt_file = prompts_dir / "worker_python.prompt" prompt_file.write_text( f'<pdd-reason>Worker module</pdd-reason>\n' f'<pdd-interface>{json.dumps(new_interface)}</pdd-interface>\n' f'\n% Prompt\n' ) result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False ) assert result['success'] is True updated_arch = json.loads(arch_file.read_text()) sig = updated_arch[0]['interface']['module']['functions'][0]['signature'] # timeout must be preserved (existing param) assert 'timeout' in sig, ( f"Existing parameter 'timeout' was dropped via sync_all! " f"Got signature: {sig}" ) assert 'verbose' in sig def test_interface_sync_new_function_no_conflict(): """ When the new interface adds an entirely new function (not present in old interface), no merge conflict — just add it. """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "mod_python.prompt", "filepath": "pdd/mod.py", "reason": "Test", "description": "Test", "dependencies": [], "priority": 1, "tags": ["module"], "interface": { "type": "module", "module": { "functions": [ { "name": "existing_func", "signature": "(a, b)", "returns": "str" } ] } } } ] arch_file.write_text(json.dumps(arch_data, indent=2)) # New interface has existing function + a brand new function new_interface = { "type": "module", "module": { "functions": [ { "name": "existing_func", "signature": "(a, b)", "returns": "str" }, { "name": "new_func", "signature": "(x)", "returns": "int" } ] } } prompt_file = prompts_dir / "mod_python.prompt" prompt_file.write_text( f'<pdd-interface>{json.dumps(new_interface)}</pdd-interface>\n' f'\n% Prompt\n' ) result = update_architecture_from_prompt( "mod_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False ) assert result['success'] is True updated_arch = json.loads(arch_file.read_text()) funcs = updated_arch[0]['interface']['module']['functions'] func_names = [f['name'] for f in funcs] assert 'existing_func' in func_names assert 'new_func' in func_names def test_interface_sync_identical_no_update(): """ When new interface is identical to existing, no update should occur. """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() interface = { "type": "module", "module": { "functions": [ { "name": "do_thing", "signature": "(a, b)", "returns": "str" } ] } } arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "mod_python.prompt", "filepath": "pdd/mod.py", "reason": "Test", "description": "Test", "dependencies": [], "priority": 1, "tags": ["module"], "interface": interface } ] arch_file.write_text(json.dumps(arch_data, indent=2)) # Prompt has same interface prompt_file = prompts_dir / "mod_python.prompt" prompt_file.write_text( f'<pdd-interface>{json.dumps(interface)}</pdd-interface>\n' f'\n% Prompt\n' ) result = update_architecture_from_prompt( "mod_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False ) assert result['success'] is True assert result['updated'] is False # No changes def test_interface_sync_disk_state_has_merged_result(): """ Verify that after sync, the architecture.json file on disk contains the merged signature with all parameters. """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "svc_python.prompt", "filepath": "pdd/svc.py", "reason": "Service", "description": "Service module", "dependencies": [], "priority": 1, "tags": ["module"], "interface": { "type": "module", "module": { "functions": [ { "name": "serve", "signature": "(host, port, debug)", "returns": "None" } ] } } } ] arch_file.write_text(json.dumps(arch_data, indent=2)) # New tag adds ssl param but drops debug new_interface = { "type": "module", "module": { "functions": [ { "name": "serve", "signature": "(host, port, ssl=False)", "returns": "None" } ] } } prompt_file = prompts_dir / "svc_python.prompt" prompt_file.write_text( f'<pdd-interface>{json.dumps(new_interface)}</pdd-interface>\n' f'\n% Prompt\n' ) update_architecture_from_prompt( "svc_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False ) # Read raw disk content and verify merged result disk_data = json.loads(arch_file.read_text()) sig = disk_data[0]['interface']['module']['functions'][0]['signature'] assert 'host' in sig assert 'port' in sig assert 'debug' in sig, f"Existing param 'debug' dropped on disk! Got: {sig}" assert 'ssl' in sig, f"New param 'ssl' missing on disk! Got: {sig}" def test_interface_sync_dry_run_shows_merged_result(): """ Dry-run should show the merged interface in the return value without writing to disk. """ with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" old_interface = { "type": "module", "module": { "functions": [ { "name": "analyze", "signature": "(data, threshold)", "returns": "Dict" } ] } } arch_data = [ { "filename": "analyzer_python.prompt", "filepath": "pdd/analyzer.py", "reason": "Analyzer", "description": "Analyzer", "dependencies": [], "priority": 1, "tags": ["module"], "interface": old_interface } ] original_content = json.dumps(arch_data, indent=2) arch_file.write_text(original_content) # New tag adds verbose but drops threshold new_interface = { "type": "module", "module": { "functions": [ { "name": "analyze", "signature": "(data, verbose=False)", "returns": "Dict" } ] } } prompt_file = prompts_dir / "analyzer_python.prompt" prompt_file.write_text( f'<pdd-interface>{json.dumps(new_interface)}</pdd-interface>\n' f'\n% Prompt\n' ) result = update_architecture_from_prompt( "analyzer_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=True ) assert result['success'] is True assert result['updated'] is True # Disk should be unchanged assert arch_file.read_text() == original_content # The changes dict should show the merged interface new_iface = result['changes']['interface']['new'] merged_sig = new_iface['module']['functions'][0]['signature'] assert 'threshold' in merged_sig, ( f"Dry-run result missing existing param 'threshold': {merged_sig}" ) assert 'verbose' in merged_sig, ( f"Dry-run result missing new param 'verbose': {merged_sig}" ) def test_interface_sync_preserves_return_annotation_and_function_style(): """Merged signatures should keep def/async style and return annotations.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "scorer_python.prompt", "filepath": "pdd/scorer.py", "reason": "Scorer", "description": "Scorer", "dependencies": [], "priority": 1, "tags": ["module"], "interface": { "type": "module", "module": { "functions": [ { "name": "compute_score", "signature": "def compute_score(value: int, threshold: float = 0.5) -> bool", "returns": "bool", } ] } }, } ] arch_file.write_text(json.dumps(arch_data, indent=2)) new_interface = { "type": "module", "module": { "functions": [ { "name": "compute_score", "signature": "def compute_score(value: int, verbose: bool = False) -> bool", "returns": "bool", } ] } } prompt_file = prompts_dir / "scorer_python.prompt" prompt_file.write_text( f'<pdd-interface>{json.dumps(new_interface)}</pdd-interface>\n' f'\n% Prompt\n' ) result = update_architecture_from_prompt( "scorer_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False, ) assert result["success"] is True updated_arch = json.loads(arch_file.read_text()) sig = updated_arch[0]["interface"]["module"]["functions"][0]["signature"] assert sig == ( "def compute_score(value: int, threshold: float = 0.5, " "verbose: bool = False) -> bool" ) def test_interface_sync_keeps_existing_signature_when_new_signature_is_unparseable(): """Unparseable new signatures should not silently replace existing parseable ones.""" with tempfile.TemporaryDirectory() as tmpdir: tmppath = Path(tmpdir) prompts_dir = tmppath / "prompts" prompts_dir.mkdir() arch_file = tmppath / "architecture.json" arch_data = [ { "filename": "processor_python.prompt", "filepath": "pdd/processor.py", "reason": "Processor", "description": "Processor", "dependencies": [], "priority": 1, "tags": ["module"], "interface": { "type": "module", "module": { "functions": [ { "name": "process", "signature": "(payload, retries, timeout)", "returns": "Dict", } ] } }, } ] arch_file.write_text(json.dumps(arch_data, indent=2)) new_interface = { "type": "module", "module": { "functions": [ { "name": "process", "signature": "(payload, retries, ...)", "returns": "Dict", } ] } } prompt_file = prompts_dir / "processor_python.prompt" prompt_file.write_text( f'<pdd-interface>{json.dumps(new_interface)}</pdd-interface>\n' f'\n% Prompt\n' ) result = update_architecture_from_prompt( "processor_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_file, dry_run=False, ) assert result["success"] is True updated_arch = json.loads(arch_file.read_text()) sig = updated_arch[0]["interface"]["module"]["functions"][0]["signature"] assert sig == "(payload, retries, timeout)" warning_text = " ".join(result.get("warnings", [])).lower() assert "could not be parsed" in warning_text def test_normalize_architecture_filenames_issue617(): """Issue #617: normalize_architecture_filenames sets filename from filepath (mirror structure).""" arch_data = [ {"filepath": "prisma/schema.prisma", "filename": "prisma_schema_Prisma.prompt", "priority": 1}, {"filepath": "app/api/route.ts", "filename": "app_api_route_TypeScript.prompt", "priority": 2}, ] normalize_architecture_filenames(arch_data) assert arch_data[0]["filename"] == "prisma/schema_Prisma.prompt" assert arch_data[1]["filename"] == "app/api/route_TypeScript.prompt" # Entry without filepath is unchanged arch_data.append({"filepath": "", "filename": "old.prompt", "priority": 3}) normalize_architecture_filenames(arch_data) assert arch_data[2]["filename"] == "old.prompt" def test_filename_mirrors_filepath_issue617(): """Issue #617: prompt filename should mirror filepath directory structure, not flatten with underscores.""" cases = [ ("prisma/schema.prisma", "Prisma", "prisma/schema_Prisma.prompt"), ("lib/types.ts", "TypeScript", "lib/types_TypeScript.prompt"), ("lib/formulaEngine.ts", "TypeScript", "lib/formulaEngine_TypeScript.prompt"), ("app/api/sheets/route.ts", "TypeScript", "app/api/sheets/route_TypeScript.prompt"), ("app/api/sheets/[id]/route.ts", "TypeScript", "app/api/sheets/[id]/route_TypeScript.prompt"), ("components/grid/Cell.tsx", "TypeScriptReact", "components/grid/Cell_TypeScriptReact.prompt"), ("app/sheet/[id]/page.tsx", "TypeScriptReact", "app/sheet/[id]/page_TypeScriptReact.prompt"), ("src/models/user.py", "Python", "src/models/user_Python.prompt"), ("app/layout.tsx", "TypeScriptReact", "app/layout_TypeScriptReact.prompt"), ] for filepath, language, expected in cases: assert filepath_to_prompt_filename(filepath, language) == expected, ( f"filepath={filepath!r} language={language!r}: expected {expected!r}" ) def test_normalize_skips_extensionless_files_issue617(): """Issue #617: extensionless files like Makefile should not be normalized.""" arch_data = [ {"filepath": "Makefile", "filename": "makefile_build.prompt", "priority": 1}, {"filepath": "app/api/route.ts", "filename": "app_api_route_TypeScript.prompt", "priority": 2}, ] normalize_architecture_filenames(arch_data) assert arch_data[0]["filename"] == "makefile_build.prompt" # unchanged assert arch_data[1]["filename"] == "app/api/route_TypeScript.prompt" # normalized def test_get_architecture_entry_for_prompt_subdir_filename_issue617(): """Issue #617: get_architecture_entry_for_prompt handles subdirectory-style filenames.""" with tempfile.TemporaryDirectory() as tmp: arch_path = Path(tmp) / "architecture.json" arch_data = [ {"filename": "app/page_TypeScriptReact.prompt", "filepath": "app/page.tsx", "priority": 1}, ] arch_path.write_text(json.dumps(arch_data), encoding="utf-8") entry = get_architecture_entry_for_prompt( "app/page_TypeScriptReact.prompt", architecture_path=arch_path ) assert entry is not None assert entry["filename"] == "app/page_TypeScriptReact.prompt" def test_get_architecture_entry_for_prompt_basename_fallback_issue617(): """Issue #617: get_architecture_entry_for_prompt falls back to basename match.""" with tempfile.TemporaryDirectory() as tmp: arch_path = Path(tmp) / "architecture.json" arch_data = [ {"filename": "app/page_TypeScriptReact.prompt", "filepath": "app/page.tsx", "priority": 1}, ] arch_path.write_text(json.dumps(arch_data), encoding="utf-8") entry = get_architecture_entry_for_prompt( "page_TypeScriptReact.prompt", architecture_path=arch_path ) assert entry is not None assert entry["filename"] == "app/page_TypeScriptReact.prompt" # --- Tests for cross-contamination guard in _merge_function_signature --- from pdd.architecture_sync import _merge_function_signature def test_merge_rejects_completely_incompatible_signatures(): """ When the LLM writes SyncApp.__init__ into ConfirmDialog's entry, the merge should detect the signatures are incompatible (no shared params beyond 'self') and keep the old signature instead of concatenating two unrelated classes' params. """ old_sig = "(self, message: str, title: str = 'Confirmation Required')" # SyncApp's signature — completely different params new_sig = ( "(self, basename: str, budget: Optional[float], " "worker_func: Callable[[], Any], function_name_ref: List[str])" ) merged, warnings = _merge_function_signature(old_sig, new_sig, "__init__") # The merged signature should NOT contain SyncApp's params assert "basename" not in merged, ( f"Cross-contamination: SyncApp param 'basename' leaked into " f"ConfirmDialog.__init__: {merged}" ) assert "worker_func" not in merged, ( f"Cross-contamination: SyncApp param 'worker_func' leaked into " f"ConfirmDialog.__init__: {merged}" ) # Should keep the old signature assert "message" in merged assert "title" in merged # Should have a warning about the incompatible merge assert len(warnings) > 0 def test_merge_accepts_compatible_signature_evolution(): """ Normal case: same function with an added parameter should merge fine. """ old_sig = "(self, host: str, port: int, debug: bool = False)" new_sig = "(self, host: str, port: int, ssl: bool = False)" merged, warnings = _merge_function_signature(old_sig, new_sig, "serve") # debug was dropped, should be preserved by merge assert "debug" in merged assert "ssl" in merged assert "host" in merged def test_merge_rejects_when_only_self_overlaps(): """ When the only shared parameter is 'self', signatures are from different classes and should not be merged. """ old_sig = "(self, app_ref: List[Optional['SyncApp']])" new_sig = ( "(self, basename: str, budget: Optional[float], " "worker_func: Callable[[], Any])" ) merged, warnings = _merge_function_signature(old_sig, new_sig, "__init__") # Should keep old, not merge assert "app_ref" in merged assert "basename" not in merged assert len(warnings) > 0 # --- Issue #1256: Dict-format architecture tolerance --- def test_register_untracked_prompts_dict_format_architecture(tmp_path): """register_untracked_prompts with dict-format architecture.json does not crash (Test 12). Bug: iterating dict-format data yields dict keys (strings like "modules"), not module entries. m.get("filename") crashes with AttributeError: 'str' object has no attribute 'get' at architecture_sync.py:313. """ prompts = tmp_path / "prompts" prompts.mkdir() # Existing prompt tracked in architecture (prompts / "existing_Python.prompt").write_text( "% PDD-generated\n", encoding="utf-8" ) # Untracked prompt not in architecture (prompts / "untracked_Python.prompt").write_text( "% PDD-generated\n", encoding="utf-8" ) # Dict-format architecture arch = {"modules": [ {"filename": "existing_Python.prompt", "priority": 1, "dependencies": []} ]} arch_path = tmp_path / "architecture.json" arch_path.write_text(json.dumps(arch), encoding="utf-8") result = register_untracked_prompts( prompts_dir=prompts, architecture_path=arch_path, dry_run=True, ) assert isinstance(result, dict), ( "register_untracked_prompts should handle dict-format architecture " "without crashing (currently iterates dict keys instead of modules)" ) # After fix, untracked_Python.prompt should be detected assert "existing_Python.prompt" not in result.get("registered", []), ( "Already-tracked prompt should not be re-registered" ) def test_get_architecture_entry_for_prompt_dict_format(tmp_path): """get_architecture_entry_for_prompt with dict-format architecture finds the entry (Test 13). Bug: iterating dict-format data yields dict keys (strings like "modules"), not module entries. entry.get("filename") crashes with AttributeError: 'str' object has no attribute 'get' at architecture_sync.py:1045. """ from pdd.architecture_sync import get_architecture_entry_for_prompt arch = {"modules": [ {"filename": "auth_Python.prompt", "priority": 1, "reason": "Auth module"} ]} arch_path = tmp_path / "architecture.json" arch_path.write_text(json.dumps(arch), encoding="utf-8") entry = get_architecture_entry_for_prompt( "auth_Python.prompt", architecture_path=arch_path ) assert entry is not None, ( "Dict-format architecture should return the matching entry, " "but directly iterating dict yields keys (strings), causing AttributeError" ) assert entry["reason"] == "Auth module" def test_register_untracked_prompts_preserves_dict_format(tmp_path): """register_untracked_prompts preserves {prd_files, modules} on-disk shape after write-back.""" prompts = tmp_path / "prompts" prompts.mkdir() (prompts / "existing_Python.prompt").write_text( "% PDD-generated\n", encoding="utf-8" ) (prompts / "new_Python.prompt").write_text( "<pdd-reason>New module</pdd-reason>\n%\n", encoding="utf-8" ) arch = { "prd_files": ["docs/prd.md"], "modules": [ {"filename": "existing_Python.prompt", "priority": 1, "dependencies": []} ], } arch_path = tmp_path / "architecture.json" arch_path.write_text(json.dumps(arch, indent=2), encoding="utf-8") register_untracked_prompts( prompts_dir=prompts, architecture_path=arch_path, dry_run=False, ) reloaded = json.loads(arch_path.read_text(encoding="utf-8")) assert isinstance(reloaded, dict), "On-disk format should remain dict after write-back" assert reloaded.get("prd_files") == ["docs/prd.md"], "prd_files should be preserved" assert isinstance(reloaded.get("modules"), list), "modules key should be preserved" filenames = {m["filename"] for m in reloaded["modules"]} assert "new_Python.prompt" in filenames, "Newly registered prompt should be in modules" def _sha256_file(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def _contract_summary_fixture(tmp_path: Path) -> tuple[Path, Path, Path]: """Minimal project layout for contract_summary sync tests.""" (tmp_path / ".pdd").mkdir() prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() arch_path = tmp_path / "architecture.json" arch_path.write_text( json.dumps( [ { "filename": "refund_python.prompt", "filepath": "src/refund.py", "priority": 1, } ] ), encoding="utf-8", ) return tmp_path, prompts_dir, arch_path def test_extract_contract_summary_prompt_only(tmp_path): """Prompt with contract_rules yields rules and capabilities; no stories or evidence.""" project_root, prompts_dir, _ = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( textwrap.dedent( """\ <contract_rules> R1 - Refund cap The system MUST cap refunds. R2 - CRITICAL audit The system MUST log refunds. </contract_rules> <capabilities> - reads_payments - writes_refunds </capabilities> """ ), encoding="utf-8", ) summary, warnings = _extract_contract_summary(prompt_path, project_root) assert warnings == [] assert summary["rules"] == ["R1", "R2"] assert summary["critical"] == ["R2"] assert summary["capabilities"] == ["reads_payments", "writes_refunds"] assert summary["stories"] == [] assert summary["coverage_status"] == "none" assert summary["evidence_status"] == "missing" def test_extract_contract_summary_with_story(tmp_path): """Story links and covers contribute story-only coverage.""" project_root, prompts_dir, _ = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( textwrap.dedent( """\ <contract_rules> R1 - Refund cap The system MUST cap refunds. </contract_rules> """ ), encoding="utf-8", ) stories_dir = tmp_path / "user_stories" stories_dir.mkdir() story_path = stories_dir / "story__refund.md" story_path.write_text( textwrap.dedent( """\ <pdd-story-prompts> refund_python.prompt </pdd-story-prompts> ## Covers - R1: refund cap ## Acceptance Criteria - Refund is capped correctly. """ ), encoding="utf-8", ) summary, _warnings = _extract_contract_summary(prompt_path, project_root) assert summary["rules"] == ["R1"] assert summary["stories"] == ["user_stories/story__refund.md"] assert summary["coverage_status"] == "story-only" assert summary["unchecked"] == [] def test_extract_contract_summary_fresh_and_stale_evidence(tmp_path): """Evidence manifest SHA match yields fresh; mismatch yields stale.""" project_root, prompts_dir, _ = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( "<contract_rules>\nR1 - X\nMUST x.\n</contract_rules>\n", encoding="utf-8", ) evidence_dir = tmp_path / ".pdd" / "evidence" / "devunits" evidence_dir.mkdir(parents=True) latest = evidence_dir / "refund.latest.json" latest.write_text( json.dumps( { "prompt": {"sha256": _sha256_file(prompt_path)}, "contracts": {"status": "not_applicable"}, } ), encoding="utf-8", ) fresh, _ = _extract_contract_summary(prompt_path, project_root) assert fresh["evidence_status"] == "fresh" latest.write_text( json.dumps({"prompt": {"sha256": "0" * 64}, "contracts": {"status": "not_applicable"}}), encoding="utf-8", ) stale, _ = _extract_contract_summary(prompt_path, project_root) assert stale["evidence_status"] == "stale" def test_extract_contract_summary_legacy_prompt_without_contracts(tmp_path): """Prompts without contract sections return an empty, non-error summary.""" project_root, prompts_dir, _ = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( "<pdd-reason>Legacy module</pdd-reason>\n", encoding="utf-8", ) summary, warnings = _extract_contract_summary(prompt_path, project_root) assert summary["rules"] == [] assert summary["coverage_status"] == "none" assert summary["evidence_status"] == "missing" assert summary["unchecked"] == [] assert "error" not in summary assert warnings == [] def test_update_architecture_from_prompt_writes_contract_summary(tmp_path): """Sync writes contract_summary into architecture.json for a module.""" project_root, prompts_dir, arch_path = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( textwrap.dedent( """\ <pdd-reason>Refund handler</pdd-reason> <contract_rules> R1 - Refund cap The system MUST cap refunds. </contract_rules> """ ), encoding="utf-8", ) result = update_architecture_from_prompt( "refund_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_path, dry_run=False, ) assert result["success"] is True assert result["updated"] is True assert "contract_summary" in result["changes"] arch_data = json.loads(arch_path.read_text(encoding="utf-8")) module = arch_data[0] assert module["contract_summary"]["rules"] == ["R1"] assert module["contract_summary"]["unchecked"] == ["R1"] assert module["reason"] == "Refund handler" assert "rules_detail" in module["contract_summary"] def test_extract_contract_summary_unchecked_and_waived(tmp_path): """Unchecked rules and waivers surface in contract_summary.""" project_root, prompts_dir, _ = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( textwrap.dedent( """\ <contract_rules> R1 - Covered The system MUST do R1. R2 - Open The system MUST do R2. </contract_rules> <coverage> R1: WAIVED W1 </coverage> <waivers> W1 rule: R1 reason: temporary </waivers> """ ), encoding="utf-8", ) summary, _ = _extract_contract_summary(prompt_path, project_root) assert "R1" in summary["rules"] assert "R2" in summary["unchecked"] assert "W1" in summary["waived"] def test_extract_contract_summary_manifest_available_full_coverage(tmp_path): """Manifest contracts.available refines coverage_status to full when all rules checked.""" project_root, prompts_dir, _ = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( "<contract_rules>\nR1 - A\nMUST a.\nR2 - B\nMUST b.\n</contract_rules>\n", encoding="utf-8", ) evidence_dir = tmp_path / ".pdd" / "evidence" / "devunits" evidence_dir.mkdir(parents=True) latest = evidence_dir / "refund.latest.json" latest.write_text( json.dumps( { "prompt": {"sha256": _sha256_file(prompt_path)}, "contracts": { "status": "available", "rules": { "R1": {"status": "checked", "stories": ["story__a.md"], "tests": ["test_a"]}, "R2": {"status": "checked", "stories": ["story__b.md"], "tests": ["test_b"]}, }, }, } ), encoding="utf-8", ) summary, _ = _extract_contract_summary(prompt_path, project_root) assert summary["evidence_status"] == "fresh" assert summary["coverage_status"] == "full" def test_extract_contract_summary_evidence_only_without_contracts(tmp_path): """Fresh evidence without contract rules still yields a persisted summary.""" project_root, prompts_dir, _ = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text("<pdd-reason>Legacy</pdd-reason>\n", encoding="utf-8") evidence_dir = tmp_path / ".pdd" / "evidence" / "devunits" evidence_dir.mkdir(parents=True) (evidence_dir / "refund.latest.json").write_text( json.dumps( { "prompt": {"sha256": _sha256_file(prompt_path)}, "contracts": {"status": "not_applicable", "rules": {}}, } ), encoding="utf-8", ) summary, _ = _extract_contract_summary(prompt_path, project_root) assert summary["rules"] == [] assert summary["evidence_status"] == "fresh" assert not _contract_summary_is_empty(summary) def test_update_architecture_clears_contract_summary_when_rules_removed(tmp_path): """Removing contract_rules drops contract_summary from architecture.json.""" project_root, prompts_dir, arch_path = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( "<contract_rules>\nR1 - X\nMUST x.\n</contract_rules>\n", encoding="utf-8", ) update_architecture_from_prompt( "refund_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_path, ) prompt_path.write_text("<pdd-reason>Legacy only</pdd-reason>\n", encoding="utf-8") result = update_architecture_from_prompt( "refund_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_path, ) module = json.loads(arch_path.read_text(encoding="utf-8"))[0] assert "contract_summary" not in module assert result["updated"] is True def test_update_architecture_prompt_content_override_uses_override_for_summary(tmp_path): """contract_summary follows prompt_content_override, not stale on-disk prompt.""" project_root, prompts_dir, arch_path = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text("<pdd-reason>On disk</pdd-reason>\n", encoding="utf-8") override = textwrap.dedent( """\ <pdd-reason>Override</pdd-reason> <contract_rules> R9 - Only in memory MUST override. </contract_rules> """ ) result = update_architecture_from_prompt( "refund_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_path, prompt_content_override=override, ) assert result["success"] is True assert result["contract_summary"]["rules"] == ["R9"] def test_sync_all_returns_contract_summary_per_module(tmp_path): """sync_all_prompts_to_architecture includes contract_summary on each result row.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() arch_path = tmp_path / "architecture.json" (prompts_dir / "mod_python.prompt").write_text( "<contract_rules>\nR1 - A\nMUST a.\n</contract_rules>\n", encoding="utf-8", ) arch_path.write_text( json.dumps([{"filename": "mod_python.prompt", "filepath": "mod.py", "priority": 1}]), encoding="utf-8", ) result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=arch_path, ) assert result["success"] is True row = result["results"][0] assert row["contract_summary"]["rules"] == ["R1"] def test_update_architecture_contract_summary_warnings_on_read_errors(tmp_path, monkeypatch): """Non-fatal coverage read errors are returned as sync warnings.""" project_root, prompts_dir, arch_path = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( "<contract_rules>\nR1 - X\nMUST x.\n</contract_rules>\n", encoding="utf-8", ) def _fake_build_coverage(path, stories_dir, tests_dir, **kwargs): # noqa: ANN001 from pdd.coverage_contracts import CoverageResult, RuleCoverage return CoverageResult( path=path, has_contract_rules=True, rules=[RuleCoverage(rule_id="R1", status="unchecked")], read_errors=["story file unreadable: broken.md"], ) monkeypatch.setattr("pdd.coverage_contracts.build_coverage", _fake_build_coverage) result = update_architecture_from_prompt( "refund_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_path, ) assert any("story file unreadable" in w for w in result["warnings"]) def test_extract_contract_summary_finds_evidence_from_write_evidence_manifest(tmp_path): """Production manifest basename (refund.latest.json) is used, not prompt stem.""" from pdd.evidence_manifest import write_evidence_manifest project_root, prompts_dir, _ = _contract_summary_fixture(tmp_path) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( "<contract_rules>\nR1 - X\nMUST x.\n</contract_rules>\n", encoding="utf-8", ) output = tmp_path / "src" / "refund.py" output.parent.mkdir(parents=True) output.write_text("def refund():\n pass\n", encoding="utf-8") write_evidence_manifest( command="pdd generate", prompt_file=prompt_path, output_files=[output], model="local-model", cost_usd=0.0, temperature=0.0, project_root=project_root, ) wrong_stem = tmp_path / ".pdd" / "evidence" / "devunits" / "refund_python.latest.json" assert not wrong_stem.is_file() summary, _ = _extract_contract_summary(prompt_path, project_root) assert summary["evidence_status"] == "fresh" def test_extract_contract_summary_nested_prompt_evidence_slug(tmp_path): """Nested prompt identities use _safe_slug basenames (frontend-page.latest.json).""" from pdd.evidence_manifest import write_evidence_manifest project_root = tmp_path (project_root / ".pdd").mkdir() prompt_path = project_root / "prompts" / "frontend" / "page_python.prompt" prompt_path.parent.mkdir(parents=True) (project_root / "tests").mkdir() (project_root / "user_stories").mkdir() prompt_path.write_text( "<contract_rules>\nR1 - Page\nThe system MUST render page.\n</contract_rules>\n", encoding="utf-8", ) write_evidence_manifest( command="pdd generate", prompt_file=prompt_path, project_root=project_root, ) wrong_path = ( project_root / ".pdd" / "evidence" / "devunits" / "frontend" / "page.latest.json" ) assert not wrong_path.is_file() latest = project_root / ".pdd" / "evidence" / "devunits" / "frontend-page.latest.json" assert latest.is_file() summary, _ = _extract_contract_summary(prompt_path, project_root) assert summary["evidence_status"] == "fresh" def test_prompt_content_override_preserves_story_metadata_scope(tmp_path): """Override content must not change prompt filename used for story scoping.""" project_root, prompts_dir, arch_path = _contract_summary_fixture(tmp_path) stories = project_root / "user_stories" stories.mkdir(exist_ok=True) prompt_path = prompts_dir / "refund_python.prompt" prompt_path.write_text( textwrap.dedent( """\ <pdd-reason>On disk</pdd-reason> <contract_rules> R1 - Refund cap MUST cap refunds. </contract_rules> """ ), encoding="utf-8", ) (stories / "story__refund_cap.md").write_text( textwrap.dedent( """\ <!-- pdd-story-prompts: refund_python.prompt --> # Refund cap story ## Acceptance Criteria - R1 is satisfied in tests. ## Covers - R1: refunds are capped. """ ), encoding="utf-8", ) override = textwrap.dedent( """\ <pdd-reason>Override</pdd-reason> <contract_rules> R1 - Refund cap MUST cap refunds. </contract_rules> """ ) result = update_architecture_from_prompt( "refund_python.prompt", prompts_dir=prompts_dir, architecture_path=arch_path, prompt_content_override=override, stories_dir=stories, tests_dir=project_root / "tests", ) summary = result["contract_summary"] assert any("story__refund_cap.md" in path for path in summary["stories"]) assert summary["coverage_status"] != "none" def test_sync_all_propagates_warnings(tmp_path, monkeypatch): """sync_all_prompts_to_architecture keeps per-module warnings on each result row.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() arch_path = tmp_path / "architecture.json" (prompts_dir / "mod_python.prompt").write_text( "<contract_rules>\nR1 - A\nMUST a.\n</contract_rules>\n", encoding="utf-8", ) arch_path.write_text( json.dumps([{"filename": "mod_python.prompt", "filepath": "mod.py", "priority": 1}]), encoding="utf-8", ) def _fake_update(*_args, **_kwargs): # noqa: ANN002 return { "success": True, "updated": True, "changes": {}, "error": None, "warnings": ["contract_summary: story file unreadable: broken.md"], "contract_summary": {"rules": ["R1"]}, } monkeypatch.setattr( "pdd.architecture_sync.update_architecture_from_prompt", _fake_update, ) result = sync_all_prompts_to_architecture( prompts_dir=prompts_dir, architecture_path=arch_path, ) row = result["results"][0] assert row["warnings"] == ["contract_summary: story file unreadable: broken.md"] def test_sync_prompts_to_architecture_named_files_propagates_warnings( tmp_path, monkeypatch, ): """Named-file sync_prompts_to_architecture keeps warnings on each result row.""" prompts_dir = tmp_path / "prompts" prompts_dir.mkdir() arch_path = tmp_path / "architecture.json" arch_path.write_text( json.dumps([{"filename": "mod_python.prompt", "filepath": "mod.py", "priority": 1}]), encoding="utf-8", ) def _fake_update(*_args, **_kwargs): # noqa: ANN002 return { "success": True, "updated": False, "changes": {}, "error": None, "warnings": ["contract_summary: evidence manifest unreadable: bad json"], "contract_summary": {"rules": ["R1"]}, } monkeypatch.setattr( "pdd.architecture_sync.update_architecture_from_prompt", _fake_update, ) result = sync_prompts_to_architecture( filenames=["mod_python.prompt"], prompts_dir=prompts_dir, architecture_path=arch_path, ) row = result["results"][0] assert row["warnings"] == ["contract_summary: evidence manifest unreadable: bad json"] assert row["contract_summary"]["rules"] == ["R1"] # --- Additional coverage tests (appended) --- import sys from pathlib import Path # Add project root to sys.path to ensure local code is prioritized # This allows testing local changes without installing the package project_root = Path(__file__).resolve().parents[1] sys.path.insert(0, str(project_root)) def test_validate_interface_structure_frontend_requires_pages(): result = validate_interface_structure({"type": "frontend", "frontend": {}}) assert result["valid"] is False assert any("pages" in e.lower() for e in result["errors"]) def test_validate_interface_structure_frontend_valid(): result = validate_interface_structure({"type": "frontend", "frontend": {"pages": []}}) assert result["valid"] is True def test_validate_interface_structure_command_requires_commands(): result = validate_interface_structure({"type": "command", "command": {}}) assert result["valid"] is False assert any("commands" in e.lower() for e in result["errors"]) def test_validate_interface_structure_page_valid(): """Simple page type only needs the nested dict.""" result = validate_interface_structure({"type": "page", "page": {}}) assert result["valid"] is True def test_validate_interface_structure_nested_not_dict(): result = validate_interface_structure({"type": "module", "module": "not-a-dict"}) assert result["valid"] is False def test_validate_interface_structure_not_a_dict(): result = validate_interface_structure("not a dict") # type: ignore[arg-type] assert result["valid"] is False assert result["errors"] def test_validate_dependencies_empty_list(tmp_path): result = validate_dependencies([], prompts_dir=tmp_path) assert result == {"valid": True, "missing": [], "duplicates": []} def test_has_pdd_tags_only_interface_or_dependency(): assert has_pdd_tags("<pdd-interface>{}</pdd-interface>") is True assert has_pdd_tags("<pdd-dependency>x.prompt</pdd-dependency>") is True def test_generate_tags_only_interface(): tags = generate_tags_from_architecture( {"interface": {"type": "module", "module": {"functions": []}}} ) assert "<pdd-interface>" in tags assert "<pdd-reason>" not in tags assert "<pdd-dependency>" not in tags def test_get_architecture_entry_missing_file(tmp_path): assert get_architecture_entry_for_prompt( "x.prompt", architecture_path=tmp_path / "nope.json" ) is None def test_get_architecture_entry_prompts_prefix_normalized(tmp_path): arch = tmp_path / "architecture.json" arch.write_text( json.dumps([{"filename": "foo_python.prompt", "reason": "R"}]), encoding="utf-8", ) # Prefix "prompts/" should be stripped for matching entry = get_architecture_entry_for_prompt( "prompts/foo_python.prompt", architecture_path=arch ) assert entry is not None assert entry["reason"] == "R" def test_parse_tags_rejects_path_like_dependency(): """Dependency values that look like file paths (with slashes, non-.prompt) are rejected.""" content = "<pdd-dependency>some/path/file.txt</pdd-dependency>" result = parse_prompt_tags(content) assert result["dependencies"] == [] def test_validate_architecture_modules_detects_circular(): modules = [ {"filename": "a.prompt", "filepath": "a.py", "description": "A", "dependencies": ["b.prompt"]}, {"filename": "b.prompt", "filepath": "b.py", "description": "B", "dependencies": ["a.prompt"]}, ] result = validate_architecture_modules(modules) assert result["valid"] is False assert any(e["type"] == "circular_dependency" for e in result["errors"]) def test_validate_architecture_modules_missing_dependency(): modules = [ {"filename": "a.prompt", "filepath": "a.py", "description": "A", "dependencies": ["ghost.prompt"]}, ] result = validate_architecture_modules(modules) assert result["valid"] is False assert any(e["type"] == "missing_dependency" for e in result["errors"]) def test_validate_architecture_modules_orphan_warning(): modules = [ {"filename": "solo.prompt", "filepath": "s.py", "description": "S", "dependencies": []}, ] result = validate_architecture_modules(modules) assert any(w["type"] == "orphan_module" for w in result["warnings"]) def test_validate_architecture_modules_duplicate_dependency_warning(): modules = [ {"filename": "a.prompt", "filepath": "a.py", "description": "A", "dependencies": ["b.prompt", "b.prompt"]}, {"filename": "b.prompt", "filepath": "b.py", "description": "B", "dependencies": []}, ] result = validate_architecture_modules(modules) assert any(w["type"] == "duplicate_dependency" for w in result["warnings"]) def test_update_architecture_from_prompt_content_override_no_disk_read(tmp_path): """prompt_content_override should be used instead of reading the file.""" prompts = tmp_path / "prompts" prompts.mkdir() (prompts / "mod_python.prompt").write_text( "<pdd-reason>On disk</pdd-reason>", encoding="utf-8" ) arch = tmp_path / "architecture.json" arch.write_text( json.dumps([{"filename": "mod_python.prompt", "filepath": "mod.py", "reason": "Old", "description": "M", "dependencies": [], "priority": 1}]), encoding="utf-8", ) result = update_architecture_from_prompt( "mod_python.prompt", prompts_dir=prompts, architecture_path=arch, prompt_content_override="<pdd-reason>From override</pdd-reason>", dry_run=False, ) assert result["success"] is True updated = json.loads(arch.read_text()) assert updated[0]["reason"] == "From override" def test_update_architecture_missing_architecture_file(tmp_path): prompts = tmp_path / "prompts" prompts.mkdir() (prompts / "mod.prompt").write_text("<pdd-reason>R</pdd-reason>", encoding="utf-8") result = update_architecture_from_prompt( "mod.prompt", prompts_dir=prompts, architecture_path=tmp_path / "no_arch.json", ) assert result["success"] is False assert "not found" in result["error"].lower() def test_sync_all_missing_architecture_file(tmp_path): prompts = tmp_path / "prompts" prompts.mkdir() result = sync_all_prompts_to_architecture( prompts_dir=prompts, architecture_path=tmp_path / "no_arch.json" ) assert result["success"] is False assert result["errors"] def test_infer_module_tags_typescript_react(): """PascalCase language suffix doesn't add 'python' tag.""" assert _infer_module_tags("components/Foo_TypeScriptReact.prompt") == ["module"]
"""
Unit tests for architecture_sync module.
Tests bidirectional sync between architecture.json and prompt file metadata tags.
"""
import hashlib
import inspect
import json
import tempfile
import textwrap
from pathlib import Path
import pytest
from pdd.architecture_sync import (
_contract_summary_is_empty,
_extract_contract_summary,
_find_renamed_prompt_file,
_infer_filepath,
_infer_module_tags,
_resolve_sync_paths,
filepath_to_prompt_filename,
generate_tags_from_architecture,
get_architecture_entry_for_prompt,
has_pdd_tags,
normalize_architecture_filenames,
parse_prompt_tags,
register_untracked_prompts,
sync_prompts_to_architecture,
sync_all_prompts_to_architecture,
update_architecture_from_prompt,
validate_dependencies,
validate_architecture_modules,
validate_interface_structure,
)
def _repository_architecture_entry(filename: str) -> dict:
"""Return a real repository architecture entry for prompt-contract checks."""
repo_root = Path(__file__).resolve().parent.parent
entries = json.loads((repo_root / "architecture.json").read_text(encoding="utf-8"))
return next(entry for entry in entries if entry["filename"] == filename)
def test_mock_contract_validation_real_prompt_interface_is_parseable():
"""XML-safe memory sentinels must preserve the real security gate contract."""
repo_root = Path(__file__).resolve().parent.parent
prompt = repo_root / "pdd" / "prompts" / "mock_contract_validation_python.prompt"
tags = parse_prompt_tags(prompt.read_text(encoding="utf-8"))
assert "interface_parse_error" not in tags
assert tags["interface"] is not None
signatures = {
function["name"]: function["signature"]
for function in tags["interface"]["module"]["functions"]
}
assert "source_path: str = '<memory>'" in signatures["extract_query_fields"]
assert "source_path: str = '<memory>'" in signatures["extract_mock_fields"]
assert _repository_architecture_entry("mock_contract_validation_python.prompt")["interface"] == tags["interface"]
def test_sync_orchestration_real_prompt_contract_matches_runtime():
"""The orchestration prompt and architecture expose only runtime arguments."""
from pdd.sync_orchestration import sync_orchestration
repo_root = Path(__file__).resolve().parent.parent
prompt = repo_root / "pdd" / "prompts" / "sync_orchestration_python.prompt"
tags = parse_prompt_tags(prompt.read_text(encoding="utf-8"))
declared_signature = tags["interface"]["module"]["functions"][0]["signature"]
runtime_parameters = list(inspect.signature(sync_orchestration).parameters)
assert "one_session" not in declared_signature
assert "one_session" not in runtime_parameters
assert runtime_parameters[-2:] == ["compressed_context", "fresh"]
architecture_signature = _repository_architecture_entry(
"sync_orchestration_python.prompt"
)["interface"]["module"]["functions"][0]["signature"]
assert "one_session" not in architecture_signature
assert architecture_signature.endswith(
"compressed_context: bool = False, fresh: bool = False) -> Dict[str, Any]"
)
# --- Test parse_prompt_tags ---
def test_parse_tags_with_all_fields():
"""Test parsing prompt with reason, interface, and dependencies."""
content = """
<pdd-reason>Provides unified LLM invocation</pdd-reason>
<pdd-interface>
{
"type": "module",
"module": {
"functions": [
{"name": "llm_invoke", "signature": "(...)", "returns": "Dict"}
]
}

Xet Storage Details

Size:
175 kB
·
Xet hash:
7941440c1ee5ed9d3f41fe134a3c913e217175dada06eb49ad122423d985a07a

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