evidenceflow 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,377 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+
27
+ (a) that the initial Contributor has attached the notice described
28
+ in Exhibit B to the Covered Software; or
29
+
30
+ (b) that the Covered Software was made available under the terms of
31
+ version 1.1 or earlier of the License, but not also under the
32
+ terms of a Secondary License.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form of the work other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+
52
+ (a) any file in Source Code Form that results from an addition to,
53
+ deletion from, or modification of the contents of Covered
54
+ Software; or
55
+
56
+ (b) any new file in Source Code Form that contains any Covered
57
+ Software.
58
+
59
+ 1.11. "Patent Claims" of a Contributor
60
+ means any patent claim(s), including without limitation, method,
61
+ process, and apparatus claims, in any patent Licensable by such
62
+ Contributor that would be infringed, but for the grant of the
63
+ License, by the making, using, selling, offering for sale, having
64
+ made, import, or transfer of either its Contributions or its
65
+ Contributor Version.
66
+
67
+ 1.12. "Secondary License"
68
+ means either the GNU General Public License, Version 2.0, the GNU
69
+ Lesser General Public License, Version 2.1, the GNU Affero General
70
+ Public License, Version 3.0, or any later versions of those
71
+ licenses.
72
+
73
+ 1.13. "Source Code Form"
74
+ means the form of the work preferred for making modifications.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your choice to
136
+ distribute the Covered Software under a subsequent version of this
137
+ License (see Section 10.2) or under the terms of a Secondary License (if
138
+ permitted under the terms of Section 3.3).
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be made available in Source Code
175
+ Form, as described in Section 3.1, and You must inform recipients of
176
+ the Executable Form how they can obtain a copy of such Source Code
177
+ Form by reasonable means in a timely manner, at a charge no more
178
+ than the cost of distribution to the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipients' rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of either this License or such Secondary
196
+ License(s).
197
+
198
+ 3.4. Notices
199
+
200
+ You may not remove or alter the substance of any license notices
201
+ (including copyright notices, patent notices, disclaimers of warranty,
202
+ or limitations of liability) contained within the Source Code Form of
203
+ the Covered Software, except that You may alter any license notices to
204
+ the extent required to remedy known factual inaccuracies.
205
+
206
+ 3.5. Application of Additional Terms
207
+
208
+ You may choose to offer, and to charge a fee for, warranty, support,
209
+ indemnity or liability obligations to one or more recipients of Covered
210
+ Software. However, You may do so only on Your own behalf, and not on
211
+ behalf of any Contributor. You must make it absolutely clear that any
212
+ such warranty, support, indemnity, or liability obligation is offered by
213
+ You alone, and You hereby agree to indemnify every Contributor for any
214
+ liability incurred by such Contributor as a result of warranty, support,
215
+ indemnity or liability terms You offer. You may include additional
216
+ disclaimers of warranty and limitations of liability specific to any
217
+ jurisdiction.
218
+
219
+ 4. Inability to Comply Due to Statute or Regulation
220
+ ---------------------------------------------------
221
+
222
+ If it is impossible for You to comply with any of the terms of this
223
+ License with respect to some or all of the Covered Software due to
224
+ statute, judicial order, or regulation then You must: (a) comply with
225
+ the terms of this License to the maximum extent possible; and (b)
226
+ describe the limitations and the code they affect. Such description must
227
+ be placed in a text file included with all distributions of the Covered
228
+ Software under this License. Except to the extent prohibited by statute
229
+ or regulation, such description must be sufficiently detailed for a
230
+ recipient of ordinary skill to be able to understand it.
231
+
232
+ 5. Termination
233
+ --------------
234
+
235
+ 5.1. The rights granted under this License will terminate automatically
236
+ if You fail to comply with any of its terms. However, if You become
237
+ compliant, then the rights granted under this License from a particular
238
+ Contributor are reinstated (a) provisionally, unless and until such
239
+ Contributor explicitly and finally terminates Your grants, and (b) on an
240
+ ongoing basis, if such Contributor fails to notify You of the
241
+ non-compliance by some reasonable means prior to 60 days after You have
242
+ come back into compliance. Moreover, Your grants from a particular
243
+ Contributor are reinstated on an ongoing basis if such Contributor
244
+ notifies You of the non-compliance by some reasonable means, this is the
245
+ first time You have received notice of non-compliance with this License
246
+ from such Contributor, and You become compliant prior to 30 days after
247
+ Your receipt of the notice.
248
+
249
+ 5.2. If You initiate litigation against any entity by asserting a patent
250
+ infringement claim (excluding declaratory judgment actions,
251
+ counter-claims, and cross-claims) alleging that a Contributor Version
252
+ directly or indirectly infringes any patent, then the rights granted to
253
+ You by any and all Contributors for the Covered Software under Section
254
+ 2.1 of this License shall terminate.
255
+
256
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257
+ end user license agreements (excluding distributors and resellers) which
258
+ have been validly granted by You or Your distributors under this License
259
+ prior to termination shall survive termination.
260
+
261
+ ************************************************************************
262
+ * *
263
+ * 6. Disclaimer of Warranty *
264
+ * ------------------------- *
265
+ * *
266
+ * Covered Software is provided under this License on an "as is" *
267
+ * basis, without warranty of any kind, either expressed, implied, or *
268
+ * statutory, including, without limitation, warranties that the *
269
+ * Covered Software is free of defects, merchantable, fit for a *
270
+ * particular purpose or non-infringing. The entire risk as to the *
271
+ * quality and performance of the Covered Software is with You. *
272
+ * Should any Covered Software prove defective in any respect, You *
273
+ * (not any Contributor) assume the cost of any necessary servicing, *
274
+ * repair, or correction. This disclaimer of warranty constitutes an *
275
+ * essential part of this License. No use of any Covered Software is *
276
+ * authorized under this License except under this disclaimer. *
277
+ * *
278
+ ************************************************************************
279
+
280
+ ************************************************************************
281
+ * *
282
+ * 7. Limitation of Liability *
283
+ * -------------------------- *
284
+ * *
285
+ * Under no circumstances and under no legal theory, whether tort *
286
+ * (including negligence), contract, or otherwise, shall any *
287
+ * Contributor, or anyone who distributes Covered Software as *
288
+ * permitted above, be liable to You for any direct, indirect, *
289
+ * special, incidental, or consequential damages of any character *
290
+ * including, without limitation, damages for lost profits, loss of *
291
+ * goodwill, work stoppage, computer failure or malfunction, or any *
292
+ * and all other commercial damages or losses, even if such party *
293
+ * shall have been informed of the possibility of such damages. This *
294
+ * limitation of liability shall not apply to liability for death or *
295
+ * personal injury resulting from such party's negligence to the *
296
+ * extent applicable law prohibits such limitation. Some *
297
+ * jurisdictions do not allow the exclusion or limitation of *
298
+ * incidental or consequential damages, so this exclusion and *
299
+ * limitation may not apply to You. *
300
+ * *
301
+ ************************************************************************
302
+
303
+ 8. Litigation
304
+ -------------
305
+
306
+ Any litigation relating to this License may be brought only in the
307
+ courts of a jurisdiction where the defendant maintains its principal
308
+ place of business and such litigation shall be governed by laws of that
309
+ jurisdiction, without reference to its conflict-of-law provisions.
310
+ Nothing in this Section shall prevent a party's ability to bring
311
+ cross-claims or counter-claims.
312
+
313
+ 9. Miscellaneous
314
+ ----------------
315
+
316
+ This License represents the complete agreement concerning the subject
317
+ matter hereof. If any provision of this License is held to be
318
+ unenforceable, such provision shall be reformed only to the extent
319
+ necessary to make it enforceable. Any law or regulation which provides
320
+ that the language of a contract shall be construed against the drafter
321
+ shall not be used to construe this License against a Contributor.
322
+
323
+ 10. Versions of the License
324
+ ---------------------------
325
+
326
+ 10.1. New Versions
327
+
328
+ Mozilla Foundation is the license steward. Except as provided in Section
329
+ 10.3, no one other than the license steward has the right to modify or
330
+ publish new versions of this License. Each version will be given a
331
+ distinguishing version number.
332
+
333
+ 10.2. Effect of New Versions
334
+
335
+ You may distribute the Covered Software under the terms of the version
336
+ of the License under which You originally received the Covered Software,
337
+ or under the terms of any subsequent version published by the license
338
+ steward.
339
+
340
+ 10.3. Modified Versions
341
+
342
+ If you create software not governed by this License, and you want to
343
+ create a new license for such software, you may create and use a
344
+ modified version of this License if you rename the license and remove
345
+ any references to the name of the license steward (except to note that
346
+ such modified license differs from this License).
347
+
348
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
349
+ Licenses
350
+
351
+ If You choose to distribute Source Code Form that is Incompatible With
352
+ Secondary Licenses under the terms of this version of the License, the
353
+ notice described in Exhibit B of this License must be attached.
354
+
355
+ Exhibit A - Source Code Form License Notice
356
+ -------------------------------------------
357
+
358
+ This Source Code Form is subject to the terms of the Mozilla Public
359
+ License, v. 2.0. If a copy of the MPL was not distributed with this
360
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
361
+
362
+ If it is not possible or desirable to put the notice in a particular
363
+ file, then You may include the notice in a location (such as a LICENSE
364
+ file in a relevant directory) where a recipient would be likely to look
365
+ for such a notice.
366
+
367
+ You may add additional accurate notices of copyright ownership.
368
+
369
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
370
+ ---------------------------------------------------------
371
+
372
+ This Source Code Form is "Incompatible With Secondary Licenses", as
373
+ defined by the Mozilla Public License, v. 2.0.
374
+
375
+ Copyright (c) 2026 Eduardo J. Barrios
376
+
377
+
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.4
2
+ Name: evidenceflow
3
+ Version: 0.1.0
4
+ Summary: Analyze how retrieved and tool-generated evidence propagates through AI-agent execution traces.
5
+ Author-email: "Eduardo J. Barrios" <edujbarrios@outlook.com>
6
+ License-Expression: MPL-2.0
7
+ Project-URL: Homepage, https://github.com/edujbarrios/evidenceflow
8
+ Project-URL: Source, https://github.com/edujbarrios/evidenceflow
9
+ Project-URL: Issues, https://github.com/edujbarrios/evidenceflow/issues
10
+ Keywords: ai,agents,llm,rag,observability,evaluation,tracing,evidence,provenance,tool-calling,information-flow
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Operating System :: OS Independent
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest; extra == "dev"
24
+ Requires-Dist: build; extra == "dev"
25
+ Requires-Dist: twine; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # EvidenceFlow
29
+
30
+ [![PyPI version](https://img.shields.io/pypi/v/evidenceflow.svg?label=PyPI&logo=pypi&cacheSeconds=300)](https://pypi.org/project/evidenceflow/)
31
+ [![License: MPL 2.0](https://img.shields.io/badge/license-MPL%202.0-blue.svg)](https://github.com/edujbarrios/evidenceflow/blob/main/LICENSE)
32
+
33
+ Track how retrieved and tool-generated evidence propagates through AI-agent traces.
34
+
35
+ EvidenceFlow is a lightweight deterministic Python library for measuring apparent evidence reuse across retrieval, tool results, intermediate reasoning, and final outputs.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install evidenceflow
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ ```python
46
+ from evidenceflow import analyze
47
+
48
+ trace = [
49
+ {"id": "1", "type": "user", "content": "Where were the 1992 Summer Olympics held?"},
50
+ {
51
+ "id": "2",
52
+ "type": "tool_result",
53
+ "tool": "search",
54
+ "content": "The 1992 Summer Olympics were held in Barcelona, Spain.",
55
+ },
56
+ {"id": "3", "type": "assistant", "content": "They were held in Barcelona, Spain."},
57
+ ]
58
+
59
+ report = analyze(trace)
60
+
61
+ print(report["final_answer_survival_ratio"])
62
+ print(report["tools"])
63
+ ```
64
+
65
+ ## Why EvidenceFlow?
66
+
67
+ Agent traces can contain much more retrieved or tool-generated text than appears in later reasoning or the final answer. EvidenceFlow provides a small, offline diagnostic for inspecting that flow. It is not an observability platform or model evaluator.
68
+
69
+ * No LLM calls or embeddings
70
+ * No external services, server, database, or dashboard
71
+ * No framework or provider coupling
72
+ * No runtime dependencies
73
+
74
+ ## Trace format
75
+
76
+ Pass any non-string iterable of dictionaries. Every step needs a supported `type`; textual steps also need string `content`. Supported types are `user`, `assistant`, `tool_call`, `tool_result`, `retrieval`, `system`, and `reasoning`. Unknown types raise `ValueError` so silently omitted evidence cannot skew a report.
77
+
78
+ Step IDs are optional and deterministically default to `step-0`, `step-1`, and so on. Supplied IDs must be unique. Evidence is introduced only by `tool_result` and `retrieval` steps in v0.1.0. Their optional `evidence_id` values must be unique; otherwise IDs default to `evidence-0`, `evidence-1`, and so on.
79
+
80
+ ## Analyze evidence flow
81
+
82
+ `analyze(trace)` returns a JSON-serializable dictionary. Its top-level counts include `evidence_units`, `reused_units`, `final_reused_units`, `overall_survival_ratio`, and `final_answer_survival_ratio`. Each item in `evidence` identifies its introduction step and later `assistant` or `reasoning` steps where overlap was detected.
83
+
84
+ The final answer is the last `assistant` step. Evidence introduced after it cannot survive into it. Input dictionaries are never mutated.
85
+
86
+ ## Tool-level analysis
87
+
88
+ `report["tools"]` groups tool results by their `tool` value and reports source and unit counts plus overall and final-answer survival ratios. These are neutral diagnostics: low overlap does not establish that a tool was unnecessary.
89
+
90
+ ## Retrieval/source analysis
91
+
92
+ A retrieval step may provide a `source`, such as `manual.pdf`. `report["sources"]` aggregates the same metrics by that value. Retrieval steps without a source remain in overall metrics but are not placed in a named source group.
93
+
94
+ ## Evidence survival
95
+
96
+ An evidence source's survival ratio is:
97
+
98
+ ```text
99
+ units with detected overlap in a later assistant or reasoning step
100
+ -----------------------------------------------------------------
101
+ evidence units introduced
102
+ ```
103
+
104
+ Final-answer survival uses the same denominator but counts only units detected in the last assistant response. Empty denominators produce `0.0`.
105
+
106
+ Per-source fields also include `reused_at`, `reuse_count`, `last_reuse_step`, and `steps_until_last_reuse`.
107
+
108
+ ## Repeated and unused evidence
109
+
110
+ `unused_evidence` lists sources with no units apparently reused later. `repeated_evidence_groups` lists connected groups of evidence sources whose units substantially overlap. Groups are transitive and ordered by trace position. Neither result proves semantic redundancy or non-use.
111
+
112
+ ## How it works
113
+
114
+ EvidenceFlow normalizes Unicode and case, handles punctuation while preserving values such as `3.14`, `2026`, and `GPT-5`, and splits evidence on simple sentence or paragraph boundaries. Segments with fewer than two informative words are ignored. A small fixed stop-word list reduces noise.
115
+
116
+ A unit matches when its normalized text is contained in a later step, or when at least two informative words overlap and they cover at least half of the unit's unique informative words. This deliberately simple rule is deterministic and readable in `src/evidenceflow/core.py`.
117
+
118
+ ## Use cases
119
+
120
+ * Inspect which tool outputs have high or low detected downstream coverage
121
+ * Find retrieval sources whose text appears in a final response
122
+ * Surface large evidence acquisitions with no detected later overlap
123
+ * Track apparent propagation through intermediate reasoning steps
124
+ * Add deterministic information-flow checks to CI
125
+
126
+ ## Features
127
+
128
+ * Plain dictionary input and JSON-serializable output
129
+ * Tool-level and retrieval-source aggregation
130
+ * Per-evidence propagation and simple decay fields
131
+ * Apparently unused and repeated evidence diagnostics
132
+ * Deterministic IDs and output
133
+ * Standard-library-only runtime
134
+
135
+ ## Limitations
136
+
137
+ EvidenceFlow measures lexical overlap. It does **not** prove causal influence, model attention, hidden-state influence, semantic equivalence, factual correctness, or answer quality. Evidence may be paraphrased, summarized, transformed, inferred, or omitted from visible text while still affecting model behavior. Conversely, lexical overlap may be coincidental. Low detected survival therefore does not mean evidence was useless.
138
+
139
+ The sentence splitter is intentionally simple, the fixed stop-word list is English-oriented, and the lexical threshold can produce false positives and false negatives. v0.1.0 does not include embeddings, custom scorers, trace adapters, visual evidence, graph export, HTML reports, or streaming traces.
140
+
141
+ ## Issues
142
+
143
+ Report issues in the [GitHub issue tracker](https://github.com/edujbarrios/evidenceflow/issues).
144
+
145
+ ## Author
146
+
147
+ Eduardo J. Barrios — [edujbarrios@outlook.com](mailto:edujbarrios@outlook.com)
148
+
149
+ ## License
150
+
151
+ [Mozilla Public License 2.0](https://github.com/edujbarrios/evidenceflow/blob/main/LICENSE)
@@ -0,0 +1,124 @@
1
+ # EvidenceFlow
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/evidenceflow.svg?label=PyPI&logo=pypi&cacheSeconds=300)](https://pypi.org/project/evidenceflow/)
4
+ [![License: MPL 2.0](https://img.shields.io/badge/license-MPL%202.0-blue.svg)](https://github.com/edujbarrios/evidenceflow/blob/main/LICENSE)
5
+
6
+ Track how retrieved and tool-generated evidence propagates through AI-agent traces.
7
+
8
+ EvidenceFlow is a lightweight deterministic Python library for measuring apparent evidence reuse across retrieval, tool results, intermediate reasoning, and final outputs.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pip install evidenceflow
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ```python
19
+ from evidenceflow import analyze
20
+
21
+ trace = [
22
+ {"id": "1", "type": "user", "content": "Where were the 1992 Summer Olympics held?"},
23
+ {
24
+ "id": "2",
25
+ "type": "tool_result",
26
+ "tool": "search",
27
+ "content": "The 1992 Summer Olympics were held in Barcelona, Spain.",
28
+ },
29
+ {"id": "3", "type": "assistant", "content": "They were held in Barcelona, Spain."},
30
+ ]
31
+
32
+ report = analyze(trace)
33
+
34
+ print(report["final_answer_survival_ratio"])
35
+ print(report["tools"])
36
+ ```
37
+
38
+ ## Why EvidenceFlow?
39
+
40
+ Agent traces can contain much more retrieved or tool-generated text than appears in later reasoning or the final answer. EvidenceFlow provides a small, offline diagnostic for inspecting that flow. It is not an observability platform or model evaluator.
41
+
42
+ * No LLM calls or embeddings
43
+ * No external services, server, database, or dashboard
44
+ * No framework or provider coupling
45
+ * No runtime dependencies
46
+
47
+ ## Trace format
48
+
49
+ Pass any non-string iterable of dictionaries. Every step needs a supported `type`; textual steps also need string `content`. Supported types are `user`, `assistant`, `tool_call`, `tool_result`, `retrieval`, `system`, and `reasoning`. Unknown types raise `ValueError` so silently omitted evidence cannot skew a report.
50
+
51
+ Step IDs are optional and deterministically default to `step-0`, `step-1`, and so on. Supplied IDs must be unique. Evidence is introduced only by `tool_result` and `retrieval` steps in v0.1.0. Their optional `evidence_id` values must be unique; otherwise IDs default to `evidence-0`, `evidence-1`, and so on.
52
+
53
+ ## Analyze evidence flow
54
+
55
+ `analyze(trace)` returns a JSON-serializable dictionary. Its top-level counts include `evidence_units`, `reused_units`, `final_reused_units`, `overall_survival_ratio`, and `final_answer_survival_ratio`. Each item in `evidence` identifies its introduction step and later `assistant` or `reasoning` steps where overlap was detected.
56
+
57
+ The final answer is the last `assistant` step. Evidence introduced after it cannot survive into it. Input dictionaries are never mutated.
58
+
59
+ ## Tool-level analysis
60
+
61
+ `report["tools"]` groups tool results by their `tool` value and reports source and unit counts plus overall and final-answer survival ratios. These are neutral diagnostics: low overlap does not establish that a tool was unnecessary.
62
+
63
+ ## Retrieval/source analysis
64
+
65
+ A retrieval step may provide a `source`, such as `manual.pdf`. `report["sources"]` aggregates the same metrics by that value. Retrieval steps without a source remain in overall metrics but are not placed in a named source group.
66
+
67
+ ## Evidence survival
68
+
69
+ An evidence source's survival ratio is:
70
+
71
+ ```text
72
+ units with detected overlap in a later assistant or reasoning step
73
+ -----------------------------------------------------------------
74
+ evidence units introduced
75
+ ```
76
+
77
+ Final-answer survival uses the same denominator but counts only units detected in the last assistant response. Empty denominators produce `0.0`.
78
+
79
+ Per-source fields also include `reused_at`, `reuse_count`, `last_reuse_step`, and `steps_until_last_reuse`.
80
+
81
+ ## Repeated and unused evidence
82
+
83
+ `unused_evidence` lists sources with no units apparently reused later. `repeated_evidence_groups` lists connected groups of evidence sources whose units substantially overlap. Groups are transitive and ordered by trace position. Neither result proves semantic redundancy or non-use.
84
+
85
+ ## How it works
86
+
87
+ EvidenceFlow normalizes Unicode and case, handles punctuation while preserving values such as `3.14`, `2026`, and `GPT-5`, and splits evidence on simple sentence or paragraph boundaries. Segments with fewer than two informative words are ignored. A small fixed stop-word list reduces noise.
88
+
89
+ A unit matches when its normalized text is contained in a later step, or when at least two informative words overlap and they cover at least half of the unit's unique informative words. This deliberately simple rule is deterministic and readable in `src/evidenceflow/core.py`.
90
+
91
+ ## Use cases
92
+
93
+ * Inspect which tool outputs have high or low detected downstream coverage
94
+ * Find retrieval sources whose text appears in a final response
95
+ * Surface large evidence acquisitions with no detected later overlap
96
+ * Track apparent propagation through intermediate reasoning steps
97
+ * Add deterministic information-flow checks to CI
98
+
99
+ ## Features
100
+
101
+ * Plain dictionary input and JSON-serializable output
102
+ * Tool-level and retrieval-source aggregation
103
+ * Per-evidence propagation and simple decay fields
104
+ * Apparently unused and repeated evidence diagnostics
105
+ * Deterministic IDs and output
106
+ * Standard-library-only runtime
107
+
108
+ ## Limitations
109
+
110
+ EvidenceFlow measures lexical overlap. It does **not** prove causal influence, model attention, hidden-state influence, semantic equivalence, factual correctness, or answer quality. Evidence may be paraphrased, summarized, transformed, inferred, or omitted from visible text while still affecting model behavior. Conversely, lexical overlap may be coincidental. Low detected survival therefore does not mean evidence was useless.
111
+
112
+ The sentence splitter is intentionally simple, the fixed stop-word list is English-oriented, and the lexical threshold can produce false positives and false negatives. v0.1.0 does not include embeddings, custom scorers, trace adapters, visual evidence, graph export, HTML reports, or streaming traces.
113
+
114
+ ## Issues
115
+
116
+ Report issues in the [GitHub issue tracker](https://github.com/edujbarrios/evidenceflow/issues).
117
+
118
+ ## Author
119
+
120
+ Eduardo J. Barrios — [edujbarrios@outlook.com](mailto:edujbarrios@outlook.com)
121
+
122
+ ## License
123
+
124
+ [Mozilla Public License 2.0](https://github.com/edujbarrios/evidenceflow/blob/main/LICENSE)
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "evidenceflow"
7
+ version = "0.1.0"
8
+ description = "Analyze how retrieved and tool-generated evidence propagates through AI-agent execution traces."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MPL-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Eduardo J. Barrios", email = "edujbarrios@outlook.com" }]
14
+ keywords = ["ai", "agents", "llm", "rag", "observability", "evaluation", "tracing", "evidence", "provenance", "tool-calling", "information-flow"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Operating System :: OS Independent",
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ dev = ["pytest", "build", "twine"]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/edujbarrios/evidenceflow"
31
+ Source = "https://github.com/edujbarrios/evidenceflow"
32
+ Issues = "https://github.com/edujbarrios/evidenceflow/issues"
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ addopts = "-ra"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from .core import analyze
2
+
3
+ __all__ = ["analyze"]
4
+ __version__ = "0.1.0"
@@ -0,0 +1,244 @@
1
+ """Deterministic lexical evidence-flow analysis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+ from collections.abc import Iterable, Mapping
8
+ from typing import Any
9
+
10
+ _KNOWN_TYPES = {"user", "assistant", "tool_call", "tool_result", "retrieval", "system", "reasoning"}
11
+ _EVIDENCE_TYPES = {"tool_result", "retrieval"}
12
+ _TEXT_TYPES = {"user", "assistant", "tool_result", "retrieval", "system", "reasoning"}
13
+ _STOP_WORDS = {
14
+ "a", "an", "and", "are", "as", "at", "be", "been", "by", "for", "from",
15
+ "in", "is", "it", "of", "on", "or", "that", "the", "their", "this", "to",
16
+ "was", "were", "with",
17
+ }
18
+ _TOKEN_RE = re.compile(r"[^\W_]+(?:[.-][^\W_]+)*", re.UNICODE)
19
+ _BOUNDARY_RE = re.compile(r"(?:\r?\n\s*){2,}|(?<=[.!?])\s+(?=[^\W_])", re.UNICODE)
20
+
21
+
22
+ def _normalize_text(text: str) -> str:
23
+ text = unicodedata.normalize("NFKC", text).lower()
24
+ return " ".join(_TOKEN_RE.findall(text))
25
+
26
+
27
+ def _tokens(text: str) -> tuple[str, ...]:
28
+ return tuple(token for token in _normalize_text(text).split() if token not in _STOP_WORDS)
29
+
30
+
31
+ def _split_units(text: str) -> list[dict[str, Any]]:
32
+ units = []
33
+ for segment in _BOUNDARY_RE.split(text.strip()):
34
+ normalized = _normalize_text(segment)
35
+ tokens = _tokens(segment)
36
+ if len(tokens) < 2:
37
+ continue
38
+ units.append({"text": segment.strip(), "normalized": normalized, "tokens": tokens})
39
+ return units
40
+
41
+
42
+ def _matches(unit: Mapping[str, Any], later_text: str) -> bool:
43
+ later_normalized = _normalize_text(later_text)
44
+ if not later_normalized:
45
+ return False
46
+ normalized = unit["normalized"]
47
+ if normalized and f" {normalized} " in f" {later_normalized} ":
48
+ return True
49
+ source_tokens = set(unit["tokens"])
50
+ later_tokens = set(_tokens(later_text))
51
+ overlap = len(source_tokens & later_tokens)
52
+ return overlap >= 2 and overlap / len(source_tokens) >= 0.5
53
+
54
+
55
+ def _validate_trace(trace: Any) -> list[dict[str, Any]]:
56
+ if isinstance(trace, (str, bytes)) or not isinstance(trace, Iterable):
57
+ raise TypeError("trace must be a non-string iterable of mappings")
58
+ steps = []
59
+ seen_ids = set()
60
+ for index, raw_step in enumerate(trace):
61
+ if not isinstance(raw_step, Mapping):
62
+ raise TypeError(f"step {index} must be a mapping")
63
+ step = dict(raw_step)
64
+ step_type = step.get("type")
65
+ if not isinstance(step_type, str) or step_type not in _KNOWN_TYPES:
66
+ raise ValueError(f"step {index} has unsupported type {step_type!r}")
67
+ step_id = step.get("id", f"step-{index}")
68
+ if not isinstance(step_id, str) or not step_id:
69
+ raise ValueError(f"step {index} id must be a non-empty string")
70
+ if step_id in seen_ids:
71
+ raise ValueError(f"duplicate step id: {step_id!r}")
72
+ seen_ids.add(step_id)
73
+ if step_type in _TEXT_TYPES:
74
+ content = step.get("content")
75
+ if not isinstance(content, str):
76
+ raise TypeError(f"step {index} content must be a string")
77
+ if step_type == "tool_call" and "tool" in step and not isinstance(step["tool"], str):
78
+ raise TypeError(f"step {index} tool must be a string")
79
+ if step_type in _EVIDENCE_TYPES:
80
+ for key in ("tool", "source", "evidence_id"):
81
+ if key in step and (not isinstance(step[key], str) or not step[key]):
82
+ raise ValueError(f"step {index} {key} must be a non-empty string")
83
+ step["id"] = step_id
84
+ steps.append(step)
85
+ return steps
86
+
87
+
88
+ def _extract_evidence(steps: list[dict[str, Any]]) -> list[dict[str, Any]]:
89
+ evidence = []
90
+ seen_ids = set()
91
+ for step_index, step in enumerate(steps):
92
+ if step["type"] not in _EVIDENCE_TYPES:
93
+ continue
94
+ evidence_id = step.get("evidence_id", f"evidence-{len(evidence)}")
95
+ if evidence_id in seen_ids:
96
+ raise ValueError(f"duplicate evidence id: {evidence_id!r}")
97
+ seen_ids.add(evidence_id)
98
+ evidence.append({
99
+ "evidence_id": evidence_id,
100
+ "step_id": step["id"],
101
+ "step_index": step_index,
102
+ "source_type": step["type"],
103
+ "tool": step.get("tool"),
104
+ "source": step.get("source"),
105
+ "units": _split_units(step["content"]),
106
+ })
107
+ return evidence
108
+
109
+
110
+ def _ratio(numerator: int, denominator: int) -> float:
111
+ return numerator / denominator if denominator else 0.0
112
+
113
+
114
+ def _aggregate(records: list[dict[str, Any]], key: str) -> dict[str, dict[str, Any]]:
115
+ result: dict[str, dict[str, Any]] = {}
116
+ for record in records:
117
+ name = record[key]
118
+ if name is None:
119
+ continue
120
+ item = result.setdefault(name, {
121
+ "evidence_sources": 0,
122
+ "evidence_units": 0,
123
+ "reused_units": 0,
124
+ "final_reused_units": 0,
125
+ })
126
+ item["evidence_sources"] += 1
127
+ item["evidence_units"] += record["evidence_units"]
128
+ item["reused_units"] += record["reused_units"]
129
+ item["final_reused_units"] += record["final_reused_units"]
130
+ for item in result.values():
131
+ item["survival_ratio"] = _ratio(item["reused_units"], item["evidence_units"])
132
+ item["final_answer_survival_ratio"] = _ratio(
133
+ item["final_reused_units"], item["evidence_units"]
134
+ )
135
+ return result
136
+
137
+
138
+ def _repeated_groups(evidence: list[dict[str, Any]]) -> list[list[str]]:
139
+ adjacency = {item["evidence_id"]: set() for item in evidence}
140
+ for index, left in enumerate(evidence):
141
+ for right in evidence[index + 1:]:
142
+ repeated = any(
143
+ _matches(left_unit, right_unit["text"]) or _matches(right_unit, left_unit["text"])
144
+ for left_unit in left["units"]
145
+ for right_unit in right["units"]
146
+ )
147
+ if repeated:
148
+ adjacency[left["evidence_id"]].add(right["evidence_id"])
149
+ adjacency[right["evidence_id"]].add(left["evidence_id"])
150
+ groups = []
151
+ visited = set()
152
+ for item in evidence:
153
+ evidence_id = item["evidence_id"]
154
+ if evidence_id in visited or not adjacency[evidence_id]:
155
+ continue
156
+ stack = [evidence_id]
157
+ group = []
158
+ visited.add(evidence_id)
159
+ while stack:
160
+ current = stack.pop()
161
+ group.append(current)
162
+ for neighbor in adjacency[current]:
163
+ if neighbor not in visited:
164
+ visited.add(neighbor)
165
+ stack.append(neighbor)
166
+ order = {value["evidence_id"]: i for i, value in enumerate(evidence)}
167
+ groups.append(sorted(group, key=order.get))
168
+ return groups
169
+
170
+
171
+ def analyze(trace: Iterable[Mapping[str, Any]]) -> dict[str, Any]:
172
+ """Analyze apparent lexical evidence reuse in a normalized trace."""
173
+ steps = _validate_trace(trace)
174
+ evidence = _extract_evidence(steps)
175
+ final_index = next(
176
+ (index for index in range(len(steps) - 1, -1, -1) if steps[index]["type"] == "assistant"),
177
+ None,
178
+ )
179
+ records = []
180
+ for item in evidence:
181
+ unit_reuse_steps = []
182
+ for unit in item["units"]:
183
+ reused_at = [
184
+ step["id"]
185
+ for step in steps[item["step_index"] + 1:]
186
+ if step["type"] in {"assistant", "reasoning"} and _matches(unit, step["content"])
187
+ ]
188
+ unit_reuse_steps.append(reused_at)
189
+ reused_units = sum(bool(value) for value in unit_reuse_steps)
190
+ final_reused_units = (
191
+ sum(steps[final_index]["id"] in value for value in unit_reuse_steps)
192
+ if final_index is not None and final_index > item["step_index"] else 0
193
+ )
194
+ reused_at = [
195
+ step["id"]
196
+ for step in steps[item["step_index"] + 1:]
197
+ if any(step["id"] in value for value in unit_reuse_steps)
198
+ ]
199
+ last_index = max((i for i, step in enumerate(steps) if step["id"] in reused_at), default=None)
200
+ records.append({
201
+ "evidence_id": item["evidence_id"],
202
+ "step_id": item["step_id"],
203
+ "source_type": item["source_type"],
204
+ "tool": item["tool"],
205
+ "source": item["source"],
206
+ "evidence_units": len(item["units"]),
207
+ "reused_units": reused_units,
208
+ "final_reused_units": final_reused_units,
209
+ "survival_ratio": _ratio(reused_units, len(item["units"])),
210
+ "final_answer_survival_ratio": _ratio(final_reused_units, len(item["units"])),
211
+ "reused_at": reused_at,
212
+ "reuse_count": len(reused_at),
213
+ "last_reuse_step": steps[last_index]["id"] if last_index is not None else None,
214
+ "steps_until_last_reuse": last_index - item["step_index"] if last_index is not None else None,
215
+ })
216
+
217
+ evidence_units = sum(item["evidence_units"] for item in records)
218
+ reused_units = sum(item["reused_units"] for item in records)
219
+ final_reused_units = sum(item["final_reused_units"] for item in records)
220
+ repeated_groups = _repeated_groups(evidence)
221
+ unused = [
222
+ {
223
+ "evidence_id": item["evidence_id"], "step_id": item["step_id"],
224
+ "tool": item["tool"], "source": item["source"], "evidence_units": item["evidence_units"],
225
+ }
226
+ for item in records if item["reused_units"] == 0
227
+ ]
228
+ return {
229
+ "steps": len(steps),
230
+ "evidence_sources": len(records),
231
+ "tool_results": sum(step["type"] == "tool_result" for step in steps),
232
+ "retrieval_steps": sum(step["type"] == "retrieval" for step in steps),
233
+ "evidence_units": evidence_units,
234
+ "reused_units": reused_units,
235
+ "final_reused_units": final_reused_units,
236
+ "overall_survival_ratio": _ratio(reused_units, evidence_units),
237
+ "final_answer_survival_ratio": _ratio(final_reused_units, evidence_units),
238
+ "apparently_unused_sources": len(unused),
239
+ "evidence": records,
240
+ "tools": _aggregate(records, "tool"),
241
+ "sources": _aggregate(records, "source"),
242
+ "unused_evidence": unused,
243
+ "repeated_evidence_groups": repeated_groups,
244
+ }
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.4
2
+ Name: evidenceflow
3
+ Version: 0.1.0
4
+ Summary: Analyze how retrieved and tool-generated evidence propagates through AI-agent execution traces.
5
+ Author-email: "Eduardo J. Barrios" <edujbarrios@outlook.com>
6
+ License-Expression: MPL-2.0
7
+ Project-URL: Homepage, https://github.com/edujbarrios/evidenceflow
8
+ Project-URL: Source, https://github.com/edujbarrios/evidenceflow
9
+ Project-URL: Issues, https://github.com/edujbarrios/evidenceflow/issues
10
+ Keywords: ai,agents,llm,rag,observability,evaluation,tracing,evidence,provenance,tool-calling,information-flow
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Operating System :: OS Independent
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest; extra == "dev"
24
+ Requires-Dist: build; extra == "dev"
25
+ Requires-Dist: twine; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # EvidenceFlow
29
+
30
+ [![PyPI version](https://img.shields.io/pypi/v/evidenceflow.svg?label=PyPI&logo=pypi&cacheSeconds=300)](https://pypi.org/project/evidenceflow/)
31
+ [![License: MPL 2.0](https://img.shields.io/badge/license-MPL%202.0-blue.svg)](https://github.com/edujbarrios/evidenceflow/blob/main/LICENSE)
32
+
33
+ Track how retrieved and tool-generated evidence propagates through AI-agent traces.
34
+
35
+ EvidenceFlow is a lightweight deterministic Python library for measuring apparent evidence reuse across retrieval, tool results, intermediate reasoning, and final outputs.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install evidenceflow
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ ```python
46
+ from evidenceflow import analyze
47
+
48
+ trace = [
49
+ {"id": "1", "type": "user", "content": "Where were the 1992 Summer Olympics held?"},
50
+ {
51
+ "id": "2",
52
+ "type": "tool_result",
53
+ "tool": "search",
54
+ "content": "The 1992 Summer Olympics were held in Barcelona, Spain.",
55
+ },
56
+ {"id": "3", "type": "assistant", "content": "They were held in Barcelona, Spain."},
57
+ ]
58
+
59
+ report = analyze(trace)
60
+
61
+ print(report["final_answer_survival_ratio"])
62
+ print(report["tools"])
63
+ ```
64
+
65
+ ## Why EvidenceFlow?
66
+
67
+ Agent traces can contain much more retrieved or tool-generated text than appears in later reasoning or the final answer. EvidenceFlow provides a small, offline diagnostic for inspecting that flow. It is not an observability platform or model evaluator.
68
+
69
+ * No LLM calls or embeddings
70
+ * No external services, server, database, or dashboard
71
+ * No framework or provider coupling
72
+ * No runtime dependencies
73
+
74
+ ## Trace format
75
+
76
+ Pass any non-string iterable of dictionaries. Every step needs a supported `type`; textual steps also need string `content`. Supported types are `user`, `assistant`, `tool_call`, `tool_result`, `retrieval`, `system`, and `reasoning`. Unknown types raise `ValueError` so silently omitted evidence cannot skew a report.
77
+
78
+ Step IDs are optional and deterministically default to `step-0`, `step-1`, and so on. Supplied IDs must be unique. Evidence is introduced only by `tool_result` and `retrieval` steps in v0.1.0. Their optional `evidence_id` values must be unique; otherwise IDs default to `evidence-0`, `evidence-1`, and so on.
79
+
80
+ ## Analyze evidence flow
81
+
82
+ `analyze(trace)` returns a JSON-serializable dictionary. Its top-level counts include `evidence_units`, `reused_units`, `final_reused_units`, `overall_survival_ratio`, and `final_answer_survival_ratio`. Each item in `evidence` identifies its introduction step and later `assistant` or `reasoning` steps where overlap was detected.
83
+
84
+ The final answer is the last `assistant` step. Evidence introduced after it cannot survive into it. Input dictionaries are never mutated.
85
+
86
+ ## Tool-level analysis
87
+
88
+ `report["tools"]` groups tool results by their `tool` value and reports source and unit counts plus overall and final-answer survival ratios. These are neutral diagnostics: low overlap does not establish that a tool was unnecessary.
89
+
90
+ ## Retrieval/source analysis
91
+
92
+ A retrieval step may provide a `source`, such as `manual.pdf`. `report["sources"]` aggregates the same metrics by that value. Retrieval steps without a source remain in overall metrics but are not placed in a named source group.
93
+
94
+ ## Evidence survival
95
+
96
+ An evidence source's survival ratio is:
97
+
98
+ ```text
99
+ units with detected overlap in a later assistant or reasoning step
100
+ -----------------------------------------------------------------
101
+ evidence units introduced
102
+ ```
103
+
104
+ Final-answer survival uses the same denominator but counts only units detected in the last assistant response. Empty denominators produce `0.0`.
105
+
106
+ Per-source fields also include `reused_at`, `reuse_count`, `last_reuse_step`, and `steps_until_last_reuse`.
107
+
108
+ ## Repeated and unused evidence
109
+
110
+ `unused_evidence` lists sources with no units apparently reused later. `repeated_evidence_groups` lists connected groups of evidence sources whose units substantially overlap. Groups are transitive and ordered by trace position. Neither result proves semantic redundancy or non-use.
111
+
112
+ ## How it works
113
+
114
+ EvidenceFlow normalizes Unicode and case, handles punctuation while preserving values such as `3.14`, `2026`, and `GPT-5`, and splits evidence on simple sentence or paragraph boundaries. Segments with fewer than two informative words are ignored. A small fixed stop-word list reduces noise.
115
+
116
+ A unit matches when its normalized text is contained in a later step, or when at least two informative words overlap and they cover at least half of the unit's unique informative words. This deliberately simple rule is deterministic and readable in `src/evidenceflow/core.py`.
117
+
118
+ ## Use cases
119
+
120
+ * Inspect which tool outputs have high or low detected downstream coverage
121
+ * Find retrieval sources whose text appears in a final response
122
+ * Surface large evidence acquisitions with no detected later overlap
123
+ * Track apparent propagation through intermediate reasoning steps
124
+ * Add deterministic information-flow checks to CI
125
+
126
+ ## Features
127
+
128
+ * Plain dictionary input and JSON-serializable output
129
+ * Tool-level and retrieval-source aggregation
130
+ * Per-evidence propagation and simple decay fields
131
+ * Apparently unused and repeated evidence diagnostics
132
+ * Deterministic IDs and output
133
+ * Standard-library-only runtime
134
+
135
+ ## Limitations
136
+
137
+ EvidenceFlow measures lexical overlap. It does **not** prove causal influence, model attention, hidden-state influence, semantic equivalence, factual correctness, or answer quality. Evidence may be paraphrased, summarized, transformed, inferred, or omitted from visible text while still affecting model behavior. Conversely, lexical overlap may be coincidental. Low detected survival therefore does not mean evidence was useless.
138
+
139
+ The sentence splitter is intentionally simple, the fixed stop-word list is English-oriented, and the lexical threshold can produce false positives and false negatives. v0.1.0 does not include embeddings, custom scorers, trace adapters, visual evidence, graph export, HTML reports, or streaming traces.
140
+
141
+ ## Issues
142
+
143
+ Report issues in the [GitHub issue tracker](https://github.com/edujbarrios/evidenceflow/issues).
144
+
145
+ ## Author
146
+
147
+ Eduardo J. Barrios — [edujbarrios@outlook.com](mailto:edujbarrios@outlook.com)
148
+
149
+ ## License
150
+
151
+ [Mozilla Public License 2.0](https://github.com/edujbarrios/evidenceflow/blob/main/LICENSE)
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/evidenceflow/__init__.py
5
+ src/evidenceflow/core.py
6
+ src/evidenceflow.egg-info/PKG-INFO
7
+ src/evidenceflow.egg-info/SOURCES.txt
8
+ src/evidenceflow.egg-info/dependency_links.txt
9
+ src/evidenceflow.egg-info/requires.txt
10
+ src/evidenceflow.egg-info/top_level.txt
11
+ tests/test_core.py
@@ -0,0 +1,5 @@
1
+
2
+ [dev]
3
+ pytest
4
+ build
5
+ twine
@@ -0,0 +1 @@
1
+ evidenceflow
@@ -0,0 +1,119 @@
1
+ from copy import deepcopy
2
+ import json
3
+
4
+ import pytest
5
+
6
+ from evidenceflow import analyze
7
+ from evidenceflow.core import _extract_evidence, _matches, _normalize_text, _split_units, _validate_trace
8
+
9
+
10
+ def test_normalization_preserves_values_and_ignores_case_and_punctuation():
11
+ assert _normalize_text(" GPT-5: 3.14, BARCELONA! ") == "gpt-5 3.14 barcelona"
12
+ unit = _split_units("The Olympic host was Barcelona, Spain.")[0]
13
+ assert _matches(unit, "THE OLYMPIC HOST WAS BARCELONA SPAIN")
14
+
15
+
16
+ def test_units_split_and_short_evidence_is_filtered():
17
+ units = _split_units("Yes.\n\nBarcelona hosted the games. Madrid was not selected!")
18
+ assert [item["text"] for item in units] == ["Barcelona hosted the games.", "Madrid was not selected!"]
19
+
20
+
21
+ def test_containment_and_partial_reuse():
22
+ unit = _split_units("The 1992 Summer Olympics were held in Barcelona, Spain.")[0]
23
+ assert _matches(unit, "The 1992 Summer Olympics were held in Barcelona, Spain.")
24
+ assert _matches(unit, "They were held in Barcelona, Spain.")
25
+ assert not _matches(unit, "Athens hosted another sporting event.")
26
+
27
+
28
+ def test_deterministic_ids_and_input_not_mutated():
29
+ trace = [
30
+ {"type": "tool_result", "tool": "search", "content": "Barcelona hosted the games."},
31
+ {"id": "answer", "type": "assistant", "content": "Barcelona hosted the games."},
32
+ ]
33
+ original = deepcopy(trace)
34
+ evidence = _extract_evidence(_validate_trace(trace))
35
+ assert evidence[0]["evidence_id"] == "evidence-0"
36
+ assert _validate_trace(trace)[0]["id"] == "step-0"
37
+ assert trace == original
38
+
39
+
40
+ @pytest.mark.parametrize("trace,error", [
41
+ (None, TypeError), ("bad", TypeError), ([1], TypeError), ([{}], ValueError),
42
+ ([{"type": "unknown"}], ValueError), ([{"type": "assistant"}], TypeError),
43
+ ([{"type": "tool_result", "content": None}], TypeError),
44
+ ([{"id": "x", "type": "user", "content": "a"}, {"id": "x", "type": "assistant", "content": "b"}], ValueError),
45
+ ])
46
+ def test_invalid_trace_structures(trace, error):
47
+ with pytest.raises(error):
48
+ analyze(trace)
49
+
50
+
51
+ def test_duplicate_supplied_evidence_ids():
52
+ trace = [
53
+ {"type": "retrieval", "evidence_id": "same", "content": "First useful sentence."},
54
+ {"type": "retrieval", "evidence_id": "same", "content": "Second useful sentence."},
55
+ ]
56
+ with pytest.raises(ValueError, match="duplicate evidence id"):
57
+ analyze(trace)
58
+
59
+
60
+ def test_empty_trace_and_trace_without_evidence():
61
+ empty = analyze([])
62
+ assert empty["steps"] == empty["evidence_units"] == 0
63
+ assert empty["overall_survival_ratio"] == empty["final_answer_survival_ratio"] == 0.0
64
+ report = analyze([{"type": "assistant", "content": "No evidence was retrieved."}])
65
+ assert report["evidence"] == [] and report["tools"] == {}
66
+
67
+
68
+ def test_hand_computed_flow_tool_source_and_final_metrics():
69
+ trace = [
70
+ {"id": "q", "type": "user", "content": "Where were the games held?"},
71
+ {"id": "r1", "type": "tool_result", "tool": "search", "content":
72
+ "Barcelona hosted the 1992 Olympics.\n\nThe mascot was Cobi."},
73
+ {"id": "thought", "type": "reasoning", "content": "Barcelona hosted the 1992 Olympics."},
74
+ {"id": "r2", "type": "retrieval", "source": "manual.pdf", "content":
75
+ "The games took place in Barcelona.\n\nSailing happened on the coast."},
76
+ {"id": "answer", "type": "assistant", "content": "The games took place in Barcelona."},
77
+ ]
78
+ report = analyze(trace)
79
+ assert report["steps"] == 5 and report["evidence_sources"] == 2
80
+ assert report["evidence_units"] == 4
81
+ assert report["reused_units"] == 2
82
+ assert report["final_reused_units"] == 1
83
+ assert report["overall_survival_ratio"] == 0.5
84
+ assert report["final_answer_survival_ratio"] == 0.25
85
+ assert report["tools"]["search"]["survival_ratio"] == 0.5
86
+ assert report["sources"]["manual.pdf"]["final_answer_survival_ratio"] == 0.5
87
+ assert report["evidence"][0]["reused_at"] == ["thought"]
88
+ assert report["evidence"][0]["steps_until_last_reuse"] == 1
89
+
90
+
91
+ def test_unused_evidence_and_intermediate_reuse_without_final_reuse():
92
+ report = analyze([
93
+ {"id": "tool", "type": "tool_result", "tool": "lookup", "content": "Mercury is closest to the Sun."},
94
+ {"id": "thought", "type": "reasoning", "content": "Mercury is closest to the Sun."},
95
+ {"id": "unused", "type": "retrieval", "source": "notes", "content": "Neptune has strong winds."},
96
+ {"id": "final", "type": "assistant", "content": "Mercury is the answer."},
97
+ ])
98
+ assert report["reused_units"] == 1
99
+ assert report["final_reused_units"] == 0
100
+ assert report["apparently_unused_sources"] == 1
101
+ assert report["unused_evidence"][0]["evidence_id"] == "evidence-1"
102
+
103
+
104
+ def test_repeated_groups_are_transitive_and_deterministic():
105
+ trace = [
106
+ {"type": "tool_result", "content": "Barcelona hosted the Olympic games."},
107
+ {"type": "retrieval", "content": "The Olympic games took place in Barcelona."},
108
+ {"type": "retrieval", "content": "Games took place in Barcelona, Spain."},
109
+ ]
110
+ first = analyze(trace)
111
+ second = analyze(trace)
112
+ assert first == second
113
+ json.dumps(first)
114
+ assert first["repeated_evidence_groups"] == [["evidence-0", "evidence-1", "evidence-2"]]
115
+
116
+
117
+ def test_containment_respects_token_boundaries():
118
+ unit = _split_units("cat facts")[0]
119
+ assert not _matches(unit, "concatenate facts")