diff --git a/crates/cyber-cli/src/commands/doctor.rs b/crates/cyber-cli/src/commands/doctor.rs index 51eed834..e749a4d1 100644 --- a/crates/cyber-cli/src/commands/doctor.rs +++ b/crates/cyber-cli/src/commands/doctor.rs @@ -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 = loaded @@ -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 @@ -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 { @@ -230,6 +227,16 @@ fn instructions_check(loaded: &cyber_server::runtime::instructions::Instructions check("instructions", status, detail) } +/// The warning names `path` as its subject (`: ...` or ` 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 { let Ok(settings) = cyber_core::config::LspSettings::from_config(config) else { return Vec::new(); diff --git a/crates/cyber-cli/tests/cli.rs b/crates/cyber-cli/tests/cli.rs index 7cd48788..922705cc 100644 --- a/crates/cyber-cli/tests/cli.rs +++ b/crates/cyber-cli/tests/cli.rs @@ -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 @@ -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); diff --git a/crates/cyber-server/src/http/sessions.rs b/crates/cyber-server/src/http/sessions.rs index b8e72f6f..1d105ec5 100644 --- a/crates/cyber-server/src/http/sessions.rs +++ b/crates/cyber-server/src/http/sessions.rs @@ -1203,8 +1203,7 @@ async fn context( Path(id): Path, Query(query): Query, ) -> Result>> { - 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 { ( diff --git a/crates/cyber-server/src/runtime/context_inspection.rs b/crates/cyber-server/src/runtime/context_inspection.rs index 0d4853f4..7732e1da 100644 --- a/crates/cyber-server/src/runtime/context_inspection.rs +++ b/crates/cyber-server/src/runtime/context_inspection.rs @@ -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() @@ -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 @@ -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. @@ -206,8 +223,53 @@ pub struct ContextInspection { pub next_request: Option, } +/// Context updates held on the Session handle rather than in its durable state. +#[derive(Debug, Default)] +pub struct PendingContext { + pub hook_contexts: Vec, + 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() @@ -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() @@ -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 = @@ -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 @@ -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) -> u64 { + let messages: Vec = 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 { let mut sources = vec![ source( @@ -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 } diff --git a/crates/cyber-server/src/runtime/context_sources.rs b/crates/cyber-server/src/runtime/context_sources.rs index 0853f0dc..cfbad9a1 100644 --- a/crates/cyber-server/src/runtime/context_sources.rs +++ b/crates/cyber-server/src/runtime/context_sources.rs @@ -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 { @@ -70,6 +72,7 @@ impl WithheldReason { Self::InvalidFrontmatter => "invalid_frontmatter", Self::CompatDisabled => "compat_disabled", Self::BoundExceeded => "bound_exceeded", + Self::OutsideProject => "outside_project", } } } diff --git a/crates/cyber-server/src/runtime/drain.rs b/crates/cyber-server/src/runtime/drain.rs index 93a1cef2..0d96620b 100644 --- a/crates/cyber-server/src/runtime/drain.rs +++ b/crates/cyber-server/src/runtime/drain.rs @@ -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. @@ -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), diff --git a/crates/cyber-server/src/runtime/instructions.rs b/crates/cyber-server/src/runtime/instructions.rs index 939c35a6..6df7c8e6 100644 --- a/crates/cyber-server/src/runtime/instructions.rs +++ b/crates/cyber-server/src/runtime/instructions.rs @@ -892,6 +892,7 @@ 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) { @@ -899,6 +900,7 @@ impl<'a> Loader<'a> { "{} 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) @@ -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, @@ -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` @@ -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, diff --git a/crates/cyber-server/src/runtime/mod.rs b/crates/cyber-server/src/runtime/mod.rs index adb7381c..4016e811 100644 --- a/crates/cyber-server/src/runtime/mod.rs +++ b/crates/cyber-server/src/runtime/mod.rs @@ -258,7 +258,9 @@ pub use auto::{AutoDecision, AutoEffect, AutoReview, AutoReviewStage, TAINTED_RE pub use bus::LiveEvent; pub use compaction::CompactionConfig; pub use context::{ContextInputs, Observed as ContextObservation, base_prompt}; -pub use context_inspection::{ContextInspection, PreparedContextEstimate, RuleApproval}; +pub use context_inspection::{ + ContextInspection, PendingContext, PreparedContextEstimate, RuleApproval, +}; pub use context_meter::ContextMeter; pub use cyber_core::prompts::ModelFamily; pub use events::{AuxiliaryUsage, CompactionTrigger, registry as event_registry}; diff --git a/crates/cyber-server/src/runtime/model.rs b/crates/cyber-server/src/runtime/model.rs index a23f087b..6236d8ca 100644 --- a/crates/cyber-server/src/runtime/model.rs +++ b/crates/cyber-server/src/runtime/model.rs @@ -480,6 +480,10 @@ pub struct SessionState { /// Delivered rules withdrawn so far, in marker order (`rule_withdrawal`). #[serde(skip)] pub(crate) rule_withdrawals: Vec, + /// System messages carrying hook `additional_context`, which inspection reports + /// as their own source. + #[serde(skip)] + pub(crate) hook_context_messages: BTreeSet, /// Pull requests this Session is linked to (`session.pr.linked.1`). #[serde(skip)] pub(crate) pull_requests: BTreeSet, @@ -798,6 +802,7 @@ impl SessionState { Self { loaded_tools: BTreeSet::new(), rule_withdrawals: Vec::new(), + hook_context_messages: BTreeSet::new(), pull_requests: BTreeSet::new(), notifications: Vec::new(), sent_files: BTreeMap::new(), @@ -1495,6 +1500,9 @@ impl SessionState { rules: s.withdrawn_rules, }); } + if s.reason == super::drain::HOOK_CONTEXT_REASON { + self.hook_context_messages.insert(s.message_id.clone()); + } self.push_entry(Entry::System { id: s.message_id, text: s.text, diff --git a/crates/cyber-server/src/runtime/view.rs b/crates/cyber-server/src/runtime/view.rs index a617deda..8880fa0a 100644 --- a/crates/cyber-server/src/runtime/view.rs +++ b/crates/cyber-server/src/runtime/view.rs @@ -75,9 +75,7 @@ pub fn messages(state: &SessionState, target: &Replay<'_>) -> Vec { Entry::System { text, epoch: e, .. } => { // Context updates from replaced epochs are no longer projected. if e.is_none() || *e == epoch { - out.push(Message::user_text(format!( - "\n{text}\n" - ))); + out.push(system_message(text)); } } Entry::Assistant(a) => { @@ -94,6 +92,11 @@ pub fn messages(state: &SessionState, target: &Replay<'_>) -> Vec { out } +/// A Mid-Conversation System Message as the model receives it. +pub(super) fn system_message(text: &str) -> Message { + Message::user_text(format!("\n{text}\n")) +} + /// `tool_loop` replays the answers after the latest user message and drops older /// reasoning, which those providers ignore or count twice. fn treatment(policy: ReasoningReplay, in_loop: bool) -> Treatment { diff --git a/crates/cyber-server/tests/context_compaction.rs b/crates/cyber-server/tests/context_compaction.rs index 8b956f03..60712a04 100644 --- a/crates/cyber-server/tests/context_compaction.rs +++ b/crates/cyber-server/tests/context_compaction.rs @@ -1221,3 +1221,197 @@ async fn inspection_lists_delivered_rules_and_marks_revoked_approval_without_rea std::fs::set_permissions(rules.join(name), std::fs::Permissions::from_mode(0o644)).unwrap(); } } + +fn source_tokens(inspection: &serde_json::Value, list: &str, id: &str) -> Option { + inspection[list] + .as_array()? + .iter() + .find(|source| source["id"] == id)?["estimated_tokens"] + .as_u64() +} + +/// `system-context` → Scope-aware rule inspection and loading: hook +/// `additional_context` queued by a background handler is a pending update counted in +/// the next-request estimate, then a `hook_context` source of its own once committed, +/// and leaves the projection once compaction summarizes it. Its text is never returned. +#[tokio::test] +async fn inspection_reports_hook_context_as_pending_then_as_its_own_source() { + let h = Harness::new(Setup { + scripts: vec![ + ("test/main", vec![text("first"), text("second")]), + ("test/summary", vec![text("summary")]), + ], + compaction: small_tail(), + ..Setup::default() + }); + let id = h.session().await; + h.runtime.admit(&id, admit("begin")).await.unwrap(); + h.settle(&id).await; + let hook_text = format!("[hook audit] HOOK_CONTEXT_SENTINEL {}", "x".repeat(400)); + h.runtime + .queue_hook_context(&id, hook_text.clone()) + .await + .unwrap(); + + let (state, pending) = h.runtime.inspect_session_context(&id).await.unwrap(); + let pending = serde_json::to_value(pending).unwrap(); + let without = serde_json::to_value(h.runtime.inspect_context(&state)).unwrap(); + assert_eq!(pending["pending_hook_contexts"], 1); + let pending_tokens = pending["pending_hook_context_tokens"].as_u64().unwrap(); + assert!(pending_tokens > 100, "{pending}"); + assert_eq!(pending["compaction_pending"], false); + assert_eq!( + pending["next_request"]["estimated_input_tokens"] + .as_u64() + .unwrap(), + without["next_request"]["estimated_input_tokens"] + .as_u64() + .unwrap() + + pending_tokens + ); + assert_eq!(source_tokens(&pending, "sources", "hook_context"), None); + assert!(!pending.to_string().contains("HOOK_CONTEXT_SENTINEL")); + + h.runtime.admit(&id, admit("continue")).await.unwrap(); + h.settle(&id).await; + let sent = &h.models.requests("test/main")[1]; + assert!(transcript(sent).contains("HOOK_CONTEXT_SENTINEL")); + let (_, committed) = h.runtime.inspect_session_context(&id).await.unwrap(); + let committed = serde_json::to_value(committed).unwrap(); + assert_eq!(committed["pending_hook_contexts"], 0); + assert_eq!(committed["pending_hook_context_tokens"], 0); + let hook = source_tokens(&committed, "sources", "hook_context").unwrap(); + assert_eq!(hook, pending_tokens); + assert_eq!( + committed["sources"] + .as_array() + .unwrap() + .iter() + .find(|source| source["id"] == "hook_context") + .unwrap()["origin"], + "hook" + ); + // The prepared request that carried it reports the same share. + assert_eq!( + source_tokens( + &committed["last_prepared_request"], + "sources", + "hook_context" + ), + Some(hook) + ); + // Splitting hook context out of history leaves the stored total unchanged. + let history = source_tokens(&committed, "sources", "history").unwrap(); + let total = committed["estimated_input_tokens"].as_u64().unwrap(); + assert!(history + hook <= total, "{committed:#}"); + assert!(!committed.to_string().contains("HOOK_CONTEXT_SENTINEL")); + + h.runtime.compact(&id, None).await.unwrap(); + let (_, compacted) = h.runtime.inspect_session_context(&id).await.unwrap(); + let compacted = serde_json::to_value(compacted).unwrap(); + assert_eq!(source_tokens(&compacted, "sources", "hook_context"), None); +} + +/// A compaction requested while a turn runs is a pending update: inspection reports it +/// and the next-request estimate states that the history it counts will be replaced. +#[tokio::test] +async fn inspection_reports_a_compaction_requested_during_a_turn() { + let h = Harness::new(Setup { + scripts: vec![ + ( + "test/main", + vec![text("a"), tools(&[("c1", "write", "{}")]), text("b")], + ), + ("test/summary", vec![text("summary")]), + ], + compaction: small_tail(), + ..Setup::default() + }); + h.tools.set("write", Behavior::Gated); + let id = h.session().await; + h.runtime.admit(&id, admit("one")).await.unwrap(); + h.settle(&id).await; + h.runtime.admit(&id, admit("two")).await.unwrap(); + h.tools.started.notified().await; + h.runtime.compact(&id, None).await.unwrap(); + let (_, inspection) = h.runtime.inspect_session_context(&id).await.unwrap(); + let inspection = serde_json::to_value(inspection).unwrap(); + assert_eq!(inspection["compaction_pending"], true); + assert!( + inspection["next_request"]["assumptions"] + .as_array() + .unwrap() + .contains(&serde_json::json!("compaction_pending")), + "{inspection:#}" + ); + h.tools.release.notify_one(); + h.settle(&id).await; + let (_, after) = h.runtime.inspect_session_context(&id).await.unwrap(); + let after = serde_json::to_value(after).unwrap(); + assert_eq!(after["compaction_pending"], false); + assert!( + !after["next_request"]["assumptions"] + .as_array() + .unwrap() + .contains(&serde_json::json!("compaction_pending")) + ); +} + +/// `system-context` → Inspection of an untrusted source: project instruction files and +/// imports refused because they resolve outside the project are listed as withheld +/// (`outside_project`), without their text reaching the model or the inspection. +#[cfg(unix)] +#[tokio::test] +async fn inspection_reports_instruction_files_refused_outside_the_project() { + let h = Harness::new(Setup { + scripts: vec![("test/main", vec![text("first")])], + ..Setup::default() + }); + let outside = h.dir.path().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("linked.md"), "OUTSIDE_LINKED_SENTINEL").unwrap(); + std::fs::write(outside.join("imported.md"), "OUTSIDE_IMPORTED_SENTINEL").unwrap(); + std::os::unix::fs::symlink(outside.join("linked.md"), h.repo.join("CYBER.md")).unwrap(); + std::fs::write( + h.repo.join("AGENTS.md"), + format!("agents\n@{}", outside.join("imported.md").display()), + ) + .unwrap(); + let request = cyber_server::runtime::CreateSession { + directory: h.repo.canonicalize().unwrap().display().to_string(), + model: "test/main".into(), + ..Default::default() + }; + let id = h.runtime.create_session(request).await.unwrap().id; + h.runtime.admit(&id, admit("begin")).await.unwrap(); + h.settle(&id).await; + let sent = transcript(&h.models.requests("test/main")[0]); + let system = h.models.requests("test/main")[0].system.join("\n"); + for text in [&sent, &system] { + assert!(!text.contains("OUTSIDE_LINKED_SENTINEL")); + assert!(!text.contains("OUTSIDE_IMPORTED_SENTINEL")); + } + assert!(system.contains("agents")); + let (_, inspection) = h.runtime.inspect_session_context(&id).await.unwrap(); + let inspection = serde_json::to_value(inspection).unwrap(); + let entries: Vec<_> = inspection["withheld_sources"] + .as_array() + .unwrap() + .iter() + .map(|entry| { + ( + entry["path"].as_str().unwrap().to_owned(), + entry["reason"].as_str().unwrap().to_owned(), + ) + }) + .collect(); + let linked = h.repo.canonicalize().unwrap().join("CYBER.md"); + let imported = outside.canonicalize().unwrap().join("imported.md"); + for path in [linked, imported] { + assert!( + entries.contains(&(path.display().to_string(), "outside_project".into())), + "{inspection:#}" + ); + } + assert!(!inspection.to_string().contains("SENTINEL")); +} diff --git a/crates/cyber-tui/src/context_inspection.rs b/crates/cyber-tui/src/context_inspection.rs index 6d1042d9..a78cbe01 100644 --- a/crates/cyber-tui/src/context_inspection.rs +++ b/crates/cyber-tui/src/context_inspection.rs @@ -43,6 +43,7 @@ pub(crate) fn format(data: &Value) -> String { if inspection["epoch_pending"].as_bool() == Some(true) { lines.push("The next turn will rebuild the Context Epoch.".into()); } + lines.extend(pending_updates(inspection)); let changed = inspection["changed_sources"].as_u64().unwrap_or(0); if changed > 0 { lines.push(format!( @@ -59,6 +60,10 @@ pub(crate) fn format(data: &Value) -> String { source["origin"].as_str(), source["estimated_tokens"].as_u64(), ) { + let (id, origin) = ( + crate::messaging::clean_line(id), + crate::messaging::clean_line(origin), + ); lines.push(format!("{id} · {origin} · ~{tokens} tokens")); } } @@ -89,6 +94,7 @@ fn next_request(next: &Value) -> Vec { Some("sources_changed_on_disk") => "changed sources will be read again", Some("excludes_turn_instructions") => "turn-only instructions not included", Some("delivered_rules_changed") => "changed or revoked rules are not delivered again", + Some("compaction_pending") => "the requested compaction has not run yet", _ => continue, }; lines.push(format!(" Assumes {text}")); @@ -96,6 +102,24 @@ fn next_request(next: &Value) -> Vec { lines } +/// Updates queued on the Session for its next Safe Boundary. +fn pending_updates(inspection: &Value) -> Vec { + let mut lines = Vec::new(); + let hooks = inspection["pending_hook_contexts"].as_u64().unwrap_or(0); + if hooks > 0 { + let tokens = inspection["pending_hook_context_tokens"] + .as_u64() + .unwrap_or(0); + lines.push(format!( + "Pending hook context: {hooks} · ~{tokens} tokens · added before the next request" + )); + } + if inspection["compaction_pending"].as_bool() == Some(true) { + lines.push("Compaction requested · runs at the next safe boundary".into()); + } + lines +} + fn prepared_request(prepared: &Value) -> Vec { if !prepared.is_object() { return Vec::new(); @@ -341,4 +365,33 @@ mod tests { assert!(text.contains(" Assumes the last request used another model")); assert!(!text.contains("future")); } + + #[test] + fn inspection_shows_pending_hook_context_and_compaction_without_hook_text() { + let text = super::format(&serde_json::json!({ + "epoch": 2, + "inspection": { + "pending_hook_contexts": 2, "pending_hook_context_tokens": 140, + "compaction_pending": true, + "sources": [ + {"id": "history", "origin": "session_replay", "estimated_tokens": 900}, + {"id": "hook_context", "origin": "hook\u{001b}", "estimated_tokens": 60} + ], + "next_request": { + "estimated_input_tokens": 1200, + "assumptions": ["compaction_pending"] + } + } + })); + assert!( + text.contains("Pending hook context: 2 · ~140 tokens · added before the next request") + ); + assert!(text.contains("Compaction requested · runs at the next safe boundary")); + assert!(text.contains("hook_context · hook · ~60 tokens")); + assert!(text.contains(" Assumes the requested compaction has not run yet")); + assert!(!text.contains('\u{001b}')); + let idle = super::format(&serde_json::json!({"epoch": 1, "inspection": {}})); + assert!(!idle.contains("Pending hook context")); + assert!(!idle.contains("Compaction requested")); + } } diff --git a/docs/features.md b/docs/features.md index 67f6a29b..51ced88f 100644 --- a/docs/features.md +++ b/docs/features.md @@ -17,7 +17,7 @@ Implemented behavior and remaining scope, reviewed on **2026-10-16** (Cross-sess | Sessions | Durable inbox, streaming tool loops, interrupt/resume, crash recovery and compaction; Session branches: a conversation rewind keeps the later messages as an inactive branch, only the active path reaches the model, a compaction summary is reused only on the path it summarized, and `cyber sessions tree\|checkout\|label\|export [--all-branches]`, `GET /sessions/{id}/tree`, `POST .../checkout` (optional `code` restore through the three-way revert, refused with `SessionBusyError` while busy), `PUT\|DELETE .../labels/{name}`, `GET .../messages?branches=all`, the SDK operations and the TUI `/tree`, `/label` and branch header switch between attempts; Sessions rewound by older builds replay into the same tree with no migration ([guide](local-core-guide.md#session-branches)) | Available; branch acceptance by hand on macOS only (2026-10-20, [evidence](implementation/p1-status.md#2026-10-20-session-branches-add-session-branches)); the export (`--all-branches`) also takes `--sanitize`, `--include-children`, `--format md\|html` and `--output`, and `/export` writes it from the TUI (HTML has no per-Turn diffs yet); branches are never deleted or merged | | Native computer use | macOS 14+ ScreenCaptureKit/CoreGraphics adapter, explicit global opt-in and owner target grants, independent Stop, private frame evidence and durable native receipts ([guide](computer-use.md)) | Experimental; live desktop and release-signing acceptance pending | | Tools | Repository inspection/editing, notebook cell editing, command execution, web tools and instruction/skill loading and durable path-triggered skill reminders with model-loaded Turn permission scopes | Available; static configured command templates also reach the public API; broader skills/commands remain | -| Project instructions | `AGENTS.md`, `CLAUDE.md` (fallback where a directory has no `AGENTS.md`), `CONTEXT.md` and `CYBER.md` from the global config directory and every directory from the project root to the Location; `@path` imports, `AGENTS.override.md`, 32 KiB truncation, `CYBER_DISABLE_CLAUDE_MD`/`CYBER_DISABLE_PROJECT_CONFIG`, nested files attached to `read` results once per Context Epoch, configurable `instruction_limits`; path-scoped `.claude/rules` and `.cyber/rules` definitions (held until the checkout is approved) delivered once per Context Epoch after a matching read, edit or patch and fenced to the approval generation at settlement; `/context` and `GET /sessions/{id}/context` with per-source estimates, changed-on-disk sources, delivered rules with their current approval, withheld definitions and a next-request estimate; and the `cyber doctor` `instructions` check, which counts scoped rules and lists withheld ones by reason ([guide](local-core-guide.md#project-instructions-and-cybermd)) | Available locally (`complete-daily-coding-surfaces` §4); a rule already delivered whose approval is revoked or whose file changes is withdrawn at the next request: its text is elided from earlier tool results and the transcript keeps a withdrawal marker, without an Epoch rebuild; `.claude/CLAUDE.md`, the `~/.claude/CLAUDE.md` fallback and `/init` remain; native platform acceptance pending | +| Project instructions | `AGENTS.md`, `CLAUDE.md` (fallback where a directory has no `AGENTS.md`), `CONTEXT.md` and `CYBER.md` from the global config directory and every directory from the project root to the Location; `@path` imports, `AGENTS.override.md`, 32 KiB truncation, `CYBER_DISABLE_CLAUDE_MD`/`CYBER_DISABLE_PROJECT_CONFIG`, nested files attached to `read` results once per Context Epoch, configurable `instruction_limits`; path-scoped `.claude/rules` and `.cyber/rules` definitions (held until the checkout is approved) delivered once per Context Epoch after a matching read, edit or patch and fenced to the approval generation at settlement; `/context` and `GET /sessions/{id}/context` with per-source estimates (hook context counted as its own source), pending hook context and compaction, changed-on-disk sources, delivered rules with their current approval, withheld definitions and a next-request estimate; and the `cyber doctor` `instructions` check, which counts scoped rules and lists withheld ones by reason ([guide](local-core-guide.md#project-instructions-and-cybermd)) | Available locally (`complete-daily-coding-surfaces` §4); a rule already delivered whose approval is revoked or whose file changes is withdrawn at the next request: its text is elided from earlier tool results and the transcript keeps a withdrawal marker, without an Epoch rebuild; `.claude/CLAUDE.md`, the `~/.claude/CLAUDE.md` fallback and `/init` remain; native platform acceptance pending | | Base prompts and output styles | Embedded base prompts chosen by model family (`openai`, `anthropic`, `gemini`, `local`, `default`) from the catalog model, not the provider; built-in styles `default`, `concise`, `explanatory`, `learning` and custom `~/.config/cyber/output-styles/*.md` and `.cyber/output-styles/*.md` (validated names and frontmatter, 32 KiB regular files, project styles held until the checkout is trusted and part of its digest); selection by Session switch, creation, `output_style` config, then `default`, for primary Sessions only; `/output-style` picker, the Settings Config row, `cyber exec --output-style`, `GET /config/output-styles`, `PUT /config/output-style` and `POST /sessions/{id}/output-style`; a family, style or base prompt version change starts a new Context Epoch at the next Turn ([guide](local-core-guide.md#base-prompts-and-output-styles)) | Available; plugin styles, `cyber import` of `.claude/output-styles` and per-agent styles remain | | Language | `/language` or Settings → Config picks a language, saved as the global `language` and applied at once (`GET`/`PUT /api/v1/config/language`); `language` (`auto`, `en`, `pt-BR`, `es`, `fr`; `auto` follows `LC_ALL`/`LC_MESSAGES`/`LANG`) translates the TUI's composer, footer, welcome, help, command palette, permission and question prompts and Settings tabs; slash command names, keys, configuration and the CLI stay English; a set language also asks the model to reply in it (`core/language`, primary Sessions) ([guide](local-core-guide.md#language)) | Available (`add-localization`); other TUI screens and the web dashboard are still English | | Safety | Workspace trust (including repository skills' grants and `skills.paths`), permission rules, protected paths (startup, credential and Cyber Code state files, case-insensitive on macOS/Windows), file tools that check a symbolic link's target, descriptor-aware shell write detection, pinned first-party provider endpoints and no provider redirects ([guide](local-core-guide.md#what-a-repository-cannot-do-before-you-trust-it)), auto classification with confirmed `/approve`, macOS/Linux sandboxing and Windows AppContainer confinement with named profiles (`deny_read`), the environment policy, credential masking, `Sandbox denied:` reports with one-call escalation, excluded commands, `sandbox.*` events, `cyber sandbox explain/test/run`, the `bypass` eligibility gate (sandbox, container or `--dangerously-bypass-permissions`), org `policy.modes.disable` and the rule dry run (`cyber permissions test`, `GET /permissions/test`) | Available; on Windows, sandboxed Git Bash and PowerShell cannot start in the AppContainer yet ([issue #9](https://github.com/CyberdyneCorp/cybercode-cli/issues/9)), and the Windows proxy and full auto-mode controls remain partial P1 | diff --git a/docs/local-core-guide.md b/docs/local-core-guide.md index 88a3d17e..449875e1 100644 --- a/docs/local-core-guide.md +++ b/docs/local-core-guide.md @@ -1342,17 +1342,17 @@ The runtime resolves settings after the read and verifies its captured Location, ### Inspecting the current context -Open `/context` in the TUI to see the stored Context Epoch, projected source groups, estimated token counts and the last measured request. The estimate uses the persisted system text and projected conversation. Tool schemas and instructions added only during a turn are excluded. The panel also reports whether an Epoch rebuild is pending, how many inputs are queued or held, and how many scoped rules were delivered in the Epoch. Individual sources show their last recorded origin, status, estimate and instruction file paths. An unavailable observation retains the admitted source and its provenance. Historical sources without recorded provenance show unknown status and origin. Output-style changes deferred during a turn are marked pending. An instruction file edited or removed since it was read is marked as changed on disk, and the panel counts such sources: the next request reads them again. The check compares each file's size and modification time with those recorded when it was read, without opening the file, for up to 512 files per inspection. A source with no recorded times, such as one recorded by an older version, shows no answer, and new files are not detected until the next request. Inspection reports up to 256 sources, largest first, and up to 128 file paths per source within 16 KiB, with explicit omission counts. +Open `/context` in the TUI to see the stored Context Epoch, projected source groups, estimated token counts and the last measured request. The estimate uses the persisted system text and projected conversation. Tool schemas and instructions added only during a turn are excluded. The panel also reports whether an Epoch rebuild is pending, how many inputs are queued or held, and how many scoped rules were delivered in the Epoch. Hook `additional_context` committed to the conversation is its own `hook_context` source (origin `hook`), counted apart from `history`; once compaction summarizes it, it is no longer listed. Context queued by background hook handlers but not yet committed is shown as pending hook context with its count and estimate, and a compaction requested while a turn runs is shown as pending until it runs at the next safe boundary. Hook text is never shown. Individual sources show their last recorded origin, status, estimate and instruction file paths. An unavailable observation retains the admitted source and its provenance. Historical sources without recorded provenance show unknown status and origin. Output-style changes deferred during a turn are marked pending. An instruction file edited or removed since it was read is marked as changed on disk, and the panel counts such sources: the next request reads them again. The check compares each file's size and modification time with those recorded when it was read, without opening the file, for up to 512 files per inspection. A source with no recorded times, such as one recorded by an older version, shows no answer, and new files are not detected until the next request. Inspection reports up to 256 sources, largest first, and up to 128 file paths per source within 16 KiB, with explicit omission counts. The panel lists up to 128 rules delivered in the current Epoch, in delivery order, with their definition path, approval generation, a 12-digit digest prefix and an approval state. `current` means the checkout approval that admitted the rule still stands and the definition file's size and modification time match those recorded at delivery. `changed` means the file was edited or removed, or the checkout was re-approved under another generation. `revoked` means the checkout approval was withdrawn. `unknown` means the host has no trust inventory or the rule was recorded without file times by an older version. The state comes from the trust approval record and file metadata only; definition files are never opened. When any listed rule is changed or revoked, the panel says the next Context Epoch differs. Such a rule is withdrawn and elided from the next request (see above). -Once a request has been prepared, the panel also shows an estimate for the next request: the stored projection plus the tool schemas of the last prepared request. It lists what it assumes: tool schemas sized as in that request, and, when they apply, that the model changed since, that the Epoch will be rebuilt, that changed sources will be read again, or that changed or revoked rules are not delivered again. Instructions added only while a turn is assembled are not included. +Once a request has been prepared, the panel also shows an estimate for the next request: the stored projection plus the tool schemas of the last prepared request. It lists what it assumes: tool schemas sized as in that request, and, when they apply, that the model changed since, that the Epoch will be rebuilt, that changed sources will be read again, that changed or revoked rules are not delivered again, or that a requested compaction has not run yet. Pending hook context is included in the estimate. Instructions added only while a turn is assembled are not included. The last prepared request has a separate complete estimate captured after attachments, turn instructions, deferred tool descriptions and callable schemas are assembled. Its step ID, model and Epoch identify the request it describes. It can precede a model call that was later interrupted. The stored projection remains an estimate of the current recorded conversation. Provider token usage appears separately when the request finishes. Individual source estimates use independent rounding. -Authenticated clients can use `GET /api/v1/sessions/{sessionID}/context` for the same metadata. Pass `include_content=true` to retrieve the stored baseline, compaction summary and task text. Inspection reads stored Session state without starting a turn or reloading instruction files; it only reads the metadata of files already loaded. Each source has `changed_on_disk` (`true`, `false` or `null` when unknown) and the response has `changed_sources`, `delivered_rules` (`path`, `root`, `digest_prefix`, `generation` and `approval`), `omitted_delivered_rules`, `changed_delivered_rules`, `withheld_sources`, `omitted_withheld_sources` and `next_request` (`estimated_input_tokens`, `estimated_input_utilization` and `assumptions`, or `null` before the first prepared request). +Authenticated clients can use `GET /api/v1/sessions/{sessionID}/context` for the same metadata. Pass `include_content=true` to retrieve the stored baseline, compaction summary and task text. Inspection reads stored Session state without starting a turn or reloading instruction files; it only reads the metadata of files already loaded. Each source has `changed_on_disk` (`true`, `false` or `null` when unknown) and the response has `changed_sources`, `delivered_rules` (`path`, `root`, `digest_prefix`, `generation` and `approval`), `omitted_delivered_rules`, `changed_delivered_rules`, `withheld_sources`, `omitted_withheld_sources`, `pending_hook_contexts`, `pending_hook_context_tokens`, `compaction_pending` and `next_request` (`estimated_input_tokens`, `estimated_input_utilization` and `assumptions`, or `null` before the first prepared request). -`withheld_sources` lists up to 64 rule definitions (or whole rule directories) that applied at the last request boundary but were left out, each with its `source`, `path` and a `reason`: `trust_held` (the checkout's definition is not approved or differs from its approval), `read_denied` (read permission rules refuse it, or it or its directory could not be read safely, for example through a symlink), `invalid_frontmatter`, `compat_disabled` (a `.claude/rules` definition while Claude compatibility is off) or `bound_exceeded` (rule discovery reached its file or byte bound). They are recorded when the request boundary loads instructions; inspection does not open them, reports no size for them and counts none of their bytes in any estimate. The `/context` panel lists them under "Withheld definitions". +`withheld_sources` lists up to 64 rule definitions (or whole rule directories) and project instruction files or imports that applied at the last request boundary but were left out, each with its `source`, `path` and a `reason`: `trust_held` (the checkout's definition is not approved or differs from its approval), `read_denied` (read permission rules refuse it, or it or its directory could not be read safely, for example through a symlink), `invalid_frontmatter`, `compat_disabled` (a `.claude/rules` definition while Claude compatibility is off), `bound_exceeded` (rule discovery reached its file or byte bound) or `outside_project` (a project instruction file or import that resolves outside the project, for example through a symlink). They are recorded when the request boundary loads instructions; inspection does not open them, reports no size for them and counts none of their bytes in any estimate. The `/context` panel lists them under "Withheld definitions". ### Switches @@ -1365,7 +1365,7 @@ These are read from the server's environment (a value of `1`, `true`, `yes` or ` ### Checking what loads -`cyber doctor` has an `instructions` line that lists, in load order, the files a new Session at the current directory loads (`N loaded: , ...`), and warns about truncated files and unresolved or refused imports. It counts the valid path-scoped rule definitions it found (`N path-scoped rule definitions attached on matching file access`); they are not part of the baseline and their paths are not listed. Rule definitions the loader withheld are listed by reason (`withheld (trust_held): , ...`, likewise `read_denied`, `invalid_frontmatter`, `compat_disabled` and `bound_exceeded`), at most 64 plus a count of the rest, without their text; any withheld definition makes the line a warning. With `compat.claude` false, `.claude/rules` directories are not read, so their definitions are neither counted nor listed; one reached through an import is listed as `compat_disabled`. `GET /api/v1/sessions/{id}/context?include_content=true` returns the rendered baseline with its `Instructions from:` labels. +`cyber doctor` has an `instructions` line that lists, in load order, the files a new Session at the current directory loads (`N loaded: , ...`), and warns about truncated files and unresolved or refused imports. It counts the valid path-scoped rule definitions it found (`N path-scoped rule definitions attached on matching file access`); they are not part of the baseline and their paths are not listed. Rule definitions and project instruction files the loader withheld are listed by reason (`withheld (trust_held): , ...`, likewise `read_denied`, `invalid_frontmatter`, `compat_disabled`, `bound_exceeded` and `outside_project`), at most 64 plus a count of the rest, without their text; any withheld definition makes the line a warning. With `compat.claude` false, `.claude/rules` directories are not read, so their definitions are neither counted nor listed; one reached through an import is listed as `compat_disabled`. `GET /api/v1/sessions/{id}/context?include_content=true` returns the rendered baseline with its `Instructions from:` labels. ### Migrating from Claude Code diff --git a/openspec/changes/complete-daily-coding-surfaces/implementation.md b/openspec/changes/complete-daily-coding-surfaces/implementation.md index 3c6454ab..558c1dc3 100644 --- a/openspec/changes/complete-daily-coding-surfaces/implementation.md +++ b/openspec/changes/complete-daily-coding-surfaces/implementation.md @@ -4255,3 +4255,28 @@ the evidence is gone). No code changed; construction evidence keeps no cleanup authority until that change is approved and implemented. A separate change validates cleanly and keeps the security-relevant protocol revision reviewable on its own. + +## Rules and context inspection audit (2026-11-16, local) + +Branch `feat/context-rules`, stacked on `feat/managed-recovery-owner` (PR #123). +Tasks 4.1–4.4 were compared clause by clause with the `system-context`, +`configuration` and `tui` deltas. The implementation and tests listed in the task +notes already covered rule discovery, precedence, overrides, validated globs, +bounded assembly, delivery fencing, withdrawal, restart and the inspection +route/TUI/doctor. Two gaps were closed: + +- Hook `additional_context` was counted inside `history`, and context queued by + background hook handlers or a compaction requested during a turn was invisible + to inspection. Inspection now reports a `hook_context` source (origin `hook`), + pending hook context with its estimate (added to `next_request`) and + `compaction_pending`, never the hook text. A new delta scenario states this. +- Project instruction files and imports refused outside the project or by read + rules were warnings only; they are now typed withheld entries + (`outside_project`, `read_denied`) shown by inspection and doctor. + +Evidence: `cyber-server` library and `context_compaction`/`http` suites, +`cyber-tui` context tests, `cyber-cli` doctor tests and `cyber-app --test +instructions` under nextest `ci` on macOS arm64; OpenAPI/SDK regenerated. Hook +context is not a rule, so once-per-Epoch delivery, approval fencing and withdrawal +do not apply, and the redaction requirement (tool output) does not cover it. +Native platform acceptance is not claimed and stays with 7.2. diff --git a/openspec/changes/complete-daily-coding-surfaces/specs/system-context/spec.md b/openspec/changes/complete-daily-coding-surfaces/specs/system-context/spec.md index 41ac9ed1..77a232be 100644 --- a/openspec/changes/complete-daily-coding-surfaces/specs/system-context/spec.md +++ b/openspec/changes/complete-daily-coding-surfaces/specs/system-context/spec.md @@ -25,6 +25,14 @@ - **AND** it lists each assumption that can make the estimate differ: tool schemas taken from the last request, a changed model, a pending Epoch rebuild, sources changed on disk, and excluded turn-only instructions - **AND** before any request is prepared the next-request estimate is absent rather than omitting tool schemas silently +#### Scenario: Hook context and queued updates in inspection +- **GIVEN** a Session whose conversation holds hook `additional_context`, while background hook context waits for the next Safe Boundary and a compaction was requested during a turn +- **WHEN** an owner inspects context +- **THEN** committed hook context is reported as its own source with origin `hook`, apart from the history estimate, until compaction summarizes it +- **AND** the queued hook context is reported as a pending update with its count and estimated tokens and is included in the next-request estimate +- **AND** the requested compaction is reported as pending and listed as a next-request assumption +- **AND** inspection never returns hook context text + #### Scenario: Delivered rules with changed or revoked approval - **GIVEN** scoped rules delivered in the current Context Epoch - **WHEN** one rule's checkout approval is withdrawn and an owner inspects context diff --git a/openspec/changes/complete-daily-coding-surfaces/tasks.md b/openspec/changes/complete-daily-coding-surfaces/tasks.md index ace4fe4b..906e54dd 100644 --- a/openspec/changes/complete-daily-coding-surfaces/tasks.md +++ b/openspec/changes/complete-daily-coding-surfaces/tasks.md @@ -168,14 +168,15 @@ proof/reconciliation for these cuts before claiming complete managed recovery. ## 4. Rules and context inspection -- [ ] 4.1 Implement trusted path-scoped rule discovery/precedence, validated globs, overrides and bounded instruction assembly without changing `instructions` array compatibility. +- [x] 4.1 Implement trusted path-scoped rule discovery/precedence, validated globs, overrides and bounded instruction assembly without changing `instructions` array compatibility. - `cyber doctor` now diagnoses rule discovery with the runtime loader: it counts discovered path-scoped definitions without adding them to the baseline it lists, and reports held, read-denied, invalid, compatibility-disabled and bound-exceeded definitions by reason, honouring `compat.claude` (see 4.3 for the tests). Directory precedence is now covered through the real App: from a nested Location the baseline holds the root's ordinary files, sorted `.claude/rules`, sorted `.cyber/rules`, then the same order for the nested directory, and `compat.claude: false` leaves every `.claude/rules` definition out (`rule_directories_load_claude_then_cyber_rules_root_before_nested`). Platform acceptance and the remaining 4.1 obligations stay open. -- [ ] 4.2 Bind reminder delivery to successful authorized operations and Context Epoch identity, including edits/patches, partial settlements, compaction/restart and changed/revoked rules. +- [x] 4.2 Bind reminder delivery to successful authorized operations and Context Epoch identity, including edits/patches, partial settlements, compaction/restart and changed/revoked rules. - Settlement now fences each delivered project rule to the approval it was discovered under: under the Session settlement lock (group settlement and exact `/approve` replay) the runtime re-resolves the Location's rule gate and drops the whole nested reminder, keeping the tool result and recording no `rule_reminders`/`reminded_rules`, unless every project binding still authorizes with the same checkout root, approval generation and definition digest (`RuleGate::still_authorizes`; owner-global bindings pass). A revocation between discovery and commit therefore neither delivers nor consumes the rule, and a later matching read after re-approval delivers it once (`a_rule_revoked_while_its_read_settles_is_neither_delivered_nor_consumed`, through the `Runtime::configure_settlement_probe` test seam). Earlier slices cover denied/failed operations, edits, partial patches, compaction and changed bytes. Each delivered binding now persists in the Epoch (`Epoch::delivered_rules`, replayed from `rule_reminders`, with the definition's size/modification time recorded at delivery), so inspection reports a rule revoked or changed after delivery (see 4.3). Restart and replay are now covered end to end over a file database with a second App: the restarted server rebuilds `reminded_rules` from durable settlements and keeps the Epoch, so a matching read after restart gets no second reminder (`a_delivered_scoped_rule_is_not_redelivered_after_server_restart`); a read cut off by the restart is recovered as `interrupted` and consumes nothing, and replay ignores even an interrupted settlement carrying a binding and proof (`a_read_interrupted_by_restart_does_not_consume_its_rule`); an approval withdrawn while the server was down suppresses delivery after restart until re-approval (`a_rule_revoked_while_the_server_was_down_is_not_delivered_after_restart`). No defect was found. Owner decision 2026-11-15: a delivered rule later revoked or changed is elided on replay. At the next request boundary one `rule_withdrawn` system marker records it (identity, path, state, delivered block label/length/digest); from that request on view projection replaces its block in earlier tool results with a notice, stored results are unchanged, no Epoch rebuild or compaction is forced, and replay restores the elision after restart (`a_revoked_delivered_rule_is_elided_from_later_requests_and_after_restart`, `a_changed_delivered_rule_is_elided_from_the_next_request`; unit tests in `runtime::rule_withdrawal`). Remaining: platform acceptance. -- [ ] 4.3 Add authenticated read-only context inspection and `/context`, source estimates/origins/status/pending updates and honest utilization; synchronize OpenAPI/SDK and doctor diagnostics. - - The Session endpoint and TUI panel expose stored source groups and an estimate based on request replay. The default response omits stored text. Individual source metadata now persists with Epoch creation and ordinary observation, including retained-unavailable state, bounded file provenance, historical unknowns and deferred output-style updates. The last prepared request now records the complete assembly estimate, including callable schemas and turn instructions, for comparison with actual provider input. Inspection now also reports instruction files edited or removed since they were read: each file's size and modification time are recorded from the handle it was read through, and inspection compares them with current metadata (bounded to 512 files, no file opened), marking each source and counting changed sources in the API and TUI. Sources without complete stamps report unknown; files added since the read are found only at the next request. Inspection also gives a next-request estimate: the stored projection plus the last prepared request's tool schemas, listing its assumptions (tool schemas from the last request, changed model, pending Epoch rebuild, sources changed on disk, excluded turn-only instructions); it is absent before the first prepared request. It is not an exact projection: tool visibility and configuration are resolved only at the next request boundary, which inspection does not run. Inspection and the TUI panel now list up to 128 rules delivered in the current Epoch (path, root, 12-digit digest prefix, approval generation, omitted count) with an `approval` of current/changed/revoked/unknown, computed from the host's trust approval record and the definition's file metadata without opening it; a changed or revoked rule is counted and adds the `delivered_rules_changed` next-request assumption (`inspection_lists_delivered_rules_and_marks_revoked_approval_without_reading_them`, `inspection_reports_a_delivered_rule_as_revoked_after_its_approval_is_withdrawn`, TUI `inspection_shows_revoked_delivered_rules`, HTTP default response without rule bodies; OpenAPI/SDK regenerated). Inspection now also reports withheld definitions (scenario "Inspection of an untrusted source"): at the ordinary request boundary the instruction loader records, as typed entries rather than only warnings, each rule definition or refused rule directory it left out, with reason `trust_held`, `read_denied`, `invalid_frontmatter`, `compat_disabled` or `bound_exceeded`, bounded to 64 per source plus an omitted count and with no sizes; they persist in the source metadata and are listed as `withheld_sources`/`omitted_withheld_sources` in the API and under "Withheld definitions" in the TUI panel (`inspection_reports_held_rule_definitions_without_reading_or_counting_them`, which makes the held file unreadable before inspecting, checks no events are appended and that the next-request estimate is the same for a 64 KiB and a tiny held body; unit `withheld_rule_definitions_are_recorded_with_their_reason`, `a_refused_rule_directory_is_withheld_as_a_whole`; HTTP default response lists only `source`/`path`/`reason`; TUI `inspection_shows_withheld_definitions_without_sizes`; OpenAPI/SDK regenerated). Withheld non-rule instruction files (outside the project, refused by read rules) and refused imports of ordinary files remain warnings only. `cyber doctor`'s `instructions` check now reuses the same typed entries: it counts valid path-scoped definitions discovered but not attached to the baseline (`Instructions::scoped`) and lists withheld definitions by reason without their text or a duplicate warning, warning when any is withheld; with `compat.claude` false, `.claude/rules` definitions are neither counted nor listed, and one reached by import is listed as `compat_disabled` (`doctor_warns_about_held_and_invalid_rule_definitions`, `doctor_counts_scoped_rules_without_adding_them_to_the_baseline`, `doctor_respects_compat_claude_false_for_claude_rules`). Platform acceptance remains open. -- [ ] 4.4 Test no rule leakage across Location/Epoch, denied/failed calls, truncation, untrusted sources, stale response and token-count consistency with actual request assembly. +- [x] 4.3 Add authenticated read-only context inspection and `/context`, source estimates/origins/status/pending updates and honest utilization; synchronize OpenAPI/SDK and doctor diagnostics. + - The Session endpoint and TUI panel expose stored source groups and an estimate based on request replay. The default response omits stored text. Individual source metadata now persists with Epoch creation and ordinary observation, including retained-unavailable state, bounded file provenance, historical unknowns and deferred output-style updates. The last prepared request now records the complete assembly estimate, including callable schemas and turn instructions, for comparison with actual provider input. Inspection now also reports instruction files edited or removed since they were read: each file's size and modification time are recorded from the handle it was read through, and inspection compares them with current metadata (bounded to 512 files, no file opened), marking each source and counting changed sources in the API and TUI. Sources without complete stamps report unknown; files added since the read are found only at the next request. Inspection also gives a next-request estimate: the stored projection plus the last prepared request's tool schemas, listing its assumptions (tool schemas from the last request, changed model, pending Epoch rebuild, sources changed on disk, excluded turn-only instructions); it is absent before the first prepared request. It is not an exact projection: tool visibility and configuration are resolved only at the next request boundary, which inspection does not run. Inspection and the TUI panel now list up to 128 rules delivered in the current Epoch (path, root, 12-digit digest prefix, approval generation, omitted count) with an `approval` of current/changed/revoked/unknown, computed from the host's trust approval record and the definition's file metadata without opening it; a changed or revoked rule is counted and adds the `delivered_rules_changed` next-request assumption (`inspection_lists_delivered_rules_and_marks_revoked_approval_without_reading_them`, `inspection_reports_a_delivered_rule_as_revoked_after_its_approval_is_withdrawn`, TUI `inspection_shows_revoked_delivered_rules`, HTTP default response without rule bodies; OpenAPI/SDK regenerated). Inspection now also reports withheld definitions (scenario "Inspection of an untrusted source"): at the ordinary request boundary the instruction loader records, as typed entries rather than only warnings, each rule definition or refused rule directory it left out, with reason `trust_held`, `read_denied`, `invalid_frontmatter`, `compat_disabled` or `bound_exceeded`, bounded to 64 per source plus an omitted count and with no sizes; they persist in the source metadata and are listed as `withheld_sources`/`omitted_withheld_sources` in the API and under "Withheld definitions" in the TUI panel (`inspection_reports_held_rule_definitions_without_reading_or_counting_them`, which makes the held file unreadable before inspecting, checks no events are appended and that the next-request estimate is the same for a 64 KiB and a tiny held body; unit `withheld_rule_definitions_are_recorded_with_their_reason`, `a_refused_rule_directory_is_withheld_as_a_whole`; HTTP default response lists only `source`/`path`/`reason`; TUI `inspection_shows_withheld_definitions_without_sizes`; OpenAPI/SDK regenerated). Project instruction files and imports refused because they resolve outside the project or because read rules deny them are now typed withheld entries too (`outside_project`, `read_denied`): unit `project_imports_stay_inside_the_project`, `the_read_gate_refuses_project_files_and_imports_but_not_global_files`; `inspection_reports_instruction_files_refused_outside_the_project`; doctor lists them once by reason (`doctor_warns_about_an_instruction_file_outside_the_project`). `cyber doctor`'s `instructions` check now reuses the same typed entries: it counts valid path-scoped definitions discovered but not attached to the baseline (`Instructions::scoped`) and lists withheld definitions by reason without their text or a duplicate warning, warning when any is withheld; with `compat.claude` false, `.claude/rules` definitions are neither counted nor listed, and one reached by import is listed as `compat_disabled` (`doctor_warns_about_held_and_invalid_rule_definitions`, `doctor_counts_scoped_rules_without_adding_them_to_the_baseline`, `doctor_respects_compat_claude_false_for_claude_rules`). Platform acceptance remains open. +- [x] 4.4 Test no rule leakage across Location/Epoch, denied/failed calls, truncation, untrusted sources, stale response and token-count consistency with actual request assembly. - A scoped rule delivered in one Epoch is delivered again, once, by the first matching read after compaction starts a new Epoch (`a_scoped_rule_is_delivered_again_in_the_epoch_after_compaction`). Earlier cases already cover denied reads, partial patches, nested checkouts, held/untrusted definitions and suppressed delivery when the Epoch or Location changes while a read settles. A trust revocation between rule discovery and commit suppresses delivery without consuming the rule (`a_rule_revoked_while_its_read_settles_is_neither_delivered_nor_consumed`; unit `a_binding_from_a_revoked_generation_is_not_authorized`). Restart does not leak or re-deliver rules: delivered rules stay consumed in the same Epoch after restart, a read interrupted by restart leaves its rule eligible, and a revocation while the server was down holds the rule after restart (the three `*_restart` tests in `crates/cyber-app/tests/instructions.rs`). Untrusted sources are now also covered at inspection: held, read-denied, invalid and compatibility-disabled definitions are reported as withheld without being opened by inspection or counted in any estimate (see 4.3). Location and Session isolation are now covered in `crates/cyber-app/tests/instructions.rs`: after the Session enters a worktree, the origin's delivery and approval neither suppress nor supply the worktree's copy of the rule (held until that checkout is approved, then delivered once with the worktree as its root), and an origin-only rule never reaches the moved Session through a read of the origin file (`a_rule_delivered_in_one_location_is_not_reused_after_the_session_moves`); a child Session and a fork cut before the delivering read start with no delivered rules, deliver the rule once in their own Epoch and leave the parent's record unchanged (`a_child_or_forked_session_does_not_inherit_parent_rule_delivery`; a full fork copies the Epoch together with the history that carries the reminder, by design). Truncation: with 20 matching rules under a 512-byte budget each reminder records exactly the rules it labels, as a delivered body or a whole entry of its bounded read list, unlisted rules stay eligible and later reads label each once (`a_truncated_rule_reminder_records_only_labelled_bindings`). Token-count consistency: rebuilding the provider-neutral request from the scripted provider's actual body (system parts, messages, tool definitions) gives exactly the `last_prepared_request` estimate, for the request carrying the rule reminder and the next one; the idle `next_request` estimate equals the following request without its new prompt, rounded in two parts (stored projection sized with an empty tool list, plus the last request's schema estimate), so it is within one token of the request sent (`inspection_estimate_matches_the_assembled_request_with_rule_reminders`). These need the real tool host's native read receipts, so they live in the App suite rather than the `cyber-server` harness. No defect was found. Platform acceptance remains open. + - Audit 2026-11-16 (`feat/context-rules`, stacked on `feat/managed-recovery-owner`). Each 4.x clause was compared with the spec deltas, code and tests. Already implemented and tested before this round: discovery/precedence and `compat.claude` (`rule_directories_load_claude_then_cyber_rules_root_before_nested`), `AGENTS.override.md` (`agents_override_replaces_agents_claude_and_cyber_md`), invalid frontmatter/globs without unscoped fallback (`cyber_core::rules` `invalid_frontmatter_never_falls_back_to_unscoped_guidance`), bounded assembly and limits (`configured_instruction_limits_bound_baseline_and_nested_provider_text`, `bounded_lists_record_only_labelled_files_and_retry_unlisted_imports`, `instruction_limits_*` in `cyber-core/tests/config.rs`, including trust-held project limits and unchanged `instructions` concatenation), delivery fencing, withdrawal and restart (4.2), and the inspection route/TUI/doctor (4.3). Gaps found and closed here: (1) hook `additional_context` was folded into `history` and queued background hook context and a compaction requested during a turn were not reported as pending updates; inspection now reports committed hook context as its own `hook_context` source (origin `hook`, also in `last_prepared_request`), `pending_hook_contexts`/`pending_hook_context_tokens` (added to `next_request`) and `compaction_pending` (assumption `compaction_pending`), never the hook text (`inspection_reports_hook_context_as_pending_then_as_its_own_source`, `inspection_reports_a_compaction_requested_during_a_turn`, TUI `inspection_shows_pending_hook_context_and_compaction_without_hook_text`; spec scenario "Hook context and queued updates in inspection"); (2) refused non-rule instruction files were warnings only (see 4.3). OpenAPI/SDK regenerated. Hook context is not a rule: once-per-Epoch delivery, approval fencing and withdrawal do not apply to it, and it is not redacted (the redaction requirement covers tool output only). Checked off from local macOS arm64 evidence; native platform acceptance is not claimed here and stays with 7.2. ## 5. Root structured output diff --git a/sdk/openapi.json b/sdk/openapi.json index a4eddefc..4ead47a7 100644 --- a/sdk/openapi.json +++ b/sdk/openapi.json @@ -10157,6 +10157,22 @@ "format": "uint", "minimum": 0 }, + "pending_hook_contexts": { + "type": "integer", + "format": "uint", + "minimum": 0, + "description": "Hook `additional_context` from background handlers, queued to be committed\nbefore the next request. Its text is never returned." + }, + "pending_hook_context_tokens": { + "type": "integer", + "format": "uint64", + "minimum": 0, + "description": "Estimated tokens of the queued hook context; included in `next_request`." + }, + "compaction_pending": { + "type": "boolean", + "description": "A compaction was requested while the Session was running and applies at the\nnext Safe Boundary." + }, "delivered_rule_count": { "type": "integer", "format": "uint", @@ -10219,6 +10235,9 @@ "epoch_pending", "queued_inputs", "held_inputs", + "pending_hook_contexts", + "pending_hook_context_tokens", + "compaction_pending", "delivered_rule_count", "delivered_rules", "omitted_delivered_rules", @@ -10457,6 +10476,11 @@ "type": "string", "const": "bound_exceeded", "description": "Rule discovery reached its file or byte bound before it." + }, + { + "type": "string", + "const": "outside_project", + "description": "A project instruction file or import resolves outside the project." } ], "description": "Why a definition that applies to the Location was left out of context." @@ -10596,6 +10620,11 @@ "type": "string", "const": "delivered_rules_changed", "description": "A rule delivered in this Context Epoch was changed or its approval revoked; the\nnext Context Epoch will not deliver that definition again." + }, + { + "type": "string", + "const": "compaction_pending", + "description": "A requested compaction runs at the next Safe Boundary and replaces the history\nthis estimate counts." } ], "description": "Why a next-request estimate can differ from the request actually sent." diff --git a/sdk/typescript/src/generated/types.ts b/sdk/typescript/src/generated/types.ts index c83fd6cd..7aca1316 100644 --- a/sdk/typescript/src/generated/types.ts +++ b/sdk/typescript/src/generated/types.ts @@ -886,6 +886,18 @@ export type ContextInspection = { epoch_pending: boolean; queued_inputs: number; held_inputs: number; + /** + * Hook `additional_context` from background handlers, queued to be committed + * before the next request. Its text is never returned. + */ + pending_hook_contexts: number; + /** Estimated tokens of the queued hook context; included in `next_request`. */ + pending_hook_context_tokens: number; + /** + * A compaction was requested while the Session was running and applies at the + * next Safe Boundary. + */ + compaction_pending: boolean; delivered_rule_count: number; /** * Rules delivered in this Context Epoch, in delivery order, with their current @@ -1508,7 +1520,7 @@ export type ErrorBody = { }; /** Why a next-request estimate can differ from the request actually sent. */ -export type EstimateAssumption = "tool_schemas_from_last_request" | "model_changed" | "epoch_rebuild_pending" | "sources_changed_on_disk" | "excludes_turn_instructions" | "delivered_rules_changed"; +export type EstimateAssumption = "tool_schemas_from_last_request" | "model_changed" | "epoch_rebuild_pending" | "sources_changed_on_disk" | "excludes_turn_instructions" | "delivered_rules_changed" | "compaction_pending"; /** `session.goal.evaluated.1`. */ export type Evaluated = { @@ -5996,7 +6008,7 @@ export type WithheldContextSource = { }; /** Why a definition that applies to the Location was left out of context. */ -export type WithheldReason = "trust_held" | "read_denied" | "invalid_frontmatter" | "compat_disabled" | "bound_exceeded"; +export type WithheldReason = "trust_held" | "read_denied" | "invalid_frontmatter" | "compat_disabled" | "bound_exceeded" | "outside_project"; /** A definition left out of context, without its content or size. */ export type WithheldSource = {