ai-change-impact-prototype 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shubham Chhapolika
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.1
2
+ Name: ai-change-impact-prototype
3
+ Version: 0.1.0
4
+ Summary: Local prototype for finding recorded RAG questions affected by document changes
5
+ License: MIT
6
+ Project-URL: Repository, https://github.com/Shubham-786/ai-change-impact
7
+ Project-URL: Issues, https://github.com/Shubham-786/ai-change-impact/issues
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Testing
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+
17
+ # AI Change Impact
18
+
19
+ 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.
20
+
21
+ **Status: alpha prototype.** Its API may change. It reports known line-level dependencies, not every potentially affected answer.
22
+
23
+ ## How it works
24
+
25
+ ```text
26
+ RAG application Document update
27
+ | |
28
+ | record question, source, | before and after text
29
+ | document hash and line span |
30
+ v v
31
+ Local SQLite observations ----------> line diff + span matching
32
+ |
33
+ v
34
+ affected observations + stale versions
35
+ |
36
+ optional caller-provided replay
37
+ ```
38
+
39
+ 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.
40
+
41
+ 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.
42
+
43
+ ## Installation
44
+
45
+ Requires Python 3.10 or newer. Install from PyPI:
46
+
47
+ ```bash
48
+ python -m pip install ai-change-impact-prototype
49
+ ```
50
+
51
+ Alternatively, install from the source checkout:
52
+
53
+ ```bash
54
+ git clone https://github.com/Shubham-786/ai-change-impact.git
55
+ cd ai-change-impact
56
+ python -m pip install .
57
+ ```
58
+
59
+ To build a local wheel, run `python -m pip install build` and then `python -m build`.
60
+
61
+ ## Record and replay from Python
62
+
63
+ No external service is required for recording or comparison.
64
+
65
+ ```python
66
+ from change_impact import ImpactStore, replay
67
+
68
+ before = "# Refund policy\nRefunds within 30 days.\n"
69
+ after = "# Refund policy\nRefunds within 14 days.\n"
70
+
71
+ with ImpactStore("impact.sqlite3") as store:
72
+ store.record(source="refund-policy", document=before, question="Refund period?",
73
+ start_line=2, end_line=2, answer="30 days")
74
+ report = store.compare(source="refund-policy", before=before, after=after)
75
+
76
+ # Your callable must use the candidate index or document version.
77
+ results = replay(report, lambda question: "14 days")
78
+ print(results[0]["changed"]) # True
79
+ ```
80
+
81
+ `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.
82
+
83
+ ## Command-line example
84
+
85
+ From the repository directory, compare the included example documents:
86
+
87
+ ```bash
88
+ impact-prototype examples/before.md examples/after.md examples/records.json --source policy
89
+ ```
90
+
91
+ 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.
92
+
93
+ ## Direct comparison without SQLite
94
+
95
+ 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`.
96
+
97
+ ```python
98
+ from impact_prototype import analyze, document_hash
99
+
100
+ before = "Refunds within 30 days.\n"
101
+ records = [{"source": "policy", "question": "Refund period?", "start_line": 1,
102
+ "end_line": 1, "document_hash": document_hash(before)}]
103
+ report = analyze(before, "Refunds within 14 days.\n", records, source="policy")
104
+ ```
105
+
106
+ ## Scope and validation
107
+
108
+ 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.
109
+
110
+ 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.
111
+
112
+ ## Data and security
113
+
114
+ 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.
115
+
116
+ 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.
117
+
118
+ 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.
119
+
120
+ ## Development
121
+
122
+ 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.
123
+
124
+ ## License
125
+
126
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,110 @@
1
+ # AI Change Impact
2
+
3
+ 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.
4
+
5
+ **Status: alpha prototype.** Its API may change. It reports known line-level dependencies, not every potentially affected answer.
6
+
7
+ ## How it works
8
+
9
+ ```text
10
+ RAG application Document update
11
+ | |
12
+ | record question, source, | before and after text
13
+ | document hash and line span |
14
+ v v
15
+ Local SQLite observations ----------> line diff + span matching
16
+ |
17
+ v
18
+ affected observations + stale versions
19
+ |
20
+ optional caller-provided replay
21
+ ```
22
+
23
+ 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.
24
+
25
+ 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.
26
+
27
+ ## Installation
28
+
29
+ Requires Python 3.10 or newer. Install from PyPI:
30
+
31
+ ```bash
32
+ python -m pip install ai-change-impact-prototype
33
+ ```
34
+
35
+ Alternatively, install from the source checkout:
36
+
37
+ ```bash
38
+ git clone https://github.com/Shubham-786/ai-change-impact.git
39
+ cd ai-change-impact
40
+ python -m pip install .
41
+ ```
42
+
43
+ To build a local wheel, run `python -m pip install build` and then `python -m build`.
44
+
45
+ ## Record and replay from Python
46
+
47
+ No external service is required for recording or comparison.
48
+
49
+ ```python
50
+ from change_impact import ImpactStore, replay
51
+
52
+ before = "# Refund policy\nRefunds within 30 days.\n"
53
+ after = "# Refund policy\nRefunds within 14 days.\n"
54
+
55
+ with ImpactStore("impact.sqlite3") as store:
56
+ store.record(source="refund-policy", document=before, question="Refund period?",
57
+ start_line=2, end_line=2, answer="30 days")
58
+ report = store.compare(source="refund-policy", before=before, after=after)
59
+
60
+ # Your callable must use the candidate index or document version.
61
+ results = replay(report, lambda question: "14 days")
62
+ print(results[0]["changed"]) # True
63
+ ```
64
+
65
+ `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.
66
+
67
+ ## Command-line example
68
+
69
+ From the repository directory, compare the included example documents:
70
+
71
+ ```bash
72
+ impact-prototype examples/before.md examples/after.md examples/records.json --source policy
73
+ ```
74
+
75
+ 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.
76
+
77
+ ## Direct comparison without SQLite
78
+
79
+ 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`.
80
+
81
+ ```python
82
+ from impact_prototype import analyze, document_hash
83
+
84
+ before = "Refunds within 30 days.\n"
85
+ records = [{"source": "policy", "question": "Refund period?", "start_line": 1,
86
+ "end_line": 1, "document_hash": document_hash(before)}]
87
+ report = analyze(before, "Refunds within 14 days.\n", records, source="policy")
88
+ ```
89
+
90
+ ## Scope and validation
91
+
92
+ 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.
93
+
94
+ 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.
95
+
96
+ ## Data and security
97
+
98
+ 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.
99
+
100
+ 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.
101
+
102
+ 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.
103
+
104
+ ## Development
105
+
106
+ 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.
107
+
108
+ ## License
109
+
110
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.1
2
+ Name: ai-change-impact-prototype
3
+ Version: 0.1.0
4
+ Summary: Local prototype for finding recorded RAG questions affected by document changes
5
+ License: MIT
6
+ Project-URL: Repository, https://github.com/Shubham-786/ai-change-impact
7
+ Project-URL: Issues, https://github.com/Shubham-786/ai-change-impact/issues
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Testing
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+
17
+ # AI Change Impact
18
+
19
+ 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.
20
+
21
+ **Status: alpha prototype.** Its API may change. It reports known line-level dependencies, not every potentially affected answer.
22
+
23
+ ## How it works
24
+
25
+ ```text
26
+ RAG application Document update
27
+ | |
28
+ | record question, source, | before and after text
29
+ | document hash and line span |
30
+ v v
31
+ Local SQLite observations ----------> line diff + span matching
32
+ |
33
+ v
34
+ affected observations + stale versions
35
+ |
36
+ optional caller-provided replay
37
+ ```
38
+
39
+ 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.
40
+
41
+ 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.
42
+
43
+ ## Installation
44
+
45
+ Requires Python 3.10 or newer. Install from PyPI:
46
+
47
+ ```bash
48
+ python -m pip install ai-change-impact-prototype
49
+ ```
50
+
51
+ Alternatively, install from the source checkout:
52
+
53
+ ```bash
54
+ git clone https://github.com/Shubham-786/ai-change-impact.git
55
+ cd ai-change-impact
56
+ python -m pip install .
57
+ ```
58
+
59
+ To build a local wheel, run `python -m pip install build` and then `python -m build`.
60
+
61
+ ## Record and replay from Python
62
+
63
+ No external service is required for recording or comparison.
64
+
65
+ ```python
66
+ from change_impact import ImpactStore, replay
67
+
68
+ before = "# Refund policy\nRefunds within 30 days.\n"
69
+ after = "# Refund policy\nRefunds within 14 days.\n"
70
+
71
+ with ImpactStore("impact.sqlite3") as store:
72
+ store.record(source="refund-policy", document=before, question="Refund period?",
73
+ start_line=2, end_line=2, answer="30 days")
74
+ report = store.compare(source="refund-policy", before=before, after=after)
75
+
76
+ # Your callable must use the candidate index or document version.
77
+ results = replay(report, lambda question: "14 days")
78
+ print(results[0]["changed"]) # True
79
+ ```
80
+
81
+ `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.
82
+
83
+ ## Command-line example
84
+
85
+ From the repository directory, compare the included example documents:
86
+
87
+ ```bash
88
+ impact-prototype examples/before.md examples/after.md examples/records.json --source policy
89
+ ```
90
+
91
+ 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.
92
+
93
+ ## Direct comparison without SQLite
94
+
95
+ 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`.
96
+
97
+ ```python
98
+ from impact_prototype import analyze, document_hash
99
+
100
+ before = "Refunds within 30 days.\n"
101
+ records = [{"source": "policy", "question": "Refund period?", "start_line": 1,
102
+ "end_line": 1, "document_hash": document_hash(before)}]
103
+ report = analyze(before, "Refunds within 14 days.\n", records, source="policy")
104
+ ```
105
+
106
+ ## Scope and validation
107
+
108
+ 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.
109
+
110
+ 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.
111
+
112
+ ## Data and security
113
+
114
+ 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.
115
+
116
+ 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.
117
+
118
+ 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.
119
+
120
+ ## Development
121
+
122
+ 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.
123
+
124
+ ## License
125
+
126
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ change_impact.py
4
+ impact_prototype.py
5
+ pyproject.toml
6
+ ai_change_impact_prototype.egg-info/PKG-INFO
7
+ ai_change_impact_prototype.egg-info/SOURCES.txt
8
+ ai_change_impact_prototype.egg-info/dependency_links.txt
9
+ ai_change_impact_prototype.egg-info/entry_points.txt
10
+ ai_change_impact_prototype.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ impact-prototype = impact_prototype:main
@@ -0,0 +1,2 @@
1
+ change_impact
2
+ impact_prototype
@@ -0,0 +1,81 @@
1
+ """Local provenance storage and targeted replay for RAG applications.
2
+
3
+ Line numbers refer to the exact source text, using 1-based inclusive ranges.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import sqlite3
9
+ from pathlib import Path
10
+ from typing import Any, Callable
11
+
12
+ from impact_prototype import analyze, document_hash
13
+
14
+
15
+ class ImpactStore:
16
+ """A SQLite-backed collection of retrieval observations.
17
+
18
+ Use one instance per thread. The database contains questions and optional
19
+ answers, so callers should store it with appropriate access controls.
20
+ """
21
+
22
+ def __init__(self, path: str | Path = "impact.sqlite3") -> None:
23
+ self._db = sqlite3.connect(str(path))
24
+ self._db.execute("""CREATE TABLE IF NOT EXISTS observations (
25
+ id INTEGER PRIMARY KEY, source TEXT NOT NULL, document_hash TEXT NOT NULL,
26
+ question TEXT NOT NULL, start_line INTEGER NOT NULL, end_line INTEGER NOT NULL,
27
+ answer TEXT, metadata TEXT NOT NULL
28
+ )""")
29
+ self._db.execute("CREATE INDEX IF NOT EXISTS observations_source ON observations(source)")
30
+ self._db.commit()
31
+
32
+ def __enter__(self) -> ImpactStore:
33
+ return self
34
+
35
+ def __exit__(self, *args: Any) -> None:
36
+ self.close()
37
+
38
+ def close(self) -> None:
39
+ self._db.close()
40
+
41
+ def record(self, *, source: str, document: str, question: str, start_line: int,
42
+ end_line: int, answer: str | None = None,
43
+ metadata: dict[str, Any] | None = None) -> int:
44
+ """Store one retrieved passage and return its observation ID."""
45
+ if not source or not question:
46
+ raise ValueError("source and question must be nonempty")
47
+ if type(start_line) is not int or type(end_line) is not int or not 1 <= start_line <= end_line <= len(document.splitlines()):
48
+ raise ValueError("line range must be within the document")
49
+ encoded = json.dumps(metadata if metadata is not None else {}, allow_nan=False)
50
+ with self._db:
51
+ cursor = self._db.execute(
52
+ "INSERT INTO observations(source, document_hash, question, start_line, end_line, answer, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)",
53
+ (source, document_hash(document), question, start_line, end_line, answer, encoded))
54
+ return int(cursor.lastrowid)
55
+
56
+ def compare(self, *, source: str, before: str, after: str) -> dict[str, Any]:
57
+ """Return known affected observations and version mismatches."""
58
+ rows = self._db.execute(
59
+ "SELECT id, source, document_hash, question, start_line, end_line, answer, metadata FROM observations WHERE source = ? ORDER BY id",
60
+ (source,)).fetchall()
61
+ records = [dict(zip(("id", "source", "document_hash", "question", "start_line", "end_line", "answer", "metadata"), row)) for row in rows]
62
+ for record in records:
63
+ record["metadata"] = json.loads(record["metadata"])
64
+ return analyze(before, after, records, source)
65
+
66
+
67
+ def replay(report: dict[str, Any], pipeline: Callable[[str], str]) -> list[dict[str, Any]]:
68
+ """Call the supplied pipeline once per affected observation.
69
+
70
+ This executes application code and may incur costs or side effects. It does
71
+ not change or configure the pipeline's data source. Exceptions propagate.
72
+ """
73
+ results = []
74
+ for item in report["affected"]:
75
+ candidate = pipeline(item["question"])
76
+ if not isinstance(candidate, str):
77
+ raise TypeError("pipeline must return a string")
78
+ results.append({"observation_id": item.get("id"), "question": item["question"],
79
+ "baseline_answer": item.get("answer"), "candidate_answer": candidate,
80
+ "changed": None if item.get("answer") is None else item["answer"] != candidate})
81
+ return results
@@ -0,0 +1,62 @@
1
+ """Document change impact based on explicitly recorded line provenance."""
2
+ import argparse
3
+ import difflib
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+
8
+
9
+ def document_hash(text: str) -> str:
10
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
11
+
12
+
13
+ def analyze(before: str, after: str, records: list[dict], source: str) -> dict:
14
+ """Compare texts against 1-based inclusive spans recorded for the old text.
15
+
16
+ Insertions are considered to touch both adjacent lines, conservatively.
17
+ Records for other documents are ignored; old-version mismatches are reported.
18
+ """
19
+ old, new = before.splitlines(), after.splitlines()
20
+ changes = []
21
+ for tag, i, j, k, l in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
22
+ if tag == "equal":
23
+ continue
24
+ start, end = (max(1, i), min(len(old), i + 1)) if i == j else (i + 1, j)
25
+ changes.append({"kind": tag, "old_lines": [start, end], "new_lines": [k + 1, l],
26
+ "before": old[i:j], "after": new[k:l]})
27
+ affected, stale = [], []
28
+ for record in records:
29
+ if record.get("source") != source:
30
+ continue
31
+ if record.get("document_hash") != document_hash(before):
32
+ stale.append(record.get("question", ""))
33
+ continue
34
+ start, end = record["start_line"], record["end_line"]
35
+ if not isinstance(start, int) or not isinstance(end, int) or not (1 <= start <= end <= len(old)):
36
+ raise ValueError(f"Invalid recorded span: {start}..{end}")
37
+ matches = [c for c in changes if c["old_lines"][0] <= end and c["old_lines"][1] >= start]
38
+ if matches:
39
+ affected.append({"id": record.get("id"), "question": record["question"],
40
+ "answer": record.get("answer"), "metadata": record.get("metadata", {}),
41
+ "span": [start, end], "changes": matches})
42
+ return {"source": source, "old_hash": document_hash(before), "new_hash": document_hash(after),
43
+ "changes": changes, "affected": affected, "version_mismatches": stale}
44
+
45
+
46
+ def main() -> None:
47
+ parser = argparse.ArgumentParser(description="Find recorded questions touching changed document lines")
48
+ parser.add_argument("before", type=Path)
49
+ parser.add_argument("after", type=Path)
50
+ parser.add_argument("records", type=Path, help="JSON list of retrieval provenance records")
51
+ parser.add_argument("--source", required=True, help="Stable source identifier recorded during retrieval")
52
+ args = parser.parse_args()
53
+ try:
54
+ result = analyze(args.before.read_text(encoding="utf-8"), args.after.read_text(encoding="utf-8"),
55
+ json.loads(args.records.read_text(encoding="utf-8")), args.source)
56
+ except (ValueError, KeyError, TypeError, OSError) as exc:
57
+ parser.error(str(exc))
58
+ print(json.dumps(result, indent=2, ensure_ascii=False))
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main()
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=65", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ai-change-impact-prototype"
7
+ version = "0.1.0"
8
+ description = "Local prototype for finding recorded RAG questions affected by document changes"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.10"
12
+ dependencies = []
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Software Development :: Testing",
19
+ ]
20
+
21
+ [project.urls]
22
+ Repository = "https://github.com/Shubham-786/ai-change-impact"
23
+ Issues = "https://github.com/Shubham-786/ai-change-impact/issues"
24
+
25
+ [project.scripts]
26
+ impact-prototype = "impact_prototype:main"
27
+
28
+ [tool.setuptools]
29
+ py-modules = ["impact_prototype", "change_impact"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+