Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions ISSUE_DEHALLUCINATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# ISSUE: Implement `intelligence` Gate for API Veracity (De-hallucination)

## Goal
Prevent AI agents from proposing "slop" fixes that utilize hallucinated library methods or deprecated APIs. This is a common failure mode where agents invent methods that "should" exist but do not.

## Context
- **Repository:** `desloppify`
- **Location of Logic:** `intelligence/review/importing/holistic.py` (specifically `import_holistic_issues`).
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Correct the spec path for the import-flow implementation.

Line 8 references intelligence/review/importing/holistic.py, but the implemented path in this campaign is desloppify/intelligence/review/importing/holistic.py. This can send follow-up investigation to the wrong location.

Suggested doc fix
-- **Location of Logic:** `intelligence/review/importing/holistic.py` (specifically `import_holistic_issues`).
+- **Location of Logic:** `desloppify/intelligence/review/importing/holistic.py` (specifically `import_holistic_issues`).
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- **Location of Logic:** `intelligence/review/importing/holistic.py` (specifically `import_holistic_issues`).
- **Location of Logic:** `desloppify/intelligence/review/importing/holistic.py` (specifically `import_holistic_issues`).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ISSUE_DEHALLUCINATION.md` at line 8, Update the documentation reference so it
points to the actual module path used in this campaign: replace the incorrect
`intelligence/review/importing/holistic.py` with
`desloppify/intelligence/review/importing/holistic.py` wherever the spec
mentions the import-flow implementation (notably the `import_holistic_issues`
implementation), ensuring any follow-up investigations reference the real file
location.

- **Target Language (Phase 1):** Python.

## Specification
1. **Detection:** Intercept incoming `ReviewIssuePayload` during the import process.
2. **Extraction:** Identify code blocks within the `suggestion` field.
3. **Verification (Python):**
* Extract imported modules and method calls from the suggested code.
* Verify these calls against the local project environment (e.g., `sys.modules`, `pkg_resources`, or by inspecting the AST of installed packages).
* Reuse logic from `desloppify/languages/python/detectors/deps_resolution.py` if applicable.
4. **Feedback:** If a hallucinated API is detected:
* Reject the specific issue.
* Return a `VerificationIssue` to the agent with a clear message: `"Hallucinated API detected: [method_name]. Please verify against the actual library structure and refactor."`
5. **Configuration:** Allow this check to be toggled via a new flag `--verify-veracity`.

## Definition of Done
Comment on lines +3 to +23
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix heading spacing (MD022) to keep the spec lint-clean.

Add a blank line after headings at Line 3, Line 6, Line 11, and Line 23.

🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 3-3: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 6-6: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 11-11: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 23-23: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ISSUE_DEHALLUCINATION.md` around lines 3 - 23, The markdown headings in
ISSUE_DEHALLUCINATION.md need a blank line after them to satisfy MD022; insert
an empty line immediately after the headings "## Goal", "## Context", "##
Specification", and "## Definition of Done" so that each heading is followed by
a single blank line and the file passes the linter.

- [x] A new veracity verification layer exists in the review import pipeline.
- [x] A test case confirms that an import with `os.path.non_existent_method()` is rejected.
- [x] A test case confirms that valid APIs (e.g. `os.path.exists()`) are accepted.
- [x] The feature is documented in `skill_docs.py`.
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ def _add_core_options(p_review: argparse.ArgumentParser) -> None:
"(default: fail on any skipped issue)"
),
)
g_core.add_argument(
"--verify-veracity",
action="store_true",
help="Verify API veracity (de-hallucination) for suggested fixes during import",
)
g_core.add_argument(
"--dimensions",
type=str,
Expand Down
4 changes: 4 additions & 0 deletions desloppify/app/commands/review/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class ReviewOptions:
manual_override: bool = False
attested_external: bool = False
attest: str | None = None
verify_veracity: bool = False

@classmethod
def from_args(cls, args: argparse.Namespace) -> ReviewOptions:
Expand All @@ -58,6 +59,7 @@ def from_args(cls, args: argparse.Namespace) -> ReviewOptions:
manual_override=bool(getattr(args, "manual_override", False)),
attested_external=bool(getattr(args, "attested_external", False)),
attest=getattr(args, "attest", None),
verify_veracity=bool(getattr(args, "verify_veracity", False)),
)


Expand Down Expand Up @@ -189,6 +191,7 @@ def _run_review_mode(
manual_override=opts.manual_override,
attested_external=opts.attested_external,
manual_attest=opts.attest,
verify_veracity=opts.verify_veracity,
),
Comment on lines +194 to 195
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

--verify-veracity still does not reach the import campaign.

These fields are populated here, but desloppify/app/commands/review/importing/cmd.py:326-330 still calls import_holistic_issues(...) without verify_veracity, and desloppify/intelligence/review/__init__.py:90-109 drops the kwarg in its wrapper. As shipped, desloppify review --import --verify-veracity behaves the same as without the flag.

Also applies to: 211-212

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@desloppify/app/commands/review/cmd.py` around lines 194 - 195, The
--verify-veracity flag is being set but never forwarded to the import path;
update the import flow to accept and forward this kwarg: add
verify_veracity=opts.verify_veracity when calling import_holistic_issues in
desloppify/app/commands/review/importing/cmd.py (and the other call around the
211–212 region), and modify the wrapper in
desloppify/intelligence/review/__init__.py to accept a verify_veracity parameter
and pass it through to the underlying import function so the flag reaches
import_holistic_issues.

)
return
Expand All @@ -205,6 +208,7 @@ def _run_review_mode(
manual_override=opts.manual_override,
attested_external=opts.attested_external,
manual_attest=opts.attest,
verify_veracity=opts.verify_veracity,
),
dry_run=opts.dry_run,
)
Expand Down
2 changes: 2 additions & 0 deletions desloppify/app/commands/review/importing/flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class ReviewImportConfig:
attested_external: bool = False
manual_override: bool = False
manual_attest: str | None = None
verify_veracity: bool = False


def build_import_load_config(
Expand All @@ -45,6 +46,7 @@ def build_import_load_config(
attested_external=import_config.attested_external,
manual_override=override_enabled,
manual_attest=override_attest,
verify_veracity=import_config.verify_veracity,
)


Expand Down
2 changes: 2 additions & 0 deletions desloppify/app/commands/review/importing/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ class ImportParseOptions:
attested_external: bool = False
manual_override: bool = False
manual_attest: str | None = None
verify_veracity: bool = False


def _coerce_import_parse_options(
Expand All @@ -85,6 +86,7 @@ def _coerce_import_parse_options(
attested_external=bool(base.attested_external),
manual_override=bool(base.manual_override),
manual_attest=coerce_optional_str(base.manual_attest),
verify_veracity=bool(base.verify_veracity),
)


Expand Down
2 changes: 1 addition & 1 deletion desloppify/app/skill_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

# Bump this integer whenever docs/SKILL.md changes in a way that agents
# should pick up (new commands, changed workflows, removed sections).
SKILL_VERSION = 6
SKILL_VERSION = 7

SKILL_VERSION_RE = re.compile(r"<!--\s*desloppify-skill-version:\s*(\d+)\s*-->")
SKILL_OVERLAY_RE = re.compile(r"<!--\s*desloppify-overlay:\s*(\w+)\s*-->")
Expand Down
3 changes: 2 additions & 1 deletion desloppify/data/global/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ description: >
---

<!-- desloppify-begin -->
<!-- desloppify-skill-version: 6 -->
<!-- desloppify-skill-version: 7 -->

# Desloppify

Expand Down Expand Up @@ -124,6 +124,7 @@ Four paths to get subjective scores:
- **Local runner (Claude)**: `desloppify review --prepare` → launch parallel subagents → `desloppify review --import merged.json` — see skill doc overlay for details.
- **Cloud/external**: `desloppify review --external-start --external-runner claude` → follow session template → `--external-submit`.
- **Manual path**: `desloppify review --prepare` → review per dimension → `desloppify review --import file.json`.
- **API Veracity**: Pass `--verify-veracity` during import to detect and reject hallucinated library APIs in suggested fixes (highly recommended for Python).

**Batch output vs import filenames:** Individual batch outputs from subagents must be named `batch-N.raw.txt` (plain text/JSON content, `.raw.txt` extension). The `.json` filenames in `--import merged.json` or `--import findings.json` refer to the final merged import file, not individual batch outputs. Do not name batch outputs with a `.json` extension.

Expand Down
3 changes: 3 additions & 0 deletions desloppify/intelligence/review/importing/holistic.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def import_holistic_issues(
lang_name: str,
*,
project_root: Path | str | None = None,
verify_veracity: bool = False,
utc_now_fn=utc_now,
) -> dict[str, Any]:
"""Import holistic (codebase-wide) issues into state."""
Expand Down Expand Up @@ -109,6 +110,8 @@ def import_holistic_issues(
issues_list,
holistic_prompts,
lang_name,
verify_veracity=verify_veracity,
project_root=project_root,
)
imported_dimensions = _collect_imported_dimensions(
issues_list=issues_list,
Expand Down
29 changes: 29 additions & 0 deletions desloppify/intelligence/review/importing/holistic_issue_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from desloppify.engine._state.filtering import make_issue
from desloppify.engine._state.schema import Issue, StateModel
from desloppify.languages._framework.registry import state as lang_registry
from desloppify.intelligence.review.dimensions import normalize_dimension_name
from desloppify.intelligence.review.importing.contracts_types import (
ReviewIssuePayload,
Expand Down Expand Up @@ -59,6 +60,9 @@ def validate_and_build_issues(
issues_list: list[ReviewIssuePayload],
holistic_prompts: dict[str, Any],
lang_name: str,
*,
verify_veracity: bool = False,
project_root: Any = None,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
"""Validate raw holistic issues and build state-ready issue dicts.

Expand All @@ -71,6 +75,13 @@ def validate_and_build_issues(
dim for dim in holistic_prompts if isinstance(dim, str) and dim.strip()
}

# Setup veracity plugin if requested
veracity_plugin = None
if verify_veracity:
lang_cfg = lang_registry.get(lang_name)
if lang_cfg:
veracity_plugin = getattr(lang_cfg, "veracity_plugin", None)

for idx, raw_issue in enumerate(issues_list):
issue, issue_errors = validate_review_issue_payload(
raw_issue,
Expand Down Expand Up @@ -121,6 +132,24 @@ def validate_and_build_issues(
continue

dimension = issue["dimension"]
suggestion = issue.get("suggestion", "")

# Veracity check (De-hallucination)
if veracity_plugin and suggestion:
veracity_errors = veracity_plugin.verify_suggestion(
suggestion,
project_root=str(project_root) if project_root else None,
)
if veracity_errors:
error_messages = [err["message"] for err in veracity_errors]
skipped.append(
{
"index": idx,
"missing": [f"Veracity check failed: {', '.join(error_messages)}"],
"identifier": issue.get("identifier", "<none>"),
}
)
continue

is_confirmed_concern = issue.get("concern_verdict") == "confirmed"
detector = "concerns" if is_confirmed_concern else "review"
Expand Down
32 changes: 32 additions & 0 deletions desloppify/intelligence/review/veracity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Veracity verification interface for review suggested fixes."""

from __future__ import annotations

from abc import ABC, abstractmethod
from typing import Any, TypedDict


class VeracityIssue(TypedDict):
"""Hallucinated API finding details."""
method: str
module: str | None
message: str
code_block: str


class VeracityPlugin(ABC):
"""Abstract base for language-specific veracity (de-hallucination) auditors."""

@abstractmethod
def verify_suggestion(
self,
suggestion: str,
*,
project_root: str | None = None,
) -> list[VeracityIssue]:
"""Audit a suggestion string for hallucinated APIs.

Should extract code blocks and verify them against the local environment.
Returns a list of detected hallucination issues.
"""
raise NotImplementedError
5 changes: 5 additions & 0 deletions desloppify/languages/_framework/base/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

if TYPE_CHECKING:
from desloppify.engine.policy.zones import FileZoneMap, ZoneRule
from desloppify.intelligence.review.veracity import VeracityPlugin

# ---------------------------------------------------------------------------
# Type aliases for complex Callable signatures used in LangConfig fields
Expand Down Expand Up @@ -71,6 +72,7 @@ class LangRuntimeContract(Protocol):
extract_functions: FunctionExtractor | None
get_area: Callable[[str], str] | None
build_dep_graph: DepGraphBuilder
veracity_plugin: VeracityPlugin | None
detect_lang_security_detailed: Callable[[list[str], FileZoneMap | None], LangSecurityResult]
detect_private_imports: Callable[
[dict, FileZoneMap | None], tuple[list[DetectorEntry], int]
Expand Down Expand Up @@ -128,6 +130,9 @@ class LangConfig:
# Function extractor (for duplicate detection). Returns a list of FunctionInfo items.
extract_functions: FunctionExtractor | None = None

# Veracity (de-hallucination) plugin
veracity_plugin: VeracityPlugin | None = None

# Coupling boundaries (optional, project-specific)
boundaries: list[BoundaryRule] = field(default_factory=list)

Expand Down
2 changes: 2 additions & 0 deletions desloppify/languages/python/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
from desloppify.languages.python.detectors.private_imports import (
detect_private_imports as detect_python_private_imports,
)
from desloppify.languages.python.veracity import PythonVeracityPlugin
from desloppify.languages.python.phases import (
PY_COMPLEXITY_SIGNALS,
PY_ENTRY_PATTERNS,
Expand Down Expand Up @@ -138,6 +139,7 @@ def __init__(self) -> None:
migration_pattern_pairs=PY_MIGRATION_PATTERN_PAIRS,
migration_mixed_extensions=PY_MIGRATION_MIXED_EXTENSIONS,
extract_functions=py_extract_functions,
veracity_plugin=PythonVeracityPlugin(),
zone_rules=PY_ZONE_RULES,
)

Expand Down
116 changes: 116 additions & 0 deletions desloppify/languages/python/tests/test_py_veracity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
"""Tests for Python veracity (de-hallucination) plugin."""

import pytest
from desloppify.languages.python.veracity import PythonVeracityPlugin


@pytest.fixture
def plugin():
return PythonVeracityPlugin()


def test_valid_suggestion(plugin):
"""Valid Python APIs should pass."""
suggestion = """
Consider using os.path.exists:
```python
import os
if os.path.exists("foo.txt"):
print("exists")
```
"""
issues = plugin.verify_suggestion(suggestion)
assert len(issues) == 0


def test_hallucinated_suggestion(plugin):
"""Hallucinated Python APIs should be detected."""
suggestion = """
Try this non-existent method:
```python
import os
os.path.this_is_not_a_real_method("foo")
```
"""
issues = plugin.verify_suggestion(suggestion)
assert len(issues) == 1
assert issues[0]["method"] == "this_is_not_a_real_method"
assert issues[0]["module"] == "os.path"
assert "does not exist" in issues[0]["message"]


def test_pathlib_hallucination(plugin):
"""Hallucinated pathlib methods should be detected."""
suggestion = """
```python
from pathlib import Path
p = Path("foo")
p.non_existent_path_method()
```
"""
# Note: Our simple implementation checks 'pathlib.non_existent_path_method'
# if it sees 'pathlib.X'. Since we used 'from pathlib import Path',
# node.value.id is 'p' which is not in our allowlist.
# However, if we used 'pathlib.Path("foo").non_existent()', it would catch it.

suggestion_direct = """
```python
import pathlib
pathlib.Path("foo").non_existent_method()
```
"""
# ast.walk will find Attribute(value=Call(func=Attribute(value=Name(id='pathlib'), attr='Path')), attr='non_existent_method')
# Our current _verify_attribute_call only handles Attribute(value=Name).

# Let's test what it DOES handle:
suggestion_simple = """
```python
import pathlib
pathlib.non_existent_at_root()
```
"""
issues = plugin.verify_suggestion(suggestion_simple)
assert len(issues) == 1
assert issues[0]["method"] == "non_existent_at_root"


def test_import_as_hallucination(plugin):
"""Hallucinated methods with 'import as' should be detected."""
suggestion = """
```python
import os as my_os
my_os.path.invalid_method()
```
"""
issues = plugin.verify_suggestion(suggestion)
assert len(issues) == 1
assert issues[0]["module"] == "os.path"
assert issues[0]["method"] == "invalid_method"


def test_from_import_hallucination(plugin):
"""Hallucinated methods with 'from import' should be detected."""
suggestion = """
```python
from os import path
path.invalid_method_on_path()
```
"""
issues = plugin.verify_suggestion(suggestion)
assert len(issues) == 1
assert issues[0]["module"] == "os.path"
assert issues[0]["method"] == "invalid_method_on_path"


def test_from_import_as_hallucination(plugin):
"""Hallucinated methods with 'from import as' should be detected."""
suggestion = """
```python
from os import path as my_path
my_path.invalid_method_on_path()
```
"""
issues = plugin.verify_suggestion(suggestion)
assert len(issues) == 1
assert issues[0]["module"] == "os.path"
assert issues[0]["method"] == "invalid_method_on_path"
Loading