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