Skip to content

Workflow API reference

The workflow package contains persistent graph compositions and deprecated compatibility workflows. New code should prefer PlanningExecutionAgent and ThinkPlanningExecutionAgent.

BaseWorkflow

Bases: ABC

Abstract base class for all workflow implementations in the URSA framework.

BaseWorkflow provides a standardized foundation for building workflows consisting of LLM-powered agents with built-in telemetry, configuration management, and execution flow control. It handles common tasks like input normalization, thread management, metrics collection, and LangGraph integration.

Subclasses only need to implement the _invoke method to define their core functionality, while inheriting standardized invocation patterns, telemetry, and graph integration capabilities. The class enforces a consistent interface through runtime checks that prevent subclasses from overriding critical methods like invoke().

The agent supports direct invocation with inputs, with automatic tracking of token usage, execution time, and other metrics. It also provides utilities for integrating with LangGraph through node wrapping and configuration.

Subclass Inheritance Guidelines
  • Must Override: _invoke() - Define your agent's core functionality
  • Can Override: _normalize_inputs() - Customize input handling Various helper methods
  • Never Override: invoke() - Final method with runtime enforcement call() - Delegates to invoke Other public methods (build_config, write_state, add_node)

To create a custom agent, inherit from this class and implement the _invoke method:

class MyWorkflow(BaseWorkflow):
    def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        # Process inputs and return results
        ...
Source code in src/ursa/workflows/base_workflow.py
class BaseWorkflow(ABC):
    """Abstract base class for all workflow implementations in the URSA framework.

    BaseWorkflow provides a standardized foundation for building workflows consisting of
    LLM-powered agents with built-in telemetry, configuration management, and execution
    flow control. It handles common tasks like input normalization, thread management,
    metrics collection, and LangGraph integration.

    Subclasses only need to implement the _invoke method to define their core
    functionality, while inheriting standardized invocation patterns, telemetry, and
    graph integration capabilities. The class enforces a consistent interface through
    runtime checks that prevent subclasses from overriding critical methods like
    invoke().

    The agent supports direct invocation with inputs, with
    automatic tracking of token usage, execution time, and other metrics. It also
    provides utilities for integrating with LangGraph through node wrapping and
    configuration.

    Subclass Inheritance Guidelines:
        - Must Override: _invoke() - Define your agent's core functionality
        - Can Override: _normalize_inputs() - Customize input handling
                        Various helper methods
        - Never Override: invoke() - Final method with runtime enforcement
                          __call__() - Delegates to invoke
                          Other public methods (build_config, write_state, add_node)

    To create a custom agent, inherit from this class and implement the _invoke method:

    ```python
    class MyWorkflow(BaseWorkflow):
        def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
            # Process inputs and return results
            ...
    ```
    """

    def __init__(self, **kwargs):
        pass

    # NOTE: The `invoke` method uses the PEP 570 `/,*` notation to explicitly state which
    # arguments can and cannot be passed as positional or keyword arguments.
    @final
    def invoke(
        self,
        inputs: Optional[InputLike] = None,
        /,
        *,
        config: Optional[dict] = None,
        **kwargs: Any,
    ) -> Any:
        """Executes the agent with the provided inputs and configuration.

        This is the main entry point for agent execution. It handles input normalization,
        telemetry tracking, and proper execution context management. The method supports
        flexible input formats - either as a positional argument or as keyword arguments.

        Args:
            inputs: Optional positional input to the agent. If provided, all non-control
                keyword arguments will be rejected to avoid ambiguity.
            config: Optional configuration dictionary to override default settings.
            **kwargs: Additional keyword arguments that can be either:
                - Input parameters (when no positional input is provided)
                - Control parameters recognized by the agent

        Returns:
            The result of the agent's execution.

        Raises:
            TypeError: If both positional inputs and non-control keyword arguments are
                provided simultaneously.
        """

        normalized = self._normalize_inputs(inputs)

        # Delegate to the subclass implementation with the normalized inputs
        # and any control parameters
        return self._invoke(normalized, config=config, **kwargs)

    def _normalize_inputs(self, inputs: InputLike) -> Mapping[str, Any]:
        """Normalizes various input formats into a standardized mapping.

        This method converts different input types into a consistent dictionary format
        that can be processed by the agent. String inputs are wrapped as messages, while
        mappings are passed through unchanged.

        Args:
            inputs: The input to normalize. Can be a string (which will be converted to a
                message) or a mapping (which will be returned as-is).

        Returns:
            A mapping containing the normalized inputs, with keys appropriate for agent
            processing.

        Raises:
            TypeError: If the input type is not supported (neither string nor mapping).
        """
        if isinstance(inputs, str):
            return {"task": inputs}
        if isinstance(inputs, Mapping):
            return inputs
        raise TypeError(f"Unsupported input type: {type(inputs)}")

    @final
    async def ainvoke(
        self,
        inputs: Optional[InputLike] = None,
        /,
        *,
        config: Optional[dict] = None,
        **kwargs: Any,
    ) -> Any:
        """Asynchronously execute the workflow with normalized inputs.

        Subclasses can provide a native async implementation by overriding
        ``_ainvoke``. The default ``_ainvoke`` implementation runs the sync
        ``_invoke`` implementation in a worker thread.
        """

        normalized = self._normalize_inputs(inputs)
        return await self._ainvoke(normalized, config=config, **kwargs)

    @abstractmethod
    def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        """Subclasses implement the actual sync work against normalized inputs."""
        ...

    async def _ainvoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        """Subclasses can override to implement native async work."""
        return await asyncio.to_thread(self._invoke, inputs, **config)

    def __call__(self, inputs: InputLike, /, **kwargs: Any) -> Any:
        """Specify calling behavior for class instance."""
        return self.invoke(inputs, **kwargs)

    # Runtime enforcement: forbid subclasses from overriding invoke
    def __init_subclass__(cls, **kwargs):
        """Ensure subclass does not override key method."""
        super().__init_subclass__(**kwargs)
        if "invoke" in cls.__dict__:
            err_msg = (
                f"{cls.__name__} must not override BaseAgent.invoke(); "
                "implement _invoke() only."
            )
            raise TypeError(err_msg)

__call__(inputs, /, **kwargs)

Specify calling behavior for class instance.

Source code in src/ursa/workflows/base_workflow.py
def __call__(self, inputs: InputLike, /, **kwargs: Any) -> Any:
    """Specify calling behavior for class instance."""
    return self.invoke(inputs, **kwargs)

__init_subclass__(**kwargs)

Ensure subclass does not override key method.

Source code in src/ursa/workflows/base_workflow.py
def __init_subclass__(cls, **kwargs):
    """Ensure subclass does not override key method."""
    super().__init_subclass__(**kwargs)
    if "invoke" in cls.__dict__:
        err_msg = (
            f"{cls.__name__} must not override BaseAgent.invoke(); "
            "implement _invoke() only."
        )
        raise TypeError(err_msg)

ainvoke(inputs=None, /, *, config=None, **kwargs) async

Asynchronously execute the workflow with normalized inputs.

Subclasses can provide a native async implementation by overriding _ainvoke. The default _ainvoke implementation runs the sync _invoke implementation in a worker thread.

Source code in src/ursa/workflows/base_workflow.py
@final
async def ainvoke(
    self,
    inputs: Optional[InputLike] = None,
    /,
    *,
    config: Optional[dict] = None,
    **kwargs: Any,
) -> Any:
    """Asynchronously execute the workflow with normalized inputs.

    Subclasses can provide a native async implementation by overriding
    ``_ainvoke``. The default ``_ainvoke`` implementation runs the sync
    ``_invoke`` implementation in a worker thread.
    """

    normalized = self._normalize_inputs(inputs)
    return await self._ainvoke(normalized, config=config, **kwargs)

invoke(inputs=None, /, *, config=None, **kwargs)

Executes the agent with the provided inputs and configuration.

This is the main entry point for agent execution. It handles input normalization, telemetry tracking, and proper execution context management. The method supports flexible input formats - either as a positional argument or as keyword arguments.

Parameters:

Name Type Description Default
inputs Optional[InputLike]

Optional positional input to the agent. If provided, all non-control keyword arguments will be rejected to avoid ambiguity.

None
config Optional[dict]

Optional configuration dictionary to override default settings.

None
**kwargs Any

Additional keyword arguments that can be either: - Input parameters (when no positional input is provided) - Control parameters recognized by the agent

{}

Returns:

Type Description
Any

The result of the agent's execution.

Raises:

Type Description
TypeError

If both positional inputs and non-control keyword arguments are provided simultaneously.

Source code in src/ursa/workflows/base_workflow.py
@final
def invoke(
    self,
    inputs: Optional[InputLike] = None,
    /,
    *,
    config: Optional[dict] = None,
    **kwargs: Any,
) -> Any:
    """Executes the agent with the provided inputs and configuration.

    This is the main entry point for agent execution. It handles input normalization,
    telemetry tracking, and proper execution context management. The method supports
    flexible input formats - either as a positional argument or as keyword arguments.

    Args:
        inputs: Optional positional input to the agent. If provided, all non-control
            keyword arguments will be rejected to avoid ambiguity.
        config: Optional configuration dictionary to override default settings.
        **kwargs: Additional keyword arguments that can be either:
            - Input parameters (when no positional input is provided)
            - Control parameters recognized by the agent

    Returns:
        The result of the agent's execution.

    Raises:
        TypeError: If both positional inputs and non-control keyword arguments are
            provided simultaneously.
    """

    normalized = self._normalize_inputs(inputs)

    # Delegate to the subclass implementation with the normalized inputs
    # and any control parameters
    return self._invoke(normalized, config=config, **kwargs)

Hypothesis dataclass

One competing hypothesis to investigate.

Source code in src/ursa/workflows/_hypotheses.py
@dataclass
class Hypothesis:
    """One competing hypothesis to investigate."""

    index: int
    statement: str
    detail: str = ""

    def as_task(self, query: str) -> str:
        lines = [
            f"Investigate the following hypothesis for the question: {query}",
            "",
            f"Hypothesis H{self.index}: {self.statement}",
        ]
        if self.detail:
            lines += ["", self.detail]
        lines += [
            "",
            "Gather and weigh evidence for and against this specific "
            "hypothesis. Report findings, confidence, and any evidence that "
            "would change your assessment.",
        ]
        return "\n".join(lines)

HypothesisInvestigation dataclass

Recorded outcome of a single (quarantined) investigation branch.

Source code in src/ursa/workflows/hypothesis_symposium.py
@dataclass
class HypothesisInvestigation:
    """Recorded outcome of a single (quarantined) investigation branch."""

    index: int
    statement: str
    findings: str = ""
    ok: bool = True
    error: str | None = None

    def as_markdown(self) -> str:
        status = "ok" if self.ok else "FAILED"
        body = self.findings if self.ok else (self.error or "unknown error")
        return f"### H{self.index} ({status}): {self.statement}\n\n{body}"

HypothesisOrchestratorWorkflow

Bases: WorkflowToolsMixin, BaseWorkflow

Hypothesize, then let an orchestrator spawn/review per-hypothesis agents.

A dynamic-topology alternative to :class:~ursa.workflows.hypothesis_symposium.HypothesisSymposiumWorkflow, intended for empirical comparison. Every scientific phase is exposed as an overridable hook.

Because the topology is dynamic there is no environment object to hand to run_with_visualization, so this workflow records its own environment run: it opens an :func:environment_run_recorder for the whole orchestration and threads the resulting run config into both the orchestrator agent and every spawned investigator. That captures (a) explicit orchestrator->investigator delegation events emitted here and (b) all structured events emitted by the sub-agents themselves, streamed live to events.jsonl. Delegation traffic is additionally rendered to the stdout logs so progress is visible without a dashboard.

Source code in src/ursa/workflows/hypothesis_orchestrator.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
class HypothesisOrchestratorWorkflow(WorkflowToolsMixin, BaseWorkflow):
    """Hypothesize, then let an orchestrator spawn/review per-hypothesis agents.

    A dynamic-topology alternative to
    :class:`~ursa.workflows.hypothesis_symposium.HypothesisSymposiumWorkflow`,
    intended for empirical comparison. Every scientific phase is exposed as an
    overridable hook.

    Because the topology is dynamic there is no environment object to hand to
    ``run_with_visualization``, so this workflow records its own environment run:
    it opens an :func:`environment_run_recorder` for the whole orchestration and
    threads the resulting run config into both the orchestrator agent and every
    spawned investigator. That captures (a) explicit orchestrator->investigator
    delegation events emitted here and (b) all structured events emitted *by* the
    sub-agents themselves, streamed live to ``events.jsonl``. Delegation traffic
    is additionally rendered to the stdout logs so progress is visible without a
    dashboard.
    """

    def __init__(
        self,
        llm: BaseChatModel,
        *,
        hypothesizer: HypothesizerAgent | None = None,
        experience_filename: str = DEFAULT_HYPOTHESIS_EXPERIENCE,
        max_hypotheses: int = 5,
        orchestrator: ExecutionAgent | None = None,
        workspace: str | Path | None = None,
        group: str | None = None,
        name: str = "hypothesis_orchestrator",
        visualize: bool = True,
        trace: bool = True,
        trace_character_limit: int = 2000,
        **kwargs: Any,
    ) -> None:
        super().__init__(**kwargs)
        self.llm = llm
        self.workspace = Path(workspace) if workspace else None
        self.group = group
        # `name`/`group` are what the visualization recorder reads off an
        # "environment"; this workflow acts as its own environment.
        self.name = name
        self.visualize = bool(visualize)
        self.trace = bool(trace)
        self.trace_character_limit = int(trace_character_limit)
        self.orchestrator_run_id: str | None = None
        # Per-run observability context, published by `_invoke` so overridable
        # hooks keep their original signatures.
        self._run_config: Mapping[str, Any] | None = None
        self._run_events: EnvironmentEvents | None = None
        self.experience_filename = (
            HypothesizerAgent._validate_experience_filename(experience_filename)
        )
        self.hypothesizer = hypothesizer or HypothesizerAgent(
            llm,
            experience_filename=self.experience_filename,
            workspace=self.workspace,
            group=self.group,
            **self._agent_kwargs,
        )
        self.max_hypotheses = max(1, int(max_hypotheses))
        self._orchestrator_override = orchestrator

    # ------------------------------------------------------- overridable hooks

    def format_result(self, result: Mapping[str, Any]) -> str:
        """Return only the final write-up, not the whole state.

        The full state carries bulky intermediate data (raw orchestrator result,
        parsed hypotheses, the hypothesis-space markdown, investigator
        identities). Returning all of it makes the dashboard output unreadable,
        so surface just the detailed final answer, falling back to ``summary``
        if a subclass produced one instead.
        """
        detailed = result.get("final")
        summary = result.get("summary")
        text = detailed or summary
        if not text:
            raise ValueError("Orchestration completed without a response.")
        return str(text).strip()

    def build_hypotheses(
        self, query: str, context: str, config: Mapping[str, Any] | None
    ) -> list[Hypothesis]:
        """Produce competing hypotheses via the HypothesizerAgent."""
        result = invoke_agent(
            self.hypothesizer,
            {
                "query": query,
                "new_information": query,
                "context": context,
                "experience_filename": self.experience_filename,
                "revision_history": [],
            },
            config=config,
        )
        artifact = self._artifact_text(result)
        self._last_hypothesis_space = artifact
        return self._parse_hypotheses(artifact, query)

    @staticmethod
    def _artifact_text(result: Any) -> str:
        return artifact_text(result)

    # ------------------------------------------------------------- run surface

    def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        cfg = config.get("config")
        query = str(inputs.get("query") or inputs.get("task") or "")
        context = str(inputs.get("context", ""))
        self._last_hypothesis_space = ""

        hypotheses = self.build_hypotheses(query, context, cfg)
        registry = self._build_registry()

        prompt = _ORCHESTRATOR_PROMPT.format(
            hypothesis_block=self._hypothesis_block(hypotheses),
            query=query,
        )
        # Open a recorder for the whole orchestration. `run_config` carries the
        # recorder callback, so it is threaded into the orchestrator AND every
        # investigator: their own structured events land in the same stream.
        with self._recording(task=query, config=cfg) as run_config:
            events = self._events(run_config)
            self._emit_topology(events, hypotheses)
            # Published as instance state (not hook arguments) so that user
            # subclasses overriding `_build_orchestrator`/`_make_spawn_tools`
            # with the original single-argument signature keep working.
            self._run_config = run_config
            self._run_events = events
            orchestrator = self._build_orchestrator(registry)
            start = perf_counter()
            try:
                result = invoke_agent(orchestrator, prompt, config=run_config)
            except BaseException as exc:
                events.emit(
                    "Orchestration failed",
                    stage="orchestration",
                    phase="error",
                    event_type="orchestration_failed",
                    level="error",
                    error=str(exc),
                    elapsed_seconds=perf_counter() - start,
                )
                raise
            events.emit(
                "Orchestration completed",
                stage="orchestration",
                phase="end",
                event_type="orchestration_completed",
                investigators=registry.identities,
                elapsed_seconds=perf_counter() - start,
            )

        return {
            "query": query,
            "hypotheses": [h.__dict__ for h in hypotheses],
            "hypothesis_space_markdown": self._last_hypothesis_space,
            "investigator_identities": registry.identities,
            "orchestrator_run_id": self.orchestrator_run_id,
            "orchestrator_result": result,
            "final": self._result_text(result),
        }

    def _normalize_inputs(self, inputs: InputLike) -> Mapping[str, Any]:
        if isinstance(inputs, str):
            return {"query": inputs}
        if isinstance(inputs, Mapping):
            return inputs
        raise TypeError(f"Unsupported input type: {type(inputs)}")

    # --------------------------------------------------------------- internals

    @contextmanager
    def _recording(
        self, *, task: str, config: Mapping[str, Any] | None
    ) -> Iterator[Mapping[str, Any] | None]:
        """Yield a run config carrying the visualization recorder callback.

        Degrades gracefully: if visualization is disabled or the recorder cannot
        be created, the original config is yielded unchanged so the run still
        proceeds (and stdout tracing still provides progress feedback).
        """
        if not self.visualize:
            yield config
            return
        try:
            from ursa.environments import environment_run_recorder
        except Exception:  # pragma: no cover - defensive import guard
            logger.warning(
                "Orchestrator visualization unavailable; running unrecorded.",
                exc_info=True,
            )
            yield config
            return

        run_id = self._new_run_id()
        # Validate viability *before* entering the recorder so a setup failure
        # cannot be confused with a failure from the orchestration body.
        try:
            from ursa.security import validate_group_name

            validate_group_name(self.group or "default")
        except Exception:
            logger.warning(
                "Orchestrator group %r is not recordable; running unrecorded.",
                self.group,
                exc_info=True,
            )
            self.orchestrator_run_id = None
            yield config
            return

        with environment_run_recorder(
            self, task=task, config=config, run_id=run_id
        ) as (recorder, run_config):
            self.orchestrator_run_id = recorder.run_id
            logger.info(
                "Orchestrator visualization run started: group=%s "
                "run_id=%s (events stream live to the dashboard)",
                recorder.group,
                recorder.run_id,
            )
            yield run_config

    @staticmethod
    def _new_run_id() -> str:
        """Readable, sortable, unique run id for one orchestration."""
        return (
            f"hyporch_{datetime.now().strftime('%Y%m%d_%H%M%S')}_"
            f"{uuid4().hex[:8]}"
        )

    def _events(self, config: Mapping[str, Any] | None) -> EnvironmentEvents:
        """Event emitter identifying this workflow as the environment."""
        return EnvironmentEvents(
            environment=self.name,
            config=config,
            environment_type="hypothesis_orchestrator",
            environment_id=self.name,
            path=[self.name],
        )

    def _source(self, name: str, *, kind: str = "agent") -> dict[str, Any]:
        return {
            "id": f"{self.name}.{name}",
            "name": name,
            "kind": kind,
            "path": [self.name, name],
        }

    def _emit_topology(
        self, events: EnvironmentEvents, hypotheses: Sequence[Hypothesis]
    ) -> None:
        """Declare the (initially known) orchestrator/investigator topology."""
        nodes = [
            {
                **self._source("orchestrator"),
                "role": "orchestrator",
            },
            *[
                {
                    **self._source(f"H{h.index}"),
                    "role": f"investigator for H{h.index}: {h.statement}",
                }
                for h in hypotheses
            ],
        ]
        topology = {
            "kind": "hypothesis_orchestrator",
            "name": self.name,
            "description": "Orchestrator spawning per-hypothesis investigators",
            "nodes": nodes,
            "edges": [
                {
                    "source": f"{self.name}.orchestrator",
                    "target": f"{self.name}.H{h.index}",
                    "kind": "spawns",
                }
                for h in hypotheses
            ],
        }
        events.emit(
            f"Hypothesis orchestrator {self.name} topology declared",
            stage="orchestration",
            phase="topology",
            event_type="topology_declared",
            topology=topology,
        )
        events.emit(
            f"Hypothesis orchestrator {self.name} started",
            stage="orchestration",
            phase="start",
            event_type="orchestration_started",
            hypothesis_count=len(hypotheses),
        )

    def _trace(self, label: str, message: str) -> None:
        """Render one orchestrator<->investigator message to the stdout logs."""
        if not self.trace:
            return
        text = message
        if (
            self.trace_character_limit > 0
            and len(text) > self.trace_character_limit
        ):
            text = text[: self.trace_character_limit] + "\n... [truncated]"
        logger.info(f"\n[HypothesisOrchestrator:{self.name}] {label}\n{text}\n")

    @staticmethod
    def _result_text(result: Any) -> str:
        if isinstance(result, Mapping) and result.get("messages"):
            last = result["messages"][-1]
            text = getattr(last, "text", None)
            if isinstance(text, str) and text:
                return text
            content = getattr(last, "content", last)
            return content if isinstance(content, str) else str(content)
        return HypothesizerAgent._response_text(result)

    def _build_registry(self) -> _InvestigatorRegistry:
        return _InvestigatorRegistry(
            self.llm,
            workspace=self.workspace,
            group=self.group,
            run_stamp=_timestamp(),
            agent_kwargs={
                **self._tool_agent_kwargs,
                "extra_tools": list(self._extra_tools.values()),
            },
        )

    def _build_orchestrator(
        self, registry: _InvestigatorRegistry
    ) -> ExecutionAgent:
        tools = [*self._extra_tools.values(), *self._make_spawn_tools(registry)]
        if self._orchestrator_override is not None:
            orchestrator = self._orchestrator_override
            orchestrator.add_tool(tools)
            return orchestrator
        kwargs: dict[str, Any] = {
            **self._tool_agent_kwargs,
            "extra_tools": tools,
        }
        if self.workspace is not None:
            kwargs["workspace"] = str(self.workspace / "orchestrator")
        if self.group is not None:
            kwargs["group"] = self.group
        return ExecutionAgent(self.llm, **kwargs)

    def _investigator_config(
        self, run_config: Mapping[str, Any] | None, label: str, agent_name: str
    ) -> dict[str, Any] | None:
        """Attach stable investigator identity to nested sub-agent events.

        Threading this config into the investigator is what makes the sub-agent's
        *own* structured events show up in the run stream, attributed to it.
        """
        if run_config is None:
            return None
        member_id = f"{self.name}.{label}"
        merged = dict(run_config)
        base_metadata = merged.get("metadata")
        metadata = (
            dict(base_metadata) if isinstance(base_metadata, Mapping) else {}
        )
        metadata.update({
            "environment_id": self.name,
            "environment_member": label,
            "environment_member_id": member_id,
            "environment_member_role": f"investigator for {label}",
            "environment_member_path": [self.name, label],
            "agent": label,
            "agent_id": member_id,
            "investigator_agent_name": agent_name,
        })
        merged["metadata"] = metadata

        base_tags = merged.get("tags")
        if isinstance(base_tags, str):
            tags = [base_tags]
        else:
            tags = list(base_tags) if base_tags else []
        for tag in (label, member_id, "environment_member"):
            if tag not in tags:
                tags.append(tag)
        merged["tags"] = tags
        return merged

    def _with_peer_access(self, registry: Any, label: str, task: str) -> str:
        """Link peer workspaces and append the read-only access note to the task.

        Guarded so that alternative/stub registries without peer support (and any
        filesystem failure) degrade to the original task rather than failing the
        delegation.
        """
        linker = getattr(registry, "link_peers", None)
        if not callable(linker):
            return task
        try:
            exposed = linker(label)
        except Exception as exc:  # noqa: BLE001 - never fail a delegation
            logger.warning(
                "Peer workspace linking failed for %s: %s", label, exc
            )
            return task
        if not isinstance(exposed, Mapping) or not exposed:
            return task
        return f"{task}{self._peer_access_note(exposed)}"

    @staticmethod
    def _peer_access_note(exposed: Mapping[str, str]) -> str:
        """Tell an investigator where peer artifacts live and that they are read-only.

        This has to be explicit: neither ``list_workspace_files`` nor the
        dashboard follows symlinks, so the peer directories are invisible to
        directory listings even though ``read_file``/``run_command`` can read
        through them by path.
        """
        if not exposed:
            return ""
        lines = "\n".join(
            f"- {label.upper()}: {path}/"
            for label, path in sorted(exposed.items())
        )
        return (
            "\n\nPEER WORKSPACE ACCESS (READ-ONLY)\n"
            "The other investigators' workspaces are mounted inside your own "
            "workspace at these relative paths:\n"
            f"{lines}\n"
            "You can read their real artifacts there (data files, plots, "
            "scripts, notes) with read_file, or inspect them with run_command "
            "(e.g. `ls peers/h1/`), which is far better evidence than a summary "
            "alone. Two caveats:\n"
            "1. These paths are READ-ONLY. Any attempt to write to, edit, or "
            "delete a file under a peer path will be refused. Never modify a "
            "peer's files; copy what you need into your own workspace instead.\n"
            "2. Directory listing tools do not traverse these mounts, so they "
            "will not appear in list_workspace_files output. Use the explicit "
            "paths above.\n"
            "Do not use `grep -r`, `find`, or other unbounded recursive scans "
            "from your workspace root, because peer mounts can nest; target the "
            "specific peer path you care about instead."
        )

    def _make_spawn_tools(
        self, registry: _InvestigatorRegistry
    ) -> list[StructuredTool]:
        run_config = self._run_config
        emitter = (
            self._run_events
            if self._run_events is not None
            else self._events(run_config)
        )

        def _start(label: str, task: str, agent_name: str) -> float:
            emitter.emit(
                f"Orchestrator -> {label}",
                stage="delegation",
                phase="start",
                event_type="delegation_started",
                source=self._source("orchestrator"),
                target=self._source(label),
                hypothesis_label=label,
                investigator_agent_name=agent_name,
                task=task,
            )
            self._trace(f"orchestrator -> {label} ({agent_name})", task)
            return perf_counter()

        def _end(label: str, task: str, text: str, started: float) -> None:
            emitter.emit(
                f"{label} -> Orchestrator",
                stage="delegation",
                phase="end",
                event_type="delegation_completed",
                source=self._source(label),
                target=self._source("orchestrator"),
                hypothesis_label=label,
                task=task,
                result=text,
                elapsed_seconds=perf_counter() - started,
            )
            self._trace(f"{label} -> orchestrator", text)

        def _error(
            label: str, task: str, exc: BaseException, started: float
        ) -> None:
            emitter.emit(
                f"Investigator {label} failed",
                stage="delegation",
                phase="error",
                event_type="delegation_failed",
                level="error",
                source=self._source(label),
                target=self._source("orchestrator"),
                hypothesis_label=label,
                task=task,
                error=str(exc),
                elapsed_seconds=perf_counter() - started,
            )
            self._trace(f"{label} -> orchestrator [FAILED]", str(exc))

        def spawn_investigator(hypothesis_label: str, task: str) -> str:
            agent = registry.get_or_create(hypothesis_label)
            agent_name = registry.identities.get(
                hypothesis_label.strip().lower(), hypothesis_label
            )
            task = self._with_peer_access(registry, hypothesis_label, task)
            started = _start(hypothesis_label, task, agent_name)
            member_config = self._investigator_config(
                run_config, hypothesis_label, agent_name
            )
            kwargs = {"config": member_config} if member_config else {}
            try:
                result = invoke_agent(agent, task, **kwargs)
            except BaseException as exc:
                _error(hypothesis_label, task, exc, started)
                raise
            text = self._result_text(result)
            _end(hypothesis_label, task, text, started)
            return text

        async def aspawn_investigator(hypothesis_label: str, task: str) -> str:
            agent = registry.get_or_create(hypothesis_label)
            agent_name = registry.identities.get(
                hypothesis_label.strip().lower(), hypothesis_label
            )
            task = self._with_peer_access(registry, hypothesis_label, task)
            started = _start(hypothesis_label, task, agent_name)
            member_config = self._investigator_config(
                run_config, hypothesis_label, agent_name
            )
            kwargs = {"config": member_config} if member_config else {}
            try:
                result = await ainvoke_agent(agent, task, **kwargs)
            except BaseException as exc:
                _error(hypothesis_label, task, exc, started)
                raise
            text = self._result_text(result)
            _end(hypothesis_label, task, text, started)
            return text

        spawn = StructuredTool.from_function(
            func=spawn_investigator,
            coroutine=aspawn_investigator,
            name="spawn_investigator",
            description=(
                "Create (or reuse) a persistent per-hypothesis investigator "
                "agent identified by a stable hypothesis_label, run the given "
                "task on it, and return its result. Reusing a label reaches the "
                "same agent so it remembers its earlier investigation."
            ),
            args_schema=SpawnInvestigatorInput,
        )

        def list_investigators() -> str:
            identities = registry.identities
            if not identities:
                text = "No investigators spawned yet."
            else:
                text = "\n".join(
                    f"- label '{label}' -> agent_name '{name}'"
                    for label, name in identities.items()
                )
            emitter.emit(
                "Orchestrator listed investigators",
                stage="registry",
                phase="update",
                event_type="investigators_listed",
                source=self._source("orchestrator"),
                investigators=identities,
            )
            self._trace("orchestrator: list_investigators", text)
            return text

        listing = StructuredTool.from_function(
            func=list_investigators,
            name="list_investigators",
            description=(
                "List the hypothesis labels spawned so far and their minted "
                "persistent agent_names. Record these in your experiences so you "
                "never lose track of which agent owns which hypothesis."
            ),
        )
        return [spawn, listing]

    def _hypothesis_block(self, hypotheses: Sequence[Hypothesis]) -> str:
        if not hypotheses:
            return "(none parsed; treat the question itself as one hypothesis)"
        return "\n".join(
            f"H{h.index}: {h.statement}"
            + (f"\n    {h.detail}" if h.detail else "")
            for h in hypotheses
        )

    def _parse_hypotheses(self, artifact: str, query: str) -> list[Hypothesis]:
        return parse_hypotheses(
            artifact, query, max_hypotheses=self.max_hypotheses
        )

build_hypotheses(query, context, config)

Produce competing hypotheses via the HypothesizerAgent.

Source code in src/ursa/workflows/hypothesis_orchestrator.py
def build_hypotheses(
    self, query: str, context: str, config: Mapping[str, Any] | None
) -> list[Hypothesis]:
    """Produce competing hypotheses via the HypothesizerAgent."""
    result = invoke_agent(
        self.hypothesizer,
        {
            "query": query,
            "new_information": query,
            "context": context,
            "experience_filename": self.experience_filename,
            "revision_history": [],
        },
        config=config,
    )
    artifact = self._artifact_text(result)
    self._last_hypothesis_space = artifact
    return self._parse_hypotheses(artifact, query)

format_result(result)

Return only the final write-up, not the whole state.

The full state carries bulky intermediate data (raw orchestrator result, parsed hypotheses, the hypothesis-space markdown, investigator identities). Returning all of it makes the dashboard output unreadable, so surface just the detailed final answer, falling back to summary if a subclass produced one instead.

Source code in src/ursa/workflows/hypothesis_orchestrator.py
def format_result(self, result: Mapping[str, Any]) -> str:
    """Return only the final write-up, not the whole state.

    The full state carries bulky intermediate data (raw orchestrator result,
    parsed hypotheses, the hypothesis-space markdown, investigator
    identities). Returning all of it makes the dashboard output unreadable,
    so surface just the detailed final answer, falling back to ``summary``
    if a subclass produced one instead.
    """
    detailed = result.get("final")
    summary = result.get("summary")
    text = detailed or summary
    if not text:
        raise ValueError("Orchestration completed without a response.")
    return str(text).strip()

HypothesisSymposiumState

Bases: TypedDict

Parent graph state.

Fan-in requires reducer channels, so investigation results and failures use operator.add accumulators. Overwrite([]) resets them between phases.

Source code in src/ursa/workflows/hypothesis_symposium.py
class HypothesisSymposiumState(TypedDict, total=False):
    """Parent graph state.

    Fan-in requires reducer channels, so investigation results and failures use
    ``operator.add`` accumulators. ``Overwrite([])`` resets them between phases.
    """

    query: str
    context: str
    experience_filename: str

    hypotheses: list[dict[str, Any]]
    investigations: Annotated[list[dict[str, Any]], operator.add]
    failures: Annotated[list[dict[str, Any]], operator.add]

    evidence_digest: str
    symposium_result: dict[str, Any]
    symposium_run_id: str
    synthesis: str
    hypothesis_space_markdown: str
    summary: str

HypothesisSymposiumWorkflow

Bases: WorkflowToolsMixin, BaseWorkflow

Hypothesize -> fan out -> investigate -> converge -> review -> update.

Every scientific phase is exposed as an overridable hook so a later Plan D layer can replace the fixed multi-round symposium with orchestrated all-member dispatch plus adaptive follow-up. The default :meth:run_symposium uses the hardened :class:AgentSymposiumEnvironment so member failures are contained rather than fatal.

Source code in src/ursa/workflows/hypothesis_symposium.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
class HypothesisSymposiumWorkflow(WorkflowToolsMixin, BaseWorkflow):
    """Hypothesize -> fan out -> investigate -> converge -> review -> update.

    Every scientific phase is exposed as an overridable hook so a later Plan D
    layer can replace the fixed multi-round symposium with orchestrated
    all-member dispatch plus adaptive follow-up. The default
    :meth:`run_symposium` uses the hardened :class:`AgentSymposiumEnvironment`
    so member failures are contained rather than fatal.
    """

    state_type = HypothesisSymposiumState

    def __init__(
        self,
        llm: BaseChatModel,
        *,
        hypothesizer: HypothesizerAgent | None = None,
        experience_filename: str = DEFAULT_HYPOTHESIS_EXPERIENCE,
        max_hypotheses: int = 5,
        revision_rounds: int = 1,
        symposium: Any | None = None,
        workspace: str | Path | None = None,
        group: str | None = None,
        name: str = "hypothesis_symposium",
        checkpointer: Any | None = None,
        thread_id: str | None = None,
        recursion_limit: int = 200,
        visualize: bool = True,
        **kwargs: Any,
    ) -> None:
        super().__init__(**kwargs)
        self.llm = llm
        # Preserve the caller/dashboard-provided workspace so the internal
        # symposium (and its per-hypothesis members) run under it instead of
        # silently falling back to the shared cache directory. Previously this
        # was swallowed into **kwargs and discarded by BaseWorkflow.__init__.
        self.workspace = Path(workspace) if workspace else None
        self.group = group
        self.thread_id = thread_id or str(uuid4())
        # Display name for the internal symposium environment. It surfaces on
        # the dashboard Runs page, so keep it short and human-readable rather
        # than deriving it from the (long) class name.
        self.name = name
        self.experience_filename = (
            HypothesizerAgent._validate_experience_filename(experience_filename)
        )
        self.hypothesizer = hypothesizer or HypothesizerAgent(
            llm,
            experience_filename=self.experience_filename,
            workspace=self.workspace,
            group=self.group,
            **self._agent_kwargs,
        )
        self.max_hypotheses = max(1, int(max_hypotheses))
        self.revision_rounds = max(1, int(revision_rounds))
        self._symposium = symposium
        # When true, the symposium stage is wrapped in the environment
        # visualization recorder so the dashboard can follow it *while running*
        # (the recorder flushes each event to events.jsonl immediately).
        self.visualize = bool(visualize)
        self.symposium_run_id: str | None = None
        self.recursion_limit = int(recursion_limit)
        self.checkpointer = checkpointer or InMemorySaver()
        # Branch retries: RetryPolicy's default predicate refuses common builtin
        # exceptions, so retry broadly on any Exception (cancellations excluded
        # by langgraph itself).
        self._branch_retry = RetryPolicy(
            max_attempts=2,
            initial_interval=0.1,
            retry_on=lambda exc: isinstance(exc, Exception),
        )
        self._graph = self._build_graph()

    # ------------------------------------------------------------------ graph

    def _build_graph(self) -> Any:
        builder = StateGraph(self.state_type)
        builder.add_node("hypothesize", self._node_hypothesize)
        builder.add_node(
            "investigate",
            RunnableLambda(
                self._node_investigate_sync,
                afunc=self._node_investigate_async,
            ),
            retry_policy=self._branch_retry,
        )
        builder.add_node("converge", self._node_converge)
        builder.add_node("symposium", self._node_symposium)
        builder.add_node("synthesize", self._node_synthesize)
        builder.add_node("update_space", self._node_update_space)

        builder.add_edge(START, "hypothesize")
        # A node cannot both return a dict and Send list, so the fan-out lives
        # in a conditional edge keyed off the hypotheses produced upstream.
        builder.add_conditional_edges(
            "hypothesize", self._fan_out, ["investigate", "converge"]
        )
        builder.add_edge("investigate", "converge")
        builder.add_edge("converge", "symposium")
        builder.add_edge("symposium", "synthesize")
        builder.add_edge("synthesize", "update_space")
        builder.add_edge("update_space", END)
        return builder.compile(checkpointer=self.checkpointer)

    # ------------------------------------------------------------ graph nodes

    def _node_hypothesize(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        hypotheses = self.build_hypotheses(state, config)
        return {
            "hypotheses": [
                {
                    "index": h.index,
                    "statement": h.statement,
                    "detail": h.detail,
                }
                for h in hypotheses
            ],
            # Reset accumulators so re-entry / re-runs start clean.
            "investigations": Overwrite([]),
            "failures": Overwrite([]),
        }

    def _fan_out(self, state: HypothesisSymposiumState) -> list[Send] | str:
        hypotheses = state.get("hypotheses") or []
        if not hypotheses:
            return "converge"
        return [
            Send("investigate", {"query": state.get("query", ""), **h})
            for h in hypotheses
        ]

    def _investigate(
        self, payload: Mapping[str, Any], config: RunnableConfig
    ) -> dict[str, Any]:
        hypothesis = Hypothesis(
            index=int(payload.get("index", 0)),
            statement=str(payload.get("statement", "")),
            detail=str(payload.get("detail", "")),
        )
        query = str(payload.get("query", ""))
        try:
            outcome = self.investigate_hypothesis(hypothesis, query, config)
        except Exception as exc:  # noqa: BLE001
            # Quarantine: record the failing branch as data. langgraph's
            # error_handler/timeout cannot suppress a sync failure, so we do it
            # here to preserve sibling branches (RetryPolicy already retried).
            failed = HypothesisInvestigation(
                index=hypothesis.index,
                statement=hypothesis.statement,
                ok=False,
                error=f"{type(exc).__name__}: {exc}",
            )
            return {"failures": [failed.__dict__]}
        return {"investigations": [outcome.__dict__]}

    def _node_investigate_sync(
        self, payload: Mapping[str, Any], config: RunnableConfig
    ) -> dict[str, Any]:
        return self._investigate(payload, config)

    async def _node_investigate_async(
        self, payload: Mapping[str, Any], config: RunnableConfig
    ) -> dict[str, Any]:
        hypothesis = Hypothesis(
            index=int(payload.get("index", 0)),
            statement=str(payload.get("statement", "")),
            detail=str(payload.get("detail", "")),
        )
        query = str(payload.get("query", ""))
        try:
            outcome = await self.ainvestigate_hypothesis(
                hypothesis, query, config
            )
        except Exception as exc:  # noqa: BLE001
            failed = HypothesisInvestigation(
                index=hypothesis.index,
                statement=hypothesis.statement,
                ok=False,
                error=f"{type(exc).__name__}: {exc}",
            )
            return {"failures": [failed.__dict__]}
        return {"investigations": [outcome.__dict__]}

    def _node_converge(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        return {"evidence_digest": self.converge(state, config)}

    async def _node_symposium(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        result = await self.run_symposium(state, config)
        update: dict[str, Any] = {"symposium_result": result}
        # Surface the visualization run id in state so the dashboard/caller can
        # locate the live event stream for this symposium stage.
        if self.symposium_run_id:
            update["symposium_run_id"] = self.symposium_run_id
        return update

    async def _node_synthesize(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        return {"synthesis": await self.synthesize(state, config)}

    async def _node_update_space(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        return await self.update_hypothesis_space(state, config)

    # ------------------------------------------------------- overridable hooks

    def format_result(self, result: HypothesisSymposiumState) -> str:
        """Return only the final write-up, not the whole state.

        Prefers the symposium's detailed final answer and falls back to the
        shorter synthesized ``summary`` when the symposium produced no final
        text (for example if the stage was skipped).
        """
        symposium_result = result.get("symposium_result")
        detailed = (
            symposium_result.get("final")
            if isinstance(symposium_result, Mapping)
            else None
        )
        summary = result.get("summary")
        text = detailed or summary
        if not text:
            raise ValueError("Symposium completed without a response.")
        return str(text).strip()

    def build_hypotheses(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> list[Hypothesis]:
        """Produce competing hypotheses via the HypothesizerAgent.

        The hypothesizer maintains a durable markdown artifact whose competing
        hypotheses are ``### H...`` lines; those become the fan-out branches.
        """
        query = str(state.get("query", ""))
        result = invoke_agent(
            self.hypothesizer,
            {
                "query": query,
                "new_information": query,
                "context": str(state.get("context", "")),
                "experience_filename": self.experience_filename,
                "revision_history": [],
            },
            config=config,
        )
        artifact = self._artifact_text(result)
        state["hypothesis_space_markdown"] = artifact
        return self._parse_hypotheses(artifact, query)

    def investigate_hypothesis(
        self,
        hypothesis: Hypothesis,
        query: str,
        config: RunnableConfig,
    ) -> HypothesisInvestigation:
        """Default synchronous investigation (assignment record).

        In the default design (A) the *substantive* per-hypothesis
        investigation is performed by the symposium member that owns this
        hypothesis (during the symposium's initial-work phase), so this fan-out
        branch only records the assignment that will be handed to that member.
        This keeps the fan-out / quarantine / fan-in plumbing intact as the
        Plan D seam: a subclass can override this (or
        :meth:`ainvestigate_hypothesis`) to dispatch a dedicated investigation
        agent per branch instead of (or in addition to) the symposium.
        """
        return HypothesisInvestigation(
            index=hypothesis.index,
            statement=hypothesis.statement,
            findings=(
                f"Assigned to a dedicated symposium member for investigation: "
                f"{hypothesis.as_task(query)}"
            ),
            ok=True,
        )

    async def ainvestigate_hypothesis(
        self,
        hypothesis: Hypothesis,
        query: str,
        config: RunnableConfig,
    ) -> HypothesisInvestigation:
        """Async investigation hook; defaults to the sync implementation."""
        return self.investigate_hypothesis(hypothesis, query, config)

    def converge(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> str:
        """Fan-in: assemble the per-hypothesis findings into one digest."""
        investigations = [
            HypothesisInvestigation(**d)
            for d in state.get("investigations", [])
        ]
        failures = [
            HypothesisInvestigation(**d) for d in state.get("failures", [])
        ]
        ordered = sorted(investigations + failures, key=lambda i: i.index)
        parts = [i.as_markdown() for i in ordered]
        if failures:
            parts.append(
                f"\n_{len(failures)} of {len(ordered)} investigation "
                "branch(es) failed and were recorded above._"
            )
        return "\n\n".join(parts)

    async def run_symposium(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        """Cross-review + multi-round revision over the collected evidence.

        The default symposium assigns one member per hypothesis (design A): each
        member investigates its own hypothesis during initial work, then reads
        every member's investigation during review to adjudicate which
        hypothesis the combined evidence best supports. Isolated behind this
        hook so a Plan D layer can swap the fixed loop for orchestrated
        all-member dispatch + adaptive follow-up. The underlying environment is
        the hardened symposium (member failures are contained).
        """
        hypotheses = [
            Hypothesis(
                index=int(h.get("index", 0)),
                statement=str(h.get("statement", "")),
                detail=str(h.get("detail", "")),
            )
            for h in (state.get("hypotheses") or [])
        ]
        symposium = self._get_symposium(hypotheses)
        digest = str(state.get("evidence_digest", ""))
        digest_block = (
            "\n\nPrior per-hypothesis notes gathered before this symposium "
            f"(shared context):\n{digest}"
            if digest.strip()
            else ""
        )
        task = (
            f"Question: {state.get('query', '')}\n\n"
            "Each member has been assigned one competing hypothesis as its "
            "expertise. Investigate your own hypothesis, then cross-review the "
            "others, challenge weak evidence, and converge on which hypothesis "
            f"is best supported.{digest_block}"
        )
        try:
            return await self._ainvoke_symposium(symposium, task, config)
        finally:
            if self._symposium is None:
                for agent in [*symposium.members.values(), symposium.organizer]:
                    await agent.aclose()
                    agent.close()

    async def _ainvoke_symposium(
        self, symposium: Any, task: str, config: RunnableConfig
    ) -> dict[str, Any]:
        """Invoke the symposium, recording a live visualization run when enabled.

        ``arun_with_visualization`` attaches an ``EnvironmentEventRecorder``
        callback to the run config and flushes every structured progress event
        to ``events.jsonl`` as it happens, so the dashboard can render the
        symposium *while it is still running* instead of only at the end. The
        run id is stashed on the workflow (and logged) so callers can locate the
        stream. Any failure to set up visualization must never break the
        science, so we degrade to a plain ``ainvoke``.
        """
        if not self.visualize:
            return await symposium.ainvoke(task, config=config)

        try:
            from ursa.environments import arun_with_visualization
        except Exception:  # pragma: no cover - defensive import guard
            logger.warning(
                "Symposium visualization unavailable; running unrecorded.",
                exc_info=True,
            )
            return await symposium.ainvoke(task, config=config)

        run_id = self._new_symposium_run_id()
        group = getattr(symposium, "group", None) or "default"
        # Decide whether visualization is viable *before* invoking: a failure
        # after the run has started would either lose the result or re-run the
        # whole (expensive) symposium.
        try:
            from ursa.security import validate_group_name

            validate_group_name(group)
        except Exception:
            logger.warning(
                "Symposium group %r is not recordable; running unrecorded.",
                group,
                exc_info=True,
            )
            return await symposium.ainvoke(task, config=config)

        self.symposium_run_id = run_id
        logger.info(
            "Symposium visualization run started: group=%s run_id=%s "
            "(events stream live to the dashboard)",
            group,
            run_id,
        )
        return await arun_with_visualization(
            symposium, task, config=config, run_id=run_id
        )

    @staticmethod
    def _new_symposium_run_id() -> str:
        """Readable, sortable, unique run id for one symposium stage."""
        return f"hypsym_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid4().hex[:8]}"

    async def synthesize(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> str:
        """Turn the symposium result into a final verdict string."""
        result = state.get("symposium_result") or {}
        final = result.get("final") if isinstance(result, Mapping) else None
        if final:
            return str(final)
        return str(state.get("evidence_digest", ""))

    async def update_hypothesis_space(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        """Fold ALL new information back into the durable hypothesis space."""
        query = str(state.get("query", ""))
        new_information = self._final_new_information(state)
        result = await ainvoke_agent(
            self.hypothesizer,
            {
                "query": query,
                "new_information": new_information,
                "context": str(state.get("context", "")),
                "experience_filename": self.experience_filename,
                "revision_history": [],
            },
            config=config,
        )
        artifact = self._artifact_text(result)
        summary = ""
        if isinstance(result, Mapping):
            summary = str(result.get("summary", "") or "")
        return {
            "hypothesis_space_markdown": artifact,
            "summary": summary,
        }

    # ------------------------------------------------------------- helpers

    def _final_new_information(self, state: HypothesisSymposiumState) -> str:
        sections = [
            "New information gathered during hypothesis investigation and "
            "symposium review:",
            "",
            "## Per-hypothesis investigation digest",
            str(state.get("evidence_digest", "")),
            "",
            "## Symposium synthesis / verdict",
            str(state.get("synthesis", "")),
        ]
        return "\n".join(sections)

    def _parse_hypotheses(self, artifact: str, query: str) -> list[Hypothesis]:
        return parse_hypotheses(
            artifact, query, max_hypotheses=self.max_hypotheses
        )

    @staticmethod
    def _artifact_text(result: Any) -> str:
        return artifact_text(result)

    def _get_symposium(
        self, hypotheses: Sequence[Hypothesis] | None = None
    ) -> Any:
        # An explicitly injected symposium is used as-is. Otherwise the default
        # symposium is built per run so its members reflect the current
        # hypotheses, while the environment retains them across review rounds.
        if self._symposium is not None:
            return self._symposium
        return self._build_default_symposium(hypotheses or [])

    def _hypothesis_member_name(self, hypothesis: Hypothesis) -> str:
        """Stable, filesystem/tool-safe member name for one hypothesis."""
        words = "".join(
            ch.lower() if ch.isalnum() else " " for ch in hypothesis.statement
        ).split()
        slug = "_".join(words[:4]) or "hypothesis"
        return f"h{hypothesis.index}_{slug}"[:48]

    def _build_default_symposium(self, hypotheses: Sequence[Hypothesis]) -> Any:
        """Build a symposium with one member per hypothesis (design A).

        Each member is assigned exactly one hypothesis as its expertise. During
        the symposium's initial-work phase the member investigates *its* own
        hypothesis (gathering evidence for and against it); during the review
        phase every member reads every other member's investigation, so all
        members can learn from the shared evidence while adjudicating which
        hypothesis is best supported. This is the "specialist-per-hypothesis"
        design: guaranteed coverage of every hypothesis, real per-hypothesis
        parallel investigation, and a naturally adversarial cross-review.
        """
        from ursa.environments.agent_symposium import (
            AgentSymposiumEnvironment,
        )
        from ursa.environments.config import EnvironmentMemberConfig

        members = []
        for hypothesis in hypotheses:
            detail = (
                f"\n\nSupporting detail from the hypothesis space:\n{hypothesis.detail}"
                if hypothesis.detail
                else ""
            )
            members.append(
                EnvironmentMemberConfig(
                    name=self._hypothesis_member_name(hypothesis),
                    role=(
                        f"Advocate/investigator for hypothesis H{hypothesis.index}: "
                        f"{hypothesis.statement}"
                    ),
                    agent="ChatAgent",
                    config=dict(self._tool_agent_kwargs),
                    reviewer=True,
                    prompt=(
                        "Your assigned hypothesis (your expertise for this "
                        f"symposium) is H{hypothesis.index}: "
                        f"{hypothesis.statement}.{detail}\n\n"
                        "During your initial work, rigorously investigate THIS "
                        "hypothesis only: gather concrete evidence for and "
                        "against it (write and run code, produce data/plots, and "
                        "quantify results where possible). Do not investigate the "
                        "other hypotheses now — other members own those. During "
                        "the review phase you will read every member's "
                        "investigation and help judge which hypothesis the "
                        "combined evidence best supports."
                    ),
                )
            )
        if not members:
            # No hypotheses parsed: fall back to a single generalist member so
            # the symposium still produces a usable adjudication.
            members.append(
                EnvironmentMemberConfig(
                    name="generalist",
                    role="Hypothesis investigator and reviewer",
                    agent="ChatAgent",
                    config=dict(self._tool_agent_kwargs),
                    reviewer=True,
                )
            )
        symposium = AgentSymposiumEnvironment(
            self.llm,
            name=self.name,
            organizer=EnvironmentMemberConfig(
                name="organizer",
                role="Symposium organizer / final synthesizer",
                agent="ChatAgent",
                config=dict(self._tool_agent_kwargs),
            ),
            members=members,
            revision_rounds=self.revision_rounds,
            persist_members=False,
            # Thread the workflow workspace/group through so members run under
            # the caller/dashboard-provided workspace instead of the shared
            # cache directory. Passing None preserves BaseEnvironment defaults.
            workspace=self.workspace,
            group=self.group,
        )
        if self._extra_tools:
            for agent in [*symposium.members.values(), symposium.organizer]:
                agent.add_tool(list(self._extra_tools.values()))
        return symposium

    # ------------------------------------------------------------- run surface

    def _base_config(self, config: Mapping[str, Any] | None) -> RunnableConfig:
        cfg: dict[str, Any] = dict(config or {})
        cfg.setdefault("recursion_limit", self.recursion_limit)
        configurable = dict(cfg.get("configurable", {}))
        configurable.setdefault("thread_id", self.thread_id)
        cfg["configurable"] = configurable
        return cfg  # type: ignore[return-value]

    def _prepare_state(
        self, inputs: Mapping[str, Any]
    ) -> HypothesisSymposiumState:
        query = str(inputs.get("query") or inputs.get("task") or "")
        return HypothesisSymposiumState(
            query=query,
            context=str(inputs.get("context", "")),
            experience_filename=self.experience_filename,
            investigations=[],
            failures=[],
        )

    def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        # The graph contains async-only nodes (symposium/synthesis/update run
        # async agent calls), so sync callers drive the async graph through a
        # boundary event loop, mirroring BaseEnvironment.
        try:
            asyncio.get_running_loop()
        except RuntimeError:
            return asyncio.run(self._ainvoke(inputs, **config))
        raise RuntimeError(
            "HypothesisSymposiumWorkflow uses async execution internally, but "
            "`.invoke()` was called from an async context. Use "
            "`await workflow.ainvoke(...)` instead."
        )

    async def _ainvoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        cfg = self._base_config(config.get("config"))
        return await self._graph.ainvoke(self._prepare_state(inputs), cfg)

    def _normalize_inputs(self, inputs: InputLike) -> Mapping[str, Any]:
        if isinstance(inputs, str):
            return {"query": inputs}
        if isinstance(inputs, Mapping):
            return inputs
        raise TypeError(f"Unsupported input type: {type(inputs)}")

ainvestigate_hypothesis(hypothesis, query, config) async

Async investigation hook; defaults to the sync implementation.

Source code in src/ursa/workflows/hypothesis_symposium.py
async def ainvestigate_hypothesis(
    self,
    hypothesis: Hypothesis,
    query: str,
    config: RunnableConfig,
) -> HypothesisInvestigation:
    """Async investigation hook; defaults to the sync implementation."""
    return self.investigate_hypothesis(hypothesis, query, config)

build_hypotheses(state, config)

Produce competing hypotheses via the HypothesizerAgent.

The hypothesizer maintains a durable markdown artifact whose competing hypotheses are ### H... lines; those become the fan-out branches.

Source code in src/ursa/workflows/hypothesis_symposium.py
def build_hypotheses(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> list[Hypothesis]:
    """Produce competing hypotheses via the HypothesizerAgent.

    The hypothesizer maintains a durable markdown artifact whose competing
    hypotheses are ``### H...`` lines; those become the fan-out branches.
    """
    query = str(state.get("query", ""))
    result = invoke_agent(
        self.hypothesizer,
        {
            "query": query,
            "new_information": query,
            "context": str(state.get("context", "")),
            "experience_filename": self.experience_filename,
            "revision_history": [],
        },
        config=config,
    )
    artifact = self._artifact_text(result)
    state["hypothesis_space_markdown"] = artifact
    return self._parse_hypotheses(artifact, query)

converge(state, config)

Fan-in: assemble the per-hypothesis findings into one digest.

Source code in src/ursa/workflows/hypothesis_symposium.py
def converge(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> str:
    """Fan-in: assemble the per-hypothesis findings into one digest."""
    investigations = [
        HypothesisInvestigation(**d)
        for d in state.get("investigations", [])
    ]
    failures = [
        HypothesisInvestigation(**d) for d in state.get("failures", [])
    ]
    ordered = sorted(investigations + failures, key=lambda i: i.index)
    parts = [i.as_markdown() for i in ordered]
    if failures:
        parts.append(
            f"\n_{len(failures)} of {len(ordered)} investigation "
            "branch(es) failed and were recorded above._"
        )
    return "\n\n".join(parts)

format_result(result)

Return only the final write-up, not the whole state.

Prefers the symposium's detailed final answer and falls back to the shorter synthesized summary when the symposium produced no final text (for example if the stage was skipped).

Source code in src/ursa/workflows/hypothesis_symposium.py
def format_result(self, result: HypothesisSymposiumState) -> str:
    """Return only the final write-up, not the whole state.

    Prefers the symposium's detailed final answer and falls back to the
    shorter synthesized ``summary`` when the symposium produced no final
    text (for example if the stage was skipped).
    """
    symposium_result = result.get("symposium_result")
    detailed = (
        symposium_result.get("final")
        if isinstance(symposium_result, Mapping)
        else None
    )
    summary = result.get("summary")
    text = detailed or summary
    if not text:
        raise ValueError("Symposium completed without a response.")
    return str(text).strip()

investigate_hypothesis(hypothesis, query, config)

Default synchronous investigation (assignment record).

In the default design (A) the substantive per-hypothesis investigation is performed by the symposium member that owns this hypothesis (during the symposium's initial-work phase), so this fan-out branch only records the assignment that will be handed to that member. This keeps the fan-out / quarantine / fan-in plumbing intact as the Plan D seam: a subclass can override this (or :meth:ainvestigate_hypothesis) to dispatch a dedicated investigation agent per branch instead of (or in addition to) the symposium.

Source code in src/ursa/workflows/hypothesis_symposium.py
def investigate_hypothesis(
    self,
    hypothesis: Hypothesis,
    query: str,
    config: RunnableConfig,
) -> HypothesisInvestigation:
    """Default synchronous investigation (assignment record).

    In the default design (A) the *substantive* per-hypothesis
    investigation is performed by the symposium member that owns this
    hypothesis (during the symposium's initial-work phase), so this fan-out
    branch only records the assignment that will be handed to that member.
    This keeps the fan-out / quarantine / fan-in plumbing intact as the
    Plan D seam: a subclass can override this (or
    :meth:`ainvestigate_hypothesis`) to dispatch a dedicated investigation
    agent per branch instead of (or in addition to) the symposium.
    """
    return HypothesisInvestigation(
        index=hypothesis.index,
        statement=hypothesis.statement,
        findings=(
            f"Assigned to a dedicated symposium member for investigation: "
            f"{hypothesis.as_task(query)}"
        ),
        ok=True,
    )

run_symposium(state, config) async

Cross-review + multi-round revision over the collected evidence.

The default symposium assigns one member per hypothesis (design A): each member investigates its own hypothesis during initial work, then reads every member's investigation during review to adjudicate which hypothesis the combined evidence best supports. Isolated behind this hook so a Plan D layer can swap the fixed loop for orchestrated all-member dispatch + adaptive follow-up. The underlying environment is the hardened symposium (member failures are contained).

Source code in src/ursa/workflows/hypothesis_symposium.py
async def run_symposium(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> dict[str, Any]:
    """Cross-review + multi-round revision over the collected evidence.

    The default symposium assigns one member per hypothesis (design A): each
    member investigates its own hypothesis during initial work, then reads
    every member's investigation during review to adjudicate which
    hypothesis the combined evidence best supports. Isolated behind this
    hook so a Plan D layer can swap the fixed loop for orchestrated
    all-member dispatch + adaptive follow-up. The underlying environment is
    the hardened symposium (member failures are contained).
    """
    hypotheses = [
        Hypothesis(
            index=int(h.get("index", 0)),
            statement=str(h.get("statement", "")),
            detail=str(h.get("detail", "")),
        )
        for h in (state.get("hypotheses") or [])
    ]
    symposium = self._get_symposium(hypotheses)
    digest = str(state.get("evidence_digest", ""))
    digest_block = (
        "\n\nPrior per-hypothesis notes gathered before this symposium "
        f"(shared context):\n{digest}"
        if digest.strip()
        else ""
    )
    task = (
        f"Question: {state.get('query', '')}\n\n"
        "Each member has been assigned one competing hypothesis as its "
        "expertise. Investigate your own hypothesis, then cross-review the "
        "others, challenge weak evidence, and converge on which hypothesis "
        f"is best supported.{digest_block}"
    )
    try:
        return await self._ainvoke_symposium(symposium, task, config)
    finally:
        if self._symposium is None:
            for agent in [*symposium.members.values(), symposium.organizer]:
                await agent.aclose()
                agent.close()

synthesize(state, config) async

Turn the symposium result into a final verdict string.

Source code in src/ursa/workflows/hypothesis_symposium.py
async def synthesize(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> str:
    """Turn the symposium result into a final verdict string."""
    result = state.get("symposium_result") or {}
    final = result.get("final") if isinstance(result, Mapping) else None
    if final:
        return str(final)
    return str(state.get("evidence_digest", ""))

update_hypothesis_space(state, config) async

Fold ALL new information back into the durable hypothesis space.

Source code in src/ursa/workflows/hypothesis_symposium.py
async def update_hypothesis_space(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> dict[str, Any]:
    """Fold ALL new information back into the durable hypothesis space."""
    query = str(state.get("query", ""))
    new_information = self._final_new_information(state)
    result = await ainvoke_agent(
        self.hypothesizer,
        {
            "query": query,
            "new_information": new_information,
            "context": str(state.get("context", "")),
            "experience_filename": self.experience_filename,
            "revision_history": [],
        },
        config=config,
    )
    artifact = self._artifact_text(result)
    summary = ""
    if isinstance(result, Mapping):
        summary = str(result.get("summary", "") or "")
    return {
        "hypothesis_space_markdown": artifact,
        "summary": summary,
    }

PlanningExecutionAgent

Bases: BaseAgent[PlanExecuteState]

Plan a task and execute each plan step in one persistent graph.

The agent uses one underlying LLM for planning, reflection, tool-driven execution, review, and recap. Both child agents are compiled with checkpointer=True so they inherit the parent agent's checkpointer and receive LangGraph-managed nested checkpoint namespaces.

max_reflection_steps configures the planner. All remaining keyword arguments are the normal :class:ExecutionAgent / :class:BaseAgent options, including workspace, tools, persistence, thread, telemetry, and retention settings.

Source code in src/ursa/workflows/planning_execution_workflow.py
class PlanningExecutionAgent(BaseAgent[PlanExecuteState]):
    """Plan a task and execute each plan step in one persistent graph.

    The agent uses one underlying LLM for planning, reflection, tool-driven
    execution, review, and recap. Both child agents are compiled with
    ``checkpointer=True`` so they inherit the parent agent's
    checkpointer and receive LangGraph-managed nested checkpoint namespaces.

    ``max_reflection_steps`` configures the planner. All remaining keyword
    arguments are the normal :class:`ExecutionAgent` / :class:`BaseAgent`
    options, including workspace, tools, persistence, thread, telemetry, and
    retention settings.
    """

    state_type = PlanExecuteState

    def __init__(
        self,
        llm: BaseChatModel,
        max_reflection_steps: int = 1,
        log_state: bool = False,
        extra_tools: list[BaseTool] | None = None,
        tokens_before_summarize: int = 50000,
        messages_to_keep: int = 20,
        use_web: bool = False,
        safe_codes: list[str] | None = None,
        **kwargs: Any,
    ) -> None:
        self.max_reflection_steps = max_reflection_steps
        self._child_llm_source = llm
        super().__init__(
            llm,
            tokens_before_summarize=tokens_before_summarize,
            messages_to_keep=messages_to_keep,
            **kwargs,
        )
        child_kwargs = {
            "workspace": self.workspace,
            "group": self.group,
            "thread_id": self.thread_id,
            "enable_metrics": False,
            "rag_tools": self.rag_tools,
            "rag_tool_group": self.rag_tool_group,
            "rag_tool_embedding": self.rag_tool_embedding,
            "rag_tool_return_k": self.rag_tool_return_k,
            "max_single_tool_message_tokens": (
                self.max_single_tool_message_tokens
            ),
        }
        self.planner_agent = PlanningAgent(
            llm,
            max_reflection_steps=max_reflection_steps,
            **child_kwargs,
        )
        self.execution_agent = ExecutionAgent(
            llm,
            log_state=log_state,
            extra_tools=extra_tools,
            tokens_before_summarize=tokens_before_summarize,
            messages_to_keep=messages_to_keep,
            use_web=use_web,
            safe_codes=safe_codes,
            **child_kwargs,
        )

    def _normalize_inputs(self, inputs: Any) -> dict[str, Any] | Command:
        normalized_input = super()._normalize_inputs(inputs)
        if isinstance(normalized_input, Command):
            return normalized_input
        normalized = dict(normalized_input)
        task = str(normalized.get("task", "") or "").strip()
        if not task:
            for message in reversed(normalized.get("messages", [])):
                text = message_text(message).strip()
                if text:
                    task = text
                    break
        if not task:
            raise ValueError(
                "PlanningExecutionAgent requires a task or message input."
            )
        # A scalar task channel ensures a new invocation on a persistent thread
        # supersedes the previous invocation's task.
        normalized["task"] = task
        # Symlink requests are invocation-scoped. An explicit empty mapping
        # prevents a prior persistent-thread request from leaking forward.
        normalized.setdefault("symlinkdir", {})
        return normalized

    def format_query(
        self, prompt: str, state: PlanExecuteState | None = None
    ) -> PlanExecuteState:
        query: dict[str, Any] = dict(state or {})
        query.update({
            "task": prompt,
            "messages": [HumanMessage(content=prompt)],
        })
        return cast(PlanExecuteState, query)

    def format_result(self, result: PlanExecuteState) -> str:
        messages = result.get("messages", [])
        if not messages:
            raise ValueError("Planning execution completed without a response.")
        return message_text(messages[-1])

    def _prepare_planning(self, state: PlanExecuteState) -> PlanExecuteState:
        task = str(state.get("task", "") or "").strip()
        if not task:
            raise ValueError(
                "PlanningExecutionAgent requires a task or message input."
            )
        self.events().emit("Planning task", stage="planning")
        return cast(
            PlanExecuteState,
            {
                "task": task,
                "step_idx": 0,
                "step_results": [],
                # Do not leak an earlier persistent run or executor transcript
                # into the planner. The planner's own full state remains in its
                # nested checkpoint namespace.
                "messages": Overwrite([HumanMessage(content=task)]),
                "symlinkdir": dict(state.get("symlinkdir", {})),
            },
        )

    @staticmethod
    def _last_step_summary(state: PlanExecuteState) -> str | None:
        results = state.get("step_results", [])
        if not results:
            return None
        summary = str(results[-1]).strip()
        return summary or None

    def _step_prompt(self, state: PlanExecuteState) -> str:
        plan = state.get("plan")
        if plan is None:
            raise ValueError("The planner completed without producing a plan.")
        if not plan.steps:
            raise ValueError(
                "The planner produced an empty plan; at least one step is required."
            )

        step_idx = state.get("step_idx", 0)
        if step_idx < 0 or step_idx >= len(plan.steps):
            raise ValueError(f"Invalid plan step index {step_idx}.")
        plan_step = plan.steps[step_idx]

        prompt_parts = [
            f"You are contributing to the larger solution:\n{state['task']}"
        ]
        if previous := self._last_step_summary(state):
            prompt_parts.append(f"Previous-step summary:\n{previous}")
        prompt_parts.extend([
            f"Current step:\n{plan_step}",
            (
                "Execute this step and report concrete results for the executor "
                "of the next step. Do not use placeholders. Run commands to "
                "execute generated code when applicable. Only address the "
                "current step."
            ),
        ])
        return "\n\n".join(prompt_parts)

    def _prepare_step(self, state: PlanExecuteState) -> PlanExecuteState:
        prompt = self._step_prompt(state)
        step_idx = state.get("step_idx", 0)
        self.events().emit(
            "Executing plan step",
            stage="execute_step",
            step=step_idx + 1,
            total=len(state["plan"].steps),
        )
        return cast(
            PlanExecuteState,
            {
                # Each executor subgraph invocation receives a clean transcript.
                # Cross-step context is explicit through step_results.
                "messages": Overwrite([HumanMessage(content=prompt)]),
                "current_user_request": prompt,
                "symlinkdir": state.get("symlinkdir", {}),
            },
        )

    def _record_step(self, state: PlanExecuteState) -> PlanExecuteState:
        messages = state.get("messages", [])
        if not messages:
            raise ValueError(
                "The executor completed a step without a response."
            )
        summary = message_text(messages[-1]).strip()
        if not summary:
            raise ValueError("The executor returned an empty step summary.")
        return cast(
            PlanExecuteState,
            {
                "step_results": [*state.get("step_results", []), summary],
                "step_idx": state.get("step_idx", 0) + 1,
            },
        )

    def _after_step(self, state: PlanExecuteState) -> str:
        plan = state.get("plan")
        if plan is None:
            raise ValueError("The planner completed without producing a plan.")
        if state.get("step_idx", 0) >= len(plan.steps):
            return self._after_plan_completion()
        return "prepare_step"

    def _after_plan_completion(self) -> str:
        """Return the route used after the final execution step."""
        return END

    def _completion_routes(self) -> dict[str, str]:
        """Declare post-execution routes added by a specialized composite."""
        return {END: END}

    def _connect_pre_planner_nodes(self) -> None:
        """Connect preparation to planning; subclasses may insert nodes."""
        self.graph.add_edge("prepare_planning", "planner")

    def _connect_post_execution_nodes(self) -> None:
        """Add specialized nodes reached after all plan steps complete."""

    def _planner_input(self, state: PlanExecuteState) -> PlanningState:
        """Expose only the planner contract to the child agent."""
        return cast(
            PlanningState,
            {
                "task": state["task"],
                "review": "",
                # The child state has an add_messages reducer and a persistent
                # namespace. Replace its transcript for every new plan.
                "messages": Overwrite(list(state.get("messages", []))),
                "reflection_steps": self.max_reflection_steps,
            },
        )

    @staticmethod
    def _planner_output(state: PlanningState) -> PlanExecuteState:
        """Return only the completed plan to the parent graph."""
        plan = state.get("plan")
        if plan is None:
            raise ValueError("The planner completed without producing a plan.")
        return cast(PlanExecuteState, {"plan": plan})

    @staticmethod
    def _executor_input(state: PlanExecuteState) -> ExecutionState:
        """Expose one isolated plan-step request to the executor child."""
        messages = list(state.get("messages", []))
        if not messages:
            raise ValueError("Execution requires a prepared step message.")
        return cast(
            ExecutionState,
            {
                "messages": Overwrite(messages),
                "symlinkdir": dict(state.get("symlinkdir", {})),
                "current_user_request": state.get("current_user_request", ""),
            },
        )

    @staticmethod
    def _executor_output(state: ExecutionState) -> PlanExecuteState:
        """Return the executor transcript and workspace update to the parent."""
        messages = list(state.get("messages", []))
        if not messages:
            raise ValueError("The executor completed without a response.")
        return cast(
            PlanExecuteState,
            {
                "messages": Overwrite(messages),
                "symlinkdir": dict(state.get("symlinkdir", {})),
            },
        )

    def _build_graph(self) -> None:
        self.add_node(self._prepare_planning, "prepare_planning")
        self.add_agent_node(
            "planner",
            self.planner_agent,
            input_fn=self._planner_input,
            output_fn=self._planner_output,
        )
        self.add_node(self._prepare_step, "prepare_step")
        self.add_agent_node(
            "executor",
            self.execution_agent,
            input_fn=self._executor_input,
            output_fn=self._executor_output,
        )
        self.add_node(self._record_step, "record_step")

        self.graph.add_edge(START, "prepare_planning")
        self._connect_pre_planner_nodes()
        self.graph.add_edge("planner", "prepare_step")
        self.graph.add_edge("prepare_step", "executor")
        self.graph.add_edge("executor", "record_step")
        self._connect_post_execution_nodes()
        self.graph.add_conditional_edges(
            "record_step",
            self._wrap_cond(
                self._after_step, "after_step", "planning_execution"
            ),
            {
                "prepare_step": "prepare_step",
                **self._completion_routes(),
            },
        )

PlanningExecutorWorkflow

Bases: BaseWorkflow

Deprecated two-agent planning/execution loop.

This preserves the original planner= / executor= constructor and string return value. New code should use :class:PlanningExecutionAgent, which composes its child agents into a persistent LangGraph.

Source code in src/ursa/workflows/planning_execution_workflow.py
class PlanningExecutorWorkflow(BaseWorkflow):
    """Deprecated two-agent planning/execution loop.

    This preserves the original ``planner=`` / ``executor=`` constructor and
    string return value. New code should use :class:`PlanningExecutionAgent`,
    which composes its child agents into a persistent LangGraph.
    """

    def __init__(
        self,
        planner: Any,
        executor: Any,
        workspace: Any = None,
        **kwargs: Any,
    ) -> None:
        warnings.warn(
            "PlanningExecutorWorkflow is deprecated; use "
            "PlanningExecutionAgent(llm=...) instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(**kwargs)
        self.planner = planner
        self.executor = executor
        self.workspace = workspace

    def _invoke(
        self,
        inputs: Mapping[str, Any],
        *,
        config: dict[str, Any] | None = None,
        **kwargs: Any,
    ) -> str:
        task = str(inputs.get("task", "") or "").strip()
        if not task:
            raise ValueError("PlanningExecutorWorkflow requires a task.")
        invoke_config = dict(config or {})

        with console.status(
            "[bold deep_pink1]Planning overarching steps . . .",
            spinner="point",
            spinner_style="deep_pink1",
        ):
            planner_prompt = (
                f"Break this down into one step per technique:\n{task}"
            )
            planning_output = self.planner.invoke(
                planner_prompt,
                config=invoke_config,
            )
            render_plan_steps_rich(planning_output["plan"].steps)

        last_step_summary = "No previous step."
        for i, step in enumerate(planning_output["plan"].steps):
            step_prompt = (
                f"You are contributing to the larger solution:\n"
                f"{task}\n\n"
                f"Previous-step summary:\n"
                f"{last_step_summary}\n\n"
                f"Current step:\n"
                f"{step}\n\n"
                "Execute this step and report results for the executor of the next step."
                "Do not use placeholders."
                "Run commands to execute code generated for the step if applicable."
                "Only address the current step. Stay in your lane."
            )
            console.print(
                Panel(
                    step_prompt,
                    title=f"[bold orange3 on black]Solving Step {i + 1}",
                    border_style="orange3 on black",
                    style="orange3 on black",
                )
            )
            result = self.executor.invoke(
                step_prompt,
                config=invoke_config,
            )
            last_step_summary = message_text(result["messages"][-1])
            console.print(
                Panel(
                    last_step_summary,
                    title=f"Step {i + 1} Final Response",
                    border_style="orange3 on black",
                    style="orange3 on black",
                )
            )
        return last_step_summary

SimulationUseWorkflow

Bases: BaseWorkflow

Deprecated simulator-schema-aware planning/execution loop.

Source code in src/ursa/workflows/simulation_use_workflow.py
class SimulationUseWorkflow(BaseWorkflow):
    """Deprecated simulator-schema-aware planning/execution loop."""

    def __init__(
        self,
        planner: Any,
        executor: Any,
        workspace: Any,
        tool_description: str,
        **kwargs: Any,
    ) -> None:
        warnings.warn(
            "SimulationUseWorkflow is deprecated; use "
            "PlanningExecutionAgent with simulator tools instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(**kwargs)
        self.planner = planner
        self.executor = executor
        self.workspace = workspace
        self.tool_schema = code_schema_prompt
        self.tool_description = tool_description

    def _invoke(
        self,
        inputs: Mapping[str, Any],
        *,
        config: dict[str, Any] | None = None,
        **kwargs: Any,
    ) -> str:
        task = str(inputs.get("task", "") or "").strip()
        if not task:
            raise ValueError("SimulationUseWorkflow requires a task.")

        with console.status(
            "[bold deep_pink1]Planning overarching steps . . .",
            spinner="point",
            spinner_style="deep_pink1",
        ):
            planner_prompt = (
                f"Break this down into one step per technique:\n{task}"
                "Here is the schema used to describe the computational model:\n"
                f"{self.tool_schema}"
                "Here is the description of what to run using this schema:\n"
                f"{self.tool_description}"
            )
            planning_output = self.planner.invoke(planner_prompt)
            render_plan_steps_rich(planning_output["plan"].steps)

        last_step_summary = "No previous step."
        for i, step in enumerate(planning_output["plan"].steps):
            step_prompt = (
                f"You are contributing to the larger solution:\n{task}\n\n"
                "Here is the schema used to describe a relevant computational model:\n"
                f"{self.tool_schema}\n\n"
                "Here is the description of what to run using this schema:\n"
                f"{self.tool_description}\n\n"
                f"Previous-step summary:\n{last_step_summary}\n\n"
                f"Current step:\n{step}\n\n"
                "Execute this step and report results for the executor of the next step."
                "Do not use placeholders."
                "Run commands to execute code generated for the step if applicable."
                "Only address the current step. Stay in your lane."
            )
            console.print(
                Panel(
                    step_prompt,
                    title=f"[bold orange3 on black]Solving Step {i + 1}",
                    border_style="orange3 on black",
                    style="orange3 on black",
                )
            )
            result = self.executor.invoke(step_prompt)
            last_step_summary = _message_text(result["messages"][-1])
            console.print(
                Panel(
                    last_step_summary,
                    title=f"Step {i + 1} Final Response",
                    border_style="orange3 on black",
                    style="orange3 on black",
                )
            )
        return last_step_summary

SpawnInvestigatorInput

Bases: BaseModel

Input schema for the spawn_investigator orchestrator tool.

Source code in src/ursa/workflows/hypothesis_orchestrator.py
class SpawnInvestigatorInput(BaseModel):
    """Input schema for the ``spawn_investigator`` orchestrator tool."""

    hypothesis_label: str = Field(
        ...,
        description=(
            "Short stable label for the hypothesis this investigator owns, e.g. "
            "'H1' or 'H2_expected_improvement'. Reuse the SAME label to reach the "
            "same persistent agent again (e.g. to have it review others). Do not "
            "call the same label twice within one parallel batch of tool calls."
        ),
    )
    task: str = Field(
        ...,
        description=(
            "Self-contained instructions for the investigator: what to "
            "investigate or review, the evidence to gather, and the deliverable."
        ),
    )

ThinkPlanningExecutionAgent

Bases: PlanningExecutionAgent

Build, investigate, and revise a durable hypothesis space.

One parent runtime adapts URSA's hypothesizer, planner, and executor agents into checkpointed child nodes. The hypothesizer first initializes or updates its durable hypothesis space from the current user request. The planner then creates a plan guided by that space, the executor performs each step, and the resulting summaries return to the hypothesizer as new evidence.

Source code in src/ursa/workflows/think_plan_execute.py
class ThinkPlanningExecutionAgent(PlanningExecutionAgent):
    """Build, investigate, and revise a durable hypothesis space.

    One parent runtime adapts URSA's hypothesizer, planner, and executor agents
    into checkpointed child nodes. The hypothesizer first initializes or
    updates its durable hypothesis space from the current user request. The
    planner then creates a plan guided by that space, the executor performs each
    step, and the resulting summaries return to the hypothesizer as new evidence.
    """

    state_type = ThinkPlanExecuteState

    def __init__(
        self,
        llm: BaseChatModel,
        experience_filename: str = DEFAULT_HYPOTHESIS_EXPERIENCE,
        **kwargs: Any,
    ) -> None:
        # The graph is built during BaseAgent initialization, so this adapter
        # setting must be available before the parent constructor runs.
        self.experience_filename = (
            HypothesizerAgent._validate_experience_filename(experience_filename)
        )
        super().__init__(llm, **kwargs)

    @staticmethod
    def _hypothesis_text(value: Any) -> str:
        return HypothesizerAgent._response_text(value)

    # Public input and follow-up formatting retain the parent workflow contract;
    # adapters isolate the standalone child-agent contracts inside the graph.
    def _normalize_inputs(self, inputs: Any) -> dict[str, Any] | Command:
        return PlanningExecutionAgent._normalize_inputs(self, inputs)

    def format_query(
        self,
        prompt: str,
        state: ThinkPlanExecuteState | None = None,
    ) -> ThinkPlanExecuteState:
        return cast(
            ThinkPlanExecuteState,
            PlanningExecutionAgent.format_query(self, prompt, state),
        )

    def format_result(self, state: ThinkPlanExecuteState) -> str:
        artifact = self._hypothesis_text(
            state.get("hypothesis_space_markdown", "")
        )
        if artifact:
            return artifact
        return PlanningExecutionAgent.format_result(self, state)

    def _build_graph(self) -> None:
        PlanningExecutionAgent._build_graph(self)

    def _prepare_initial_hypothesis(
        self, state: ThinkPlanExecuteState
    ) -> ThinkPlanExecuteState:
        task = state["task"]
        prior_artifact = self._hypothesis_text(
            state.get("hypothesis_space_markdown", "")
        )
        # A follow-up is new evidence for the original question rather than an
        # unrelated replacement. A fresh thread starts a fresh question while
        # the experience artifact can still supply durable background.
        query = (
            str(state.get("query", "") or "").strip()
            if prior_artifact
            else task
        )
        query = query or task
        return cast(
            ThinkPlanExecuteState,
            {
                "query": query,
                "new_information": task,
                "context": (
                    "Treat this as a follow-up request and update the existing "
                    "hypothesis space before planning."
                    if prior_artifact
                    else "Initialize a hypothesis space before planning."
                ),
                "experience_filename": state.get(
                    "experience_filename", self.experience_filename
                ),
                "revision_history": list(state.get("revision_history", [])),
                "hypothesis_phase": "initial",
            },
        )

    def _prepare_results_hypothesis_update(
        self, state: ThinkPlanExecuteState
    ) -> ThinkPlanExecuteState:
        results = [
            str(result).strip()
            for result in state.get("step_results", [])
            if str(result).strip()
        ]
        if not results:
            raise ValueError(
                "Think-plan-execute completed without results to send back "
                "to the hypothesizer."
            )
        summary = "\n".join(
            f"- Step {index}: {result}"
            for index, result in enumerate(results, start=1)
        )
        return cast(
            ThinkPlanExecuteState,
            {
                "query": state.get("query", state["task"]),
                "new_information": (
                    "Execution produced the following evidence and results:\n"
                    f"{summary}"
                ),
                "context": f"Current user request:\n{state['task']}",
                "experience_filename": state.get(
                    "experience_filename", self.experience_filename
                ),
                "revision_history": list(state.get("revision_history", [])),
                "hypothesis_phase": "results",
            },
        )

    def _adopt_hypothesis_space(
        self, state: ThinkPlanExecuteState
    ) -> ThinkPlanExecuteState:
        artifact = self._hypothesis_text(
            state.get("hypothesis_space_markdown", "")
        )
        if not artifact:
            raise ValueError(
                "The hypothesizer completed without producing a hypothesis "
                "space."
            )
        return cast(ThinkPlanExecuteState, {"hypothesis": artifact})

    @staticmethod
    def _after_hypothesis_space(
        state: ThinkPlanExecuteState,
    ) -> Literal["planner", "END"]:
        phase = state.get("hypothesis_phase")
        if phase == "initial":
            return "planner"
        if phase == "results":
            return "END"
        raise ValueError(f"Unknown hypothesis update phase: {phase!r}.")

    @staticmethod
    def _hypothesizer_input(
        state: ThinkPlanExecuteState,
    ) -> HypothesizerState:
        """Expose only the hypothesis-maintenance contract to the child."""
        return cast(
            HypothesizerState,
            {
                key: state[key]
                for key in HypothesizerState.__annotations__
                if key in state
            },
        )

    @staticmethod
    def _hypothesizer_output(
        state: HypothesizerState,
    ) -> ThinkPlanExecuteState:
        """Map the child artifact state back into the composite state."""
        return cast(ThinkPlanExecuteState, dict(state))

    def _planner_input(self, state: ThinkPlanExecuteState) -> PlanningState:
        planner_state = super()._planner_input(state)
        planner_state["hypothesis"] = state.get("hypothesis", "")
        return planner_state

    def _step_prompt(self, state: ThinkPlanExecuteState) -> str:
        prompt = super()._step_prompt(state)
        hypothesis = str(state.get("hypothesis", "") or "").strip()
        if not hypothesis:
            return prompt
        return f"Hypothesis to test or refine:\n{hypothesis}\n\n{prompt}"

    def _connect_pre_planner_nodes(self) -> None:
        if not hasattr(self, "hypothesizer_agent"):
            self.hypothesizer_agent = HypothesizerAgent(
                self._child_llm_source,
                # The child does not own persistence. Point its artifact
                # directory at the parent's den while LangGraph owns
                # checkpoint persistence.
                workspace=self.den,
                group=self.group,
                thread_id=self.thread_id,
                experience_filename=self.experience_filename,
                enable_metrics=False,
            )

        self.add_node(
            self._prepare_initial_hypothesis, "prepare_initial_hypothesis"
        )
        self.add_agent_node(
            "hypothesizer",
            self.hypothesizer_agent,
            input_fn=self._hypothesizer_input,
            output_fn=self._hypothesizer_output,
        )
        self.add_node(self._adopt_hypothesis_space, "adopt_hypothesis_space")
        self.add_node(
            self._prepare_results_hypothesis_update,
            "prepare_results_hypothesis_update",
        )

        self.graph.add_edge("prepare_planning", "prepare_initial_hypothesis")
        self.graph.add_edge("prepare_initial_hypothesis", "hypothesizer")
        self.graph.add_edge("hypothesizer", "adopt_hypothesis_space")
        self.graph.add_conditional_edges(
            "adopt_hypothesis_space",
            self._wrap_cond(
                self._after_hypothesis_space,
                "after_hypothesis_space",
                "think_planning_execution",
            ),
            {"planner": "planner", "END": END},
        )

    def _after_plan_completion(self) -> str:
        return "prepare_results_hypothesis_update"

    def _completion_routes(self) -> dict[str, str]:
        return {
            "prepare_results_hypothesis_update": (
                "prepare_results_hypothesis_update"
            )
        }

    def _connect_post_execution_nodes(self) -> None:
        self.graph.add_edge("prepare_results_hypothesis_update", "hypothesizer")

think_plan_execute_workflow(llm, **agent_kwargs)

Create a persistent hypothesis-plan-execute-update parent agent.

Source code in src/ursa/workflows/think_plan_execute.py
def think_plan_execute_workflow(
    llm: BaseChatModel, **agent_kwargs: Any
) -> ThinkPlanningExecutionAgent:
    """Create a persistent hypothesis-plan-execute-update parent agent."""
    return ThinkPlanningExecutionAgent(llm=llm, **agent_kwargs)

base_workflow

Base workflow class providing telemetry and execution abstractions.

This module defines the BaseWorkflow abstract class, which serves as the foundation for all workflow implementations in the URSA framework. It provides:

  • Telemetry and metrics collection
  • Thread and checkpoint management
  • Input normalization and validation
  • Execution flow control with invoke methods
  • Graph integration utilities for LangGraph compatibility
  • Runtime enforcement of the agent interface contract

Workflows built on this base class benefit from consistent behavior, observability, and integration capabilities while only needing to implement the core _invoke method.

BaseWorkflow

Bases: ABC

Abstract base class for all workflow implementations in the URSA framework.

BaseWorkflow provides a standardized foundation for building workflows consisting of LLM-powered agents with built-in telemetry, configuration management, and execution flow control. It handles common tasks like input normalization, thread management, metrics collection, and LangGraph integration.

Subclasses only need to implement the _invoke method to define their core functionality, while inheriting standardized invocation patterns, telemetry, and graph integration capabilities. The class enforces a consistent interface through runtime checks that prevent subclasses from overriding critical methods like invoke().

The agent supports direct invocation with inputs, with automatic tracking of token usage, execution time, and other metrics. It also provides utilities for integrating with LangGraph through node wrapping and configuration.

Subclass Inheritance Guidelines
  • Must Override: _invoke() - Define your agent's core functionality
  • Can Override: _normalize_inputs() - Customize input handling Various helper methods
  • Never Override: invoke() - Final method with runtime enforcement call() - Delegates to invoke Other public methods (build_config, write_state, add_node)

To create a custom agent, inherit from this class and implement the _invoke method:

class MyWorkflow(BaseWorkflow):
    def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        # Process inputs and return results
        ...
Source code in src/ursa/workflows/base_workflow.py
class BaseWorkflow(ABC):
    """Abstract base class for all workflow implementations in the URSA framework.

    BaseWorkflow provides a standardized foundation for building workflows consisting of
    LLM-powered agents with built-in telemetry, configuration management, and execution
    flow control. It handles common tasks like input normalization, thread management,
    metrics collection, and LangGraph integration.

    Subclasses only need to implement the _invoke method to define their core
    functionality, while inheriting standardized invocation patterns, telemetry, and
    graph integration capabilities. The class enforces a consistent interface through
    runtime checks that prevent subclasses from overriding critical methods like
    invoke().

    The agent supports direct invocation with inputs, with
    automatic tracking of token usage, execution time, and other metrics. It also
    provides utilities for integrating with LangGraph through node wrapping and
    configuration.

    Subclass Inheritance Guidelines:
        - Must Override: _invoke() - Define your agent's core functionality
        - Can Override: _normalize_inputs() - Customize input handling
                        Various helper methods
        - Never Override: invoke() - Final method with runtime enforcement
                          __call__() - Delegates to invoke
                          Other public methods (build_config, write_state, add_node)

    To create a custom agent, inherit from this class and implement the _invoke method:

    ```python
    class MyWorkflow(BaseWorkflow):
        def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
            # Process inputs and return results
            ...
    ```
    """

    def __init__(self, **kwargs):
        pass

    # NOTE: The `invoke` method uses the PEP 570 `/,*` notation to explicitly state which
    # arguments can and cannot be passed as positional or keyword arguments.
    @final
    def invoke(
        self,
        inputs: Optional[InputLike] = None,
        /,
        *,
        config: Optional[dict] = None,
        **kwargs: Any,
    ) -> Any:
        """Executes the agent with the provided inputs and configuration.

        This is the main entry point for agent execution. It handles input normalization,
        telemetry tracking, and proper execution context management. The method supports
        flexible input formats - either as a positional argument or as keyword arguments.

        Args:
            inputs: Optional positional input to the agent. If provided, all non-control
                keyword arguments will be rejected to avoid ambiguity.
            config: Optional configuration dictionary to override default settings.
            **kwargs: Additional keyword arguments that can be either:
                - Input parameters (when no positional input is provided)
                - Control parameters recognized by the agent

        Returns:
            The result of the agent's execution.

        Raises:
            TypeError: If both positional inputs and non-control keyword arguments are
                provided simultaneously.
        """

        normalized = self._normalize_inputs(inputs)

        # Delegate to the subclass implementation with the normalized inputs
        # and any control parameters
        return self._invoke(normalized, config=config, **kwargs)

    def _normalize_inputs(self, inputs: InputLike) -> Mapping[str, Any]:
        """Normalizes various input formats into a standardized mapping.

        This method converts different input types into a consistent dictionary format
        that can be processed by the agent. String inputs are wrapped as messages, while
        mappings are passed through unchanged.

        Args:
            inputs: The input to normalize. Can be a string (which will be converted to a
                message) or a mapping (which will be returned as-is).

        Returns:
            A mapping containing the normalized inputs, with keys appropriate for agent
            processing.

        Raises:
            TypeError: If the input type is not supported (neither string nor mapping).
        """
        if isinstance(inputs, str):
            return {"task": inputs}
        if isinstance(inputs, Mapping):
            return inputs
        raise TypeError(f"Unsupported input type: {type(inputs)}")

    @final
    async def ainvoke(
        self,
        inputs: Optional[InputLike] = None,
        /,
        *,
        config: Optional[dict] = None,
        **kwargs: Any,
    ) -> Any:
        """Asynchronously execute the workflow with normalized inputs.

        Subclasses can provide a native async implementation by overriding
        ``_ainvoke``. The default ``_ainvoke`` implementation runs the sync
        ``_invoke`` implementation in a worker thread.
        """

        normalized = self._normalize_inputs(inputs)
        return await self._ainvoke(normalized, config=config, **kwargs)

    @abstractmethod
    def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        """Subclasses implement the actual sync work against normalized inputs."""
        ...

    async def _ainvoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        """Subclasses can override to implement native async work."""
        return await asyncio.to_thread(self._invoke, inputs, **config)

    def __call__(self, inputs: InputLike, /, **kwargs: Any) -> Any:
        """Specify calling behavior for class instance."""
        return self.invoke(inputs, **kwargs)

    # Runtime enforcement: forbid subclasses from overriding invoke
    def __init_subclass__(cls, **kwargs):
        """Ensure subclass does not override key method."""
        super().__init_subclass__(**kwargs)
        if "invoke" in cls.__dict__:
            err_msg = (
                f"{cls.__name__} must not override BaseAgent.invoke(); "
                "implement _invoke() only."
            )
            raise TypeError(err_msg)

__call__(inputs, /, **kwargs)

Specify calling behavior for class instance.

Source code in src/ursa/workflows/base_workflow.py
def __call__(self, inputs: InputLike, /, **kwargs: Any) -> Any:
    """Specify calling behavior for class instance."""
    return self.invoke(inputs, **kwargs)

__init_subclass__(**kwargs)

Ensure subclass does not override key method.

Source code in src/ursa/workflows/base_workflow.py
def __init_subclass__(cls, **kwargs):
    """Ensure subclass does not override key method."""
    super().__init_subclass__(**kwargs)
    if "invoke" in cls.__dict__:
        err_msg = (
            f"{cls.__name__} must not override BaseAgent.invoke(); "
            "implement _invoke() only."
        )
        raise TypeError(err_msg)

ainvoke(inputs=None, /, *, config=None, **kwargs) async

Asynchronously execute the workflow with normalized inputs.

Subclasses can provide a native async implementation by overriding _ainvoke. The default _ainvoke implementation runs the sync _invoke implementation in a worker thread.

Source code in src/ursa/workflows/base_workflow.py
@final
async def ainvoke(
    self,
    inputs: Optional[InputLike] = None,
    /,
    *,
    config: Optional[dict] = None,
    **kwargs: Any,
) -> Any:
    """Asynchronously execute the workflow with normalized inputs.

    Subclasses can provide a native async implementation by overriding
    ``_ainvoke``. The default ``_ainvoke`` implementation runs the sync
    ``_invoke`` implementation in a worker thread.
    """

    normalized = self._normalize_inputs(inputs)
    return await self._ainvoke(normalized, config=config, **kwargs)

invoke(inputs=None, /, *, config=None, **kwargs)

Executes the agent with the provided inputs and configuration.

This is the main entry point for agent execution. It handles input normalization, telemetry tracking, and proper execution context management. The method supports flexible input formats - either as a positional argument or as keyword arguments.

Parameters:

Name Type Description Default
inputs Optional[InputLike]

Optional positional input to the agent. If provided, all non-control keyword arguments will be rejected to avoid ambiguity.

None
config Optional[dict]

Optional configuration dictionary to override default settings.

None
**kwargs Any

Additional keyword arguments that can be either: - Input parameters (when no positional input is provided) - Control parameters recognized by the agent

{}

Returns:

Type Description
Any

The result of the agent's execution.

Raises:

Type Description
TypeError

If both positional inputs and non-control keyword arguments are provided simultaneously.

Source code in src/ursa/workflows/base_workflow.py
@final
def invoke(
    self,
    inputs: Optional[InputLike] = None,
    /,
    *,
    config: Optional[dict] = None,
    **kwargs: Any,
) -> Any:
    """Executes the agent with the provided inputs and configuration.

    This is the main entry point for agent execution. It handles input normalization,
    telemetry tracking, and proper execution context management. The method supports
    flexible input formats - either as a positional argument or as keyword arguments.

    Args:
        inputs: Optional positional input to the agent. If provided, all non-control
            keyword arguments will be rejected to avoid ambiguity.
        config: Optional configuration dictionary to override default settings.
        **kwargs: Additional keyword arguments that can be either:
            - Input parameters (when no positional input is provided)
            - Control parameters recognized by the agent

    Returns:
        The result of the agent's execution.

    Raises:
        TypeError: If both positional inputs and non-control keyword arguments are
            provided simultaneously.
    """

    normalized = self._normalize_inputs(inputs)

    # Delegate to the subclass implementation with the normalized inputs
    # and any control parameters
    return self._invoke(normalized, config=config, **kwargs)

hypothesis_orchestrator

Sub-agent orchestrator variant of the hypothesis workflow (Plan D).

This workflow is a dynamic-topology counterpart to :class:~ursa.workflows.hypothesis_symposium.HypothesisSymposiumWorkflow. It is built for empirical comparison: instead of a fixed fan-out + symposium graph, an orchestrating agent is given tools to spawn persistent, per-hypothesis investigation agents on demand, then task each of them with reviewing the others.

Design:

  • build_hypotheses runs the :class:HypothesizerAgent to produce the hypothesis space (same as the symposium workflow).
  • A run-scoped :class:_InvestigatorRegistry mints a timestamped persistent agent_name per hypothesis (mirroring the ursa save-agent timestamp convention %Y%m%d_%H%M%S). Timestamping guarantees uniqueness across concurrent dashboard runs; caching by hypothesis label guarantees the same agent both investigates a hypothesis and later reviews the others, so it accumulates durable memory across phases.
  • The orchestrator is an :class:ExecutionAgent given two extra tools: spawn_investigator (create-or-reuse a persistent investigator and invoke it) and list_investigators (recall minted identities). The orchestrator is prompted to record the minted identities in its experiences and to avoid calling the same investigator twice in one parallel batch of tool calls.
  • Each investigator works in its own private sub-workspace, but before every delegation its peers' workspaces are symlinked under peers/<label>/ inside it. That lets the review round read peers' real artifacts instead of only the summary text, while the write-tool sandbox keeps those paths read-only.

Observability/testability is deliberately weaker than the static symposium graph (dynamic topology), which is the expected tradeoff for adaptive orchestration.

HypothesisOrchestratorWorkflow

Bases: WorkflowToolsMixin, BaseWorkflow

Hypothesize, then let an orchestrator spawn/review per-hypothesis agents.

A dynamic-topology alternative to :class:~ursa.workflows.hypothesis_symposium.HypothesisSymposiumWorkflow, intended for empirical comparison. Every scientific phase is exposed as an overridable hook.

Because the topology is dynamic there is no environment object to hand to run_with_visualization, so this workflow records its own environment run: it opens an :func:environment_run_recorder for the whole orchestration and threads the resulting run config into both the orchestrator agent and every spawned investigator. That captures (a) explicit orchestrator->investigator delegation events emitted here and (b) all structured events emitted by the sub-agents themselves, streamed live to events.jsonl. Delegation traffic is additionally rendered to the stdout logs so progress is visible without a dashboard.

Source code in src/ursa/workflows/hypothesis_orchestrator.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
class HypothesisOrchestratorWorkflow(WorkflowToolsMixin, BaseWorkflow):
    """Hypothesize, then let an orchestrator spawn/review per-hypothesis agents.

    A dynamic-topology alternative to
    :class:`~ursa.workflows.hypothesis_symposium.HypothesisSymposiumWorkflow`,
    intended for empirical comparison. Every scientific phase is exposed as an
    overridable hook.

    Because the topology is dynamic there is no environment object to hand to
    ``run_with_visualization``, so this workflow records its own environment run:
    it opens an :func:`environment_run_recorder` for the whole orchestration and
    threads the resulting run config into both the orchestrator agent and every
    spawned investigator. That captures (a) explicit orchestrator->investigator
    delegation events emitted here and (b) all structured events emitted *by* the
    sub-agents themselves, streamed live to ``events.jsonl``. Delegation traffic
    is additionally rendered to the stdout logs so progress is visible without a
    dashboard.
    """

    def __init__(
        self,
        llm: BaseChatModel,
        *,
        hypothesizer: HypothesizerAgent | None = None,
        experience_filename: str = DEFAULT_HYPOTHESIS_EXPERIENCE,
        max_hypotheses: int = 5,
        orchestrator: ExecutionAgent | None = None,
        workspace: str | Path | None = None,
        group: str | None = None,
        name: str = "hypothesis_orchestrator",
        visualize: bool = True,
        trace: bool = True,
        trace_character_limit: int = 2000,
        **kwargs: Any,
    ) -> None:
        super().__init__(**kwargs)
        self.llm = llm
        self.workspace = Path(workspace) if workspace else None
        self.group = group
        # `name`/`group` are what the visualization recorder reads off an
        # "environment"; this workflow acts as its own environment.
        self.name = name
        self.visualize = bool(visualize)
        self.trace = bool(trace)
        self.trace_character_limit = int(trace_character_limit)
        self.orchestrator_run_id: str | None = None
        # Per-run observability context, published by `_invoke` so overridable
        # hooks keep their original signatures.
        self._run_config: Mapping[str, Any] | None = None
        self._run_events: EnvironmentEvents | None = None
        self.experience_filename = (
            HypothesizerAgent._validate_experience_filename(experience_filename)
        )
        self.hypothesizer = hypothesizer or HypothesizerAgent(
            llm,
            experience_filename=self.experience_filename,
            workspace=self.workspace,
            group=self.group,
            **self._agent_kwargs,
        )
        self.max_hypotheses = max(1, int(max_hypotheses))
        self._orchestrator_override = orchestrator

    # ------------------------------------------------------- overridable hooks

    def format_result(self, result: Mapping[str, Any]) -> str:
        """Return only the final write-up, not the whole state.

        The full state carries bulky intermediate data (raw orchestrator result,
        parsed hypotheses, the hypothesis-space markdown, investigator
        identities). Returning all of it makes the dashboard output unreadable,
        so surface just the detailed final answer, falling back to ``summary``
        if a subclass produced one instead.
        """
        detailed = result.get("final")
        summary = result.get("summary")
        text = detailed or summary
        if not text:
            raise ValueError("Orchestration completed without a response.")
        return str(text).strip()

    def build_hypotheses(
        self, query: str, context: str, config: Mapping[str, Any] | None
    ) -> list[Hypothesis]:
        """Produce competing hypotheses via the HypothesizerAgent."""
        result = invoke_agent(
            self.hypothesizer,
            {
                "query": query,
                "new_information": query,
                "context": context,
                "experience_filename": self.experience_filename,
                "revision_history": [],
            },
            config=config,
        )
        artifact = self._artifact_text(result)
        self._last_hypothesis_space = artifact
        return self._parse_hypotheses(artifact, query)

    @staticmethod
    def _artifact_text(result: Any) -> str:
        return artifact_text(result)

    # ------------------------------------------------------------- run surface

    def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        cfg = config.get("config")
        query = str(inputs.get("query") or inputs.get("task") or "")
        context = str(inputs.get("context", ""))
        self._last_hypothesis_space = ""

        hypotheses = self.build_hypotheses(query, context, cfg)
        registry = self._build_registry()

        prompt = _ORCHESTRATOR_PROMPT.format(
            hypothesis_block=self._hypothesis_block(hypotheses),
            query=query,
        )
        # Open a recorder for the whole orchestration. `run_config` carries the
        # recorder callback, so it is threaded into the orchestrator AND every
        # investigator: their own structured events land in the same stream.
        with self._recording(task=query, config=cfg) as run_config:
            events = self._events(run_config)
            self._emit_topology(events, hypotheses)
            # Published as instance state (not hook arguments) so that user
            # subclasses overriding `_build_orchestrator`/`_make_spawn_tools`
            # with the original single-argument signature keep working.
            self._run_config = run_config
            self._run_events = events
            orchestrator = self._build_orchestrator(registry)
            start = perf_counter()
            try:
                result = invoke_agent(orchestrator, prompt, config=run_config)
            except BaseException as exc:
                events.emit(
                    "Orchestration failed",
                    stage="orchestration",
                    phase="error",
                    event_type="orchestration_failed",
                    level="error",
                    error=str(exc),
                    elapsed_seconds=perf_counter() - start,
                )
                raise
            events.emit(
                "Orchestration completed",
                stage="orchestration",
                phase="end",
                event_type="orchestration_completed",
                investigators=registry.identities,
                elapsed_seconds=perf_counter() - start,
            )

        return {
            "query": query,
            "hypotheses": [h.__dict__ for h in hypotheses],
            "hypothesis_space_markdown": self._last_hypothesis_space,
            "investigator_identities": registry.identities,
            "orchestrator_run_id": self.orchestrator_run_id,
            "orchestrator_result": result,
            "final": self._result_text(result),
        }

    def _normalize_inputs(self, inputs: InputLike) -> Mapping[str, Any]:
        if isinstance(inputs, str):
            return {"query": inputs}
        if isinstance(inputs, Mapping):
            return inputs
        raise TypeError(f"Unsupported input type: {type(inputs)}")

    # --------------------------------------------------------------- internals

    @contextmanager
    def _recording(
        self, *, task: str, config: Mapping[str, Any] | None
    ) -> Iterator[Mapping[str, Any] | None]:
        """Yield a run config carrying the visualization recorder callback.

        Degrades gracefully: if visualization is disabled or the recorder cannot
        be created, the original config is yielded unchanged so the run still
        proceeds (and stdout tracing still provides progress feedback).
        """
        if not self.visualize:
            yield config
            return
        try:
            from ursa.environments import environment_run_recorder
        except Exception:  # pragma: no cover - defensive import guard
            logger.warning(
                "Orchestrator visualization unavailable; running unrecorded.",
                exc_info=True,
            )
            yield config
            return

        run_id = self._new_run_id()
        # Validate viability *before* entering the recorder so a setup failure
        # cannot be confused with a failure from the orchestration body.
        try:
            from ursa.security import validate_group_name

            validate_group_name(self.group or "default")
        except Exception:
            logger.warning(
                "Orchestrator group %r is not recordable; running unrecorded.",
                self.group,
                exc_info=True,
            )
            self.orchestrator_run_id = None
            yield config
            return

        with environment_run_recorder(
            self, task=task, config=config, run_id=run_id
        ) as (recorder, run_config):
            self.orchestrator_run_id = recorder.run_id
            logger.info(
                "Orchestrator visualization run started: group=%s "
                "run_id=%s (events stream live to the dashboard)",
                recorder.group,
                recorder.run_id,
            )
            yield run_config

    @staticmethod
    def _new_run_id() -> str:
        """Readable, sortable, unique run id for one orchestration."""
        return (
            f"hyporch_{datetime.now().strftime('%Y%m%d_%H%M%S')}_"
            f"{uuid4().hex[:8]}"
        )

    def _events(self, config: Mapping[str, Any] | None) -> EnvironmentEvents:
        """Event emitter identifying this workflow as the environment."""
        return EnvironmentEvents(
            environment=self.name,
            config=config,
            environment_type="hypothesis_orchestrator",
            environment_id=self.name,
            path=[self.name],
        )

    def _source(self, name: str, *, kind: str = "agent") -> dict[str, Any]:
        return {
            "id": f"{self.name}.{name}",
            "name": name,
            "kind": kind,
            "path": [self.name, name],
        }

    def _emit_topology(
        self, events: EnvironmentEvents, hypotheses: Sequence[Hypothesis]
    ) -> None:
        """Declare the (initially known) orchestrator/investigator topology."""
        nodes = [
            {
                **self._source("orchestrator"),
                "role": "orchestrator",
            },
            *[
                {
                    **self._source(f"H{h.index}"),
                    "role": f"investigator for H{h.index}: {h.statement}",
                }
                for h in hypotheses
            ],
        ]
        topology = {
            "kind": "hypothesis_orchestrator",
            "name": self.name,
            "description": "Orchestrator spawning per-hypothesis investigators",
            "nodes": nodes,
            "edges": [
                {
                    "source": f"{self.name}.orchestrator",
                    "target": f"{self.name}.H{h.index}",
                    "kind": "spawns",
                }
                for h in hypotheses
            ],
        }
        events.emit(
            f"Hypothesis orchestrator {self.name} topology declared",
            stage="orchestration",
            phase="topology",
            event_type="topology_declared",
            topology=topology,
        )
        events.emit(
            f"Hypothesis orchestrator {self.name} started",
            stage="orchestration",
            phase="start",
            event_type="orchestration_started",
            hypothesis_count=len(hypotheses),
        )

    def _trace(self, label: str, message: str) -> None:
        """Render one orchestrator<->investigator message to the stdout logs."""
        if not self.trace:
            return
        text = message
        if (
            self.trace_character_limit > 0
            and len(text) > self.trace_character_limit
        ):
            text = text[: self.trace_character_limit] + "\n... [truncated]"
        logger.info(f"\n[HypothesisOrchestrator:{self.name}] {label}\n{text}\n")

    @staticmethod
    def _result_text(result: Any) -> str:
        if isinstance(result, Mapping) and result.get("messages"):
            last = result["messages"][-1]
            text = getattr(last, "text", None)
            if isinstance(text, str) and text:
                return text
            content = getattr(last, "content", last)
            return content if isinstance(content, str) else str(content)
        return HypothesizerAgent._response_text(result)

    def _build_registry(self) -> _InvestigatorRegistry:
        return _InvestigatorRegistry(
            self.llm,
            workspace=self.workspace,
            group=self.group,
            run_stamp=_timestamp(),
            agent_kwargs={
                **self._tool_agent_kwargs,
                "extra_tools": list(self._extra_tools.values()),
            },
        )

    def _build_orchestrator(
        self, registry: _InvestigatorRegistry
    ) -> ExecutionAgent:
        tools = [*self._extra_tools.values(), *self._make_spawn_tools(registry)]
        if self._orchestrator_override is not None:
            orchestrator = self._orchestrator_override
            orchestrator.add_tool(tools)
            return orchestrator
        kwargs: dict[str, Any] = {
            **self._tool_agent_kwargs,
            "extra_tools": tools,
        }
        if self.workspace is not None:
            kwargs["workspace"] = str(self.workspace / "orchestrator")
        if self.group is not None:
            kwargs["group"] = self.group
        return ExecutionAgent(self.llm, **kwargs)

    def _investigator_config(
        self, run_config: Mapping[str, Any] | None, label: str, agent_name: str
    ) -> dict[str, Any] | None:
        """Attach stable investigator identity to nested sub-agent events.

        Threading this config into the investigator is what makes the sub-agent's
        *own* structured events show up in the run stream, attributed to it.
        """
        if run_config is None:
            return None
        member_id = f"{self.name}.{label}"
        merged = dict(run_config)
        base_metadata = merged.get("metadata")
        metadata = (
            dict(base_metadata) if isinstance(base_metadata, Mapping) else {}
        )
        metadata.update({
            "environment_id": self.name,
            "environment_member": label,
            "environment_member_id": member_id,
            "environment_member_role": f"investigator for {label}",
            "environment_member_path": [self.name, label],
            "agent": label,
            "agent_id": member_id,
            "investigator_agent_name": agent_name,
        })
        merged["metadata"] = metadata

        base_tags = merged.get("tags")
        if isinstance(base_tags, str):
            tags = [base_tags]
        else:
            tags = list(base_tags) if base_tags else []
        for tag in (label, member_id, "environment_member"):
            if tag not in tags:
                tags.append(tag)
        merged["tags"] = tags
        return merged

    def _with_peer_access(self, registry: Any, label: str, task: str) -> str:
        """Link peer workspaces and append the read-only access note to the task.

        Guarded so that alternative/stub registries without peer support (and any
        filesystem failure) degrade to the original task rather than failing the
        delegation.
        """
        linker = getattr(registry, "link_peers", None)
        if not callable(linker):
            return task
        try:
            exposed = linker(label)
        except Exception as exc:  # noqa: BLE001 - never fail a delegation
            logger.warning(
                "Peer workspace linking failed for %s: %s", label, exc
            )
            return task
        if not isinstance(exposed, Mapping) or not exposed:
            return task
        return f"{task}{self._peer_access_note(exposed)}"

    @staticmethod
    def _peer_access_note(exposed: Mapping[str, str]) -> str:
        """Tell an investigator where peer artifacts live and that they are read-only.

        This has to be explicit: neither ``list_workspace_files`` nor the
        dashboard follows symlinks, so the peer directories are invisible to
        directory listings even though ``read_file``/``run_command`` can read
        through them by path.
        """
        if not exposed:
            return ""
        lines = "\n".join(
            f"- {label.upper()}: {path}/"
            for label, path in sorted(exposed.items())
        )
        return (
            "\n\nPEER WORKSPACE ACCESS (READ-ONLY)\n"
            "The other investigators' workspaces are mounted inside your own "
            "workspace at these relative paths:\n"
            f"{lines}\n"
            "You can read their real artifacts there (data files, plots, "
            "scripts, notes) with read_file, or inspect them with run_command "
            "(e.g. `ls peers/h1/`), which is far better evidence than a summary "
            "alone. Two caveats:\n"
            "1. These paths are READ-ONLY. Any attempt to write to, edit, or "
            "delete a file under a peer path will be refused. Never modify a "
            "peer's files; copy what you need into your own workspace instead.\n"
            "2. Directory listing tools do not traverse these mounts, so they "
            "will not appear in list_workspace_files output. Use the explicit "
            "paths above.\n"
            "Do not use `grep -r`, `find`, or other unbounded recursive scans "
            "from your workspace root, because peer mounts can nest; target the "
            "specific peer path you care about instead."
        )

    def _make_spawn_tools(
        self, registry: _InvestigatorRegistry
    ) -> list[StructuredTool]:
        run_config = self._run_config
        emitter = (
            self._run_events
            if self._run_events is not None
            else self._events(run_config)
        )

        def _start(label: str, task: str, agent_name: str) -> float:
            emitter.emit(
                f"Orchestrator -> {label}",
                stage="delegation",
                phase="start",
                event_type="delegation_started",
                source=self._source("orchestrator"),
                target=self._source(label),
                hypothesis_label=label,
                investigator_agent_name=agent_name,
                task=task,
            )
            self._trace(f"orchestrator -> {label} ({agent_name})", task)
            return perf_counter()

        def _end(label: str, task: str, text: str, started: float) -> None:
            emitter.emit(
                f"{label} -> Orchestrator",
                stage="delegation",
                phase="end",
                event_type="delegation_completed",
                source=self._source(label),
                target=self._source("orchestrator"),
                hypothesis_label=label,
                task=task,
                result=text,
                elapsed_seconds=perf_counter() - started,
            )
            self._trace(f"{label} -> orchestrator", text)

        def _error(
            label: str, task: str, exc: BaseException, started: float
        ) -> None:
            emitter.emit(
                f"Investigator {label} failed",
                stage="delegation",
                phase="error",
                event_type="delegation_failed",
                level="error",
                source=self._source(label),
                target=self._source("orchestrator"),
                hypothesis_label=label,
                task=task,
                error=str(exc),
                elapsed_seconds=perf_counter() - started,
            )
            self._trace(f"{label} -> orchestrator [FAILED]", str(exc))

        def spawn_investigator(hypothesis_label: str, task: str) -> str:
            agent = registry.get_or_create(hypothesis_label)
            agent_name = registry.identities.get(
                hypothesis_label.strip().lower(), hypothesis_label
            )
            task = self._with_peer_access(registry, hypothesis_label, task)
            started = _start(hypothesis_label, task, agent_name)
            member_config = self._investigator_config(
                run_config, hypothesis_label, agent_name
            )
            kwargs = {"config": member_config} if member_config else {}
            try:
                result = invoke_agent(agent, task, **kwargs)
            except BaseException as exc:
                _error(hypothesis_label, task, exc, started)
                raise
            text = self._result_text(result)
            _end(hypothesis_label, task, text, started)
            return text

        async def aspawn_investigator(hypothesis_label: str, task: str) -> str:
            agent = registry.get_or_create(hypothesis_label)
            agent_name = registry.identities.get(
                hypothesis_label.strip().lower(), hypothesis_label
            )
            task = self._with_peer_access(registry, hypothesis_label, task)
            started = _start(hypothesis_label, task, agent_name)
            member_config = self._investigator_config(
                run_config, hypothesis_label, agent_name
            )
            kwargs = {"config": member_config} if member_config else {}
            try:
                result = await ainvoke_agent(agent, task, **kwargs)
            except BaseException as exc:
                _error(hypothesis_label, task, exc, started)
                raise
            text = self._result_text(result)
            _end(hypothesis_label, task, text, started)
            return text

        spawn = StructuredTool.from_function(
            func=spawn_investigator,
            coroutine=aspawn_investigator,
            name="spawn_investigator",
            description=(
                "Create (or reuse) a persistent per-hypothesis investigator "
                "agent identified by a stable hypothesis_label, run the given "
                "task on it, and return its result. Reusing a label reaches the "
                "same agent so it remembers its earlier investigation."
            ),
            args_schema=SpawnInvestigatorInput,
        )

        def list_investigators() -> str:
            identities = registry.identities
            if not identities:
                text = "No investigators spawned yet."
            else:
                text = "\n".join(
                    f"- label '{label}' -> agent_name '{name}'"
                    for label, name in identities.items()
                )
            emitter.emit(
                "Orchestrator listed investigators",
                stage="registry",
                phase="update",
                event_type="investigators_listed",
                source=self._source("orchestrator"),
                investigators=identities,
            )
            self._trace("orchestrator: list_investigators", text)
            return text

        listing = StructuredTool.from_function(
            func=list_investigators,
            name="list_investigators",
            description=(
                "List the hypothesis labels spawned so far and their minted "
                "persistent agent_names. Record these in your experiences so you "
                "never lose track of which agent owns which hypothesis."
            ),
        )
        return [spawn, listing]

    def _hypothesis_block(self, hypotheses: Sequence[Hypothesis]) -> str:
        if not hypotheses:
            return "(none parsed; treat the question itself as one hypothesis)"
        return "\n".join(
            f"H{h.index}: {h.statement}"
            + (f"\n    {h.detail}" if h.detail else "")
            for h in hypotheses
        )

    def _parse_hypotheses(self, artifact: str, query: str) -> list[Hypothesis]:
        return parse_hypotheses(
            artifact, query, max_hypotheses=self.max_hypotheses
        )

build_hypotheses(query, context, config)

Produce competing hypotheses via the HypothesizerAgent.

Source code in src/ursa/workflows/hypothesis_orchestrator.py
def build_hypotheses(
    self, query: str, context: str, config: Mapping[str, Any] | None
) -> list[Hypothesis]:
    """Produce competing hypotheses via the HypothesizerAgent."""
    result = invoke_agent(
        self.hypothesizer,
        {
            "query": query,
            "new_information": query,
            "context": context,
            "experience_filename": self.experience_filename,
            "revision_history": [],
        },
        config=config,
    )
    artifact = self._artifact_text(result)
    self._last_hypothesis_space = artifact
    return self._parse_hypotheses(artifact, query)

format_result(result)

Return only the final write-up, not the whole state.

The full state carries bulky intermediate data (raw orchestrator result, parsed hypotheses, the hypothesis-space markdown, investigator identities). Returning all of it makes the dashboard output unreadable, so surface just the detailed final answer, falling back to summary if a subclass produced one instead.

Source code in src/ursa/workflows/hypothesis_orchestrator.py
def format_result(self, result: Mapping[str, Any]) -> str:
    """Return only the final write-up, not the whole state.

    The full state carries bulky intermediate data (raw orchestrator result,
    parsed hypotheses, the hypothesis-space markdown, investigator
    identities). Returning all of it makes the dashboard output unreadable,
    so surface just the detailed final answer, falling back to ``summary``
    if a subclass produced one instead.
    """
    detailed = result.get("final")
    summary = result.get("summary")
    text = detailed or summary
    if not text:
        raise ValueError("Orchestration completed without a response.")
    return str(text).strip()

SpawnInvestigatorInput

Bases: BaseModel

Input schema for the spawn_investigator orchestrator tool.

Source code in src/ursa/workflows/hypothesis_orchestrator.py
class SpawnInvestigatorInput(BaseModel):
    """Input schema for the ``spawn_investigator`` orchestrator tool."""

    hypothesis_label: str = Field(
        ...,
        description=(
            "Short stable label for the hypothesis this investigator owns, e.g. "
            "'H1' or 'H2_expected_improvement'. Reuse the SAME label to reach the "
            "same persistent agent again (e.g. to have it review others). Do not "
            "call the same label twice within one parallel batch of tool calls."
        ),
    )
    task: str = Field(
        ...,
        description=(
            "Self-contained instructions for the investigator: what to "
            "investigate or review, the evidence to gather, and the deliverable."
        ),
    )

hypothesis_symposium

Hypothesis-driven symposium workflow (Plan A).

This workflow builds a durable hypothesis space, fans out one investigation branch per competing hypothesis, converges the per-hypothesis findings, runs a symposium-style cross-review / multi-round revision over the collected evidence, synthesizes a verdict, and finally folds every piece of new information back into the hypothesis space.

Design goals baked into the structure:

  • The multi-round symposium loop is deliberately isolated behind overridable hooks (:meth:build_hypotheses, :meth:investigate_hypothesis, :meth:converge, :meth:run_symposium, :meth:synthesize, :meth:update_hypothesis_space). A future Plan D layer can subclass this workflow and replace :meth:run_symposium with orchestrated all-member dispatch plus adaptive follow-up without touching the fan-out plumbing.
  • Per-hypothesis investigation is quarantined: an exception in one branch is captured as recorded failure data (via a reducer channel) instead of aborting the run, so healthy sibling branches and downstream review survive.

Hypothesis dataclass

One competing hypothesis to investigate.

Source code in src/ursa/workflows/_hypotheses.py
@dataclass
class Hypothesis:
    """One competing hypothesis to investigate."""

    index: int
    statement: str
    detail: str = ""

    def as_task(self, query: str) -> str:
        lines = [
            f"Investigate the following hypothesis for the question: {query}",
            "",
            f"Hypothesis H{self.index}: {self.statement}",
        ]
        if self.detail:
            lines += ["", self.detail]
        lines += [
            "",
            "Gather and weigh evidence for and against this specific "
            "hypothesis. Report findings, confidence, and any evidence that "
            "would change your assessment.",
        ]
        return "\n".join(lines)

HypothesisInvestigation dataclass

Recorded outcome of a single (quarantined) investigation branch.

Source code in src/ursa/workflows/hypothesis_symposium.py
@dataclass
class HypothesisInvestigation:
    """Recorded outcome of a single (quarantined) investigation branch."""

    index: int
    statement: str
    findings: str = ""
    ok: bool = True
    error: str | None = None

    def as_markdown(self) -> str:
        status = "ok" if self.ok else "FAILED"
        body = self.findings if self.ok else (self.error or "unknown error")
        return f"### H{self.index} ({status}): {self.statement}\n\n{body}"

HypothesisSymposiumState

Bases: TypedDict

Parent graph state.

Fan-in requires reducer channels, so investigation results and failures use operator.add accumulators. Overwrite([]) resets them between phases.

Source code in src/ursa/workflows/hypothesis_symposium.py
class HypothesisSymposiumState(TypedDict, total=False):
    """Parent graph state.

    Fan-in requires reducer channels, so investigation results and failures use
    ``operator.add`` accumulators. ``Overwrite([])`` resets them between phases.
    """

    query: str
    context: str
    experience_filename: str

    hypotheses: list[dict[str, Any]]
    investigations: Annotated[list[dict[str, Any]], operator.add]
    failures: Annotated[list[dict[str, Any]], operator.add]

    evidence_digest: str
    symposium_result: dict[str, Any]
    symposium_run_id: str
    synthesis: str
    hypothesis_space_markdown: str
    summary: str

HypothesisSymposiumWorkflow

Bases: WorkflowToolsMixin, BaseWorkflow

Hypothesize -> fan out -> investigate -> converge -> review -> update.

Every scientific phase is exposed as an overridable hook so a later Plan D layer can replace the fixed multi-round symposium with orchestrated all-member dispatch plus adaptive follow-up. The default :meth:run_symposium uses the hardened :class:AgentSymposiumEnvironment so member failures are contained rather than fatal.

Source code in src/ursa/workflows/hypothesis_symposium.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
class HypothesisSymposiumWorkflow(WorkflowToolsMixin, BaseWorkflow):
    """Hypothesize -> fan out -> investigate -> converge -> review -> update.

    Every scientific phase is exposed as an overridable hook so a later Plan D
    layer can replace the fixed multi-round symposium with orchestrated
    all-member dispatch plus adaptive follow-up. The default
    :meth:`run_symposium` uses the hardened :class:`AgentSymposiumEnvironment`
    so member failures are contained rather than fatal.
    """

    state_type = HypothesisSymposiumState

    def __init__(
        self,
        llm: BaseChatModel,
        *,
        hypothesizer: HypothesizerAgent | None = None,
        experience_filename: str = DEFAULT_HYPOTHESIS_EXPERIENCE,
        max_hypotheses: int = 5,
        revision_rounds: int = 1,
        symposium: Any | None = None,
        workspace: str | Path | None = None,
        group: str | None = None,
        name: str = "hypothesis_symposium",
        checkpointer: Any | None = None,
        thread_id: str | None = None,
        recursion_limit: int = 200,
        visualize: bool = True,
        **kwargs: Any,
    ) -> None:
        super().__init__(**kwargs)
        self.llm = llm
        # Preserve the caller/dashboard-provided workspace so the internal
        # symposium (and its per-hypothesis members) run under it instead of
        # silently falling back to the shared cache directory. Previously this
        # was swallowed into **kwargs and discarded by BaseWorkflow.__init__.
        self.workspace = Path(workspace) if workspace else None
        self.group = group
        self.thread_id = thread_id or str(uuid4())
        # Display name for the internal symposium environment. It surfaces on
        # the dashboard Runs page, so keep it short and human-readable rather
        # than deriving it from the (long) class name.
        self.name = name
        self.experience_filename = (
            HypothesizerAgent._validate_experience_filename(experience_filename)
        )
        self.hypothesizer = hypothesizer or HypothesizerAgent(
            llm,
            experience_filename=self.experience_filename,
            workspace=self.workspace,
            group=self.group,
            **self._agent_kwargs,
        )
        self.max_hypotheses = max(1, int(max_hypotheses))
        self.revision_rounds = max(1, int(revision_rounds))
        self._symposium = symposium
        # When true, the symposium stage is wrapped in the environment
        # visualization recorder so the dashboard can follow it *while running*
        # (the recorder flushes each event to events.jsonl immediately).
        self.visualize = bool(visualize)
        self.symposium_run_id: str | None = None
        self.recursion_limit = int(recursion_limit)
        self.checkpointer = checkpointer or InMemorySaver()
        # Branch retries: RetryPolicy's default predicate refuses common builtin
        # exceptions, so retry broadly on any Exception (cancellations excluded
        # by langgraph itself).
        self._branch_retry = RetryPolicy(
            max_attempts=2,
            initial_interval=0.1,
            retry_on=lambda exc: isinstance(exc, Exception),
        )
        self._graph = self._build_graph()

    # ------------------------------------------------------------------ graph

    def _build_graph(self) -> Any:
        builder = StateGraph(self.state_type)
        builder.add_node("hypothesize", self._node_hypothesize)
        builder.add_node(
            "investigate",
            RunnableLambda(
                self._node_investigate_sync,
                afunc=self._node_investigate_async,
            ),
            retry_policy=self._branch_retry,
        )
        builder.add_node("converge", self._node_converge)
        builder.add_node("symposium", self._node_symposium)
        builder.add_node("synthesize", self._node_synthesize)
        builder.add_node("update_space", self._node_update_space)

        builder.add_edge(START, "hypothesize")
        # A node cannot both return a dict and Send list, so the fan-out lives
        # in a conditional edge keyed off the hypotheses produced upstream.
        builder.add_conditional_edges(
            "hypothesize", self._fan_out, ["investigate", "converge"]
        )
        builder.add_edge("investigate", "converge")
        builder.add_edge("converge", "symposium")
        builder.add_edge("symposium", "synthesize")
        builder.add_edge("synthesize", "update_space")
        builder.add_edge("update_space", END)
        return builder.compile(checkpointer=self.checkpointer)

    # ------------------------------------------------------------ graph nodes

    def _node_hypothesize(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        hypotheses = self.build_hypotheses(state, config)
        return {
            "hypotheses": [
                {
                    "index": h.index,
                    "statement": h.statement,
                    "detail": h.detail,
                }
                for h in hypotheses
            ],
            # Reset accumulators so re-entry / re-runs start clean.
            "investigations": Overwrite([]),
            "failures": Overwrite([]),
        }

    def _fan_out(self, state: HypothesisSymposiumState) -> list[Send] | str:
        hypotheses = state.get("hypotheses") or []
        if not hypotheses:
            return "converge"
        return [
            Send("investigate", {"query": state.get("query", ""), **h})
            for h in hypotheses
        ]

    def _investigate(
        self, payload: Mapping[str, Any], config: RunnableConfig
    ) -> dict[str, Any]:
        hypothesis = Hypothesis(
            index=int(payload.get("index", 0)),
            statement=str(payload.get("statement", "")),
            detail=str(payload.get("detail", "")),
        )
        query = str(payload.get("query", ""))
        try:
            outcome = self.investigate_hypothesis(hypothesis, query, config)
        except Exception as exc:  # noqa: BLE001
            # Quarantine: record the failing branch as data. langgraph's
            # error_handler/timeout cannot suppress a sync failure, so we do it
            # here to preserve sibling branches (RetryPolicy already retried).
            failed = HypothesisInvestigation(
                index=hypothesis.index,
                statement=hypothesis.statement,
                ok=False,
                error=f"{type(exc).__name__}: {exc}",
            )
            return {"failures": [failed.__dict__]}
        return {"investigations": [outcome.__dict__]}

    def _node_investigate_sync(
        self, payload: Mapping[str, Any], config: RunnableConfig
    ) -> dict[str, Any]:
        return self._investigate(payload, config)

    async def _node_investigate_async(
        self, payload: Mapping[str, Any], config: RunnableConfig
    ) -> dict[str, Any]:
        hypothesis = Hypothesis(
            index=int(payload.get("index", 0)),
            statement=str(payload.get("statement", "")),
            detail=str(payload.get("detail", "")),
        )
        query = str(payload.get("query", ""))
        try:
            outcome = await self.ainvestigate_hypothesis(
                hypothesis, query, config
            )
        except Exception as exc:  # noqa: BLE001
            failed = HypothesisInvestigation(
                index=hypothesis.index,
                statement=hypothesis.statement,
                ok=False,
                error=f"{type(exc).__name__}: {exc}",
            )
            return {"failures": [failed.__dict__]}
        return {"investigations": [outcome.__dict__]}

    def _node_converge(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        return {"evidence_digest": self.converge(state, config)}

    async def _node_symposium(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        result = await self.run_symposium(state, config)
        update: dict[str, Any] = {"symposium_result": result}
        # Surface the visualization run id in state so the dashboard/caller can
        # locate the live event stream for this symposium stage.
        if self.symposium_run_id:
            update["symposium_run_id"] = self.symposium_run_id
        return update

    async def _node_synthesize(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        return {"synthesis": await self.synthesize(state, config)}

    async def _node_update_space(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        return await self.update_hypothesis_space(state, config)

    # ------------------------------------------------------- overridable hooks

    def format_result(self, result: HypothesisSymposiumState) -> str:
        """Return only the final write-up, not the whole state.

        Prefers the symposium's detailed final answer and falls back to the
        shorter synthesized ``summary`` when the symposium produced no final
        text (for example if the stage was skipped).
        """
        symposium_result = result.get("symposium_result")
        detailed = (
            symposium_result.get("final")
            if isinstance(symposium_result, Mapping)
            else None
        )
        summary = result.get("summary")
        text = detailed or summary
        if not text:
            raise ValueError("Symposium completed without a response.")
        return str(text).strip()

    def build_hypotheses(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> list[Hypothesis]:
        """Produce competing hypotheses via the HypothesizerAgent.

        The hypothesizer maintains a durable markdown artifact whose competing
        hypotheses are ``### H...`` lines; those become the fan-out branches.
        """
        query = str(state.get("query", ""))
        result = invoke_agent(
            self.hypothesizer,
            {
                "query": query,
                "new_information": query,
                "context": str(state.get("context", "")),
                "experience_filename": self.experience_filename,
                "revision_history": [],
            },
            config=config,
        )
        artifact = self._artifact_text(result)
        state["hypothesis_space_markdown"] = artifact
        return self._parse_hypotheses(artifact, query)

    def investigate_hypothesis(
        self,
        hypothesis: Hypothesis,
        query: str,
        config: RunnableConfig,
    ) -> HypothesisInvestigation:
        """Default synchronous investigation (assignment record).

        In the default design (A) the *substantive* per-hypothesis
        investigation is performed by the symposium member that owns this
        hypothesis (during the symposium's initial-work phase), so this fan-out
        branch only records the assignment that will be handed to that member.
        This keeps the fan-out / quarantine / fan-in plumbing intact as the
        Plan D seam: a subclass can override this (or
        :meth:`ainvestigate_hypothesis`) to dispatch a dedicated investigation
        agent per branch instead of (or in addition to) the symposium.
        """
        return HypothesisInvestigation(
            index=hypothesis.index,
            statement=hypothesis.statement,
            findings=(
                f"Assigned to a dedicated symposium member for investigation: "
                f"{hypothesis.as_task(query)}"
            ),
            ok=True,
        )

    async def ainvestigate_hypothesis(
        self,
        hypothesis: Hypothesis,
        query: str,
        config: RunnableConfig,
    ) -> HypothesisInvestigation:
        """Async investigation hook; defaults to the sync implementation."""
        return self.investigate_hypothesis(hypothesis, query, config)

    def converge(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> str:
        """Fan-in: assemble the per-hypothesis findings into one digest."""
        investigations = [
            HypothesisInvestigation(**d)
            for d in state.get("investigations", [])
        ]
        failures = [
            HypothesisInvestigation(**d) for d in state.get("failures", [])
        ]
        ordered = sorted(investigations + failures, key=lambda i: i.index)
        parts = [i.as_markdown() for i in ordered]
        if failures:
            parts.append(
                f"\n_{len(failures)} of {len(ordered)} investigation "
                "branch(es) failed and were recorded above._"
            )
        return "\n\n".join(parts)

    async def run_symposium(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        """Cross-review + multi-round revision over the collected evidence.

        The default symposium assigns one member per hypothesis (design A): each
        member investigates its own hypothesis during initial work, then reads
        every member's investigation during review to adjudicate which
        hypothesis the combined evidence best supports. Isolated behind this
        hook so a Plan D layer can swap the fixed loop for orchestrated
        all-member dispatch + adaptive follow-up. The underlying environment is
        the hardened symposium (member failures are contained).
        """
        hypotheses = [
            Hypothesis(
                index=int(h.get("index", 0)),
                statement=str(h.get("statement", "")),
                detail=str(h.get("detail", "")),
            )
            for h in (state.get("hypotheses") or [])
        ]
        symposium = self._get_symposium(hypotheses)
        digest = str(state.get("evidence_digest", ""))
        digest_block = (
            "\n\nPrior per-hypothesis notes gathered before this symposium "
            f"(shared context):\n{digest}"
            if digest.strip()
            else ""
        )
        task = (
            f"Question: {state.get('query', '')}\n\n"
            "Each member has been assigned one competing hypothesis as its "
            "expertise. Investigate your own hypothesis, then cross-review the "
            "others, challenge weak evidence, and converge on which hypothesis "
            f"is best supported.{digest_block}"
        )
        try:
            return await self._ainvoke_symposium(symposium, task, config)
        finally:
            if self._symposium is None:
                for agent in [*symposium.members.values(), symposium.organizer]:
                    await agent.aclose()
                    agent.close()

    async def _ainvoke_symposium(
        self, symposium: Any, task: str, config: RunnableConfig
    ) -> dict[str, Any]:
        """Invoke the symposium, recording a live visualization run when enabled.

        ``arun_with_visualization`` attaches an ``EnvironmentEventRecorder``
        callback to the run config and flushes every structured progress event
        to ``events.jsonl`` as it happens, so the dashboard can render the
        symposium *while it is still running* instead of only at the end. The
        run id is stashed on the workflow (and logged) so callers can locate the
        stream. Any failure to set up visualization must never break the
        science, so we degrade to a plain ``ainvoke``.
        """
        if not self.visualize:
            return await symposium.ainvoke(task, config=config)

        try:
            from ursa.environments import arun_with_visualization
        except Exception:  # pragma: no cover - defensive import guard
            logger.warning(
                "Symposium visualization unavailable; running unrecorded.",
                exc_info=True,
            )
            return await symposium.ainvoke(task, config=config)

        run_id = self._new_symposium_run_id()
        group = getattr(symposium, "group", None) or "default"
        # Decide whether visualization is viable *before* invoking: a failure
        # after the run has started would either lose the result or re-run the
        # whole (expensive) symposium.
        try:
            from ursa.security import validate_group_name

            validate_group_name(group)
        except Exception:
            logger.warning(
                "Symposium group %r is not recordable; running unrecorded.",
                group,
                exc_info=True,
            )
            return await symposium.ainvoke(task, config=config)

        self.symposium_run_id = run_id
        logger.info(
            "Symposium visualization run started: group=%s run_id=%s "
            "(events stream live to the dashboard)",
            group,
            run_id,
        )
        return await arun_with_visualization(
            symposium, task, config=config, run_id=run_id
        )

    @staticmethod
    def _new_symposium_run_id() -> str:
        """Readable, sortable, unique run id for one symposium stage."""
        return f"hypsym_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid4().hex[:8]}"

    async def synthesize(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> str:
        """Turn the symposium result into a final verdict string."""
        result = state.get("symposium_result") or {}
        final = result.get("final") if isinstance(result, Mapping) else None
        if final:
            return str(final)
        return str(state.get("evidence_digest", ""))

    async def update_hypothesis_space(
        self, state: HypothesisSymposiumState, config: RunnableConfig
    ) -> dict[str, Any]:
        """Fold ALL new information back into the durable hypothesis space."""
        query = str(state.get("query", ""))
        new_information = self._final_new_information(state)
        result = await ainvoke_agent(
            self.hypothesizer,
            {
                "query": query,
                "new_information": new_information,
                "context": str(state.get("context", "")),
                "experience_filename": self.experience_filename,
                "revision_history": [],
            },
            config=config,
        )
        artifact = self._artifact_text(result)
        summary = ""
        if isinstance(result, Mapping):
            summary = str(result.get("summary", "") or "")
        return {
            "hypothesis_space_markdown": artifact,
            "summary": summary,
        }

    # ------------------------------------------------------------- helpers

    def _final_new_information(self, state: HypothesisSymposiumState) -> str:
        sections = [
            "New information gathered during hypothesis investigation and "
            "symposium review:",
            "",
            "## Per-hypothesis investigation digest",
            str(state.get("evidence_digest", "")),
            "",
            "## Symposium synthesis / verdict",
            str(state.get("synthesis", "")),
        ]
        return "\n".join(sections)

    def _parse_hypotheses(self, artifact: str, query: str) -> list[Hypothesis]:
        return parse_hypotheses(
            artifact, query, max_hypotheses=self.max_hypotheses
        )

    @staticmethod
    def _artifact_text(result: Any) -> str:
        return artifact_text(result)

    def _get_symposium(
        self, hypotheses: Sequence[Hypothesis] | None = None
    ) -> Any:
        # An explicitly injected symposium is used as-is. Otherwise the default
        # symposium is built per run so its members reflect the current
        # hypotheses, while the environment retains them across review rounds.
        if self._symposium is not None:
            return self._symposium
        return self._build_default_symposium(hypotheses or [])

    def _hypothesis_member_name(self, hypothesis: Hypothesis) -> str:
        """Stable, filesystem/tool-safe member name for one hypothesis."""
        words = "".join(
            ch.lower() if ch.isalnum() else " " for ch in hypothesis.statement
        ).split()
        slug = "_".join(words[:4]) or "hypothesis"
        return f"h{hypothesis.index}_{slug}"[:48]

    def _build_default_symposium(self, hypotheses: Sequence[Hypothesis]) -> Any:
        """Build a symposium with one member per hypothesis (design A).

        Each member is assigned exactly one hypothesis as its expertise. During
        the symposium's initial-work phase the member investigates *its* own
        hypothesis (gathering evidence for and against it); during the review
        phase every member reads every other member's investigation, so all
        members can learn from the shared evidence while adjudicating which
        hypothesis is best supported. This is the "specialist-per-hypothesis"
        design: guaranteed coverage of every hypothesis, real per-hypothesis
        parallel investigation, and a naturally adversarial cross-review.
        """
        from ursa.environments.agent_symposium import (
            AgentSymposiumEnvironment,
        )
        from ursa.environments.config import EnvironmentMemberConfig

        members = []
        for hypothesis in hypotheses:
            detail = (
                f"\n\nSupporting detail from the hypothesis space:\n{hypothesis.detail}"
                if hypothesis.detail
                else ""
            )
            members.append(
                EnvironmentMemberConfig(
                    name=self._hypothesis_member_name(hypothesis),
                    role=(
                        f"Advocate/investigator for hypothesis H{hypothesis.index}: "
                        f"{hypothesis.statement}"
                    ),
                    agent="ChatAgent",
                    config=dict(self._tool_agent_kwargs),
                    reviewer=True,
                    prompt=(
                        "Your assigned hypothesis (your expertise for this "
                        f"symposium) is H{hypothesis.index}: "
                        f"{hypothesis.statement}.{detail}\n\n"
                        "During your initial work, rigorously investigate THIS "
                        "hypothesis only: gather concrete evidence for and "
                        "against it (write and run code, produce data/plots, and "
                        "quantify results where possible). Do not investigate the "
                        "other hypotheses now — other members own those. During "
                        "the review phase you will read every member's "
                        "investigation and help judge which hypothesis the "
                        "combined evidence best supports."
                    ),
                )
            )
        if not members:
            # No hypotheses parsed: fall back to a single generalist member so
            # the symposium still produces a usable adjudication.
            members.append(
                EnvironmentMemberConfig(
                    name="generalist",
                    role="Hypothesis investigator and reviewer",
                    agent="ChatAgent",
                    config=dict(self._tool_agent_kwargs),
                    reviewer=True,
                )
            )
        symposium = AgentSymposiumEnvironment(
            self.llm,
            name=self.name,
            organizer=EnvironmentMemberConfig(
                name="organizer",
                role="Symposium organizer / final synthesizer",
                agent="ChatAgent",
                config=dict(self._tool_agent_kwargs),
            ),
            members=members,
            revision_rounds=self.revision_rounds,
            persist_members=False,
            # Thread the workflow workspace/group through so members run under
            # the caller/dashboard-provided workspace instead of the shared
            # cache directory. Passing None preserves BaseEnvironment defaults.
            workspace=self.workspace,
            group=self.group,
        )
        if self._extra_tools:
            for agent in [*symposium.members.values(), symposium.organizer]:
                agent.add_tool(list(self._extra_tools.values()))
        return symposium

    # ------------------------------------------------------------- run surface

    def _base_config(self, config: Mapping[str, Any] | None) -> RunnableConfig:
        cfg: dict[str, Any] = dict(config or {})
        cfg.setdefault("recursion_limit", self.recursion_limit)
        configurable = dict(cfg.get("configurable", {}))
        configurable.setdefault("thread_id", self.thread_id)
        cfg["configurable"] = configurable
        return cfg  # type: ignore[return-value]

    def _prepare_state(
        self, inputs: Mapping[str, Any]
    ) -> HypothesisSymposiumState:
        query = str(inputs.get("query") or inputs.get("task") or "")
        return HypothesisSymposiumState(
            query=query,
            context=str(inputs.get("context", "")),
            experience_filename=self.experience_filename,
            investigations=[],
            failures=[],
        )

    def _invoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        # The graph contains async-only nodes (symposium/synthesis/update run
        # async agent calls), so sync callers drive the async graph through a
        # boundary event loop, mirroring BaseEnvironment.
        try:
            asyncio.get_running_loop()
        except RuntimeError:
            return asyncio.run(self._ainvoke(inputs, **config))
        raise RuntimeError(
            "HypothesisSymposiumWorkflow uses async execution internally, but "
            "`.invoke()` was called from an async context. Use "
            "`await workflow.ainvoke(...)` instead."
        )

    async def _ainvoke(self, inputs: Mapping[str, Any], **config: Any) -> Any:
        cfg = self._base_config(config.get("config"))
        return await self._graph.ainvoke(self._prepare_state(inputs), cfg)

    def _normalize_inputs(self, inputs: InputLike) -> Mapping[str, Any]:
        if isinstance(inputs, str):
            return {"query": inputs}
        if isinstance(inputs, Mapping):
            return inputs
        raise TypeError(f"Unsupported input type: {type(inputs)}")

ainvestigate_hypothesis(hypothesis, query, config) async

Async investigation hook; defaults to the sync implementation.

Source code in src/ursa/workflows/hypothesis_symposium.py
async def ainvestigate_hypothesis(
    self,
    hypothesis: Hypothesis,
    query: str,
    config: RunnableConfig,
) -> HypothesisInvestigation:
    """Async investigation hook; defaults to the sync implementation."""
    return self.investigate_hypothesis(hypothesis, query, config)

build_hypotheses(state, config)

Produce competing hypotheses via the HypothesizerAgent.

The hypothesizer maintains a durable markdown artifact whose competing hypotheses are ### H... lines; those become the fan-out branches.

Source code in src/ursa/workflows/hypothesis_symposium.py
def build_hypotheses(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> list[Hypothesis]:
    """Produce competing hypotheses via the HypothesizerAgent.

    The hypothesizer maintains a durable markdown artifact whose competing
    hypotheses are ``### H...`` lines; those become the fan-out branches.
    """
    query = str(state.get("query", ""))
    result = invoke_agent(
        self.hypothesizer,
        {
            "query": query,
            "new_information": query,
            "context": str(state.get("context", "")),
            "experience_filename": self.experience_filename,
            "revision_history": [],
        },
        config=config,
    )
    artifact = self._artifact_text(result)
    state["hypothesis_space_markdown"] = artifact
    return self._parse_hypotheses(artifact, query)

converge(state, config)

Fan-in: assemble the per-hypothesis findings into one digest.

Source code in src/ursa/workflows/hypothesis_symposium.py
def converge(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> str:
    """Fan-in: assemble the per-hypothesis findings into one digest."""
    investigations = [
        HypothesisInvestigation(**d)
        for d in state.get("investigations", [])
    ]
    failures = [
        HypothesisInvestigation(**d) for d in state.get("failures", [])
    ]
    ordered = sorted(investigations + failures, key=lambda i: i.index)
    parts = [i.as_markdown() for i in ordered]
    if failures:
        parts.append(
            f"\n_{len(failures)} of {len(ordered)} investigation "
            "branch(es) failed and were recorded above._"
        )
    return "\n\n".join(parts)

format_result(result)

Return only the final write-up, not the whole state.

Prefers the symposium's detailed final answer and falls back to the shorter synthesized summary when the symposium produced no final text (for example if the stage was skipped).

Source code in src/ursa/workflows/hypothesis_symposium.py
def format_result(self, result: HypothesisSymposiumState) -> str:
    """Return only the final write-up, not the whole state.

    Prefers the symposium's detailed final answer and falls back to the
    shorter synthesized ``summary`` when the symposium produced no final
    text (for example if the stage was skipped).
    """
    symposium_result = result.get("symposium_result")
    detailed = (
        symposium_result.get("final")
        if isinstance(symposium_result, Mapping)
        else None
    )
    summary = result.get("summary")
    text = detailed or summary
    if not text:
        raise ValueError("Symposium completed without a response.")
    return str(text).strip()

investigate_hypothesis(hypothesis, query, config)

Default synchronous investigation (assignment record).

In the default design (A) the substantive per-hypothesis investigation is performed by the symposium member that owns this hypothesis (during the symposium's initial-work phase), so this fan-out branch only records the assignment that will be handed to that member. This keeps the fan-out / quarantine / fan-in plumbing intact as the Plan D seam: a subclass can override this (or :meth:ainvestigate_hypothesis) to dispatch a dedicated investigation agent per branch instead of (or in addition to) the symposium.

Source code in src/ursa/workflows/hypothesis_symposium.py
def investigate_hypothesis(
    self,
    hypothesis: Hypothesis,
    query: str,
    config: RunnableConfig,
) -> HypothesisInvestigation:
    """Default synchronous investigation (assignment record).

    In the default design (A) the *substantive* per-hypothesis
    investigation is performed by the symposium member that owns this
    hypothesis (during the symposium's initial-work phase), so this fan-out
    branch only records the assignment that will be handed to that member.
    This keeps the fan-out / quarantine / fan-in plumbing intact as the
    Plan D seam: a subclass can override this (or
    :meth:`ainvestigate_hypothesis`) to dispatch a dedicated investigation
    agent per branch instead of (or in addition to) the symposium.
    """
    return HypothesisInvestigation(
        index=hypothesis.index,
        statement=hypothesis.statement,
        findings=(
            f"Assigned to a dedicated symposium member for investigation: "
            f"{hypothesis.as_task(query)}"
        ),
        ok=True,
    )

run_symposium(state, config) async

Cross-review + multi-round revision over the collected evidence.

The default symposium assigns one member per hypothesis (design A): each member investigates its own hypothesis during initial work, then reads every member's investigation during review to adjudicate which hypothesis the combined evidence best supports. Isolated behind this hook so a Plan D layer can swap the fixed loop for orchestrated all-member dispatch + adaptive follow-up. The underlying environment is the hardened symposium (member failures are contained).

Source code in src/ursa/workflows/hypothesis_symposium.py
async def run_symposium(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> dict[str, Any]:
    """Cross-review + multi-round revision over the collected evidence.

    The default symposium assigns one member per hypothesis (design A): each
    member investigates its own hypothesis during initial work, then reads
    every member's investigation during review to adjudicate which
    hypothesis the combined evidence best supports. Isolated behind this
    hook so a Plan D layer can swap the fixed loop for orchestrated
    all-member dispatch + adaptive follow-up. The underlying environment is
    the hardened symposium (member failures are contained).
    """
    hypotheses = [
        Hypothesis(
            index=int(h.get("index", 0)),
            statement=str(h.get("statement", "")),
            detail=str(h.get("detail", "")),
        )
        for h in (state.get("hypotheses") or [])
    ]
    symposium = self._get_symposium(hypotheses)
    digest = str(state.get("evidence_digest", ""))
    digest_block = (
        "\n\nPrior per-hypothesis notes gathered before this symposium "
        f"(shared context):\n{digest}"
        if digest.strip()
        else ""
    )
    task = (
        f"Question: {state.get('query', '')}\n\n"
        "Each member has been assigned one competing hypothesis as its "
        "expertise. Investigate your own hypothesis, then cross-review the "
        "others, challenge weak evidence, and converge on which hypothesis "
        f"is best supported.{digest_block}"
    )
    try:
        return await self._ainvoke_symposium(symposium, task, config)
    finally:
        if self._symposium is None:
            for agent in [*symposium.members.values(), symposium.organizer]:
                await agent.aclose()
                agent.close()

synthesize(state, config) async

Turn the symposium result into a final verdict string.

Source code in src/ursa/workflows/hypothesis_symposium.py
async def synthesize(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> str:
    """Turn the symposium result into a final verdict string."""
    result = state.get("symposium_result") or {}
    final = result.get("final") if isinstance(result, Mapping) else None
    if final:
        return str(final)
    return str(state.get("evidence_digest", ""))

update_hypothesis_space(state, config) async

Fold ALL new information back into the durable hypothesis space.

Source code in src/ursa/workflows/hypothesis_symposium.py
async def update_hypothesis_space(
    self, state: HypothesisSymposiumState, config: RunnableConfig
) -> dict[str, Any]:
    """Fold ALL new information back into the durable hypothesis space."""
    query = str(state.get("query", ""))
    new_information = self._final_new_information(state)
    result = await ainvoke_agent(
        self.hypothesizer,
        {
            "query": query,
            "new_information": new_information,
            "context": str(state.get("context", "")),
            "experience_filename": self.experience_filename,
            "revision_history": [],
        },
        config=config,
    )
    artifact = self._artifact_text(result)
    summary = ""
    if isinstance(result, Mapping):
        summary = str(result.get("summary", "") or "")
    return {
        "hypothesis_space_markdown": artifact,
        "summary": summary,
    }

planning_execution_workflow

Persistent workflow for planning and stepwise execution.

The parent owns the LangGraph runtime, checkpointer, store, and thread. Separate PlanningAgent and ExecutionAgent instances are adapted into checkpointed child nodes with narrow state contracts.

PlanExecuteState

Bases: TypedDict

Parent orchestration state for planning and stepwise execution.

Source code in src/ursa/workflows/planning_execution_workflow.py
class PlanExecuteState(TypedDict, total=False):
    """Parent orchestration state for planning and stepwise execution."""

    task: str
    plan: Plan
    step_idx: int
    step_results: list[str]

    messages: Annotated[list[AnyMessage], add_messages]
    symlinkdir: dict[str, Any]
    current_user_request: str

PlanningExecutionAgent

Bases: BaseAgent[PlanExecuteState]

Plan a task and execute each plan step in one persistent graph.

The agent uses one underlying LLM for planning, reflection, tool-driven execution, review, and recap. Both child agents are compiled with checkpointer=True so they inherit the parent agent's checkpointer and receive LangGraph-managed nested checkpoint namespaces.

max_reflection_steps configures the planner. All remaining keyword arguments are the normal :class:ExecutionAgent / :class:BaseAgent options, including workspace, tools, persistence, thread, telemetry, and retention settings.

Source code in src/ursa/workflows/planning_execution_workflow.py
class PlanningExecutionAgent(BaseAgent[PlanExecuteState]):
    """Plan a task and execute each plan step in one persistent graph.

    The agent uses one underlying LLM for planning, reflection, tool-driven
    execution, review, and recap. Both child agents are compiled with
    ``checkpointer=True`` so they inherit the parent agent's
    checkpointer and receive LangGraph-managed nested checkpoint namespaces.

    ``max_reflection_steps`` configures the planner. All remaining keyword
    arguments are the normal :class:`ExecutionAgent` / :class:`BaseAgent`
    options, including workspace, tools, persistence, thread, telemetry, and
    retention settings.
    """

    state_type = PlanExecuteState

    def __init__(
        self,
        llm: BaseChatModel,
        max_reflection_steps: int = 1,
        log_state: bool = False,
        extra_tools: list[BaseTool] | None = None,
        tokens_before_summarize: int = 50000,
        messages_to_keep: int = 20,
        use_web: bool = False,
        safe_codes: list[str] | None = None,
        **kwargs: Any,
    ) -> None:
        self.max_reflection_steps = max_reflection_steps
        self._child_llm_source = llm
        super().__init__(
            llm,
            tokens_before_summarize=tokens_before_summarize,
            messages_to_keep=messages_to_keep,
            **kwargs,
        )
        child_kwargs = {
            "workspace": self.workspace,
            "group": self.group,
            "thread_id": self.thread_id,
            "enable_metrics": False,
            "rag_tools": self.rag_tools,
            "rag_tool_group": self.rag_tool_group,
            "rag_tool_embedding": self.rag_tool_embedding,
            "rag_tool_return_k": self.rag_tool_return_k,
            "max_single_tool_message_tokens": (
                self.max_single_tool_message_tokens
            ),
        }
        self.planner_agent = PlanningAgent(
            llm,
            max_reflection_steps=max_reflection_steps,
            **child_kwargs,
        )
        self.execution_agent = ExecutionAgent(
            llm,
            log_state=log_state,
            extra_tools=extra_tools,
            tokens_before_summarize=tokens_before_summarize,
            messages_to_keep=messages_to_keep,
            use_web=use_web,
            safe_codes=safe_codes,
            **child_kwargs,
        )

    def _normalize_inputs(self, inputs: Any) -> dict[str, Any] | Command:
        normalized_input = super()._normalize_inputs(inputs)
        if isinstance(normalized_input, Command):
            return normalized_input
        normalized = dict(normalized_input)
        task = str(normalized.get("task", "") or "").strip()
        if not task:
            for message in reversed(normalized.get("messages", [])):
                text = message_text(message).strip()
                if text:
                    task = text
                    break
        if not task:
            raise ValueError(
                "PlanningExecutionAgent requires a task or message input."
            )
        # A scalar task channel ensures a new invocation on a persistent thread
        # supersedes the previous invocation's task.
        normalized["task"] = task
        # Symlink requests are invocation-scoped. An explicit empty mapping
        # prevents a prior persistent-thread request from leaking forward.
        normalized.setdefault("symlinkdir", {})
        return normalized

    def format_query(
        self, prompt: str, state: PlanExecuteState | None = None
    ) -> PlanExecuteState:
        query: dict[str, Any] = dict(state or {})
        query.update({
            "task": prompt,
            "messages": [HumanMessage(content=prompt)],
        })
        return cast(PlanExecuteState, query)

    def format_result(self, result: PlanExecuteState) -> str:
        messages = result.get("messages", [])
        if not messages:
            raise ValueError("Planning execution completed without a response.")
        return message_text(messages[-1])

    def _prepare_planning(self, state: PlanExecuteState) -> PlanExecuteState:
        task = str(state.get("task", "") or "").strip()
        if not task:
            raise ValueError(
                "PlanningExecutionAgent requires a task or message input."
            )
        self.events().emit("Planning task", stage="planning")
        return cast(
            PlanExecuteState,
            {
                "task": task,
                "step_idx": 0,
                "step_results": [],
                # Do not leak an earlier persistent run or executor transcript
                # into the planner. The planner's own full state remains in its
                # nested checkpoint namespace.
                "messages": Overwrite([HumanMessage(content=task)]),
                "symlinkdir": dict(state.get("symlinkdir", {})),
            },
        )

    @staticmethod
    def _last_step_summary(state: PlanExecuteState) -> str | None:
        results = state.get("step_results", [])
        if not results:
            return None
        summary = str(results[-1]).strip()
        return summary or None

    def _step_prompt(self, state: PlanExecuteState) -> str:
        plan = state.get("plan")
        if plan is None:
            raise ValueError("The planner completed without producing a plan.")
        if not plan.steps:
            raise ValueError(
                "The planner produced an empty plan; at least one step is required."
            )

        step_idx = state.get("step_idx", 0)
        if step_idx < 0 or step_idx >= len(plan.steps):
            raise ValueError(f"Invalid plan step index {step_idx}.")
        plan_step = plan.steps[step_idx]

        prompt_parts = [
            f"You are contributing to the larger solution:\n{state['task']}"
        ]
        if previous := self._last_step_summary(state):
            prompt_parts.append(f"Previous-step summary:\n{previous}")
        prompt_parts.extend([
            f"Current step:\n{plan_step}",
            (
                "Execute this step and report concrete results for the executor "
                "of the next step. Do not use placeholders. Run commands to "
                "execute generated code when applicable. Only address the "
                "current step."
            ),
        ])
        return "\n\n".join(prompt_parts)

    def _prepare_step(self, state: PlanExecuteState) -> PlanExecuteState:
        prompt = self._step_prompt(state)
        step_idx = state.get("step_idx", 0)
        self.events().emit(
            "Executing plan step",
            stage="execute_step",
            step=step_idx + 1,
            total=len(state["plan"].steps),
        )
        return cast(
            PlanExecuteState,
            {
                # Each executor subgraph invocation receives a clean transcript.
                # Cross-step context is explicit through step_results.
                "messages": Overwrite([HumanMessage(content=prompt)]),
                "current_user_request": prompt,
                "symlinkdir": state.get("symlinkdir", {}),
            },
        )

    def _record_step(self, state: PlanExecuteState) -> PlanExecuteState:
        messages = state.get("messages", [])
        if not messages:
            raise ValueError(
                "The executor completed a step without a response."
            )
        summary = message_text(messages[-1]).strip()
        if not summary:
            raise ValueError("The executor returned an empty step summary.")
        return cast(
            PlanExecuteState,
            {
                "step_results": [*state.get("step_results", []), summary],
                "step_idx": state.get("step_idx", 0) + 1,
            },
        )

    def _after_step(self, state: PlanExecuteState) -> str:
        plan = state.get("plan")
        if plan is None:
            raise ValueError("The planner completed without producing a plan.")
        if state.get("step_idx", 0) >= len(plan.steps):
            return self._after_plan_completion()
        return "prepare_step"

    def _after_plan_completion(self) -> str:
        """Return the route used after the final execution step."""
        return END

    def _completion_routes(self) -> dict[str, str]:
        """Declare post-execution routes added by a specialized composite."""
        return {END: END}

    def _connect_pre_planner_nodes(self) -> None:
        """Connect preparation to planning; subclasses may insert nodes."""
        self.graph.add_edge("prepare_planning", "planner")

    def _connect_post_execution_nodes(self) -> None:
        """Add specialized nodes reached after all plan steps complete."""

    def _planner_input(self, state: PlanExecuteState) -> PlanningState:
        """Expose only the planner contract to the child agent."""
        return cast(
            PlanningState,
            {
                "task": state["task"],
                "review": "",
                # The child state has an add_messages reducer and a persistent
                # namespace. Replace its transcript for every new plan.
                "messages": Overwrite(list(state.get("messages", []))),
                "reflection_steps": self.max_reflection_steps,
            },
        )

    @staticmethod
    def _planner_output(state: PlanningState) -> PlanExecuteState:
        """Return only the completed plan to the parent graph."""
        plan = state.get("plan")
        if plan is None:
            raise ValueError("The planner completed without producing a plan.")
        return cast(PlanExecuteState, {"plan": plan})

    @staticmethod
    def _executor_input(state: PlanExecuteState) -> ExecutionState:
        """Expose one isolated plan-step request to the executor child."""
        messages = list(state.get("messages", []))
        if not messages:
            raise ValueError("Execution requires a prepared step message.")
        return cast(
            ExecutionState,
            {
                "messages": Overwrite(messages),
                "symlinkdir": dict(state.get("symlinkdir", {})),
                "current_user_request": state.get("current_user_request", ""),
            },
        )

    @staticmethod
    def _executor_output(state: ExecutionState) -> PlanExecuteState:
        """Return the executor transcript and workspace update to the parent."""
        messages = list(state.get("messages", []))
        if not messages:
            raise ValueError("The executor completed without a response.")
        return cast(
            PlanExecuteState,
            {
                "messages": Overwrite(messages),
                "symlinkdir": dict(state.get("symlinkdir", {})),
            },
        )

    def _build_graph(self) -> None:
        self.add_node(self._prepare_planning, "prepare_planning")
        self.add_agent_node(
            "planner",
            self.planner_agent,
            input_fn=self._planner_input,
            output_fn=self._planner_output,
        )
        self.add_node(self._prepare_step, "prepare_step")
        self.add_agent_node(
            "executor",
            self.execution_agent,
            input_fn=self._executor_input,
            output_fn=self._executor_output,
        )
        self.add_node(self._record_step, "record_step")

        self.graph.add_edge(START, "prepare_planning")
        self._connect_pre_planner_nodes()
        self.graph.add_edge("planner", "prepare_step")
        self.graph.add_edge("prepare_step", "executor")
        self.graph.add_edge("executor", "record_step")
        self._connect_post_execution_nodes()
        self.graph.add_conditional_edges(
            "record_step",
            self._wrap_cond(
                self._after_step, "after_step", "planning_execution"
            ),
            {
                "prepare_step": "prepare_step",
                **self._completion_routes(),
            },
        )

PlanningExecutorWorkflow

Bases: BaseWorkflow

Deprecated two-agent planning/execution loop.

This preserves the original planner= / executor= constructor and string return value. New code should use :class:PlanningExecutionAgent, which composes its child agents into a persistent LangGraph.

Source code in src/ursa/workflows/planning_execution_workflow.py
class PlanningExecutorWorkflow(BaseWorkflow):
    """Deprecated two-agent planning/execution loop.

    This preserves the original ``planner=`` / ``executor=`` constructor and
    string return value. New code should use :class:`PlanningExecutionAgent`,
    which composes its child agents into a persistent LangGraph.
    """

    def __init__(
        self,
        planner: Any,
        executor: Any,
        workspace: Any = None,
        **kwargs: Any,
    ) -> None:
        warnings.warn(
            "PlanningExecutorWorkflow is deprecated; use "
            "PlanningExecutionAgent(llm=...) instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(**kwargs)
        self.planner = planner
        self.executor = executor
        self.workspace = workspace

    def _invoke(
        self,
        inputs: Mapping[str, Any],
        *,
        config: dict[str, Any] | None = None,
        **kwargs: Any,
    ) -> str:
        task = str(inputs.get("task", "") or "").strip()
        if not task:
            raise ValueError("PlanningExecutorWorkflow requires a task.")
        invoke_config = dict(config or {})

        with console.status(
            "[bold deep_pink1]Planning overarching steps . . .",
            spinner="point",
            spinner_style="deep_pink1",
        ):
            planner_prompt = (
                f"Break this down into one step per technique:\n{task}"
            )
            planning_output = self.planner.invoke(
                planner_prompt,
                config=invoke_config,
            )
            render_plan_steps_rich(planning_output["plan"].steps)

        last_step_summary = "No previous step."
        for i, step in enumerate(planning_output["plan"].steps):
            step_prompt = (
                f"You are contributing to the larger solution:\n"
                f"{task}\n\n"
                f"Previous-step summary:\n"
                f"{last_step_summary}\n\n"
                f"Current step:\n"
                f"{step}\n\n"
                "Execute this step and report results for the executor of the next step."
                "Do not use placeholders."
                "Run commands to execute code generated for the step if applicable."
                "Only address the current step. Stay in your lane."
            )
            console.print(
                Panel(
                    step_prompt,
                    title=f"[bold orange3 on black]Solving Step {i + 1}",
                    border_style="orange3 on black",
                    style="orange3 on black",
                )
            )
            result = self.executor.invoke(
                step_prompt,
                config=invoke_config,
            )
            last_step_summary = message_text(result["messages"][-1])
            console.print(
                Panel(
                    last_step_summary,
                    title=f"Step {i + 1} Final Response",
                    border_style="orange3 on black",
                    style="orange3 on black",
                )
            )
        return last_step_summary

message_text(message)

Return plain text content from a message-like value.

Source code in src/ursa/workflows/planning_execution_workflow.py
def message_text(message: Any) -> str:
    """Return plain text content from a message-like value."""
    if isinstance(message, BaseMessage):
        return message.text
    content = getattr(message, "content", message)
    return content if isinstance(content, str) else str(content or "")

simulation_use_workflow

Deprecated planner/executor workflow specialized for simulator schemas.

SimulationUseWorkflow

Bases: BaseWorkflow

Deprecated simulator-schema-aware planning/execution loop.

Source code in src/ursa/workflows/simulation_use_workflow.py
class SimulationUseWorkflow(BaseWorkflow):
    """Deprecated simulator-schema-aware planning/execution loop."""

    def __init__(
        self,
        planner: Any,
        executor: Any,
        workspace: Any,
        tool_description: str,
        **kwargs: Any,
    ) -> None:
        warnings.warn(
            "SimulationUseWorkflow is deprecated; use "
            "PlanningExecutionAgent with simulator tools instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(**kwargs)
        self.planner = planner
        self.executor = executor
        self.workspace = workspace
        self.tool_schema = code_schema_prompt
        self.tool_description = tool_description

    def _invoke(
        self,
        inputs: Mapping[str, Any],
        *,
        config: dict[str, Any] | None = None,
        **kwargs: Any,
    ) -> str:
        task = str(inputs.get("task", "") or "").strip()
        if not task:
            raise ValueError("SimulationUseWorkflow requires a task.")

        with console.status(
            "[bold deep_pink1]Planning overarching steps . . .",
            spinner="point",
            spinner_style="deep_pink1",
        ):
            planner_prompt = (
                f"Break this down into one step per technique:\n{task}"
                "Here is the schema used to describe the computational model:\n"
                f"{self.tool_schema}"
                "Here is the description of what to run using this schema:\n"
                f"{self.tool_description}"
            )
            planning_output = self.planner.invoke(planner_prompt)
            render_plan_steps_rich(planning_output["plan"].steps)

        last_step_summary = "No previous step."
        for i, step in enumerate(planning_output["plan"].steps):
            step_prompt = (
                f"You are contributing to the larger solution:\n{task}\n\n"
                "Here is the schema used to describe a relevant computational model:\n"
                f"{self.tool_schema}\n\n"
                "Here is the description of what to run using this schema:\n"
                f"{self.tool_description}\n\n"
                f"Previous-step summary:\n{last_step_summary}\n\n"
                f"Current step:\n{step}\n\n"
                "Execute this step and report results for the executor of the next step."
                "Do not use placeholders."
                "Run commands to execute code generated for the step if applicable."
                "Only address the current step. Stay in your lane."
            )
            console.print(
                Panel(
                    step_prompt,
                    title=f"[bold orange3 on black]Solving Step {i + 1}",
                    border_style="orange3 on black",
                    style="orange3 on black",
                )
            )
            result = self.executor.invoke(step_prompt)
            last_step_summary = _message_text(result["messages"][-1])
            console.print(
                Panel(
                    last_step_summary,
                    title=f"Step {i + 1} Final Response",
                    border_style="orange3 on black",
                    style="orange3 on black",
                )
            )
        return last_step_summary

think_plan_execute

Think-plan-execute composite using URSA's hypothesis-space behavior.

ThinkPlanExecuteState

Bases: PlanExecuteState, HypothesizerState

Parent state shared with the planner, executor, and hypothesizer.

Source code in src/ursa/workflows/think_plan_execute.py
class ThinkPlanExecuteState(PlanExecuteState, HypothesizerState, total=False):
    """Parent state shared with the planner, executor, and hypothesizer."""

    hypothesis: str
    hypothesis_phase: Literal["initial", "results"]

ThinkPlanningExecutionAgent

Bases: PlanningExecutionAgent

Build, investigate, and revise a durable hypothesis space.

One parent runtime adapts URSA's hypothesizer, planner, and executor agents into checkpointed child nodes. The hypothesizer first initializes or updates its durable hypothesis space from the current user request. The planner then creates a plan guided by that space, the executor performs each step, and the resulting summaries return to the hypothesizer as new evidence.

Source code in src/ursa/workflows/think_plan_execute.py
class ThinkPlanningExecutionAgent(PlanningExecutionAgent):
    """Build, investigate, and revise a durable hypothesis space.

    One parent runtime adapts URSA's hypothesizer, planner, and executor agents
    into checkpointed child nodes. The hypothesizer first initializes or
    updates its durable hypothesis space from the current user request. The
    planner then creates a plan guided by that space, the executor performs each
    step, and the resulting summaries return to the hypothesizer as new evidence.
    """

    state_type = ThinkPlanExecuteState

    def __init__(
        self,
        llm: BaseChatModel,
        experience_filename: str = DEFAULT_HYPOTHESIS_EXPERIENCE,
        **kwargs: Any,
    ) -> None:
        # The graph is built during BaseAgent initialization, so this adapter
        # setting must be available before the parent constructor runs.
        self.experience_filename = (
            HypothesizerAgent._validate_experience_filename(experience_filename)
        )
        super().__init__(llm, **kwargs)

    @staticmethod
    def _hypothesis_text(value: Any) -> str:
        return HypothesizerAgent._response_text(value)

    # Public input and follow-up formatting retain the parent workflow contract;
    # adapters isolate the standalone child-agent contracts inside the graph.
    def _normalize_inputs(self, inputs: Any) -> dict[str, Any] | Command:
        return PlanningExecutionAgent._normalize_inputs(self, inputs)

    def format_query(
        self,
        prompt: str,
        state: ThinkPlanExecuteState | None = None,
    ) -> ThinkPlanExecuteState:
        return cast(
            ThinkPlanExecuteState,
            PlanningExecutionAgent.format_query(self, prompt, state),
        )

    def format_result(self, state: ThinkPlanExecuteState) -> str:
        artifact = self._hypothesis_text(
            state.get("hypothesis_space_markdown", "")
        )
        if artifact:
            return artifact
        return PlanningExecutionAgent.format_result(self, state)

    def _build_graph(self) -> None:
        PlanningExecutionAgent._build_graph(self)

    def _prepare_initial_hypothesis(
        self, state: ThinkPlanExecuteState
    ) -> ThinkPlanExecuteState:
        task = state["task"]
        prior_artifact = self._hypothesis_text(
            state.get("hypothesis_space_markdown", "")
        )
        # A follow-up is new evidence for the original question rather than an
        # unrelated replacement. A fresh thread starts a fresh question while
        # the experience artifact can still supply durable background.
        query = (
            str(state.get("query", "") or "").strip()
            if prior_artifact
            else task
        )
        query = query or task
        return cast(
            ThinkPlanExecuteState,
            {
                "query": query,
                "new_information": task,
                "context": (
                    "Treat this as a follow-up request and update the existing "
                    "hypothesis space before planning."
                    if prior_artifact
                    else "Initialize a hypothesis space before planning."
                ),
                "experience_filename": state.get(
                    "experience_filename", self.experience_filename
                ),
                "revision_history": list(state.get("revision_history", [])),
                "hypothesis_phase": "initial",
            },
        )

    def _prepare_results_hypothesis_update(
        self, state: ThinkPlanExecuteState
    ) -> ThinkPlanExecuteState:
        results = [
            str(result).strip()
            for result in state.get("step_results", [])
            if str(result).strip()
        ]
        if not results:
            raise ValueError(
                "Think-plan-execute completed without results to send back "
                "to the hypothesizer."
            )
        summary = "\n".join(
            f"- Step {index}: {result}"
            for index, result in enumerate(results, start=1)
        )
        return cast(
            ThinkPlanExecuteState,
            {
                "query": state.get("query", state["task"]),
                "new_information": (
                    "Execution produced the following evidence and results:\n"
                    f"{summary}"
                ),
                "context": f"Current user request:\n{state['task']}",
                "experience_filename": state.get(
                    "experience_filename", self.experience_filename
                ),
                "revision_history": list(state.get("revision_history", [])),
                "hypothesis_phase": "results",
            },
        )

    def _adopt_hypothesis_space(
        self, state: ThinkPlanExecuteState
    ) -> ThinkPlanExecuteState:
        artifact = self._hypothesis_text(
            state.get("hypothesis_space_markdown", "")
        )
        if not artifact:
            raise ValueError(
                "The hypothesizer completed without producing a hypothesis "
                "space."
            )
        return cast(ThinkPlanExecuteState, {"hypothesis": artifact})

    @staticmethod
    def _after_hypothesis_space(
        state: ThinkPlanExecuteState,
    ) -> Literal["planner", "END"]:
        phase = state.get("hypothesis_phase")
        if phase == "initial":
            return "planner"
        if phase == "results":
            return "END"
        raise ValueError(f"Unknown hypothesis update phase: {phase!r}.")

    @staticmethod
    def _hypothesizer_input(
        state: ThinkPlanExecuteState,
    ) -> HypothesizerState:
        """Expose only the hypothesis-maintenance contract to the child."""
        return cast(
            HypothesizerState,
            {
                key: state[key]
                for key in HypothesizerState.__annotations__
                if key in state
            },
        )

    @staticmethod
    def _hypothesizer_output(
        state: HypothesizerState,
    ) -> ThinkPlanExecuteState:
        """Map the child artifact state back into the composite state."""
        return cast(ThinkPlanExecuteState, dict(state))

    def _planner_input(self, state: ThinkPlanExecuteState) -> PlanningState:
        planner_state = super()._planner_input(state)
        planner_state["hypothesis"] = state.get("hypothesis", "")
        return planner_state

    def _step_prompt(self, state: ThinkPlanExecuteState) -> str:
        prompt = super()._step_prompt(state)
        hypothesis = str(state.get("hypothesis", "") or "").strip()
        if not hypothesis:
            return prompt
        return f"Hypothesis to test or refine:\n{hypothesis}\n\n{prompt}"

    def _connect_pre_planner_nodes(self) -> None:
        if not hasattr(self, "hypothesizer_agent"):
            self.hypothesizer_agent = HypothesizerAgent(
                self._child_llm_source,
                # The child does not own persistence. Point its artifact
                # directory at the parent's den while LangGraph owns
                # checkpoint persistence.
                workspace=self.den,
                group=self.group,
                thread_id=self.thread_id,
                experience_filename=self.experience_filename,
                enable_metrics=False,
            )

        self.add_node(
            self._prepare_initial_hypothesis, "prepare_initial_hypothesis"
        )
        self.add_agent_node(
            "hypothesizer",
            self.hypothesizer_agent,
            input_fn=self._hypothesizer_input,
            output_fn=self._hypothesizer_output,
        )
        self.add_node(self._adopt_hypothesis_space, "adopt_hypothesis_space")
        self.add_node(
            self._prepare_results_hypothesis_update,
            "prepare_results_hypothesis_update",
        )

        self.graph.add_edge("prepare_planning", "prepare_initial_hypothesis")
        self.graph.add_edge("prepare_initial_hypothesis", "hypothesizer")
        self.graph.add_edge("hypothesizer", "adopt_hypothesis_space")
        self.graph.add_conditional_edges(
            "adopt_hypothesis_space",
            self._wrap_cond(
                self._after_hypothesis_space,
                "after_hypothesis_space",
                "think_planning_execution",
            ),
            {"planner": "planner", "END": END},
        )

    def _after_plan_completion(self) -> str:
        return "prepare_results_hypothesis_update"

    def _completion_routes(self) -> dict[str, str]:
        return {
            "prepare_results_hypothesis_update": (
                "prepare_results_hypothesis_update"
            )
        }

    def _connect_post_execution_nodes(self) -> None:
        self.graph.add_edge("prepare_results_hypothesis_update", "hypothesizer")

think_plan_execute_workflow(llm, **agent_kwargs)

Create a persistent hypothesis-plan-execute-update parent agent.

Source code in src/ursa/workflows/think_plan_execute.py
def think_plan_execute_workflow(
    llm: BaseChatModel, **agent_kwargs: Any
) -> ThinkPlanningExecutionAgent:
    """Create a persistent hypothesis-plan-execute-update parent agent."""
    return ThinkPlanningExecutionAgent(llm=llm, **agent_kwargs)