@raytrace-cli/cli 0.13.0 → 0.14.1

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/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "@raytrace-cli/cli",
3
- "version": "0.13.0",
3
+ "version": "0.14.1",
4
4
  "description": "See what your coding agent did: traces, tool calls, cost and step-by-step evidence for Claude Code and Codex.",
5
5
  "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Godcreatebugs/raytrace-cli.git"
9
+ },
6
10
  "type": "module",
7
11
  "bin": {
8
12
  "raytrace": "bin/raytrace.mjs"
@@ -150,6 +150,24 @@ export function fold(events) {
150
150
  }
151
151
  continue;
152
152
  }
153
+ if (event.kind === 'exec_failed') {
154
+ // A program that never started (missing, or not executable). Shown as
155
+ // its own line, under the command whose process tried it: a shell that
156
+ // could not find what it was asked to run is otherwise just "exit 127".
157
+ const tried = Array.isArray(event.argv) ? event.argv : [];
158
+ if (!tried.length || underHarness(pid)) { folded.machinery += underHarness(pid) ? 1 : 0; continue; }
159
+ const owner = byPid.get(pid);
160
+ const entry = {
161
+ event_id: Number(event.event_id), pid, ppid: eventPpid, argv: tried, command: bareCommand(tried), marker_call_id: null,
162
+ started_ns: event.timestamp_ns ?? null, process_start_ns: typeof event.process_start_ns === 'string' ? event.process_start_ns : null,
163
+ ended_ns: event.timestamp_ns ?? null, exit_code: null, signal: null, parent_event_id: owner ? owner.event_id : null,
164
+ exec_failed: true, errno: typeof event.errno === 'number' ? event.errno : null,
165
+ };
166
+ // The forked child that only tried this: its exit closes this line.
167
+ if (!owner) byPid.set(pid, entry);
168
+ commands.push(entry);
169
+ continue;
170
+ }
153
171
  if (event.kind !== 'exec_succeeded') continue;
154
172
 
155
173
  const argv = Array.isArray(event.argv) ? event.argv : [];
@@ -158,7 +176,7 @@ export function fold(events) {
158
176
  if (isMachinery(argv)) { folded.machinery += 1; continue; }
159
177
 
160
178
  // A pid that already has a command is re-execing: same job, new image.
161
- if (byPid.has(pid)) { folded.reexec += 1; continue; }
179
+ if (byPid.has(pid) && !byPid.get(pid).exec_failed) { folded.reexec += 1; continue; }
162
180
 
163
181
  const entry = {
164
182
  event_id: Number(event.event_id),
@@ -191,6 +209,7 @@ export function fold(events) {
191
209
  // children to the nearest ancestor that survived. A process whose parent ran
192
210
  // outside this window is genuinely unattributed and stays at the top level.
193
211
  for (const entry of commands) {
212
+ if (entry.parent_event_id != null) continue; // a failed exec already under the command that tried it
194
213
  let ancestor = entry.ppid;
195
214
  const seen = new Set([entry.pid]);
196
215
  while (ancestor != null && !seen.has(ancestor)) {
@@ -210,7 +229,7 @@ export function fold(events) {
210
229
  const byEventId = new Map(commands.map((entry) => [entry.event_id, entry]));
211
230
  const collapsed = commands.filter((entry) => {
212
231
  const parent = entry.parent_event_id != null ? byEventId.get(entry.parent_event_id) : null;
213
- if (!parent || !sameWork(entry.command, parent.command)) return true;
232
+ if (entry.exec_failed || !parent || !sameWork(entry.command, parent.command)) return true;
214
233
  parent.exit_code = entry.exit_code ?? parent.exit_code;
215
234
  parent.signal = entry.signal ?? parent.signal;
216
235
  parent.ended_ns = entry.ended_ns ?? parent.ended_ns;
@@ -260,3 +260,26 @@ test('a folded command keeps its process start time, so it can be matched to a c
260
260
  assert.equal(commands[0].event_id, 2, 'the tree keeps a different exec event than the first one...');
261
261
  assert.equal(commands[0].process_start_ns, '9000', '...but the same process identity');
262
262
  });
263
+
264
+ test('a program that never started is its own failed line under the command that tried it', () => {
265
+ const failed = (id, pid, ppid, argv) => ({ event_id: id, kind: 'exec_failed', pid, ppid, argv, errno: null, timestamp_ns: String(id * 1000), process_start_ns: '5' });
266
+ const { commands } = fold([
267
+ exec(1, 300, 1, ['/bin/bash', '-c', './build.sh && ./missing-tool --flag']),
268
+ exec(2, 301, 300, ['./build.sh']),
269
+ exit(3, 301, 0),
270
+ failed(4, 302, 300, ['./missing-tool', '--flag']), // the forked child that only tried it
271
+ exit(5, 302, 127),
272
+ exit(6, 300, 127),
273
+ ]);
274
+ assert.deepEqual(commands.map((entry) => [entry.command, entry.exec_failed === true, entry.exit_code]),
275
+ [['./build.sh && ./missing-tool --flag', false, 127], ['./build.sh', false, 0], ['./missing-tool --flag', true, 127]]);
276
+ assert.equal(commands[2].parent_event_id, 1);
277
+
278
+ // A process that tries one program, fails, and starts another keeps both lines.
279
+ const again = fold([failed(1, 400, 1, ['/opt/a']), exec(2, 400, 1, ['/usr/bin/b']), exit(3, 400, 0)]).commands;
280
+ assert.deepEqual(again.map((entry) => [entry.command, entry.exec_failed === true, entry.exit_code]), [['/opt/a', true, null], ['/usr/bin/b', false, 0]]);
281
+
282
+ // The shell handed exactly the program that is missing: the failure is not folded into the shell.
283
+ const same = fold([exec(1, 500, 1, ['/bin/sh', '-c', './gone']), failed(2, 501, 500, ['./gone']), exit(3, 501, 127), exit(4, 500, 127)]).commands;
284
+ assert.equal(same.filter((entry) => entry.exec_failed).length, 1);
285
+ });
@@ -89,6 +89,10 @@ WRITER_LIFE = 900 # how long an open for writing may explain a lat
89
89
  RAW_WINDOW = (2_000_000_000, 1_000_000_000) # ns a delete or rename call may precede, or follow, the watcher's notice
90
90
  BULK = 200 # opens from which a step is worth one summary line
91
91
  RETAIN_DAYS, RETAIN_ROWS = 14, 50_000
92
+ ALIAS_WINDOW = 5_000_000_000 # ns before a change within which an open of another name may be a link to the file
93
+ # Programs whose folder argument reaches the files under it. Any other program
94
+ # naming a folder (a script given its working folder) says nothing of them.
95
+ FOLDER_TOOLS = frozenset(['rm', 'rmdir', 'mv', 'cp', 'chmod', 'chown', 'chgrp', 'find', 'rsync', 'shred', 'unlink', 'truncate'])
92
96
  PACKAGE_TOOLS = frozenset(['npm', 'npx', 'pnpm', 'yarn', 'bun', 'pip', 'pip3', 'uv', 'poetry'])
93
97
  REGISTRIES = frozenset(['registry.npmjs.org', 'registry.yarnpkg.com', 'pypi.org', 'files.pythonhosted.org'])
94
98
  MAX_PACKAGES = 400
@@ -304,6 +308,7 @@ class Sandbox:
304
308
  self.final = {} # path -> when to stop waiting for a change
305
309
  self.causes = {} # path -> what the watcher saw of it since the last look
306
310
  self.raw = collections.deque(maxlen=512) # recent delete, rename, resize and mode calls: they carry no path
311
+ self.aliases = collections.deque(maxlen=256) # recent opens for writing of files not kept: one may be a link to a kept file
307
312
  self.watches = {} # folder -> inotify watch
308
313
  self.counts = {} # step -> opens that were only counted
309
314
  self.packages = None # what was installed when last looked
@@ -567,6 +572,16 @@ class Engine(threading.Thread):
567
572
 
568
573
  def exited(self, box, event):
569
574
  gone = box.processes.pop(event.get('pid'), None)
575
+ # A process that has exited writes nothing more. Whatever it did to a
576
+ # file it had open is looked at now, and after that look it is no
577
+ # longer a candidate: a change an hour later is not its doing.
578
+ pid, now = event.get('pid'), self.clock()
579
+ for path, writers in box.writers.items():
580
+ for writer in writers:
581
+ if (writer['who'].get('pid') == pid and not writer.get('gone')
582
+ and writer['who'].get('start_ns') in (None, event.get('process_start_ns'))):
583
+ writer['gone'] = True
584
+ box.due[path] = min(box.due.get(path, now + SETTLE), now + SETTLE)
570
585
  if gone and box.workspace and PACKAGE_TOOLS & {posixpath.basename(part) for part in gone['argv'][:4]}:
571
586
  # A package manager finished: see what it left, once it has settled.
572
587
  box.package_due = self.clock() + 1
@@ -679,6 +694,8 @@ class Engine(threading.Thread):
679
694
  self.arm(box)
680
695
  guard = 'sensitive'
681
696
  if guard is None:
697
+ if writing and not errno and box.guarded:
698
+ box.aliases.append({'path': path, 'who': who, 'at_ns': at_ns, 'syscall': self.calls.get(event.get('sysno'), ('open', 'open'))[0]})
682
699
  return self.counted(box, who, top, at_ns)
683
700
  call = self.calls.get(event.get('sysno'), ('open', 'open'))[0]
684
701
  basis = {'syscall': call, 'flags': flags, 'resolution': 'lexical'}
@@ -731,9 +748,10 @@ class Engine(threading.Thread):
731
748
  at = name[len(WORKSPACE):] # empty for the project folder itself: `rm -r .` names everything
732
749
  if at in box.guarded:
733
750
  found[at] = 'argv'
734
- for path in box.guarded: # `rm -r src` reaches every file under src
735
- if not at or path.startswith(at + '/'):
736
- found.setdefault(path, 'argv_folder')
751
+ if who.get('name') in FOLDER_TOOLS:
752
+ for path in box.guarded: # `rm -r src` reaches every file under src
753
+ if not at or path.startswith(at + '/'):
754
+ found.setdefault(path, 'argv_folder')
737
755
  if not found:
738
756
  text = ' '.join(who.get('argv') or [])
739
757
  found = {path: 'argv_text' for path in box.guarded if path in text}
@@ -800,7 +818,9 @@ class Engine(threading.Thread):
800
818
  return
801
819
  cause = box.causes.pop(path, None) or {'events': set(), 'at_ns': time.time_ns()}
802
820
  now = self.clock()
803
- writers = box.writers[path] = [writer for writer in box.writers.get(path, []) if now - writer['seen'] < WRITER_LIFE]
821
+ # Not a writer that exited and has had its look since: see exited().
822
+ writers = box.writers[path] = [writer for writer in box.writers.get(path, [])
823
+ if now - writer['seen'] < WRITER_LIFE and not writer.get('settled')]
804
824
  before = box.photos.get(path)
805
825
  after = photo(box.workspace, path, box.hashing)
806
826
  flags = 0
@@ -811,25 +831,38 @@ class Engine(threading.Thread):
811
831
  box.photos[path] = after
812
832
  if after is None and box.known is not None:
813
833
  box.known.discard(path)
834
+ via = None
814
835
  if effect in ('deleted', 'renamed'):
815
836
  found = self.actors(box, 'remove' if effect == 'deleted' else 'rename', cause['at_ns'], path)
816
837
  elif effect == 'permissions_changed':
817
838
  found = self.actors(box, 'metadata', cause['at_ns'], path)
818
839
  else:
819
- found, seen = [], set()
840
+ opened, seen = [], set()
820
841
  for writer in reversed(writers): # the latest to open it first
821
842
  key = (writer['who']['pid'], writer['who']['start_ns'])
822
843
  if key not in seen:
823
844
  seen.add(key)
824
- found.append((writer['who'], writer['syscall']))
845
+ opened.append((writer['who'], writer['syscall']))
825
846
  writer['credited'] = True
826
- if 'moved_to' in cause['events']: # written elsewhere and moved over it, as editors and `sed -i` do
827
- found += self.actors(box, 'rename', cause['at_ns'], path)
847
+ found = None
848
+ if 'moved_to' in cause['events']:
849
+ # Written elsewhere and moved over it, as editors and `sed -i`
850
+ # do: the bytes are the mover's, whoever opened this name before.
851
+ found = self.actors(box, 'rename', cause['at_ns'], path)
852
+ elif 'close_write' not in cause['events']:
853
+ # Changed with nobody closing it: truncate(2), which opens
854
+ # nothing, ahead of whoever still has it open.
855
+ found = self.actors(box, 'resize', cause['at_ns'], path) + opened
856
+ found = found or opened
828
857
  if not found:
829
- found = self.actors(box, 'resize', cause['at_ns'], path)
858
+ link = self.linked(box, path, after, cause['at_ns'])
859
+ if link:
860
+ found, via = [(link['who'], link['syscall'])], link['path']
830
861
  who, call = found[0] if found else ({}, None)
831
862
  certainty = 'unattributed' if not found else 'confirmed' if len(found) == 1 else 'one_of'
832
863
  basis = {'syscall': call, 'watcher': sorted(cause['events']), 'before': before, 'after': after, 'resolution': 'lexical'}
864
+ if via:
865
+ basis.update(resolution='link', via=via, note='opened under another name that is a link to this file')
833
866
  if len(found) > 1:
834
867
  basis['candidates'] = [{'pid': other['pid'], 'process': other['name']} for other, _ in found[:5]]
835
868
  fact = self.fact(box, 'file', (path, effect, certainty), who,
@@ -845,9 +878,44 @@ class Engine(threading.Thread):
845
878
  {'path': path, 'guard': guard, 'effect': 'opened_for_writing', 'certainty': 'possible',
846
879
  'basis': {'syscall': writer['syscall'], 'flags': writer['flags'], 'before': before, 'after': after,
847
880
  'resolution': 'lexical', 'note': 'opened for writing; the file is as it was'}}, writer['at_ns'])
881
+ for writer in writers:
882
+ if writer.get('gone'):
883
+ writer['settled'] = True
848
884
  if not writers:
849
885
  box.writers.pop(path, None)
850
886
 
887
+ def linked(self, box, path, after, at_ns):
888
+ """A recent open for writing of another name that is this file: a hard
889
+ link to it (the same inode) or a symbolic link whose text leads to it.
890
+ Links are read, never followed: the text is worked out as a path."""
891
+ for other in reversed(box.aliases):
892
+ if not at_ns - ALIAS_WINDOW <= other['at_ns'] <= at_ns + RAW_WINDOW[1]:
893
+ continue
894
+ name = other['path']
895
+ for _ in range(8): # a link to a link, a few deep
896
+ if name == path:
897
+ return other
898
+ try:
899
+ folder = open_inside(box.workspace, posixpath.dirname(name), directory=True) if posixpath.dirname(name) else os.open(box.workspace, os.O_RDONLY | os.O_DIRECTORY)
900
+ except (OSError, ValueError):
901
+ break
902
+ try:
903
+ info = os.stat(posixpath.basename(name), dir_fd=folder, follow_symlinks=False)
904
+ if not stat.S_ISLNK(info.st_mode):
905
+ if after and stat.S_ISREG(info.st_mode) and info.st_ino == after['inode']:
906
+ return other
907
+ break
908
+ target = os.readlink(posixpath.basename(name), dir_fd=folder)
909
+ except OSError:
910
+ break
911
+ finally:
912
+ os.close(folder)
913
+ target = posixpath.normpath(target if target.startswith('/') else posixpath.join(WORKSPACE, posixpath.dirname(name), target))
914
+ if not target.startswith(WORKSPACE):
915
+ break
916
+ name = target[len(WORKSPACE):]
917
+ return None
918
+
851
919
  # ------------------------------------------------------------ network, identity, packages
852
920
 
853
921
  def host_name(self, box, ip):
@@ -873,8 +941,11 @@ class Engine(threading.Thread):
873
941
  there = ipaddress.ip_address(ip)
874
942
  at_ns = int(event.get('timestamp_ns') or 0) or time.time_ns()
875
943
  listening = event['kind'] == 'listen'
876
- if not listening and (there.is_loopback or there.is_unspecified):
877
- return # the sandbox talking to itself
944
+ if not listening and (there.is_loopback or there.is_unspecified or ip == box.ip):
945
+ # The sandbox talking to itself, by loopback or by its own address:
946
+ # that one is in a range the firewall rejects for other machines,
947
+ # and it never leaves the sandbox to be rejected.
948
+ return
878
949
  if not listening and port == 0:
879
950
  # No traffic: the resolver library "connects" a datagram socket to each
880
951
  # address a name answered with, port 0, to choose which to use.
@@ -1,7 +1,11 @@
1
1
  """Raw-call context and failed execs. Run: python3 -B -m unittest discover -s worker/sandbox -p 'test_*.py'"""
2
2
  import json
3
+ import os
3
4
  from pathlib import Path
5
+ import sqlite3
4
6
  import sys
7
+ import tempfile
8
+ import time
5
9
  import unittest
6
10
 
7
11
  sys.path.insert(0, str(Path(__file__).parent))
@@ -54,6 +58,115 @@ class RawCalls(unittest.TestCase):
54
58
  self.assertEqual(box.raw[0]['who']['pid'], 41)
55
59
 
56
60
 
61
+ class WhoChangedIt(unittest.TestCase):
62
+ """engine.look(): a change goes to the process that made it, not to
63
+ whoever opened that name before."""
64
+ def setUp(self):
65
+ self.now = 1000.0
66
+ self.engine = engine.Engine(':memory:', arch='aarch64', watch=False, clock=lambda: self.now)
67
+ self.folder = tempfile.TemporaryDirectory()
68
+ self.addCleanup(self.folder.cleanup)
69
+ self.box = engine.Sandbox('c' * 64)
70
+ self.box.workspace, self.box.ip = self.folder.name, '172.30.60.3'
71
+ self.write('keys.js', 'one')
72
+ self.box.guarded = {'keys.js': 'watched'}
73
+ self.box.photos['keys.js'] = engine.photo(self.folder.name, 'keys.js')
74
+ for pid, name in ((10, 'python3'), (20, 'sed'), (30, 'truncate')):
75
+ self.box.processes[pid] = {'start_ns': str(pid), 'ppid': 1, 'name': name, 'argv': [name], 'call_id': f'call_{pid}'}
76
+
77
+ def write(self, name, text):
78
+ (Path(self.folder.name) / name).write_text(text)
79
+
80
+ def opened(self, pid, name='keys.js', flags=engine.O_TRUNC | 1):
81
+ self.engine.opened(self.box, {'kind': 'open', 'pathname': '/workspace/' + name, 'flags': flags, 'errno': 0, 'pid': pid,
82
+ 'ppid': 1, 'process_start_ns': str(pid), 'timestamp_ns': str(time.time_ns()), 'sysno': 56})
83
+
84
+ def call(self, pid, sysno, errno=0):
85
+ self.engine.numbered_call(self.box, {'kind': 'syscall_return', 'sysno': sysno, 'errno': errno, 'pid': pid, 'ppid': 1,
86
+ 'process_start_ns': str(pid), 'timestamp_ns': str(time.time_ns()), 'cwd': '/workspace'})
87
+
88
+ def changed(self, *words):
89
+ self.engine.noticed(self.box, 'keys.js', list(words))
90
+ self.engine.look(self.box, 'keys.js')
91
+ return [fact for fact in self.engine.facts.values() if fact['kind'] == 'file' and fact['effect'] not in ('read', 'opened_for_writing')]
92
+
93
+ def earlier_writer(self):
94
+ """Process 10 writes the file, exits, and its change is recorded."""
95
+ self.opened(10)
96
+ self.write('keys.js', 'two')
97
+ self.engine.exited(self.box, {'pid': 10, 'process_start_ns': '10'})
98
+ (fact,) = self.changed('modify', 'close_write')
99
+ self.assertEqual((fact['pid'], fact['certainty']), (10, 'confirmed'))
100
+ self.engine.facts.clear()
101
+ self.now += 60
102
+
103
+ def test_a_writer_that_exited_is_not_credited_with_a_later_change(self):
104
+ self.earlier_writer()
105
+ self.write('keys.js', 'three')
106
+ (fact,) = self.changed('modify', 'close_write')
107
+ self.assertEqual((fact['pid'], fact['certainty']), (None, 'unattributed'))
108
+
109
+ def test_exit_brings_the_look_forward(self):
110
+ self.opened(10)
111
+ self.box.due.clear()
112
+ self.engine.exited(self.box, {'pid': 10, 'process_start_ns': '10'})
113
+ self.assertIn('keys.js', self.box.due)
114
+
115
+ def test_a_file_moved_over_it_is_the_movers(self):
116
+ self.earlier_writer()
117
+ self.opened(10) # another process still has the name open
118
+ self.write('keys.js', 'by sed')
119
+ self.call(20, 38) # renameat
120
+ (fact,) = self.changed('moved_to', 'close_write')
121
+ self.assertEqual((fact['pid'], fact['call_id'], fact['certainty'], fact['basis']['syscall']), (20, 'call_20', 'confirmed', 'renameat'))
122
+
123
+ def test_truncate_is_the_truncaters(self):
124
+ self.earlier_writer()
125
+ self.write('keys.js', '')
126
+ self.call(30, 45) # truncate
127
+ (fact,) = self.changed('modify')
128
+ self.assertEqual((fact['effect'], fact['pid'], fact['certainty']), ('emptied', 30, 'confirmed'))
129
+
130
+ def test_a_write_through_a_symbolic_link_or_a_hard_link(self):
131
+ for make in (lambda: os.symlink('keys.js', Path(self.folder.name) / 'alias'),
132
+ lambda: os.link(Path(self.folder.name) / 'keys.js', Path(self.folder.name) / 'alias')):
133
+ with self.subTest():
134
+ make()
135
+ self.opened(20, 'alias')
136
+ (Path(self.folder.name) / 'alias').write_text('through ' + str(self.now))
137
+ (fact,) = self.changed('modify', 'close_write')
138
+ self.assertEqual((fact['pid'], fact['certainty'], fact['basis']['resolution'], fact['basis']['via']), (20, 'confirmed', 'link', 'alias'))
139
+ self.engine.facts.clear()
140
+ self.box.aliases.clear()
141
+ os.unlink(Path(self.folder.name) / 'alias')
142
+ self.now += 60
143
+
144
+ def test_a_link_out_of_the_project_is_not_followed(self):
145
+ os.symlink('/etc/hostname', Path(self.folder.name) / 'alias')
146
+ self.opened(20, 'alias')
147
+ self.write('keys.js', 'someone')
148
+ (fact,) = self.changed('modify', 'close_write')
149
+ self.assertEqual(fact['certainty'], 'unattributed')
150
+
151
+ def test_a_folder_argument_reaches_its_files_only_for_a_file_tool(self):
152
+ self.box.guarded = {'src/a.js': 'watched', 'src/b.js': 'watched'}
153
+ script = {'name': 'python3', 'argv': ['python3', 'run.py', 'src']}
154
+ self.assertEqual(self.engine.named(self.box, script, '/workspace'), [])
155
+ self.assertEqual(self.engine.named(self.box, {'name': 'rm', 'argv': ['rm', '-r', 'src']}, '/workspace'),
156
+ [('src/a.js', 'argv_folder'), ('src/b.js', 'argv_folder')])
157
+ self.assertEqual(self.engine.named(self.box, {'name': 'python3', 'argv': ['python3', 'run.py', 'src/a.js']}, '/workspace'), [('src/a.js', 'argv')])
158
+
159
+ def test_a_connection_to_its_own_address_is_the_sandbox_talking_to_itself(self):
160
+ event = {'kind': 'connect', 'family': 'inet', 'ip': '172.30.60.3', 'port': 18082, 'errno': 0, 'pid': 10, 'ppid': 1, 'process_start_ns': '10'}
161
+ self.engine.connected(self.box, event)
162
+ self.assertEqual(self.engine.facts, {})
163
+ self.engine.db = sqlite3.connect(':memory:')
164
+ self.engine.db.executescript(engine.SCHEMA)
165
+ self.engine.connected(self.box, {**event, 'ip': '172.30.60.9'}) # another machine in that range
166
+ (fact,) = self.engine.facts.values()
167
+ self.assertEqual(fact['outcomes'], {'refused_by_policy': 1})
168
+
169
+
57
170
  class FailedExecs(unittest.TestCase):
58
171
  def setUp(self):
59
172
  self.attempts = collector.ExecAttempts()