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#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
834#[serde(rename_all = "snake_case")]
835pub enum ToolSemanticFacet {
836    /// Legacy coarse goal-state capability. New exact observations should use
837    /// the narrow facet that was actually returned.
838    GoalState,
839    Schedule,
840    RunState,
841    Recovery,
842    Control,
843    Measurement,
844    Authorization,
845    Ownership,
846}
847
848impl ToolSemanticFacet {
849    pub const PROTOCOL_NAMES: [&'static str; 8] = [
850        Self::GoalState.as_str(),
851        Self::Schedule.as_str(),
852        Self::RunState.as_str(),
853        Self::Recovery.as_str(),
854        Self::Control.as_str(),
855        Self::Measurement.as_str(),
856        Self::Authorization.as_str(),
857        Self::Ownership.as_str(),
858    ];
859
860    pub const fn as_str(self) -> &'static str {
861        match self {
862            Self::GoalState => "goal_state",
863            Self::Schedule => "schedule",
864            Self::RunState => "run_state",
865            Self::Recovery => "recovery",
866            Self::Control => "control",
867            Self::Measurement => "measurement",
868            Self::Authorization => "authorization",
869            Self::Ownership => "ownership",
870        }
871    }
872}
873
874/// Whether an adapter returned the whole requested collection. A truncated or
875/// otherwise partial list may prove facts about the subjects it contains, but
876/// it can never prove that another subject is absent.
877#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
878#[serde(rename_all = "snake_case")]
879pub enum ToolCollectionCompleteness {
880    #[default]
881    Unknown,
882    Partial,
883    Complete,
884}
885
886impl ToolCollectionCompleteness {
887    pub const fn satisfies(self, required: Self) -> bool {
888        matches!(required, Self::Unknown)
889            || matches!(required, Self::Partial) && matches!(self, Self::Partial | Self::Complete)
890            || matches!(required, Self::Complete) && matches!(self, Self::Complete)
891    }
892}
893
894/// One exact subject/facet tuple observed in a successful tool result. This is
895/// result evidence, not a capability prediction: adapters populate it only
896/// after domain I/O has returned.
897#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
898pub struct ToolObservationEvidence {
899    pub subject: ToolTargetHint,
900    #[serde(default, skip_serializing_if = "Vec::is_empty")]
901    pub facets: Vec<ToolSemanticFacet>,
902    /// Collections from which this row was selected. Membership is lineage;
903    /// absence still requires a separate complete collection observation.
904    #[serde(default, skip_serializing_if = "Vec::is_empty")]
905    pub source_collections: Vec<ToolTargetHint>,
906}
907
908impl ToolObservationEvidence {
909    pub fn new(subject: ToolTargetHint, facets: &[ToolSemanticFacet]) -> Self {
910        Self {
911            subject,
912            facets: facets.to_vec(),
913            source_collections: Vec::new(),
914        }
915    }
916
917    pub fn with_source_collection(mut self, collection: ToolTargetHint) -> Self {
918        if !self.source_collections.contains(&collection) {
919            self.source_collections.push(collection);
920        }
921        self
922    }
923}
924
925/// Exact coverage of one collection returned by an adapter. `members` contains
926/// stable identities, never display labels. Only `Complete` coverage can prove
927/// non-membership; counts remain audit facts and are not interpreted as proof
928/// on their own.
929#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
930pub struct ToolCollectionObservation {
931    pub collection: ToolTargetHint,
932    #[serde(default, skip_serializing_if = "Vec::is_empty")]
933    pub facets: Vec<ToolSemanticFacet>,
934    #[serde(default)]
935    pub completeness: ToolCollectionCompleteness,
936    #[serde(default)]
937    pub returned_count: usize,
938    #[serde(default, skip_serializing_if = "Option::is_none")]
939    pub total_count: Option<usize>,
940    #[serde(default, skip_serializing_if = "Vec::is_empty")]
941    pub members: Vec<ToolTargetHint>,
942}
943
944impl ToolCollectionObservation {
945    pub fn complete(
946        collection: ToolTargetHint,
947        facets: &[ToolSemanticFacet],
948        members: Vec<ToolTargetHint>,
949    ) -> Self {
950        let returned_count = members.len();
951        Self {
952            collection,
953            facets: facets.to_vec(),
954            completeness: ToolCollectionCompleteness::Complete,
955            returned_count,
956            total_count: Some(returned_count),
957            members,
958        }
959    }
960}
961
962/// A receipt subject an adapter reports verbatim, published ahead of any call
963/// so the executor's checklist can bind to identities that receipts will
964/// actually carry. A checklist target outside every advertised subject and
965/// member namespace can never be credited, so the checklist tool refuses to
966/// compile it into an exact obligation.
967#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
968pub struct StableObservationSubject {
969    /// Exact `ResourceId` the adapter reports for a fixed collection or
970    /// singleton subject, when that identity is known before the call.
971    #[serde(default, skip_serializing_if = "Option::is_none")]
972    pub resource_id: Option<String>,
973    /// Facets a receipt for this subject or its members can carry.
974    #[serde(default, skip_serializing_if = "Vec::is_empty")]
975    pub facets: Vec<ToolSemanticFacet>,
976    /// `ResourceId` prefixes of exact member identities the adapter or the
977    /// runtime mints (for example `auth_profile:`). A value under a prefix is
978    /// exact and is credited only by a receipt naming it.
979    #[serde(default, skip_serializing_if = "Vec::is_empty")]
980    pub member_namespaces: Vec<String>,
981    /// Short model-facing meaning of the subject.
982    pub summary: String,
983}
984
985impl StableObservationSubject {
986    pub fn collection(
987        resource_id: impl Into<String>,
988        facets: &[ToolSemanticFacet],
989        member_namespace: impl Into<String>,
990        summary: impl Into<String>,
991    ) -> Self {
992        Self {
993            resource_id: Some(resource_id.into()),
994            facets: facets.to_vec(),
995            member_namespaces: vec![member_namespace.into()],
996            summary: summary.into(),
997        }
998    }
999
1000    pub fn namespace(prefix: impl Into<String>, summary: impl Into<String>) -> Self {
1001        Self {
1002            resource_id: None,
1003            facets: Vec::new(),
1004            member_namespaces: vec![prefix.into()],
1005            summary: summary.into(),
1006        }
1007    }
1008
1009    /// Whether `value` is this subject itself or an exact member under one of
1010    /// its namespaces. A bare prefix with nothing after it is not a member.
1011    pub fn binds(&self, value: &str) -> bool {
1012        self.resource_id.as_deref() == Some(value)
1013            || self
1014                .member_namespaces
1015                .iter()
1016                .any(|prefix| value.len() > prefix.len() && value.starts_with(prefix.as_str()))
1017    }
1018}
1019
1020/// Canonical adapter operation used by deterministic operation-scoped policy.
1021/// Unknown/new HTTP verbs deliberately remain untyped and therefore cannot
1022/// match a delegated mandate scope.
1023#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1024#[serde(rename_all = "UPPERCASE")]
1025pub enum ToolCallOperation {
1026    Get,
1027    Head,
1028    Options,
1029    Post,
1030    Put,
1031    Patch,
1032    Delete,
1033}
1034
1035impl ToolCallOperation {
1036    pub const fn from_http_method(method: &str) -> Option<Self> {
1037        match method.as_bytes() {
1038            b"GET" => Some(Self::Get),
1039            b"HEAD" => Some(Self::Head),
1040            b"OPTIONS" => Some(Self::Options),
1041            b"POST" => Some(Self::Post),
1042            b"PUT" => Some(Self::Put),
1043            b"PATCH" => Some(Self::Patch),
1044            b"DELETE" => Some(Self::Delete),
1045            _ => None,
1046        }
1047    }
1048}
1049
1050/// Structured completion semantics for a specific tool call.
1051#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1052pub struct ToolCallSemantics {
1053    #[serde(default)]
1054    pub effect: ToolCallEffect,
1055    #[serde(default)]
1056    pub verification_mode: ToolVerificationMode,
1057    /// Fine-grained mutation effects. Older persisted rows omit this field and
1058    /// continue to deserialize through the default empty set.
1059    #[serde(default, skip_serializing_if = "ToolMutationEffects::is_empty")]
1060    pub mutation_effects: ToolMutationEffects,
1061    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1062    pub target_hints: Vec<ToolTargetHint>,
1063    /// Adapter-defined canonical operation for policy matching. This is an
1064    /// exact, typed identifier (for example `GET` or `POST`), not a natural-
1065    /// language action inferred by the policy layer.
1066    #[serde(default, skip_serializing_if = "Option::is_none")]
1067    pub operation: Option<ToolCallOperation>,
1068    /// Typed claim-support affordances for this exact call/result. These are
1069    /// persisted in the durable receipt so recovery and completion do not have
1070    /// to reconstruct evidence from prose.
1071    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1072    pub evidence: Vec<ToolEvidenceCapability>,
1073}
1074
1075/// Prepared filesystem access requested by one exact tool call.
1076///
1077/// Execution location, readable context, and mutation authority are different
1078/// roles. Keeping them separate prevents a read-only working directory from
1079/// becoming an implied write grant and gives adapters one canonical contract
1080/// to enforce and persist.
1081#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1082pub struct ToolCallAccessManifest {
1083    #[serde(default, skip_serializing_if = "Option::is_none")]
1084    pub execution_cwd: Option<String>,
1085    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1086    pub read_targets: Vec<ToolTargetHint>,
1087    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1088    pub write_targets: Vec<ToolTargetHint>,
1089    /// Immutable capabilities owned by the adapter itself (for example the
1090    /// system executable roots a confined terminal needs to start a process).
1091    /// These are deliberately separate from task data grants: callers may use
1092    /// them for runtime loading, but they do not authorize arbitrary user
1093    /// paths or writes and are never inferred from command prose.
1094    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1095    pub adapter_read_targets: Vec<ToolTargetHint>,
1096}
1097
1098impl ToolCallSemantics {
1099    /// These semantics plus a change static inspection cannot type: still
1100    /// the observation they were, now also a mutation (`UNSPECIFIED`, which
1101    /// proves only the checklist items the call carries out).
1102    pub fn with_untyped_change(&self) -> Self {
1103        let mut changed = self.clone();
1104        changed.mutation_effects = changed
1105            .mutation_effects
1106            .union(ToolMutationEffects::UNSPECIFIED);
1107        changed.effect = if changed.observes_state() {
1108            ToolCallEffect::ObservationAndMutation
1109        } else {
1110            ToolCallEffect::Mutation
1111        };
1112        changed
1113    }
1114
1115    pub fn administrative() -> Self {
1116        Self {
1117            effect: ToolCallEffect::Administrative,
1118            ..Self::default()
1119        }
1120    }
1121
1122    pub fn observation() -> Self {
1123        Self {
1124            effect: ToolCallEffect::Observation,
1125            ..Self::default()
1126        }
1127    }
1128
1129    pub fn mutation() -> Self {
1130        Self {
1131            effect: ToolCallEffect::Mutation,
1132            mutation_effects: ToolMutationEffects::UNSPECIFIED,
1133            ..Self::default()
1134        }
1135    }
1136
1137    pub fn observation_and_mutation() -> Self {
1138        Self {
1139            effect: ToolCallEffect::ObservationAndMutation,
1140            mutation_effects: ToolMutationEffects::UNSPECIFIED,
1141            ..Self::default()
1142        }
1143    }
1144
1145    pub fn mutation_with(mutation_effects: ToolMutationEffects) -> Self {
1146        Self {
1147            effect: ToolCallEffect::Mutation,
1148            mutation_effects: if mutation_effects.is_empty() {
1149                ToolMutationEffects::UNSPECIFIED
1150            } else {
1151                mutation_effects
1152            },
1153            ..Self::default()
1154        }
1155    }
1156
1157    pub fn observation_and_mutation_with(mutation_effects: ToolMutationEffects) -> Self {
1158        Self {
1159            effect: ToolCallEffect::ObservationAndMutation,
1160            mutation_effects: if mutation_effects.is_empty() {
1161                ToolMutationEffects::UNSPECIFIED
1162            } else {
1163                mutation_effects
1164            },
1165            ..Self::default()
1166        }
1167    }
1168
1169    pub fn with_verification_mode(mut self, verification_mode: ToolVerificationMode) -> Self {
1170        self.verification_mode = verification_mode;
1171        self
1172    }
1173
1174    pub fn with_target_hint(mut self, kind: ToolTargetHintKind, value: impl Into<String>) -> Self {
1175        if let Some(target) = ToolTargetHint::new(kind, value) {
1176            self.target_hints.push(target);
1177        }
1178        self
1179    }
1180
1181    pub fn with_operation(mut self, operation: ToolCallOperation) -> Self {
1182        self.operation = Some(operation);
1183        self
1184    }
1185
1186    pub fn with_evidence(mut self, evidence: Vec<ToolEvidenceCapability>) -> Self {
1187        self.evidence = evidence;
1188        self
1189    }
1190
1191    pub fn observes_state(&self) -> bool {
1192        self.effect.observes_state()
1193    }
1194
1195    pub fn mutates_state(&self) -> bool {
1196        self.effect.mutates_state() || !self.mutation_effects.is_empty()
1197    }
1198
1199    pub fn can_verify_with_result_content(&self) -> bool {
1200        self.verification_mode == ToolVerificationMode::ResultContent
1201    }
1202
1203    pub fn is_empty(&self) -> bool {
1204        self.effect == ToolCallEffect::Unknown
1205            && self.verification_mode == ToolVerificationMode::None
1206            && self.mutation_effects.is_empty()
1207            && self.target_hints.is_empty()
1208            && self.operation.is_none()
1209            && self.evidence.is_empty()
1210    }
1211
1212    pub fn merge_missing_from(&mut self, fallback: Self) {
1213        if self.effect == ToolCallEffect::Unknown {
1214            self.effect = fallback.effect;
1215        }
1216        if self.verification_mode == ToolVerificationMode::None {
1217            self.verification_mode = fallback.verification_mode;
1218        }
1219        // An explicit observational effect is authoritative. Filling its empty
1220        // mutation bitset from a conservative pre-dispatch fallback would turn
1221        // a tool-enforced read-only execution back into a mutation receipt.
1222        if self.mutation_effects.is_empty()
1223            && (self.effect == ToolCallEffect::Unknown || self.effect.mutates_state())
1224        {
1225            self.mutation_effects = fallback.mutation_effects;
1226        }
1227        if self.target_hints.is_empty() {
1228            self.target_hints = fallback.target_hints;
1229        }
1230        if self.operation.is_none() {
1231            self.operation = fallback.operation;
1232        }
1233        if self.evidence.is_empty() {
1234            self.evidence = fallback.evidence;
1235        }
1236    }
1237}
1238
1239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1240#[serde(rename_all = "snake_case")]
1241pub enum ReadFileSelectionMetadata {
1242    Full,
1243    BoundedRange { start_line: usize, end_line: usize },
1244    OpenEndedRange { start_line: usize },
1245    Tail { requested_lines: usize },
1246}
1247
1248#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1249pub struct ReadFileResultMetadata {
1250    pub display_path: String,
1251    pub canonical_path: String,
1252    pub selection: ReadFileSelectionMetadata,
1253    pub returned_start_line: Option<usize>,
1254    pub returned_end_line: Option<usize>,
1255    pub total_lines: usize,
1256    pub file_size: u64,
1257    #[serde(skip_serializing_if = "Option::is_none")]
1258    pub modified: Option<String>,
1259    pub selected_lines: Vec<String>,
1260    /// True when the read returned fewer lines than requested because the
1261    /// per-call output cap was hit. The rendered output then carries an
1262    /// explicit continuation hint.
1263    #[serde(default)]
1264    pub truncated: bool,
1265}
1266
1267/// Structured record of tool-output truncation. Populated at the tool
1268/// boundary — the instructional notice text is rendered into the
1269/// model-visible message by the loop (single site), never embedded in the
1270/// tool's returned content, so text-scanning consumers (error-line
1271/// extraction, classifiers, summaries) always see clean output.
1272#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1273pub struct TruncationInfo {
1274    pub shown_chars: usize,
1275    pub total_chars: usize,
1276    /// Tool-specific remediation sentence (see `utils::truncation_notice_with_hint`).
1277    #[serde(default, skip_serializing_if = "Option::is_none")]
1278    pub remediation_hint: Option<String>,
1279}
1280
1281/// Whether a particular retained view contains the authoritative tool result.
1282#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1283#[serde(rename_all = "snake_case")]
1284pub enum ToolResultCompleteness {
1285    Complete,
1286    Truncated,
1287    #[default]
1288    Unavailable,
1289}
1290
1291impl ToolResultCompleteness {
1292    pub const fn as_str(self) -> &'static str {
1293        match self {
1294            Self::Complete => "complete",
1295            Self::Truncated => "truncated",
1296            Self::Unavailable => "unavailable",
1297        }
1298    }
1299}
1300
1301/// Origin of the bytes represented by a durable observation receipt.
1302#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1303#[serde(rename_all = "snake_case")]
1304pub enum ToolResultContentSource {
1305    ToolOutput,
1306    DurableReplay,
1307    SpillPreview,
1308    PersistentSummary,
1309    #[default]
1310    Unavailable,
1311}
1312
1313impl ToolResultContentSource {
1314    pub const fn as_str(self) -> &'static str {
1315        match self {
1316            Self::ToolOutput => "tool_output",
1317            Self::DurableReplay => "durable_replay",
1318            Self::SpillPreview => "spill_preview",
1319            Self::PersistentSummary => "persistent_summary",
1320            Self::Unavailable => "unavailable",
1321        }
1322    }
1323}
1324
1325/// Content provenance shared by live completion and durable continuation.
1326/// The digest is computed over the authoritative pre-compression result; the
1327/// view-specific fields state exactly what the model and event log retained.
1328#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1329pub struct ToolResultProvenance {
1330    #[serde(default, skip_serializing_if = "Option::is_none")]
1331    pub result_id: Option<String>,
1332    #[serde(default, skip_serializing_if = "Option::is_none")]
1333    pub sha256: Option<String>,
1334    #[serde(default)]
1335    pub source: ToolResultContentSource,
1336    #[serde(default)]
1337    pub model_view_completeness: ToolResultCompleteness,
1338    #[serde(default)]
1339    pub durable_view_completeness: ToolResultCompleteness,
1340    #[serde(default)]
1341    pub authoritative_chars: usize,
1342    #[serde(default)]
1343    pub model_visible_chars: usize,
1344    #[serde(default)]
1345    pub durable_chars: usize,
1346    #[serde(default, skip_serializing_if = "Option::is_none")]
1347    pub requested_range: Option<ReadFileSelectionMetadata>,
1348    #[serde(default, skip_serializing_if = "Option::is_none")]
1349    pub returned_start_line: Option<usize>,
1350    #[serde(default, skip_serializing_if = "Option::is_none")]
1351    pub returned_end_line: Option<usize>,
1352}
1353
1354/// Deterministic credential/target readiness checked immediately before an
1355/// autonomous adapter is allowed to perform I/O. The accompanying durable
1356/// receipt carries the mandate grant, which binds this record to the stable
1357/// mandate identity and policy version without exposing credentials.
1358#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1359#[serde(rename_all = "snake_case")]
1360pub enum AuthorizationPreflightStatus {
1361    Ready,
1362    Blocked,
1363    Unverifiable,
1364}
1365
1366#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1367pub struct AuthorizationPreflightRecord {
1368    pub schema_version: u16,
1369    pub status: AuthorizationPreflightStatus,
1370    pub intended_operation: String,
1371    pub target_digest: String,
1372    #[serde(default, skip_serializing_if = "Option::is_none")]
1373    pub auth_profile: Option<String>,
1374    #[serde(default, skip_serializing_if = "Option::is_none")]
1375    pub account_id: Option<String>,
1376    /// Provider-declared OAuth scopes known at the readiness boundary. Static
1377    /// non-OAuth profiles legitimately leave this empty.
1378    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1379    pub authorized_scopes: Vec<String>,
1380    #[serde(default, skip_serializing_if = "Option::is_none")]
1381    pub credential_generation: Option<String>,
1382    #[serde(default, skip_serializing_if = "Option::is_none")]
1383    pub refresh_result: Option<String>,
1384    #[serde(default, skip_serializing_if = "Option::is_none")]
1385    pub reason_code: Option<String>,
1386    pub checked_at: String,
1387}
1388
1389impl AuthorizationPreflightRecord {
1390    pub const SCHEMA_VERSION: u16 = 1;
1391
1392    pub const fn permits_io(&self) -> bool {
1393        matches!(self.status, AuthorizationPreflightStatus::Ready)
1394    }
1395}
1396
1397impl ToolResultProvenance {
1398    pub fn from_authoritative_result(
1399        result: &str,
1400        metadata: &ToolCallMetadata,
1401        source: ToolResultContentSource,
1402    ) -> Self {
1403        use sha2::{Digest, Sha256};
1404
1405        let sha256 = hex::encode(Sha256::digest(result.as_bytes()));
1406        let chars = result.chars().count();
1407        let tool_truncated = metadata.truncation.is_some()
1408            || metadata
1409                .read_file
1410                .as_ref()
1411                .is_some_and(|read| read.truncated);
1412        let completeness = if tool_truncated {
1413            ToolResultCompleteness::Truncated
1414        } else {
1415            ToolResultCompleteness::Complete
1416        };
1417        let read = metadata.read_file.as_ref();
1418        Self {
1419            result_id: Some(format!("sha256:{sha256}")),
1420            sha256: Some(sha256),
1421            source,
1422            model_view_completeness: completeness,
1423            durable_view_completeness: completeness,
1424            authoritative_chars: chars,
1425            model_visible_chars: chars,
1426            durable_chars: chars,
1427            requested_range: read.map(|read| read.selection.clone()),
1428            returned_start_line: read.and_then(|read| read.returned_start_line),
1429            returned_end_line: read.and_then(|read| read.returned_end_line),
1430        }
1431    }
1432
1433    pub fn mark_model_view_truncated(&mut self, visible_result: &str) {
1434        self.model_visible_chars = visible_result.chars().count();
1435        self.model_view_completeness = ToolResultCompleteness::Truncated;
1436    }
1437
1438    pub fn record_durable_view(&mut self, durable_result: &str, is_summary: bool) {
1439        self.durable_chars = durable_result.chars().count();
1440        if is_summary {
1441            self.durable_view_completeness = ToolResultCompleteness::Truncated;
1442            self.source = ToolResultContentSource::PersistentSummary;
1443        } else {
1444            self.durable_view_completeness = self.model_view_completeness;
1445        }
1446    }
1447}
1448
1449/// Structured outcome of a tool invocation. This separates transport/execution
1450/// success from the domain result: a test runner can execute correctly while
1451/// reporting failing tests, and a lookup can complete with no matches.
1452#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1453#[serde(rename_all = "snake_case")]
1454pub enum ToolOutcomeStatus {
1455    Succeeded,
1456    CompletedWithNegativeResult,
1457    FailedRetryable,
1458    FailedPermanent,
1459    Blocked,
1460    Backgrounded,
1461}
1462
1463/// Where an invocation reached in the common execution pipeline.
1464///
1465/// This is deliberately orthogonal to [`ToolOutcomeStatus`]. A deterministic
1466/// argument rejection can be a completed validation observation, but it did
1467/// not dispatch the requested domain operation and therefore cannot inherit
1468/// that operation's effects, targets, or evidence capabilities.
1469#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1470#[serde(rename_all = "snake_case")]
1471pub enum ToolInvocationStage {
1472    /// Legacy receipt or adapter that did not report a stage.
1473    #[default]
1474    Unknown,
1475    /// The common policy/retry boundary refused dispatch.
1476    RejectedBeforeDispatch,
1477    /// The adapter rejected its typed argument contract before domain I/O.
1478    RejectedBeforeIo,
1479    /// The adapter was invoked for the prepared operation.
1480    Dispatched,
1481    /// The result was reconstructed from a durable prior receipt.
1482    Replayed,
1483}
1484
1485impl ToolInvocationStage {
1486    pub const fn as_str(self) -> &'static str {
1487        match self {
1488            Self::Unknown => "unknown",
1489            Self::RejectedBeforeDispatch => "rejected_before_dispatch",
1490            Self::RejectedBeforeIo => "rejected_before_io",
1491            Self::Dispatched => "dispatched",
1492            Self::Replayed => "replayed",
1493        }
1494    }
1495
1496    pub const fn reached_dispatch(self) -> bool {
1497        matches!(self, Self::Dispatched | Self::Replayed)
1498    }
1499
1500    /// True only for a newly executed adapter call. A durable replay carries
1501    /// evidence forward but does not consume another operation attempt.
1502    pub const fn performed_io(self) -> bool {
1503        matches!(self, Self::Dispatched)
1504    }
1505}
1506
1507/// Shape of the machine receipt produced by a tool invocation.
1508///
1509/// Completion predicates are compiled against this protocol type instead of
1510/// assuming every tool is a subprocess. In particular, an absent exit code on
1511/// a management/API receipt means "not applicable", not "the invocation did
1512/// not happen".
1513#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1514#[serde(rename_all = "snake_case")]
1515pub enum ToolReceiptKind {
1516    #[default]
1517    Generic,
1518    Process,
1519    Http,
1520}
1521
1522/// Strength of the boundary that enforced a tool's declared filesystem
1523/// manifest. This reports enforcement, not merely manifest presence.
1524#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1525#[serde(rename_all = "snake_case")]
1526pub enum ToolAccessEnforcement {
1527    /// Legacy or uninstrumented adapter; no enforcement claim is made.
1528    #[default]
1529    Unknown,
1530    /// The operation has no filesystem access contract.
1531    NotApplicable,
1532    /// A delegated sandbox adapter accepted the manifest.
1533    AdapterEnforced,
1534    /// The daemon controller rejected the proposal before adapter dispatch
1535    /// because it exceeded the compiled task capability.
1536    ControllerEnforced,
1537    /// The daemon installed a kernel-enforced policy from the exact manifest.
1538    KernelEnforced,
1539}
1540
1541/// Typed diagnostic emitted when a proposal is rejected by the controller or
1542/// an adapter is denied by its installed filesystem policy. This is audit
1543/// telemetry only; the manifest remains the authority and this record never
1544/// widens it.
1545#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1546pub struct ToolAccessDenial {
1547    pub reason_code: String,
1548    pub enforcement: ToolAccessEnforcement,
1549    #[serde(default, skip_serializing_if = "Option::is_none")]
1550    pub exit_code: Option<i32>,
1551    /// Evidence the refused operation WOULD have produced. A rejection
1552    /// receipt carries no observed evidence (nothing ran), but the run ledger
1553    /// needs to know which observation obligation the refusal was attempting
1554    /// to satisfy; that binding is proposal data, typed on the denial.
1555    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1556    pub proposed_evidence: Vec<ToolEvidenceCapability>,
1557}
1558
1559impl ToolOutcomeStatus {
1560    /// Normalize the execution backend's process status convention. Unix
1561    /// commands that exit normally produce a nonnegative code; the backend
1562    /// uses a negative sentinel when no normal exit status exists (for
1563    /// example, a sandbox kill). Such termination is not a completed negative
1564    /// predicate observation.
1565    pub const fn from_process_exit_code(code: i32) -> Self {
1566        if code == 0 {
1567            Self::Succeeded
1568        } else if code > 0 {
1569            Self::CompletedWithNegativeResult
1570        } else {
1571            Self::FailedPermanent
1572        }
1573    }
1574
1575    pub const fn as_str(self) -> &'static str {
1576        match self {
1577            Self::Succeeded => "succeeded",
1578            Self::CompletedWithNegativeResult => "completed_with_negative_result",
1579            Self::FailedRetryable => "failed_retryable",
1580            Self::FailedPermanent => "failed_permanent",
1581            Self::Blocked => "blocked",
1582            Self::Backgrounded => "backgrounded",
1583        }
1584    }
1585
1586    pub fn satisfies_requested_condition(self) -> bool {
1587        matches!(self, Self::Succeeded)
1588    }
1589
1590    pub fn is_failure(self) -> bool {
1591        matches!(
1592            self,
1593            Self::FailedRetryable | Self::FailedPermanent | Self::Blocked
1594        )
1595    }
1596}
1597
1598/// How the response layer should treat a successful tool result.
1599///
1600/// This is control-plane metadata, not a canned user response. Tools use it to
1601/// distinguish an owner-facing operational outcome from an explicitly
1602/// requested diagnostic view while leaving the wording to the model.
1603#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1604#[serde(rename_all = "snake_case")]
1605pub enum ToolResultPresentation {
1606    NaturalSummary,
1607    DiagnosticDetail,
1608}
1609
1610/// Structured execution metadata returned by tools.
1611///
1612/// This is intentionally minimal and backward-compatible: tools can continue
1613/// returning plain text while selectively populating structured fields.
1614#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1615pub struct ToolCallMetadata {
1616    /// Protocol family for fields whose applicability differs by adapter.
1617    /// The dispatcher stamps this from the registered tool before completion
1618    /// evaluation; tools do not need to repeat the declaration per result.
1619    #[serde(default)]
1620    pub receipt_kind: ToolReceiptKind,
1621    /// Effective filesystem access contract enforced for this invocation.
1622    /// This is an audit receipt, not a reusable authority grant.
1623    #[serde(default, skip_serializing_if = "Option::is_none")]
1624    pub access_manifest: Option<ToolCallAccessManifest>,
1625    /// Whether the declared access manifest was installed at an execution
1626    /// boundary. A populated manifest with `Unknown` is audit data only.
1627    #[serde(default)]
1628    pub access_enforcement: ToolAccessEnforcement,
1629    /// Kernel/adapter denial details when a dispatched process was prevented
1630    /// from opening a path. The declared manifest is retained separately.
1631    #[serde(default, skip_serializing_if = "Option::is_none")]
1632    pub access_denial: Option<ToolAccessDenial>,
1633    /// Authoritative domain outcome when the tool can provide one. Older tools
1634    /// may omit it; the loop then derives a conservative status from structured
1635    /// exit/HTTP/transport metadata before falling back to legacy text parsing.
1636    #[serde(default, skip_serializing_if = "Option::is_none")]
1637    pub outcome_status: Option<ToolOutcomeStatus>,
1638    /// Authoritative pipeline stage for this result. Completion and effect
1639    /// projection must never infer dispatch from intended call semantics.
1640    #[serde(default)]
1641    pub invocation_stage: ToolInvocationStage,
1642    /// The adapter deterministically rejected the invocation contract before
1643    /// performing domain I/O. This is an authoritative negative outcome, not
1644    /// evidence that the requested read/write itself occurred.
1645    #[serde(default)]
1646    pub contract_rejected: bool,
1647    /// Actual adapter that produced the result when dispatch was routed from
1648    /// the requested tool through another implementation.
1649    #[serde(default, skip_serializing_if = "Option::is_none")]
1650    pub effective_tool_name: Option<String>,
1651    /// True when the dispatcher reconstructed this outcome from a prior
1652    /// durable receipt instead of invoking the side effect again.
1653    #[serde(default)]
1654    pub receipt_replayed: bool,
1655    /// Process exit code when applicable (e.g. terminal/run_command style tools).
1656    #[serde(skip_serializing_if = "Option::is_none")]
1657    pub exit_code: Option<i32>,
1658    /// True when tool execution exceeded a timeout threshold.
1659    #[serde(default)]
1660    pub timed_out: bool,
1661    /// True when execution moved to background tracking.
1662    #[serde(default)]
1663    pub background_started: bool,
1664    /// True when the process is detached and intentionally long-lived.
1665    #[serde(default)]
1666    pub detached: bool,
1667    /// True when the tool guarantees automatic completion delivery for a
1668    /// backgrounded operation in the current run.
1669    #[serde(default)]
1670    pub completion_notifications_enabled: bool,
1671    /// Transport/runtime failure outside normal tool semantics.
1672    #[serde(skip_serializing_if = "Option::is_none")]
1673    pub transport_error: Option<String>,
1674    /// HTTP status code for API tools (http_request, web_fetch).
1675    /// Populated at the tool boundary — not scraped from result text.
1676    #[serde(default, skip_serializing_if = "Option::is_none")]
1677    pub http_status: Option<u16>,
1678    /// Canonical id of the resource a successful write created, read by the
1679    /// adapter from the response's machine format (JSON `/data/id` or `/id`)
1680    /// and validated as `[A-Za-z0-9_-]{1,64}`. Never model or prose text.
1681    #[serde(default, skip_serializing_if = "Option::is_none")]
1682    pub created_resource_id: Option<String>,
1683    /// Output truncation performed at the tool boundary. Rendered into the
1684    /// model-visible text by the loop after ledger/classifier consumption.
1685    #[serde(default, skip_serializing_if = "Option::is_none")]
1686    pub truncation: Option<TruncationInfo>,
1687    /// Strong provenance for the result body. Populated centrally by the tool
1688    /// dispatcher so individual adapters cannot silently omit it.
1689    #[serde(default, skip_serializing_if = "Option::is_none")]
1690    pub result_provenance: Option<ToolResultProvenance>,
1691    /// Exact pre-I/O authorization readiness for autonomous authenticated
1692    /// adapters. It is persisted with the receipt and never contains secrets.
1693    #[serde(default, skip_serializing_if = "Option::is_none")]
1694    pub authorization_preflight: Option<AuthorizationPreflightRecord>,
1695    /// The call handed the rest of the turn's work to a background job whose
1696    /// result reaches the session later (a launch moved to background
1697    /// tracking, a background sub-agent). Set with the call's finish by
1698    /// [`ToolCallOutcome::handed_to_background`]; unlike
1699    /// `background_started` it says nothing about the receipt's status.
1700    #[serde(default)]
1701    pub background_handoff: bool,
1702    /// The call observed the end of a background job a launch left running
1703    /// (a check that returned its finished result, or a cancel). The run
1704    /// pairs it with `background_started` launches to know whether work it
1705    /// handed off is still running when the model wants to stop.
1706    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1707    pub background_settled: bool,
1708    /// The names, as the owner reads them, of the runs this call left
1709    /// running in the background (a helper, a command, a CLI agent; every
1710    /// child of a batch call, in order): the turn's launch line names its
1711    /// runs from these, never from the call's text (live 2026-11-14: a
1712    /// batch of two named only its first child).
1713    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1714    pub background_run_labels: Vec<String>,
1715    /// The declared checklist items (their indices) this call took on: a
1716    /// launch hands them to the job it starts (`checklist_items`). Typed
1717    /// attribution of work to declared items, never read from text.
1718    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1719    pub checklist_items: Vec<usize>,
1720    /// How many runs this call launched, still working when it returned or
1721    /// run to their end within it (a batch launch starts one per child).
1722    /// Each run takes on its own work: a launch of two helpers that names no
1723    /// items is two attempts, never one. One run that names no items and
1724    /// ends within the call took on the whole request.
1725    #[serde(default, skip_serializing_if = "is_zero")]
1726    pub launched_runs: usize,
1727    /// The call changed something its semantics could not type (a write
1728    /// inside `docker exec` or `ssh`, judged from the command's structure):
1729    /// the runtime may attribute it to the one checklist item in progress.
1730    /// Never itself a typed change.
1731    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1732    pub changes_untyped: bool,
1733    /// Completion semantics for this specific tool call.
1734    #[serde(default, skip_serializing_if = "ToolCallSemantics::is_empty")]
1735    pub semantics: ToolCallSemantics,
1736    /// Exact subject/facet observations made by this dispatched result. These
1737    /// are intentionally separate from `ToolCallSemantics`: proposed call
1738    /// semantics must never become proof merely because dispatch was planned.
1739    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1740    pub observations: Vec<ToolObservationEvidence>,
1741    /// Collection membership and coverage observed by this dispatched result.
1742    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1743    pub collection_observations: Vec<ToolCollectionObservation>,
1744    /// Complete typed result for successful text-file reads.
1745    #[serde(skip_serializing_if = "Option::is_none")]
1746    pub read_file: Option<ReadFileResultMetadata>,
1747    /// Image (or other) files produced by the tool for agent vision context.
1748    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1749    pub attachments: Vec<MessageAttachment>,
1750    /// The runtime's own pre-dispatch preparation failed (for example
1751    /// materializing a declared write root), attributed to the exact argument
1752    /// declaration that caused it. Set only when no domain I/O ran.
1753    #[serde(default, skip_serializing_if = "Option::is_none")]
1754    pub runtime_preparation_failure: Option<Box<RuntimePreparationFailure>>,
1755    /// Preserve exact, untrusted bytes while still wrapping them as untrusted
1756    /// tool data. Intended for canonical-history evidence whose wording must
1757    /// not be rewritten by prompt-injection sanitization.
1758    #[serde(default)]
1759    pub untrusted_verbatim: bool,
1760    /// Keep bounded tool output inline and never write it to a temporary spill
1761    /// file or run lossy generic compression.
1762    #[serde(default)]
1763    pub preserve_inline: bool,
1764    /// Durable audit representation. The full output remains available to the
1765    /// current model turn, but only this stub is written to canonical events.
1766    #[serde(default, skip_serializing_if = "Option::is_none")]
1767    pub persistent_output: Option<String>,
1768    /// Do not copy result content into executor task-activity telemetry.
1769    #[serde(default)]
1770    pub suppress_activity_result: bool,
1771    /// Presentation policy for this result. `NaturalSummary` asks the response
1772    /// layer to communicate the user-level outcome without exposing control-
1773    /// plane bookkeeping. `DiagnosticDetail` is selected only when the caller
1774    /// explicitly requested those details.
1775    #[serde(default, skip_serializing_if = "Option::is_none")]
1776    pub presentation: Option<ToolResultPresentation>,
1777    /// Exact control-plane identifiers observed by the tool. They remain
1778    /// available to the agent/runtime but are omitted from a natural summary
1779    /// unless the owner supplied the same identifier or requested diagnostics.
1780    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1781    pub internal_identifiers: Vec<String>,
1782    /// Who authored this exact output, when the tool knows better than its
1783    /// declared `Tool::output_trust` (a delegated run reports whether it read
1784    /// untrusted content). The dispatcher stamps this over the declaration.
1785    #[serde(default, skip_serializing_if = "Option::is_none")]
1786    pub output_trust: Option<aidaemon_core::SourceTrust>,
1787}
1788
1789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1790pub struct ToolCallOutcome {
1791    pub output: String,
1792    #[serde(default)]
1793    pub metadata: ToolCallMetadata,
1794    /// The tool ends the run on this call, from its own typed outcome (never
1795    /// from argument or output text). The dispatcher hands it to the kernel
1796    /// as [`aidaemon_core::ToolOutput::finish`]; a finish without a reply
1797    /// ships the call's own output.
1798    #[serde(default, skip_serializing_if = "Option::is_none")]
1799    pub finish: Option<aidaemon_core::Finish>,
1800}
1801
1802/// A failure of the runtime's own pre-dispatch preparation, attributed to the
1803/// exact argument declaration that caused it. The dispatcher uses this to
1804/// decide whether the declaration was its own projection (repairable without
1805/// involving the model) or the model's (surfaced as a typed rejection).
1806#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1807pub struct RuntimePreparationFailure {
1808    /// Argument field the declaration came from (for example `write_roots`).
1809    pub field: String,
1810    /// The exact declared value.
1811    pub value: String,
1812    /// The underlying runtime error.
1813    pub error: String,
1814}
1815
1816impl ToolCallOutcome {
1817    pub fn from_output(output: String) -> Self {
1818        Self {
1819            output,
1820            metadata: ToolCallMetadata::default(),
1821            finish: None,
1822        }
1823    }
1824
1825    pub fn contract_rejection(output: impl Into<String>) -> Self {
1826        Self {
1827            output: output.into(),
1828            metadata: ToolCallMetadata {
1829                // A rejected invocation observed no domain condition. Keep it
1830                // distinct from an executed observation whose answer is
1831                // legitimately negative (for example process exit 1).
1832                outcome_status: Some(ToolOutcomeStatus::Blocked),
1833                invocation_stage: ToolInvocationStage::RejectedBeforeIo,
1834                contract_rejected: true,
1835                // No requested domain effect ran, but the adapter directly
1836                // observed and completed its deterministic validation. This
1837                // lets an explicit receipt predicate prove the negative result
1838                // without relabeling it as a successful mutation.
1839                semantics: ToolCallSemantics::observation()
1840                    .with_verification_mode(ToolVerificationMode::ResultContent),
1841                ..ToolCallMetadata::default()
1842            },
1843            finish: None,
1844        }
1845    }
1846
1847    pub fn blocked(output: impl Into<String>) -> Self {
1848        Self {
1849            output: output.into(),
1850            metadata: ToolCallMetadata {
1851                outcome_status: Some(ToolOutcomeStatus::Blocked),
1852                ..ToolCallMetadata::default()
1853            },
1854            finish: None,
1855        }
1856    }
1857
1858    /// The runtime could not prepare the invocation (no domain I/O ran). The
1859    /// failure names the exact declaration so the dispatcher can repair its
1860    /// own projections instead of reporting its mistake to the model.
1861    pub fn runtime_preparation_failure(
1862        field: impl Into<String>,
1863        value: impl Into<String>,
1864        error: impl std::fmt::Display,
1865    ) -> Self {
1866        let field = field.into();
1867        let value = value.into();
1868        let error = error.to_string();
1869        Self {
1870            output: format!(
1871                "Error: the runtime could not prepare `{field}` entry `{value}` before running the command: {error}"
1872            ),
1873            metadata: ToolCallMetadata {
1874                outcome_status: Some(ToolOutcomeStatus::Blocked),
1875                invocation_stage: ToolInvocationStage::RejectedBeforeIo,
1876                semantics: ToolCallSemantics::observation()
1877                    .with_verification_mode(ToolVerificationMode::ResultContent),
1878                runtime_preparation_failure: Some(Box::new(RuntimePreparationFailure {
1879                    field,
1880                    value,
1881                    error,
1882                })),
1883                ..ToolCallMetadata::default()
1884            },
1885            finish: None,
1886        }
1887    }
1888
1889    pub fn completed_negative_result(output: impl Into<String>) -> Self {
1890        Self {
1891            output: output.into(),
1892            metadata: ToolCallMetadata {
1893                outcome_status: Some(ToolOutcomeStatus::CompletedWithNegativeResult),
1894                ..ToolCallMetadata::default()
1895            },
1896            finish: None,
1897        }
1898    }
1899
1900    /// End the run on this call (see [`Self::finish`]).
1901    pub fn with_finish(mut self, finish: aidaemon_core::Finish) -> Self {
1902        self.finish = Some(finish);
1903        self
1904    }
1905
1906    /// The call moved the rest of the work to the background: the run ends
1907    /// on it as partial work, and the dispatcher writes the handoff reply
1908    /// (it knows the user's request and whether completion notifications
1909    /// reach them).
1910    pub fn handed_to_background(mut self) -> Self {
1911        self.metadata.background_handoff = true;
1912        self.finish = Some(aidaemon_core::Finish::new(
1913            aidaemon_core::FinishOutcome::Partial,
1914            None,
1915        ));
1916        self
1917    }
1918
1919    pub fn with_semantics(mut self, semantics: ToolCallSemantics) -> Self {
1920        self.metadata.semantics = semantics;
1921        self
1922    }
1923
1924    pub fn with_observation_evidence(
1925        mut self,
1926        observations: Vec<ToolObservationEvidence>,
1927        collection_observations: Vec<ToolCollectionObservation>,
1928    ) -> Self {
1929        self.metadata.observations = observations;
1930        self.metadata.collection_observations = collection_observations;
1931        self
1932    }
1933}
1934
1935impl ToolCapabilities {
1936    /// Reads only the daemon's own state or the local machine: no approval, safe to repeat.
1937    pub const READ_ONLY: Self = Self {
1938        read_only: true,
1939        external_side_effect: false,
1940        needs_approval: false,
1941        idempotent: true,
1942        high_impact_write: false,
1943    };
1944    /// Changes something outside the daemon in a way that matters: the owner approves it, and it is not safe to repeat.
1945    pub const EXTERNAL_HIGH_IMPACT: Self = Self {
1946        read_only: false,
1947        external_side_effect: true,
1948        needs_approval: true,
1949        idempotent: false,
1950        high_impact_write: true,
1951    };
1952    /// Changes only the daemon's own state (a reminder, a note), without approval.
1953    pub const LOCAL_WRITE: Self = Self {
1954        read_only: false,
1955        external_side_effect: false,
1956        needs_approval: false,
1957        idempotent: false,
1958        high_impact_write: false,
1959    };
1960    /// Reaches outside the daemon (sends, posts) without approval; not safe to repeat.
1961    pub const EXTERNAL_WRITE: Self = Self {
1962        read_only: false,
1963        external_side_effect: true,
1964        needs_approval: false,
1965        idempotent: false,
1966        high_impact_write: false,
1967    };
1968    /// Changes only the daemon's own state, the same way however often it runs.
1969    pub const IDEMPOTENT_LOCAL_WRITE: Self = Self {
1970        read_only: false,
1971        external_side_effect: false,
1972        needs_approval: false,
1973        idempotent: true,
1974        high_impact_write: false,
1975    };
1976    /// Reads from outside the daemon (the web, a service): no approval, safe to repeat, its output untrusted.
1977    pub const READ_ONLY_EXTERNAL: Self = Self {
1978        read_only: true,
1979        external_side_effect: true,
1980        needs_approval: false,
1981        idempotent: true,
1982        high_impact_write: false,
1983    };
1984    /// Changes the daemon's own configuration or authority: the owner approves it.
1985    pub const APPROVED_HIGH_IMPACT_LOCAL: Self = Self {
1986        read_only: false,
1987        external_side_effect: false,
1988        needs_approval: true,
1989        idempotent: false,
1990        high_impact_write: true,
1991    };
1992    /// Reaches outside the daemon without approval, the same way however often it runs.
1993    pub const IDEMPOTENT_EXTERNAL_WRITE: Self = Self {
1994        read_only: false,
1995        external_side_effect: true,
1996        needs_approval: false,
1997        idempotent: true,
1998        high_impact_write: false,
1999    };
2000}
2001
2002impl Default for ToolCapabilities {
2003    fn default() -> Self {
2004        Self {
2005            read_only: false,
2006            external_side_effect: false,
2007            needs_approval: true,
2008            idempotent: false,
2009            high_impact_write: false,
2010        }
2011    }
2012}
2013
2014fn string_to_target_hint(key: &str, value: &str) -> Option<ToolTargetHint> {
2015    let trimmed = value.trim();
2016    if trimmed.is_empty() {
2017        return None;
2018    }
2019
2020    let lower_key = key.to_ascii_lowercase();
2021    if lower_key == "resource_id" {
2022        return ToolTargetHint::new(ToolTargetHintKind::ResourceId, trimmed);
2023    }
2024
2025    if matches!(
2026        lower_key.as_str(),
2027        "url" | "verify_url" | "callback_url" | "target_url" | "auth_url"
2028    ) || trimmed.starts_with("http://")
2029        || trimmed.starts_with("https://")
2030    {
2031        return ToolTargetHint::new(ToolTargetHintKind::Url, trimmed);
2032    }
2033
2034    if matches!(
2035        lower_key.as_str(),
2036        "path"
2037            | "file_path"
2038            | "working_dir"
2039            | "cwd"
2040            | "directory"
2041            | "dir"
2042            | "repo_path"
2043            | "repo_dir"
2044            | "resource_path"
2045    ) {
2046        return ToolTargetHint::new(ToolTargetHintKind::Path, trimmed);
2047    }
2048
2049    if matches!(
2050        lower_key.as_str(),
2051        "project_path" | "project_dir" | "scope" | "project_scope"
2052    ) {
2053        return ToolTargetHint::new(ToolTargetHintKind::ProjectScope, trimmed);
2054    }
2055
2056    None
2057}
2058
2059fn push_unique_target_hint(hints: &mut Vec<ToolTargetHint>, candidate: Option<ToolTargetHint>) {
2060    let Some(candidate) = candidate else {
2061        return;
2062    };
2063    if !hints.iter().any(|existing| existing == &candidate) {
2064        hints.push(candidate);
2065    }
2066}
2067
2068fn collect_common_target_hints(arguments: &str) -> Vec<ToolTargetHint> {
2069    let parsed = match serde_json::from_str::<Value>(arguments) {
2070        Ok(Value::Object(map)) => map,
2071        _ => return Vec::new(),
2072    };
2073
2074    let mut hints = Vec::new();
2075    for (key, value) in &parsed {
2076        match value {
2077            Value::String(s) => push_unique_target_hint(&mut hints, string_to_target_hint(key, s)),
2078            Value::Array(items) if matches!(key.as_str(), "paths" | "urls") => {
2079                for item in items.iter().filter_map(|item| item.as_str()) {
2080                    push_unique_target_hint(&mut hints, string_to_target_hint(key, item));
2081                }
2082            }
2083            _ => {}
2084        }
2085    }
2086    hints
2087}
2088
2089fn default_access_manifest(
2090    arguments: &str,
2091    semantics: &ToolCallSemantics,
2092) -> ToolCallAccessManifest {
2093    let parsed = serde_json::from_str::<Value>(arguments).ok();
2094    let execution_cwd = parsed.as_ref().and_then(|value| {
2095        value
2096            .get("working_dir")
2097            .or_else(|| value.get("cwd"))
2098            .and_then(Value::as_str)
2099            .map(str::trim)
2100            .filter(|value| !value.is_empty())
2101            .map(str::to_string)
2102    });
2103    let targets = if semantics.target_hints.is_empty() {
2104        collect_common_target_hints(arguments)
2105    } else {
2106        semantics.target_hints.clone()
2107    };
2108    let non_cwd_targets = targets
2109        .into_iter()
2110        .filter(|target| {
2111            matches!(
2112                target.kind,
2113                ToolTargetHintKind::Path | ToolTargetHintKind::ProjectScope
2114            )
2115        })
2116        .filter(|target| execution_cwd.as_deref() != Some(target.value.as_str()))
2117        .collect::<Vec<_>>();
2118    let mut read_targets = Vec::new();
2119    if let Some(cwd) = execution_cwd.as_deref()
2120        && let Some(target) = ToolTargetHint::new(ToolTargetHintKind::ProjectScope, cwd)
2121    {
2122        read_targets.push(target);
2123    }
2124    if semantics.observes_state() {
2125        read_targets.extend(non_cwd_targets.iter().cloned());
2126    }
2127    let write_targets = if semantics.mutates_state() {
2128        non_cwd_targets
2129    } else {
2130        Vec::new()
2131    };
2132    ToolCallAccessManifest {
2133        execution_cwd,
2134        read_targets,
2135        write_targets,
2136        adapter_read_targets: Vec::new(),
2137    }
2138}
2139
2140/// Classify a mixed-operation tool from the exact `action` enum in its schema.
2141///
2142/// This helper intentionally performs no tokenization, substring matching, or
2143/// interpretation of unknown action names. Tools pass their exhaustive set of
2144/// read-only enum variants; every missing, malformed, or new variant fails
2145/// conservatively as a mutation until the tool implementation classifies it.
2146pub fn semantics_for_exact_read_actions(
2147    arguments: &str,
2148    read_actions: &[&str],
2149    mutation_effects: ToolMutationEffects,
2150) -> ToolCallSemantics {
2151    let action = serde_json::from_str::<Value>(arguments)
2152        .ok()
2153        .and_then(|value| {
2154            value
2155                .get("action")
2156                .and_then(Value::as_str)
2157                .map(str::to_string)
2158        });
2159    let mut semantics = if action
2160        .as_deref()
2161        .is_some_and(|action| read_actions.contains(&action))
2162    {
2163        ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
2164    } else if mutation_effects.is_empty() {
2165        ToolCallSemantics::mutation()
2166    } else {
2167        ToolCallSemantics::mutation_with(mutation_effects)
2168    };
2169    for target_hint in collect_common_target_hints(arguments) {
2170        semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
2171    }
2172    semantics
2173}
2174
2175fn default_semantics_from_identity(arguments: &str, caps: ToolCapabilities) -> ToolCallSemantics {
2176    let mut semantics = if caps.read_only {
2177        ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
2178    } else {
2179        // Unknown non-read-only tools fail conservatively as mutations. Mixed
2180        // tools must override `call_semantics` with an exact match on their
2181        // schema enum; names, descriptions, and arbitrary action vocabulary are
2182        // never an authority source.
2183        ToolCallSemantics::mutation()
2184    };
2185
2186    for target_hint in collect_common_target_hints(arguments) {
2187        semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
2188    }
2189    semantics
2190}
2191
2192/// The scope of an approval the agent kernel gave a call (see
2193/// [`ToolCallContext::kernel_approved`]).
2194#[derive(Debug, Clone, PartialEq, Eq)]
2195pub enum ApprovalScope {
2196    /// This call came through the kernel, which judged it.
2197    Call,
2198    /// One exact inner request (`METHOD url`) of an outer call the kernel
2199    /// approved, for example `manage_api`'s live probe.
2200    Request { method: String, url: String },
2201}
2202
2203/// Refuse `what` (the tool and action, as the refusal names them) unless the
2204/// agent kernel approved the whole call ([`ApprovalScope::Call`]). An
2205/// approval scoped to one inner request never authorizes the outer call.
2206pub fn require_call_approval(scope: Option<&ApprovalScope>, what: &str) -> anyhow::Result<()> {
2207    if scope != Some(&ApprovalScope::Call) {
2208        anyhow::bail!(
2209            "{what} requires approval through the agent kernel; it was called outside an \
2210             approved agent call"
2211        );
2212    }
2213    Ok(())
2214}
2215
2216/// One call as the kernel's approval rules show it to
2217/// [`ToolSemantics::owner_approval_request`].
2218#[derive(Debug, Clone, Copy)]
2219pub struct ApprovalCall<'a> {
2220    /// The arguments the dispatcher will execute (for a tool whose calls the
2221    /// kernel judges in canonical form, the canonical form; otherwise the
2222    /// model's own).
2223    pub arguments: &'a Value,
2224    /// The arguments as the model sent them, for a card about a call whose
2225    /// arguments cannot be read.
2226    pub as_sent: &'a Value,
2227    /// The dispatcher refuses this call before it runs (an out-of-scope
2228    /// target nobody may authorize), so nothing about it needs the owner.
2229    pub refused: bool,
2230}
2231
2232impl<'a> ApprovalCall<'a> {
2233    /// A call the dispatcher runs as the model sent it.
2234    pub fn as_sent(arguments: &'a Value) -> Self {
2235        Self {
2236            arguments,
2237            as_sent: arguments,
2238            refused: false,
2239        }
2240    }
2241}
2242
2243/// What a tool says about the owner's approval for one call.
2244#[derive(Debug, Clone, PartialEq)]
2245pub enum OwnerApprovalNeed {
2246    /// The tool has no opinion: the approval policy's allow rules and mode
2247    /// decide.
2248    Unjudged,
2249    /// The tool judged the call and it needs no approval.
2250    NotNeeded,
2251    /// Ask the owner with this request (unless a grant covers it).
2252    Ask(aidaemon_core::OwnerApprovalRequest),
2253}
2254
2255/// The dispatcher's facts about one tool call, passed to the tool beside its
2256/// arguments.
2257///
2258/// This is a Rust-side control-plane type: it is NEVER serialized and never
2259/// appears in model-visible JSON, tool schemas, logs, or persisted tool
2260/// arguments. Every fact about who is calling, from where, and under what
2261/// authority lives here and only here: a tool's arguments are the model's
2262/// own, and the dispatcher strips any `_`-prefixed key a model sends.
2263#[derive(Clone, Default)]
2264pub struct ToolCallContext {
2265    /// True only after the final common dispatcher revalidated an exact,
2266    /// action-bound `MandateAuthorityGrant` for this mutating call, so tools
2267    /// can honor owner-delegated autonomy.
2268    pub mandate_preapproved: bool,
2269    /// True only when the common dispatcher resolved this call to an active
2270    /// autonomous mandate. Network adapters use this control-plane bit to keep
2271    /// one target-bound call from following redirects outside the target that
2272    /// was evaluated by the mandate authority kernel.
2273    pub mandate_execution: bool,
2274    /// Hard negative task contract propagated from the validated request.
2275    /// Open-ended adapters must prove an operation is observational before I/O.
2276    pub mutation_forbidden: bool,
2277    /// What the agent kernel approved, set only by the dispatcher (never
2278    /// from arguments): `Call` for a call that came through the kernel,
2279    /// whose `ApprovalPolicy` already asked the owner where the daemon's
2280    /// rules require it; `Request` for one exact inner request an approved
2281    /// outer call makes. A tool that needs the owner's approval refuses a
2282    /// call without a matching scope rather than asking itself.
2283    pub kernel_approved: Option<ApprovalScope>,
2284    /// The turn is a trusted scheduled session (never one under a mandate),
2285    /// set only by the dispatcher from the channel context and the goal's
2286    /// provenance.
2287    pub trusted_session: bool,
2288    /// The role of the turn's user (`None` outside the dispatcher: an
2289    /// unknown caller is not the owner).
2290    pub user_role: Option<UserRole>,
2291    /// The session was started by an automated trigger (an email, an
2292    /// event), not by the owner.
2293    pub untrusted_source: bool,
2294    /// Exact out-of-scope targets the controller routed to the owner's
2295    /// approval instead of refusing them.
2296    pub scope_escalation: Option<ScopeEscalation>,
2297    /// The session the call belongs to (empty outside the dispatcher).
2298    pub session_id: String,
2299    /// The session whose owner approvals cover this call: the chat that
2300    /// started the work. A sub-agent runs in a session of its own but works
2301    /// for that chat, so a tool's own session-scoped grants ("allow for
2302    /// session") key on this, never on `session_id`. Empty: `session_id`.
2303    pub grant_session: String,
2304    /// Visibility of the channel the turn came from (`None` outside the
2305    /// dispatcher; each tool keeps its own fallback).
2306    pub channel_visibility: Option<ChannelVisibility>,
2307    /// The channel the turn came from, when the channel has an id.
2308    pub channel_id: Option<String>,
2309    /// The task the call runs under.
2310    pub task_id: Option<String>,
2311    /// The owner/user message text of this turn (control-plane only; used for
2312    /// synchronous provenance verification in `remember_fact`).
2313    pub user_message: Option<String>,
2314    /// The model's id for this tool call.
2315    pub tool_call_id: Option<String>,
2316    /// The call is the only one in a root turn's model response, so a reply
2317    /// the tool finishes the run with answers the user's request directly.
2318    pub lone_root_call: bool,
2319    /// The session's current turn.
2320    pub turn_id: Option<String>,
2321    /// The goal the call serves: the agent's goal, or (for `cli_agent` and
2322    /// `terminal`) the goal of the executor's task, so background
2323    /// notifications reach the origin session.
2324    pub goal_id: Option<String>,
2325    /// The goal run of the mandate fence the call runs under.
2326    pub goal_run_id: Option<String>,
2327    /// The task attempt of the mandate fence the call runs under.
2328    pub task_attempt_id: Option<String>,
2329    /// The mandate of the fence the call runs under.
2330    pub mandate_id: Option<String>,
2331    /// The mandate version of the fence the call runs under.
2332    pub mandate_version: Option<i64>,
2333    /// The single project the turn is scoped to.
2334    pub project_scope: Option<String>,
2335    /// The project the owner's turn works in (an app project, a chat placed
2336    /// in one), set only by the dispatcher from typed turn state. `None` for
2337    /// guests, public channels and mandate runs: project-scoped writes (a
2338    /// memory tool's project notes) key on it.
2339    pub project: Option<aidaemon_core::ProjectRef>,
2340    /// A guest's granted workspace root (only under an active grant).
2341    pub workspace_collaboration_root: Option<String>,
2342    /// The turn's trusted file roots (set for `terminal`), so a run moved to
2343    /// the background records the trust its launch was judged with.
2344    pub trust_roots: Option<Vec<String>>,
2345    /// The cwd relative paths resolve against for [`Self::trust_roots`].
2346    pub trust_cwd: Option<String>,
2347    /// The live model (set for `computer_use`).
2348    pub model: Option<String>,
2349    /// The provider kind behind [`Self::model`], as the daemon names it.
2350    pub provider_kind: Option<String>,
2351    /// The router's models in order, when a router is configured.
2352    pub model_chain: Option<Vec<String>>,
2353    /// Application facts whose types cannot live in the SDK (they depend on
2354    /// the application's configuration), read by the tool that needs them
2355    /// through a typed getter.
2356    pub extensions: aidaemon_core::Extensions,
2357}
2358
2359impl std::fmt::Debug for ToolCallContext {
2360    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2361        f.debug_struct("ToolCallContext")
2362            .field("mandate_preapproved", &self.mandate_preapproved)
2363            .field("mandate_execution", &self.mandate_execution)
2364            .field("mutation_forbidden", &self.mutation_forbidden)
2365            .field("kernel_approved", &self.kernel_approved)
2366            .field("trusted_session", &self.trusted_session)
2367            .field("user_role", &self.user_role)
2368            .field("untrusted_source", &self.untrusted_source)
2369            .field("scope_escalation", &self.scope_escalation)
2370            .field("session_id", &self.session_id)
2371            .field("channel_visibility", &self.channel_visibility)
2372            .field("channel_id", &self.channel_id)
2373            .field("task_id", &self.task_id)
2374            .field(
2375                "user_message",
2376                &self.user_message.as_ref().map(|_| "[USER MESSAGE]"),
2377            )
2378            .field("tool_call_id", &self.tool_call_id)
2379            .field("lone_root_call", &self.lone_root_call)
2380            .field("turn_id", &self.turn_id)
2381            .field("goal_id", &self.goal_id)
2382            .field("goal_run_id", &self.goal_run_id)
2383            .field("task_attempt_id", &self.task_attempt_id)
2384            .field("mandate_id", &self.mandate_id)
2385            .field("mandate_version", &self.mandate_version)
2386            .field("project_scope", &self.project_scope)
2387            .field(
2388                "workspace_collaboration_root",
2389                &self
2390                    .workspace_collaboration_root
2391                    .as_ref()
2392                    .map(|_| "[SCOPED WORKSPACE]"),
2393            )
2394            .field("trust_roots", &self.trust_roots)
2395            .field("trust_cwd", &self.trust_cwd)
2396            .field("model", &self.model)
2397            .field("provider_kind", &self.provider_kind)
2398            .field("model_chain", &self.model_chain)
2399            .field("extensions", &self.extensions)
2400            .finish()
2401    }
2402}
2403
2404impl ToolCallContext {
2405    /// The session id, or `None` when the call carries none.
2406    pub fn session(&self) -> Option<&str> {
2407        Some(self.session_id.as_str()).filter(|id| !id.trim().is_empty())
2408    }
2409
2410    /// The session a tool's own session-scoped grants key on
2411    /// ([`Self::grant_session`], else the call's session).
2412    pub fn grants_session(&self) -> &str {
2413        if self.grant_session.trim().is_empty() {
2414            &self.session_id
2415        } else {
2416            &self.grant_session
2417        }
2418    }
2419
2420    /// The typed-scope grants the owner gave the work this call is part of
2421    /// ([`Self::grants_session`]: the chat, shared by its sub-agents). The
2422    /// runtime checks them before asking about a call whose tool offers a
2423    /// reusable scope ([`crate::OutcomeTool::approval_grant`]); a tool may
2424    /// read them too.
2425    pub fn scoped_grants(&self) -> std::sync::Arc<ScopedGrants> {
2426        ScopedGrants::for_session(self.grants_session())
2427    }
2428}
2429
2430/// Filesystem targets a tool call declared that fall outside the compiled
2431/// task scope but are not protected host data or credential stores. The
2432/// controller does not reject such a call outright; it hands the exact
2433/// out-of-scope targets to the tool, which must obtain explicit user approval
2434/// (or a persisted capability grant) before running with them.
2435#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
2436pub struct ScopeEscalation {
2437    #[serde(default)]
2438    pub read_paths: Vec<String>,
2439    #[serde(default)]
2440    pub write_paths: Vec<String>,
2441}
2442
2443impl ScopeEscalation {
2444    pub fn is_empty(&self) -> bool {
2445        self.read_paths.is_empty() && self.write_paths.is_empty()
2446    }
2447}
2448
2449/// A tool-owned decision about whether a previously successful durable receipt
2450/// still represents current state.
2451///
2452/// Most mutations cannot be repeated safely and therefore use `Replay`. Tools
2453/// with an exact deterministic postcondition may opt into current-state
2454/// reconciliation and either re-execute when that postcondition is missing or
2455/// block when the target drifted in a way that could make repetition unsafe.
2456#[derive(Debug, Clone, PartialEq, Eq)]
2457pub enum DurableReplayDecision {
2458    Replay,
2459    Reexecute { reason: String },
2460    Block { reason: String },
2461}
2462
2463/// Tool trait — system tools, terminal, MCP-proxied tools.
2464#[derive(Debug, Clone, PartialEq, Eq)]
2465pub struct ToolArgumentContractViolation {
2466    pub reason: String,
2467    pub recovery_hint: Option<String>,
2468}
2469
2470impl ToolArgumentContractViolation {
2471    pub fn new(reason: impl Into<String>) -> Self {
2472        Self {
2473            reason: reason.into(),
2474            recovery_hint: None,
2475        }
2476    }
2477
2478    pub fn with_recovery_hint(mut self, hint: impl Into<String>) -> Self {
2479        self.recovery_hint = Some(hint.into());
2480        self
2481    }
2482}
2483
2484/// Permission persistence mode for commands requiring owner approval.
2485#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
2486#[serde(rename_all = "lowercase")]
2487pub enum PermissionMode {
2488    /// Safe/Medium/High persist; Critical remains session-scoped.
2489    #[default]
2490    Default,
2491    /// All approvals remain session-scoped.
2492    Cautious,
2493    /// All approvals persist, including Critical.
2494    Yolo,
2495}
2496
2497impl std::fmt::Display for PermissionMode {
2498    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2499        match self {
2500            PermissionMode::Default => write!(f, "default"),
2501            PermissionMode::Cautious => write!(f, "cautious"),
2502            PermissionMode::Yolo => write!(f, "yolo"),
2503        }
2504    }
2505}
2506
2507/// Distinguishes different kinds of approval requests so channels can render
2508/// appropriate buttons (e.g., Allow Once / Deny for commands vs Confirm / Cancel
2509/// for scheduled-goal confirmations).
2510#[derive(Debug, Clone, Copy, Default)]
2511pub enum ApprovalKind {
2512    /// Standard command approval (Allow Once / Allow Session / Allow Always / Deny).
2513    #[default]
2514    Command,
2515    /// Point-of-action approval that can authorize only this invocation.
2516    /// Channels must not offer session or persistent approval buttons.
2517    CommandOnce,
2518    /// Scheduled-goal confirmation (Confirm / Cancel).
2519    GoalConfirmation,
2520    /// Exact owner confirmation for a persisted Autopilot mandate policy.
2521    /// Kept distinct so channels never infer high-autonomy presentation from
2522    /// user or model prose.
2523    AutopilotConfirmation,
2524    /// The agent asks the owner to do something themselves on a live surface
2525    /// (sign in, enter a code): Done or Not now, this one time only.
2526    Handoff,
2527}
2528
2529pub use aidaemon_policies::{GrantLifetime, GrantOffer, GrantScope, ScopedGrants};
2530
2531/// The card kind a card for `offer` is sent as, from the kind the tool
2532/// asked for: a once-only offer turns a standard command card into a
2533/// one-time card, so no session or persistent button is offered. Other
2534/// kinds (goal confirmations, hand-offs) already offer nothing lasting.
2535pub fn offered_card_kind(offer: &GrantOffer, kind: ApprovalKind) -> ApprovalKind {
2536    match (offer.max, kind) {
2537        (GrantLifetime::Once, ApprovalKind::Command) => ApprovalKind::CommandOnce,
2538        _ => kind,
2539    }
2540}
2541
2542/// The permission mode a card for `offer` is sent with, from the tool's
2543/// own: an offer that lasts at most the session keeps every button
2544/// session-scoped (Cautious), so the card never advertises Always.
2545pub fn offered_card_mode(offer: &GrantOffer, mode: PermissionMode) -> PermissionMode {
2546    match offer.max {
2547        GrantLifetime::Once | GrantLifetime::Session => PermissionMode::Cautious,
2548        GrantLifetime::Persistent => mode,
2549    }
2550}
2551
2552impl ApprovalResponse {
2553    /// How long this answer asks an approval to last (`None`: Deny).
2554    pub fn grant_lifetime(&self) -> Option<GrantLifetime> {
2555        match self {
2556            ApprovalResponse::AllowOnce => Some(GrantLifetime::Once),
2557            ApprovalResponse::AllowSession => Some(GrantLifetime::Session),
2558            ApprovalResponse::AllowAlways => Some(GrantLifetime::Persistent),
2559            ApprovalResponse::Deny => None,
2560        }
2561    }
2562
2563    /// This answer as it stands under `offer`: one that asks for longer
2564    /// than the offer's `max` is capped to it (Always on a session offer is
2565    /// Allow for session; any Allow on a once offer is Allow once). Deny
2566    /// stays Deny.
2567    pub fn capped_to(self, offer: &GrantOffer) -> ApprovalResponse {
2568        match self.grant_lifetime().map(|asked| offer.cap(asked)) {
2569            None => ApprovalResponse::Deny,
2570            Some(GrantLifetime::Once) => ApprovalResponse::AllowOnce,
2571            Some(GrantLifetime::Session) => ApprovalResponse::AllowSession,
2572            Some(GrantLifetime::Persistent) => ApprovalResponse::AllowAlways,
2573        }
2574    }
2575}
2576
2577/// Response to an approval request from the user.
2578#[derive(Debug, Clone)]
2579pub enum ApprovalResponse {
2580    /// Allow this specific command only
2581    AllowOnce,
2582    /// Allow this command prefix for the current session (resets on restart)
2583    AllowSession,
2584    /// Allow this command prefix forever (persists to database)
2585    AllowAlways,
2586    /// Deny the command
2587    Deny,
2588}
2589
2590/// Relative impact of an operation requiring approval.
2591#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
2592pub enum RiskLevel {
2593    Safe,
2594    Medium,
2595    High,
2596    Critical,
2597}
2598
2599impl std::fmt::Display for RiskLevel {
2600    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2601        match self {
2602            RiskLevel::Safe => write!(f, "Safe"),
2603            RiskLevel::Medium => write!(f, "Medium"),
2604            RiskLevel::High => write!(f, "High"),
2605            RiskLevel::Critical => write!(f, "Critical"),
2606        }
2607    }
2608}
2609
2610impl RiskLevel {
2611    /// Whether this risk level represents an action that should interrupt the
2612    /// owner for approval. Safe and medium operations may still be observable
2613    /// or locally mutating, but they are not dangerous enough to justify
2614    /// blocking an otherwise authorized task.
2615    pub const fn requires_owner_approval(self) -> bool {
2616        matches!(self, Self::High | Self::Critical)
2617    }
2618}
2619
2620/// Typed presentation requested for an exact goal/mandate confirmation.
2621#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2622pub enum GoalConfirmationStyle {
2623    #[default]
2624    Standard,
2625    Autopilot,
2626}
2627
2628/// Role assigned to an agent for role-based tool scoping.
2629#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2630pub enum AgentRole {
2631    /// Root agent — routes, classifies, full tool access (legacy behavior).
2632    Orchestrator,
2633    /// Plans & delegates — management tools only.
2634    TaskLead,
2635    /// Executes a single task — action tools + report_blocker.
2636    Executor,
2637}
2638
2639/// How one call changes a file (see [`ToolSemantics::call_file_write`]).
2640#[derive(Debug, Clone, PartialEq, Eq)]
2641pub enum FileWriteKind {
2642    /// Replaces this exact text.
2643    Edit { old_text: String, replace_all: bool },
2644    /// Replaces each exact text in order, each in the result of the one
2645    /// before: all of them, or nothing.
2646    Edits(Vec<TextEdit>),
2647    /// Replaces the whole file.
2648    Replace,
2649    /// Adds to the end of the file.
2650    Append,
2651}
2652
2653/// One find-and-replace of a [`FileWriteKind::Edits`] batch.
2654#[derive(Debug, Clone, PartialEq, Eq)]
2655pub struct TextEdit {
2656    pub old_text: String,
2657    pub replace_all: bool,
2658}
2659
2660/// The file one call writes, as the tool's arguments name it.
2661#[derive(Debug, Clone, PartialEq, Eq)]
2662pub struct FileWrite {
2663    pub path: String,
2664    pub kind: FileWriteKind,
2665}
2666
2667/// A write in progress under a [`FileFence`]. Dropping it records nothing.
2668#[async_trait]
2669pub trait FileWriteGuard: Send {
2670    /// The write landed.
2671    async fn committed(self: Box<Self>);
2672}
2673
2674/// Handed to a file tool by a host whose agents share a workspace. Without
2675/// one the tool behaves as it would alone.
2676#[async_trait]
2677pub trait FileFence: Send + Sync {
2678    /// The call read these exact bytes of `path`.
2679    async fn observed(&self, path: &str, bytes: &[u8]);
2680
2681    /// Hold `path` for this write, or say why the write must not happen.
2682    /// Taken before the tool reads the file it is about to change, and held
2683    /// until the write has landed.
2684    async fn begin_write(&self, path: &str) -> Result<Box<dyn FileWriteGuard>, String>;
2685
2686    /// Claim the delivery to the owner of the artifact `subject` names (a
2687    /// page's screenshot names the page) for this call. One request's agents
2688    /// deliver each artifact once: whoever delivers it first owns it, and a
2689    /// later claim gets who did and when. Release a claim whose delivery
2690    /// then failed ([`Self::release_delivery`]).
2691    async fn claim_delivery(&self, _subject: &str) -> Result<(), DeliveredArtifact> {
2692        Ok(())
2693    }
2694
2695    /// Give back a claim whose delivery did not happen.
2696    async fn release_delivery(&self, _subject: &str) {}
2697
2698    /// The call declares `deliverable` for the owner. A helper's run keeps
2699    /// it on its record and sends it once, when the run ends: the last one
2700    /// of each kind it declared, so a capture taken before the work was
2701    /// done is replaced by the final one, never sent beside it. Anyone
2702    /// else's (the turn's own agent, a host with no run record) is sent now
2703    /// by the caller, under [`Self::claim_delivery`].
2704    async fn declare_deliverable(&self, deliverable: Deliverable) -> DeliveryPlan {
2705        DeliveryPlan::Now(deliverable)
2706    }
2707}
2708
2709/// What a deliverable is, by kind: each run delivers one of each kind (the
2710/// last it declared), and each request delivers each subject once.
2711#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2712pub enum DeliverableKind {
2713    /// A page's screenshot, named by its page ("demo.ddev.site").
2714    Screenshot { page: String },
2715    /// Any other file, named by its file name.
2716    File { name: String },
2717}
2718
2719impl DeliverableKind {
2720    /// The delivery ledger's key for it.
2721    pub fn subject(&self) -> String {
2722        match self {
2723            Self::Screenshot { page } => format!("screenshot:{page}"),
2724            Self::File { name } => format!("file:{name}"),
2725        }
2726    }
2727
2728    /// The kind in the owner's words ("a screenshot of demo.ddev.site").
2729    pub fn words(&self) -> String {
2730        match self {
2731            Self::Screenshot { page } => format!("a screenshot of {page}"),
2732            Self::File { name } => format!("the file {name}"),
2733        }
2734    }
2735}
2736
2737/// The send a tool hands over with a deliverable sent later: run once, it
2738/// reports whether the channel accepted it.
2739pub type DeliverySend = Box<
2740    dyn FnOnce() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>
2741        + Send
2742        + Sync,
2743>;
2744
2745/// One artifact a call declares for the owner.
2746pub struct Deliverable {
2747    pub kind: DeliverableKind,
2748    /// What the owner reads with it ("Screenshot of demo.ddev.site").
2749    pub caption: String,
2750    pub send: DeliverySend,
2751}
2752
2753impl std::fmt::Debug for Deliverable {
2754    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2755        f.debug_struct("Deliverable")
2756            .field("kind", &self.kind)
2757            .field("caption", &self.caption)
2758            .finish_non_exhaustive()
2759    }
2760}
2761
2762/// When a declared deliverable is sent ([`FileFence::declare_deliverable`]).
2763#[derive(Debug)]
2764pub enum DeliveryPlan {
2765    /// The caller sends it now, under a delivery claim.
2766    Now(Deliverable),
2767    /// It is on the run's record and is sent when the run ends. `replaced`:
2768    /// it took the place of an earlier one of the same kind.
2769    AtRunEnd { replaced: bool },
2770}
2771
2772/// An artifact one of the request's agents already delivered to the owner.
2773#[derive(Debug, Clone, PartialEq, Eq)]
2774pub struct DeliveredArtifact {
2775    /// Who delivered it, in words the owner reads ("you", or the helper's
2776    /// mission).
2777    pub by: String,
2778    pub at: chrono::DateTime<chrono::Utc>,
2779}
2780
2781impl DeliveredArtifact {
2782    /// When it was delivered, on the owner's clock ("3:41:22 AM").
2783    pub fn owner_time(&self) -> String {
2784        self.at
2785            .with_timezone(&chrono::Local)
2786            .format("%-I:%M:%S %p")
2787            .to_string()
2788    }
2789}
2790
2791/// This call's [`FileFence`], carried in [`ToolCallContext::extensions`].
2792#[derive(Clone)]
2793pub struct CallFileFence(pub std::sync::Arc<dyn FileFence>);
2794
2795/// The call's file fence, if its host gave it one.
2796pub fn file_fence(facts: &ToolCallContext) -> Option<&std::sync::Arc<dyn FileFence>> {
2797    facts
2798        .extensions
2799        .get::<CallFileFence>()
2800        .map(|fence| &fence.0)
2801}
2802
2803/// A job a tool runs in the background for a chat.
2804#[derive(Debug, Clone, PartialEq, Eq)]
2805pub struct BackgroundJob {
2806    /// The tool's own handle for it; never shown.
2807    pub key: String,
2808    /// What it is, in plain words.
2809    pub title: String,
2810    pub started_at: chrono::DateTime<chrono::Utc>,
2811    /// The task (turn) that started it, when known.
2812    pub task_id: Option<String>,
2813    /// The run it is in the runtime's records, when it is one.
2814    pub run: Option<String>,
2815}
2816
2817/// What a tool says about a call without executing it: its capabilities,
2818/// typed semantics, access manifest, receipt protocol, effects and trust.
2819/// Every method has a conservative default; a tool overrides only what it
2820/// can state exactly.
2821#[async_trait]
2822pub trait ToolSemantics: Send + Sync {
2823    /// Canonicalize provider argument projections before any semantics,
2824    /// authority, retry, or access decision is made. The default is identity;
2825    /// adapters with representational aliases or optional-empty projection
2826    /// quirks can normalize them without teaching the orchestration layer
2827    /// adapter-specific rules.
2828    fn canonicalize_arguments(
2829        &self,
2830        arguments: &str,
2831    ) -> Result<String, ToolArgumentContractViolation> {
2832        Ok(arguments.to_string())
2833    }
2834
2835    /// Adapter-owned, deterministic argument invariants evaluated by the
2836    /// common dispatcher before any tool I/O. The default accepts all schema-
2837    /// valid calls. Rejections become typed `contract_rejected` receipts.
2838    fn validate_arguments(&self, _arguments: &str) -> Result<(), ToolArgumentContractViolation> {
2839        Ok(())
2840    }
2841
2842    /// Task lifecycle callback fired after the agent emits `TaskEnd`.
2843    /// Tools that spawn background activity can use this to clean up
2844    /// task-scoped resources.
2845    async fn on_task_end(&self, _task_id: &str, _session_id: &str) -> anyhow::Result<()> {
2846        Ok(())
2847    }
2848
2849    /// Live state this tool holds for a session that outlives a turn (for
2850    /// example background processes still running), rendered for the next
2851    /// turn's task context so a follow-up sees it instead of guessing.
2852    async fn session_context_note(&self, _session_id: &str) -> Option<String> {
2853        None
2854    }
2855
2856    /// The jobs this tool is running in the background for `session_id`
2857    /// (they outlive the turn that started them), as the chat's list of
2858    /// running work shows them.
2859    async fn background_jobs(&self, _session_id: &str) -> Vec<BackgroundJob> {
2860        Vec::new()
2861    }
2862
2863    /// Stop the background job `key` (from [`Self::background_jobs`]) and
2864    /// read its state back: `true` only once the job is gone.
2865    async fn stop_background_job(&self, _key: &str) -> bool {
2866        false
2867    }
2868
2869    /// How many jobs task `task_id` started that are still running and that
2870    /// the task's end would stop: nothing reports their result, so a run that
2871    /// ended now would lose their work.
2872    async fn jobs_ended_by_task_end(&self, _task_id: &str) -> usize {
2873        0
2874    }
2875
2876    /// A run starts (`held`) or stops holding its answer until task
2877    /// `task_id`'s jobs ([`Self::jobs_ended_by_task_end`]) end. Only while a
2878    /// run holds may a tool stop such a job for making no progress: while
2879    /// the run still works, a quiet job (a test server it still uses) is the
2880    /// run's own. Holds nest; each start is matched by one stop.
2881    fn set_stop_held(&self, _task_id: &str, _held: bool) {}
2882
2883    /// A run of task `task_id` starts (`live`) or ends, however it ends:
2884    /// returning, failing, or being cancelled (its future dropped, so its
2885    /// task-end cleanup never runs). A job whose task has no live run and no
2886    /// hold ([`Self::set_stop_held`]) is nobody's: a tool may stop it for
2887    /// making no progress. Runs of one task nest; each start is matched by
2888    /// one end.
2889    fn set_run_live(&self, _task_id: &str, _live: bool) {}
2890
2891    /// Categorize this tool for role-based scoping.
2892    /// Default: Action (most tools are action tools).
2893    fn tool_role(&self) -> ToolRole {
2894        ToolRole::Action
2895    }
2896
2897    /// How the dispatcher and the engine treat this tool. Default: nothing
2898    /// special.
2899    fn dispatch_facts(&self) -> ToolDispatchFacts {
2900        ToolDispatchFacts::default()
2901    }
2902
2903    /// Capability metadata used by the execution policy and risk gate.
2904    /// Defaults are intentionally conservative.
2905    fn capabilities(&self) -> ToolCapabilities {
2906        ToolCapabilities::default()
2907    }
2908
2909    /// The tool only manages the owner's own durable policy (mandates). A
2910    /// request assessment that narrows a turn's tools still offers it to the
2911    /// owner in a private chat, but only calls `owner_control_plane_call`
2912    /// accepts are admitted there.
2913    fn owner_control_plane(&self) -> bool {
2914        false
2915    }
2916
2917    /// Whether this exact call is safe on a turn whose assessment did not
2918    /// name the tool: read-only, or committing only through an explicit
2919    /// owner confirmation. Decided from the tool's own schema enum.
2920    fn owner_control_plane_call(&self, _arguments: &str) -> bool {
2921        false
2922    }
2923
2924    /// The owner approval this exact call needs before it runs, judged from
2925    /// the call and the dispatcher's facts for it (never from `_` arguments).
2926    /// The kernel's approval rules ask it for every call and send the card
2927    /// it returns. The default has no opinion, so the approval policy's mode
2928    /// decides.
2929    async fn owner_approval_request(
2930        &self,
2931        _call: &ApprovalCall<'_>,
2932        _facts: &ToolCallContext,
2933    ) -> OwnerApprovalNeed {
2934        OwnerApprovalNeed::Unjudged
2935    }
2936
2937    /// Machine-receipt protocol emitted by this adapter.
2938    ///
2939    /// Keep this independent from natural-language descriptions and call
2940    /// semantics: it exists solely to type-check completion predicates.
2941    fn receipt_kind(&self, _arguments: &str) -> ToolReceiptKind {
2942        ToolReceiptKind::Generic
2943    }
2944
2945    /// Structured completion semantics for a specific call.
2946    ///
2947    /// Default behavior derives a conservative fallback from `capabilities()`.
2948    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
2949        default_semantics_from_identity(arguments, self.capabilities())
2950    }
2951
2952    /// Filesystem access roles for this exact call. Open-ended adapters should
2953    /// override this when their schema exposes explicit read/write grants.
2954    fn call_access_manifest(&self, arguments: &str) -> ToolCallAccessManifest {
2955        let semantics = self.call_semantics(arguments);
2956        default_access_manifest(arguments, &semantics)
2957    }
2958
2959    /// The paths this call reads and writes, as `ProtectedPathGuard` judges
2960    /// them. Defaults to the access manifest; a tool overrides it for a path
2961    /// that scope checks must not see as a task read.
2962    fn guarded_paths(&self, arguments: &str) -> (Vec<String>, Vec<String>) {
2963        let manifest = self.call_access_manifest(arguments);
2964        let values =
2965            |targets: Vec<ToolTargetHint>| targets.into_iter().map(|target| target.value).collect();
2966        (
2967            values(manifest.read_targets),
2968            values(manifest.write_targets),
2969        )
2970    }
2971
2972    /// Capabilities supplied by the adapter rather than requested as task
2973    /// data.  The common dispatcher uses this typed lane when attenuating the
2974    /// call against the task manifest.  The default is empty so an adapter
2975    /// cannot accidentally widen authority by inheriting a generic grant.
2976    fn adapter_owned_access_manifest(&self, _arguments: &str) -> ToolCallAccessManifest {
2977        ToolCallAccessManifest::default()
2978    }
2979
2980    /// Reconcile a successful durable receipt with current state before replay.
2981    ///
2982    /// The conservative default always replays. An override may return
2983    /// `Reexecute` only when repeating the exact same invocation is safe after
2984    /// the observed state transition, and `Block` when current state cannot be
2985    /// reconciled safely.
2986    async fn durable_replay_decision(&self, _arguments: &str) -> DurableReplayDecision {
2987        DurableReplayDecision::Replay
2988    }
2989
2990    /// Exact receipt subjects this adapter reports verbatim: fixed collection
2991    /// IDs and the namespaces of member identities it mints. The checklist
2992    /// tool publishes the union so declared targets bind only to identities a
2993    /// receipt can carry. The default advertises nothing.
2994    fn stable_observation_subjects(&self) -> Vec<StableObservationSubject> {
2995        Vec::new()
2996    }
2997
2998    /// The file this exact call writes and how, read from its arguments. A
2999    /// tool that does not declare one is invisible to stale-write checks.
3000    fn call_file_write(&self, _arguments: &str) -> Option<FileWrite> {
3001        None
3002    }
3003
3004    /// What the file would hold after this exact call, were it holding
3005    /// `current` now (`None`: no such file). `Err` is the tool's own reason
3006    /// the call cannot apply to that content. A tool that cannot say returns
3007    /// `None`, and a host that asks then treats the call as changing all of
3008    /// the file.
3009    fn file_write_result(
3010        &self,
3011        _arguments: &str,
3012        _current: Option<&[u8]>,
3013    ) -> Option<Result<Vec<u8>, String>> {
3014        None
3015    }
3016
3017    /// What this call carries out of the machine if it only reads.
3018    fn call_outbound(&self, _arguments: &str) -> aidaemon_core::Outbound {
3019        aidaemon_core::Outbound::Nothing
3020    }
3021
3022    /// The typed effects of this exact call (effect class and normalized
3023    /// target), which the kernel checks against the owner's declines and
3024    /// hands the approval and egress policies. Build keys only with the
3025    /// kernel constructors, through `command_effects::{path_effect,
3026    /// egress_effect, url_effect}`. The default is `CallEffects::none()` for a
3027    /// tool whose capabilities are read-only and `CallEffects::unknown()`
3028    /// otherwise; a tool that can name what a call does overrides it.
3029    fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
3030        if self.capabilities().read_only {
3031            aidaemon_core::CallEffects::none()
3032        } else {
3033            aidaemon_core::CallEffects::unknown()
3034        }
3035    }
3036
3037    /// Every file or resource this exact call names as something it reads
3038    /// or writes, from typed facts only (never its prose): its declared
3039    /// target hints, its access manifest and its typed path effects. A tool
3040    /// whose arguments name more structurally (a shell command's operands)
3041    /// adds them. One reading for every tool, so a fact about a file (the
3042    /// request's own work produced it) reaches each call that names it.
3043    fn named_files(&self, arguments: &str) -> Vec<String> {
3044        declared_named_files(self, arguments)
3045    }
3046
3047    /// Authority annotations for this exact call, judged against the turn's
3048    /// trusted roots: read-only, destructive, idempotent, and whether it
3049    /// sends data or acts outside the owner's machine and workspace
3050    /// (`egress`). Derived from the call's typed semantics, never from the
3051    /// tool's name. Roots matter for effects whose class depends on where
3052    /// they land (a delete inside the owner's roots is not egress); empty
3053    /// roots mean every such target counts as outside them. The default
3054    /// ignores the roots.
3055    fn call_annotations_in(
3056        &self,
3057        arguments: &str,
3058        _roots: &TrustRoots<'_>,
3059    ) -> aidaemon_core::ToolAnnotations {
3060        default_call_annotations(self.capabilities(), &self.call_semantics(arguments))
3061    }
3062
3063    /// Who authored what this exact call returns. The default is
3064    /// `Untrusted` iff the tool reaches outside the machine
3065    /// (`external_side_effect`); local tools override with the owner's
3066    /// trusted roots.
3067    fn output_trust(
3068        &self,
3069        _arguments: &str,
3070        _roots: &TrustRoots<'_>,
3071    ) -> aidaemon_core::SourceTrust {
3072        if self.capabilities().external_side_effect {
3073            aidaemon_core::SourceTrust::Untrusted
3074        } else {
3075            aidaemon_core::SourceTrust::Trusted
3076        }
3077    }
3078
3079    /// A few plain words the call itself gave for what it does ("running
3080    /// the site installer"), for the owner's status line and lists of
3081    /// running work. Never authority. Default: none.
3082    fn call_title(&self, _arguments: &str) -> Option<String> {
3083        None
3084    }
3085
3086    /// Whether this tool is currently operational.
3087    ///
3088    /// Default: true. Override for tools with dynamic backends that may be
3089    /// temporarily unavailable at runtime.
3090    fn is_available(&self) -> bool {
3091        true
3092    }
3093
3094    /// Whether the tool is offered on a turn of `session_id`, judged from
3095    /// the tool's own typed state, never from the request's wording.
3096    ///
3097    /// Default: true. A tool whose only effect lands on one client
3098    /// connection (the agent-driven view) is offered only while that
3099    /// session's turn came from a connection that can show it.
3100    fn offered_in_session(&self, _session_id: &str) -> bool {
3101        true
3102    }
3103}
3104
3105/// Effects that send data or act outside the owner's machine and workspace,
3106/// or cannot be undone. A call with any of these is egress.
3107pub const EGRESS_EFFECTS: ToolMutationEffects = ToolMutationEffects::EXTERNAL_DELIVERY
3108    .union(ToolMutationEffects::REMOTE_MUTATION)
3109    .union(ToolMutationEffects::REMOTE_DEPLOY)
3110    .union(ToolMutationEffects::DESTRUCTIVE)
3111    .union(ToolMutationEffects::CONFIGURATION);
3112
3113/// Per-call authority annotations from a tool's capabilities and the call's
3114/// typed semantics.
3115pub fn default_call_annotations(
3116    cap: ToolCapabilities,
3117    semantics: &ToolCallSemantics,
3118) -> aidaemon_core::ToolAnnotations {
3119    let read_only = cap.read_only
3120        || (matches!(
3121            semantics.effect,
3122            ToolCallEffect::Observation | ToolCallEffect::Administrative
3123        ) && !semantics.mutates_state());
3124    let effects = semantics.mutation_effects;
3125    let egress = !read_only
3126        && (effects.intersects(EGRESS_EFFECTS)
3127            || (cap.external_side_effect && !effects.has_specific_effects()));
3128    aidaemon_core::ToolAnnotations {
3129        read_only,
3130        destructive: !read_only && effects.intersects(ToolMutationEffects::DESTRUCTIVE),
3131        idempotent: read_only,
3132        egress,
3133    }
3134}
3135
3136/// The folders a request's work made fresh for itself (a spawn's
3137/// `new_folders`, claimed empty by the runtime), shared by every run of the
3138/// request's tree. Everything inside them is the work's own: a change or a
3139/// delete there acts on nothing anyone else made. A planning and effect
3140/// fact only, never a trust source for what is read there (a package
3141/// manager fills them with other people's code).
3142#[derive(Debug, Clone, Default)]
3143pub struct OwnedFolders(std::sync::Arc<std::sync::RwLock<Vec<String>>>);
3144
3145impl OwnedFolders {
3146    /// Record folders the runtime just made for this request's work.
3147    pub fn claim(&self, folders: &[String]) {
3148        let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
3149        for folder in folders {
3150            let folder = folder.trim();
3151            if std::path::Path::new(folder).is_absolute() && !owned.iter().any(|f| f == folder) {
3152                owned.push(folder.to_string());
3153            }
3154        }
3155    }
3156
3157    /// Give back folders that were removed again (the work never started).
3158    pub fn release<P: AsRef<std::path::Path>>(&self, folders: &[P]) {
3159        let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
3160        owned.retain(|kept| {
3161            !folders
3162                .iter()
3163                .any(|folder| std::path::Path::new(kept) == folder.as_ref())
3164        });
3165    }
3166
3167    /// The folders, as claimed.
3168    pub fn list(&self) -> Vec<String> {
3169        self.0.read().unwrap_or_else(|e| e.into_inner()).clone()
3170    }
3171
3172    /// Where a call's declared writes land that does not exist yet, taken
3173    /// just before it runs: what it may create. Once it succeeded,
3174    /// [`Self::claim_created`] claims each that it did create as a folder.
3175    pub fn absent_write_targets(effects: &aidaemon_core::CallEffects) -> Vec<std::path::PathBuf> {
3176        effects
3177            .keys
3178            .iter()
3179            .filter(|key| key.class == aidaemon_core::EffectClass::Write)
3180            .map(|key| std::path::PathBuf::from(shellexpand::tilde(key.target.trim()).as_ref()))
3181            .filter(|path| path.is_absolute() && std::fs::symlink_metadata(path).is_err())
3182            .collect()
3183    }
3184
3185    /// Ownership from evidence of creation: of `absent` (taken before a
3186    /// call that then succeeded), each path that is now a folder was made
3187    /// by this request's work (`mkdir`, a project tool's init in a new
3188    /// path), so it joins the request's owned folders, as a spawn's
3189    /// declared `new_folders` do (live 2026-11-13: two helpers each created
3190    /// their site's folder without declaring it, and every later change
3191    /// there was judged as someone else's project). A folder that existed
3192    /// before never joins. Returns what it claimed.
3193    pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
3194        let created: Vec<String> = absent
3195            .iter()
3196            .filter(|path| {
3197                std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir())
3198            })
3199            .map(|path| path.display().to_string())
3200            .collect();
3201        self.claim(&created);
3202        created
3203    }
3204}
3205
3206#[cfg(test)]
3207mod owned_folder_tests {
3208    use super::OwnedFolders;
3209
3210    /// A folder a succeeded call created joins the request's own; one that
3211    /// existed before it does not, and neither does a file it wrote.
3212    #[test]
3213    fn a_folder_a_call_created_becomes_owned() {
3214        let base = tempfile::tempdir().unwrap();
3215        let fresh = base.path().join("claude-drupal-11");
3216        let file = base.path().join("notes.txt");
3217        let before = base.path().join("existing-site");
3218        std::fs::create_dir(&before).unwrap();
3219        let key = |path: &std::path::Path| aidaemon_core::EffectKey {
3220            class: aidaemon_core::EffectClass::Write,
3221            target: path.display().to_string(),
3222        };
3223        let effects = aidaemon_core::CallEffects {
3224            keys: vec![key(&fresh), key(&file), key(&before)],
3225            complete: false,
3226            understood: true,
3227        };
3228        let absent = OwnedFolders::absent_write_targets(&effects);
3229        assert_eq!(absent, vec![fresh.clone(), file.clone()]);
3230        std::fs::create_dir(&fresh).unwrap();
3231        std::fs::write(&file, "x").unwrap();
3232        let owned = OwnedFolders::default();
3233        assert_eq!(
3234            owned.claim_created(&absent),
3235            vec![fresh.display().to_string()]
3236        );
3237        assert_eq!(owned.list(), vec![fresh.display().to_string()]);
3238    }
3239}
3240
3241/// Whether absolute `path` resolves inside one of `folders`, by the one
3242/// path resolver every scope check uses (`aidaemon_policies::resolves_within`).
3243pub fn within_owned(path: &str, folders: &[String]) -> bool {
3244    let expanded = shellexpand::tilde(path.trim()).into_owned();
3245    let path = std::path::Path::new(&expanded);
3246    path.is_absolute()
3247        && folders.iter().any(|folder| {
3248            aidaemon_policies::resolves_within(path, std::path::Path::new(folder.trim()))
3249        })
3250}
3251
3252/// How one of a request's files came to be, when the request's own work
3253/// produced it ([`ProducedFiles`]).
3254#[derive(Debug, Clone, PartialEq, Eq)]
3255pub enum ProducedFile {
3256    /// A capture one of the request's calls saved, showing `kind` (a
3257    /// browser screenshot shows its page).
3258    Capture(DeliverableKind),
3259    /// A file one of the request's calls created where nothing was before.
3260    Created,
3261}
3262
3263impl ProducedFile {
3264    /// What it is, in plain words for the untrusted-call check.
3265    pub fn words(&self) -> String {
3266        match self {
3267            Self::Capture(kind) => format!("this request's own capture: {}", kind.words()),
3268            Self::Created => "a file this request's own work created".to_string(),
3269        }
3270    }
3271}
3272
3273/// The files a request's own work produced, shared by every run of its
3274/// tree, from evidence rather than anyone's account of them: a capture a
3275/// tool noted as it saved it, and a file a succeeded call created where
3276/// its declared write found nothing before ([`Self::claim_created`], the
3277/// file counterpart of [`OwnedFolders::claim_created`]). Each is the
3278/// request's own artifact wherever it is saved (a capture lands in the
3279/// daemon's inbox, outside any project). Keyed by the resolved path, and a
3280/// capture also by its resource id, so either handle a later call names
3281/// finds it. A planning and effect fact, never a trust source for what the
3282/// file holds.
3283#[derive(Debug, Clone, Default)]
3284pub struct ProducedFiles(
3285    std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, ProducedFile>>>,
3286);
3287
3288impl ProducedFiles {
3289    /// A capture was saved at `path` (with `resource_id`, when it has one)
3290    /// and shows `kind`.
3291    pub fn note_capture(&self, path: &str, resource_id: Option<&str>, kind: &DeliverableKind) {
3292        let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3293        let capture = ProducedFile::Capture(kind.clone());
3294        produced.insert(produced_key(path), capture.clone());
3295        if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
3296            produced.insert(id.to_string(), capture);
3297        }
3298    }
3299
3300    /// A tool of the request made the file at `path` itself (with
3301    /// `resource_id`, when it has one): a generated image saved to the
3302    /// daemon's inbox. A capture already noted keeps what it shows.
3303    pub fn note_created(&self, path: &str, resource_id: Option<&str>) {
3304        let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3305        produced
3306            .entry(produced_key(path))
3307            .or_insert(ProducedFile::Created);
3308        if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
3309            produced
3310                .entry(id.to_string())
3311                .or_insert(ProducedFile::Created);
3312        }
3313    }
3314
3315    /// Ownership from evidence of creation: of `absent` (taken before a
3316    /// call that then succeeded, [`OwnedFolders::absent_write_targets`]),
3317    /// each path that is now a regular file was made by this request's
3318    /// work. A file that existed before never joins, and a capture already
3319    /// noted keeps what it shows. Returns what it claimed.
3320    pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
3321        let created: Vec<String> = absent
3322            .iter()
3323            .filter(|path| std::fs::symlink_metadata(path).is_ok_and(|meta| meta.is_file()))
3324            .map(|path| path.display().to_string())
3325            .collect();
3326        let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3327        for path in &created {
3328            produced
3329                .entry(produced_key(path))
3330                .or_insert(ProducedFile::Created);
3331        }
3332        created
3333    }
3334
3335    /// What the request's work produced at `target` (a path, or a
3336    /// capture's resource id), when it produced it.
3337    pub fn get(&self, target: &str) -> Option<ProducedFile> {
3338        self.0
3339            .read()
3340            .unwrap_or_else(|e| e.into_inner())
3341            .get(&produced_key(target))
3342            .cloned()
3343    }
3344
3345    /// What the capture saved at `path` shows, when one was noted: a later
3346    /// `send_file` of that path delivers that kind, not a file of its own.
3347    pub fn capture_kind(&self, path: &str) -> Option<DeliverableKind> {
3348        match self.get(path)? {
3349            ProducedFile::Capture(kind) => Some(kind),
3350            ProducedFile::Created => None,
3351        }
3352    }
3353
3354    /// Every handle noted, each a path or a capture's resource id, with
3355    /// what it is.
3356    pub fn entries(&self) -> Vec<(String, ProducedFile)> {
3357        self.0
3358            .read()
3359            .unwrap_or_else(|e| e.into_inner())
3360            .iter()
3361            .map(|(key, file)| (key.clone(), file.clone()))
3362            .collect()
3363    }
3364
3365    /// Of the files and resources a call names (its
3366    /// [`ToolSemantics::named_files`]), the ones this request's work
3367    /// produced, each as named.
3368    pub fn named_by(&self, named: &[String]) -> Vec<(String, ProducedFile)> {
3369        named
3370            .iter()
3371            .filter_map(|name| Some((name.clone(), self.get(name)?)))
3372            .collect()
3373    }
3374}
3375
3376/// The files and resources a call names by its declared facts (see
3377/// [`ToolSemantics::named_files`]): its path and resource-id target hints,
3378/// its access manifest's path targets, and its path effects' targets.
3379pub fn declared_named_files<T: ToolSemantics + ?Sized>(tool: &T, arguments: &str) -> Vec<String> {
3380    let mut named: Vec<String> = Vec::new();
3381    let mut add = |value: &str| {
3382        let value = value.trim();
3383        if !value.is_empty() && !named.iter().any(|known| known == value) {
3384            named.push(value.to_string());
3385        }
3386    };
3387    for hint in tool.call_semantics(arguments).target_hints {
3388        if matches!(
3389            hint.kind,
3390            ToolTargetHintKind::Path | ToolTargetHintKind::ResourceId
3391        ) {
3392            add(&hint.value);
3393        }
3394    }
3395    let manifest = tool.call_access_manifest(arguments);
3396    for hint in manifest
3397        .read_targets
3398        .iter()
3399        .chain(manifest.write_targets.iter())
3400    {
3401        if hint.kind == ToolTargetHintKind::Path {
3402            add(&hint.value);
3403        }
3404    }
3405    for key in tool.call_effects(arguments).keys {
3406        if matches!(
3407            key.class,
3408            aidaemon_core::EffectClass::Write
3409                | aidaemon_core::EffectClass::Delete
3410                | aidaemon_core::EffectClass::Configuration
3411        ) {
3412            add(&key.target);
3413        }
3414    }
3415    named
3416}
3417
3418/// A produced file's key, whichever spelling names it: a path as it
3419/// resolves on disk (when it does), anything else (a resource id) as given.
3420fn produced_key(target: &str) -> String {
3421    let expanded = shellexpand::tilde(target.trim()).into_owned();
3422    dunce::canonicalize(&expanded)
3423        .map(|path| path.to_string_lossy().into_owned())
3424        .unwrap_or(expanded)
3425}
3426
3427/// The request's produced files, carried in [`ToolCallContext::extensions`]
3428/// by a host that keeps them.
3429pub fn produced_files(facts: &ToolCallContext) -> Option<&ProducedFiles> {
3430    facts.extensions.get::<ProducedFiles>()
3431}
3432
3433#[cfg(test)]
3434mod produced_file_tests {
3435    use super::{DeliverableKind, ProducedFile, ProducedFiles};
3436
3437    /// A file a tool made itself (a generated image in the inbox) is the
3438    /// request's own by its path and by its resource id; a capture noted
3439    /// at that path keeps what it shows.
3440    #[test]
3441    fn a_file_a_tool_made_is_the_requests_own_by_path_and_id() {
3442        let produced = ProducedFiles::default();
3443        produced.note_created("/inbox/018d9d29_generated_image.png", Some("res_img"));
3444        assert_eq!(
3445            produced.get("/inbox/018d9d29_generated_image.png"),
3446            Some(ProducedFile::Created)
3447        );
3448        assert_eq!(produced.get("res_img"), Some(ProducedFile::Created));
3449        let page = DeliverableKind::Screenshot {
3450            page: "demo.ddev.site".to_string(),
3451        };
3452        produced.note_capture("/inbox/shot.png", None, &page);
3453        produced.note_created("/inbox/shot.png", None);
3454        assert_eq!(produced.capture_kind("/inbox/shot.png"), Some(page));
3455    }
3456
3457    /// A capture is found by its path in any spelling and by its resource
3458    /// id; a file a call created joins, one that existed before does not,
3459    /// and a capture keeps what it shows.
3460    #[test]
3461    fn the_requests_own_files_come_from_evidence() {
3462        let base = tempfile::tempdir().unwrap();
3463        let shot = base.path().join("ea19c410_screenshot.png");
3464        std::fs::write(&shot, b"png").unwrap();
3465        let page = DeliverableKind::Screenshot {
3466            page: "claude-drupal.ddev.site".to_string(),
3467        };
3468        let produced = ProducedFiles::default();
3469        produced.note_capture(&shot.display().to_string(), Some("res_1"), &page);
3470        let spelled = base
3471            .path()
3472            .join(".")
3473            .join("ea19c410_screenshot.png")
3474            .display()
3475            .to_string();
3476        assert_eq!(produced.capture_kind(&spelled), Some(page.clone()));
3477        assert_eq!(
3478            produced.get("res_1"),
3479            Some(ProducedFile::Capture(page.clone()))
3480        );
3481
3482        let fresh = base.path().join("report.md");
3483        let older = base.path().join("notes.md");
3484        std::fs::write(&older, "x").unwrap();
3485        let absent = vec![fresh.clone(), shot.clone()];
3486        std::fs::write(&fresh, "x").unwrap();
3487        assert_eq!(produced.claim_created(&absent).len(), 2);
3488        assert_eq!(
3489            produced.get(&fresh.display().to_string()),
3490            Some(ProducedFile::Created)
3491        );
3492        assert_eq!(
3493            produced.capture_kind(&shot.display().to_string()),
3494            Some(page)
3495        );
3496        assert_eq!(produced.get(&older.display().to_string()), None);
3497
3498        let named = produced.named_by(&[older.display().to_string(), fresh.display().to_string()]);
3499        assert_eq!(named.len(), 1);
3500        assert_eq!(named[0].1, ProducedFile::Created);
3501    }
3502}
3503
3504/// The owner's trusted file roots for one turn. A path is trusted only when
3505/// it normalizes without escaping and equals a root or sits below it. A
3506/// relative path resolves against `cwd` (where the file tools resolve it);
3507/// without one it is never trusted.
3508///
3509/// `owned` are the folders the request's work made for itself
3510/// ([`OwnedFolders`]): an effect landing there is the work's own
3511/// ([`Self::holds_effect`]), but what is read there is not trusted for it.
3512pub struct TrustRoots<'a> {
3513    roots: &'a [String],
3514    owned: &'a [String],
3515    cwd: Option<&'a str>,
3516}
3517
3518impl<'a> TrustRoots<'a> {
3519    pub fn new(roots: &'a [String]) -> Self {
3520        Self {
3521            roots,
3522            owned: &[],
3523            cwd: None,
3524        }
3525    }
3526
3527    /// The folders the request's work made for itself.
3528    pub fn with_owned(mut self, owned: &'a [String]) -> Self {
3529        self.owned = owned;
3530        self
3531    }
3532
3533    /// Resolve relative paths against `cwd` (an absolute directory).
3534    pub fn with_cwd(mut self, cwd: Option<&'a str>) -> Self {
3535        self.cwd = cwd;
3536        self
3537    }
3538
3539    /// The same roots with relative paths resolved against `cwd` instead
3540    /// (a call that runs in its own directory).
3541    pub fn anchored_at<'b>(&'b self, cwd: Option<&'b str>) -> TrustRoots<'b> {
3542        TrustRoots {
3543            roots: self.roots,
3544            owned: self.owned,
3545            cwd,
3546        }
3547    }
3548
3549    /// Whether an effect (a change, a delete) on `path` stays with the
3550    /// owner's own things: inside a trusted root, or inside a folder the
3551    /// request's work made for itself. Never a statement about trusting
3552    /// what is read there ([`Self::contains`] is).
3553    pub fn holds_effect(&self, path: &str) -> bool {
3554        if self.contains(path) {
3555            return true;
3556        }
3557        let resolved = match self.cwd {
3558            Some(cwd) if !is_absolute_or_home(path) => {
3559                format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
3560            }
3561            _ => path.to_string(),
3562        };
3563        within_owned(&resolved, self.owned)
3564    }
3565
3566    /// Whether `path` is inside a folder the request's work made for
3567    /// itself (not merely inside a trusted root).
3568    pub fn owns(&self, path: &str) -> bool {
3569        within_owned(path, self.owned)
3570    }
3571
3572    /// The directory relative paths resolve against, if any.
3573    pub fn cwd(&self) -> Option<&str> {
3574        self.cwd
3575    }
3576
3577    pub fn contains(&self, path: &str) -> bool {
3578        let resolved = match self.cwd {
3579            Some(cwd) if !is_absolute_or_home(path) => {
3580                format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
3581            }
3582            _ => path.to_string(),
3583        };
3584        let Some(path) = resolve_absolute(&resolved) else {
3585            return false;
3586        };
3587        self.roots
3588            .iter()
3589            .any(|root| resolve_absolute(root).is_some_and(|root| path.starts_with(&root)))
3590    }
3591}
3592
3593/// Output trust of a file read: the owner's own files (inside the trusted
3594/// roots) are `Trusted`; anything else, or a call whose first present path
3595/// argument in `keys` is missing, is someone else's content.
3596pub fn file_output_trust(
3597    arguments: &str,
3598    keys: &[&str],
3599    roots: &TrustRoots<'_>,
3600) -> aidaemon_core::SourceTrust {
3601    let args = serde_json::from_str::<Value>(arguments).ok();
3602    let path = args.as_ref().and_then(|args| {
3603        keys.iter()
3604            .find_map(|key| args.get(*key).and_then(Value::as_str))
3605    });
3606    match path {
3607        Some(path) if roots.contains(path) => aidaemon_core::SourceTrust::Trusted,
3608        _ => aidaemon_core::SourceTrust::Untrusted,
3609    }
3610}
3611
3612/// Expand `~`, then resolve the path the way the filesystem will: every
3613/// existing prefix through its symlinks (a link inside a root that points
3614/// elsewhere leaves the root), the rest lexically. `None` for a relative
3615/// path or one whose `..` climbs above the root.
3616fn resolve_absolute(path: &str) -> Option<std::path::PathBuf> {
3617    use std::path::{Component, PathBuf};
3618    let expanded = shellexpand::tilde(path.trim()).into_owned();
3619    let path = std::path::Path::new(&expanded);
3620    if !path.is_absolute() {
3621        return None;
3622    }
3623    let mut resolved = PathBuf::new();
3624    let mut existing = true;
3625    for component in path.components() {
3626        match component {
3627            Component::CurDir => {}
3628            Component::ParentDir => {
3629                if !resolved.pop() {
3630                    return None;
3631                }
3632            }
3633            Component::Normal(part) => {
3634                resolved.push(part);
3635                if existing {
3636                    match dunce::canonicalize(&resolved) {
3637                        Ok(canonical) => resolved = canonical,
3638                        Err(_) => existing = false,
3639                    }
3640                }
3641            }
3642            other => resolved.push(other.as_os_str()),
3643        }
3644    }
3645    Some(resolved)
3646}
3647
3648fn is_absolute_or_home(path: &str) -> bool {
3649    let path = path.trim();
3650    // `has_root`: on Windows `\etc\hosts` is on the current drive, not
3651    // under the working directory (and, with no drive, never trusted).
3652    let path_ref = std::path::Path::new(path);
3653    path.starts_with('~') || path_ref.is_absolute() || path_ref.has_root()
3654}
3655
3656/// Validated, canonical tool input. This is the boundary object shared by
3657/// policy, retry, dispatch, and receipt projection; raw model JSON is not an
3658/// execution fact.
3659#[derive(Debug, Clone, PartialEq, Eq)]
3660pub struct PreparedToolInvocation {
3661    pub canonical_arguments: String,
3662    pub semantics: ToolCallSemantics,
3663    pub access_manifest: ToolCallAccessManifest,
3664    pub receipt_kind: ToolReceiptKind,
3665}
3666
3667/// Produce the single typed invocation object consumed by the execution
3668/// control plane. Validation deliberately precedes semantics and access
3669/// derivation so a rejected proposal can never acquire intended effects.
3670pub fn prepare_invocation<T: ToolSemantics + ?Sized>(
3671    tool: &T,
3672    arguments: &str,
3673) -> Result<PreparedToolInvocation, ToolArgumentContractViolation> {
3674    let canonical_arguments = tool.canonicalize_arguments(arguments)?;
3675    tool.validate_arguments(&canonical_arguments)?;
3676    Ok(PreparedToolInvocation {
3677        semantics: tool.call_semantics(&canonical_arguments),
3678        access_manifest: tool.call_access_manifest(&canonical_arguments),
3679        receipt_kind: tool.receipt_kind(&canonical_arguments),
3680        canonical_arguments,
3681    })
3682}
3683
3684#[cfg(test)]
3685mod file_trust_tests {
3686    use super::{TrustRoots, file_output_trust};
3687    use aidaemon_core::SourceTrust::{Trusted, Untrusted};
3688
3689    #[test]
3690    fn files_inside_the_trusted_roots_are_trusted() {
3691        let roots = vec!["/tmp/aidaemon-test/ws".to_string()];
3692        let roots = TrustRoots::new(&roots);
3693        let keys = ["path", "file_path"];
3694        assert_eq!(
3695            file_output_trust(r#"{"path":"/tmp/aidaemon-test/ws/a.txt"}"#, &keys, &roots),
3696            Trusted
3697        );
3698        assert_eq!(
3699            file_output_trust(
3700                r#"{"file_path":"/tmp/aidaemon-test/ws/a.txt"}"#,
3701                &keys,
3702                &roots
3703            ),
3704            Trusted
3705        );
3706        assert_eq!(
3707            file_output_trust(r#"{"path":"/etc/hosts"}"#, &keys, &roots),
3708            Untrusted
3709        );
3710        assert_eq!(file_output_trust(r#"{}"#, &keys, &roots), Untrusted);
3711        assert_eq!(file_output_trust("not json", &keys, &roots), Untrusted);
3712    }
3713}
3714
3715fn is_zero(value: &usize) -> bool {
3716    *value == 0
3717}
3718
3719#[cfg(test)]
3720mod local_write_satisfaction_tests {
3721    use super::ToolMutationEffects as E;
3722
3723    /// Workspace and derived writes close each other's plans; a source edit
3724    /// is proven only by a source write.
3725    #[test]
3726    fn local_write_labels_satisfy_each_other_except_source() {
3727        assert!(E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
3728        assert!(E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
3729        assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
3730        assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
3731        assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
3732        assert!(!E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
3733        assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::EXTERNAL_DELIVERY));
3734    }
3735}