Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions crates/cyber-cli/src/commands/doctor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ fn instructions(ctx: &Context, config: Option<&cyber_core::config::Resolved>) ->
}

/// Baseline files, path-scoped rule definitions discovered for later attachment, and
/// withheld rule definitions grouped by reason. A loader warning that only repeats a
/// withheld rule definitions and instruction files grouped by reason. A loader warning that only repeats a
/// withheld definition is not listed twice.
fn instructions_check(loaded: &cyber_server::runtime::instructions::Instructions) -> Check {
let files: Vec<String> = loaded
Expand Down Expand Up @@ -204,10 +204,7 @@ fn instructions_check(loaded: &cyber_server::runtime::instructions::Instructions
detail.push_str(&format!("; withheld ({reason}): {}", paths.join(", ")));
}
if withheld.omitted > 0 {
detail.push_str(&format!(
"; {} more withheld rule definitions",
withheld.omitted
));
detail.push_str(&format!("; {} more withheld definitions", withheld.omitted));
}
let warnings: Vec<&String> = loaded
.warnings
Expand All @@ -216,7 +213,7 @@ fn instructions_check(loaded: &cyber_server::runtime::instructions::Instructions
!withheld
.entries
.iter()
.any(|entry| warning.starts_with(&format!("{}: ", entry.path)))
.any(|entry| repeats(warning, &entry.path))
})
.collect();
for warning in &warnings {
Expand All @@ -230,6 +227,16 @@ fn instructions_check(loaded: &cyber_server::runtime::instructions::Instructions
check("instructions", status, detail)
}

/// The warning names `path` as its subject (`<path>: ...` or `<path> resolves ...`),
/// so it only repeats that withheld definition.
fn repeats(warning: &str, path: &str) -> bool {
warning.strip_prefix(path).is_some_and(|rest| {
rest.starts_with(": ")
|| rest.starts_with(" resolves ")
|| rest.starts_with(" is not allowed ")
})
}

fn lsp_checks(ctx: &Context, config: &Value) -> Vec<Check> {
let Ok(settings) = cyber_core::config::LspSettings::from_config(config) else {
return Vec::new();
Expand Down
12 changes: 8 additions & 4 deletions crates/cyber-cli/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2442,10 +2442,13 @@ fn doctor_warns_about_an_instruction_file_outside_the_project() {
assert_eq!(row["status"], "warn", "{row}");
let detail = row["detail"].as_str().unwrap();
assert!(detail.starts_with("no instruction files"), "{detail}");
assert!(
detail.contains("CYBER.md resolves outside the project and was not loaded"),
"{detail}"
);
// Listed once, as a typed withheld entry, not again as a repeated warning.
let listed = detail
.split("; ")
.find(|part| part.starts_with("withheld (outside_project): "))
.unwrap_or_else(|| panic!("{detail}"));
assert!(listed.ends_with("CYBER.md"), "{detail}");
assert!(!detail.contains("resolves outside the project"), "{detail}");
}

/// Regression: doctor (like the runtime) loaded `@.env` imports of project instruction
Expand All @@ -2467,6 +2470,7 @@ fn doctor_refuses_protected_imports_and_project_files_under_a_broken_config() {
detail.contains("import @.env is not allowed by the read permission rules"),
"{detail}"
);
assert!(detail.contains("withheld (read_denied): "), "{detail}");
std::fs::write(repo.join("CLAUDE.md"), "claude").unwrap();
std::fs::write(repo.join("cyber.json"), "{ not json").unwrap();
let row = doctor_instructions(&env, &repo);
Expand Down
3 changes: 1 addition & 2 deletions crates/cyber-server/src/http/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1203,8 +1203,7 @@ async fn context(
Path(id): Path<String>,
Query(query): Query<ContextQuery>,
) -> Result<Json<Data<SessionContext>>> {
let s = state.runtime.state(&id).await?;
let inspection = state.runtime.inspect_context(&s);
let (s, inspection) = state.runtime.inspect_session_context(&id).await?;
let epoch = s.epoch.as_ref().map(|e| e.number);
let (baseline, summary, task) = if query.include_content {
(
Expand Down
124 changes: 120 additions & 4 deletions crates/cyber-server/src/runtime/context_inspection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,18 @@ impl PreparedContextEstimate {
resolved: &super::ResolvedModel,
epoch: u32,
compacted: bool,
hook_tokens: u64,
step_id: String,
) -> Self {
let window = (resolved.context_limit > 0).then_some(resolved.context_limit);
let estimated_input_tokens =
view::estimate_tokens(&request.system, &request.messages, &request.tools);
let mut sources = estimates(&request.system[..2], &request.messages, compacted);
let mut sources = estimates(
&request.system[..2],
&request.messages,
compacted,
hook_tokens,
);
let turn_bytes = request
.system
.iter()
Expand Down Expand Up @@ -151,6 +157,9 @@ pub enum EstimateAssumption {
/// A rule delivered in this Context Epoch was changed or its approval revoked; the
/// next Context Epoch will not deliver that definition again.
DeliveredRulesChanged,
/// A requested compaction runs at the next Safe Boundary and replaces the history
/// this estimate counts.
CompactionPending,
}

/// The stored projection plus the tool schemas of the last prepared request: what the
Expand Down Expand Up @@ -183,6 +192,14 @@ pub struct ContextInspection {
pub epoch_pending: bool,
pub queued_inputs: usize,
pub held_inputs: usize,
/// Hook `additional_context` from background handlers, queued to be committed
/// before the next request. Its text is never returned.
pub pending_hook_contexts: usize,
/// Estimated tokens of the queued hook context; included in `next_request`.
pub pending_hook_context_tokens: u64,
/// A compaction was requested while the Session was running and applies at the
/// next Safe Boundary.
pub compaction_pending: bool,
pub delivered_rule_count: usize,
/// Rules delivered in this Context Epoch, in delivery order, with their current
/// approval. Definition bodies are never included or read.
Expand All @@ -206,8 +223,53 @@ pub struct ContextInspection {
pub next_request: Option<NextRequestEstimate>,
}

/// Context updates held on the Session handle rather than in its durable state.
#[derive(Debug, Default)]
pub struct PendingContext {
pub hook_contexts: Vec<String>,
pub compaction: bool,
}

impl Runtime {
/// Inspect a Session's context, including updates queued on its handle for the
/// next Safe Boundary. Reads state only; nothing is committed or started.
pub async fn inspect_session_context(
&self,
session_id: &str,
) -> Result<(SessionState, ContextInspection), super::RuntimeError> {
let handle = self.inner.handle(session_id).await?;
// The Safe Boundary commits queued hook context under the state lock, so reading
// both under it counts each queued text once, as pending or as committed.
let (mut state, pending) = {
let state = handle.state.lock().await;
let pending = PendingContext {
hook_contexts: handle
.pending_hook_context
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone(),
compaction: handle
.pending_compaction
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.is_some(),
};
(state.clone(), pending)
};
state.children_usage = self.children_usage(session_id)?;
let inspection = self.inspect_context_with(&state, &pending);
Ok((state, inspection))
}

pub fn inspect_context(&self, state: &SessionState) -> ContextInspection {
self.inspect_context_with(state, &PendingContext::default())
}

pub fn inspect_context_with(
&self,
state: &SessionState,
pending: &PendingContext,
) -> ContextInspection {
let model = self.inner.resolve(&state.info.model).ok();
let window = model
.as_ref()
Expand All @@ -231,6 +293,11 @@ impl Runtime {
}),
queued_inputs: count_inputs(state, InputStatus::Pending),
held_inputs: count_inputs(state, InputStatus::Held),
pending_hook_contexts: pending.hook_contexts.len(),
pending_hook_context_tokens: system_message_tokens(
pending.hook_contexts.iter().map(String::as_str),
),
compaction_pending: pending.compaction,
delivered_rule_count: state
.epoch
.as_ref()
Expand Down Expand Up @@ -300,7 +367,12 @@ impl Runtime {
};
let system = super::context::request_system(epoch, model.family);
let messages = view::messages(state, &view::Replay::of(&model));
inspection.sources = estimates(&system, &messages, state.compacted.is_some());
inspection.sources = estimates(
&system,
&messages,
state.compacted.is_some(),
hook_context_tokens(state),
);
let estimate = view::estimate_tokens(&system, &messages, &[]);
inspection.estimated_input_tokens = Some(estimate);
inspection.estimated_input_utilization =
Expand Down Expand Up @@ -405,8 +477,13 @@ fn next_request(
if inspection.changed_delivered_rules > 0 {
assumptions.push(EstimateAssumption::DeliveredRulesChanged);
}
if inspection.compaction_pending {
assumptions.push(EstimateAssumption::CompactionPending);
}
assumptions.push(EstimateAssumption::ExcludesTurnInstructions);
let estimated_input_tokens = stored.saturating_add(tools);
let estimated_input_tokens = stored
.saturating_add(tools)
.saturating_add(inspection.pending_hook_context_tokens);
Some(NextRequestEstimate {
estimated_input_tokens,
estimated_input_utilization: inspection
Expand Down Expand Up @@ -447,10 +524,45 @@ fn count_inputs(state: &SessionState, status: InputStatus) -> usize {
.count()
}

/// Estimated tokens of the hook-context system messages in the projected history.
/// They are committed without a Context Epoch, so every one after the compaction
/// tail start is projected.
pub(super) fn hook_context_tokens(state: &SessionState) -> u64 {
let start = state
.compacted
.as_ref()
.map_or(0, |c| c.tail_start)
.min(state.entries.len());
system_message_tokens(
state.entries[start..]
.iter()
.filter_map(|entry| match entry {
super::Entry::System { id, text, .. }
if state.hook_context_messages.contains(id) =>
{
Some(text.as_str())
}
_ => None,
}),
)
}

/// Estimated tokens of `texts` sent as Mid-Conversation System Messages.
fn system_message_tokens<'a>(texts: impl Iterator<Item = &'a str>) -> u64 {
let messages: Vec<Message> = texts.map(view::system_message).collect();
if messages.is_empty() {
return 0;
}
view::estimate_tokens(&[], &messages, &[])
}

/// Source groups of a projected request. Hook context is reported apart from the
/// history it is part of, so `history` counts the rest.
fn estimates(
system: &[String],
messages: &[Message],
compacted: bool,
hook_tokens: u64,
) -> Vec<ContextSourceEstimate> {
let mut sources = vec![
source(
Expand All @@ -471,12 +583,16 @@ fn estimates(
messages
};
if !history.is_empty() {
let tokens = view::estimate_tokens(&[], history, &[]);
sources.push(source(
"history",
"session_replay",
view::estimate_tokens(&[], history, &[]),
tokens.saturating_sub(hook_tokens),
));
}
if hook_tokens > 0 {
sources.push(source("hook_context", "hook", hook_tokens));
}
sort_sources(&mut sources);
sources
}
Expand Down
3 changes: 3 additions & 0 deletions crates/cyber-server/src/runtime/context_sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ pub enum WithheldReason {
CompatDisabled,
/// Rule discovery reached its file or byte bound before it.
BoundExceeded,
/// A project instruction file or import resolves outside the project.
OutsideProject,
}

impl WithheldReason {
Expand All @@ -70,6 +72,7 @@ impl WithheldReason {
Self::InvalidFrontmatter => "invalid_frontmatter",
Self::CompatDisabled => "compat_disabled",
Self::BoundExceeded => "bound_exceeded",
Self::OutsideProject => "outside_project",
}
}
}
Expand Down
6 changes: 5 additions & 1 deletion crates/cyber-server/src/runtime/drain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -767,9 +767,12 @@ impl Inner {
}
}

/// The `session.system.added` reason of hook-provided context.
pub(crate) const HOOK_CONTEXT_REASON: &str = "hook_context";

/// A Mid-Conversation System Message carrying hook-provided context.
pub(crate) fn hook_context(text: String) -> cyber_store::NewEvent {
system(text, "hook_context")
system(text, HOOK_CONTEXT_REASON)
}

/// The durable record of a hook's `continue: false`, with its tagged stop reason.
Expand Down Expand Up @@ -1305,6 +1308,7 @@ impl Inner {
resolved,
epoch.number,
state.compacted.is_some(),
super::context_inspection::hook_context_tokens(&state),
message_id.clone(),
)),
input_message_ids: super::requests::input_owners::capture(&state),
Expand Down
25 changes: 24 additions & 1 deletion crates/cyber-server/src/runtime/instructions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -892,13 +892,15 @@ impl<'a> Loader<'a> {
"{} resolves outside the project and was not loaded",
path.display()
));
self.withhold(path, WithheldReason::OutsideProject);
return Ok(());
}
if confine.is_some() && !self.settings.read_allowed(path, &key) {
self.out.warnings.push(format!(
"{} is not allowed by the read permission rules and was not loaded",
path.display()
));
self.withhold(path, WithheldReason::ReadDenied);
return Ok(());
}
self.include(path, key, confine)
Expand Down Expand Up @@ -1032,15 +1034,17 @@ impl<'a> Loader<'a> {
if self.stack.len() > MAX_IMPORT_DEPTH {
return self.warn(from, reference, "exceeds the import depth of 5");
}
let target = target.unwrap_or_default();
if confine.is_some_and(|root| !key.starts_with(root)) {
self.withhold(&key, WithheldReason::OutsideProject);
return self.warn(
from,
reference,
"is outside the project and was not imported",
);
}
let target = target.unwrap_or_default();
if confine.is_some() && !self.settings.read_allowed(&target, &key) {
self.withhold(&key, WithheldReason::ReadDenied);
return self.warn(
from,
reference,
Expand Down Expand Up @@ -1398,6 +1402,11 @@ mod tests {
assert!(!loaded.text().unwrap().contains("secret\n"));
assert_eq!(loaded.warnings.len(), 2, "{:?}", loaded.warnings);
assert!(loaded.warnings[0].contains("outside the project"));
// The refused import is a typed withheld entry, so inspection reports it.
let entries = &loaded.withheld.entries;
assert_eq!(entries.len(), 1, "{entries:?}");
assert!(entries[0].path.ends_with("secret.md"), "{entries:?}");
assert_eq!(entries[0].reason, WithheldReason::OutsideProject);
}

/// Regression: project files and their imports skipped the read rules, so `@.env`
Expand All @@ -1419,6 +1428,20 @@ mod tests {
assert_eq!(loaded.warnings.len(), 2, "{:?}", loaded.warnings);
assert!(loaded.warnings[0].contains("@.env is not allowed by the read permission rules"));
assert!(loaded.warnings[1].contains("not allowed by the read permission rules"));
let withheld: Vec<_> = loaded
.withheld
.entries
.iter()
.map(|entry| (entry.path.as_str(), entry.reason))
.collect();
assert_eq!(withheld.len(), 2, "{withheld:?}");
assert!(withheld[0].0.ends_with(".env"), "{withheld:?}");
assert!(withheld[1].0.ends_with("AGENTS.md"), "{withheld:?}");
assert!(
withheld
.iter()
.all(|(_, reason)| *reason == WithheldReason::ReadDenied)
);
let nested = load_nested(
&repo.global,
&repo.root,
Expand Down
Loading
Loading