Skip to content

API Reference parrot.flows.dev_loop.session_state

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.flows.dev_loop.session_state

View source

DevLoop session-state model — AHP-style channels, actions & pure reducers.

Authoritative core for sdd/specs/agent-host-protocol-session-state.spec.md (FEAT-322). Protocol-agnostic: this module deliberately does NOT import JSON-RPC, aiohttp or Redis. It defines the invariant layers that survive whatever wire protocol wins (AHP, A2A, or in-house):

  1. State — DevLoopSessionState (per run) and RunRegistryState (root channel): immutable, authoritative, snapshot-able.
  2. Actions — closed discriminated unions; the only mechanism of mutation (DevLoopAction for the session channel, RootAction for the root channel).
  3. Reducers— pure (state, action) -> state; run identically host-side and client-side (a future Svelte port mirrors this file 1:1).

Mapping from the current ad-hoc events:

FlowEventPublisher            DispatchEvent.kind          Action here
─────────────────────         ─────────────────────       ─────────────────────
flow.node_started         →   —                           NodeStarted
flow.node_completed       →   —                           NodeCompleted
flow.node_failed          →   —                           NodeFailed
flow.node_skipped         →   —                           NodeSkipped
—                             dispatch.queued             DispatchQueued
—                             dispatch.started            DispatchStarted
—                             dispatch.message             DispatchDelta
—                             dispatch.tool_use           DispatchToolUse
—                             dispatch.tool_result        DispatchToolResult
—                             dispatch.output_invalid     DispatchOutputInvalid
—                             dispatch.failed             DispatchFailed
—                             dispatch.completed          DispatchCompleted
(new — HITL)                                              GateOpened / GateResolved
(new — lifecycle)                                         RunCreated / RunCancelled / RunClosed

Host-side sequencing contract (AHP-compatible; the host itself — SessionHost — and the migration shims land in a second pass, TASK-1849):

  • Every accepted action is wrapped in an ActionEnvelope with a per-channel monotonically increasing server_seq (AHP serverSeq) plus optional multi-client origin attribution (ActionOrigin) and a rejection_reason slot.
  • subscribe(channel) → Snapshot(state, from_seq) + subsequent envelopes.
  • Reconnect: client sends last_seen_server_seq; host replays envelopes > last_seen from the retained log (Redis Stream keeps being the log — it just stops being the state).

HITL arbitration contract (the mutex analogy):

  • GateResolved is only valid while the gate is pending. The host validates before sequencing: the first client to resolve wins; later attempts are rejected with GateAlreadyResolvedError and never become actions. Reducers therefore never see a conflicting resolve — reducers stay total and non-raising.

Root channel (parrot-root://): a lightweight run catalogue — RunRegistryState tracks one RunSummary per run_id, mutated by RunAdded / RunSummaryChanged / RunRemoved through reduce_root.

Class ActionEnvelope

Wire-agnostic envelope — mirrors AHP's ActionEnvelope.

Attributes:

Attribute Type Description
channel str
server_seq int
action DevLoopAction
origin Optional[ActionOrigin]
rejection_reason str

Class ActionOrigin

Multi-client attribution for an accepted action (AHP common type).

Attributes:

Attribute Type Description
client_id str
client_seq int

Class ApprovalGate

A HITL gate: the run blocks until exactly one client resolves it.

Deterministic contract: resolved_by/status are set at most once (host-validated). expires_at enables auto-expiry policies (e.g. escalate to escalation_assignee after N hours).

Attributes:

Attribute Type Description
gate_id str
kind GateKind
node_id NodeId
status GateStatus
on_expiry Literal['fail', 'approve']
title str
instructions str
payload_ref str
opened_at float
expires_at Optional[float]
resolved_by str
resolved_at Optional[float]
comment str
questions List[str]
answers Dict[str, str]

Class ChangeSet

What a run touched, measured by git in the worktree — never self-reported.

Computed by parrot.flows.dev_loop.nodes._changeset.compute_changeset after development (and again by the handoff nodes right before the PR, so the docs-artifact commit is included). Lives in shared["changeset"] and session state (run/changesetRecorded) rather than on DevelopmentOutput, whose JSON schema is part of the coding sub-agent's prompt contract.

Attributes:

Attribute Type Description
base_ref str
head_ref str
branch str
worktree_path str
files List[ChangedFile]
total_additions int
total_deletions int
commits int
uncommitted int
computed_at float

Class ChangedFile

One file in a run's :class:ChangeSet — the PR-style +/- row.

status follows git diff --name-status letters (A added, M modified, D deleted, R renamed, C copied, T type change) plus ? for an untracked, not-yet-committed file. Binary files carry no line counts (git diff --numstat prints -), so binary=True with zero additions/deletions is an honest row, not an empty one.

Attributes:

Attribute Type Description
path str
additions int
deletions int
status Literal['A', 'M', 'D', 'R', 'C', 'T', '?']
binary bool

Class ChangesetRecorded

Git-measured file list for the run (+/- per file, commits).

Recorded once development reconciles files_changed and again by the handoff node right before the PR (so the docs-artifact commit is in). The reducer REPLACES — the latest measurement is the truth.

Attributes:

Attribute Type Description
type Literal['run/changesetRecorded']
changeset ChangeSet

Attribute DeltaContentKind

Attribute DevLoopAction

Class DevLoopSessionState

Authoritative, immutable state tree for one dev-loop run.

This is what subscribe(session_channel(run_id)) snapshots. All fields are cheap to serialise; everything heavy is by-reference.

Attributes:

Attribute Type Description
run_id str
channel str
revision bool
phase RunPhase
created_at float
finished_at Optional[float]
work_kind Literal['bug', 'enhancement', 'new_feature', '']
summary str
jira_issue_key str
pr_url str
nodes Dict[str, NodeState]
gates Dict[str, ApprovalGate]
cancel_requested_by str
error str
judge_verdicts Dict[str, List[JudgeVerdict]]
feedback_decisions List[FeedbackDecisionRecord]
docs_artifacts List[DocsArtifact]
qa_attempts int
qa_notes str
changeset Optional[ChangeSet]
seat_usage List[SeatUsageSummary]

Class DispatchCompleted

Attributes:

Attribute Type Description
type Literal['dispatch/completed']
input_tokens Optional[int]
output_tokens Optional[int]
cache_creation_input_tokens Optional[int]
cache_read_input_tokens Optional[int]
total_cost_usd Optional[float]
num_turns Optional[int]
duration_ms Optional[int]

Class DispatchDelta

One SDK message arrived. Content lives on the terminal channel; the session state only bumps the counter (lazy loading).

content_kind classifies the message (additive; every pre-existing envelope reads as "empty") and thinking carries the throttled reasoning snippet for claude-code seats — the ONE piece of message content the narrative view is allowed to keep, clamped to 400 chars.

Attributes:

Attribute Type Description
type Literal['dispatch/delta']
content_kind DeltaContentKind
thinking str

Class DispatchFailed

Attributes:

Attribute Type Description
type Literal['dispatch/failed']
error str

Class DispatchOutputInvalid

Attributes:

Attribute Type Description
type Literal['dispatch/output_invalid']
error str

Class DispatchQueued

Attributes:

Attribute Type Description
type Literal['dispatch/queued']
dispatcher str

Class DispatchStarted

Attributes:

Attribute Type Description
type Literal['dispatch/started']
terminal str

Class DispatchState

Reduced view of one dispatcher execution inside a node.

Heavy payloads (full SDK messages, tool outputs) do NOT live here — AHP's lazy-loading rule: large content is stored by reference and fetched separately. The terminal channel carries the raw stream; the session state only keeps display-ready counters and the last error.

Attributes:

Attribute Type Description
status DispatchStatus
dispatcher str
started_at Optional[float]
finished_at Optional[float]
message_count int
tool_use_count int
last_error str
terminal str
input_tokens Optional[int]
output_tokens Optional[int]
cache_creation_input_tokens Optional[int]
cache_read_input_tokens Optional[int]
total_cost_usd Optional[float]
num_turns Optional[int]
duration_ms Optional[int]
seats Dict[str, 'SeatState']

Attribute DispatchStatus

Class DispatchToolResult

Attributes:

Attribute Type Description
type Literal['dispatch/tool_result']

Class DispatchToolUse

Attributes:

Attribute Type Description
type Literal['dispatch/tool_use']
tool_name str

Class GateAlreadyResolvedError

Second (and later) resolve attempts on a gate — first one won.

Carries the resolver identity/status in the exception message so callers can surface a 409-style conflict with resolver attribution.

Class GateExpired

Attributes:

Attribute Type Description
type Literal['gate/expired']
gate_id str

Attribute GateKind

Class GateNotFoundError

Raised when a command targets a gate_id that does not exist.

Class GateOpened

Attributes:

Attribute Type Description
type Literal['gate/opened']
gate ApprovalGate

Class GateResolved

Host-arbitrated: sequenced only if the gate is still pending.

Attributes:

Attribute Type Description
type Literal['gate/resolved']
gate_id str
resolution Literal['approved', 'rejected']
resolved_by str
comment str
answers Dict[str, str]

Attribute GateStatus

Class JiraLinked

Attributes:

Attribute Type Description
type Literal['run/jiraLinked']
issue_key str

Class NodeCompleted

Attributes:

Attribute Type Description
type Literal['node/completed']
node_id NodeId
summary Dict[str, str]

Class NodeFailed

Attributes:

Attribute Type Description
type Literal['node/failed']
node_id NodeId
error str

Attribute NodeId

Class NodeProgress

A node narrates what it is about to do, is doing, or concluded.

Authored by the node itself (DevLoopNode.report_progress), never derived from the SDK stream — so it says "Generating spec + task index from X" rather than "AssistantMessage". Text is clamped at validation so a careless caller cannot bloat the persisted envelope.

Attributes:

Attribute Type Description
type Literal['node/progress']
node_id NodeId
phase ProgressPhase
headline str
detail str
seat str
task_id str

Class NodeProgressEntry

One node-authored narrative line (what it is about to do / did).

Written by DevLoopNode.report_progress via :class:NodeProgress; headline is the one-liner the console shows, detail an optional second line. Both are clamped at the action boundary, so the projection can never grow past its display budget.

Attributes:

Attribute Type Description
phase ProgressPhase
headline str
detail str
ts float
seat str
task_id str

Class NodeSkipped

Attributes:

Attribute Type Description
type Literal['node/skipped']
node_id NodeId

Class NodeStarted

Attributes:

Attribute Type Description
type Literal['node/started']
node_id NodeId

Class NodeState

Per-node projection of the flow graph.

Attributes:

Attribute Type Description
node_id NodeId
status NodeStatus
started_at Optional[float]
finished_at Optional[float]
error str
dispatch Optional[DispatchState]
summary Dict[str, str]
progress List[NodeProgressEntry]

Attribute NodeStatus

Attribute PROGRESS_MAX

Attribute ProgressPhase

Class PullRequestLinked

Attributes:

Attribute Type Description
type Literal['run/prLinked']
pr_url str
changeset str

Class QaAttemptRecorded

Recorded each time QA fails and a repair retry is dispatched (FEAT-377 TASK-1910 — G1 bounded QA→development repair loop).

Note: the spec's §2 Data Models sketch names this action's type literal "qa_attempt_recorded"; every other action in this union follows a strict "<namespace>/camelCase" convention (e.g. "run/jiraLinked"), so this uses "run/qaAttemptRecorded" instead for consistency — semantically identical, no reducer dispatch anywhere parses the string structurally.

Attributes:

Attribute Type Description
type Literal['run/qaAttemptRecorded']
attempt int
qa_notes str

Attribute ROOT_CHANNEL

Attribute RootAction

Class RunAdded

Attributes:

Attribute Type Description
type Literal['root/runAdded']
summary RunSummary

Class RunCancelled

Attributes:

Attribute Type Description
type Literal['run/cancelled']
requested_by str

Class RunClosed

Attributes:

Attribute Type Description
type Literal['run/closed']
outcome Literal['succeeded', 'failed']
jira_issue_key str
pr_url str

Class RunCreated

Attributes:

Attribute Type Description
type Literal['run/created']
run_id str
revision bool
work_kind Literal['bug', 'enhancement', 'new_feature']
summary str

Class RunParked

FEAT-377 TASK-1917 (G6): a run released its concurrency slot to await a gate. Applied by DevLoopRunner when DEV_LOOP_GATE_PARK=true and the FIRST gate for this run opens (a run with multiple concurrently-pending gates parks once, on the 0->1 transition).

Attributes:

Attribute Type Description
type Literal['root/runParked']
run_id str

Attribute RunPhase

Class RunRegistryState

Authoritative state tree for the root channel (run catalogue).

Attributes:

Attribute Type Description
channel str
runs Dict[str, RunSummary]

Class RunRemoved

Attributes:

Attribute Type Description
type Literal['root/runRemoved']
run_id str

Class RunResumed

FEAT-377 TASK-1917 (G6): a parked run re-acquired its concurrency slot — applied on the LAST pending gate's resolution (the 1->0 transition), whether by explicit approval/rejection or TTL expiry.

Attributes:

Attribute Type Description
type Literal['root/runResumed']
run_id str

Class RunSummary

Small, display-ready projection of a run for the root catalogue.

Attributes:

Attribute Type Description
run_id str
phase RunPhase
work_kind str
summary str
jira_issue_key str
pr_url str
pending_gate_count int
created_at float
finished_at Optional[float]
parked bool

Class RunSummaryChanged

Attributes:

Attribute Type Description
type Literal['root/runSummaryChanged']
summary RunSummary

Class SeatUsageRecorded

Per-seat roll-up (tasks, retries, duration, tokens) for the summary.

Emitted by DevelopmentNode from the sdd-coder job journals or the pool's seat counters. The reducer REPLACES the list.

Attributes:

Attribute Type Description
type Literal['development/seatUsageRecorded']
seats List[SeatUsageSummary]

Class SeatUsageSummary

One agent seat's roll-up for the run summary: tasks, retries, time, tokens.

Built deterministically from the sdd-coder job journals (<worktree>/.sdd-coder/jobs/*.json, one AttemptRecord per attempt) by parrot.flows.dev_loop.sdd_coder.summary.summarize_job_seats, or from the dev-agent pool's per-seat SeatState counters. Token fields stay None — and usage_known False — when no attempt on the seat reported usage (codex CLI, native haiku seats); a fabricated 0 would read as "free".

Attributes:

Attribute Type Description
seat str
backend str
model str
tasks_handled List[str]
tasks_merged int
attempts int
retries int
failures int
duration_s float
input_tokens Optional[int]
output_tokens Optional[int]
cost_usd Optional[float]
usage_known bool

Class SessionHost

Minimal authoritative host for one session channel.

Responsibilities (per AHP): hold the state tree, validate commands, sequence accepted actions with server_seq, retain the envelope log for replay, and let gate-opening nodes await a gate's resolution. Transport (WS/REST) and persistence (Redis XADD of the envelope) plug in via on_envelope — this class stays pure-ish and NEVER imports redis/aiohttp itself.

NOT thread-safe by design: one host per run, driven from the runner's event loop (single-writer). Multi-client writes arrive as commands and are serialised here — that's the whole point.

Parameter Type Default Description
run_id str The run this host is authoritative for.
on_envelope Optional[Callable[[ActionEnvelope], None]] None Optional sink invoked with every accepted :class:ActionEnvelope (e.g. XADD to flow:{run_id}:actions). Exceptions raised by the sink are swallowed — the new-path publish must never break a run.

Attributes:

Attribute Type Description
state DevLoopSessionState The current, authoritative session state.

Method SessionHost.snapshot

Return a :class:Snapshot of the current state and seq.

snapshot() -> Snapshot

Returns: Snapshot

Method SessionHost.replay_since

Return all envelopes with server_seq > last_seen_server_seq.

replay_since(last_seen_server_seq: int) -> List[ActionEnvelope]

Parameter Type Default Description
last_seen_server_seq int

Returns: List[ActionEnvelope]

Method SessionHost.apply

Sequence + fold one action. Trusted-producer path (the flow).

apply(action: DevLoopAction, origin: Optional[ActionOrigin] = None) -> ActionEnvelope

Parameter Type Default Description
action DevLoopAction The action to sequence and fold.
origin Optional[ActionOrigin] None Optional multi-client attribution for this action.

Returns: ActionEnvelope — The sequenced :class:ActionEnvelope.

Method SessionHost.resolve_gate

Client command path — validated BEFORE sequencing.

First writer wins; later attempts raise and never become actions. This is the arbitration AHP describes for tool-call confirmation, applied to deployment/QA gates.

resolve_gate(gate_id: str, resolution: Literal['approved', 'rejected'], resolved_by: str, comment: str = '', origin: Optional[ActionOrigin] = None, answers: Optional[Dict[str, str]] = None) -> ActionEnvelope

Parameter Type Default Description
gate_id str The gate to resolve.
resolution Literal['approved', 'rejected'] "approved" or "rejected".
resolved_by str Identity of the resolving client/user.
comment str '' Optional free-text audit comment.
origin Optional[ActionOrigin] None Optional multi-client attribution (FEAT-322 TASK-1855 — the REST command layer records the calling client here).
answers Optional[Dict[str, str]] None FEAT-412 — structured question -> answer mapping for an open_questions gate. Required (non-empty) when approving such a gate; ignored for every other kind. Partial answers are allowed: questions the user left out simply stay open in the ideation document.

Returns: ActionEnvelope — The sequenced :class:ActionEnvelope for the resolution.

Raises:

  • GateNotFoundError — gate_id does not exist.
  • GateAlreadyResolvedError — the gate is no longer "pending".
  • ValueError — An open_questions gate is being approved with no answers — approving an ideation round means answering at least one question (rejection needs none: it aborts the ideation).

Method SessionHost.open_gate

Open a new gate (convenience for QA/DeploymentHandoff nodes).

open_gate(*, kind: GateKind, node_id: NodeId, title: str, instructions: str = '', payload_ref: str = '', ttl_seconds: Optional[int] = None, on_expiry: Literal['fail', 'approve'] = 'fail', questions: Optional[List[str]] = None) -> Tuple[str, ActionEnvelope]

Parameter Type Default Description
kind GateKind The gate kind (manual_criterion, deployment_approval, revision_approval, plan_approval, review_escalation, open_questions).
node_id NodeId The node opening the gate.
title str Short human-readable title.
instructions str '' Longer instructions/context for the approver.
payload_ref str '' Changeset/terminal URI carrying supporting evidence.
ttl_seconds Optional[int] None Optional per-gate TTL override.
on_expiry Literal['fail', 'approve'] 'fail' "fail" (fail-closed) or "approve" (fail-open).
questions Optional[List[str]] None FEAT-412 — the structured Open Questions carried by an open_questions gate (ONE gate per ideation round holds ALL of that round's questions). The UI renders one input per entry and POSTs back an answers mapping.

Returns: Tuple[str, ActionEnvelope] — A (gate_id, envelope) tuple.

Method SessionHost.expire_due_gates

Expiry sweep — call periodically from the runner's loop.

For each pending gate past its expires_at, applies the gate's on_expiry policy: "fail" → GateExpired (fail-closed; the flow routes to failure/escalation); "approve" → GateResolved by system:ttl-auto-approve (fail-open; audited in-state exactly like a human resolution). Reducer stays untouched.

expire_due_gates(now: Optional[float] = None) -> List[ActionEnvelope]

Parameter Type Default Description
now Optional[float] None Optional override for the current time (testing).

Returns: List[ActionEnvelope] — The list of envelopes emitted by this sweep pass.

Method SessionHost.wait_gate

Await a gate's resolution (approved/rejected/expired).

Works regardless of ordering: if the gate is already resolved when called, returns immediately; otherwise awaits the internal asyncio.Event set by :meth:apply when a matching gate/resolved/gate/expired action folds.

wait_gate(gate_id: str) -> ApprovalGate

Parameter Type Default Description
gate_id str The gate to wait on.

Returns: ApprovalGate — The final :class:ApprovalGate (status != "pending").

Raises:

  • GateNotFoundError — gate_id does not exist in state.

Class Snapshot

subscribe() result — state + the seq it corresponds to.

Attributes:

Attribute Type Description
channel str
state DevLoopSessionState
from_seq int

Function action_from_dispatch_event

Map a DispatchEvent.kind to a :data:DevLoopAction.

action_from_dispatch_event(kind: str, node_id: str, ts: float, payload: Optional[dict] = None, seat: str = '') -> Optional[DevLoopAction]

Parameter Type Default Description
kind str The dispatch event kind (e.g. "dispatch.queued").
node_id str The node hosting the dispatch (already rolled up to the owning node via _owning_node_id when the raw event's node_id is a pool seat).
ts float Event timestamp (POSIX seconds).
payload Optional[dict] None Optional raw payload dict; only display-ready fields are extracted (lazy-loading rule — heavy content stays by-reference).
seat str '' The raw dispatch seat (FEAT-496, e.g. "development.w1"), distinct from node_id. payload["seat"] (stamped by DispatchLabels) wins when present; this parameter is the fallback for unlabelled dispatches. Defaults to "" so every existing caller (pre-FEAT-496) is unaffected.

Returns: Optional[DevLoopAction] — The mapped action, or None if kind is not recognised.

Function action_from_flow_event

Map a FlowEventPublisher event to a :data:DevLoopAction.

action_from_flow_event(event: str, node_id: str, ts: float, error: str = '', node_result: Any = None) -> Optional[DevLoopAction]

Parameter Type Default Description
event str The flow event name (e.g. "node_started", unprefixed — callers strip the "flow." prefix before calling this shim).
node_id str The node the event concerns.
ts float Event timestamp (POSIX seconds).
error str '' Optional error string (only used for node_failed).
node_result Any None Serialised node result (only for node_completed).

Returns: Optional[DevLoopAction] — The mapped action, or None if event is not recognised (forward-compat: unknown events are ignored, never raise).

Function changeset_channel

Return the channel URI for the run's diff/PR view (AHP changeset channel).

changeset_channel(run_id: str) -> str

Parameter Type Default Description
run_id str The run identifier.

Returns: str — The parrot-changeset:/<run_id> channel URI.

Function classify_delta_content

Classify a dispatch.message payload (:data:DeltaContentKind).

Single source of truth for "does this message carry anything worth a narrative row": the dispatchers stamp its result onto the raw event payload (normalize_payload), the state shim copies it onto :class:DispatchDelta, and the consoles read the field instead of guessing from raw keys.

Precedence: visible assistant text, then a thinking snippet, then the SDK lifecycle frames (ResultMessage → "result", a SystemMessage/subtype init frame → "system"); anything else — the bare UserMessage envelopes that made the console unreadable — is "empty".

classify_delta_content(payload: dict) -> DeltaContentKind

Parameter Type Default Description
payload dict

Returns: DeltaContentKind

Function reduce

Pure reducer: (state, action) -> new_state.

Total over the action union; unknown/late actions against terminal states degrade to no-ops rather than raising (host validation is the layer that rejects — the reducer only folds).

reduce(state: DevLoopSessionState, action: DevLoopAction) -> DevLoopSessionState

Parameter Type Default Description
state DevLoopSessionState The current session state.
action DevLoopAction The action to fold.

Returns: DevLoopSessionState — The new session state. fold(log) == state is the invariant this function must uphold under any action sequence.

Function reduce_root

Pure reducer for the root channel (run catalogue).

Total and non-raising, mirroring :func:reduce: an unknown/late root/runRemoved for a run_id not in state.runs is a no-op.

reduce_root(state: RunRegistryState, action: RootAction) -> RunRegistryState

Parameter Type Default Description
state RunRegistryState The current run-registry state.
action RootAction The root action to fold.

Returns: RunRegistryState — The new run-registry state.

Function session_channel

Return the channel URI for a dev-loop run (AHP session channel).

session_channel(run_id: str) -> str

Parameter Type Default Description
run_id str The run identifier (e.g. run-<hex8> or rev-<hex8>).

Returns: str — The parrot-session:/<run_id> channel URI.

Function terminal_channel

Return the channel URI for a dispatch pty/stream (AHP terminal channel).

terminal_channel(run_id: str, node_id: str) -> str

Parameter Type Default Description
run_id str The run identifier.
node_id str The node hosting the dispatch (e.g. "development").

Returns: str — The parrot-terminal:/<run_id>/<node_id> channel URI.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally