synaps 0.10.2

Terminal-native AI agent runtime — parallel orchestration, reactive subagents, MCP, autonomous supervision
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
//! Task 16 — `ExecutionGate` wired into the stream tool loop (spec §7.1).
//!
//! End-to-end through the real `Runtime` stream loop against a loopback
//! Anthropic stub:
//! - a forged call to a registered-but-unverified (non-core) tool is denied
//!   BEFORE implementation execution and BEFORE `before_tool_call` hook
//!   emission, with a typed static tool_result;
//! - an unknown wire name still yields the bounded typed denial;
//! - default registered core tools (e.g. `ls`) still execute — behavior
//!   preservation for the default core set;
//! - tool-loop result ordering is preserved when denials and successes mix.

#[path = "support/phase2/mod.rs"]
mod support;

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use serial_test::serial;
use support::*;
use synaps_cli::extensions::hooks::events::HookKind;
use synaps_cli::extensions::hooks::events::{HookEvent, HookResult};
use synaps_cli::extensions::permissions::PermissionSet;
use synaps_cli::extensions::runtime::ExtensionHandler;
use synaps_cli::runtime::{Runtime, SessionEvent, StreamEvent};
use synaps_cli::tools::{Tool, ToolContext, ToolOrigin};
use synaps_cli::{Result, Value};

// ── SSE fixtures ────────────────────────────────────────────────────────────

/// Turn requesting the forged non-core fixture tool.
const SSE_FORGED_TOOL_USE: &str = concat!(
    "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_g1\",\"type\":\"message\",",
    "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
    "\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}\n\n",
    "data: {\"type\":\"content_block_start\",\"index\":0,",
    "\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_forged\",\"name\":\"gate_forged_fixture\"}}\n\n",
    "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
    "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",",
    "\"stop_sequence\":null},\"usage\":{\"input_tokens\":10,\"output_tokens\":5,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}\n\n",
    "data: {\"type\":\"message_stop\"}\n\n",
);

/// Turn requesting a wire name no live tool has.
const SSE_UNKNOWN_TOOL_USE: &str = concat!(
    "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_g2\",\"type\":\"message\",",
    "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
    "\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}\n\n",
    "data: {\"type\":\"content_block_start\",\"index\":0,",
    "\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_unknown\",\"name\":\"totally_unknown_tool\"}}\n\n",
    "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
    "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",",
    "\"stop_sequence\":null},\"usage\":{\"input_tokens\":10,\"output_tokens\":5,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}\n\n",
    "data: {\"type\":\"message_stop\"}\n\n",
);

/// Parallel round: core `ls` first, forged fixture second — ordering of the
/// tool_result blocks must match the tool_use order.
const SSE_MIXED_TOOL_USE: &str = concat!(
    "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_g3\",\"type\":\"message\",",
    "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
    "\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}\n\n",
    "data: {\"type\":\"content_block_start\",\"index\":0,",
    "\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_ls\",\"name\":\"ls\"}}\n\n",
    "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
    "data: {\"type\":\"content_block_start\",\"index\":1,",
    "\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_forged2\",\"name\":\"gate_forged_fixture\"}}\n\n",
    "data: {\"type\":\"content_block_stop\",\"index\":1}\n\n",
    "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",",
    "\"stop_sequence\":null},\"usage\":{\"input_tokens\":10,\"output_tokens\":5,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}\n\n",
    "data: {\"type\":\"message_stop\"}\n\n",
);

// ── Fixtures ────────────────────────────────────────────────────────────────

/// A registered tool with NO verifiable origin (`ToolOrigin::Unknown`) —
/// cataloged, live, but excluded from the default core set. Executing it
/// flips the flag, which the gate must prevent.
struct ForgedFixtureTool {
    executed: Arc<AtomicBool>,
}

#[async_trait]
impl Tool for ForgedFixtureTool {
    fn name(&self) -> &str {
        "gate_forged_fixture"
    }
    fn description(&self) -> &str {
        "deliberately non-core fixture tool"
    }
    fn parameters(&self) -> Value {
        serde_json::json!({"type": "object"})
    }
    fn origin(&self) -> ToolOrigin {
        ToolOrigin::Unknown
    }
    async fn execute(&self, _params: Value, _ctx: ToolContext) -> Result<String> {
        self.executed.store(true, Ordering::SeqCst);
        Ok("MUST_NEVER_RUN".to_string())
    }
}

/// Hook spy: records every tool name seen by `before_tool_call`.
struct HookSpy {
    seen: Arc<Mutex<Vec<String>>>,
}

#[async_trait]
impl ExtensionHandler for HookSpy {
    fn id(&self) -> &str {
        "gate-hook-spy"
    }
    async fn handle(&self, event: &HookEvent) -> HookResult {
        if let Some(name) = &event.tool_name {
            self.seen.lock().unwrap().push(name.clone());
        }
        HookResult::Continue
    }
    async fn shutdown(&self) {}
}

async fn install_hook_spy(rt: &Runtime) -> Arc<Mutex<Vec<String>>> {
    let seen = Arc::new(Mutex::new(Vec::new()));
    rt.hook_bus()
        .subscribe(
            HookKind::BeforeToolCall,
            Arc::new(HookSpy {
                seen: Arc::clone(&seen),
            }),
            None,
            None,
            PermissionSet::from_strings(&["tools.intercept".to_string()]),
        )
        .await
        .expect("spy subscription");
    seen
}

fn final_history(events: &[StreamEvent]) -> Vec<synaps_cli::SharedMessage> {
    events
        .iter()
        .rev()
        .find_map(|e| match e {
            StreamEvent::Session(SessionEvent::MessageHistory(h)) => Some(h.clone()),
            _ => None,
        })
        .expect("turn must surface message history")
}

fn tool_results(history: &[synaps_cli::SharedMessage]) -> Vec<(String, String)> {
    history
        .iter()
        .filter_map(|m| m["content"].as_array())
        .flat_map(|blocks| blocks.iter())
        .filter(|b| b["type"] == "tool_result")
        .map(|b| {
            (
                b["tool_use_id"].as_str().unwrap_or("").to_string(),
                b["content"].as_str().unwrap_or("").to_string(),
            )
        })
        .collect()
}

// ── Scenarios ───────────────────────────────────────────────────────────────

/// Forged known-but-non-core call: typed denial BEFORE implementation
/// execution and BEFORE before_tool_call hook emission.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn forged_non_core_tool_denied_before_execution_and_hooks() {
    let _guard = HomeGuard::new();
    let (url, hits, _) = spawn_stub(Script::SeqSse(&[SSE_FORGED_TOOL_USE, ANTHROPIC_SSE])).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);

    let mut rt = Runtime::new().await.expect("runtime");
    rt.set_model("claude-sonnet-4-5".to_string());
    let executed = Arc::new(AtomicBool::new(false));
    rt.tools_shared()
        .write()
        .await
        .register(Arc::new(ForgedFixtureTool {
            executed: Arc::clone(&executed),
        }));
    let seen_hooks = install_hook_spy(&rt).await;

    let ev = drive_runtime_turn(&rt, "forged call fixture", false).await;
    assert_eq!(
        hits.load(Ordering::SeqCst),
        2,
        "denial still continues the loop"
    );

    let results = tool_results(&final_history(&ev));
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, "toolu_forged");
    assert!(
        results[0].1.contains("Tool call denied"),
        "denial must be the typed static gate error, got: {}",
        results[0].1
    );
    assert!(
        !results[0].1.contains("MUST_NEVER_RUN"),
        "implementation output must never appear"
    );
    assert!(
        !executed.load(Ordering::SeqCst),
        "forged call must be denied BEFORE implementation execution"
    );
    assert!(
        seen_hooks.lock().unwrap().is_empty(),
        "denial must happen BEFORE before_tool_call hook emission, saw: {:?}",
        seen_hooks.lock().unwrap()
    );
}

/// Unknown wire names stay bounded typed denials.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn unknown_wire_name_yields_bounded_typed_denial() {
    let _guard = HomeGuard::new();
    let (url, _, _) = spawn_stub(Script::SeqSse(&[SSE_UNKNOWN_TOOL_USE, ANTHROPIC_SSE])).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);

    let mut rt = Runtime::new().await.expect("runtime");
    rt.set_model("claude-sonnet-4-5".to_string());
    let seen_hooks = install_hook_spy(&rt).await;

    let ev = drive_runtime_turn(&rt, "unknown tool fixture", false).await;
    let results = tool_results(&final_history(&ev));
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, "toolu_unknown");
    assert_eq!(results[0].1, "Unknown tool: totally_unknown_tool");
    assert!(seen_hooks.lock().unwrap().is_empty());
}

/// Default registered core tool still executes (behavior preservation) and
/// its before_tool_call hook still fires.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn default_core_tool_still_executes_through_gate() {
    let _guard = HomeGuard::new();
    let (url, hits, _) = spawn_stub(Script::SeqSse(&[ANTHROPIC_SSE_TOOL_USE, ANTHROPIC_SSE])).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);

    let mut rt = Runtime::new().await.expect("runtime");
    rt.set_model("claude-sonnet-4-5".to_string());
    let seen_hooks = install_hook_spy(&rt).await;

    let ev = drive_runtime_turn(&rt, "core tool fixture", false).await;
    assert_eq!(hits.load(Ordering::SeqCst), 2);
    let results = tool_results(&final_history(&ev));
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, "toolu_ph2");
    assert!(
        !results[0].1.contains("denied") && !results[0].1.contains("Unknown tool"),
        "core tool must execute, got: {}",
        results[0].1
    );
    assert_eq!(
        seen_hooks.lock().unwrap().as_slice(),
        ["ls"],
        "authorized core tool still emits before_tool_call"
    );
}

// ── Retained per-session set semantics (Task 16 review fixes) ───────────────

/// Round 1: TWO parallel `ls` calls. Round 2: one `ls`. Round 3: final text.
const SSE_PARALLEL_LS_TOOL_USE: &str = concat!(
    "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_g4\",\"type\":\"message\",",
    "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
    "\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}\n\n",
    "data: {\"type\":\"content_block_start\",\"index\":0,",
    "\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_s1\",\"name\":\"ls\"}}\n\n",
    "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
    "data: {\"type\":\"content_block_start\",\"index\":1,",
    "\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_s2\",\"name\":\"ls\"}}\n\n",
    "data: {\"type\":\"content_block_stop\",\"index\":1}\n\n",
    "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",",
    "\"stop_sequence\":null},\"usage\":{\"input_tokens\":10,\"output_tokens\":5,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}\n\n",
    "data: {\"type\":\"message_stop\"}\n\n",
);

/// Round 1 (parallel): the dynamic-registration fixture AND the tool it
/// registers, in the SAME model response.
const SSE_DYNREG_ROUND: &str = concat!(
    "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_g5\",\"type\":\"message\",",
    "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
    "\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}\n\n",
    "data: {\"type\":\"content_block_start\",\"index\":0,",
    "\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_d1\",\"name\":\"gate_dyn_reg_fixture\"}}\n\n",
    "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
    "data: {\"type\":\"content_block_start\",\"index\":1,",
    "\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_d2\",\"name\":\"gate_late_fixture\"}}\n\n",
    "data: {\"type\":\"content_block_stop\",\"index\":1}\n\n",
    "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",",
    "\"stop_sequence\":null},\"usage\":{\"input_tokens\":10,\"output_tokens\":5,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}\n\n",
    "data: {\"type\":\"message_stop\"}\n\n",
);

/// Round 2: the freshly registered tool alone.
const SSE_LATE_TOOL_ROUND: &str = concat!(
    "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_g6\",\"type\":\"message\",",
    "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
    "\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}\n\n",
    "data: {\"type\":\"content_block_start\",\"index\":0,",
    "\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_d3\",\"name\":\"gate_late_fixture\"}}\n\n",
    "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
    "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",",
    "\"stop_sequence\":null},\"usage\":{\"input_tokens\":10,\"output_tokens\":5,",
    "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}\n\n",
    "data: {\"type\":\"message_stop\"}\n\n",
);

/// Builtin-origin fixture registered mid-round by the `before_message`
/// mutator under a NEW name: its registration bumps the catalog generation
/// without touching any tool the model is about to call.
struct MidRoundRegisteredTool;

#[async_trait]
impl Tool for MidRoundRegisteredTool {
    fn name(&self) -> &str {
        "gate_mid_round_fixture"
    }
    fn description(&self) -> &str {
        "registered mid-round to bump the catalog generation"
    }
    fn parameters(&self) -> Value {
        serde_json::json!({"type": "object"})
    }
    fn origin(&self) -> ToolOrigin {
        ToolOrigin::Builtin
    }
    async fn execute(&self, _params: Value, _ctx: ToolContext) -> Result<String> {
        Ok("MID_OK".to_string())
    }
}

/// Builtin-origin imposter registered mid-round OVER the real `ls`: same
/// `ToolId` (`builtin:ls`), different schema → the catalog record's digest
/// drifts from the digest the session pinned at the round-top rebuild.
struct DriftedLsTool;

#[async_trait]
impl Tool for DriftedLsTool {
    fn name(&self) -> &str {
        "ls"
    }
    fn description(&self) -> &str {
        "schema-drifted replacement for ls registered mid-round"
    }
    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {"drifted": {"type": "boolean"}}
        })
    }
    fn origin(&self) -> ToolOrigin {
        ToolOrigin::Builtin
    }
    async fn execute(&self, _params: Value, _ctx: ToolContext) -> Result<String> {
        Ok("DRIFTED_OK".to_string())
    }
}

/// `before_message` handler that registers `tool` into the live registry
/// exactly once — AFTER the round-top session-set rebuild, BEFORE tool
/// authorization.
struct RegistryMutator {
    tools: Arc<tokio::sync::RwLock<synaps_cli::ToolRegistry>>,
    tool: Arc<dyn Tool>,
    fired: Arc<AtomicBool>,
}

#[async_trait]
impl ExtensionHandler for RegistryMutator {
    fn id(&self) -> &str {
        "gate-registry-mutator"
    }
    async fn handle(&self, _event: &HookEvent) -> HookResult {
        if !self.fired.swap(true, Ordering::SeqCst) {
            self.tools
                .write()
                .await
                .register(Arc::clone(&self.tool));
        }
        HookResult::Continue
    }
    async fn shutdown(&self) {}
}

async fn install_mid_round_mutator(rt: &Runtime, tool: Arc<dyn Tool>) {
    rt.hook_bus()
        .subscribe(
            HookKind::BeforeMessage,
            Arc::new(RegistryMutator {
                tools: rt.tools_shared(),
                tool,
                fired: Arc::new(AtomicBool::new(false)),
            }),
            None,
            None,
            PermissionSet::from_strings(&["privacy.llm_content".to_string()]),
        )
        .await
        .expect("mutator subscription");
}

/// Builtin-origin fixture that dynamically registers `gate_late_fixture`
/// through the stream's `tool_register_tx` channel (the dynamic-registration
/// seam), which is drained only AFTER the round completes.
struct DynRegFixtureTool;

#[async_trait]
impl Tool for DynRegFixtureTool {
    fn name(&self) -> &str {
        "gate_dyn_reg_fixture"
    }
    fn description(&self) -> &str {
        "registers gate_late_fixture dynamically"
    }
    fn parameters(&self) -> Value {
        serde_json::json!({"type": "object"})
    }
    fn origin(&self) -> ToolOrigin {
        ToolOrigin::Builtin
    }
    async fn execute(&self, _params: Value, ctx: ToolContext) -> Result<String> {
        if let Some(tx) = &ctx.capabilities.tool_register_tx {
            let _ = tx.send(vec![Arc::new(LateFixtureTool) as Arc<dyn Tool>]);
        }
        Ok("REGISTERED".to_string())
    }
}

/// The verified (builtin-origin) tool registered dynamically mid-turn.
struct LateFixtureTool;

#[async_trait]
impl Tool for LateFixtureTool {
    fn name(&self) -> &str {
        "gate_late_fixture"
    }
    fn description(&self) -> &str {
        "late dynamically registered fixture"
    }
    fn parameters(&self) -> Value {
        serde_json::json!({"type": "object"})
    }
    fn origin(&self) -> ToolOrigin {
        ToolOrigin::Builtin
    }
    async fn execute(&self, _params: Value, _ctx: ToolContext) -> Result<String> {
        Ok("LATE_OK".to_string())
    }
}

/// #100 contract, half 1: a catalog mutation AFTER the round-top rebuild
/// that does NOT touch the called tool (an unrelated registration bumping
/// the catalog generation) must NOT deny. Generation drift alone is not a
/// denial: BOTH sibling `ls` calls of the same response execute against
/// their unchanged pinned digest, `before_tool_call` fires for each, and the
/// next round's explicit rebuild keeps executing.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn mid_round_unrelated_catalog_mutation_does_not_deny_schema_identical_core_tool() {
    let _guard = HomeGuard::new();
    let (url, hits, _) = spawn_stub(Script::SeqSse(&[
        SSE_PARALLEL_LS_TOOL_USE,
        ANTHROPIC_SSE_TOOL_USE,
        ANTHROPIC_SSE,
    ]))
    .await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);

    let mut rt = Runtime::new().await.expect("runtime");
    rt.set_model("claude-sonnet-4-5".to_string());
    let seen_hooks = install_hook_spy(&rt).await;
    install_mid_round_mutator(&rt, Arc::new(MidRoundRegisteredTool)).await;

    let ev = drive_runtime_turn(&rt, "unrelated drift fixture", false).await;
    assert_eq!(hits.load(Ordering::SeqCst), 3, "three model rounds");

    let results = tool_results(&final_history(&ev));
    assert_eq!(results.len(), 3, "two round-1 runs plus one round-2 run");
    assert_eq!(results[0].0, "toolu_s1");
    assert_eq!(results[1].0, "toolu_s2");
    assert_eq!(results[2].0, "toolu_ph2");
    for (id, content) in &results {
        assert!(
            !content.contains("denied") && !content.contains("stale"),
            "unrelated catalog mutation must not deny a schema-identical core \
             tool ({id}), got: {content}"
        );
    }
    assert_eq!(
        seen_hooks.lock().unwrap().as_slice(),
        ["ls", "ls", "ls"],
        "every executed call emits before_tool_call: two round-1 siblings \
         plus the round-2 call"
    );
}

/// #100 contract, half 2: a catalog mutation AFTER the round-top rebuild
/// that DOES change the called tool's record — `ls` replaced under the same
/// `ToolId` with a different schema, so its digest drifts from the pinned
/// core digest — denies THAT tool with the typed per-tool
/// `SchemaDigestMismatch` message. BOTH sibling calls of the same response
/// are judged against the one pinned snapshot (identical denial text), no
/// `before_tool_call` hook fires for them, and the NEXT round's explicit
/// rebuild re-pins the current digest so the replacement executes.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn mid_round_schema_drift_of_called_tool_denies_per_tool_until_next_round_rebuild() {
    let _guard = HomeGuard::new();
    let (url, hits, _) = spawn_stub(Script::SeqSse(&[
        SSE_PARALLEL_LS_TOOL_USE,
        ANTHROPIC_SSE_TOOL_USE,
        ANTHROPIC_SSE,
    ]))
    .await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);

    let mut rt = Runtime::new().await.expect("runtime");
    rt.set_model("claude-sonnet-4-5".to_string());
    let seen_hooks = install_hook_spy(&rt).await;
    install_mid_round_mutator(&rt, Arc::new(DriftedLsTool)).await;

    let ev = drive_runtime_turn(&rt, "digest drift fixture", false).await;
    assert_eq!(hits.load(Ordering::SeqCst), 3, "denial continues the loop");

    let results = tool_results(&final_history(&ev));
    assert_eq!(results.len(), 3, "two round-1 denials plus one round-2 run");
    assert_eq!(results[0].0, "toolu_s1");
    assert_eq!(results[1].0, "toolu_s2");
    assert!(
        results[0].1.contains("Tool call denied")
            && results[0].1.contains("schema digest changed"),
        "post-rebuild digest drift of the called tool must deny with the \
         per-tool SchemaDigestMismatch, got: {}",
        results[0].1
    );
    assert!(
        !results[0].1.contains("stale"),
        "denial must be per-tool, never the retired set-wide stale-generation \
         message, got: {}",
        results[0].1
    );
    assert_eq!(
        results[0].1, results[1].1,
        "sibling calls of one response must be judged against ONE pinned \
         set snapshot"
    );
    assert_eq!(results[2].0, "toolu_ph2");
    assert_eq!(
        results[2].1, "DRIFTED_OK",
        "next-round explicit rebuild must re-pin the current digest and \
         execute the replacement"
    );
    assert_eq!(
        seen_hooks.lock().unwrap().as_slice(),
        ["ls"],
        "digest denials must not emit before_tool_call; only the recovered \
         round-2 call may"
    );
}

/// Stream dynamic registrations are drained only after a round: a sibling
/// call to the not-yet-drained tool in the SAME response stays a typed
/// Unknown denial, and the NEXT round's explicit rebuild exposes the newly
/// registered verified tool as default core (no inherited activations).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn drained_registration_executes_only_after_next_round_rebuild() {
    let _guard = HomeGuard::new();
    let (url, _, _) = spawn_stub(Script::SeqSse(&[
        SSE_DYNREG_ROUND,
        SSE_LATE_TOOL_ROUND,
        ANTHROPIC_SSE,
    ]))
    .await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);

    let mut rt = Runtime::new().await.expect("runtime");
    rt.set_model("claude-sonnet-4-5".to_string());
    rt.tools_shared()
        .write()
        .await
        .register(Arc::new(DynRegFixtureTool));

    let ev = drive_runtime_turn(&rt, "dyn reg fixture", false).await;
    let results = tool_results(&final_history(&ev));
    assert_eq!(results.len(), 3);
    assert_eq!(results[0].0, "toolu_d1");
    assert_eq!(results[0].1, "REGISTERED");
    assert_eq!(results[1].0, "toolu_d2");
    assert_eq!(
        results[1].1, "Unknown tool: gate_late_fixture",
        "not-yet-drained registration must stay unknown within the round"
    );
    assert_eq!(results[2].0, "toolu_d3");
    assert_eq!(
        results[2].1, "LATE_OK",
        "next-round rebuild must expose the drained verified tool as \
         default core"
    );
}

/// Mixed parallel round: denial and success keep the tool_use ordering.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn mixed_round_preserves_result_ordering() {
    let _guard = HomeGuard::new();
    let (url, _, _) = spawn_stub(Script::SeqSse(&[SSE_MIXED_TOOL_USE, ANTHROPIC_SSE])).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);

    let mut rt = Runtime::new().await.expect("runtime");
    rt.set_model("claude-sonnet-4-5".to_string());
    let executed = Arc::new(AtomicBool::new(false));
    rt.tools_shared()
        .write()
        .await
        .register(Arc::new(ForgedFixtureTool {
            executed: Arc::clone(&executed),
        }));

    let ev = drive_runtime_turn(&rt, "mixed round fixture", false).await;
    let results = tool_results(&final_history(&ev));
    assert_eq!(results.len(), 2, "one result per tool_use");
    assert_eq!(results[0].0, "toolu_ls", "ordering follows tool_use order");
    assert_eq!(results[1].0, "toolu_forged2");
    assert!(results[1].1.contains("Tool call denied"));
    assert!(!executed.load(Ordering::SeqCst));
}