Find code by asking what it does. A CLI for coding agents that uses Jev to discover relevant files and source context.
TypeScript ai-sdkclaude-codeclicode-searchcodexcoding-agentscontext-retrievaldeveloper-toolsjevsemantic-searchtypescriptvercel-ai-gateway
Exclude standalone retrieval waits from prospective treatment work clock
David Zhang7bf053654322
diff --git a/evals/implementation/swebench/installed.md b/evals/implementation/swebench/installed.mdindex 6cd656d..6e2c65c 100644--- a/evals/implementation/swebench/installed.md+++ b/evals/implementation/swebench/installed.md@@ -73,3 +73,28 @@ benchmark source and remain local with the ignored study evidence.[Focused tests](test_installed.py) run in an isolated Docker container. They coverprompt identity, drift rejection, no-call validation, retained attempts, incompletebilling, cohort acceptance and exact body capture through a synthetic provider.++## Treatment work clock++New schema-3 plans freeze a 900-second treatment **work** budget. The monitor uses+host monotonic observation of native `command_execution` started/completed events.+It excludes the union of standalone `jg` search waits only while no other command+is active. Overlapping retrieval calls earn no double credit; unrelated concurrent+commands count as work. Completion, cancellation, terminal turns and process EOF+end credit. A separate 24-hour wall limit protects against a runaway retrieval.+Receipts retain work, credited retrieval and wall durations plus the disjoint+credit intervals and native command IDs, so timing remains auditable.++The recognizer accepts a direct installed `jg` search, including the native shell+wrapper. It gives no credit to auth, doctor, cache, skill, help/version, compound+commands, redirections or shell expansions. Ambiguous invocations count as work.+Event-observation timestamps measure what the harness sees, not provider execution+time; malformed timing events invalidate the timing evidence rather than inventing+credit. Process startup and time outside qualifying waits count toward work.++The treatment prompt states this clock explicitly; its timing sentence therefore+differs from the retained baseline prompt. Baseline prompt bytes, receipts, model,+grading and the solve/Sol-cost acceptance rule are unchanged. This correction does+not rescore old attempts or explain away earlier task failures. Schema-2 studies+remain usable with their archived runner and wall-clock policy; the current runner+requires a fresh schema-3 plan and rejects timing-policy drift.diff --git a/evals/implementation/swebench/installed.py b/evals/implementation/swebench/installed.pyindex fc4a257..f429a90 100644--- a/evals/implementation/swebench/installed.py+++ b/evals/implementation/swebench/installed.py@@ -9,6 +9,8 @@ import osfrom pathlib import Pathimport reimport shutil+import shlex+import selectorsimport subprocessimport timeimport urllib.parse@@ -19,6 +21,11 @@ HERE = Path(__file__).resolve().parentROOT = HERE.parents[2]REGISTRY = json.loads((HERE / 'fixed-baselines.json').read_text())HARNESS_COMMIT = '02e7a74ffd0b707aab73d203fe87bdc7c76afc8e'+TIMING_POLICY = {'clock': 'work_excluding_standalone_jg_search_wait', 'work_seconds': 900,+ 'hard_wall_seconds': 86400, 'overlapping_other_commands': 'count_as_work',+ 'event_clock': 'host_monotonic_observation'}+TREATMENT_TIMING = ('The task, including verification, has a 900-second work budget, excluding time waiting for standalone jg search commands when no other command is running. '+ 'Other commands, compound commands, and concurrent work count toward that budget; a 24-hour wall-clock guard stops runaway attempts. ')SAFE_FIELDS = {'instance_id', 'repo', 'base_commit', 'image', 'problem_statement'}VERSIONS = {'node': 'v24.14.0', 'codex': 'codex-cli 0.153.4', 'claude': '2.1.278 (Claude Code)'}VERIFICATION = (@@ -44,7 +51,8 @@ def baseline_prompt(row):def treatment_prompt(row):- return '$jevgrep\n\n' + baseline_prompt(row)+ return '$jevgrep\n\n' + baseline_prompt(row).replace(+ 'The entire task, including verification, has a 900-second deadline. ', TREATMENT_TIMING, 1)def digest(path):@@ -165,7 +173,7 @@ tar -C /opt -cf /tmp/installed-prefix.tar jg-installfor source in [Path(__file__).resolve(), HERE / 'gateway_broker.py', HERE / 'fixed-baselines.json']:shutil.copyfile(source, frozen / source.name)artifacts = [*frozen.iterdir(), package, out / 'installed-prefix.tar', out / 'skill.md', out / 'agent-inputs.json', root / REGISTRY['dataset']]- plan = {'schema': 2, 'status': 'frozen', 'cells': cells,+ plan = {'schema': 3, 'timing_policy': dict(TIMING_POLICY), 'status': 'frozen', 'cells': cells,'purpose': 'One prospective package cohort; reuse fixed baselines without execution.','inputs': str(out / 'agent-inputs.json'), 'skill': str(out / 'skill.md'), 'package': str(package),'runner': str(frozen / 'installed.py'), 'broker': str(frozen / 'gateway_broker.py'),@@ -180,8 +188,10 @@ tar -C /opt -cf /tmp/installed-prefix.tar jg-installdef load_cohort(path):plan = json.loads(path.read_text())- if plan.get('schema') != 2 or plan.get('status') != 'frozen':- raise ValueError('Expected a frozen prospective cohort plan')+ if plan.get('schema') != 3 or plan.get('status') != 'frozen':+ raise ValueError('Expected a frozen schema-3 cohort; use the archived runner for older studies')+ if plan.get('timing_policy') != TIMING_POLICY:+ raise ValueError('Frozen treatment timing policy changed')for artifact, expected in plan['artifacts'].items():if digest(artifact) != expected:raise ValueError('Frozen artifact changed: ' + artifact)@@ -245,6 +255,142 @@ def existing_attempt(plan):return True+def direct_jg_search(command):+ """Recognize a standalone invocation, never a shell program that also runs jg."""+ try:+ argv = shlex.split(command)+ if len(argv) == 3 and argv[0] in ('/bin/sh', '/bin/bash', 'sh', 'bash') and argv[1] in ('-c', '-lc'):+ command = argv[2]+ # Expansions and shell operators can execute additional work. Quoted query+ # punctuation is data; shlex keeps it within its argument.+ if any(character in command for character in '$`\n\r'):+ return False+ raw = shlex.shlex(command, posix=False, punctuation_chars=';&|<>()')+ raw.whitespace_split, raw.commenters = True, ''+ if any(not token.startswith(('\"', "'")) and any(char in token for char in '*?[{~') for token in raw):+ return False+ lexer = shlex.shlex(command, posix=True, punctuation_chars=';&|<>()')+ lexer.whitespace_split = True+ lexer.commenters = ''+ argv = list(lexer)+ if not argv or argv[0] not in ('jg', '/opt/jg-install/bin/jg'):+ return False+ if any(re.fullmatch(r'[;&|<>()]+', token) for token in argv):+ return False+ positionals, options = [], True+ index = 1+ while index < len(argv):+ arg = argv[index]+ if options and arg == '--':+ options = False+ elif options and arg in ('--no-cache', '--hidden', '--no-ignore', '--include-dependencies', '--include-sensitive'):+ pass+ elif options and arg == '--max-source-bytes':+ index += 1+ if index >= len(argv) or not argv[index].isdigit():+ return False+ elif options and arg.startswith('--max-source-bytes='):+ if not arg.split('=', 1)[1].isdigit():+ return False+ elif options and arg.startswith('-'):+ return False+ else:+ positionals.append(arg)+ index += 1+ return (1 <= len(positionals) <= 2 and bool(positionals[0].strip()) and+ positionals[0] not in ('auth', 'doctor', 'cache', 'skill'))+ except ValueError:+ return False+++def monitor_native(invocation, stdout, stderr, policy):+ """Charge wall time except observed standalone retrieval with no other command active."""+ started = time.monotonic()+ active, intervals = {}, []+ credit_start, credited, errors = None, 0.0, 0+ timed_out, timeout_kind = False, None++ def close_credit(now):+ nonlocal credit_start, credited+ if credit_start is not None:+ intervals.append({'start_seconds': credit_start - started, 'end_seconds': now - started,+ 'command_ids': sorted(active)})+ credited += now - credit_start+ credit_start = None++ def event(line, now):+ nonlocal credit_start, errors+ try:+ value = json.loads(line)+ item = value.get('item', {})+ kind = value.get('type')+ if kind in ('turn.completed', 'turn.failed', 'error'):+ close_credit(now)+ active.clear()+ elif kind in ('item.started', 'item.completed') and item.get('type') == 'command_execution':+ identifier = item.get('id')+ if not isinstance(identifier, str):+ raise ValueError('Missing command identity')+ close_credit(now)+ if kind == 'item.started':+ if identifier in active:+ errors += 1+ active[identifier] = direct_jg_search(item.get('command', ''))+ else:+ if identifier not in active:+ errors += 1+ active.pop(identifier, None)+ if active and all(active.values()):+ credit_start = now+ except (ValueError, TypeError, AttributeError):+ errors += 1+ close_credit(now)+ active.clear()++ process = subprocess.Popen(invocation, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=stderr)+ pending = b''+ try:+ with selectors.DefaultSelector() as selector:+ selector.register(process.stdout, selectors.EVENT_READ)+ while selector.get_map() or process.poll() is None:+ now = time.monotonic()+ retrieval = credited + (now - credit_start if credit_start is not None else 0)+ work = now - started - retrieval+ if work >= policy['work_seconds'] or now - started >= policy['hard_wall_seconds']:+ timed_out = True+ timeout_kind = 'work' if work >= policy['work_seconds'] else 'hard_wall'+ break+ if not selector.get_map():+ time.sleep(0.05)+ continue+ for key, _ in selector.select(0.05):+ chunk = os.read(key.fd, 65536)+ if not chunk:+ selector.unregister(key.fileobj)+ close_credit(time.monotonic())+ active.clear()+ continue+ stdout.write(chunk)+ stdout.flush()+ pending += chunk+ while b'\n' in pending:+ line, pending = pending.split(b'\n', 1)+ event(line, time.monotonic())+ finally:+ close_credit(time.monotonic())+ if process.poll() is None:+ process.kill()+ process.wait()+ process.stdout.close()+ elapsed = time.monotonic() - started+ if pending.strip():+ errors += 1+ return {'exit_code': process.returncode, 'timed_out': timed_out, 'timeout_kind': timeout_kind,+ 'wall_seconds': elapsed, 'work_seconds': elapsed - credited,+ 'retrieval_wait_seconds': credited, 'credit_intervals': intervals,+ 'timing_event_errors': errors}++def run(args):plan, row = load_plan(args.plan.resolve(), args.task)cell = plan['cell']@@ -324,15 +470,15 @@ def run(args):write_json(out / 'receipt.json', receipt)start = time.monotonic()with (out / 'events.jsonl').open('wb') as stdout, (out / 'stderr.txt').open('wb') as stderr:- try:- result = subprocess.run(invocation, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr, timeout=900)- receipt['exit_code'] = result.returncode- except subprocess.TimeoutExpired:- receipt['timed_out'] = True+ receipt['timing_policy'] = plan['timing_policy']+ receipt['timing'] = monitor_native(invocation, stdout, stderr, plan['timing_policy'])+ receipt['exit_code'] = receipt['timing']['exit_code']+ receipt['timed_out'] = receipt['timing']['timed_out']+ if receipt['timed_out']:subprocess.run(['docker', 'exec', tag, 'pkill', '-KILL', '-u', '1001'], capture_output=True)receipt['agent_elapsed_seconds'] = time.monotonic() - startreceipt['agent_finished_at'] = time.time()- receipt['timing_valid'] = abs(receipt['agent_finished_at'] - receipt['agent_started_at'] - receipt['agent_elapsed_seconds']) <= 5+ receipt['timing_valid'] = receipt['timing']['timing_event_errors'] == 0 and abs(receipt['agent_finished_at'] - receipt['agent_started_at'] - receipt['agent_elapsed_seconds']) <= 5events = []for line in (out / 'events.jsonl').read_text().splitlines():try: events.append(json.loads(line))diff --git a/evals/implementation/swebench/test_installed.py b/evals/implementation/swebench/test_installed.pyindex db745ec..a07e58b 100644--- a/evals/implementation/swebench/test_installed.py+++ b/evals/implementation/swebench/test_installed.py@@ -8,6 +8,7 @@ import importlib.utilimport ioimport jsonimport os+import sysfrom pathlib import Pathimport tempfileimport threading@@ -31,8 +32,108 @@ class InstalledTests(unittest.TestCase):self.assertEqual(hashlib.sha256(runner.baseline_prompt(row).encode()).hexdigest(), '41c7e3cf7acbc19d0b24ab55e6ea29fe3cdbc2b777549d158488c6c55baaa643')prompt = runner.treatment_prompt(row)self.assertTrue(prompt.startswith('$jevgrep\n\n'))- self.assertEqual(prompt, '$jevgrep\n\n' + runner.baseline_prompt(row))- self.assertTrue(prompt.endswith(runner.baseline_prompt(row)))+ self.assertEqual(prompt, '$jevgrep\n\n' + runner.baseline_prompt(row).replace(+ 'The entire task, including verification, has a 900-second deadline. ', runner.TREATMENT_TIMING, 1))+ self.assertTrue(prompt.endswith(runner.VERIFICATION + '\n\nFix behavior.'))++ def monitor(self, steps, work_seconds=2, hard_wall_seconds=10):+ script = "import json,time\n" + "\n".join(+ "time.sleep(%r)" % step if isinstance(step, (int, float)) else+ "print(%r, flush=True)" % json.dumps(step) for step in steps)+ with tempfile.TemporaryDirectory() as temporary:+ with open(Path(temporary)/'events.jsonl', 'wb') as stdout, open(Path(temporary)/'stderr', 'wb') as stderr:+ result = runner.monitor_native([sys.executable, '-u', '-c', script], stdout, stderr,+ {**runner.TIMING_POLICY, 'work_seconds':work_seconds,+ 'hard_wall_seconds':hard_wall_seconds})+ events = (Path(temporary)/'events.jsonl').read_text()+ return result, events++ def event(self, identifier, command, completed=False, **extra):+ return {'type':'item.completed' if completed else 'item.started',+ 'item':{'id':identifier,'type':'command_execution','command':command,**extra}}++ def test_direct_jg_wait_does_not_consume_work_budget(self):+ command = "/bin/sh -lc 'jg \"research the mechanism\"'"+ result, events = self.monitor([self.event('search', command), 3.2,+ self.event('search', command, True), {'type':'turn.completed'}])+ self.assertEqual(result['exit_code'], 0)+ self.assertFalse(result['timed_out'])+ self.assertGreater(result['retrieval_wait_seconds'], 3)+ self.assertLess(result['work_seconds'], 2)+ self.assertEqual(result['credit_intervals'][0]['command_ids'], ['search'])+ self.assertIn('turn.completed', events)++ def test_unrelated_command_reaches_work_deadline(self):+ result, events = self.monitor([self.event('test', "python -m unittest"), 3,+ {'type':'turn.completed'}])+ self.assertTrue(result['timed_out'])+ self.assertEqual(result['timeout_kind'], 'work')+ self.assertEqual(result['retrieval_wait_seconds'], 0)+ self.assertGreaterEqual(result['work_seconds'], 2)+ self.assertNotIn('turn.completed', events)++ def test_cancelled_jg_stops_credit_and_remaining_work_times_out(self):+ command = 'jg "research"'+ result, events = self.monitor([self.event('search', command), 0.6,+ self.event('search', command, True, exit_code=130, status='failed'),+ 3, {'type':'turn.completed'}])+ self.assertTrue(result['timed_out'])+ self.assertEqual(result['timeout_kind'], 'work')+ self.assertGreater(result['retrieval_wait_seconds'], 0.4)+ self.assertGreaterEqual(result['work_seconds'], 2)+ self.assertEqual(len(result['credit_intervals']), 1)+ self.assertIn('"exit_code": 130', events)++ def test_other_command_overlap_counts_as_work(self):+ command = 'jg "research"'+ result, events = self.monitor([self.event('search', command), 0.6,+ self.event('test', 'python -m unittest'), 3,+ {'type':'turn.completed'}])+ self.assertTrue(result['timed_out'])+ self.assertEqual(result['timeout_kind'], 'work')+ self.assertGreater(result['retrieval_wait_seconds'], 0.4)+ self.assertGreaterEqual(result['work_seconds'], 2)+ self.assertEqual(result['credit_intervals'][0]['command_ids'], ['search'])+ self.assertNotIn('turn.completed', events)++ def test_overlapping_retrieval_is_union_not_double_credit(self):+ result, _ = self.monitor([self.event('a', 'jg "first"'), 0.3,+ self.event('b', 'jg "second"'), 0.6,+ self.event('a', 'jg "first"', True), 0.3,+ self.event('b', 'jg "second"', True), {'type':'turn.completed'}])+ self.assertEqual(result['exit_code'], 0)+ self.assertFalse(result['timed_out'])+ self.assertEqual([span['command_ids'] for span in result['credit_intervals']], [['a'], ['a', 'b'], ['b']])+ self.assertAlmostEqual(result['work_seconds'] + result['retrieval_wait_seconds'], result['wall_seconds'])+ self.assertLessEqual(result['retrieval_wait_seconds'], result['wall_seconds'])++ def test_hard_wall_stops_unfinished_retrieval(self):+ result, _ = self.monitor([self.event('search', 'jg "research"'), 5], work_seconds=4, hard_wall_seconds=1.5)+ self.assertTrue(result['timed_out'])+ self.assertEqual(result['timeout_kind'], 'hard_wall')+ self.assertTrue(result['credit_intervals'])++ def test_only_unambiguous_standalone_search_gets_credit(self):+ for command in ['jg "query with ; punctuation"', "/bin/sh -lc 'jg query'",+ 'jg --no-cache "query" /testbed', '/opt/jg-install/bin/jg "query" --max-source-bytes=0']:+ with self.subTest(command=command): self.assertTrue(runner.direct_jg_search(command))+ for command in ['jg', 'jg doctor', 'jg auth --stdin', 'jg cache clear', 'jg skill', 'jg --help',+ 'jg -h', 'jg --version', 'jg "query" --version', 'jg "query"; sleep 5',+ 'jg "query" && sleep 5', 'sleep 5 | jg "query"', 'jg "query" > out',+ 'jg "$(sleep 5)"', 'env KEY=value jg "query"', 'echo jg "query"', 'jg "query" &', 'jg doc*', 'jg auth?', 'jg {auth,doctor}',+ 'jg "query"\nsleep 5']:+ with self.subTest(command=command): self.assertFalse(runner.direct_jg_search(command))++ def test_timing_policy_drift_and_legacy_schema_require_their_archived_runner(self):+ with tempfile.TemporaryDirectory() as temporary:+ path, _ = self.fixture(Path(temporary))+ plan = json.loads(path.read_text())+ plan['timing_policy']['work_seconds'] = 901+ runner.write_json(path, plan)+ with self.assertRaisesRegex(ValueError, 'timing policy changed'): runner.load_cohort(path)+ plan['schema'] = 2+ runner.write_json(path, plan)+ with self.assertRaisesRegex(ValueError, 'archived runner'): runner.load_cohort(path)def fixture(self, root, all_tasks=False):registry = json.loads(json.dumps(runner.REGISTRY))@@ -57,7 +158,7 @@ class InstalledTests(unittest.TestCase):inputs = root / 'agent-inputs.json'; runner.write_json(inputs,rows)dataset=root/'dataset.json';dataset.write_text('fixture dataset')paths = [dataset,Path(runner.__file__),HERE/'gateway_broker.py',registry_path,inputs,skill,package,prefix]- plan = {'schema':2,'status':'frozen','cells':cells,'runner':str(Path(runner.__file__)),'broker':str(HERE/'gateway_broker.py'),+ plan = {'schema':3,'timing_policy':dict(runner.TIMING_POLICY),'status':'frozen','cells':cells,'runner':str(Path(runner.__file__)),'broker':str(HERE/'gateway_broker.py'),'registry':str(registry_path),'tooling':str(root/'tooling'),'dataset':str(root/'dataset.json'),'inputs':str(inputs),'skill':str(skill),'package':str(package),'artifacts':{str(p):runner.digest(p) for p in paths}}plan_path=root/'plan.json';runner.write_json(plan_path,plan)