taskforce-loop-engineering 0.16.2 → 0.16.4
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.
- package/CHANGELOG.md +16 -0
- package/README.md +4 -0
- package/docs/isolated-verification.md +81 -0
- package/lib/context-budget.mjs +9 -1
- package/lib/core.mjs +298 -40
- package/lib/isolated-verification.mjs +47 -0
- package/package.json +6 -4
- package/scripts/async-acceptance-refresh-self-test.mjs +3 -0
- package/scripts/context-budget-self-test.mjs +25 -7
- package/scripts/final-judgement-self-test.mjs +568 -1
- package/scripts/isolated-verification-self-test.mjs +201 -0
- package/scripts/isolated-verify-self-test.py +133 -0
- package/scripts/isolated-verify.py +418 -0
- package/scripts/project-gate-reconciliation-self-test.mjs +36 -1
- package/scripts/revision-coverage-self-test.mjs +105 -0
- package/skills/taskforce-loop-engineering/SKILL.md +26 -1
- package/skills/taskforce-loop-engineering/references/context-budget.md +1 -1
- package/skills/taskforce-loop-engineering/references/frozen-input-verification.md +40 -0
- package/skills/taskforce-loop-engineering/references/scope-task-acceptance.md +29 -0
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Fail-closed Linux verification of explicitly frozen project inputs.
|
|
3
|
+
|
|
4
|
+
The project supplies file/directory inputs and a command. This supervisor is
|
|
5
|
+
host-owned; strace wraps bwrap, so the sandbox cannot edit its read trace.
|
|
6
|
+
"""
|
|
7
|
+
import argparse
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import posixpath
|
|
12
|
+
import stat
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import signal
|
|
17
|
+
import subprocess
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
OPEN = re.compile(r"=\s+\d+<([^<>]+)(?:<[^>]+>)?>(?:\(deleted\))?\s*$")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def sha(path):
|
|
25
|
+
h = hashlib.sha256()
|
|
26
|
+
with path.open("rb") as stream:
|
|
27
|
+
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
|
28
|
+
h.update(block)
|
|
29
|
+
return h.hexdigest()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def living_process_group(group):
|
|
33
|
+
"""Ignore reaped-but-uncollected zombies; they cannot execute or retain fds."""
|
|
34
|
+
for proc in Path("/proc").iterdir():
|
|
35
|
+
if not proc.name.isdigit():
|
|
36
|
+
continue
|
|
37
|
+
try:
|
|
38
|
+
fields = (proc / "stat").read_text().rsplit(") ", 1)[1].split()
|
|
39
|
+
pgrp = int(fields[2])
|
|
40
|
+
except (FileNotFoundError, ProcessLookupError, PermissionError, IndexError, ValueError):
|
|
41
|
+
continue
|
|
42
|
+
if pgrp == group and fields[0] != "Z":
|
|
43
|
+
return True
|
|
44
|
+
return False
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def inventory(root, names):
|
|
48
|
+
if not isinstance(names, list) or not names:
|
|
49
|
+
raise ValueError("inputs must be a nonempty array")
|
|
50
|
+
files = {}
|
|
51
|
+
for name in names:
|
|
52
|
+
if not isinstance(name, str) or not name or name.startswith("/") or ".." in Path(name).parts:
|
|
53
|
+
raise ValueError("unsafe input path")
|
|
54
|
+
target = root / name
|
|
55
|
+
cursor = root
|
|
56
|
+
for part in Path(name).parts:
|
|
57
|
+
cursor = cursor / part
|
|
58
|
+
if cursor.is_symlink():
|
|
59
|
+
raise ValueError("symlink input ancestor: " + name)
|
|
60
|
+
if not target.exists() or target.is_symlink():
|
|
61
|
+
raise ValueError("missing or symlink input: " + name)
|
|
62
|
+
candidates = [target] if target.is_file() else sorted(target.rglob("*"))
|
|
63
|
+
for candidate in candidates:
|
|
64
|
+
relative = candidate.relative_to(root).as_posix()
|
|
65
|
+
if candidate.is_symlink():
|
|
66
|
+
raise ValueError("symlink input: " + relative)
|
|
67
|
+
if candidate.is_file():
|
|
68
|
+
files[relative] = {"sha256": sha(candidate), "size": candidate.stat().st_size,
|
|
69
|
+
"mode": stat.S_IMODE(candidate.stat().st_mode)}
|
|
70
|
+
elif not candidate.is_dir():
|
|
71
|
+
raise ValueError("special input: " + relative)
|
|
72
|
+
return dict(sorted(files.items()))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def decode_trace_string(value):
|
|
76
|
+
"""Decode strace C byte escapes, not JSON or Python Unicode escapes."""
|
|
77
|
+
result = bytearray()
|
|
78
|
+
escapes = {'a': 7, 'b': 8, 't': 9, 'n': 10, 'v': 11, 'f': 12,
|
|
79
|
+
'r': 13, '\\': 92, '"': 34}
|
|
80
|
+
i = 0
|
|
81
|
+
while i < len(value):
|
|
82
|
+
char = value[i]
|
|
83
|
+
if char != '\\':
|
|
84
|
+
result.extend(os.fsencode(char))
|
|
85
|
+
i += 1
|
|
86
|
+
continue
|
|
87
|
+
i += 1
|
|
88
|
+
if i >= len(value):
|
|
89
|
+
raise ValueError('trailing escape')
|
|
90
|
+
if value[i] in escapes:
|
|
91
|
+
result.append(escapes[value[i]])
|
|
92
|
+
i += 1
|
|
93
|
+
elif value[i] in '01234567':
|
|
94
|
+
match = re.match(r'[0-7]{1,3}', value[i:])
|
|
95
|
+
result.append(int(match[0], 8))
|
|
96
|
+
i += len(match[0])
|
|
97
|
+
elif value[i] == 'x' and re.match(r'[0-9a-fA-F]{2}', value[i + 1:]):
|
|
98
|
+
result.append(int(value[i + 1:i + 3], 16))
|
|
99
|
+
i += 3
|
|
100
|
+
else:
|
|
101
|
+
raise ValueError('unknown escape')
|
|
102
|
+
if 0 in result:
|
|
103
|
+
raise ValueError('NUL path')
|
|
104
|
+
return os.fsdecode(bytes(result))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def available_project_attempt(raw_name, root, runtime_files):
|
|
108
|
+
"""Walk in the sandbox namespace before mapping /work to the source.
|
|
109
|
+
|
|
110
|
+
Do not normalize away missing or non-directory ancestors. In particular,
|
|
111
|
+
/work/../work re-enters the same mount, not a host sibling named work.
|
|
112
|
+
Linux treats any number of leading slashes as the same root.
|
|
113
|
+
"""
|
|
114
|
+
virtual_dirs = {'/home', '/tmp', '/out', '/proc', '/dev'}
|
|
115
|
+
for name in runtime_files:
|
|
116
|
+
virtual_dirs.update(str(parent) for parent in Path(name).parents)
|
|
117
|
+
parts = raw_name.split('/')
|
|
118
|
+
cursor = []
|
|
119
|
+
for index, part in enumerate(parts):
|
|
120
|
+
if not part:
|
|
121
|
+
continue
|
|
122
|
+
if part == '.':
|
|
123
|
+
continue
|
|
124
|
+
if part == '..':
|
|
125
|
+
if cursor:
|
|
126
|
+
cursor.pop()
|
|
127
|
+
continue
|
|
128
|
+
cursor.append(part)
|
|
129
|
+
final = index == len(parts) - 1
|
|
130
|
+
if cursor[0] == 'work':
|
|
131
|
+
source = root.joinpath(*cursor[1:])
|
|
132
|
+
if final:
|
|
133
|
+
return os.path.lexists(source)
|
|
134
|
+
if source.is_symlink():
|
|
135
|
+
raise ValueError('unresolved source symlink traversal')
|
|
136
|
+
if not source.is_dir():
|
|
137
|
+
return False
|
|
138
|
+
elif '/' + '/'.join(cursor) in virtual_dirs:
|
|
139
|
+
continue # supervisor-created mount roots
|
|
140
|
+
elif cursor[0] in ('usr', 'bin', 'lib', 'lib64', 'etc'):
|
|
141
|
+
source = Path('/').joinpath(*cursor)
|
|
142
|
+
# --ro-bind dereferences the host source at its destination root.
|
|
143
|
+
# /bin and /lib can be host symlinks but are sandbox directories.
|
|
144
|
+
# Descendant symlinks are not covered by that mount guarantee.
|
|
145
|
+
if len(cursor) > 1 and source.is_symlink():
|
|
146
|
+
raise ValueError('unresolved system symlink traversal')
|
|
147
|
+
if not source.is_dir():
|
|
148
|
+
return False
|
|
149
|
+
else:
|
|
150
|
+
if cursor[0] in ('tmp', 'out', 'proc', 'dev'):
|
|
151
|
+
# Dynamic mounts cannot be reconstructed from the source.
|
|
152
|
+
raise ValueError('unresolved sandbox path traversal')
|
|
153
|
+
# The sandbox root/home/opt contain only explicit mounts and
|
|
154
|
+
# runtime ancestors; a missing component cannot be crossed by '..'.
|
|
155
|
+
return False
|
|
156
|
+
return bool(cursor and cursor[0] == 'work' and root.joinpath(*cursor[1:]).is_dir())
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def resolve_failed_process_alias(raw_name, cwd):
|
|
160
|
+
"""Resolve proven self cwd/root links; unknown dynamic aliases fail closed.
|
|
161
|
+
|
|
162
|
+
Keep the suffix raw so missing ancestors and trailing slash semantics are
|
|
163
|
+
still checked by available_project_attempt, not erased by normpath.
|
|
164
|
+
"""
|
|
165
|
+
alias = r'/proc/(self|thread-self|[0-9]+)/(cwd|root|fd)(?=/|$)|/dev/fd(?=/|$)'
|
|
166
|
+
value = '/' + raw_name.lstrip('/')
|
|
167
|
+
for _ in range(8):
|
|
168
|
+
match = re.match(alias, value)
|
|
169
|
+
if not match:
|
|
170
|
+
if re.match(alias, '/' + posixpath.normpath(value).lstrip('/')):
|
|
171
|
+
raise ValueError('unresolved dynamic alias traversal')
|
|
172
|
+
return value
|
|
173
|
+
if match[1] not in ('self', 'thread-self') or match[2] == 'fd':
|
|
174
|
+
raise ValueError('unresolved dynamic fd or process alias')
|
|
175
|
+
base = cwd if match[2] == 'cwd' else '/'
|
|
176
|
+
if base is None:
|
|
177
|
+
raise ValueError('unknown cwd for process alias')
|
|
178
|
+
value = base.rstrip('/') + value[match.end():]
|
|
179
|
+
if not value:
|
|
180
|
+
value = '/'
|
|
181
|
+
raise ValueError('recursive process alias traversal')
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def trace_verdict(trace, declared, root, runtime_files):
|
|
185
|
+
if not trace.exists() or trace.stat().st_size == 0:
|
|
186
|
+
return False, ['missing read trace']
|
|
187
|
+
violations, pending, events = [], {}, []
|
|
188
|
+
written, cwds = set(), {}
|
|
189
|
+
# Keep syscall entry order: a child can execute before clone's resumed line.
|
|
190
|
+
for line in trace.read_text(errors='surrogateescape').splitlines():
|
|
191
|
+
pid = line.split(maxsplit=1)[0] if line.strip() else ''
|
|
192
|
+
if '<unfinished ...>' in line:
|
|
193
|
+
if pid in pending:
|
|
194
|
+
violations.append('overlapping file syscall')
|
|
195
|
+
pending[pid] = (len(events), line.split('<unfinished ...>', 1)[0])
|
|
196
|
+
events.append(None)
|
|
197
|
+
continue
|
|
198
|
+
resumed = re.search(r'<\.\.\. \w+ resumed>', line)
|
|
199
|
+
if resumed:
|
|
200
|
+
prior = pending.pop(pid, None)
|
|
201
|
+
if prior is None:
|
|
202
|
+
violations.append('unmatched file syscall')
|
|
203
|
+
continue
|
|
204
|
+
index, prefix = prior
|
|
205
|
+
events[index] = (pid, prefix + line[resumed.end():])
|
|
206
|
+
else:
|
|
207
|
+
events.append((pid, line))
|
|
208
|
+
if pending:
|
|
209
|
+
violations.append('unfinished file syscall')
|
|
210
|
+
for event in events:
|
|
211
|
+
if event is None:
|
|
212
|
+
continue
|
|
213
|
+
pid, line = event
|
|
214
|
+
call = re.search(r'\b(\w+)\((.*)\)\s+=\s+(-?\d+)', line)
|
|
215
|
+
if not call:
|
|
216
|
+
continue
|
|
217
|
+
syscall, args, result = call[1], call[2], int(call[3])
|
|
218
|
+
if not cwds:
|
|
219
|
+
cwds[pid] = [str(root)]
|
|
220
|
+
state = cwds.setdefault(pid, [None])
|
|
221
|
+
if syscall in ('clone', 'clone3', 'fork', 'vfork') and result > 0:
|
|
222
|
+
host_pid = re.search(r"=\s+\d+ /\* (\d+) in strace's PID NS \*/", line)
|
|
223
|
+
child_pid = host_pid[1] if host_pid else str(result)
|
|
224
|
+
cwds[child_pid] = state if 'CLONE_FS' in args else state.copy()
|
|
225
|
+
continue
|
|
226
|
+
attempted = re.search(r'"((?:[^"\\]|\\.)*)"(\.\.\.)?', args)
|
|
227
|
+
name = None
|
|
228
|
+
raw_name = None
|
|
229
|
+
if attempted:
|
|
230
|
+
try:
|
|
231
|
+
if attempted[2]:
|
|
232
|
+
raise ValueError('truncated path')
|
|
233
|
+
name = decode_trace_string(attempted[1])
|
|
234
|
+
if not name.startswith('/'):
|
|
235
|
+
# *at calls supply a directory fd; ordinary access/execve/
|
|
236
|
+
# stat/open use the process cwd inherited at fork/clone.
|
|
237
|
+
directory = re.match(r'(?:AT_FDCWD|\d+)<([^<>]+)>\s*,', args)
|
|
238
|
+
if not directory and re.match(r'-?\d+(?:<[^>]*>)?\s*,', args):
|
|
239
|
+
raise ValueError('unresolved directory fd')
|
|
240
|
+
base = decode_trace_string(directory[1]) if directory else state[0]
|
|
241
|
+
if base is None:
|
|
242
|
+
raise ValueError('unknown cwd')
|
|
243
|
+
name = posixpath.join(base, name)
|
|
244
|
+
raw_name = name
|
|
245
|
+
name = '/' + posixpath.normpath(name).lstrip('/')
|
|
246
|
+
except (ValueError, UnicodeError):
|
|
247
|
+
if result < 0 or syscall == 'chdir':
|
|
248
|
+
violations.append('undecodable or unresolved file path')
|
|
249
|
+
name = None
|
|
250
|
+
if syscall == 'chdir' and result == 0:
|
|
251
|
+
state[0] = name
|
|
252
|
+
if syscall == 'fchdir' and result == 0:
|
|
253
|
+
directory = re.match(r'\d+<([^<>]+)>$', args)
|
|
254
|
+
try:
|
|
255
|
+
state[0] = decode_trace_string(directory[1]) if directory else None
|
|
256
|
+
except ValueError:
|
|
257
|
+
state[0] = None
|
|
258
|
+
if state[0] is None:
|
|
259
|
+
violations.append('unresolved fchdir')
|
|
260
|
+
if result < 0:
|
|
261
|
+
if raw_name:
|
|
262
|
+
try:
|
|
263
|
+
raw_name = resolve_failed_process_alias(raw_name, state[0])
|
|
264
|
+
name = '/' + posixpath.normpath(raw_name).lstrip('/')
|
|
265
|
+
except ValueError as exc:
|
|
266
|
+
violations.append(str(exc))
|
|
267
|
+
continue
|
|
268
|
+
if name and name.startswith('/work/'):
|
|
269
|
+
relative = name[6:]
|
|
270
|
+
try:
|
|
271
|
+
available = available_project_attempt(raw_name, root, runtime_files)
|
|
272
|
+
if relative not in declared and available:
|
|
273
|
+
violations.append('undeclared available project input: ' + relative)
|
|
274
|
+
except ValueError as exc:
|
|
275
|
+
violations.append(str(exc))
|
|
276
|
+
continue
|
|
277
|
+
if syscall not in ('open', 'openat', 'openat2'):
|
|
278
|
+
continue
|
|
279
|
+
match = OPEN.search(line)
|
|
280
|
+
if not match:
|
|
281
|
+
violations.append('undecodable successful open')
|
|
282
|
+
continue
|
|
283
|
+
try:
|
|
284
|
+
name = decode_trace_string(match[1])
|
|
285
|
+
except ValueError:
|
|
286
|
+
violations.append('undecodable successful open path')
|
|
287
|
+
continue
|
|
288
|
+
if name.startswith('/work/'):
|
|
289
|
+
relative = name[6:]
|
|
290
|
+
# Snapshot ancestor directories contain only declared descendants.
|
|
291
|
+
if relative in declared or relative in written or any(
|
|
292
|
+
item.startswith(relative + '/') for item in declared):
|
|
293
|
+
continue
|
|
294
|
+
if any(flag in line for flag in ('O_WRONLY', 'O_RDWR', 'O_CREAT')):
|
|
295
|
+
written.add(relative)
|
|
296
|
+
else:
|
|
297
|
+
violations.append('undeclared project read: ' + relative)
|
|
298
|
+
elif name.startswith(('/home/', '/opt/', '/root/')) and name not in runtime_files:
|
|
299
|
+
violations.append('undeclared home read: ' + name)
|
|
300
|
+
return not violations, violations[:30]
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def main():
|
|
304
|
+
parser = argparse.ArgumentParser()
|
|
305
|
+
parser.add_argument("--root", required=True)
|
|
306
|
+
parser.add_argument("--inputs-json", required=True)
|
|
307
|
+
parser.add_argument("--command", required=True)
|
|
308
|
+
parser.add_argument("--runtime-files-json", default="[]")
|
|
309
|
+
parser.add_argument("--evidence", required=True)
|
|
310
|
+
parser.add_argument("--timeout", type=int, default=300)
|
|
311
|
+
args = parser.parse_args()
|
|
312
|
+
root = Path(args.root).resolve(strict=True)
|
|
313
|
+
evidence = Path(args.evidence).resolve()
|
|
314
|
+
if evidence.exists():
|
|
315
|
+
raise ValueError("evidence directory already exists")
|
|
316
|
+
evidence.mkdir(parents=True)
|
|
317
|
+
record = {"version": 1, "status": "failed_or_unknown", "command": args.command,
|
|
318
|
+
"exit_code": None, "read_trace_verified": False, "snapshot_unchanged": False,
|
|
319
|
+
"source_unchanged": False, "process_group_gone": False}
|
|
320
|
+
try:
|
|
321
|
+
if not root.is_dir() or evidence == root or root in evidence.parents:
|
|
322
|
+
raise ValueError("evidence must be outside project root")
|
|
323
|
+
names = json.loads(args.inputs_json)
|
|
324
|
+
runtime_names = json.loads(args.runtime_files_json)
|
|
325
|
+
if not isinstance(runtime_names, list) or any(not isinstance(name, str) or not name.startswith("/") for name in runtime_names):
|
|
326
|
+
raise ValueError("runtime files must be absolute paths")
|
|
327
|
+
runtime_files = {}
|
|
328
|
+
for name in runtime_names:
|
|
329
|
+
candidate = Path(name)
|
|
330
|
+
if (not name.startswith(("/home/", "/opt/")) or ".." in candidate.parts or
|
|
331
|
+
candidate.resolve() != candidate or not candidate.is_file() or
|
|
332
|
+
root == candidate or root in candidate.parents or evidence == candidate or evidence in candidate.parents):
|
|
333
|
+
raise ValueError("unsafe runtime file: " + name)
|
|
334
|
+
runtime_files[name] = sha(candidate)
|
|
335
|
+
record["runtime_files"] = runtime_files
|
|
336
|
+
before = inventory(root, names)
|
|
337
|
+
if not before:
|
|
338
|
+
raise ValueError("empty frozen input")
|
|
339
|
+
digest = hashlib.sha256(json.dumps(before, sort_keys=True).encode()).hexdigest()
|
|
340
|
+
record["input_digest"] = digest
|
|
341
|
+
tools = {}
|
|
342
|
+
for name in ("bwrap", "strace"):
|
|
343
|
+
binary = shutil.which(name)
|
|
344
|
+
if not binary:
|
|
345
|
+
raise FileNotFoundError(name + " required")
|
|
346
|
+
tools[name] = {"path": str(Path(binary).resolve(strict=True)), "sha256": sha(Path(binary).resolve(strict=True))}
|
|
347
|
+
record["host_tools"] = tools
|
|
348
|
+
snapshot = evidence / "snapshot"
|
|
349
|
+
snapshot.mkdir()
|
|
350
|
+
for name in before:
|
|
351
|
+
dest = snapshot / name
|
|
352
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
353
|
+
shutil.copyfile(root / name, dest, follow_symlinks=False)
|
|
354
|
+
os.chmod(dest, before[name]["mode"])
|
|
355
|
+
if inventory(snapshot, names) != before or inventory(root, names) != before:
|
|
356
|
+
raise ValueError("inputs changed during freeze")
|
|
357
|
+
record["snapshot_unchanged"] = True
|
|
358
|
+
trace = evidence / "trace.log"
|
|
359
|
+
output = evidence / "output"
|
|
360
|
+
output.mkdir()
|
|
361
|
+
sandbox = [tools["bwrap"]["path"], "--die-with-parent", "--unshare-user", "--unshare-net",
|
|
362
|
+
"--unshare-pid", "--unshare-ipc", "--unshare-uts",
|
|
363
|
+
"--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp",
|
|
364
|
+
"--ro-bind", str(snapshot), "/work", "--bind", str(output), "/out",
|
|
365
|
+
"--dir", "/home", "--setenv", "HOME", "/tmp", "--chdir", "/work"]
|
|
366
|
+
for system in ("/usr", "/bin", "/lib", "/lib64", "/etc"):
|
|
367
|
+
if Path(system).exists():
|
|
368
|
+
sandbox += ["--ro-bind", system, system]
|
|
369
|
+
if any(name.startswith("/opt/") for name in runtime_files):
|
|
370
|
+
sandbox += ["--dir", "/opt"]
|
|
371
|
+
for name in runtime_files:
|
|
372
|
+
for parent in reversed(Path(name).parents):
|
|
373
|
+
if str(parent) not in ("/", "/home", "/opt", "/usr", "/bin", "/lib", "/lib64", "/etc"):
|
|
374
|
+
sandbox += ["--dir", str(parent)]
|
|
375
|
+
sandbox += ["--ro-bind", name, name]
|
|
376
|
+
sandbox += ["--", "/bin/sh", "-c", args.command]
|
|
377
|
+
invocation = [tools["strace"]["path"], "-f", "-yy", "--decode-pids=pidns", "-e", "trace=%file,%process,fchdir", "-s", "65535", "-o", str(trace), *sandbox]
|
|
378
|
+
with (evidence / "stdout.log").open("wb") as stdout, (evidence / "stderr.log").open("wb") as stderr:
|
|
379
|
+
child = subprocess.Popen(invocation, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr,
|
|
380
|
+
start_new_session=True, cwd=root, env={"PATH": "/usr/bin:/bin", "HOME": "/tmp", "LANG": "C.UTF-8"})
|
|
381
|
+
try:
|
|
382
|
+
record["exit_code"] = child.wait(timeout=args.timeout)
|
|
383
|
+
except subprocess.TimeoutExpired:
|
|
384
|
+
record["timed_out"] = True
|
|
385
|
+
os.killpg(child.pid, signal.SIGTERM)
|
|
386
|
+
try:
|
|
387
|
+
child.wait(timeout=5)
|
|
388
|
+
except subprocess.TimeoutExpired:
|
|
389
|
+
os.killpg(child.pid, signal.SIGKILL)
|
|
390
|
+
child.wait()
|
|
391
|
+
for _ in range(20):
|
|
392
|
+
if not living_process_group(child.pid):
|
|
393
|
+
record["process_group_gone"] = True
|
|
394
|
+
break
|
|
395
|
+
time.sleep(0.05)
|
|
396
|
+
if not record["process_group_gone"]:
|
|
397
|
+
try:
|
|
398
|
+
os.killpg(child.pid, signal.SIGKILL)
|
|
399
|
+
except ProcessLookupError:
|
|
400
|
+
record["process_group_gone"] = True
|
|
401
|
+
record["read_trace_verified"], record["read_violations"] = trace_verdict(trace, before, root, runtime_files)
|
|
402
|
+
record["snapshot_unchanged"] = inventory(snapshot, names) == before
|
|
403
|
+
record["source_unchanged"] = inventory(root, names) == before
|
|
404
|
+
record["host_tools_unchanged"] = all(sha(Path(item["path"])) == item["sha256"] for item in tools.values())
|
|
405
|
+
record["runtime_files_unchanged"] = all(sha(Path(name)) == digest for name, digest in runtime_files.items())
|
|
406
|
+
record["status"] = "passed" if (record["exit_code"] == 0 and record["read_trace_verified"]
|
|
407
|
+
and record["snapshot_unchanged"] and record["source_unchanged"]
|
|
408
|
+
and record["host_tools_unchanged"] and record["runtime_files_unchanged"]
|
|
409
|
+
and record["process_group_gone"]) else "failed_or_unknown"
|
|
410
|
+
except Exception as exc:
|
|
411
|
+
record["error"] = str(exc)
|
|
412
|
+
(evidence / "terminal.json").write_text(json.dumps(record, indent=2, sort_keys=True) + "\n")
|
|
413
|
+
print(json.dumps({"status": record["status"], "evidence": str(evidence), "input_digest": record.get("input_digest")}))
|
|
414
|
+
return 0 if record["status"] == "passed" else 1
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
if __name__ == "__main__":
|
|
418
|
+
raise SystemExit(main())
|
|
@@ -61,6 +61,41 @@ assert.equal(status.waiting, 0, 'B-01 waiting gate must disappear after B-01 lea
|
|
|
61
61
|
assert.equal(status.canceled, 1);
|
|
62
62
|
assert.equal(JSON.parse(await readFile(gateFile, 'utf8')).status, 'canceled');
|
|
63
63
|
|
|
64
|
+
// A task-scoped human gate has no project id by design. Project reconciliation
|
|
65
|
+
// must not reinterpret that absence as project_not_found and cancel the task.
|
|
66
|
+
const taskScoped = await enqueueTask(root, {
|
|
67
|
+
queue,
|
|
68
|
+
title: 'Task-scoped external precondition',
|
|
69
|
+
task: 'Wait for a task-local external precondition',
|
|
70
|
+
sourceChannel: 'test',
|
|
71
|
+
sourceTarget: 'owner',
|
|
72
|
+
sourceAccount: 'main'
|
|
73
|
+
});
|
|
74
|
+
const taskScopedDir = path.join(taskRuntimeDirFor(root, queue, taskScoped.task.id), 'checkpoints');
|
|
75
|
+
await mkdir(taskScopedDir, { recursive: true });
|
|
76
|
+
await writeFile(path.join(taskScopedDir, 'cp1.json'), `${JSON.stringify({
|
|
77
|
+
version: 1,
|
|
78
|
+
task_id: taskScoped.task.id,
|
|
79
|
+
checkpoint_id: 'cp1',
|
|
80
|
+
status: 'blocked',
|
|
81
|
+
blockers: [{
|
|
82
|
+
action: 'Wait for task-local connectivity.',
|
|
83
|
+
required_authority: 'Owner confirms the external precondition is restored.',
|
|
84
|
+
authorization_state: 'missing',
|
|
85
|
+
needed_when: 'now',
|
|
86
|
+
materialize: true
|
|
87
|
+
}]
|
|
88
|
+
}, null, 2)}\n`);
|
|
89
|
+
const taskScopedNotice = await notifyHumanInputRequests(root, { queue, notifyCommand: '/bin/true' });
|
|
90
|
+
const taskScopedResult = taskScopedNotice.results.find((item) => item.taskId === taskScoped.task.id);
|
|
91
|
+
assert.equal(taskScopedResult.outcome, 'sent');
|
|
92
|
+
const taskScopedGateFile = path.join(root, taskScopedResult.ledger);
|
|
93
|
+
assert.equal(JSON.parse(await readFile(taskScopedGateFile, 'utf8')).project_id, null);
|
|
94
|
+
await reconcileProjectGates(root, { queue });
|
|
95
|
+
assert.equal(JSON.parse(await readFile(taskScopedGateFile, 'utf8')).status, 'waiting_for_human');
|
|
96
|
+
assert.equal((await queueStatus(root, queue)).waiting, 1, 'task-scoped gate must remain waiting');
|
|
97
|
+
await resolveHumanInput(root, { queue, gateId: `${taskScoped.task.id}:cp1`, input: 'task-local precondition restored' });
|
|
98
|
+
|
|
64
99
|
const other = await enqueueTask(root, { queue, title: 'Other project task', task: 'Project other', projectId: 'other' });
|
|
65
100
|
const openreel = await enqueueTask(root, { queue, title: 'OpenReel target', task: 'Project openreel', projectId: 'openreel' });
|
|
66
101
|
await rename(path.join(root, other.file), path.join(root, 'runtime', 'loops', queue, 'active', path.basename(other.file)));
|
|
@@ -399,4 +434,4 @@ assert.equal(unboundResult.outcome, 'fail_closed');
|
|
|
399
434
|
assert.equal(unboundResult.message, undefined);
|
|
400
435
|
assert.equal((await queueStatus(root, queue)).waiting, 0);
|
|
401
436
|
|
|
402
|
-
console.log(JSON.stringify({ status: 'ok', assertions: ['standing project authorization reaches task contract', 'structured gate context', 'B-01 waiting to zero', 'project-isolated supersede', 'doctor strong validation', 'authoritative ledger drift', 'ready milestone deferred gate', 'future gate does not stop safe actionable backlog', 'conditional policy prose does not create a gate', 'authorized and consumed authority do not create gates', 'checkpoint-bound subproject backlog remains actionable', 'missing current authority creates a gate', 'standing-authorized production blocker does not create a gate', 'missing publication blocker creates a gate', 'accepted project optional deferred gate stays out of queue', 'unbound gate fails closed without actionable text'] }));
|
|
437
|
+
console.log(JSON.stringify({ status: 'ok', assertions: ['standing project authorization reaches task contract', 'structured gate context', 'B-01 waiting to zero', 'task-scoped gate survives project reconciliation', 'project-isolated supersede', 'doctor strong validation', 'authoritative ledger drift', 'ready milestone deferred gate', 'future gate does not stop safe actionable backlog', 'conditional policy prose does not create a gate', 'authorized and consumed authority do not create gates', 'checkpoint-bound subproject backlog remains actionable', 'missing current authority creates a gate', 'standing-authorized production blocker does not create a gate', 'missing publication blocker creates a gate', 'accepted project optional deferred gate stays out of queue', 'unbound gate fails closed without actionable text'] }));
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { writeAcceptanceReviews, buildFinalJudgement, enqueueTask, runQueueOnce } from '../lib/core.mjs';
|
|
7
|
+
|
|
8
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-revision-coverage-'));
|
|
9
|
+
const contract = { task_id: 'coverage-task', task_scope: 'project', requires_human_gate: false };
|
|
10
|
+
const plan = { checkpoints: [{ id: 'stable' }] };
|
|
11
|
+
const acceptance = { functional_checks: [], regression_checks: [], negative_tests: [], edge_cases: [], manual_review: [], automation: [], rubric: [] };
|
|
12
|
+
const phase = id => ({ task_id: contract.task_id, checkpoint_id: id, milestone_id: 'stable', status: 'in_progress', summary: 'Phase completed; integration pending', verification: ['phase test passed'], risks: ['integration pending'], blockers: [], project_completion: { status: 'in_progress' } });
|
|
13
|
+
const history = [phase('p1'), phase('p2'), phase('p3')];
|
|
14
|
+
const bytes = cp => JSON.stringify(cp);
|
|
15
|
+
const digest = cp => createHash('sha256').update(bytes(cp)).digest('hex');
|
|
16
|
+
const final = () => ({ ...phase('done'), sequence: 4, status: 'ready_for_acceptance', summary: 'Integration completed', risks: [], verification: ['integration test passed'], project_completion: { status: 'accepted' }, revises_checkpoint_id: 'p3', revision_coverage: history.map(cp => ({ checkpoint_id: cp.checkpoint_id, checkpoint_sha256: digest(cp), resolution: 'Integrated and verified this phase', verification: ['integration test passed'] })) });
|
|
17
|
+
let cases = 0;
|
|
18
|
+
try {
|
|
19
|
+
async function judge(name, records) {
|
|
20
|
+
const dir = path.join(root, name);
|
|
21
|
+
await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
|
|
22
|
+
await mkdir(path.join(dir, 'reviews'));
|
|
23
|
+
for (const [i, cp] of records.entries()) await writeFile(path.join(dir, 'checkpoints', `${i}.json`), typeof cp === 'string' ? cp : bytes(cp));
|
|
24
|
+
const reviews = await writeAcceptanceReviews(dir, 'disposable', { id: contract.task_id }, { contract }, { plan: acceptance }, { plan, checkpointsDir: 'checkpoints', reviewsDir: 'reviews' }, { persist: false });
|
|
25
|
+
cases++;
|
|
26
|
+
return buildFinalJudgement(contract, acceptance, plan, { count: records.length }, reviews, { dispatchStatus: 'completed' });
|
|
27
|
+
}
|
|
28
|
+
assert.equal((await judge('complete', [...history, final()])).outcome, 'ready_to_apply');
|
|
29
|
+
assert.equal((await judge('reverse-order', [final(), ...history.toReversed()])).outcome, 'ready_to_apply');
|
|
30
|
+
for (const [name, mutate] of [
|
|
31
|
+
['no-coverage', cp => { delete cp.revision_coverage; }],
|
|
32
|
+
['partial', cp => { cp.revision_coverage.pop(); }],
|
|
33
|
+
['stale-digest', cp => { cp.revision_coverage[0].checkpoint_sha256 = 'old'; }],
|
|
34
|
+
['unknown-target', cp => { cp.revision_coverage[0].checkpoint_id = 'missing'; }],
|
|
35
|
+
['no-resolution', cp => { cp.revision_coverage[0].resolution = ''; }],
|
|
36
|
+
['no-evidence', cp => { cp.revision_coverage[0].verification = []; }],
|
|
37
|
+
['unbound-evidence', cp => { cp.revision_coverage[0].verification = ['invented verification']; }],
|
|
38
|
+
['rename', cp => { cp.milestone_id = 'renamed'; }],
|
|
39
|
+
['different-task', cp => { cp.task_id = 'other'; }],
|
|
40
|
+
['duplicate-coverage', cp => { cp.revision_coverage.push(cp.revision_coverage[0]); }],
|
|
41
|
+
['malformed-coverage', cp => { cp.revision_coverage = {}; }]
|
|
42
|
+
]) {
|
|
43
|
+
const cp = final(); mutate(cp);
|
|
44
|
+
assert.equal((await judge(name, [...history, cp])).outcome, 'needs_revision', name);
|
|
45
|
+
}
|
|
46
|
+
for (const [name, patch, expected] of [
|
|
47
|
+
['real-defect', { status: 'needs_revision' }, 'needs_revision'],
|
|
48
|
+
['invalid-phase-coverage', { revision_coverage: [{ checkpoint_id: 'missing' }] }, 'needs_revision'],
|
|
49
|
+
['missing-verification', { verification: [] }, 'needs_revision'],
|
|
50
|
+
['missing-summary', { summary: '' }, 'needs_revision'],
|
|
51
|
+
['different-milestone', { milestone_id: 'other' }, 'needs_revision'],
|
|
52
|
+
['human-gate', { status: 'needs_human_input', blockers: ['Owner approval required'] }, 'blocked'],
|
|
53
|
+
['reversed-clock', { sequence: 5 }, 'needs_revision']
|
|
54
|
+
]) {
|
|
55
|
+
const records = structuredClone(history); Object.assign(records[0], patch);
|
|
56
|
+
const cp = final(); cp.revision_coverage[0].checkpoint_sha256 = digest(records[0]);
|
|
57
|
+
assert.equal((await judge(name, [...records, cp])).outcome, expected, name);
|
|
58
|
+
}
|
|
59
|
+
assert.equal((await judge('corruption', [...history, '{', final()])).outcome, 'needs_revision');
|
|
60
|
+
assert.equal((await judge('duplicate-id', [...history, history[0], final()])).outcome, 'needs_revision');
|
|
61
|
+
// Ordered unrelated failure must survive even without the coverage protocol.
|
|
62
|
+
const unrelated = { ...phase('unrelated'), milestone_id: 'other', sequence: 1, status: 'needs_revision' };
|
|
63
|
+
const done = final(); delete done.revision_coverage;
|
|
64
|
+
assert.equal((await judge('ordered-cross-scope', [unrelated, done])).outcome, 'needs_revision');
|
|
65
|
+
const renamed = { ...done, milestone_id: 'renamed' };
|
|
66
|
+
assert.equal((await judge('renamed-terminal', [renamed])).outcome, 'needs_revision');
|
|
67
|
+
// Invalid coverage must not silently use clocks instead.
|
|
68
|
+
const ordered = history.map((cp, i) => ({ ...cp, sequence: i + 1 }));
|
|
69
|
+
assert.equal((await judge('invalid-coverage-with-clocks', [...ordered, final()])).outcome, 'needs_revision');
|
|
70
|
+
console.log(`revision coverage self-test passed (${cases} cases)`);
|
|
71
|
+
} finally {
|
|
72
|
+
await rm(root, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
// Exercise the same protocol through dispatch, final judgement and queue state.
|
|
77
|
+
for (const scenario of ['covered', 'uncovered', 'cross-scope', 'invalid-phase-coverage', 'blocked']) {
|
|
78
|
+
const queueRoot = await mkdtemp(path.join(tmpdir(), 'loop-coverage-queue-'));
|
|
79
|
+
try {
|
|
80
|
+
const { task } = await enqueueTask(queueRoot, { queue: 'probe', title: scenario, task: '开发完整项目并完成整体目标' });
|
|
81
|
+
const dir = path.join(queueRoot, 'runtime/loops/probe/tasks', task.id);
|
|
82
|
+
await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
|
|
83
|
+
const records = history.map(cp => ({ ...cp, task_id: task.id }));
|
|
84
|
+
if (scenario === 'cross-scope') records[0].milestone_id = 'unrelated';
|
|
85
|
+
if (scenario === 'invalid-phase-coverage') records[0].revision_coverage = [{ checkpoint_id: 'missing' }];
|
|
86
|
+
if (scenario === 'blocked') Object.assign(records[0], { status: 'needs_human_input', blockers: ['Owner approval required'] });
|
|
87
|
+
for (const cp of records) await writeFile(path.join(dir, 'checkpoints', cp.checkpoint_id + '.json'), bytes(cp));
|
|
88
|
+
await writeFile(path.join(dir, 'dev_plan.json'), bytes({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', ...plan }));
|
|
89
|
+
await writeFile(path.join(dir, 'acceptance_plan.json'), bytes({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', ...acceptance }));
|
|
90
|
+
const cp = { ...final(), task_id: task.id };
|
|
91
|
+
cp.revision_coverage.forEach((entry, i) => { entry.checkpoint_sha256 = digest(records[i]); });
|
|
92
|
+
if (scenario === 'uncovered') delete cp.revision_coverage;
|
|
93
|
+
const worker = path.join(queueRoot, 'worker.mjs');
|
|
94
|
+
await writeFile(worker, `import {writeFile} from 'node:fs/promises'; import path from 'node:path'; await writeFile(path.join(process.env.LOOP_CHECKPOINTS_DIR, 'done.json'), ${JSON.stringify(bytes(cp))});`);
|
|
95
|
+
const options = { queue: 'probe', dispatcher: `${process.execPath} '${worker}'`, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
96
|
+
const result = await runQueueOnce(queueRoot, options);
|
|
97
|
+
const effectiveContract = JSON.parse(await readFile(path.join(dir, 'task_contract.json'), 'utf8'));
|
|
98
|
+
const expected = scenario === 'covered' ? (effectiveContract.requires_human_gate ? 'ready_for_human_review' : 'ready_to_apply') : scenario === 'blocked' ? 'blocked' : 'needs_revision';
|
|
99
|
+
assert.equal(result.run.finalJudgement.outcome, expected, scenario);
|
|
100
|
+
assert.equal((await runQueueOnce(queueRoot, options)).processed, false, 'terminal or revision queue must not replay');
|
|
101
|
+
console.log(JSON.stringify({ test: 'revision-coverage-queue', scenario, outcome: expected, node: process.version, replay: false }));
|
|
102
|
+
} finally {
|
|
103
|
+
await rm(queueRoot, { recursive: true, force: true });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -52,6 +52,10 @@ node bin/loop-engineering.mjs --help
|
|
|
52
52
|
|
|
53
53
|
Do not guess a workspace source path. Use `node packages/loop-engineering/bin/loop-engineering.mjs ...` only after confirming that exact path exists in the current workspace.
|
|
54
54
|
|
|
55
|
+
### Verify the effective implementation
|
|
56
|
+
|
|
57
|
+
A skill update does not upgrade the CLI or generated integration. Before relying on scope inference, task-gate reconciliation or isolated verification, inspect the installed package and wrapper imports against the exact implementation that provides the feature. A candidate may share a version label with an older published package. Keep PR source, merged source, published packages, installed CLI and live integration as separate states; do not infer deployment from a green CI run.
|
|
58
|
+
|
|
55
59
|
### OpenClaw Integration
|
|
56
60
|
|
|
57
61
|
Installing the npm package exposes the CLI, but it does not automatically route conversations, select a worker agent, or create queue wrappers. First generate a read-only installation plan:
|
|
@@ -166,7 +170,7 @@ For OpenClaw workers, follow `references/context-budget.md` before long-running
|
|
|
166
170
|
|
|
167
171
|
## Task vs Project Classification
|
|
168
172
|
|
|
169
|
-
Classify scope before enqueueing.
|
|
173
|
+
Classify scope before enqueueing. For scope inference, task-level gate reconciliation and effective acceptance reviews, follow [scope and task acceptance](references/scope-task-acceptance.md). Verify the generated contract against the original request; inference is heuristic, not authority.
|
|
170
174
|
|
|
171
175
|
### Scoped task
|
|
172
176
|
|
|
@@ -185,6 +189,8 @@ For a project-level objective:
|
|
|
185
189
|
5. Continue through implementation, verification, revisions, and the next actionable backlog item within the authorized safety boundary.
|
|
186
190
|
6. Stop only when total project acceptance passes, or a genuine human authorization/product decision/external-state blocker prevents meaningful progress.
|
|
187
191
|
|
|
192
|
+
For project continuations (explicit or inferred scope), preserve worker-authored plans and reread durable plans after dispatch. Progress means a committed milestone newly passes acceptance, including repairing an existing failed milestone; extra checkpoint files or re-emitting accepted milestones do not count. Accepted progress must match durable checkpoint/milestone identity even for a single planned milestone; changing only the plan ID cannot transfer old acceptance to new work. A no-progress continuation stops for revision instead of requeueing. Acceptance refresh re-evaluates changed plans and rebuilds legacy judgements missing coverage once.
|
|
193
|
+
|
|
188
194
|
Never silently narrow a complete-project request into “first milestone” and call that the Loop complete. A single queue task or milestone may be complete while the project remains active.
|
|
189
195
|
|
|
190
196
|
Recommended commands:
|
|
@@ -301,6 +307,10 @@ Default revision policy may stop after three rounds, two repeated goal signature
|
|
|
301
307
|
|
|
302
308
|
For L2 code-changing tasks, prefer isolated worktrees. The runner prepares reviewable local changes and verification evidence; it does not implicitly commit, push, publish, deploy, merge, or delete branches.
|
|
303
309
|
|
|
310
|
+
Before enabling or diagnosing this backend, follow [frozen-input verification](references/frozen-input-verification.md) for prerequisites, receipt checks and compatibility boundaries.
|
|
311
|
+
|
|
312
|
+
For Linux code queues whose verification must not read the shared project tree, use the opt-in `worktree.isolatedVerification` backend described in [isolated verification](../../docs/isolated-verification.md). Declare the exact project inputs and any user-local runtime files before running the gate. Frozen project files preserve permission bits, which are included in input identity; mode-only changes invalidate stability. Failed undeclared file accesses remain failures from nested working directories even if the command swallows the error. Treat missing/failed receipts, undeclared reads, changed input digests between commands, or unsupported host isolation as `verify_failed`; a zero command exit alone is not acceptance evidence. This generic backend does not cover browser profiles, Docker/Git replay, networked checks, or undeclared dynamic dependencies. Keep those on a separately reviewed project-specific gate until explicitly enrolled and proven; do not silently fall back to ordinary `verifyCommands`.
|
|
313
|
+
|
|
304
314
|
Safe review flow:
|
|
305
315
|
|
|
306
316
|
```bash
|
|
@@ -365,3 +375,18 @@ Before saying a loop is finished, verify:
|
|
|
365
375
|
- Are evidence paths and next actions included?
|
|
366
376
|
|
|
367
377
|
If any project requirement remains, report a phase/task result and continue with the next authorized item; do not claim the project or Loop is complete.
|
|
378
|
+
|
|
379
|
+
### Invalid checkpoint baseline repair
|
|
380
|
+
|
|
381
|
+
Pre-dispatch review treats malformed JSON and non-object checkpoint roots as explicit invalid evidence, not empty accepted coverage. A bounded worker may repair the local record, but an unknown dispatch baseline is persisted as `invalid_checkpoint_baseline` and prevents automatic acceptance/continuation, including after acceptance refresh. Repair success is not proof of new milestone progress: use an explicit revision from validated history. Unrepaired invalid evidence cannot be superseded by a terminal snapshot. Human blockers take precedence; gate reconciliation leaves all gates unchanged while any checkpoint is invalid. Filesystem/permission failures are not classified as repairable JSON corruption. This conservative path may require an additional explicit revision even after a successful repair; it must not replay automatically.
|
|
382
|
+
|
|
383
|
+
### Normal context handoff versus runtime recovery
|
|
384
|
+
|
|
385
|
+
A valid successful handoff with nonempty, previously unseen checkpoint verification rotates the session without consuming or resetting runtimeRecoveryCount. Repeated verification (even with renamed checkpoints/new run IDs), empty verification and invalid handoffs stop; unresolved authority or external outcomes remain human blockers. Exception recovery remains capped independently. Verification fingerprints are cooperative progress evidence, not independent semantic proof: final task acceptance is still required. Keep checkpoint verification concrete and tied to the completed unit. When hotfixing an installed runner under explicit authority, stage/test the narrow patch separately, back up originals, and note existing processes retain already imported modules.
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
### Explicit closure of unordered phase checkpoints
|
|
389
|
+
|
|
390
|
+
New checkpoints must carry stable `task_id`/`milestone_id`, a monotonic `sequence` and checkpoint-owned `created_at`; do not invent clocks for historical records. `revises_checkpoint_id` is lineage only, not proof that every older snapshot is resolved. A final accepted checkpoint can close unordered, status-only `in_progress` records with `revision_coverage`: one entry per old record containing `checkpoint_id`, SHA-256 of the exact checkpoint bytes in `checkpoint_sha256`, a concrete `resolution`, and nonempty `verification` strings also present in the final checkpoint's verification array. Same-task and same-planned-milestone identity must match. Preserve historical files.
|
|
391
|
+
|
|
392
|
+
Coverage cannot close real failed checks, missing evidence, corruption, duplicate identities, human blockers or deferred gates. A phase that itself declares revision coverage is not a plain status-only target: its invalid declaration cannot be laundered away by a later coverage edge. Invalid coverage remains a revision failure even if clocks otherwise order the records. Uncovered unordered history remains effective. Different explicit milestone identities never supersede each other by time alone; legacy unlabelled single-plan chronology remains supported. Evidence references are cooperative claims, not independent proof of test execution: review the actual artifacts before emitting final coverage.
|