Skip to main content

Typed scenario invocation

Build a typed scenario request, bind it to an accepted task scope, and handle policy rejection or incomplete execution results.

User Guides

CodeGraph exports a typed Python request contract for role-bound scenario execution. Use it for an in-process integration that already participates in a governed CodeGraph task. For an agent or remote client, prefer the registered MCP or API interface for that client; see the MCP operator guide for setup.

Use a typed request when an application repeats an operation, such as preparing interface documentation for each accepted task. The application supplies the scenario and work scope; CodeGraph checks the selected employee and returns the result with execution metadata. This metadata connects the answer to the task and helps diagnose a rejected request.

Minimal request

Run the example from a local CodeGraph repository root with the project dependencies installed; see the prerequisites in the CLI guide. A working scenario needs a registered project, an accepted task, configured context services, and an LLM provider. See the configuration guide for instance settings. Replace <project-key>, <namespace> and <task-id> with accepted task values, and source://current-contract with a current source reference. Before invocation, check the project service settings and selected LLM provider in your instance configuration.

The documentation scenario needs a current CPG for the selected project. Check the graph revision and completion of its update using Prepare the project. Then invoke the accepted task: the scenario uses this graph to retrieve code context.

from src.digital_employees.runtime.scenarios import (
    RoleBoundScenarioInvocationRequest,
    invoke_role_bound_scenario_request,
)

request = RoleBoundScenarioInvocationRequest(
    query="Update the interface documentation for the selected task.",
    context={
        "project_key": "<project-key>",
        "namespace": "<namespace>",
        "task_id": "<task-id>",
        "source_refs": ["source://current-contract"],
    },
    employee_id="codegraph_docs",
    scenario_id="scenario_03",
    event_type="docs_memory_sync_start",
    execution_source="customer_in_process_integration",
)

result = invoke_role_bound_scenario_request(request)

The example is intentionally bound to the documentation employee and scenario. Choose another scenario only when its employee policy and task carrier allow it.

Required governance context

The invocation function checks three scope fields in context before execution:

  • project_key identifies the registered CodeGraph project;
  • namespace identifies its namespace;
  • task_id binds the work to the active task capsule.

An empty scope fails closed with role_bound_scenario_contract_missing:<fields>. The runtime also resolves or validates the accountable employee_id, verifies that the employee may run the selected scenario, builds invocation evidence and runs the scenario preflight.

When preflight rejects a request, restore the task scope, employee policy, event or evidence named in the message. Then repeat the same typed invocation.

Request fields

Request fields
Field Purpose
query Required request string passed to the selected workflow.
context Project and task mapping; defaults to None. Execution rejects missing task scope.
employee_id String; defaults to empty. The runtime resolves or checks the accountable employee against scenario policy.
scenario_id String; defaults to empty. Use a canonical ID such as scenario_03 for explicit selection.
event_type Event string; defaults to empty. When omitted, the runtime selects the employee’s default event.
execution_source Integration identifier string; defaults to role_bound_runtime.

If scenario_id is omitted, the runtime classifies the query. Explicit IDs are usually better for reproducible automation because they preserve the intended lane and make policy failures easier to diagnose.

Result contract

The return value is a dictionary produced by the selected scenario. Shared fields added by the role-bound wrapper include:

  • scenario_id: canonical selected scenario;
  • intent: intent mapped from that scenario;
  • classification_method: selection method;
  • metadata.role_bound_scenario_invocation: employee, event, execution source, workflow, evidence reference and preflight status;
  • metadata.scenario_invocation_evidence: the full invocation evidence object.

Use the shared envelope to identify the selected workflow and its preflight result. Then read the selected scenario fields; for this example, see the documentation scenario guide. In that workflow, a populated error field contains an execution error. Handle it separately from an exception that rejects the request before the scenario starts.

Error handling

Treat stable prefixes as categories and preserve their complete message in diagnostics:

  • role_bound_scenario_contract_missing — required task scope is absent;
  • role_bound_scenario_preflight_blocked — evidence or event preflight did not pass;
  • role_bound_employee_has_no_policy — the employee has no policy;
  • role_bound_scenario_manual_only — the scenario permits manual execution only;
  • role_bound_employee_not_allowed_for_scenario — employee/scenario policy mismatch;
  • role_bound_scenario_retired — the requested scenario cannot execute;
  • role_bound_scenario_not_registered — no workflow handler is registered.

Example boundary handling:

class IntegrationError(RuntimeError):
    """Report a CodeGraph invocation failure at the integration boundary."""


try:
    result = invoke_role_bound_scenario_request(request)
except RuntimeError as exc:
    if str(exc).startswith("role_bound_"):
        raise IntegrationError(f"CodeGraph scenario rejected: {exc}") from exc
    raise

if result.get("error"):
    raise IntegrationError(f"CodeGraph documentation workflow failed: {result['error']}")

This fragment replaces the final invocation line in the first example and uses the same request. To check rejection without calling an LLM, create a request with context={}. Invocation raises role_bound_scenario_contract_missing before context retrieval or scenario execution. Preserve the complete message: it lists missing fields. After restoring the required conditions, repeat the request with the same task scope and selected employee.

Concurrency and side effects

Invocation is synchronous from the caller’s perspective. The selected workflow may query project services or produce governed evidence. Run it outside an async event loop’s main thread when it can block, and use the orchestration surface appropriate to the deployment when durable remote execution is needed.

The typed request covers the declared scenario operation. File edits, publication and state changes run through the task carrier, lane ownership and approval defined by their own contracts.