Metadata-Version: 2.1
Name: ai-change-impact-prototype
Version: 0.4.0
Summary: Local-first change impact analysis and visual reports for RAG applications
License: MIT
Project-URL: Repository, https://github.com/Shubham-786/ai-change-impact
Project-URL: Issues, https://github.com/Shubham-786/ai-change-impact/issues
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE

# AI Change Impact

Find recorded RAG questions that retrieved a changed passage, then replay those questions against your updated pipeline. AI Change Impact stores provenance locally in SQLite and has no runtime dependencies.

**Status: alpha prototype.** Its API may change. It reports known line-level dependencies, not every potentially affected answer.

## How it works

```mermaid
flowchart LR
    A["RAG application"] -->|"Record source, hash and retrieved lines"| B["Local SQLite"]
    C["Before and after documents"] --> D["Line diff"]
    B --> E["Match versions and spans"]
    D --> E
    E --> F["Affected observations"]
    E --> G["Version mismatches"]
    F -.-> H["Optional replay through your pipeline"]
```

Your application supplies the source text, a stable source identifier, and the line range it retrieved. The package hashes the source text and records the observation. During comparison, it computes a line diff and finds observations whose recorded spans overlap changed lines. It reports records for a different document version separately. Insertions are matched against adjacent old lines.

Replay is opt-in and calls your function once per affected observation. It compares returned strings with stored answers; it does not evaluate factual correctness or automatically update an index.

## Installation

Requires Python 3.10 or newer. Install from PyPI:

```bash
python -m pip install ai-change-impact-prototype
```

Alternatively, install from the source checkout:

```bash
git clone https://github.com/Shubham-786/ai-change-impact.git
cd ai-change-impact
python -m pip install .
```

To build a local wheel, run `python -m pip install build` and then `python -m build`.

## Try the demo

With version 0.3.0 or newer, run a small local keyword-retrieval example without a model, API key, or network:

```bash
python -m pip install --upgrade ai-change-impact-prototype
impact demo --html demo-report.html
```

Open the generated HTML file to inspect the recorded question and change. The command refuses to overwrite an existing report. The demo is illustrative: it does not run a language model or measure answer quality.

## Record retrieved chunks

Version 0.3.0 and newer can map an exact chunk back to the source without manually counting lines:

```python
from change_impact import ImpactStore

source_text = "Refund policy\nRefunds are available for 30 days.\n"
with ImpactStore("impact.sqlite3") as store:
    store.record_chunk(source="policy", document=source_text, question="Refund period?",
                       chunk="Refunds are available for 30 days.", chunk_id="refund-1")
    report = store.compare(source="policy", before=source_text,
                           after=source_text.replace("30 days", "14 days"))
    print(report["affected"])
```

Chunks must occur exactly in the original source text. If a chunk occurs more than once, provide its `start_index` as a Python character offset. Transformed or OCR-altered text must be mapped to the source by the caller; incorrect mappings are rejected rather than guessed. The chunk identifier is stored in observation metadata, preserving compatibility with the 0.2 SQLite schema.

For LangChain-style `Document` objects, `impact_langchain.record_document` accepts `page_content` and optional `metadata["start_index"]` and `metadata["chunk_id"]`. The adapter has no LangChain dependency. The application must provide the matching original source text; metadata is not copied automatically.

See [`examples/langchain_chunk.py`](examples/langchain_chunk.py) for a runnable example using a real LangChain `Document`; install `langchain-core` separately to run it. It demonstrates the adapter with a constructed document, not a production retriever.

[`examples/rag_smoke_test.py`](examples/rag_smoke_test.py) exercises a small offline LangChain retrieval-and-answer pipeline end to end. It uses keyword retrieval and a deterministic answer function; it does not call an LLM or use a vector database. Install `langchain-core` separately, then run `python examples/rag_smoke_test.py` from the source checkout.

## Record and replay from Python

No external service is required for recording or comparison.

```python
from change_impact import ImpactStore, replay

before = "# Refund policy\nRefunds within 30 days.\n"
after = "# Refund policy\nRefunds within 14 days.\n"

with ImpactStore("impact.sqlite3") as store:
    store.record(source="refund-policy", document=before, question="Refund period?",
                 start_line=2, end_line=2, answer="30 days")
    report = store.compare(source="refund-policy", before=before, after=after)

    # Your callable must use the candidate index or document version.
    results = replay(report, lambda question: "14 days")
    print(results[0]["changed"])  # True
```

`replay` calls the supplied function for each affected observation; it does not update your index, run an evaluator, or verify correctness. Your function can make network calls, incur costs, or have side effects. Repeated observations are replayed separately. Version mismatches appear in the report and require review. The database stores questions, answers, and metadata in plaintext; handle access, retention, and deletion yourself.

## Command-line example

Version 0.4.0 and newer supports a read-only comparison of an existing SQLite store:

```bash
impact compare --db impact.sqlite3 --source refund-policy \
  --before policy-old.txt --after policy-new.txt --fail-on-impact
```

It prints JSON, or use `--format html` for a local HTML report. `--fail-on-impact` exits with status 1 when recorded observations overlap the changes, document versions do not match, or no observations exist for the requested source. Invalid files or databases exit with status 2. A successful check still cannot rule out effects outside recorded passages. Source text files are read without converting line endings so their hashes match text recorded exactly as supplied.

From the repository directory, compare the included example documents:

```bash
impact-prototype examples/before.md examples/after.md examples/records.json --source policy
```

The JSON report includes changed lines, affected questions, and records whose document hash does not match the provided old version. The example identifies the refund-period question as affected by the change from 30 to 14 days.

## Visualize an impact report

Version 0.2.0 and newer can render an analysis as a Mermaid flowchart:

```python
from change_impact import render_flow

print(render_flow(report))  # report is returned by ImpactStore.compare()
```

Or generate the Mermaid source from the example files:

```bash
impact-prototype examples/before.md examples/after.md examples/records.json --source policy --format mermaid
```

Paste the output into a Mermaid code block in GitHub Markdown or another compatible viewer. The diagram shows change, affected-observation, and version-mismatch counts; it does not include source text or questions. The optional replay node describes an available next step and does not mean replay was performed. Use the JSON report to inspect the evidence.

For a self-contained local HTML report with clickable sections and the actual changed passages and questions:

```bash
impact-prototype examples/before.md examples/after.md examples/records.json --source policy --format html > impact-report.html
```

Open `impact-report.html` in a browser. No server or network connection is needed. The report contains potentially sensitive source excerpts and questions; store and share it accordingly. Python callers can use `render_html(report)` from `change_impact`.

## Direct comparison without SQLite

Record the exact source identifier, `document_hash(text)`, question, and 1-based inclusive line range for each retrieved passage. Hash the exact Unicode text passed to `analyze`.

```python
from impact_prototype import analyze, document_hash

before = "Refunds within 30 days.\n"
records = [{"source": "policy", "question": "Refund period?", "start_line": 1,
            "end_line": 1, "document_hash": document_hash(before)}]
report = analyze(before, "Refunds within 14 days.\n", records, source="policy")
```

## Scope and validation

This only identifies recorded retrievals overlapping line-level edits; insertions conservatively touch neighboring lines. It cannot identify indirect dependencies, newly relevant documents, changes in retrieval behavior, or semantic effects. Missing or stale provenance must not be treated as unaffected. Replay requires a user-supplied function; the package does not test answer correctness, parse PDFs, or connect to tracing systems. Run full evaluation suites as well. Source text and questions remain local unless the supplied function sends them elsewhere; reports can contain sensitive content.

Line numbers are 1-based and inclusive in the exact source text your application recorded. Document identity uses the SHA-256 hash of its UTF-8 text, so a version mismatch requires separate review. Diffing uses Python's `splitlines()`: changes that affect only line endings or the final newline do not produce changed line spans even though the document hashes differ. The matching algorithm can flag unchanged material around insertions and may align repeated lines in unexpected ways. An empty affected list is not a guarantee that no answer is impacted.

## Data and security

The SQLite database contains source identifiers, questions, optional answers, line ranges, document hashes, and metadata in plaintext. It does not store the full source document, but reports include the changed text. Protect database files and reports using your environment's access controls and retention procedures. The SDK does not send telemetry or make network requests; your replay function may do both. See [SECURITY.md](SECURITY.md) for reporting vulnerabilities.

The store uses SQLite's default thread behavior: use a separate `ImpactStore` instance per thread. Database schema migrations, multi-process coordination beyond SQLite's own behavior, and compatibility guarantees across alpha versions are not yet provided.

Next validate with real users: compare the effort needed to find affected cases in Phoenix, Langfuse, and DeepEval against this approach on the same document changes. Measure setup time, relevant cases found and missed, and developer time saved. No user interviews or competitor hands-on benchmark have yet been conducted.

## Development

Run the test suite with `python -m unittest discover -s tests -v`. Build distributions with `python -m pip install build` followed by `python -m build`. Contributions should include a focused test for behavior changes and avoid collecting user data or sending it over the network without explicit configuration.

## License

MIT. See [LICENSE](LICENSE).
