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/__init__.py +4 -0
- gitvouch/cli.py +381 -0
- gitvouch/core.py +131 -0
- gitvouch/ops.py +730 -0
- gitvouch/schemas/__init__.py +1 -0
- gitvouch/schemas/config.schema.json +35 -0
- gitvouch/schemas/event.schema.json +200 -0
- gitvouch/schemas/evidence.schema.json +44 -0
- gitvouch/schemas/milestone.schema.json +21 -0
- gitvouch/schemas/project.schema.json +20 -0
- gitvouch/schemas/state.schema.json +31 -0
- gitvouch/schemas/task.schema.json +74 -0
- gitvouch/verifier.py +687 -0
- gitvouch-0.1.0.dist-info/METADATA +190 -0
- gitvouch-0.1.0.dist-info/RECORD +19 -0
- gitvouch-0.1.0.dist-info/WHEEL +5 -0
- gitvouch-0.1.0.dist-info/entry_points.txt +2 -0
- gitvouch-0.1.0.dist-info/licenses/LICENSE +21 -0
- gitvouch-0.1.0.dist-info/top_level.txt +1 -0
gitvouch/ops.py
ADDED
|
@@ -0,0 +1,730 @@
|
|
|
1
|
+
"""Repository mutation operations for gitvouch."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
from datetime import datetime, timedelta
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .core import (
|
|
14
|
+
ALLOWED_TRANSITIONS,
|
|
15
|
+
CONFIG_PATH,
|
|
16
|
+
FORWARD_TRANSITIONS,
|
|
17
|
+
compact_utc,
|
|
18
|
+
iso_utc,
|
|
19
|
+
load_json,
|
|
20
|
+
repo_path,
|
|
21
|
+
utc_now,
|
|
22
|
+
write_json,
|
|
23
|
+
)
|
|
24
|
+
from .verifier import calculate_progress, evaluate_criterion_evidence, validate_repository
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class GitvouchError(RuntimeError):
|
|
28
|
+
"""Raised when a gitvouch operation violates a contract invariant."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def default_actor() -> str:
|
|
32
|
+
return os.environ.get("GITVOUCH_ACTOR") or os.environ.get("USER") or "operator"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _slug_project_id(name: str) -> str:
|
|
36
|
+
cleaned = re.sub(r"[^A-Za-z0-9]+", "-", name.upper()).strip("-")
|
|
37
|
+
return f"P-{(cleaned or 'PROJECT')[:60]}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _load_config(root: Path) -> dict[str, Any]:
|
|
41
|
+
cfg_path = root / CONFIG_PATH
|
|
42
|
+
if not cfg_path.is_file():
|
|
43
|
+
raise GitvouchError(
|
|
44
|
+
f"Repository is not initialized ({CONFIG_PATH.as_posix()} missing). Run 'gitvouch init'."
|
|
45
|
+
)
|
|
46
|
+
return load_json(cfg_path)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _control_root(root: Path, config: dict[str, Any]) -> Path:
|
|
50
|
+
if not config["control"].get("enabled"):
|
|
51
|
+
raise GitvouchError("Control layer is disabled in .gitvouch/config.json.")
|
|
52
|
+
return repo_path(root, config["control"]["root"])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _memory_root(root: Path, config: dict[str, Any]) -> Path:
|
|
56
|
+
if not config["memory"].get("enabled"):
|
|
57
|
+
raise GitvouchError("Memory layer is disabled in .gitvouch/config.json.")
|
|
58
|
+
return repo_path(root, config["memory"]["root"])
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _next_numeric_id(directory: Path, prefix: str, *, recursive: bool = False) -> str:
|
|
62
|
+
max_num = 0
|
|
63
|
+
pattern = re.compile(rf"^{re.escape(prefix)}-([0-9]+)$")
|
|
64
|
+
if directory.is_dir():
|
|
65
|
+
glob_pat = "**/*.json" if recursive else "*.json"
|
|
66
|
+
for path in directory.glob(glob_pat):
|
|
67
|
+
stem = path.stem
|
|
68
|
+
if "--" in stem:
|
|
69
|
+
stem = stem.split("--", 1)[1]
|
|
70
|
+
match = pattern.match(stem)
|
|
71
|
+
if match:
|
|
72
|
+
max_num = max(max_num, int(match.group(1)))
|
|
73
|
+
return f"{prefix}-{max_num + 1:03d}"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _next_event_id(ctrl_root: Path) -> str:
|
|
77
|
+
return _next_numeric_id(ctrl_root / "events", "EVT", recursive=True)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _next_evidence_id(ctrl_root: Path) -> str:
|
|
81
|
+
return _next_numeric_id(ctrl_root / "evidence", "E", recursive=True)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _write_event(
|
|
85
|
+
ctrl_root: Path,
|
|
86
|
+
task_id: str,
|
|
87
|
+
event_type: str,
|
|
88
|
+
details: dict[str, Any],
|
|
89
|
+
*,
|
|
90
|
+
actor: str,
|
|
91
|
+
occurred_at: datetime,
|
|
92
|
+
) -> dict[str, Any]:
|
|
93
|
+
event_id = _next_event_id(ctrl_root)
|
|
94
|
+
event = {
|
|
95
|
+
"schema_version": 2,
|
|
96
|
+
"event_id": event_id,
|
|
97
|
+
"task_id": task_id,
|
|
98
|
+
"occurred_at": iso_utc(occurred_at),
|
|
99
|
+
"actor": actor,
|
|
100
|
+
"type": event_type,
|
|
101
|
+
"details": details,
|
|
102
|
+
}
|
|
103
|
+
filename = f"{compact_utc(occurred_at)}--{event_id}.json"
|
|
104
|
+
write_json(ctrl_root / "events" / task_id / filename, event)
|
|
105
|
+
return event
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _git_provenance(root: Path) -> dict[str, Any]:
|
|
109
|
+
info: dict[str, Any] = {}
|
|
110
|
+
head = subprocess.run(
|
|
111
|
+
["git", "rev-parse", "HEAD"],
|
|
112
|
+
cwd=root,
|
|
113
|
+
capture_output=True,
|
|
114
|
+
text=True,
|
|
115
|
+
check=False,
|
|
116
|
+
)
|
|
117
|
+
if head.returncode == 0 and len(head.stdout.strip()) >= 7:
|
|
118
|
+
info["commit"] = head.stdout.strip()
|
|
119
|
+
status = subprocess.run(
|
|
120
|
+
["git", "status", "--porcelain"],
|
|
121
|
+
cwd=root,
|
|
122
|
+
capture_output=True,
|
|
123
|
+
text=True,
|
|
124
|
+
check=False,
|
|
125
|
+
)
|
|
126
|
+
if status.returncode == 0:
|
|
127
|
+
info["working_tree_dirty"] = bool(status.stdout.strip())
|
|
128
|
+
return info
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def init_repo(
|
|
132
|
+
root: Path,
|
|
133
|
+
*,
|
|
134
|
+
project_name: str | None = None,
|
|
135
|
+
profile: str = "application",
|
|
136
|
+
mode: str = "full",
|
|
137
|
+
milestone_title: str = "Initial Milestone",
|
|
138
|
+
warn_after_days: int = 14,
|
|
139
|
+
force: bool = False,
|
|
140
|
+
) -> dict[str, Any]:
|
|
141
|
+
root = root.resolve()
|
|
142
|
+
cfg_path = root / CONFIG_PATH
|
|
143
|
+
if cfg_path.exists() and not force:
|
|
144
|
+
raise GitvouchError(
|
|
145
|
+
f"{CONFIG_PATH.as_posix()} already exists. Pass --force to re-initialize."
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
name = project_name or root.name
|
|
149
|
+
now = utc_now()
|
|
150
|
+
today = now.date().isoformat()
|
|
151
|
+
enable_control = mode in {"full", "control"}
|
|
152
|
+
enable_memory = mode in {"full", "memory"}
|
|
153
|
+
|
|
154
|
+
config = {
|
|
155
|
+
"schema_version": 1,
|
|
156
|
+
"project_name": name,
|
|
157
|
+
"profile": profile,
|
|
158
|
+
"entrypoint": "AGENTS.md",
|
|
159
|
+
"control": {
|
|
160
|
+
"enabled": enable_control,
|
|
161
|
+
"root": ".gitvouch/control",
|
|
162
|
+
},
|
|
163
|
+
"memory": {
|
|
164
|
+
"enabled": enable_memory,
|
|
165
|
+
"root": ".gitvouch/memory",
|
|
166
|
+
"warn_after_days": warn_after_days,
|
|
167
|
+
},
|
|
168
|
+
}
|
|
169
|
+
write_json(cfg_path, config)
|
|
170
|
+
|
|
171
|
+
if enable_control:
|
|
172
|
+
ctrl = root / ".gitvouch" / "control"
|
|
173
|
+
for sub in ("milestones", "tasks", "events", "evidence"):
|
|
174
|
+
(ctrl / sub).mkdir(parents=True, exist_ok=True)
|
|
175
|
+
write_json(
|
|
176
|
+
ctrl / "project.json",
|
|
177
|
+
{
|
|
178
|
+
"schema_version": 1,
|
|
179
|
+
"id": _slug_project_id(name),
|
|
180
|
+
"name": name,
|
|
181
|
+
"description": f"Auditable delivery control for {name}.",
|
|
182
|
+
"milestone_ids": ["M-001"],
|
|
183
|
+
"created_at": iso_utc(now),
|
|
184
|
+
"updated_at": iso_utc(now),
|
|
185
|
+
},
|
|
186
|
+
)
|
|
187
|
+
write_json(
|
|
188
|
+
ctrl / "milestones" / "M-001.json",
|
|
189
|
+
{
|
|
190
|
+
"schema_version": 1,
|
|
191
|
+
"id": "M-001",
|
|
192
|
+
"title": milestone_title,
|
|
193
|
+
"description": "Default milestone created by gitvouch init.",
|
|
194
|
+
"status": "active",
|
|
195
|
+
"task_ids": [],
|
|
196
|
+
"created_at": iso_utc(now),
|
|
197
|
+
"updated_at": iso_utc(now),
|
|
198
|
+
},
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
if enable_memory:
|
|
202
|
+
mem = root / ".gitvouch" / "memory"
|
|
203
|
+
mem.mkdir(parents=True, exist_ok=True)
|
|
204
|
+
write_json(
|
|
205
|
+
mem / "state_snapshot.json",
|
|
206
|
+
{
|
|
207
|
+
"schema_version": 1,
|
|
208
|
+
"last_reviewed": today,
|
|
209
|
+
"freshness": {
|
|
210
|
+
"basis": "Initial repository initialization via gitvouch init",
|
|
211
|
+
},
|
|
212
|
+
"project": {
|
|
213
|
+
"name": name,
|
|
214
|
+
"profile": profile,
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
)
|
|
218
|
+
(mem / "current_state.md").write_text(
|
|
219
|
+
f"# Current State: {name}\n\n"
|
|
220
|
+
f"- **Last reviewed**: {today}\n"
|
|
221
|
+
f"- **Profile**: `{profile}`\n\n"
|
|
222
|
+
"Record only verified facts here. Plans belong in `.gitvouch/control/tasks/`, "
|
|
223
|
+
"not as completed facts.\n",
|
|
224
|
+
encoding="utf-8",
|
|
225
|
+
)
|
|
226
|
+
(mem / "decisions.md").write_text(
|
|
227
|
+
f"# Architecture & Operational Decisions: {name}\n\n"
|
|
228
|
+
f"## {today}: Adopt gitvouch\n\n"
|
|
229
|
+
"- Adopted Git-native evidence-gated verification and durable repo memory via `gitvouch`.\n",
|
|
230
|
+
encoding="utf-8",
|
|
231
|
+
)
|
|
232
|
+
(mem / "operation_log.md").write_text(
|
|
233
|
+
f"# Operation Log: {name}\n\n## {today}\n\n- Initialized `.gitvouch/` contract.\n",
|
|
234
|
+
encoding="utf-8",
|
|
235
|
+
)
|
|
236
|
+
(mem / "runbook.md").write_text(
|
|
237
|
+
f"# Runbook: {name}\n\n"
|
|
238
|
+
"## Verification Gate\n\n"
|
|
239
|
+
"```bash\n"
|
|
240
|
+
"gitvouch check\n"
|
|
241
|
+
"gitvouch status\n"
|
|
242
|
+
"```\n",
|
|
243
|
+
encoding="utf-8",
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
agents_path = root / "AGENTS.md"
|
|
247
|
+
block = (
|
|
248
|
+
"\n## Repository Governance (`gitvouch`)\n\n"
|
|
249
|
+
"This repository uses `.gitvouch/config.json` as its Git-native source of truth.\n\n"
|
|
250
|
+
"1. Read `.gitvouch/memory/current_state.md` and `.gitvouch/memory/decisions.md` before changes.\n"
|
|
251
|
+
"2. Never mark a task `verified` without capturing real evidence (`gitvouch evidence run` or `add`).\n"
|
|
252
|
+
"3. Never edit acceptance criteria after a task enters `ready` (they are snapshotted in `.gitvouch/control/events/`).\n"
|
|
253
|
+
"4. Run `gitvouch check` before finishing any change.\n"
|
|
254
|
+
)
|
|
255
|
+
if agents_path.is_file():
|
|
256
|
+
existing = agents_path.read_text(encoding="utf-8")
|
|
257
|
+
if "gitvouch check" not in existing:
|
|
258
|
+
agents_path.write_text(existing.rstrip() + "\n" + block, encoding="utf-8")
|
|
259
|
+
else:
|
|
260
|
+
agents_path.write_text(f"# Agent Instructions: {name}\n" + block, encoding="utf-8")
|
|
261
|
+
|
|
262
|
+
return config
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def add_milestone(
|
|
266
|
+
root: Path,
|
|
267
|
+
*,
|
|
268
|
+
title: str,
|
|
269
|
+
description: str = "",
|
|
270
|
+
status: str = "planned",
|
|
271
|
+
) -> dict[str, Any]:
|
|
272
|
+
config = _load_config(root)
|
|
273
|
+
ctrl = _control_root(root, config)
|
|
274
|
+
now = utc_now()
|
|
275
|
+
milestone_id = _next_numeric_id(ctrl / "milestones", "M")
|
|
276
|
+
milestone = {
|
|
277
|
+
"schema_version": 1,
|
|
278
|
+
"id": milestone_id,
|
|
279
|
+
"title": title,
|
|
280
|
+
"description": description,
|
|
281
|
+
"status": status,
|
|
282
|
+
"task_ids": [],
|
|
283
|
+
"created_at": iso_utc(now),
|
|
284
|
+
"updated_at": iso_utc(now),
|
|
285
|
+
}
|
|
286
|
+
write_json(ctrl / "milestones" / f"{milestone_id}.json", milestone)
|
|
287
|
+
|
|
288
|
+
project_path = ctrl / "project.json"
|
|
289
|
+
project = load_json(project_path)
|
|
290
|
+
project["milestone_ids"].append(milestone_id)
|
|
291
|
+
project["updated_at"] = iso_utc(now)
|
|
292
|
+
write_json(project_path, project)
|
|
293
|
+
return milestone
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def create_task(
|
|
297
|
+
root: Path,
|
|
298
|
+
*,
|
|
299
|
+
title: str,
|
|
300
|
+
scope: str,
|
|
301
|
+
criteria: list[str],
|
|
302
|
+
milestone_id: str = "M-001",
|
|
303
|
+
weight: int = 1,
|
|
304
|
+
owners: list[str] | None = None,
|
|
305
|
+
dependencies: list[str] | None = None,
|
|
306
|
+
max_age_days: int | None = None,
|
|
307
|
+
actor: str | None = None,
|
|
308
|
+
) -> dict[str, Any]:
|
|
309
|
+
config = _load_config(root)
|
|
310
|
+
ctrl = _control_root(root, config)
|
|
311
|
+
milestone_path = ctrl / "milestones" / f"{milestone_id}.json"
|
|
312
|
+
if not milestone_path.is_file():
|
|
313
|
+
raise GitvouchError(f"Milestone {milestone_id} does not exist.")
|
|
314
|
+
if weight < 1:
|
|
315
|
+
raise GitvouchError("Task weight must be >= 1.")
|
|
316
|
+
|
|
317
|
+
deps = list(dict.fromkeys(dependencies or []))
|
|
318
|
+
for dep in deps:
|
|
319
|
+
if not (ctrl / "tasks" / f"{dep}.json").is_file():
|
|
320
|
+
raise GitvouchError(f"Dependency task {dep} does not exist.")
|
|
321
|
+
|
|
322
|
+
now = utc_now()
|
|
323
|
+
task_id = _next_numeric_id(ctrl / "tasks", "T")
|
|
324
|
+
task_owners = list(dict.fromkeys(owners or [actor or default_actor()]))
|
|
325
|
+
ac_list: list[dict[str, Any]] = []
|
|
326
|
+
for idx, desc in enumerate(criteria, start=1):
|
|
327
|
+
item: dict[str, Any] = {"id": f"AC-{idx}", "description": desc.strip()}
|
|
328
|
+
if max_age_days is not None:
|
|
329
|
+
item["max_age_days"] = max_age_days
|
|
330
|
+
ac_list.append(item)
|
|
331
|
+
|
|
332
|
+
task = {
|
|
333
|
+
"schema_version": 1,
|
|
334
|
+
"id": task_id,
|
|
335
|
+
"milestone_id": milestone_id,
|
|
336
|
+
"title": title.strip(),
|
|
337
|
+
"scope": scope.strip(),
|
|
338
|
+
"state": "proposed",
|
|
339
|
+
"weight": weight,
|
|
340
|
+
"dependencies": deps,
|
|
341
|
+
"owners": task_owners,
|
|
342
|
+
"acceptance_criteria": ac_list,
|
|
343
|
+
"active_blockers": [],
|
|
344
|
+
"created_at": iso_utc(now),
|
|
345
|
+
"updated_at": iso_utc(now),
|
|
346
|
+
}
|
|
347
|
+
write_json(ctrl / "tasks" / f"{task_id}.json", task)
|
|
348
|
+
_write_event(
|
|
349
|
+
ctrl,
|
|
350
|
+
task_id,
|
|
351
|
+
"task_created",
|
|
352
|
+
{
|
|
353
|
+
"state": "proposed",
|
|
354
|
+
"scope": task["scope"],
|
|
355
|
+
"weight": task["weight"],
|
|
356
|
+
"owners": task["owners"],
|
|
357
|
+
},
|
|
358
|
+
actor=actor or default_actor(),
|
|
359
|
+
occurred_at=now,
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
milestone = load_json(milestone_path)
|
|
363
|
+
milestone["task_ids"].append(task_id)
|
|
364
|
+
milestone["updated_at"] = iso_utc(now)
|
|
365
|
+
write_json(milestone_path, milestone)
|
|
366
|
+
return task
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _load_task_evidence(ctrl: Path, task_id: str) -> list[dict[str, Any]]:
|
|
370
|
+
ev_dir = ctrl / "evidence" / task_id
|
|
371
|
+
if not ev_dir.is_dir():
|
|
372
|
+
return []
|
|
373
|
+
records = [load_json(p) for p in sorted(ev_dir.glob("*.json"))]
|
|
374
|
+
records.sort(key=lambda r: (r["collected_at"], r["id"]), reverse=True)
|
|
375
|
+
return records
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def transition_task(
|
|
379
|
+
root: Path,
|
|
380
|
+
task_id: str,
|
|
381
|
+
target_state: str,
|
|
382
|
+
*,
|
|
383
|
+
evidence_ids: list[str] | None = None,
|
|
384
|
+
actor: str | None = None,
|
|
385
|
+
) -> dict[str, Any]:
|
|
386
|
+
config = _load_config(root)
|
|
387
|
+
ctrl = _control_root(root, config)
|
|
388
|
+
task_path = ctrl / "tasks" / f"{task_id}.json"
|
|
389
|
+
if not task_path.is_file():
|
|
390
|
+
raise GitvouchError(f"Task {task_id} does not exist.")
|
|
391
|
+
|
|
392
|
+
task = load_json(task_path)
|
|
393
|
+
current = task["state"]
|
|
394
|
+
actor_name = actor or default_actor()
|
|
395
|
+
now = utc_now()
|
|
396
|
+
|
|
397
|
+
# Ergonomic auto-step: allow `verify` directly from `implemented` by recording
|
|
398
|
+
# both immutable transitions (`implemented -> verifying`, then `verifying -> verified`).
|
|
399
|
+
if target_state == "verified" and current == "implemented":
|
|
400
|
+
transition_task(root, task_id, "verifying", actor=actor_name)
|
|
401
|
+
task = load_json(task_path)
|
|
402
|
+
current = task["state"]
|
|
403
|
+
now = utc_now()
|
|
404
|
+
|
|
405
|
+
if target_state not in ALLOWED_TRANSITIONS.get(current, set()):
|
|
406
|
+
raise GitvouchError(f"Illegal state transition for {task_id}: {current} -> {target_state}.")
|
|
407
|
+
|
|
408
|
+
if task["active_blockers"] and (current, target_state) in FORWARD_TRANSITIONS:
|
|
409
|
+
raise GitvouchError(
|
|
410
|
+
f"Task {task_id} is blocked by {task['active_blockers']} and cannot advance to {target_state}."
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
details: dict[str, Any] = {
|
|
414
|
+
"from": current,
|
|
415
|
+
"to": target_state,
|
|
416
|
+
"evidence_ids": [],
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
if target_state == "ready":
|
|
420
|
+
if not task["acceptance_criteria"]:
|
|
421
|
+
raise GitvouchError(
|
|
422
|
+
f"Task {task_id} cannot enter 'ready' without at least one acceptance criterion."
|
|
423
|
+
)
|
|
424
|
+
for dep_id in task["dependencies"]:
|
|
425
|
+
dep_path = ctrl / "tasks" / f"{dep_id}.json"
|
|
426
|
+
if not dep_path.is_file():
|
|
427
|
+
raise GitvouchError(f"Task {task_id} depends on missing task {dep_id}.")
|
|
428
|
+
dep = load_json(dep_path)
|
|
429
|
+
if dep["state"] != "verified":
|
|
430
|
+
raise GitvouchError(
|
|
431
|
+
f"Task {task_id} cannot enter 'ready': dependency {dep_id} is '{dep['state']}', not 'verified'."
|
|
432
|
+
)
|
|
433
|
+
details["dependency_ids"] = list(task["dependencies"])
|
|
434
|
+
details["acceptance_criteria_ids"] = [c["id"] for c in task["acceptance_criteria"]]
|
|
435
|
+
details["acceptance_criteria_snapshot"] = [dict(c) for c in task["acceptance_criteria"]]
|
|
436
|
+
|
|
437
|
+
if target_state == "verified":
|
|
438
|
+
all_evidence = _load_task_evidence(ctrl, task_id)
|
|
439
|
+
by_id = {item["id"]: item for item in all_evidence}
|
|
440
|
+
selected_ids: list[str] = []
|
|
441
|
+
if evidence_ids:
|
|
442
|
+
missing = [eid for eid in evidence_ids if eid not in by_id]
|
|
443
|
+
if missing:
|
|
444
|
+
raise GitvouchError(f"Unknown evidence IDs for {task_id}: {', '.join(missing)}.")
|
|
445
|
+
pool = [by_id[eid] for eid in evidence_ids]
|
|
446
|
+
selected_ids = list(dict.fromkeys(evidence_ids))
|
|
447
|
+
else:
|
|
448
|
+
pool = all_evidence
|
|
449
|
+
|
|
450
|
+
missing_criteria: list[str] = []
|
|
451
|
+
auto_chosen: list[str] = []
|
|
452
|
+
for criterion in task["acceptance_criteria"]:
|
|
453
|
+
valid_item, reasons = evaluate_criterion_evidence(
|
|
454
|
+
task,
|
|
455
|
+
criterion,
|
|
456
|
+
pool,
|
|
457
|
+
at_time=now,
|
|
458
|
+
now=now,
|
|
459
|
+
)
|
|
460
|
+
if valid_item is None:
|
|
461
|
+
detail = f" ({'; '.join(reasons)})" if reasons else " (no evidence recorded)"
|
|
462
|
+
missing_criteria.append(f"{criterion['id']}: {criterion['description']}{detail}")
|
|
463
|
+
else:
|
|
464
|
+
auto_chosen.append(valid_item["id"])
|
|
465
|
+
|
|
466
|
+
if missing_criteria:
|
|
467
|
+
joined = "\n - ".join(missing_criteria)
|
|
468
|
+
raise GitvouchError(
|
|
469
|
+
f"Verification gate REFUSED {task_id} -> verified. Missing valid passing evidence:\n"
|
|
470
|
+
f" - {joined}"
|
|
471
|
+
)
|
|
472
|
+
details["evidence_ids"] = selected_ids or list(dict.fromkeys(auto_chosen))
|
|
473
|
+
|
|
474
|
+
_write_event(
|
|
475
|
+
ctrl,
|
|
476
|
+
task_id,
|
|
477
|
+
"state_transition",
|
|
478
|
+
details,
|
|
479
|
+
actor=actor_name,
|
|
480
|
+
occurred_at=now,
|
|
481
|
+
)
|
|
482
|
+
task["state"] = target_state
|
|
483
|
+
task["updated_at"] = iso_utc(now)
|
|
484
|
+
write_json(task_path, task)
|
|
485
|
+
return task
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def add_blocker(
|
|
489
|
+
root: Path,
|
|
490
|
+
task_id: str,
|
|
491
|
+
blocker_id: str,
|
|
492
|
+
summary: str,
|
|
493
|
+
*,
|
|
494
|
+
actor: str | None = None,
|
|
495
|
+
) -> dict[str, Any]:
|
|
496
|
+
config = _load_config(root)
|
|
497
|
+
ctrl = _control_root(root, config)
|
|
498
|
+
task_path = ctrl / "tasks" / f"{task_id}.json"
|
|
499
|
+
if not task_path.is_file():
|
|
500
|
+
raise GitvouchError(f"Task {task_id} does not exist.")
|
|
501
|
+
task = load_json(task_path)
|
|
502
|
+
if blocker_id in task["active_blockers"]:
|
|
503
|
+
raise GitvouchError(f"Blocker {blocker_id} is already active on {task_id}.")
|
|
504
|
+
|
|
505
|
+
now = utc_now()
|
|
506
|
+
_write_event(
|
|
507
|
+
ctrl,
|
|
508
|
+
task_id,
|
|
509
|
+
"blocker_added",
|
|
510
|
+
{"blocker_id": blocker_id, "summary": summary.strip()},
|
|
511
|
+
actor=actor or default_actor(),
|
|
512
|
+
occurred_at=now,
|
|
513
|
+
)
|
|
514
|
+
task["active_blockers"].append(blocker_id)
|
|
515
|
+
task["updated_at"] = iso_utc(now)
|
|
516
|
+
write_json(task_path, task)
|
|
517
|
+
return task
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def resolve_blocker(
|
|
521
|
+
root: Path,
|
|
522
|
+
task_id: str,
|
|
523
|
+
blocker_id: str,
|
|
524
|
+
resolution: str,
|
|
525
|
+
*,
|
|
526
|
+
actor: str | None = None,
|
|
527
|
+
) -> dict[str, Any]:
|
|
528
|
+
config = _load_config(root)
|
|
529
|
+
ctrl = _control_root(root, config)
|
|
530
|
+
task_path = ctrl / "tasks" / f"{task_id}.json"
|
|
531
|
+
if not task_path.is_file():
|
|
532
|
+
raise GitvouchError(f"Task {task_id} does not exist.")
|
|
533
|
+
task = load_json(task_path)
|
|
534
|
+
if blocker_id not in task["active_blockers"]:
|
|
535
|
+
raise GitvouchError(f"Blocker {blocker_id} is not active on {task_id}.")
|
|
536
|
+
|
|
537
|
+
now = utc_now()
|
|
538
|
+
_write_event(
|
|
539
|
+
ctrl,
|
|
540
|
+
task_id,
|
|
541
|
+
"blocker_resolved",
|
|
542
|
+
{"blocker_id": blocker_id, "resolution": resolution.strip()},
|
|
543
|
+
actor=actor or default_actor(),
|
|
544
|
+
occurred_at=now,
|
|
545
|
+
)
|
|
546
|
+
task["active_blockers"] = [b for b in task["active_blockers"] if b != blocker_id]
|
|
547
|
+
task["updated_at"] = iso_utc(now)
|
|
548
|
+
write_json(task_path, task)
|
|
549
|
+
return task
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def add_evidence(
|
|
553
|
+
root: Path,
|
|
554
|
+
*,
|
|
555
|
+
task_id: str,
|
|
556
|
+
criterion_id: str,
|
|
557
|
+
result: str,
|
|
558
|
+
summary: str,
|
|
559
|
+
provenance: dict[str, Any],
|
|
560
|
+
collector: str | None = None,
|
|
561
|
+
applicable: bool = True,
|
|
562
|
+
expires_days: int | None = None,
|
|
563
|
+
) -> dict[str, Any]:
|
|
564
|
+
config = _load_config(root)
|
|
565
|
+
ctrl = _control_root(root, config)
|
|
566
|
+
task_path = ctrl / "tasks" / f"{task_id}.json"
|
|
567
|
+
if not task_path.is_file():
|
|
568
|
+
raise GitvouchError(f"Task {task_id} does not exist.")
|
|
569
|
+
task = load_json(task_path)
|
|
570
|
+
criteria = {c["id"] for c in task["acceptance_criteria"]}
|
|
571
|
+
if criterion_id not in criteria:
|
|
572
|
+
raise GitvouchError(f"Criterion {criterion_id} does not exist on task {task_id}.")
|
|
573
|
+
if not provenance:
|
|
574
|
+
raise GitvouchError(
|
|
575
|
+
"At least one provenance field (commit, command, ci_job, url, artifact_sha256) is required."
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
now = utc_now()
|
|
579
|
+
evidence_id = _next_evidence_id(ctrl)
|
|
580
|
+
record: dict[str, Any] = {
|
|
581
|
+
"schema_version": 1,
|
|
582
|
+
"id": evidence_id,
|
|
583
|
+
"task_id": task_id,
|
|
584
|
+
"criterion_id": criterion_id,
|
|
585
|
+
"result": result,
|
|
586
|
+
"applicable": applicable,
|
|
587
|
+
"collected_at": iso_utc(now),
|
|
588
|
+
"collector": collector or default_actor(),
|
|
589
|
+
"summary": summary.strip()[:2000],
|
|
590
|
+
"provenance": provenance,
|
|
591
|
+
}
|
|
592
|
+
if expires_days is not None:
|
|
593
|
+
if expires_days < 1:
|
|
594
|
+
raise GitvouchError("--expires-days must be >= 1.")
|
|
595
|
+
record["expires_at"] = iso_utc(now + timedelta(days=expires_days))
|
|
596
|
+
|
|
597
|
+
write_json(ctrl / "evidence" / task_id / f"{evidence_id}.json", record)
|
|
598
|
+
return record
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def run_evidence_command(
|
|
602
|
+
root: Path,
|
|
603
|
+
*,
|
|
604
|
+
task_id: str,
|
|
605
|
+
criterion_id: str,
|
|
606
|
+
command: str,
|
|
607
|
+
collector: str | None = None,
|
|
608
|
+
expires_days: int | None = None,
|
|
609
|
+
timeout: int = 300,
|
|
610
|
+
) -> tuple[dict[str, Any], int]:
|
|
611
|
+
"""Execute a real verification command and persist tamper-evident pass/fail provenance."""
|
|
612
|
+
proc = subprocess.run(
|
|
613
|
+
command,
|
|
614
|
+
cwd=root,
|
|
615
|
+
shell=True,
|
|
616
|
+
capture_output=True,
|
|
617
|
+
text=True,
|
|
618
|
+
timeout=timeout,
|
|
619
|
+
check=False,
|
|
620
|
+
)
|
|
621
|
+
combined = (proc.stdout or "") + (("\n" + proc.stderr) if proc.stderr else "")
|
|
622
|
+
digest = hashlib.sha256(combined.encode("utf-8", errors="replace")).hexdigest()
|
|
623
|
+
tail_lines = [line for line in combined.strip().splitlines()[-8:] if line.strip()]
|
|
624
|
+
tail = " | ".join(tail_lines)
|
|
625
|
+
summary = f"Command exited {proc.returncode}: {command}"
|
|
626
|
+
if tail:
|
|
627
|
+
summary = f"{summary} - {tail}"
|
|
628
|
+
|
|
629
|
+
provenance: dict[str, Any] = {
|
|
630
|
+
"command": command,
|
|
631
|
+
"exit_code": proc.returncode,
|
|
632
|
+
"artifact_sha256": digest,
|
|
633
|
+
}
|
|
634
|
+
provenance.update(_git_provenance(root))
|
|
635
|
+
|
|
636
|
+
record = add_evidence(
|
|
637
|
+
root,
|
|
638
|
+
task_id=task_id,
|
|
639
|
+
criterion_id=criterion_id,
|
|
640
|
+
result="pass" if proc.returncode == 0 else "fail",
|
|
641
|
+
summary=summary[:2000],
|
|
642
|
+
provenance=provenance,
|
|
643
|
+
collector=collector or f"gitvouch-run:{default_actor()}",
|
|
644
|
+
expires_days=expires_days,
|
|
645
|
+
)
|
|
646
|
+
return record, proc.returncode
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def review_memory(root: Path, *, note: str, basis: str | None = None) -> dict[str, Any]:
|
|
650
|
+
config = _load_config(root)
|
|
651
|
+
mem = _memory_root(root, config)
|
|
652
|
+
today = utc_now().date().isoformat()
|
|
653
|
+
|
|
654
|
+
snap_path = mem / "state_snapshot.json"
|
|
655
|
+
state = load_json(snap_path)
|
|
656
|
+
state["last_reviewed"] = today
|
|
657
|
+
if basis:
|
|
658
|
+
state.setdefault("freshness", {})["basis"] = basis.strip()
|
|
659
|
+
write_json(snap_path, state)
|
|
660
|
+
|
|
661
|
+
current_path = mem / "current_state.md"
|
|
662
|
+
current_text = current_path.read_text(encoding="utf-8")
|
|
663
|
+
updated_current, count = re.subn(
|
|
664
|
+
r"(\*\*Last reviewed\*\*:\s*)[0-9]{4}-[0-9]{2}-[0-9]{2}",
|
|
665
|
+
rf"\g<1>{today}",
|
|
666
|
+
current_text,
|
|
667
|
+
)
|
|
668
|
+
if count == 0 and today not in updated_current:
|
|
669
|
+
updated_current = f"- **Last reviewed**: {today}\n\n" + updated_current
|
|
670
|
+
current_path.write_text(updated_current, encoding="utf-8")
|
|
671
|
+
|
|
672
|
+
log_path = mem / "operation_log.md"
|
|
673
|
+
log_text = log_path.read_text(encoding="utf-8")
|
|
674
|
+
heading = f"## {today}"
|
|
675
|
+
entry = f"- {note.strip()}\n"
|
|
676
|
+
if heading in log_text:
|
|
677
|
+
log_text = log_text.rstrip() + "\n" + entry
|
|
678
|
+
else:
|
|
679
|
+
log_text = log_text.rstrip() + f"\n\n{heading}\n\n{entry}"
|
|
680
|
+
log_path.write_text(log_text, encoding="utf-8")
|
|
681
|
+
|
|
682
|
+
return {"last_reviewed": today, "note": note.strip()}
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def collect_status(root: Path) -> dict[str, Any]:
|
|
686
|
+
root = root.resolve()
|
|
687
|
+
config = _load_config(root)
|
|
688
|
+
report = validate_repository(root)
|
|
689
|
+
status: dict[str, Any] = {
|
|
690
|
+
"project_name": config["project_name"],
|
|
691
|
+
"profile": config["profile"],
|
|
692
|
+
"valid": report.ok,
|
|
693
|
+
"failure_count": len(report.failures),
|
|
694
|
+
"warning_count": len(report.warnings),
|
|
695
|
+
"memory_age_days": report.memory_age_days,
|
|
696
|
+
"progress": report.progress,
|
|
697
|
+
"tasks": [],
|
|
698
|
+
}
|
|
699
|
+
if config["control"].get("enabled"):
|
|
700
|
+
ctrl = _control_root(root, config)
|
|
701
|
+
tasks_dir = ctrl / "tasks"
|
|
702
|
+
now = utc_now()
|
|
703
|
+
task_map: dict[str, tuple[Path, dict[str, Any]]] = {}
|
|
704
|
+
if tasks_dir.is_dir():
|
|
705
|
+
for path in sorted(tasks_dir.glob("*.json")):
|
|
706
|
+
task = load_json(path)
|
|
707
|
+
task_map[task["id"]] = (path, task)
|
|
708
|
+
ev = _load_task_evidence(ctrl, task["id"])
|
|
709
|
+
passed_ac = 0
|
|
710
|
+
for criterion in task["acceptance_criteria"]:
|
|
711
|
+
valid_item, _ = evaluate_criterion_evidence(
|
|
712
|
+
task, criterion, ev, at_time=now, now=now
|
|
713
|
+
)
|
|
714
|
+
if valid_item is not None:
|
|
715
|
+
passed_ac += 1
|
|
716
|
+
status["tasks"].append(
|
|
717
|
+
{
|
|
718
|
+
"id": task["id"],
|
|
719
|
+
"milestone_id": task["milestone_id"],
|
|
720
|
+
"title": task["title"],
|
|
721
|
+
"state": task["state"],
|
|
722
|
+
"weight": task["weight"],
|
|
723
|
+
"blocked": bool(task["active_blockers"]),
|
|
724
|
+
"active_blockers": task["active_blockers"],
|
|
725
|
+
"criteria_verified": passed_ac,
|
|
726
|
+
"criteria_total": len(task["acceptance_criteria"]),
|
|
727
|
+
}
|
|
728
|
+
)
|
|
729
|
+
status["progress"] = calculate_progress(task_map)
|
|
730
|
+
return status
|