pub struct SessionRegistry { /* private fields */ }Expand description
The daemon-owned session registry (Axiom 4).
Why: single source of truth for every session’s state, in-memory only
(§12, M1) — see the module docs for the full rationale.
What: see method docs below; new() uses DEFAULT_RING_CAPACITY,
with_capacity lets tests use a tiny buffer to exercise eviction cheaply.
Test: registry_tests::*.
Implementations§
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn record_index_readiness(
&self,
id: &str,
readiness: Option<&IndexReadiness>,
summary: &str,
) -> Result<(), RpcError>
pub fn record_index_readiness( &self, id: &str, readiness: Option<&IndexReadiness>, summary: &str, ) -> Result<(), RpcError>
Record a project’s trusty-search index readiness (issue #2784’s UI Phase-1 follow-up).
Why: trusty_common::search_readiness already probes this per lane and
then only logged it to stderr, where no API consumer could reach it.
The UI is a thin client over this daemon — anything it renders must
arrive as an event — so a warming index was structurally unrenderable.
Critically, this is what lets a consumer tell a COLD index from a READY
one with genuinely zero hits: both return an empty search, but they mean
opposite things, and conflating them is exactly what makes a model
conclude “nothing there” and hand-explore to the wrong target.
What: takes the probe’s Option<IndexReadiness> — None (fail-open: no
daemon, undrivable id, HTTP error) maps to state: "unavailable" with
every lane false and no index fields, which is itself the useful
signal rather than something to swallow. Some maps to "ready" when
semantic_search_ready() and "warming" otherwise, carrying the
per-lane flags through verbatim. Errors with session_not_found if id
is unknown.
(DOC-39 §5.6 Slice D) Also caches the resulting IndexReadinessSnapshot
on the session (last-writer-wins), so a client that attaches AFTER this
one-time event fires can still retrieve it via
Self::get_readiness/session.get_readiness.
Test: registry_tests::record_index_readiness_warming_publishes_event,
registry_tests::record_index_readiness_ready_publishes_event,
registry_tests::record_index_readiness_unavailable_publishes_event,
registry_tests::record_index_readiness_caches_snapshot_for_late_query.
Sourcepub fn get_readiness(&self, id: &str) -> Result<ReadinessQuery, RpcError>
pub fn get_readiness(&self, id: &str) -> Result<ReadinessQuery, RpcError>
session.get_readiness: return the last-recorded index-readiness
probe for a session, for clients that attach after the one-time
Event::IndexReadiness already fired (DOC-39 §5.6 Slice D).
Why: Self::record_index_readiness emits its event exactly once, at
task start (see run_task::ensure_project_indexed_in_background’s
call site in task::executor). A UI that connects even a moment later
has no query surface to ask “what is the readiness state right now” —
only a stream it may have missed. This is that query surface.
What: Err(session_not_found) if id is unknown. Otherwise
[ReadinessQuery::Probed] wrapping the cached IndexReadinessSnapshot
if a probe has ever landed for this session, or
[ReadinessQuery::NeverProbed] — a distinct, clearly-typed state,
never a bare null — if no record_index_readiness call has happened
yet (e.g. a projectless session, or one queried before its background
indexing probe completes).
Test: registry_tests::record_index_readiness_caches_snapshot_for_late_query,
protocol_readiness::tests::get_readiness_never_probed_session_returns_never_probed,
registry_tests::get_readiness_unknown_session_errors.
Sourcepub fn record_context_budget(
&self,
id: &str,
measurement: &ContextBudgetSnapshot,
) -> Result<(), RpcError>
pub fn record_context_budget( &self, id: &str, measurement: &ContextBudgetSnapshot, ) -> Result<(), RpcError>
Record one turn’s working-context budget measurement (epic #2343; caches the snapshot for late queries as of issue #3015).
Why: the Infinite Sessions guarantee (working context >= 60%, session
overhead <= 40%) is enforced every single turn and was visible to
nothing — CadenceOutcome was computed and dropped. This is the
emission plumbing that lets task::SessionToolEventSink forward the
measurement to a session.attached UI’s budget indicator. (issue
#3015) Also caches the resulting ContextBudgetSnapshot on the
session (last-writer-wins), mirroring Self::record_index_readiness,
so a client that attaches or reconnects AFTER a turn’s event already
fired can still retrieve it via Self::get_context_budget/
session.get_context_budget — the API PR #3014’s GUI status bar
polls instead of leaving “budget: unavailable” permanently.
What: maps the caller’s agent_loop::ContextBudgetSnapshot field-for-
field onto a cached ContextBudgetSnapshot first, then derives
Event::ContextBudget from that cached value so the two can never
disagree; every value is already computed by the caller, so this adds
no arithmetic of its own. Errors with session_not_found if id is
unknown.
(#3868) lifetime_compaction_alarm_count is stored as a 0
placeholder here — this method runs on the EVERY-TURN write path
(AgentLoop::maybe_cadence_compress forwards to it once per cadence
tick), so a File::open + line-scan here would pay the durable-log
read cost once per turn per session. Self::get_context_budget
(the actual RPC query path — called far less often, once per client
poll) overwrites this field with a fresh read before returning, so no
caller ever observes the placeholder.
(#3948) The session’s working-context floor takes the opposite route:
it is folded in HERE, under the same lock that stores the snapshot,
because a min over one u8 costs nothing per turn while the query
path’s alternative — rescanning the multi-session
compression.jsonl — grows with the machine’s whole compression
history.
Test: registry_tests::record_context_budget_publishes_event,
registry_tests::record_context_budget_caches_snapshot_for_late_query,
registry_tests::context_floor_tracks_every_measurement,
registry_tests::context_floor_is_session_scoped.
Sourcepub fn get_context_budget(
&self,
id: &str,
) -> Result<ContextBudgetQuery, RpcError>
pub fn get_context_budget( &self, id: &str, ) -> Result<ContextBudgetQuery, RpcError>
session.get_context_budget: return the last-recorded working-context
budget measurement for a session, for clients that attach after the
per-turn Event::ContextBudget already fired (issue #3015).
Why: Self::record_context_budget emits its event once per PM turn
boundary — a client that attaches (or reconnects) between turns has no
query surface to ask “what is the budget right now”, only a stream it
may have missed. This is that query surface, the exact counterpart to
Self::get_readiness.
What: Err(session_not_found) if id is unknown. Otherwise
[ContextBudgetQuery::Recorded] wrapping the cached
ContextBudgetSnapshot if a turn has ever completed for this
session, or [ContextBudgetQuery::NeverRecorded] — a distinct,
clearly-typed state, never a bare null — if no
record_context_budget call has happened yet (e.g. a session queried
before its first PM turn completes, or a delegated sub-agent session,
which never emits cadence budget events at all).
(#3868) lifetime_compaction_alarm_count is read fresh from the
durable, cross-session alarm log HERE — the query path, called once
per client poll — rather than in Self::record_context_budget (the
every-turn write path), so the File::open + line-scan cost is paid
once per query, not once per turn per session. This is also why the
count reflects fires from ANY session on this machine, not just this
one: it is derived from a shared log, not a per-session cache.
(#3948) working_context_pct_low_water_mark/
working_context_pct_sample_count are read from the state
Self::record_context_budget retains per session, NOT from
compression.jsonl. This query used to call
telemetry::session_working_context_floor, which reopens and reparses
the machine-wide compression log on every poll; that function is
unchanged and remains the offline-history reader, but no live query
path calls it. The two answers are not identical, and the difference
is deliberate: the live floor samples EVERY cadence tick, while the
log only carries a percentage for turns where compaction work
happened (rounds > 0) plus threshold-compaction fires, which
record_context_budget never sees. So the live floor is over a
per-turn superset of this session’s cadence measurements, and
working_context_pct_sample_count counts cadence measurements rather
than durable rows.
Test: registry_tests::record_context_budget_caches_snapshot_for_late_query,
protocol_budget::tests::get_context_budget_never_recorded_session_returns_never_recorded,
registry_tests::get_context_budget_unknown_session_errors,
protocol_budget::tests::get_context_budget_reflects_lifetime_compaction_alarm_count,
protocol_budget::tests::get_context_budget_reflects_working_context_floor,
registry_tests::context_budget_query_does_not_open_compression_log,
registry_tests::context_floor_after_restart_is_absent_not_wrong.
Sourcepub fn record_tool_started(
&self,
id: &str,
agent: &str,
agent_id: &str,
tool: &str,
call_id: &str,
args: &str,
) -> Result<(), RpcError>
pub fn record_tool_started( &self, id: &str, agent: &str, agent_id: &str, tool: &str, call_id: &str, args: &str, ) -> Result<(), RpcError>
Record a tool invocation starting (#2055 emission plumbing for #2056’s agent loop).
Why: gives the future agent loop a stable, already-wired call for
ToolStarted without it needing to touch the ring buffer, sequencing,
or bus directly.
What: errors with session_not_found if id is unknown; args_preview
is truncated via crate::events::preview before emission so a large
argument payload can’t blow the ring buffer / wire size. agent
(UI Phase 1) is the dispatching agent’s name — see
crate::events::Event::ToolStarted. agent_id (DOC-39 AC-13) is
that same agent’s stable per-spawn id.
Test: registry_tests::record_tool_started_publishes_event.
Sourcepub fn record_tool_finished(
&self,
id: &str,
agent: &str,
agent_id: &str,
tool: &str,
call_id: &str,
success: bool,
result: &str,
) -> Result<(), RpcError>
pub fn record_tool_finished( &self, id: &str, agent: &str, agent_id: &str, tool: &str, call_id: &str, success: bool, result: &str, ) -> Result<(), RpcError>
Record a tool invocation finishing (#2055 emission plumbing for
#2056’s agent loop). See Self::record_tool_started.
Test: registry_tests::record_tool_finished_publishes_event.
(DOC-39 AC-13) agent_id pushed this past clippy’s
too_many_arguments gate; every parameter is a plain, independent
piece of the event and none pair naturally into a sub-struct, so the
attribute is the pragmatic choice here (mirrors
serve::transport::run_loop’s same allowance).
Sourcepub fn record_tool_error(
&self,
id: &str,
agent: &str,
agent_id: &str,
tool: &str,
call_id: &str,
error: &str,
) -> Result<(), RpcError>
pub fn record_tool_error( &self, id: &str, agent: &str, agent_id: &str, tool: &str, call_id: &str, error: &str, ) -> Result<(), RpcError>
Record a tool invocation raising an exceptional error (#2055 emission
plumbing for #2056’s agent loop). See Self::record_tool_started.
Test: registry_tests::record_tool_error_publishes_event.
Sourcepub fn record_search_performed(
&self,
id: &str,
agent: &str,
agent_id: &str,
telemetry: &SearchTelemetry,
) -> Result<(), RpcError>
pub fn record_search_performed( &self, id: &str, agent: &str, agent_id: &str, telemetry: &SearchTelemetry, ) -> Result<(), RpcError>
Record a search_code call’s real lane + hit count + per-hit
path/score + latency (UI Phase 1; hits added DOC-39 Slice B). See
crate::events::Event::SearchPerformed.
Why: emitted ALONGSIDE the generic tool events so the UI can trace a
change back to the searches that drove it without re-parsing prose.
What: same existence guard + ring-buffer/sequencing path as every
other record_*, so a structured event replays on session.attach
exactly like the generic ones.
Test: registry_tests::record_search_performed_publishes_event,
registry_search_audit::tests::get_search_audit_returns_records_after_recording.
Sourcepub fn record_memory_recalled(
&self,
id: &str,
agent: &str,
agent_id: &str,
telemetry: &RecallTelemetry,
) -> Result<(), RpcError>
pub fn record_memory_recalled( &self, id: &str, agent: &str, agent_id: &str, telemetry: &RecallTelemetry, ) -> Result<(), RpcError>
Record a recall_session call’s results and which ones entered
context (UI Phase 1). See crate::events::Event::MemoryRecalled.
Why: the injected flag is the UI’s differentiating surface —
injected memories vs ones recalled and held back.
What: as Self::record_search_performed.
Test: registry_tests::record_memory_recalled_publishes_event,
registry_search_audit::tests::get_search_audit_returns_records_after_recording.
Sourcepub fn record_log(
&self,
id: &str,
level: &str,
message: &str,
) -> Result<(), RpcError>
pub fn record_log( &self, id: &str, level: &str, message: &str, ) -> Result<(), RpcError>
Record a session-scoped diagnostic log line (#2055 emission plumbing).
Test: registry_tests::record_log_publishes_event.
Sourcepub fn record_progress(
&self,
id: &str,
message: &str,
percent: Option<f32>,
) -> Result<(), RpcError>
pub fn record_progress( &self, id: &str, message: &str, percent: Option<f32>, ) -> Result<(), RpcError>
Record a coarse progress update (#2055 emission plumbing).
Test: registry_tests::record_progress_publishes_event.
Sourcepub fn record_message(&self, id: &str, text: &str) -> Result<(), RpcError>
pub fn record_message(&self, id: &str, text: &str) -> Result<(), RpcError>
Record a generic freeform session message (#2055 emission plumbing).
Test: registry_tests::record_message_publishes_event.
Sourcepub fn record_agent_message_delta(
&self,
id: &str,
agent: &str,
agent_id: &str,
turn_id: &str,
delta: &str,
done: bool,
) -> Result<(), RpcError>
pub fn record_agent_message_delta( &self, id: &str, agent: &str, agent_id: &str, turn_id: &str, delta: &str, done: bool, ) -> Result<(), RpcError>
Record one assistant turn’s text as an AgentMessageDelta (tcode
streaming epic #3696, Gap A, Slice 1). See
crate::events::Event::AgentMessageDelta for the turn_id
uniqueness requirement and the (agent_id, turn_id) grouping contract.
Test: registry_tests::record_agent_message_delta_publishes_event.
Sourcepub fn record_agent_spawned(
&self,
id: &str,
agent: &str,
agent_id: &str,
task: &str,
) -> Result<(), RpcError>
pub fn record_agent_spawned( &self, id: &str, agent: &str, agent_id: &str, task: &str, ) -> Result<(), RpcError>
Record a delegated sub-agent’s loop starting (#7940).
Why: the opening bracket of a delegation block — see
crate::events::Event::AgentSpawned for why a client cannot infer
it from the attributed tool/message events alone.
What: errors with session_not_found if id is unknown;
task_preview is truncated via crate::events::preview so a long
delegation brief can’t blow the ring buffer / wire size.
Test: registry_tests::record_agent_spawned_publishes_event.
Sourcepub fn record_agent_done(
&self,
id: &str,
agent: &str,
agent_id: &str,
status: &str,
) -> Result<(), RpcError>
pub fn record_agent_done( &self, id: &str, agent: &str, agent_id: &str, status: &str, ) -> Result<(), RpcError>
Record a delegated sub-agent’s loop returning normally (#7940). See
Self::record_agent_spawned.
Test: registry_tests::record_agent_done_publishes_event.
Sourcepub fn record_agent_failed(
&self,
id: &str,
agent: &str,
agent_id: &str,
error: &str,
) -> Result<(), RpcError>
pub fn record_agent_failed( &self, id: &str, agent: &str, agent_id: &str, error: &str, ) -> Result<(), RpcError>
Record a delegated sub-agent’s loop aborting (#7940). See
Self::record_agent_spawned.
Test: registry_tests::record_agent_failed_publishes_event.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn claim_prompter(&self, id: &str) -> Option<PrompterGuard>
pub fn claim_prompter(&self, id: &str) -> Option<PrompterGuard>
Claim id as watched by a prompter until the returned guard drops.
Why (#8100): the counted thing is a client that can both SEE this
session’s permission_requested event and answer it with
session.permission.respond — session.attach, the session.events
stream, and the per-session HTTP SSE route. The workstream-aggregate
route (workstreams::sse) is deliberately NOT a claimant: it is bound
to a workstream, re-checks membership per event, and a session can
leave the group mid-ask, so no session’s prompt is its to display.
What: None when id names no live session — nothing was claimed, so
there is nothing to release, and prompter_count keeps reading 0.
Test: registry_tests::prompter_attached_while_a_session_attachment_lives,
registry_tests::prompter_claim_is_released_when_its_guard_drops.
Sourcepub fn prompter_count(&self, id: &str) -> usize
pub fn prompter_count(&self, id: &str) -> usize
How many prompters currently watch id; 0 for an unknown session.
Why (#8100): an unknown session is the fail-safe arm — a permission
prompt for a session the registry cannot find is a prompt nobody can be
shown, so it must read as unwatched and deny rather than wait.
What: SessionRegistry::lock recovers a poisoned mutex through
into_inner, so the count stays readable after an unrelated panic and
the missing entry is the only unreadable arm.
Test: registry_tests::prompter_attached_for_an_unknown_session_is_false,
registry_tests::prompter_count_survives_a_poisoned_registry_lock.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn record_permission_requested(
&self,
id: &str,
request_id: &str,
agent: &str,
agent_id: &str,
tool: &str,
subject: &str,
rule: &str,
) -> Result<(), RpcError>
pub fn record_permission_requested( &self, id: &str, request_id: &str, agent: &str, agent_id: &str, tool: &str, subject: &str, rule: &str, ) -> Result<(), RpcError>
Record a tool call suspended on an ask permission rule (#7948).
Why: crate::permissions emits through its PermissionEvents trait so
it never depends on the session layer; this is the implementation side.
What: subject arrives already redacted and bounded by the gate and is
recorded as-is.
Test: registry_tests::record_permission_requested_publishes_event.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn memory_sink_for(
self: &Arc<Self>,
id: &str,
project_dir: Option<&Path>,
) -> Option<Arc<TurnMemorySink>>
pub fn memory_sink_for( self: &Arc<Self>, id: &str, project_dir: Option<&Path>, ) -> Option<Arc<TurnMemorySink>>
Lazily construct (on first call) or return (on every later call) this session’s durable turn-recorder sink.
Why: task::executor::run_and_record needs the SAME
Arc<TurnMemorySink> — and therefore the same background drain task
and bounded queue — across every task.run on one session, not a
fresh one per run (a fresh sink per run would spawn a new drain task
each time, multiplying in-flight writers with no bound). Constructing
it here, inside the session-map lock, means two calls can never build
two different sinks for the same session even under a hypothetical
race (in practice Self::begin_execution’s single-in-flight-run guard
already prevents concurrent calls per session).
What: None if id is unknown (best-effort — mirrors
Self::set_run_outcome’s framing; the caller has already validated
the session’s existence earlier in the same run via
begin_execution/begin_pm_transcript). On the FIRST call for a
session, derives the palace id from project_dir via
derive_palace_id_for_project, resolves trusty-memory’s base URL
via [resolve_recorder_socket] (never the live daemon from a test
process, #9139; fail-open — the sink is built regardless of whether the daemon is
currently reachable; every write attempt after that is independently
fail-open, see memory_sink::write_turn), and stores the constructed
Arc. On every SUBSEQUENT call, project_dir is ignored and the
already-built sink is returned unchanged — a session’s palace/base-url
binding is fixed for its lifetime, mirroring
Self::begin_pm_transcript’s analogous “the system prompt is fixed
after the first call” rule.
project_dir is None for a PROJECTLESS session, which returns None:
a memory palace is project-scoped by construction, so with no project
there is nothing to scope one to. This is a deliberate skip, not a
degradation — the caller must NOT substitute the run’s scratch root,
since deriving a palace id from a throwaway temp path would mint a fresh,
orphaned palace on every projectless run. The whole sink is already
fail-open and fire-and-forget, so its absence costs a projectless run
nothing but the durable turn record it has no home for anyway.
(#4638) This is also where the sink’s PalaceCreation entitlement is
decided, and that decision is the fix for the leak the paragraph above
was written to prevent. The projectless branch guarded only the None
case, so a session BOUND to a tempfile::TempDir walked straight
through it: derive_palace_id_for_project fell to its
parent_dir_slug level and produced a per-RUN-unique id
(t-tmp<random> on macOS, from $TMPDIR/.tmpXXXXXX), and
TurnMemorySink’s drain task auto-CREATED that palace on the live
daemon at the first turn. Every such run minted one palace nothing would
ever read again: 5,667 orphans in three weeks, 97.8% of every palace on
the machine, which turned trusty-memory’s O(n) full-registry handlers
(#4637) into a ~90-minute GET /api/v1/status. A palace is an expensive
object (usearch index, KG redb, drawer table, recall log), not a cheap
namespace, and the trusty-code suite alone drives dozens of temp-rooted
sessions per cargo test run.
The BOUND: PalaceCreation::Allowed only for a DURABLE project root,
so the recorder can create at most one palace per real project, reused
by every session on that project forever — the same palace
catchup::pm_catchup_context reads its digest from. N sessions create
at most one palace, never N. Sessions stay distinguishable INSIDE it via
chat_turn_append’s session_id and memory_remember’s
session:<id> tag (exactly how #2348’s recall_session already scopes
its query), so no session-level recall is lost.
(#5811) A project root whose palace CANNOT BE RESOLVED gets no sink at
all. derive_palace_id_for_project used to answer the shared literal
"unknown-project" on any failure, and a durable root carries
PalaceCreation::Allowed, so two projects with unresolvable identity
auto-created and then shared one palace holding both of their real
prompts and responses. Declining the sink is the structural fix: there is
no palace to name, so there is nothing to write into. The resolve runs
BEFORE the temp-root check because an unresolvable identity is
disqualifying whether or not the root is durable.
An ephemeral root still gets a full sink — only the CREATE is withheld.
That distinction is deliberate: the sink is what registers #2348’s
recall_session tool and what run_and_record reuses for its
socket/palace, so returning None here would silently change the
PM’s tool surface for a temp-rooted run. With
PalaceCreation::Forbidden the drain task still writes into a palace
that ALREADY exists and merely declines to bring a new one into being —
see memory_sink::drain.
Test: registry_tests::memory_sink_for_reuses_the_same_sink_across_calls,
registry_tests::memory_sink_for_unknown_session_returns_none,
registry_tests::memory_sink_for_projectless_session_returns_none,
registry_tests::memory_sink_for_temp_rooted_session_forbids_palace_create,
registry_tests::memory_sink_for_many_sessions_mint_at_most_one_palace.
(#2425) The receiver is &Arc<Self> rather than &self because the
sink is handed a durability observer holding a Weak<SessionRegistry>,
and a weak reference can only be minted from an Arc. Weak and not
Arc: the registry owns the sink, which owns the observer, so a strong
back-reference would be a cycle that never drops. This is a BREAKING
change to trusty-code’s public API — every in-workspace caller already
holds an Arc<SessionRegistry>, so no call site changed.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn get_transcript(&self, id: &str) -> Result<TranscriptRecord, RpcError>
pub fn get_transcript(&self, id: &str) -> Result<TranscriptRecord, RpcError>
session.get_transcript: fetch the stored run record for a session
(#2058).
Why: Self::set_run_outcome populates the storage; this is its read
counterpart — the M1 cut-line’s “inspect transcript” verb. A never-run
session is a valid, empty transcript, not an error: SessionEntry’s
transcript/usage/cost_usd fields already default to
empty/zero/None at create time, so returning them unconditionally
(once the session itself is confirmed to exist) is correct with no
extra branching.
What: Err(session_not_found) if id is unknown; otherwise a clone of
whatever is currently stored, wrapped in a self-describing
TranscriptRecord. Never recomputes cost, usage, or durability —
exposes exactly what Self::set_run_outcome and (#2425)
Self::record_memory_durability last stored. compaction_events
(#2349) reads entry.pm_transcript’s own cumulative counter — 0 when
the session has never run (pm_transcript still None).
Test: registry_tests::get_transcript_returns_stored_record,
registry_tests::get_transcript_on_never_run_session_is_empty,
registry_tests::get_transcript_unknown_session_errors,
registry_tests::get_transcript_reports_compaction_events,
registry_tests::get_transcript_round_trips_goal_state,
registry_tests::memory_durability_retains_counts_resets_streak_and_warns_at_one_and_three.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn set_goal(
&self,
id: &str,
slot: usize,
text: &str,
) -> Result<(), RpcError>
pub fn set_goal( &self, id: &str, slot: usize, text: &str, ) -> Result<(), RpcError>
session.set_goal: write an operator-provided goal into a 1-based
slot (#2350).
Why: the operator-facing counterpart to the model-facing set_goal
tool (#2347) — same shared GoalSlots, tagged GoalSource::Operator
so a later read can tell the two apart.
What: Err(session_not_found) if id is unknown. Err(invalid_argument)
if the session has no pm_transcript yet (see module docs’ design
decision) or if slot is 0/greater than GOAL_SLOT_COUNT. A
poisoned goals lock is recovered (mirrors tools::goals’s
convention) rather than propagating a panic.
Test: registry_tests::set_goal_writes_operator_source,
registry_tests::set_goal_no_transcript_yet_errors,
registry_tests::set_goal_out_of_range_slot_errors,
registry_tests::set_goal_unknown_session_errors.
Sourcepub fn clear_goal(&self, id: &str, slot: usize) -> Result<(), RpcError>
pub fn clear_goal(&self, id: &str, slot: usize) -> Result<(), RpcError>
session.clear_goal: clear an operator-named 1-based slot (#2350).
Why: the operator-facing counterpart to the model-facing clear_goal
tool (#2347).
What: same error shape as Self::set_goal. Clearing an
already-empty slot is idempotent success (mirrors
GoalSlots::clear’s own convention).
Test: registry_tests::clear_goal_clears_slot,
registry_tests::clear_goal_no_transcript_yet_errors,
registry_tests::clear_goal_out_of_range_slot_errors.
Sourcepub fn get_goals(&self, id: &str) -> Result<Vec<GoalSlotRecord>, RpcError>
pub fn get_goals(&self, id: &str) -> Result<Vec<GoalSlotRecord>, RpcError>
session.get_goals: snapshot every currently-occupied goal slot
(#2350).
Why: the operator-facing read path — lets a client inspect the
current goal state (from either source) without going through
session.get_transcript’s larger payload.
What: Err(session_not_found) if id is unknown; otherwise
[goal_records] — [] for a session with no pm_transcript yet,
matching session.get_transcript’s never-run convention rather than
set_goal/clear_goal’s stricter error.
Test: registry_tests::get_goals_returns_operator_and_model_sources,
registry_tests::get_goals_on_never_run_session_is_empty,
registry_tests::get_goals_unknown_session_errors.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn get_agents(&self, id: &str) -> Result<Vec<AgentRosterEntry>, RpcError>
pub fn get_agents(&self, id: &str) -> Result<Vec<AgentRosterEntry>, RpcError>
session.get_agents(session_id) -> { agents: [AgentRosterEntry] }
(DOC-39 §5.4).
Why: the principled, daemon-owned, EVICTION-SAFE replacement for the
client-side ring-buffer fold §5.4 originally acknowledged as a
time-boxed Phase-1 loan — see the module docs for why reading the
bounded ring directly (this endpoint’s first cut) was itself still a
silent-data-loss bug, not a fix.
What: -32007 session_not_found if id is unknown. Otherwise
projects SessionEntry::agents (the always-retained per-agent
roster, in first-seen order) into one [AgentRosterEntry] per row. A
session with no tool activity yet returns an empty roster, not an
error — the same “empty means nothing yet” convention
session.get_goals/session.get_transcript use.
Test: registry_agents::tests::get_agents_empty_session_returns_empty_roster,
registry_agents::tests::get_agents_running_tool_reports_running_state,
registry_agents::tests::get_agents_finished_tool_reports_idle_state,
registry_agents::tests::get_agents_distinguishes_same_named_concurrent_spawns,
registry_agents::tests::get_agents_survives_ring_eviction,
registry_agents::tests::get_agents_unknown_session_errors.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn bind_workstream(
&self,
id: &str,
workstream_id: WorkstreamId,
) -> Result<(), RpcError>
pub fn bind_workstream( &self, id: &str, workstream_id: WorkstreamId, ) -> Result<(), RpcError>
Stamp a freshly-minted session’s immutable workstream binding, and
publish Event::SessionAdded.
Why: session::protocol::create and task::protocol::task_run are
the ONLY callers, each calling this at most once — immediately after
Self::create mints the session’s id and the caller has separately
persisted the binding into the workstream store — so there is no
setter that changes Session.workstream_id a second time; this
method itself does not enforce that (it would silently overwrite),
the immutability guarantee comes from the call sites never invoking
it twice for the same session (a REUSED session on task.run never
calls this again — see task::protocol::task_run’s docs on the
mismatch rejection it performs instead).
What: Err(session_not_found) if id is unknown; otherwise sets
entry.session.workstream_id = Some(workstream_id) and records+
publishes Event::SessionAdded { session_id, workstream_id, binding_time } through the normal per-session ring buffer/live bus
(Self::record) — see that event’s own docs for why this is what
lets crate::workstreams::sse::aggregate_live’s dynamic membership
re-check pick it up with no changes.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn get_search_audit(
&self,
id: &str,
) -> Result<Vec<SearchAuditRecord>, RpcError>
pub fn get_search_audit( &self, id: &str, ) -> Result<Vec<SearchAuditRecord>, RpcError>
session.get_search_audit(session_id) -> { search_audit: [SearchAuditRecord] } (issue #3072).
Why: the query surface DOC-39 §4.7’s Search tab and #3027’s monitor
card poll instead of buffering the SSE stream client-side — see
module docs.
What: -32007 session_not_found if id is unknown; otherwise the
retained SearchAuditRecord list, oldest-first, verbatim. A session
with no search/recall activity yet returns an empty list, not an
error — the same “empty means nothing yet” convention
session.get_agents/session.get_goals use.
Test: tests::get_search_audit_empty_session_returns_empty_list,
tests::get_search_audit_returns_records_after_recording,
tests::get_search_audit_unknown_session_errors.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn set_task_result(&self, id: &str, result: TaskResult)
pub fn set_task_result(&self, id: &str, result: TaskResult)
Record this session’s actionable run result (#4351).
Why: session.status must be able to hand a caller the branch/ref/
pass-fail story, not just an opaque id — see
crate::session::task_result for why. crate::task::executor is the
only production caller; it fires exactly once, immediately before
finish, so the result and the terminal status become visible in the
same snapshot.
What: overwrites Session::result wholesale. A session that has
vanished (never created, or already pruned) is a silent no-op — the
same contract Self::set_run_outcome uses, and for the same reason:
this is called from a detached task that cannot meaningfully handle
“the session went away while I was running”.
Test: registry_tests::set_task_result_stores_the_result,
registry_tests::set_task_result_on_unknown_session_is_a_no_op.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub async fn await_cancelled(
&self,
id: &str,
grace: Duration,
) -> Result<(), RpcError>
pub async fn await_cancelled( &self, id: &str, grace: Duration, ) -> Result<(), RpcError>
Wait, bounded by grace, for id’s cancelled execution to ACTUALLY
stop (#8207).
Why: Self::request_cancel only flips a cooperative flag, so a
caller that reported “cancelled” the moment it returned was reporting a
request, not an outcome — the daemon-side task kept running and the
next task.run on the same session was rejected with
invalid_argument (“already has a task running”). “Reported cancelled”
and “actually stopped” have to be the same fact, so session.cancel
blocks here until the spawned run’s JoinHandle resolves. The run
clears its own slot as its last act (task::executor::run_and_record
calls finish_execution), so a resolved handle IS the guarantee that a
following begin_execution will be accepted.
What: claims the run via Self::claim_cancel_confirm and then, per
claim: joins the handle it owns (Self::join_owned), waits for the
peer that owns it (Self::await_peer_confirm), returns Ok(()) for
an idle session (nothing left to wait for), or fails closed for an
execution that is tracked with no handle at all. Never downgrades a
failure to success: every unconfirmed outcome is
RpcError::cancel_unconfirmed, so the caller can say “still
cancelling” rather than lie. Err(session_not_found) for an unknown
id.
Test: registry_cancel_tests::await_cancelled_returns_once_the_task_has_stopped,
registry_cancel_tests::await_cancelled_errors_when_the_task_outlives_the_grace,
registry_cancel_tests::await_cancelled_is_ok_when_nothing_is_executing,
registry_cancel_tests::await_cancelled_errors_when_the_execution_has_no_handle,
registry_cancel_tests::await_cancelled_unknown_session_errors,
registry_cancel_tests::a_panicked_run_lands_failed_and_releases_its_slot,
registry_cancel_tests::a_dead_handle_never_fails_a_newer_run,
registry_cancel_tests::the_grace_timeout_never_clobbers_a_newer_runs_handle,
registry_cancel_tests::two_concurrent_cancels_both_learn_the_run_stopped.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn set_agent_todos(
&self,
id: &str,
agent: &str,
agent_id: &str,
todos: Vec<TodoItem>,
) -> Result<(), RpcError>
pub fn set_agent_todos( &self, id: &str, agent: &str, agent_id: &str, todos: Vec<TodoItem>, ) -> Result<(), RpcError>
Replace agent_id’s checklist in session id, then stream the change
(#8235).
Why: the ONE write path onto the roster’s todos, so the state and
the Event::TodosChanged that announces it can never disagree — a
second call site could update one without the other.
What: Err(session_not_found) if id is unknown;
Err(invalid_argument) for an empty agent_id, which has no roster
row to key on and would therefore make the write silently invisible.
Otherwise find-or-inserts the row (a new row starts running: false —
writing a checklist is not a tool call in flight), replaces todos
whole, releases the lock, and records the event. An existing row keeps
its running state and its name is refreshed, matching
SessionEntry::note_agent_activity’s last-writer-wins convention.
Test: tests::set_agent_todos_writes_the_roster_row,
tests::set_agent_todos_replaces_the_whole_list,
tests::set_agent_todos_keeps_two_agents_lists_apart,
tests::set_agent_todos_keeps_two_sessions_lists_apart,
tests::set_agent_todos_streams_a_change_event,
tests::set_agent_todos_unknown_session_errors,
tests::set_agent_todos_empty_agent_id_errors,
tests::set_agent_todos_leaves_running_state_alone.
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn with_capacity(ring_capacity: usize) -> Self
pub fn with_capacity(ring_capacity: usize) -> Self
Construct an empty registry with an explicit ring-buffer capacity.
Why: unit tests need a small capacity to exercise eviction without pushing 1000 events.
Sourcepub fn create(
&self,
task: String,
agent: Option<String>,
binding: ProjectBinding,
) -> Session
pub fn create( &self, task: String, agent: Option<String>, binding: ProjectBinding, ) -> Session
session.create: register a brand-new session and publish its
lifecycle-start events.
Why: the sole entry point that mints a session id and puts a
Session into the registry.
What: builds a Session with a fresh UUIDv4 id and
status = Created, inserts it (with a fresh seq = 0 counter),
publishes Event::SessionStarted (assigned seq = 1), then
immediately transitions to Running (M1 has no queue ahead of real
task execution — see session::model docs) which publishes
Event::SessionStatusChanged (seq = 2). Returns the
post-transition snapshot (so the caller sees status: "running",
not the momentary "created").
binding replaces what was an untyped project: Option<String> label.
The label still exists on the wire (Session.project) but is now DERIVED
from the binding via ProjectBinding::label, so the two can never
disagree — see Session’s docs. ProjectBinding::None (projectless) is
a fully supported binding, not a missing one.
Test: registry_tests::create_publishes_started_and_status_events,
registry_tests::create_derives_project_label_from_binding.
(#8184) Mints a DELEGATING session — use
SessionRegistry::create_with_delegation to mint the solo
(no_delegate) shape. A wrapper rather than a fifth parameter because
every other call site here wants this same default.
Sourcepub fn create_with_delegation(
&self,
task: String,
agent: Option<String>,
binding: ProjectBinding,
no_delegate: bool,
) -> Session
pub fn create_with_delegation( &self, task: String, agent: Option<String>, binding: ProjectBinding, no_delegate: bool, ) -> Session
SessionRegistry::create with this session’s agent shape chosen
explicitly (#8184).
Why: session.create defaults to the SOLO agent (the interactive TUI’s
default, issue #8184) while task.run’s own mint path keeps the
pre-#8184 delegating default unless its no_delegate param says
otherwise. Both need the same mint, so the flag is a parameter here
rather than two divergent copies of the body.
What: no_delegate is persisted onto Session::no_delegate and is
immutable afterwards — there is no setter, mirroring binding’s own
once-at-creation convention.
Test: session::protocol::tests::create_defaults_to_the_solo_agent,
task::protocol::tests::task_run_minted_session_records_its_no_delegate.
Sourcepub fn list(&self) -> Vec<Session>
pub fn list(&self) -> Vec<Session>
session.list: snapshot every session currently in the registry.
Why: the read side of the registry for operators/CLI/TUI to enumerate
running sessions.
What: clones every Session snapshot; order is unspecified (backed
by a HashMap).
Test: registry_tests::list_returns_every_created_session.
Sourcepub fn status(&self, id: &str) -> Result<Session, RpcError>
pub fn status(&self, id: &str) -> Result<Session, RpcError>
session.status: snapshot one session by id.
Why: shared by create’s return value and the standalone
session.status method.
What: Ok(Session) if present, Err(RpcError::session_not_found)
otherwise.
Test: registry_tests::status_returns_not_found_for_unknown_id.
Sourcepub fn send(&self, id: &str, input: &str) -> Result<(), RpcError>
pub fn send(&self, id: &str, input: &str) -> Result<(), RpcError>
session.send: deliver input to a session and publish an observable
event proving the daemon received it.
Why: #2054/#2055 do not wire a real agent loop (that is task.*,
#2056); publishing Event::SessionInput is what makes session.send
observably reach a session.attached client NOW, and gives #2056 a
concrete event to build real echo/ack behaviour on top of.
What: errors with session_not_found if id is unknown; otherwise
records+publishes Event::SessionInput { session_id, input }.
Test: registry_tests::send_publishes_input_event,
registry_tests::send_unknown_session_errors.
Sourcepub fn cancel(&self, id: &str) -> Result<Session, RpcError>
pub fn cancel(&self, id: &str) -> Result<Session, RpcError>
session.cancel: send a cancellation signal and mark the session
terminal.
Why: vision spec §12 (11.6) Cancellation Semantics — cancellation is
a status transition + event, not a deletion. #2054/#2055 have no
in-flight agent loop to interrupt yet (that lands with #2056), so
this is the full implementation available today: it marks the
session Cancelled and publishes the terminal events; #2056 hooks
the actual agent-loop interrupt onto the same status transition.
What: idempotent — cancelling an already-terminal session is a no-op
that returns the current snapshot rather than erroring (repeated
session.cancel calls are safe). Errors with session_not_found if
id is unknown. On a live session: publishes
Event::SessionStatusChanged (status: "cancelled"), then the
dedicated Event::SessionCancelled signal, then the generic terminal
Event::SessionDone (status: "cancelled") — matching the vision
spec’s started/status-changed/input/cancelled/done taxonomy — and
returns the updated snapshot.
#4351: also records a refless Cancelled TaskResult, so cancelling is
not the one terminal state that answers session.status with no
result — see Self::set_cancelled_result.
Test: registry_tests::cancel_transitions_to_cancelled_and_publishes,
registry_tests::cancel_is_idempotent_on_terminal_session,
registry_tests::cancel_unknown_session_errors,
registry_tests::cancel_records_a_refless_cancelled_result.
Sourcepub fn finish(
&self,
id: &str,
status: SessionStatus,
) -> Result<Session, RpcError>
pub fn finish( &self, id: &str, status: SessionStatus, ) -> Result<Session, RpcError>
Mark a session terminal (finished, failed, or cancelled while
executing) and publish the terminal Event::SessionDone (#2056).
Why: the background executor (crate::task::executor) needs to set
the FINAL status once an agent loop returns, distinctly from the
user-initiated session.cancel JSON-RPC path (Self::cancel),
which ALSO emits a dedicated Event::SessionCancelled signal that
only makes sense for an explicit user cancel request — not a natural
finish or failure, and not a cancellation the EXECUTOR itself
observed (that path already went through request_cancel, which
does not transition status; the executor calls this afterward to
actually land the transition once it has unwound).
What: idempotent — a no-op (returns the current snapshot) if the
session is already terminal, since a race between request_cancel’s
caller and the executor noticing cancellation is possible but
harmless. Errors with session_not_found if id is unknown.
Otherwise transitions to status and publishes
Event::SessionDone { status }.
Test: registry_tests::finish_transitions_and_publishes_session_done,
registry_tests::finish_is_idempotent_on_terminal_session,
registry_tests::finish_unknown_session_errors.
Sourcepub fn attach(
&self,
id: &str,
connection_id: Uuid,
notify: NotifySender,
) -> Result<Vec<SessionEventEnvelope>, RpcError>
pub fn attach( &self, id: &str, connection_id: Uuid, notify: NotifySender, ) -> Result<Vec<SessionEventEnvelope>, RpcError>
session.attach: replay recent history and start forwarding this
session’s live events to notify.
Why: the streaming half of the session-attach protocol (vision spec
§4.4/Axiom 4). Works identically regardless of transport — the
difference between STDIO (long-lived notify, events interleaved on
stdout) and HTTP (throwaway notify; the real live path is the GET /sessions/{id}/events SSE route) lives entirely in
crate::jsonrpc::ConnectionContext’s docs and crate::serve’s
transports, not here.
What: errors with session_not_found if id is unknown. Otherwise
takes a snapshot of the ring buffer (oldest-first, each entry a full
SessionEventEnvelope with its seq intact) to return as the
replay, registers connection_id’s cancel sender (replacing — and
thus cancelling — any prior forwarder for the same
(session, connection) pair), and spawns a task that subscribes to
crate::events::subscribe(), filters by session_id, and forwards
each match into notify as a JSON-RPC notification whose params IS
the envelope ({"jsonrpc":"2.0","method":"session.event","params": {"session_id":...,"seq":...,"at":...,"kind":...,"event":{...}}})
until detach fires the cancel sender or notify.send fails (the
connection is gone). Because every envelope — replayed or live —
comes from the SAME per-session seq counter (record), a client
that concatenates the replay array with the live notifications it
receives afterward sees one gap-free, strictly increasing sequence.
Test: registry_tests::attach_returns_ring_buffer_replay,
registry_tests::attach_forwards_live_events_until_detach,
registry_tests::attach_replay_then_live_seq_is_contiguous,
registry_tests::attach_unknown_session_errors.
Sourcepub fn detach(&self, id: &str, connection_id: Uuid) -> Result<(), RpcError>
pub fn detach(&self, id: &str, connection_id: Uuid) -> Result<(), RpcError>
session.detach: stop forwarding this session’s live events to the
calling connection.
Why: the other half of the attach protocol — releases the forwarder
task started by attach for this (session, connection) pair.
What: errors with session_not_found if id is unknown. If the
connection has no live attachment (already detached, or never
attached), this is a no-op success rather than an error — detach is
idempotent. Otherwise fires the stored cancel sender, which stops the
forwarder task on its next select! poll.
Test: registry_tests::detach_stops_the_forwarder,
registry_tests::detach_without_prior_attach_is_a_noop,
registry_tests::detach_unknown_session_errors.
Sourcepub fn replay(&self, id: &str) -> Result<Vec<SessionEventEnvelope>, RpcError>
pub fn replay(&self, id: &str) -> Result<Vec<SessionEventEnvelope>, RpcError>
Snapshot the ring buffer for a session without attaching to it.
Why: the HTTP SSE route (crate::serve::http) needs the same replay
burst attach returns, but subscribes to the live bus itself (one
Stream per SSE connection) rather than going through a
NotifySender forwarder — so it calls this directly instead of
attach.
What: same replay semantics as attach (full envelopes, seq
intact), no side effects (no forwarder spawned, no attachment
recorded).
Test: registry_tests::replay_returns_ring_buffer_without_attaching.
Sourcepub fn begin_execution(&self, id: &str) -> Result<Arc<AtomicBool>, RpcError>
pub fn begin_execution(&self, id: &str) -> Result<Arc<AtomicBool>, RpcError>
Begin tracking a new background task execution for id (#2056; #2344
resumption semantics).
Why: task.run (and session.send on an idle session) must not start
a second overlapping run for the same session, and the returned flag
is how the executor’s AgentLoop(s) later observe cancellation.
(#2344/#3888/#8207) A Finished, TurnCapExceeded or Cancelled
session is NOT dead — see SessionStatus::is_resumable for which
statuses resume and why. Only Failed/DeadlineExceeded remain
genuinely terminal: those represent a broken run, and resuming one
still requires a fresh session.
What: errors with session_not_found if id is unknown,
invalid_argument if the session is Failed/
DeadlineExceeded, or already has an execution in flight — this
SINGLE in-flight-execution guard is also this ticket’s concurrency
guard for pm_transcript: two overlapping task.run calls on one
session can never both hold the transcript, because the second one is
rejected here before either reaches begin_pm_transcript. On success,
stores a fresh Arc<AtomicBool> cancel flag (initially false) with
handle: None — the caller attaches the real JoinHandle via
Self::attach_execution_handle immediately after spawning, since
the handle cannot exist before that — and returns the flag. If the
session was resumable (is_resumable), transitions it back to
Running and publishes Event::SessionStatusChanged — matching the
transition every other status change in this module publishes.
Test: registry_tests::begin_execution_rejects_second_overlapping_run,
registry_tests::begin_execution_rejects_terminal_session,
registry_tests::begin_execution_unknown_session_errors,
registry_tests::begin_execution_resumes_a_finished_session,
registry_tests::begin_execution_resumes_a_turn_cap_exceeded_session,
registry_tests::begin_execution_resumes_a_cancelled_session.
Sourcepub fn attach_execution_handle(&self, id: &str, handle: JoinHandle<()>)
pub fn attach_execution_handle(&self, id: &str, handle: JoinHandle<()>)
Attach the real JoinHandle to id’s tracked execution (#2056).
Why: the handle only exists once the caller has actually called
tokio::spawn, which must happen after begin_execution returns (the
spawned future needs the cancel flag begin_execution produces).
What: best-effort — a no-op if id or its execution is already gone
(e.g. the run finished astonishingly fast, or the session vanished).
Test: registry_tests::shutdown_executions_awaits_cancelled_tasks
(exercises this indirectly via a real spawn).
Sourcepub fn finish_execution(&self, id: &str)
pub fn finish_execution(&self, id: &str)
Clear the execution-in-flight marker for id (#2056).
Why: called by the executor once the background task has stopped
(finished, failed, or cancelled) so a later task.run/session.send
can start a new run against the same session.
What: best-effort — a no-op if id is already gone.
Test: registry_tests::begin_execution_rejects_second_overlapping_run
(calls this between the two begin_execution attempts).
Sourcepub fn is_executing(&self, id: &str) -> bool
pub fn is_executing(&self, id: &str) -> bool
Whether id currently has a background execution in flight (#2056).
Why: session::protocol::cancel uses this to choose between
cooperative cancellation (Self::request_cancel) and the original
#2054 immediate-transition Self::cancel.
What: false for both “unknown session” and “known but idle” — callers
that need to distinguish those already call another method first.
Test: registry_tests::request_cancel_*.
Sourcepub fn request_cancel(&self, id: &str) -> Result<bool, RpcError>
pub fn request_cancel(&self, id: &str) -> Result<bool, RpcError>
Request cooperative cancellation of id’s in-flight execution, if any
(#2056).
Why: session.cancel on a RUNNING session must signal the background
task rather than force an immediate status transition — the task
itself transitions to Cancelled once it actually observes the flag
and unwinds (see crate::task::executor).
What: Err(session_not_found) if id is unknown. Ok(true) if an
execution was in flight and its flag was set; Ok(false) if the
session exists but nothing is executing (the caller should fall back
to Self::cancel for the immediate-transition path).
Test: registry_tests::request_cancel_sets_flag_when_executing,
registry_tests::request_cancel_returns_false_when_idle.
Sourcepub fn set_run_outcome(
&self,
id: &str,
transcript: Vec<TurnRecord>,
usage: TokenUsage,
cost_usd: Option<f64>,
)
pub fn set_run_outcome( &self, id: &str, transcript: Vec<TurnRecord>, usage: TokenUsage, cost_usd: Option<f64>, )
Persist a finished execution’s transcript/usage/cost into the session (#2056; #2344 made CUMULATIVE across runs).
Why: populates the storage Self::get_transcript (#2058) reads back
over the wire. (#2344) A session’s turns/usage/cost now accumulate
across every task.run rather than the last run overwriting the
previous one’s — the whole point of a persistent session is that
session.get_transcript shows the FULL conversation, not just its
most recent slice.
What: best-effort — a no-op if id is already gone (e.g. the daemon
is shutting down mid-run). transcript is APPENDED onto the existing
turns (not replacing them); usage is added field-wise via
TokenUsage::add (the same accumulator run_task::aggregate_usage_per_role
uses internally); cost_usd sums the two Option<f64>s the same way
TokenUsage::add combines its own cost_usd field (Some+Some ->
sum, either Some alone passes through, None+None stays None).
Test: registry_tests::set_run_outcome_stores_transcript_and_usage,
registry_tests::set_run_outcome_accumulates_across_two_calls.
(Issue #3298) Also records+publishes Event::SessionActivityUpdate —
the natural “a turn just happened” hook DOC-48 §5.3’s event table asks
for, so a workstream observer can see which bound sessions are
recently active without polling. Published ONLY when id is
workstream-bound (Session.workstream_id.is_some()): the event
exists for workstream observers (§5.3 lists it in the WORKSTREAM
event set), an unbound session has no such observer, and — decisive
— the M1 cutline e2e contract (tests/m1_cutline_e2e.rs) freezes the
exact event-kind sequence a plain, workstream-less session emits;
firing this unconditionally inserted a new kind into that baseline
and broke both transports’ frozen sequences (CI failure on PR #3354).
A no-op alongside the rest of this method if id is already gone.
Test: registry_tests::set_run_outcome_publishes_activity_update_when_workstream_bound,
registry_tests::set_run_outcome_stays_silent_for_unbound_session;
the frozen unbound-session baseline itself in
m1_cutline_e2e::m1_cutline_full_scenario_over_stdio/_http.
Sourcepub fn begin_pm_transcript(
&self,
id: &str,
system: &str,
task: &str,
) -> Result<Transcript, RpcError>
pub fn begin_pm_transcript( &self, id: &str, system: &str, task: &str, ) -> Result<Transcript, RpcError>
Retrieve this session’s persistent PM conversation Transcript,
seeding it on the session’s FIRST task.run and appending task as a
new user turn onto the existing history on every SUBSEQUENT one
(#2344 — the infinite-sessions conversation-continuity entry point).
Why: task::executor::run_and_record must hand the PM’s AgentLoop
the SAME growing Transcript every run drives via
AgentLoop::run_with_transcript, rather than reseeding fresh each
time (the pre-#2344 behaviour). Taking ownership OUT of the entry
(rather than cloning) lets the caller drive the loop against it
directly with no extra copy; briefly leaving None in storage while a
run is active can never be observed by a second concurrent caller —
Self::begin_execution’s single-in-flight-run guard already rejects a
second task.run on the same session before it would ever reach this
method (see that method’s docs).
What: Err(session_not_found) if id is unknown. If pm_transcript
is None (the session has never run, or is between runs having been
taken and not yet restored — the call-order guarantee above means
the latter should never actually happen), seeds a fresh
Transcript::seed(system, task). If Some, takes the existing
transcript out of storage and appends task as a new user turn via
Transcript::push_user — system is IGNORED on this branch: the
original seed’s system message stays authoritative for the life of
the session (a refresh mechanism, if agent/mode config changes
between runs, is future work — not this ticket).
Test: registry_tests::begin_pm_transcript_seeds_on_first_call,
registry_tests::begin_pm_transcript_appends_on_second_call,
registry_tests::begin_pm_transcript_unknown_session_errors.
Sourcepub fn store_pm_transcript(&self, id: &str, transcript: Transcript)
pub fn store_pm_transcript(&self, id: &str, transcript: Transcript)
Persist the PM’s conversation Transcript back onto the session once
a run ends (#2344).
Why: pairs with Self::begin_pm_transcript — MUST be called
regardless of the run’s outcome (success, failure, cancellation, or
timeout) so the conversation up to the point of interruption survives
for the NEXT task.run to continue from, rather than the session
being left with no pm_transcript at all (which would silently
re-seed from scratch on the next run instead of erroring).
What: best-effort — a no-op if id is already gone (mirrors
Self::set_run_outcome’s same best-effort framing).
Test: registry_tests::begin_pm_transcript_appends_on_second_call
(exercises both halves of the round trip).
Sourcepub fn set_mode(&self, id: &str, mode: HarnessMode) -> Result<(), RpcError>
pub fn set_mode(&self, id: &str, mode: HarnessMode) -> Result<(), RpcError>
task.run: persist the resolved HarnessMode onto the session
(#2059).
Why: task::protocol::task_run resolves the mode (env var >
task.run param > .claude/settings.json > default) BEFORE spawning
the execution; storing it here — rather than waiting for
set_run_outcome at the end of the run — makes it queryable via
session.status/session.list (Session.mode) and
session.get_transcript (TranscriptRecord.mode, which reads the
SAME field) as soon as task.run returns, not only after the run
completes.
What: Err(session_not_found) if id is unknown; otherwise sets
entry.session.mode = Some(mode). No event is published — mode is
bookkeeping metadata, not a session-lifecycle transition in the
#2055 event taxonomy.
Test: registry_tests::set_mode_stores_on_session,
registry_tests::set_mode_unknown_session_errors.
Sourcepub async fn shutdown_executions(&self, grace: Duration)
pub async fn shutdown_executions(&self, grace: Duration)
Cooperatively cancel every in-flight execution and wait, bounded by
grace, for them to actually stop (#2056 — graceful daemon shutdown).
Why: without this, a tokio::spawn’d background execution would be
abruptly dropped — never given a chance to unwind — the instant the
process’s tokio runtime shuts down, violating the connection-safe
daemon-restart convention (issue #534) this extends from connections
to long-running tasks.
What: flips every tracked execution’s cancel flag, takes ownership of
each JoinHandle, then awaits all of them concurrently with an
overall grace timeout. A handle that doesn’t finish in time is left
to be dropped when the process exits (best-effort, not a hard
guarantee — matching the same best-effort framing as every other
shutdown step in this codebase).
Test: registry_tests::shutdown_executions_awaits_cancelled_tasks.
Trait Implementations§
Source§impl Default for SessionRegistry
impl Default for SessionRegistry
Source§impl PermissionEvents for SessionRegistry
(#7948) The registry is the permission gate’s event sink.
impl PermissionEvents for SessionRegistry
(#7948) The registry is the permission gate’s event sink.
Why: SessionRegistry::record is the sole assigner of an event’s seq;
implementing the trait here keeps crate::permissions free of a registry
dependency.
What: a session_not_found is logged at debug and dropped. It affects
only the event, never the decision: the gate still waits for an answer or
the timeout, and a timeout denies.
Test: registry_tests::record_permission_requested_publishes_event,
registry_tests::record_permission_resolved_publishes_event.
Source§fn prompter_attached(&self, session_id: &str) -> bool
fn prompter_attached(&self, session_id: &str) -> bool
Whether a prompter is watching THIS session and could answer its ask.
Why (#8100): the signal must be per session. A daemon-global reading —
crate::events::bus().receiver_count(), this method’s first cut — is
true for every session in the process as soon as one console attaches
to one of them, so the normal trusty-mpm shape (a watched PM session
dispatching headless task.run sub-agents) put every sub-agent back on
the 300 s stall. SessionRegistry::claim_prompter counts only the
paths bound to one session id that can BOTH see its
permission_requested event and answer with
session.permission.respond: session.attach, the session.events
stream, and the per-session HTTP SSE route. The workstream-aggregate
SSE route is an observer, not a prompter — it is bound to a workstream
whose membership is re-checked per event, so no session’s prompt is
its to display — and deliberately claims nothing.
What: prompter_count reads 0 for a session the registry cannot
find, which denies. That is the fail-safe arm: a prompt for a session
that does not exist is a prompt nobody can be shown.
Test: registry_tests::prompter_attached_while_a_session_attachment_lives,
registry_tests::prompter_claim_is_released_when_its_guard_drops,
registry_tests::prompter_attached_for_an_unknown_session_is_false,
registry_tests::prompter_count_survives_a_poisoned_registry_lock,
gate_tests::an_ask_on_an_unwatched_session_is_headless_while_a_sibling_is_watched.
Auto Trait Implementations§
impl !Freeze for SessionRegistry
impl RefUnwindSafe for SessionRegistry
impl Send for SessionRegistry
impl Sync for SessionRegistry
impl Unpin for SessionRegistry
impl UnsafeUnpin for SessionRegistry
impl UnwindSafe for SessionRegistry
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more