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