gitvouch 0.1.0__py3-none-any.whl

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.
gitvouch/verifier.py ADDED
@@ -0,0 +1,687 @@
1
+ """Deterministic, offline verifier for gitvouch control and memory contracts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import UTC, date, datetime, timedelta
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .core import (
11
+ ALLOWED_TRANSITIONS,
12
+ CONFIG_PATH,
13
+ EVENT_FILENAME,
14
+ FORWARD_TRANSITIONS,
15
+ IMPLEMENTED_STATES,
16
+ TERMINAL_STATES,
17
+ ValidationReport,
18
+ load_json,
19
+ load_schema,
20
+ normalized_criteria,
21
+ parse_time,
22
+ repo_path,
23
+ schema_failures,
24
+ )
25
+
26
+
27
+ def _load_records(
28
+ directory: Path,
29
+ schema: dict[str, Any],
30
+ label: str,
31
+ failures: list[str],
32
+ *,
33
+ recursive: bool = False,
34
+ ) -> list[tuple[Path, dict[str, Any]]]:
35
+ if not directory.is_dir():
36
+ failures.append(f"Required {label} directory is missing: {directory}.")
37
+ return []
38
+ pattern = "**/*.json" if recursive else "*.json"
39
+ records: list[tuple[Path, dict[str, Any]]] = []
40
+ for path in sorted(directory.glob(pattern)):
41
+ try:
42
+ record = load_json(path)
43
+ except (OSError, json.JSONDecodeError) as exc:
44
+ failures.append(f"Cannot load {label} record {path}: {exc}.")
45
+ continue
46
+ item_failures = schema_failures(record, schema, f"{label} {path.name}")
47
+ failures.extend(item_failures)
48
+ if not item_failures and isinstance(record, dict):
49
+ records.append((path, record))
50
+ return records
51
+
52
+
53
+ def _index_records(
54
+ records: list[tuple[Path, dict[str, Any]]],
55
+ label: str,
56
+ failures: list[str],
57
+ ) -> dict[str, tuple[Path, dict[str, Any]]]:
58
+ indexed: dict[str, tuple[Path, dict[str, Any]]] = {}
59
+ for path, record in records:
60
+ record_id = str(record["id"])
61
+ if record_id in indexed:
62
+ failures.append(f"Duplicate {label} ID: {record_id}.")
63
+ else:
64
+ indexed[record_id] = (path, record)
65
+ return indexed
66
+
67
+
68
+ def evaluate_criterion_evidence(
69
+ task: dict[str, Any],
70
+ criterion: dict[str, Any],
71
+ candidates: list[dict[str, Any]],
72
+ *,
73
+ at_time: datetime,
74
+ now: datetime,
75
+ ) -> tuple[dict[str, Any] | None, list[str]]:
76
+ """Return the first valid passing evidence for a criterion or disqualification reasons."""
77
+ failures_dummy: list[str] = []
78
+ reasons: list[str] = []
79
+ for item in candidates:
80
+ if item["task_id"] != task["id"] or item["criterion_id"] != criterion["id"]:
81
+ continue
82
+ if item["applicable"] is not True:
83
+ reasons.append(f"{item['id']} is marked not applicable")
84
+ continue
85
+ if item["result"] != "pass":
86
+ reasons.append(f"{item['id']} has result={item['result']}")
87
+ continue
88
+ collected = parse_time(
89
+ item["collected_at"], f"Evidence {item['id']} collected_at", failures_dummy
90
+ )
91
+ if collected is None:
92
+ reasons.append(f"{item['id']} has invalid collected_at")
93
+ continue
94
+ if collected > at_time:
95
+ reasons.append(f"{item['id']} was collected after verification")
96
+ continue
97
+ expires_text = item.get("expires_at")
98
+ if expires_text:
99
+ expires = parse_time(expires_text, f"Evidence {item['id']} expires_at", failures_dummy)
100
+ if expires is None:
101
+ reasons.append(f"{item['id']} has invalid expires_at")
102
+ continue
103
+ if expires <= at_time:
104
+ reasons.append(f"{item['id']} was expired at verification")
105
+ continue
106
+ if expires <= now:
107
+ reasons.append(f"{item['id']} is now expired")
108
+ continue
109
+ max_age_days = criterion.get("max_age_days")
110
+ if max_age_days is not None:
111
+ max_age = timedelta(days=max_age_days)
112
+ if at_time - collected > max_age:
113
+ reasons.append(f"{item['id']} exceeded max_age_days at verification")
114
+ continue
115
+ if now - collected > max_age:
116
+ reasons.append(f"{item['id']} now exceeds max_age_days")
117
+ continue
118
+ return item, []
119
+ return None, reasons
120
+
121
+
122
+ def _verify_evidence_gate(
123
+ task: dict[str, Any],
124
+ event: dict[str, Any],
125
+ event_time: datetime,
126
+ evidence: dict[str, tuple[Path, dict[str, Any]]],
127
+ now: datetime,
128
+ failures: list[str],
129
+ ) -> None:
130
+ referenced_ids = event["details"]["evidence_ids"]
131
+ referenced: list[dict[str, Any]] = []
132
+ for evidence_id in referenced_ids:
133
+ item = evidence.get(evidence_id)
134
+ if item is None:
135
+ failures.append(
136
+ f"Task {task['id']} verification references missing evidence {evidence_id}."
137
+ )
138
+ continue
139
+ referenced.append(item[1])
140
+
141
+ for criterion in task["acceptance_criteria"]:
142
+ valid_item, reasons = evaluate_criterion_evidence(
143
+ task,
144
+ criterion,
145
+ referenced,
146
+ at_time=event_time,
147
+ now=now,
148
+ )
149
+ if valid_item is None:
150
+ suffix = f" ({'; '.join(reasons)})" if reasons else ""
151
+ failures.append(
152
+ f"Task {task['id']} criterion {criterion['id']} lacks valid passing "
153
+ f"verification evidence{suffix}."
154
+ )
155
+
156
+
157
+ def _replay_task(
158
+ task: dict[str, Any],
159
+ events: list[tuple[Path, dict[str, Any], datetime]],
160
+ tasks: dict[str, tuple[Path, dict[str, Any]]],
161
+ verified_at: dict[str, datetime],
162
+ evidence: dict[str, tuple[Path, dict[str, Any]]],
163
+ now: datetime,
164
+ failures: list[str],
165
+ ) -> set[str]:
166
+ task_id = task["id"]
167
+ if not events:
168
+ failures.append(f"Task {task_id} has no events.")
169
+ return set()
170
+
171
+ events = sorted(events, key=lambda item: (item[2], item[1]["event_id"]))
172
+ first_path, first, first_time = events[0]
173
+ if first["type"] != "task_created":
174
+ failures.append(f"Task {task_id} first event is not task_created: {first_path}.")
175
+ return set()
176
+ if any(event["type"] == "task_created" for _, event, _ in events[1:]):
177
+ failures.append(f"Task {task_id} has more than one task_created event.")
178
+
179
+ current_state = first["details"]["state"]
180
+ current_scope = first["details"]["scope"]
181
+ current_weight = first["details"]["weight"]
182
+ current_owners = first["details"]["owners"]
183
+ active_blockers: set[str] = set()
184
+
185
+ created_at = parse_time(task["created_at"], f"Task {task_id} created_at", failures)
186
+ if created_at is not None and created_at != first_time:
187
+ failures.append(f"Task {task_id} created_at does not match its first event.")
188
+
189
+ for _path, event, event_time in events[1:]:
190
+ event_type = event["type"]
191
+ details = event["details"]
192
+ if current_state in TERMINAL_STATES:
193
+ failures.append(
194
+ f"Task {task_id} has event {event['event_id']} after terminal state "
195
+ f"{current_state}."
196
+ )
197
+ continue
198
+
199
+ if event_type == "task_created":
200
+ continue
201
+ if event_type == "state_transition":
202
+ source = details["from"]
203
+ target = details["to"]
204
+ if source != current_state:
205
+ failures.append(
206
+ f"Task {task_id} event {event['event_id']} starts at {source}, "
207
+ f"but replay state is {current_state}."
208
+ )
209
+ continue
210
+ if target not in ALLOWED_TRANSITIONS[current_state]:
211
+ failures.append(f"Task {task_id} has illegal transition {source} -> {target}.")
212
+ continue
213
+ if active_blockers and (source, target) in FORWARD_TRANSITIONS:
214
+ failures.append(
215
+ f"Task {task_id} cannot advance {source} -> {target} while blocked "
216
+ f"by {sorted(active_blockers)}."
217
+ )
218
+ continue
219
+ if target == "ready":
220
+ criterion_ids = [item["id"] for item in task["acceptance_criteria"]]
221
+ if not criterion_ids:
222
+ failures.append(f"Task {task_id} entered ready without acceptance criteria.")
223
+ if sorted(details.get("acceptance_criteria_ids", [])) != sorted(criterion_ids):
224
+ failures.append(
225
+ f"Task {task_id} ready event acceptance criteria IDs do not match "
226
+ "the task record."
227
+ )
228
+ criterion_snapshot = details.get("acceptance_criteria_snapshot")
229
+ if criterion_snapshot is None:
230
+ failures.append(
231
+ f"Task {task_id} ready event {event['event_id']} is missing "
232
+ "acceptance_criteria_snapshot."
233
+ )
234
+ elif normalized_criteria(criterion_snapshot) != normalized_criteria(
235
+ task["acceptance_criteria"]
236
+ ):
237
+ failures.append(
238
+ f"Task {task_id} acceptance criteria were modified after entering ready "
239
+ f"(tamper detected vs snapshot in {event['event_id']})."
240
+ )
241
+ if sorted(details.get("dependency_ids", [])) != sorted(task["dependencies"]):
242
+ failures.append(
243
+ f"Task {task_id} ready event dependencies do not match the task record."
244
+ )
245
+ for dependency_id in task["dependencies"]:
246
+ dependency = tasks.get(dependency_id)
247
+ if dependency is None:
248
+ continue
249
+ dependency_time = verified_at.get(dependency_id)
250
+ if dependency[1]["state"] != "verified" or dependency_time is None:
251
+ failures.append(
252
+ f"Task {task_id} entered ready before dependency "
253
+ f"{dependency_id} was verified."
254
+ )
255
+ elif dependency_time > event_time:
256
+ failures.append(
257
+ f"Task {task_id} entered ready before dependency "
258
+ f"{dependency_id}'s verification event."
259
+ )
260
+ if target == "verified":
261
+ _verify_evidence_gate(task, event, event_time, evidence, now, failures)
262
+ current_state = target
263
+ elif event_type == "blocker_added":
264
+ blocker_id = details["blocker_id"]
265
+ if blocker_id in active_blockers:
266
+ failures.append(f"Task {task_id} adds already-active blocker {blocker_id}.")
267
+ active_blockers.add(blocker_id)
268
+ elif event_type == "blocker_resolved":
269
+ blocker_id = details["blocker_id"]
270
+ if blocker_id not in active_blockers:
271
+ failures.append(f"Task {task_id} resolves inactive blocker {blocker_id}.")
272
+ active_blockers.discard(blocker_id)
273
+ elif event_type == "assignment_changed":
274
+ if details["before"] != current_owners:
275
+ failures.append(
276
+ f"Task {task_id} assignment event {event['event_id']} has stale before value."
277
+ )
278
+ current_owners = details["after"]
279
+ elif event_type == "scope_changed":
280
+ if details["before"] != current_scope:
281
+ failures.append(
282
+ f"Task {task_id} scope event {event['event_id']} has stale before value."
283
+ )
284
+ current_scope = details["after"]
285
+ elif event_type == "weight_changed":
286
+ if current_state != "proposed":
287
+ failures.append(f"Task {task_id} weight changed after leaving proposed state.")
288
+ if details["before"] != current_weight:
289
+ failures.append(
290
+ f"Task {task_id} weight event {event['event_id']} has stale before value."
291
+ )
292
+ current_weight = details["after"]
293
+
294
+ comparisons = (
295
+ ("state", current_state, task["state"]),
296
+ ("scope", current_scope, task["scope"]),
297
+ ("weight", current_weight, task["weight"]),
298
+ ("owners", current_owners, task["owners"]),
299
+ ("active_blockers", sorted(active_blockers), sorted(task["active_blockers"])),
300
+ )
301
+ for field_name, replayed, recorded in comparisons:
302
+ if replayed != recorded:
303
+ failures.append(
304
+ f"Task {task_id} {field_name} does not match event replay: "
305
+ f"{recorded!r} != {replayed!r}."
306
+ )
307
+
308
+ updated_at = parse_time(task["updated_at"], f"Task {task_id} updated_at", failures)
309
+ if updated_at is not None and updated_at != events[-1][2]:
310
+ failures.append(f"Task {task_id} updated_at does not match its latest event.")
311
+ return active_blockers
312
+
313
+
314
+ def calculate_progress(tasks: dict[str, tuple[Path, dict[str, Any]]]) -> dict[str, int]:
315
+ eligible = [
316
+ task for _, task in tasks.values() if task["state"] not in {"cancelled", "superseded"}
317
+ ]
318
+ eligible_weight = sum(task["weight"] for task in eligible)
319
+ implemented_weight = sum(
320
+ task["weight"] for task in eligible if task["state"] in IMPLEMENTED_STATES
321
+ )
322
+ verified_weight = sum(task["weight"] for task in eligible if task["state"] == "verified")
323
+ debt_weight = sum(
324
+ task["weight"] for task in eligible if task["state"] in {"implemented", "verifying"}
325
+ )
326
+ return {
327
+ "eligible_weight": eligible_weight,
328
+ "implemented_weight": implemented_weight,
329
+ "verified_weight": verified_weight,
330
+ "verification_debt_weight": debt_weight,
331
+ }
332
+
333
+
334
+ def _find_dependency_cycles(tasks: dict[str, tuple[Path, dict[str, Any]]]) -> list[list[str]]:
335
+ cycles: list[list[str]] = []
336
+ visited: set[str] = set()
337
+ active: list[str] = []
338
+ active_set: set[str] = set()
339
+
340
+ def visit(task_id: str) -> None:
341
+ if task_id in active_set:
342
+ start = active.index(task_id)
343
+ cycle = active[start:] + [task_id]
344
+ if cycle not in cycles:
345
+ cycles.append(cycle)
346
+ return
347
+ if task_id in visited:
348
+ return
349
+ active.append(task_id)
350
+ active_set.add(task_id)
351
+ for dependency_id in tasks[task_id][1]["dependencies"]:
352
+ if dependency_id in tasks:
353
+ visit(dependency_id)
354
+ active.pop()
355
+ active_set.remove(task_id)
356
+ visited.add(task_id)
357
+
358
+ for task_id in tasks:
359
+ visit(task_id)
360
+ return cycles
361
+
362
+
363
+ def _validate_memory(
364
+ root: Path,
365
+ config: dict[str, Any],
366
+ now: datetime,
367
+ report: ValidationReport,
368
+ ) -> None:
369
+ mem_cfg = config["memory"]
370
+ if not mem_cfg.get("enabled"):
371
+ return
372
+
373
+ try:
374
+ mem_root = repo_path(root, mem_cfg["root"])
375
+ except ValueError as exc:
376
+ report.failures.append(f"Invalid memory root: {exc}.")
377
+ return
378
+
379
+ required_docs = {
380
+ "state_snapshot": mem_root / "state_snapshot.json",
381
+ "current_state": mem_root / "current_state.md",
382
+ "decisions": mem_root / "decisions.md",
383
+ "operation_log": mem_root / "operation_log.md",
384
+ "runbook": mem_root / "runbook.md",
385
+ }
386
+ for name, path in required_docs.items():
387
+ if not path.is_file():
388
+ report.failures.append(
389
+ f"Required memory file {name!r} is missing: {path.relative_to(root)}."
390
+ )
391
+
392
+ snap_path = required_docs["state_snapshot"]
393
+ if not snap_path.is_file():
394
+ return
395
+
396
+ try:
397
+ state = load_json(snap_path)
398
+ except (OSError, json.JSONDecodeError) as exc:
399
+ report.failures.append(f"Cannot load memory state snapshot: {exc}.")
400
+ return
401
+
402
+ report.failures.extend(schema_failures(state, load_schema("state"), "memory state_snapshot"))
403
+ if isinstance(state.get("project"), dict):
404
+ state_name = state["project"].get("name")
405
+ if state_name != config["project_name"]:
406
+ report.failures.append(
407
+ "Config project_name does not match memory state_snapshot project.name: "
408
+ f"{config['project_name']!r} != {state_name!r}."
409
+ )
410
+
411
+ reviewed_text = str(state.get("last_reviewed", ""))
412
+ try:
413
+ reviewed = date.fromisoformat(reviewed_text)
414
+ except ValueError:
415
+ reviewed = None
416
+
417
+ if reviewed is not None:
418
+ age = (now.date() - reviewed).days
419
+ report.memory_age_days = age
420
+ if age < 0:
421
+ report.failures.append(f"Memory last_reviewed is in the future: {reviewed_text}.")
422
+ elif age > mem_cfg["warn_after_days"]:
423
+ report.warnings.append(
424
+ f"Memory state was last reviewed {reviewed_text} ({age} days ago; "
425
+ f"threshold {mem_cfg['warn_after_days']} days)."
426
+ )
427
+
428
+ current_state = required_docs["current_state"]
429
+ if current_state.is_file() and reviewed_text not in current_state.read_text(
430
+ encoding="utf-8"
431
+ ):
432
+ report.failures.append(
433
+ f"Memory current_state.md does not contain last_reviewed date {reviewed_text}."
434
+ )
435
+ operation_log = required_docs["operation_log"]
436
+ if operation_log.is_file() and f"## {reviewed_text}" not in operation_log.read_text(
437
+ encoding="utf-8"
438
+ ):
439
+ report.failures.append(f"Memory operation_log.md has no '## {reviewed_text}' heading.")
440
+
441
+
442
+ def _validate_control(
443
+ root: Path,
444
+ config: dict[str, Any],
445
+ now: datetime,
446
+ report: ValidationReport,
447
+ ) -> None:
448
+ ctrl_cfg = config["control"]
449
+ if not ctrl_cfg.get("enabled"):
450
+ return
451
+
452
+ try:
453
+ ctrl_root = repo_path(root, ctrl_cfg["root"])
454
+ except ValueError as exc:
455
+ report.failures.append(f"Invalid control root: {exc}.")
456
+ return
457
+
458
+ project_path = ctrl_root / "project.json"
459
+ if not project_path.is_file():
460
+ report.failures.append(
461
+ f"Required project record is missing: {project_path.relative_to(root)}."
462
+ )
463
+ return
464
+
465
+ try:
466
+ project = load_json(project_path)
467
+ except (OSError, json.JSONDecodeError) as exc:
468
+ report.failures.append(f"Cannot load project record: {exc}.")
469
+ return
470
+
471
+ report.failures.extend(schema_failures(project, load_schema("project"), "project"))
472
+ if not report.ok:
473
+ return
474
+
475
+ if project["name"] != config["project_name"]:
476
+ report.failures.append(
477
+ "Config project_name does not match control project.name: "
478
+ f"{config['project_name']!r} != {project['name']!r}."
479
+ )
480
+
481
+ milestone_records = _load_records(
482
+ ctrl_root / "milestones", load_schema("milestone"), "milestone", report.failures
483
+ )
484
+ task_records = _load_records(ctrl_root / "tasks", load_schema("task"), "task", report.failures)
485
+ event_records = _load_records(
486
+ ctrl_root / "events", load_schema("event"), "event", report.failures, recursive=True
487
+ )
488
+ evidence_records = _load_records(
489
+ ctrl_root / "evidence", load_schema("evidence"), "evidence", report.failures, recursive=True
490
+ )
491
+
492
+ milestones = _index_records(milestone_records, "milestone", report.failures)
493
+ tasks = _index_records(task_records, "task", report.failures)
494
+ evidence = _index_records(evidence_records, "evidence", report.failures)
495
+
496
+ for record_id, (path, _) in milestones.items():
497
+ if path.stem != record_id:
498
+ report.failures.append(f"Milestone filename {path.name} does not match ID {record_id}.")
499
+ for record_id, (path, task) in tasks.items():
500
+ if path.stem != record_id:
501
+ report.failures.append(f"Task filename {path.name} does not match ID {record_id}.")
502
+ criterion_ids = [item["id"] for item in task["acceptance_criteria"]]
503
+ if len(criterion_ids) != len(set(criterion_ids)):
504
+ report.failures.append(f"Task {record_id} has duplicate acceptance criterion IDs.")
505
+ if record_id in task["dependencies"]:
506
+ report.failures.append(f"Task {record_id} depends on itself.")
507
+ for dependency_id in task["dependencies"]:
508
+ if dependency_id not in tasks:
509
+ report.failures.append(
510
+ f"Task {record_id} references missing dependency {dependency_id}."
511
+ )
512
+ for cycle in _find_dependency_cycles(tasks):
513
+ report.failures.append(f"Task dependency cycle detected: {' -> '.join(cycle)}.")
514
+
515
+ for record_id, (path, item) in evidence.items():
516
+ if path.stem != record_id:
517
+ report.failures.append(f"Evidence filename {path.name} does not match ID {record_id}.")
518
+ if path.parent.name != item["task_id"]:
519
+ report.failures.append(
520
+ f"Evidence {record_id} is stored under {path.parent.name}, not {item['task_id']}."
521
+ )
522
+ if item["task_id"] not in tasks:
523
+ report.failures.append(
524
+ f"Evidence {record_id} references missing task {item['task_id']}."
525
+ )
526
+ else:
527
+ criteria = {c["id"] for c in tasks[item["task_id"]][1]["acceptance_criteria"]}
528
+ if item["criterion_id"] not in criteria:
529
+ report.failures.append(
530
+ f"Evidence {record_id} references missing criterion "
531
+ f"{item['criterion_id']} on task {item['task_id']}."
532
+ )
533
+ collected = parse_time(
534
+ item["collected_at"], f"Evidence {record_id} collected_at", report.failures
535
+ )
536
+ expires_text = item.get("expires_at")
537
+ if collected is not None and expires_text:
538
+ expires = parse_time(expires_text, f"Evidence {record_id} expires_at", report.failures)
539
+ if expires is not None and expires <= collected:
540
+ report.failures.append(
541
+ f"Evidence {record_id} expires_at must be after collected_at."
542
+ )
543
+
544
+ if set(project["milestone_ids"]) != set(milestones):
545
+ report.failures.append(
546
+ "Project milestone_ids do not match milestone records: "
547
+ f"{sorted(project['milestone_ids'])} != {sorted(milestones)}."
548
+ )
549
+
550
+ listed_tasks: dict[str, str] = {}
551
+ for milestone_id, (_, milestone) in milestones.items():
552
+ for task_id in milestone["task_ids"]:
553
+ previous = listed_tasks.get(task_id)
554
+ if previous is not None:
555
+ report.failures.append(
556
+ f"Task {task_id} appears in milestones {previous} and {milestone_id}."
557
+ )
558
+ listed_tasks[task_id] = milestone_id
559
+ task_item = tasks.get(task_id)
560
+ if task_item is None:
561
+ report.failures.append(
562
+ f"Milestone {milestone_id} references missing task {task_id}."
563
+ )
564
+ elif task_item[1]["milestone_id"] != milestone_id:
565
+ report.failures.append(
566
+ f"Task {task_id} names milestone {task_item[1]['milestone_id']}, not {milestone_id}."
567
+ )
568
+ if milestone["status"] == "completed":
569
+ for task_id in milestone["task_ids"]:
570
+ task_item = tasks.get(task_id)
571
+ if task_item and task_item[1]["state"] not in TERMINAL_STATES:
572
+ report.failures.append(
573
+ f"Completed milestone {milestone_id} has non-terminal task {task_id}."
574
+ )
575
+ for task_id in tasks:
576
+ if task_id not in listed_tasks:
577
+ report.failures.append(f"Task {task_id} does not appear in a milestone.")
578
+
579
+ events_by_task: dict[str, list[tuple[Path, dict[str, Any], datetime]]] = {
580
+ task_id: [] for task_id in tasks
581
+ }
582
+ event_ids: set[str] = set()
583
+ verified_at: dict[str, datetime] = {}
584
+ for path, event in event_records:
585
+ event_id = event["event_id"]
586
+ if event_id in event_ids:
587
+ report.failures.append(f"Duplicate event ID: {event_id}.")
588
+ event_ids.add(event_id)
589
+ task_id = event["task_id"]
590
+ if path.parent.name != task_id:
591
+ report.failures.append(
592
+ f"Event {event_id} is stored under {path.parent.name}, not {task_id}."
593
+ )
594
+ match = EVENT_FILENAME.fullmatch(path.name)
595
+ event_time = parse_time(
596
+ event["occurred_at"], f"Event {event_id} occurred_at", report.failures
597
+ )
598
+ if match is None:
599
+ report.failures.append(f"Event filename has invalid form: {path.name}.")
600
+ elif match.group("event_id") != event_id:
601
+ report.failures.append(f"Event filename {path.name} does not match ID {event_id}.")
602
+ elif event_time is not None:
603
+ expected_ts = event_time.strftime("%Y%m%dT%H%M%SZ")
604
+ if match.group("timestamp") != expected_ts:
605
+ report.failures.append(f"Event filename {path.name} does not match occurred_at.")
606
+ if task_id not in tasks:
607
+ report.failures.append(f"Event {event_id} references missing task {task_id}.")
608
+ elif event_time is not None:
609
+ events_by_task[task_id].append((path, event, event_time))
610
+ if event["type"] == "state_transition" and event["details"]["to"] == "verified":
611
+ previous = verified_at.get(task_id)
612
+ if previous is None or event_time < previous:
613
+ verified_at[task_id] = event_time
614
+
615
+ for task_id, (_, task) in tasks.items():
616
+ _replay_task(
617
+ task,
618
+ events_by_task[task_id],
619
+ tasks,
620
+ verified_at,
621
+ evidence,
622
+ now,
623
+ report.failures,
624
+ )
625
+
626
+ referenced_evidence = {
627
+ evidence_id
628
+ for records in events_by_task.values()
629
+ for _, event, _ in records
630
+ if event["type"] == "state_transition"
631
+ for evidence_id in event["details"]["evidence_ids"]
632
+ }
633
+ for evidence_id in sorted(set(evidence) - referenced_evidence):
634
+ report.warnings.append(f"Evidence {evidence_id} is not referenced by a transition event.")
635
+
636
+ report.progress = calculate_progress(tasks)
637
+
638
+
639
+ def validate_repository(root: Path, *, now: datetime | None = None) -> ValidationReport:
640
+ report = ValidationReport()
641
+ root = root.resolve()
642
+ now_utc = (now or datetime.now(UTC)).astimezone(UTC)
643
+
644
+ cfg_path = root / CONFIG_PATH
645
+ if not cfg_path.is_file():
646
+ report.failures.append(
647
+ f"Repository is not initialized for gitvouch (missing {CONFIG_PATH.as_posix()})."
648
+ )
649
+ return report
650
+
651
+ try:
652
+ config = load_json(cfg_path)
653
+ except (OSError, json.JSONDecodeError) as exc:
654
+ report.failures.append(f"Cannot load {CONFIG_PATH.as_posix()}: {exc}.")
655
+ return report
656
+
657
+ report.failures.extend(schema_failures(config, load_schema("config"), "config"))
658
+ if not report.ok:
659
+ return report
660
+
661
+ try:
662
+ entrypoint = repo_path(root, config["entrypoint"])
663
+ except ValueError as exc:
664
+ report.failures.append(f"Invalid entrypoint path: {exc}.")
665
+ entrypoint = None
666
+
667
+ if entrypoint is None or not entrypoint.is_file():
668
+ report.failures.append(f"Required entrypoint is missing: {config['entrypoint']}.")
669
+ else:
670
+ entry_text = entrypoint.read_text(encoding="utf-8")
671
+ if "gitvouch check" not in entry_text:
672
+ report.failures.append(
673
+ f"Entrypoint {config['entrypoint']} does not instruct agents to run 'gitvouch check'."
674
+ )
675
+
676
+ claude_path = root / "CLAUDE.md"
677
+ if claude_path.is_file() and entrypoint is not None and entrypoint.name == "AGENTS.md":
678
+ claude_text = claude_path.read_text(encoding="utf-8").strip()
679
+ agents_text = entrypoint.read_text(encoding="utf-8").strip()
680
+ if claude_text not in {"AGENTS.md", "@AGENTS.md", agents_text}:
681
+ report.failures.append(
682
+ "CLAUDE.md must symlink, import (@AGENTS.md), or match AGENTS.md."
683
+ )
684
+
685
+ _validate_memory(root, config, now_utc, report)
686
+ _validate_control(root, config, now_utc, report)
687
+ return report