diff --git a/README.md b/README.md index 8720eb9..ddba476 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,21 @@ can replace a verified pre-caret span in supported Unicode Edit controls. Unknow controls, unsafe selections and security refusals skip correction and log only failure metadata. +**App Rules** adds layered terminal/editor safety. New terminal and editor rules +disable manual, word-count and character triggers. Enable **Manual** explicitly; +editors also require **Editor prose**. **Safety** defaults to automatic detection, +or can classify a custom app as `terminal` or `code_editor`. Known apps cannot be +downgraded by choosing `auto`. + +Manual requests in these apps require selected prose. Heuristics reject commands, +flags, paths, URLs, identifiers, code and uncertain fragments before either engine +runs. Editor automatic correction requires explicit trigger and prose opt-ins, +and a whole segment of recognizable line-comment prose. Terminal automatic +requests still skip because the shell context cannot be proven safe. +Existing permissions survive migration; the new editor prose permission starts +off. Selected results still skip native replacement until caret-end proof is +available, and manual-only rules do not enable continuous typed-input capture. + ## Run App From the repository root, build and run AutoFix: diff --git a/app-core-rust/README.md b/app-core-rust/README.md index a0d9bdd..647a16e 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -283,6 +283,34 @@ context/executable/caret-anchor versions, trigger, engine kind, and correction m Grammar, language, confidence, dictionary, and API settings are snapshotted for engine execution. Following selected text stays informative. +Terminal/editor text safety lives in `background/security/text_safety`. +SQLite app rules store `safety_mode` (`auto`, `terminal`, `code_editor`) and +`prose_context_allowed` (false by default). Schema v5 adds these fields without +changing existing trigger/engine choices; legacy IPC payloads default to auto/off. +Fresh and reset editor rules now default manual correction to off too. Known +process names and terminal/editor title heuristics enforce conservative defaults +even after a rule is deleted. Custom profiles classify other applications; +known terminal/editor identities cannot be downgraded to general text fields. + +Restricted manual requests require selection, explicit manual permission and, +for editors, explicit prose permission. Admission recognizes only conservative +English sentence shapes, with at least three words, sentence punctuation and a +prose function word. Structured punctuation, identifiers, commands, paths, URLs, +mixed prose/code and unclear surrounding lines refuse the entire request. +Uncertain languages and fragments skip. Editor automatic requests additionally +require their trigger permission and complete `//` or `#` line-comment sentences; +inline/block comments are unsupported. Terminal automatic text requests skip +because the shell dialect and prompt state are unknown. Manual-only rules never +authorize tracking or final-fix triggers. Selected results retain the existing +native replacement refusal until the live caret end can be proven. + +Admission reads app rules through a fresh, nonblocking read-only connection without +migrations or writer reservations. API sends and native replacement recheck the +same text policy under their existing writer reservations, so a committed prose +revocation prevents further sends or mutation. Neither logs nor skip notices include +the rejected text. Hard secure-field gates, dictionary policy, clipboard preservation, +session ownership and undo remain enforced. + Frozen results survive processed typing and backspace confined to the new active context. The tracker retains the original typed ranges and supplies the replacement owner with the known following text up to the current caret, which must be verified diff --git a/app-core-rust/src/background/mod.rs b/app-core-rust/src/background/mod.rs index 498805f..a69fcb1 100644 --- a/app-core-rust/src/background/mod.rs +++ b/app-core-rust/src/background/mod.rs @@ -472,9 +472,9 @@ impl InputProcessor { context_capture::read_before_caret(target, &config.context, known_chars) }, |target, request, output| { - let Some(_policy_guard) = - SecurityGate::authorize_replacement(request.trigger, config, database, target) - else { + let Some(_policy_guard) = SecurityGate::authorize_correction_replacement( + request, config, database, target, + ) else { tracing::warn!( success = false, method = "none", diff --git a/app-core-rust/src/background/pipeline.rs b/app-core-rust/src/background/pipeline.rs index 88e6cfe..6365b82 100644 --- a/app-core-rust/src/background/pipeline.rs +++ b/app-core-rust/src/background/pipeline.rs @@ -193,6 +193,30 @@ impl CorrectionPipeline { config: &AppConfig, dictionary: Vec, ) -> bool { + // Check executable text before either local execution or API transmission. + if let Some(path) = self.database_path.as_deref() { + let allowed = + crate::storage::AppPolicyGuard::read_rules_nowait(path).is_ok_and(|rules| { + matches!( + super::security::check_detection( + request.trigger, + config, + &rules, + super::target::TargetDetection::Available(target.clone()) + ), + super::security::SecurityDecision::Allowed { .. } + ) && super::security::request_allowed(&rules, &target, &request) + }); + if !allowed { + self.feedback_event = Some(( + Event::Blocked, + request.trigger == TriggerKind::ManualShortcut, + )); + return false; + } + } else if !super::security::request_allowed(&[], &target, &request) { + return false; + } if request.pending_segment_id.is_none() { self.cancel(); } @@ -203,7 +227,7 @@ impl CorrectionPipeline { self.database_path.clone(), config.clone(), target.clone(), - request.trigger, + request.clone(), Arc::clone(&cancelled), ); let input = CorrectionInput { diff --git a/app-core-rust/src/background/pipeline/tests.rs b/app-core-rust/src/background/pipeline/tests.rs index a805273..ee33feb 100644 --- a/app-core-rust/src/background/pipeline/tests.rs +++ b/app-core-rust/src/background/pipeline/tests.rs @@ -12,6 +12,64 @@ const STAMP: InputStamp = InputStamp { sequence: 12, }; +/// Both routes refuse restricted content before dispatch; refusal preserves session ownership. +#[test] +fn restricted_text_never_reaches_either_correction_engine() { + let path = std::env::temp_dir().join(format!( + "autofix-text-safety-{}-{}.sqlite", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let database = crate::storage::Database::open(&path).unwrap(); + for process in ["cmd.exe", "code.exe"] { + let mut rule = database + .app_rules() + .list() + .unwrap() + .into_iter() + .find(|rule| rule.process_name == process) + .unwrap(); + rule.manual_shortcut_allowed = true; + rule.prose_context_allowed = true; + database.app_rules().upsert(&rule).unwrap(); + for engine in [ + crate::settings::CorrectionEngine::Local, + crate::settings::CorrectionEngine::Api, + ] { + let mut config = AppConfig::default(); + config.correction.engine = engine; + let mut restricted_target = target(); + restricted_target.process_name = process.into(); + let manager = manager(&config, "This is user_name."); + let mut request = request(&manager, &config); + request.selected_text = true; + let mut pipeline = + CorrectionPipeline::start(|_| panic!("unsafe text reached correction engine")) + .unwrap(); + pipeline.database_path = Some(path.clone()); + assert!(!pipeline.submit( + request, + manager.active().unwrap(), + restricted_target, + STAMP, + &config, + vec![] + )); + assert!(pipeline.active.is_empty()); + assert!(pipeline.mailbox.0.lock().unwrap().jobs.is_empty()); + assert_eq!( + manager.active().unwrap().editable_context(), + "This is user_name." + ); + } + } + drop(database); + std::fs::remove_file(path).unwrap(); +} + /// Unavailable exclusion storage refuses submission without dispatching work or changing session text. #[test] fn unavailable_exclusions_refuse_submission_without_storage_side_effects() { @@ -344,6 +402,8 @@ fn queued_api_job_is_denied_after_rule_revocation_and_releases_its_slot() { character_trigger_allowed: true, local_engine_allowed: true, api_engine_allowed: false, + safety_mode: "auto".into(), + prose_context_allowed: false, }) .unwrap(); wait_completion(&pipeline); diff --git a/app-core-rust/src/background/security.rs b/app-core-rust/src/background/security.rs index b2579f5..b602d2e 100644 --- a/app-core-rust/src/background/security.rs +++ b/app-core-rust/src/background/security.rs @@ -6,7 +6,9 @@ use crate::{ use super::target::{self, CorrectionEligibility, FocusedTarget, TargetDetection}; mod outbound; +mod text_safety; pub(super) use outbound::api_send_authorization; +pub(super) use text_safety::request_allowed; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum TriggerKind { @@ -48,6 +50,17 @@ pub(crate) enum BlockReason { pub(crate) struct SecurityGate; impl SecurityGate { + /// Revalidate prose opt-in and text heuristics under the mutation reservation. + pub(super) fn authorize_correction_replacement( + request: &super::triggers::CorrectionRequest, + config: &AppConfig, + database: &Database, + target: &FocusedTarget, + ) -> Option { + let guard = Self::authorize_replacement(request.trigger, config, database, target)?; + request_allowed(&guard.rules().ok()?, target, request).then_some(guard) + } + /// Keep the current app rules stable through native mutation and verification. /// Missing/busy storage refuses replacement before any selection or input. pub(super) fn authorize_replacement( @@ -127,8 +140,12 @@ pub(crate) fn check_detection( }; } - // TODO: Once typed-session executable text is available here, block command - // lines, filesystem paths, URLs, and code-like text before app rules. + if !text_safety::trigger_allowed(app_rules, &target, trigger) { + return SecurityDecision::Blocked { + reason: BlockReason::AppRuleBlocked, + target: Some(target), + }; + } let matching_rule = matching_rule(app_rules, &target); if let Some(rule) = matching_rule.filter(|rule| !trigger_allowed(rule, trigger)) { let _ = rule; @@ -248,9 +265,7 @@ fn trigger_allowed(rule: &AppRule, trigger: TriggerKind) -> bool { TriggerKind::WordCount => rule.word_count_trigger_allowed, TriggerKind::Character => rule.character_trigger_allowed, TriggerKind::FinalFixBeforeReanchor => { - rule.manual_shortcut_allowed - || rule.word_count_trigger_allowed - || rule.character_trigger_allowed + rule.word_count_trigger_allowed || rule.character_trigger_allowed } TriggerKind::Undo => rule.manual_shortcut_allowed, } @@ -454,6 +469,8 @@ mod tests { character_trigger_allowed: true, local_engine_allowed: true, api_engine_allowed: true, + safety_mode: "auto".into(), + prose_context_allowed: false, } } @@ -554,6 +571,8 @@ mod tests { character_trigger_allowed: false, local_engine_allowed: false, api_engine_allowed: false, + safety_mode: "auto".into(), + prose_context_allowed: false, ..allow_rule(process_name) } } @@ -568,6 +587,8 @@ mod tests { character_trigger_allowed: false, local_engine_allowed: true, api_engine_allowed: true, + safety_mode: "auto".into(), + prose_context_allowed: false, } } diff --git a/app-core-rust/src/background/security/outbound.rs b/app-core-rust/src/background/security/outbound.rs index 3dbd06b..647c65a 100644 --- a/app-core-rust/src/background/security/outbound.rs +++ b/app-core-rust/src/background/security/outbound.rs @@ -8,7 +8,7 @@ use std::{ }, }; -use super::{check_detection, SecurityDecision, TriggerKind}; +use super::{check_detection, request_allowed, SecurityDecision}; use crate::{ background::target::{FocusedTarget, TargetDetection}, correction::SendAuthorization, @@ -21,7 +21,7 @@ pub(in crate::background) fn api_send_authorization( path: Option, mut config: AppConfig, target: FocusedTarget, - trigger: TriggerKind, + request: crate::background::triggers::CorrectionRequest, cancelled: Arc, ) -> SendAuthorization { config.correction.engine = CorrectionEngine::Api; @@ -33,13 +33,14 @@ pub(in crate::background) fn api_send_authorization( let rules = guard.rules().ok()?; if !matches!( check_detection( - trigger, + request.trigger, &config, &rules, TargetDetection::Available(target.clone()) ), SecurityDecision::Allowed { .. } - ) || cancelled.load(Ordering::Acquire) + ) || !request_allowed(&rules, &target, &request) + || cancelled.load(Ordering::Acquire) { return None; } @@ -50,6 +51,10 @@ pub(in crate::background) fn api_send_authorization( #[cfg(test)] mod tests { use super::*; + use crate::background::{ + context_capture::SelectionCapture, security::TriggerKind, session::ContextVersions, + triggers, + }; use crate::storage::{AppRule, Database}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -80,6 +85,8 @@ mod tests { character_trigger_allowed: true, local_engine_allowed: true, api_engine_allowed: true, + safety_mode: "auto".into(), + prose_context_allowed: false, } } @@ -105,11 +112,21 @@ mod tests { } fn authorize(&self, trigger: TriggerKind, cancelled: Arc) -> SendAuthorization { + let mut request = triggers::manual( + 1, + "", + "This is teh sentence.", + ContextVersions::default(), + &SelectionCapture::NoSelection, + &AppConfig::default(), + ) + .unwrap(); + request.trigger = trigger; api_send_authorization( Some(self.path.clone()), AppConfig::default(), target(), - trigger, + request, cancelled, ) } @@ -124,6 +141,76 @@ mod tests { } } + #[test] + fn prose_revocation_and_code_like_content_deny_outbound_requests() { + let fixture = Fixture::new(); + let mut target = target(); + target.process_name = "code.exe".into(); + let mut rule = allow_rule(); + rule.process_name = "code.exe".into(); + rule.prose_context_allowed = true; + fixture.database.app_rules().upsert(&rule).unwrap(); + let mut request = triggers::manual( + 1, + "", + "This is teh sentence.", + ContextVersions::default(), + &SelectionCapture::NoSelection, + &AppConfig::default(), + ) + .unwrap(); + request.selected_text = true; + assert!( + super::super::SecurityGate::authorize_correction_replacement( + &request, + &AppConfig::default(), + &fixture.database, + &target + ) + .is_some() + ); + let authorize = api_send_authorization( + Some(fixture.path.clone()), + AppConfig::default(), + target.clone(), + request.clone(), + Arc::new(AtomicBool::new(false)), + ); + assert!(authorize().is_some()); + rule.prose_context_allowed = false; + fixture.database.app_rules().upsert(&rule).unwrap(); + assert!(authorize().is_none()); + assert!( + super::super::SecurityGate::authorize_correction_replacement( + &request, + &AppConfig::default(), + &fixture.database, + &target + ) + .is_none() + ); + rule.prose_context_allowed = true; + fixture.database.app_rules().upsert(&rule).unwrap(); + request.executable_context = "This is user_name.".into(); + assert!( + super::super::SecurityGate::authorize_correction_replacement( + &request, + &AppConfig::default(), + &fixture.database, + &target + ) + .is_none() + ); + let authorize = api_send_authorization( + Some(fixture.path.clone()), + AppConfig::default(), + target, + request, + Arc::new(AtomicBool::new(false)), + ); + assert!(authorize().is_none()); + } + /// Permission is read at every send, including changes to trigger and title rules. #[test] fn revocation_blocks_existing_authorizations_for_every_correction_trigger() { @@ -210,7 +297,15 @@ mod tests { Some(missing.clone()), AppConfig::default(), target(), - TriggerKind::ManualShortcut, + triggers::manual( + 1, + "", + "This is teh sentence.", + ContextVersions::default(), + &SelectionCapture::NoSelection, + &AppConfig::default(), + ) + .unwrap(), cancelled, ); assert!(authorize().is_none()); diff --git a/app-core-rust/src/background/security/text_safety.rs b/app-core-rust/src/background/security/text_safety.rs new file mode 100644 index 0000000..3baa8b8 --- /dev/null +++ b/app-core-rust/src/background/security/text_safety.rs @@ -0,0 +1,660 @@ +//! Conservative admission for terminal/editor prose. Unrecognized syntax refuses work. + +use super::{matching_rule, TriggerKind}; +use crate::{ + background::{target::FocusedTarget, triggers::CorrectionRequest}, + storage::AppRule, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum SafetyMode { + General, + Terminal, + CodeEditor, + Unknown, +} + +pub(super) fn mode(rules: &[AppRule], target: &FocusedTarget) -> SafetyMode { + // A custom rule can classify an unknown app, but cannot downgrade a known target. + let process = target.process_name.trim().to_ascii_lowercase(); + let title = target.window_title.to_ascii_lowercase(); + let configured = matching_rule(rules, target) + .map(|rule| rule.safety_mode.as_str()) + .unwrap_or("auto"); + if process.is_empty() + || process == "unknown app" + || !matches!(configured, "auto" | "terminal" | "code_editor") + { + return SafetyMode::Unknown; + } + if matches!( + process.as_str(), + "cmd.exe" + | "powershell.exe" + | "pwsh.exe" + | "windowsterminal.exe" + | "wt.exe" + | "conhost.exe" + | "bash.exe" + | "wsl.exe" + | "mintty.exe" + | "putty.exe" + | "wezterm-gui.exe" + | "alacritty.exe" + | "hyper.exe" + ) || configured == "terminal" + || process.contains("terminal") + || process.contains("shell") + || ["terminal", "powershell", "command prompt", "shell", "ssh"] + .iter() + .any(|word| title.contains(word)) + { + return SafetyMode::Terminal; + } + if matches!( + process.as_str(), + "code.exe" + | "code-insiders.exe" + | "devenv.exe" + | "rider64.exe" + | "idea64.exe" + | "pycharm64.exe" + | "webstorm64.exe" + | "clion64.exe" + | "notepad++.exe" + | "sublime_text.exe" + | "vim.exe" + | "nvim.exe" + | "cursor.exe" + | "windsurf.exe" + | "zed.exe" + | "eclipse.exe" + | "goland64.exe" + | "rustrover64.exe" + ) || [ + "visual studio", + "intellij", + "pycharm", + "webstorm", + "sublime text", + "code editor", + ] + .iter() + .any(|word| title.contains(word)) + || title.split_whitespace().any(|part| { + [ + ".rs", ".py", ".js", ".ts", ".tsx", ".jsx", ".cs", ".cpp", ".c", ".h", ".java", + ".go", ".rb", ".sql", ".ps1", ".bat", ".cmd", ".sh", ".html", ".css", ".json", + ".yaml", ".yml", ".toml", ".xml", + ] + .iter() + .any(|extension| part.trim_matches(['\'', '"', '*']).ends_with(extension)) + }) + { + return SafetyMode::CodeEditor; + } + match configured { + "auto" => SafetyMode::General, + "terminal" => SafetyMode::Terminal, + "code_editor" => SafetyMode::CodeEditor, + _ => SafetyMode::Unknown, + } +} + +pub(super) fn trigger_allowed( + rules: &[AppRule], + target: &FocusedTarget, + trigger: TriggerKind, +) -> bool { + match mode(rules, target) { + SafetyMode::General => true, + SafetyMode::Unknown => false, + SafetyMode::Terminal | SafetyMode::CodeEditor => { + let Some(rule) = matching_rule(rules, target) else { + return false; + }; + // Manual permission never enables a final automatic fix or continuous capture. + let allowed = match trigger { + TriggerKind::Tracking | TriggerKind::FinalFixBeforeReanchor => { + rule.word_count_trigger_allowed || rule.character_trigger_allowed + } + TriggerKind::ManualShortcut | TriggerKind::Undo => rule.manual_shortcut_allowed, + TriggerKind::WordCount => rule.word_count_trigger_allowed, + TriggerKind::Character => rule.character_trigger_allowed, + }; + allowed + && (trigger == TriggerKind::Undo + || mode(rules, target) != SafetyMode::CodeEditor + || rule.prose_context_allowed) + } + } +} + +pub(in crate::background) fn request_allowed( + rules: &[AppRule], + target: &FocusedTarget, + request: &CorrectionRequest, +) -> bool { + if !trigger_allowed(rules, target, request.trigger) { + return false; + } + match mode(rules, target) { + SafetyMode::General => true, + SafetyMode::Unknown => false, + SafetyMode::Terminal | SafetyMode::CodeEditor => { + if mode(rules, target) == SafetyMode::Terminal + && (request.trigger != TriggerKind::ManualShortcut + || request.executable_context.contains(['#', '/']) + || request + .informative_context + .rsplit('\n') + .next() + .unwrap_or("") + .contains(['#', '/']) + || request + .following_context + .split('\n') + .next() + .unwrap_or("") + .contains(['#', '/'])) + { + // Shell dialect and prompt state are unknown. Neither comment markers + // nor automatic invocation prove that this is inert prose. + return false; + } + // Native caret/context APIs cannot prove a programming language's grammar. + // Even explicit trigger permission must pass a deliberate selection and prose test. + (if request.trigger == TriggerKind::ManualShortcut { + request.selected_text + } else { + request.executable_context.lines().all(|line| { + line.trim_start().starts_with('#') || line.trim_start().starts_with("//") + }) + }) && prose(&request.executable_context) + && surrounding_line_is_prose(&request.informative_context, true) + && surrounding_line_is_prose(&request.following_context, false) + } + } +} + +fn surrounding_line_is_prose(context: &str, preceding: bool) -> bool { + let line = if preceding { + context.rsplit('\n').next() + } else { + context.split('\n').next() + } + .unwrap_or("") + .trim(); + let line = strip_comment(line); + line.is_empty() || plain_words(line) +} + +fn strip_comment(line: &str) -> &str { + line.strip_prefix("//") + .or_else(|| line.strip_prefix('#')) + .unwrap_or(line) + .trim() +} + +fn prose(text: &str) -> bool { + !text.trim().is_empty() + && text.lines().all(|line| { + let line = strip_comment(line.trim()); + // A single identifier, command or fragment is uncertain. Require a sentence + // with several words and a common prose word. Unsupported languages skip. + line.split_whitespace().count() >= 3 + && plain_words(line) + && line.ends_with(['.', '!', '?']) + && (line.chars().next().is_some_and(char::is_uppercase) + || line.trim_start().starts_with("please ")) + && line.split_whitespace().next().is_some_and(|first| { + matches!( + first.to_ascii_lowercase().as_str(), + "this" + | "that" + | "these" + | "those" + | "please" + | "the" + | "a" + | "an" + | "i" + | "we" + | "you" + | "it" + | "there" + | "here" + | "our" + | "your" + | "my" + | "their" + | "because" + ) + }) + && line.split_whitespace().any(|word| { + matches!( + word.trim_matches(|c: char| !c.is_alphabetic()) + .to_ascii_lowercase() + .as_str(), + "the" + | "this" + | "that" + | "these" + | "those" + | "is" + | "are" + | "was" + | "were" + | "please" + | "should" + | "because" + | "with" + | "for" + | "and" + | "we" + | "you" + ) + }) + }) +} + +fn plain_words(text: &str) -> bool { + if !text.chars().all(|c| { + c.is_alphabetic() || c.is_whitespace() || matches!(c, '.' | ',' | '!' | '?' | '\'' | '’') + }) { + return false; + } + let words: Vec<_> = text.split_whitespace().collect(); + let Some(first) = words.first() else { + return false; + }; + // Commands can contain only letters and spaces; punctuation alone is not proof. + if matches!( + first.to_ascii_lowercase().as_str(), + "git" + | "cargo" + | "dotnet" + | "npm" + | "npx" + | "pip" + | "python" + | "node" + | "ruby" + | "go" + | "make" + | "cmake" + | "curl" + | "wget" + | "ssh" + | "sudo" + | "echo" + | "printf" + | "cd" + | "dir" + | "ls" + | "rm" + | "del" + | "copy" + | "move" + | "start" + | "set" + | "export" + | "docker" + | "kubectl" + | "winget" + | "choco" + | "get" + | "select" + | "insert" + | "update" + | "delete" + | "create" + | "drop" + | "alter" + | "return" + | "import" + | "from" + | "use" + | "let" + | "const" + | "var" + | "fn" + | "class" + | "public" + | "private" + | "def" + | "if" + | "while" + | "foreach" + ) { + return false; + } + words.iter().all(|word| { + // Leading dots can be relative paths; boundary apostrophes can be code literals. + if word.starts_with(['.', '\'', '’']) { + return false; + } + let word = word.trim_end_matches(['.', ',', '!', '?']); + if word.ends_with(['\'', '’']) { + return false; + } + if word.is_empty() { + return false; + } + // Embedded dots, punctuation or uppercase transitions identify paths/names. + if word.contains(['.', ',', '!', '?']) { + return false; + } + let mut chars = word.chars(); + chars.next(); + !chars.any(char::is_uppercase) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::background::{ + context_capture::SelectionCapture, session::ContextVersions, triggers, + }; + use crate::{ + background::{ + security::{check_detection, SecurityDecision}, + target::TargetDetection, + }, + settings::AppConfig, + }; + + fn target(process: &str) -> FocusedTarget { + FocusedTarget { + process_id: 42, + process_name: process.into(), + window_handle: 123, + window_title: "Document".into(), + focused_element_id: None, + is_elevated: false, + is_password_or_protected: false, + is_hidden_or_unavailable: false, + field_safety_known: true, + is_secure_desktop: false, + is_lock_screen: false, + is_credential_dialog: false, + } + } + + fn rule(process: &str) -> AppRule { + AppRule { + process_name: process.into(), + window_title_pattern: None, + list_behavior: "allowlist".into(), + manual_shortcut_allowed: true, + word_count_trigger_allowed: false, + character_trigger_allowed: false, + local_engine_allowed: true, + api_engine_allowed: true, + safety_mode: "auto".into(), + prose_context_allowed: false, + } + } + + fn request(text: &str) -> CorrectionRequest { + let mut request = triggers::manual( + 1, + "", + text, + ContextVersions::default(), + &SelectionCapture::NoSelection, + &AppConfig::default(), + ) + .unwrap(); + request.selected_text = true; + request + } + + #[test] + fn deleted_rules_and_manual_only_rules_keep_automatic_paths_disabled() { + for process in [ + "cmd.exe", + "pwsh.exe", + "conhost.exe", + "bash.exe", + "code.exe", + "cursor.exe", + "devenv.exe", + ] { + let target = target(process); + let mut rule = rule(process); + rule.prose_context_allowed = true; + for trigger in [ + TriggerKind::ManualShortcut, + TriggerKind::Tracking, + TriggerKind::WordCount, + TriggerKind::Character, + TriggerKind::FinalFixBeforeReanchor, + ] { + assert!(!trigger_allowed(&[], &target, trigger)); + let rules = std::slice::from_ref(&rule); + assert_eq!( + trigger_allowed(rules, &target, trigger), + trigger == TriggerKind::ManualShortcut + ); + assert_eq!( + matches!( + check_detection( + trigger, + &AppConfig::default(), + rules, + TargetDetection::Available(target.clone()) + ), + SecurityDecision::Allowed { .. } + ), + trigger == TriggerKind::ManualShortcut + ); + } + } + } + + #[test] + fn editor_requires_prose_opt_in_and_manual_selection_even_with_engine_permission() { + let target = target("code.exe"); + let mut rule = rule("code.exe"); + let mut request = request("This is teh sentence."); + assert!(!request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + rule.prose_context_allowed = true; + assert!(request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + request.selected_text = false; + assert!(!request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + request.selected_text = true; + request.informative_context = "let message = \"".into(); + assert!(!request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + request.informative_context = "code();\n// ".into(); + assert!(request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + request.executable_context = "This is user_name.".into(); + assert!(!request_allowed(&[rule], &target, &request)); + } + + #[test] + fn automatic_editor_comments_require_both_prose_and_trigger_opt_ins() { + let target = target("code.exe"); + let mut rule = rule("code.exe"); + let mut request = request("// This is teh comment."); + request.trigger = TriggerKind::Character; + request.selected_text = false; + assert!(!request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + rule.character_trigger_allowed = true; + assert!(!request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + rule.prose_context_allowed = true; + assert!(request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + for text in [ + "This is teh sentence.", + "// This is user_name.", + "// This is teh comment.\nlet value = teh;", + "// Fix typo", + "#define This is teh sentence.", + ] { + request.executable_context = text.into(); + assert!( + !request_allowed(std::slice::from_ref(&rule), &target, &request), + "admitted {text}" + ); + } + } + + #[test] + fn terminal_requires_selection_and_rejects_ambiguous_shell_comments() { + let target = target("cmd.exe"); + let rule = rule("cmd.exe"); + let mut request = request("This is teh sentence."); + assert!(request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + request.selected_text = false; + assert!(!request_allowed( + std::slice::from_ref(&rule), + &target, + &request + )); + request.selected_text = true; + for text in [ + "Git commit the changes.", + "Echo this is teh text.", + "This is --force please.", + "This is file.rs.", + "This is .env.", + "This is 'teh'.", + "# This is teh comment.", + "// This is teh comment.", + "This is teh sentence", + ] { + request.executable_context = text.into(); + assert!( + !request_allowed(std::slice::from_ref(&rule), &target, &request), + "admitted {text}" + ); + } + } + + #[test] + fn custom_profiles_and_title_heuristics_cannot_downgrade_known_apps() { + let mut target = target("custom.exe"); + let mut rule = rule("custom.exe"); + rule.safety_mode = "code_editor".into(); + assert_eq!( + mode(std::slice::from_ref(&rule), &target), + SafetyMode::CodeEditor + ); + rule.safety_mode = "terminal".into(); + assert_eq!( + mode(std::slice::from_ref(&rule), &target), + SafetyMode::Terminal + ); + let mut editor_rule = self::rule("code.exe"); + editor_rule.safety_mode = "terminal".into(); + assert_eq!( + mode(&[editor_rule], &self::target("code.exe")), + SafetyMode::Terminal + ); + rule.safety_mode = "invalid".into(); + assert!(!request_allowed( + std::slice::from_ref(&rule), + &target, + &request("This is teh text.") + )); + target.window_title = "Remote terminal".into(); + rule.safety_mode = "auto".into(); + assert_eq!(mode(&[rule], &target), SafetyMode::Terminal); + for process in ["CODE.EXE", "cmd.exe"] { + assert_ne!( + mode(&[self::rule(process)], &self::target(process)), + SafetyMode::General + ); + } + assert_eq!(mode(&[], &self::target("Unknown app")), SafetyMode::Unknown); + let mut code_document = self::target("custom.exe"); + code_document.window_title = "script.rs - Text app".into(); + assert_eq!(mode(&[], &code_document), SafetyMode::CodeEditor); + } + + #[test] + fn rejects_commands_code_paths_urls_identifiers_and_ambiguous_fragments() { + for text in [ + "git commit the changes", + "echo this is teh text", + "npm run the test", + "Get-Content the file", + "Please use --force here.", + "This is C:\\temp\\teh.txt.", + "This is /tmp/teh.", + "This is example.com.", + "This is https://example.com.", + "let value = teh;", + "This is user_name.", + "This is userName.", + "This is USER.", + "This is file.rs.", + "SELECT the name FROM users", + "teh", + "fix typo", + "Please do $(teh).", + "This is foo().", + "This is foo-bar.", + "This is `teh`.", + "This is .", + "Touch this is teh.", + ] { + assert!(!prose(text), "admitted {text}"); + } + for text in [ + "This is teh sentence.", + "// This is teh comment.", + "# This is teh comment.", + "Please fix teh spelling.", + "This isn't teh sentence.", + ] { + assert!(prose(text), "rejected {text}"); + } + } + + #[test] + fn rejects_selections_inside_command_arguments_and_code() { + assert!(!surrounding_line_is_prose("git commit -m \"", true)); + assert!(!surrounding_line_is_prose("let value = \"", true)); + assert!(!surrounding_line_is_prose("\";\nnext", false)); + assert!(surrounding_line_is_prose("previous code();\n// ", true)); + assert!(surrounding_line_is_prose("\nnext code();", false)); + } +} diff --git a/app-core-rust/src/ipc/protocol.rs b/app-core-rust/src/ipc/protocol.rs index 2b40dfd..e257c50 100644 --- a/app-core-rust/src/ipc/protocol.rs +++ b/app-core-rust/src/ipc/protocol.rs @@ -48,6 +48,10 @@ pub(crate) struct AppRuleRequest { pub(crate) character_trigger_allowed: bool, pub(crate) local_engine_allowed: bool, pub(crate) api_engine_allowed: bool, + #[serde(default = "default_safety_mode")] + pub(crate) safety_mode: String, + #[serde(default)] + pub(crate) prose_context_allowed: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -150,3 +154,7 @@ impl IpcResponse { }) } } + +fn default_safety_mode() -> String { + "auto".into() +} diff --git a/app-core-rust/src/ipc/server.rs b/app-core-rust/src/ipc/server.rs index 2592fae..8102a4e 100644 --- a/app-core-rust/src/ipc/server.rs +++ b/app-core-rust/src/ipc/server.rs @@ -117,8 +117,18 @@ fn create_pipe(pipe_path: &str) -> Result { } } -/// Serve one connected client under a pipe-I/O deadline and drain its response before disconnect. +/// Bound request/response pipe I/O separately from application work, then drain before disconnect. fn handle_pipe(pipe: HANDLE, state: &Arc>) { + handle_pipe_with(pipe, |request| { + state + .lock() + .map_err(|_| "IPC state lock poisoned".to_owned()) + .map(|mut state| state.handle(request)) + .unwrap_or_else(IpcResponse::error) + }); +} + +fn handle_pipe_with(pipe: HANDLE, handle_request: impl FnOnce(IpcRequest) -> IpcResponse) { let connected = unsafe { ConnectNamedPipe(pipe, null_mut()) }; if connected == 0 && std::io::Error::last_os_error().raw_os_error() != Some(ERROR_PIPE_CONNECTED as i32) @@ -126,25 +136,26 @@ fn handle_pipe(pipe: HANDLE, state: &Arc>) { return; } - let Ok(deadline) = super::request_deadline::RequestDeadline::start(pipe) else { - tracing::warn!("cannot enforce IPC request deadline"); - return; + let request = { + let Ok(deadline) = super::request_deadline::RequestDeadline::start(pipe) else { + tracing::warn!("cannot enforce IPC request read deadline"); + return; + }; + let request = read_request(pipe); + if deadline.expired() { + return; + } + request }; - let response = read_request(pipe) - .and_then(|request| { - if deadline.expired() { - return Err("IPC request deadline exceeded".into()); - } - state - .lock() - .map_err(|_| "IPC state lock poisoned".to_owned()) - .map(|mut state| state.handle(request)) - }) + // CancelIoEx cannot cancel a state lock or SQLite work. Do not let that work + // expire a later response before any response I/O has even started. + let response = request + .map(handle_request) .unwrap_or_else(IpcResponse::error); - - if deadline.expired() { + let Ok(_deadline) = super::request_deadline::RequestDeadline::start(pipe) else { + tracing::warn!("cannot enforce IPC response delivery deadline"); return; - } + }; if let Err(error) = write_response(pipe, &response) { tracing::warn!(%error, "IPC response delivery failed"); } @@ -217,3 +228,47 @@ pub(crate) fn pipe_path_for_process(name: &str) -> String { fn wide(value: &str) -> Vec { OsStr::new(value).encode_wide().chain(once(0)).collect() } + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + sync::mpsc, + time::{Duration, SystemTime, UNIX_EPOCH}, + }; + + #[test] + fn slow_request_handling_does_not_consume_pipe_io_deadlines() { + let pipe_path = pipe_path_for_process(&format!( + "AutoFix.SlowHandler.{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let server_path = pipe_path.clone(); + let (ready, started) = mpsc::channel(); + let worker = thread::spawn(move || { + let pipe = create_pipe(&server_path).unwrap(); + ready.send(()).unwrap(); + handle_pipe_with(pipe, |request| { + assert!(matches!(request, IpcRequest::IsBackgroundRunning)); + // Deterministic stand-in for storage work or a contended state lock. + thread::sleep(Duration::from_millis(1200)); + IpcResponse::BackgroundRunning(super::super::protocol::BackgroundRunningResponse { + running: true, + }) + }); + unsafe { + DisconnectNamedPipe(pipe); + CloseHandle(pipe); + } + }); + started.recv_timeout(Duration::from_secs(5)).unwrap(); + let response = + super::super::client::send_request(&pipe_path, &IpcRequest::IsBackgroundRunning); + worker.join().unwrap(); + assert!(matches!(response, Ok(IpcResponse::BackgroundRunning(status)) if status.running)); + } +} diff --git a/app-core-rust/src/ipc/state.rs b/app-core-rust/src/ipc/state.rs index 8abaed0..fd7f481 100644 --- a/app-core-rust/src/ipc/state.rs +++ b/app-core-rust/src/ipc/state.rs @@ -180,6 +180,12 @@ fn validate_app_rule_request(rule: &AppRuleRequest) -> Result<(), String> { if !matches!(rule.list_behavior.as_str(), "allowlist" | "blocklist") { return Err("list_behavior must be allowlist or blocklist".to_owned()); } + if !matches!( + rule.safety_mode.as_str(), + "auto" | "terminal" | "code_editor" + ) { + return Err("safety_mode must be auto, terminal or code_editor".into()); + } Ok(()) } @@ -194,6 +200,8 @@ impl From for AppRuleRequest { character_trigger_allowed: value.character_trigger_allowed, local_engine_allowed: value.local_engine_allowed, api_engine_allowed: value.api_engine_allowed, + safety_mode: value.safety_mode, + prose_context_allowed: value.prose_context_allowed, } } } @@ -211,6 +219,8 @@ impl From for AppRule { character_trigger_allowed: value.character_trigger_allowed, local_engine_allowed: value.local_engine_allowed, api_engine_allowed: value.api_engine_allowed, + safety_mode: value.safety_mode, + prose_context_allowed: value.prose_context_allowed, } } } diff --git a/app-core-rust/src/ipc/tests.rs b/app-core-rust/src/ipc/tests.rs index 99e0ada..b601044 100644 --- a/app-core-rust/src/ipc/tests.rs +++ b/app-core-rust/src/ipc/tests.rs @@ -38,21 +38,33 @@ fn dotnet_status_clients_preserve_delayed_responses_in_byte_and_message_modes() let script = format!( r#" $ErrorActionPreference = 'Stop' -$pipe = [System.IO.Pipes.NamedPipeClientStream]::new('.', '{pipe_name}', [System.IO.Pipes.PipeDirection]::InOut, [System.IO.Pipes.PipeOptions]::Asynchronous) -try {{ - $pipe.Connect(2000) - $pipe.ReadMode = [System.IO.Pipes.PipeTransmissionMode]::{read_mode} - $bytes = [System.Text.Encoding]::UTF8.GetBytes('{{"type":"get_app_status"}}') - $pipe.Write($bytes, 0, $bytes.Length) - $pipe.Flush() - Start-Sleep -Milliseconds 100 - $reader = [System.IO.StreamReader]::new($pipe) - try {{ - $read = $reader.ReadToEndAsync() - if (!$read.Wait(2000)) {{ throw 'IPC response timed out.' }} - [Console]::Write($read.GetAwaiter().GetResult()) - }} finally {{ $reader.Dispose() }} -}} finally {{ $pipe.Dispose() }} +# Compile before connecting: cold PowerShell statement/type binding must not +# consume the server's one-second pipe-I/O deadline on busy CI hosts. +Add-Type -TypeDefinition @' +using System; +using System.IO; +using System.IO.Pipes; +using System.Text; +using System.Threading; + +public static class DelayedStatusClient {{ + public static string ReadStatus() {{ + byte[] bytes = Encoding.UTF8.GetBytes("{{\"type\":\"get_app_status\"}}"); + using (var pipe = new NamedPipeClientStream(".", @"{pipe_name}", PipeDirection.InOut, PipeOptions.Asynchronous)) + using (var reader = new StreamReader(pipe)) {{ + pipe.Connect(2000); + pipe.ReadMode = PipeTransmissionMode.{read_mode}; + pipe.Write(bytes, 0, bytes.Length); + pipe.Flush(); + Thread.Sleep(100); + var read = reader.ReadToEndAsync(); + if (!read.Wait(2000)) {{ throw new TimeoutException("IPC response timed out."); }} + return read.GetAwaiter().GetResult(); + }} + }} +}} +'@ +[Console]::Write([DelayedStatusClient]::ReadStatus()) "# ); let mut child = Command::new("powershell.exe") @@ -64,13 +76,13 @@ try {{ .unwrap(); let started = Instant::now(); while child.try_wait().unwrap().is_none() { - // Allow cold PowerShell/.NET startup on busy CI hosts; the connect and - // response deadlines inside the client remain two seconds each. - if started.elapsed() > Duration::from_secs(30) { + // Allow cold PowerShell/.NET startup and C# compilation on busy CI hosts; + // the connect and response deadlines remain two seconds each. + if started.elapsed() > Duration::from_secs(120) { child.kill().unwrap(); let output = child.wait_with_output().unwrap(); panic!( - ".NET IPC client did not finish in {read_mode} mode: {}", + ".NET IPC client setup/exchange did not finish within 120 seconds in {read_mode} mode: {}", String::from_utf8_lossy(&output.stderr) ); } @@ -82,8 +94,12 @@ try {{ "{}", String::from_utf8_lossy(&output.stderr) ); - let response: IpcResponse = serde_json::from_slice(&output.stdout) - .expect(".NET tray client must receive a complete JSON response"); + let response: IpcResponse = serde_json::from_slice(&output.stdout).unwrap_or_else(|error| { + panic!( + ".NET tray client must receive a complete JSON response in {read_mode} mode: {error}; stderr: {}", + String::from_utf8_lossy(&output.stderr) + ) + }); assert!(matches!(response, IpcResponse::AppStatus(status) if status.running)); } } @@ -361,6 +377,8 @@ fn lists_upserts_and_deletes_app_rules() { character_trigger_allowed: false, local_engine_allowed: false, api_engine_allowed: false, + safety_mode: "auto".into(), + prose_context_allowed: false, }; let upserted = diff --git a/app-core-rust/src/storage/app_policy.rs b/app-core-rust/src/storage/app_policy.rs index 9455ae2..84d89e3 100644 --- a/app-core-rust/src/storage/app_policy.rs +++ b/app-core-rust/src/storage/app_policy.rs @@ -11,6 +11,14 @@ pub(crate) struct AppPolicyGuard { } impl AppPolicyGuard { + /// Admission may read committed policy during an API send. Never create, + /// migrate, reserve a writer, or wait for a contended policy database. + pub(crate) fn read_rules_nowait(path: &Path) -> Result> { + let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?; + connection.busy_timeout(Duration::ZERO)?; + AppRuleRepository::new(&connection).list() + } + /// Reserve the writer slot before reading, even in WAL mode. Never create or migrate. pub(crate) fn acquire(path: &Path) -> Result { let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE)?; diff --git a/app-core-rust/src/storage/migrations.rs b/app-core-rust/src/storage/migrations.rs index 8fdf264..819b13a 100644 --- a/app-core-rust/src/storage/migrations.rs +++ b/app-core-rust/src/storage/migrations.rs @@ -1,6 +1,6 @@ use rusqlite::{Connection, Result}; -pub(super) const CURRENT_SCHEMA_VERSION: i64 = 4; +pub(super) const CURRENT_SCHEMA_VERSION: i64 = 5; pub(super) struct DefaultAppRule { pub(super) process_name: &'static str, @@ -11,6 +11,8 @@ pub(super) struct DefaultAppRule { pub(super) character_trigger_allowed: bool, pub(super) local_engine_allowed: bool, pub(super) api_engine_allowed: bool, + pub(super) safety_mode: &'static str, + pub(super) prose_context_allowed: bool, } pub(super) const DEFAULT_APP_RULES: &[DefaultAppRule] = &[ @@ -70,6 +72,8 @@ const fn terminal_rule(process_name: &'static str) -> DefaultAppRule { character_trigger_allowed: false, local_engine_allowed: true, api_engine_allowed: true, + safety_mode: "terminal", + prose_context_allowed: false, } } @@ -78,11 +82,13 @@ const fn editor_rule(process_name: &'static str) -> DefaultAppRule { process_name, window_title_pattern: None, list_behavior: "allowlist", - manual_shortcut_allowed: true, + manual_shortcut_allowed: false, word_count_trigger_allowed: false, character_trigger_allowed: false, local_engine_allowed: true, api_engine_allowed: true, + safety_mode: "code_editor", + prose_context_allowed: false, } } @@ -96,6 +102,8 @@ const fn block_all_rule(process_name: &'static str) -> DefaultAppRule { character_trigger_allowed: false, local_engine_allowed: false, api_engine_allowed: false, + safety_mode: "auto", + prose_context_allowed: false, } } @@ -119,16 +127,23 @@ pub(super) fn migrate(connection: &Connection) -> Result<()> { migrate_to_v2(connection)?; connection.execute("insert into schema_migrations (version) values (2)", [])?; } + // Safety columns are needed by v3 seeding. Commit them with the remaining + // migrations and their version markers so a failed step cannot leave v5 partial. + let transaction = connection.unchecked_transaction()?; + migrate_app_safety(&transaction)?; if version < 3 { - seed_default_app_rules(connection)?; - connection.execute("insert into schema_migrations (version) values (3)", [])?; + seed_default_app_rules(&transaction)?; + transaction.execute("insert into schema_migrations (version) values (3)", [])?; } if version < 4 { - migrate_to_v4(connection)?; - connection.execute("insert into schema_migrations (version) values (4)", [])?; + migrate_to_v4(&transaction)?; + transaction.execute("insert into schema_migrations (version) values (4)", [])?; } - Ok(()) + if version < 5 { + transaction.execute("insert into schema_migrations (version) values (5)", [])?; + } + transaction.commit() } pub(super) fn seed_default_app_rules(connection: &Connection) -> Result<()> { @@ -137,8 +152,8 @@ pub(super) fn seed_default_app_rules(connection: &Connection) -> Result<()> { insert or ignore into app_rules ( process_name, window_title_pattern, list_behavior, manual_shortcut_allowed, word_count_trigger_allowed, character_trigger_allowed, local_engine_allowed, - api_engine_allowed - ) values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) + api_engine_allowed, safety_mode, prose_context_allowed + ) values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) ", )?; @@ -152,6 +167,8 @@ pub(super) fn seed_default_app_rules(connection: &Connection) -> Result<()> { rule.character_trigger_allowed, rule.local_engine_allowed, rule.api_engine_allowed, + rule.safety_mode, + rule.prose_context_allowed, ))?; } @@ -306,3 +323,20 @@ fn migrate_to_v4(connection: &Connection) -> Result<()> { ", ) } + +fn migrate_app_safety(connection: &Connection) -> Result<()> { + let mut statement = connection.prepare("PRAGMA table_info(app_rules)")?; + let columns = statement + .query_map([], |row| row.get::<_, String>(1))? + .collect::>>()?; + if !columns.iter().any(|column| column == "safety_mode") { + connection.execute_batch("ALTER TABLE app_rules ADD COLUMN safety_mode TEXT NOT NULL DEFAULT 'auto' CHECK (safety_mode IN ('auto', 'terminal', 'code_editor'));")?; + } + if !columns + .iter() + .any(|column| column == "prose_context_allowed") + { + connection.execute_batch("ALTER TABLE app_rules ADD COLUMN prose_context_allowed INTEGER NOT NULL DEFAULT 0 CHECK (prose_context_allowed IN (0, 1));")?; + } + Ok(()) +} diff --git a/app-core-rust/src/storage/repositories.rs b/app-core-rust/src/storage/repositories.rs index 3cd5df5..10fd2b1 100644 --- a/app-core-rust/src/storage/repositories.rs +++ b/app-core-rust/src/storage/repositories.rs @@ -20,8 +20,8 @@ impl<'a> AppRuleRepository<'a> { insert into app_rules ( process_name, window_title_pattern, list_behavior, manual_shortcut_allowed, word_count_trigger_allowed, character_trigger_allowed, local_engine_allowed, - api_engine_allowed - ) values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) + api_engine_allowed, safety_mode, prose_context_allowed + ) values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) on conflict(process_name, window_title_pattern) do update set list_behavior = excluded.list_behavior, manual_shortcut_allowed = excluded.manual_shortcut_allowed, @@ -29,6 +29,8 @@ impl<'a> AppRuleRepository<'a> { character_trigger_allowed = excluded.character_trigger_allowed, local_engine_allowed = excluded.local_engine_allowed, api_engine_allowed = excluded.api_engine_allowed, + safety_mode = excluded.safety_mode, + prose_context_allowed = excluded.prose_context_allowed, updated_at = current_timestamp ", params![ @@ -39,7 +41,9 @@ impl<'a> AppRuleRepository<'a> { rule.word_count_trigger_allowed, rule.character_trigger_allowed, rule.local_engine_allowed, - rule.api_engine_allowed + rule.api_engine_allowed, + rule.safety_mode, + rule.prose_context_allowed ], )?; Ok(()) @@ -50,7 +54,7 @@ impl<'a> AppRuleRepository<'a> { " select process_name, window_title_pattern, list_behavior, manual_shortcut_allowed, word_count_trigger_allowed, character_trigger_allowed, local_engine_allowed, - api_engine_allowed + api_engine_allowed, safety_mode, prose_context_allowed from app_rules order by process_name, window_title_pattern ", @@ -65,6 +69,8 @@ impl<'a> AppRuleRepository<'a> { character_trigger_allowed: row.get(5)?, local_engine_allowed: row.get(6)?, api_engine_allowed: row.get(7)?, + safety_mode: row.get(8)?, + prose_context_allowed: row.get(9)?, }) })?; rows.collect() @@ -90,8 +96,10 @@ impl<'a> AppRuleRepository<'a> { } pub(crate) fn reset_to_defaults(&self) -> Result<()> { - self.connection.execute("delete from app_rules", [])?; - migrations::seed_default_app_rules(self.connection) + let transaction = self.connection.unchecked_transaction()?; + transaction.execute("delete from app_rules", [])?; + migrations::seed_default_app_rules(&transaction)?; + transaction.commit() } } diff --git a/app-core-rust/src/storage/tests.rs b/app-core-rust/src/storage/tests.rs index f1b9ece..5984c2b 100644 --- a/app-core-rust/src/storage/tests.rs +++ b/app-core-rust/src/storage/tests.rs @@ -85,6 +85,8 @@ fn stores_and_lists_app_rules() { character_trigger_allowed: true, local_engine_allowed: true, api_engine_allowed: false, + safety_mode: "auto".into(), + prose_context_allowed: false, }; database.app_rules().upsert(&rule).unwrap(); @@ -104,6 +106,8 @@ fn upserts_process_only_app_rules_into_one_row() { character_trigger_allowed: false, local_engine_allowed: true, api_engine_allowed: true, + safety_mode: "auto".into(), + prose_context_allowed: false, }; database.app_rules().upsert(&rule).unwrap(); @@ -188,7 +192,7 @@ fn seeds_default_app_rules() { && !rule.word_count_trigger_allowed && !rule.character_trigger_allowed)); assert!(rules.iter().any(|rule| rule.process_name == "code.exe" - && rule.manual_shortcut_allowed + && !rule.manual_shortcut_allowed && !rule.word_count_trigger_allowed && !rule.character_trigger_allowed)); assert!(rules @@ -196,6 +200,88 @@ fn seeds_default_app_rules() { .any(|rule| rule.process_name == "Bitwarden.exe" && rule.list_behavior == "blocklist")); } +#[test] +fn safety_migration_preserves_existing_permissions_and_defaults_prose_to_off() { + let connection = Connection::open_in_memory().unwrap(); + migrations::migrate(&connection).unwrap(); + connection.execute_batch("UPDATE app_rules SET manual_shortcut_allowed=1, character_trigger_allowed=1 WHERE process_name='code.exe'; ALTER TABLE app_rules DROP COLUMN safety_mode; ALTER TABLE app_rules DROP COLUMN prose_context_allowed; DELETE FROM schema_migrations WHERE version=5;").unwrap(); + migrations::migrate(&connection).unwrap(); + migrations::migrate(&connection).unwrap(); + let repository = super::repositories::AppRuleRepository::new(&connection); + let mut rule = repository + .list() + .unwrap() + .into_iter() + .find(|rule| rule.process_name == "code.exe") + .unwrap(); + assert!(rule.manual_shortcut_allowed && rule.character_trigger_allowed); + assert_eq!(rule.safety_mode, "auto"); + assert!(!rule.prose_context_allowed); + rule.safety_mode = "code_editor".into(); + rule.prose_context_allowed = true; + repository.upsert(&rule).unwrap(); + assert!(repository.list().unwrap().contains(&rule)); +} + +#[test] +fn safety_migration_rolls_back_columns_and_retries_after_marker_failure() { + for retained_column in [None, Some("safety_mode"), Some("prose_context_allowed")] { + let connection = Connection::open_in_memory().unwrap(); + migrations::migrate(&connection).unwrap(); + connection + .execute_batch( + "UPDATE app_rules SET safety_mode='code_editor', prose_context_allowed=1, + manual_shortcut_allowed=1 WHERE process_name='code.exe'; + DELETE FROM schema_migrations WHERE version=5; + CREATE TRIGGER reject_safety_version BEFORE INSERT ON schema_migrations + WHEN NEW.version=5 BEGIN SELECT RAISE(ABORT, 'migration failure'); END;", + ) + .unwrap(); + for column in ["safety_mode", "prose_context_allowed"] { + if retained_column != Some(column) { + connection + .execute_batch(&format!("ALTER TABLE app_rules DROP COLUMN {column}")) + .unwrap(); + } + } + let original_columns = table_columns(&connection, "app_rules"); + let original_rows = row_count(&connection, "app_rules"); + + let error = migrations::migrate(&connection).unwrap_err(); + assert!(error.to_string().contains("migration failure")); + assert_eq!(table_columns(&connection, "app_rules"), original_columns); + assert_eq!(schema_version(&connection), 4); + assert_eq!(row_count(&connection, "app_rules"), original_rows); + assert!(connection.is_autocommit()); + + connection + .execute_batch("DROP TRIGGER reject_safety_version") + .unwrap(); + migrations::migrate(&connection).unwrap(); + migrations::migrate(&connection).unwrap(); + assert_eq!(schema_version(&connection), CURRENT_SCHEMA_VERSION); + let rule = super::repositories::AppRuleRepository::new(&connection) + .list() + .unwrap() + .into_iter() + .find(|rule| rule.process_name == "code.exe") + .unwrap(); + assert!(rule.manual_shortcut_allowed); + assert_eq!( + rule.safety_mode, + if retained_column == Some("safety_mode") { + "code_editor" + } else { + "auto" + } + ); + assert_eq!( + rule.prose_context_allowed, + retained_column == Some("prose_context_allowed") + ); + } +} + #[test] fn deletes_app_rules_by_process_and_title_pattern() { let database = Database::open_memory().unwrap(); @@ -208,6 +294,8 @@ fn deletes_app_rules_by_process_and_title_pattern() { character_trigger_allowed: false, local_engine_allowed: false, api_engine_allowed: false, + safety_mode: "auto".into(), + prose_context_allowed: false, }; database.app_rules().upsert(&rule).unwrap(); @@ -233,6 +321,38 @@ fn reset_app_rules_restores_seed_defaults() { .any(|rule| rule.process_name == "cmd.exe")); } +#[test] +fn failed_app_rule_reset_preserves_all_existing_rules() { + let database = Database::open_memory().unwrap(); + let mut custom = database.app_rules().list().unwrap().remove(0); + custom.process_name = "custom.exe".into(); + custom.list_behavior = "blocklist".into(); + database.app_rules().upsert(&custom).unwrap(); + let before = database.app_rules().list().unwrap(); + // Fail after cmd.exe has been inserted, so rollback must undo both the + // original deletion and an already partially seeded replacement list. + database + .connection + .execute_batch( + "create trigger reject_default before insert on app_rules + when new.process_name = 'powershell.exe' + begin select raise(abort, 'injected seed failure'); end;", + ) + .unwrap(); + + assert!(database.app_rules().reset_to_defaults().is_err()); + assert_eq!(database.app_rules().list().unwrap(), before); + + database + .connection + .execute_batch("drop trigger reject_default") + .unwrap(); + database.app_rules().reset_to_defaults().unwrap(); + let after = database.app_rules().list().unwrap(); + assert!(!after.contains(&custom)); + assert_eq!(after.len(), migrations::DEFAULT_APP_RULES.len()); +} + #[test] fn dictionary_matches_global_or_app_specific_entries() { let database = Database::open_memory().unwrap(); diff --git a/app-core-rust/src/storage/types.rs b/app-core-rust/src/storage/types.rs index 2db07a2..0450533 100644 --- a/app-core-rust/src/storage/types.rs +++ b/app-core-rust/src/storage/types.rs @@ -8,6 +8,8 @@ pub(crate) struct AppRule { pub(crate) character_trigger_allowed: bool, pub(crate) local_engine_allowed: bool, pub(crate) api_engine_allowed: bool, + pub(crate) safety_mode: String, + pub(crate) prose_context_allowed: bool, } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/shared-schema/README.md b/shared-schema/README.md index 342a846..a80f888 100644 --- a/shared-schema/README.md +++ b/shared-schema/README.md @@ -82,8 +82,10 @@ as that account share the configuration trust boundary; IPC does not authenticat individual executables. Anonymous local clients cannot connect, including for read-only access. -After one second, a watchdog requests cancellation of that client's pipe I/O, -covering request reads, response writes and response consumption. Cancellation +Request reads and response delivery each have a one-second watchdog. Application +handling, including settings-file and SQLite work, runs between those I/O phases; +it cannot expire a response before delivery starts. The delivery watchdog covers +both response writes and response consumption. Cancellation targets only that pipe and is best-effort; one second is the cancellation threshold, not a guaranteed completion bound. Native tests verify endpoint recovery with idle and nonreading clients held open. Responses drain @@ -128,3 +130,8 @@ clipboard paste and SendInput replacement are implemented for supported controls direct text APIs and UI Automation mutation remain planned. Focused native tests verify correction, recorded app-level undo, clipboard preservation and recovery, and preservation of newer typing, caret position, and text after the caret. + +App-rule safety fields (SQLite schema v5 and IPC): `safety_mode` is `auto`, +`terminal` or `code_editor`; `prose_context_allowed` defaults to false. Legacy +IPC requests default to auto/off. Both runtimes add missing columns idempotently +and preserve existing trigger and engine preferences. diff --git a/shared-schema/ipc.schema.json b/shared-schema/ipc.schema.json index af7925d..13e6cb5 100644 --- a/shared-schema/ipc.schema.json +++ b/shared-schema/ipc.schema.json @@ -20,6 +20,32 @@ "type": "string", "enum": ["idle", "active", "correcting", "blocked", "error"] }, + "appRule": { + "type": "object", + "required": ["process_name", "list_behavior", "manual_shortcut_allowed", "word_count_trigger_allowed", "character_trigger_allowed", "local_engine_allowed", "api_engine_allowed"], + "properties": { + "process_name": { "type": "string", "minLength": 1 }, + "window_title_pattern": { "type": ["string", "null"] }, + "list_behavior": { "enum": ["allowlist", "blocklist"] }, + "manual_shortcut_allowed": { "type": "boolean" }, + "word_count_trigger_allowed": { "type": "boolean" }, + "character_trigger_allowed": { "type": "boolean" }, + "local_engine_allowed": { "type": "boolean" }, + "api_engine_allowed": { "type": "boolean" }, + "safety_mode": { "enum": ["auto", "terminal", "code_editor"], "default": "auto" }, + "prose_context_allowed": { "type": "boolean", "default": false } + }, + "additionalProperties": false + }, + "deleteAppRule": { + "type": "object", + "required": ["process_name"], + "properties": { + "process_name": { "type": "string" }, + "window_title_pattern": { "type": ["string", "null"] } + }, + "additionalProperties": false + }, "appStatus": { "type": "object", "required": ["running", "correction_mode", "engine", "tray_state", "tray_state_enabled"], @@ -43,6 +69,10 @@ "get_current_engine", "reload_config", "update_setting", + "list_app_rules", + "upsert_app_rule", + "delete_app_rule", + "reset_app_rules", "open_logs", "request_undo_last_correction", "test_correction_engine_later", @@ -50,14 +80,26 @@ ] }, "payload": { - "oneOf": [{ "$ref": "#/$defs/updateSettingRequest" }] + "oneOf": [{ "$ref": "#/$defs/updateSettingRequest" }, { "$ref": "#/$defs/appRule" }, { "$ref": "#/$defs/deleteAppRule" }] } }, "allOf": [ { - "if": { "properties": { "type": { "const": "update_setting" } } }, + "if": { "properties": { "type": { "enum": ["update_setting", "upsert_app_rule", "delete_app_rule"] } } }, "then": { "required": ["payload"] }, "else": { "not": { "required": ["payload"] } } + }, + { + "if": { "properties": { "type": { "const": "upsert_app_rule" } } }, + "then": { "properties": { "payload": { "$ref": "#/$defs/appRule" } } } + }, + { + "if": { "properties": { "type": { "const": "delete_app_rule" } } }, + "then": { "properties": { "payload": { "$ref": "#/$defs/deleteAppRule" } } } + }, + { + "if": { "properties": { "type": { "const": "update_setting" } } }, + "then": { "properties": { "payload": { "$ref": "#/$defs/updateSettingRequest" } } } } ] }, @@ -85,6 +127,10 @@ "current_engine", "config_reloaded", "setting_updated", + "app_rules", + "app_rule_updated", + "app_rule_deleted", + "app_rules_reset", "logs", "undo_requested", "test_correction_engine_queued", diff --git a/ui/settings-ui-tests/AppRuleStorageTests.cs b/ui/settings-ui-tests/AppRuleStorageTests.cs index a305e5a..681f5ac 100644 --- a/ui/settings-ui-tests/AppRuleStorageTests.cs +++ b/ui/settings-ui-tests/AppRuleStorageTests.cs @@ -1,3 +1,4 @@ +using AutoFix.SettingsUi.Ipc; using AutoFix.SettingsUi.Models; using AutoFix.SettingsUi.Settings; using Microsoft.Data.Sqlite; @@ -7,6 +8,47 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class AppRuleStorageTests { + [DataTestMethod] + [DataRow("", "auto", false)] + [DataRow(",\"safety_mode\":null", "auto", false)] + [DataRow(",\"safety_mode\":\"terminal\"", "terminal", false)] + [DataRow(",\"safety_mode\":\"code_editor\",\"prose_context_allowed\":true", "code_editor", true)] + public void IpcSafetyFieldsRoundTripThroughStorage(string safetyFields, string expectedMode, bool expectedProse) + { + var json = """ + {"type":"app_rules","payload":{"rules":[{"process_name":"code.exe","list_behavior":"allowlist","manual_shortcut_allowed":true,"word_count_trigger_allowed":true,"character_trigger_allowed":false,"local_engine_allowed":true,"api_engine_allowed":false + """ + safetyFields + "}]}}"; + var envelope = System.Text.Json.JsonSerializer.Deserialize(json)!; + var response = envelope.ReadPayload("app_rules"); + Assert.IsNull(response.Error); + var rule = AppRuleStorage.FromDto(response.Value!.Rules.Single()); + AppRuleStorage.Validate(rule); + + using var fixture = TempConfigFixture.Create(); + var storage = new AppRuleStorage(Path.Combine(fixture.Root, "autofix.sqlite")); + storage.Upsert(rule); + var saved = storage.List().Single(); + Assert.AreEqual(expectedMode, saved.SafetyMode); + Assert.AreEqual(expectedProse, saved.ProseContextAllowed); + Assert.IsTrue(saved.ManualShortcutAllowed); + Assert.IsTrue(saved.WordCountTriggerAllowed); + Assert.IsFalse(saved.CharacterTriggerAllowed); + Assert.IsTrue(saved.LocalEngineAllowed); + Assert.IsFalse(saved.ApiEngineAllowed); + Assert.AreEqual(AppRuleStorage.ToDto(rule), AppRuleStorage.ToDto(saved)); + } + + [DataTestMethod] + [DataRow("")] + [DataRow("unsafe")] + public void DtoMappingPreservesInvalidSafetyModesForValidation(string safetyMode) + { + var dto = new AppRuleDto("code.exe", null, "allowlist", true, false, false, true, true, safetyMode); + var rule = AppRuleStorage.FromDto(dto); + Assert.AreEqual(safetyMode, rule.SafetyMode); + Assert.ThrowsException(() => AppRuleStorage.Validate(rule)); + } + [TestMethod] public void UpsertListAndDeleteRoundTrip() { @@ -22,12 +64,16 @@ public void UpsertListAndDeleteRoundTrip() CharacterTriggerAllowed = false, LocalEngineAllowed = false, ApiEngineAllowed = false, + SafetyMode = "code_editor", + ProseContextAllowed = true, }; storage.Upsert(rule); var listed = storage.List(); Assert.IsTrue(listed.Any(item => item.ProcessName == "word.exe" && item.WindowTitlePattern == "*admin*")); + Assert.AreEqual("code_editor", listed[0].SafetyMode); + Assert.IsTrue(listed[0].ProseContextAllowed); Assert.IsTrue(storage.Delete("word.exe", "*admin*")); } @@ -41,6 +87,8 @@ public void ResetDefaultsSeedsEditableSafetyRules() Assert.IsTrue(rules.Any(rule => rule.ProcessName == "cmd.exe" && !rule.ManualShortcutAllowed)); Assert.IsTrue(rules.Any(rule => rule.ProcessName == "code.exe" && !rule.WordCountTriggerAllowed)); + Assert.IsTrue(rules.Any(rule => rule.ProcessName == "code.exe" && !rule.ManualShortcutAllowed && !rule.ProseContextAllowed && rule.SafetyMode == "code_editor")); + Assert.IsTrue(rules.Any(rule => rule.ProcessName == "cmd.exe" && !rule.WordCountTriggerAllowed && !rule.CharacterTriggerAllowed && rule.SafetyMode == "terminal")); Assert.IsTrue(rules.Any(rule => rule.ProcessName == "Bitwarden.exe" && rule.ListBehavior == "blocklist")); } @@ -115,6 +163,14 @@ insert into app_rules ( Assert.AreEqual(1, listed.Count); Assert.AreEqual("", listed[0].WindowTitlePattern); Assert.AreEqual("blocklist", listed[0].ListBehavior); + Assert.AreEqual("auto", listed[0].SafetyMode); + Assert.IsFalse(listed[0].ProseContextAllowed); + Assert.IsFalse(listed[0].ManualShortcutAllowed); + // Repeat migration and save; existing trigger choices remain intact. + listed[0].SafetyMode = "code_editor"; + listed[0].ProseContextAllowed = true; + storage.Upsert(listed[0]); + Assert.IsTrue(storage.List().Single().ProseContextAllowed); } [TestMethod] @@ -130,6 +186,8 @@ public void DtoMappingUsesSnakeCaseContractFields() CharacterTriggerAllowed = false, LocalEngineAllowed = true, ApiEngineAllowed = false, + SafetyMode = "code_editor", + ProseContextAllowed = true, }; var dto = AppRuleStorage.ToDto(rule); @@ -137,5 +195,29 @@ public void DtoMappingUsesSnakeCaseContractFields() Assert.AreEqual("code.exe", dto.ProcessName); Assert.AreEqual("*repo*", dto.WindowTitlePattern); Assert.IsFalse(dto.ApiEngineAllowed); + var mapped = AppRuleStorage.FromDto(dto); + Assert.AreEqual("code_editor", mapped.SafetyMode); + Assert.IsTrue(mapped.ProseContextAllowed); + Assert.IsTrue(mapped.Clone().ProseContextAllowed); + var json = System.Text.Json.JsonSerializer.Serialize(dto); + StringAssert.Contains(json, "\"safety_mode\":\"code_editor\""); + StringAssert.Contains(json, "\"prose_context_allowed\":true"); + } + + [TestMethod] + public void NewRulesAndLegacyDtosKeepSafetyOptInsDisabled() + { + var rule = new AppRuleItem(); + Assert.IsFalse(rule.ManualShortcutAllowed); + Assert.IsFalse(rule.WordCountTriggerAllowed); + Assert.IsFalse(rule.CharacterTriggerAllowed); + Assert.IsFalse(rule.ProseContextAllowed); + var dto = System.Text.Json.JsonSerializer.Deserialize( + """{"process_name":"code.exe","list_behavior":"allowlist","manual_shortcut_allowed":true,"word_count_trigger_allowed":false,"character_trigger_allowed":false,"local_engine_allowed":true,"api_engine_allowed":true}""")!; + Assert.AreEqual("auto", dto.SafetyMode); + Assert.IsFalse(dto.ProseContextAllowed); + rule.SafetyMode = "unsafe"; + rule.ProcessName = "custom.exe"; + Assert.ThrowsException(() => AppRuleStorage.Validate(rule)); } } diff --git a/ui/settings-ui/Ipc/IpcProtocol.cs b/ui/settings-ui/Ipc/IpcProtocol.cs index d4ef9cf..b21f396 100644 --- a/ui/settings-ui/Ipc/IpcProtocol.cs +++ b/ui/settings-ui/Ipc/IpcProtocol.cs @@ -31,7 +31,9 @@ public sealed record AppRuleDto( [property: JsonPropertyName("word_count_trigger_allowed")] bool WordCountTriggerAllowed, [property: JsonPropertyName("character_trigger_allowed")] bool CharacterTriggerAllowed, [property: JsonPropertyName("local_engine_allowed")] bool LocalEngineAllowed, - [property: JsonPropertyName("api_engine_allowed")] bool ApiEngineAllowed); + [property: JsonPropertyName("api_engine_allowed")] bool ApiEngineAllowed, + [property: JsonPropertyName("safety_mode")] string? SafetyMode = "auto", + [property: JsonPropertyName("prose_context_allowed")] bool ProseContextAllowed = false); public sealed record AppRulesResponse( [property: JsonPropertyName("rules")] IReadOnlyList Rules); diff --git a/ui/settings-ui/MainWindow.xaml b/ui/settings-ui/MainWindow.xaml index 8a826b0..71653de 100644 --- a/ui/settings-ui/MainWindow.xaml +++ b/ui/settings-ui/MainWindow.xaml @@ -329,6 +329,7 @@ Margin="0,0,0,10" Visibility="{Binding SelectedSection.HasAppRules, Converter={StaticResource BoolToVisibility}}"> + + + + + auto + terminal + code_editor + + + + diff --git a/ui/settings-ui/Models/AppRuleItem.cs b/ui/settings-ui/Models/AppRuleItem.cs index e9f11b9..4785354 100644 --- a/ui/settings-ui/Models/AppRuleItem.cs +++ b/ui/settings-ui/Models/AppRuleItem.cs @@ -7,11 +7,13 @@ public sealed class AppRuleItem : ObservableObject private string processName = ""; private string windowTitlePattern = ""; private string listBehavior = "allowlist"; - private bool manualShortcutAllowed = true; - private bool wordCountTriggerAllowed = true; - private bool characterTriggerAllowed = true; + private bool manualShortcutAllowed; + private bool wordCountTriggerAllowed; + private bool characterTriggerAllowed; private bool localEngineAllowed = true; private bool apiEngineAllowed = true; + private string safetyMode = "auto"; + private bool proseContextAllowed; public string ProcessName { @@ -61,6 +63,18 @@ public bool ApiEngineAllowed set => SetProperty(ref apiEngineAllowed, value); } + public string SafetyMode + { + get => safetyMode; + set => SetProperty(ref safetyMode, value); + } + + public bool ProseContextAllowed + { + get => proseContextAllowed; + set => SetProperty(ref proseContextAllowed, value); + } + public AppRuleItem Clone() => new() { ProcessName = ProcessName, @@ -71,5 +85,7 @@ public bool ApiEngineAllowed CharacterTriggerAllowed = CharacterTriggerAllowed, LocalEngineAllowed = LocalEngineAllowed, ApiEngineAllowed = ApiEngineAllowed, + SafetyMode = SafetyMode, + ProseContextAllowed = ProseContextAllowed, }; } diff --git a/ui/settings-ui/README.md b/ui/settings-ui/README.md index c869f03..7ab47ba 100644 --- a/ui/settings-ui/README.md +++ b/ui/settings-ui/README.md @@ -2,6 +2,15 @@ WPF settings application for AutoFix. +**App Rules** offers **Safety** (`auto`, `terminal`, `code_editor`) and +**Editor prose**. New rules and terminal/editor defaults disable all triggers. +Enable Manual and, for editors, Editor prose to admit selected prose. Known app +detection remains active under auto. Heuristics reject commands, flags, paths, +URLs, code, identifiers and uncertain text. Automatic editor line comments also +need Words/Chars permission; terminal automatic requests skip. Migration preserves +existing choices and defaults Editor prose to off. Native selected-text replacement +still requires proof of the live caret end. + **Shortcuts** configures correction and app-level undo hotkeys (undo defaults to Ctrl+Alt+Z), plus undo history capacity (default 10, range 1–1000). Capacity saves as `context.undo_history_size`; legacy settings keep the default. History itself diff --git a/ui/settings-ui/Settings/AppRuleStorage.cs b/ui/settings-ui/Settings/AppRuleStorage.cs index 9869513..06014df 100644 --- a/ui/settings-ui/Settings/AppRuleStorage.cs +++ b/ui/settings-ui/Settings/AppRuleStorage.cs @@ -26,7 +26,7 @@ public IReadOnlyList List() """ select process_name, window_title_pattern, list_behavior, manual_shortcut_allowed, word_count_trigger_allowed, character_trigger_allowed, local_engine_allowed, - api_engine_allowed + api_engine_allowed, safety_mode, prose_context_allowed from app_rules order by process_name, window_title_pattern """; @@ -45,6 +45,8 @@ from app_rules CharacterTriggerAllowed = reader.GetBoolean(5), LocalEngineAllowed = reader.GetBoolean(6), ApiEngineAllowed = reader.GetBoolean(7), + SafetyMode = reader.GetString(8), + ProseContextAllowed = reader.GetBoolean(9), }); } @@ -61,8 +63,8 @@ public void Upsert(AppRuleItem rule) insert into app_rules ( process_name, window_title_pattern, list_behavior, manual_shortcut_allowed, word_count_trigger_allowed, character_trigger_allowed, local_engine_allowed, - api_engine_allowed - ) values ($process_name, $window_title_pattern, $list_behavior, $manual, $word_count, $character, $local, $api) + api_engine_allowed, safety_mode, prose_context_allowed + ) values ($process_name, $window_title_pattern, $list_behavior, $manual, $word_count, $character, $local, $api, $safety, $prose) on conflict(process_name, window_title_pattern) do update set list_behavior = excluded.list_behavior, manual_shortcut_allowed = excluded.manual_shortcut_allowed, @@ -70,6 +72,8 @@ insert into app_rules ( character_trigger_allowed = excluded.character_trigger_allowed, local_engine_allowed = excluded.local_engine_allowed, api_engine_allowed = excluded.api_engine_allowed, + safety_mode = excluded.safety_mode, + prose_context_allowed = excluded.prose_context_allowed, updated_at = current_timestamp """; BindRule(command, rule); @@ -111,8 +115,8 @@ public IReadOnlyList ResetDefaults() insert into app_rules ( process_name, window_title_pattern, list_behavior, manual_shortcut_allowed, word_count_trigger_allowed, character_trigger_allowed, local_engine_allowed, - api_engine_allowed - ) values ($process_name, $window_title_pattern, $list_behavior, $manual, $word_count, $character, $local, $api) + api_engine_allowed, safety_mode, prose_context_allowed + ) values ($process_name, $window_title_pattern, $list_behavior, $manual, $word_count, $character, $local, $api, $safety, $prose) """; BindRule(insert, rule); insert.ExecuteNonQuery(); @@ -130,7 +134,9 @@ insert into app_rules ( rule.WordCountTriggerAllowed, rule.CharacterTriggerAllowed, rule.LocalEngineAllowed, - rule.ApiEngineAllowed); + rule.ApiEngineAllowed, + rule.SafetyMode, + rule.ProseContextAllowed); public static AppRuleItem FromDto(AppRuleDto rule) => new() { @@ -142,6 +148,8 @@ insert into app_rules ( CharacterTriggerAllowed = rule.CharacterTriggerAllowed, LocalEngineAllowed = rule.LocalEngineAllowed, ApiEngineAllowed = rule.ApiEngineAllowed, + SafetyMode = rule.SafetyMode ?? "auto", + ProseContextAllowed = rule.ProseContextAllowed, }; public static void Validate(AppRuleItem rule) @@ -151,6 +159,11 @@ public static void Validate(AppRuleItem rule) throw new ArgumentException("process_name must not be empty"); } + if (rule.SafetyMode is not ("auto" or "terminal" or "code_editor")) + { + throw new ArgumentException("safety_mode must be auto, terminal or code_editor"); + } + if (rule.ListBehavior is not ("allowlist" or "blocklist")) { throw new ArgumentException("list_behavior must be allowlist or blocklist"); @@ -186,6 +199,7 @@ api_engine_allowed integer not null check (api_engine_allowed in (0, 1)), ); """; command.ExecuteNonQuery(); + MigrateSafetyColumns(connection); NormalizeProcessOnlyRules(connection); return connection; } @@ -200,6 +214,30 @@ private static void BindRule(SqliteCommand command, AppRuleItem rule) command.Parameters.AddWithValue("$character", rule.CharacterTriggerAllowed); command.Parameters.AddWithValue("$local", rule.LocalEngineAllowed); command.Parameters.AddWithValue("$api", rule.ApiEngineAllowed); + command.Parameters.AddWithValue("$safety", rule.SafetyMode); + command.Parameters.AddWithValue("$prose", rule.ProseContextAllowed); + } + + private static void MigrateSafetyColumns(SqliteConnection connection) + { + using var info = connection.CreateCommand(); + info.CommandText = "pragma table_info(app_rules)"; + var columns = new HashSet(); + using (var reader = info.ExecuteReader()) + { + while (reader.Read()) columns.Add(reader.GetString(1)); + } + using var migration = connection.CreateCommand(); + if (!columns.Contains("safety_mode")) + { + migration.CommandText = "alter table app_rules add column safety_mode text not null default 'auto' check (safety_mode in ('auto', 'terminal', 'code_editor'))"; + migration.ExecuteNonQuery(); + } + if (!columns.Contains("prose_context_allowed")) + { + migration.CommandText = "alter table app_rules add column prose_context_allowed integer not null default 0 check (prose_context_allowed in (0, 1))"; + migration.ExecuteNonQuery(); + } } private static string EmptyWhenBlank(string? value) => @@ -294,17 +332,19 @@ private static IReadOnlyList DefaultRules() => CharacterTriggerAllowed = false, LocalEngineAllowed = true, ApiEngineAllowed = true, + SafetyMode = "terminal", }; private static AppRuleItem Editor(string processName) => new() { ProcessName = processName, ListBehavior = "allowlist", - ManualShortcutAllowed = true, + ManualShortcutAllowed = false, WordCountTriggerAllowed = false, CharacterTriggerAllowed = false, LocalEngineAllowed = true, ApiEngineAllowed = true, + SafetyMode = "code_editor", }; private static AppRuleItem Block(string processName) => new()