File size: 23,217 Bytes
5e5d6c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import io
import os
import sqlite3
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from pathlib import Path

import pytest
import ctx.runtime.query_delivery as query_delivery_module

from ctx.core.install_policy_store import persist_install_policy
from ctx.engine.installation import InstallConsentPolicy
from ctx.runtime.query_decision import QueryHostDescriptor
from ctx.runtime.query_delivery import QueryDeliveryController, SensitiveQueryInput
from ctx.runtime.release_skill_dispatcher import dispatch_release_skill_install
from ctx.runtime.release_skill_layout import open_release_skill_runtime_layout
from ctx.runtime.release_skill_layout import open_workspace_release_skill_runtime_layout
from ctx.runtime.release_skill_lifecycle import activate_installed_release_skill


NOW = datetime(2026, 8, 2, 12, 30, tzinfo=UTC)
OCCURRED_AT = "2026-08-02T12:00:00Z"
STATE_PROTOCOLS_SHA256 = "c87c65b5b09f48e27c683fb5ada9d8bc377d6d72d7742ce7aac3c2d3d97ac441"
FIRST_ASK_PROMPT = "repair nested Python context manager state restoration"
SECOND_ASK_PROMPT = "fix Python state restoration for nested context managers"


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_manage_first_prompt_auto_installs_loads_and_cross_host_reuses_workspace(
    tmp_path: Path,
) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "shared-state"
    policy_root = tmp_path / "onboarding-policy"
    persist_install_policy(
        InstallConsentPolicy(skill_mode="preapproved-auto"),
        policy_root,
    )
    outputs: list[bytes] = []

    for host, native_session_id, logical_prompt_id in (
        (QueryHostDescriptor.codex(), "codex-native", "codex-turn"),
        (QueryHostDescriptor.claude_code(), "claude-native", "claude-turn"),
    ):
        report = QueryDeliveryController(
            host=host,
            mode="manage",
            state_root=state_root,
            environment={"CTX_INSTALL_POLICY_ROOT": str(policy_root)},
        ).issue(
            SensitiveQueryInput(
                native_session_id=native_session_id,
                logical_prompt_id=logical_prompt_id,
                workspace=workspace,
                prompt="repair nested Python context manager state restoration",
                language="Python",
            )
        )

        assert report.status == "issued"
        assert report.emission_permit is not None
        output = io.BytesIO()
        report.emission_permit.emit_once(output)
        outputs.append(output.getvalue())

    assert all(b"# ctx Python State and Protocols" in output for output in outputs)
    installed = tuple(state_root.rglob(STATE_PROTOCOLS_SHA256))
    assert len(installed) == 1
    assert installed[0].is_file()


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_concurrent_cross_host_manage_prompts_apply_one_workspace_install(
    tmp_path: Path,
) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "shared-state"
    policy_root = tmp_path / "onboarding-policy"
    persist_install_policy(
        InstallConsentPolicy(skill_mode="preapproved-auto"),
        policy_root,
    )

    def issue(item: tuple[QueryHostDescriptor, str, str]) -> bytes:
        host, native_session_id, logical_prompt_id = item
        report = QueryDeliveryController(
            host=host,
            mode="manage",
            state_root=state_root,
            environment={"CTX_INSTALL_POLICY_ROOT": str(policy_root)},
            # These two hosts contend for one lock by design. The production
            # default (2s) fails closed rather than stalling a prompt hook,
            # which is correct for a user but makes this assertion a race
            # against machine load. The subject here is that both hosts
            # converge on one install, not how fast a lock is acquired.
            lock_timeout_seconds=10.0,
        ).issue(
            SensitiveQueryInput(
                native_session_id=native_session_id,
                logical_prompt_id=logical_prompt_id,
                workspace=workspace,
                prompt="repair nested Python context manager state restoration",
                language="Python",
            )
        )
        assert report.status == "issued"
        assert report.emission_permit is not None
        output = io.BytesIO()
        report.emission_permit.emit_once(output)
        return output.getvalue()

    with ThreadPoolExecutor(max_workers=2) as pool:
        outputs = tuple(
            pool.map(
                issue,
                (
                    (QueryHostDescriptor.codex(), "codex-native", "codex-turn"),
                    (
                        QueryHostDescriptor.claude_code(),
                        "claude-native",
                        "claude-turn",
                    ),
                ),
            )
        )

    assert all(b"# ctx Python State and Protocols" in output for output in outputs)
    assert len(tuple(state_root.rglob(STATE_PROTOCOLS_SHA256))) == 1


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_activate_mode_never_auto_installs_from_persisted_policy(tmp_path: Path) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "state"
    policy_root = tmp_path / "onboarding-policy"
    persist_install_policy(
        InstallConsentPolicy(skill_mode="preapproved-auto"),
        policy_root,
    )

    report = QueryDeliveryController(
        host=QueryHostDescriptor.codex(),
        mode="activate",
        state_root=state_root,
        environment={"CTX_INSTALL_POLICY_ROOT": str(policy_root)},
    ).issue(
        SensitiveQueryInput(
            native_session_id="native-session",
            logical_prompt_id="relevant-turn",
            workspace=workspace,
            prompt="repair nested Python context manager state restoration",
            language="Python",
        )
    )

    assert report.status == "abstained"
    assert report.emission_permit is None
    assert not tuple(state_root.rglob(STATE_PROTOCOLS_SHA256))


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_manage_ask_each_time_emits_only_an_authority_free_recommendation(
    tmp_path: Path,
) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "state"
    policy_root = tmp_path / "onboarding-policy"
    persist_install_policy(
        InstallConsentPolicy(skill_mode="ask-each-time"),
        policy_root,
    )

    report = QueryDeliveryController(
        host=QueryHostDescriptor.codex(),
        mode="manage",
        state_root=state_root,
        environment={"CTX_INSTALL_POLICY_ROOT": str(policy_root)},
    ).issue(
        SensitiveQueryInput(
            native_session_id="native-session",
            logical_prompt_id="consent-turn",
            workspace=workspace,
            prompt="repair nested Python context manager state restoration",
            language="Python",
        )
    )

    assert report.status == "issued"
    assert report.emission_permit is not None
    output = io.BytesIO()
    report.emission_permit.emit_once(output)
    rendered = output.getvalue()
    assert b"skill:ctx-python-state-protocols" in rendered
    assert b"approval=required" in rendered
    assert b"no installation performed" in rendered.lower()
    assert b"# ctx Python State and Protocols" not in rendered
    assert not tuple(state_root.rglob(STATE_PROTOCOLS_SHA256))


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_manage_irrelevant_then_relevant_prompt_uses_fresh_management_stream(
    tmp_path: Path,
) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "state"
    policy_root = tmp_path / "onboarding-policy"
    persist_install_policy(
        InstallConsentPolicy(skill_mode="preapproved-auto"),
        policy_root,
    )
    layout = open_workspace_release_skill_runtime_layout(
        state_root=state_root,
        policy_store_root=policy_root,
        workspace=workspace,
    )
    controller = QueryDeliveryController(
        host=QueryHostDescriptor.codex(),
        mode="manage",
        state_root=state_root,
        environment={"CTX_INSTALL_POLICY_ROOT": str(policy_root)},
    )

    irrelevant = controller.issue(
        SensitiveQueryInput(
            native_session_id="native-session",
            logical_prompt_id="irrelevant-turn",
            workspace=workspace,
            prompt="write a JavaScript button label",
            language="JavaScript",
        )
    )

    assert irrelevant.status == "abstained"
    assert irrelevant.emission_permit is None
    assert not layout.journal_path.exists()
    assert not layout.benefit_audit_path.exists()
    assert not (layout.skill_store_root / STATE_PROTOCOLS_SHA256).exists()

    relevant = controller.issue(
        SensitiveQueryInput(
            native_session_id="native-session",
            logical_prompt_id="relevant-turn",
            workspace=workspace,
            prompt="repair nested Python context manager state restoration",
            language="Python",
        )
    )

    assert relevant.status == "issued"
    assert relevant.emission_permit is not None
    output = io.BytesIO()
    relevant.emission_permit.emit_once(output)
    assert b"# ctx Python State and Protocols" in output.getvalue()
    assert (layout.skill_store_root / STATE_PROTOCOLS_SHA256).is_file()


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_manage_repeated_ask_prompts_reuse_one_authority_free_consent_challenge(
    tmp_path: Path,
) -> None:
    """Repeated ask-each-time prompts must accumulate no new authority.

    An earlier revision of this test asserted that no journal or benefit audit
    existed at all.  That contract is unsatisfiable together with the accepted
    ask-each-time design: `ManagedQueryService.resolve_consent` authenticates a
    signed human decision against a *durable* challenge record
    (`status_by_challenge_digest`), so a resumable ask cannot exist without one
    persisted challenge.  The property that actually protects the user is that
    an untrusted prompt hook creates that authority exactly once, reuses it for
    later prompts, never installs anything, never leaks consent authority into
    model-visible bytes, and never persists raw prompt text or absolute paths.
    """

    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "state"
    policy_root = tmp_path / "onboarding-policy"
    persist_install_policy(
        InstallConsentPolicy(skill_mode="ask-each-time"),
        policy_root,
    )
    layout = open_workspace_release_skill_runtime_layout(
        state_root=state_root,
        policy_store_root=policy_root,
        workspace=workspace,
    )
    controller = QueryDeliveryController(
        host=QueryHostDescriptor.codex(),
        mode="manage",
        state_root=state_root,
        environment={"CTX_INSTALL_POLICY_ROOT": str(policy_root)},
    )
    outputs: list[bytes] = []

    for logical_prompt_id, prompt in (
        ("first-turn", FIRST_ASK_PROMPT),
        ("second-turn", SECOND_ASK_PROMPT),
    ):
        report = controller.issue(
            SensitiveQueryInput(
                native_session_id="native-session",
                logical_prompt_id=logical_prompt_id,
                workspace=workspace,
                prompt=prompt,
                language="Python",
            )
        )
        assert report.status == "issued"
        assert report.emission_permit is not None
        output = io.BytesIO()
        report.emission_permit.emit_once(output)
        outputs.append(output.getvalue())

    assert all(b"approval=required" in output for output in outputs)
    assert all(b"no installation performed" in output.lower() for output in outputs)
    assert all(b"consent_id=" not in output for output in outputs)
    assert all(b"requested_action" not in output for output in outputs)
    # Authority is created exactly once and then reused: the second prompt
    # neither publishes a second challenge nor advances the journal.
    assert outputs[0] == outputs[1]
    assert layout.consent_broker_path is not None
    with sqlite3.connect(layout.consent_broker_path) as connection:
        assert connection.execute("SELECT count(*) FROM consent_challenges").fetchone() == (1,)
    with sqlite3.connect(layout.journal_path) as connection:
        journal_records = connection.execute("SELECT count(*) FROM engine_journal").fetchone()[0]
    assert journal_records == 3
    # Nothing is installed and no host material is published by an ask.
    assert not (layout.skill_store_root / STATE_PROTOCOLS_SHA256).exists()
    # No durable byte carries raw prompt text or an absolute workspace path.
    durable = b"".join(
        path.read_bytes()
        for path in sorted(state_root.rglob("*"))
        if path.is_file() and path.stat().st_size
    )
    for secret in (FIRST_ASK_PROMPT.encode(), SECOND_ASK_PROMPT.encode(), str(workspace).encode()):
        assert secret not in durable


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_manage_reconciliation_failure_is_not_committed_as_abstention(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "state"
    policy_root = tmp_path / "onboarding-policy"
    persist_install_policy(
        InstallConsentPolicy(skill_mode="preapproved-auto"),
        policy_root,
    )
    attempts = 0

    def failed_reconciliation(**_kwargs: object) -> object:
        nonlocal attempts
        attempts += 1
        raise RuntimeError("private failure detail")

    monkeypatch.setattr(
        query_delivery_module,
        "reconcile_prompt_capabilities",
        failed_reconciliation,
    )
    controller = QueryDeliveryController(
        host=QueryHostDescriptor.codex(),
        mode="manage",
        state_root=state_root,
        environment={"CTX_INSTALL_POLICY_ROOT": str(policy_root)},
    )
    request = SensitiveQueryInput(
        native_session_id="native-session",
        logical_prompt_id="failure-turn",
        workspace=workspace,
        prompt="repair nested Python context manager state restoration",
        language="Python",
    )

    assert controller.issue(request).status == "failed"
    assert attempts == 3
    assert controller.issue(request).status == "failed"
    assert attempts == 6


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
@pytest.mark.parametrize(
    "host",
    (QueryHostDescriptor.codex(), QueryHostDescriptor.claude_code()),
)
def test_later_relevant_host_prompt_routes_activated_release_skill_from_cas(
    tmp_path: Path,
    host: QueryHostDescriptor,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / f"{host.host_context_id}-state"
    native_session_id = f"{host.host_context_id}-native-session"
    layout = open_release_skill_runtime_layout(
        state_root=state_root,
        host_context_id=host.host_context_id,
        native_session_id=native_session_id,
        workspace=workspace,
    )
    request = layout.install_request(
        task="repair nested Python context manager state restoration",
        language="Python",
        occurred_at=OCCURRED_AT,
    )
    persist_install_policy(
        InstallConsentPolicy(skill_mode="preapproved-auto"),
        request.policy_store_root,
    )
    assert (
        dispatch_release_skill_install(
            request,
            trusted_utc_now=lambda: NOW,
        ).status
        == "installed"
    )
    activate_installed_release_skill(request, trusted_utc_now=lambda: NOW)
    availability_opens = 0
    original_open = query_delivery_module.open_activated_skill_query_availability

    def observed_open(**kwargs: object):  # type: ignore[no-untyped-def]
        nonlocal availability_opens
        availability_opens += 1
        return original_open(**kwargs)  # type: ignore[arg-type]

    monkeypatch.setattr(
        query_delivery_module,
        "open_activated_skill_query_availability",
        observed_open,
    )

    controller = QueryDeliveryController(
        host=host,
        mode="activate",
        state_root=state_root,
        environment={},
    )
    report = controller.issue(
        SensitiveQueryInput(
            native_session_id=native_session_id,
            logical_prompt_id="later-relevant-turn",
            workspace=workspace,
            prompt="repair nested Python context manager state restoration",
            language="Python",
        )
    )

    assert report.status == "issued"
    assert availability_opens == 1
    assert report.emission_permit is not None
    output = io.BytesIO()
    report.emission_permit.emit_once(output)
    assert b"# ctx Python State and Protocols" in output.getvalue()
    assert b"# ctx Python Testing" not in output.getvalue()


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_irrelevant_prompt_does_not_expose_activated_release_skill(tmp_path: Path) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "state"
    native_session_id = "native-session"
    layout = open_release_skill_runtime_layout(
        state_root=state_root,
        host_context_id="codex",
        native_session_id=native_session_id,
        workspace=workspace,
    )
    request = layout.install_request(
        task="repair nested Python context manager state restoration",
        language="Python",
        occurred_at=OCCURRED_AT,
    )
    persist_install_policy(
        InstallConsentPolicy(skill_mode="preapproved-auto"),
        request.policy_store_root,
    )
    assert (
        dispatch_release_skill_install(
            request,
            trusted_utc_now=lambda: NOW,
        ).status
        == "installed"
    )
    activate_installed_release_skill(request, trusted_utc_now=lambda: NOW)

    report = QueryDeliveryController(
        host=QueryHostDescriptor.codex(),
        mode="activate",
        state_root=state_root,
        environment={},
    ).issue(
        SensitiveQueryInput(
            native_session_id=native_session_id,
            logical_prompt_id="irrelevant-turn",
            workspace=workspace,
            prompt="write a JavaScript button label",
            language="JavaScript",
        )
    )

    assert report.status == "abstained"
    assert report.emission_permit is None


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_activation_epoch_preserves_prompt_terminal_and_new_turn_replans(
    tmp_path: Path,
) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "state"
    native_session_id = "native-session"
    prompt = "repair nested Python context manager state restoration"
    sensitive = SensitiveQueryInput(
        native_session_id=native_session_id,
        logical_prompt_id="same-logical-turn",
        workspace=workspace,
        prompt=prompt,
        language="Python",
    )
    before = QueryDeliveryController(
        host=QueryHostDescriptor.codex(),
        mode="activate",
        state_root=state_root,
        environment={},
    )

    assert before.issue(sensitive).status == "abstained"
    assert before.issue(sensitive).status == "already-terminal"

    layout = open_release_skill_runtime_layout(
        state_root=state_root,
        host_context_id="codex",
        native_session_id=native_session_id,
        workspace=workspace,
    )
    request = layout.install_request(
        task=prompt,
        language="Python",
        occurred_at=OCCURRED_AT,
    )
    persist_install_policy(
        InstallConsentPolicy(skill_mode="preapproved-auto"),
        request.policy_store_root,
    )
    assert (
        dispatch_release_skill_install(
            request,
            trusted_utc_now=lambda: NOW,
        ).status
        == "installed"
    )
    activate_installed_release_skill(request, trusted_utc_now=lambda: NOW)

    after = QueryDeliveryController(
        host=QueryHostDescriptor.codex(),
        mode="activate",
        state_root=state_root,
        environment={},
    )
    assert after.issue(sensitive).status == "already-terminal"

    next_turn = SensitiveQueryInput(
        native_session_id=native_session_id,
        logical_prompt_id="next-logical-turn",
        workspace=workspace,
        prompt=prompt,
        language="Python",
    )
    reopened = after.issue(next_turn)

    assert reopened.status == "issued"
    assert after.issue(next_turn).status == "already-terminal"


@pytest.mark.skipif(os.name == "nt", reason="managed skill CAS is POSIX-only")
def test_tampered_activated_cas_fails_bundle_without_packaged_fallback(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    workspace = tmp_path / "workspace"
    workspace.mkdir()
    state_root = tmp_path / "state"
    native_session_id = "native-session"
    task = "repair nested Python context manager state restoration and fix pytest tests"
    layout = open_release_skill_runtime_layout(
        state_root=state_root,
        host_context_id="codex",
        native_session_id=native_session_id,
        workspace=workspace,
    )
    request = layout.install_request(
        task=task,
        language="Python",
        occurred_at=OCCURRED_AT,
    )
    persist_install_policy(
        InstallConsentPolicy(skill_mode="preapproved-auto"),
        request.policy_store_root,
    )
    assert dispatch_release_skill_install(request, trusted_utc_now=lambda: NOW).status == (
        "installed"
    )
    activate_installed_release_skill(request, trusted_utc_now=lambda: NOW)
    target = next(
        path
        for path in request.skill_store_root.iterdir()
        if path.is_file() and len(path.name) == 64
    )
    original_open = query_delivery_module.open_activated_skill_query_availability

    def open_then_tamper(**kwargs: object):  # type: ignore[no-untyped-def]
        availability = original_open(**kwargs)  # type: ignore[arg-type]
        target.write_bytes(b"x" * target.stat().st_size)
        return availability

    monkeypatch.setattr(
        query_delivery_module,
        "open_activated_skill_query_availability",
        open_then_tamper,
    )

    report = QueryDeliveryController(
        host=QueryHostDescriptor.codex(),
        mode="activate",
        state_root=state_root,
        environment={},
    ).issue(
        SensitiveQueryInput(
            native_session_id=native_session_id,
            logical_prompt_id="tampered-cas-turn",
            workspace=workspace,
            prompt=task,
            language="Python",
        )
    )

    assert report.status == "failed"
    assert report.emission_permit is None