@raytrace-cli/cli 0.22.1 → 0.22.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.
@@ -209,48 +209,151 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
209
209
  started_at: row.started_at ?? null, ended_at: row.ended_at ?? null,
210
210
  });
211
211
  }
212
+ // Where a sandboxed Claude Code's project folder stood after each call,
213
+ // and any host-observed activity facts (file, network, dns) stamped with call_id.
214
+ const allCallIds = traceOrigins.map((origin) => origin.call_id);
215
+ const sessionScope = { sessionId: trace.sandboxId || trace.id };
216
+ const snapshots = await db.snapshotsForCalls(allCallIds, sessionScope);
217
+ const activityFacts = db?.activityFactsForCalls ? await db.activityFactsForCalls(allCallIds, sessionScope) : new Map();
218
+ const FILE_WRITERS = /^(?:Write|Edit|MultiEdit|NotebookEdit|apply_patch)$/i;
219
+ const factVerification = (origin, real) => {
220
+ if (real && real.outcome !== 'not_executed') {
221
+ return {
222
+ outcome: real.outcome,
223
+ verified: true,
224
+ status: real.status ?? null,
225
+ error: real.error ?? null,
226
+ match_score: real.match_score ?? null,
227
+ match_basis: real.match_basis ?? null,
228
+ source: real.source ?? null,
229
+ kernel_confirmed: real.kernel_confirmed === 1,
230
+ file_confirmed: false,
231
+ tier: real.tier ?? null,
232
+ };
233
+ }
234
+ const facts = activityFacts.get(origin.call_id) ?? [];
235
+ const fileFacts = facts.filter((fact) => fact.kind === 'file');
236
+ const snapshot = snapshots.get(origin.call_id) ?? null;
237
+ if (origin.kind === 'file') {
238
+ if (fileFacts.length > 0) {
239
+ const fromReport = fileFacts.some((fact) => fact.call_from === 'tool_report');
240
+ return {
241
+ outcome: 'file_observed',
242
+ verified: true,
243
+ status: 'completed',
244
+ error: null,
245
+ match_score: 1,
246
+ match_basis: fromReport ? 'tool_report' : 'file_fact',
247
+ source: 'file_fact',
248
+ kernel_confirmed: false,
249
+ file_confirmed: true,
250
+ tier: 'corroborated',
251
+ };
252
+ }
253
+ if (snapshot?.changed === true) {
254
+ return {
255
+ outcome: 'file_observed',
256
+ verified: true,
257
+ status: 'completed',
258
+ error: null,
259
+ match_score: 1,
260
+ match_basis: 'snapshot',
261
+ source: 'snapshot',
262
+ kernel_confirmed: false,
263
+ file_confirmed: true,
264
+ tier: 'corroborated',
265
+ };
266
+ }
267
+ if (!FILE_WRITERS.test(origin.name || '')) {
268
+ // Read-only file tools (Read, Grep, Glob, LS) run inside the agent
269
+ // process and start no program; never flag them as a missing command.
270
+ return {
271
+ outcome: 'in_agent',
272
+ verified: false,
273
+ status: 'in_agent',
274
+ error: null,
275
+ match_score: null,
276
+ match_basis: null,
277
+ source: null,
278
+ kernel_confirmed: false,
279
+ file_confirmed: false,
280
+ tier: null,
281
+ };
282
+ }
283
+ } else if (facts.length > 0) {
284
+ // Activity already carries this call_id (e.g. network/dns/file fact),
285
+ // so the call definitely ran even if the process row has not joined yet.
286
+ return {
287
+ outcome: 'join_pending',
288
+ verified: true,
289
+ status: 'join_pending',
290
+ error: null,
291
+ match_score: 1,
292
+ match_basis: 'id',
293
+ source: 'activity_fact',
294
+ kernel_confirmed: false,
295
+ file_confirmed: fileFacts.length > 0,
296
+ tier: 'corroborated',
297
+ };
298
+ }
299
+ return {
300
+ outcome: real?.outcome ?? 'not_executed',
301
+ verified: false,
302
+ status: real?.status ?? null,
303
+ error: real?.error ?? null,
304
+ match_score: real?.match_score ?? null,
305
+ match_basis: real?.match_basis ?? null,
306
+ source: real?.source ?? null,
307
+ kernel_confirmed: false,
308
+ file_confirmed: false,
309
+ tier: real?.tier ?? null,
310
+ };
311
+ };
312
+
313
+ const originByCallId = new Map(traceOrigins.map((origin) => [origin.call_id, origin]));
212
314
  trace.evidence = trace.evidence.map((item) => {
213
315
  const real = item.call_id ? byCallId.get(item.call_id) : null;
214
- if (!real) return item;
215
- // 'not_executed' means no execution row was correlated — this could be
216
- // a call that genuinely never ran, or one the (deliberately
217
- // conservative) matcher failed to correlate. Either way, there is no
218
- // real ground truth to show yet, so this stays "unverified" and keeps
219
- // the regex-heuristic succeeded value rather than asserting a fact we
220
- // don't actually have.
221
- const verified = real.outcome !== 'not_executed';
222
- return {
223
- ...item,
224
- real_outcome: real.outcome,
225
- real_status: real.status ?? null,
226
- real_error: real.error ?? null,
316
+ const origin = item.call_id ? originByCallId.get(item.call_id) : null;
317
+ if (!real && !origin) return item;
318
+ const resolved = origin ? factVerification(origin, real) : {
319
+ outcome: real.outcome,
320
+ verified: real.outcome !== 'not_executed',
321
+ status: real.status ?? null,
322
+ error: real.error ?? null,
227
323
  match_score: real.match_score ?? null,
228
324
  match_basis: real.match_basis ?? null,
229
- // Which witness observed it (only 'gvisor' now), and whether the
230
- // runtime layer saw it start. Both drive the badge.
231
325
  source: real.source ?? null,
232
326
  kernel_confirmed: real.kernel_confirmed === 1,
233
- // How this call's execution was attributed, recorded at capture (see
234
- // migration 005). The UI badges this directly instead of re-deriving
235
- // confidence from kernel_confirmed + match_basis, which is how a
236
- // text-similarity guess ended up wearing the same badge as an exact
237
- // join. Null for rows written before 005.
327
+ file_confirmed: false,
238
328
  tier: real.tier ?? null,
329
+ };
330
+ return {
331
+ ...item,
332
+ real_outcome: resolved.outcome,
333
+ real_status: resolved.status,
334
+ real_error: resolved.error,
335
+ match_score: resolved.match_score,
336
+ match_basis: resolved.match_basis,
337
+ // Which witness observed it (gvisor, file_fact, snapshot, activity_fact),
338
+ // and whether the runtime layer saw a program start.
339
+ source: resolved.source,
340
+ kernel_confirmed: resolved.kernel_confirmed,
341
+ file_confirmed: resolved.file_confirmed,
342
+ tier: resolved.tier,
239
343
  // The call's own process, so the decision chain can say which pid
240
344
  // this call ran as and jump to it in the sandbox tree.
241
345
  ...executionFields(real),
242
346
  descendants: descendantsByCall.get(item.call_id) ?? [],
243
- descendant_count: real.descendant_count ?? 0,
244
- verified,
347
+ descendant_count: real?.descendant_count ?? 0,
348
+ verified: resolved.verified,
245
349
  // Whether the agent's own report of the result (exit code, wall
246
350
  // time) agrees with what the runtime observed. See migration 007.
247
- reported_check: real.reported_check ?? null,
351
+ reported_check: real?.reported_check ?? null,
248
352
  // Real ground truth overrides the text-scanning heuristic once we
249
- // have it -- except while a sandbox command is still 'running'
250
- // (gVisor has seen it start but not exit yet) or its outcome is
251
- // 'unknown' (the evidence that would say was lost): asserting success
252
- // or failure there would be a fact we don't have, so keep the heuristic.
253
- succeeded: verified && real.status !== 'running' && real.status !== 'unknown' ? real.status === 'completed' : item.succeeded,
353
+ // have it -- except while a sandbox command is still 'running' /
354
+ // 'join_pending' / 'in_agent' or its outcome is 'unknown'.
355
+ succeeded: resolved.verified && resolved.kernel_confirmed && resolved.status !== 'running' && resolved.status !== 'unknown'
356
+ ? resolved.status === 'completed' : item.succeeded,
254
357
  };
255
358
  });
256
359
 
@@ -258,13 +361,9 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
258
361
  // above, this isn't limited to calls whose result got resent as later
259
362
  // input — it covers every call this trace ever proposed, including one
260
363
  // in the very last response with no later request to resend it into.
261
- // `origins` already has one entry per call_id with the exchange that
262
- // proposed it, so this is just that, decorated with whatever real
263
- // execution data (if any) `divergence()` found for the same call_id.
264
- // Where a sandboxed Claude Code's project folder stood after each call.
265
- const snapshots = await db.snapshotsForCalls(traceOrigins.map((origin) => origin.call_id), { sessionId: trace.sandboxId || trace.id });
266
364
  trace.callVerifications = traceOrigins.map((origin) => {
267
365
  const real = byCallId.get(origin.call_id);
366
+ const resolved = factVerification(origin, real);
268
367
  return {
269
368
  call_id: origin.call_id,
270
369
  exchange_id: origin.exchange_id,
@@ -273,14 +372,15 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
273
372
  category: origin.category.category,
274
373
  category_source: origin.category.source,
275
374
  ...(origin.category.command ? { category_command: origin.category.command } : {}),
276
- verified: real ? real.outcome !== 'not_executed' : false,
277
- status: real?.status ?? null,
278
- error: real?.error ?? null,
279
- match_score: real?.match_score ?? null,
280
- match_basis: real?.match_basis ?? null,
281
- source: real?.source ?? null,
282
- kernel_confirmed: real?.kernel_confirmed === 1,
283
- tier: real?.tier ?? null,
375
+ verified: resolved.verified,
376
+ status: resolved.status,
377
+ error: resolved.error,
378
+ match_score: resolved.match_score,
379
+ match_basis: resolved.match_basis,
380
+ source: resolved.source,
381
+ kernel_confirmed: resolved.kernel_confirmed,
382
+ file_confirmed: resolved.file_confirmed,
383
+ tier: resolved.tier,
284
384
  reported_check: real?.reported_check ?? null,
285
385
  descendant_count: real?.descendant_count ?? 0,
286
386
  // Everything the "proposed vs observed" table needs for this row:
@@ -268,7 +268,7 @@ def project_path(event):
268
268
  def dist_info_from_path(path):
269
269
  """If `path` is a Python package metadata file inside a `*.dist-info`
270
270
  folder anywhere in the container (including `/tmp/venv`), return
271
- `('pip', package, version)`; else None."""
271
+ `('pip', package, version, site_dir)`; else None."""
272
272
  if not path:
273
273
  return None
274
274
  folder, leaf = posixpath.split(path)
@@ -280,7 +280,8 @@ def dist_info_from_path(path):
280
280
  package, _, version = dist[:-len('.dist-info')].rpartition('-')
281
281
  if not package or not version or package.startswith('.'):
282
282
  return None
283
- return ('pip', package[:200], version[:80])
283
+ site_dir = posixpath.dirname(folder) or '/'
284
+ return ('pip', package[:200], version[:80], site_dir[:300])
284
285
 
285
286
 
286
287
  def is_package_manager(argv):
@@ -331,18 +332,24 @@ def package_prefixes(argv):
331
332
  return found
332
333
 
333
334
 
334
- def _scan_pip_site(found, volume, site):
335
+ def _scan_pip_site(found, volume, site, container_site):
335
336
  for name in names_inside(volume, site):
336
337
  if name.endswith('.dist-info') and '-' in name:
337
338
  package, _, version = name[:-len('.dist-info')].rpartition('-')
338
339
  if package and version:
339
- found[('pip', package[:200], version[:80])] = None
340
+ found[('pip', package[:200], version[:80], container_site[:300])] = None
340
341
 
341
342
 
342
343
  def installed(workspace, home, extra_prefixes=()):
343
- """{(manager, name, version): where it came from} as the package managers'
344
- own records on the host-mounted volumes have it. The agent can write those
345
- files, so a fact drawn from them is `reported`, not seen.
344
+ """{(manager, name, version, site_dir): where it came from} as the package
345
+ managers' own records on the host-mounted volumes have it. The agent can
346
+ write those files, so a fact drawn from them is `reported`, not seen.
347
+
348
+ Keys include `site_dir` (the container path of the site-packages or
349
+ node_modules directory) so installing the same `(name, version)` into a
350
+ second environment (e.g. `/tmp/venv` after `/tmp/pylibs`) is not dropped,
351
+ while volume scans and `opened()` observations of the same prefix still
352
+ deduplicate cleanly.
346
353
 
347
354
  `extra_prefixes` may name container prefixes (e.g. `/workspace/custom-env`
348
355
  or `/home/node/myenv`) extracted from package-manager argv; only prefixes
@@ -354,6 +361,7 @@ def installed(workspace, home, extra_prefixes=()):
354
361
  roots = [''] + [name for name in names_inside(workspace, '') if name not in SKIPPED and not name.startswith('.')][:50]
355
362
  for root in roots:
356
363
  modules = posixpath.join(root, 'node_modules')
364
+ container_modules = posixpath.normpath(WORKSPACE + modules)
357
365
  lock = read_inside(workspace, posixpath.join(modules, '.package-lock.json'), 32 * 1024 * 1024)
358
366
  try:
359
367
  listed = json.loads(lock)['packages'] if lock else None
@@ -362,7 +370,7 @@ def installed(workspace, home, extra_prefixes=()):
362
370
  if isinstance(listed, dict):
363
371
  for key, entry in listed.items():
364
372
  if isinstance(key, str) and isinstance(entry, dict) and isinstance(entry.get('version'), str):
365
- found[('npm', key.rsplit('node_modules/', 1)[-1][:200], entry['version'][:80])] = str(entry.get('resolved') or '')[:300] or None
373
+ found[('npm', key.rsplit('node_modules/', 1)[-1][:200], entry['version'][:80], container_modules[:300])] = str(entry.get('resolved') or '')[:300] or None
366
374
  continue
367
375
  # No npm record (yarn, pnpm, bun): the packages at the top of node_modules.
368
376
  for name in names_inside(workspace, modules)[:1000]:
@@ -374,9 +382,12 @@ def installed(workspace, home, extra_prefixes=()):
374
382
  except (ValueError, KeyError, TypeError):
375
383
  version = None
376
384
  if isinstance(version, str):
377
- found[('node', package[:200], version[:80])] = None
378
- sites = ([(workspace, posixpath.join(env, 'lib')) for env in ('.venv', 'venv')] if workspace else []) + ([(home, '.local/lib')] if home else [])
385
+ found[('node', package[:200], version[:80], container_modules[:300])] = None
386
+ sites = ([(workspace, posixpath.join(env, 'lib'), posixpath.normpath(WORKSPACE + posixpath.join(env, 'lib'))) for env in ('.venv', 'venv')] if workspace else []) \
387
+ + ([(home, '.local/lib', '/home/node/.local/lib')] if home else [])
379
388
  direct_sites = []
389
+ seen_sites = {(v, lib) for v, lib, _ in sites}
390
+ seen_direct = set()
380
391
  for prefix in extra_prefixes or ():
381
392
  if not isinstance(prefix, str) or not prefix:
382
393
  continue
@@ -384,24 +395,30 @@ def installed(workspace, home, extra_prefixes=()):
384
395
  if workspace and (norm == WORKSPACE.rstrip('/') or norm.startswith(WORKSPACE)):
385
396
  rel = norm[len(WORKSPACE):] if norm.startswith(WORKSPACE) else ''
386
397
  lib = posixpath.join(rel, 'lib') if rel else 'lib'
387
- if (workspace, lib) not in sites:
388
- sites.append((workspace, lib))
389
- if rel and (workspace, rel) not in direct_sites:
390
- direct_sites.append((workspace, rel))
398
+ container_lib = posixpath.join(norm, 'lib')
399
+ if (workspace, lib) not in seen_sites:
400
+ seen_sites.add((workspace, lib))
401
+ sites.append((workspace, lib, container_lib))
402
+ if rel and (workspace, rel) not in seen_direct:
403
+ seen_direct.add((workspace, rel))
404
+ direct_sites.append((workspace, rel, norm))
391
405
  elif home and norm.startswith('/home/'):
392
406
  parts = PurePosixPath(norm).parts # ('/', 'home', '<user>', ...)
393
407
  if len(parts) >= 4:
394
408
  rel = posixpath.join(*parts[3:])
395
409
  lib = posixpath.join(rel, 'lib')
396
- if (home, lib) not in sites:
397
- sites.append((home, lib))
398
- if (home, rel) not in direct_sites:
399
- direct_sites.append((home, rel))
400
- for volume, lib in sites:
410
+ container_lib = posixpath.join(norm, 'lib')
411
+ if (home, lib) not in seen_sites:
412
+ seen_sites.add((home, lib))
413
+ sites.append((home, lib, container_lib))
414
+ if (home, rel) not in seen_direct:
415
+ seen_direct.add((home, rel))
416
+ direct_sites.append((home, rel, norm))
417
+ for volume, lib, container_lib in sites:
401
418
  for python in names_inside(volume, lib)[:10]:
402
- _scan_pip_site(found, volume, posixpath.join(lib, python, 'site-packages'))
403
- for volume, site in direct_sites:
404
- _scan_pip_site(found, volume, site)
419
+ _scan_pip_site(found, volume, posixpath.join(lib, python, 'site-packages'), posixpath.join(container_lib, python, 'site-packages'))
420
+ for volume, site, container_site in direct_sites:
421
+ _scan_pip_site(found, volume, site, container_site)
405
422
  return found
406
423
 
407
424
 
@@ -940,6 +957,15 @@ class Engine(threading.Thread):
940
957
  if guard is None:
941
958
  if writing and not errno and box.guarded:
942
959
  box.aliases.append({'path': path, 'who': who, 'at_ns': at_ns, 'syscall': self.calls.get(event.get('sysno'), ('open', 'open'))[0]})
960
+ elif not writing and not errno and not who.get('own'):
961
+ announced_who = self.called(box, who, path, at_ns)
962
+ if announced_who.get('call_from') == 'tool_report':
963
+ call = self.calls.get(event.get('sysno'), ('open', 'open'))[0]
964
+ self.fact(box, 'file', (path, 'read'), announced_who,
965
+ {'path': path, 'guard': None, 'effect': 'read', 'certainty': 'confirmed',
966
+ 'basis': {'syscall': call, 'flags': flags, 'resolution': 'lexical',
967
+ 'note': 'opened for reading; the bytes read are not captured'}}, at_ns)
968
+ return
943
969
  return self.counted(box, who, top, at_ns)
944
970
  who = self.called(box, who, path, at_ns)
945
971
  call = self.calls.get(event.get('sysno'), ('open', 'open'))[0]
@@ -953,7 +979,9 @@ class Engine(threading.Thread):
953
979
  if not writing:
954
980
  # Reads of ordinary files are counted, as before: a test run reads hundreds.
955
981
  # So is the snapshot hook reading every file after each tool call.
956
- if guard == 'project' or who.get('own'):
982
+ # An explicit agent Read tool call announced by the hook (`call_from=tool_report`)
983
+ # is recorded as a confirmed read fact from the kernel open syscall (#156).
984
+ if (guard == 'project' and who.get('call_from') != 'tool_report') or who.get('own'):
957
985
  return self.counted(box, who, top, at_ns)
958
986
  self.fact(box, 'file', (path, 'read'), who, {'path': path, 'guard': guard, 'effect': 'read', 'certainty': 'confirmed',
959
987
  'basis': {**basis, 'note': 'opened for reading; the bytes read are not captured'}}, at_ns)
@@ -1324,13 +1352,13 @@ class Engine(threading.Thread):
1324
1352
  who = box.package_who or {}
1325
1353
  # Seen reaching a registry about then: the list is the manager's own word, with that beside it.
1326
1354
  certainty = 'corroborated' if self.clock() - box.registry_at < 300 else 'reported'
1327
- for manager in sorted({key[0] for key in fresh}):
1328
- mine = [key for key in fresh if key[0] == manager]
1329
- fact = self.fact(box, 'package', (manager,), who, {'manager': manager, 'packages': [], 'total': 0, 'effect': 'installed',
1355
+ for manager, site_dir in sorted({(key[0], key[3]) for key in fresh}):
1356
+ mine = [key for key in fresh if key[0] == manager and key[3] == site_dir]
1357
+ fact = self.fact(box, 'package', (manager, site_dir), who, {'manager': manager, 'prefix': site_dir, 'packages': [], 'total': 0, 'effect': 'installed',
1330
1358
  'basis': {'note': "read from the package manager's own records in the sandbox after it ran; the agent can write those files"}},
1331
1359
  time.time_ns())
1332
1360
  fact['certainty'] = certainty
1333
1361
  fact['total'] += len(mine)
1334
1362
  room = MAX_PACKAGES - len(fact['packages'])
1335
- fact['packages'] += [{'name': name, 'version': version, **({'source': now[(manager, name, version)]} if now[(manager, name, version)] else {})}
1336
- for _, name, version in mine[:max(0, room)]]
1363
+ fact['packages'] += [{'name': name, 'version': version, **({'source': now[(manager, name, version, site_dir)]} if now[(manager, name, version, site_dir)] else {})}
1364
+ for _, name, version, _ in mine[:max(0, room)]]
@@ -55,19 +55,29 @@ def event_page(db, query):
55
55
  clauses.append("kind IN ('exec_succeeded','exec_failed','process_exit','collection_gap','collection_error','collector_connected','collector_disconnected')")
56
56
  where = ' WHERE ' + ' AND '.join(clauses) if clauses else ''
57
57
  order = 'ASC' if 'after' in query else 'DESC'
58
- rows = db.execute('SELECT id,body,container_id FROM runtime_events'+where+' ORDER BY id '+order+' LIMIT ?', (*params, limit+1)).fetchall()
59
- events = []
60
- for identifier, body, bound_container in rows[:limit]:
61
- event=json.loads(body); event.pop('raw_packet_base64',None)
62
- event['event_id']=identifier; event['container_id']=bound_container; events.append(event)
63
- page = {'events':events,'next_before':None if 'after' in query else (rows[limit-1][0] if len(rows)>limit else None)}
64
- if 'after' in query:
65
- page['next_after'] = rows[limit-1][0] if len(rows) > limit else None
66
- # Metadata comes from the same selected container and time interval,
67
- # independently of pagination or the processes-only display filter.
68
- page['coverage'] = coverage_page(db, query)
69
- page['gaps'] = page['coverage']['gaps']
70
- return page
58
+ # Hold a single SQLite read snapshot across the event select and
59
+ # coverage_page() so a process_exit written in between can never advance
60
+ # coverage.latest past the returned rows and make the forwarder skip it (#157).
61
+ started_tx = not db.in_transaction
62
+ if started_tx:
63
+ db.execute('BEGIN')
64
+ try:
65
+ rows = db.execute('SELECT id,body,container_id FROM runtime_events'+where+' ORDER BY id '+order+' LIMIT ?', (*params, limit+1)).fetchall()
66
+ events = []
67
+ for identifier, body, bound_container in rows[:limit]:
68
+ event=json.loads(body); event.pop('raw_packet_base64',None)
69
+ event['event_id']=identifier; event['container_id']=bound_container; events.append(event)
70
+ page = {'events':events,'next_before':None if 'after' in query else (rows[limit-1][0] if len(rows)>limit else None)}
71
+ if 'after' in query:
72
+ page['next_after'] = rows[limit-1][0] if len(rows) > limit else None
73
+ # Metadata comes from the same selected container and time interval,
74
+ # independently of pagination or the processes-only display filter.
75
+ page['coverage'] = coverage_page(db, query)
76
+ page['gaps'] = page['coverage']['gaps']
77
+ return page
78
+ finally:
79
+ if started_tx and db.in_transaction:
80
+ db.execute('COMMIT')
71
81
 
72
82
 
73
83
  def coverage_page(db, query):
@@ -113,10 +123,17 @@ def fact_page(db, query):
113
123
  clauses, params = ['id > ?'], [after]
114
124
  if container:
115
125
  clauses.append('container_id = ?'); params.append(container)
116
- rows = db.execute('SELECT id, body FROM facts WHERE ' + ' AND '.join(clauses) + ' ORDER BY id LIMIT ?', (*params, limit + 1)).fetchall()
117
- facts = [{**json.loads(body), 'id': identifier} for identifier, body in rows[:limit]]
118
- latest = db.execute("SELECT seq FROM sqlite_sequence WHERE name = 'facts'").fetchone()
119
- return {'facts': facts, 'next_after': facts[-1]['id'] if len(rows) > limit else None, 'latest': latest[0] if latest else 0}
126
+ started_tx = not db.in_transaction
127
+ if started_tx:
128
+ db.execute('BEGIN')
129
+ try:
130
+ rows = db.execute('SELECT id, body FROM facts WHERE ' + ' AND '.join(clauses) + ' ORDER BY id LIMIT ?', (*params, limit + 1)).fetchall()
131
+ facts = [{**json.loads(body), 'id': identifier} for identifier, body in rows[:limit]]
132
+ latest = db.execute("SELECT seq FROM sqlite_sequence WHERE name = 'facts'").fetchone()
133
+ return {'facts': facts, 'next_after': facts[-1]['id'] if len(rows) > limit else None, 'latest': latest[0] if latest else 0}
134
+ finally:
135
+ if started_tx and db.in_transaction:
136
+ db.execute('COMMIT')
120
137
 
121
138
  PAGE = '''<!doctype html><meta charset="utf-8"><title>RayTrace runtime evidence</title>
122
139
  <style>body{font:15px system-ui;background:#111827;color:#e5e7eb;margin:32px}table{width:100%;border-collapse:collapse}td,th{text-align:left;padding:10px;border-bottom:1px solid #374151}code{white-space:pre-wrap}select{padding:8px} .note{color:#fbbf24}</style>