use super::{
PermissionAdmissionDecision, PermissionAdmissionReviewSource, PermissionRequest,
PermissionedAction, request_json,
};
use std::{
collections::VecDeque,
fmt,
sync::{Arc, RwLock},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ReviewGuidanceId(u64);
impl ReviewGuidanceId {
#[must_use]
pub const fn as_u64(self) -> u64 {
self.0
}
#[must_use]
pub const fn from_u64(value: u64) -> Self {
Self(value)
}
}
impl fmt::Display for ReviewGuidanceId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "note-{}", self.0)
}
}
pub(crate) const MAX_RECORDED_PERMISSION_DECISIONS: usize = 16;
pub const MAX_SESSION_REVIEW_GUIDANCE: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RecordedPermissionDecision {
source: PermissionAdmissionReviewSource,
approved: bool,
tool_name: String,
command: String,
requested_json: String,
user_note: Option<String>,
}
impl RecordedPermissionDecision {
pub(crate) fn from_request_and_decision(
request: &PermissionRequest,
decision: &PermissionAdmissionDecision,
) -> Self {
Self {
source: decision.review().source(),
approved: decision.is_approved(),
tool_name: request.tool_name().as_str().to_owned(),
command: action_command_summary(request.action()),
requested_json: request_json::requested_capabilities_json(request.requested())
.to_string(),
user_note: decision
.user_note()
.map(str::trim)
.filter(|note| !note.is_empty())
.map(str::to_owned),
}
}
pub(crate) fn render_json_line(&self) -> String {
let mut entry = serde_json::json!({
"source": self.source.as_str(),
"decision": if self.approved { "approved" } else { "denied" },
"tool": sanitize_recorded_field(&self.tool_name),
"command": sanitize_recorded_field(&self.command),
"requested": sanitize_recorded_field(&self.requested_json),
});
if let Some(note) = self.user_note.as_deref() {
entry["user_note"] = serde_json::json!(sanitize_recorded_field(note));
}
entry.to_string()
}
}
fn action_command_summary(action: &PermissionedAction) -> String {
match action {
PermissionedAction::Process(intent) => crate::shell_command_for_argv(intent.argv()),
PermissionedAction::FileRead { path } => format!("read_file {path}"),
PermissionedAction::FileWrite { paths } => format!("apply_patch {}", paths.join(", ")),
PermissionedAction::NetworkUrl { tool, url, .. } => format!("{tool} {url}"),
}
}
pub(crate) fn sanitize_recorded_field(text: &str) -> String {
const MAX_LEN: usize = 320;
let flattened: String = text
.chars()
.map(|ch| {
if matches!(
ch,
'\r' | '\n' | '\u{0085}' | '\u{000B}' | '\u{000C}' | '\u{2028}' | '\u{2029}'
) {
' '
} else {
ch
}
})
.collect();
crate::compaction::bounded_excerpt(&flattened, MAX_LEN)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReviewGuidanceDecision {
Allow,
Deny,
}
impl ReviewGuidanceDecision {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Allow => "allow",
Self::Deny => "deny",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewGuidanceEntry {
id: ReviewGuidanceId,
decision: ReviewGuidanceDecision,
user_note: String,
tool_name: String,
command: String,
requested_json: String,
}
impl ReviewGuidanceEntry {
#[must_use]
pub fn new(
id: ReviewGuidanceId,
decision: ReviewGuidanceDecision,
user_note: impl Into<String>,
tool_name: impl Into<String>,
command: impl Into<String>,
requested_json: impl Into<String>,
) -> Self {
Self {
id,
decision,
user_note: user_note.into().trim().to_owned(),
tool_name: tool_name.into(),
command: command.into(),
requested_json: requested_json.into(),
}
}
pub(crate) fn from_request_and_decision(
id: ReviewGuidanceId,
request: &PermissionRequest,
decision: &PermissionAdmissionDecision,
user_note: &str,
) -> Self {
Self {
id,
decision: if decision.is_approved() {
ReviewGuidanceDecision::Allow
} else {
ReviewGuidanceDecision::Deny
},
user_note: user_note.trim().to_owned(),
tool_name: request.tool_name().as_str().to_owned(),
command: action_command_summary(request.action()),
requested_json: request_json::requested_capabilities_json(request.requested())
.to_string(),
}
}
#[must_use]
pub const fn id(&self) -> ReviewGuidanceId {
self.id
}
#[must_use]
pub const fn decision(&self) -> ReviewGuidanceDecision {
self.decision
}
#[must_use]
pub fn user_note(&self) -> &str {
&self.user_note
}
#[must_use]
pub fn tool_name(&self) -> &str {
&self.tool_name
}
#[must_use]
pub fn command(&self) -> &str {
&self.command
}
pub(crate) fn render_json_line(&self) -> String {
serde_json::json!({
"decision": self.decision.as_str(),
"user_note": sanitize_recorded_field(&self.user_note),
"tool": sanitize_recorded_field(&self.tool_name),
"command": sanitize_recorded_field(&self.command),
"requested": sanitize_recorded_field(&self.requested_json),
})
.to_string()
}
}
#[derive(Debug)]
struct SessionReviewGuidanceState {
next_id: u64,
entries: VecDeque<ReviewGuidanceEntry>,
}
impl Default for SessionReviewGuidanceState {
fn default() -> Self {
Self {
next_id: 1,
entries: VecDeque::new(),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct SessionReviewGuidance {
state: Arc<RwLock<SessionReviewGuidanceState>>,
}
impl SessionReviewGuidance {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub(crate) fn record_decision(
&self,
request: &PermissionRequest,
decision: &PermissionAdmissionDecision,
) {
if decision.review().source() != PermissionAdmissionReviewSource::Host {
return;
}
let Some(note) = decision
.user_note()
.map(str::trim)
.filter(|n| !n.is_empty())
else {
return;
};
let mut state = self
.state
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let id = ReviewGuidanceId(state.next_id);
state.next_id = state.next_id.saturating_add(1);
let entry = ReviewGuidanceEntry::from_request_and_decision(id, request, decision, note);
if state.entries.len() >= MAX_SESSION_REVIEW_GUIDANCE {
state.entries.pop_front();
}
state.entries.push_back(entry);
}
pub fn revoke(&self, id: ReviewGuidanceId) -> bool {
let mut state = self
.state
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(index) = state.entries.iter().position(|entry| entry.id == id) {
state.entries.remove(index);
true
} else {
false
}
}
#[must_use]
pub fn snapshot(&self) -> Vec<ReviewGuidanceEntry> {
let state = self
.state
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner());
state.entries.iter().cloned().collect()
}
#[must_use]
pub fn len(&self) -> usize {
let state = self
.state
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner());
state.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[derive(Debug, Clone, Default)]
pub struct WorkspaceReviewNotes {
notes: Arc<RwLock<Vec<String>>>,
}
impl WorkspaceReviewNotes {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn from_notes(notes: Vec<String>) -> Self {
let normalized = normalize_workspace_review_notes(notes);
Self {
notes: Arc::new(RwLock::new(normalized)),
}
}
pub fn replace(&self, notes: Vec<String>) {
let normalized = normalize_workspace_review_notes(notes);
*self
.notes
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = normalized;
}
#[must_use]
pub fn snapshot(&self) -> Vec<String> {
self.notes
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone()
}
}
fn normalize_workspace_review_notes(notes: Vec<String>) -> Vec<String> {
let mut out = Vec::new();
for note in notes {
let trimmed = note.trim();
if trimmed.is_empty() {
continue;
}
let owned = trimmed.to_owned();
if !out.contains(&owned) {
out.push(owned);
}
}
out
}
pub(crate) fn render_workspace_review_note_json_line(note: &str) -> String {
serde_json::json!({
"scope": "workspace",
"user_note": sanitize_recorded_field(note),
})
.to_string()
}