forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafety.rs
More file actions
702 lines (616 loc) · 22.7 KB
/
safety.rs
File metadata and controls
702 lines (616 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
use crate::notifications::NotificationDispatcher;
use crate::storage;
// ---------------------------------------------------------------------------
// Action classification
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionTier {
AutoAllowed,
RequiresPermission,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Urgency {
Low,
Normal,
High,
}
// ---------------------------------------------------------------------------
// Permission request / result / decision
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionRequest {
pub id: String,
pub action: String,
pub description: String,
pub rationale: String,
pub urgency: Urgency,
pub wait: bool,
pub created_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub context: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PermissionResult {
Approved { message: Option<String> },
Denied { reason: Option<String> },
Queued { request_id: String },
Timeout,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Decision {
pub request_id: String,
pub approved: bool,
pub decided_at: DateTime<Utc>,
pub decided_via: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
// ---------------------------------------------------------------------------
// Action log / transcript
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionLog {
pub action_type: String,
pub description: String,
pub tier: ActionTier,
#[serde(skip_serializing_if = "Option::is_none")]
pub details: Option<serde_json::Value>,
pub timestamp: DateTime<Utc>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TranscriptStatus {
Complete,
Interrupted,
Incomplete,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AmbientTranscript {
pub session_id: String,
pub started_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ended_at: Option<DateTime<Utc>>,
pub status: TranscriptStatus,
pub provider: String,
pub model: String,
pub actions: Vec<ActionLog>,
pub pending_permissions: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
pub compactions: u32,
pub memories_modified: u32,
/// Full conversation transcript (markdown) for email notifications
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation: Option<String>,
}
// ---------------------------------------------------------------------------
// Tier-1 (auto-allowed) action names
// ---------------------------------------------------------------------------
const AUTO_ALLOWED: &[&str] = &[
"read",
"glob",
"grep",
"ls",
"memory",
"todo",
"todowrite",
"todoread",
"conversation_search",
"session_search",
"codesearch",
];
// ---------------------------------------------------------------------------
// SafetySystem
// ---------------------------------------------------------------------------
pub struct SafetySystem {
queue: Mutex<Vec<PermissionRequest>>,
history: Mutex<Vec<Decision>>,
actions: Mutex<Vec<ActionLog>>,
notifier: NotificationDispatcher,
}
impl SafetySystem {
/// Create a new SafetySystem, loading persisted queue/history from disk.
pub fn new() -> Self {
let queue: Vec<PermissionRequest> = queue_path()
.ok()
.and_then(|p| storage::read_json(&p).ok())
.unwrap_or_default();
let history: Vec<Decision> = history_path()
.ok()
.and_then(|p| storage::read_json(&p).ok())
.unwrap_or_default();
SafetySystem {
queue: Mutex::new(queue),
history: Mutex::new(history),
actions: Mutex::new(Vec::new()),
notifier: NotificationDispatcher::new(),
}
}
/// Classify an action name into a tier.
pub fn classify(&self, action: &str) -> ActionTier {
let lower = action.to_lowercase();
if AUTO_ALLOWED.iter().any(|&a| a == lower) {
ActionTier::AutoAllowed
} else {
ActionTier::RequiresPermission
}
}
/// Submit a permission request. Returns `Queued` with the request id.
pub fn request_permission(&self, request: PermissionRequest) -> PermissionResult {
let request_id = request.id.clone();
let action = request.action.clone();
let description = request.description.clone();
if let Ok(mut q) = self.queue.lock() {
q.push(request);
let _ = persist_queue(&q);
}
// Send high-priority notification for permission request
self.notifier
.dispatch_permission_request(&action, &description, &request_id);
PermissionResult::Queued { request_id }
}
/// Expire pending permission requests that can no longer be serviced
/// because their originating session is no longer active.
pub fn expire_dead_session_requests(&self, via: &str) -> Result<Vec<String>> {
let mut expired: Vec<(String, String)> = Vec::new();
if let Ok(mut q) = self.queue.lock() {
let mut retained: Vec<PermissionRequest> = Vec::with_capacity(q.len());
for req in q.drain(..) {
if let Some(reason) = stale_request_reason(&req) {
expired.push((req.id.clone(), reason));
} else {
retained.push(req);
}
}
*q = retained;
let _ = persist_queue(&q);
}
if expired.is_empty() {
return Ok(Vec::new());
}
if let Ok(mut h) = self.history.lock() {
for (request_id, reason) in &expired {
h.push(Decision {
request_id: request_id.clone(),
approved: false,
decided_at: Utc::now(),
decided_via: via.to_string(),
message: Some(format!(
"Expired automatically: {}. Original agent is no longer active.",
reason
)),
});
}
let _ = persist_history(&h);
}
Ok(expired.into_iter().map(|(id, _)| id).collect())
}
/// Record a user decision (approve / deny) for a pending request.
pub fn record_decision(
&self,
request_id: &str,
approved: bool,
via: &str,
message: Option<String>,
) -> Result<()> {
// Remove from queue
if let Ok(mut q) = self.queue.lock() {
q.retain(|r| r.id != request_id);
let _ = persist_queue(&q);
}
let decision = Decision {
request_id: request_id.to_string(),
approved,
decided_at: Utc::now(),
decided_via: via.to_string(),
message,
};
if let Ok(mut h) = self.history.lock() {
h.push(decision);
let _ = persist_history(&h);
}
Ok(())
}
/// Return all pending permission requests.
pub fn pending_requests(&self) -> Vec<PermissionRequest> {
self.queue.lock().map(|q| q.clone()).unwrap_or_default()
}
/// Append an action to the in-memory log.
pub fn log_action(&self, log: ActionLog) {
if let Ok(mut actions) = self.actions.lock() {
actions.push(log);
}
}
/// Generate a human-readable summary of logged actions.
pub fn generate_summary(&self) -> String {
let actions = self.actions.lock().map(|a| a.clone()).unwrap_or_default();
let pending = self.pending_requests();
let mut lines: Vec<String> = Vec::new();
if actions.is_empty() && pending.is_empty() {
return "No actions recorded.".to_string();
}
// Separate auto vs permission-required
let auto: Vec<&ActionLog> = actions
.iter()
.filter(|a| a.tier == ActionTier::AutoAllowed)
.collect();
let perm: Vec<&ActionLog> = actions
.iter()
.filter(|a| a.tier == ActionTier::RequiresPermission)
.collect();
if !auto.is_empty() {
lines.push("Done (auto-allowed):".to_string());
for a in &auto {
lines.push(format!("- {} — {}", a.action_type, a.description));
}
}
if !perm.is_empty() {
lines.push(String::new());
lines.push("Done (with permission):".to_string());
for a in &perm {
lines.push(format!("- {} — {}", a.action_type, a.description));
}
}
if !pending.is_empty() {
lines.push(String::new());
lines.push("Needs your review:".to_string());
for r in &pending {
lines.push(format!(
"- [{:?}] {} — {}",
r.urgency, r.action, r.description
));
}
}
lines.join("\n")
}
/// Persist a transcript to ~/.jcode/ambient/transcripts/{timestamp}.json
pub fn save_transcript(&self, transcript: &AmbientTranscript) -> Result<()> {
let dir = storage::jcode_dir()?.join("ambient").join("transcripts");
storage::ensure_dir(&dir)?;
let filename = transcript.started_at.format("%Y-%m-%d-%H%M%S").to_string();
let path = dir.join(format!("{}.json", filename));
storage::write_json(&path, transcript)
}
}
impl Default for SafetySystem {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// Persistence helpers
// ---------------------------------------------------------------------------
fn queue_path() -> Result<std::path::PathBuf> {
Ok(storage::jcode_dir()?.join("safety").join("queue.json"))
}
fn history_path() -> Result<std::path::PathBuf> {
Ok(storage::jcode_dir()?.join("safety").join("history.json"))
}
fn persist_queue(queue: &[PermissionRequest]) -> Result<()> {
let path = queue_path()?;
storage::write_json(&path, queue)
}
fn persist_history(history: &[Decision]) -> Result<()> {
let path = history_path()?;
storage::write_json(&path, history)
}
// ---------------------------------------------------------------------------
// File-based permission decision (for IMAP poller / external callers)
// ---------------------------------------------------------------------------
/// Record a permission decision by directly manipulating the queue/history JSON files.
/// Used by the IMAP reply poller which doesn't have access to the live SafetySystem instance.
pub fn record_permission_via_file(
request_id: &str,
approved: bool,
via: &str,
message: Option<String>,
) -> Result<()> {
let qp = queue_path()?;
if let Some(parent) = qp.parent() {
storage::ensure_dir(parent)?;
}
let mut queue: Vec<PermissionRequest> = if qp.exists() {
storage::read_json(&qp).unwrap_or_default()
} else {
Vec::new()
};
queue.retain(|r| r.id != request_id);
persist_queue(&queue)?;
let hp = history_path()?;
if let Some(parent) = hp.parent() {
storage::ensure_dir(parent)?;
}
let mut history: Vec<Decision> = if hp.exists() {
storage::read_json(&hp).unwrap_or_default()
} else {
Vec::new()
};
history.push(Decision {
request_id: request_id.to_string(),
approved,
decided_at: Utc::now(),
decided_via: via.to_string(),
message,
});
persist_history(&history)?;
Ok(())
}
/// Expire stale permission requests directly via queue/history files.
/// Used by processes that don't hold the live SafetySystem instance.
pub fn expire_stale_permissions_via_file(via: &str) -> Result<Vec<String>> {
let qp = queue_path()?;
if let Some(parent) = qp.parent() {
storage::ensure_dir(parent)?;
}
let mut queue: Vec<PermissionRequest> = if qp.exists() {
storage::read_json(&qp).unwrap_or_default()
} else {
Vec::new()
};
let mut expired: Vec<(String, String)> = Vec::new();
queue.retain(|req| {
if let Some(reason) = stale_request_reason(req) {
expired.push((req.id.clone(), reason));
false
} else {
true
}
});
persist_queue(&queue)?;
if expired.is_empty() {
return Ok(Vec::new());
}
let hp = history_path()?;
if let Some(parent) = hp.parent() {
storage::ensure_dir(parent)?;
}
let mut history: Vec<Decision> = if hp.exists() {
storage::read_json(&hp).unwrap_or_default()
} else {
Vec::new()
};
for (request_id, reason) in &expired {
history.push(Decision {
request_id: request_id.clone(),
approved: false,
decided_at: Utc::now(),
decided_via: via.to_string(),
message: Some(format!(
"Expired automatically: {}. Original agent is no longer active.",
reason
)),
});
}
persist_history(&history)?;
Ok(expired.into_iter().map(|(id, _)| id).collect())
}
fn stale_request_reason(request: &PermissionRequest) -> Option<String> {
let session_id = request_session_id(request)?;
let mut session = match crate::session::Session::load(&session_id) {
Ok(s) => s,
Err(_) => return Some(format!("owner session '{}' was not found", session_id)),
};
// Refresh crash status based on PID if needed.
if session.detect_crash() {
let _ = session.save();
}
if session.status == crate::session::SessionStatus::Active {
None
} else {
Some(format!(
"owner session '{}' is {}",
session_id,
session.status.display()
))
}
}
fn request_session_id(request: &PermissionRequest) -> Option<String> {
let context = request.context.as_ref()?;
context
.get("session_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.or_else(|| {
context
.get("requester")
.and_then(|r| r.get("session_id"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
})
}
// ---------------------------------------------------------------------------
// ID generation helper
// ---------------------------------------------------------------------------
/// Generate a unique permission request id: `req_{timestamp}_{random}`
pub fn new_request_id() -> String {
crate::id::new_id("req")
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
fn with_temp_home<F, T>(f: F) -> T
where
F: FnOnce() -> T,
{
let _guard = crate::storage::lock_test_env();
let prev_home = std::env::var_os("JCODE_HOME");
let temp = tempfile::TempDir::new().expect("create temp dir");
crate::env::set_var("JCODE_HOME", temp.path());
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
match prev_home {
Some(value) => crate::env::set_var("JCODE_HOME", value),
None => crate::env::remove_var("JCODE_HOME"),
}
result.unwrap_or_else(|payload| std::panic::resume_unwind(payload))
}
#[test]
fn test_classify_auto_allowed() {
with_temp_home(|| {
let sys = SafetySystem::new();
assert_eq!(sys.classify("read"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("glob"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("grep"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("ls"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("memory"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("todo"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("todowrite"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("todoread"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("conversation_search"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("session_search"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("codesearch"), ActionTier::AutoAllowed);
});
}
#[test]
fn test_classify_requires_permission() {
with_temp_home(|| {
let sys = SafetySystem::new();
assert_eq!(sys.classify("bash"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("write"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("edit"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("multiedit"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("patch"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("apply_patch"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("communicate"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("open"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("launch"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("webfetch"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("websearch"), ActionTier::RequiresPermission);
assert_eq!(sys.classify("unknown_tool"), ActionTier::RequiresPermission);
});
}
#[test]
fn test_classify_case_insensitive() {
with_temp_home(|| {
let sys = SafetySystem::new();
assert_eq!(sys.classify("Read"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("GLOB"), ActionTier::AutoAllowed);
assert_eq!(sys.classify("Bash"), ActionTier::RequiresPermission);
});
}
#[test]
fn test_request_permission_returns_queued() {
with_temp_home(|| {
let sys = SafetySystem::new();
let baseline = sys.pending_requests().len();
let req = PermissionRequest {
id: "req_test_1".to_string(),
action: "create_pull_request".to_string(),
description: "Create PR for test fixes".to_string(),
rationale: "Found failing tests".to_string(),
urgency: Urgency::Normal,
wait: false,
created_at: Utc::now(),
context: None,
};
let result = sys.request_permission(req);
match result {
PermissionResult::Queued { request_id } => {
assert_eq!(request_id, "req_test_1");
}
_ => panic!("Expected Queued result"),
}
assert_eq!(sys.pending_requests().len(), baseline + 1);
});
}
#[test]
fn test_record_decision_removes_from_queue() {
with_temp_home(|| {
let sys = SafetySystem::new();
let baseline = sys.pending_requests().len();
let req = PermissionRequest {
id: "req_test_2".to_string(),
action: "push".to_string(),
description: "Push to origin".to_string(),
rationale: "Ready for review".to_string(),
urgency: Urgency::Low,
wait: false,
created_at: Utc::now(),
context: None,
};
sys.request_permission(req);
assert_eq!(sys.pending_requests().len(), baseline + 1);
sys.record_decision("req_test_2", true, "tui", Some("looks good".to_string()))
.unwrap();
assert_eq!(sys.pending_requests().len(), baseline);
});
}
#[test]
fn test_log_action_and_summary() {
with_temp_home(|| {
let sys = SafetySystem::new();
sys.log_action(ActionLog {
action_type: "memory_consolidation".to_string(),
description: "Merged 2 duplicate memories".to_string(),
tier: ActionTier::AutoAllowed,
details: None,
timestamp: Utc::now(),
});
sys.log_action(ActionLog {
action_type: "edit".to_string(),
description: "Fixed typo in README".to_string(),
tier: ActionTier::RequiresPermission,
details: None,
timestamp: Utc::now(),
});
let summary = sys.generate_summary();
assert!(summary.contains("memory_consolidation"));
assert!(summary.contains("edit"));
assert!(summary.contains("Done (auto-allowed)"));
assert!(summary.contains("Done (with permission)"));
});
}
#[test]
fn test_empty_summary() {
with_temp_home(|| {
let sys = SafetySystem::new();
let summary = sys.generate_summary();
assert_eq!(summary, "No actions recorded.");
});
}
#[test]
fn test_new_request_id_format() {
with_temp_home(|| {
let id = new_request_id();
assert!(id.starts_with("req_"));
});
}
#[test]
fn test_record_permission_via_file() {
with_temp_home(|| {
let sys = SafetySystem::new();
let baseline = sys.pending_requests().len();
let req = PermissionRequest {
id: "req_file_test".to_string(),
action: "push".to_string(),
description: "Push to origin".to_string(),
rationale: "Ready for review".to_string(),
urgency: Urgency::Low,
wait: false,
created_at: Utc::now(),
context: None,
};
sys.request_permission(req);
assert_eq!(sys.pending_requests().len(), baseline + 1);
record_permission_via_file("req_file_test", true, "email_reply", None).unwrap();
let sys2 = SafetySystem::new();
let still_pending = sys2
.pending_requests()
.iter()
.any(|r| r.id == "req_file_test");
assert!(
!still_pending,
"request should have been removed from queue"
);
});
}
}