Compare a trusted evidence baseline
Identify added, changed, and missing files without labelling every change as malicious.
Compare two observations
A baseline is a previous inventory that you have chosen to trust for a particular purpose. Compare it with a current inventory by relative path. A path only in the current set is added; one only in the baseline is missing. If both contain the path but their digests differ, its bytes changed.
Do not compare list positions. Filesystem order can change without the evidence changing. Build dictionaries keyed by exact relative path, then inspect the union of their keys. In this exercise path spelling is case-sensitive while hexadecimal digest spelling is case-insensitive.
Refuse an ambiguous baseline
Two rows for the same path make it unclear which digest should be trusted. A dictionary comprehension would quietly keep the last one. Detect duplicates explicitly and raise ValueError in either inventory before comparing them.
Exclude unchanged paths from the result and sort the remaining rows by path. This produces a small report that is easy to review. A changed file is an observation, not a conclusion about intent: an approved update can also change many bytes.
The previous lesson can generate the current inventory. Here the supplied JSON contains both inventories so you can practise comparison independently. Keeping these functions separate makes it possible to test the comparison with tiny examples, then reuse it in a larger evidence workflow.
before = {"a.txt": "abc", "old.txt": "def"}
after = {"a.txt": "xyz", "new.txt": "123"}
print(sorted(before.keys() | after.keys()))
Put it into practice.
Define compare_baseline(baseline, current). Each list contains path and sha256 fields. Match paths exactly, compare digests case-insensitively, and return {path, status} rows for added, missing or changed files, sorted by path. Omit unchanged files. Duplicate paths in either input must raise ValueError. Do not modify inputs.
See an explained solution
def compare_baseline(baseline, current):
def index(rows):
result = {}
for row in rows:
if row["path"] in result:
raise ValueError("Duplicate evidence path")
result[row["path"]] = row["sha256"].lower()
return result
before, after = index(baseline), index(current)
changes = []
for path in sorted(before.keys() | after.keys()):
if path not in before:
status = "added"
elif path not in after:
status = "missing"
elif before[path] != after[path]:
status = "changed"
else:
continue
changes.append({"path": path, "status": status})
return changes
The union covers additions and deletions as well as modifications. Duplicate rejection prevents one inventory row silently overriding another.