Skip to main content

code_system_graph_core/
execution_policy.rs

1use std::fmt::Write as _;
2use std::num::NonZeroUsize;
3use std::time::{Duration, Instant};
4
5use code_system_graph_model::stable_id;
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8use thiserror::Error;
9
10mod tracker;
11
12pub use tracker::{MonotonicClock, ScanJobTracker};
13
14/// Default maximum wall time for one supervised scan or sync pass.
15pub const DEFAULT_MAX_SCAN_WALL_TIME_MS: u64 = 21_600_000;
16/// Default maximum time without verified forward progress.
17pub const DEFAULT_MAX_NO_PROGRESS_TIME_MS: u64 = 300_000;
18/// Default maximum wall time for one repository-local `CodeGraph` synchronization.
19pub const DEFAULT_MAX_CODEGRAPH_SYNC_WALL_TIME_MS_PER_REPO: u64 = 3_600_000;
20/// Default maximum source-symbol anchors corroborated through `CodeGraph` per repository.
21pub const DEFAULT_MAX_CODEGRAPH_CORROBORATION_ANCHORS_PER_REPO: i64 = 50;
22/// Default maximum resident memory accepted for one worker process.
23pub const DEFAULT_MAX_WORKER_MEMORY_BYTES: u64 = 17_179_869_184;
24/// Default cooperative shutdown grace period before forced termination.
25pub const DEFAULT_GRACEFUL_TERMINATION_MS: u64 = 5_000;
26/// Default inactivity lease for a foreground watch session.
27pub const DEFAULT_WATCH_IDLE_TIMEOUT_MS: u64 = 28_800_000;
28/// Default absolute lifetime for one foreground watch session.
29pub const DEFAULT_MAX_WATCH_SESSION_WALL_TIME_MS: u64 = 86_400_000;
30/// Default minimum delay between watched sync pass starts.
31pub const DEFAULT_MIN_WATCH_RESCAN_INTERVAL_MS: u64 = 10_000;
32/// Default maximum retained historical checkpoint-cache bytes.
33pub const DEFAULT_MAX_CHECKPOINT_CACHE_BYTES: u64 = 10_737_418_240;
34pub const DEFAULT_MAX_EXPLORE_WALL_TIME_MS: u64 = 8_000;
35pub const DEFAULT_MAX_EXPLORE_CODEGRAPH_OPERATIONS: u64 = 8;
36pub const DEFAULT_MAX_EXPLORE_CONCURRENT_CODEGRAPH_PROCESSES: u64 = 2;
37pub const DEFAULT_MAX_EXPLORE_SOURCE_FILES: u64 = 25;
38pub const DEFAULT_MAX_EXPLORE_RESOLVED_SYMBOLS: u64 = 5;
39pub const DEFAULT_MAX_EXPLORE_ANCHORS: u64 = 3;
40pub const DEFAULT_MAX_EXPLORE_NEIGHBORS_PER_DIRECTION: u64 = 8;
41pub const DEFAULT_MAX_EXPLORE_LOCAL_RELATIONSHIPS: u64 = 48;
42pub const DEFAULT_MAX_EXPLORE_FEDERATED_HANDOFFS_PER_ANCHOR: u64 = 10;
43pub const DEFAULT_MAX_EXPLORE_FEDERATED_HANDOFFS: u64 = 30;
44pub const DEFAULT_MAX_EXPLORE_EVIDENCE_LOCATIONS_PER_HANDOFF: u64 = 4;
45pub const DEFAULT_MAX_EXPLORE_SOURCE_MARKDOWN_BYTES: u64 = 262_144;
46pub const DEFAULT_MAX_EXPLORE_ENRICHMENT_BYTES: u64 = 65_536;
47pub const DEFAULT_MAX_AGENT_NEXT_ACTIONS_PER_RESPONSE: u64 = 12;
48pub const DEFAULT_MAX_QUERY_REPOSITORY_SUGGESTIONS: u64 = 20;
49pub const DEFAULT_MAX_MCP_TOOL_RESPONSE_BYTES: u64 = 524_288;
50pub const DEFAULT_MAX_MCP_RESOURCE_ITEMS: u64 = 100;
51pub const DEFAULT_MAX_MCP_RESOURCE_BYTES: u64 = 262_144;
52pub const DEFAULT_MAX_MCP_SCHEMA_CATALOG_BYTES: u64 = 2_097_152;
53/// Smallest Markdown response budget that can retain the mandatory MCP control block.
54pub const MIN_MCP_MARKDOWN_BYTES: u64 = 256;
55
56// Keep the agent-facing policy inventory in one declarative list. The two public serde structs
57// intentionally remain flat for schema-v2 compatibility; defaults, override resolution, and the
58// delivery fingerprint are generated from this list so a new field cannot silently omit one of
59// those behaviors.
60macro_rules! with_agent_policy_fields {
61    ($consumer:ident) => {
62        $consumer! {
63            max_explore_wall_time_ms: DEFAULT_MAX_EXPLORE_WALL_TIME_MS => "maxExploreWallTimeMs";
64            max_explore_codegraph_operations: DEFAULT_MAX_EXPLORE_CODEGRAPH_OPERATIONS => "maxExploreCodeGraphOperations";
65            max_explore_concurrent_codegraph_processes: DEFAULT_MAX_EXPLORE_CONCURRENT_CODEGRAPH_PROCESSES => "maxExploreConcurrentCodeGraphProcesses";
66            max_explore_source_files: DEFAULT_MAX_EXPLORE_SOURCE_FILES => "maxExploreSourceFiles";
67            max_explore_resolved_symbols: DEFAULT_MAX_EXPLORE_RESOLVED_SYMBOLS => "maxExploreResolvedSymbols";
68            max_explore_anchors: DEFAULT_MAX_EXPLORE_ANCHORS => "maxExploreAnchors";
69            max_explore_neighbors_per_direction: DEFAULT_MAX_EXPLORE_NEIGHBORS_PER_DIRECTION => "maxExploreNeighborsPerDirection";
70            max_explore_local_relationships: DEFAULT_MAX_EXPLORE_LOCAL_RELATIONSHIPS => "maxExploreLocalRelationships";
71            max_explore_federated_handoffs_per_anchor: DEFAULT_MAX_EXPLORE_FEDERATED_HANDOFFS_PER_ANCHOR => "maxExploreFederatedHandoffsPerAnchor";
72            max_explore_federated_handoffs: DEFAULT_MAX_EXPLORE_FEDERATED_HANDOFFS => "maxExploreFederatedHandoffs";
73            max_explore_evidence_locations_per_handoff: DEFAULT_MAX_EXPLORE_EVIDENCE_LOCATIONS_PER_HANDOFF => "maxExploreEvidenceLocationsPerHandoff";
74            max_explore_source_markdown_bytes: DEFAULT_MAX_EXPLORE_SOURCE_MARKDOWN_BYTES => "maxExploreSourceMarkdownBytes";
75            max_explore_enrichment_bytes: DEFAULT_MAX_EXPLORE_ENRICHMENT_BYTES => "maxExploreEnrichmentBytes";
76            max_agent_next_actions_per_response: DEFAULT_MAX_AGENT_NEXT_ACTIONS_PER_RESPONSE => "maxAgentNextActionsPerResponse";
77            max_query_repository_suggestions: DEFAULT_MAX_QUERY_REPOSITORY_SUGGESTIONS => "maxQueryRepositorySuggestions";
78            max_mcp_tool_response_bytes: DEFAULT_MAX_MCP_TOOL_RESPONSE_BYTES => "maxMcpToolResponseBytes";
79            max_mcp_resource_items: DEFAULT_MAX_MCP_RESOURCE_ITEMS => "maxMcpResourceItems";
80            max_mcp_resource_bytes: DEFAULT_MAX_MCP_RESOURCE_BYTES => "maxMcpResourceBytes";
81            max_mcp_schema_catalog_bytes: DEFAULT_MAX_MCP_SCHEMA_CATALOG_BYTES => "maxMcpSchemaCatalogBytes";
82        }
83    };
84}
85
86/// Effective per-repository limit for source-symbol corroboration through `CodeGraph`.
87///
88/// The workspace manifest keeps `-1` as its portable unlimited sentinel, but resolved policy and
89/// consumers use this type so that sentinel handling does not leak beyond the serde boundary.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, JsonSchema)]
91pub enum CodeGraphCorroborationAnchorLimit {
92    /// Corroborate at most this many source-symbol anchors per repository.
93    Bounded(NonZeroUsize),
94    /// Do not apply a count limit.
95    Unlimited,
96}
97
98impl CodeGraphCorroborationAnchorLimit {
99    /// Returns the bounded limit, or `None` when corroboration is unlimited.
100    #[must_use]
101    pub const fn bounded(self) -> Option<NonZeroUsize> {
102        match self {
103            Self::Bounded(limit) => Some(limit),
104            Self::Unlimited => None,
105        }
106    }
107}
108
109impl TryFrom<i64> for CodeGraphCorroborationAnchorLimit {
110    type Error = InvalidExecutionPolicy;
111
112    fn try_from(value: i64) -> Result<Self, Self::Error> {
113        if value == -1 {
114            return Ok(Self::Unlimited);
115        }
116        let limit = usize::try_from(value)
117            .ok()
118            .and_then(NonZeroUsize::new)
119            .ok_or(InvalidExecutionPolicy::InvalidValue {
120                field: "maxCodeGraphCorroborationAnchorsPerRepo",
121                value: value.unsigned_abs(),
122            })?;
123        Ok(Self::Bounded(limit))
124    }
125}
126
127impl Serialize for CodeGraphCorroborationAnchorLimit {
128    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
129    where
130        S: serde::Serializer,
131    {
132        let value = match self {
133            Self::Bounded(limit) => i64::try_from(limit.get()).map_err(|_| {
134                serde::ser::Error::custom("CodeGraph corroboration anchor limit exceeds i64")
135            })?,
136            Self::Unlimited => -1,
137        };
138        serializer.serialize_i64(value)
139    }
140}
141
142impl<'de> Deserialize<'de> for CodeGraphCorroborationAnchorLimit {
143    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
144    where
145        D: serde::Deserializer<'de>,
146    {
147        i64::deserialize(deserializer)?
148            .try_into()
149            .map_err(serde::de::Error::custom)
150    }
151}
152
153impl std::fmt::Display for CodeGraphCorroborationAnchorLimit {
154    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        match self {
156            Self::Bounded(limit) => limit.fmt(formatter),
157            Self::Unlimited => formatter.write_str("-1"),
158        }
159    }
160}
161
162/// Optional operator-owned execution-policy overrides from the workspace manifest.
163#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
164#[serde(rename_all = "camelCase", deny_unknown_fields)]
165pub struct ExecutionPolicyOverrides {
166    /// Optional maximum wall time for one scan or sync pass.
167    pub max_scan_wall_time_ms: Option<u64>,
168    /// Optional maximum time without verified forward progress.
169    pub max_no_progress_time_ms: Option<u64>,
170    /// Optional per-repository `CodeGraph` synchronization wall time.
171    #[serde(rename = "maxCodeGraphSyncWallTimeMsPerRepo")]
172    pub max_codegraph_sync_wall_time_ms_per_repo: Option<u64>,
173    /// Optional maximum worker resident memory.
174    pub max_worker_memory_bytes: Option<u64>,
175    /// Optional cooperative shutdown grace period.
176    pub graceful_termination_ms: Option<u64>,
177    /// Optional watcher inactivity lease.
178    pub watch_idle_timeout_ms: Option<u64>,
179    /// Optional absolute watcher-session lifetime.
180    pub max_watch_session_wall_time_ms: Option<u64>,
181    /// Optional minimum delay between watched sync pass starts.
182    pub min_watch_rescan_interval_ms: Option<u64>,
183    /// Optional maximum retained checkpoint-cache bytes.
184    pub max_checkpoint_cache_bytes: Option<u64>,
185    /// Optional corroboration-anchor count, or `-1` for unlimited.
186    #[serde(rename = "maxCodeGraphCorroborationAnchorsPerRepo")]
187    pub max_codegraph_corroboration_anchors_per_repo: Option<i64>,
188    /// Optional Explore wall-time budget.
189    pub max_explore_wall_time_ms: Option<u64>,
190    /// Optional maximum public provider operations per Explore request.
191    #[serde(rename = "maxExploreCodeGraphOperations")]
192    pub max_explore_codegraph_operations: Option<u64>,
193    /// Optional maximum concurrent provider child processes.
194    #[serde(rename = "maxExploreConcurrentCodeGraphProcesses")]
195    pub max_explore_concurrent_codegraph_processes: Option<u64>,
196    /// Optional maximum source files returned by Explore.
197    pub max_explore_source_files: Option<u64>,
198    /// Optional maximum resolved local symbols.
199    pub max_explore_resolved_symbols: Option<u64>,
200    /// Optional maximum symbols selected as traversal anchors.
201    pub max_explore_anchors: Option<u64>,
202    /// Optional maximum neighbors per anchor and direction.
203    pub max_explore_neighbors_per_direction: Option<u64>,
204    /// Optional maximum retained local relationships.
205    pub max_explore_local_relationships: Option<u64>,
206    /// Optional maximum federated handoffs per anchor.
207    pub max_explore_federated_handoffs_per_anchor: Option<u64>,
208    /// Optional maximum federated handoffs per response.
209    pub max_explore_federated_handoffs: Option<u64>,
210    /// Optional maximum evidence locations per federated handoff.
211    pub max_explore_evidence_locations_per_handoff: Option<u64>,
212    /// Optional maximum retained source Markdown bytes.
213    pub max_explore_source_markdown_bytes: Option<u64>,
214    /// Optional maximum retained enrichment bytes.
215    pub max_explore_enrichment_bytes: Option<u64>,
216    /// Optional maximum agent next actions per response.
217    pub max_agent_next_actions_per_response: Option<u64>,
218    /// Optional maximum repository suggestions from Query.
219    pub max_query_repository_suggestions: Option<u64>,
220    /// Optional final MCP tool response byte limit.
221    pub max_mcp_tool_response_bytes: Option<u64>,
222    /// Optional MCP resource item limit.
223    pub max_mcp_resource_items: Option<u64>,
224    /// Optional final MCP resource byte limit.
225    pub max_mcp_resource_bytes: Option<u64>,
226    /// Optional final MCP schema-catalog byte limit.
227    pub max_mcp_schema_catalog_bytes: Option<u64>,
228}
229
230/// Effective global execution policy for one workspace operation.
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
232#[serde(rename_all = "camelCase")]
233pub struct ExecutionPolicy {
234    /// Maximum wall time for one scan or sync pass.
235    pub max_scan_wall_time_ms: u64,
236    /// Maximum time without verified forward progress.
237    pub max_no_progress_time_ms: u64,
238    /// Maximum wall time for one repository-local `CodeGraph` synchronization.
239    #[serde(rename = "maxCodeGraphSyncWallTimeMsPerRepo")]
240    pub max_codegraph_sync_wall_time_ms_per_repo: u64,
241    /// Maximum resident memory accepted for one worker process.
242    pub max_worker_memory_bytes: u64,
243    /// Cooperative shutdown grace period before forced termination.
244    pub graceful_termination_ms: u64,
245    /// Inactivity lease for a foreground watch session.
246    pub watch_idle_timeout_ms: u64,
247    /// Absolute lifetime for one foreground watch session.
248    pub max_watch_session_wall_time_ms: u64,
249    /// Minimum delay between watched sync pass starts.
250    pub min_watch_rescan_interval_ms: u64,
251    /// Maximum retained historical checkpoint-cache bytes.
252    pub max_checkpoint_cache_bytes: u64,
253    /// Effective corroboration-anchor count, or unlimited.
254    #[serde(rename = "maxCodeGraphCorroborationAnchorsPerRepo")]
255    #[schemars(with = "i64")]
256    pub max_codegraph_corroboration_anchors_per_repo: CodeGraphCorroborationAnchorLimit,
257    /// Effective Explore wall-time budget.
258    pub max_explore_wall_time_ms: u64,
259    /// Effective maximum public provider operations per Explore request.
260    #[serde(rename = "maxExploreCodeGraphOperations")]
261    pub max_explore_codegraph_operations: u64,
262    /// Effective maximum concurrent provider child processes.
263    #[serde(rename = "maxExploreConcurrentCodeGraphProcesses")]
264    pub max_explore_concurrent_codegraph_processes: u64,
265    /// Effective maximum source files returned by Explore.
266    pub max_explore_source_files: u64,
267    /// Effective maximum resolved local symbols.
268    pub max_explore_resolved_symbols: u64,
269    /// Effective maximum symbols selected as traversal anchors.
270    pub max_explore_anchors: u64,
271    /// Effective maximum neighbors per anchor and direction.
272    pub max_explore_neighbors_per_direction: u64,
273    /// Effective maximum retained local relationships.
274    pub max_explore_local_relationships: u64,
275    /// Effective maximum federated handoffs per anchor.
276    pub max_explore_federated_handoffs_per_anchor: u64,
277    /// Effective maximum federated handoffs per response.
278    pub max_explore_federated_handoffs: u64,
279    /// Effective maximum evidence locations per federated handoff.
280    pub max_explore_evidence_locations_per_handoff: u64,
281    /// Effective maximum retained source Markdown bytes.
282    pub max_explore_source_markdown_bytes: u64,
283    /// Effective maximum retained enrichment bytes.
284    pub max_explore_enrichment_bytes: u64,
285    /// Effective maximum agent next actions per response.
286    pub max_agent_next_actions_per_response: u64,
287    /// Effective maximum repository suggestions from Query.
288    pub max_query_repository_suggestions: u64,
289    /// Effective final MCP tool response byte limit.
290    pub max_mcp_tool_response_bytes: u64,
291    /// Effective MCP resource item limit.
292    pub max_mcp_resource_items: u64,
293    /// Effective final MCP resource byte limit.
294    pub max_mcp_resource_bytes: u64,
295    /// Effective final MCP schema-catalog byte limit.
296    pub max_mcp_schema_catalog_bytes: u64,
297}
298
299impl Default for ExecutionPolicy {
300    fn default() -> Self {
301        macro_rules! policy_defaults {
302            ($($field:ident: $default:ident => $external:literal;)*) => {
303                Self {
304            max_scan_wall_time_ms: DEFAULT_MAX_SCAN_WALL_TIME_MS,
305            max_no_progress_time_ms: DEFAULT_MAX_NO_PROGRESS_TIME_MS,
306            max_codegraph_sync_wall_time_ms_per_repo:
307                DEFAULT_MAX_CODEGRAPH_SYNC_WALL_TIME_MS_PER_REPO,
308            max_worker_memory_bytes: DEFAULT_MAX_WORKER_MEMORY_BYTES,
309            graceful_termination_ms: DEFAULT_GRACEFUL_TERMINATION_MS,
310            watch_idle_timeout_ms: DEFAULT_WATCH_IDLE_TIMEOUT_MS,
311            max_watch_session_wall_time_ms: DEFAULT_MAX_WATCH_SESSION_WALL_TIME_MS,
312            min_watch_rescan_interval_ms: DEFAULT_MIN_WATCH_RESCAN_INTERVAL_MS,
313            max_checkpoint_cache_bytes: DEFAULT_MAX_CHECKPOINT_CACHE_BYTES,
314            max_codegraph_corroboration_anchors_per_repo:
315                CodeGraphCorroborationAnchorLimit::try_from(
316                    DEFAULT_MAX_CODEGRAPH_CORROBORATION_ANCHORS_PER_REPO,
317                )
318                .expect("the built-in corroboration limit is valid"),
319                    $($field: $default,)*
320                }
321            };
322        }
323        with_agent_policy_fields!(policy_defaults)
324    }
325}
326
327impl ExecutionPolicy {
328    /// Resolves a partial global override and validates the effective relationships.
329    ///
330    /// # Errors
331    ///
332    /// Returns [`InvalidExecutionPolicy`] for zero, unrepresentable, or inconsistent values.
333    pub fn resolve(
334        overrides: Option<&ExecutionPolicyOverrides>,
335    ) -> Result<Self, InvalidExecutionPolicy> {
336        let mut policy = Self::default();
337        if let Some(values) = overrides {
338            macro_rules! apply {
339                ($field:ident) => {
340                    if let Some(value) = values.$field {
341                        policy.$field = value;
342                    }
343                };
344            }
345            apply!(max_scan_wall_time_ms);
346            apply!(max_no_progress_time_ms);
347            apply!(max_codegraph_sync_wall_time_ms_per_repo);
348            apply!(max_worker_memory_bytes);
349            apply!(graceful_termination_ms);
350            apply!(watch_idle_timeout_ms);
351            apply!(max_watch_session_wall_time_ms);
352            apply!(min_watch_rescan_interval_ms);
353            apply!(max_checkpoint_cache_bytes);
354            if let Some(value) = values.max_codegraph_corroboration_anchors_per_repo {
355                policy.max_codegraph_corroboration_anchors_per_repo = value.try_into()?;
356            }
357            macro_rules! apply_agent_overrides {
358                ($($field:ident: $default:ident => $external:literal;)*) => {
359                    $(apply!($field);)*
360                };
361            }
362            with_agent_policy_fields!(apply_agent_overrides);
363        }
364        policy.validate()?;
365        Ok(policy)
366    }
367
368    fn validate(&self) -> Result<(), InvalidExecutionPolicy> {
369        self.validate_scalar_values()?;
370        self.validate_mcp_minimums()?;
371        self.validate_scan_relationships()?;
372        self.validate_explore_relationships()
373    }
374
375    fn validate_mcp_minimums(&self) -> Result<(), InvalidExecutionPolicy> {
376        for (field, value) in [
377            ("maxMcpToolResponseBytes", self.max_mcp_tool_response_bytes),
378            ("maxMcpResourceBytes", self.max_mcp_resource_bytes),
379            (
380                "maxMcpSchemaCatalogBytes",
381                self.max_mcp_schema_catalog_bytes,
382            ),
383        ] {
384            if value < MIN_MCP_MARKDOWN_BYTES {
385                return Err(InvalidExecutionPolicy::BelowMinimum {
386                    field,
387                    value,
388                    minimum: MIN_MCP_MARKDOWN_BYTES,
389                });
390            }
391        }
392        Ok(())
393    }
394
395    fn validate_scalar_values(&self) -> Result<(), InvalidExecutionPolicy> {
396        for (field, value) in self
397            .scan_canonical_values()
398            .into_iter()
399            .chain(self.agent_canonical_values())
400        {
401            let invalid_bytes = field.ends_with("Bytes") && usize::try_from(value).is_err();
402            let invalid_count = !field.ends_with("Ms") && usize::try_from(value).is_err();
403            let invalid_sqlite_quota =
404                field == "maxCheckpointCacheBytes" && i64::try_from(value).is_err();
405            let invalid_deadline = field.ends_with("Ms")
406                && Instant::now()
407                    .checked_add(Duration::from_millis(value))
408                    .is_none();
409            if value == 0
410                || invalid_bytes
411                || invalid_count
412                || invalid_sqlite_quota
413                || invalid_deadline
414            {
415                return Err(InvalidExecutionPolicy::InvalidValue { field, value });
416            }
417        }
418        Ok(())
419    }
420
421    fn validate_scan_relationships(&self) -> Result<(), InvalidExecutionPolicy> {
422        Self::require_not_greater(
423            "maxNoProgressTimeMs",
424            self.max_no_progress_time_ms,
425            "maxScanWallTimeMs",
426            self.max_scan_wall_time_ms,
427        )?;
428        Self::require_not_greater(
429            "maxCodeGraphSyncWallTimeMsPerRepo",
430            self.max_codegraph_sync_wall_time_ms_per_repo,
431            "maxScanWallTimeMs",
432            self.max_scan_wall_time_ms,
433        )?;
434        Self::require_not_greater(
435            "gracefulTerminationMs",
436            self.graceful_termination_ms,
437            "maxNoProgressTimeMs",
438            self.max_no_progress_time_ms,
439        )?;
440        Self::require_not_greater(
441            "watchIdleTimeoutMs",
442            self.watch_idle_timeout_ms,
443            "maxWatchSessionWallTimeMs",
444            self.max_watch_session_wall_time_ms,
445        )?;
446        Self::require_not_greater(
447            "minWatchRescanIntervalMs",
448            self.min_watch_rescan_interval_ms,
449            "watchIdleTimeoutMs",
450            self.watch_idle_timeout_ms,
451        )
452    }
453
454    fn validate_explore_relationships(&self) -> Result<(), InvalidExecutionPolicy> {
455        Self::require_not_greater(
456            "maxExploreAnchors",
457            self.max_explore_anchors,
458            "maxExploreResolvedSymbols",
459            self.max_explore_resolved_symbols,
460        )?;
461        Self::require_not_greater(
462            "maxExploreConcurrentCodeGraphProcesses",
463            self.max_explore_concurrent_codegraph_processes,
464            "maxExploreCodeGraphOperations",
465            self.max_explore_codegraph_operations,
466        )?;
467        let local_ceiling = self
468            .max_explore_anchors
469            .checked_mul(2)
470            .and_then(|value| value.checked_mul(self.max_explore_neighbors_per_direction))
471            .ok_or(InvalidExecutionPolicy::ArithmeticOverflow {
472                expression: "maxExploreAnchors × 2 × maxExploreNeighborsPerDirection",
473            })?;
474        Self::require_not_greater(
475            "maxExploreLocalRelationships",
476            self.max_explore_local_relationships,
477            "anchor neighbor capacity",
478            local_ceiling,
479        )?;
480        let handoff_ceiling = self
481            .max_explore_anchors
482            .checked_mul(self.max_explore_federated_handoffs_per_anchor)
483            .ok_or(InvalidExecutionPolicy::ArithmeticOverflow {
484                expression: "maxExploreAnchors × maxExploreFederatedHandoffsPerAnchor",
485            })?;
486        Self::require_not_greater(
487            "maxExploreFederatedHandoffs",
488            self.max_explore_federated_handoffs,
489            "anchor handoff capacity",
490            handoff_ceiling,
491        )?;
492        Self::require_not_greater(
493            "maxExploreSourceMarkdownBytes",
494            self.max_explore_source_markdown_bytes,
495            "maxMcpToolResponseBytes",
496            self.max_mcp_tool_response_bytes,
497        )?;
498        Self::require_not_greater(
499            "maxExploreEnrichmentBytes",
500            self.max_explore_enrichment_bytes,
501            "maxMcpToolResponseBytes",
502            self.max_mcp_tool_response_bytes,
503        )
504    }
505
506    fn require_not_greater(
507        field: &'static str,
508        value: u64,
509        maximum_field: &'static str,
510        maximum: u64,
511    ) -> Result<(), InvalidExecutionPolicy> {
512        if value > maximum {
513            return Err(InvalidExecutionPolicy::InvalidRelationship {
514                field,
515                value,
516                maximum_field,
517                maximum,
518            });
519        }
520        Ok(())
521    }
522
523    fn scan_canonical_values(&self) -> [(&'static str, u64); 9] {
524        [
525            ("maxScanWallTimeMs", self.max_scan_wall_time_ms),
526            ("maxNoProgressTimeMs", self.max_no_progress_time_ms),
527            (
528                "maxCodeGraphSyncWallTimeMsPerRepo",
529                self.max_codegraph_sync_wall_time_ms_per_repo,
530            ),
531            ("maxWorkerMemoryBytes", self.max_worker_memory_bytes),
532            ("gracefulTerminationMs", self.graceful_termination_ms),
533            ("watchIdleTimeoutMs", self.watch_idle_timeout_ms),
534            (
535                "maxWatchSessionWallTimeMs",
536                self.max_watch_session_wall_time_ms,
537            ),
538            (
539                "minWatchRescanIntervalMs",
540                self.min_watch_rescan_interval_ms,
541            ),
542            ("maxCheckpointCacheBytes", self.max_checkpoint_cache_bytes),
543        ]
544    }
545
546    fn agent_canonical_values(&self) -> Vec<(&'static str, u64)> {
547        macro_rules! canonical_agent_values {
548            ($($field:ident: $default:ident => $external:literal;)*) => {
549                vec![$(($external, self.$field),)*]
550            };
551        }
552        with_agent_policy_fields!(canonical_agent_values)
553    }
554
555    /// Returns the stable canonical fingerprint of the effective operational policy.
556    #[must_use]
557    pub fn scan_fingerprint(&self) -> String {
558        let mut canonical = self
559            .scan_canonical_values()
560            .into_iter()
561            .map(|(name, value)| format!("{name}={value}"))
562            .collect::<Vec<_>>()
563            .join(";");
564        write!(
565            canonical,
566            ";maxCodeGraphCorroborationAnchorsPerRepo={}",
567            self.max_codegraph_corroboration_anchors_per_repo
568        )
569        .expect("writing to a String cannot fail");
570        stable_id("execution-policy", &canonical)
571    }
572
573    #[must_use]
574    /// Returns the historical scan-only fingerprint alias.
575    pub fn fingerprint(&self) -> String {
576        self.scan_fingerprint()
577    }
578
579    /// Returns a fingerprint that also includes the additive `CodeGraph` corroboration bound.
580    #[must_use]
581    pub fn fingerprint_with_codegraph_limit(
582        &self,
583        limit: CodeGraphCorroborationAnchorLimit,
584    ) -> String {
585        let mut canonical = self
586            .scan_canonical_values()
587            .into_iter()
588            .map(|(name, value)| format!("{name}={value}"))
589            .collect::<Vec<_>>()
590            .join(";");
591        write!(
592            canonical,
593            ";maxCodeGraphCorroborationAnchorsPerRepo={limit}"
594        )
595        .expect("writing to a String cannot fail");
596        stable_id("execution-policy", &canonical)
597    }
598
599    /// Returns the fingerprint for limits that only affect ephemeral agent delivery.
600    #[must_use]
601    pub fn agent_delivery_fingerprint(&self) -> String {
602        let mut canonical = String::new();
603        for (index, (name, value)) in self.agent_canonical_values().into_iter().enumerate() {
604            if index > 0 {
605                canonical.push(';');
606            }
607            write!(canonical, "{name}={value}").expect("writing to a String cannot fail");
608        }
609        stable_id("agent-delivery-policy", &canonical)
610    }
611}
612
613/// Invalid operator-owned execution policy.
614#[derive(Debug, Clone, PartialEq, Eq, Error)]
615pub enum InvalidExecutionPolicy {
616    /// One effective value is zero or cannot be represented internally.
617    #[error("execution policy `{field}` must be positive and representable; received {value}")]
618    InvalidValue {
619        /// Manifest field containing the invalid value.
620        field: &'static str,
621        /// Rejected numeric value.
622        value: u64,
623    },
624    /// An MCP Markdown budget cannot retain its mandatory control block.
625    #[error("execution policy `{field}` must be at least {minimum}; received {value}")]
626    BelowMinimum {
627        /// Manifest field containing the undersized budget.
628        field: &'static str,
629        /// Rejected byte budget.
630        value: u64,
631        /// Smallest supported byte budget.
632        minimum: u64,
633    },
634    /// One subordinate deadline exceeds its containing deadline.
635    #[error("execution policy `{field}` ({value}) must not exceed `{maximum_field}` ({maximum})")]
636    InvalidRelationship {
637        /// Subordinate manifest field.
638        field: &'static str,
639        /// Supplied subordinate value.
640        value: u64,
641        /// Containing manifest field.
642        maximum_field: &'static str,
643        /// Supplied containing value.
644        maximum: u64,
645    },
646    /// A checked capacity relationship overflowed before it could be compared.
647    #[error("execution policy arithmetic overflow in `{expression}`")]
648    ArithmeticOverflow {
649        /// Checked expression that overflowed.
650        expression: &'static str,
651    },
652}
653
654/// Observable phase of one supervised scan or synchronization pass.
655#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
656#[serde(rename_all = "snake_case")]
657pub enum JobPhase {
658    /// Workspace configuration and checkout validation.
659    Configuration,
660    /// Filesystem artifact discovery.
661    Discovery,
662    /// Bounded content fingerprinting.
663    Fingerprinting,
664    /// Source-owned extraction and batch encoding.
665    Extraction,
666    /// Candidate graph assembly and linking.
667    GraphAssembly,
668    /// Deterministic community analysis.
669    Communities,
670    /// Atomic snapshot persistence.
671    Publication,
672    /// External repository-local `CodeGraph` synchronization.
673    CodeGraphSync,
674}
675
676/// Resource exhausted by one supervised workspace operation.
677#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
678#[serde(rename_all = "snake_case")]
679pub enum ExecutionResource {
680    /// Absolute wall time.
681    WallTimeMs,
682    /// Time without verified forward progress.
683    NoProgressTimeMs,
684    /// Resident worker memory.
685    WorkerMemoryBytes,
686    /// Deterministic work accounting overflow.
687    WorkUnits,
688    /// The worker terminated without a valid final protocol message.
689    WorkerProcess,
690    /// The worker protocol exceeded its byte limit or was malformed.
691    WorkerProtocolBytes,
692    /// The operator or hosting agent requested cancellation.
693    Cancellation,
694}
695
696/// Observable resource accounting attached to a completed scan or sync pass.
697#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
698#[serde(rename_all = "camelCase")]
699pub struct ExecutionSummary {
700    /// Unique identifier assigned by the supervisor to this pass.
701    pub run_id: String,
702    /// Monotonic wall-clock duration observed by the supervisor.
703    pub duration_ms: u64,
704    /// Largest combined resident set observed for the worker process tree.
705    pub peak_worker_memory_bytes: u64,
706    /// Number of completed units reported through the progress protocol.
707    pub completed_work_units: u64,
708    /// Number of deterministic checkpoint records reused by this pass.
709    pub checkpoint_hits: u64,
710    /// Number of complete deterministic checkpoint records written by this pass.
711    pub checkpoints_written: u64,
712    /// Number of artifact-extractor invocations measured by the worker.
713    pub measured_artifacts: u64,
714    /// Median artifact-extractor duration in milliseconds.
715    pub artifact_duration_p50_ms: u64,
716    /// 95th-percentile artifact-extractor duration in milliseconds.
717    pub artifact_duration_p95_ms: u64,
718    /// 99th-percentile artifact-extractor duration in milliseconds.
719    pub artifact_duration_p99_ms: u64,
720}
721
722/// Typed failure produced when one supervised execution resource is exhausted.
723#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Error)]
724#[error(
725    "execution `{run_id}` exceeded {resource:?} during {phase:?}: observed {observed}, maximum {maximum}, completed {completed_units} units"
726)]
727pub struct ExecutionLimitExceeded {
728    /// Stable identifier of the supervised operation.
729    pub run_id: String,
730    /// Phase active when the resource was exhausted.
731    pub phase: JobPhase,
732    /// Exhausted resource.
733    pub resource: ExecutionResource,
734    /// Observed resource value.
735    pub observed: u64,
736    /// Effective maximum.
737    pub maximum: u64,
738    /// Verified work units completed before rejection.
739    pub completed_units: u64,
740}
741
742#[cfg(test)]
743mod tests {
744    use super::*;
745
746    #[test]
747    fn defaults_should_be_generous_and_finite() {
748        let policy = ExecutionPolicy::default();
749
750        assert_eq!(policy.max_scan_wall_time_ms, 21_600_000);
751        assert_eq!(
752            CodeGraphCorroborationAnchorLimit::try_from(
753                DEFAULT_MAX_CODEGRAPH_CORROBORATION_ANCHORS_PER_REPO
754            )
755            .expect("default anchor limit")
756            .bounded()
757            .map(NonZeroUsize::get),
758            Some(50)
759        );
760        assert_eq!(policy.max_worker_memory_bytes, 17_179_869_184);
761        assert_eq!(policy.max_checkpoint_cache_bytes, 10_737_418_240);
762    }
763
764    #[test]
765    fn partial_override_should_preserve_other_defaults() {
766        let policy = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
767            max_scan_wall_time_ms: Some(28_800_000),
768            ..ExecutionPolicyOverrides::default()
769        }))
770        .expect("valid override");
771
772        assert_eq!(policy.max_scan_wall_time_ms, 28_800_000);
773        assert_eq!(policy.max_no_progress_time_ms, 300_000);
774    }
775
776    #[test]
777    fn zero_should_be_rejected() {
778        let error = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
779            max_worker_memory_bytes: Some(0),
780            ..ExecutionPolicyOverrides::default()
781        }))
782        .expect_err("zero must fail");
783
784        assert!(matches!(
785            error,
786            InvalidExecutionPolicy::InvalidValue {
787                field: "maxWorkerMemoryBytes",
788                value: 0
789            }
790        ));
791    }
792
793    #[test]
794    fn corroboration_anchor_limit_should_accept_positive_or_unlimited() {
795        let bounded =
796            CodeGraphCorroborationAnchorLimit::try_from(12).expect("positive anchor limit");
797        let unlimited =
798            CodeGraphCorroborationAnchorLimit::try_from(-1).expect("unlimited anchor limit");
799
800        assert_eq!(bounded.bounded().map(NonZeroUsize::get), Some(12));
801        assert_eq!(unlimited.bounded(), None);
802        assert_ne!(
803            ExecutionPolicy::default().fingerprint_with_codegraph_limit(bounded),
804            ExecutionPolicy::default().fingerprint_with_codegraph_limit(unlimited)
805        );
806        assert_eq!(
807            serde_json::to_value(bounded).expect("bounded limit serializes"),
808            serde_json::json!(12)
809        );
810        assert_eq!(
811            serde_json::to_value(unlimited).expect("unlimited limit serializes"),
812            serde_json::json!(-1)
813        );
814    }
815
816    #[test]
817    fn corroboration_anchor_limit_should_reject_zero_and_values_below_sentinel() {
818        for value in [0, -2] {
819            let error = CodeGraphCorroborationAnchorLimit::try_from(value)
820                .expect_err("invalid anchor limit");
821
822            assert!(matches!(
823                error,
824                InvalidExecutionPolicy::InvalidValue {
825                    field: "maxCodeGraphCorroborationAnchorsPerRepo",
826                    value: observed
827                } if observed == value.unsigned_abs()
828            ));
829        }
830    }
831
832    #[test]
833    fn technically_unrepresentable_values_should_be_rejected() {
834        let quota = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
835            max_checkpoint_cache_bytes: Some(u64::MAX),
836            ..ExecutionPolicyOverrides::default()
837        }))
838        .expect_err("SQLite quota overflow must fail");
839
840        assert!(matches!(quota, InvalidExecutionPolicy::InvalidValue { .. }));
841    }
842
843    #[test]
844    fn mcp_markdown_budgets_should_enforce_the_control_block_minimum() {
845        for overrides in [
846            ExecutionPolicyOverrides {
847                max_mcp_tool_response_bytes: Some(MIN_MCP_MARKDOWN_BYTES - 1),
848                ..ExecutionPolicyOverrides::default()
849            },
850            ExecutionPolicyOverrides {
851                max_mcp_resource_bytes: Some(MIN_MCP_MARKDOWN_BYTES - 1),
852                ..ExecutionPolicyOverrides::default()
853            },
854            ExecutionPolicyOverrides {
855                max_mcp_schema_catalog_bytes: Some(MIN_MCP_MARKDOWN_BYTES - 1),
856                ..ExecutionPolicyOverrides::default()
857            },
858        ] {
859            assert!(matches!(
860                ExecutionPolicy::resolve(Some(&overrides)),
861                Err(InvalidExecutionPolicy::BelowMinimum {
862                    minimum: MIN_MCP_MARKDOWN_BYTES,
863                    ..
864                })
865            ));
866        }
867
868        let minimum = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
869            max_mcp_tool_response_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
870            max_mcp_resource_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
871            max_mcp_schema_catalog_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
872            max_explore_source_markdown_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
873            max_explore_enrichment_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
874            ..ExecutionPolicyOverrides::default()
875        }));
876        assert!(minimum.is_ok());
877    }
878
879    #[test]
880    fn subordinate_deadline_should_not_exceed_scan_deadline() {
881        let error = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
882            max_scan_wall_time_ms: Some(1_000),
883            max_no_progress_time_ms: Some(1_001),
884            max_codegraph_sync_wall_time_ms_per_repo: Some(1_000),
885            graceful_termination_ms: Some(500),
886            ..ExecutionPolicyOverrides::default()
887        }))
888        .expect_err("relationship must fail");
889
890        assert!(matches!(
891            error,
892            InvalidExecutionPolicy::InvalidRelationship {
893                field: "maxNoProgressTimeMs",
894                ..
895            }
896        ));
897    }
898
899    #[test]
900    fn fingerprint_should_ignore_yaml_field_order() {
901        let first = ExecutionPolicy::default();
902        let second = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides::default()))
903            .expect("defaults valid");
904
905        assert_eq!(first.fingerprint(), second.fingerprint());
906    }
907
908    #[test]
909    fn agent_delivery_limits_should_not_change_scan_fingerprint() {
910        let baseline = ExecutionPolicy::default();
911        let changed = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
912            max_mcp_tool_response_bytes: Some(600_000),
913            max_explore_source_markdown_bytes: Some(300_000),
914            ..ExecutionPolicyOverrides::default()
915        }))
916        .expect("agent-only override is valid");
917
918        assert_eq!(baseline.scan_fingerprint(), changed.scan_fingerprint());
919        assert_ne!(
920            baseline.agent_delivery_fingerprint(),
921            changed.agent_delivery_fingerprint()
922        );
923    }
924
925    #[test]
926    fn explore_capacity_relationships_should_be_checked() {
927        for overrides in [
928            ExecutionPolicyOverrides {
929                max_explore_anchors: Some(6),
930                ..ExecutionPolicyOverrides::default()
931            },
932            ExecutionPolicyOverrides {
933                max_explore_concurrent_codegraph_processes: Some(9),
934                ..ExecutionPolicyOverrides::default()
935            },
936            ExecutionPolicyOverrides {
937                max_explore_local_relationships: Some(49),
938                ..ExecutionPolicyOverrides::default()
939            },
940            ExecutionPolicyOverrides {
941                max_explore_federated_handoffs: Some(31),
942                ..ExecutionPolicyOverrides::default()
943            },
944            ExecutionPolicyOverrides {
945                max_explore_source_markdown_bytes: Some(524_289),
946                ..ExecutionPolicyOverrides::default()
947            },
948        ] {
949            assert!(matches!(
950                ExecutionPolicy::resolve(Some(&overrides)),
951                Err(InvalidExecutionPolicy::InvalidRelationship { .. })
952            ));
953        }
954    }
955}