taskforce-loop-engineering 0.16.2 → 0.16.3
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 +8 -0
- package/README.md +4 -0
- package/docs/isolated-verification.md +81 -0
- package/lib/core.mjs +67 -7
- package/lib/isolated-verification.mjs +47 -0
- package/package.json +5 -3
- package/scripts/final-judgement-self-test.mjs +325 -0
- 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/skills/taskforce-loop-engineering/SKILL.md +9 -1
- package/skills/taskforce-loop-engineering/references/frozen-input-verification.md +40 -0
- package/skills/taskforce-loop-engineering/references/scope-task-acceptance.md +19 -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'] }));
|
|
@@ -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
|
|
|
@@ -301,6 +305,10 @@ Default revision policy may stop after three rounds, two repeated goal signature
|
|
|
301
305
|
|
|
302
306
|
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
307
|
|
|
308
|
+
Before enabling or diagnosing this backend, follow [frozen-input verification](references/frozen-input-verification.md) for prerequisites, receipt checks and compatibility boundaries.
|
|
309
|
+
|
|
310
|
+
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`.
|
|
311
|
+
|
|
304
312
|
Safe review flow:
|
|
305
313
|
|
|
306
314
|
```bash
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Frozen-input verification
|
|
2
|
+
|
|
3
|
+
## Configure and prove prerequisites
|
|
4
|
+
|
|
5
|
+
Use this opt-in backend only on Linux with `python3`, `bwrap`, and `strace` supporting `--decode-pids=pidns`. Missing capabilities fail closed; never silently substitute ordinary verification.
|
|
6
|
+
|
|
7
|
+
Configure `worktree.isolatedVerification` beside `worktree.verifyCommands`:
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"worktree": {
|
|
12
|
+
"enabled": true,
|
|
13
|
+
"verifyCommands": ["python3 -m unittest discover -s tests"],
|
|
14
|
+
"isolatedVerification": {
|
|
15
|
+
"inputs": ["src", "tests", "pyproject.toml"],
|
|
16
|
+
"runtimeFiles": []
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Declare exact project files or recursive directories. Missing inputs, symlinks and special files fail closed; exclude generated outputs. Required user-local runtime files must be exact regular files under `/home` or `/opt`. Do not weaken the allowlist to admit a temporary runtime under `/tmp`.
|
|
23
|
+
|
|
24
|
+
Project inputs are frozen read-only at `/work`; `/out` is persistent writable output. Network and inherited home/proxy/Node options are unavailable. Input identity covers content, size and permissions, including executable bits. Require stable source, snapshot and tool identities and the same input digest across commands.
|
|
25
|
+
|
|
26
|
+
## Inspect receipts, not only command exit
|
|
27
|
+
|
|
28
|
+
Inspect each host-owned trace and `terminal.json`, command and supervisor exits, declared reads, input stability and process-group cleanup. Missing, malformed, stale or failed receipts mean `verify_failed` even if the command swallowed an error or exited zero. A sandbox receipt, checkpoint acceptance and final task judgement are separate evidence levels.
|
|
29
|
+
|
|
30
|
+
Before making this backend mandatory, prove the project's real command and dependencies with declared-input positive controls and existing-undeclared-input negative controls. Browser profiles, directory toolchains, Docker/Git replay and networked checks need a separately reviewed project-specific gate.
|
|
31
|
+
|
|
32
|
+
## Path-audit boundaries
|
|
33
|
+
|
|
34
|
+
- Pair existing undeclared files with genuinely absent optional files. Optional absence may pass; swallowing an existing undeclared access must not. Include failed stat/access/exec prechecks, not only opens.
|
|
35
|
+
- Track nested cwd, chdir/fchdir, child inheritance and directory descriptors. PID-namespace decoding is required to associate child traces correctly. Include C-escaped non-ASCII, quotes and backslashes; unresolved or truncated paths fail closed.
|
|
36
|
+
- Preserve raw components. Missing/non-directory ancestors before `..` and trailing slashes retain traversal semantics. Repeated slashes and re-entry into `/work` must not bypass auditing.
|
|
37
|
+
- Distinguish explicit sandbox mount roots from unknown internal symlinks: a host `/bin` symlink can be a directory at its read-only mount destination. Pair missing and existing undeclared probes across these roots.
|
|
38
|
+
- Resolve proven `/proc/self/cwd`, `/proc/thread-self/cwd` and self-root aliases using traced cwd or sandbox root, retaining raw suffixes. Unknown process/fd aliases, including `/dev/fd`, and unresolved internal symlink traversal remain conservative failures; legitimate optional accesses may be rejected.
|
|
39
|
+
|
|
40
|
+
This is bounded trace auditing, not unrestricted syscall/procfs emulation. A missed attempted-access audit is not by itself proof of hidden-content exposure. Run paired controls through the real sandbox and disposable queue; record isolation and final task verdicts independently. Keep local tests, exact-HEAD remote CI and live deployment claims separate.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Scope and task acceptance
|
|
2
|
+
|
|
3
|
+
## Classify the requested outcome
|
|
4
|
+
|
|
5
|
+
Read the original request and generated `task_contract.json` before dispatch. Explicit complete-project goals and affirmative bounded work are distinct. Negation applies to its object, not every later cue: neither/nor, not-only/but-also, double negatives and unrelated “without deploying” context must not silently expand or narrow scope.
|
|
6
|
+
|
|
7
|
+
For example, “Complete the project-level objective, not just the first bounded milestone” remains a project; “Without deploying anything implement a bounded milestone for the project-level objective” remains scoped work. Verify Chinese and English affirmative/negative controls and generated contracts in disposable queues after changes. The inference is not a complete natural-language parser; correct a mismatched contract before executing it.
|
|
8
|
+
|
|
9
|
+
## Inspect effective reviews and gates
|
|
10
|
+
|
|
11
|
+
- Read checkpoint reviews, task gates and `final_judgement.json` together. Checkpoint sequence and creation time establish chronology; filename numbering and regenerated review timestamps do not. Missing or conflicting ordering must not erase a live blocker.
|
|
12
|
+
- For a task with at most one planned checkpoint, an accepted terminal task review can remain terminal despite a later project `needs_human_acceptance` snapshot only when chronology is established and that later review is independently accepted with no materializable deferred gates. Preserve blocked, revise and unordered reviews. Multiple planned milestones still require their effective reviews.
|
|
13
|
+
- A task terminal result is not project completion or deployment authorization. Inspect the original completion contract and project backlog independently.
|
|
14
|
+
- Reconcile a consumed gate only through the recorded same-task successor link, `revises_checkpoint_id`. A satisfied gate records the successor, not proof that the successor passed acceptance. Check the effective review and final queue state separately.
|
|
15
|
+
- Effective human/authority blockers and uncertain external outcomes remain `needs_human_input`, including after ordinary worker failure; do not turn them into development revisions or automatic retries. Resolved historical blockers do not permanently veto continuation.
|
|
16
|
+
|
|
17
|
+
## Evidence boundaries
|
|
18
|
+
|
|
19
|
+
Inspect artifacts rather than dispatcher exit status. A checkpoint accepted by the worker is not the outer queue's final judgement; `ready_to_apply` is not applied. For multiple PRs, test each exact candidate and a correctly constructed combined tree separately. Local tests, exact-HEAD remote CI, package installation and live-instance acceptance are distinct claims.
|