@yahyahammad/venastine 0.3.17 → 0.3.19

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/main.py CHANGED
@@ -71,6 +71,11 @@ from security import posture, protected_paths
71
71
 
72
72
  logger = logging.getLogger(__name__)
73
73
 
74
+ #: ROADMAP_v3 §98. What a bare `--resume` parses to: list the runs that can be
75
+ #: resumed rather than resume one. A sentinel, not a string, so no run id can
76
+ #: collide with it -- GRANT_PICKER's shape, one flag over.
77
+ RESUME_LIST = object()
78
+
74
79
 
75
80
  class _Visible:
76
81
  """Every untrusted string one prompt prints, and whether any of them
@@ -2168,6 +2173,39 @@ def run_memory_command(args) -> int:
2168
2173
  return 0
2169
2174
 
2170
2175
 
2176
+ def run_resume_list() -> int:
2177
+ """A bare `--resume` (ROADMAP_v3 §98): the runs that can be resumed,
2178
+ newest first, and how to resume one. The CLI's picker, since a line
2179
+ shell has nothing to pick with. The first eight characters of an id
2180
+ are shown because they are what `--resume` needs."""
2181
+ from core.reasoning.resume import resumable_runs
2182
+ for line in resume_list_lines(resumable_runs()):
2183
+ print(line)
2184
+ return 0
2185
+
2186
+
2187
+ def resume_list_lines(runs) -> list:
2188
+ """The listing `run_resume_list` prints, as lines a test can read."""
2189
+ if not runs:
2190
+ return ["No failed or abandoned research run to resume."]
2191
+ lines = ["Research runs that can be resumed, newest first:"]
2192
+ for row in runs:
2193
+ status = ("stopped, or still running elsewhere"
2194
+ if row["status"] == "running" else row["status"])
2195
+ started = row["started_at"]
2196
+ when = (started.strftime("%Y-%m-%d %H:%M")
2197
+ if hasattr(started, "strftime") else str(started or ""))
2198
+ where = (f"cannot resume: {row['note']}" if row.get("note")
2199
+ else f"resumes {row['stage']}")
2200
+ query = ansi.for_display(str(row["user_query"]))
2201
+ if len(query) > 60:
2202
+ query = query[:59] + "…"
2203
+ lines.append(f" {str(row['id'])[:8]} {when} {status} {where}")
2204
+ lines.append(f" {query}")
2205
+ lines.append("Resume one with: venastine --resume <id>")
2206
+ return lines
2207
+
2208
+
2171
2209
  def run_summary_command(args, provider_name: str, model: str) -> int:
2172
2210
  """`--summary [thread]`, ROADMAP_v2 §21c (M21).
2173
2211
 
@@ -2392,6 +2430,7 @@ def run_research(
2392
2430
  review=None,
2393
2431
  subagent_review=None,
2394
2432
  effort: str | None = None,
2433
+ resume=None,
2395
2434
  ) -> None:
2396
2435
  """Run the full deep-research pipeline, write artifacts to disk,
2397
2436
  and print the results. ensemble_mode/ensemble_n come from
@@ -2411,11 +2450,27 @@ def run_research(
2411
2450
  §22: the pipeline is ITERATED, not called, so a run that takes many
2412
2451
  minutes says what it is doing while it does it. The CLI is where that
2413
2452
  matters most -- it is the shell an unattended run is usually launched
2414
- from, and it had nothing at all to show until the run ended."""
2453
+ from, and it had nothing at all to show until the run ended.
2454
+
2455
+ resume (ROADMAP_v3 §98) is a run id, or the start of one, to pick up
2456
+ instead of starting `query`. A run that fails, this time or that one,
2457
+ ends with the command that resumes it, because the id is otherwise
2458
+ printed only by a run that completed."""
2415
2459
  from core.reasoning.orchestrator import stream_deep_research_pipeline
2416
2460
  from core.reasoning.output_writer import write_run_artifacts
2461
+ from core.reasoning.resume import ResumeRefused, find_run
2417
2462
 
2418
- print(f"Running deep-research pipeline on: {query!r}")
2463
+ run_id = None
2464
+ if resume is not None:
2465
+ try:
2466
+ run_id = find_run(resume)
2467
+ except ResumeRefused as e:
2468
+ print(f"Cannot resume {ansi.for_display(resume)}: "
2469
+ f"{ansi.for_display(e)}.")
2470
+ raise SystemExit(1) from None
2471
+ print(f"Resuming research run {run_id}")
2472
+ else:
2473
+ print(f"Running deep-research pipeline on: {query!r}")
2419
2474
  print(f"Provider: {provider_name} | Model: {model} | "
2420
2475
  f"Effort: {effort or 'auto'}\n")
2421
2476
 
@@ -2426,6 +2481,7 @@ def run_research(
2426
2481
  ensemble_mode=ensemble_mode, ensemble_n=ensemble_n,
2427
2482
  authorization=authorization, review=review,
2428
2483
  subagent_review=subagent_review, effort=effort,
2484
+ resume=run_id,
2429
2485
  ):
2430
2486
  # §26: tool calls and code stages print here too. The CLI is
2431
2487
  # the shell an unattended run is launched from, so a
@@ -2473,6 +2529,10 @@ def run_research(
2473
2529
  print(f" .. {event.chars // 1000}k chars", flush=True)
2474
2530
  elif event.kind == "trace_line":
2475
2531
  print(f"- {ansi.for_display(event.text)}", flush=True)
2532
+ elif event.kind == "run_started":
2533
+ # §98. Kept, not printed: the id is what the failure line
2534
+ # below needs, and a completed run prints it at the end.
2535
+ run_id = event.text
2476
2536
  elif event.kind == "run_complete":
2477
2537
  run = event.run
2478
2538
  if run is None:
@@ -2482,11 +2542,20 @@ def run_research(
2482
2542
  raise RuntimeError(
2483
2543
  "Pipeline generator completed without yielding a "
2484
2544
  "run_complete event")
2545
+ except ResumeRefused as e:
2546
+ # §98. Refused before anything changed, so this is not a pipeline
2547
+ # failure and the run keeps the status it had.
2548
+ print(f"\nCannot resume run {run_id}: {ansi.for_display(e)}.")
2549
+ raise SystemExit(1) from None
2485
2550
  except Exception as e:
2486
2551
  logger.exception("Research pipeline failed")
2487
2552
  print(f"\nPipeline failed: {ansi.for_display(e)}")
2488
- print("If any partial results were persisted, they can be "
2489
- "inspected via the database.")
2553
+ if run_id:
2554
+ print(f"Completed passes are kept. Resume the run where it "
2555
+ f"stopped with: venastine --resume {run_id}")
2556
+ else:
2557
+ print("If any partial results were persisted, they can be "
2558
+ "inspected via the database.")
2490
2559
  raise SystemExit(1)
2491
2560
 
2492
2561
  output_dir = None
@@ -2661,6 +2730,21 @@ def build_parser() -> argparse.ArgumentParser:
2661
2730
  help="Research mode: skip the post-pipeline review even if "
2662
2731
  "settings.json or config.yaml turns it on.",
2663
2732
  )
2733
+ # ROADMAP_v3 §98. An optional value, which is safe here where --grant
2734
+ # was not: a resumed run takes no query, so there is no next token for
2735
+ # it to swallow by mistake. Bare, it lists the runs it could take.
2736
+ parser.add_argument(
2737
+ "--resume",
2738
+ nargs="?",
2739
+ const=RESUME_LIST,
2740
+ default=None,
2741
+ metavar="RUN_ID",
2742
+ help="Research mode: pick a failed or abandoned run up where it "
2743
+ "stopped -- completed passes are not run again. Give the run "
2744
+ "id (its first eight characters are enough); with no id, list "
2745
+ "the runs that can be resumed. Implies --mode research and "
2746
+ "takes the usual --grant/--attended/--review flags.",
2747
+ )
2664
2748
  parser.add_argument(
2665
2749
  "--tui",
2666
2750
  action="store_true",
@@ -3409,6 +3493,21 @@ def main(argv=None) -> int:
3409
3493
  if args.summary is not None:
3410
3494
  return run_summary_command(args, provider, model)
3411
3495
 
3496
+ # ROADMAP_v3 §98. --resume names a research run, so it implies the mode
3497
+ # rather than requiring it to be typed too. Checked here, ahead of the
3498
+ # validation below that wants a query for --mode research, because a
3499
+ # resumed run keeps its own query and must not be given another.
3500
+ if args.resume is not None:
3501
+ if args.tui:
3502
+ parser.error("--tui does not take --resume; use /research "
3503
+ "--resume inside the TUI.")
3504
+ if args.query:
3505
+ parser.error("--resume takes no query: a resumed run keeps the "
3506
+ "query it was started with.")
3507
+ args.mode = "research"
3508
+ if args.resume is RESUME_LIST:
3509
+ return run_resume_list()
3510
+
3412
3511
  # §24. Beside the others, and AFTER load_project_config for a reason the
3413
3512
  # rest do not share: the generator resolves its destination through
3414
3513
  # config_loader.get_project_path(), and reads the trust state that
@@ -3432,8 +3531,10 @@ def main(argv=None) -> int:
3432
3531
  # §16 ships the chat shell; research mode's coarse progress view
3433
3532
  # is driven from inside the TUI, not from a launch flag.
3434
3533
  parser.error("--tui does not take --mode research; use /research inside the TUI.")
3435
- if args.mode == "research" and not args.tui and not args.query:
3436
- parser.error("--mode research requires a positional query argument.")
3534
+ if (args.mode == "research" and not args.tui and not args.query
3535
+ and args.resume is None):
3536
+ parser.error("--mode research requires a positional query argument "
3537
+ "(or --resume, to pick up a run that stopped).")
3437
3538
  if args.tui and args.query:
3438
3539
  # The parser help says a positional query is "sent as the first
3439
3540
  # message", and tui.app.run() has no first-message parameter --
@@ -3574,6 +3675,7 @@ def main(argv=None) -> int:
3574
3675
  subagent_review=review_on,
3575
3676
  review=build_review_consent() if review_on else None,
3576
3677
  effort=effort,
3678
+ resume=args.resume,
3577
3679
  )
3578
3680
  else:
3579
3681
  thread_id = args.thread
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yahyahammad/venastine",
3
- "version": "0.3.17",
3
+ "version": "0.3.19",
4
4
  "description": "A from-scratch agentic harness: tool-using chat plus a ten-pass self-critiquing research pipeline.",
5
5
  "keywords": [
6
6
  "agent",
package/pyproject.toml CHANGED
@@ -18,7 +18,7 @@ build-backend = "setuptools.build_meta"
18
18
 
19
19
  [project]
20
20
  name = "venastine-research-harness"
21
- version = "0.3.17"
21
+ version = "0.3.19"
22
22
  description = "A from-scratch agentic harness: tool-using chat plus a ten-pass self-critiquing research pipeline."
23
23
  readme = "README.md"
24
24
  # The same words as package.json's `keywords`, in the same order: what a
@@ -234,6 +234,17 @@ _PEM_SEP = _PEM_BREAK + r"+[ \t]*"
234
234
  # key carries before its base64.
235
235
  _PEM_UNIT = r"(?:[A-Za-z0-9+/=]{16,}|(?:Proc-Type|DEK-Info):[^\r\n\\]*)"
236
236
 
237
+ # A token character that CLOSES AN ESCAPE, so a pattern that refuses to start
238
+ # after a token character still starts here: the second hex digit of `%3D`
239
+ # in a URL-encoded value, and the letter of `\n`, `\r` or `\t` in a
240
+ # JSON-escaped one. Batch 260 wrote it for GitHub's stateless form. Batch 268
241
+ # measured the same miss in every other pattern anchored that way: `hf_`,
242
+ # `ms-` and the JWT each passed whole after `%3D`, `\n` and `\t`, and the
243
+ # `Authorization` header after `\n`. They share this one copy. Each such
244
+ # start sits two characters after a `%` or a `\`, which none of their runs
245
+ # contains, so a pattern that was linear stays linear.
246
+ _AFTER_ESCAPE = r"(?<=%[0-9A-Fa-f]{2})|(?<=\\[nrt])"
247
+
237
248
  _SECRET_PATTERNS = [
238
249
  # OpenAI-style keys
239
250
  re.compile(r"sk-[a-zA-Z0-9]{20,}"),
@@ -292,14 +303,14 @@ _SECRET_PATTERNS = [
292
303
  # long run is a start that scans to the run's end: measured quadratic,
293
304
  # 99 s on a hostile megabyte against 0.03 s with it. A token character
294
305
  # is allowed before the prefix only where it closes an escape, `%3D`
295
- # or `\n`, since a URL-encoded or JSON-escaped token is still a token,
296
- # and the classic pattern catches those. Each of those starts sits two
297
- # characters after a `%` or a `\`, which no run contains, so the scan
298
- # stays linear.
306
+ # or `\n` (`_AFTER_ESCAPE`), since a URL-encoded or JSON-escaped token
307
+ # is still a token, and the classic pattern catches those. Each of those
308
+ # starts sits two characters after a `%` or a `\`, which no run
309
+ # contains, so the scan stays linear.
299
310
  # This pattern runs BEFORE the classic one, because a 36-character
300
311
  # alphanumeric run inside a segment would otherwise take a piece of
301
312
  # the token and leave the rest standing.
302
- re.compile(r"(?:(?<![A-Za-z0-9_-])|(?<=%[0-9A-Fa-f]{2})|(?<=\\[nrt]))"
313
+ re.compile(r"(?:(?<![A-Za-z0-9_-])|" + _AFTER_ESCAPE + r")"
303
314
  r"gh[ousr]_[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}"
304
315
  r"\.[A-Za-z0-9_-]{20,}"),
305
316
  # GitHub OAuth, user-to-server, server-to-server and refresh tokens
@@ -316,14 +327,21 @@ _SECRET_PATTERNS = [
316
327
  # --- the rest of the list.
317
328
  # Hugging Face user access tokens and OAuth access tokens. An
318
329
  # identifier like `hf_hub_download` breaks the run of word characters
319
- # at its second underscore and is not matched.
320
- re.compile(r"(?<![A-Za-z0-9])hf_(?:oauth_)?[A-Za-z0-9]{30,}"),
330
+ # at its second underscore and is not matched. An escape's closing
331
+ # character may come before the prefix (`_AFTER_ESCAPE`, batch 268):
332
+ # before that, `%3Dhf_...` and `\nhf_...` were neither redacted nor
333
+ # refused.
334
+ re.compile(r"(?:(?<![A-Za-z0-9])|" + _AFTER_ESCAPE + r")"
335
+ r"hf_(?:oauth_)?[A-Za-z0-9]{30,}"),
321
336
  # OpenRouter keys, which `sk-` above misses at the second hyphen
322
337
  re.compile(r"sk-or-v1-[A-Za-z0-9]{32,}"),
323
338
  # ModelScope access tokens in their prefixed form: `ms-` and a UUID. A
324
339
  # bare UUID is NOT matched -- thread ids are UUIDs -- and neither is one
325
- # that merely ENDS a word like `items-<uuid>`.
326
- re.compile(r"(?<![A-Za-z0-9])ms-[0-9a-f]{8}-[0-9a-f]{4}"
340
+ # that merely ENDS a word like `items-<uuid>`. An escape's closing
341
+ # character is not a word (`_AFTER_ESCAPE`, batch 268), so `%3Dms-...`
342
+ # and `\nms-...` are matched, as `hf_` is.
343
+ re.compile(r"(?:(?<![A-Za-z0-9])|" + _AFTER_ESCAPE + r")"
344
+ r"ms-[0-9a-f]{8}-[0-9a-f]{4}"
327
345
  r"-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"),
328
346
  ]
329
347
 
@@ -426,19 +444,26 @@ _ASSIGNMENT_RE = re.compile(
426
444
  # `Digest username=...`, whose secret is not one value, is left alone. A
427
445
  # value with NO scheme word must also be 16 characters and carry a digit,
428
446
  # because API documentation writes "Authorization: required" and a bare
429
- # 8-character floor redacted the word.
447
+ # 8-character floor redacted the word. The header may follow an escape's
448
+ # closing character (`_AFTER_ESCAPE`, batch 268), case-sensitively, since
449
+ # `\b` fails between the `n` of a JSON-escaped `\n` and the header name: a
450
+ # captured request's `\nAuthorization: Bearer ...` passed whole before it.
430
451
  # Groups: 1 header name, 2 separator, 3 scheme (or None).
431
452
  _AUTH_HEADER_RE = re.compile(
432
- r"(?i)\b((?:proxy-)?authorization)([\"']?\s*[:=]\s*[\"']?)"
453
+ r"(?i)(?:\b|(?-i:" + _AFTER_ESCAPE + r"))"
454
+ r"((?:proxy-)?authorization)([\"']?\s*[:=]\s*[\"']?)"
433
455
  r"(?:((?:bearer|basic|token)\s+)[A-Za-z0-9._~+/=\-]{8,}"
434
456
  r"|(?=[A-Za-z._~+/=\-]*[0-9])[A-Za-z0-9._~+/=\-]{16,})")
435
457
 
436
458
  # A JSON Web Token, whole: three base64url segments, the first two of
437
459
  # which open with `eyJ` because both are JSON objects (`{"`). A bearer
438
460
  # credential wherever it appears, and the shape `_AUTH_HEADER_RE` cannot
439
- # reach when the token is pasted without its header.
461
+ # reach when the token is pasted without its header. It may follow an
462
+ # escape's closing character (`_AFTER_ESCAPE`, batch 268), where `\b` fails:
463
+ # `%3DeyJ...` and `\neyJ...` passed whole before that.
440
464
  _JWT_RE = re.compile(
441
- r"\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}")
465
+ r"(?:\b|" + _AFTER_ESCAPE + r")"
466
+ r"eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}")
442
467
 
443
468
  # The END of a PEM key block whose BEGIN is not in this string: the footer
444
469
  # and the run of base64 lines above it. The vendor pattern takes a block
@@ -1065,7 +1090,23 @@ def check_output_policy(tool_name: str, result: dict) -> dict:
1065
1090
  # claims and reports constantly, and refusing every mention would make the
1066
1091
  # blocklist unusable while blocking nothing an attacker couldn't rephrase.
1067
1092
  # fetch_url.py keeps its own bare-domain check for the value it is given.
1068
- _URL_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9+.\-]*://[^\s\"'<>]+")
1093
+ #
1094
+ # The scan starts once per RUN of scheme characters (TECHNICAL_DEBT 117,
1095
+ # batch 268). It used to be `[a-zA-Z][a-zA-Z0-9+.\-]*://...`, tried at every
1096
+ # letter, and on one long run of letters and digits each try scanned to the
1097
+ # run's end before failing to find `://`. That was quadratic: 4.8 s at
1098
+ # 100 KB and 441 s at a megabyte, before the handler ran. Now the lookbehind
1099
+ # refuses every start inside a run, the run's leading digits and `+.-` are
1100
+ # skipped, and the group captures from the run's first letter, which is
1101
+ # where the old pattern's leftmost match began. So `findall`, which returns
1102
+ # that one group, gives exactly the list it gave before (`0https://h` still
1103
+ # gives `https://h`), and the blocklist reads the same strings. Measured:
1104
+ # 0.05 s or less on each of ten hostile megabytes, and the old pattern's
1105
+ # list on 303,000 random strings. The shape the register recorded, a scheme
1106
+ # bounded to 32 characters, was linear too, but it found nothing in `a` and
1107
+ # 40 digits before `://evil.com`, where today's scan finds the host.
1108
+ _URL_RE = re.compile(
1109
+ r"(?<![a-zA-Z0-9+.\-])[0-9+.\-]*([a-zA-Z][a-zA-Z0-9+.\-]*://[^\s\"'<>]+)")
1069
1110
 
1070
1111
 
1071
1112
  def _input_leaf(text: str) -> str:
package/storage.py CHANGED
@@ -825,11 +825,24 @@ def _ordered_rows(thread_id: UUID) -> list[dict]:
825
825
  # ROADMAP_v3 §81 (IM2). NULL for every row that attached no
826
826
  # image; the compactor's size proxy reads it (IM8).
827
827
  "images": m.images,
828
+ # ROADMAP_v3 §98 (RS6): when a tool result arrived, which a
829
+ # resumed run's rebuilt corpus keeps as the page's
830
+ # retrieved_at. The ordering above already reads it.
831
+ "created_at": m.created_at,
828
832
  }
829
833
  for m in session.exec(statement).all()
830
834
  ]
831
835
 
832
836
 
837
+ def tool_result_times(thread_id: UUID) -> dict:
838
+ """When each tool result in a thread was written, by tool_call_id
839
+ (ROADMAP_v3 §98, RS6). Over `_ordered_rows`, so the suite's fake
840
+ storage answers it through the one read it already mirrors."""
841
+ return {row["tool_call_id"]: row.get("created_at")
842
+ for row in _ordered_rows(thread_id)
843
+ if row["role"] == "tool" and row["tool_call_id"]}
844
+
845
+
833
846
  def _split_at(rows: list[dict], message_id: Optional[UUID]) -> int:
834
847
  """Index just past `message_id` in `rows`, or 0 when it isn't there.
835
848
 
package/tui/app.py CHANGED
@@ -112,6 +112,7 @@ from tui.screens import (
112
112
  PermissionScreen,
113
113
  ProjectKindScreen,
114
114
  QuestionScreen,
115
+ ResumeRunPickerScreen,
115
116
  ReviewScreen,
116
117
  SecretScreen,
117
118
  SessionKillScreen,
@@ -5382,6 +5383,10 @@ class VenastineApp(App):
5382
5383
  event.claim_id, {"id": event.claim_id})
5383
5384
  claim["retry_count"] = event.attempt
5384
5385
  panel.retried()
5386
+ elif event.kind == "run_started":
5387
+ # §98. Kept for _write_resume_hint, and not drawn: a completed
5388
+ # run prints its id at the end, and a failed one in the hint.
5389
+ self._research_run_id = event.text
5385
5390
 
5386
5391
  def on_research_finished(self, message: ResearchFinished) -> None:
5387
5392
  self._busy = False
@@ -5396,9 +5401,17 @@ class VenastineApp(App):
5396
5401
  "[run abandoned — quit requested. Checkpoints so far are "
5397
5402
  "kept; the run's record stays 'running' rather than "
5398
5403
  "claiming completion.]")
5404
+ self._write_resume_hint()
5399
5405
  return
5400
5406
  if message.error is not None:
5407
+ from core.reasoning.resume import ResumeRefused
5408
+ if isinstance(message.error, ResumeRefused):
5409
+ # §98. Nothing ran, so this is not "pipeline failed".
5410
+ self._transcript.write_error(
5411
+ f"[cannot resume: {message.error}]")
5412
+ return
5401
5413
  self._write_failure(message.error, "pipeline failed")
5414
+ self._write_resume_hint()
5402
5415
  return
5403
5416
  run = message.run
5404
5417
  self._last_run = run
@@ -5426,6 +5439,16 @@ class VenastineApp(App):
5426
5439
  if run.run_id:
5427
5440
  self._transcript.write_system(f"[run id: {run.run_id}]")
5428
5441
 
5442
+ def _write_resume_hint(self) -> None:
5443
+ """How to pick up a run that failed or was abandoned (ROADMAP_v3
5444
+ §98), once its id is known -- the run_started event carries it, and
5445
+ the exception that ended the run does not."""
5446
+ run_id = getattr(self, "_research_run_id", None)
5447
+ if run_id:
5448
+ self._transcript.write_system(
5449
+ f"Completed passes are kept. /research --resume "
5450
+ f"{str(run_id)[:8]} picks the run up where it stopped.")
5451
+
5429
5452
  def on_worker_state_changed(self, event: Worker.StateChanged) -> None:
5430
5453
  """§16 AC3. Required alongside exit_on_error=False: without a handler the
5431
5454
  exception is available on the worker and reported nowhere."""
@@ -5909,6 +5932,11 @@ def _cmd_research(app: VenastineApp, args: str) -> None:
5909
5932
  §25: --grant [names] takes the same values as the CLI flag and goes
5910
5933
  through the same parser, so the two shells cannot offer different
5911
5934
  sets. Bare --grant opens the picker.
5935
+
5936
+ ROADMAP_v3 §98: `--resume [run-id]` in the query's place picks a failed
5937
+ or abandoned run up where it stopped; bare, it opens the picker. It
5938
+ comes LAST, after the other flags, which a resume takes too -- a grant
5939
+ is never stored (R12), so a resumed run is authorised afresh.
5912
5940
  """
5913
5941
  from core.reasoning.authorization import (
5914
5942
  GrantSpecError,
@@ -5917,6 +5945,7 @@ def _cmd_research(app: VenastineApp, args: str) -> None:
5917
5945
  )
5918
5946
 
5919
5947
  attended, review, grant_spec, query = _split_research_flags(args)
5948
+ resume = _split_resume(query)
5920
5949
  if not attended:
5921
5950
  attended = app._settings.get("research", {}).get(
5922
5951
  "approval_mode") == "attended"
@@ -5929,10 +5958,26 @@ def _cmd_research(app: VenastineApp, args: str) -> None:
5929
5958
  if not query:
5930
5959
  app._transcript.write_error(
5931
5960
  "Usage: /research [--attended] [--review|--no-review] "
5932
- "[--grant[=a,b]] <query>")
5961
+ "[--grant[=a,b]] <query>|--resume [run-id]")
5933
5962
  return
5934
5963
  if app.refuse_if_occupied("start a research run"):
5935
5964
  return
5965
+ if resume is not None and resume is not RESUME_PICKER:
5966
+ from core.reasoning.resume import ResumeRefused, find_run
5967
+ try:
5968
+ resume = find_run(resume)
5969
+ except ResumeRefused as e:
5970
+ app._transcript.write_error(f"/research --resume: {e}.")
5971
+ return
5972
+
5973
+ def launch(authorization) -> None:
5974
+ """Start the run, or, for a bare --resume, ask which run first."""
5975
+ if resume is None:
5976
+ _start_research(app, query, authorization)
5977
+ elif resume is RESUME_PICKER:
5978
+ _pick_run_to_resume(app, authorization)
5979
+ else:
5980
+ _start_research(app, None, authorization, resume=resume)
5936
5981
 
5937
5982
  offered = candidates()
5938
5983
  if grant_spec is GRANT_PICKER:
@@ -5954,7 +5999,7 @@ def _cmd_research(app: VenastineApp, args: str) -> None:
5954
5999
  # connects. What was config-dependent is now what happens on
5955
6000
  # a fresh clone.
5956
6001
  app._transcript.write_system(NOTHING_TO_GRANT)
5957
- _start_research(app, query, _authorization_for(app, set()))
6002
+ launch(_authorization_for(app, set()))
5958
6003
  return
5959
6004
 
5960
6005
  def _picked(selected) -> None:
@@ -5963,7 +6008,7 @@ def _cmd_research(app: VenastineApp, args: str) -> None:
5963
6008
  if selected is None:
5964
6009
  app._transcript.write_system("Research cancelled.")
5965
6010
  return
5966
- _start_research(app, query, _authorization_for(app, selected))
6011
+ launch(_authorization_for(app, selected))
5967
6012
 
5968
6013
  app.push_screen(GrantPickerScreen(offered), _picked)
5969
6014
  return
@@ -5975,7 +6020,47 @@ def _cmd_research(app: VenastineApp, args: str) -> None:
5975
6020
  except GrantSpecError as e:
5976
6021
  app._transcript.write_error(f"/research --grant: {e}")
5977
6022
  return
5978
- _start_research(app, query, _authorization_for(app, granted))
6023
+ launch(_authorization_for(app, granted))
6024
+
6025
+
6026
+ #: ROADMAP_v3 §98. A bare `/research --resume`: open the picker rather than
6027
+ #: resume a named run. GRANT_PICKER's shape, for the same reason.
6028
+ RESUME_PICKER = object()
6029
+
6030
+
6031
+ def _split_resume(query: str):
6032
+ """`--resume [run-id]` at the front of what is left once the leading
6033
+ flags are taken: None when the query is not a resume, RESUME_PICKER
6034
+ for a bare one, else the id as typed (ROADMAP_v3 §98). A separate step
6035
+ rather than a fifth value from _split_research_flags, whose four are
6036
+ unpacked by name at its call sites and in the suite."""
6037
+ head, _sep, rest = (query or "").strip().partition(" ")
6038
+ if head != "--resume":
6039
+ return None
6040
+ return rest.strip() or RESUME_PICKER
6041
+
6042
+
6043
+ def _pick_run_to_resume(app: VenastineApp, authorization) -> None:
6044
+ """The picker behind a bare `/research --resume` (ROADMAP_v3 §98).
6045
+
6046
+ The read runs on the UI thread, in a command handler, so a failure is
6047
+ written rather than raised -- `action_pick_thread`'s rule (#104), and
6048
+ for its reason: app.db is shared with any CLI run, so `database is
6049
+ locked` needs nothing to be wrong."""
6050
+ from core.reasoning.resume import resumable_runs
6051
+ try:
6052
+ runs = resumable_runs()
6053
+ except Exception as e: # noqa: BLE001 -- see the docstring
6054
+ app._transcript.write_error(f"Could not list research runs: {e}")
6055
+ return
6056
+
6057
+ def chosen(run_id) -> None:
6058
+ if run_id is None:
6059
+ app._transcript.write_system("Resume cancelled.")
6060
+ return
6061
+ _start_research(app, None, authorization, resume=run_id)
6062
+
6063
+ app.push_screen(ResumeRunPickerScreen(runs), chosen)
5979
6064
 
5980
6065
 
5981
6066
  def _authorization_for(app: VenastineApp, granted: set):
@@ -6093,12 +6178,25 @@ def _forwarding(app: "VenastineApp", events, outcome: dict):
6093
6178
  yield event
6094
6179
 
6095
6180
 
6096
- def _start_research(app: VenastineApp, query: str, authorization) -> None:
6181
+ def _start_research(app: VenastineApp, query, authorization,
6182
+ resume=None) -> None:
6097
6183
  """Kick off the worker. Split from _cmd_research because the picker
6098
- path resolves asynchronously and lands here from a callback."""
6184
+ path resolves asynchronously and lands here from a callback.
6185
+
6186
+ `resume` (ROADMAP_v3 §98) is the id of a run to pick up instead of
6187
+ starting `query`, which is then None. The id is kept on the app from
6188
+ here, and from the run's run_started event, so a failure can say how
6189
+ to resume."""
6099
6190
  app._busy = True
6100
- app._transcript.write_user(f"/research {query}")
6101
- app._transcript.write_system("Running the ten-pass pipeline. This takes a while.")
6191
+ app._research_run_id = str(resume) if resume is not None else None
6192
+ if resume is not None:
6193
+ app._transcript.write_user(f"/research --resume {resume}")
6194
+ app._transcript.write_system(
6195
+ "Resuming the run where it stopped; completed passes are not "
6196
+ "run again.")
6197
+ else:
6198
+ app._transcript.write_user(f"/research {query}")
6199
+ app._transcript.write_system("Running the ten-pass pipeline. This takes a while.")
6102
6200
  app._raven.state = ravens.THINKING
6103
6201
  app._research_progress.start_run()
6104
6202
  review_on = bool(getattr(app, "_research_review", False))
@@ -6110,6 +6208,7 @@ def _start_research(app: VenastineApp, query: str, authorization) -> None:
6110
6208
  stream_deep_research_pipeline,
6111
6209
  )
6112
6210
  from core.reasoning.output_writer import write_run_artifacts
6211
+ from core.reasoning.resume import ResumeRefused
6113
6212
  error = None
6114
6213
  try:
6115
6214
  # §22: ITERATED, not drained. A drainer would
@@ -6135,12 +6234,19 @@ def _start_research(app: VenastineApp, query: str, authorization) -> None:
6135
6234
  # in the status bar -- captured HERE, so a mid-run /effort
6136
6235
  # affects the next run, exactly like model/provider.
6137
6236
  effort=app.effort,
6237
+ resume=resume,
6138
6238
  )
6139
6239
  outcome = {}
6140
6240
  run = None
6141
6241
  try:
6142
6242
  run = run_pipeline_to_completion(
6143
6243
  _forwarding(app, events, outcome))
6244
+ except ResumeRefused as refused:
6245
+ # §98. Refused before anything changed: reported as what it
6246
+ # is, and NOT re-raised -- it is an answer, not a worker
6247
+ # failure, and re-raising would log and toast it again.
6248
+ app.post_message(ResearchFinished(None, refused))
6249
+ return
6144
6250
  except RuntimeError:
6145
6251
  if not outcome.get("abandoned"):
6146
6252
  raise
package/tui/app.tcss CHANGED
@@ -460,7 +460,11 @@ Button:focus {
460
460
  border-right: none;
461
461
  }
462
462
 
463
- ThreadPickerScreen {
463
+ /* ROADMAP_v3 §98's run picker shares the thread picker's dialog, so it
464
+ shares the rule that centres it -- the sweep in test_tui.py measured it
465
+ at the screen's left edge without. */
466
+ ThreadPickerScreen,
467
+ ResumeRunPickerScreen {
464
468
  align: center middle;
465
469
  }
466
470
 
package/tui/screens.py CHANGED
@@ -1189,6 +1189,67 @@ class ThreadPickerScreen(ModalScreen[object]):
1189
1189
  self.dismiss(None)
1190
1190
 
1191
1191
 
1192
+ def resume_run_row(run: dict) -> str:
1193
+ """One research run in the resume picker (ROADMAP_v3 §98): the start of
1194
+ its id, when it started, what state it is in, where it would resume, and
1195
+ its query on the line below -- the query is what a person recognises.
1196
+ A run that is still 'running' may be live in another process sharing
1197
+ app.db, and nothing in the record can tell, so the row says both."""
1198
+ status = ("stopped, or still running elsewhere"
1199
+ if run.get("status") == "running" else str(run.get("status")))
1200
+ started = run.get("started_at")
1201
+ when = (started.strftime("%Y-%m-%d %H:%M")
1202
+ if hasattr(started, "strftime") else str(started or ""))
1203
+ where = (f"cannot resume: {run['note']}" if run.get("note")
1204
+ else f"resumes {run.get('stage')}")
1205
+ query = " ".join(str(run.get("user_query") or "").split())
1206
+ if len(query) > 70:
1207
+ query = query[:69] + "…"
1208
+ return f"{str(run.get('id'))[:8]} {when} {status} {where}\n {query}"
1209
+
1210
+
1211
+ class ResumeRunPickerScreen(ModalScreen[object]):
1212
+ """Pick a failed or abandoned research run to resume (ROADMAP_v3 §98).
1213
+ Dismisses with the run's id, or None to cancel.
1214
+
1215
+ The thread picker's shape and its CSS, because it is the same decision
1216
+ one level up -- which earlier piece of work to carry on -- and a second
1217
+ look for it would be a second thing to keep styled. A run this build
1218
+ cannot resume is still listed, with the reason, so a person looking
1219
+ for it learns why rather than wondering where it went; choosing it gets
1220
+ the same reason as an error.
1221
+ """
1222
+
1223
+ BINDINGS = [("escape", "cancel", "Cancel")]
1224
+
1225
+ def __init__(self, runs: list[dict], note: str = ""):
1226
+ super().__init__()
1227
+ self._runs = runs
1228
+ self._note = note
1229
+
1230
+ def compose(self) -> ComposeResult:
1231
+ items = [ListItem(Label(Text(resume_run_row(r)))) for r in self._runs]
1232
+ children = [Label("Resume which research run?", id="thread-title")]
1233
+ if self._note:
1234
+ children.append(Static(Text(self._note), id="thread-note"))
1235
+ if items:
1236
+ children.append(ListView(*items, id="thread-list"))
1237
+ else:
1238
+ children.append(Static("No failed or abandoned research run to "
1239
+ "resume.", id="thread-empty"))
1240
+ yield Vertical(*children, id="thread-dialog")
1241
+
1242
+ def on_list_view_selected(self, event: ListView.Selected) -> None:
1243
+ index = event.list_view.index
1244
+ if index is not None and 0 <= index < len(self._runs):
1245
+ self.dismiss(self._runs[index]["id"])
1246
+ else:
1247
+ self.dismiss(None)
1248
+
1249
+ def action_cancel(self) -> None:
1250
+ self.dismiss(None)
1251
+
1252
+
1192
1253
  class SecretScreen(ModalScreen[object]):
1193
1254
  """Ask for one secret, masked (ROADMAP_v3 §49 slice 5a, SS59).
1194
1255