sqz-engine 0.1.0

Adaptive multi-pass LLM context compression engine — content-aware pipeline with AST parsing, token counting, session persistence, and budget tracking
Documentation
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// The 5 hook types supported by the sqz hook system.
///
/// Requirements: 44.1
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HookType {
    /// Fires before a tool is executed. Can block, redirect, or inject context.
    PreToolUse,
    /// Fires after a tool completes. Captures structured events.
    PostToolUse,
    /// Fires before context compaction. Builds session snapshot.
    PreCompact,
    /// Fires on session start or resume. Restores from snapshot.
    SessionStart,
    /// Fires when the user submits a prompt. Captures decisions and corrections.
    UserPromptSubmit,
}

impl HookType {
    /// Returns all hook types in canonical order.
    pub fn all() -> &'static [HookType] {
        &[
            HookType::PreToolUse,
            HookType::PostToolUse,
            HookType::PreCompact,
            HookType::SessionStart,
            HookType::UserPromptSubmit,
        ]
    }

    /// Human-readable label for this hook type.
    pub fn label(&self) -> &'static str {
        match self {
            HookType::PreToolUse => "pre_tool_use",
            HookType::PostToolUse => "post_tool_use",
            HookType::PreCompact => "pre_compact",
            HookType::SessionStart => "session_start",
            HookType::UserPromptSubmit => "user_prompt_submit",
        }
    }
}

/// Actions a hook can take when fired.
///
/// Requirements: 44.2, 44.3, 44.4, 44.5
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum HookAction {
    /// Allow the operation to proceed (no-op).
    Allow,
    /// Block the operation with a reason (PreToolUse).
    Block { reason: String },
    /// Redirect to a different tool (PreToolUse).
    Redirect { to_tool: String },
    /// Inject additional context into the operation (PreToolUse).
    InjectContext { content: String },
    /// Capture a structured event (PostToolUse).
    CaptureEvent { event_type: String, data: String },
    /// Build a session snapshot (PreCompact).
    BuildSnapshot,
    /// Restore session state from snapshot (SessionStart).
    RestoreSnapshot,
    /// Capture a user decision or correction (UserPromptSubmit).
    CaptureDecision { decision: String },
}

/// A registered hook with its type, action, and optional filter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Hook {
    pub hook_type: HookType,
    pub action: HookAction,
    /// Optional filter — when set, the hook only fires if the context
    /// matches this pattern (e.g. a tool name for PreToolUse).
    pub filter: Option<String>,
}

/// Context passed to hooks when they fire.
#[derive(Debug, Clone, Default)]
pub struct HookContext {
    /// The tool name (relevant for PreToolUse / PostToolUse).
    pub tool_name: Option<String>,
    /// The command being executed.
    pub command: Option<String>,
    /// Arbitrary key-value metadata.
    pub metadata: HashMap<String, String>,
}

/// Manages hook registration and dispatch.
///
/// Requirements: 44.1–44.6
pub struct HookManager {
    hooks: HashMap<HookType, Vec<Hook>>,
}

impl HookManager {
    pub fn new() -> Self {
        Self {
            hooks: HashMap::new(),
        }
    }

    /// Register a hook.
    pub fn register(&mut self, hook: Hook) {
        self.hooks
            .entry(hook.hook_type)
            .or_default()
            .push(hook);
    }

    /// Fire all hooks of the given type and return the first non-Allow action,
    /// or `HookAction::Allow` if no hook matched.
    pub fn fire(&self, hook_type: HookType, context: &HookContext) -> HookAction {
        let Some(hooks) = self.hooks.get(&hook_type) else {
            return HookAction::Allow;
        };

        for hook in hooks {
            if let Some(ref filter) = hook.filter {
                // Check filter against tool_name or command.
                let matches = context
                    .tool_name
                    .as_deref()
                    .map_or(false, |t| t == filter)
                    || context
                        .command
                        .as_deref()
                        .map_or(false, |c| c.contains(filter));
                if !matches {
                    continue;
                }
            }
            // Return the first matching non-Allow action.
            if hook.action != HookAction::Allow {
                return hook.action.clone();
            }
        }

        HookAction::Allow
    }

    /// Return all hooks registered for a given type.
    pub fn hooks_for(&self, hook_type: HookType) -> &[Hook] {
        self.hooks.get(&hook_type).map_or(&[], |v| v.as_slice())
    }

    /// Total number of registered hooks.
    pub fn len(&self) -> usize {
        self.hooks.values().map(|v| v.len()).sum()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Default for HookManager {
    fn default() -> Self {
        Self::new()
    }
}


// ── Platform config generation ────────────────────────────────────────────

/// Known platforms for `sqz init --agent <platform>`.
const KNOWN_PLATFORMS: &[&str] = &[
    "claude-code",
    "cursor",
    "kiro",
    "copilot",
    "windsurf",
    "cline",
    "gemini-cli",
    "codex",
    "opencode",
    "goose",
    "aider",
    "amp",
    "continue",
    "zed",
    "amazon-q",
];

/// Generate a platform-specific hook configuration for `sqz init --agent <platform>`.
///
/// Returns a TOML string for Level 2 platforms (shell hook + MCP) and a JSON
/// string for Level 1 platforms (MCP-only).
///
/// Requirements: 44.6
pub fn generate_platform_config(platform: &str) -> Option<String> {
    match platform {
        // ── Level 1: MCP config only ──────────────────────────────────
        "continue" | "zed" | "amazon-q" => Some(generate_level1_config(platform)),

        // ── Level 2: Shell hook + MCP + hooks ─────────────────────────
        "claude-code" | "cursor" | "kiro" | "copilot" | "windsurf" | "cline"
        | "gemini-cli" | "codex" | "opencode" | "goose" | "aider" | "amp" => {
            Some(generate_level2_config(platform))
        }

        _ => None,
    }
}

/// Returns the list of known platform identifiers.
pub fn known_platforms() -> &'static [&'static str] {
    KNOWN_PLATFORMS
}

fn generate_level1_config(platform: &str) -> String {
    let config_path = match platform {
        "continue" => "~/.continue/config.json",
        "zed" => "~/.config/zed/settings.json",
        "amazon-q" => "~/.aws/amazonq/mcp.json",
        _ => "mcp.json",
    };

    format!(
        r#"{{
  "_comment": "sqz MCP config for {platform}",
  "_path": "{config_path}",
  "mcpServers": {{
    "sqz": {{
      "command": "sqz-mcp",
      "args": ["--transport", "stdio"],
      "env": {{}}
    }}
  }}
}}"#
    )
}

fn generate_level2_config(platform: &str) -> String {
    let config_path = match platform {
        "claude-code" => ".claude/mcp_servers.json",
        "cursor" => "~/.cursor/mcp.json",
        "kiro" => ".kiro/settings/mcp.json",
        "copilot" => ".github/copilot/mcp.json",
        "windsurf" => "~/.windsurf/mcp.json",
        "cline" => "~/.cline/mcp.json",
        _ => "mcp.json",
    };

    format!(
        r#"# sqz hook config for {platform}
# MCP config path: {config_path}

[hooks.pre_tool_use]
enabled = true
block_dangerous = true
sandbox_redirect = ["shell", "bash", "exec"]
inject_context = true

[hooks.post_tool_use]
enabled = true
capture_events = ["file_edit", "git_op", "task_update", "error"]

[hooks.pre_compact]
enabled = true
build_snapshot = true

[hooks.session_start]
enabled = true
restore_snapshot = true

[hooks.user_prompt_submit]
enabled = true
capture_decisions = true
capture_corrections = true

[mcp]
command = "sqz-mcp"
args = ["--transport", "stdio"]
config_path = "{config_path}"
"#
    )
}

// ── Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── HookType ──────────────────────────────────────────────────────

    #[test]
    fn test_hook_type_all_returns_5_variants() {
        assert_eq!(HookType::all().len(), 5);
    }

    #[test]
    fn test_hook_type_labels_are_unique() {
        let labels: Vec<&str> = HookType::all().iter().map(|h| h.label()).collect();
        let mut deduped = labels.clone();
        deduped.sort();
        deduped.dedup();
        assert_eq!(labels.len(), deduped.len());
    }

    // ── HookManager basics ────────────────────────────────────────────

    #[test]
    fn test_new_manager_is_empty() {
        let mgr = HookManager::new();
        assert!(mgr.is_empty());
        assert_eq!(mgr.len(), 0);
    }

    #[test]
    fn test_register_and_count() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::Block {
                reason: "dangerous".into(),
            },
            filter: None,
        });
        assert_eq!(mgr.len(), 1);
        assert!(!mgr.is_empty());
    }

    #[test]
    fn test_hooks_for_returns_registered_hooks() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PostToolUse,
            action: HookAction::CaptureEvent {
                event_type: "file_edit".into(),
                data: "{}".into(),
            },
            filter: None,
        });
        assert_eq!(mgr.hooks_for(HookType::PostToolUse).len(), 1);
        assert_eq!(mgr.hooks_for(HookType::PreToolUse).len(), 0);
    }

    // ── fire() dispatch ───────────────────────────────────────────────

    #[test]
    fn test_fire_returns_allow_when_no_hooks() {
        let mgr = HookManager::new();
        let ctx = HookContext::default();
        assert_eq!(mgr.fire(HookType::PreToolUse, &ctx), HookAction::Allow);
    }

    #[test]
    fn test_fire_returns_first_matching_action() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::Block {
                reason: "blocked".into(),
            },
            filter: None,
        });
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::Redirect {
                to_tool: "sandbox".into(),
            },
            filter: None,
        });

        let ctx = HookContext::default();
        // First non-Allow wins.
        assert_eq!(
            mgr.fire(HookType::PreToolUse, &ctx),
            HookAction::Block {
                reason: "blocked".into()
            }
        );
    }

    #[test]
    fn test_fire_with_filter_matches_tool_name() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::Redirect {
                to_tool: "sandbox".into(),
            },
            filter: Some("exec_shell".into()),
        });

        // No match → Allow.
        let ctx_miss = HookContext {
            tool_name: Some("read_file".into()),
            ..Default::default()
        };
        assert_eq!(mgr.fire(HookType::PreToolUse, &ctx_miss), HookAction::Allow);

        // Match → Redirect.
        let ctx_hit = HookContext {
            tool_name: Some("exec_shell".into()),
            ..Default::default()
        };
        assert_eq!(
            mgr.fire(HookType::PreToolUse, &ctx_hit),
            HookAction::Redirect {
                to_tool: "sandbox".into()
            }
        );
    }

    #[test]
    fn test_fire_with_filter_matches_command_substring() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::Block {
                reason: "rm blocked".into(),
            },
            filter: Some("rm -rf".into()),
        });

        let ctx = HookContext {
            command: Some("rm -rf /tmp/stuff".into()),
            ..Default::default()
        };
        assert_eq!(
            mgr.fire(HookType::PreToolUse, &ctx),
            HookAction::Block {
                reason: "rm blocked".into()
            }
        );
    }

    // ── PreToolUse actions ────────────────────────────────────────────

    #[test]
    fn test_pre_tool_use_block() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::Block {
                reason: "dangerous command".into(),
            },
            filter: None,
        });
        let action = mgr.fire(HookType::PreToolUse, &HookContext::default());
        assert!(matches!(action, HookAction::Block { .. }));
    }

    #[test]
    fn test_pre_tool_use_redirect() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::Redirect {
                to_tool: "sandbox_exec".into(),
            },
            filter: None,
        });
        let action = mgr.fire(HookType::PreToolUse, &HookContext::default());
        assert!(matches!(action, HookAction::Redirect { .. }));
    }

    #[test]
    fn test_pre_tool_use_inject_context() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::InjectContext {
                content: "extra context".into(),
            },
            filter: None,
        });
        let action = mgr.fire(HookType::PreToolUse, &HookContext::default());
        assert!(matches!(action, HookAction::InjectContext { .. }));
    }

    // ── PostToolUse capture ───────────────────────────────────────────

    #[test]
    fn test_post_tool_use_capture_event() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PostToolUse,
            action: HookAction::CaptureEvent {
                event_type: "file_edit".into(),
                data: r#"{"path":"src/main.rs"}"#.into(),
            },
            filter: None,
        });
        let action = mgr.fire(HookType::PostToolUse, &HookContext::default());
        assert!(matches!(action, HookAction::CaptureEvent { .. }));
    }

    // ── PreCompact snapshot ───────────────────────────────────────────

    #[test]
    fn test_pre_compact_build_snapshot() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PreCompact,
            action: HookAction::BuildSnapshot,
            filter: None,
        });
        let action = mgr.fire(HookType::PreCompact, &HookContext::default());
        assert_eq!(action, HookAction::BuildSnapshot);
    }

    // ── SessionStart restore ──────────────────────────────────────────

    #[test]
    fn test_session_start_restore_snapshot() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::SessionStart,
            action: HookAction::RestoreSnapshot,
            filter: None,
        });
        let action = mgr.fire(HookType::SessionStart, &HookContext::default());
        assert_eq!(action, HookAction::RestoreSnapshot);
    }

    // ── UserPromptSubmit capture ──────────────────────────────────────

    #[test]
    fn test_user_prompt_submit_capture_decision() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::UserPromptSubmit,
            action: HookAction::CaptureDecision {
                decision: "use async/await".into(),
            },
            filter: None,
        });
        let action = mgr.fire(HookType::UserPromptSubmit, &HookContext::default());
        assert!(matches!(action, HookAction::CaptureDecision { .. }));
    }

    // ── Platform config generation ────────────────────────────────────

    #[test]
    fn test_generate_config_unknown_platform_returns_none() {
        assert!(generate_platform_config("unknown-platform").is_none());
    }

    #[test]
    fn test_generate_config_level1_platforms_produce_json() {
        for platform in &["continue", "zed", "amazon-q"] {
            let config = generate_platform_config(platform).unwrap();
            assert!(config.contains("mcpServers"), "missing mcpServers for {platform}");
            assert!(config.contains("sqz-mcp"), "missing sqz-mcp for {platform}");
        }
    }

    #[test]
    fn test_generate_config_level2_platforms_produce_toml() {
        for platform in &[
            "claude-code", "cursor", "kiro", "copilot", "windsurf", "cline",
            "gemini-cli", "codex", "opencode", "goose", "aider", "amp",
        ] {
            let config = generate_platform_config(platform).unwrap();
            assert!(
                config.contains("[hooks.pre_tool_use]"),
                "missing pre_tool_use section for {platform}"
            );
            assert!(
                config.contains("[hooks.session_start]"),
                "missing session_start section for {platform}"
            );
            assert!(
                config.contains("sqz-mcp"),
                "missing sqz-mcp for {platform}"
            );
        }
    }

    #[test]
    fn test_generate_config_claude_code_has_correct_path() {
        let config = generate_platform_config("claude-code").unwrap();
        assert!(config.contains(".claude/mcp_servers.json"));
    }

    #[test]
    fn test_generate_config_kiro_has_correct_path() {
        let config = generate_platform_config("kiro").unwrap();
        assert!(config.contains(".kiro/settings/mcp.json"));
    }

    #[test]
    fn test_generate_config_cursor_has_correct_path() {
        let config = generate_platform_config("cursor").unwrap();
        assert!(config.contains("~/.cursor/mcp.json"));
    }

    #[test]
    fn test_known_platforms_covers_all() {
        assert_eq!(known_platforms().len(), 15);
        // Every known platform should produce a config.
        for p in known_platforms() {
            assert!(
                generate_platform_config(p).is_some(),
                "no config for known platform: {p}"
            );
        }
    }

    #[test]
    fn test_level2_config_contains_all_5_hook_sections() {
        let config = generate_platform_config("claude-code").unwrap();
        assert!(config.contains("[hooks.pre_tool_use]"));
        assert!(config.contains("[hooks.post_tool_use]"));
        assert!(config.contains("[hooks.pre_compact]"));
        assert!(config.contains("[hooks.session_start]"));
        assert!(config.contains("[hooks.user_prompt_submit]"));
    }

    // ── Multiple hooks per type ───────────────────────────────────────

    #[test]
    fn test_multiple_hooks_same_type_different_filters() {
        let mut mgr = HookManager::new();
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::Block {
                reason: "shell blocked".into(),
            },
            filter: Some("exec_shell".into()),
        });
        mgr.register(Hook {
            hook_type: HookType::PreToolUse,
            action: HookAction::Redirect {
                to_tool: "sandbox".into(),
            },
            filter: Some("run_code".into()),
        });

        assert_eq!(mgr.len(), 2);

        let ctx_shell = HookContext {
            tool_name: Some("exec_shell".into()),
            ..Default::default()
        };
        assert!(matches!(
            mgr.fire(HookType::PreToolUse, &ctx_shell),
            HookAction::Block { .. }
        ));

        let ctx_code = HookContext {
            tool_name: Some("run_code".into()),
            ..Default::default()
        };
        assert!(matches!(
            mgr.fire(HookType::PreToolUse, &ctx_code),
            HookAction::Redirect { .. }
        ));
    }
}