Skip to main content

aidaemon_tools/
semantics.rs

1//! The semantic half of a daemon tool: plain data that describes a call
2//! without executing it (capabilities, typed call semantics, access
3//! manifests, receipt metadata, execution facts) and the helpers that derive
4//! the conservative defaults.
5
6use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10use aidaemon_core::ChannelVisibility;
11
12/// The sender's role, shared across the SDK.
13pub use aidaemon_core::UserRole;
14
15/// Where an attachment originated — drives vision retention in archived turns.
16#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
17#[serde(rename_all = "snake_case")]
18pub enum AttachmentProvenance {
19    /// User sent via a channel (Telegram, Slack, Discord).
20    #[default]
21    Inbound,
22    /// Produced by a tool observation (browser screenshot, MCP image, etc.).
23    ToolObservation,
24    /// Produced as a durable artifact by a tool (PDF, document, archive, etc.).
25    ToolArtifact,
26}
27
28/// Metadata for a file saved from an inbound channel message or tool observation.
29#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
30pub struct MessageAttachment {
31    /// Stable opaque handle used by tools and policy. Legacy attachments omit
32    /// it and receive one when they next cross the canonical event boundary.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub resource_id: Option<String>,
35    pub local_path: String,
36    pub filename: String,
37    pub mime_type: String,
38    pub size_bytes: u64,
39    #[serde(default)]
40    pub provenance: AttachmentProvenance,
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub source_tool: Option<String>,
43    /// Content digest captured when the attachment was registered. Execution
44    /// re-checks this before sensitive use to detect stale/replaced files.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub sha256: Option<String>,
47    /// The owner drew marks over a picture to make this one: the unmarked
48    /// picture's local path. The model is told the marks are the owner's.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub marked_up_from: Option<String>,
51}
52
53/// Categorization of a tool for role-based scoping.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum ToolRole {
56    /// Terminal, web_search, web_fetch, browser, etc.
57    Action,
58    /// ManageGoalTasksTool, ReportBlockerTool — task lead tools.
59    Management,
60    /// SystemInfoTool, RememberFactTool — available to all roles.
61    Universal,
62}
63
64/// How a tool is offered to the model.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
66pub enum Offering {
67    /// Sent on every call: without it the agent cannot do its everyday
68    /// work (run commands, read and change files, reach the web, keep
69    /// memory, schedule, track its checklist, delegate).
70    Core,
71    /// Exists only in a role-scoped run (a task's, a mandate run's or a
72    /// coordinated child's own tools), where it is sent on every call.
73    Scoped,
74    /// Listed by name and one line in `load_tools`; its schema is sent once
75    /// loaded (by `load_tools` or by calling it).
76    #[default]
77    Deferred,
78}
79
80impl Offering {
81    /// Sent on every call where the tool is registered.
82    pub fn always_sent(self) -> bool {
83        matches!(self, Self::Core | Self::Scoped)
84    }
85}
86
87/// Typed facts about how the dispatcher and the engine treat a tool. A tool
88/// states them about itself; nothing keys on its name. Several can hold for
89/// one tool, so they are flags beside [`ToolRole`] (which scopes tools by
90/// agent role) rather than more roles.
91#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
92pub struct ToolDispatchFacts {
93    /// The kernel's approval rules judge this tool's calls in the canonical
94    /// form the dispatcher executes, and the dispatcher then runs each call
95    /// exactly as judged (the terminal).
96    pub runs_as_judged: bool,
97    /// The tool keeps the owner's answers to its cards in its own grant
98    /// stores, consulted by its own ladder (the terminal's command
99    /// prefixes), instead of the kernel's session grants.
100    pub keeps_own_grants: bool,
101    /// The call's `command` or `script` is a shell command line, which the
102    /// kernel's access manifest carries so the approval policy's
103    /// catastrophic-command check sees it (the terminal).
104    pub shell_command_line: bool,
105    /// Whether the tool's schema is sent on every model call
106    /// ([`Offering::Core`]) or listed by name until the run loads it
107    /// ([`Offering::Deferred`], the default).
108    pub offering: Offering,
109    /// A task lead keeps the tool through pruning: it is its delegation
110    /// surface (`spawn_agent`, `cli_agent`, `manage_goal_tasks`).
111    pub task_lead_delegation: bool,
112    /// How long a run may call the tool consecutively before the
113    /// same-tool guard treats it as a loop.
114    pub same_tool_streak: SameToolStreak,
115    /// The tool delivers a file to the user; the same file and caption go
116    /// out once per task.
117    pub delivers_files: bool,
118    /// The tool spawns child agents, which inherit the turn's authority as
119    /// it is when the call runs.
120    pub spawns_child_agents: bool,
121    /// The tool is the executor's requirement checklist: the status line
122    /// shows the checklist, and its items become ledger expectations.
123    pub requirement_checklist: bool,
124    /// The call runs inside a process the daemon cannot see into (an MCP
125    /// server), so its downstream effects escape per-action scoping and
126    /// accounting. A mandate never delegates such a tool.
127    pub opaque_execution: bool,
128    /// The tool manages its own timeout and backgrounding, so the generic
129    /// watchdog never wraps it (it would cancel the call early and could
130    /// orphan the process it started).
131    pub manages_own_timeout: bool,
132    /// The tool records the trusted roots its launch was judged with (the
133    /// terminal), so a background result keeps the trust it ran under.
134    pub records_launch_trust: bool,
135    /// Which goal facts the call receives.
136    pub goal_context: GoalContext,
137    /// Which addresses a call may name, judged by `web::NetworkGuard`.
138    pub network_reach: NetworkReach,
139    /// Which of a call's paths `ProtectedPathGuard` judges.
140    pub file_guard: FileGuard,
141    /// The dispatcher takes a file checkpoint before the call runs, so its
142    /// writes can be rolled back.
143    pub checkpoints_writes: bool,
144    /// The call receives the live model, provider and model chain (a tool
145    /// that runs its own model loop).
146    pub needs_live_model: bool,
147    /// The status line summarizes a finished call from its arguments, not
148    /// its result (memory and people edits, whose result text is terse).
149    pub status_from_arguments: bool,
150    /// What a run's activity recap counts a finished call as.
151    pub recap: RecapKind,
152    /// What kind of work every card shows a call as.
153    pub activity: ToolActivity,
154    /// The words a live status ping uses for the tool ("reading a file").
155    /// `None`: its name in words.
156    pub status_label: Option<&'static str>,
157    /// Which argument names the project directory a call works in, and how
158    /// the turn's known project directory fills it when it is empty.
159    pub project_dir_argument: ProjectDirArgument,
160    /// The paths a call touches open their project's instructions on first
161    /// access (reads, writes and command working directories; broad
162    /// searches do not).
163    pub opens_project_instructions: bool,
164    /// How the engine fits the call's result for the model.
165    pub result_fit: ResultFit,
166    /// Which conversations the tool may be offered in.
167    pub channel_reach: ChannelReach,
168    /// What a substantive result from the call can serve as evidence for.
169    pub evidence: EvidenceSource,
170    /// The domain the tool inspects or changes, when it states no
171    /// per-call semantics.
172    pub semantic_scope: Option<ToolSemanticScope>,
173    /// A result that says only that it worked (a write's confirmation):
174    /// the turn's recent-work context leaves it out.
175    pub low_signal_result: bool,
176}
177
178/// What a run's activity recap counts a finished call as (see
179/// [`ToolDispatchFacts::recap`]).
180#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
181pub enum RecapKind {
182    /// Counted only by what its summary says.
183    #[default]
184    Other,
185    /// A file was read.
186    FileRead,
187    /// A file was written or edited.
188    FileWrite,
189    /// A command ran.
190    Command,
191    /// A file was sent to the user.
192    FileSent,
193    /// The web or the files were searched.
194    Search,
195    /// An external source was read.
196    ExternalRead,
197}
198
199/// What kind of work a call is on every card (see
200/// [`ToolDispatchFacts::activity`]).
201#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
202pub enum ToolActivity {
203    /// A check, or a change when the call's admitted semantics mutate.
204    #[default]
205    ByEffect,
206    /// Always this kind.
207    Fixed(aidaemon_core::card::ActivityKind),
208    /// Memory: recalling when the call only reads, remembering when it
209    /// changes what is kept.
210    Memory,
211}
212
213impl ToolActivity {
214    /// The kind a call of this tool shows as, given whether its admitted
215    /// semantics mutate state.
216    pub fn kind(self, mutates: bool) -> aidaemon_core::card::ActivityKind {
217        use aidaemon_core::card::ActivityKind;
218        match self {
219            Self::Fixed(kind) => kind,
220            Self::Memory if mutates => ActivityKind::Remember,
221            Self::Memory => ActivityKind::Recall,
222            Self::ByEffect if mutates => ActivityKind::Change,
223            Self::ByEffect => ActivityKind::Check,
224        }
225    }
226}
227
228/// Which argument of a call names the directory it works in (see
229/// [`ToolDispatchFacts::project_dir_argument`]).
230#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
231pub enum ProjectDirArgument {
232    /// Any path-like argument names a project directory; none is filled.
233    #[default]
234    AnyPath,
235    /// The search root, `path`: filled with the known project directory.
236    SearchRoot,
237    /// The working directory, `working_dir`: filled with the known project
238    /// directory, or its nearest existing parent when it is not made yet.
239    WorkingDir,
240    /// A shell: only `working_dir` or `cwd` names the directory (paths in
241    /// the command are its data), filled as [`Self::WorkingDir`] and only
242    /// when the call carries a command or script.
243    ShellWorkingDir,
244}
245
246impl ProjectDirArgument {
247    /// The argument the known project directory fills, if any.
248    pub const fn injected_key(self) -> Option<&'static str> {
249        match self {
250            Self::AnyPath => None,
251            Self::SearchRoot => Some("path"),
252            Self::WorkingDir | Self::ShellWorkingDir => Some("working_dir"),
253        }
254    }
255}
256
257/// How the engine fits a call's result for the model (see
258/// [`ToolDispatchFacts::result_fit`]).
259#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
260pub struct ResultFit {
261    /// The result is the model's working data and stays inline and whole,
262    /// never spilled or compressed (the desktop's accessibility tree).
263    pub preserve_inline: bool,
264    /// A trusted result may carry the tool's internal control markers,
265    /// stripped before the model sees it.
266    pub strip_control_markers: bool,
267    /// A large result is a structured API body, compacted losslessly.
268    pub compact_json: bool,
269    /// A large error is process output, cut to its head and tail.
270    pub cap_large_errors: bool,
271    /// The model can page through a spilled result with this tool, so an
272    /// oversized result may be spilled to a file instead of compressed.
273    pub pages_spilled_results: bool,
274}
275
276/// Which conversations a tool may be offered in (see
277/// [`ToolDispatchFacts::channel_reach`]).
278#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
279pub enum ChannelReach {
280    /// Any conversation except a public external channel.
281    #[default]
282    Shared,
283    /// Every conversation, a public external channel included.
284    Public,
285    /// It drives the owner's machine: only direct messages and internal
286    /// sessions, never a shared or public channel.
287    DirectOnly,
288}
289
290impl ChannelReach {
291    /// Whether a tool of this reach may be offered in a conversation of
292    /// `visibility`. The one rule for which tools a channel may see.
293    pub fn offered_in(self, visibility: ChannelVisibility) -> bool {
294        match self {
295            Self::Public => true,
296            Self::Shared => visibility != ChannelVisibility::PublicExternal,
297            Self::DirectOnly => matches!(
298                visibility,
299                ChannelVisibility::Private | ChannelVisibility::Internal
300            ),
301        }
302    }
303}
304
305/// What a substantive result from a tool can serve as evidence for, by the
306/// kind of source it reads (see [`ToolDispatchFacts::evidence`]). The
307/// capabilities each source supports live with the evidence ontology.
308#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
309pub enum EvidenceSource {
310    /// No static evidence model: what the call supports is learnt from
311    /// its result's own semantics.
312    #[default]
313    None,
314    /// Goal and task forensics: a targeted trace, or a recent listing.
315    GoalTrace,
316    /// The owner's mandates, by action.
317    Mandates,
318    /// Goal tasks and automations: their state and record.
319    GoalRecords,
320    /// Past conversation.
321    ConversationHistory,
322    /// A remote page or API, read directly.
323    RemoteRead,
324    /// A connected node's readings.
325    NodeReading,
326    /// What a connected node did.
327    NodeAction,
328    /// A web search: advisory.
329    WebSearch,
330    /// A local file read.
331    FileRead,
332    /// A local file search.
333    FileSearch,
334    /// A local file edited in place: the edit read the file under its write
335    /// fence and its result shows what the file now holds, so a successful
336    /// one observes the file's current state as well as the write's outcome.
337    FileWrite,
338    /// A shell on this computer.
339    Shell,
340    /// This computer's state.
341    HostInfo,
342    /// The daemon's own diagnostics.
343    Diagnostics,
344}
345
346impl EvidenceSource {
347    /// Every source with an evidence model.
348    pub const MODELED: [Self; 14] = [
349        Self::GoalTrace,
350        Self::Mandates,
351        Self::GoalRecords,
352        Self::ConversationHistory,
353        Self::RemoteRead,
354        Self::NodeReading,
355        Self::NodeAction,
356        Self::WebSearch,
357        Self::FileRead,
358        Self::FileSearch,
359        Self::FileWrite,
360        Self::Shell,
361        Self::HostInfo,
362        Self::Diagnostics,
363    ];
364}
365
366/// Which of a tool's paths are judged against the secret and sensitive
367/// patterns. A shell is not: the owner is asked about its commands instead.
368#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
369pub enum FileGuard {
370    #[default]
371    None,
372    /// The paths it reads must not hold secrets.
373    Reads,
374    /// The paths it reads must not be sensitive (a superset of secrets, for
375    /// a tool that publishes what it reads).
376    SensitiveReads,
377    /// The paths it changes must not be sensitive.
378    Writes,
379}
380
381/// Which addresses a tool's egress may name. Cloud metadata endpoints are
382/// refused for every tool, whatever this says.
383#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
384pub enum NetworkReach {
385    /// Anything else, as a shell reaches the owner's own network.
386    #[default]
387    Any,
388    /// Public hosts and this computer.
389    PublicAndLoopback,
390    /// Public hosts only.
391    PublicOnly,
392}
393
394/// Which goal facts a call receives (see
395/// [`ToolDispatchFacts::goal_context`]).
396#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
397pub enum GoalContext {
398    /// None.
399    #[default]
400    None,
401    /// The goal the run works for.
402    Goal,
403    /// The goal, found through the executor's task when the run carries
404    /// only a task: the call's background notifications go to the goal's
405    /// own session, since a child agent's session is not routable.
406    BackgroundDelivery,
407    /// The goal and, in a mandate run, the run's mandate fence (goal run,
408    /// attempt, mandate and version).
409    MandateRun,
410}
411
412/// The consecutive-call allowance of a tool (see
413/// [`ToolDispatchFacts::same_tool_streak`]). Defined in the kernel so the
414/// same-tool guard can take it without a dependency on the tools crate.
415pub use aidaemon_core::SameToolStreak;
416
417/// Safety and execution metadata for policy-driven tool selection.
418#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
419pub struct ToolCapabilities {
420    pub read_only: bool,
421    pub external_side_effect: bool,
422    pub needs_approval: bool,
423    pub idempotent: bool,
424    pub high_impact_write: bool,
425}
426
427/// Effect classification for a specific tool call.
428#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
429pub enum ToolCallEffect {
430    #[default]
431    Unknown,
432    Administrative,
433    Observation,
434    Mutation,
435    ObservationAndMutation,
436}
437
438/// Typed mutation effects for one tool call.
439///
440/// `ToolCallEffect` deliberately remains the compact observation/mutation
441/// summary used by older persisted events. This set carries the detail needed
442/// by policy and completion accounting so an incidental build-cache write does
443/// not satisfy a requested source edit, and a local write does not satisfy a
444/// requested remote deployment.
445#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
446#[serde(transparent)]
447pub struct ToolMutationEffects(u32);
448
449impl ToolMutationEffects {
450    pub const PROTOCOL_NAMES: [&str; 13] = [
451        "local_source_write",
452        "local_workspace_write",
453        "local_derived_write",
454        "repository_write",
455        "remote_mutation",
456        "remote_deploy",
457        "external_delivery",
458        "process_state",
459        "configuration",
460        "destructive",
461        "unspecified",
462        "scheduled_work",
463        "memory_write",
464    ];
465    pub const NONE: Self = Self(0);
466    /// A write to user-authored files through a path-aware editing tool.
467    pub const LOCAL_SOURCE_WRITE: Self = Self(1 << 0);
468    /// A local write whose target is not typed precisely (shell redirect,
469    /// copy, generated file, and similar workspace activity).
470    pub const LOCAL_WORKSPACE_WRITE: Self = Self(1 << 1);
471    /// Compiler caches, dependency directories, and other reproducible output.
472    pub const LOCAL_DERIVED_WRITE: Self = Self(1 << 2);
473    /// Git refs, index state, commits, and related repository metadata.
474    pub const REPOSITORY_WRITE: Self = Self(1 << 3);
475    /// A remote state change that is not specifically a deployment.
476    pub const REMOTE_MUTATION: Self = Self(1 << 4);
477    /// Publishing a new application/site deployment or version.
478    pub const REMOTE_DEPLOY: Self = Self(1 << 5);
479    /// Sending, posting, uploading, or otherwise delivering content.
480    pub const EXTERNAL_DELIVERY: Self = Self(1 << 6);
481    /// Starting, stopping, restarting, or killing a process/service.
482    pub const PROCESS_STATE: Self = Self(1 << 7);
483    /// Mutating configuration, permissions, packages, or runtime setup.
484    pub const CONFIGURATION: Self = Self(1 << 8);
485    /// Deletion or another intentionally destructive local/remote operation.
486    pub const DESTRUCTIVE: Self = Self(1 << 9);
487    /// A command can mutate, but static inspection cannot state how. This is
488    /// intentionally not allowed to satisfy a more specific required outcome.
489    pub const UNSPECIFIED: Self = Self(1 << 10);
490    /// Creating or changing the daemon's own goals, schedules and reminders.
491    /// Nothing leaves the machine; the work it sets up is judged when it runs.
492    pub const SCHEDULED_WORK: Self = Self(1 << 11);
493    /// Saving to the daemon's own long-term memory. Nothing leaves the
494    /// machine and no workspace file changes.
495    pub const MEMORY_WRITE: Self = Self(1 << 12);
496
497    /// Stable bit representation retained for durable telemetry and audits.
498    /// Human-readable names are emitted alongside it; consumers must never
499    /// interpret a raw bitset as a count.
500    pub const fn bits(self) -> u32 {
501        self.0
502    }
503
504    /// Rehydrate a durable effect set without interpreting the bits as a
505    /// count. Unknown future bits remain visible to `telemetry_value` and do
506    /// not silently become a known effect.
507    pub const fn from_bits(bits: u32) -> Self {
508        Self(bits)
509    }
510
511    /// Return the protocol names represented by this effect set. These names
512    /// describe typed adapter effects, not natural-language task wording.
513    pub fn protocol_names(self) -> Vec<&'static str> {
514        [
515            (Self::LOCAL_SOURCE_WRITE, "local_source_write"),
516            (Self::LOCAL_WORKSPACE_WRITE, "local_workspace_write"),
517            (Self::LOCAL_DERIVED_WRITE, "local_derived_write"),
518            (Self::REPOSITORY_WRITE, "repository_write"),
519            (Self::REMOTE_MUTATION, "remote_mutation"),
520            (Self::REMOTE_DEPLOY, "remote_deploy"),
521            (Self::EXTERNAL_DELIVERY, "external_delivery"),
522            (Self::PROCESS_STATE, "process_state"),
523            (Self::CONFIGURATION, "configuration"),
524            (Self::DESTRUCTIVE, "destructive"),
525            (Self::UNSPECIFIED, "unspecified"),
526            (Self::SCHEDULED_WORK, "scheduled_work"),
527            (Self::MEMORY_WRITE, "memory_write"),
528        ]
529        .into_iter()
530        .filter_map(|(effect, name)| self.intersects(effect).then_some(name))
531        .collect()
532    }
533
534    /// Machine-readable telemetry projection that keeps unknown future bits
535    /// visible instead of silently dropping them.
536    pub fn telemetry_value(self) -> serde_json::Value {
537        let known_bits = Self::MEMORY_WRITE.bits()
538            | Self::SCHEDULED_WORK.bits()
539            | Self::UNSPECIFIED.bits()
540            | ((1 << 10) - 1);
541        serde_json::json!({
542            "bits": self.bits(),
543            "names": self.protocol_names(),
544            "unknown_bits": self.bits() & !known_bits,
545        })
546    }
547
548    pub const fn union(self, other: Self) -> Self {
549        Self(self.0 | other.0)
550    }
551
552    /// Keep only effects present in both sets.  This is used when an adapter
553    /// projects a task's typed obligation onto the subset it can actually
554    /// report; it never interprets the bitset as a count.
555    pub const fn intersect(self, other: Self) -> Self {
556        Self(self.0 & other.0)
557    }
558
559    /// Parse a protocol enum value. These names are structured tool metadata,
560    /// not natural-language routing keywords.
561    pub fn from_protocol_name(name: &str) -> Option<Self> {
562        match name {
563            "local_source_write" => Some(Self::LOCAL_SOURCE_WRITE),
564            "local_workspace_write" => Some(Self::LOCAL_WORKSPACE_WRITE),
565            "local_derived_write" => Some(Self::LOCAL_DERIVED_WRITE),
566            "repository_write" => Some(Self::REPOSITORY_WRITE),
567            "remote_mutation" => Some(Self::REMOTE_MUTATION),
568            "remote_deploy" => Some(Self::REMOTE_DEPLOY),
569            "external_delivery" => Some(Self::EXTERNAL_DELIVERY),
570            "process_state" => Some(Self::PROCESS_STATE),
571            "configuration" => Some(Self::CONFIGURATION),
572            "destructive" => Some(Self::DESTRUCTIVE),
573            "unspecified" => Some(Self::UNSPECIFIED),
574            "scheduled_work" => Some(Self::SCHEDULED_WORK),
575            "memory_write" => Some(Self::MEMORY_WRITE),
576            _ => None,
577        }
578    }
579
580    pub const fn is_empty(&self) -> bool {
581        self.0 == 0
582    }
583
584    pub const fn contains(self, other: Self) -> bool {
585        (self.0 & other.0) == other.0
586    }
587
588    pub const fn intersects(self, other: Self) -> bool {
589        (self.0 & other.0) != 0
590    }
591
592    pub const fn has_specific_effects(self) -> bool {
593        (self.0 & !Self::UNSPECIFIED.0) != 0
594    }
595
596    /// Whether observed effects fulfill every typed requirement.
597    ///
598    /// Known effects are checked strictly: cache output, repository metadata,
599    /// and directory scaffolding cannot masquerade as authored source. Opaque
600    /// execution surfaces report `UNSPECIFIED`, but unknown evidence is never
601    /// allowed to prove a more specific effect. A caller that requires a source
602    /// edit, deployment, or delivery must observe that exact typed effect.
603    pub const fn satisfies(self, required: Self) -> bool {
604        if required.is_empty() {
605            return true;
606        }
607        let generic_required = required.intersects(Self::UNSPECIFIED);
608        let generic_satisfied = !generic_required || !self.is_empty();
609        let specific_required = Self(required.0 & !Self::UNSPECIFIED.0);
610        // A precisely typed source write is also a workspace and a derived
611        // write. Workspace and derived writes satisfy each other: the plan's
612        // label is a hint, and the model cannot tell which one a tool
613        // records (live 2026-11-18: a generated image, recorded as a
614        // workspace write, never closed an item planned as a derived write,
615        // and the closeout held a delivered reply for five model calls).
616        // A source edit is still proven only by a source write.
617        let widened = if self.intersects(Self::LOCAL_SOURCE_WRITE)
618            || self.intersects(Self::LOCAL_DERIVED_WRITE)
619            || self.intersects(Self::LOCAL_WORKSPACE_WRITE)
620        {
621            Self(self.0 | Self::LOCAL_WORKSPACE_WRITE.0 | Self::LOCAL_DERIVED_WRITE.0)
622        } else {
623            self
624        };
625        // A schedule is what a model means by `configuration` or
626        // `process_state` when it plans one: the goal tools have nothing else
627        // to report, so those plans must be able to close.
628        let widened = if widened.intersects(Self::SCHEDULED_WORK) {
629            Self(widened.0 | Self::CONFIGURATION.0 | Self::PROCESS_STATE.0)
630        } else {
631            widened
632        };
633        // A saved memory is what a model means by a derived write when it
634        // plans one. Added after the workspace widening: it is not a file.
635        let widened = if widened.intersects(Self::MEMORY_WRITE) {
636            Self(widened.0 | Self::LOCAL_DERIVED_WRITE.0)
637        } else {
638            widened
639        };
640        generic_satisfied && widened.contains(specific_required)
641    }
642}
643
644impl ToolCallEffect {
645    pub fn observes_state(self) -> bool {
646        matches!(self, Self::Observation | Self::ObservationAndMutation)
647    }
648
649    pub fn mutates_state(self) -> bool {
650        matches!(self, Self::Mutation | Self::ObservationAndMutation)
651    }
652}
653
654/// How a tool call can contribute verification evidence.
655#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
656pub enum ToolVerificationMode {
657    #[default]
658    None,
659    ResultContent,
660}
661
662/// Typed target hint emitted by a tool call.
663#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
664pub enum ToolTargetHintKind {
665    Url,
666    Path,
667    ProjectScope,
668    /// Stable opaque identity from the session resource registry. Unlike a
669    /// filename or prose reference this is exact, session-scoped, and safe to
670    /// compare without natural-language interpretation.
671    ResourceId,
672}
673
674#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
675pub struct ToolTargetHint {
676    pub kind: ToolTargetHintKind,
677    pub value: String,
678}
679
680impl ToolTargetHint {
681    pub fn new(kind: ToolTargetHintKind, value: impl Into<String>) -> Option<Self> {
682        let value = value.into().trim().to_string();
683        if value.is_empty() {
684            None
685        } else {
686            Some(Self { kind, value })
687        }
688    }
689}
690
691/// High-level domain a tool can inspect or mutate.
692#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
693#[serde(rename_all = "snake_case")]
694pub enum ToolSemanticScope {
695    GoalState,
696    UserMemory,
697    ConversationHistory,
698    ExternalRemote,
699    LocalWorkspace,
700    HostLocal,
701}
702
703impl ToolSemanticScope {
704    pub const fn as_str(self) -> &'static str {
705        match self {
706            Self::GoalState => "goal_state",
707            Self::UserMemory => "user_memory",
708            Self::ConversationHistory => "conversation_history",
709            Self::ExternalRemote => "external_remote",
710            Self::LocalWorkspace => "local_workspace",
711            Self::HostLocal => "host_local",
712        }
713    }
714}
715
716/// The kind of claim an observation can support. These are evidence roles,
717/// not request-language keywords or tool names.
718#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
719#[serde(rename_all = "snake_case")]
720pub enum EvidencePurpose {
721    CurrentState,
722    HistoricalRecord,
723    Content,
724    Outcome,
725    Attribution,
726    CausalExplanation,
727}
728
729impl EvidencePurpose {
730    pub const fn as_str(self) -> &'static str {
731        match self {
732            Self::CurrentState => "current_state",
733            Self::HistoricalRecord => "historical_record",
734            Self::Content => "content",
735            Self::Outcome => "outcome",
736            Self::Attribution => "attribution",
737            Self::CausalExplanation => "causal_explanation",
738        }
739    }
740}
741
742/// Strength of the source behind an observation.
743#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
744#[serde(rename_all = "snake_case")]
745pub enum EvidenceAuthority {
746    /// A compressed memory, model-derived summary, or other discovery lead.
747    Advisory,
748    /// A direct observation of the resource being discussed.
749    Direct,
750    /// The daemon's authoritative ledger for the historical fact in question.
751    Canonical,
752}
753
754impl EvidenceAuthority {
755    const fn rank(self) -> u8 {
756        match self {
757            Self::Advisory => 0,
758            Self::Direct => 1,
759            Self::Canonical => 2,
760        }
761    }
762
763    pub const fn satisfies(self, required: Self) -> bool {
764        self.rank() >= required.rank()
765    }
766
767    pub const fn as_str(self) -> &'static str {
768        match self {
769            Self::Advisory => "advisory",
770            Self::Direct => "direct",
771            Self::Canonical => "canonical",
772        }
773    }
774}
775
776/// Time coverage of the subject records an observation surface can return.
777/// Receipt timestamps independently prove when the observation itself ran; a
778/// current query may therefore support historical subject data when the tool
779/// exposes both current and historical records.
780#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
781#[serde(rename_all = "snake_case")]
782pub enum EvidenceTemporalScope {
783    Current,
784    Historical,
785    Both,
786}
787
788impl EvidenceTemporalScope {
789    pub const fn satisfies(self, required: Self) -> bool {
790        matches!(required, Self::Both) && matches!(self, Self::Both)
791            || matches!(required, Self::Current) && matches!(self, Self::Current | Self::Both)
792            || matches!(required, Self::Historical) && matches!(self, Self::Historical | Self::Both)
793    }
794
795    pub const fn as_str(self) -> &'static str {
796        match self {
797            Self::Current => "current",
798            Self::Historical => "historical",
799            Self::Both => "both",
800        }
801    }
802}
803
804/// Claim-support metadata for one successful tool result. Unlike
805/// [`ToolCapabilities`], this describes what information the result can prove,
806/// not whether executing the tool is safe.
807#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
808pub struct ToolEvidenceCapability {
809    pub scope: ToolSemanticScope,
810    #[serde(default, skip_serializing_if = "Vec::is_empty")]
811    pub purposes: Vec<EvidencePurpose>,
812    pub authority: EvidenceAuthority,
813    pub temporal_scope: EvidenceTemporalScope,
814}
815
816impl ToolEvidenceCapability {
817    pub fn new(
818        scope: ToolSemanticScope,
819        purposes: &[EvidencePurpose],
820        authority: EvidenceAuthority,
821        temporal_scope: EvidenceTemporalScope,
822    ) -> Self {
823        Self {
824            scope,
825            purposes: purposes.to_vec(),
826            authority,
827            temporal_scope,
828        }
829    }
830}
831
832/// Fine-grained semantic capability advertised by a tool.
833#[allow(dead_code)]
834#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
835#[serde(rename_all = "snake_case")]
836pub enum ToolSemanticFacet {
837    /// Legacy coarse goal-state capability. New exact observations should use
838    /// the narrow facet that was actually returned.
839    GoalState,
840    Schedule,
841    RunState,
842    Recovery,
843    Control,
844    Measurement,
845    Authorization,
846    Ownership,
847}
848
849impl ToolSemanticFacet {
850    pub const PROTOCOL_NAMES: [&'static str; 8] = [
851        Self::GoalState.as_str(),
852        Self::Schedule.as_str(),
853        Self::RunState.as_str(),
854        Self::Recovery.as_str(),
855        Self::Control.as_str(),
856        Self::Measurement.as_str(),
857        Self::Authorization.as_str(),
858        Self::Ownership.as_str(),
859    ];
860
861    pub const fn as_str(self) -> &'static str {
862        match self {
863            Self::GoalState => "goal_state",
864            Self::Schedule => "schedule",
865            Self::RunState => "run_state",
866            Self::Recovery => "recovery",
867            Self::Control => "control",
868            Self::Measurement => "measurement",
869            Self::Authorization => "authorization",
870            Self::Ownership => "ownership",
871        }
872    }
873}
874
875/// Whether an adapter returned the whole requested collection. A truncated or
876/// otherwise partial list may prove facts about the subjects it contains, but
877/// it can never prove that another subject is absent.
878#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
879#[serde(rename_all = "snake_case")]
880pub enum ToolCollectionCompleteness {
881    #[default]
882    Unknown,
883    Partial,
884    Complete,
885}
886
887impl ToolCollectionCompleteness {
888    pub const fn satisfies(self, required: Self) -> bool {
889        matches!(required, Self::Unknown)
890            || matches!(required, Self::Partial) && matches!(self, Self::Partial | Self::Complete)
891            || matches!(required, Self::Complete) && matches!(self, Self::Complete)
892    }
893}
894
895/// One exact subject/facet tuple observed in a successful tool result. This is
896/// result evidence, not a capability prediction: adapters populate it only
897/// after domain I/O has returned.
898#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
899pub struct ToolObservationEvidence {
900    pub subject: ToolTargetHint,
901    #[serde(default, skip_serializing_if = "Vec::is_empty")]
902    pub facets: Vec<ToolSemanticFacet>,
903    /// Collections from which this row was selected. Membership is lineage;
904    /// absence still requires a separate complete collection observation.
905    #[serde(default, skip_serializing_if = "Vec::is_empty")]
906    pub source_collections: Vec<ToolTargetHint>,
907}
908
909impl ToolObservationEvidence {
910    pub fn new(subject: ToolTargetHint, facets: &[ToolSemanticFacet]) -> Self {
911        Self {
912            subject,
913            facets: facets.to_vec(),
914            source_collections: Vec::new(),
915        }
916    }
917
918    pub fn with_source_collection(mut self, collection: ToolTargetHint) -> Self {
919        if !self.source_collections.contains(&collection) {
920            self.source_collections.push(collection);
921        }
922        self
923    }
924}
925
926/// Exact coverage of one collection returned by an adapter. `members` contains
927/// stable identities, never display labels. Only `Complete` coverage can prove
928/// non-membership; counts remain audit facts and are not interpreted as proof
929/// on their own.
930#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
931pub struct ToolCollectionObservation {
932    pub collection: ToolTargetHint,
933    #[serde(default, skip_serializing_if = "Vec::is_empty")]
934    pub facets: Vec<ToolSemanticFacet>,
935    #[serde(default)]
936    pub completeness: ToolCollectionCompleteness,
937    #[serde(default)]
938    pub returned_count: usize,
939    #[serde(default, skip_serializing_if = "Option::is_none")]
940    pub total_count: Option<usize>,
941    #[serde(default, skip_serializing_if = "Vec::is_empty")]
942    pub members: Vec<ToolTargetHint>,
943}
944
945impl ToolCollectionObservation {
946    pub fn complete(
947        collection: ToolTargetHint,
948        facets: &[ToolSemanticFacet],
949        members: Vec<ToolTargetHint>,
950    ) -> Self {
951        let returned_count = members.len();
952        Self {
953            collection,
954            facets: facets.to_vec(),
955            completeness: ToolCollectionCompleteness::Complete,
956            returned_count,
957            total_count: Some(returned_count),
958            members,
959        }
960    }
961}
962
963/// A receipt subject an adapter reports verbatim, published ahead of any call
964/// so the executor's checklist can bind to identities that receipts will
965/// actually carry. A checklist target outside every advertised subject and
966/// member namespace can never be credited, so the checklist tool refuses to
967/// compile it into an exact obligation.
968#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
969pub struct StableObservationSubject {
970    /// Exact `ResourceId` the adapter reports for a fixed collection or
971    /// singleton subject, when that identity is known before the call.
972    #[serde(default, skip_serializing_if = "Option::is_none")]
973    pub resource_id: Option<String>,
974    /// Facets a receipt for this subject or its members can carry.
975    #[serde(default, skip_serializing_if = "Vec::is_empty")]
976    pub facets: Vec<ToolSemanticFacet>,
977    /// `ResourceId` prefixes of exact member identities the adapter or the
978    /// runtime mints (for example `auth_profile:`). A value under a prefix is
979    /// exact and is credited only by a receipt naming it.
980    #[serde(default, skip_serializing_if = "Vec::is_empty")]
981    pub member_namespaces: Vec<String>,
982    /// Short model-facing meaning of the subject.
983    pub summary: String,
984}
985
986impl StableObservationSubject {
987    pub fn collection(
988        resource_id: impl Into<String>,
989        facets: &[ToolSemanticFacet],
990        member_namespace: impl Into<String>,
991        summary: impl Into<String>,
992    ) -> Self {
993        Self {
994            resource_id: Some(resource_id.into()),
995            facets: facets.to_vec(),
996            member_namespaces: vec![member_namespace.into()],
997            summary: summary.into(),
998        }
999    }
1000
1001    pub fn namespace(prefix: impl Into<String>, summary: impl Into<String>) -> Self {
1002        Self {
1003            resource_id: None,
1004            facets: Vec::new(),
1005            member_namespaces: vec![prefix.into()],
1006            summary: summary.into(),
1007        }
1008    }
1009
1010    /// Whether `value` is this subject itself or an exact member under one of
1011    /// its namespaces. A bare prefix with nothing after it is not a member.
1012    pub fn binds(&self, value: &str) -> bool {
1013        self.resource_id.as_deref() == Some(value)
1014            || self
1015                .member_namespaces
1016                .iter()
1017                .any(|prefix| value.len() > prefix.len() && value.starts_with(prefix.as_str()))
1018    }
1019}
1020
1021/// Canonical adapter operation used by deterministic operation-scoped policy.
1022/// Unknown/new HTTP verbs deliberately remain untyped and therefore cannot
1023/// match a delegated mandate scope.
1024#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1025#[serde(rename_all = "UPPERCASE")]
1026pub enum ToolCallOperation {
1027    Get,
1028    Head,
1029    Options,
1030    Post,
1031    Put,
1032    Patch,
1033    Delete,
1034}
1035
1036impl ToolCallOperation {
1037    pub const fn from_http_method(method: &str) -> Option<Self> {
1038        match method.as_bytes() {
1039            b"GET" => Some(Self::Get),
1040            b"HEAD" => Some(Self::Head),
1041            b"OPTIONS" => Some(Self::Options),
1042            b"POST" => Some(Self::Post),
1043            b"PUT" => Some(Self::Put),
1044            b"PATCH" => Some(Self::Patch),
1045            b"DELETE" => Some(Self::Delete),
1046            _ => None,
1047        }
1048    }
1049}
1050
1051/// Structured completion semantics for a specific tool call.
1052#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1053pub struct ToolCallSemantics {
1054    #[serde(default)]
1055    pub effect: ToolCallEffect,
1056    #[serde(default)]
1057    pub verification_mode: ToolVerificationMode,
1058    /// Fine-grained mutation effects. Older persisted rows omit this field and
1059    /// continue to deserialize through the default empty set.
1060    #[serde(default, skip_serializing_if = "ToolMutationEffects::is_empty")]
1061    pub mutation_effects: ToolMutationEffects,
1062    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1063    pub target_hints: Vec<ToolTargetHint>,
1064    /// Adapter-defined canonical operation for policy matching. This is an
1065    /// exact, typed identifier (for example `GET` or `POST`), not a natural-
1066    /// language action inferred by the policy layer.
1067    #[serde(default, skip_serializing_if = "Option::is_none")]
1068    pub operation: Option<ToolCallOperation>,
1069    /// Typed claim-support affordances for this exact call/result. These are
1070    /// persisted in the durable receipt so recovery and completion do not have
1071    /// to reconstruct evidence from prose.
1072    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1073    pub evidence: Vec<ToolEvidenceCapability>,
1074}
1075
1076/// Prepared filesystem access requested by one exact tool call.
1077///
1078/// Execution location, readable context, and mutation authority are different
1079/// roles. Keeping them separate prevents a read-only working directory from
1080/// becoming an implied write grant and gives adapters one canonical contract
1081/// to enforce and persist.
1082#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1083pub struct ToolCallAccessManifest {
1084    #[serde(default, skip_serializing_if = "Option::is_none")]
1085    pub execution_cwd: Option<String>,
1086    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1087    pub read_targets: Vec<ToolTargetHint>,
1088    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1089    pub write_targets: Vec<ToolTargetHint>,
1090    /// Immutable capabilities owned by the adapter itself (for example the
1091    /// system executable roots a confined terminal needs to start a process).
1092    /// These are deliberately separate from task data grants: callers may use
1093    /// them for runtime loading, but they do not authorize arbitrary user
1094    /// paths or writes and are never inferred from command prose.
1095    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1096    pub adapter_read_targets: Vec<ToolTargetHint>,
1097}
1098
1099impl ToolCallSemantics {
1100    /// These semantics plus a change static inspection cannot type: still
1101    /// the observation they were, now also a mutation (`UNSPECIFIED`, which
1102    /// proves only the checklist items the call carries out).
1103    pub fn with_untyped_change(&self) -> Self {
1104        let mut changed = self.clone();
1105        changed.mutation_effects = changed
1106            .mutation_effects
1107            .union(ToolMutationEffects::UNSPECIFIED);
1108        changed.effect = if changed.observes_state() {
1109            ToolCallEffect::ObservationAndMutation
1110        } else {
1111            ToolCallEffect::Mutation
1112        };
1113        changed
1114    }
1115
1116    pub fn administrative() -> Self {
1117        Self {
1118            effect: ToolCallEffect::Administrative,
1119            ..Self::default()
1120        }
1121    }
1122
1123    pub fn observation() -> Self {
1124        Self {
1125            effect: ToolCallEffect::Observation,
1126            ..Self::default()
1127        }
1128    }
1129
1130    /// Apply a dispatcher-owned hard observation boundary while retaining
1131    /// target and evidence metadata from the original call. Use only when the
1132    /// adapter itself enforces that boundary before I/O.
1133    pub fn constrained_to_observation(mut self) -> Self {
1134        self.effect = ToolCallEffect::Observation;
1135        self.mutation_effects = ToolMutationEffects::NONE;
1136        self
1137    }
1138
1139    pub fn mutation() -> Self {
1140        Self {
1141            effect: ToolCallEffect::Mutation,
1142            mutation_effects: ToolMutationEffects::UNSPECIFIED,
1143            ..Self::default()
1144        }
1145    }
1146
1147    pub fn observation_and_mutation() -> Self {
1148        Self {
1149            effect: ToolCallEffect::ObservationAndMutation,
1150            mutation_effects: ToolMutationEffects::UNSPECIFIED,
1151            ..Self::default()
1152        }
1153    }
1154
1155    pub fn mutation_with(mutation_effects: ToolMutationEffects) -> Self {
1156        Self {
1157            effect: ToolCallEffect::Mutation,
1158            mutation_effects: if mutation_effects.is_empty() {
1159                ToolMutationEffects::UNSPECIFIED
1160            } else {
1161                mutation_effects
1162            },
1163            ..Self::default()
1164        }
1165    }
1166
1167    pub fn observation_and_mutation_with(mutation_effects: ToolMutationEffects) -> Self {
1168        Self {
1169            effect: ToolCallEffect::ObservationAndMutation,
1170            mutation_effects: if mutation_effects.is_empty() {
1171                ToolMutationEffects::UNSPECIFIED
1172            } else {
1173                mutation_effects
1174            },
1175            ..Self::default()
1176        }
1177    }
1178
1179    pub fn with_verification_mode(mut self, verification_mode: ToolVerificationMode) -> Self {
1180        self.verification_mode = verification_mode;
1181        self
1182    }
1183
1184    pub fn with_target_hint(mut self, kind: ToolTargetHintKind, value: impl Into<String>) -> Self {
1185        if let Some(target) = ToolTargetHint::new(kind, value) {
1186            self.target_hints.push(target);
1187        }
1188        self
1189    }
1190
1191    pub fn with_operation(mut self, operation: ToolCallOperation) -> Self {
1192        self.operation = Some(operation);
1193        self
1194    }
1195
1196    pub fn with_evidence(mut self, evidence: Vec<ToolEvidenceCapability>) -> Self {
1197        self.evidence = evidence;
1198        self
1199    }
1200
1201    pub fn observes_state(&self) -> bool {
1202        self.effect.observes_state()
1203    }
1204
1205    pub fn mutates_state(&self) -> bool {
1206        self.effect.mutates_state() || !self.mutation_effects.is_empty()
1207    }
1208
1209    pub fn can_verify_with_result_content(&self) -> bool {
1210        self.verification_mode == ToolVerificationMode::ResultContent
1211    }
1212
1213    pub fn is_empty(&self) -> bool {
1214        self.effect == ToolCallEffect::Unknown
1215            && self.verification_mode == ToolVerificationMode::None
1216            && self.mutation_effects.is_empty()
1217            && self.target_hints.is_empty()
1218            && self.operation.is_none()
1219            && self.evidence.is_empty()
1220    }
1221
1222    pub fn merge_missing_from(&mut self, fallback: Self) {
1223        if self.effect == ToolCallEffect::Unknown {
1224            self.effect = fallback.effect;
1225        }
1226        if self.verification_mode == ToolVerificationMode::None {
1227            self.verification_mode = fallback.verification_mode;
1228        }
1229        // An explicit observational effect is authoritative. Filling its empty
1230        // mutation bitset from a conservative pre-dispatch fallback would turn
1231        // a tool-enforced read-only execution back into a mutation receipt.
1232        if self.mutation_effects.is_empty()
1233            && (self.effect == ToolCallEffect::Unknown || self.effect.mutates_state())
1234        {
1235            self.mutation_effects = fallback.mutation_effects;
1236        }
1237        if self.target_hints.is_empty() {
1238            self.target_hints = fallback.target_hints;
1239        }
1240        if self.operation.is_none() {
1241            self.operation = fallback.operation;
1242        }
1243        if self.evidence.is_empty() {
1244            self.evidence = fallback.evidence;
1245        }
1246    }
1247}
1248
1249#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1250#[serde(rename_all = "snake_case")]
1251pub enum ReadFileSelectionMetadata {
1252    Full,
1253    BoundedRange { start_line: usize, end_line: usize },
1254    OpenEndedRange { start_line: usize },
1255    Tail { requested_lines: usize },
1256}
1257
1258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1259pub struct ReadFileResultMetadata {
1260    pub display_path: String,
1261    pub canonical_path: String,
1262    pub selection: ReadFileSelectionMetadata,
1263    pub returned_start_line: Option<usize>,
1264    pub returned_end_line: Option<usize>,
1265    pub total_lines: usize,
1266    pub file_size: u64,
1267    #[serde(skip_serializing_if = "Option::is_none")]
1268    pub modified: Option<String>,
1269    pub selected_lines: Vec<String>,
1270    /// True when the read returned fewer lines than requested because the
1271    /// per-call output cap was hit. The rendered output then carries an
1272    /// explicit continuation hint.
1273    #[serde(default)]
1274    pub truncated: bool,
1275}
1276
1277/// Structured record of tool-output truncation. Populated at the tool
1278/// boundary — the instructional notice text is rendered into the
1279/// model-visible message by the loop (single site), never embedded in the
1280/// tool's returned content, so text-scanning consumers (error-line
1281/// extraction, classifiers, summaries) always see clean output.
1282#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1283pub struct TruncationInfo {
1284    pub shown_chars: usize,
1285    pub total_chars: usize,
1286    /// Tool-specific remediation sentence (see `utils::truncation_notice_with_hint`).
1287    #[serde(default, skip_serializing_if = "Option::is_none")]
1288    pub remediation_hint: Option<String>,
1289}
1290
1291/// Whether a particular retained view contains the authoritative tool result.
1292#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1293#[serde(rename_all = "snake_case")]
1294pub enum ToolResultCompleteness {
1295    Complete,
1296    Truncated,
1297    #[default]
1298    Unavailable,
1299}
1300
1301impl ToolResultCompleteness {
1302    pub const fn as_str(self) -> &'static str {
1303        match self {
1304            Self::Complete => "complete",
1305            Self::Truncated => "truncated",
1306            Self::Unavailable => "unavailable",
1307        }
1308    }
1309}
1310
1311/// Origin of the bytes represented by a durable observation receipt.
1312#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1313#[serde(rename_all = "snake_case")]
1314pub enum ToolResultContentSource {
1315    ToolOutput,
1316    DurableReplay,
1317    SpillPreview,
1318    PersistentSummary,
1319    #[default]
1320    Unavailable,
1321}
1322
1323impl ToolResultContentSource {
1324    pub const fn as_str(self) -> &'static str {
1325        match self {
1326            Self::ToolOutput => "tool_output",
1327            Self::DurableReplay => "durable_replay",
1328            Self::SpillPreview => "spill_preview",
1329            Self::PersistentSummary => "persistent_summary",
1330            Self::Unavailable => "unavailable",
1331        }
1332    }
1333}
1334
1335/// Content provenance shared by live completion and durable continuation.
1336/// The digest is computed over the authoritative pre-compression result; the
1337/// view-specific fields state exactly what the model and event log retained.
1338#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1339pub struct ToolResultProvenance {
1340    #[serde(default, skip_serializing_if = "Option::is_none")]
1341    pub result_id: Option<String>,
1342    #[serde(default, skip_serializing_if = "Option::is_none")]
1343    pub sha256: Option<String>,
1344    #[serde(default)]
1345    pub source: ToolResultContentSource,
1346    #[serde(default)]
1347    pub model_view_completeness: ToolResultCompleteness,
1348    #[serde(default)]
1349    pub durable_view_completeness: ToolResultCompleteness,
1350    #[serde(default)]
1351    pub authoritative_chars: usize,
1352    #[serde(default)]
1353    pub model_visible_chars: usize,
1354    #[serde(default)]
1355    pub durable_chars: usize,
1356    #[serde(default, skip_serializing_if = "Option::is_none")]
1357    pub requested_range: Option<ReadFileSelectionMetadata>,
1358    #[serde(default, skip_serializing_if = "Option::is_none")]
1359    pub returned_start_line: Option<usize>,
1360    #[serde(default, skip_serializing_if = "Option::is_none")]
1361    pub returned_end_line: Option<usize>,
1362}
1363
1364/// Deterministic credential/target readiness checked immediately before an
1365/// autonomous adapter is allowed to perform I/O. The accompanying durable
1366/// receipt carries the mandate grant, which binds this record to the stable
1367/// mandate identity and policy version without exposing credentials.
1368#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1369#[serde(rename_all = "snake_case")]
1370pub enum AuthorizationPreflightStatus {
1371    Ready,
1372    Blocked,
1373    Unverifiable,
1374}
1375
1376#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1377pub struct AuthorizationPreflightRecord {
1378    pub schema_version: u16,
1379    pub status: AuthorizationPreflightStatus,
1380    pub intended_operation: String,
1381    pub target_digest: String,
1382    #[serde(default, skip_serializing_if = "Option::is_none")]
1383    pub auth_profile: Option<String>,
1384    #[serde(default, skip_serializing_if = "Option::is_none")]
1385    pub account_id: Option<String>,
1386    /// Provider-declared OAuth scopes known at the readiness boundary. Static
1387    /// non-OAuth profiles legitimately leave this empty.
1388    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1389    pub authorized_scopes: Vec<String>,
1390    #[serde(default, skip_serializing_if = "Option::is_none")]
1391    pub credential_generation: Option<String>,
1392    #[serde(default, skip_serializing_if = "Option::is_none")]
1393    pub refresh_result: Option<String>,
1394    #[serde(default, skip_serializing_if = "Option::is_none")]
1395    pub reason_code: Option<String>,
1396    pub checked_at: String,
1397}
1398
1399impl AuthorizationPreflightRecord {
1400    pub const SCHEMA_VERSION: u16 = 1;
1401
1402    pub const fn permits_io(&self) -> bool {
1403        matches!(self.status, AuthorizationPreflightStatus::Ready)
1404    }
1405}
1406
1407impl ToolResultProvenance {
1408    pub fn from_authoritative_result(
1409        result: &str,
1410        metadata: &ToolCallMetadata,
1411        source: ToolResultContentSource,
1412    ) -> Self {
1413        use sha2::{Digest, Sha256};
1414
1415        let sha256 = hex::encode(Sha256::digest(result.as_bytes()));
1416        let chars = result.chars().count();
1417        let tool_truncated = metadata.truncation.is_some()
1418            || metadata
1419                .read_file
1420                .as_ref()
1421                .is_some_and(|read| read.truncated);
1422        let completeness = if tool_truncated {
1423            ToolResultCompleteness::Truncated
1424        } else {
1425            ToolResultCompleteness::Complete
1426        };
1427        let read = metadata.read_file.as_ref();
1428        Self {
1429            result_id: Some(format!("sha256:{sha256}")),
1430            sha256: Some(sha256),
1431            source,
1432            model_view_completeness: completeness,
1433            durable_view_completeness: completeness,
1434            authoritative_chars: chars,
1435            model_visible_chars: chars,
1436            durable_chars: chars,
1437            requested_range: read.map(|read| read.selection.clone()),
1438            returned_start_line: read.and_then(|read| read.returned_start_line),
1439            returned_end_line: read.and_then(|read| read.returned_end_line),
1440        }
1441    }
1442
1443    pub fn mark_model_view_truncated(&mut self, visible_result: &str) {
1444        self.model_visible_chars = visible_result.chars().count();
1445        self.model_view_completeness = ToolResultCompleteness::Truncated;
1446    }
1447
1448    pub fn record_durable_view(&mut self, durable_result: &str, is_summary: bool) {
1449        self.durable_chars = durable_result.chars().count();
1450        if is_summary {
1451            self.durable_view_completeness = ToolResultCompleteness::Truncated;
1452            self.source = ToolResultContentSource::PersistentSummary;
1453        } else {
1454            self.durable_view_completeness = self.model_view_completeness;
1455        }
1456    }
1457}
1458
1459/// Structured outcome of a tool invocation. This separates transport/execution
1460/// success from the domain result: a test runner can execute correctly while
1461/// reporting failing tests, and a lookup can complete with no matches.
1462#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1463#[serde(rename_all = "snake_case")]
1464pub enum ToolOutcomeStatus {
1465    Succeeded,
1466    CompletedWithNegativeResult,
1467    FailedRetryable,
1468    FailedPermanent,
1469    Blocked,
1470    Backgrounded,
1471}
1472
1473/// Where an invocation reached in the common execution pipeline.
1474///
1475/// This is deliberately orthogonal to [`ToolOutcomeStatus`]. A deterministic
1476/// argument rejection can be a completed validation observation, but it did
1477/// not dispatch the requested domain operation and therefore cannot inherit
1478/// that operation's effects, targets, or evidence capabilities.
1479#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1480#[serde(rename_all = "snake_case")]
1481pub enum ToolInvocationStage {
1482    /// Legacy receipt or adapter that did not report a stage.
1483    #[default]
1484    Unknown,
1485    /// The common policy/retry boundary refused dispatch.
1486    RejectedBeforeDispatch,
1487    /// The adapter rejected its typed argument contract before domain I/O.
1488    RejectedBeforeIo,
1489    /// The adapter was invoked for the prepared operation.
1490    Dispatched,
1491    /// The result was reconstructed from a durable prior receipt.
1492    Replayed,
1493}
1494
1495impl ToolInvocationStage {
1496    pub const fn as_str(self) -> &'static str {
1497        match self {
1498            Self::Unknown => "unknown",
1499            Self::RejectedBeforeDispatch => "rejected_before_dispatch",
1500            Self::RejectedBeforeIo => "rejected_before_io",
1501            Self::Dispatched => "dispatched",
1502            Self::Replayed => "replayed",
1503        }
1504    }
1505
1506    pub const fn reached_dispatch(self) -> bool {
1507        matches!(self, Self::Dispatched | Self::Replayed)
1508    }
1509
1510    /// True only for a newly executed adapter call. A durable replay carries
1511    /// evidence forward but does not consume another operation attempt.
1512    pub const fn performed_io(self) -> bool {
1513        matches!(self, Self::Dispatched)
1514    }
1515}
1516
1517/// Shape of the machine receipt produced by a tool invocation.
1518///
1519/// Completion predicates are compiled against this protocol type instead of
1520/// assuming every tool is a subprocess. In particular, an absent exit code on
1521/// a management/API receipt means "not applicable", not "the invocation did
1522/// not happen".
1523#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1524#[serde(rename_all = "snake_case")]
1525pub enum ToolReceiptKind {
1526    #[default]
1527    Generic,
1528    Process,
1529    Http,
1530}
1531
1532/// Strength of the boundary that enforced a tool's declared filesystem
1533/// manifest. This reports enforcement, not merely manifest presence.
1534#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1535#[serde(rename_all = "snake_case")]
1536pub enum ToolAccessEnforcement {
1537    /// Legacy or uninstrumented adapter; no enforcement claim is made.
1538    #[default]
1539    Unknown,
1540    /// The operation has no filesystem access contract.
1541    NotApplicable,
1542    /// A delegated sandbox adapter accepted the manifest.
1543    AdapterEnforced,
1544    /// The daemon controller rejected the proposal before adapter dispatch
1545    /// because it exceeded the compiled task capability.
1546    ControllerEnforced,
1547    /// The daemon installed a kernel-enforced policy from the exact manifest.
1548    KernelEnforced,
1549}
1550
1551/// Typed diagnostic emitted when a proposal is rejected by the controller or
1552/// an adapter is denied by its installed filesystem policy. This is audit
1553/// telemetry only; the manifest remains the authority and this record never
1554/// widens it.
1555#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1556pub struct ToolAccessDenial {
1557    pub reason_code: String,
1558    pub enforcement: ToolAccessEnforcement,
1559    #[serde(default, skip_serializing_if = "Option::is_none")]
1560    pub exit_code: Option<i32>,
1561    /// Evidence the refused operation WOULD have produced. A rejection
1562    /// receipt carries no observed evidence (nothing ran), but the run ledger
1563    /// needs to know which observation obligation the refusal was attempting
1564    /// to satisfy; that binding is proposal data, typed on the denial.
1565    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1566    pub proposed_evidence: Vec<ToolEvidenceCapability>,
1567}
1568
1569impl ToolOutcomeStatus {
1570    /// Normalize the execution backend's process status convention. Unix
1571    /// commands that exit normally produce a nonnegative code; the backend
1572    /// uses a negative sentinel when no normal exit status exists (for
1573    /// example, a sandbox kill). Such termination is not a completed negative
1574    /// predicate observation.
1575    pub const fn from_process_exit_code(code: i32) -> Self {
1576        if code == 0 {
1577            Self::Succeeded
1578        } else if code > 0 {
1579            Self::CompletedWithNegativeResult
1580        } else {
1581            Self::FailedPermanent
1582        }
1583    }
1584
1585    pub const fn as_str(self) -> &'static str {
1586        match self {
1587            Self::Succeeded => "succeeded",
1588            Self::CompletedWithNegativeResult => "completed_with_negative_result",
1589            Self::FailedRetryable => "failed_retryable",
1590            Self::FailedPermanent => "failed_permanent",
1591            Self::Blocked => "blocked",
1592            Self::Backgrounded => "backgrounded",
1593        }
1594    }
1595
1596    pub fn satisfies_requested_condition(self) -> bool {
1597        matches!(self, Self::Succeeded)
1598    }
1599
1600    pub fn is_failure(self) -> bool {
1601        matches!(
1602            self,
1603            Self::FailedRetryable | Self::FailedPermanent | Self::Blocked
1604        )
1605    }
1606}
1607
1608/// How the response layer should treat a successful tool result.
1609///
1610/// This is control-plane metadata, not a canned user response. Tools use it to
1611/// distinguish an owner-facing operational outcome from an explicitly
1612/// requested diagnostic view while leaving the wording to the model.
1613#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1614#[serde(rename_all = "snake_case")]
1615pub enum ToolResultPresentation {
1616    NaturalSummary,
1617    DiagnosticDetail,
1618}
1619
1620/// Structured execution metadata returned by tools.
1621///
1622/// This is intentionally minimal and backward-compatible: tools can continue
1623/// returning plain text while selectively populating structured fields.
1624#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1625pub struct ToolCallMetadata {
1626    /// Protocol family for fields whose applicability differs by adapter.
1627    /// The dispatcher stamps this from the registered tool before completion
1628    /// evaluation; tools do not need to repeat the declaration per result.
1629    #[serde(default)]
1630    pub receipt_kind: ToolReceiptKind,
1631    /// Effective filesystem access contract enforced for this invocation.
1632    /// This is an audit receipt, not a reusable authority grant.
1633    #[serde(default, skip_serializing_if = "Option::is_none")]
1634    pub access_manifest: Option<ToolCallAccessManifest>,
1635    /// Whether the declared access manifest was installed at an execution
1636    /// boundary. A populated manifest with `Unknown` is audit data only.
1637    #[serde(default)]
1638    pub access_enforcement: ToolAccessEnforcement,
1639    /// Kernel/adapter denial details when a dispatched process was prevented
1640    /// from opening a path. The declared manifest is retained separately.
1641    #[serde(default, skip_serializing_if = "Option::is_none")]
1642    pub access_denial: Option<ToolAccessDenial>,
1643    /// Authoritative domain outcome when the tool can provide one. Older tools
1644    /// may omit it; the loop then derives a conservative status from structured
1645    /// exit/HTTP/transport metadata before falling back to legacy text parsing.
1646    #[serde(default, skip_serializing_if = "Option::is_none")]
1647    pub outcome_status: Option<ToolOutcomeStatus>,
1648    /// Authoritative pipeline stage for this result. Completion and effect
1649    /// projection must never infer dispatch from intended call semantics.
1650    #[serde(default)]
1651    pub invocation_stage: ToolInvocationStage,
1652    /// The adapter deterministically rejected the invocation contract before
1653    /// performing domain I/O. This is an authoritative negative outcome, not
1654    /// evidence that the requested read/write itself occurred.
1655    #[serde(default)]
1656    pub contract_rejected: bool,
1657    /// Actual adapter that produced the result when dispatch was routed from
1658    /// the requested tool through another implementation.
1659    #[serde(default, skip_serializing_if = "Option::is_none")]
1660    pub effective_tool_name: Option<String>,
1661    /// True when the dispatcher reconstructed this outcome from a prior
1662    /// durable receipt instead of invoking the side effect again.
1663    #[serde(default)]
1664    pub receipt_replayed: bool,
1665    /// Process exit code when applicable (e.g. terminal/run_command style tools).
1666    #[serde(skip_serializing_if = "Option::is_none")]
1667    pub exit_code: Option<i32>,
1668    /// True when tool execution exceeded a timeout threshold.
1669    #[serde(default)]
1670    pub timed_out: bool,
1671    /// True when execution moved to background tracking.
1672    #[serde(default)]
1673    pub background_started: bool,
1674    /// True when the process is detached and intentionally long-lived.
1675    #[serde(default)]
1676    pub detached: bool,
1677    /// True when the tool guarantees automatic completion delivery for a
1678    /// backgrounded operation in the current run.
1679    #[serde(default)]
1680    pub completion_notifications_enabled: bool,
1681    /// Transport/runtime failure outside normal tool semantics.
1682    #[serde(skip_serializing_if = "Option::is_none")]
1683    pub transport_error: Option<String>,
1684    /// HTTP status code for API tools (http_request, web_fetch).
1685    /// Populated at the tool boundary — not scraped from result text.
1686    #[serde(default, skip_serializing_if = "Option::is_none")]
1687    pub http_status: Option<u16>,
1688    /// Output truncation performed at the tool boundary. Rendered into the
1689    /// model-visible text by the loop after ledger/classifier consumption.
1690    #[serde(default, skip_serializing_if = "Option::is_none")]
1691    pub truncation: Option<TruncationInfo>,
1692    /// Strong provenance for the result body. Populated centrally by the tool
1693    /// dispatcher so individual adapters cannot silently omit it.
1694    #[serde(default, skip_serializing_if = "Option::is_none")]
1695    pub result_provenance: Option<ToolResultProvenance>,
1696    /// Exact pre-I/O authorization readiness for autonomous authenticated
1697    /// adapters. It is persisted with the receipt and never contains secrets.
1698    #[serde(default, skip_serializing_if = "Option::is_none")]
1699    pub authorization_preflight: Option<AuthorizationPreflightRecord>,
1700    /// The call handed the rest of the turn's work to a background job whose
1701    /// result reaches the session later (a launch moved to background
1702    /// tracking, a background sub-agent). Set with the call's finish by
1703    /// [`ToolCallOutcome::handed_to_background`]; unlike
1704    /// `background_started` it says nothing about the receipt's status.
1705    #[serde(default)]
1706    pub background_handoff: bool,
1707    /// The call observed the end of a background job a launch left running
1708    /// (a check that returned its finished result, or a cancel). The run
1709    /// pairs it with `background_started` launches to know whether work it
1710    /// handed off is still running when the model wants to stop.
1711    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1712    pub background_settled: bool,
1713    /// The names, as the owner reads them, of the runs this call left
1714    /// running in the background (a helper, a command, a CLI agent; every
1715    /// child of a batch call, in order): the turn's launch line names its
1716    /// runs from these, never from the call's text (live 2026-11-14: a
1717    /// batch of two named only its first child).
1718    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1719    pub background_run_labels: Vec<String>,
1720    /// The declared checklist items (their indices) this call took on: a
1721    /// launch hands them to the job it starts (`checklist_items`). Typed
1722    /// attribution of work to declared items, never read from text.
1723    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1724    pub checklist_items: Vec<usize>,
1725    /// How many runs this call left working (a batch launch starts one per
1726    /// child). Each run takes on its own work: a launch of two helpers that
1727    /// names no items is two attempts, never one.
1728    #[serde(default, skip_serializing_if = "is_zero")]
1729    pub launched_runs: usize,
1730    /// The call changed something its semantics could not type (a write
1731    /// inside `docker exec` or `ssh`, judged from the command's structure):
1732    /// the runtime may attribute it to the one checklist item in progress.
1733    /// Never itself a typed change.
1734    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1735    pub changes_untyped: bool,
1736    /// Completion semantics for this specific tool call.
1737    #[serde(default, skip_serializing_if = "ToolCallSemantics::is_empty")]
1738    pub semantics: ToolCallSemantics,
1739    /// Exact subject/facet observations made by this dispatched result. These
1740    /// are intentionally separate from `ToolCallSemantics`: proposed call
1741    /// semantics must never become proof merely because dispatch was planned.
1742    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1743    pub observations: Vec<ToolObservationEvidence>,
1744    /// Collection membership and coverage observed by this dispatched result.
1745    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1746    pub collection_observations: Vec<ToolCollectionObservation>,
1747    /// Complete typed result for successful text-file reads.
1748    #[serde(skip_serializing_if = "Option::is_none")]
1749    pub read_file: Option<ReadFileResultMetadata>,
1750    /// Image (or other) files produced by the tool for agent vision context.
1751    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1752    pub attachments: Vec<MessageAttachment>,
1753    /// The runtime's own pre-dispatch preparation failed (for example
1754    /// materializing a declared write root), attributed to the exact argument
1755    /// declaration that caused it. Set only when no domain I/O ran.
1756    #[serde(default, skip_serializing_if = "Option::is_none")]
1757    pub runtime_preparation_failure: Option<Box<RuntimePreparationFailure>>,
1758    /// Preserve exact, untrusted bytes while still wrapping them as untrusted
1759    /// tool data. Intended for canonical-history evidence whose wording must
1760    /// not be rewritten by prompt-injection sanitization.
1761    #[serde(default)]
1762    pub untrusted_verbatim: bool,
1763    /// Keep bounded tool output inline and never write it to a temporary spill
1764    /// file or run lossy generic compression.
1765    #[serde(default)]
1766    pub preserve_inline: bool,
1767    /// Durable audit representation. The full output remains available to the
1768    /// current model turn, but only this stub is written to canonical events.
1769    #[serde(default, skip_serializing_if = "Option::is_none")]
1770    pub persistent_output: Option<String>,
1771    /// Do not copy result content into executor task-activity telemetry.
1772    #[serde(default)]
1773    pub suppress_activity_result: bool,
1774    /// Presentation policy for this result. `NaturalSummary` asks the response
1775    /// layer to communicate the user-level outcome without exposing control-
1776    /// plane bookkeeping. `DiagnosticDetail` is selected only when the caller
1777    /// explicitly requested those details.
1778    #[serde(default, skip_serializing_if = "Option::is_none")]
1779    pub presentation: Option<ToolResultPresentation>,
1780    /// Exact control-plane identifiers observed by the tool. They remain
1781    /// available to the agent/runtime but are omitted from a natural summary
1782    /// unless the owner supplied the same identifier or requested diagnostics.
1783    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1784    pub internal_identifiers: Vec<String>,
1785    /// Who authored this exact output, when the tool knows better than its
1786    /// declared `Tool::output_trust` (a delegated run reports whether it read
1787    /// untrusted content). The dispatcher stamps this over the declaration.
1788    #[serde(default, skip_serializing_if = "Option::is_none")]
1789    pub output_trust: Option<aidaemon_core::SourceTrust>,
1790}
1791
1792#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1793pub struct ToolCallOutcome {
1794    pub output: String,
1795    #[serde(default)]
1796    pub metadata: ToolCallMetadata,
1797    /// The tool ends the run on this call, from its own typed outcome (never
1798    /// from argument or output text). The dispatcher hands it to the kernel
1799    /// as [`aidaemon_core::ToolOutput::finish`]; a finish without a reply
1800    /// ships the call's own output.
1801    #[serde(default, skip_serializing_if = "Option::is_none")]
1802    pub finish: Option<aidaemon_core::Finish>,
1803}
1804
1805/// A failure of the runtime's own pre-dispatch preparation, attributed to the
1806/// exact argument declaration that caused it. The dispatcher uses this to
1807/// decide whether the declaration was its own projection (repairable without
1808/// involving the model) or the model's (surfaced as a typed rejection).
1809#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1810pub struct RuntimePreparationFailure {
1811    /// Argument field the declaration came from (for example `write_roots`).
1812    pub field: String,
1813    /// The exact declared value.
1814    pub value: String,
1815    /// The underlying runtime error.
1816    pub error: String,
1817}
1818
1819impl ToolCallOutcome {
1820    pub fn from_output(output: String) -> Self {
1821        Self {
1822            output,
1823            metadata: ToolCallMetadata::default(),
1824            finish: None,
1825        }
1826    }
1827
1828    pub fn contract_rejection(output: impl Into<String>) -> Self {
1829        Self {
1830            output: output.into(),
1831            metadata: ToolCallMetadata {
1832                // A rejected invocation observed no domain condition. Keep it
1833                // distinct from an executed observation whose answer is
1834                // legitimately negative (for example process exit 1).
1835                outcome_status: Some(ToolOutcomeStatus::Blocked),
1836                invocation_stage: ToolInvocationStage::RejectedBeforeIo,
1837                contract_rejected: true,
1838                // No requested domain effect ran, but the adapter directly
1839                // observed and completed its deterministic validation. This
1840                // lets an explicit receipt predicate prove the negative result
1841                // without relabeling it as a successful mutation.
1842                semantics: ToolCallSemantics::observation()
1843                    .with_verification_mode(ToolVerificationMode::ResultContent),
1844                ..ToolCallMetadata::default()
1845            },
1846            finish: None,
1847        }
1848    }
1849
1850    pub fn blocked(output: impl Into<String>) -> Self {
1851        Self {
1852            output: output.into(),
1853            metadata: ToolCallMetadata {
1854                outcome_status: Some(ToolOutcomeStatus::Blocked),
1855                ..ToolCallMetadata::default()
1856            },
1857            finish: None,
1858        }
1859    }
1860
1861    /// The runtime could not prepare the invocation (no domain I/O ran). The
1862    /// failure names the exact declaration so the dispatcher can repair its
1863    /// own projections instead of reporting its mistake to the model.
1864    pub fn runtime_preparation_failure(
1865        field: impl Into<String>,
1866        value: impl Into<String>,
1867        error: impl std::fmt::Display,
1868    ) -> Self {
1869        let field = field.into();
1870        let value = value.into();
1871        let error = error.to_string();
1872        Self {
1873            output: format!(
1874                "Error: the runtime could not prepare `{field}` entry `{value}` before running the command: {error}"
1875            ),
1876            metadata: ToolCallMetadata {
1877                outcome_status: Some(ToolOutcomeStatus::Blocked),
1878                invocation_stage: ToolInvocationStage::RejectedBeforeIo,
1879                semantics: ToolCallSemantics::observation()
1880                    .with_verification_mode(ToolVerificationMode::ResultContent),
1881                runtime_preparation_failure: Some(Box::new(RuntimePreparationFailure {
1882                    field,
1883                    value,
1884                    error,
1885                })),
1886                ..ToolCallMetadata::default()
1887            },
1888            finish: None,
1889        }
1890    }
1891
1892    pub fn completed_negative_result(output: impl Into<String>) -> Self {
1893        Self {
1894            output: output.into(),
1895            metadata: ToolCallMetadata {
1896                outcome_status: Some(ToolOutcomeStatus::CompletedWithNegativeResult),
1897                ..ToolCallMetadata::default()
1898            },
1899            finish: None,
1900        }
1901    }
1902
1903    /// End the run on this call (see [`Self::finish`]).
1904    pub fn with_finish(mut self, finish: aidaemon_core::Finish) -> Self {
1905        self.finish = Some(finish);
1906        self
1907    }
1908
1909    /// The call moved the rest of the work to the background: the run ends
1910    /// on it as partial work, and the dispatcher writes the handoff reply
1911    /// (it knows the user's request and whether completion notifications
1912    /// reach them).
1913    pub fn handed_to_background(mut self) -> Self {
1914        self.metadata.background_handoff = true;
1915        self.finish = Some(aidaemon_core::Finish::new(
1916            aidaemon_core::FinishOutcome::Partial,
1917            None,
1918        ));
1919        self
1920    }
1921
1922    pub fn with_semantics(mut self, semantics: ToolCallSemantics) -> Self {
1923        self.metadata.semantics = semantics;
1924        self
1925    }
1926
1927    pub fn with_observation_evidence(
1928        mut self,
1929        observations: Vec<ToolObservationEvidence>,
1930        collection_observations: Vec<ToolCollectionObservation>,
1931    ) -> Self {
1932        self.metadata.observations = observations;
1933        self.metadata.collection_observations = collection_observations;
1934        self
1935    }
1936}
1937
1938impl Default for ToolCapabilities {
1939    fn default() -> Self {
1940        Self {
1941            read_only: false,
1942            external_side_effect: false,
1943            needs_approval: true,
1944            idempotent: false,
1945            high_impact_write: false,
1946        }
1947    }
1948}
1949
1950fn string_to_target_hint(key: &str, value: &str) -> Option<ToolTargetHint> {
1951    let trimmed = value.trim();
1952    if trimmed.is_empty() {
1953        return None;
1954    }
1955
1956    let lower_key = key.to_ascii_lowercase();
1957    if lower_key == "resource_id" {
1958        return ToolTargetHint::new(ToolTargetHintKind::ResourceId, trimmed);
1959    }
1960
1961    if matches!(
1962        lower_key.as_str(),
1963        "url" | "verify_url" | "callback_url" | "target_url" | "auth_url"
1964    ) || trimmed.starts_with("http://")
1965        || trimmed.starts_with("https://")
1966    {
1967        return ToolTargetHint::new(ToolTargetHintKind::Url, trimmed);
1968    }
1969
1970    if matches!(
1971        lower_key.as_str(),
1972        "path"
1973            | "file_path"
1974            | "working_dir"
1975            | "cwd"
1976            | "directory"
1977            | "dir"
1978            | "repo_path"
1979            | "repo_dir"
1980            | "resource_path"
1981    ) {
1982        return ToolTargetHint::new(ToolTargetHintKind::Path, trimmed);
1983    }
1984
1985    if matches!(
1986        lower_key.as_str(),
1987        "project_path" | "project_dir" | "scope" | "project_scope"
1988    ) {
1989        return ToolTargetHint::new(ToolTargetHintKind::ProjectScope, trimmed);
1990    }
1991
1992    None
1993}
1994
1995fn push_unique_target_hint(hints: &mut Vec<ToolTargetHint>, candidate: Option<ToolTargetHint>) {
1996    let Some(candidate) = candidate else {
1997        return;
1998    };
1999    if !hints.iter().any(|existing| existing == &candidate) {
2000        hints.push(candidate);
2001    }
2002}
2003
2004fn collect_common_target_hints(arguments: &str) -> Vec<ToolTargetHint> {
2005    let parsed = match serde_json::from_str::<Value>(arguments) {
2006        Ok(Value::Object(map)) => map,
2007        _ => return Vec::new(),
2008    };
2009
2010    let mut hints = Vec::new();
2011    for (key, value) in &parsed {
2012        match value {
2013            Value::String(s) => push_unique_target_hint(&mut hints, string_to_target_hint(key, s)),
2014            Value::Array(items) if matches!(key.as_str(), "paths" | "urls") => {
2015                for item in items.iter().filter_map(|item| item.as_str()) {
2016                    push_unique_target_hint(&mut hints, string_to_target_hint(key, item));
2017                }
2018            }
2019            _ => {}
2020        }
2021    }
2022    hints
2023}
2024
2025fn default_access_manifest(
2026    arguments: &str,
2027    semantics: &ToolCallSemantics,
2028) -> ToolCallAccessManifest {
2029    let parsed = serde_json::from_str::<Value>(arguments).ok();
2030    let execution_cwd = parsed.as_ref().and_then(|value| {
2031        value
2032            .get("working_dir")
2033            .or_else(|| value.get("cwd"))
2034            .and_then(Value::as_str)
2035            .map(str::trim)
2036            .filter(|value| !value.is_empty())
2037            .map(str::to_string)
2038    });
2039    let targets = if semantics.target_hints.is_empty() {
2040        collect_common_target_hints(arguments)
2041    } else {
2042        semantics.target_hints.clone()
2043    };
2044    let non_cwd_targets = targets
2045        .into_iter()
2046        .filter(|target| {
2047            matches!(
2048                target.kind,
2049                ToolTargetHintKind::Path | ToolTargetHintKind::ProjectScope
2050            )
2051        })
2052        .filter(|target| execution_cwd.as_deref() != Some(target.value.as_str()))
2053        .collect::<Vec<_>>();
2054    let mut read_targets = Vec::new();
2055    if let Some(cwd) = execution_cwd.as_deref()
2056        && let Some(target) = ToolTargetHint::new(ToolTargetHintKind::ProjectScope, cwd)
2057    {
2058        read_targets.push(target);
2059    }
2060    if semantics.observes_state() {
2061        read_targets.extend(non_cwd_targets.iter().cloned());
2062    }
2063    let write_targets = if semantics.mutates_state() {
2064        non_cwd_targets
2065    } else {
2066        Vec::new()
2067    };
2068    ToolCallAccessManifest {
2069        execution_cwd,
2070        read_targets,
2071        write_targets,
2072        adapter_read_targets: Vec::new(),
2073    }
2074}
2075
2076/// Classify a mixed-operation tool from the exact `action` enum in its schema.
2077///
2078/// This helper intentionally performs no tokenization, substring matching, or
2079/// interpretation of unknown action names. Tools pass their exhaustive set of
2080/// read-only enum variants; every missing, malformed, or new variant fails
2081/// conservatively as a mutation until the tool implementation classifies it.
2082pub fn semantics_for_exact_read_actions(
2083    arguments: &str,
2084    read_actions: &[&str],
2085    mutation_effects: ToolMutationEffects,
2086) -> ToolCallSemantics {
2087    let action = serde_json::from_str::<Value>(arguments)
2088        .ok()
2089        .and_then(|value| {
2090            value
2091                .get("action")
2092                .and_then(Value::as_str)
2093                .map(str::to_string)
2094        });
2095    let mut semantics = if action
2096        .as_deref()
2097        .is_some_and(|action| read_actions.contains(&action))
2098    {
2099        ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
2100    } else if mutation_effects.is_empty() {
2101        ToolCallSemantics::mutation()
2102    } else {
2103        ToolCallSemantics::mutation_with(mutation_effects)
2104    };
2105    for target_hint in collect_common_target_hints(arguments) {
2106        semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
2107    }
2108    semantics
2109}
2110
2111fn default_semantics_from_identity(arguments: &str, caps: ToolCapabilities) -> ToolCallSemantics {
2112    let mut semantics = if caps.read_only {
2113        ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
2114    } else {
2115        // Unknown non-read-only tools fail conservatively as mutations. Mixed
2116        // tools must override `call_semantics` with an exact match on their
2117        // schema enum; names, descriptions, and arbitrary action vocabulary are
2118        // never an authority source.
2119        ToolCallSemantics::mutation()
2120    };
2121
2122    for target_hint in collect_common_target_hints(arguments) {
2123        semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
2124    }
2125    semantics
2126}
2127
2128/// The scope of an approval the agent kernel gave a call (see
2129/// [`ToolCallContext::kernel_approved`]).
2130#[derive(Debug, Clone, PartialEq, Eq)]
2131pub enum ApprovalScope {
2132    /// This call came through the kernel, which judged it.
2133    Call,
2134    /// One exact inner request (`METHOD url`) of an outer call the kernel
2135    /// approved, for example `manage_api`'s live probe.
2136    Request { method: String, url: String },
2137}
2138
2139/// One call as the kernel's approval rules show it to
2140/// [`ToolSemantics::owner_approval_request`].
2141#[derive(Debug, Clone, Copy)]
2142pub struct ApprovalCall<'a> {
2143    /// The arguments the dispatcher will execute (for a tool whose calls the
2144    /// kernel judges in canonical form, the canonical form; otherwise the
2145    /// model's own).
2146    pub arguments: &'a Value,
2147    /// The arguments as the model sent them, for a card about a call whose
2148    /// arguments cannot be read.
2149    pub as_sent: &'a Value,
2150    /// The dispatcher refuses this call before it runs (an out-of-scope
2151    /// target nobody may authorize), so nothing about it needs the owner.
2152    pub refused: bool,
2153}
2154
2155impl<'a> ApprovalCall<'a> {
2156    /// A call the dispatcher runs as the model sent it.
2157    pub fn as_sent(arguments: &'a Value) -> Self {
2158        Self {
2159            arguments,
2160            as_sent: arguments,
2161            refused: false,
2162        }
2163    }
2164}
2165
2166/// What a tool says about the owner's approval for one call.
2167#[derive(Debug, Clone, PartialEq)]
2168pub enum OwnerApprovalNeed {
2169    /// The tool has no opinion: the approval policy's allow rules and mode
2170    /// decide.
2171    Unjudged,
2172    /// The tool judged the call and it needs no approval.
2173    NotNeeded,
2174    /// Ask the owner with this request (unless a grant covers it).
2175    Ask(aidaemon_core::OwnerApprovalRequest),
2176}
2177
2178/// The dispatcher's facts about one tool call, passed to the tool beside its
2179/// arguments.
2180///
2181/// This is a Rust-side control-plane type: it is NEVER serialized and never
2182/// appears in model-visible JSON, tool schemas, logs, or persisted tool
2183/// arguments. Every fact about who is calling, from where, and under what
2184/// authority lives here and only here: a tool's arguments are the model's
2185/// own, and the dispatcher strips any `_`-prefixed key a model sends.
2186#[derive(Clone, Default)]
2187pub struct ToolCallContext {
2188    /// True only after the final common dispatcher revalidated an exact,
2189    /// action-bound `MandateAuthorityGrant` for this mutating call, so tools
2190    /// can honor owner-delegated autonomy.
2191    pub mandate_preapproved: bool,
2192    /// True only when the common dispatcher resolved this call to an active
2193    /// autonomous mandate. Network adapters use this control-plane bit to keep
2194    /// one target-bound call from following redirects outside the target that
2195    /// was evaluated by the mandate authority kernel.
2196    pub mandate_execution: bool,
2197    /// Hard negative task contract propagated from the validated request.
2198    /// Open-ended adapters must prove an operation is observational before I/O.
2199    pub mutation_forbidden: bool,
2200    /// What the agent kernel approved, set only by the dispatcher (never
2201    /// from arguments): `Call` for a call that came through the kernel,
2202    /// whose `ApprovalPolicy` already asked the owner where the daemon's
2203    /// rules require it; `Request` for one exact inner request an approved
2204    /// outer call makes. A tool that needs the owner's approval refuses a
2205    /// call without a matching scope rather than asking itself.
2206    pub kernel_approved: Option<ApprovalScope>,
2207    /// The turn is a trusted scheduled session (never one under a mandate),
2208    /// set only by the dispatcher from the channel context and the goal's
2209    /// provenance.
2210    pub trusted_session: bool,
2211    /// The role of the turn's user (`None` outside the dispatcher: an
2212    /// unknown caller is not the owner).
2213    pub user_role: Option<UserRole>,
2214    /// The session was started by an automated trigger (an email, an
2215    /// event), not by the owner.
2216    pub untrusted_source: bool,
2217    /// Exact out-of-scope targets the controller routed to the owner's
2218    /// approval instead of refusing them.
2219    pub scope_escalation: Option<ScopeEscalation>,
2220    /// The session the call belongs to (empty outside the dispatcher).
2221    pub session_id: String,
2222    /// The session whose owner approvals cover this call: the chat that
2223    /// started the work. A sub-agent runs in a session of its own but works
2224    /// for that chat, so a tool's own session-scoped grants ("allow for
2225    /// session") key on this, never on `session_id`. Empty: `session_id`.
2226    pub grant_session: String,
2227    /// Visibility of the channel the turn came from (`None` outside the
2228    /// dispatcher; each tool keeps its own fallback).
2229    pub channel_visibility: Option<ChannelVisibility>,
2230    /// The channel the turn came from, when the channel has an id.
2231    pub channel_id: Option<String>,
2232    /// The task the call runs under.
2233    pub task_id: Option<String>,
2234    /// The model's id for this tool call.
2235    pub tool_call_id: Option<String>,
2236    /// The call is the only one in a root turn's model response, so a reply
2237    /// the tool finishes the run with answers the user's request directly.
2238    pub lone_root_call: bool,
2239    /// The session's current turn.
2240    pub turn_id: Option<String>,
2241    /// The goal the call serves: the agent's goal, or (for `cli_agent` and
2242    /// `terminal`) the goal of the executor's task, so background
2243    /// notifications reach the origin session.
2244    pub goal_id: Option<String>,
2245    /// The goal run of the mandate fence the call runs under.
2246    pub goal_run_id: Option<String>,
2247    /// The task attempt of the mandate fence the call runs under.
2248    pub task_attempt_id: Option<String>,
2249    /// The mandate of the fence the call runs under.
2250    pub mandate_id: Option<String>,
2251    /// The mandate version of the fence the call runs under.
2252    pub mandate_version: Option<i64>,
2253    /// The single project the turn is scoped to.
2254    pub project_scope: Option<String>,
2255    /// The project the owner's turn works in (an app project, a chat placed
2256    /// in one), set only by the dispatcher from typed turn state. `None` for
2257    /// guests, public channels and mandate runs: project-scoped writes (a
2258    /// memory tool's project notes) key on it.
2259    pub project: Option<aidaemon_core::ProjectRef>,
2260    /// A guest's granted workspace root (only under an active grant).
2261    pub workspace_collaboration_root: Option<String>,
2262    /// The turn's trusted file roots (set for `terminal`), so a run moved to
2263    /// the background records the trust its launch was judged with.
2264    pub trust_roots: Option<Vec<String>>,
2265    /// The cwd relative paths resolve against for [`Self::trust_roots`].
2266    pub trust_cwd: Option<String>,
2267    /// The live model (set for `computer_use`).
2268    pub model: Option<String>,
2269    /// The provider kind behind [`Self::model`], as the daemon names it.
2270    pub provider_kind: Option<String>,
2271    /// The router's models in order, when a router is configured.
2272    pub model_chain: Option<Vec<String>>,
2273    /// Application facts whose types cannot live in the SDK (they depend on
2274    /// the application's configuration), read by the tool that needs them
2275    /// through a typed getter.
2276    pub extensions: aidaemon_core::Extensions,
2277}
2278
2279impl std::fmt::Debug for ToolCallContext {
2280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2281        f.debug_struct("ToolCallContext")
2282            .field("mandate_preapproved", &self.mandate_preapproved)
2283            .field("mandate_execution", &self.mandate_execution)
2284            .field("mutation_forbidden", &self.mutation_forbidden)
2285            .field("kernel_approved", &self.kernel_approved)
2286            .field("trusted_session", &self.trusted_session)
2287            .field("user_role", &self.user_role)
2288            .field("untrusted_source", &self.untrusted_source)
2289            .field("scope_escalation", &self.scope_escalation)
2290            .field("session_id", &self.session_id)
2291            .field("channel_visibility", &self.channel_visibility)
2292            .field("channel_id", &self.channel_id)
2293            .field("task_id", &self.task_id)
2294            .field("tool_call_id", &self.tool_call_id)
2295            .field("lone_root_call", &self.lone_root_call)
2296            .field("turn_id", &self.turn_id)
2297            .field("goal_id", &self.goal_id)
2298            .field("goal_run_id", &self.goal_run_id)
2299            .field("task_attempt_id", &self.task_attempt_id)
2300            .field("mandate_id", &self.mandate_id)
2301            .field("mandate_version", &self.mandate_version)
2302            .field("project_scope", &self.project_scope)
2303            .field(
2304                "workspace_collaboration_root",
2305                &self
2306                    .workspace_collaboration_root
2307                    .as_ref()
2308                    .map(|_| "[SCOPED WORKSPACE]"),
2309            )
2310            .field("trust_roots", &self.trust_roots)
2311            .field("trust_cwd", &self.trust_cwd)
2312            .field("model", &self.model)
2313            .field("provider_kind", &self.provider_kind)
2314            .field("model_chain", &self.model_chain)
2315            .field("extensions", &self.extensions)
2316            .finish()
2317    }
2318}
2319
2320impl ToolCallContext {
2321    /// The session id, or `None` when the call carries none.
2322    pub fn session(&self) -> Option<&str> {
2323        Some(self.session_id.as_str()).filter(|id| !id.trim().is_empty())
2324    }
2325
2326    /// The session a tool's own session-scoped grants key on
2327    /// ([`Self::grant_session`], else the call's session).
2328    pub fn grants_session(&self) -> &str {
2329        if self.grant_session.trim().is_empty() {
2330            &self.session_id
2331        } else {
2332            &self.grant_session
2333        }
2334    }
2335}
2336
2337/// Filesystem targets a tool call declared that fall outside the compiled
2338/// task scope but are not protected host data or credential stores. The
2339/// controller does not reject such a call outright; it hands the exact
2340/// out-of-scope targets to the tool, which must obtain explicit user approval
2341/// (or a persisted capability grant) before running with them.
2342#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
2343pub struct ScopeEscalation {
2344    #[serde(default)]
2345    pub read_paths: Vec<String>,
2346    #[serde(default)]
2347    pub write_paths: Vec<String>,
2348}
2349
2350impl ScopeEscalation {
2351    pub fn is_empty(&self) -> bool {
2352        self.read_paths.is_empty() && self.write_paths.is_empty()
2353    }
2354}
2355
2356/// A tool-owned decision about whether a previously successful durable receipt
2357/// still represents current state.
2358///
2359/// Most mutations cannot be repeated safely and therefore use `Replay`. Tools
2360/// with an exact deterministic postcondition may opt into current-state
2361/// reconciliation and either re-execute when that postcondition is missing or
2362/// block when the target drifted in a way that could make repetition unsafe.
2363#[derive(Debug, Clone, PartialEq, Eq)]
2364pub enum DurableReplayDecision {
2365    Replay,
2366    Reexecute { reason: String },
2367    Block { reason: String },
2368}
2369
2370/// Tool trait — system tools, terminal, MCP-proxied tools.
2371#[derive(Debug, Clone, PartialEq, Eq)]
2372pub struct ToolArgumentContractViolation {
2373    pub reason: String,
2374    pub recovery_hint: Option<String>,
2375}
2376
2377impl ToolArgumentContractViolation {
2378    pub fn new(reason: impl Into<String>) -> Self {
2379        Self {
2380            reason: reason.into(),
2381            recovery_hint: None,
2382        }
2383    }
2384
2385    pub fn with_recovery_hint(mut self, hint: impl Into<String>) -> Self {
2386        self.recovery_hint = Some(hint.into());
2387        self
2388    }
2389}
2390
2391/// Permission persistence mode for commands requiring owner approval.
2392#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
2393#[serde(rename_all = "lowercase")]
2394pub enum PermissionMode {
2395    /// Safe/Medium/High persist; Critical remains session-scoped.
2396    #[default]
2397    Default,
2398    /// All approvals remain session-scoped.
2399    Cautious,
2400    /// All approvals persist, including Critical.
2401    Yolo,
2402}
2403
2404impl std::fmt::Display for PermissionMode {
2405    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2406        match self {
2407            PermissionMode::Default => write!(f, "default"),
2408            PermissionMode::Cautious => write!(f, "cautious"),
2409            PermissionMode::Yolo => write!(f, "yolo"),
2410        }
2411    }
2412}
2413
2414/// Distinguishes different kinds of approval requests so channels can render
2415/// appropriate buttons (e.g., Allow Once / Deny for commands vs Confirm / Cancel
2416/// for scheduled-goal confirmations).
2417#[derive(Debug, Clone, Copy, Default)]
2418pub enum ApprovalKind {
2419    /// Standard command approval (Allow Once / Allow Session / Allow Always / Deny).
2420    #[default]
2421    Command,
2422    /// Point-of-action approval that can authorize only this invocation.
2423    /// Channels must not offer session or persistent approval buttons.
2424    CommandOnce,
2425    /// Scheduled-goal confirmation (Confirm / Cancel).
2426    GoalConfirmation,
2427    /// Exact owner confirmation for a persisted Autopilot mandate policy.
2428    /// Kept distinct so channels never infer high-autonomy presentation from
2429    /// user or model prose.
2430    AutopilotConfirmation,
2431    /// The agent asks the owner to do something themselves on a live surface
2432    /// (sign in, enter a code): Done or Not now, this one time only.
2433    Handoff,
2434}
2435
2436/// Response to an approval request from the user.
2437#[derive(Debug, Clone)]
2438pub enum ApprovalResponse {
2439    /// Allow this specific command only
2440    AllowOnce,
2441    /// Allow this command prefix for the current session (resets on restart)
2442    AllowSession,
2443    /// Allow this command prefix forever (persists to database)
2444    AllowAlways,
2445    /// Deny the command
2446    Deny,
2447}
2448
2449/// Relative impact of an operation requiring approval.
2450#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
2451pub enum RiskLevel {
2452    Safe,
2453    Medium,
2454    High,
2455    Critical,
2456}
2457
2458impl std::fmt::Display for RiskLevel {
2459    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2460        match self {
2461            RiskLevel::Safe => write!(f, "Safe"),
2462            RiskLevel::Medium => write!(f, "Medium"),
2463            RiskLevel::High => write!(f, "High"),
2464            RiskLevel::Critical => write!(f, "Critical"),
2465        }
2466    }
2467}
2468
2469impl RiskLevel {
2470    /// Whether this risk level represents an action that should interrupt the
2471    /// owner for approval. Safe and medium operations may still be observable
2472    /// or locally mutating, but they are not dangerous enough to justify
2473    /// blocking an otherwise authorized task.
2474    pub const fn requires_owner_approval(self) -> bool {
2475        matches!(self, Self::High | Self::Critical)
2476    }
2477}
2478
2479/// Typed presentation requested for an exact goal/mandate confirmation.
2480#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2481pub enum GoalConfirmationStyle {
2482    #[default]
2483    Standard,
2484    Autopilot,
2485}
2486
2487/// Role assigned to an agent for role-based tool scoping.
2488#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2489pub enum AgentRole {
2490    /// Root agent — routes, classifies, full tool access (legacy behavior).
2491    Orchestrator,
2492    /// Plans & delegates — management tools only.
2493    TaskLead,
2494    /// Executes a single task — action tools + report_blocker.
2495    Executor,
2496}
2497
2498/// How one call changes a file (see [`ToolSemantics::call_file_write`]).
2499#[derive(Debug, Clone, PartialEq, Eq)]
2500pub enum FileWriteKind {
2501    /// Replaces this exact text.
2502    Edit { old_text: String, replace_all: bool },
2503    /// Replaces each exact text in order, each in the result of the one
2504    /// before: all of them, or nothing.
2505    Edits(Vec<TextEdit>),
2506    /// Replaces the whole file.
2507    Replace,
2508    /// Adds to the end of the file.
2509    Append,
2510}
2511
2512/// One find-and-replace of a [`FileWriteKind::Edits`] batch.
2513#[derive(Debug, Clone, PartialEq, Eq)]
2514pub struct TextEdit {
2515    pub old_text: String,
2516    pub replace_all: bool,
2517}
2518
2519/// The file one call writes, as the tool's arguments name it.
2520#[derive(Debug, Clone, PartialEq, Eq)]
2521pub struct FileWrite {
2522    pub path: String,
2523    pub kind: FileWriteKind,
2524}
2525
2526/// A write in progress under a [`FileFence`]. Dropping it records nothing.
2527#[async_trait]
2528pub trait FileWriteGuard: Send {
2529    /// The write landed.
2530    async fn committed(self: Box<Self>);
2531}
2532
2533/// Handed to a file tool by a host whose agents share a workspace. Without
2534/// one the tool behaves as it would alone.
2535#[async_trait]
2536pub trait FileFence: Send + Sync {
2537    /// The call read these exact bytes of `path`.
2538    async fn observed(&self, path: &str, bytes: &[u8]);
2539
2540    /// Hold `path` for this write, or say why the write must not happen.
2541    /// Taken before the tool reads the file it is about to change, and held
2542    /// until the write has landed.
2543    async fn begin_write(&self, path: &str) -> Result<Box<dyn FileWriteGuard>, String>;
2544
2545    /// Claim the delivery to the owner of the artifact `subject` names (a
2546    /// page's screenshot names the page) for this call. One request's agents
2547    /// deliver each artifact once: whoever delivers it first owns it, and a
2548    /// later claim gets who did and when. Release a claim whose delivery
2549    /// then failed ([`Self::release_delivery`]).
2550    async fn claim_delivery(&self, _subject: &str) -> Result<(), DeliveredArtifact> {
2551        Ok(())
2552    }
2553
2554    /// Give back a claim whose delivery did not happen.
2555    async fn release_delivery(&self, _subject: &str) {}
2556
2557    /// The call declares `deliverable` for the owner. A helper's run keeps
2558    /// it on its record and sends it once, when the run ends: the last one
2559    /// of each kind it declared, so a capture taken before the work was
2560    /// done is replaced by the final one, never sent beside it. Anyone
2561    /// else's (the turn's own agent, a host with no run record) is sent now
2562    /// by the caller, under [`Self::claim_delivery`].
2563    async fn declare_deliverable(&self, deliverable: Deliverable) -> DeliveryPlan {
2564        DeliveryPlan::Now(deliverable)
2565    }
2566}
2567
2568/// What a deliverable is, by kind: each run delivers one of each kind (the
2569/// last it declared), and each request delivers each subject once.
2570#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2571pub enum DeliverableKind {
2572    /// A page's screenshot, named by its page ("demo.ddev.site").
2573    Screenshot { page: String },
2574    /// Any other file, named by its file name.
2575    File { name: String },
2576}
2577
2578impl DeliverableKind {
2579    /// The delivery ledger's key for it.
2580    pub fn subject(&self) -> String {
2581        match self {
2582            Self::Screenshot { page } => format!("screenshot:{page}"),
2583            Self::File { name } => format!("file:{name}"),
2584        }
2585    }
2586
2587    /// The kind in the owner's words ("a screenshot of demo.ddev.site").
2588    pub fn words(&self) -> String {
2589        match self {
2590            Self::Screenshot { page } => format!("a screenshot of {page}"),
2591            Self::File { name } => format!("the file {name}"),
2592        }
2593    }
2594}
2595
2596/// The send a tool hands over with a deliverable sent later: run once, it
2597/// reports whether the channel accepted it.
2598pub type DeliverySend = Box<
2599    dyn FnOnce() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>
2600        + Send
2601        + Sync,
2602>;
2603
2604/// One artifact a call declares for the owner.
2605pub struct Deliverable {
2606    pub kind: DeliverableKind,
2607    /// What the owner reads with it ("Screenshot of demo.ddev.site").
2608    pub caption: String,
2609    pub send: DeliverySend,
2610}
2611
2612impl std::fmt::Debug for Deliverable {
2613    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2614        f.debug_struct("Deliverable")
2615            .field("kind", &self.kind)
2616            .field("caption", &self.caption)
2617            .finish_non_exhaustive()
2618    }
2619}
2620
2621/// When a declared deliverable is sent ([`FileFence::declare_deliverable`]).
2622#[derive(Debug)]
2623pub enum DeliveryPlan {
2624    /// The caller sends it now, under a delivery claim.
2625    Now(Deliverable),
2626    /// It is on the run's record and is sent when the run ends. `replaced`:
2627    /// it took the place of an earlier one of the same kind.
2628    AtRunEnd { replaced: bool },
2629}
2630
2631/// An artifact one of the request's agents already delivered to the owner.
2632#[derive(Debug, Clone, PartialEq, Eq)]
2633pub struct DeliveredArtifact {
2634    /// Who delivered it, in words the owner reads ("you", or the helper's
2635    /// mission).
2636    pub by: String,
2637    pub at: chrono::DateTime<chrono::Utc>,
2638}
2639
2640impl DeliveredArtifact {
2641    /// When it was delivered, on the owner's clock ("3:41:22 AM").
2642    pub fn owner_time(&self) -> String {
2643        self.at
2644            .with_timezone(&chrono::Local)
2645            .format("%-I:%M:%S %p")
2646            .to_string()
2647    }
2648}
2649
2650/// This call's [`FileFence`], carried in [`ToolCallContext::extensions`].
2651#[derive(Clone)]
2652pub struct CallFileFence(pub std::sync::Arc<dyn FileFence>);
2653
2654/// The call's file fence, if its host gave it one.
2655pub fn file_fence(facts: &ToolCallContext) -> Option<&std::sync::Arc<dyn FileFence>> {
2656    facts
2657        .extensions
2658        .get::<CallFileFence>()
2659        .map(|fence| &fence.0)
2660}
2661
2662/// A job a tool runs in the background for a chat.
2663#[derive(Debug, Clone, PartialEq, Eq)]
2664pub struct BackgroundJob {
2665    /// The tool's own handle for it; never shown.
2666    pub key: String,
2667    /// What it is, in plain words.
2668    pub title: String,
2669    pub started_at: chrono::DateTime<chrono::Utc>,
2670    /// The task (turn) that started it, when known.
2671    pub task_id: Option<String>,
2672}
2673
2674/// What a tool says about a call without executing it: its capabilities,
2675/// typed semantics, access manifest, receipt protocol, effects and trust.
2676/// Every method has a conservative default; a tool overrides only what it
2677/// can state exactly.
2678#[async_trait]
2679pub trait ToolSemantics: Send + Sync {
2680    /// Canonicalize provider argument projections before any semantics,
2681    /// authority, retry, or access decision is made. The default is identity;
2682    /// adapters with representational aliases or optional-empty projection
2683    /// quirks can normalize them without teaching the orchestration layer
2684    /// adapter-specific rules.
2685    fn canonicalize_arguments(
2686        &self,
2687        arguments: &str,
2688    ) -> Result<String, ToolArgumentContractViolation> {
2689        Ok(arguments.to_string())
2690    }
2691
2692    /// Adapter-owned, deterministic argument invariants evaluated by the
2693    /// common dispatcher before any tool I/O. The default accepts all schema-
2694    /// valid calls. Rejections become typed `contract_rejected` receipts.
2695    fn validate_arguments(&self, _arguments: &str) -> Result<(), ToolArgumentContractViolation> {
2696        Ok(())
2697    }
2698
2699    /// Task lifecycle callback fired after the agent emits `TaskEnd`.
2700    /// Tools that spawn background activity can use this to clean up
2701    /// task-scoped resources.
2702    async fn on_task_end(&self, _task_id: &str, _session_id: &str) -> anyhow::Result<()> {
2703        Ok(())
2704    }
2705
2706    /// Live state this tool holds for a session that outlives a turn (for
2707    /// example background processes still running), rendered for the next
2708    /// turn's task context so a follow-up sees it instead of guessing.
2709    async fn session_context_note(&self, _session_id: &str) -> Option<String> {
2710        None
2711    }
2712
2713    /// The jobs this tool is running in the background for `session_id`
2714    /// (they outlive the turn that started them), as the chat's list of
2715    /// running work shows them.
2716    async fn background_jobs(&self, _session_id: &str) -> Vec<BackgroundJob> {
2717        Vec::new()
2718    }
2719
2720    /// Stop the background job `key` (from [`Self::background_jobs`]) and
2721    /// read its state back: `true` only once the job is gone.
2722    async fn stop_background_job(&self, _key: &str) -> bool {
2723        false
2724    }
2725
2726    /// How many jobs task `task_id` started that are still running and that
2727    /// the task's end would stop: nothing reports their result, so a run that
2728    /// ended now would lose their work.
2729    async fn jobs_ended_by_task_end(&self, _task_id: &str) -> usize {
2730        0
2731    }
2732
2733    /// Categorize this tool for role-based scoping.
2734    /// Default: Action (most tools are action tools).
2735    fn tool_role(&self) -> ToolRole {
2736        ToolRole::Action
2737    }
2738
2739    /// How the dispatcher and the engine treat this tool. Default: nothing
2740    /// special.
2741    fn dispatch_facts(&self) -> ToolDispatchFacts {
2742        ToolDispatchFacts::default()
2743    }
2744
2745    /// Capability metadata used by the execution policy and risk gate.
2746    /// Defaults are intentionally conservative.
2747    fn capabilities(&self) -> ToolCapabilities {
2748        ToolCapabilities::default()
2749    }
2750
2751    /// The tool only manages the owner's own durable policy (mandates). A
2752    /// request assessment that narrows a turn's tools still offers it to the
2753    /// owner in a private chat, but only calls `owner_control_plane_call`
2754    /// accepts are admitted there.
2755    fn owner_control_plane(&self) -> bool {
2756        false
2757    }
2758
2759    /// Whether this exact call is safe on a turn whose assessment did not
2760    /// name the tool: read-only, or committing only through an explicit
2761    /// owner confirmation. Decided from the tool's own schema enum.
2762    fn owner_control_plane_call(&self, _arguments: &str) -> bool {
2763        false
2764    }
2765
2766    /// The owner approval this exact call needs before it runs, judged from
2767    /// the call and the dispatcher's facts for it (never from `_` arguments).
2768    /// The kernel's approval rules ask it for every call and send the card
2769    /// it returns. The default has no opinion, so the approval policy's mode
2770    /// decides.
2771    async fn owner_approval_request(
2772        &self,
2773        _call: &ApprovalCall<'_>,
2774        _facts: &ToolCallContext,
2775    ) -> OwnerApprovalNeed {
2776        OwnerApprovalNeed::Unjudged
2777    }
2778
2779    /// Machine-receipt protocol emitted by this adapter.
2780    ///
2781    /// Keep this independent from natural-language descriptions and call
2782    /// semantics: it exists solely to type-check completion predicates.
2783    fn receipt_kind(&self, _arguments: &str) -> ToolReceiptKind {
2784        ToolReceiptKind::Generic
2785    }
2786
2787    /// Structured completion semantics for a specific call.
2788    ///
2789    /// Default behavior derives a conservative fallback from `capabilities()`.
2790    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
2791        default_semantics_from_identity(arguments, self.capabilities())
2792    }
2793
2794    /// Filesystem access roles for this exact call. Open-ended adapters should
2795    /// override this when their schema exposes explicit read/write grants.
2796    fn call_access_manifest(&self, arguments: &str) -> ToolCallAccessManifest {
2797        let semantics = self.call_semantics(arguments);
2798        default_access_manifest(arguments, &semantics)
2799    }
2800
2801    /// The paths this call reads and writes, as `ProtectedPathGuard` judges
2802    /// them. Defaults to the access manifest; a tool overrides it for a path
2803    /// that scope checks must not see as a task read.
2804    fn guarded_paths(&self, arguments: &str) -> (Vec<String>, Vec<String>) {
2805        let manifest = self.call_access_manifest(arguments);
2806        let values =
2807            |targets: Vec<ToolTargetHint>| targets.into_iter().map(|target| target.value).collect();
2808        (
2809            values(manifest.read_targets),
2810            values(manifest.write_targets),
2811        )
2812    }
2813
2814    /// Capabilities supplied by the adapter rather than requested as task
2815    /// data.  The common dispatcher uses this typed lane when attenuating the
2816    /// call against the task manifest.  The default is empty so an adapter
2817    /// cannot accidentally widen authority by inheriting a generic grant.
2818    fn adapter_owned_access_manifest(&self, _arguments: &str) -> ToolCallAccessManifest {
2819        ToolCallAccessManifest::default()
2820    }
2821
2822    /// Reconcile a successful durable receipt with current state before replay.
2823    ///
2824    /// The conservative default always replays. An override may return
2825    /// `Reexecute` only when repeating the exact same invocation is safe after
2826    /// the observed state transition, and `Block` when current state cannot be
2827    /// reconciled safely.
2828    async fn durable_replay_decision(&self, _arguments: &str) -> DurableReplayDecision {
2829        DurableReplayDecision::Replay
2830    }
2831
2832    /// Exact receipt subjects this adapter reports verbatim: fixed collection
2833    /// IDs and the namespaces of member identities it mints. The checklist
2834    /// tool publishes the union so declared targets bind only to identities a
2835    /// receipt can carry. The default advertises nothing.
2836    fn stable_observation_subjects(&self) -> Vec<StableObservationSubject> {
2837        Vec::new()
2838    }
2839
2840    /// The file this exact call writes and how, read from its arguments. A
2841    /// tool that does not declare one is invisible to stale-write checks.
2842    fn call_file_write(&self, _arguments: &str) -> Option<FileWrite> {
2843        None
2844    }
2845
2846    /// What the file would hold after this exact call, were it holding
2847    /// `current` now (`None`: no such file). `Err` is the tool's own reason
2848    /// the call cannot apply to that content. A tool that cannot say returns
2849    /// `None`, and a host that asks then treats the call as changing all of
2850    /// the file.
2851    fn file_write_result(
2852        &self,
2853        _arguments: &str,
2854        _current: Option<&[u8]>,
2855    ) -> Option<Result<Vec<u8>, String>> {
2856        None
2857    }
2858
2859    /// What this call carries out of the machine if it only reads.
2860    fn call_outbound(&self, _arguments: &str) -> aidaemon_core::Outbound {
2861        aidaemon_core::Outbound::Nothing
2862    }
2863
2864    /// The typed effects of this exact call (effect class and normalized
2865    /// target), which the kernel checks against the owner's declines and
2866    /// hands the approval and egress policies. Build keys only with the
2867    /// kernel constructors, through `command_effects::{path_effect,
2868    /// egress_effect, url_effect}`. The default is `CallEffects::none()` for a
2869    /// tool whose capabilities are read-only and `CallEffects::unknown()`
2870    /// otherwise; a tool that can name what a call does overrides it.
2871    fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
2872        if self.capabilities().read_only {
2873            aidaemon_core::CallEffects::none()
2874        } else {
2875            aidaemon_core::CallEffects::unknown()
2876        }
2877    }
2878
2879    /// Every file or resource this exact call names as something it reads
2880    /// or writes, from typed facts only (never its prose): its declared
2881    /// target hints, its access manifest and its typed path effects. A tool
2882    /// whose arguments name more structurally (a shell command's operands)
2883    /// adds them. One reading for every tool, so a fact about a file (the
2884    /// request's own work produced it) reaches each call that names it.
2885    fn named_files(&self, arguments: &str) -> Vec<String> {
2886        declared_named_files(self, arguments)
2887    }
2888
2889    /// Authority annotations for this exact call, judged against the turn's
2890    /// trusted roots: read-only, destructive, idempotent, and whether it
2891    /// sends data or acts outside the owner's machine and workspace
2892    /// (`egress`). Derived from the call's typed semantics, never from the
2893    /// tool's name. Roots matter for effects whose class depends on where
2894    /// they land (a delete inside the owner's roots is not egress); empty
2895    /// roots mean every such target counts as outside them. The default
2896    /// ignores the roots.
2897    fn call_annotations_in(
2898        &self,
2899        arguments: &str,
2900        _roots: &TrustRoots<'_>,
2901    ) -> aidaemon_core::ToolAnnotations {
2902        default_call_annotations(self.capabilities(), &self.call_semantics(arguments))
2903    }
2904
2905    /// Who authored what this exact call returns. The default is
2906    /// `Untrusted` iff the tool reaches outside the machine
2907    /// (`external_side_effect`); local tools override with the owner's
2908    /// trusted roots.
2909    fn output_trust(
2910        &self,
2911        _arguments: &str,
2912        _roots: &TrustRoots<'_>,
2913    ) -> aidaemon_core::SourceTrust {
2914        if self.capabilities().external_side_effect {
2915            aidaemon_core::SourceTrust::Untrusted
2916        } else {
2917            aidaemon_core::SourceTrust::Trusted
2918        }
2919    }
2920
2921    /// A few plain words the call itself gave for what it does ("running
2922    /// the site installer"), for the owner's status line and lists of
2923    /// running work. Never authority. Default: none.
2924    fn call_title(&self, _arguments: &str) -> Option<String> {
2925        None
2926    }
2927
2928    /// Whether this tool is currently operational.
2929    ///
2930    /// Default: true. Override for tools with dynamic backends that may be
2931    /// temporarily unavailable at runtime.
2932    fn is_available(&self) -> bool {
2933        true
2934    }
2935
2936    /// Whether the tool is offered on a turn of `session_id`, judged from
2937    /// the tool's own typed state, never from the request's wording.
2938    ///
2939    /// Default: true. A tool whose only effect lands on one client
2940    /// connection (the agent-driven view) is offered only while that
2941    /// session's turn came from a connection that can show it.
2942    fn offered_in_session(&self, _session_id: &str) -> bool {
2943        true
2944    }
2945}
2946
2947/// Effects that send data or act outside the owner's machine and workspace,
2948/// or cannot be undone. A call with any of these is egress.
2949pub const EGRESS_EFFECTS: ToolMutationEffects = ToolMutationEffects::EXTERNAL_DELIVERY
2950    .union(ToolMutationEffects::REMOTE_MUTATION)
2951    .union(ToolMutationEffects::REMOTE_DEPLOY)
2952    .union(ToolMutationEffects::DESTRUCTIVE)
2953    .union(ToolMutationEffects::CONFIGURATION);
2954
2955/// Per-call authority annotations from a tool's capabilities and the call's
2956/// typed semantics.
2957pub fn default_call_annotations(
2958    cap: ToolCapabilities,
2959    semantics: &ToolCallSemantics,
2960) -> aidaemon_core::ToolAnnotations {
2961    let read_only = cap.read_only
2962        || (matches!(
2963            semantics.effect,
2964            ToolCallEffect::Observation | ToolCallEffect::Administrative
2965        ) && !semantics.mutates_state());
2966    let effects = semantics.mutation_effects;
2967    let egress = !read_only
2968        && (effects.intersects(EGRESS_EFFECTS)
2969            || (cap.external_side_effect && !effects.has_specific_effects()));
2970    aidaemon_core::ToolAnnotations {
2971        read_only,
2972        destructive: !read_only && effects.intersects(ToolMutationEffects::DESTRUCTIVE),
2973        idempotent: read_only,
2974        egress,
2975    }
2976}
2977
2978/// The folders a request's work made fresh for itself (a spawn's
2979/// `new_folders`, claimed empty by the runtime), shared by every run of the
2980/// request's tree. Everything inside them is the work's own: a change or a
2981/// delete there acts on nothing anyone else made. A planning and effect
2982/// fact only, never a trust source for what is read there (a package
2983/// manager fills them with other people's code).
2984#[derive(Debug, Clone, Default)]
2985pub struct OwnedFolders(std::sync::Arc<std::sync::RwLock<Vec<String>>>);
2986
2987impl OwnedFolders {
2988    /// Record folders the runtime just made for this request's work.
2989    pub fn claim(&self, folders: &[String]) {
2990        let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
2991        for folder in folders {
2992            let folder = folder.trim();
2993            if std::path::Path::new(folder).is_absolute() && !owned.iter().any(|f| f == folder) {
2994                owned.push(folder.to_string());
2995            }
2996        }
2997    }
2998
2999    /// Give back folders that were removed again (the work never started).
3000    pub fn release<P: AsRef<std::path::Path>>(&self, folders: &[P]) {
3001        let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
3002        owned.retain(|kept| {
3003            !folders
3004                .iter()
3005                .any(|folder| std::path::Path::new(kept) == folder.as_ref())
3006        });
3007    }
3008
3009    /// The folders, as claimed.
3010    pub fn list(&self) -> Vec<String> {
3011        self.0.read().unwrap_or_else(|e| e.into_inner()).clone()
3012    }
3013
3014    /// Where a call's declared writes land that does not exist yet, taken
3015    /// just before it runs: what it may create. Once it succeeded,
3016    /// [`Self::claim_created`] claims each that it did create as a folder.
3017    pub fn absent_write_targets(effects: &aidaemon_core::CallEffects) -> Vec<std::path::PathBuf> {
3018        effects
3019            .keys
3020            .iter()
3021            .filter(|key| key.class == aidaemon_core::EffectClass::Write)
3022            .map(|key| std::path::PathBuf::from(shellexpand::tilde(key.target.trim()).as_ref()))
3023            .filter(|path| path.is_absolute() && std::fs::symlink_metadata(path).is_err())
3024            .collect()
3025    }
3026
3027    /// Ownership from evidence of creation: of `absent` (taken before a
3028    /// call that then succeeded), each path that is now a folder was made
3029    /// by this request's work (`mkdir`, a project tool's init in a new
3030    /// path), so it joins the request's owned folders, as a spawn's
3031    /// declared `new_folders` do (live 2026-11-13: two helpers each created
3032    /// their site's folder without declaring it, and every later change
3033    /// there was judged as someone else's project). A folder that existed
3034    /// before never joins. Returns what it claimed.
3035    pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
3036        let created: Vec<String> = absent
3037            .iter()
3038            .filter(|path| {
3039                std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir())
3040            })
3041            .map(|path| path.display().to_string())
3042            .collect();
3043        self.claim(&created);
3044        created
3045    }
3046}
3047
3048#[cfg(test)]
3049mod owned_folder_tests {
3050    use super::OwnedFolders;
3051
3052    /// A folder a succeeded call created joins the request's own; one that
3053    /// existed before it does not, and neither does a file it wrote.
3054    #[test]
3055    fn a_folder_a_call_created_becomes_owned() {
3056        let base = tempfile::tempdir().unwrap();
3057        let fresh = base.path().join("claude-drupal-11");
3058        let file = base.path().join("notes.txt");
3059        let before = base.path().join("existing-site");
3060        std::fs::create_dir(&before).unwrap();
3061        let key = |path: &std::path::Path| aidaemon_core::EffectKey {
3062            class: aidaemon_core::EffectClass::Write,
3063            target: path.display().to_string(),
3064        };
3065        let effects = aidaemon_core::CallEffects {
3066            keys: vec![key(&fresh), key(&file), key(&before)],
3067            complete: false,
3068            understood: true,
3069        };
3070        let absent = OwnedFolders::absent_write_targets(&effects);
3071        assert_eq!(absent, vec![fresh.clone(), file.clone()]);
3072        std::fs::create_dir(&fresh).unwrap();
3073        std::fs::write(&file, "x").unwrap();
3074        let owned = OwnedFolders::default();
3075        assert_eq!(
3076            owned.claim_created(&absent),
3077            vec![fresh.display().to_string()]
3078        );
3079        assert_eq!(owned.list(), vec![fresh.display().to_string()]);
3080    }
3081}
3082
3083/// Whether absolute `path` resolves inside one of `folders`, by the one
3084/// path resolver every scope check uses (`aidaemon_policies::resolves_within`).
3085pub fn within_owned(path: &str, folders: &[String]) -> bool {
3086    let expanded = shellexpand::tilde(path.trim()).into_owned();
3087    let path = std::path::Path::new(&expanded);
3088    path.is_absolute()
3089        && folders.iter().any(|folder| {
3090            aidaemon_policies::resolves_within(path, std::path::Path::new(folder.trim()))
3091        })
3092}
3093
3094/// How one of a request's files came to be, when the request's own work
3095/// produced it ([`ProducedFiles`]).
3096#[derive(Debug, Clone, PartialEq, Eq)]
3097pub enum ProducedFile {
3098    /// A capture one of the request's calls saved, showing `kind` (a
3099    /// browser screenshot shows its page).
3100    Capture(DeliverableKind),
3101    /// A file one of the request's calls created where nothing was before.
3102    Created,
3103}
3104
3105impl ProducedFile {
3106    /// What it is, in plain words for the untrusted-call check.
3107    pub fn words(&self) -> String {
3108        match self {
3109            Self::Capture(kind) => format!("this request's own capture: {}", kind.words()),
3110            Self::Created => "a file this request's own work created".to_string(),
3111        }
3112    }
3113}
3114
3115/// The files a request's own work produced, shared by every run of its
3116/// tree, from evidence rather than anyone's account of them: a capture a
3117/// tool noted as it saved it, and a file a succeeded call created where
3118/// its declared write found nothing before ([`Self::claim_created`], the
3119/// file counterpart of [`OwnedFolders::claim_created`]). Each is the
3120/// request's own artifact wherever it is saved (a capture lands in the
3121/// daemon's inbox, outside any project). Keyed by the resolved path, and a
3122/// capture also by its resource id, so either handle a later call names
3123/// finds it. A planning and effect fact, never a trust source for what the
3124/// file holds.
3125#[derive(Debug, Clone, Default)]
3126pub struct ProducedFiles(
3127    std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, ProducedFile>>>,
3128);
3129
3130impl ProducedFiles {
3131    /// A capture was saved at `path` (with `resource_id`, when it has one)
3132    /// and shows `kind`.
3133    pub fn note_capture(&self, path: &str, resource_id: Option<&str>, kind: &DeliverableKind) {
3134        let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3135        let capture = ProducedFile::Capture(kind.clone());
3136        produced.insert(produced_key(path), capture.clone());
3137        if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
3138            produced.insert(id.to_string(), capture);
3139        }
3140    }
3141
3142    /// A tool of the request made the file at `path` itself (with
3143    /// `resource_id`, when it has one): a generated image saved to the
3144    /// daemon's inbox. A capture already noted keeps what it shows.
3145    pub fn note_created(&self, path: &str, resource_id: Option<&str>) {
3146        let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3147        produced
3148            .entry(produced_key(path))
3149            .or_insert(ProducedFile::Created);
3150        if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
3151            produced
3152                .entry(id.to_string())
3153                .or_insert(ProducedFile::Created);
3154        }
3155    }
3156
3157    /// Ownership from evidence of creation: of `absent` (taken before a
3158    /// call that then succeeded, [`OwnedFolders::absent_write_targets`]),
3159    /// each path that is now a regular file was made by this request's
3160    /// work. A file that existed before never joins, and a capture already
3161    /// noted keeps what it shows. Returns what it claimed.
3162    pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
3163        let created: Vec<String> = absent
3164            .iter()
3165            .filter(|path| std::fs::symlink_metadata(path).is_ok_and(|meta| meta.is_file()))
3166            .map(|path| path.display().to_string())
3167            .collect();
3168        let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3169        for path in &created {
3170            produced
3171                .entry(produced_key(path))
3172                .or_insert(ProducedFile::Created);
3173        }
3174        created
3175    }
3176
3177    /// What the request's work produced at `target` (a path, or a
3178    /// capture's resource id), when it produced it.
3179    pub fn get(&self, target: &str) -> Option<ProducedFile> {
3180        self.0
3181            .read()
3182            .unwrap_or_else(|e| e.into_inner())
3183            .get(&produced_key(target))
3184            .cloned()
3185    }
3186
3187    /// What the capture saved at `path` shows, when one was noted: a later
3188    /// `send_file` of that path delivers that kind, not a file of its own.
3189    pub fn capture_kind(&self, path: &str) -> Option<DeliverableKind> {
3190        match self.get(path)? {
3191            ProducedFile::Capture(kind) => Some(kind),
3192            ProducedFile::Created => None,
3193        }
3194    }
3195
3196    /// Every handle noted, each a path or a capture's resource id, with
3197    /// what it is.
3198    pub fn entries(&self) -> Vec<(String, ProducedFile)> {
3199        self.0
3200            .read()
3201            .unwrap_or_else(|e| e.into_inner())
3202            .iter()
3203            .map(|(key, file)| (key.clone(), file.clone()))
3204            .collect()
3205    }
3206
3207    /// Of the files and resources a call names (its
3208    /// [`ToolSemantics::named_files`]), the ones this request's work
3209    /// produced, each as named.
3210    pub fn named_by(&self, named: &[String]) -> Vec<(String, ProducedFile)> {
3211        named
3212            .iter()
3213            .filter_map(|name| Some((name.clone(), self.get(name)?)))
3214            .collect()
3215    }
3216}
3217
3218/// The files and resources a call names by its declared facts (see
3219/// [`ToolSemantics::named_files`]): its path and resource-id target hints,
3220/// its access manifest's path targets, and its path effects' targets.
3221pub fn declared_named_files<T: ToolSemantics + ?Sized>(tool: &T, arguments: &str) -> Vec<String> {
3222    let mut named: Vec<String> = Vec::new();
3223    let mut add = |value: &str| {
3224        let value = value.trim();
3225        if !value.is_empty() && !named.iter().any(|known| known == value) {
3226            named.push(value.to_string());
3227        }
3228    };
3229    for hint in tool.call_semantics(arguments).target_hints {
3230        if matches!(
3231            hint.kind,
3232            ToolTargetHintKind::Path | ToolTargetHintKind::ResourceId
3233        ) {
3234            add(&hint.value);
3235        }
3236    }
3237    let manifest = tool.call_access_manifest(arguments);
3238    for hint in manifest
3239        .read_targets
3240        .iter()
3241        .chain(manifest.write_targets.iter())
3242    {
3243        if hint.kind == ToolTargetHintKind::Path {
3244            add(&hint.value);
3245        }
3246    }
3247    for key in tool.call_effects(arguments).keys {
3248        if matches!(
3249            key.class,
3250            aidaemon_core::EffectClass::Write
3251                | aidaemon_core::EffectClass::Delete
3252                | aidaemon_core::EffectClass::Configuration
3253        ) {
3254            add(&key.target);
3255        }
3256    }
3257    named
3258}
3259
3260/// A produced file's key, whichever spelling names it: a path as it
3261/// resolves on disk (when it does), anything else (a resource id) as given.
3262fn produced_key(target: &str) -> String {
3263    let expanded = shellexpand::tilde(target.trim()).into_owned();
3264    dunce::canonicalize(&expanded)
3265        .map(|path| path.to_string_lossy().into_owned())
3266        .unwrap_or(expanded)
3267}
3268
3269/// The request's produced files, carried in [`ToolCallContext::extensions`]
3270/// by a host that keeps them.
3271pub fn produced_files(facts: &ToolCallContext) -> Option<&ProducedFiles> {
3272    facts.extensions.get::<ProducedFiles>()
3273}
3274
3275#[cfg(test)]
3276mod produced_file_tests {
3277    use super::{DeliverableKind, ProducedFile, ProducedFiles};
3278
3279    /// A file a tool made itself (a generated image in the inbox) is the
3280    /// request's own by its path and by its resource id; a capture noted
3281    /// at that path keeps what it shows.
3282    #[test]
3283    fn a_file_a_tool_made_is_the_requests_own_by_path_and_id() {
3284        let produced = ProducedFiles::default();
3285        produced.note_created("/inbox/018d9d29_generated_image.png", Some("res_img"));
3286        assert_eq!(
3287            produced.get("/inbox/018d9d29_generated_image.png"),
3288            Some(ProducedFile::Created)
3289        );
3290        assert_eq!(produced.get("res_img"), Some(ProducedFile::Created));
3291        let page = DeliverableKind::Screenshot {
3292            page: "demo.ddev.site".to_string(),
3293        };
3294        produced.note_capture("/inbox/shot.png", None, &page);
3295        produced.note_created("/inbox/shot.png", None);
3296        assert_eq!(produced.capture_kind("/inbox/shot.png"), Some(page));
3297    }
3298
3299    /// A capture is found by its path in any spelling and by its resource
3300    /// id; a file a call created joins, one that existed before does not,
3301    /// and a capture keeps what it shows.
3302    #[test]
3303    fn the_requests_own_files_come_from_evidence() {
3304        let base = tempfile::tempdir().unwrap();
3305        let shot = base.path().join("ea19c410_screenshot.png");
3306        std::fs::write(&shot, b"png").unwrap();
3307        let page = DeliverableKind::Screenshot {
3308            page: "claude-drupal.ddev.site".to_string(),
3309        };
3310        let produced = ProducedFiles::default();
3311        produced.note_capture(&shot.display().to_string(), Some("res_1"), &page);
3312        let spelled = base
3313            .path()
3314            .join(".")
3315            .join("ea19c410_screenshot.png")
3316            .display()
3317            .to_string();
3318        assert_eq!(produced.capture_kind(&spelled), Some(page.clone()));
3319        assert_eq!(
3320            produced.get("res_1"),
3321            Some(ProducedFile::Capture(page.clone()))
3322        );
3323
3324        let fresh = base.path().join("report.md");
3325        let older = base.path().join("notes.md");
3326        std::fs::write(&older, "x").unwrap();
3327        let absent = vec![fresh.clone(), shot.clone()];
3328        std::fs::write(&fresh, "x").unwrap();
3329        assert_eq!(produced.claim_created(&absent).len(), 2);
3330        assert_eq!(
3331            produced.get(&fresh.display().to_string()),
3332            Some(ProducedFile::Created)
3333        );
3334        assert_eq!(
3335            produced.capture_kind(&shot.display().to_string()),
3336            Some(page)
3337        );
3338        assert_eq!(produced.get(&older.display().to_string()), None);
3339
3340        let named = produced.named_by(&[older.display().to_string(), fresh.display().to_string()]);
3341        assert_eq!(named.len(), 1);
3342        assert_eq!(named[0].1, ProducedFile::Created);
3343    }
3344}
3345
3346/// The owner's trusted file roots for one turn. A path is trusted only when
3347/// it normalizes without escaping and equals a root or sits below it. A
3348/// relative path resolves against `cwd` (where the file tools resolve it);
3349/// without one it is never trusted.
3350///
3351/// `owned` are the folders the request's work made for itself
3352/// ([`OwnedFolders`]): an effect landing there is the work's own
3353/// ([`Self::holds_effect`]), but what is read there is not trusted for it.
3354pub struct TrustRoots<'a> {
3355    roots: &'a [String],
3356    owned: &'a [String],
3357    cwd: Option<&'a str>,
3358}
3359
3360impl<'a> TrustRoots<'a> {
3361    pub fn new(roots: &'a [String]) -> Self {
3362        Self {
3363            roots,
3364            owned: &[],
3365            cwd: None,
3366        }
3367    }
3368
3369    /// The folders the request's work made for itself.
3370    pub fn with_owned(mut self, owned: &'a [String]) -> Self {
3371        self.owned = owned;
3372        self
3373    }
3374
3375    /// Resolve relative paths against `cwd` (an absolute directory).
3376    pub fn with_cwd(mut self, cwd: Option<&'a str>) -> Self {
3377        self.cwd = cwd;
3378        self
3379    }
3380
3381    /// The same roots with relative paths resolved against `cwd` instead
3382    /// (a call that runs in its own directory).
3383    pub fn anchored_at<'b>(&'b self, cwd: Option<&'b str>) -> TrustRoots<'b> {
3384        TrustRoots {
3385            roots: self.roots,
3386            owned: self.owned,
3387            cwd,
3388        }
3389    }
3390
3391    /// Whether an effect (a change, a delete) on `path` stays with the
3392    /// owner's own things: inside a trusted root, or inside a folder the
3393    /// request's work made for itself. Never a statement about trusting
3394    /// what is read there ([`Self::contains`] is).
3395    pub fn holds_effect(&self, path: &str) -> bool {
3396        if self.contains(path) {
3397            return true;
3398        }
3399        let resolved = match self.cwd {
3400            Some(cwd) if !is_absolute_or_home(path) => {
3401                format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
3402            }
3403            _ => path.to_string(),
3404        };
3405        within_owned(&resolved, self.owned)
3406    }
3407
3408    /// Whether `path` is inside a folder the request's work made for
3409    /// itself (not merely inside a trusted root).
3410    pub fn owns(&self, path: &str) -> bool {
3411        within_owned(path, self.owned)
3412    }
3413
3414    /// The directory relative paths resolve against, if any.
3415    pub fn cwd(&self) -> Option<&str> {
3416        self.cwd
3417    }
3418
3419    pub fn contains(&self, path: &str) -> bool {
3420        let resolved = match self.cwd {
3421            Some(cwd) if !is_absolute_or_home(path) => {
3422                format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
3423            }
3424            _ => path.to_string(),
3425        };
3426        let Some(path) = resolve_absolute(&resolved) else {
3427            return false;
3428        };
3429        self.roots
3430            .iter()
3431            .any(|root| resolve_absolute(root).is_some_and(|root| path.starts_with(&root)))
3432    }
3433}
3434
3435/// Output trust of a file read: the owner's own files (inside the trusted
3436/// roots) are `Trusted`; anything else, or a call whose first present path
3437/// argument in `keys` is missing, is someone else's content.
3438pub fn file_output_trust(
3439    arguments: &str,
3440    keys: &[&str],
3441    roots: &TrustRoots<'_>,
3442) -> aidaemon_core::SourceTrust {
3443    let args = serde_json::from_str::<Value>(arguments).ok();
3444    let path = args.as_ref().and_then(|args| {
3445        keys.iter()
3446            .find_map(|key| args.get(*key).and_then(Value::as_str))
3447    });
3448    match path {
3449        Some(path) if roots.contains(path) => aidaemon_core::SourceTrust::Trusted,
3450        _ => aidaemon_core::SourceTrust::Untrusted,
3451    }
3452}
3453
3454/// Expand `~`, then resolve the path the way the filesystem will: every
3455/// existing prefix through its symlinks (a link inside a root that points
3456/// elsewhere leaves the root), the rest lexically. `None` for a relative
3457/// path or one whose `..` climbs above the root.
3458fn resolve_absolute(path: &str) -> Option<std::path::PathBuf> {
3459    use std::path::{Component, PathBuf};
3460    let expanded = shellexpand::tilde(path.trim()).into_owned();
3461    let path = std::path::Path::new(&expanded);
3462    if !path.is_absolute() {
3463        return None;
3464    }
3465    let mut resolved = PathBuf::new();
3466    let mut existing = true;
3467    for component in path.components() {
3468        match component {
3469            Component::CurDir => {}
3470            Component::ParentDir => {
3471                if !resolved.pop() {
3472                    return None;
3473                }
3474            }
3475            Component::Normal(part) => {
3476                resolved.push(part);
3477                if existing {
3478                    match dunce::canonicalize(&resolved) {
3479                        Ok(canonical) => resolved = canonical,
3480                        Err(_) => existing = false,
3481                    }
3482                }
3483            }
3484            other => resolved.push(other.as_os_str()),
3485        }
3486    }
3487    Some(resolved)
3488}
3489
3490fn is_absolute_or_home(path: &str) -> bool {
3491    let path = path.trim();
3492    // `has_root`: on Windows `\etc\hosts` is on the current drive, not
3493    // under the working directory (and, with no drive, never trusted).
3494    let path_ref = std::path::Path::new(path);
3495    path.starts_with('~') || path_ref.is_absolute() || path_ref.has_root()
3496}
3497
3498/// Validated, canonical tool input. This is the boundary object shared by
3499/// policy, retry, dispatch, and receipt projection; raw model JSON is not an
3500/// execution fact.
3501#[derive(Debug, Clone, PartialEq, Eq)]
3502pub struct PreparedToolInvocation {
3503    pub canonical_arguments: String,
3504    pub semantics: ToolCallSemantics,
3505    pub access_manifest: ToolCallAccessManifest,
3506    pub receipt_kind: ToolReceiptKind,
3507}
3508
3509/// Produce the single typed invocation object consumed by the execution
3510/// control plane. Validation deliberately precedes semantics and access
3511/// derivation so a rejected proposal can never acquire intended effects.
3512pub fn prepare_invocation<T: ToolSemantics + ?Sized>(
3513    tool: &T,
3514    arguments: &str,
3515) -> Result<PreparedToolInvocation, ToolArgumentContractViolation> {
3516    let canonical_arguments = tool.canonicalize_arguments(arguments)?;
3517    tool.validate_arguments(&canonical_arguments)?;
3518    Ok(PreparedToolInvocation {
3519        semantics: tool.call_semantics(&canonical_arguments),
3520        access_manifest: tool.call_access_manifest(&canonical_arguments),
3521        receipt_kind: tool.receipt_kind(&canonical_arguments),
3522        canonical_arguments,
3523    })
3524}
3525
3526#[cfg(test)]
3527mod file_trust_tests {
3528    use super::{TrustRoots, file_output_trust};
3529    use aidaemon_core::SourceTrust::{Trusted, Untrusted};
3530
3531    #[test]
3532    fn files_inside_the_trusted_roots_are_trusted() {
3533        let roots = vec!["/tmp/aidaemon-test/ws".to_string()];
3534        let roots = TrustRoots::new(&roots);
3535        let keys = ["path", "file_path"];
3536        assert_eq!(
3537            file_output_trust(r#"{"path":"/tmp/aidaemon-test/ws/a.txt"}"#, &keys, &roots),
3538            Trusted
3539        );
3540        assert_eq!(
3541            file_output_trust(
3542                r#"{"file_path":"/tmp/aidaemon-test/ws/a.txt"}"#,
3543                &keys,
3544                &roots
3545            ),
3546            Trusted
3547        );
3548        assert_eq!(
3549            file_output_trust(r#"{"path":"/etc/hosts"}"#, &keys, &roots),
3550            Untrusted
3551        );
3552        assert_eq!(file_output_trust(r#"{}"#, &keys, &roots), Untrusted);
3553        assert_eq!(file_output_trust("not json", &keys, &roots), Untrusted);
3554    }
3555}
3556
3557fn is_zero(value: &usize) -> bool {
3558    *value == 0
3559}
3560
3561#[cfg(test)]
3562mod local_write_satisfaction_tests {
3563    use super::ToolMutationEffects as E;
3564
3565    /// Workspace and derived writes close each other's plans; a source edit
3566    /// is proven only by a source write.
3567    #[test]
3568    fn local_write_labels_satisfy_each_other_except_source() {
3569        assert!(E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
3570        assert!(E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
3571        assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
3572        assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
3573        assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
3574        assert!(!E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
3575        assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::EXTERNAL_DELIVERY));
3576    }
3577}