Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
226 changes: 150 additions & 76 deletions osiris_cli/orchestration/council.py

Large diffs are not rendered by default.

180 changes: 130 additions & 50 deletions osiris_cli/orchestration/trio.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
* The best outcome is PENDING_HUMAN_APPROVAL. Nothing here applies, merges or promotes.
* Candidates stay UNMEASURED until the runner has measured them; rejected and quarantined
candidates are kept (patch + evidence) under the run directory.
* The four steps run as a workflow (``osiris_cli.runtime``): baseline -> research -> developer
-> critic. ``trio_workflow`` builds it; ``run_trio`` keeps the run record and receipt chain.
"""

from __future__ import annotations
Expand All @@ -28,6 +30,7 @@
from pathlib import Path
from typing import Callable, Dict, List, Optional, Set, Tuple

from ..runtime._workflows import Executor, Workflow, WorkflowBuilder, WorkflowContext, handler
from .agent_spec import (AgentRun, AgentSpec, AgentState, BudgetExceeded, RunBudget, digest,
new_run_id)
from .controller import GovernanceController
Expand Down Expand Up @@ -401,68 +404,111 @@ def verify_chain(path: str) -> bool:
return True


def run_trio(repo: str, propose_fn: ProposeFn, out_dir: str, *, timeout: float = 60.0,
budget: Optional[RunBudget] = None,
supplementary_fn: Optional[Callable[[str], str]] = None, sandboxed: bool = False) -> TrioResult:
"""Run the slice. ``repo`` is only read. ``out_dir`` receives the run record (and must not be
inside ``repo``); the receipt chain there is its own file, not the live genome ledger."""
if sandboxed:
from osiris_cli import sandbox
if not sandbox.available():
raise sandbox.SandboxUnavailable("sandboxed run requested but no namespace sandbox is available")
repo, out_dir = os.path.realpath(repo), os.path.realpath(out_dir)
if out_dir == repo or out_dir.startswith(repo + os.sep):
raise ValueError("out_dir must be outside the repo under test")
run_id = new_run_id()
run_dir = os.path.join(out_dir, run_id)
os.makedirs(run_dir)
budget = budget or RunBudget()
repo_before = tree_digest(repo)
res = TrioResult(run_id, "FAILED", "UNMEASURED", run_dir)
runs: List[AgentRun] = []
work = tempfile.mkdtemp(prefix="osiris_trio_")
chain = os.path.join(out_dir, "receipts.jsonl")
try:
# frozen baseline
base_sb = make_sandbox(repo, work)
res.baseline, base_pass, base_fail = run_pytest(base_sb, timeout, sandboxed)
if res.baseline.green:
res.outcome, res.reasons = "NO_DEFECT", ["baseline suite is already green"]
return res

r = AgentRun(RESEARCH, run_id, budget)

runs.append(r)
r.start({"repo_digest": repo_before})
findings = research(base_sb, res.baseline, base_fail)
r.finish(asdict(findings))
if not findings.sources:
res.outcome, res.reasons = "FAILED", ["research found no implicated source file"]
return res

d = AgentRun(DEVELOPER, run_id, budget)

runs.append(d)
@dataclass
class _TrioState:
"""One run as it moves through the trio workflow (baseline -> research -> developer -> critic)."""

repo: str
propose_fn: ProposeFn
timeout: float
budget: RunBudget
supplementary_fn: Optional[Callable[[str], str]]
sandboxed: bool
run_id: str
run_dir: str
work: str
repo_before: str
res: TrioResult
runs: List[AgentRun] = field(default_factory=list)
base_sb: str = ""
base_pass: Set[str] = field(default_factory=set)
base_fail: Set[str] = field(default_factory=set)
findings: Optional[ResearchFindings] = None
out: Optional[DeveloperOutput] = None
diffs: Dict[str, str] = field(default_factory=dict)
refused: List[str] = field(default_factory=list)


class _BaselineStep(Executor):
"""Freeze the unpatched run. A green baseline ends the run as NO_DEFECT."""

def __init__(self) -> None:
super().__init__("baseline")

@handler(input=_TrioState)
async def step(self, st: _TrioState, ctx: WorkflowContext) -> None:
st.base_sb = make_sandbox(st.repo, st.work)
st.res.baseline, st.base_pass, st.base_fail = run_pytest(st.base_sb, st.timeout, st.sandboxed)
if st.res.baseline.green:
st.res.outcome, st.res.reasons = "NO_DEFECT", ["baseline suite is already green"]
return
await ctx.send_message(st)


class _ResearchStep(Executor):
def __init__(self) -> None:
super().__init__("research")

@handler(input=_TrioState)
async def step(self, st: _TrioState, ctx: WorkflowContext) -> None:
r = AgentRun(RESEARCH, st.run_id, st.budget)

st.runs.append(r)
r.start({"repo_digest": st.repo_before})
st.findings = research(st.base_sb, st.res.baseline, st.base_fail)
r.finish(asdict(st.findings))
if not st.findings.sources:
st.res.outcome, st.res.reasons = "FAILED", ["research found no implicated source file"]
return
await ctx.send_message(st)


class _DeveloperStep(Executor):
def __init__(self) -> None:
super().__init__("developer")

@handler(input=_TrioState)
async def step(self, st: _TrioState, ctx: WorkflowContext) -> None:
findings, res = st.findings, st.res
assert findings is not None
d = AgentRun(DEVELOPER, st.run_id, st.budget)

st.runs.append(d)
d.start(asdict(findings))
dev_sb = make_sandbox(repo, work)
out = propose_fn(findings, dev_sb)
dev_sb = make_sandbox(st.repo, st.work)
out = st.propose_fn(findings, dev_sb)
diffs, refused = apply_to_sandbox(dev_sb, out)
d.finish({"files": sorted(out.patched_files), "report": out.report})
res.findings, res.proposed_files, res.refused = findings, dict(out.patched_files), refused
res.patched_files = {k: v for k, v in out.patched_files.items() if k in diffs}
res.dev_report = out.report
Path(run_dir, "candidate.json").write_text(json.dumps(
Path(st.run_dir, "candidate.json").write_text(json.dumps(
{"proposed_files": out.patched_files, "accepted": sorted(diffs), "refused": refused,
"report": out.report}, indent=2, sort_keys=True))
for rel, df in diffs.items():
Path(run_dir, "candidate_" + rel.replace("/", "__") + ".diff").write_text(df)
Path(st.run_dir, "candidate_" + rel.replace("/", "__") + ".diff").write_text(df)
st.out, st.diffs, st.refused = out, diffs, refused
await ctx.send_message(st)

c = AgentRun(CRITIC, run_id, budget)

runs.append(c)
c.start({"diffs": digest(diffs), "refused": refused})
class _CriticStep(Executor):
"""Re-derive the verdict from fresh runs plus the diff; set the outcome."""

def __init__(self) -> None:
super().__init__("critic")

@handler(input=_TrioState)
async def step(self, st: _TrioState, ctx: WorkflowContext) -> None:
res, out = st.res, st.out
assert out is not None and st.findings is not None
d = st.runs[-1]
c = AgentRun(CRITIC, st.run_id, st.budget)

st.runs.append(c)
c.start({"diffs": digest(st.diffs), "refused": st.refused})
verdict, res.candidate, fw = critic_review(
repo, diffs, out.patched_files, refused, findings, base_pass, out.report, timeout, work, supplementary_fn, sandboxed)
st.repo, st.diffs, out.patched_files, st.refused, st.findings, st.base_pass, out.report, st.timeout,
st.work, st.supplementary_fn, st.sandboxed)
res.critic, res.firewall, res.candidate_status = verdict, fw, "MEASURED"
c.finish({"approve": verdict.approve, "reasons": verdict.reasons})

Expand All @@ -480,9 +526,43 @@ def run_trio(repo: str, propose_fn: ProposeFn, out_dir: str, *, timeout: float =
d.to(AgentState.REJECTED, "; ".join(res.reasons)[:300])
elif res.outcome == "QUARANTINED":
d.to(AgentState.QUARANTINED, "; ".join(res.reasons)[:300])


def trio_workflow() -> Workflow:
"""The trio as a workflow: baseline -> research -> developer -> critic. A step that ends the
run early (green baseline, nothing implicated) sends nothing on. A new workflow per run."""
steps = [_BaselineStep(), _ResearchStep(), _DeveloperStep(), _CriticStep()]
return WorkflowBuilder(name="trio", start_executor=steps[0]).add_chain(steps).build()


def run_trio(repo: str, propose_fn: ProposeFn, out_dir: str, *, timeout: float = 60.0,
budget: Optional[RunBudget] = None,
supplementary_fn: Optional[Callable[[str], str]] = None, sandboxed: bool = False) -> TrioResult:
"""Run the slice. ``repo`` is only read. ``out_dir`` receives the run record (and must not be
inside ``repo``); the receipt chain there is its own file, not the live genome ledger."""
if sandboxed:
from osiris_cli import sandbox
if not sandbox.available():
raise sandbox.SandboxUnavailable("sandboxed run requested but no namespace sandbox is available")
repo, out_dir = os.path.realpath(repo), os.path.realpath(out_dir)
if out_dir == repo or out_dir.startswith(repo + os.sep):
raise ValueError("out_dir must be outside the repo under test")
run_id = new_run_id()
run_dir = os.path.join(out_dir, run_id)
os.makedirs(run_dir)
budget = budget or RunBudget()
repo_before = tree_digest(repo)
res = TrioResult(run_id, "FAILED", "UNMEASURED", run_dir)
work = tempfile.mkdtemp(prefix="osiris_trio_")
chain = os.path.join(out_dir, "receipts.jsonl")
st = _TrioState(repo, propose_fn, timeout, budget, supplementary_fn, sandboxed, run_id, run_dir, work,
repo_before, res)
try:
trio_workflow().run_sync(st)
except BudgetExceeded as e:
res.outcome, res.reasons = "FAILED", [f"budget: {e}"]
finally:
runs = st.runs
repo_after = tree_digest(repo)
if repo_after != repo_before: # would be a bug in this module; fail loudly
res.outcome, res.reasons = "FAILED", res.reasons + ["REPO MODIFIED DURING RUN"]
Expand Down
25 changes: 18 additions & 7 deletions osiris_cli/runtime/PORT_MAP.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# osiris_cli.runtime port map

Phase 1 of re-engineering Microsoft Agent Framework (MAF) into osiris-cli.
Phases 1 and 2 of re-engineering Microsoft Agent Framework (MAF) into osiris-cli. Phase 1: the governed agent core. Phase 2: workflows, checkpoints and multi-agent orchestrations, with the trio and the council moved onto them.

- **Source:** `microsoft/agent-framework` at `567e4d458b59b83ac9b19088a43a2853094c6df1` (2026-12-04), MIT. License text: `THIRD_PARTY_NOTICES.md` in the repo and `LICENSE-agent-framework.txt` in this package (shipped in the wheel).
- **Method:** each MAF module was read, then rebuilt here as a smaller module that keeps its design and semantics. This is a re-implementation guided by the source, not a line-for-line copy. Files that adapt MAF code carry a header naming the source file.
- **Size:** MAF's Python core is about 86,000 lines. This runtime is about 2,400 lines of code and 1,400 lines of tests.
- **Size:** MAF's Python core is about 86,000 lines, of which workflows are about 17,000, and its orchestrations package about 6,400. This runtime is about 2,600 lines of code after Phase 1 and about 4,700 after Phase 2.

## Files

Expand All @@ -19,8 +19,11 @@ Phase 1 of re-engineering Microsoft Agent Framework (MAF) into osiris-cli.
| `_telemetry.py` | `core/agent_framework/observability.py` | OpenTelemetry GenAI attribute names; one span per agent run, model call and tool call | Spans are always recorded in-process; OpenTelemetry is used only when installed. The span summary (with a timing-free SHA-256) goes into the task ledger's `task_close`. |
| `_governance.py` | — (OSIRIS only) | — | Binds the hooks to existing OSIRIS governance: `task_context` (ledger, budget), `intent_router` (risk tier), `evidence_firewall`, `governance_scope`, `ast_firewall` (SYS-025), `exec_policy` + `exec_kernel`. |
| `testing.py`, `demo.py` | — (OSIRIS only) | — | Scripted chat client; end-to-end demo with an Ollama preflight before any ledger write. |
| `_workflows.py` (Phase 2) | `core/agent_framework/_workflows/` (`_executor.py`, `_function_executor.py`, `_workflow_context.py`, `_edge.py`, `_edge_runner.py`, `_workflow_builder.py`, `_runner.py`, `_workflow.py`, `_events.py`) | Executors with typed `@handler`s and `@response_handler`; `WorkflowBuilder` (`add_edge` with conditions, fan-out with selection, fan-in, switch-case, `add_chain`); Pregel supersteps with state committed at superstep boundaries; `request_info` and `run(responses=...)`; streaming; run states | Per-superstep results are applied in executor registration order, so runs are deterministic (streaming is per superstep). A superstep limit ends the run as `STOPPED` with messages kept, not an exception. Executor exceptions are re-raised unchanged. Responses must have exactly the requested type (no `1` for `True`). No build-time edge type check. Optional run governance: task ledger record (`kind` `workflow`), intent gate on the input, one budget step per superstep, evidence firewall on text outputs. |
| `_checkpoints.py` (Phase 2) | `core/agent_framework/_workflows/_checkpoint.py`, `_checkpoint_encoding.py` | The checkpoint record (workflow name, graph signature, messages, state, executor and edge state, pending requests, previous checkpoint); storage interface; in-memory and file storage; refusing a checkpoint from another graph | No pickle. MAF encodes non-JSON values with pickle behind an allowlist it calls "not a security boundary". Here only JSON values and types registered with `register_checkpoint_type` are written or rebuilt; anything else refuses to checkpoint. File storage is a hash-chained JSONL per workflow name; the checkpoint id is the record hash and a tampered file is refused. |
| `_orchestrations.py` (Phase 2) | `core/agent_framework/_workflows/_agent_executor.py`; `orchestrations/agent_framework_orchestrations/` (`_sequential.py`, `_concurrent.py`, `_group_chat.py`, `_handoff.py`, `_magentic.py`) | `AgentExecutor`; Sequential; Concurrent with the default aggregator; group chat; handoff tools that end the agent's turn; Magentic task ledger, progress ledger, stall and reset counts | Builders are governed by default (same rule as `Agent`). Group chat: the speaker is chosen by a code `selector`. Handoff: tools only for the routes declared, checked again with `max_handoffs` before the next agent runs; handoff calls are removed from the conversation passed on. Magentic: the progress ledger is parsed strictly; an invalid ledger or unknown speaker counts as a stall; a limit ends the run with no final answer. |

Tests: `tests/test_runtime_{middleware,tools,agent,clients,governance,sessions_telemetry}.py`. The cases mirrored from MAF's `core/tests` name the source test file in their module docstring.
Tests: `tests/test_runtime_{middleware,tools,agent,clients,governance,sessions_telemetry}.py` (Phase 1); `tests/test_runtime_{workflows,orchestrations}.py` and `tests/test_council_trio_workflows.py` (Phase 2). The cases mirrored from MAF's `core/tests` name the source test file in their module docstring.

## Governance order (outermost first)

Expand All @@ -30,11 +33,19 @@ Tests: `tests/test_runtime_{middleware,tools,agent,clients,governance,sessions_t

ToolPolicy is innermost, so it checks the arguments that will actually run. The stack can be left out only when `osiris_cli/policy/runtime_policy.json` says `"governance_required": false`. That file sits in a governance-protected directory.

## Not ported in Phase 1
## Workflow-level governance (Phase 2)

A workflow run given a `GovernanceConfig` opens a `workflow` task before any executor runs, refuses input at a blocked risk tier (and asks for a grant at a grant-required one), charges one budget step per superstep, and closes the task with the run's status, superstep count, graph signature, checkpoint head and the evidence firewall's decision on each text output. The five orchestration builders do this by default. Agents inside a workflow are governed by their own stack regardless, so an orchestration run leaves one `workflow` task and one `agent` task per agent turn. Hand-built workflows of plain executors run without a task record unless given a config.

## Trio and council (Phase 2)

`orchestration/trio.py` and `orchestration/council.py` now run on the engine (`trio_workflow()`: baseline → research → developer → critic; `council_workflow()`: AURA → AIDEN → IRIS → OSIRIS, where a failing role goes straight to OSIRIS through a switch-case edge). `run_trio` and `run_task` keep their signatures, receipts and results. Their existing test files pass unchanged. 27 recorded scenarios (12 council outcomes, 3 invalid inputs, a receipt failure, the receipt rows, 8 trio outcomes, a green repo and an out-dir refusal) give identical results on `main` and after the move, apart from receipt hashes, which contain a timestamp. They do not open task-ledger records (they did not before); bringing them under L0's task ledger is a separate decision, because their tests do not isolate `$OSIRIS_HOME`.

## Not ported yet

| MAF area | Why not now |
|---|---|
| Workflows (`_workflows/`, about 12k lines) and `orchestrations` | Phase 2 |
| Workflow-as-agent, sub-workflows (`WorkflowExecutor`), declarative and functional workflow APIs, visualization, checkpoint storage backends other than memory and file | Later; not needed by trio, council or the five patterns |
| MCP client and server (`_mcp.py`, `hosting-mcp`) | Phase 3 |
| Compaction strategies (`_compaction.py`) | Phase 3 (`osiris.runtime.context` has a bounded broker already) |
| Information-flow security labels (`security.py`) | Phase 4 |
Expand All @@ -50,8 +61,8 @@ ToolPolicy is innermost, so it checks the arguments that will actually run. The

osiris-cli also has `osiris/runtime/`, about 1,500 lines of opt-in primitives: contracts, a policy decision, a SQLite session store, a scheduler, workspace tools, an isolation backend, and an MCP registration registry. It has no model-client layer, middleware or agent loop, and its only user outside tests is `osiris_launcher.py` (capability status).

This package does not import or change it. The two overlap on policy hooks, traces, context compaction and session storage. Before merge, decide whether to keep both, rename this package, or fold `osiris.runtime`'s primitives into these hooks in Phase 2.
This package does not import or change it. The two overlap on policy hooks, traces, context compaction, session storage and now scheduling and checkpoints (`osiris.runtime.persistence` keeps checkpoints in SQLite). Phase 2 did not touch it; the ownership decision is still open.

## Change outside the package

`osiris_cli/task_context.py`: `KINDS` gains `"agent"` so runtime runs are recorded under their own kind instead of being mislabelled `code`. `new_context` still floors the cost class at `workspace_write` and the tier at `MEDIUM` for every kind. That is conservative for read-only agents, and the ledger reason text reads "a agent task proposes local changes" even when it doesn't.
`osiris_cli/task_context.py`: `KINDS` gains `"agent"` (Phase 1) and `"workflow"` (Phase 2) so runtime runs are recorded under their own kind instead of being mislabelled `code`. `new_context` still floors the cost class at `workspace_write` and the tier at `MEDIUM` for every kind. That is conservative for read-only agents, and the ledger reason text reads "a agent task proposes local changes" even when it doesn't.
Loading
Loading