Repository navigation
Expand file tree
/
Copy pathcfw_progress.py
More file actions
216 lines (192 loc) · 10.1 KB
/
Copy pathcfw_progress.py
File metadata and controls
216 lines (192 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env python3
"""Evaluate the fixed generic-CFW goal against reviewed, hashed evidence.
A matching file hash proves integrity, not the truth of its contents. Reviewers
must check that the evidence actually satisfies every criterion before claiming it.
"""
import argparse
import hashlib
import contextlib
import datetime
import os
import sys
import uuid
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SCOPE = ROOT / 'docs/data/generic-cfw-boot-scope.json'
CLAIMS = ROOT / 'docs/data/generic-cfw-boot-claims.json'
SCOPE_SHA256 = 'cf0885ae8e8eebb76b6cead8d4c57546eaba99457c5d02b5f464da9a9ab0167a'
def validate_scope(scope):
encoded = (json.dumps(scope, indent=2, ensure_ascii=False) + '\n').encode()
if hashlib.sha256(encoded).hexdigest() != SCOPE_SHA256:
raise ValueError('Scope differs from the approved version 1 baseline')
def _verify_claim(gate, claim, root):
if not
8000
isinstance(claim, dict) or not str(claim.get('reviewer', '')).strip():
return 'missing reviewer or claim'
evidence = claim.get('evidence')
if not isinstance(evidence, dict) or set(evidence) != set(gate['acceptance']):
return 'missing or unexpected acceptance criteria'
root = Path(root).resolve()
for entries in evidence.values():
if not isinstance(entries, list) or not entries:
return 'missing evidence'
for entry in entries:
if not isinstance(entry, dict) or not isinstance(entry.get('path'), str):
return 'invalid evidence reference'
path = (root / entry['path']).resolve()
if not path.is_relative_to(root) or not path.is_file():
return 'missing or out-of-root evidence'
try:
digest = hashlib.sha256(path.read_bytes()).hexdigest()
except OSError:
return 'unreadable evidence'
if digest != entry.get('sha256'):
return 'evidence hash mismatch'
return None
def evaluate(scope, claims, evidence_root):
validate_scope(scope)
latest = {}
for claim in claims:
if not isinstance(claim, dict) or claim.get('gate') not in {g['id'] for g in scope['gates']}:
raise ValueError('Unknown or malformed gate claim')
latest[claim['gate']] = claim
results, passed, points = [], set(), 0
for gate in scope['gates']:
claim = latest.get(gate['id'])
reason = _verify_claim(gate, claim, evidence_root)
missing = [dependency for dependency in gate['depends'] if dependency not in passed]
if not reason and missing:
reason = 'prerequisites not verified: ' + ', '.join(missing)
if not reason:
points += gate['weight']
passed.add(gate['id'])
results.append({'id': gate['id'], 'weight': gate['weight'], 'status': 'verified' if not reason else 'unverified', 'reason': reason})
return {'scope': scope['id'], 'version': scope['version'], 'points': points, 'out_of': 100, 'gates': results}
def render_markdown(scope, report):
lines = ['# Generic CFW boot testing progress', '',
f"**Progress: {report['points']} / 100 points**", '',
'Evidence hashes establish integrity only; acceptance requires substantive review.', '',
'| Gate | Weight | Status | Reason |', '| --- | ---: | --- | --- |']
for gate in report['gates']:
reason = (gate['reason'] or 'reviewed evidence intact').replace('|', '\\|').replace('\n', ' ')
lines.append(f"| {gate['id']} | {gate['weight']} | {gate['status']} | {reason} |")
return '\n'.join(lines) + '\n'
@contextlib.contextmanager
def _lock(path):
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('a+b') as lockfile:
if os.name == 'nt':
import msvcrt
lockfile.seek(0, 2)
if lockfile.tell() == 0:
lockfile.write(b'0')
lockfile.flush()
lockfile.seek(0)
msvcrt.locking(lockfile.fileno(), msvcrt.LK_LOCK, 1)
else:
import fcntl
fcntl.flock(lockfile.fileno(), fcntl.LOCK_EX)
try:
yield
finally:
if os.name == 'nt':
lockfile.seek(0)
msvcrt.locking(lockfile.fileno(), msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(lockfile.fileno(), fcntl.LOCK_UN)
class Ledger:
"""Append-only task history; recovery is an explicit recorded decision."""
def __init__(self, path):
self.path = Path(path)
self.lock = self.path.with_suffix(self.path.suffix + '.lock')
def read(self):
if not self.path.exists():
return []
with self.path.open(encoding='utf-8') as source:
return [json.loads(line) for line in source if line.strip()]
def _append(self, event):
event['time'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
with self.path.open('a', encoding='utf-8') as target:
target.write(json.dumps(event, ensure_ascii=False) + '\n')
target.flush()
os.fsync(target.fileno())
def start(self, key, fingerprint, owner, description, repeat_reason='', inputs=None):
if not all(isinstance(v, str) and v.strip() for v in (key, fingerprint, owner, description)):
raise ValueError('key, fingerprint, owner and description are required')
with _lock(self.lock):
history = self.read()
starts = [e for e in history if e.get('event') == 'start' and e.get('key') == key and e.get('fingerprint') == fingerprint]
for start in starts:
terminal = next((e for e in reversed(history) if e.get('task') == start['task'] and e.get('event') in ('finish', 'recover')), None)
if terminal is None:
raise ValueError('matching task already active; verify its process before recovery')
if terminal.get('outcome') == 'done' and not repeat_reason.strip():
raise ValueError('matching task already completed; provide repeat reason')
task = 'cfw-' + uuid.uuid4().hex
self._append({'event': 'start', 'task': task, 'key': key, 'fingerprint': fingerprint, 'owner': owner, 'description': description, 'repeat_reason': repeat_reason, 'inputs': inputs or []})
return task
def _end(self, task, event, outcome, evidence, reason):
if not isinstance(reason, str) or not reason.strip():
raise ValueError('reason is required')
with _lock(self.lock):
history = self.read()
if not any(e.get('event') == 'start' and e.get('task') == task for e in history) or any(e.get('event') in ('finish', 'recover') and e.get('task') == task for e in history):
raise ValueError('task is not active')
self._append({'event': event, 'task': task, 'outcome': outcome, 'evidence': evidence, 'reason': reason})
def finish(self, task, outcome, evidence, reason):
if outcome not in ('done', 'failed', 'deferred'):
raise ValueError('invalid outcome')
if not evidence.strip():
raise ValueError('evidence reference is required')
self._end(task, 'finish', outcome, evidence, reason)
def recover(self, task, reason):
self._end(task, 'recover', 'deferred', '', reason)
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command')
report = sub.add_parser('report', help='evaluate reviewed claims')
report.add_argument('--claims', type=Path)
report.add_argument('--format', choices=('json', 'markdown'), default='json')
report.add_argument('--evidence-root', type=Path, default=ROOT)
start = sub.add_parser('start', help='record a new task and its input fingerprint')
start.add_argument('--key', required=True)
start.add_argument('--owner', required=True)
start.add_argument('--description', required=True)
start.add_argument('--input', type=Path, action='append', required=True)
start.add_argument('--repeat-reason', default='')
finish = sub.add_parser('finish', help='record a task outcome')
finish.add_argument('--task', required=True)
finish.add_argument('--outcome', choices=('done', 'failed', 'deferred'), required=True)
finish.add_argument('--evidence', required=True)
finish.add_argument('--reason', required=True)
recover = sub.add_parser('recover', help='record an interrupted task after checking its process')
recover.add_argument('--task', required=True)
recover.add_argument('--reason', required=True)
for p in (start, finish, recover):
p.add_argument('--ledger', type=Path, default=ROOT / 'docs/data/generic-cfw-boot-work-log.jsonl')
args = parser.parse_args(sys.argv[1:] or ['report'])
if args.command == 'report':
scope = json.loads(SCOPE.read_text(encoding='utf-8'))
claims_path = args.claims if args.claims is not None else CLAIMS
claims = json.loads(claims_path.read_text(encoding='utf-8')) if args.claims is not None or claims_path.exists() else []
if not isinstance(claims, list):
parser.error('claims must be a JSON array')
result = evaluate(scope, claims, args.evidence_root)
print(render_markdown(scope, result) if args.format == 'markdown' else json.dumps(result, indent=2))
return
if not args.command:
parser.error('select report, start, finish, or recover')
ledger = Ledger(args.ledger)
try:
if args.command == 'start':
inputs = sorted((str(p.resolve()), hashlib.sha256(p.read_bytes()).hexdigest()) for p in args.input)
fingerprint = hashlib.sha256(json.dumps(inputs, separators=(',', ':')).encode()).hexdigest()
print(ledger.start(args.key, fingerprint, args.owner, args.description, args.repeat_reason, [{'path': path, 'sha256': digest} for path, digest in inputs]))
elif args.command == 'finish':
ledger.finish(args.task, args.outcome, args.evidence, args.reason)
else:
ledger.recover(args.task, args.reason)
except (OSError, ValueError) as exc:
parser.error(str(exc))
if __name__ == '__main__':
main()