taskforce-loop-engineering 0.16.1 → 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.
@@ -0,0 +1,133 @@
1
+ """Parser and mode-identity regressions independent of sandbox availability."""
2
+ import importlib.util
3
+ from pathlib import Path
4
+ import tempfile
5
+ import sys
6
+ sys.dont_write_bytecode = True
7
+
8
+ spec = importlib.util.spec_from_file_location('isolation', Path(__file__).with_name('isolated-verify.py'))
9
+ module = importlib.util.module_from_spec(spec)
10
+ spec.loader.exec_module(module)
11
+ with tempfile.TemporaryDirectory() as tmp:
12
+ root = Path(tmp)
13
+ (root / 'sub').mkdir()
14
+ (root / 'hidden.txt').write_text('hidden')
15
+ (root / 'sub/hidden.txt').write_text('hidden')
16
+ trace = root / 'trace'
17
+ for call in [
18
+ 'openat(AT_FDCWD</work>, "hidden.txt", O_RDONLY)',
19
+ 'openat(AT_FDCWD</work/sub>, "hidden.txt", O_RDONLY)',
20
+ 'openat(AT_FDCWD</work/sub>, "../hidden.txt", O_RDONLY)',
21
+ 'openat(3</work/sub>, "hidden.txt", O_RDONLY)',
22
+ 'statx(AT_FDCWD</work/sub>, "hidden.txt", 0, STATX_ALL, 0x123)',
23
+ 'openat(AT_FDCWD</work/sub>, "hidden.txt", O_RDONLY <unfinished ...>\n1 <... openat resumed>)',
24
+ ]:
25
+ trace.write_text('1 ' + call + ' = -1 ENOENT (No such file or directory)\n')
26
+ ok, errors = module.trace_verdict(trace, {}, root, {})
27
+ assert not ok and any('undeclared available project input' in e for e in errors), (call, errors)
28
+ trace.write_text('1 openat(AT_FDCWD</work/sub>, "absent.txt", O_RDONLY) = -1 ENOENT (No such file or directory)\n')
29
+ assert module.trace_verdict(trace, {}, root, {}) == (True, [])
30
+ script = root / 'test.sh'
31
+ script.write_text('#!/bin/sh\ntrue\n')
32
+ script.chmod(0o755)
33
+ before = module.inventory(root, ['test.sh'])
34
+ script.chmod(0o644)
35
+ after = module.inventory(root, ['test.sh'])
36
+ assert before != after
37
+ assert before['test.sh']['sha256'] == after['test.sh']['sha256']
38
+ assert before['test.sh']['mode'] == 0o755
39
+ print('isolation parser and permission identity regressions passed')
40
+
41
+ # Byte escapes, malformed/truncated paths, process cwd inheritance and fchdir.
42
+ assert module.decode_trace_string(r'\344\270\255\346\226\207') == '中文'
43
+ assert module.decode_trace_string(r'a\"b\\c') == 'a"b\\c'
44
+ for value in [r'\q', r'\xZZ', r'\000', r'\777']:
45
+ try:
46
+ module.decode_trace_string(value)
47
+ raise AssertionError(value)
48
+ except ValueError:
49
+ pass
50
+ with tempfile.TemporaryDirectory() as tmp:
51
+ root = Path(tmp)
52
+ (root / 'sub').mkdir()
53
+ (root / 'sub/hidden.txt').write_text('secret')
54
+ trace = root / 'trace'
55
+ for transition in ['1 chdir("/work/sub") = 0', '1 fchdir(3</work/sub>) = 0']:
56
+ for filename, expected in [('hidden.txt', False), ('absent.txt', True)]:
57
+ trace.write_text(transition + '\n1 clone(child_stack=NULL, flags=SIGCHLD <unfinished ...>\n'
58
+ + f'2 access("{filename}", R_OK) = -1 ENOENT (missing)\n'
59
+ + '1 <... clone resumed>) = 2\n')
60
+ assert module.trace_verdict(trace, {}, root, {})[0] == expected
61
+ for path in ['"hidden"...', r'"\q"']:
62
+ trace.write_text(f'1 access({path}, R_OK) = -1 ENOENT (missing)\n')
63
+ assert not module.trace_verdict(trace, {}, root, {})[0]
64
+ print('C byte escapes, truncated paths and inherited cwd regressions passed')
65
+
66
+ with tempfile.TemporaryDirectory() as tmp:
67
+ root = Path(tmp)
68
+ (root / 'hidden.txt').write_text('secret')
69
+ trace = root / 'trace'
70
+ trace.write_text('1 chdir("/work") = 0\n'
71
+ "1 clone(child_stack=NULL, flags=SIGCHLD) = 2 /* 12345 in strace's PID NS */\n"
72
+ '12345 access("hidden.txt", R_OK) = -1 ENOENT (missing)\n')
73
+ assert not module.trace_verdict(trace, {}, root, {})[0]
74
+ trace.write_text('1 openat(4, "absent.txt", O_RDONLY) = -1 ENOENT (missing)\n')
75
+ assert not module.trace_verdict(trace, {}, root, {})[0]
76
+ print('PID namespace mapping and unknown directory fd regressions passed')
77
+
78
+ with tempfile.TemporaryDirectory() as tmp:
79
+ root = Path(tmp)
80
+ (root / 'sub').mkdir()
81
+ (root / 'hidden.txt').write_text('private')
82
+ (root / 'input.txt').write_text('declared')
83
+ trace = root / 'trace'
84
+ for name, allowed in [
85
+ ('../work/hidden.txt', False), ('/work/../work/hidden.txt', False),
86
+ ('//work/hidden.txt', False), ('///work//hidden.txt', False),
87
+ ('/work/../../work/sub/../../work/hidden.txt', False),
88
+ ('../work/missing.txt', True), ('//work/absent/../hidden.txt', True),
89
+ ('../work/input.txt/../hidden.txt', True),
90
+ ('/work/../work/hidden.txt/', True), ('/work/../work/hidden.txt/.', True),
91
+ ('/nonexistent_r4/../work/hidden.txt', True),
92
+ ('/work/../nonexistent_r4/../work/hidden.txt', True),
93
+ ('/home/../work/hidden.txt', False),
94
+ ]:
95
+ trace.write_text(f'1 openat(AT_FDCWD</work>, "{name}", O_RDONLY) = -1 ENOENT (missing)\n')
96
+ ok, errors = module.trace_verdict(trace, {'input.txt': {}}, root, {})
97
+ assert ok == allowed, (name, errors)
98
+ print('namespace re-entry, slash aliases and missing component regressions passed')
99
+
100
+ # Explicit ro-bind roots differ from internal system symlinks.
101
+ with tempfile.TemporaryDirectory() as tmp:
102
+ root = Path(tmp)
103
+ (root / 'hidden.txt').write_text('private')
104
+ for mount in ['bin', 'lib', 'lib64', 'usr', 'etc']:
105
+ if not Path('/' + mount).is_dir():
106
+ continue
107
+ assert not module.available_project_attempt('/' + mount + '/../work/missing.txt', root, {})
108
+ assert module.available_project_attempt('/' + mount + '/../work/hidden.txt', root, {})
109
+ # Use a mocked descendant type: no changes to the host system directories.
110
+ from unittest.mock import patch
111
+ original = Path.is_symlink
112
+ with patch.object(Path, 'is_symlink', lambda p: str(p) == '/usr/internal-link' or original(p)):
113
+ try:
114
+ module.available_project_attempt('/usr/internal-link/../../work/hidden.txt', root, {})
115
+ raise AssertionError('unknown internal symlink must fail closed')
116
+ except ValueError as error:
117
+ assert 'unresolved system symlink' in str(error)
118
+ print('ro-bind roots and unknown descendant symlinks passed')
119
+
120
+ with tempfile.TemporaryDirectory() as tmp:
121
+ root = Path(tmp)
122
+ (root / 'hidden.txt').write_text('hidden')
123
+ (root / 'sub').mkdir()
124
+ trace = root / 'trace'
125
+ for prefix in ['/proc/self/cwd/', '/proc/thread-self/cwd/', '/proc/self/root/work/']:
126
+ for suffix, allowed in [('hidden.txt', False), ('missing.txt', True), ('absent/../hidden.txt', True), ('hidden.txt/', True)]:
127
+ trace.write_text('1 chdir("/work") = 0\n' + f'1 access("{prefix}{suffix}", R_OK) = -1 ENOENT (missing)\n')
128
+ ok, errors = module.trace_verdict(trace, {}, root, {})
129
+ assert ok == allowed, (prefix, suffix, errors)
130
+ for name in ['/dev/fd/9/hidden.txt', '/proc/self/fd/9/hidden.txt', '/proc/9/cwd/hidden.txt']:
131
+ trace.write_text(f'1 access("{name}", R_OK) = -1 ENOENT (missing)\n')
132
+ assert not module.trace_verdict(trace, {}, root, {})[0]
133
+ print('self cwd/root aliases and unknown fd/process alias regressions passed')
@@ -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())
@@ -0,0 +1,27 @@
1
+ import assert from 'node:assert/strict';
2
+ import { diagnosticSources } from '../lib/openclaw-diagnostic-source.mjs';
3
+ const args = { root: '/tmp', openclawBin: 'profile-cli' };
4
+ const inventory = { telegram: ['personal'], feishu: { accounts: ['main', 'other'] }, slack: { accounts: ['team'] }, discord: [], signal: { accounts: ['phone'] } };
5
+ const run = async (bin, argv) => {
6
+ assert.equal(bin, 'profile-cli');
7
+ assert.deepEqual(argv, ['channels', 'list', '--json']);
8
+ return { code: 0, stdout: JSON.stringify({ chat: inventory }) };
9
+ };
10
+ assert.equal((await diagnosticSources(args, run)).length, 5);
11
+ assert.deepEqual(await diagnosticSources({ ...args, sourceChannel: 'telegram' }, run), [{ channel: 'telegram', account: 'personal', target: '1', reply_to: '1' }]);
12
+ assert.equal((await diagnosticSources({ ...args, sourceAccount: 'other', sourceTarget: 'custom-target' }, run))[0].target, 'custom-target');
13
+ for (const selection of [{ sourceChannel: 'absent' }, { sourceAccount: 'missing' }]) await assert.rejects(diagnosticSources({ ...args, ...selection }, run), /No matching/);
14
+ for (const result of [{ code: 1 }, { code: 0, stdout: 'not json' }, { code: 0, stdout: '{}' }, { code: 0, stdout: '{"chat":{}}' }]) await assert.rejects(diagnosticSources(args, async () => result));
15
+ console.log('diagnostic source selection: passed');
16
+
17
+ for (const broken of [null, {}, 'accounts', { accounts: 'bad' }, ['personal', 42], ['personal', ''], ['personal', ' '], ['personal', null]]) {
18
+ const mixed = async () => ({ code: 0, stdout: JSON.stringify({ chat: { telegram: ['personal'], slack: broken } }) });
19
+ await assert.rejects(diagnosticSources(args, mixed), /Malformed/);
20
+ await assert.rejects(diagnosticSources({ ...args, sourceAccount: 'personal' }, mixed), /Malformed/);
21
+ assert.equal((await diagnosticSources({ ...args, sourceChannel: 'telegram' }, mixed)).length, 1);
22
+ await assert.rejects(diagnosticSources({ ...args, sourceChannel: 'slack' }, mixed), /Malformed/);
23
+ }
24
+ const empty = async () => ({ code: 0, stdout: JSON.stringify({ chat: { telegram: ['personal'], slack: [] } }) });
25
+ assert.equal((await diagnosticSources(args, empty)).length, 1);
26
+ await assert.rejects(diagnosticSources({ ...args, sourceChannel: 'slack' }, empty), /No matching/);
27
+ console.log('mixed-validity inventory regression: passed');
@@ -2,6 +2,7 @@
2
2
  import { access, readFile } from 'node:fs/promises';
3
3
  import { spawn } from 'node:child_process';
4
4
  import path from 'node:path';
5
+ import { diagnosticSources, verifyDiagnosticRuntime, diagnosticEnvironment } from '../lib/openclaw-diagnostic-source.mjs';
5
6
 
6
7
  function parseArgs(argv) {
7
8
  const out = { root: process.cwd(), queue: 'agent-tasks', workerAgent: 'main', openclawBin: 'openclaw', json: false };
@@ -11,6 +12,12 @@ function parseArgs(argv) {
11
12
  else if (arg === '--queue') out.queue = argv[++i];
12
13
  else if (arg === '--worker-agent') out.workerAgent = argv[++i];
13
14
  else if (arg === '--openclaw-bin') out.openclawBin = argv[++i];
15
+ else if (['--source-channel', '--source-account', '--source-target'].includes(arg)) {
16
+ const key = { '--source-channel': 'sourceChannel', '--source-account': 'sourceAccount', '--source-target': 'sourceTarget' }[arg];
17
+ const value = argv[++i];
18
+ if (!value || value.startsWith('--')) throw new Error(`Missing value for ${arg}`);
19
+ out[key] = value;
20
+ }
14
21
  else if (arg === '--json') out.json = true;
15
22
  else if (arg === '--help' || arg === '-h') out.help = true;
16
23
  else throw new Error(`Unknown argument: ${arg}`);
@@ -34,7 +41,7 @@ async function present(file) { try { await access(file); return true; } catch {
34
41
  async function main() {
35
42
  const args = parseArgs(process.argv.slice(2));
36
43
  if (args.help) {
37
- console.log('Usage: loop-engineering-openclaw-doctor [--root workspace] [--queue agent-tasks] [--worker-agent main] [--openclaw-bin openclaw] [--json]');
44
+ console.log('Usage: loop-engineering-openclaw-doctor [--root workspace] [--queue agent-tasks] [--worker-agent main] [--openclaw-bin openclaw] [--source-channel channel] [--source-account account] [--source-target dry-run-target] [--json]');
38
45
  return;
39
46
  }
40
47
  const required = [
@@ -53,6 +60,13 @@ async function main() {
53
60
  );
54
61
  const checks = [];
55
62
  for (const relative of required) checks.push({ id: `file:${relative}`, ok: await present(path.join(args.root, relative)) });
63
+ let runtimeVerified = false;
64
+ try {
65
+ const executable = await verifyDiagnosticRuntime(args);
66
+ args.openclawBin = executable;
67
+ runtimeVerified = true;
68
+ checks.push({ id: 'diagnostic_runtime', ok: true, detail: executable });
69
+ } catch (error) { checks.push({ id: 'diagnostic_runtime', ok: false, detail: error.message }); }
56
70
  const cli = await run(args.openclawBin, ['--version'], { cwd: args.root });
57
71
  checks.push({ id: 'openclaw_cli', ok: cli.code === 0, detail: (cli.stdout || cli.stderr).trim().slice(0, 300) });
58
72
  const agentsResult = await run(args.openclawBin, ['agents', 'list', '--json'], { cwd: args.root });
@@ -67,12 +81,17 @@ async function main() {
67
81
  } catch (error) { checks.push({ id: 'queue_config', ok: false, detail: error.message }); }
68
82
  }
69
83
  const notifier = path.join(args.root, 'scripts/loops/openclaw-loop-notify.mjs');
70
- if (await present(notifier)) {
71
- const smoke = await run(process.execPath, [notifier, 'Loop Engineering notification dry-run'], {
72
- cwd: args.root,
73
- env: { ...process.env, LOOP_NOTIFICATION_DRY_RUN: '1', LOOP_NOTIFICATION_SOURCE: JSON.stringify({ channel: 'feishu', target: 'user:loop-doctor-dry-run', reply_to: 'doctor-message' }) }
74
- });
75
- checks.push({ id: 'notification_dry_run', ok: smoke.code === 0, detail: (smoke.stdout || smoke.stderr).trim().slice(0, 500) });
84
+ let notificationSources = [];
85
+ try { if (runtimeVerified) notificationSources = await diagnosticSources(args, run); }
86
+ catch (error) { checks.push({ id: 'notification_channels', ok: false, detail: error.message }); }
87
+ if (runtimeVerified && await present(notifier)) {
88
+ for (const source of notificationSources) {
89
+ const smoke = await run(process.execPath, [notifier, 'Loop Engineering notification dry-run'], {
90
+ cwd: args.root,
91
+ env: { ...diagnosticEnvironment(), LOOP_NOTIFICATION_DRY_RUN: '1', LOOP_NOTIFICATION_SOURCE: JSON.stringify(source) }
92
+ });
93
+ checks.push({ id: 'notification_dry_run', channel: source.channel, account: source.account, ok: smoke.code === 0, detail: (smoke.stdout || smoke.stderr).trim().slice(0, 500) });
94
+ }
76
95
  }
77
96
  const gateBridge = path.join(args.root, 'scripts/loops/openclaw-loop-gate.mjs');
78
97
  if (await present(gateBridge)) {
@@ -82,7 +101,7 @@ async function main() {
82
101
  checks.push({ id: 'human_gate_bridge_self_test', ok: selfTest.code === 0 && /"externalWrite":false/.test(selfTest.stdout), detail: (selfTest.stdout || selfTest.stderr).trim().slice(0, 500) });
83
102
  }
84
103
  const failed = checks.filter((check) => !check.ok);
85
- const report = { version: 1, status: failed.length ? 'fail' : 'ok', readOnly: true, externalWrite: false, root: args.root, queue: args.queue, workerAgent: args.workerAgent, checks, failed: failed.map((check) => check.id) };
104
+ const report = { version: 1, status: failed.length ? 'fail' : 'ok', readOnly: true, externalWrite: false, root: args.root, queue: args.queue, workerAgent: args.workerAgent, notificationSources, checks, failed: failed.map((check) => check.id) };
86
105
  console.log(args.json ? JSON.stringify(report, null, 2) : `OpenClaw Loop doctor: ${report.status}\nchecks: ${checks.length - failed.length}/${checks.length}\nfailed: ${report.failed.join(', ') || 'none'}`);
87
106
  if (failed.length) process.exitCode = 1;
88
107
  }