A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
scripts: drop the pinned-TS leg of the lifecycle parity suite (#3697)
Sebastian Müllerd8e4af19bfac
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 6c2d6dbc95..c8666cf2d2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -344,74 +344,42 @@ jobs:- name: Bootstrap the kernel venv (ready before the kernel e2e units)if: steps.selection.outputs.units != '0'run: ./target/debug/prime-agent --prime-agent-bootstrap- # The targeted lifecycle comparisons use the recognized, pinned TS release- # and only synthetic loopback providers/state. One leg avoids 8 downloads.- - name: Compare the lifecycle binaries (pinned TS reference)- id: lifecycle_parity- if: matrix.shard == 1 && steps.selection.outputs.units != '0' && hashFiles('scripts/review_*_parity.py') != ''- env:- GH_TOKEN: ${{ github.token }}+ # The real-binary lifecycle checks drive the debug binary through owned+ # daemons, PTYs and loopback providers only. One leg is enough.+ - name: Run the rust lifecycle checks+ id: lifecycle_checks+ if: matrix.shard == 1 && steps.selection.outputs.units != '0' && hashFiles('scripts/check_*.py') != ''run: |set -euo pipefail- mkdir -p "${RUNNER_TEMP}/lifecycle-parity-receipts"- comparison_status=0- if [ -f scripts/review_new_goal_parity.py ]; then- PA_COMPACTION_TRACE=stderr RUST_BACKTRACE=1 cargo test --locked -p pa-daemon --lib \- lazy_build_restores_only_the_pre_admission_prompt_context -- --nocapture \- 2>&1 | tee "${RUNNER_TEMP}/lifecycle-parity-receipts/new-goal-regression.log" || comparison_status=1- fi- reference="${RUNNER_TEMP}/lifecycle-ts-reference"- mkdir -p "${reference}"- gh release download v0.9.8 --repo "${GITHUB_REPOSITORY}" \- --pattern prime-agent-0.9.8-linux-x64.tar.gz --dir "${reference}"- archive="${reference}/prime-agent-0.9.8-linux-x64.tar.gz"- echo "83fb09129bf78e3e60268212cd70932166591b15188caa70c1b0efbcc76235e2 ${archive}" | sha256sum --check- mkdir -p "${reference}/package"- tar -xzf "${archive}" -C "${reference}/package"- export PA_TS_ARCHIVE="${archive}"- export PA_TS_BINARY="${reference}/package/prime-agent"+ mkdir -p "${RUNNER_TEMP}/lifecycle-check-receipts"export PA_RUST_BINARY="${GITHUB_WORKSPACE}/target/debug/prime-agent"- export PI_PACKAGE_DIR="${reference}/package"export PRIME_AGENT_KERNEL_PYTHON="${HOME}/.prime/agent/kernel-venv/bin/python"export PA_E2E_KERNEL_PYTHON="${PRIME_AGENT_KERNEL_PYTHON}"- export PYTHONPATH="${reference}/package/skills/goal/src"test -x "${PRIME_AGENT_KERNEL_PYTHON}"- # The pinned TS @ provider needs the real fd executable. Stage- # the distro binary only for the completion fixture; enumeration- # stays in the actual product rather than a mocked tool.- if [ -f scripts/review_at_completion_parity.py ]; then- if ! command -v fd >/dev/null && ! command -v fdfind >/dev/null; then- sudo apt-get update -qq- sudo apt-get install -y --no-install-recommends fd-find- fi- if ! command -v fd >/dev/null; then- mkdir -p "${RUNNER_TEMP}/at-completion-tools"- ln -s "$(command -v fdfind)" "${RUNNER_TEMP}/at-completion-tools/fd"- export PATH="${RUNNER_TEMP}/at-completion-tools:${PATH}"- fi- fi- # Discover independently added verifiers so feature PRs do not- # overwrite or conflict with each other's comparison selection.- for verifier in scripts/review_*_parity.py; do- [ -f "${verifier}" ] || continue- scenario="${verifier#scripts/review_}"- scenario="${scenario%_parity.py}"- verifier_test="scripts/test_review_${scenario}_parity.py"- if [ -f "${verifier_test}" ]; then- python3 "${verifier_test}" || comparison_status=1+ check_status=0+ python3 scripts/test_lifecycle_lib.py || check_status=1+ # Discover independently added checks so feature PRs do not+ # overwrite or conflict with each other's selection.+ for check in scripts/check_*.py; do+ [ -f "${check}" ] || continue+ scenario="${check#scripts/check_}"+ scenario="${scenario%.py}"+ check_test="scripts/test_check_${scenario}.py"+ if [ -f "${check_test}" ]; then+ python3 "${check_test}" || check_status=1fi- python3 "${verifier}" --receipt "${RUNNER_TEMP}/lifecycle-parity-receipts/${scenario}.json" || comparison_status=1+ python3 "${check}" --receipt "${RUNNER_TEMP}/lifecycle-check-receipts/${scenario}.json" || check_status=1done- exit "${comparison_status}"- - name: Upload the binary comparison receipts- if: always() && matrix.shard == 1 && steps.selection.outputs.units != '0' && hashFiles('scripts/review_*_parity.py') != ''+ exit "${check_status}"+ - name: Upload the lifecycle check receipts+ if: always() && matrix.shard == 1 && steps.selection.outputs.units != '0' && hashFiles('scripts/check_*.py') != ''uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2with:- name: lifecycle-parity-receipts-attempt-${{ github.run_attempt }}- path: ${{ runner.temp }}/lifecycle-parity-receipts/+ name: lifecycle-check-receipts-attempt-${{ github.run_attempt }}+ path: ${{ runner.temp }}/lifecycle-check-receipts/if-no-files-found: error- name: Run this shard's test subset- if: ${{ !cancelled() && (success() || steps.lifecycle_parity.outcome == 'failure') }}+ if: ${{ !cancelled() && (success() || steps.lifecycle_checks.outcome == 'failure') }}run: |python3 scripts/ci_test_shard.py --shard ${{ matrix.shard }} --total ${{ env.SHARD_COUNT }} --crates "${{ needs.changes.outputs.crates }}" --manifest "$RUNNER_TEMP/shard-manifest-${{ matrix.shard }}-attempt-${{ github.run_attempt }}.json"- name: Upload the shard manifest (always — the summary audits it)diff --git a/scripts/review_agent_bounce_parity.py b/scripts/check_agent_bounce.pysimilarity index 74%rename from scripts/review_agent_bounce_parity.pyrename to scripts/check_agent_bounce.pyindex db6be5651a..7108fb80ef 100644--- a/scripts/review_agent_bounce_parity.py+++ b/scripts/check_agent_bounce.py@@ -1,9 +1,7 @@#!/usr/bin/env python3-"""Real-daemon #3558 comparison: baseline queue clear and explicit Rust bounce addition.+"""Real-daemon #3558 check: clear_queue empties the receiver and bounces agent messages to their sender.-TS 0.9.8 clears queued actions but never sends a sender bounce (daemon-mode.ts-clear_queue; agent-session.ts clearQueue). The receipt records that difference,-not exact behavioral parity. Journal recovery is covered by the separate Rust+Journal recovery is covered by the separate Rustclear_queue_bounces_recovered_agent_messages_to_their_senders regression.All processes, sockets, provider requests and session state belong to this fixture."""@@ -18,7 +16,7 @@ import tempfileimport threadingimport time-from review_draft_disconnect_parity import digest, env_for, stop, TS_ARCHIVE_SHA256+from lifecycle_lib import digest, env_for, stopLIMIT = 35MESSAGE = 'AGENT_BOUNCE_PARITY_MESSAGE'@@ -107,8 +105,8 @@ class Client:self.sock.close()-def run_case(binary, kind, root, long_name, observed):- env = env_for(root, kind)+def run_case(binary, root, long_name, observed):+ env = env_for(root)provider = Provider()thread = threading.Thread(target=provider.serve_forever, daemon=True)thread.start()@@ -157,29 +155,23 @@ def run_case(binary, kind, root, long_name, observed):empty = clients[1].call('get_queue', activeSessionId=receiver)observed['receiver_after_clear'] = emptyassert empty == {'steering': [], 'followUp': []}, empty- # TS source has no asynchronous bounce operation. Record the actual- # immediate baseline; do not claim a bounded observation proves absence forever.queue = clients[0].call('get_queue', activeSessionId=source)- if kind == 'rust':- deadline = time.monotonic() + LIMIT- while not queue['steering'] and not queue['followUp']:- assert time.monotonic() < deadline, 'sender bounce never arrived'- threading.Event().wait(0.025)- queue = clients[0].call('get_queue', activeSessionId=source)- dropped = clients[0].call('clear_queue', activeSessionId=source)- texts = dropped['steering'] + dropped['followUp']- assert len(texts) == 1, dropped- prefix, body = texts[0].split('\n\n', 1)- assert prefix.startswith('[agent-message from '), prefix- budget = 16384 - len(OPENING) - len(ENDING)- expected = OPENING + receiver_name[:budget] + ENDING- expected += MESSAGE[:16384 - len(expected)]- assert body == expected, repr(body[:200])- assert len(body) <= 16384, len(body)- observed['bounce'] = {'message': texts[0], 'body_characters': len(body)}- else:- assert queue == {'steering': [], 'followUp': []}, queue- observed['bounce'] = None+ deadline = time.monotonic() + LIMIT+ while not queue['steering'] and not queue['followUp']:+ assert time.monotonic() < deadline, 'sender bounce never arrived'+ threading.Event().wait(0.025)+ queue = clients[0].call('get_queue', activeSessionId=source)+ dropped = clients[0].call('clear_queue', activeSessionId=source)+ texts = dropped['steering'] + dropped['followUp']+ assert len(texts) == 1, dropped+ prefix, body = texts[0].split('\n\n', 1)+ assert prefix.startswith('[agent-message from '), prefix+ budget = 16384 - len(OPENING) - len(ENDING)+ expected = OPENING + receiver_name[:budget] + ENDING+ expected += MESSAGE[:16384 - len(expected)]+ assert body == expected, repr(body[:200])+ assert len(body) <= 16384, len(body)+ observed['bounce'] = {'message': texts[0], 'body_characters': len(body)}observed['sender_queue_observed'] = queueobserved['hello'] = clients[0].helloobserved['provider_request_count'] = len(provider.requests)@@ -213,24 +205,17 @@ def main():parser.add_argument('--receipt', required=True, type=Path)args = parser.parse_args()receipt = {'scenario': 'agent_bounce', 'status': 'failed',- 'scope': 'actual clear_queue response and emptied receiver baseline; added Rust sender bounce',- 'intentional_difference': 'TS 0.9.8 has no sender bounce; Rust adds it',- 'recovery_scope': 'separate Rust journal reopen/clear regression, not TS binary parity',+ 'scope': 'actual clear_queue response, emptied receiver queue and sender bounce',+ 'recovery_scope': 'separate Rust journal reopen/clear regression','cases': {}}try:- archive = Path(os.environ['PA_TS_ARCHIVE'])- assert digest(archive) == TS_ARCHIVE_SHA256, 'TS reference archive digest mismatch'- receipt['ts_archive_sha256'] = digest(archive)with tempfile.TemporaryDirectory(prefix='pa-bounce-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ['PA_' + kind.upper() + '_BINARY']).resolve()- receipt[kind + '_binary_sha256'] = digest(binary)- for long_name in (False, True):- key = kind + ('_long_receiver' if long_name else '_ordinary')- observed = receipt['cases'][key] = {}- run_case(binary, kind, Path(folder) / key, long_name, observed)- for suffix in ('_ordinary', '_long_receiver'):- assert receipt['cases']['ts' + suffix]['cleared'] == receipt['cases']['rust' + suffix]['cleared']+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ receipt['binary_sha256'] = digest(binary)+ for long_name in (False, True):+ key = 'long_receiver' if long_name else 'ordinary'+ observed = receipt['cases'][key] = {}+ run_case(binary, Path(folder) / key, long_name, observed)receipt['status'] = 'passed'except Exception as error:receipt['error'] = str(error)diff --git a/scripts/review_at_completion_parity.py b/scripts/check_at_completion.pysimilarity index 71%rename from scripts/review_at_completion_parity.pyrename to scripts/check_at_completion.pyindex 840f3fe45a..c5de939846 100644--- a/scripts/review_at_completion_parity.py+++ b/scripts/check_at_completion.py@@ -1,30 +1,25 @@#!/usr/bin/env python3-"""Hosted actual TS/Rust quoted @ completion keys and menu captures.+"""Hosted actual quoted @ completion keys and menu captures.Ordinary PTY clients use a controlled protocol-7 peer with no selected model.-The actual binaries enumerate a temporary project containing spaces. Rust must+The actual binary enumerates a temporary project containing spaces. It mustrefresh directory children after Tab, Enter, a typed quoted slash, and deleting-inside that quoted token. TS's-observed reaction and complete frames are retained as an intentional comparison,-not normalized into equality or used to claim the new ranking matches TS.+inside that quoted token."""import argparseimport jsonimport osfrom pathlib import Pathimport signal-import shutilimport subprocessimport sysimport tempfileimport time-from review_agent_bounce_parity import Client-from review_dock_screen import DockScreen-from review_draft_disconnect_parity import (- Supervisor, Terminal, digest, env_for, TS_ARCHIVE_SHA256, TS_SOURCE_COMMIT,-)-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish, process_identity+from check_agent_bounce import Client+from lifecycle_lib import DockScreen+from lifecycle_lib import Supervisor, Terminal, digest, env_for+from lifecycle_lib import OwnedProcesses, TAG, finish, process_identityDIRECTORY = 'dir with spaces'CHILD = 'only_child.rs'@@ -93,10 +88,10 @@ def discover_direct(scope, command):scope.discover()-def discover_hello(binary, kind, root, observed):+def discover_hello(binary, root, observed):"""Learn the real schema; graceful ACK + close + exit, with fallback RED."""root.mkdir(parents=True)- env = env_for(root, kind)+ env = env_for(root)env[TAG] = str(root)socket_path = root / 'hello.sock'scope = OwnedProcesses(binary, root, socket_path)@@ -171,9 +166,9 @@ def close_terminal(terminal, scope, server, observed):observed['cleanup_verified'] = True-def run_case(binary, kind, root, hello, case, observed):+def run_case(binary, root, hello, case, observed):root.mkdir(parents=True)- env = env_for(root, kind)+ env = env_for(root)env[TAG] = str(root)(root / DIRECTORY).mkdir()(root / DIRECTORY / CHILD).write_text('fixture child\n')@@ -209,64 +204,43 @@ def run_case(binary, kind, root, hello, case, observed):observed['frames']['after'] = stable_frame(terminal, server,'directory action painted', lambda text: expected_token in textand (token not in text if case in ('backspace', 'delete') else True)- and (children_visible(text) if kind == 'rust' else True))+ and children_visible(text))assert not server.prompts, 'completion key accidentally submitted a prompt'- if kind == 'rust':- assert observed['frames']['after']['children_visible'], 'Rust directory children menu missing'+ assert observed['frames']['after']['children_visible'], 'directory children menu missing'observed['behavior_verified'] = Truefinally:close_terminal(terminal, scope, server, observed)-def compare(receipt):- """Fail closed on missing execution/cleanup; report actual differences."""- comparisons = {}+def verify(cases):+ """Fail closed on missing execution, cleanup or children menu."""for case in CASES:- sides = [receipt['runs'][kind]['cases'][case] for kind in ('ts', 'rust')]- for side in sides:- assert side.get('behavior_verified') and side.get('cleanup_verified'), case- assert not side.get('error') and not side.get('cleanup_errors'), case- assert sides[1]['frames']['after']['children_visible'], case- comparisons[case] = {- 'inputs_equal': sides[0]['inputs'] == sides[1]['inputs'],- 'ts_children_visible': sides[0]['frames']['after']['children_visible'],- 'rust_children_visible': sides[1]['frames']['after']['children_visible'],- 'full_text_equal': sides[0]['frames']['after']['text'] == sides[1]['frames']['after']['text'],- 'menu_rows_equal': sides[0]['frames']['after']['menu_rows'] == sides[1]['frames']['after']['menu_rows'],- }- assert comparisons[case]['inputs_equal'], 'different key sequences are not a comparison'- return comparisons+ observed = cases[case]+ assert observed.get('behavior_verified') and observed.get('cleanup_verified'), case+ assert not observed.get('error') and not observed.get('cleanup_errors'), case+ assert observed['frames']['after']['children_visible'], casedef main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- receipt = {'verified': False, 'runs': {}, 'scope': __doc__,- 'ts_source_commit': TS_SOURCE_COMMIT,- 'intentional_difference': 'Rust refreshes children after accepting or typing a quoted directory. Ranking changes are intentional; captured rows are not normalized into TS equality.',+ receipt = {'verified': False, 'scope': __doc__,'not_verified': ['pixel/font equality', 'complete ranking matrix', 'in-flight search race timing','real daemon/provider completion transport', 'model inference', 'file submission']}try:assert sys.platform == 'linux', 'hosted Linux fixture only'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'TS archive mismatch'- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256- fd = shutil.which('fd')- assert fd, 'real fd executable is required for pinned TS @ completion'- receipt['fd'] = {'path': fd, 'sha256': digest(Path(fd)),- 'version': subprocess.check_output([fd, '--version'], text=True, timeout=10).strip()}with tempfile.TemporaryDirectory(prefix='pa-at-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ['PA_' + kind.upper() + '_BINARY']).resolve()- side = receipt['runs'][kind] = {'binary_sha256': digest(binary), 'hello_discovery': {}, 'cases': {}}- hello = discover_hello(binary, kind, Path(folder) / (kind + '-hello'), side['hello_discovery'])- for case in CASES:- observed = side['cases'][case] = {}- try:- run_case(binary, kind, Path(folder) / (kind + '-' + case + ' project space'), hello, case, observed)- except Exception as error:- observed['error'] = str(error)- receipt['comparisons'] = compare(receipt)+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ receipt.update(binary_sha256=digest(binary), hello_discovery={}, cases={})+ hello = discover_hello(binary, Path(folder) / 'hello', receipt['hello_discovery'])+ for case in CASES:+ observed = receipt['cases'][case] = {}+ try:+ run_case(binary, Path(folder) / (case + ' project space'), hello, case, observed)+ except Exception as error:+ observed['error'] = str(error)+ verify(receipt['cases'])receipt['verified'] = Trueexcept Exception as error:receipt['error'] = str(error)diff --git a/scripts/check_autocompact_settings.py b/scripts/check_autocompact_settings.pynew file mode 100644index 0000000000..2e28a66e67--- /dev/null+++ b/scripts/check_autocompact_settings.py@@ -0,0 +1,79 @@+#!/usr/bin/env python3+"""Drive /settings through the PTY: the auto-compaction toggle and the percentage row.++Keep full frames and wire commands. No real inference, user home, or production+daemon is used.+"""+import argparse+import json+import os+import re+from pathlib import Path+import tempfile++from lifecycle_lib import Supervisor, Terminal, actual_hello, digest, env_for+++def observe(binary, root):+ root.mkdir()+ env = env_for(root)+ hello = actual_hello(binary, root, env)+ server = Supervisor(root / 'ui.sock', hello, 'settings', root)+ terminal = None+ result = {'binary_sha256': digest(binary), 'executed': False}+ try:+ terminal = Terminal([str(binary), '--daemon-socket', str(server.path)], root, env)+ terminal.wait('initial attach', lambda: server.attaches > 0 and bool(terminal.screen.text().strip()), server)+ terminal.send('/settings')+ terminal.wait('settings typed', lambda: '/settings' in terminal.screen.text(), server)+ terminal.send('\r')+ terminal.wait('settings menu', lambda: 'Auto-compact' in terminal.screen.text(), server)+ result['settings_frame'] = terminal.screen.text()+ terminal.send('\r')+ terminal.wait('toggle delivered', lambda: any(c.get('type') == 'set_auto_compaction' for c in server.commands), server)+ terminal.wait('toggle rendered', lambda: any('Auto-compact' in row and 'true' in row for row in terminal.screen.text().splitlines()), server)+ result['toggle_frame'] = terminal.screen.text()+ result['toggle_rows'] = [re.sub(r'\s+', ' ', row.strip().lstrip('›> ').strip()) for row in terminal.screen.text().splitlines()+ if 'Auto-compact' in row and 'threshold' not in row]+ result['toggle_payloads'] = [json.dumps({k: c[k] for k in ('type', 'activeSessionId', 'enabled')}, sort_keys=True)+ for c in server.commands if c.get('type') == 'set_auto_compaction']+ # Search for the added row so other General settings can evolve independently.+ terminal.send('threshold')+ terminal.wait('percentage focused', lambda: any(row.strip().startswith('› Auto-compact threshold (%)') for row in terminal.screen.text().splitlines()), server)+ result['percentage_frame'] = terminal.screen.text()+ terminal.send('\r')+ path = root / 'agent/settings.json'+ terminal.wait('percentage persisted', lambda: json.loads(path.read_text()).get('compaction', {}).get('thresholdPercent') == 100, server)+ terminal.wait('percentage rendered', lambda: any('threshold (%)' in row and '100' in row for row in terminal.screen.text().splitlines()), server)+ result['changed_percentage_frame'] = terminal.screen.text()+ result['saved_percentage'] = json.loads(path.read_text())['compaction']['thresholdPercent']+ result['executed'] = True+ except Exception as error:+ result['error'] = str(error)+ finally:+ if terminal:+ terminal.close()+ result['terminal_raw_hex'] = terminal.raw.hex()+ server.close()+ result['commands'] = server.commands+ result['fixture_errors'] = server.errors+ return result+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ receipt = {'scope': 'Real client binary against an isolated synthetic daemon; model compaction execution is covered by Rust tests.'}+ with tempfile.TemporaryDirectory(prefix='autocompact-check-') as directory:+ receipt['result'] = result = observe(Path(os.environ['PA_RUST_BINARY']).resolve(), Path(directory) / 'rust')+ receipt['passed'] = bool(result.get('executed') and not result['fixture_errors']+ and result.get('saved_percentage') == 100)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(receipt, indent=2) + '\n')+ print(json.dumps({'passed': receipt['passed'], 'error': result.get('error')}))+ return 0 if receipt['passed'] else 1+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/scripts/review_catalog_field_removal_parity.py b/scripts/check_catalog_field_removal.pysimilarity index 73%rename from scripts/review_catalog_field_removal_parity.pyrename to scripts/check_catalog_field_removal.pyindex eb7dfe16da..69285b906d 100644--- a/scripts/review_catalog_field_removal_parity.py+++ b/scripts/check_catalog_field_removal.py@@ -1,9 +1,8 @@#!/usr/bin/env python3-"""Actual unbounded catalog evidence for intentional allMessagesText removal.+"""Actual unbounded catalog evidence for the allMessagesText removal.-This is NOT whole-wire parity: pinned TS retains its transcript corpus; Rust-must omit the key in streamed and terminal rows. Remaining selected stable-fields match. No provider, kernel, create command or UI is exercised.+The key must be omitted in streamed and terminal rows; the selected stable+fields match the seeded sessions. No provider, kernel, create command or UI is exercised."""import argparseimport json@@ -13,9 +12,9 @@ import subprocessimport sysimport tempfile-from review_agent_bounce_parity import Client-from review_draft_disconnect_parity import digest, env_for, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+from check_agent_bounce import Client+from lifecycle_lib import digest, env_for+from lifecycle_lib import OwnedProcesses, TAG, finishCOUNT = 3BASE_MS = 1704067200000@@ -28,13 +27,11 @@ REMOVED = 'allMessagesText'def seed(root):directory = root / 'agent/sessions'directory.mkdir(parents=True, exist_ok=True)- expected, transcripts = [], {}+ expected = []for index in range(COUNT):ident = f'field-removal-{index}'name = f'Field removal row {index}'user = f'FIELD_REMOVAL_USER_{index}'- # Unicode and separate assistant text distinguish a real corpus from- # a first-message alias; exact comparison retains whitespace and text.assistant = f'FIELD_REMOVAL_ASSISTANT_{index} café 界'entries = [{'type': 'session', 'version': 3, 'id': ident, 'timestamp': STAMP,@@ -55,8 +52,7 @@ def seed(root):os.utime(path, ns=(ns, ns))assert path.stat().st_mtime_ns == ns, 'fixture lost deterministic mtime'expected.append(dict(zip(FIELDS, (path.name, ident, CWD, name, 2, user))))- transcripts[ident] = user + ' ' + assistant- return expected, transcripts+ return expecteddef stable_rows(rows, root):@@ -74,14 +70,10 @@ def stable_rows(rows, root):return sorted(values, key=lambda row: row['id'])-def check_rows(rows, kind, root, expected, transcripts):+def check_rows(rows, root, expected):assert stable_rows(rows, root) == sorted(expected, key=lambda row: row['id']), 'stable catalog fields differ'for row in rows:- if kind == 'ts':- assert REMOVED in row and row[REMOVED] == transcripts[row['id']], 'TS transcript corpus differs'- else:- assert kind == 'rust', 'unknown implementation'- assert REMOVED not in row, 'Rust must OMIT allMessagesText, not null or empty it'+ assert REMOVED not in row, 'allMessagesText must be OMITTED, not null or empty'class RawReader:@@ -118,10 +110,10 @@ class CatalogClient(Client):self.sock = RawSocket(self.sock, self.sent)-def validate(observed, kind, root, expected, transcripts):+def validate(observed, root, expected):frames, data = observed['frames'], observed['final_data']assert isinstance(data, dict), 'terminal data is not an object'- check_rows(data.get('sessions'), kind, root, expected, transcripts)+ check_rows(data.get('sessions'), root, expected)assert observed['raw_received_hex'] and observed['raw_sent_hex'], 'missing raw traffic'assert [json.loads(bytes.fromhex(line)) for line in observed['raw_received_hex']] == frames, 'raw/decoded traffic mismatch'final, = [frame for frame in frames if frame.get('type') == 'response']@@ -141,21 +133,21 @@ def validate(observed, kind, root, expected, transcripts):progress.append(frame)# Three small rows must all stream; no large-store/backpressure claim.assert progress, 'missing catalog progress'- check_rows(streamed, kind, root, expected, transcripts)+ check_rows(streamed, root, expected)return stable_rows(data['sessions'], root)-def observe(binary, kind, root, observed):- env = env_for(root, kind)+def observe(binary, root, observed):+ env = env_for(root)env[TAG] = str(root)(root / 'agent/settings.json').write_text(json.dumps({'prewarmPythonKernel': False, 'sessionArchiveMaxSessions': 'off','sessionArchiveMaxAgeDays': 'off', 'onboardingCompleted': True,'telemetry': {'noticeShown': True}}))- expected, transcripts = seed(root)+ expected = seed(root)observed['fixture'] = {'count': COUNT, 'mtime_base_ms': BASE_MS, 'mtime_step_ms': 10000,'archive_max_sessions': 'off', 'archive_max_age_days': 'off',- 'expected_stable_rows': expected, 'expected_ts_transcripts': transcripts}+ 'expected_stable_rows': expected}path = root / 'd.sock'scope = OwnedProcesses(binary, root, path)daemon = client = None@@ -173,7 +165,7 @@ def observe(binary, kind, root, observed):observed['frames'] = list(client.wire)observed['raw_received_hex'] = list(client.received)observed['raw_sent_hex'] = list(client.sent)- observed['stable_rows'] = validate(observed, kind, root, expected, transcripts)+ observed['stable_rows'] = validate(observed, root, expected)scope.discover()assert set(scope.targets) == set(scope.direct), 'catalog unexpectedly spawned worker/kernel'observed['behavior_verified'] = True@@ -188,27 +180,22 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', required=True, type=Path)args = parser.parse_args()- receipt = {'verified': False, 'scope': __doc__, 'runs': {},- 'intentional_difference': 'TS allMessagesText exact transcript text; Rust key absent in stream and final',+ receipt = {'verified': False, 'scope': __doc__,'normalization': 'owned path basename; compare rows by durable ID, not stream order',- 'not_verified': ['whole-wire equality (intentional field removal)', 'UI frames or input',+ 'not_verified': ['UI frames or input','performance or heap reduction', 'sidecar old/new compatibility (catalog-only CLI does not emit lease sidecars)','provider/kernel execution', 'large-store backpressure']}try:assert sys.platform == 'linux', 'hosted Linux only'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'TS archive digest mismatch'- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-cat-field-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = receipt['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed)- except Exception as error:- observed['error'] = f'{type(error).__name__}: {error}'- assert all(run.get('behavior_verified') and run.get('cleanup_verified')- and 'error' not in run for run in receipt['runs'].values()), 'actual field removal comparison failed'- assert receipt['runs']['ts']['stable_rows'] == receipt['runs']['rust']['stable_rows'], 'TS/Rust stable fields differ'+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = receipt['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ except Exception as error:+ observed['error'] = f'{type(error).__name__}: {error}'+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual field removal check failed'receipt['verified'] = Trueexcept Exception as error:receipt['error'] = f'{type(error).__name__}: {error}'diff --git a/scripts/review_client_write_cleanup_parity.py b/scripts/check_client_write_cleanup.pysimilarity index 77%rename from scripts/review_client_write_cleanup_parity.pyrename to scripts/check_client_write_cleanup.pyindex b522f00d71..c30301fbdc 100644--- a/scripts/review_client_write_cleanup_parity.py+++ b/scripts/check_client_write_cleanup.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Real TS/Rust #3602 half-close comparison, with an owned blocked provider.+"""Real-daemon #3602 half-close check, with an owned blocked provider.Only fixture-created daemon trees are stopped. Provider arrival, not elapsedsleep, proves the initial turn is busy and the queued prompt actually drains.@@ -15,8 +15,8 @@ import subprocessimport tempfileimport threading-from review_agent_bounce_parity import Client, Provider, Handler, LIMIT-from review_draft_disconnect_parity import digest, env_for, stop, TS_ARCHIVE_SHA256+from check_agent_bounce import Client, Provider, Handler, LIMIT+from lifecycle_lib import digest, env_for, stopFIRST = 'WRITE_CLEANUP_INITIAL_BUSY_TURN'SECOND = 'WRITE_CLEANUP_QUEUED_SECOND_CLIENT'@@ -112,25 +112,11 @@ def settle_owned_processes(root, observed):raise RuntimeError('owned fixture processes survived shutdown: ' + str(remaining))-def canonical(value):- """The pause lease is the only generated value in the compared responses."""- if isinstance(value, dict):- return {key: '<pause-id>' if key == 'pauseId' else canonical(item)- for key, item in value.items()}- if isinstance(value, list):- return [canonical(item) for item in value]- return value---def validate_rename_trigger(kind, data, active):- """Pin the existing fixture-only response deviation, without hiding others."""- if kind == 'ts':- assert data is None, 'TS rename trigger unexpectedly returned response data'- else:- assert isinstance(data, dict), 'Rust rename trigger omitted its existing summary'- assert data.get('activeSessionId') == active, 'Rust rename summary changed session identity'- assert data.get('sessionName') == 'Write cleanup fixture', 'Rust rename summary has wrong name'- assert isinstance(data.get('workerPid'), int), 'Rust rename summary omitted worker identity'+def validate_rename_trigger(data, active):+ assert isinstance(data, dict), 'rename trigger omitted its session summary'+ assert data.get('activeSessionId') == active, 'rename summary changed session identity'+ assert data.get('sessionName') == 'Write cleanup fixture', 'rename summary has wrong name'+ assert isinstance(data.get('workerPid'), int), 'rename summary omitted worker identity'def pause_released(client, active, pause_id):@@ -145,8 +131,8 @@ def pause_released(client, active, pause_id):return False-def run_case(binary, kind, root, observed):- env = env_for(root, kind)+def run_case(binary, root, observed):+ env = env_for(root)provider = Provider()provider.RequestHandlerClass = CompletionHandlerthreading.Thread(target=provider.serve_forever, daemon=True).start()@@ -191,13 +177,13 @@ def run_case(binary, kind, root, observed):before = b.call('get_state', activeSessionId=active)assert before['attachedClients'] == 1, beforeassert not pause_released(b, active, pause_id), 'pause was not held before disconnect'- # TS rejects new input while a pause is held. A rename is a legal- # non-input action and publishes the attached event that must fail its- # write to A; A keeps its write half open, so no read EOF can clean up.+ # A rename is a legal non-input action while a pause is held; it publishes+ # the attached event that must fail its write to A. A keeps its write half+ # open, so no read EOF can clean up.a.sock.shutdown(socket.SHUT_RD)trigger = observed['rename_trigger_response'] = b.call('set_session_name',activeSessionId=active, name='Write cleanup fixture')- validate_rename_trigger(kind, trigger, active)+ validate_rename_trigger(trigger, active)deadline = time.monotonic() + LIMITobservations = observed['disconnect_observations'] = []while True:@@ -221,7 +207,7 @@ def run_case(binary, kind, root, observed):responses['settle_second_client'] = b.call('wait_for_idle', activeSessionId=active)responses['queue_after_drain'] = b.call('get_queue', activeSessionId=active)assert responses['queue_after_drain'] == {'steering': [], 'followUp': []}, responses- observed['canonical_action_responses'] = canonical(responses)+ observed['action_responses'] = responsesobserved['hello'] = observer.helloobserved['provider_requests'] = provider.requestsexcept Exception as error:@@ -234,7 +220,7 @@ def run_case(binary, kind, root, observed):if process and process.poll() is None and clients:try:clients[0].call('shutdown', force=True)- # TS net.Server.close waits for every fixture peer to close.+ # The daemon's close waits for every fixture peer to close.# The SECOND provider-arrival proof already finished above.for client in clients:client.close()@@ -272,24 +258,15 @@ def main():parser = argparse.ArgumentParser()parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- receipt = {'scenario': 'client_write_cleanup', 'verified': False, 'cases': {},+ receipt = {'scenario': 'client_write_cleanup', 'verified': False,'scope': 'real attached-client read-half-close, rename triggers failed write, observed detach and non-owner pause-release probe, then second-client queue drain',- 'preexisting_admission_difference': 'TS rejects new prompt admission while a pause is held; fixture submits followUp only after disconnect cleanup, without redesigning Rust policy',- 'normalization': 'only generated pauseId in compared cleanup/pause/queued-delivery action response data; raw JSONL preserved',- 'fixture_trigger_response_deviation': 'Existing set_session_name returns no data in TS and a full session summary in Rust. Both expected shapes are asserted and their complete responses preserved separately; rename payload parity is outside this cleanup change.','not_covered': 'admission cancellation races or direct worker attach-state introspection'}try:- archive = Path(os.environ['PA_TS_ARCHIVE'])- assert digest(archive) == TS_ARCHIVE_SHA256, 'TS archive digest mismatch'- receipt['ts_archive_sha256'] = digest(archive)with tempfile.TemporaryDirectory(prefix='pa-write-cleanup-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ['PA_' + kind.upper() + '_BINARY']).resolve()- receipt[kind + '_binary_sha256'] = digest(binary)- observed = receipt['cases'][kind] = {}- run_case(binary, kind, Path(folder) / kind, observed)- assert receipt['cases']['ts']['canonical_action_responses'] == receipt['cases']['rust']['canonical_action_responses'], 'changed-action wire response data differs'- assert receipt['cases']['ts']['before_provider_release'] == receipt['cases']['rust']['before_provider_release'], 'queued input shape differs'+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ receipt['binary_sha256'] = digest(binary)+ observed = receipt['case'] = {}+ run_case(binary, Path(folder) / 'rust', observed)receipt['verified'] = Trueexcept Exception as error:receipt['error'] = str(error)diff --git a/scripts/review_custom_ca_parity.py b/scripts/check_custom_ca.pysimilarity index 85%rename from scripts/review_custom_ca_parity.pyrename to scripts/check_custom_ca.pyindex 279f59767c..c46126166f 100644--- a/scripts/review_custom_ca_parity.py+++ b/scripts/check_custom_ca.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Hosted-only real TS/Rust HTTPS custom-root and unknown-issuer comparison.+"""Hosted-only real HTTPS custom-root and unknown-issuer check.The provider and private CA are synthetic, loopback-only and fixture-owned.This verifies provider transport, not native OS loading, catalog/OAuth clients,@@ -18,10 +18,9 @@ import tempfileimport threadingimport time-from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256-from review_restore_notice_parity import texts-from review_agent_bounce_parity import Client-from review_draft_disconnect_parity import stop+from lifecycle_lib import digest, stop+from check_restore_notice import texts+from check_agent_bounce import ClientPROMPT = 'Complete the custom CA transport fixture.'ANSWER = 'Custom CA transport completed.'@@ -166,14 +165,12 @@ def request_contract(request):'current_prompt': PROMPT, 'current_prompt_count': count}-def run_case(binary, label, root, trusted, key, cert, ca_cert, unrelated, observation):+def run_case(binary, root, trusted, key, cert, ca_cert, unrelated, observation):for name in ('home', 'agent', 'sessions', 'work', 'tmp'):(root / name).mkdir(parents=True)agent, sessions, cwd = root / 'agent', root / 'sessions', root / 'work'env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ','PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}- if label == 'ts':- env['PI_PACKAGE_DIR'] = os.environ['PI_PACKAGE_DIR']env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1',PI_OFFLINE='1', PI_CODING_AGENT_DIR=str(agent), PRIME_AGENT_CODING_AGENT_DIR=str(agent),PI_SESSION_DIR=str(sessions), PRIME_AGENT_SESSION_DIR=str(sessions),@@ -277,37 +274,23 @@ def main():parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()result = {'verified': False, 'runs': {}, 'scope': __doc__,- 'retry_scope': 'Set documented retry.enabled=false identically in both real runtimes; compare certificate outcome, not retry policy.',- 'dependency_scope': 'Warm ordinary startup get_commands before admission in both binaries. Cold lazy-first-prompt duplicate remains an unresolved dependency on #3560; no prompt deduplication or production repair in this TLS PR.',+ 'retry_scope': 'Set documented retry.enabled=false; check certificate outcome, not retry policy.','execution_scope': 'Explicit owned daemon, ordinary create/attach/get_commands/prompt_and_wait/get_messages, graceful shutdown acknowledgement then close socket before waiting.',- 'prompt_scope': 'Compare current fixture prompt once, auth, model, stream and outcome. Harness digests/unrelated layers excluded; raw messages retained.',- 'cache_scope': 'Each case starts a fresh actual process. No assertion about in-process native-store refresh or TS native-root caching.'}+ 'prompt_scope': 'Check current fixture prompt once, auth, model, stream and outcome. Raw messages retained.',+ 'cache_scope': 'Each case starts a fresh actual process. No assertion about in-process native-store refresh.'}try:assert sys.platform == 'linux', 'requires hosted Linux CI'- archive_hash = sha256(os.environ['PA_TS_ARCHIVE'])- assert archive_hash == TS_ARCHIVE_SHA256, 'pinned TS archive mismatch'- binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- for label in ('ts', 'rust')}- result.update(ts_release_archive_sha256=archive_hash,- binaries={label: {'path': str(path), 'sha256': sha256(path)}- for label, path in binaries.items()})- with tempfile.TemporaryDirectory(prefix='custom-ca-parity-') as temporary:+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ result['binary'] = {'path': str(binary), 'sha256': digest(binary)}+ with tempfile.TemporaryDirectory(prefix='custom-ca-check-') as temporary:root = Path(temporary)ca_key, ca_cert = certificate(root, 'trusted')key, cert = server_certificate(root, ca_key, ca_cert)_, unrelated = certificate(root, 'unrelated')for scenario, trusted in [('trusted_custom_ca', True), ('untrusted_custom_ca', False)]:- runs = result['runs'][scenario] = {}- for label, binary in binaries.items():- observation = runs[label] = {}- try:- observation['contract'] = run_case(binary, label, root / scenario / label,- trusted, key, cert, ca_cert, unrelated, observation)- except Exception as error:- observation['error'] = str(error)- errors = {label: run['error'] for label, run in runs.items() if 'error' in run}- assert not errors, errors- assert runs['ts']['contract'] == runs['rust']['contract'], scenario + ' contract mismatch'+ observation = result['runs'][scenario] = {}+ observation['contract'] = run_case(binary, root / scenario, trusted, key, cert, ca_cert,+ unrelated, observation)result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/check_dead_child_delete.py b/scripts/check_dead_child_delete.pynew file mode 100644index 0000000000..1180ac4b70--- /dev/null+++ b/scripts/check_dead_child_delete.py@@ -0,0 +1,144 @@+#!/usr/bin/env python3+"""Hosted real RLM child deletion and idempotent retry.++A real kernel admits a child whose model request is held. The ordinary daemon+kill command closes the separate child worker and removes its projection;+rlmLedgerDelete persists the edge boundary, and a retry leaves it unchanged.+The dead-PID and interrupted-cleanup branches are separately exercised by hosted+Unix supervisor regressions; this fixture does not manufacture a process death.+"""+import argparse+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import threading+import time++from check_ledger_liveness import Provider, PARENT, NAME+from check_agent_bounce import Client+from lifecycle_lib import digest, env_for+from lifecycle_lib import OwnedProcesses, TAG, finish, verify_worker, process_identity+++def delete_contract(rows, child_id):+ deletes = [row for row in rows if row.get('op') == 'delete' and row.get('childId') == child_id]+ assert deletes, 'the actual child deletion did not persist its boundary'+ assert all(row.get('reason') == 'user' for row in deletes), deletes+ return deletes+++def observe(binary, root, observed):+ env = env_for(root)+ env[TAG] = str(root)+ provider = Provider()+ threading.Thread(target=provider.serve_forever, daemon=True).start()+ (root / 'agent/models.json').write_text(json.dumps({'providers': {'parity-local': {+ 'api': 'openai-completions', 'apiKey': 'fixture-only',+ 'baseUrl': f'http://127.0.0.1:{provider.server_port}/v1', 'models': [{+ 'id': 'parity-1', 'name': 'Parity 1', 'reasoning': False,+ 'contextWindow': 128000, 'maxTokens': 4096}]}}}))+ (root / 'agent/settings.json').write_text(json.dumps({'prewarmPythonKernel': False,+ 'defaultProvider': 'parity-local', 'defaultModel': 'parity-1'}))+ path = root / 'd.sock'+ scope = OwnedProcesses(binary, root, path)+ daemon = control = None+ log = open(root / 'daemon.log', 'wb')+ try:+ command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(path)]+ daemon = subprocess.Popen(command, cwd=root, env=env, stdout=log,+ stderr=subprocess.STDOUT, start_new_session=True)+ scope.register(daemon, command)+ control = Client(path, daemon)+ created = control.call('create', config={'cwd': str(root), 'agentDir': str(root / 'agent'),+ 'provider': 'parity-local', 'model': 'parity-1', 'telemetryDisabled': True})+ active = created.get('activeSessionId') or created.get('id')+ assert active, created+ control.call('attach', activeSessionId=active)+ control.call('prompt', activeSessionId=active, message=PARENT)+ child_id = provider.ready()['child_id']+ listed = control.call('list', all=True)+ rows = [r for r in listed['sessions'] if r.get('rlmChildId') == child_id]+ assert len(rows) == 1 and rows[0].get('sessionName') == NAME, rows+ row = rows[0]+ child_active = row.get('activeSessionId') or row.get('id')+ assert child_active and row.get('parentActiveSessionId') == active, row+ observed['child_before'] = row+ descriptors = [json.loads(p.read_text()) for p in (root / 'agent/daemon-workers').rglob('*.json')]+ child_descriptors = [d for d in descriptors if d.get('rootActiveSessionId') == child_active]+ assert len(child_descriptors) == 1, child_descriptors+ pid, identity = verify_worker(child_descriptors[0], child_active, binary, path)+ scope.discover()+ observed['child_process_identity'] = {'pid': pid, 'start_id': identity}+ payload = {'activeSessionId': child_active, 'rlmLedgerDelete': 'user', 'rlmChildId': child_id}+ observed['delete_response'] = control.call('kill', **payload)+ after_list = control.call('list', all=True)+ observed['sessions_after'] = after_list+ assert not any(r.get('activeSessionId') == child_active for r in after_list['sessions']), after_list+ observed['child_session_closed'] = True+ deadline = time.monotonic() + 15+ while True:+ try:+ current, state = process_identity(pid)+ stopped = current != identity or state == 'Z'+ except FileNotFoundError:+ stopped = True+ if stopped:+ break+ assert time.monotonic() < deadline, 'actual child worker did not exit after kill'+ threading.Event().wait(0.025)+ observed['child_worker_stopped'] = True+ def ledger():+ return [json.loads(line) for p in (root / 'agent/rlm-ledger').glob('*.jsonl')+ for line in p.read_text().splitlines()]+ observed['ledger_after'] = ledger()+ boundary = delete_contract(observed['ledger_after'], child_id)+ assert len(boundary) == 1, 'expected exactly one original deletion boundary'+ observed['retry_response'] = control.call('kill', **payload)+ observed['ledger_after_retry'] = ledger()+ # No second deletion boundary; usage amendments, if any, retain+ # their actual rows and are not normalized out of this count.+ after = delete_contract(observed['ledger_after_retry'], child_id)+ assert after == boundary, 'idempotent retry changed the original boundary'+ observed['behavior_verified'] = True+ finally:+ observed['wire'] = list(control.wire) if control else []+ observed['provider_requests'] = provider.requests+ provider.release.set()+ finish(scope, control, daemon, observed)+ log.close()+ observed['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')[-10000:]+ provider.shutdown()+ provider.server_close()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ result = {'verified': False, 'scope': __doc__, 'not_verified': [+ 'dead PID and interrupted cleanup (hosted Unix supervisor tests)',+ 'parent kernel registry removal', 'TUI']}+ try:+ assert sys.platform == 'linux'+ with tempfile.TemporaryDirectory(prefix='pa-ddelete-', dir='/tmp') as folder:+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = result['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ except Exception as error:+ observed['error'] = str(error)+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual delete verification failed'+ result['verified'] = True+ except Exception as error:+ result['error'] = str(error)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(result, ensure_ascii=False, indent=2))+ return 0 if result['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/review_dock_events_parity.py b/scripts/check_dock_events.pysimilarity index 70%rename from scripts/review_dock_events_parity.pyrename to scripts/check_dock_events.pyindex 8a90e22ab8..f22f616c17 100644--- a/scripts/review_dock_events_parity.py+++ b/scripts/check_dock_events.py@@ -1,12 +1,10 @@#!/usr/bin/env python3-"""Hosted actual TS/Rust TUI dock reactions, styled frames and raw ANSI.+"""Hosted actual TUI dock reactions, styled frames and raw ANSI.-Both ordinary clients receive controlled protocol-7 roster/goal events after-observable attach. No headless flags, provider or live sessions are used. The-receipt records full-frame differences instead of normalizing TS's boxed dock-into Rust's one-line dock, which expands into per-group rows on focus.-Behavioral assertions cover event-driven refresh; full-frame/style equality is-reported separately and never claimed by them.+The ordinary client receives controlled protocol-7 roster/goal events after+observable attach. No headless flags, provider or live sessions are used.+Behavioral assertions cover event-driven refresh of the one-line dock, which+expands into per-group rows on focus, and the live title cost."""import argparseimport json@@ -17,10 +15,8 @@ import sysimport tempfileimport threading-from review_dock_screen import DockScreen-from review_draft_disconnect_parity import (- Supervisor, Terminal, actual_hello, digest, env_for, TS_ARCHIVE_SHA256,-)+from lifecycle_lib import DockScreen+from lifecycle_lib import Supervisor, Terminal, actual_hello, digest, env_fordef parent():@@ -55,9 +51,8 @@ class DockSupervisor(Supervisor):def send(self, sock, data):if data.get('type') == 'daemon_hello':- # The inherited draft fixture advertises only prompt admission.- # This fixture also implements roster snapshot/deltas; TS gates- # both on agent_roster (pinned daemon-protocol.ts:798,1214).+ # The base fixture advertises only prompt admission. This fixture+ # also implements roster snapshot/deltas, gated on agent_roster.data = dict(data, serverCapabilities=['session_input_admission', 'agent_roster'])elif data.get('type') == 'response' and data.get('command') == 'roster_subscribe':data = dict(data, data={'roster': self.roster})@@ -66,8 +61,8 @@ class DockSupervisor(Supervisor):data['data']['snapshot']['summary'].update(sessionId='fixture-durable',activeSessionId='s1', sessionFile='/fixture/root.jsonl', sessionName='Dock fixture')elif data.get('type') == 'response' and data.get('command') == 'get_context_tree':- # TS's top bar reads the context tree, whereas Rust reads roster- # usage. Both protocol views must describe the same fixture family.+ # The top bar reads roster usage; the context tree must describe+ # the same fixture family.children = [{'id': row['summary']['sessionId'], 'label': row['agentId'],'status': 'active' if row['status'] == 'running' else 'completed',@@ -107,19 +102,13 @@ class DockSupervisor(Supervisor):'timeUsedSeconds': 12, 'continuationsUsed': 0}}})-def running_visible(text, kind, count, expanded=False):- # Rust's collapsed dock reads "N subagent(s)"; its focused (expanded) dock's- # subagents row reads the "N running · …" breakdown, like TS's box.- label = 'running' if kind == 'ts' or expanded else 'subagents?'+def running_visible(text, count, expanded=False):+ # The collapsed dock reads "N subagent(s)"; the focused (expanded) dock's+ # subagents row reads the "N running · …" breakdown.+ label = 'running' if expanded else 'subagents?'return re.search(r'(?<!\d)' + str(count) + r'\s+' + label + r'\b', text) is not None-def ts_dock_visible(text):- # The actual TS dock header, not an arbitrary occurrence of "subagents":- # its optional-ripgrep startup warning mentions that word after removal.- return re.search(r'^\s*╭─\s+subagents\b', text, re.MULTILINE) is not None--def visible_cost(text):costs = re.findall(r'\$(\d+\.\d{2})(?!\d)', text)assert len(costs) == 1, 'fixture frame must paint one unambiguous title cost'@@ -142,9 +131,9 @@ def capture(terminal, root, offset):'unsupported_terminal': terminal.screen.unsupported_terminal.copy()}-def run_case(binary, kind, root, observed):+def run_case(binary, root, observed):root.mkdir()- env = env_for(root, kind)+ env = env_for(root)hello = actual_hello(binary, root, env)server = DockSupervisor(root / 'fixture.sock', hello, root)terminal = None@@ -169,21 +158,17 @@ def run_case(binary, kind, root, observed):terminal.wait(name + ' stable dock', ready, server)observed['frames'][name] = capture(terminal, root, offset)offset = len(terminal.raw)- snap('snapshot', lambda text: server.attaches >= 1 and running_visible(text, kind, 1) and '$0.42' in text)+ snap('snapshot', lambda text: server.attaches >= 1 and running_visible(text, 1) and '$0.42' in text)server.roster_delta([child('c2', 'running', 0.49)])- # Pinned TS refreshTopBarCost fetches on initial bind/turn-end/status,- # not roster-only updates (interactive-mode.ts:1899,5771,6326). Do not- # invent a turn-end event to make its cached title match Rust's live one.- ts_cached_cost = '0.42'- snap('roster_added', lambda text: running_visible(text, kind, 2)- and cost_ready(text, ts_cached_cost if kind == 'ts' else '0.91'))+ snap('roster_added', lambda text: running_visible(text, 2)+ and cost_ready(text, '0.91'))server.goal('active')snap('goal_active', lambda text: 'Pursuing goal (12s)' in text)before_focus = terminal.screen.dock_styles()terminal.send('\x1b[B') # Same ordinary Down key from an empty editor.terminal.wait('dock focus changes rendered attributes',lambda: terminal.screen.dock_styles() != before_focus, server)- snap('dock_focused', lambda text: running_visible(text, kind, 2, expanded=True))+ snap('dock_focused', lambda text: running_visible(text, 2, expanded=True))assert observed['frames']['dock_focused']['dock_styled_rows'] != before_focusterminal.send('\x1b')terminal.wait('Escape restores editor focus', lambda: terminal.screen.dock_styles() == before_focus, server)@@ -192,13 +177,13 @@ def run_case(binary, kind, root, observed):terminal.send('\x15') # Clear draft without submitting a prompt.terminal.wait('draft cleared', lambda: 'DOCK_EDITOR_FOCUS_PROBE' not in terminal.screen.text(), server)server.roster_delta([child('c1', 'idle', 0.42)], removed=['c2'])- snap('child_settled', lambda text: running_visible(text, kind, 0) and '$0.42' in text)+ snap('child_settled', lambda text: running_visible(text, 0) and '$0.42' in text)server.roster_delta([], removed=['c1'])- snap('child_removed', lambda text: cost_ready(text, ts_cached_cost if kind == 'ts' else '0.00')- and (not ts_dock_visible(text) if kind == 'ts' else running_visible(text, kind, 0)))+ snap('child_removed', lambda text: cost_ready(text, '0.00')+ and running_visible(text, 0))server.roster_delta([parent(), child('c3', 'running', 0.73)], resync=True)- snap('roster_restored', lambda text: running_visible(text, kind, 1)- and cost_ready(text, ts_cached_cost if kind == 'ts' else '0.73'))+ snap('roster_restored', lambda text: running_visible(text, 1)+ and cost_ready(text, '0.73'))server.goal('paused')snap('goal_paused', lambda text: 'Goal paused (12s)' in text)assert not server.prompts, 'focus interactions accidentally submitted a prompt'@@ -208,9 +193,7 @@ def run_case(binary, kind, root, observed):expected_costs = {'snapshot': '0.42', 'roster_added': '0.91', 'goal_active': '0.91','dock_focused': '0.91', 'editor_restored': '0.91', 'child_settled': '0.42','child_removed': '0.00', 'roster_restored': '0.73', 'goal_paused': '0.73'}- if kind == 'ts':- expected_costs = {phase: ts_cached_cost for phase in expected_costs}- assert observed['title_costs'] == expected_costs, 'actual title cost reaction differs from pinned source'+ assert observed['title_costs'] == expected_costs, 'actual title cost reaction differs'observed['behavior_verified'] = Truefinally:try:@@ -233,30 +216,19 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- receipt = {'verified': False, 'runs': {}, 'scope': __doc__,+ receipt = {'verified': False, 'scope': __doc__,'frame_scope': '120x40 decoded text + dock SGR cells and complete raw ANSI, not pixels/font rendering.',- 'preexisting_ts_limitation': 'Pinned TS uses a boxed running/idle/inactive dock; Rust uses a one-line fixed-group dock that expands into per-group rows on focus. Layouts are not normalized into equality.',- 'preexisting_cost_difference': 'TS binds initial family cost from get_context_tree and does not refresh it on roster-only events. Rust refreshes cost from the live roster. Exact phase costs asserted and retained without normalization or synthetic refresh events.',- 'not_verified': ['frame/style equality', 'actual daemon roster production', 'new-session/no-session fallback', 'agents-view lazy query search']}+ 'not_verified': ['actual daemon roster production', 'new-session/no-session fallback', 'agents-view lazy query search']}try:assert sys.platform == 'linux', 'hosted Linux binary fixture only'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'TS archive mismatch'- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-dock-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ['PA_' + kind.upper() + '_BINARY']).resolve()- observed = receipt['runs'][kind] = {'binary_sha256': digest(binary)}- try:- run_case(binary, kind, Path(folder) / kind, observed)- except Exception as error:- observed['error'] = str(error)- assert all('error' not in run for run in receipt['runs'].values()), 'actual binary scenario failed'- frames = receipt['runs']['ts']['frames']- assert frames.keys() == receipt['runs']['rust']['frames'].keys(), 'different phases executed'- receipt['frame_diffs'] = {phase: {- 'text_equal': frame['text'] == receipt['runs']['rust']['frames'][phase]['text'],- 'dock_attributes_equal': frame['dock_styled_rows'] == receipt['runs']['rust']['frames'][phase]['dock_styled_rows']}- for phase, frame in frames.items()}+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = receipt['run'] = {'binary_sha256': digest(binary)}+ try:+ run_case(binary, Path(folder) / 'rust', observed)+ except Exception as error:+ observed['error'] = str(error)+ assert 'error' not in observed, 'actual binary scenario failed'receipt['verified'] = True # Only the explicitly scoped reaction assertions.except Exception as error:receipt['error'] = str(error)diff --git a/scripts/review_factory_navigation_parity.py b/scripts/check_factory_navigation.pysimilarity index 76%rename from scripts/review_factory_navigation_parity.pyrename to scripts/check_factory_navigation.pyindex 85e35f1eba..3658cc08ee 100644--- a/scripts/review_factory_navigation_parity.py+++ b/scripts/check_factory_navigation.py@@ -1,9 +1,8 @@#!/usr/bin/env python3-"""Hosted actual Rust factory Left/Right navigation with raw PTY evidence.+"""Hosted actual factory Left/Right navigation with raw PTY evidence.-Pinned TS daemon capability absence is recorded explicitly: there is no factory-page counterpart. A protocol fixture supplies one real-shaped run; actual Rust-input parsing, view rendering and fallback keys execute unchanged.+A protocol fixture supplies one real-shaped run; actual input parsing, view+rendering and fallback keys execute unchanged."""import argparseimport copy@@ -16,10 +15,10 @@ import sysimport tempfileimport time-from review_agent_bounce_parity import Client-from review_dock_screen import DockScreen-from review_draft_disconnect_parity import Supervisor, Terminal, digest, env_for, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+from check_agent_bounce import Client+from lifecycle_lib import DockScreen+from lifecycle_lib import Supervisor, Terminal, digest, env_for+from lifecycle_lib import OwnedProcesses, TAG, finishRUN = 'factory-navigation-run'GRAPH = {'runs': [{'run_id': RUN, 'spec_id': 'navigation-fixture', 'name': RUN,@@ -65,15 +64,11 @@ def factory_click(screen):raise AssertionError('factory dock click target absent')-def observe(binary, kind, root, observed):- env = env_for(root, kind)+def observe(binary, root, observed):+ env = env_for(root)env[TAG] = str(root)discovered = observed['hello_discovery'] = {}actual = hello(binary, root, env, discovered)- if kind == 'ts':- assert 'factory_activity' not in actual.get('serverCapabilities', []), actual- observed.update(behavior_verified=True, cleanup_verified=True)- returnserver = FactorySupervisor(root / 'ui.sock', actual, 'factory-navigation', root)scope = OwnedProcesses(binary, root, server.path)terminal = None@@ -133,23 +128,20 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', required=True, type=Path)args = parser.parse_args()- receipt = {'verified': False, 'scope': __doc__, 'runs': {}, 'not_verified': [- 'TS factory frame equality (no historical counterpart)', 'real factory execution',+ receipt = {'verified': False, 'scope': __doc__, 'not_verified': [+ 'real factory execution','rebound keybindings (unit regression)', 'action execution after Right confirmation']}try:assert sys.platform == 'linux', 'hosted Linux only'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-fnav-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = receipt['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed)- except Exception as error:- observed['error'] = str(error)- assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r- for r in receipt['runs'].values()), 'actual factory navigation failed'+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = receipt['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ except Exception as error:+ observed['error'] = str(error)+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual factory navigation failed'receipt['verified'] = Trueexcept Exception as error:receipt['error'] = str(error)diff --git a/scripts/review_factory_resumption_parity.py b/scripts/check_factory_resumption.pysimilarity index 67%rename from scripts/review_factory_resumption_parity.pyrename to scripts/check_factory_resumption.pyindex 090dc8211e..41514b70aa 100644--- a/scripts/review_factory_resumption_parity.py+++ b/scripts/check_factory_resumption.py@@ -1,9 +1,8 @@#!/usr/bin/env python3-"""Hosted real-daemon factory recovery receipt; TS has no advertised factory lane.+"""Hosted real-daemon factory recovery receipt.-The Rust kernel runs a real factory child, fails its declared JSON output,-resumes the same entry, and binds the second child's valid output. Historical-TS absence is scoped to its actual capability advertisement, not full parity.+The kernel runs a real factory child, fails its declared JSON output,+resumes the same entry, and binds the second child's valid output."""import argparseimport http.server@@ -16,10 +15,10 @@ import tempfileimport threadingimport time-from review_kernel_env_parity import KernelClient as Client-from review_draft_disconnect_parity import digest, env_for, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish-from review_restore_notice_parity import texts+from check_kernel_env import KernelClient as Client+from lifecycle_lib import digest, env_for+from lifecycle_lib import OwnedProcesses, TAG, finish+from check_restore_notice import textsMARKER = 'FACTORY_RECOVERY_RESULT='CELL = '''import asyncio, json, time@@ -115,8 +114,8 @@ def validate(probe):assert node['status'] == 'done', node-def observe(binary, kind, root, observed):- env = env_for(root, kind)+def observe(binary, root, observed):+ env = env_for(root)env[TAG] = str(root)server = Provider()threading.Thread(target=server.serve_forever, daemon=True).start()@@ -139,41 +138,36 @@ def observe(binary, kind, root, observed):scope.register(daemon, command)control = Client(path, daemon)observed['hello'] = control.hello- caps = control.hello.get('serverCapabilities', [])- if kind == 'ts':- assert 'factory_activity' not in caps, 'TS unexpectedly advertises factory'- observed['factory_lane_advertised'] = False- else:- created = control.call('create', config={'cwd': str(root), 'agentDir': str(root / 'agent'),- 'provider': 'parity-local', 'model': 'parity-1', 'telemetryDisabled': True,- 'noExtensions': True, 'noContextFiles': True})- active = created.get('activeSessionId') or created.get('id')- assert active, created- control.call('attach', activeSessionId=active)- control.call('prompt', activeSessionId=active, message='Run FACTORY_PARENT_PROBE')- control.call('wait_for_idle', timeout_seconds=120, activeSessionId=active)- started = extract(server.parent_requests[:2])- observed['started'] = started- run_id = started['run_id']- def settled():- snapshots = []- deadline = time.monotonic() + 60- while time.monotonic() < deadline:- status = control.call('factory_activity', activeSessionId=active,- action='status', runId=run_id)- snapshots.append(status)- if status['state'] != 'running':- return status- threading.Event().wait(0.025)- observed.setdefault('timed_out_snapshots', []).extend(snapshots)- raise AssertionError('factory did not leave running after parent turn completed')- paused = settled()- assert paused['state'] == 'paused', paused- observed['resume_response'] = control.call('factory_activity', activeSessionId=active,- action='resume', runId=run_id)- observed['probe'] = {'paused': paused, 'done': settled()}- validate(observed['probe'])- assert len(server.child_requests) == 3, 'not two producer attempts plus one guarded verifier'+ created = control.call('create', config={'cwd': str(root), 'agentDir': str(root / 'agent'),+ 'provider': 'parity-local', 'model': 'parity-1', 'telemetryDisabled': True,+ 'noExtensions': True, 'noContextFiles': True})+ active = created.get('activeSessionId') or created.get('id')+ assert active, created+ control.call('attach', activeSessionId=active)+ control.call('prompt', activeSessionId=active, message='Run FACTORY_PARENT_PROBE')+ control.call('wait_for_idle', timeout_seconds=120, activeSessionId=active)+ started = extract(server.parent_requests[:2])+ observed['started'] = started+ run_id = started['run_id']+ def settled():+ snapshots = []+ deadline = time.monotonic() + 60+ while time.monotonic() < deadline:+ status = control.call('factory_activity', activeSessionId=active,+ action='status', runId=run_id)+ snapshots.append(status)+ if status['state'] != 'running':+ return status+ threading.Event().wait(0.025)+ observed.setdefault('timed_out_snapshots', []).extend(snapshots)+ raise AssertionError('factory did not leave running after parent turn completed')+ paused = settled()+ assert paused['state'] == 'paused', paused+ observed['resume_response'] = control.call('factory_activity', activeSessionId=active,+ action='resume', runId=run_id)+ observed['probe'] = {'paused': paused, 'done': settled()}+ validate(observed['probe'])+ assert len(server.child_requests) == 3, 'not two producer attempts plus one guarded verifier'observed['behavior_verified'] = Truefinally:observed['provider_requests'] = server.requests@@ -189,23 +183,20 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'verified': False, 'scope': __doc__, 'runs': {}, 'not_verified': [- 'TS factory behavior (no advertised historical counterpart)', 'TUI',+ result = {'verified': False, 'scope': __doc__, 'not_verified': [+ 'TUI','worker-death respawn (separate executor regression)', 'pause/stop races (separate regressions)']}try:assert sys.platform == 'linux', 'hosted Linux only'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256- result['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-factory-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = result['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed)- except Exception as error:- observed['error'] = str(error)- assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r- for r in result['runs'].values()), 'actual factory observation failed'+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = result['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ except Exception as error:+ observed['error'] = str(error)+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual factory observation failed'result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_factory_validation_parity.py b/scripts/check_factory_validation.pysimilarity index 73%rename from scripts/review_factory_validation_parity.pyrename to scripts/check_factory_validation.pyindex b123a05f61..32b60d0bd0 100644--- a/scripts/review_factory_validation_parity.py+++ b/scripts/check_factory_validation.py@@ -1,8 +1,7 @@#!/usr/bin/env python3"""Hosted actual factory harness validator API receipt.-Rust executes real harness writes through its kernel. Historical TS absence-is scoped to its actual capability advertisement, not full behavior parity.+The binary executes real harness writes through its kernel."""import argparseimport http.server@@ -14,10 +13,10 @@ import sysimport tempfileimport threading-from review_kernel_env_parity import KernelClient as Client-from review_draft_disconnect_parity import digest, env_for, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish-from review_restore_notice_parity import texts+from check_kernel_env import KernelClient as Client+from lifecycle_lib import digest, env_for+from lifecycle_lib import OwnedProcesses, TAG, finish+from check_restore_notice import textsMARKER = 'FACTORY_VALIDATION_RESULT='CELL = '''import json@@ -104,8 +103,8 @@ def validate(probe):assert 'retries must be an integer between 0 and 10' in malformed['error'], malformed-def observe(binary, kind, root, observed):- env = env_for(root, kind)+def observe(binary, root, observed):+ env = env_for(root)env[TAG] = str(root)server = Provider()threading.Thread(target=server.serve_forever, daemon=True).start()@@ -127,21 +126,16 @@ def observe(binary, kind, root, observed):scope.register(daemon, command)control = Client(path, daemon)observed['hello'] = control.hello- caps = control.hello.get('serverCapabilities', [])- if kind == 'ts':- assert 'factory_activity' not in caps, 'TS unexpectedly advertises factory'- observed['factory_lane_advertised'] = False- else:- created = control.call('create', config={'cwd': str(root), 'agentDir': str(root / 'agent'),- 'provider': 'parity-local', 'model': 'parity-1', 'telemetryDisabled': True})- active = created.get('activeSessionId') or created.get('id')- assert active, created- control.call('attach', activeSessionId=active)- control.call('prompt', activeSessionId=active, message='Run FACTORY_VALIDATION_PARENT')- control.call('wait_for_idle', timeout_seconds=120, activeSessionId=active)- observed['probe'] = extract(server.parent_requests)- validate(observed['probe'])- assert not server.errors, server.errors+ created = control.call('create', config={'cwd': str(root), 'agentDir': str(root / 'agent'),+ 'provider': 'parity-local', 'model': 'parity-1', 'telemetryDisabled': True})+ active = created.get('activeSessionId') or created.get('id')+ assert active, created+ control.call('attach', activeSessionId=active)+ control.call('prompt', activeSessionId=active, message='Run FACTORY_VALIDATION_PARENT')+ control.call('wait_for_idle', timeout_seconds=120, activeSessionId=active)+ observed['probe'] = extract(server.parent_requests)+ validate(observed['probe'])+ assert not server.errors, server.errorsobserved['behavior_verified'] = Truefinally:observed['provider_requests'] = server.requests@@ -158,22 +152,19 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'verified': False, 'scope': __doc__, 'runs': {}, 'not_verified': [- 'TS factory behavior (no advertised historical counterpart)', 'TUI', 'factory execution and recovery', 'TS validator equality']}+ result = {'verified': False, 'scope': __doc__, 'not_verified': [+ 'TUI', 'factory execution and recovery']}try:assert sys.platform == 'linux', 'hosted Linux only'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256- result['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-factory-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = result['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed)- except Exception as error:- observed['error'] = str(error)- assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r- for r in result['runs'].values()), 'actual factory observation failed'+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = result['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ except Exception as error:+ observed['error'] = str(error)+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual factory observation failed'result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_kernel_env_parity.py b/scripts/check_kernel_env.pysimilarity index 90%rename from scripts/review_kernel_env_parity.pyrename to scripts/check_kernel_env.pyindex 403e183662..5088ec849b 100644--- a/scripts/review_kernel_env_parity.py+++ b/scripts/check_kernel_env.py@@ -1,9 +1,9 @@#!/usr/bin/env python3-"""Actual pinned TS/Rust REPL comparison for bash prefix and Serper wiring.+"""Actual REPL check for bash prefix and Serper wiring.Only synthetic credentials and loopback provider traffic. The same Python cellreads the kernel env and runs the real bash() helper. Windows PYTHONUTF8 is not-verified by this Linux comparison; the separate Windows test is cross-compiled.+verified by this Linux check; the separate Windows test is cross-compiled."""import argparseimport http.server@@ -18,9 +18,9 @@ import sysimport tempfileimport threading-from review_restore_notice_parity import texts, Server, sha256, TS_ARCHIVE_SHA256-from review_draft_disconnect_parity import stop-from review_agent_bounce_parity import Client as BounceClient+from check_restore_notice import texts, Server+from lifecycle_lib import digest, stop+from check_agent_bounce import Client as BounceClientMARKER = 'KERNEL_ENV_PARITY='LIMIT = 35@@ -294,16 +294,12 @@ def reap_leftovers(agent, binary, socket_path, descriptor, kernels, worker_pid,observation['fallback_remaining'] = sorted(remaining)-def run_case(binary, label, name, case, root, observation):+def run_case(binary, name, case, root, observation):for directory in ('home', 'tmp', 'work', 'agent', 'sessions'):(root / directory).mkdir(parents=True)agent, cwd = root / 'agent', root / 'work'env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ','PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}- library = Path(os.environ['PI_PACKAGE_DIR'])- if label == 'ts':- env['PI_PACKAGE_DIR'] = str(library)- env['PYTHONPATH'] = os.pathsep.join(str(path) for path in sorted((library / 'skills').glob('*/src')))env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1', PI_OFFLINE='1',PI_CODING_AGENT_DIR=str(agent), PRIME_AGENT_CODING_AGENT_DIR=str(agent),PI_SESSION_DIR=str(root / 'sessions'), PRIME_AGENT_SESSION_DIR=str(root / 'sessions'),@@ -370,8 +366,6 @@ def run_case(binary, label, name, case, root, observation):finished.wait(0.025)tracker = threading.Thread(target=discover, daemon=True)tracker.start()- # Raw daemon user input is identical in both products. This avoids TS's- # CLI->daemon worker route vs Rust's in-process JSON route entirely.client.call('prompt_and_wait', timeout_seconds=90, activeSessionId=active, message='Run the kernel environment fixture cell.')observation['probe'] = current_probe(server.requests[name], name)assert observation['probe'] == expected(case), (observation['probe'], expected(case))@@ -394,7 +388,7 @@ def run_case(binary, label, name, case, root, observation):try:assert client is not None, 'fixture did not establish cleanup control'observation['wire'] = client.wire- finish_daemon(client, process) # Close after ack, before waiting for TS exit.+ finish_daemon(client, process) # Close after ack, before waiting for exit.wait_gone(tracked)assert tracker is None or not tracker.is_alive(), 'kernel tracker did not stop'observation['cleanup_verified'] = True@@ -424,28 +418,22 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- receipt = {'verified': False, 'runs': {}, 'scope': 'Identical raw daemon create/prompt_and_wait + actual REPL kernel env + real bash output; '+ receipt = {'verified': False, 'scope': 'Raw daemon create/prompt_and_wait + actual REPL kernel env + real bash output; ''command-backed credential, trimming, ambient precedence, custom skill gate, empty-prefix omission','not_verified': ['Windows PYTHONUTF8 behavior (cross-compiled Rust regression only)',- 'TUI/JSON CLI sender routing; runtime settings reload of captured env'],- 'normalization': 'Identical synthetic scalar results; legacy offered ipython/python_repl tool name selected per binary. Raw traffic retained.'}+ 'TUI/JSON CLI sender routing; runtime settings reload of captured env']}try:assert sys.platform == 'linux', 'requires hosted Linux binaries'- assert sha256(os.environ['PA_TS_ARCHIVE']) == TS_ARCHIVE_SHA256, 'TS release archive mismatch'- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256- with tempfile.TemporaryDirectory(prefix='kernel-env-parity-', dir='/tmp') as folder:- for label in ('ts', 'rust'):- binary = Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- run = receipt['runs'][label] = {'binary_sha256': sha256(binary), 'cases': {}}- for name, case in CASES.items():- observation = run['cases'][name] = {}- try:- run_case(binary, label, name, case, Path(folder) / label / name, observation)- except Exception as error:- observation['error'] = str(error)- assert all('error' not in case for run in receipt['runs'].values() for case in run['cases'].values()), receipt['runs']- for name in CASES:- assert receipt['runs']['ts']['cases'][name]['probe'] == receipt['runs']['rust']['cases'][name]['probe']+ with tempfile.TemporaryDirectory(prefix='kernel-env-check-', dir='/tmp') as folder:+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ receipt.update(binary_sha256=digest(binary), cases={})+ for name, case in CASES.items():+ observation = receipt['cases'][name] = {}+ try:+ run_case(binary, name, case, Path(folder) / name, observation)+ except Exception as error:+ observation['error'] = str(error)+ assert all('error' not in case for case in receipt['cases'].values()), receipt['cases']receipt['verified'] = Trueexcept Exception as error:receipt['error'] = str(error)diff --git a/scripts/review_late_message_receipt_parity.py b/scripts/check_late_message_receipt.pysimilarity index 83%rename from scripts/review_late_message_receipt_parity.pyrename to scripts/check_late_message_receipt.pyindex 72d03f435f..ea200971b1 100644--- a/scripts/review_late_message_receipt_parity.py+++ b/scripts/check_late_message_receipt.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Actual TS/Rust print child fire-and-forget receipt after its REPL result lands.+"""Actual print-mode child fire-and-forget receipt after its REPL result lands.The child send waits on a loopback gate. Only the child's second real modelrequest (containing its finished tool result) opens it. The parent remains in@@ -17,9 +17,9 @@ import tempfileimport threadingimport time-from review_draft_disconnect_parity import env_for, digest, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish-from review_restore_notice_parity import texts, probe_from+from lifecycle_lib import digest, env_for, skill_pythonpath+from lifecycle_lib import OwnedProcesses, TAG, finish+from check_restore_notice import texts, probe_fromMESSAGE = 'LATE_RECEIPT_FIXTURE_MESSAGE'PARENT_CELL = "late_child = await rlm.spawn('LATE_RECEIPT_CHILD', name='late-child')\nprint('LATE_SPAWN_HANDLE=' + __import__('json').dumps({'rlm_child_id': late_child.rlm_child_id, 'session_dir': str(late_child.session_dir)}))"@@ -138,9 +138,8 @@ def validate(observed):assert isinstance(message['id'], str) and message['id'], messageassert message['deliveryStatus'] in ('delivered', 'queued'), messageassert message['target']['sessionId'] == observed['parent_session_id'], message- # TS print hosts allocate a runtime activeSessionId distinct from the- # durable UUID. The durable target and child-parent edge below identify- # the recipient; retain the volatile runtime ID without equating the two.+ # The runtime activeSessionId may differ from the durable UUID. The durable+ # target and child-parent edge below identify the recipient.active_id = message['target'].get('activeSessionId')assert isinstance(active_id, str) and active_id.strip(), messageassert rows[0]['file'] != observed['parent_session_file'], 'receipt must belong to child'@@ -153,12 +152,10 @@ def validate(observed):return {key: message[key] for key in ('message', 'receiverRole', 'deliveryStatus')}-def observe(binary, kind, root, observed):- env = env_for(root, kind)+def observe(binary, root, observed):+ env = env_for(root)env[TAG] = str(root)- library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'- env['PYTHONPATH'] = os.pathsep.join(sorted(str(p) for p in library.glob('*/src') if p.is_dir()))- observed['fixture_pythonpath'] = env['PYTHONPATH']+ env['PYTHONPATH'] = skill_pythonpath()provider = Provider(root)thread = threading.Thread(target=provider.serve_forever, daemon=True)thread.start()@@ -211,28 +208,22 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'verified': False, 'runs': {}, 'scope': __doc__,- 'fixture_prerequisite': 'Both kernels receive the same pinned TS skill libraries through PYTHONPATH; this tests host receipt delivery, not native skill packaging.',+ result = {'verified': False, 'scope': __doc__,'not_verified': ['pre-result receipt landing (Rust regression)', 'I/O failure (Rust regression)',- 'compaction/tree-navigation receipt restoration', 'receipt event/frame equality',- 'all volatile generated target identifiers are retained, not compared as equal']}+ 'compaction/tree-navigation receipt restoration']}try:assert sys.platform == 'linux'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256- result['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-late-receipt-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = result['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed)- observed['behavior_verified'] = True- except Exception as error:- observed['error'] = str(error)- assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r- for r in result['runs'].values()), 'actual late receipt observation failed'- assert result['runs']['ts']['semantic_receipt'] == result['runs']['rust']['semantic_receipt']+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = result['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ observed['behavior_verified'] = True+ except Exception as error:+ observed['error'] = str(error)+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual late receipt observation failed'result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_launch_env_parity.py b/scripts/check_launch_env.pysimilarity index 69%rename from scripts/review_launch_env_parity.pyrename to scripts/check_launch_env.pyindex 0ca674de52..c7ea31bf15 100644--- a/scripts/review_launch_env_parity.py+++ b/scripts/check_launch_env.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Actual daemon/kernel launch-env comparison; owned Linux CI processes only.+"""Actual daemon/kernel launch-env check; owned Linux CI processes only.Exercises raw create wire (not TUI sender rendering), isolation, resident crashrecovery, owned recovery, promotion lifetime, and durable secret exclusion.@@ -19,9 +19,9 @@ import tempfileimport threadingimport time-from review_agent_bounce_parity import Client-from review_draft_disconnect_parity import digest, env_for, stop, TS_ARCHIVE_SHA256-from review_restore_notice_parity import texts+from check_agent_bounce import Client+from lifecycle_lib import digest, env_for, stop+from check_restore_notice import textsMARKER = 'LAUNCH_ENV_PARITY='LIMIT = 35@@ -148,7 +148,7 @@ def wait_gone(identities):raise AssertionError('owned fixture processes remained after shutdown: ' + str(alive))-def restart(client, active, agent, binary, config, owned, observation, tracked, label, session_info):+def restart(client, active, agent, binary, config, owned, observation, tracked, session_info):socket_path = agent.parent / 'd.sock'path, row = worker_descriptor(agent, active, socket_path)pid, identity = verify_worker(row, active, binary, socket_path)@@ -171,77 +171,33 @@ def restart(client, active, agent, binary, config, owned, observation, tracked,raise AssertionError('owner recovery never observed worker death')# Same owner context; refreshed attach launchEnv is deliberately out of scope.client.call('attach', activeSessionId=active, recoveryConfig=config)- replacement_active = active- if label == 'ts' and not owned:- # Pinned TS recoverWorker (4236-4242) deliberately parks a resident- # whose transient runtime/env were cleared at Ready. Rust instead- # relaunches from its durable descriptor. Do not call those policies- # equivalent: record the actual TS failed state, then explicitly reopen- # the same file with fresh context and an empty client environment.- deadline = time.monotonic() + LIMIT- while time.monotonic() < deadline:- try:- failed = json.loads(path.read_text())- if failed.get('lifecycle') == 'failed':- assert failed.get('lastError') == 'Waiting for a client with fresh runtime context', failed.get('lastError')- observation['parked_descriptor'] = failed- break- except (OSError, ValueError):- pass- threading.Event().wait(0.025)- else:- raise AssertionError('TS resident did not reach its fresh-context-required state')- action = {'type': 'create', 'sessionPath': session_info['sessionFile'],- 'config': config, 'lifecycle': 'resident', 'launchEnv': {}}- observation['recovery_input'] = action- created = client.call(action['type'], **{key: value for key, value in action.items() if key != 'type'})- observation['recovery_create_response'] = created- assert created['sessionId'] == session_info['sessionId'], 'TS fresh create changed durable session identity'- assert created['sessionFile'] == session_info['sessionFile'], 'TS fresh create opened a different file'- replacement_active = created.get('activeSessionId') or created.get('id')- assert replacement_active, 'TS fresh create omitted active identity'- observation['recovery_policy'] = 'TS parked after crash; explicit fresh-context create with empty launchEnv reopened the same durable session'- elif not owned:- observation['recovery_policy'] = 'Rust automatically relaunched from durable descriptor without retained client launchEnv'- else:+ if owned:observation['recovery_policy'] = 'Owned recovery retained the original client launchEnv'- new_path, new_row = worker_descriptor(agent, replacement_active, socket_path, previous=pid)- if label != 'ts' or owned:- assert new_path == path- tracked.add(verify_worker(new_row, replacement_active, binary, socket_path))+ else:+ observation['recovery_policy'] = 'Automatically relaunched from durable descriptor without retained client launchEnv'+ new_path, new_row = worker_descriptor(agent, active, socket_path, previous=pid)+ assert new_path == path+ tracked.add(verify_worker(new_row, active, binary, socket_path))observation['replacement_worker_pid'] = new_row['pid']- observation['replacement_active_session_id'] = replacement_activeif not owned:- client.call('attach', activeSessionId=replacement_active)- state = client.call('get_state', activeSessionId=replacement_active)+ client.call('attach', activeSessionId=active)+ state = client.call('get_state', activeSessionId=active)observation['replacement_state'] = stateassert state['sessionId'] == session_info['sessionId'], 'recovery changed durable session identity'assert state['sessionFile'] == session_info['sessionFile'], 'recovery changed durable session file'- return replacement_active+ return activedef finish_daemon(client, process, kind, **payload):client.call(kind, **payload) # Successful acknowledgement is mandatory.- client.close() # TS net.Server.close waits for every fixture client to end.+ client.close() # The daemon's close waits for every fixture client to end.process.wait(timeout=15)assert process.returncode == 0, 'supervisor did not shut down successfully'-def comparable_probes(probes):- # The ordinary client filters internal vars in both products. This raw-wire- # injection additionally tests Rust's documented receive-side re-filter;- # TS merges raw maps verbatim. Both actual values are asserted and retained.- projected = json.loads(json.dumps(probes))- for probe in projected.values():- del probe['env']['PRIME_AGENT_INTERNAL_PARITY_CANARY']- return projected---def run_case(binary, label, root, observed):- env = env_for(root, label)+def run_case(binary, root, observed):+ env = env_for(root)env.update(PA_ENV_BASE='daemon-base', PA_ENV_PRECEDENCE='daemon', RLM_DEPTH='3')- library = Path(os.environ['PI_PACKAGE_DIR'])- env['PYTHONPATH'] = os.pathsep.join(str(path) for path in sorted((library / 'skills').glob('*/src')))provider = Provider()thread = threading.Thread(target=provider.serve_forever, daemon=True)thread.start()@@ -283,8 +239,7 @@ def run_case(binary, label, root, observed):client.call('prompt_and_wait', activeSessionId=active, message='Probe ' + phase)result = current_probe(provider.requests[phase], phase)expected = {'env': {'PA_ENV_MARKER': expected_marker, 'PA_ENV_BASE': 'daemon-base',- 'PA_ENV_PRECEDENCE': expected_precedence, 'PRIME_AGENT_INTERNAL_PARITY_CANARY':- 'must-not-inherit' if label == 'ts' and expected_marker is not None else None},+ 'PA_ENV_PRECEDENCE': expected_precedence, 'PRIME_AGENT_INTERNAL_PARITY_CANARY': None},'child_marker': expected_marker or 'ABSENT'}assert result == expected, (phase, result, expected)probes[phase] = result@@ -295,16 +250,16 @@ def run_case(binary, label, root, observed):probe(a, 'resident_initial', secret, 'client')probe(b, 'isolated_other', None, 'daemon')observed['resident_recovery'] = {}- a = restart(client, a, root / 'agent', binary, config, False, observed['resident_recovery'], tracked, label, session_info['launch-a'])+ a = restart(client, a, root / 'agent', binary, config, False, observed['resident_recovery'], tracked, session_info['launch-a'])probe(a, 'resident_recovered', None, 'daemon')owner = create('launch-owned', 'client_owned', {'launchEnv': launch})probe(owner, 'owned_initial', secret, 'client')observed['owned_recovery'] = {}- owner = restart(client, owner, root / 'agent', binary, config, True, observed['owned_recovery'], tracked, label, session_info['launch-owned'])+ owner = restart(client, owner, root / 'agent', binary, config, True, observed['owned_recovery'], tracked, session_info['launch-owned'])probe(owner, 'owned_recovered', secret, 'client')client.call('promote_owned_session', activeSessionId=owner)observed['promoted_recovery'] = {}- owner = restart(client, owner, root / 'agent', binary, config, False, observed['promoted_recovery'], tracked, label, session_info['launch-owned'])+ owner = restart(client, owner, root / 'agent', binary, config, False, observed['promoted_recovery'], tracked, session_info['launch-owned'])probe(owner, 'promoted_recovered', None, 'daemon')descriptors = list((root / 'agent/daemon-workers').rglob('*.json'))assert len(descriptors) >= 3, 'durable descriptor audit would be empty'@@ -314,15 +269,11 @@ def run_case(binary, label, root, observed):prepared = client.call('prepare_update_restart', updateId='launch-env-parity')prepared_transaction = Trueobserved['prepare_update'] = prepared- if label == 'rust':- assert prepared.get('state') == 'prepared', 'update did not prepare'- rosters = list((root / 'agent/update-restarts').glob('*/prepared/launch-env-parity/roster.json'))- assert len(rosters) == 1, 'actual prepared Rust roster missing/ambiguous'- roster = json.loads(rosters[0].read_text())- assert len(roster['workers']) == 3, 'prepared roster omitted fixture workers'- else:- roster = prepared- assert len(roster['sessions']) == 3, 'prepared manifest omitted fixture sessions'+ assert prepared.get('state') == 'prepared', 'update did not prepare'+ rosters = list((root / 'agent/update-restarts').glob('*/prepared/launch-env-parity/roster.json'))+ assert len(rosters) == 1, 'actual prepared roster missing/ambiguous'+ roster = json.loads(rosters[0].read_text())+ assert len(roster['workers']) == 3, 'prepared roster omitted fixture workers'assert secret not in json.dumps(roster), 'launch secret leaked into actual update roster'observed['update_roster'] = rosterexcept BaseException as error:@@ -336,7 +287,7 @@ def run_case(binary, label, root, observed):if client:observed['wire'] = client.wireif process.poll() is None:- if label == 'rust' and prepared_transaction:+ if prepared_transaction:finish_daemon(client, process, 'commit_update_restart', updateId='launch-env-parity')else:finish_daemon(client, process, 'shutdown', force=True)@@ -365,26 +316,20 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- receipt = {'verified': False, 'runs': {}, 'scope': 'Raw daemon create, actual REPL/subprocess env, '- 'env clearing/retention and durable launch-env secret exclusion. TS residents require explicit fresh-context reopen; Rust auto-relaunches. No recovery-policy equivalence claim.',+ receipt = {'verified': False, 'scope': 'Raw daemon create, actual REPL/subprocess env, '+ 'env clearing/retention, internal-prefixed launchEnv re-filtering and durable launch-env secret exclusion.','not_verified': ['TUI/ACP sender env collection', 'refreshed attach launchEnv recovery',- 'rlm.spawn and minimal depth-0 root forwarding', 'automatic resident/promotion recovery parity (actual policies differ)'],- 'intentional_difference': 'Rust re-filters raw launchEnv internal-prefixed keys; TS trusts sender filtering and merges the injected canary. Exact canary values asserted per phase; raw results retained. Separately, TS parks crashed residents requiring fresh create context, whereas Rust relaunches automatically; exact parked states, explicit fresh-create inputs and durable identity proofs retained.',- 'normalization': 'Generated session IDs, roots, worker PIDs and timestamps excluded only from cross-run comparison; raw wire retained.'}+ 'rlm.spawn and minimal depth-0 root forwarding']}try:assert sys.platform == 'linux', 'requires hosted Linux /proc ownership checks'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'TS archive mismatch'- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256- with tempfile.TemporaryDirectory(prefix='launch-env-parity-', dir='/tmp') as folder:- for label in ('ts', 'rust'):- binary = Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- run = receipt['runs'][label] = {'binary_sha256': digest(binary)}- try:- run_case(binary, label, Path(folder) / label, run)- except Exception as error:- run['error'] = str(error)- assert all('error' not in run for run in receipt['runs'].values()), receipt['runs']- assert comparable_probes(receipt['runs']['ts']['probes']) == comparable_probes(receipt['runs']['rust']['probes']), 'environment behavior differs'+ with tempfile.TemporaryDirectory(prefix='launch-env-check-', dir='/tmp') as folder:+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ run = receipt['run'] = {'binary_sha256': digest(binary)}+ try:+ run_case(binary, Path(folder) / 'rust', run)+ except Exception as error:+ run['error'] = str(error)+ assert 'error' not in run, runreceipt['verified'] = Trueexcept Exception as error:receipt['error'] = str(error)diff --git a/scripts/review_ledger_liveness_parity.py b/scripts/check_ledger_liveness.pysimilarity index 76%rename from scripts/review_ledger_liveness_parity.pyrename to scripts/check_ledger_liveness.pyindex 0275187a72..0be70c649f 100644--- a/scripts/review_ledger_liveness_parity.py+++ b/scripts/check_ledger_liveness.py@@ -1,11 +1,11 @@#!/usr/bin/env python3-"""Hosted actual TS/Rust RLM spawn, durable ledger and warm-list liveness comparison.+"""Hosted actual RLM spawn, durable ledger and warm-list liveness check.A real parent kernel admits a child with rlm.spawn. The synthetic provider holds-that child's turn while both daemons answer repeated list/roster reads. This is-live-family baseline parity plus real disk relocation/deletion and catalog wake-restore observations. Historical flat-path tombstone rows are explicit fixture-inputs. Symlink retargeting and registration timing remain out of scope.+that child's turn while the daemon answers repeated list/roster reads. This checks+the live family plus real disk relocation/deletion, the ended child's current exit+sidecar and catalog wake restore. Historical flat-path tombstone rows are explicit+fixture inputs. Symlink retargeting and registration timing remain out of scope."""import argparseimport http.server@@ -19,9 +19,9 @@ import tempfileimport threadingimport time-from review_agent_bounce_parity import Client, LIMIT-from review_draft_disconnect_parity import digest, env_for, stop, TS_ARCHIVE_SHA256-from review_restore_notice_parity import texts+from check_agent_bounce import Client, LIMIT+from lifecycle_lib import digest, env_for, stop+from check_restore_notice import textsPARENT = 'Create the ledger liveness fixture child.'CHILD = 'LEDGER_LIVENESS_CHILD_HOLD'@@ -182,14 +182,7 @@ def catalog_row(view, path):return rows[0]-def archive_restore_unsupported(response, session_id):- return (response.get('type') == 'response' and response.get('command') == 'send_message'- and response.get('success') is False- and response.get('error') == 'Unknown active session: ' + session_id)---def cache_boundaries(client, config, root, created, child, ledger_path, provider, kind, observed,- require_current_sidecar):+def cache_boundaries(client, config, root, created, child, ledger_path, provider, observed):parent_file = Path(created['sessionFile'])child_file = Path(child['sessionFile'])child_active = child.get('activeSessionId') or child.get('id')@@ -203,17 +196,15 @@ def cache_boundaries(client, config, root, created, child, ledger_path, providerclient.call('wait_for_idle', activeSessionId=created.get('activeSessionId') or created['id'])client.call('kill', activeSessionId=child_active)sidecar = child_file.with_suffix('.info-cache.json')- if kind == 'rust':- observed['lease_exit_sidecar'] = {'path': str(sidecar), 'exists': sidecar.is_file()}- if sidecar.is_file():- data = json.loads(sidecar.read_text())- generation = data['state']['generation']['len']- offset = data['state']['offset']- length = child_file.stat().st_size- observed['lease_exit_sidecar'].update(version=data['version'], generation=generation,- offset=offset, transcript_bytes=length, current=(generation == offset == length))- if require_current_sidecar:- assert observed['lease_exit_sidecar'].get('current'), 'ended child sidecar is not current'+ observed['lease_exit_sidecar'] = {'path': str(sidecar), 'exists': sidecar.is_file()}+ if sidecar.is_file():+ data = json.loads(sidecar.read_text())+ generation = data['state']['generation']['len']+ offset = data['state']['offset']+ length = child_file.stat().st_size+ observed['lease_exit_sidecar'].update(version=data['version'], generation=generation,+ offset=offset, transcript_bytes=length, current=(generation == offset == length))+ assert observed['lease_exit_sidecar'].get('current'), 'ended child sidecar is not current'before = ledger_path.read_bytes()trace = observed['cache_boundaries'] = {'artifact_reads': [], 'setup':'actual spawned child transcript moved only after worker kill; historical flat-path tombstone fixture below'}@@ -225,8 +216,7 @@ def cache_boundaries(client, config, root, created, child, ledger_path, providerfirst_matches = [row for row in first['sessions'] if Path(row['path']).resolve() == relocated.resolve()]assert len(first_matches) <= 1, first_matchestrace['first_relocated_child_present'] = len(first_matches) == 1- if kind == 'rust':- assert catalog_row(first, relocated)['id'] == child_session_id+ assert catalog_row(first, relocated)['id'] == child_session_idmoved_again = root / 'agent/session-artifacts/ledger-moved/second' / child_file.namemoved_again.parent.mkdir(parents=True)relocated.rename(moved_again)@@ -239,8 +229,7 @@ def cache_boundaries(client, config, root, created, child, ledger_path, providertrace['artifact_reads'].append(third)stale = [row for row in third['sessions'] if row['id'] == child_session_id]trace['artifact_contract'] = {'relocation_recovered': len(recovered) == 1, 'removed_child_absent': not stale}- if kind == 'rust':- assert trace['artifact_contract'] == {'relocation_recovered': True, 'removed_child_absent': True}, trace+ assert trace['artifact_contract'] == {'relocation_recovered': True, 'removed_child_absent': True}, traceassert ledger_path.read_bytes() == before, 'artifact mutations unexpectedly changed ledger'# Restore the actual transcript so normal cleanup retains the original fixture layout.removed.rename(child_file)@@ -273,24 +262,9 @@ def cache_boundaries(client, config, root, created, child, ledger_path, providertrace['bucket_warm'] = warmparent_before = catalog_row(warm, parent_file)trace['warm_bucket_matches_actual_usage'] = parent_before.get('deletedDescendantUsage') == usage- if kind == 'rust':- assert trace['warm_bucket_matches_actual_usage'], parent_before- try:- wake = client.call('send_message', targetActiveSessionId=own['id'], message='Restore the billing fixture.')- except AssertionError:- response = client.wire[-1]- if kind != 'ts' or not archive_restore_unsupported(response, own['id']):- raise- # The pinned binary has now actually refused this archived selector.- # Retain the refusal; never simulate a restore or call it parity.- trace['actual_restore_wake'] = {'supported': False, 'response': response}- assert archive.is_file() and not billing_file.exists(), 'refused wake partially restored the file'- assert ledger_path.read_bytes() == unchanged, 'refused wake changed the ledger'- trace['bucket_contract'] = {'actual_archive_restore_supported': False,- 'restored_child_has_own_usage': None, 'parent_bucket_withdrawn': None}- trace['ledger_unchanged_across_boundary_operations'] = True- return {'artifact': trace['artifact_contract'], 'bucket': trace['bucket_contract']}- trace['actual_restore_wake'] = {'supported': True, 'receipt': wake}+ assert trace['warm_bucket_matches_actual_usage'], parent_before+ wake = client.call('send_message', targetActiveSessionId=own['id'], message='Restore the billing fixture.')+ trace['actual_restore_wake'] = wakeassert billing_file.is_file() and not archive.exists(), 'actual catalog wake did not restore transcript'restored = client.call('list_saved_sessions', cwd=str(root), scope='all')trace['bucket_after_actual_restore'] = restored@@ -298,17 +272,14 @@ def cache_boundaries(client, config, root, created, child, ledger_path, providerrestored_child = catalog_row(restored, billing_file)trace['bucket_contract'] = {'restored_child_has_own_usage': restored_child.get('usage') == usage,'parent_bucket_withdrawn': 'deletedDescendantUsage' not in parent_after}- if kind == 'rust':- assert trace['bucket_contract'] == {'restored_child_has_own_usage': True, 'parent_bucket_withdrawn': True}, trace+ assert trace['bucket_contract'] == {'restored_child_has_own_usage': True, 'parent_bucket_withdrawn': True}, traceassert ledger_path.read_bytes() == unchanged, 'actual restore unexpectedly appended ledger'trace['ledger_unchanged_across_boundary_operations'] = Truereturn {'artifact': trace['artifact_contract'], 'bucket': trace['bucket_contract']}-def run_case(binary, kind, root, observed, require_current_sidecar=False):- env = env_for(root, kind)- library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'- env['PYTHONPATH'] = os.pathsep.join(sorted(str(path) for path in library.glob('*/src') if path.is_dir()))+def run_case(binary, root, observed):+ env = env_for(root)provider = Provider()thread = threading.Thread(target=provider.serve_forever, daemon=True)thread.start()@@ -361,8 +332,7 @@ def run_case(binary, kind, root, observed, require_current_sidecar=False):assert Path(spawns[0]['child']).resolve() == Path(listed[0]['sessionFile']).resolve(), spawnsassert Path(spawns[0]['child']).is_file(), spawnsassert len(ledgers) == 1, ledgers- cache_boundaries(client, config, root, created, listed[0], ledgers[0], provider, kind, observed,- require_current_sidecar)+ cache_boundaries(client, config, root, created, listed[0], ledgers[0], provider, observed)return {'list': contracts, 'roster': roster_contract,'durable_spawn': {'name': NAME, 'depth': 1, 'count': 1,'parent_matches_created_session': True, 'child_transcript_exists': True}}@@ -393,38 +363,19 @@ def run_case(binary, kind, root, observed, require_current_sidecar=False):confirm_cleanup(root, observed)-def main(require_current_sidecar=False):+def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'verified': False, 'scope': __doc__, 'runs': {},- 'not_compared': ['external symlink retarget on an active transcript',- 'nonresident-child passivation/registration timing',- 'whole wire equality: full raw responses preserved; compare declared family contract']}+ result = {'verified': False, 'scope': __doc__,+ 'not_verified': ['external symlink retarget on an active transcript',+ 'nonresident-child passivation/registration timing']}try:assert sys.platform == 'linux', 'hosted Linux CI only'- assert digest(os.environ['PA_TS_ARCHIVE']) == TS_ARCHIVE_SHA256, 'TS archive hash mismatch'- result['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-ledger-', dir='/tmp') as temporary:- for kind in ('ts', 'rust'):- binary = Path(os.environ['PA_' + kind.upper() + '_BINARY']).resolve()- observed = result['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observed['contract'] = run_case(binary, kind, Path(temporary) / kind, observed, require_current_sidecar)- except Exception as error:- observed['error'] = str(error)- errors = {kind: run['error'] for kind, run in result['runs'].items() if 'error' in run}- assert not errors, errors- assert result['runs']['ts']['contract'] == result['runs']['rust']['contract'], 'family contract mismatch'- result['cache_boundary_observations'] = {kind: {key: run['cache_boundaries'][key] for key in- ('artifact_contract', 'bucket_contract')} for kind, run in result['runs'].items()}- result['cache_boundary_scope'] = ('Rust regression invariants required; actual TS observations retained. '- 'Pinned TS omitted relocated passive children, did not expose the warmed deleted-spend bucket, and '- 'refused the archived selector with Unknown active session in actual hosted reads. These are '- 'explicit baseline limitations; no full cache-boundary parity is claimed.')- result['cache_boundary_comparison'] = ('identical' if result['cache_boundary_observations']['ts'] ==- result['cache_boundary_observations']['rust'] else 'actual TS/Rust difference; raw reads retained')- result['require_current_rust_lease_exit_sidecar'] = require_current_sidecar+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = result['run'] = {'binary_sha256': digest(binary)}+ observed['contract'] = run_case(binary, Path(temporary) / 'rust', observed)result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_live_mcp_parity.py b/scripts/check_live_mcp.pysimilarity index 79%rename from scripts/review_live_mcp_parity.pyrename to scripts/check_live_mcp.pyindex a090cf9a40..bb43d0b237 100644--- a/scripts/review_live_mcp_parity.py+++ b/scripts/check_live_mcp.py@@ -1,10 +1,9 @@#!/usr/bin/env python3-"""Compare real TS/Rust kernel mcp.config before and after a live settings reload.+"""Check the real kernel mcp.config before and after a live settings reload.-Both owned daemon binaries execute identical cells through an offline provider.-The shared public reload command refreshes settings between probes. Rust must-keep its kernel (and already registered host handler) alive; TS's reload rebuild-is recorded explicitly. Exact config objects are compared without filtering.+The owned daemon executes cells through an offline provider. The public reload+command refreshes settings between probes. The kernel (and its already registered+host handler) must stay alive. Exact config objects are checked without filtering."""import argparseimport http.server@@ -19,8 +18,8 @@ import tempfileimport threadingimport time-from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256-from review_restore_notice_parity import texts+from lifecycle_lib import digest+from check_restore_notice import textsMARKER = 'LIVE_MCP_PARITY_RESULT='CELL = """import os, json@@ -166,24 +165,19 @@ def stop(process):process.wait(timeout=5)-def validate_observation(observation, label):+def validate_observation(observation):assert observation['before']['configs'] == {'fixture-before': BEFORE, 'fixture-after': {}}, observation['before']assert observation['after']['configs'] == {'fixture-before': {}, 'fixture-after': AFTER}, observation['after']observation['kernel_pid_equal'] = observation['before']['pid'] == observation['after']['pid']- if label == 'rust':- assert observation['kernel_pid_equal'], 'Rust replaced the kernel; stale-handler regression was not exercised'+ assert observation['kernel_pid_equal'], 'reload replaced the kernel; stale-handler regression was not exercised'-def run_case(binary, label, root, observation):+def run_case(binary, root, observation):for name in ('home', 'agent', 'sessions', 'work', 'tmp'):(root / name).mkdir(parents=True)agent, cwd = root / 'agent', root / 'work'env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ','PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}- if label == 'ts':- env['PI_PACKAGE_DIR'] = os.environ['PI_PACKAGE_DIR']- library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'- env['PYTHONPATH'] = os.pathsep.join(sorted(str(p) for p in library.glob('*/src') if p.is_dir()))env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1',PI_OFFLINE='1', PI_CODING_AGENT_DIR=str(agent),PRIME_AGENT_CODING_AGENT_DIR=str(agent), PI_SESSION_DIR=str(root / 'sessions'),@@ -220,8 +214,8 @@ def run_case(binary, label, root, observation):if phase == 'after':settings['mcpServers'] = {'fixture-after': AFTER}settings_path.write_text(json.dumps(settings))- # Identical public command to both runtimes. Rust does not- # rebuild the core: the same registered handler must read live.+ # The public reload does not rebuild the core: the same+ # registered handler must read live.client.request({'type': 'reload', 'activeSessionId': active})client.request({'type': 'prompt', 'activeSessionId': active,'message': 'Probe live MCP configuration: ' + phase})@@ -229,7 +223,7 @@ def run_case(binary, label, root, observation):observation[phase] = latest_probe(server.requests[phase])assert not server.errors, server.errorsassert {k: len(v) for k, v in server.requests.items()} == {'before': 2, 'after': 2}- validate_observation(observation, label)+ validate_observation(observation)finally:if client is not None:if active is not None:@@ -252,33 +246,20 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'verified': False, 'runs': {}, 'comparison': 'Exact mcp.config objects before/after public reload',- 'kernel_lifecycle_scope': 'TS reload may rebuild; Rust must keep the existing kernel/host handler.',- 'tool_name_selection': 'Offered python_repl or legacy ipython; identical cell code.'}+ result = {'verified': False, 'scope': 'Exact mcp.config objects before/after public reload; the kernel/host handler must survive',+ 'tool_name_selection': 'Offered python_repl or legacy ipython.'}try:assert sys.platform == 'linux', 'requires hosted Linux CI'- archive_hash = sha256(os.environ['PA_TS_ARCHIVE'])- result['ts_release_archive_sha256'] = archive_hash- assert archive_hash == TS_ARCHIVE_SHA256, 'TS release archive hash mismatch'- binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- for label in ('ts', 'rust')}- result['binaries'] = {label: {'path': str(path), 'sha256': sha256(path)}- for label, path in binaries.items()}- with tempfile.TemporaryDirectory(prefix='live-mcp-parity-') as temp:- for label, binary in binaries.items():- observation = {}- result['runs'][label] = observation- try:- run_case(binary, label, Path(temp) / label, observation)- except Exception as error:- observation['error'] = str(error)- errors = {label: value['error'] for label, value in result['runs'].items() if 'error' in value}- assert not errors, errors- cleanup_errors = {label: value['cleanup_error'] for label, value in result['runs'].items()- if 'cleanup_error' in value}- assert not cleanup_errors, cleanup_errors- for phase in ('before', 'after'):- assert result['runs']['ts'][phase]['configs'] == result['runs']['rust'][phase]['configs']+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ result['binary'] = {'path': str(binary), 'sha256': digest(binary)}+ with tempfile.TemporaryDirectory(prefix='live-mcp-check-') as temp:+ observation = result['run'] = {}+ try:+ run_case(binary, Path(temp) / 'rust', observation)+ except Exception as error:+ observation['error'] = str(error)+ assert 'error' not in observation, observation['error']+ assert 'cleanup_error' not in observation, observation['cleanup_error']result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_local_harness_parity.py b/scripts/check_local_harness.pysimilarity index 74%rename from scripts/review_local_harness_parity.pyrename to scripts/check_local_harness.pyindex eb2872f792..ef6fae3a2a 100644--- a/scripts/review_local_harness_parity.py+++ b/scripts/check_local_harness.py@@ -1,10 +1,9 @@#!/usr/bin/env python3-"""Drive real TS/Rust REPLs through session-local/global memory CRUD and isolation.+"""Drive the real REPL through session-local/global memory CRUD and isolation.-Uses the restore-notice verifier's loopback-provider protocol and subprocess-isolation. Compares actual tool results and persisted files, not source strings.-Only volatile timestamps, fixture roots and generated session IDs are normalized.-Tool names (legacy ipython/python_repl) are selected from each binary's offer.+Uses the restore-notice check's loopback-provider protocol and subprocess+isolation. Checks actual tool results and persisted files, not source strings.+Tool names (legacy ipython/python_repl) are selected from the binary's offer."""import argparseimport http.server@@ -15,7 +14,8 @@ import sysimport tempfileimport threading-from review_restore_notice_parity import invoke, texts, Server, sha256, TS_ARCHIVE_SHA256+from check_restore_notice import invoke, texts, Server+from lifecycle_lib import digestMARKER = 'LOCAL_HARNESS_PARITY='READ = """import os, json, dataclasses@@ -110,24 +110,18 @@ def stored(path):return rows-def run_case(binary, label, root, observation):+def run_case(binary, root, observation):for name in ('home', 'agent', 'sessions', 'work', 'tmp'):(root / name).mkdir(parents=True)cwd, agent, sessions = root / 'work', root / 'agent', root / 'sessions'env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ',- 'PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON', 'PYTHONPATH') if key in os.environ}- library = Path(os.environ['PI_PACKAGE_DIR'])- if label == 'ts':- env['PI_PACKAGE_DIR'] = str(library)+ 'PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1',PI_OFFLINE='1', PI_CODING_AGENT_DIR=str(agent), PRIME_AGENT_CODING_AGENT_DIR=str(agent),PI_SESSION_DIR=str(sessions), PRIME_AGENT_SESSION_DIR=str(sessions),XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(root / 'cache'),XDG_DATA_HOME=str(root / 'data'))- # Common skill imports only; never inject RLM_* harness paths, which would- # mask the missing runtime exports this PR repairs.- env['PYTHONPATH'] = os.pathsep.join(sorted(str(p) for p in (library / 'skills').glob('*/src')- if p.is_dir()) + [env.get('PYTHONPATH', '')])+ # Never inject RLM_* harness paths, which would mask missing runtime exports.server = Server(root)server.RequestHandlerClass = Handlerserver.requests['other'] = []@@ -164,10 +158,9 @@ def run_case(binary, label, root, observation):artifact = root / 'session-artifacts' / session_idassert probe['env']['RLM_SESSION_DIR'] == str(artifact), probe['env']assert probe['env']['RLM_HARNESS_STATE_DIR'] == str(artifact / 'harness'), probe['env']- # The effective global destination is checked on disk below; record- # any optional explicit global env export difference without hiding it.- expected_global_env = str(agent / 'harness') if label == 'ts' else None- assert probe['env']['RLM_GLOBAL_HARNESS_STATE_DIR'] == expected_global_env, probe['env']+ # RLM_GLOBAL_HARNESS_STATE_DIR stays unset; the runtime resolves+ # PRIME_AGENT_CODING_AGENT_DIR/harness, checked on disk below.+ assert probe['env']['RLM_GLOBAL_HARNESS_STATE_DIR'] is None, probe['env']observation[phase]['kernel_env'] = probe.pop('env')assert probe['local_ids'] == ([] if phase == 'other' else ['parity-local']), probeassert probe['global_ids'] == ['parity-global'], probe@@ -194,34 +187,19 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'verified': False, 'runs': {}, 'normalization': [- 'Volatile created_at/updated_at timestamps only in HarnessEntry objects.',- 'Fixture roots/session IDs checked exactly within each run, then excluded from cross-run entry comparison.',- 'Select offered python_repl or legacy ipython; identical cell code.'],- 'scope': 'Actual REPL results and local/global files: CRUD, resume durability, fresh-session isolation. No TUI frame or daemon-wire parity claim.'}+ result = {'verified': False,+ 'tool_name_selection': 'Select offered python_repl or legacy ipython.',+ 'scope': 'Actual REPL results and local/global files: CRUD, resume durability, fresh-session isolation.'}try:assert sys.platform == 'linux', 'requires Linux hosted CI binaries'- result['ts_release_archive_sha256'] = sha256(os.environ['PA_TS_ARCHIVE'])- assert result['ts_release_archive_sha256'] == TS_ARCHIVE_SHA256, 'TS archive hash mismatch'- with tempfile.TemporaryDirectory(prefix='local-harness-parity-') as temp:- for label in ('ts', 'rust'):- binary = Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- observation = {'binary': str(binary), 'binary_sha256': sha256(binary)}- result['runs'][label] = observation- try:- run_case(binary, label, Path(temp) / label, observation)- except Exception as error:- observation['error'] = str(error)- errors = {label: run['error'] for label, run in result['runs'].items() if 'error' in run}- assert not errors, errors- ts, rust = result['runs']['ts'], result['runs']['rust']- assert ts['probes'] == rust['probes'], 'TS/Rust memory behavior differs'- result['global_env_exports'] = {label: {phase: run[phase]['kernel_env']['RLM_GLOBAL_HARNESS_STATE_DIR']- for phase in ('setup', 'resume', 'other')} for label, run in result['runs'].items()}- result['global_env_scope'] = ('Known provisioning difference: TS explicitly exports its agent/harness directory; '- 'Rust leaves RLM_GLOBAL_HARNESS_STATE_DIR unset and the common runtime resolves '- 'PRIME_AGENT_CODING_AGENT_DIR/harness. Both exact environments are asserted, '- 'and the effective global files and complete entries must match.')+ with tempfile.TemporaryDirectory(prefix='local-harness-check-') as temp:+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observation = result['run'] = {'binary': str(binary), 'binary_sha256': digest(binary)}+ try:+ run_case(binary, Path(temp) / 'rust', observation)+ except Exception as error:+ observation['error'] = str(error)+ assert 'error' not in observation, observation['error']result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_mcp_oauth_config_parity.py b/scripts/check_mcp_oauth_config.pysimilarity index 84%rename from scripts/review_mcp_oauth_config_parity.pyrename to scripts/check_mcp_oauth_config.pyindex a6c11000cc..034f785f47 100644--- a/scripts/review_mcp_oauth_config_parity.py+++ b/scripts/check_mcp_oauth_config.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Actual TS/Rust settings -> live mcp.config roundtrip for clientId/callbackPort.+"""Actual settings -> live mcp.config roundtrip for clientId/callbackPort.This exercises real daemon/kernel config delivery before and after reload.It never performs network OAuth, opens a browser or uses real credentials.@@ -16,10 +16,10 @@ import sysimport tempfileimport threading-from review_kernel_env_parity import KernelClient as Client-from review_draft_disconnect_parity import env_for, digest, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish-from review_restore_notice_parity import texts+from check_kernel_env import KernelClient as Client+from lifecycle_lib import env_for, digest+from lifecycle_lib import OwnedProcesses, TAG, finish+from check_restore_notice import textsMARKER = 'MCP_OAUTH_CONFIG_RESULT='NAMES = ('fixture-oauth', 'fixture-default')@@ -95,8 +95,8 @@ def validate(observed):assert observed['after'] == {'fixture-oauth': AFTER, 'fixture-default': DEFAULT}, observed-def observe(binary, kind, root, observed):- env = env_for(root, kind)+def observe(binary, root, observed):+ env = env_for(root)env[TAG] = str(root)provider = Provider()thread = threading.Thread(target=provider.serve_forever, daemon=True)@@ -153,25 +153,20 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'verified': False, 'runs': {}, 'scope': __doc__, 'not_verified': [+ result = {'verified': False, 'scope': __doc__, 'not_verified': ['actual authorization browser callback or token exchange', 'credentialed Slack login','live refresh-token compatibility', 'TUI rendering']}try:assert sys.platform == 'linux'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256- result['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-oauth-config-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = result['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed)- except Exception as error:- observed['error'] = str(error)- assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r- for r in result['runs'].values()), 'actual OAuth config observation failed'- for phase in ('before', 'after'):- assert result['runs']['ts'][phase] == result['runs']['rust'][phase]+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = result['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ except Exception as error:+ observed['error'] = str(error)+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual OAuth config observation failed'result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_minimum_reasoning_parity.py b/scripts/check_minimum_reasoning.pysimilarity index 77%rename from scripts/review_minimum_reasoning_parity.pyrename to scripts/check_minimum_reasoning.pyindex c25b26ad6b..c3fccc072e 100644--- a/scripts/review_minimum_reasoning_parity.py+++ b/scripts/check_minimum_reasoning.py@@ -1,14 +1,11 @@#!/usr/bin/env python3-"""Capture mandatory-thinking summary/refiner requests from real TS/Rust binaries.+"""Capture mandatory-thinking summary/refiner requests from the real binary.-The pinned TS v0.9.8 release and the current Rust binary run identical Python-cells through their offered REPL tool. Only auxiliary request thinking controls-are compared, recording TS summary thinking-off as the intended correction:-prompt wording, token budgets, and whole UI/frame parity are not-claimed. Branch summary uses an owned daemon and its real navigate_tree command.-Both binaries use the same raw daemon commands; the owned supervisor shuts down-workers and kernels before temporary files are removed. All providers, homes,-sessions, and subprocesses belong to this fixture.+Python cells run through the offered REPL tool. Only auxiliary request thinking+controls are checked: prompt wording, token budgets, and UI frames are not.+Branch summary uses an owned daemon and its real navigate_tree command. The owned+supervisor shuts down workers and kernels before temporary files are removed.+All providers, homes, sessions, and subprocesses belong to this fixture."""import argparseimport http.server@@ -21,10 +18,9 @@ import tempfileimport threadingimport time-from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256-from review_restore_notice_parity import invoke, probe_from, texts-from review_kernel_env_parity import KernelClient-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+from check_restore_notice import invoke, probe_from, texts+from check_kernel_env import KernelClient+from lifecycle_lib import OwnedProcesses, TAG, digest, finish, skill_pythonpathMARKER = 'MINIMUM_REASONING_RESULT='@@ -147,34 +143,26 @@ def wait_for_operation(server, scenario, sessions, timeout_seconds=90):threading.Event().wait(0.025)-def run_case(binary, label, scenario, root, observation):+def run_case(binary, scenario, root, observation):for name in ('home', 'agent', 'sessions', 'work', 'tmp'):(root / name).mkdir(parents=True)agent, sessions, cwd = root / 'agent', root / 'sessions', root / 'work'env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ','PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}- library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'- paths = sorted(str(path) for path in library.glob('*/src') if path.is_dir())- for skill in ('compact', 'refine'):- assert (library / skill / 'src' / skill / '__init__.py').is_file(), skill + ' skill missing'env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1',PI_OFFLINE='1', PI_CODING_AGENT_DIR=str(agent),PRIME_AGENT_CODING_AGENT_DIR=str(agent), PI_SESSION_DIR=str(sessions),PRIME_AGENT_SESSION_DIR=str(sessions), XDG_CONFIG_HOME=str(root / 'config'),XDG_CACHE_HOME=str(root / 'cache'), XDG_DATA_HOME=str(root / 'data'),- PYTHONPATH=os.pathsep.join(paths))+ PYTHONPATH=skill_pythonpath())env[TAG] = str(root)- if label == 'ts':- env['PI_PACKAGE_DIR'] = os.environ['PI_PACKAGE_DIR']server = Server(scenario)thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()(agent / 'models.json').write_text(json.dumps({'providers': {'fixture': {'api': 'openai-completions', 'apiKey': 'fixture-only',- # Provider-level compat is supported by both loaders. TS also merges- # model-level compat; Rust's existing custom loader ignores that field.- # Keep this fixture on their common configuration surface and require- # the exact zai wire toggle, without accepting another adapter's format.+ # The custom loader honors provider-level compat (it ignores model-level+ # compat). Require the exact zai wire toggle, not another adapter's format.'compat': {'thinkingFormat': 'zai'},'baseUrl': 'http://127.0.0.1:%s/v1' % server.server_address[1],'models': [{'id': 'mandatory-fixture', 'name': 'Mandatory thinking fixture',@@ -221,7 +209,7 @@ def run_case(binary, label, scenario, root, observation):assert auxiliary, 'scheduled operation made no auxiliary provider request'controls = [{key: body[key] for key in ('enable_thinking', 'thinking', 'reasoning_effort','reasoning', 'chat_template_kwargs') if key in body} for body in auxiliary]- expected = {'enable_thinking': label == 'rust' or scenario == 'refine'}+ expected = {'enable_thinking': True}assert all(control == expected for control in controls), {'expected': expected, 'actual': controls}observation.update(controls=controls, outcome_count=len(outcomes), tool_name=server.tool_name)return {'scheduled': scheduled['scheduled'], 'completed': bool(outcomes)}@@ -232,8 +220,7 @@ def run_case(binary, label, scenario, root, observation):finally:observation['requests'] = server.requestsobservation['daemon_wire'] = list(client.wire) if client else []- # CLI exit leaves the TS kernel alive. Owning the supervisor gives both- # binaries the same acknowledged shutdown before temporary files vanish.+ # Owning the supervisor gives an acknowledged shutdown before temporary files vanish.finish(scope, client, process, observation)log.close()observation['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')[-6000:]@@ -250,28 +237,17 @@ def main():parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()result = {'verified': False, 'runs': {},- 'scope': 'Compaction, branch summary, and refinement auxiliary thinking controls; no frame parity claim.',- 'intended_difference': 'TS v0.9.8 compaction and branch summary requests disable zai thinking; Rust enables mandatory thinking. Refinement enables thinking in both.',- 'fixture_compat_scope': 'Provider-level zai compat used identically by both custom-model loaders; model-level compat is not relied on.',- 'comparison': 'Both schedule and persist completed outcomes. Every captured auxiliary request must match the exact expected control; request counts and full bodies remain in runs.'}+ 'scope': 'Compaction, branch summary, and refinement auxiliary requests enable mandatory thinking; no frame claim.',+ 'fixture_compat_scope': 'Provider-level zai compat; model-level compat is not relied on.',+ 'check': 'Each operation schedules and persists a completed outcome. Every captured auxiliary request must match the exact expected control; request counts and full bodies remain in runs.'}try:- assert sys.platform == 'linux', 'requires Linux hosted CI and pinned Linux TS binary'- archive_hash = sha256(os.environ['PA_TS_ARCHIVE'])- assert archive_hash == TS_ARCHIVE_SHA256, 'TS archive hash mismatch'- result['ts_release_archive_sha256'] = archive_hash- binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- for label in ('ts', 'rust')}- result['binaries'] = {label: {'path': str(path), 'sha256': sha256(path)}- for label, path in binaries.items()}- with tempfile.TemporaryDirectory(prefix='minimum-reasoning-parity-') as temp:+ assert sys.platform == 'linux', 'requires Linux hosted CI'+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ result['binary'] = {'path': str(binary), 'sha256': digest(binary)}+ with tempfile.TemporaryDirectory(prefix='minimum-reasoning-check-') as temp:for scenario in ('compact', 'branch', 'refine'):- results = {}- for label, binary in binaries.items():- observation = {}- result['runs'][scenario + '_' + label] = observation- results[label] = run_case(binary, label, scenario,- Path(temp) / scenario / label, observation)- assert results['ts'] == results['rust'], results+ observation = result['runs'][scenario] = {}+ run_case(binary, scenario, Path(temp) / scenario, observation)result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_model_facts_parity.py b/scripts/check_model_facts.pysimilarity index 81%rename from scripts/review_model_facts_parity.pyrename to scripts/check_model_facts.pyindex 6deb50f007..e4b1b2a29f 100644--- a/scripts/review_model_facts_parity.py+++ b/scripts/check_model_facts.py@@ -1,13 +1,13 @@#!/usr/bin/env python3-"""Observe model.info and compact.status through actual TS/Rust daemon binaries.+"""Observe model.info and compact.status through the actual daemon binary.-Both sessions execute the same REPL cell before and after two explicit model+The session executes the same REPL cell before and after two explicit modelswitches. The first cell builds the kernel; later probes must use its survivingnamespace, exercising the daemon's live-core rebind rather than fresh startup.All provider requests and daemon responses are saved. Model facts and context-windows must match exactly. Other usage fields are reported, never normalized;-this verifier does not claim token-estimator parity. A retryable primary failure-then exercises backup-provider facts and automatic primary restoration.+windows must match the selected model exactly; token estimates are not checked.+A retryable primary failure then exercises backup-provider facts and automatic+primary restoration."""import argparseimport http.server@@ -21,9 +21,8 @@ import tempfileimport threadingimport time-from review_draft_disconnect_parity import env_for, stop-from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256-from review_restore_notice_parity import texts+from lifecycle_lib import digest, env_for, stop+from check_restore_notice import textsMARKER = 'MODEL_FACTS_PARITY='CELL = """import json@@ -158,14 +157,10 @@ class Client:self.sock.close()-def run_case(binary, label, root, observation):- env = env_for(root, label)+def run_case(binary, root, observation):+ env = env_for(root)env['PRIME_AGENT_MODEL_PROVIDER'] = 'fixture'env['PRIME_AGENT_MODEL'] = 'facts-text'- library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'- skill_paths = sorted(str(path) for path in library.glob('*/src') if path.is_dir())- assert skill_paths, 'Pinned TS fixture skill library missing'- env['PYTHONPATH'] = os.pathsep.join(skill_paths)server = Server()thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()@@ -227,10 +222,8 @@ def run_case(binary, label, root, observation):probe = latest_probe(requests[-1], 'call_facts_%s' % phase)observation['probes'].append(probe)if phase == 3:- # Observe before asserting cross-runtime parity: TS restores session- # facts at assistant message_end, before this backup tool executes.- # The Rust failover driver restores at turn settlement. Retain the- # actual facts; compare() must expose any difference.+ # The failover driver restores primary facts at turn settlement;+ # the persisted model changes below check that restore.assert probe['kernel_probe_count'] == phase + 1, probeassert probe['compact_status']['scheduled'] is False, probeelse:@@ -256,45 +249,22 @@ def run_case(binary, label, root, observation):thread.join(timeout=2)-def compare(result):- ts, rust = result['runs']['ts']['probes'], result['runs']['rust']['probes']- assert len(ts) == len(rust) == len(SEQUENCE)- result['complete_compact_status_equal'] = [- a['compact_status'] == b['compact_status'] for a, b in zip(ts, rust)]- for a, b in zip(ts, rust):- assert a['model_info'] == b['model_info'], 'model.info differs'- assert a['kernel_probe_count'] == b['kernel_probe_count'], 'kernel continuity differs'- assert a['compact_status']['context_window'] == b['compact_status']['context_window'], 'context window differs'--def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'verified': False, 'runs': {}, 'scope':+ result = {'verified': False, 'scope':'Actual daemon set_model, surviving kernel, model.info and compact.status context_window. ''Retryable primary failure -> backup-provider probe -> automatic primary restoration probe. '- 'Full compact.status values retained; token/percent estimator parity is not claimed.'}+ 'Full compact.status values retained; token/percent estimates are not checked.'}try:assert sys.platform == 'linux', 'Requires hosted Linux binaries and kernel'- archive_hash = sha256(os.environ['PA_TS_ARCHIVE'])- assert archive_hash == TS_ARCHIVE_SHA256, 'TS archive hash mismatch'- result['ts_release_archive_sha256'] = archive_hash- binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- for label in ('ts', 'rust')}- result['binaries'] = {label: {'path': str(path), 'sha256': sha256(path)}- for label, path in binaries.items()}+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ result['binary'] = {'path': str(binary), 'sha256': digest(binary)}# Keep Unix socket paths short, independent of RUNNER_TEMP/TMPDIR lengths.with tempfile.TemporaryDirectory(prefix='facts-', dir='/tmp') as temp:- for label, binary in binaries.items():- observation = result['runs'][label] = {}- try:- run_case(binary, label, Path(temp) / label, observation)- except Exception as error:- observation['error'] = str(error)- errors = {label: run['error'] for label, run in result['runs'].items() if 'error' in run}- assert not errors, errors- compare(result)+ observation = result['run'] = {}+ run_case(binary, Path(temp) / 'rust', observation)result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_new_goal_parity.py b/scripts/check_new_goal.pysimilarity index 77%rename from scripts/review_new_goal_parity.pyrename to scripts/check_new_goal.pyindex 2fee65e553..8e8a14b890 100644--- a/scripts/review_new_goal_parity.py+++ b/scripts/check_new_goal.py@@ -1,9 +1,9 @@#!/usr/bin/env python3-"""Compare /new PTY behavior and /goal image rows in actual TS/Rust binaries.+"""Check /new PTY behavior and /goal image rows in the actual binary.Owned daemons, homes, kernel state and loopback providers only. Receipts retainfull model requests and terminal output; no product state or credentials are used.-Requires the same pinned TS archive and kernel provisioned by lifecycle CI.+Requires the kernel provisioned by lifecycle CI."""import argparseimport http.server@@ -18,8 +18,7 @@ import tempfileimport threadingimport time-from review_draft_disconnect_parity import Terminal, env_for, stop, LIMIT-from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256+from lifecycle_lib import Terminal, digest, env_for, skill_pythonpath, stop, LIMITPROMPT = 'NEW_GOAL_PARITY_INITIAL_PROMPT'SETTLED = 'Parity fixture settled'@@ -84,17 +83,11 @@ class Handler(http.server.BaseHTTPRequestHandler):self.send_error(500, str(exc))-def setup(root, label, provider):+def setup(root, provider):root.mkdir(parents=True)- env = env_for(root, label)- if label == 'rust':- env['PA_COMPACTION_TRACE'] = 'stderr'- for key in ('PYTHONPATH', 'PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON'):- if key in os.environ:- env[key] = os.environ[key]- library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'- env['PYTHONPATH'] = os.pathsep.join(sorted(str(p) for p in library.glob('*/src'))- + [env.get('PYTHONPATH', '')])+ env = env_for(root)+ env['PA_COMPACTION_TRACE'] = 'stderr'+ env['PYTHONPATH'] = skill_pythonpath()env['PI_SESSION_DIR'] = env['PRIME_AGENT_SESSION_DIR'] = str(root / 'agent/sessions')(root / 'agent/models.json').write_text(json.dumps({'providers': {'parity-local': {'api': 'openai-completions', 'apiKey': 'fixture-only',@@ -128,12 +121,12 @@ def session_rows(root):return result-def new_case(binary, label, root, observation):+def new_case(binary, root, observation):provider = Provider(False)terminal = daemon = Nonepath = root / 'daemon.sock'try:- env = setup(root, label, provider)+ env = setup(root, provider)with (root / 'daemon.log').open('wb') as log:daemon = subprocess.Popen([str(binary), '--mode', 'daemon', '--daemon-socket', str(path)],cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)@@ -234,21 +227,20 @@ class Rpc:self.process.stderr.close()-def goal_case(binary, label, root, observation):+def goal_case(binary, root, observation):provider = Provider(True)rpc = Nonetry:- env = setup(root, label, provider)+ env = setup(root, provider)rpc = Rpc(binary, root, env)rpc.send({'type': 'prompt', 'id': 'goal-image', 'message': '/goal ' + OBJECTIVE,'images': [IMAGE]})response = rpc.until(lambda f: f.get('type') == 'response' and f.get('id') == 'goal-image')assert response.get('success'), response- # The changed surface is the goal-context carrier. RPC's existing Rust- # continuation path publishes an active update before the model turn,- # but not the tool's final complete update. Preserve that difference;- # query authoritative host state after agent_end rather than assuming- # the TS event-publication sequence or trusting fixture answer text.+ # The checked surface is the goal-context carrier. RPC's continuation+ # path publishes an active update before the model turn, but not the+ # tool's final complete update; query authoritative host state after+ # agent_end rather than trusting fixture answer text.rpc.until(lambda f: f.get('type') == 'agent_end')rpc.send({'type': 'get_state', 'id': 'settled-goal-state'})settled = rpc.until(lambda f: f.get('type') == 'response'@@ -290,44 +282,24 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'runs': {}, 'differences': {}, 'verified': False,+ result = {'runs': {}, 'verified': False,'scope': {'new': 'Real PTY command, owned real daemon, persisted name and model initial prompt.','goal': 'Actual RPC image-bearing goal_context row and completed goal.',- 'provider_images': 'Recorded independently; existing model-routing limitation is not normalized into context-row evidence.',- 'goal_updates': 'Recorded independently: Rust RPC publishes before continuation, not on goal.complete; final completion is verified by get_state after agent_end.'}}+ 'provider_images': 'Recorded only; existing model-routing limitation is not normalized into context-row evidence.',+ 'goal_updates': 'Recorded only: RPC publishes before continuation, not on goal.complete; final completion is verified by get_state after agent_end.'}}try:assert sys.platform == 'linux', 'requires Linux hosted CI'- archive_hash = sha256(os.environ['PA_TS_ARCHIVE'])- assert archive_hash == TS_ARCHIVE_SHA256, 'TS archive checksum mismatch'- result['ts_release_archive_sha256'] = archive_hash- binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- for label in ('ts', 'rust')}- result['binaries'] = {label: {'path': str(binary), 'sha256': sha256(binary)}- for label, binary in binaries.items()}- with tempfile.TemporaryDirectory(prefix='new-goal-parity-', dir='/tmp') as temp:+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ result['binary'] = {'path': str(binary), 'sha256': digest(binary)}+ with tempfile.TemporaryDirectory(prefix='new-goal-check-', dir='/tmp') as temp:for scenario, run in (('new', new_case), ('goal_images', goal_case)):- result['runs'][scenario] = {}- for label, binary in binaries.items():- observation = {}- result['runs'][scenario][label] = observation- try:- observation['surface'] = run(binary, label, Path(temp) / (scenario + '-' + label), observation)- except Exception as exc:- observation['error'] = str(exc)- ts, rust = result['runs'][scenario]['ts'], result['runs'][scenario]['rust']- if ts.get('surface') != rust.get('surface'):- result['differences'][scenario] = {'ts': ts.get('surface'), 'rust': rust.get('surface')}- failures = {scenario + '/' + label: run['error'] for scenario, runs in result['runs'].items()- for label, run in runs.items() if 'error' in run}- images = result['runs']['goal_images']- if all('provider_image_urls' in run for run in images.values()):- result['provider_image_routing_equal'] = (images['ts']['provider_image_urls']- == images['rust']['provider_image_urls'])- if all('goal_update_statuses' in run for run in images.values()):- result['goal_update_event_sequence_equal'] = (images['ts']['goal_update_statuses']- == images['rust']['goal_update_statuses'])+ observation = result['runs'][scenario] = {}+ try:+ observation['surface'] = run(binary, Path(temp) / scenario, observation)+ except Exception as exc:+ observation['error'] = str(exc)+ failures = {scenario: run['error'] for scenario, run in result['runs'].items() if 'error' in run}assert not failures, failures- assert not result['differences'], 'changed-surface parity mismatch'result['verified'] = Trueexcept Exception as exc:result['error'] = str(exc)diff --git a/scripts/review_observe_selectors_parity.py b/scripts/check_observe_selectors.pysimilarity index 90%rename from scripts/review_observe_selectors_parity.pyrename to scripts/check_observe_selectors.pyindex fd9b74e155..a9a2af6019 100644--- a/scripts/review_observe_selectors_parity.py+++ b/scripts/check_observe_selectors.py@@ -1,9 +1,9 @@#!/usr/bin/env python3-"""Actual resident agent_observe selector comparison, pinned TS vs Rust.+"""Actual resident agent_observe selector check.-Only identity/transcript selection, ambiguity and family rejection are compared.-Full summary/preview objects and differing rejection messages remain in receipt;-passive hydration, transient progress events and preview fidelity are excluded.+Only identity/transcript selection, ambiguity and family rejection are checked.+Full summary/preview objects remain in the receipt; passive hydration, transient+progress events and preview fidelity are excluded."""import argparseimport http.server@@ -16,10 +16,10 @@ import tempfileimport threadingimport time-from review_agent_bounce_parity import Client-from review_draft_disconnect_parity import digest, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish, verify_worker-from review_restore_notice_parity import texts+from check_agent_bounce import Client+from lifecycle_lib import digest, skill_pythonpath+from lifecycle_lib import OwnedProcesses, TAG, finish, verify_worker+from check_restore_notice import textsMARKER = 'OBSERVE_SELECTORS_PARITY='LIMIT = 35@@ -251,32 +251,27 @@ def selected(row, expected, marker):return {'selection': 'child-a', 'transcript_marker': marker}-def rejected(row, kind, label):+def rejected(row, kind):errors = [row[operation].get('error', '') for operation in ('get', 'recent')]assert all(errors), row # A successful foreign/ambiguous read is never accepted.if kind == 'ambiguous':assert all('Ambiguous active session' in error for error in errors), errorselse:- expected = ('Unknown active session:' if label == 'ts'- else 'is not reachable')- assert all(expected in error for error in errors), errors+ assert all('is not reachable' in error for error in errors), errorsreturn {'rejection': kind}-def run_case(binary, label, root, observation):+def run_case(binary, root, observation):for directory in ('home', 'tmp', 'work', 'agent', 'sessions'):(root / directory).mkdir(parents=True)root = root.resolve()env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ','PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}- library = Path(os.environ['PI_PACKAGE_DIR'])- if label == 'ts':- env['PI_PACKAGE_DIR'] = str(library)- env['PYTHONPATH'] = os.pathsep.join(str(path) for path in sorted((library / 'skills').glob('*/src')))env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1', PI_OFFLINE='1',PI_CODING_AGENT_DIR=str(root / 'agent'), PRIME_AGENT_CODING_AGENT_DIR=str(root / 'agent'),PI_SESSION_DIR=str(root / 'sessions'), PRIME_AGENT_SESSION_DIR=str(root / 'sessions'),- XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(root / 'cache'), XDG_DATA_HOME=str(root / 'data'))+ XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(root / 'cache'), XDG_DATA_HOME=str(root / 'data'),+ PYTHONPATH=skill_pythonpath())env[TAG] = str(root)provider = Provider()thread = threading.Thread(target=provider.serve_forever, daemon=True)@@ -419,16 +414,16 @@ print('OBSERVE_SELECTORS_PARITY=' + json.dumps({'children': [dataclasses.asdict('foreign_suffix': suffix(foreign['active'], ids)})for name in ('exact', 'active_suffix', 'durable_suffix', 'name'):contract[name] = selected(basic[name], a, 'OBSERVE_TASK_A')- contract['foreign_suffix'] = rejected(basic['foreign_suffix'], 'foreign-family', label)+ contract['foreign_suffix'] = rejected(basic['foreign_suffix'], 'foreign-family')client.call('rename', activeSessionId=b['active'], name=a['active'])collision = probe('collision', {'exact_id_over_name': a['active']})contract['exact_id_over_name'] = selected(collision['exact_id_over_name'], a, 'OBSERVE_TASK_A')client.call('rename', activeSessionId=b['active'], name='observe-child-b')- # Same-depth siblings cannot share a name in TS. Parent and child belong- # to distinct name namespaces, but both are reachable from the parent.+ # Parent and child belong to distinct name namespaces, but both are+ # reachable from the parent.client.call('rename', activeSessionId=parent['active'], name='observe-child-a')ambiguous = probe('ambiguity', {'duplicate_name': 'observe-child-a'})- contract['duplicate_name'] = rejected(ambiguous['duplicate_name'], 'ambiguous', label)+ contract['duplicate_name'] = rejected(ambiguous['duplicate_name'], 'ambiguous')# Selection is proven only for resident rows; no hydration or full summary equality.assert len(observation['worker_identities']) == 2, 'missing owned root-worker proof'assert set(provider.child_requests) == ALL_TASKS, 'missing live spawned-child proof'@@ -473,27 +468,19 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- receipt = {'verified': False, 'runs': {}, 'scope': 'Resident agent_observe.get/recent/list: exact active ID, '+ receipt = {'verified': False, 'scope': 'Resident agent_observe.get/recent/list: exact active ID, ''normalized active/durable ID suffix, exact name, exact ID/name precedence, ambiguous name, foreign family rejection.','not_verified': ['Passive child hydration', 'Transient progress-note event retention',- 'latestMessage/full summary field parity', 'Tool/image/bash preview fidelity', 'TUI/ACP presentation', 'RLM spawn/settle policy equivalence (real spawn is fixture setup only)'],- 'normalization': 'Dynamic IDs verified exactly inside each run, then compared by selected fixture identity. '- 'Foreign denial text differs (TS worker-local unknown selector vs Rust family-filtered unreachable); raw errors are retained. '- 'All summary/preview objects remain raw and are not claimed equal.',- 'ownership': 'pa-daemon internal family resolver; existing pa-core host bridge and Python skill unchanged; no new pub API/dependencies.'}+ 'latestMessage/full summary fields', 'Tool/image/bash preview fidelity', 'TUI/ACP presentation'],+ 'normalization': 'Dynamic IDs verified exactly inside the run, then recorded by selected fixture identity. '+ 'All summary/preview objects remain raw.'}try:assert sys.platform == 'linux', 'requires hosted Linux binaries'- assert digest(os.environ['PA_TS_ARCHIVE']) == TS_ARCHIVE_SHA256, 'TS archive SHA mismatch'- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256temp = tempfile.TemporaryDirectory(prefix='observe-selectors-')try:- for label in ('ts', 'rust'):- binary = Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- observation = receipt['runs'][label] = {'binary': str(binary), 'binary_sha256': digest(binary)}- run_case(binary, label, Path(temp.name) / label, observation)- assert receipt['runs']['ts']['contract'] == receipt['runs']['rust']['contract'], 'selector contract differs'- receipt['summary_field_presence'] = {label: run['summary_field_presence']- for label, run in receipt['runs'].items()}+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observation = receipt['run'] = {'binary': str(binary), 'binary_sha256': digest(binary)}+ run_case(binary, Path(temp.name) / 'rust', observation)receipt['verified'] = Truefinally:primary_pending = sys.exc_info()[0] is not Nonediff --git a/scripts/review_print_bash_parity.py b/scripts/check_print_bash.pysimilarity index 77%rename from scripts/review_print_bash_parity.pyrename to scripts/check_print_bash.pyindex 2ab670622e..135fcce89c 100644--- a/scripts/review_print_bash_parity.py+++ b/scripts/check_print_bash.py@@ -1,12 +1,9 @@#!/usr/bin/env python3-"""Actual TS/Rust print background completion wake, held until the first turn ends.--Both binaries receive identical REPL cells. A loopback HTTP gate holds the-background process. Expected difference: TS 0.9.8 --print exits after its-first turn without waiting for the command, so its gate opens only when the-process is gone (no wake, no notice); Rust print waits for it on purpose, so-its gate opens once the first turn ended, and the completion must wake a-second turn and persist the notice.+"""Actual print-mode background completion wake, held until the first turn ends.++A loopback HTTP gate holds the background process. Print mode waits for it, so+the gate opens once the first turn ended, and the completion must wake a second+turn and persist the notice."""import argparseimport http.server@@ -19,9 +16,9 @@ import sysimport tempfileimport threading-from review_draft_disconnect_parity import env_for, digest, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish-from review_restore_notice_parity import texts, probe_from+from lifecycle_lib import env_for, digest+from lifecycle_lib import OwnedProcesses, TAG, finish+from check_restore_notice import texts, probe_fromSTART = 'PRINT_BASH_STARTED='DONE = 'PRINT_BASH_FINISHED='@@ -37,7 +34,6 @@ class Provider(http.server.ThreadingHTTPServer):self.errors = []self.waiting_seen = Falseself.first_turn_ended = False- self.gate_timed_out = Falseclass Handler(http.server.BaseHTTPRequestHandler):@@ -49,7 +45,6 @@ class Handler(http.server.BaseHTTPRequestHandler):self.send_error(404)returnif not self.server.release.wait(75):- self.server.gate_timed_out = Trueself.send_error(504)returnpayload = b'BG_DONE'@@ -110,16 +105,8 @@ def validate(observed):assert observed['notice']['matches_started_pid'] is True-def validate_ts(observed):- # TS --print ends with its first turn: no wake request, no notice.- assert observed['first_turn_ended_before_release'] is True- assert observed['request_count'] == 2- assert observed['notice_count'] == 0- assert observed['gate_timed_out'] is False---def observe(binary, kind, root, observed):- env = env_for(root, kind)+def observe(binary, root, observed):+ env = env_for(root)env[TAG] = str(root)provider = Provider()thread = threading.Thread(target=provider.serve_forever, daemon=True)@@ -155,8 +142,7 @@ def observe(binary, kind, root, observed):provider.waiting_seen = Trueif event.get('type') == 'turn_end' and provider.waiting_seen and not provider.first_turn_ended:provider.first_turn_ended = True- if kind != 'ts':- provider.release.set()+ provider.release.set()reader = threading.Thread(target=read_events, daemon=True)reader.start()process.wait(timeout=110)@@ -169,12 +155,6 @@ def observe(binary, kind, root, observed):for line in path.read_text().splitlines()]notices = [row for row in rows if row.get('type') == 'custom_message'and row.get('customType') == 'async_bash_completion']- if kind == 'ts':- observed.update(first_turn_ended_before_release=provider.first_turn_ended,- request_count=len(provider.requests), notice_count=len(notices),- gate_timed_out=provider.gate_timed_out)- validate_ts(observed)- returnfinished = probe_from(provider.requests, DONE)assert len(notices) == 1, noticesnotice = notices[0]@@ -200,24 +180,21 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- result = {'verified': False, 'runs': {}, 'scope': __doc__, 'not_verified': [+ result = {'verified': False, 'scope': __doc__, 'not_verified': ['RPC wake/replacement (Rust e2e)', 'inline child background wake (Rust e2e)',- 'late agent-message receipt delivery (Rust regression)', 'full prompt/frame parity']}+ 'late agent-message receipt delivery (Rust regression)', 'prompt/frame content']}try:assert sys.platform == 'linux'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256- result['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-print-bash-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = result['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed)- observed['behavior_verified'] = True- except Exception as error:- observed['error'] = str(error)- assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r- for r in result['runs'].values()), 'actual print bash observation failed'+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = result['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ observed['behavior_verified'] = True+ except Exception as error:+ observed['error'] = str(error)+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual print bash observation failed'result['verified'] = Trueexcept Exception as error:result['error'] = str(error)diff --git a/scripts/review_private_default_frames_parity.py b/scripts/check_private_default_frames.pysimilarity index 82%rename from scripts/review_private_default_frames_parity.pyrename to scripts/check_private_default_frames.pyindex 6b54ed3182..3091230fcf 100644--- a/scripts/review_private_default_frames_parity.py+++ b/scripts/check_private_default_frames.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Actual TS/Rust fresh-startup model and warning captures, without inference.+"""Actual fresh-startup model and warning captures, without inference.Uses the shared fingerprinted authorization-cache format with synthetic key/teamand disables all external networking in a hosted-only network namespace. This@@ -7,7 +7,6 @@ measures fresh process startup from controlled cache states, not live catalogfetch timing. The current scoped-selection policy is characterized, not approved."""import argparse-import difflibimport fcntlimport hashlibimport hmac@@ -26,9 +25,9 @@ import termiosimport threadingimport time-from review_draft_disconnect_parity import Screen, TS_ARCHIVE_SHA256, digest, stop-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish-from review_kernel_env_parity import KernelClient+from lifecycle_lib import Screen, digest, stop+from lifecycle_lib import OwnedProcesses, TAG, finish+from check_kernel_env import KernelClientPUBLIC = 'z-ai/glm-5.3'PRIVATE = 'internal/glm-5.3-fast'@@ -55,7 +54,7 @@ def cache_document(authorized):'data': [private_item()] if authorized else []}-def prepare(root, label, scenario):+def prepare(root, scenario):for name in ('home', 'agent', 'sessions', 'work', 'tmp', 'xdg'):(root / name).mkdir(parents=True)agent = root / 'agent'@@ -85,8 +84,6 @@ def prepare(root, label, scenario):PI_SESSION_DIR=str(root / 'sessions'), PRIME_AGENT_SESSION_DIR=str(root / 'sessions'),PI_OFFLINE='1', DO_NOT_TRACK='1')env[TAG] = str(root)- if label == 'ts':- env['PI_PACKAGE_DIR'] = os.environ['PI_PACKAGE_DIR']return env@@ -185,8 +182,8 @@ def wait_for_created_session(terminal, client, active):if isinstance(response, dict) and response.get('success') is False:info = response.get('errorInfo') or {}if (response.get('error') == 'Unknown active session: ' + active- # Pinned TS requireAvailableWorkerClient reports its- # lifecycle before accepting forwarded state requests.+ # The daemon reports worker lifecycle before accepting+ # forwarded state requests.or response.get('error') in ('Session worker is starting','Session worker is recovering', 'Session worker is not connected')or (info.get('code') == 'session_recovering'@@ -198,13 +195,13 @@ def wait_for_created_session(terminal, client, active):return state-def validate_observation(label, scenario, observed):+def validate_observation(scenario, observed):permitted = [PUBLIC, PRIVATE] if scenario == 'authorized' else [PUBLIC]assert observed['selected_model'] in permitted, 'selected an unavailable or excluded model'available = observed['available_ids']assert PUBLIC in available, 'public fixture model is not available'assert (PRIVATE in available) == (scenario != 'unavailable'), 'authorization fixture was not adopted'- expected_warning = label == 'rust' and scenario == 'unavailable'+ expected_warning = scenario == 'unavailable'if expected_warning:assert observed['fallback_message'] and WARNING in observed['fallback_message'], 'missing warning on attach'assert 'Using prime-inference/' + observed['selected_model'] in observed['fallback_message'], 'warning names the wrong fallback'@@ -223,8 +220,8 @@ def validate_observation(label, scenario, observed):assert frame['warning_prefix_count'] <= int(expected_warning), 'duplicate or unexpected resized warning'-def capture(binary, label, scenario, root, directory, observed):- env = prepare(root, label, scenario)+def capture(binary, scenario, root, directory, observed):+ env = prepare(root, scenario)socket_path = root / 'd.sock'scope = OwnedProcesses(binary, root, socket_path)process = client = terminal = None@@ -254,7 +251,7 @@ def capture(binary, label, scenario, root, directory, observed):observed['fallback_message'] = summary.get('modelFallbackMessage')terminal.wait('visible startup frame', lambda: bool(terminal.screen.text().strip()))os.write(terminal.master, INPUT.encode())- expected_warning = label == 'rust' and scenario == 'unavailable'+ expected_warning = scenario == 'unavailable'terminal.wait('editor, selected model and startup warning', lambda: INPUT in terminal.screen.text()and selected in terminal.screen.text()and (not expected_warning or 'Default model prime-inference/' in terminal.screen.text()))@@ -280,7 +277,7 @@ def capture(binary, label, scenario, root, directory, observed):refreshed_model = connection_model(after_refresh) or {}assert (refreshed_model.get('provider'), refreshed_model.get('id')) == (model['provider'], selected), 'catalog read retargeted the active model'- validate_observation(label, scenario, observed)+ validate_observation(scenario, observed)observed['warning_present_after_resize'] = observed['frames']['80x28']['warning_prefix_count'] == 1observed['capture_verified'] = Trueexcept BaseException as error:@@ -309,45 +306,24 @@ def run(args):assert not routes and not routes_v6, 'capture namespace must have no external route'result = {'validation_passed': False, 'runs': {}, 'network_default_route': routes,'network_ipv6_default_route': routes_v6,- 'policy_decision_pending': True,'scope': 'Actual fresh TUI startup against owned daemons, matched PTY dimensions, signed synthetic authorization-cache states; no inference or external networking.',- 'limits': 'Does not exercise live catalog fetch timing, OS terminal font/pixel fidelity, or full application parity. SVGs render captured cells; raw ANSI preserves original attributes.',- 'expected_difference': 'The isolated TS findInitialModel resolver chooses the first scoped model, but TS main.ts buildSessionOptions first prefers an authorized saved default. Record the real startup selection without approving policy. Rust adds the requested-default-unavailable attach warning.',+ 'limits': 'Does not exercise live catalog fetch timing or OS terminal font/pixel fidelity. SVGs render captured cells; raw ANSI preserves original attributes.','source': {key: os.environ.get(key) for key in ('GITHUB_RUN_ID', 'GITHUB_SHA')}}try:if os.environ.get('GITHUB_EVENT_PATH'):event = json.loads(Path(os.environ['GITHUB_EVENT_PATH']).read_text())result['source']['pull_request_head_sha'] = event.get('pull_request', {}).get('head', {}).get('sha')- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256- binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- for label in ('ts', 'rust')}- result['binaries'] = {label: {'path': str(path), 'sha256': digest(path)}- for label, path in binaries.items()}+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ result['binary'] = {'path': str(binary), 'sha256': digest(binary)}output = args.receipt.with_suffix('')errors = []- result['comparisons'] = {}with tempfile.TemporaryDirectory(prefix='pa-startup-') as temp:for scenario in ('authorized', 'unavailable', 'excluded'):- for label, binary in binaries.items():- name = scenario + '-' + label- observed = result['runs'][name] = {}- try:- capture(binary, label, scenario, Path(temp) / name, output / name, observed)- except Exception as error:- errors.append({'case': name, 'error': str(error)})- pair = {label: result['runs'][scenario + '-' + label] for label in binaries}- result['comparisons'][scenario] = {label: {- 'selected_model': value.get('selected_model'),- 'fallback_message': value.get('fallback_message'),- 'warning_present_after_resize': value.get('warning_present_after_resize'),- 'capture_verified': value.get('capture_verified', False)} for label, value in pair.items()}- for size in ('120x40', '80x28'):- if not all(size in value.get('frames', {}) for value in pair.values()):- continue- left, right = (pair[label]['frames'][size]['text'] for label in ('ts', 'rust'))- (output / (scenario + '-' + size + '.diff')).write_text(''.join(- difflib.unified_diff(left.splitlines(True), right.splitlines(True),- fromfile='TS0.9.8', tofile='Rust')))+ observed = result['runs'][scenario] = {}+ try:+ capture(binary, scenario, Path(temp) / scenario, output / scenario, observed)+ except Exception as error:+ errors.append({'case': scenario, 'error': str(error)})assert not errors, errorsresult['validation_passed'] = Trueexcept BaseException as error:@@ -371,9 +347,8 @@ def main():args.receipt.parent.mkdir(parents=True, exist_ok=True)args.receipt.write_text(json.dumps({'validation_passed': False,'error': 'network namespace capture child has not completed'}) + '\n')- names = ('PATH', 'LANG', 'LC_ALL', 'TZ', 'PA_TS_ARCHIVE', 'PA_TS_BINARY',- 'PA_RUST_BINARY', 'PI_PACKAGE_DIR', 'GITHUB_ACTIONS', 'GITHUB_RUN_ID', 'GITHUB_SHA',- 'GITHUB_EVENT_PATH')+ names = ('PATH', 'LANG', 'LC_ALL', 'TZ', 'PA_RUST_BINARY', 'GITHUB_ACTIONS',+ 'GITHUB_RUN_ID', 'GITHUB_SHA', 'GITHUB_EVENT_PATH')values = [name + '=' + os.environ[name] for name in names if name in os.environ]return subprocess.run(['sudo', '-n', 'unshare', '--net', '/usr/bin/env', *values,sys.executable, str(Path(__file__).resolve()), '--isolated-network',diff --git a/scripts/review_queue_browse_parity.py b/scripts/check_queue_browse.pysimilarity index 65%rename from scripts/review_queue_browse_parity.pyrename to scripts/check_queue_browse.pyindex e913e17f5e..b877de163f 100644--- a/scripts/review_queue_browse_parity.py+++ b/scripts/check_queue_browse.py@@ -1,10 +1,9 @@#!/usr/bin/env python3-"""Actual ordinary TS/Rust PTY queue browsing and mutation comparison.+"""Actual ordinary PTY queue browsing and mutation check.-Operator-requested delta: Rust visits only user rows and swaps with the adjacent-user row; TS visits every projected item. Full decoded styled frames and raw-ANSI are retained, without claiming layout equality. A protocol fixture controls-only the queue snapshot; both clients parse real input and construct mutations.+Browsing visits only user rows and swaps with the adjacent user row. Full decoded+styled frames and raw ANSI are retained. A protocol fixture controls only the+queue snapshot; the client parses real input and constructs mutations."""import argparseimport copy@@ -17,10 +16,10 @@ import sysimport tempfileimport time-from review_agent_bounce_parity import Client-from review_dock_screen import DockScreen-from review_draft_disconnect_parity import Supervisor, Terminal, digest, env_for, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+from check_agent_bounce import Client+from lifecycle_lib import DockScreen+from lifecycle_lib import Supervisor, Terminal, digest, env_for+from lifecycle_lib import OwnedProcesses, TAG, finishUSER_A, USER_B = 'QUEUE_BROWSE_USER_A', 'QUEUE_BROWSE_USER_B'INTERNAL = 'Agent message received: QUEUE_BROWSE_INTERNAL'@@ -28,15 +27,11 @@ DRAFT = 'QUEUE_BROWSE_DRAFT'OLDER, NEWER, LATER = '\x1b[1;3A', '\x1b[1;3B', '\x1b[1;7B'-def check_mutation(kind, command):+def check_mutation(command):expected = {'type': 'mutate_queued_message', 'activeSessionId': 's1','lane': 'steering', 'index': 0, 'expectedText': USER_A,- 'mutation': {'type': 'move', 'direction': 1 if kind == 'ts' else 2}}- # TS places its request ID inside the command as well as its envelope.- # Retain that raw transport ID, compare only the addressed mutation here.- if 'id' in command:- assert isinstance(command['id'], str) and command['id'], command- assert {key: value for key, value in command.items() if key != 'id'} == expected, command+ 'mutation': {'type': 'move', 'direction': 2}}+ assert command == expected, commandclass QueueSupervisor(Supervisor):@@ -53,7 +48,7 @@ class QueueSupervisor(Supervisor):name = data.get('command')if data.get('type') == 'daemon_hello':# Advertise the actual queue-mutation protocol this subclass owns.- # The shared draft-only server deliberately omits this capability.+ # The base fixture server deliberately omits this capability.data['serverCapabilities'] = ['session_input_admission', 'queue_message_mutation']if data.get('type') == 'response':if name == 'attach':@@ -109,8 +104,8 @@ def frame(terminal):'unsupported_terminal': terminal.screen.unsupported_terminal[:]}-def observe(binary, kind, root, internal_only, observed):- env = env_for(root, kind)+def observe(binary, root, internal_only, observed):+ env = env_for(root)env[TAG] = str(root)hello_cleanup = observed['hello_discovery'] = {}hello = discover_hello(binary, root, env, hello_cleanup)@@ -126,42 +121,34 @@ def observe(binary, kind, root, internal_only, observed):def snap(label, predicate):terminal.wait(label, lambda: predicate(terminal.screen.text()), server)observed['frames'][label] = copy.deepcopy(frame(terminal))- snap('initial', lambda text: server.attaches > 0 and (INTERNAL in text if kind == 'ts' else '1 agent message' in text))+ snap('initial', lambda text: server.attaches > 0 and '1 agent message' in text)terminal.send(DRAFT)snap('draft', lambda text: DRAFT in text)if internal_only:- if kind == 'rust':- assert 'to browse and edit queued messages' not in terminal.screen.text()+ assert 'to browse and edit queued messages' not in terminal.screen.text()terminal.send(OLDER)- if kind == 'rust':- # The next typed character is an input-order barrier: Alt+Up was- # handled before this character, so no absence-by-sleep assertion.- terminal.send('_BARRIER')- snap('internal_only_input', lambda text: DRAFT + '_BARRIER' in text)- assert 'enter steers' not in terminal.screen.text()- else:- snap('internal_only_input', lambda text: 'steering 1' in text and 'enter steers' in text)+ # The next typed character is an input-order barrier: Alt+Up was+ # handled before this character, so no absence-by-sleep assertion.+ terminal.send('_BARRIER')+ snap('internal_only_input', lambda text: DRAFT + '_BARRIER' in text)+ assert 'enter steers' not in terminal.screen.text()else:terminal.send(OLDER)- snap('newest', lambda text: ('steering 3' if kind == 'ts' else 'steering 2') in text and 'enter steers' in text)+ snap('newest', lambda text: 'steering 2' in text and 'enter steers' in text)terminal.send(OLDER)- snap('older', lambda text: ('steering 2' if kind == 'ts' else 'steering 1') in text and 'enter steers' in text)+ snap('older', lambda text: 'steering 1' in text and 'enter steers' in text)terminal.send(OLDER)- if kind == 'ts':- snap('oldest', lambda text: 'steering 1' in text and 'enter steers' in text)- else:- # At the oldest boundary, an input barrier proves the no-op was- # processed; restore text so the reorder expectedText stays original.- terminal.send('_BARRIER')- snap('oldest', lambda text: USER_A + '_BARRIER' in text)- terminal.send('\x7f' * len('_BARRIER'))- snap('oldest_restored', lambda text: USER_A + '_BARRIER' not in text and 'steering 1' in text)+ # At the oldest boundary, an input barrier proves the no-op was+ # processed; restore text so the reorder expectedText stays original.+ terminal.send('_BARRIER')+ snap('oldest', lambda text: USER_A + '_BARRIER' in text)+ terminal.send('\x7f' * len('_BARRIER'))+ snap('oldest_restored', lambda text: USER_A + '_BARRIER' not in text and 'steering 1' in text)terminal.send(LATER)terminal.wait('reorder command', lambda: len(server.mutations) == 1, server)- check_mutation(kind, server.mutations[0])- snap('reordered', lambda text: ('steering 2' if kind == 'ts' else 'steering 2') in text and 'enter steers' in text)- expected = [INTERNAL, USER_A, USER_B] if kind == 'ts' else [USER_B, INTERNAL, USER_A]- assert server.queue == {'steering': expected, 'followUp': []}, server.queue+ check_mutation(server.mutations[0])+ snap('reordered', lambda text: 'steering 2' in text and 'enter steers' in text)+ assert server.queue == {'steering': [USER_B, INTERNAL, USER_A], 'followUp': []}, server.queueassert not server.prompts, 'browse submitted a prompt'assert not terminal.screen.unsupported_sgr and not terminal.screen.unsupported_terminal, 'unsupported terminal sequences'observed['behavior_verified'] = True@@ -202,24 +189,22 @@ def main():parser.add_argument('--receipt', required=True, type=Path)args = parser.parse_args()receipt = {'verified': False, 'scope': __doc__, 'runs': {},- 'not_verified': ['real daemon queue admission (separate queue_priority fixture)',+ 'not_verified': ['real daemon queue admission (separate queue_priority check)','pixel/font equality', 'delete/replace/attachments', 'wire-typed child and continuation riders (Rust units)']}try:assert sys.platform == 'linux', 'hosted Linux only'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'reference archive mismatch'- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-qbrowse-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- for internal_only in (False, True):- label = kind + ('_internal_only' if internal_only else '_mixed')- observed = receipt['runs'][label] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / label, internal_only, observed)- except Exception as error:- observed['error'] = str(error)+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ receipt['binary_sha256'] = digest(binary)+ for internal_only in (False, True):+ label = 'internal_only' if internal_only else 'mixed'+ observed = receipt['runs'][label] = {}+ try:+ observe(binary, Path(folder) / label, internal_only, observed)+ except Exception as error:+ observed['error'] = str(error)assert all(run.get('behavior_verified') and run.get('cleanup_verified') and 'error' not in run- for run in receipt['runs'].values()), 'actual PTY comparison failed'+ for run in receipt['runs'].values()), 'actual PTY check failed'receipt['verified'] = Trueexcept Exception as error:receipt['error'] = str(error)diff --git a/scripts/review_queue_priority_parity.py b/scripts/check_queue_priority.pysimilarity index 77%rename from scripts/review_queue_priority_parity.pyrename to scripts/check_queue_priority.pyindex d78e3233ae..45d273ae74 100644--- a/scripts/review_queue_priority_parity.py+++ b/scripts/check_queue_priority.py@@ -1,9 +1,8 @@#!/usr/bin/env python3-"""Actual protocol-7 daemon comparison for a follow-up edited into steering.+"""Actual protocol-7 daemon check for a follow-up edited into steering.-Pinned TS appends a re-laned item; Rust preserves existing admission priority.-The measured intentional delta is retained, not normalized into equality. The-reverse move into a plain-user lane is a shared baseline. No model is external.+The re-laned item keeps its existing admission priority, ahead of a later agent+message; the reverse move into a plain-user lane restores it. No model is external."""import argparseimport json@@ -14,21 +13,20 @@ import sysimport tempfileimport threading-from review_agent_bounce_parity import Client, Provider-from review_draft_disconnect_parity import digest, env_for, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+from check_agent_bounce import Client, Provider+from lifecycle_lib import digest, env_for+from lifecycle_lib import OwnedProcesses, TAG, finishEARLIER, DRAFT, EDITED = 'QUEUE_PRIORITY_EARLIER', 'QUEUE_PRIORITY_DRAFT', 'QUEUE_PRIORITY_EDITED'AGENT = 'QUEUE_PRIORITY_AGENT'-def check_order(kind, queue, agent_preview):- expected = [EARLIER, agent_preview, EDITED] if kind == 'ts' else [EARLIER, EDITED, agent_preview]- assert queue == {'steering': expected, 'followUp': []}, queue+def check_order(queue, agent_preview):+ assert queue == {'steering': [EARLIER, EDITED, agent_preview], 'followUp': []}, queue-def observe(binary, kind, root, observed):- env = env_for(root, kind)+def observe(binary, root, observed):+ env = env_for(root)env[TAG] = str(root)provider = Provider()threading.Thread(target=provider.serve_forever, daemon=True).start()@@ -78,7 +76,7 @@ def observe(binary, kind, root, observed):assert response == {'status': 'applied'}, responseafter = receiver.call('get_queue', activeSessionId=target)observed['after'] = after- check_order(kind, after, agent_preview)+ check_order(after, agent_preview)# Reverse direction retains existing users; internal target-lane admission# in BOTH directions remains covered by the worker integration regression.receiver.call('follow_up', activeSessionId=target, message='QUEUE_REVERSE_EARLIER')@@ -111,23 +109,20 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', required=True, type=Path)args = parser.parse_args()- receipt = {'verified': False, 'scope': __doc__, 'runs': {},+ receipt = {'verified': False, 'scope': __doc__,'not_verified': ['TUI key/render path', 'internal follow-up target lane (worker integration test covers it)','forced Esc batch execution', 'restart recovery', 'full wire byte equality (IDs/timestamps differ)']}try:assert sys.platform == 'linux', 'hosted Linux only'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'reference archive mismatch'- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-qpriority-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = receipt['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed)- except Exception as error:- observed['error'] = str(error)- assert all(run.get('behavior_verified') and run.get('cleanup_verified') and 'error' not in run- for run in receipt['runs'].values()), 'actual daemon observation failed'+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = receipt['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ except Exception as error:+ observed['error'] = str(error)+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual daemon observation failed'receipt['verified'] = Trueexcept Exception as error:receipt['error'] = str(error)diff --git a/scripts/review_reconnect_version_parity.py b/scripts/check_reconnect_version.pysimilarity index 67%rename from scripts/review_reconnect_version_parity.pyrename to scripts/check_reconnect_version.pyindex 81efd2b0d1..a60c466314 100644--- a/scripts/review_reconnect_version_parity.py+++ b/scripts/check_reconnect_version.py@@ -1,12 +1,11 @@#!/usr/bin/env python3-"""Compare actual TS/Rust reconnect banners, recording the SemVer correction.+"""Check actual reconnect banners and their SemVer restart advice.-The pinned TS runtime treats an all-numeric suffix as another release segment;-Rust deliberately corrects that invalid precedence. Raw screens and both actual-versions are retained. The ordinary post-reconnect command catalog response is-held until capture because TS resync can erase the transient status before paint.-This checks version advice, not restart durability. No fake renderer or extracted-comparator executes here.+An all-numeric prerelease suffix is older than its release, so it never asks for+a window restart. Raw screens and actual versions are retained. The ordinary+post-reconnect command catalog response is held until capture so a resync cannot+erase the transient status before paint. This checks version advice, not restart+durability. No fake renderer or extracted comparator executes here."""import argparseimport errno@@ -19,8 +18,7 @@ import tempfileimport threadingimport uuid-from review_draft_disconnect_parity import (Supervisor, Terminal, actual_hello,- digest, env_for, fixture_state, TS_ARCHIVE_SHA256)+from lifecycle_lib import Supervisor, Terminal, actual_hello, digest, env_for, fixture_statedef runtime_version(binary, root, env):@@ -41,9 +39,9 @@ class RestartSupervisor(Supervisor):def send(self, sock, data):if self.closed and data.get('type') == 'response' and data.get('command') == 'get_commands':- # TS shows the status before its asynchronous resync rebuild clears- # the transcript. Hold that rebuild at its ordinary catalog request- # so a real terminal frame can expose the comparator's banner.+ # A resync rebuild can clear the transcript after the status shows.+ # Hold that rebuild at its ordinary catalog request so a real+ # terminal frame can expose the banner.self.catalog_held.set()if not self.release_catalog.wait(35):raise TimeoutError('restart catalog gate was not released')@@ -61,7 +59,7 @@ class RestartSupervisor(Supervisor):super().send(sock, data)def restart(self, version):- # Both clients reserve the versioned restart banner for an announced+ # The client reserves the versioned restart banner for an announced# daemon shutdown/update. A bare EOF exercises transport recovery and# emits a different generic reconnect status.with self.lock:@@ -80,9 +78,9 @@ class RestartSupervisor(Supervisor):raise-def run_case(kind, binary, root, hello, client, name, observed=None):+def run_case(binary, root, hello, client, name, observed=None):root.mkdir()- env = env_for(root, kind)+ env = env_for(root)base = client.split('+')[0].split('-')[0]parts = [int(x) for x in base.split('.')]newer = f'{parts[0] + 1}.0.0'@@ -110,9 +108,8 @@ def run_case(kind, binary, root, hello, client, name, observed=None):and 'Daemon restarted (v' in terminal.screen.text(), server)screen = terminal.screen.text()actual_advice = 'restart the window to pick up the update.' in screen- # This explicitly documents the baseline TS defect corrected by #3566.- expected_advice = name == 'newer' or (kind == 'ts' and name == 'numeric_prerelease')- assert actual_advice == expected_advice, (kind, name, screen)+ expected_advice = name == 'newer'+ assert actual_advice == expected_advice, (name, screen)if name == 'same':expected = f'Daemon restarted (v{daemon}) - reconnected'elif expected_advice:@@ -151,36 +148,25 @@ def main():parser = argparse.ArgumentParser()parser.add_argument('--receipt', required=True)args = parser.parse_args()- receipt = {'scenario': 'reconnect_version', 'ts_archive_expected_sha256': TS_ARCHIVE_SHA256,+ receipt = {'scenario': 'reconnect_version','fixture': 'Announced shutdown/session_closed, durable attach/list identity, successor hello; ordinary resync command catalog response held until actual banner capture.','scope': 'Actual rendered version advice; not restart durability or uninterrupted banner visibility.',- 'intentional_difference': 'TS interprets numeric prerelease -20 as a release segment; Rust correctly treats it as older than the release.',- 'observations': {}, 'passed': False}+ 'cases': {}, 'passed': False}try:- receipt['ts_archive_sha256'] = digest(Path(os.environ['PA_TS_ARCHIVE']))- assert receipt['ts_archive_sha256'] == TS_ARCHIVE_SHA256- with tempfile.TemporaryDirectory(prefix='pa-reconnect-parity-', dir='/tmp') as temp:- for kind, variable in (('ts', 'PA_TS_BINARY'), ('rust', 'PA_RUST_BINARY')):- binary = Path(os.environ[variable]).resolve()- root = Path(temp) / kind- root.mkdir()- env = env_for(root, kind)- client = runtime_version(binary, root, env)- # Fixture expects current stable binaries; prerelease algorithm edges- # are separately covered by red-first exact production-module tests.- assert '-' not in client and '+' not in client, client- hello = actual_hello(binary, root, env)- receipt['observations'][kind] = {'binary_sha256': digest(binary),- 'actual_hello': hello, 'client_version': client,- 'cases': {}}- for name in ('same', 'newer', 'older', 'metadata', 'numeric_prerelease'):- observed = receipt['observations'][kind]['cases'][name] = {}- run_case(kind, binary, root / name, hello, client, name, observed)- ts, rust = (receipt['observations'][kind]['cases'] for kind in ('ts', 'rust'))- for name in ('same', 'newer', 'older', 'metadata'):- assert ts[name]['restart_advice'] == rust[name]['restart_advice'], name- assert ts['numeric_prerelease']['restart_advice'] is True- assert rust['numeric_prerelease']['restart_advice'] is False+ with tempfile.TemporaryDirectory(prefix='pa-reconnect-check-', dir='/tmp') as temp:+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ root = Path(temp) / 'rust'+ root.mkdir()+ env = env_for(root)+ client = runtime_version(binary, root, env)+ # Fixture expects a current stable binary; prerelease algorithm edges+ # are separately covered by red-first exact production-module tests.+ assert '-' not in client and '+' not in client, client+ hello = actual_hello(binary, root, env)+ receipt.update(binary_sha256=digest(binary), actual_hello=hello, client_version=client)+ for name in ('same', 'newer', 'older', 'metadata', 'numeric_prerelease'):+ observed = receipt['cases'][name] = {}+ run_case(binary, root / name, hello, client, name, observed)receipt['passed'] = Trueexcept Exception as error:receipt['error'] = f'{type(error).__name__}: {error}'diff --git a/scripts/review_restore_notice_parity.py b/scripts/check_restore_notice.pysimilarity index 71%rename from scripts/review_restore_notice_parity.pyrename to scripts/check_restore_notice.pyindex 02c5faf87d..8cda797083 100644--- a/scripts/review_restore_notice_parity.py+++ b/scripts/check_restore_notice.py@@ -1,9 +1,8 @@#!/usr/bin/env python3-"""Compare real TS/Rust resume behavior, recording #3525's intended notice addition.+"""Check real resume behavior and #3525's restore notice.-Runs the same setup, resume, and acknowledgement fixture against the pinned TS 0.9.8 release and Rust.-Both must revive a namespace while resetting cwd/env; Rust alone must disclose-that reset. Only the exact added sentence is excluded from notice parity.+Runs a setup, resume, and acknowledgement fixture. The binary must revive a+namespace while resetting cwd/env, and the notice must disclose that reset.All provider traffic, homes, sessions, and subprocesses belong to this fixture."""import argparse@@ -19,7 +18,7 @@ import tempfileimport threadingimport time-from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256+from lifecycle_lib import digest, skill_pythonpathRESET = ("The working directory and environment variables were reset to the session defaults; ""re-apply any os.chdir(...) or os.environ[...] changes you still need.")@@ -157,35 +156,25 @@ def skill_availability(requests):'model_visible': {name: name in names for name in SKILLS}}-def validate_skill_availability(runs):- for label, expected in [('ts', True), ('rust', False)]:- actual = runs[label]['skill_availability']- assert actual == {- 'preimports': {'agent_message': True, 'agent_observe': expected,- 'rlm_heartbeat': expected},- 'model_visible': {'agent-message': True, 'agent-observe': expected,- 'rlm-heartbeat': expected}}, (label, actual)+def validate_skill_availability(actual):+ """Print mode hides the unwired agent-observe and rlm-heartbeat skills."""+ assert actual == {+ 'preimports': {'agent_message': True, 'agent_observe': False, 'rlm_heartbeat': False},+ 'model_visible': {'agent-message': True, 'agent-observe': False, 'rlm-heartbeat': False}}, actual-def run_case(binary, label, root, observation):+def run_case(binary, root, observation):for name in ('home', 'agent', 'sessions', 'work', 'tmp'):(root / name).mkdir(parents=True)cwd, agent, sessions = root / 'work', root / 'agent', root / 'sessions'env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ',- 'PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON', 'PYTHONPATH') if key in os.environ}- if label == 'ts' and 'PI_PACKAGE_DIR' in os.environ:- env['PI_PACKAGE_DIR'] = os.environ['PI_PACKAGE_DIR']+ 'PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1',PI_OFFLINE='1', PI_CODING_AGENT_DIR=str(agent),PRIME_AGENT_CODING_AGENT_DIR=str(agent), PI_SESSION_DIR=str(sessions),PRIME_AGENT_SESSION_DIR=str(sessions), XDG_CONFIG_HOME=str(root / 'config'),- XDG_CACHE_HOME=str(root / 'cache'), XDG_DATA_HOME=str(root / 'data'))- # Both runtimes receive the same fixture skill library. This isolates the- # restore notice from different installed/bundled skill discovery paths.- library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'- skill_paths = sorted(str(path) for path in library.glob('*/src') if path.is_dir())- env['PYTHONPATH'] = os.pathsep.join(skill_paths + [env.get('PYTHONPATH', '')])- observation['fixture_pythonpath'] = env['PYTHONPATH']+ XDG_CACHE_HOME=str(root / 'cache'), XDG_DATA_HOME=str(root / 'data'),+ PYTHONPATH=skill_pythonpath())server = Server(root)thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()@@ -227,10 +216,8 @@ def run_case(binary, label, root, observation):for phase, requests in server.requests.items()})actual = probe_from(server.requests['resume'], PROBE)assert actual == {'marker': 'namespace-survived', 'cwd': str(cwd), 'env': None}, actual- # TS queues a restore triggered by the first cell for the next user turn- # (sendCustomMessage(nextTurn), consumed during prompt preparation).- # Submit the same acknowledgement prompt to both binaries and record- # every request, including any pre-existing delivery-timing difference.+ # A restore triggered by the first cell is queued for the next user turn;+ # the acknowledgement prompt must carry it. Every request is recorded.notice_request_numbers = [i + 1 for i, body in enumerate(server.requests['resume'])if notices_in(body)]notices = notices_in(server.requests['resume'][-1])@@ -243,7 +230,7 @@ def run_case(binary, label, root, observation):assert len(stored) == 1 and stored[0].get('display') is True, storedstored_notice = '\n'.join(texts(stored[0].get('content')))assert stored_notice in notice, 'provider must receive the persisted notice'- assert (RESET in stored_notice) == (label == 'rust'), stored_notice+ assert RESET in stored_notice, stored_noticereturn {'version': version['stdout'].strip(), 'setup': setup_probe,'restored': {**actual, 'cwd': '<session-cwd>'},'notice': stored_notice, 'notice_request_numbers': notice_request_numbers,@@ -263,63 +250,26 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', type=Path, required=True)args = parser.parse_args()- binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()- for label in ('ts', 'rust')}+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()assert sys.platform == 'linux', 'requires Linux hosted CI'- archive_hash = sha256(os.environ['PA_TS_ARCHIVE'])- assert archive_hash == TS_ARCHIVE_SHA256, 'TS release archive hash mismatch'- result = {'ts_release_archive_sha256': archive_hash,- 'binaries': {label: {'path': str(path), 'sha256': sha256(path)}- for label, path in binaries.items()},- 'intended_difference': RESET,- 'tool_name_normalization': 'Select offered python_repl or legacy ipython; identical cell code.',+ result = {'binary': {'path': str(binary), 'sha256': digest(binary)},+ 'tool_name_normalization': 'Select offered python_repl or legacy ipython.','fixture_prerequisites': [- 'Wait for observable nonempty debounced snapshot before setup final answer in both binaries.',- 'Existing Rust print shutdown disposes descendants but does not await root snapshot; no disposal parity claimed.',- 'Both kernels receive the same pinned TS skills/src library via PYTHONPATH; initial preimports and prompt inventory are separately asserted before explicit equal restore imports.'],- 'runs': {}, 'verified': False}+ 'Wait for observable nonempty debounced snapshot before setup final answer.',+ 'Print shutdown disposes descendants but does not await root snapshot.',+ 'Initial preimports and prompt inventory are asserted before explicit restore imports.'],+ 'run': {}, 'verified': False}try:- with tempfile.TemporaryDirectory(prefix='restore-notice-parity-') as temp:- for label, binary in binaries.items():- observation = {}- result['runs'][label] = observation- try:- observation.update(run_case(binary, label, Path(temp) / label, observation))- except Exception as error:- observation['error'] = str(error)- ts, rust = result['runs']['ts'], result['runs']['rust']- errors = {label: run['error'] for label, run in result['runs'].items() if 'error' in run}- assert not errors, errors- validate_skill_availability(result['runs'])- assert rust['notice'].removesuffix('\n' + RESET) == ts['notice'], 'additional notice difference'- assert rust['restored'] == ts['restored'], 'restored state differs'- assert rust['request_counts'] == ts['request_counts'] == {'setup': 2, 'resume': 3}- result['notice_timing_equal'] = ts['notice_request_numbers'] == rust['notice_request_numbers']- result['timing_scope'] = ('Observed, not normalized: #3525 changes only notice_content and its tests; '- 'kernel boot and next-turn queue timing are unchanged from base Rust. '- 'Both binaries must deliver the notice by the acknowledgement prompt.')+ with tempfile.TemporaryDirectory(prefix='restore-notice-check-') as temp:+ observation = result['run']+ observation.update(run_case(binary, Path(temp) / 'rust', observation))+ validate_skill_availability(observation['skill_availability'])+ assert observation['request_counts'] == {'setup': 2, 'resume': 3}, observation['request_counts']result['verified'] = Trueexcept Exception as error:result['error'] = str(error)args.receipt.parent.mkdir(parents=True, exist_ok=True)args.receipt.write_text(json.dumps(result, indent=2) + '\n')- availability = {- 'ts_release_archive_sha256': archive_hash,- 'binaries': result['binaries'],- 'scope': 'Actual initial print REPL preimports and model-visible inventory, before equal restore fixture imports.',- 'intended_difference': 'Rust hides unwired agent-observe and rlm-heartbeat; TS print exposes them. agent-message stays visible.',- 'not_verified': ['RPC/daemon skill availability', 'controller handler operation',- 'background bash wake/quiescence', 'late-receipt delivery'],- 'runs': {label: run.get('skill_availability') for label, run in result['runs'].items()},- 'verified': False,- }- try:- validate_skill_availability(result['runs'])- availability['verified'] = True- except Exception as error:- availability['error'] = str(error)- args.receipt.with_name('headless_skill_availability.json').write_text(- json.dumps(availability, indent=2) + '\n')print(json.dumps({'receipt': str(args.receipt), 'verified': result['verified'],'error': result.get('error')}))return 0 if result['verified'] else 1diff --git a/scripts/review_saved_catalog_parity.py b/scripts/check_saved_catalog.pysimilarity index 72%rename from scripts/review_saved_catalog_parity.pyrename to scripts/check_saved_catalog.pyindex eb580884d9..614bdcce14 100644--- a/scripts/review_saved_catalog_parity.py+++ b/scripts/check_saved_catalog.py@@ -1,9 +1,8 @@#!/usr/bin/env python3-"""Actual TS/Rust saved-catalog baseline and Rust paging evidence.+"""Actual saved-catalog listing and limit/cursor paging evidence.-No UI/frame parity is claimed. Historical TS ignores optional limit/cursor;-Rust intentionally adds a bounded walk. Both actual daemons read the same-synthetic saved-session corpus without create, prompt, provider or kernel.+No UI/frame claim. The actual daemon reads a synthetic saved-session corpus+without create, prompt, provider or kernel, and pages it newest-first."""import argparsefrom datetime import datetime, timezone@@ -14,9 +13,9 @@ import subprocessimport sysimport tempfile-from review_agent_bounce_parity import Client-from review_draft_disconnect_parity import digest, env_for, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+from check_agent_bounce import Client+from lifecycle_lib import digest, env_for+from lifecycle_lib import OwnedProcesses, TAG, finishCOUNT = 205PAGE = 200@@ -86,10 +85,6 @@ def same_rows(actual, expected):expected, key=lambda row: row['id']), 'catalog stable fields differ'-def ts_ignores_paging(call):- assert set(call['final_data']) == {'sessions'}, 'TS paging shape changed; inspect before updating expectation'--class RawReader:def __init__(self, reader, received):self.reader, self.received = reader, received@@ -143,7 +138,7 @@ def validate_query(call, root, expected, *, ordered=False, remaining=None, cursorows = normalize(data.get('sessions'), root)same_rows(rows, expected)if ordered:- assert rows == expected, 'Rust catalog is not deterministic newest-first'+ assert rows == expected, 'catalog is not deterministic newest-first'finals = [frame for frame in call['frames'] if frame.get('type') == 'response']assert len(finals) == 1, 'missing/duplicate terminal response'final = finals[0]@@ -165,7 +160,7 @@ def validate_query(call, root, expected, *, ordered=False, remaining=None, cursoassert frame.get('type') == 'session_list_progress', frameassert 0 <= frame['loaded'] <= frame['total'], frameprogress.append(frame)- # Rust may drop progress/item frames under backpressure. Final rows are+ # The daemon may drop progress/item frames under backpressure. Final rows are# authoritative; streamed rows must be unique, correct members of that final.streamed = normalize(items, root)assert streamed and progress, 'no catalog stream observed'@@ -173,7 +168,7 @@ def validate_query(call, root, expected, *, ordered=False, remaining=None, cursoassert all(by_id.get(row['id']) == row for row in streamed), 'stream/final disagreement'if ordered:streamed_ids = {row['id'] for row in streamed}- assert streamed == [row for row in rows if row['id'] in streamed_ids], 'Rust stream order differs from final'+ assert streamed == [row for row in rows if row['id'] in streamed_ids], 'stream order differs from final'if remaining is not None:assert data.get('remaining') == remaining, 'incorrect remaining count'if cursor:@@ -183,8 +178,8 @@ def validate_query(call, root, expected, *, ordered=False, remaining=None, cursoreturn rows-def observe(binary, kind, root, observed, ts_cursor=None):- env = env_for(root, kind)+def observe(binary, root, observed):+ env = env_for(root)env[TAG] = str(root)(root / 'agent/settings.json').write_text(json.dumps({'prewarmPythonKernel': False, 'sessionArchiveMaxSessions': 'off',@@ -209,44 +204,24 @@ def observe(binary, kind, root, observed, ts_cursor=None):client = CatalogClient(path, daemon)observed['hello'] = client.hellobaseline = query(client, observed, 'unbounded')- observed['baseline_rows'] = validate_query(baseline, root, expected,- ordered=kind == 'rust', remaining=0 if kind == 'rust' else None)- if kind == 'ts':- ts_ignores_paging(baseline)+ observed['baseline_rows'] = validate_query(baseline, root, expected, ordered=True, remaining=0)first = query(client, observed, 'limit_200', limit=PAGE)- if kind == 'rust':- validate_query(first, root, expected[:PAGE], ordered=True,- remaining=COUNT - PAGE, cursor=True)- cursor = first['final_data']['nextCursor']- observed['continuation_cursor'] = cursor- else:- # Historical TS has no paging semantics. Unexpected acceptance is- # RED, not silently reclassified as intentional parity.- validate_query(first, root, expected)- ts_ignores_paging(first)- cursor = ts_cursor- assert isinstance(cursor, str) and cursor, 'actual Rust cursor unavailable'- observed['optional_paging_behavior'] = 'limit and cursor ignored; complete catalog returned'+ validate_query(first, root, expected[:PAGE], ordered=True,+ remaining=COUNT - PAGE, cursor=True)+ cursor = first['final_data']['nextCursor']+ observed['continuation_cursor'] = cursorrest = query(client, observed, 'continuation', cursor=cursor)- validate_query(rest, root, expected[PAGE:] if kind == 'rust' else expected,- ordered=kind == 'rust', remaining=0 if kind == 'rust' else None)- if kind == 'rust':- joined = normalize(first['final_data']['sessions'] + rest['final_data']['sessions'], root)- assert joined == expected, 'pages did not cover full catalog exactly once'- assert TARGET not in json.dumps(first['final_data']['sessions'])- assert rest['final_data']['sessions'][-1]['name'] == TARGET- else:- ts_ignores_paging(rest)+ validate_query(rest, root, expected[PAGE:], ordered=True, remaining=0)+ joined = normalize(first['final_data']['sessions'] + rest['final_data']['sessions'], root)+ assert joined == expected, 'pages did not cover full catalog exactly once'+ assert TARGET not in json.dumps(first['final_data']['sessions'])+ assert rest['final_data']['sessions'][-1]['name'] == TARGETboundary = expected[PAGE - 1]boundary_path = root / 'agent/sessions' / boundary['path']boundary_path.unlink()observed['deleted_cursor_file'] = boundary['path']after = query(client, observed, 'continuation_after_cursor_delete', cursor=cursor)- validate_query(after, root, expected[PAGE:] if kind == 'rust' else [- row for row in expected if row['id'] != boundary['id']],- ordered=kind == 'rust', remaining=0 if kind == 'rust' else None)- if kind == 'ts':- ts_ignores_paging(after)+ validate_query(after, root, expected[PAGE:], ordered=True, remaining=0)for rows in (observed['baseline_rows'], after['final_data']['sessions']):target, = [row for row in rows if row['id'] == expected[-1]['id']]assert target['name'] == TARGET@@ -267,27 +242,21 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--receipt', required=True, type=Path)args = parser.parse_args()- receipt = {'verified': False, 'scope': __doc__, 'runs': {},- 'normalization': 'owned path basename only; baseline order compared as an ID-keyed set',- 'intentional_difference': 'Rust limit/cursor pages newest-mtime-first; historical TS ignores both optional fields',+ receipt = {'verified': False, 'scope': __doc__,+ 'normalization': 'owned path basename only','not_verified': ['TUI frames or keyboard/search interactions', 'paint latency','large-transcript timing', 'provider/kernel execution', 'concurrent catalog mutations']}try:assert sys.platform == 'linux', 'hosted Linux only'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'TS archive digest mismatch'- receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256with tempfile.TemporaryDirectory(prefix='pa-catalog-', dir='/tmp') as folder:- for kind in ('rust', 'ts'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = receipt['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed,- receipt['runs'].get('rust', {}).get('continuation_cursor'))- except Exception as error:- observed['error'] = str(error)- assert all(run.get('behavior_verified') and run.get('cleanup_verified')- and 'error' not in run for run in receipt['runs'].values()), 'actual catalog comparison failed'- same_rows(receipt['runs']['ts']['baseline_rows'], receipt['runs']['rust']['baseline_rows'])+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ observed = receipt['run'] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, Path(folder) / 'rust', observed)+ except Exception as error:+ observed['error'] = str(error)+ assert observed.get('behavior_verified') and observed.get('cleanup_verified') \+ and 'error' not in observed, 'actual catalog check failed'receipt['verified'] = Trueexcept Exception as error:receipt['error'] = str(error)diff --git a/scripts/review_shutdown_scope_parity.py b/scripts/check_shutdown_scope.pysimilarity index 79%rename from scripts/review_shutdown_scope_parity.pyrename to scripts/check_shutdown_scope.pyindex 376f40ffc9..79738560af 100644--- a/scripts/review_shutdown_scope_parity.py+++ b/scripts/check_shutdown_scope.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Owned real TS/Rust shutdown fixtures; root scoping is an intentional safety delta."""+"""Owned real shutdown fixtures: exact-socket and pinned-root shutdown stay scoped to their own tree."""import argparseimport jsonimport os@@ -10,8 +10,8 @@ import tempfileimport threadingimport time-from review_agent_bounce_parity import Client, Provider, Handler, LIMIT-from review_draft_disconnect_parity import digest, env_for, stop, TS_ARCHIVE_SHA256+from check_agent_bounce import Client, Provider, Handler, LIMIT+from lifecycle_lib import digest, env_for, stopclass CompletionHandler(Handler):@@ -131,8 +131,8 @@ def finish_tree(tree, observed):raise RuntimeError('owned cleanup failed: ' + str(error)) from error-def launch(binary, kind, root, socket_path, shared_tmp, provider, trees):- env = env_for(root, kind)+def launch(binary, root, socket_path, shared_tmp, provider, trees):+ env = env_for(root)env['TMPDIR'] = str(shared_tmp)env['PRIME_AGENT_DAEMON_SOCKET'] = str(socket_path)env['PRIME_AGENT_INTERNAL_WORKER_SUPERVISOR_LOST_EXIT_MS'] = '15000'@@ -173,7 +173,7 @@ def invoke(binary, args, tree):return {'returncode': result.returncode, 'stdout': result.stdout, 'stderr': result.stderr}-def run_case(binary, kind, root, mode, observed):+def run_case(binary, root, mode, observed):shared_tmp = root / 'shared-tmp'shared_tmp.mkdir(parents=True)default_socket = shared_tmp / f'prime-agent-{os.getuid()}' / 'daemon.sock'@@ -187,8 +187,8 @@ def run_case(binary, kind, root, mode, observed):trees = []primary_error = Nonetry:- foreign = launch(binary, kind, root / 'foreign', default_socket, shared_tmp, provider, trees)- own = launch(binary, kind, root / 'own', pins / 'own.sock', shared_tmp, provider, trees)+ foreign = launch(binary, root / 'foreign', default_socket, shared_tmp, provider, trees)+ own = launch(binary, root / 'own', pins / 'own.sock', shared_tmp, provider, trees)observed['process_roles'] = {name: tree['process_roles'] for name, tree in [('own', own), ('foreign', foreign)]}observed['critical_processes'] = {name: tree['critical_processes'] for name, tree in [('own', own), ('foreign', foreign)]}observed['original_processes'] = {name: tree['original_processes']@@ -207,17 +207,11 @@ def run_case(binary, kind, root, mode, observed):assert status['returncode'] == 0, statusservices = observed['discovered_services'] = json.loads(status['stdout'])paths = [service['socketPath'] for service in services]- if kind == 'rust':- assert paths == [str(own['socket'])], paths- else:- assert str(foreign['socket']) in paths, 'TS shared default tree was not discovered'+ assert paths == [str(own['socket'])], pathsprovider.release.set()- # Root CLI creates its own shutdown client. Close fixture observers- # beforehand so TS net.Server.close can retire acknowledged trees.+ # Root CLI creates its own shutdown client. Close the fixture observer+ # beforehand so the daemon's close can retire the acknowledged tree.close_client(own)- if kind == 'ts':- close_client(foreign)- provider.foreign_release.set()shutdown = observed['shutdown_cli'] = invoke(binary, ['shutdown', '--force', '--json'], own)assert shutdown['returncode'] == 0, shutdownreport = json.loads(shutdown['stdout'])@@ -233,15 +227,7 @@ def run_case(binary, kind, root, mode, observed):kept = survivors(foreign['original_processes'], foreign['root'])observed['foreign_original_processes_after'] = keptobserved['own_supervisor_stopped'] = own['process'].poll() is not None- if kind == 'rust':- observed['own_supervisor_stopped'] = True- assert survivors(foreign['critical_processes'], foreign['root']) == foreign['critical_processes'], 'pinned root shutdown harmed foreign supervisor or worker'- else:- wait_stopped(foreign['process'])- deadline = time.monotonic() + LIMIT- while survivors(foreign['original_processes'], foreign['root']) and time.monotonic() < deadline:- threading.Event().wait(0.025)- assert not survivors(foreign['original_processes'], foreign['root']), 'TS global root did not stop default tree'+ assert survivors(foreign['critical_processes'], foreign['root']) == foreign['critical_processes'], 'pinned root shutdown harmed foreign supervisor or worker'observed['provider_requests'] = provider.requestsexcept Exception as error:primary_error = error@@ -271,22 +257,16 @@ def main():parser.add_argument('--receipt', required=True, type=Path)args = parser.parse_args()receipt = {'scenario': 'shutdown_scope', 'verified': False, 'cases': {},- 'scope': 'real supervisor and busy worker identities, exact-socket shutdown baseline, pinned-root status and shutdown',- 'intentional_difference': 'TS 0.9.8 discovers/stops the shared default tree; Rust pinned root discovers/stops only its own supervisor tree',- 'process_scope': 'original supervisor and worker identities must survive Rust isolation; other inherited-environment processes are role/cmdline captured but can complete naturally',+ 'scope': 'real supervisor and busy worker identities, exact-socket shutdown, pinned-root status and shutdown',+ 'process_scope': 'original foreign supervisor and worker identities must survive; other inherited-environment processes are role/cmdline captured but can complete naturally','not_covered': 'doctor output, inherited worker environment routing, overlapping agent-dir regression (separate Rust hosted red/green test)'}try:- archive = Path(os.environ['PA_TS_ARCHIVE'])- assert digest(archive) == TS_ARCHIVE_SHA256, 'TS archive digest mismatch'- receipt['ts_archive_sha256'] = digest(archive)with tempfile.TemporaryDirectory(prefix='pa-shutdown-scope-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ['PA_' + kind.upper() + '_BINARY']).resolve()- receipt[kind + '_binary_sha256'] = digest(binary)- for mode in ('exact_socket', 'pinned_root'):- observed = receipt['cases'][kind + '_' + mode] = {}- run_case(binary, kind, Path(folder) / (kind + '_' + mode), mode, observed)- assert receipt['cases']['ts_exact_socket']['action_response'] == receipt['cases']['rust_exact_socket']['action_response'], 'exact-socket shutdown response data differs'+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ receipt['binary_sha256'] = digest(binary)+ for mode in ('exact_socket', 'pinned_root'):+ observed = receipt['cases'][mode] = {}+ run_case(binary, Path(folder) / mode, mode, observed)receipt['verified'] = Trueexcept Exception as error:receipt['error'] = str(error)diff --git a/scripts/check_socket_pin.py b/scripts/check_socket_pin.pynew file mode 100644index 0000000000..805ee7b777--- /dev/null+++ b/scripts/check_socket_pin.py@@ -0,0 +1,138 @@+#!/usr/bin/env python3+"""Real daemon check of preserved legacy sockets and the byte-length fallback.++A Darwin uname shim exercises the actual published launcher on Linux with the+exact CI-built payload. The daemon runs only in fixture-owned homes and socket+paths. No installer downloads occur.+"""+import argparse+import json+import os+from pathlib import Path+import shutil+import socket+import subprocess+import tempfile+import threading+import time++from lifecycle_lib import digest, env_for, stop+++def launch_daemon(command, expected, root, env):+ log_path = root / 'daemon.log'+ with log_path.open('wb') as log:+ process = subprocess.Popen(command + ['--mode', 'daemon'], cwd=root, env=env,+ stdout=log, stderr=log, start_new_session=True)+ try:+ deadline = time.monotonic() + 35+ while time.monotonic() < deadline:+ if process.poll() is not None:+ raise RuntimeError('daemon exited before bind: ' + log_path.read_text(errors='replace'))+ try:+ with socket.socket(socket.AF_UNIX) as sock:+ sock.settimeout(2)+ sock.connect(str(expected))+ with sock.makefile('rb') as stream:+ hello = json.loads(stream.readline())+ assert hello.get('type') == 'daemon_hello' and hello.get('schemaId'), hello+ return {'bound_socket': str(expected), 'hello': hello,+ 'log': log_path.read_text(errors='replace')}+ except (FileNotFoundError, ConnectionRefusedError, socket.timeout):+ threading.Event().wait(0.05)+ raise TimeoutError('daemon did not bind expected launcher socket: ' + str(expected))+ finally:+ stop(process)+++def install_launcher(binary, root, env):+ prefix = root / 'prefix'+ payload = prefix / 'share/prime-agent'+ payload.mkdir(parents=True)+ (payload / 'prime-agent').symlink_to(binary)+ installer = Path(__file__).resolve().parents[1].joinpath('install-rust.sh').read_text()+ marker = '# --- the launcher (the takeover lives here)'+ section = marker + installer.split(marker, 1)[1]+ section = section.split('# The cmd/PowerShell launcher twin', 1)[0]+ script = '''PREFIX="$PRIME_AGENT_RUST_PREFIX"+bin_dir="$PREFIX/bin"+mkdir -p "$bin_dir"+launcher="$bin_dir/prime-agent"+WINDOWS=no+say() { :; }; note() { :; }; die() { echo "$*" >&2; exit 1; }+trap '[ -z "${launcher_tmp:-}" ] || rm -f "$launcher_tmp"' EXIT+''' + section+ installed = subprocess.run(['sh', '-eu'], input=script,+ env={**env, 'PRIME_AGENT_RUST_PREFIX': str(prefix)},+ cwd=root, text=True, capture_output=True, timeout=15)+ if installed.returncode:+ raise RuntimeError('launcher extraction failed: ' + installed.stderr)+ return prefix / 'bin/prime-agent'+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ receipt = {'passed': False, 'scenario': 'socket_pin', 'runs': {},+ 'scope': 'Actual installed launcher: legacy namespace with the npm-bridge marker, explicit override, UTF-8 byte fallback under Darwin uname shim, and the installer stop probe.'}+ fallback_dir = None+ try:+ binary = Path(os.environ['PA_RUST_BINARY']).resolve()+ receipt['binary_sha256'] = digest(binary)+ with tempfile.TemporaryDirectory(prefix='pa-pin-', dir='/tmp') as temp:+ owned = Path(temp) / 'rust'+ owned.mkdir()+ env = env_for(owned)+ tmp = owned / 'tmp'+ legacy = tmp / f'prime-agent-{os.getuid()}/daemon.sock'+ command = install_launcher(binary, owned, env)+ marker = owned / 'prefix/share/.prime-agent-npm-bridge/legacy-daemon-socket'+ marker.parent.mkdir()+ marker.write_text('fixture\n')+ receipt['runs']['legacy'] = launch_daemon([str(command)], legacy, owned, env)+ explicit = tmp / 'explicit.sock'+ receipt['runs']['override'] = launch_daemon([str(command), '--daemon-socket', str(explicit)], explicit, owned,+ {**env, 'PRIME_AGENT_DAEMON_SOCKET': str(explicit)})+ marker.unlink()+ shim = owned / 'shim'+ shim.mkdir()+ fixture_uid = str(500000000 + os.getpid())+ for name, text in (('uname', 'Darwin'), ('id', fixture_uid)):+ path = shim / name+ path.write_text(f'#!/bin/sh\nprintf "%s\\n" "{text}"\n')+ path.chmod(0o755)+ long_tmp = str(owned / ('é' * 25))+ long_pin = f'{long_tmp}/prime-agent-rust-{fixture_uid}/daemon.sock'+ assert len(long_pin) <= 103 and len(long_pin.encode()) > 103, long_pin+ candidate = Path(f'/tmp/prime-agent-rust-{fixture_uid}')+ # Atomic reservation: a collision never authorizes cleanup.+ candidate.mkdir(mode=0o700, exist_ok=False)+ fallback_dir = candidate+ fallback = fallback_dir / 'daemon.sock'+ long_env = {**env, 'TMPDIR': long_tmp,+ 'PATH': str(shim) + os.pathsep + env['PATH'], 'OS': 'Darwin',+ 'LC_ALL': 'C.UTF-8'}+ receipt['runs']['utf8_fallback'] = launch_daemon([str(command)], fallback, owned, long_env)+ source = Path(__file__).resolve().parents[1].joinpath('install-rust.sh').read_text()+ probe = 'rust_socket="${TMPDIR:-/tmp}' + source.split('rust_socket="${TMPDIR:-/tmp}', 1)[1].split('env_socket=', 1)[0]+ observed = subprocess.run(['sh', '-eu'], input=probe + '\nprintf "%s" "$rust_socket"',+ env=long_env, text=True, capture_output=True, timeout=10, check=True).stdout+ assert observed == str(fallback), (observed, fallback)+ receipt['stop_probe'] = observed+ receipt['utf8_pin'] = {'characters': len(long_pin), 'bytes': len(long_pin.encode()),+ 'original_pin': long_pin}+ receipt['passed'] = True+ except Exception as error:+ receipt['error'] = f'{type(error).__name__}: {error}'+ finally:+ if fallback_dir is not None and fallback_dir.exists():+ shutil.rmtree(fallback_dir)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(receipt, indent=2) + '\n')+ print(json.dumps({'passed': receipt['passed'], 'error': receipt.get('error')}))+ return 0 if receipt['passed'] else 1+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/scripts/review_draft_disconnect_parity.py b/scripts/lifecycle_lib.pysimilarity index 52%rename from scripts/review_draft_disconnect_parity.pyrename to scripts/lifecycle_lib.pyindex 3404fcd127..1744ce8672 100644--- a/scripts/review_draft_disconnect_parity.py+++ b/scripts/lifecycle_lib.py@@ -1,12 +1,5 @@-#!/usr/bin/env python3-"""Real-binary #3401 parity: isolated supervisor failures and ordinary PTY input.--No inference, ambient state, binary installation, or production daemon is used.-A short owned daemon supplies each binary's actual hello/schema. The supervisor-fixture then exercises the ordinary --daemon-socket UI, with no test-only flags.-All terminal captures and wire observations are preserved in the receipt.-"""-import argparse+"""Shared real-binary lifecycle check infrastructure: owned daemons, PTY terminals,+protocol fixture supervisors, terminal screen capture and owned-process cleanup."""import codecsimport hashlibimport json@@ -19,20 +12,13 @@ import signalimport socketimport structimport subprocess-import sys-import tempfileimport threadingimport timeimport fcntlimport termiosimport unicodedata-TS_ARCHIVE_SHA256 = "83fb09129bf78e3e60268212cd70932166591b15188caa70c1b0efbcc76235e2"LIMIT = 35-PROMPT = "DRAFT_DISCONNECT_SENTINEL"-PROBE = "DRAFT_TRANSPORT_PROBE"-TS_SOURCE_COMMIT = "7d442aafa985f9342134fac16c2ef41f03fb45c1"-REFUSAL = "Fixture definitively refused this prompt"def digest(path):@@ -56,11 +42,9 @@ def stop(process):process.wait(timeout=5)-def env_for(root, kind):+def env_for(root):env = {key: os.environ[key] for key in ("PATH", "LANG", "LC_ALL", "TZ")if key in os.environ}- if kind == "ts" and "PI_PACKAGE_DIR" in os.environ:- env["PI_PACKAGE_DIR"] = os.environ["PI_PACKAGE_DIR"]for key in ("PRIME_AGENT_KERNEL_PYTHON", "PA_E2E_KERNEL_PYTHON"):if key in os.environ:env[key] = os.environ[key]@@ -82,6 +66,14 @@ def env_for(root, kind):return env+def skill_pythonpath():+ """The repo's bundled skill sources for kernel cells that import skills. With a+ PRIME_AGENT_KERNEL_PYTHON override the product installs no bundled skills into+ that venv (it disables them), so these checks put the sources on PYTHONPATH."""+ skills = Path(__file__).resolve().parent.parent / "skills"+ return os.pathsep.join(sorted(str(path) for path in skills.glob("*/src")))++def actual_hello(binary, root, env):path = root / "hello.sock"with open(root / "hello-daemon.log", "wb") as log:@@ -190,7 +182,7 @@ class Screen:def fixture_state(root, active):- # AgentConnectionState in the pinned TS binary's source commit (types.ts).+ # AgentConnectionState wire shape.# No model selected: model and contextUsage are optional on the wire.return {"activeSessionId": active, "cwd": str(root), "sessionId": "fixture-durable","sessionName": "Draft fixture", "thinkingLevel": "off", "serviceTier": "default",@@ -218,7 +210,6 @@ class Supervisor:self.messages = []self.attaches = 0self.closed = False- self.rebound = Falseself.post_close_attached = Falseself.thread = threading.Thread(target=self.accept, daemon=True)self.thread.start()@@ -266,7 +257,7 @@ class Supervisor:self.threads.append(thread); thread.start()def serve(self, sock):- # The pinned protocol requires this for prompt dispatch. Advertise only+ # The protocol requires this for prompt dispatch. Advertise only# the admission path implemented here; leave direct-peer routing disabled.hello = dict(self.hello, serverCapabilities=["session_input_admission"], clientId="draft-fixture")buffer = b""@@ -288,11 +279,11 @@ class Supervisor:key = (client_id, request_id)with self.lock:self.commands.append(command)- active = "s2" if self.rebound else "s1"+ active = "s1"response = {"type": "response", "id": request_id, "command": name,"success": True, "data": {}}if name == "ack_result":- # TS supervisor acknowledges its journal and returns undefined;+ # The supervisor acknowledges its journal and returns nothing;# this one-way command must not receive a synthetic response.with self.lock:ack_key = (client_id, command.get("commandId"))@@ -324,7 +315,7 @@ class Supervisor:self.prompt_envelopes.append({"id": request_id, "clientId": client_id, "command": command})cached = self.journal.get(key)if cached is not None:- # Exact TS supervisor semantics: (clientId, commandId) completion+ # Supervisor semantics: (clientId, commandId) completion# returns the cached result without dispatching the prompt again.cached_response, index = cachedself.send(sock, cached_response)@@ -334,34 +325,16 @@ class Supervisor:with self.lock:self.prompts.append(command)index = len(self.prompts)- first = index == 1- if first and self.scenario == "refusal":- response.update(success=False, error=REFUSAL)- with self.lock:- # Model complete-before-reply loss, not pending/uncertain journal- # recovery. This scenario tests a lost ACK for a completed admission.self.journal[key] = (dict(response), index)if response["success"]:self.accepted_prompts.append({"id": request_id, "clientId": client_id,"command": command})- if first and self.scenario == "rebind_close":- self.settle(sock, active, key, index, emit=False)- self.rebound = True- self.send(sock, {"type": "session_binding", "previousActiveSessionId": "s1", "activeSessionId": "s2"})- continue- if first and self.scenario == "queued_close":- self.settle(sock, active, key, index, emit=False)- self.closed = True- return # Admission/result cached; reply intentionally lost.- elif name == "detach" and self.scenario == "rebind_close" and self.rebound and not self.closed:- self.closed = True- return # The attach already adopted s2 before it requested detach(s1).elif name == "list": response["data"] = {"sessions": []}elif name == "heartbeats_list": response["data"] = {"heartbeats": []}elif name == "roster_subscribe": response["data"] = {"changed": [], "removed": [], "resync": True}elif name == "get_available_models": response["data"] = {"models": []}elif name == "get_resource_snapshot":- # AgentConnectionResourceSnapshot from the pinned TS source.+ # AgentConnectionResourceSnapshot wire shape.response["data"] = {"contextFiles": [], "skills": [], "prompts": [],"extensions": [], "themes": [], "diagnostics": {"skills": [], "prompts": [], "extensions": [], "themes": []}}@@ -376,7 +349,7 @@ class Supervisor:assistantMessages=len(self.messages) // 2,totalMessages=len(self.messages))elif name == "get_context_tree":- # Pinned AgentSession.getContextTree / ContextTreeNode and+ # AgentSession.getContextTree / ContextTreeNode and# usage.emptyUsage: an empty session is a single active root.usage = {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0,"totalTokens": 0, "cost": {"input": 0, "output": 0,@@ -392,8 +365,8 @@ class Supervisor:with self.lock:response["data"]["messageCount"] = len(self.messages)elif name == "get_messages":- # pa-daemon worker::commands::handle_get_messages and TS- # daemon-mode get_messages return the actual transcript.+ # pa-daemon worker::commands::handle_get_messages returns+ # the actual transcript.# Fixture turns only append; no branches/pagination are used.with self.lock:response["data"] = {"messages": list(self.messages)}@@ -473,203 +446,392 @@ class Terminal:os.close(self.master)-def scenario(kind, binary, root, hello, name):- root.mkdir()- env = env_for(root, kind)- server = Supervisor(root / "fixture.sock", hello, name, root)- terminal = None- result = {"scenario": name, "executed": False, "screens": {}}+TAG = 'PA_GOAL_FIXTURE_ID'+++def process_identity(pid):+ stat = Path('/proc/%d/stat' % pid).read_text()+ fields = stat[stat.rfind(')') + 2:].split()+ return 'proc:' + fields[19], fields[0]+++def verify_worker(row, active, binary, socket_path):+ pid = row['pid']+ assert row.get('rootActiveSessionId') == active, 'wrong descriptor identity'+ assert row.get('supervisorSocketPath') == str(socket_path), 'wrong supervisor descriptor'+ command = Path('/proc/%d/cmdline' % pid).read_bytes().split(b'\0')+ assert command[0] == str(binary).encode(), 'worker argv0 is not fixture binary'+ env = dict(item.split(b'=', 1) for item in Path('/proc/%d/environ' % pid).read_bytes().split(b'\0') if b'=' in item)+ for key, value in {+ 'PRIME_AGENT_INTERNAL_DAEMON_WORKER': '1',+ 'PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID': active,+ 'PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET': str(socket_path),+ }.items():+ assert env.get(key.encode()) == value.encode(), 'wrong fixture worker env identity'+ worker_socket = str(row['socketPath']).encode()+ assert (worker_socket in command or env.get(b'PRIME_AGENT_INTERNAL_DAEMON_WORKER_SOCKET') == worker_socket), 'wrong worker socket identity'+ identity, state = process_identity(pid)+ assert row.get('processStartId') == identity and state != 'Z', 'wrong/reused worker PID'+ return pid, identity+++++class OwnedProcesses:+ def __init__(self, binary, root, socket_path):+ self.binary, self.root, self.socket_path = binary, root, socket_path+ self.direct = {}+ self.targets = {}+ self.errors = []++ def register(self, process, command):+ identity, state = process_identity(process.pid)+ assert state != 'Z', 'fixture process exited before identity capture'+ self.direct[process.pid] = (identity, [str(arg).encode() for arg in command])+ self.targets[process.pid] = identity++ def ownership(self, pid, identity):+ try:+ current, state = process_identity(pid)+ if current != identity or state == 'Z':+ return False+ env = dict(item.split(b'=', 1) for item in Path('/proc/%d/environ' % pid).read_bytes().split(b'\0') if b'=' in item)+ if env.get(TAG.encode()) != str(self.root).encode():+ return False+ command = Path('/proc/%d/cmdline' % pid).read_bytes().rstrip(b'\0').split(b'\0')+ if pid in self.direct:+ return self.direct[pid] == (identity, command)+ if command[0] == str(self.binary).encode():+ for path in (self.root / 'agent' / 'daemon-workers').rglob('*.json'):+ row = json.loads(path.read_text())+ if row.get('pid') == pid:+ return verify_worker(row, row['rootActiveSessionId'], self.binary, self.socket_path) == (pid, identity)+ return False+ # Kernels retain the owner PID supplied by the actual launcher.+ return ('python' in Path(command[0].decode()).name+ and env.get(b'PRIME_AGENT_KERNEL_OWNER_PID') in+ {str(owner).encode() for owner in self.targets})+ except (OSError, ValueError, KeyError, AssertionError, UnicodeError):+ return False++ def discover(self):+ # Capture verified workers before their kernels, including detached workers.+ for path in (self.root / 'agent' / 'daemon-workers').rglob('*.json'):+ try:+ row = json.loads(path.read_text())+ pid, identity = verify_worker(row, row['rootActiveSessionId'], self.binary, self.socket_path)+ if self.ownership(pid, identity):+ self.targets[pid] = identity+ except (OSError, ValueError, KeyError, AssertionError):+ pass # A partial/retired descriptor is not an ownership proof.+ for entry in Path('/proc').iterdir():+ if entry.name.isdigit():+ pid = int(entry.name)+ try:+ identity, _ = process_identity(pid)+ if self.ownership(pid, identity):+ self.targets[pid] = identity+ except OSError:+ pass++ def live(self):+ alive = []+ for pid, identity in list(self.targets.items()):+ try:+ current, state = process_identity(pid)+ if current == identity and state != 'Z':+ alive.append(pid)+ except (FileNotFoundError, ProcessLookupError):+ pass+ return alive++ def wait_gone(self, timeout):+ deadline = time.monotonic() + timeout+ while True:+ self.discover()+ alive = self.live()+ if not alive:+ return+ if time.monotonic() >= deadline:+ raise AssertionError('owned goal fixture processes remained: ' + str(alive))+ threading.Event().wait(0.025)++ def send(self, pid, signum):+ identity = self.targets[pid]+ try:+ fd = os.pidfd_open(pid)+ except ProcessLookupError:+ return False+ try:+ if not self.ownership(pid, identity):+ return False+ signal.pidfd_send_signal(fd, signum)+ return True+ except ProcessLookupError:+ return False+ finally:+ os.close(fd)+++def finish(scope, client, daemon, observation):+ """Fallback can reap leftovers but never converts failed shutdown into success."""+ observation['cleanup_verified'] = Falsetry:- terminal = Terminal([str(binary), "--daemon-socket", str(server.path)], root, env)- terminal.wait("initial attach and visible terminal", lambda: server.attaches >= 1- and bool(terminal.screen.text().strip()), server)- terminal.send(PROMPT)- terminal.wait("typed sentinel visibly in editor", lambda: PROMPT in terminal.screen.text(), server)- terminal.send("\r")- terminal.wait("first prompt received", lambda: len(server.prompts) == 1, server)- if name == "refusal":- terminal.wait("definite refusal and restored draft", lambda: REFUSAL in terminal.screen.text()- and PROMPT in terminal.screen.text(), server)- else:- terminal.wait("reconnected attach and visible reconnect result", lambda: server.post_close_attached- and ("Fixture settled 1" in terminal.screen.text()- or any(phrase in terminal.screen.text().lower() for phrase in- ("daemon reconnected", "daemon restarted (v0.9.8) - reconnected"))), server)- result["screens"]["before_resubmit"] = terminal.screen.text()- before = len(server.prompts)- terminal.send("\r")- if name == "refusal":- terminal.wait("resubmitted refusal visibly settled", lambda:- "Fixture settled 2" in terminal.screen.text(), server)- # A visible marker typed afterwards is the barrier that Enter has been handled;- # the next prompt also proves the post-reconnect transport is operational.- terminal.send(PROBE)- terminal.wait("probe visibly typed", lambda: PROBE in terminal.screen.text(), server)- result["screens"]["after_resubmit"] = terminal.screen.text()- terminal.send("\r")- terminal.wait("transport probe received", lambda: any(PROBE in p.get("message", "") for p in server.prompts), server)- probe_index = next(index + 1 for index, prompt in enumerate(server.prompts)- if PROBE in prompt.get("message", ""))- terminal.wait("transport probe visibly settled", lambda:- f"Fixture settled {probe_index}" in terminal.screen.text(), server)- result.update(executed=True, dispatches_before_resubmit=before,- rebound=server.rebound, reconnected=server.post_close_attached)+ scope.discover()+ if daemon is not None:+ assert client is not None, 'owned daemon cleanup client unavailable'+ client.call('shutdown', force=True)+ observation['shutdown_wire'] = client.wire+ client.close() # The daemon's close waits for raw fixture connections.+ daemon.wait(timeout=15)+ assert daemon.returncode == 0, 'owned goal daemon shutdown failed'+ scope.wait_gone(5)+ observation['cleanup_verified'] = Trueexcept Exception as error:- result["error"] = f"{type(error).__name__}: {error}"+ observation['cleanup_error'] = str(error)+ observation['fallback_signals'] = []+ for signum, timeout in ((signal.SIGTERM, 3), (signal.SIGKILL, 2)):+ try:+ scope.discover()+ except Exception as discovery_error:+ scope.errors.append('fallback discovery failed: ' + str(discovery_error))+ for pid in scope.live():+ try:+ if scope.send(pid, signum):+ observation['fallback_signals'].append({'pid': pid, 'signal': signum.name})+ except OSError as signal_error:+ scope.errors.append(str(signal_error))+ try:+ scope.wait_gone(timeout)+ break+ except Exception as wait_error:+ scope.errors.append('fallback wait failed: ' + str(wait_error))+ observation['fallback_remaining'] = scope.live()+ observation['fallback_errors'] = scope.errorsfinally:- if terminal is not None:- result["terminal_raw"] = terminal.raw.decode("utf-8", "replace")- result["screens"]["final"] = terminal.screen.text()+ if client is not None:try:- terminal.close()- except Exception as error:- result.setdefault("cleanup_errors", []).append(f"UI cleanup: {type(error).__name__}: {error}")- try:- server.close()- except Exception as error:- result.setdefault("cleanup_errors", []).append(f"supervisor cleanup: {type(error).__name__}: {error}")- # Snapshot only after the owned UI has stopped and all fixture threads joined.- # A late dispatch cannot be hidden behind an earlier passing invariant.- messages = [p.get("message") for p in server.prompts]- expected = [PROMPT, PROMPT, PROBE] if name == "refusal" else [PROMPT, PROBE]- accepted = [item["command"].get("message") for item in server.accepted_prompts]- wire_messages = [item["command"].get("message") for item in server.prompt_envelopes]- result.update(wire_commands=server.commands, prompts=messages,- wire_prompt_messages=wire_messages,- prompt_envelopes=server.prompt_envelopes,- accepted_logical_prompts=server.accepted_prompts,- accepted_logical_messages=accepted, result_acks=server.result_acks,- persisted_messages=server.messages,- expected_prompts=expected, fixture_errors=server.errors,- draft_restored=name == "refusal" and messages == expected,- draft_consumed=name != "refusal" and messages == expected,- invariant_passed=bool(result["executed"] and messages == expected- and accepted == [PROMPT, PROBE] and not server.errors and not result.get("cleanup_errors")))- return result---def classify_validation(receipt):- """Classify real observations; passing the targeted check does not prove full parity."""- comparisons = {}- for name in ("queued_close", "refusal", "rebind_close"):- sides = [receipt.get("results", {}).get(kind, {}).get("scenarios", {}).get(name, {}) for kind in ("ts", "rust")]- executed = all(x.get("executed") for x in sides)- comparisons[name] = {"comparable": name != "rebind_close",- "both_executed": executed,- "same_logical_prompt_observations": bool(executed and sides[0].get("prompts") == sides[1].get("prompts")),- "same_accepted_logical_observations": bool(executed and sides[0].get("accepted_logical_messages") == sides[1].get("accepted_logical_messages")),- "same_wire_prompt_observations": bool(executed and sides[0].get("wire_prompt_messages") == sides[1].get("wire_prompt_messages")),- "both_invariants_passed": all(x.get("invariant_passed") for x in sides)}- for name, comparison in comparisons.items():- if not comparison["comparable"]:- comparison["status"] = "not_comparable"- comparison["reason"] = (- "Pinned TS source " + TS_SOURCE_COMMIT + " has no session_binding or "- "previousActiveSessionId protocol; session_replaced retains the active ID. "- "The Rust-only rebind fixture cannot establish a TS behavioral difference."- )- elif not comparison["both_executed"]:- comparison["status"] = "incomplete"- else:- comparison["status"] = "matched" if all(comparison[key] for key in (- "same_logical_prompt_observations", "same_accepted_logical_observations",- "both_invariants_passed")) else "different"- receipt["comparisons"] = comparisons- receipt["shared_contract_parity"] = bool("preflight_error" not in receipt and all(- comparisons[name]["status"] == "matched" for name in ("queued_close", "refusal")))- # Full parity remains unproven when a requested scenario is not comparable.- receipt["parity"] = bool("preflight_error" not in receipt and all(- item["comparable"] and all(item[key] for key in ("both_executed", "same_logical_prompt_observations",- "same_accepted_logical_observations", "both_invariants_passed"))- for item in comparisons.values()))- # Targeted validation is distinct from full rendered/wire parity. The pinned- # TS binary cannot execute the Rust binding extension, so only its recorded- # unsupported-case timeout is expected; every other error fails validation.- errors = []- if "preflight_error" in receipt:- errors.append("preflight failed")- results = receipt.get("results", {})- for kind in ("ts", "rust"):- side = results.get(kind, {})- if not side or "error" in side:- errors.append(f"{kind}: binary setup failed or missing")- for name in ("queued_close", "refusal", "rebind_close"):- scenario_result = side.get("scenarios", {}).get(name, {})- if not scenario_result:- errors.append(f"{kind}/{name}: result missing")+ client.close()+ except Exception as close_error:+ observation['cleanup_verified'] = False+ observation.setdefault('cleanup_error', str(close_error))+ observation['owned_process_identities'] = dict(scope.targets)+++class DockScreen:+ """Existing xterm cell capture with explicit per-cell SGR attributes."""+ def __init__(self, width=120, height=40):+ self.width, self.height = width, height+ self.cells = [[" "] * width for _ in range(height)]+ self.styles = [[{} for _ in range(width)] for _ in range(height)]+ self.sgr = {}+ self.unsupported_sgr = []+ self.unsupported_terminal = []+ self.keyboard_controls = []+ self.autowrap = True+ self.alternate = None+ self.row = self.col = 0+ self.saved = (0, 0, {})+ self.pending = ""+ self.decoder = codecs.getincrementaldecoder("utf-8")("replace")++ def text(self):+ return "\n".join("".join(row).rstrip() for row in self.cells)++ def feed(self, data):+ self.pending += self.decoder.decode(data)+ replies = []+ while self.pending:+ if self.pending[0] == "\x1b":+ if len(self.pending) < 2:+ break+ if self.pending[1] in "]P_^":+ end = re.search(r"\x07|\x1b\\", self.pending[2:])+ if end is None:+ break+ sequence = self.pending[:2 + end.end()]+ # OSC titles/hyperlinks do not move terminal cells. DCS,+ # APC and PM can carry graphics or sixel: never silently+ # accept their unknown effect on the captured frame.+ payload = self.pending[2:2 + end.start()]+ osc_kind = payload.split(';', 1)[0]+ # Terminals may be asked for the default foreground/background via+ # OSC10;? / OSC11;?. Queries+ # do not paint or set a color; a legacy PTY may stay silent.+ # Color-setting variants remain unsupported and fail closed.+ color_query = payload in ('10;?', '11;?')+ if self.pending[1] != ']' or (not color_query and osc_kind not in ('0', '1', '2', '7', '8', '52', '133')):+ self.unsupported_terminal.append(sequence)+ self.pending = self.pending[2 + end.end():]+ continue+ if self.pending[1] == "[":+ match = re.match(r"\x1b\[([0-?]*)([ -/]*)([@-~])", self.pending)+ if match is None:+ break+ params, intermediate, command = match.groups()+ sequence = self.pending[:match.end()]+ self.pending = self.pending[match.end():]+ nums = [int(x) if x.isdigit() else 0 for x in params.lstrip("?<>").split(";")]+ n = nums[0] or 1+ if intermediate and not (command == 'q' and intermediate == ' '):+ self.unsupported_terminal.append(sequence)+ continue+ # Actual hosted captures contain these keyboard+ # protocol controls. They do not paint cells and must not+ # be interpreted as SGR4 (underline) after stripping >.+ if command == 'm' and params in ('>4;0', '>4;1', '>4;2'):+ self.keyboard_controls.append(sequence)+ continue+ if command == 'u' and params == '?':+ self.keyboard_controls.append(sequence)+ # Even a zero-flags reply advertises Kitty support to+ # crossterm (vendor terminal/sys/unix.rs:255). This PTY+ # emits legacy keys: stay silent on the Kitty query.+ # The following DA1 query's response settles non-Kitty+ # through KeyboardEnhancementFlagsFilter instead.+ continue+ if command == 'u' and (re.fullmatch(r'[>=]\d+(?:;\d+)?', params)+ or re.fullmatch(r'<\d*', params)):+ self.keyboard_controls.append(sequence)+ continue+ if params.startswith(('?', '<', '>')) and command not in 'hlnc':+ self.unsupported_terminal.append(sequence)+ continue+ if command == "m": self.apply_sgr(nums)+ elif command in "Hf":+ self.row = min(self.height - 1, max(0, (nums[0] or 1) - 1))+ self.col = min(self.width - 1, max(0, ((nums[1] if len(nums) > 1 else 1) or 1) - 1))+ elif command == "A": self.row = max(0, self.row - n)+ elif command == "B": self.row = min(self.height - 1, self.row + n)+ elif command == "C": self.col = min(self.width - 1, self.col + n)+ elif command == "D": self.col = max(0, self.col - n)+ elif command == "G": self.col = min(self.width - 1, n - 1)+ elif command == "J":+ if nums[0] == 2:+ self.cells = [[" "] * self.width for _ in range(self.height)]+ self.styles = [[dict(self.sgr) for _ in range(self.width)] for _ in range(self.height)]+ elif nums[0] == 0:+ self.cells[self.row][self.col:] = [" "] * (self.width - self.col)+ self.styles[self.row][self.col:] = [dict(self.sgr) for _ in range(self.width - self.col)]+ for row in range(self.row + 1, self.height):+ self.cells[row] = [" "] * self.width+ self.styles[row] = [dict(self.sgr) for _ in range(self.width)]+ elif nums[0] != 3: # ED3 clears scrollback, not visible cells.+ self.unsupported_terminal.append(sequence)+ elif command == "K":+ if nums[0] not in (0, 1, 2):+ self.unsupported_terminal.append(sequence)+ continue+ start, end = (0, self.width) if nums[0] == 2 else ((0, self.col + 1) if nums[0] == 1 else (self.col, self.width))+ self.cells[self.row][start:end] = [" "] * (end - start)+ self.styles[self.row][start:end] = [dict(self.sgr) for _ in range(end - start)]+ elif command == "P":+ line = self.cells[self.row]+ line[self.col:] = (line[self.col + n:] + [" "] * n)[:self.width - self.col]+ styles = self.styles[self.row]+ styles[self.col:] = (styles[self.col + n:] + [dict(self.sgr) for _ in range(n)])[:self.width - self.col]+ elif command == "X":+ end = min(self.width, self.col + n)+ self.cells[self.row][self.col:end] = [" "] * (end - self.col)+ self.styles[self.row][self.col:end] = [dict(self.sgr) for _ in range(end - self.col)]+ elif command == "n" and nums[0] == 6:+ replies.append(f"\x1b[{self.row + 1};{self.col + 1}R".encode())+ elif command == "c": replies.append(b"\x1b[?1;2c")+ elif command in 'hl' and params.startswith('?'):+ for mode in nums:+ if mode == 7:+ self.autowrap = command == 'h'+ elif mode == 1049:+ if command == 'h' and self.alternate is None:+ self.alternate = (self.cells, self.styles, self.row, self.col,+ dict(self.sgr), self.autowrap)+ self.cells = [[' '] * self.width for _ in range(self.height)]+ self.styles = [[{} for _ in range(self.width)] for _ in range(self.height)]+ self.row = self.col = 0+ elif command == 'l' and self.alternate is not None:+ self.cells, self.styles, self.row, self.col, self.sgr, self.autowrap = self.alternate+ self.alternate = None+ elif mode not in (12, 25, 1000, 1002, 1003, 1004, 1006, 2004, 2026):+ self.unsupported_terminal.append(sequence)+ elif command == 'q' and intermediate == ' ':+ pass # Cursor presentation, not cell geometry.+ else:+ self.unsupported_terminal.append(sequence)+ continue+ command = self.pending[1]+ if command in '()' and len(self.pending) < 3:+ break+ self.pending = self.pending[2:]+ if command == "7": self.saved = (self.row, self.col, dict(self.sgr))+ elif command == "8":+ self.row, self.col, saved_sgr = self.saved+ self.sgr = dict(saved_sgr)+ elif command in "()" and self.pending:+ charset = self.pending[0]+ self.pending = self.pending[1:]+ if charset != 'B':+ self.unsupported_terminal.append('\x1b' + command + charset)+ else:+ self.unsupported_terminal.append('\x1b' + command)continue- if scenario_result.get("fixture_errors") or scenario_result.get("cleanup_errors"):- errors.append(f"{kind}/{name}: fixture or cleanup failed")- if any(not isinstance(scenario_result.get(field), list) for field in (- "prompts", "accepted_logical_messages", "wire_prompt_messages")):- errors.append(f"{kind}/{name}: prompt observations missing")- if kind == "ts" and name == "rebind_close":- if (scenario_result.get("error") != "TimeoutError: reconnected attach and visible reconnect result"- or scenario_result.get("executed") is not False- or scenario_result.get("invariant_passed") is not False):- errors.append("ts/rebind_close: expected unsupported-case observation missing")- elif (scenario_result.get("error") or scenario_result.get("executed") is not True- or scenario_result.get("invariant_passed") is not True):- errors.append(f"{kind}/{name}: execution or invariant failed")- if not receipt["shared_contract_parity"]:- errors.append("shared contracts did not match")- receipt["validation_scope"] = (- "Both shared draft contracts plus the Rust-only binding regression. "- "Pinned TS binding is not comparable; full frame/wire parity remains unproven."- )- receipt["validation_errors"] = errors- receipt["validation_passed"] = not errors- return receipt["validation_passed"]---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--receipt", required=True, type=Path)- args = parser.parse_args()- repo = Path(__file__).resolve().parent.parent- receipt_path = args.receipt.resolve()- if receipt_path == repo or repo in receipt_path.parents:- print("receipt must be outside repository", file=sys.stderr)- return 1- receipt = {"fixture": "pr3401-draft-disconnect", "results": {},- "fixture_schema_source_commit": TS_SOURCE_COMMIT,- "comparison_scope": "Targeted accepted logical prompt/draft behavior; complete result recovery is keyed by the actual (clientId, commandId), so same-ID wire retries are recorded but do not dispatch a second prompt. Raw IDs, attempts, terminals and commands are retained; full frame/wire equivalence is not asserted.",- "ci_provenance": {key: os.environ.get(key) for key in ("GITHUB_RUN_ID", "GITHUB_SHA")},- "ts_reference": {"version": "0.9.8", "expected_archive_sha256": TS_ARCHIVE_SHA256},- "pre_send_limitation": "A deterministically dead client before send needs the in-process death-watch seam; the binary fixture tests definitive refusal separately."}- try:- if sys.platform != "linux": raise RuntimeError("real binary fixture requires Linux")- event_path = os.environ.get("GITHUB_EVENT_PATH")- if event_path:- event = json.loads(Path(event_path).read_text())- receipt["ci_provenance"]["pull_request_head_sha"] = event.get("pull_request", {}).get("head", {}).get("sha")- archive = Path(os.environ["PA_TS_ARCHIVE"])- receipt["ts_reference"]["verified_archive_sha256"] = digest(archive)- if digest(archive) != TS_ARCHIVE_SHA256: raise RuntimeError("official TS archive SHA-256 mismatch")- with tempfile.TemporaryDirectory(prefix="pa-draft-parity-") as temp:- for kind in ("ts", "rust"):- item = receipt["results"][kind] = {}- try:- binary = Path(os.environ.get(f"PA_{kind.upper()}_BINARY") or os.environ[f"{kind.upper()}_BINARY"]).resolve()- if not binary.is_file() or not os.access(binary, os.X_OK): raise RuntimeError("missing executable")- item.update(binary=str(binary), sha256=digest(binary))- root = Path(temp) / kind; root.mkdir()- env = env_for(root, kind)- version = subprocess.run([str(binary), "--version"], cwd=root, env=env,- stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=15, check=True)- item["version"] = version.stdout.strip()- if kind == "ts" and "0.9.8" not in item["version"]: raise RuntimeError("unexpected TS version")- item["actual_hello"] = actual_hello(binary, root, env)- item["scenarios"] = {name: scenario(kind, binary, root / name, item["actual_hello"], name)- for name in ("queued_close", "refusal", "rebind_close")}- except Exception as error: item["error"] = f"{type(error).__name__}: {error}"- except Exception as error: receipt["preflight_error"] = f"{type(error).__name__}: {error}"- classify_validation(receipt)- args.receipt.parent.mkdir(parents=True, exist_ok=True)- args.receipt.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n")- print(json.dumps(receipt, indent=2, sort_keys=True))- return 0 if receipt["validation_passed"] else 1---if __name__ == "__main__":- sys.exit(main())+ char, self.pending = self.pending[0], self.pending[1:]+ if char == "\r": self.col = 0+ elif char == "\n":+ self.row += 1+ if self.row >= self.height:+ self.cells.pop(0); self.cells.append([" "] * self.width)+ self.styles.pop(0); self.styles.append([dict(self.sgr) for _ in range(self.width)])+ self.row = self.height - 1+ elif char == "\b": self.col = max(0, self.col - 1)+ elif char == '\t': self.col = min(self.width - 1, ((self.col // 8) + 1) * 8)+ elif char >= " " and not unicodedata.combining(char):+ if self.col >= self.width:+ if self.autowrap:+ self.col = 0+ self.row += 1+ if self.row == self.height:+ self.cells.pop(0); self.cells.append([' '] * self.width)+ self.styles.pop(0); self.styles.append([dict(self.sgr) for _ in range(self.width)])+ self.row = self.height - 1+ else:+ self.col = self.width - 1+ self.cells[self.row][self.col] = char+ self.styles[self.row][self.col] = dict(self.sgr)+ self.col += 2 if unicodedata.east_asian_width(char) in "WF" else 1+ elif char not in ('\x00', '\x07') and not unicodedata.combining(char):+ self.unsupported_terminal.append(char)+ return replies++ def apply_sgr(self, nums):+ i = 0+ while i < len(nums):+ value = nums[i]+ if value == 0:+ self.sgr = {}+ elif value in (1, 2, 3, 4, 7, 9):+ self.sgr[str(value)] = True+ elif value in (22, 23, 24, 27, 29):+ for key in {22: ('1', '2'), 23: ('3',), 24: ('4',), 27: ('7',), 29: ('9',)}[value]:+ self.sgr.pop(key, None)+ elif 30 <= value <= 37 or 90 <= value <= 97:+ self.sgr['fg'] = ['ansi', value]+ elif 40 <= value <= 47 or 100 <= value <= 107:+ self.sgr['bg'] = ['ansi', value]+ elif value in (39, 49):+ self.sgr.pop('fg' if value == 39 else 'bg', None)+ elif value in (38, 48) and i + 1 < len(nums):+ count = {5: 1, 2: 3}.get(nums[i + 1])+ if count is not None and i + 2 + count <= len(nums):+ self.sgr['fg' if value == 38 else 'bg'] = nums[i + 1:i + 2 + count]+ i += 1 + count+ else:+ self.unsupported_sgr.append(nums[i:])+ break+ else:+ self.unsupported_sgr.append([value])+ i += 1++ def dock_styles(self):+ return [{"text": ''.join(row).rstrip(), "styles": [dict(style) for style in self.styles[index]]}+ for index, row in enumerate(self.cells)+ if 'subagents' in ''.join(row) or 'running' in ''.join(row)]diff --git a/scripts/review_autocompact_settings_parity.py b/scripts/review_autocompact_settings_parity.pydeleted file mode 100644index 69bf1bbab0..0000000000--- a/scripts/review_autocompact_settings_parity.py+++ /dev/null@@ -1,92 +0,0 @@-#!/usr/bin/env python3-"""Observe /settings in pinned TS and Rust binaries with the same PTY input.--Keep full frames and wire commands, compare the existing auto-compaction toggle,-and record the requested Rust-only percentage row as an explicit feature addition.-No real inference, user home, or production daemon is used.-"""-import argparse-import difflib-import json-import os-import re-from pathlib import Path-import tempfile--from review_draft_disconnect_parity import (- Supervisor, Terminal, actual_hello, digest, env_for,-)---def observe(binary, kind, root):- root.mkdir()- env = env_for(root, kind)- hello = actual_hello(binary, root, env)- server = Supervisor(root / 'ui.sock', hello, 'settings', root)- terminal = None- result = {'binary_sha256': digest(binary), 'executed': False}- try:- terminal = Terminal([str(binary), '--daemon-socket', str(server.path)], root, env)- terminal.wait('initial attach', lambda: server.attaches > 0 and bool(terminal.screen.text().strip()), server)- terminal.send('/settings')- terminal.wait('settings typed', lambda: '/settings' in terminal.screen.text(), server)- terminal.send('\r')- terminal.wait('settings menu', lambda: 'Auto-compact' in terminal.screen.text(), server)- result['settings_frame'] = terminal.screen.text()- terminal.send('\r')- terminal.wait('toggle delivered', lambda: any(c.get('type') == 'set_auto_compaction' for c in server.commands), server)- terminal.wait('toggle rendered', lambda: any('Auto-compact' in row and 'true' in row for row in terminal.screen.text().splitlines()), server)- result['toggle_frame'] = terminal.screen.text()- result['toggle_rows'] = [re.sub(r'\s+', ' ', row.strip().lstrip('›> ').strip()) for row in terminal.screen.text().splitlines()- if 'Auto-compact' in row and 'threshold' not in row]- result['toggle_payloads'] = [json.dumps({k: c[k] for k in ('type', 'activeSessionId', 'enabled')}, sort_keys=True)- for c in server.commands if c.get('type') == 'set_auto_compaction']- if kind == 'rust':- # Search for the added row so other General settings can evolve independently.- terminal.send('threshold')- terminal.wait('percentage focused', lambda: any(row.strip().startswith('› Auto-compact threshold (%)') for row in terminal.screen.text().splitlines()), server)- result['percentage_frame'] = terminal.screen.text()- terminal.send('\r')- path = root / 'agent/settings.json'- terminal.wait('percentage persisted', lambda: json.loads(path.read_text()).get('compaction', {}).get('thresholdPercent') == 100, server)- terminal.wait('percentage rendered', lambda: any('threshold (%)' in row and '100' in row for row in terminal.screen.text().splitlines()), server)- result['changed_percentage_frame'] = terminal.screen.text()- result['saved_percentage'] = json.loads(path.read_text())['compaction']['thresholdPercent']- result['executed'] = True- except Exception as error:- result['error'] = str(error)- finally:- if terminal:- terminal.close()- result['terminal_raw_hex'] = terminal.raw.hex()- server.close()- result['commands'] = server.commands- result['fixture_errors'] = server.errors- return result---def main():- parser = argparse.ArgumentParser()- parser.add_argument('--receipt', type=Path, required=True)- args = parser.parse_args()- receipt = {'intended_addition': 'Rust adds the requested 1–100% auto-compaction percentage row; TS 0.9.8 has no such row.',- 'existing_layout_difference': 'Rust already groups settings into tabs; the full frame diff preserves that difference.',- 'scope': 'Real client binaries against an isolated synthetic daemon; model compaction execution is covered by Rust tests.',- 'results': {}}- with tempfile.TemporaryDirectory(prefix='autocompact-parity-') as directory:- root = Path(directory)- for kind, name in [('ts', 'PA_TS_BINARY'), ('rust', 'PA_RUST_BINARY')]:- receipt['results'][kind] = observe(Path(os.environ[name]).resolve(), kind, root / kind)- ts, rust = (receipt['results'][kind] for kind in ('ts', 'rust'))- receipt['frame_diff'] = list(difflib.unified_diff(ts.get('settings_frame', '').splitlines(), rust.get('settings_frame', '').splitlines(), fromfile='TS', tofile='Rust'))- receipt['toggle_wire_equal'] = ts.get('toggle_payloads') == rust.get('toggle_payloads') and bool(ts.get('toggle_payloads'))- receipt['toggle_rows_equal'] = ts.get('toggle_rows') == rust.get('toggle_rows') and bool(ts.get('toggle_rows'))- receipt['passed'] = all(result.get('executed') and not result['fixture_errors'] for result in (ts, rust)) and receipt['toggle_wire_equal'] and receipt['toggle_rows_equal'] and rust.get('saved_percentage') == 100- args.receipt.parent.mkdir(parents=True, exist_ok=True)- args.receipt.write_text(json.dumps(receipt, indent=2) + '\n')- print(json.dumps({key: receipt[key] for key in ('passed', 'toggle_wire_equal', 'toggle_rows_equal')}))- return 0 if receipt['passed'] else 1---if __name__ == '__main__':- raise SystemExit(main())diff --git a/scripts/review_dead_child_delete_parity.py b/scripts/review_dead_child_delete_parity.pydeleted file mode 100644index 35abd9e2e9..0000000000--- a/scripts/review_dead_child_delete_parity.py+++ /dev/null@@ -1,170 +0,0 @@-#!/usr/bin/env python3-"""Hosted real TS/Rust RLM child deletion baseline and Rust idempotent retry.--A real kernel admits a child whose model request is held. The ordinary daemon-kill command is accepted by both implementations. Rust closes its separate-child worker and removes its projection. TS hosts the child in its parent worker-and its plain kill leaves the spawn edge live; its immediate projection is-retained in the receipt without claiming delete parity. Rust recognizes rlmLedgerDelete and persists-its edge boundary; pinned TS ignores that Rust-native marker (raw ledger-absence is retained as an explicit difference). The new dead-PID and-interrupted-cleanup branches are separately exercised by hosted Unix supervisor-regressions; this fixture does not manufacture a process death or claim parity-for historical TS retry errors.-"""-import argparse-import json-import os-from pathlib import Path-import subprocess-import sys-import tempfile-import threading-import time--from review_ledger_liveness_parity import Provider, PARENT, NAME-from review_agent_bounce_parity import Client-from review_draft_disconnect_parity import digest, env_for, TS_ARCHIVE_SHA256-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish, verify_worker, process_identity---def delete_contract(rows, child_id):- deletes = [row for row in rows if row.get('op') == 'delete' and row.get('childId') == child_id]- assert deletes, 'the actual child deletion did not persist its boundary'- assert all(row.get('reason') == 'user' for row in deletes), deletes- return deletes---def observe(binary, kind, root, observed):- env = env_for(root, kind)- env[TAG] = str(root)- library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'- env['PYTHONPATH'] = os.pathsep.join(str(p) for p in library.glob('*/src') if p.is_dir())- provider = Provider()- threading.Thread(target=provider.serve_forever, daemon=True).start()- (root / 'agent/models.json').write_text(json.dumps({'providers': {'parity-local': {- 'api': 'openai-completions', 'apiKey': 'fixture-only',- 'baseUrl': f'http://127.0.0.1:{provider.server_port}/v1', 'models': [{- 'id': 'parity-1', 'name': 'Parity 1', 'reasoning': False,- 'contextWindow': 128000, 'maxTokens': 4096}]}}}))- (root / 'agent/settings.json').write_text(json.dumps({'prewarmPythonKernel': False,- 'defaultProvider': 'parity-local', 'defaultModel': 'parity-1'}))- path = root / 'd.sock'- scope = OwnedProcesses(binary, root, path)- daemon = control = None- log = open(root / 'daemon.log', 'wb')- try:- command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(path)]- daemon = subprocess.Popen(command, cwd=root, env=env, stdout=log,- stderr=subprocess.STDOUT, start_new_session=True)- scope.register(daemon, command)- control = Client(path, daemon)- created = control.call('create', config={'cwd': str(root), 'agentDir': str(root / 'agent'),- 'provider': 'parity-local', 'model': 'parity-1', 'telemetryDisabled': True})- active = created.get('activeSessionId') or created.get('id')- assert active, created- control.call('attach', activeSessionId=active)- control.call('prompt', activeSessionId=active, message=PARENT)- child_id = provider.ready()['child_id']- listed = control.call('list', all=True)- rows = [r for r in listed['sessions'] if r.get('rlmChildId') == child_id]- assert len(rows) == 1 and rows[0].get('sessionName') == NAME, rows- row = rows[0]- child_active = row.get('activeSessionId') or row.get('id')- assert child_active and row.get('parentActiveSessionId') == active, row- observed['child_before'] = row- descriptors = [json.loads(p.read_text()) for p in (root / 'agent/daemon-workers').rglob('*.json')]- worker_root = child_active if kind == 'rust' else active- child_descriptors = [d for d in descriptors if d.get('rootActiveSessionId') == worker_root]- assert len(child_descriptors) == 1, child_descriptors- pid, identity = verify_worker(child_descriptors[0], worker_root, binary, path)- if kind == 'ts':- assert row['workerPid'] == pid, 'TS child is not in the verified parent worker'- observed['worker_layout'] = 'separate child worker' if kind == 'rust' else 'shared parent worker'- scope.discover()- observed['child_process_identity'] = {'pid': pid, 'start_id': identity}- payload = {'activeSessionId': child_active, 'rlmLedgerDelete': 'user', 'rlmChildId': child_id}- observed['delete_response'] = control.call('kill', **payload)- after_list = control.call('list', all=True)- observed['sessions_after'] = after_list- if kind == 'rust':- assert not any(r.get('activeSessionId') == child_active for r in after_list['sessions']), after_list- observed['child_session_closed'] = True- deadline = time.monotonic() + 15- while True:- try:- current, state = process_identity(pid)- stopped = current != identity or state == 'Z'- except FileNotFoundError:- stopped = True- if stopped:- break- assert time.monotonic() < deadline, 'actual child worker did not exit after kill'- threading.Event().wait(0.025)- observed['child_worker_stopped'] = True- else:- observed['ts_child_projection_after_raw_kill'] = [r for r in after_list['sessions']- if r.get('rlmChildId') == child_id]- current, state = process_identity(pid)- assert current == identity and state != 'Z', 'TS unexpectedly lost the shared parent worker'- observed['shared_parent_worker_alive'] = True- def ledger():- return [json.loads(line) for p in (root / 'agent/rlm-ledger').glob('*.jsonl')- for line in p.read_text().splitlines()]- observed['ledger_after'] = ledger()- if kind == 'ts':- assert not [r for r in observed['ledger_after']- if r.get('op') == 'delete' and r.get('childId') == child_id], observed['ledger_after']- observed['intentional_difference'] = 'TS does not recognize the Rust-native rlmLedgerDelete kill marker'- else:- boundary = delete_contract(observed['ledger_after'], child_id)- assert len(boundary) == 1, 'expected exactly one original deletion boundary'- observed['retry_response'] = control.call('kill', **payload)- observed['ledger_after_retry'] = ledger()- # No second deletion boundary; usage amendments, if any, retain- # their actual rows and are not normalized out of this count.- after = delete_contract(observed['ledger_after_retry'], child_id)- assert after == boundary, 'idempotent retry changed the original boundary'- observed['behavior_verified'] = True- finally:- observed['wire'] = list(control.wire) if control else []- observed['provider_requests'] = provider.requests- provider.release.set()- finish(scope, control, daemon, observed)- log.close()- observed['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')[-10000:]- provider.shutdown()- provider.server_close()---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument('--receipt', type=Path, required=True)- args = parser.parse_args()- result = {'verified': False, 'scope': __doc__, 'runs': {}, 'not_verified': [- 'dead PID and interrupted cleanup (hosted Unix supervisor tests)',- 'parent kernel registry removal', 'TS repeated-delete behavior', 'TUI']}- try:- assert sys.platform == 'linux'- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256- result['ts_archive_sha256'] = TS_ARCHIVE_SHA256- with tempfile.TemporaryDirectory(prefix='pa-ddelete-', dir='/tmp') as folder:- for kind in ('ts', 'rust'):- binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()- observed = result['runs'][kind] = {'binary_sha256': digest(binary)}- try:- observe(binary, kind, Path(folder) / kind, observed)- except Exception as error:- observed['error'] = str(error)- assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r- for r in result['runs'].values()), 'actual delete verification failed'- result['verified'] = True- except Exception as error:- result['error'] = str(error)- args.receipt.parent.mkdir(parents=True, exist_ok=True)- args.receipt.write_text(json.dumps(result, ensure_ascii=False, indent=2))- return 0 if result['verified'] else 1---if __name__ == '__main__':- sys.exit(main())diff --git a/scripts/review_dock_screen.py b/scripts/review_dock_screen.pydeleted file mode 100644index ce123d61ee..0000000000--- a/scripts/review_dock_screen.py+++ /dev/null@@ -1,228 +0,0 @@-#!/usr/bin/env python3-"""SGR-aware variant of the existing binary comparator's Screen.--Supports the cursor/erase/color vocabulary already used by its terminal capture.-Unsupported SGR is disclosed; raw ANSI is the audit ground truth. This does not-claim a complete terminal emulator or pixel-exact font rendering.-"""-import codecs-import re-import unicodedata--class DockScreen:- """Existing xterm cell capture with explicit per-cell SGR attributes."""- def __init__(self, width=120, height=40):- self.width, self.height = width, height- self.cells = [[" "] * width for _ in range(height)]- self.styles = [[{} for _ in range(width)] for _ in range(height)]- self.sgr = {}- self.unsupported_sgr = []- self.unsupported_terminal = []- self.keyboard_controls = []- self.autowrap = True- self.alternate = None- self.row = self.col = 0- self.saved = (0, 0, {})- self.pending = ""- self.decoder = codecs.getincrementaldecoder("utf-8")("replace")-- def text(self):- return "\n".join("".join(row).rstrip() for row in self.cells)-- def feed(self, data):- self.pending += self.decoder.decode(data)- replies = []- while self.pending:- if self.pending[0] == "\x1b":- if len(self.pending) < 2:- break- if self.pending[1] in "]P_^":- end = re.search(r"\x07|\x1b\\", self.pending[2:])- if end is None:- break- sequence = self.pending[:2 + end.end()]- # OSC titles/hyperlinks do not move terminal cells. DCS,- # APC and PM can carry graphics or sixel: never silently- # accept their unknown effect on the captured frame.- payload = self.pending[2:2 + end.start()]- osc_kind = payload.split(';', 1)[0]- # Pinned TS asks for the default foreground/background via- # OSC10;? / OSC11;? (actual failed hosted receipt). Queries- # do not paint or set a color; a legacy PTY may stay silent.- # Color-setting variants remain unsupported and fail closed.- color_query = payload in ('10;?', '11;?')- if self.pending[1] != ']' or (not color_query and osc_kind not in ('0', '1', '2', '7', '8', '52', '133')):- self.unsupported_terminal.append(sequence)- self.pending = self.pending[2 + end.end():]- continue- if self.pending[1] == "[":- match = re.match(r"\x1b\[([0-?]*)([ -/]*)([@-~])", self.pending)- if match is None:- break- params, intermediate, command = match.groups()- sequence = self.pending[:match.end()]- self.pending = self.pending[match.end():]- nums = [int(x) if x.isdigit() else 0 for x in params.lstrip("?<>").split(";")]- n = nums[0] or 1- if intermediate and not (command == 'q' and intermediate == ' '):- self.unsupported_terminal.append(sequence)- continue- # Actual hosted TS/Rust captures contain these keyboard- # protocol controls. They do not paint cells and must not- # be interpreted as SGR4 (underline) after stripping >.- if command == 'm' and params in ('>4;0', '>4;1', '>4;2'):- self.keyboard_controls.append(sequence)- continue- if command == 'u' and params == '?':- self.keyboard_controls.append(sequence)- # Even a zero-flags reply advertises Kitty support to- # crossterm (vendor terminal/sys/unix.rs:255). This PTY- # emits legacy keys: stay silent on the Kitty query.- # The following DA1 query's response settles non-Kitty- # through KeyboardEnhancementFlagsFilter instead.- continue- if command == 'u' and (re.fullmatch(r'[>=]\d+(?:;\d+)?', params)- or re.fullmatch(r'<\d*', params)):- self.keyboard_controls.append(sequence)- continue- if params.startswith(('?', '<', '>')) and command not in 'hlnc':- self.unsupported_terminal.append(sequence)- continue- if command == "m": self.apply_sgr(nums)- elif command in "Hf":- self.row = min(self.height - 1, max(0, (nums[0] or 1) - 1))- self.col = min(self.width - 1, max(0, ((nums[1] if len(nums) > 1 else 1) or 1) - 1))- elif command == "A": self.row = max(0, self.row - n)- elif command == "B": self.row = min(self.height - 1, self.row + n)- elif command == "C": self.col = min(self.width - 1, self.col + n)- elif command == "D": self.col = max(0, self.col - n)- elif command == "G": self.col = min(self.width - 1, n - 1)- elif command == "J":- if nums[0] == 2:- self.cells = [[" "] * self.width for _ in range(self.height)]- self.styles = [[dict(self.sgr) for _ in range(self.width)] for _ in range(self.height)]- elif nums[0] == 0:- self.cells[self.row][self.col:] = [" "] * (self.width - self.col)- self.styles[self.row][self.col:] = [dict(self.sgr) for _ in range(self.width - self.col)]- for row in range(self.row + 1, self.height):- self.cells[row] = [" "] * self.width- self.styles[row] = [dict(self.sgr) for _ in range(self.width)]- elif nums[0] != 3: # ED3 clears scrollback, not visible cells.- self.unsupported_terminal.append(sequence)- elif command == "K":- if nums[0] not in (0, 1, 2):- self.unsupported_terminal.append(sequence)- continue- start, end = (0, self.width) if nums[0] == 2 else ((0, self.col + 1) if nums[0] == 1 else (self.col, self.width))- self.cells[self.row][start:end] = [" "] * (end - start)- self.styles[self.row][start:end] = [dict(self.sgr) for _ in range(end - start)]- elif command == "P":- line = self.cells[self.row]- line[self.col:] = (line[self.col + n:] + [" "] * n)[:self.width - self.col]- styles = self.styles[self.row]- styles[self.col:] = (styles[self.col + n:] + [dict(self.sgr) for _ in range(n)])[:self.width - self.col]- elif command == "X":- end = min(self.width, self.col + n)- self.cells[self.row][self.col:end] = [" "] * (end - self.col)- self.styles[self.row][self.col:end] = [dict(self.sgr) for _ in range(end - self.col)]- elif command == "n" and nums[0] == 6:- replies.append(f"\x1b[{self.row + 1};{self.col + 1}R".encode())- elif command == "c": replies.append(b"\x1b[?1;2c")- elif command in 'hl' and params.startswith('?'):- for mode in nums:- if mode == 7:- self.autowrap = command == 'h'- elif mode == 1049:- if command == 'h' and self.alternate is None:- self.alternate = (self.cells, self.styles, self.row, self.col,- dict(self.sgr), self.autowrap)- self.cells = [[' '] * self.width for _ in range(self.height)]- self.styles = [[{} for _ in range(self.width)] for _ in range(self.height)]- self.row = self.col = 0- elif command == 'l' and self.alternate is not None:- self.cells, self.styles, self.row, self.col, self.sgr, self.autowrap = self.alternate- self.alternate = None- elif mode not in (12, 25, 1000, 1002, 1003, 1004, 1006, 2004, 2026):- self.unsupported_terminal.append(sequence)- elif command == 'q' and intermediate == ' ':- pass # Cursor presentation, not cell geometry.- else:- self.unsupported_terminal.append(sequence)- continue- command = self.pending[1]- if command in '()' and len(self.pending) < 3:- break- self.pending = self.pending[2:]- if command == "7": self.saved = (self.row, self.col, dict(self.sgr))- elif command == "8":- self.row, self.col, saved_sgr = self.saved- self.sgr = dict(saved_sgr)- elif command in "()" and self.pending:- charset = self.pending[0]- self.pending = self.pending[1:]- if charset != 'B':- self.unsupported_terminal.append('\x1b' + command + charset)- else:- self.unsupported_terminal.append('\x1b' + command)- continue- char, self.pending = self.pending[0], self.pending[1:]- if char == "\r": self.col = 0- elif char == "\n":- self.row += 1- if self.row >= self.height:- self.cells.pop(0); self.cells.append([" "] * self.width)- self.styles.pop(0); self.styles.append([dict(self.sgr) for _ in range(self.width)])- self.row = self.height - 1- elif char == "\b": self.col = max(0, self.col - 1)- elif char == '\t': self.col = min(self.width - 1, ((self.col // 8) + 1) * 8)- elif char >= " " and not unicodedata.combining(char):- if self.col >= self.width:- if self.autowrap:- self.col = 0- self.row += 1- if self.row == self.height:- self.cells.pop(0); self.cells.append([' '] * self.width)- self.styles.pop(0); self.styles.append([dict(self.sgr) for _ in range(self.width)])- self.row = self.height - 1- else:- self.col = self.width - 1- self.cells[self.row][self.col] = char- self.styles[self.row][self.col] = dict(self.sgr)- self.col += 2 if unicodedata.east_asian_width(char) in "WF" else 1- elif char not in ('\x00', '\x07') and not unicodedata.combining(char):- self.unsupported_terminal.append(char)- return replies-- def apply_sgr(self, nums):- i = 0- while i < len(nums):- value = nums[i]- if value == 0:- self.sgr = {}- elif value in (1, 2, 3, 4, 7, 9):- self.sgr[str(value)] = True- elif value in (22, 23, 24, 27, 29):- for key in {22: ('1', '2'), 23: ('3',), 24: ('4',), 27: ('7',), 29: ('9',)}[value]:- self.sgr.pop(key, None)- elif 30 <= value <= 37 or 90 <= value <= 97:- self.sgr['fg'] = ['ansi', value]- elif 40 <= value <= 47 or 100 <= value <= 107:- self.sgr['bg'] = ['ansi', value]- elif value in (39, 49):- self.sgr.pop('fg' if value == 39 else 'bg', None)- elif value in (38, 48) and i + 1 < len(nums):- count = {5: 1, 2: 3}.get(nums[i + 1])- if count is not None and i + 2 + count <= len(nums):- self.sgr['fg' if value == 38 else 'bg'] = nums[i + 1:i + 2 + count]- i += 1 + count- else:- self.unsupported_sgr.append(nums[i:])- break- else:- self.unsupported_sgr.append([value])- i += 1-- def dock_styles(self):- return [{"text": ''.join(row).rstrip(), "styles": [dict(style) for style in self.styles[index]]}- for index, row in enumerate(self.cells)- if 'subagents' in ''.join(row) or 'running' in ''.join(row)]diff --git a/scripts/review_goal_backoff_parity.py b/scripts/review_goal_backoff_parity.pydeleted file mode 100755index 6e2fcffa3e..0000000000--- a/scripts/review_goal_backoff_parity.py+++ /dev/null@@ -1,427 +0,0 @@-#!/usr/bin/env python3-"""Binary-level, offline observation of goal continuation in TS and Rust.--Requires PA_TS_BINARY and PA_RUST_BINARY. The TS binary is the official 0.9.8-Linux release extracted by CI. All model traffic goes to this process's-loopback HTTP server; each invocation gets a disposable home and session tree.-Behavioral differences are evidence in --receipt, not silently normalized.-"""--import argparse-import hashlib-import http.server-import json-import os-import pathlib-import signal-import subprocess-import sys-import tempfile-import threading-import time--from review_agent_bounce_parity import Client-from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish---TS_ARCHIVE_SHA256 = "83fb09129bf78e3e60268212cd70932166591b15188caa70c1b0efbcc76235e2"-TIMEOUT_SECONDS = 35-MAX_REQUESTS = 6---def sha256(path):- digest = hashlib.sha256()- with open(path, "rb") as stream:- for chunk in iter(lambda: stream.read(1024 * 1024), b""):- digest.update(chunk)- return digest.hexdigest()---class MockServer(http.server.ThreadingHTTPServer):- daemon_threads = True-- def __init__(self, scenario):- super().__init__(("127.0.0.1", 0), MockHandler)- self.scenario = scenario- self.requests = []- self.changed = threading.Condition()- self.process = None- self.limit_hit = False---class MockHandler(http.server.BaseHTTPRequestHandler):- def log_message(self, *args):- pass-- def do_POST(self):- if self.path != "/v1/chat/completions":- self.send_error(404)- return- try:- length = int(self.headers.get("Content-Length", "0"))- body = json.loads(self.rfile.read(length))- except (ValueError, json.JSONDecodeError):- self.send_error(400)- return- server = self.server- with server.changed:- number = len(server.requests) + 1- server.requests.append({- "number": number,- "elapsed_ms": round((time.monotonic() - server.started) * 1000),- "path": self.path,- "model": body.get("model"),- "stream": body.get("stream"),- "roles": [m.get("role") for m in body.get("messages", [])],- "wake_marker": "<goal_backoff_wake>" in json.dumps(body),- "goal_context": "goal_context" in json.dumps(body),- })- if number >= MAX_REQUESTS:- server.limit_hit = True- server.changed.notify_all()-- if server.scenario == "recover" and number == 2:- delta = {"tool_calls": [{"index": 0, "id": "call_complete", "type": "function",- "function": {"name": "ipython", "arguments": json.dumps({"code": "await goal.complete()"})}}]}- finish = "tool_calls"- elif server.scenario == "recover" and number >= 3:- delta = {"content": "Goal completed."}- finish = "stop"- else:- delta = {}- finish = "stop"-- def chunk(value, reason=None):- return {"id": "mock-goal", "object": "chat.completion.chunk", "created": 1,- "model": "goal-fixture", "choices": [{"index": 0, "delta": value, "finish_reason": reason}]}-- usage = {"id": "mock-goal", "object": "chat.completion.chunk", "created": 1,- "model": "goal-fixture", "choices": [],- "usage": {"prompt_tokens": 10, "completion_tokens": 1,- "total_tokens": 11, "prompt_tokens_details": {"cached_tokens": 0}}}- payload = "".join("data: " + json.dumps(item, separators=(",", ":")) + "\n\n"- for item in (chunk({"role": "assistant", **delta}),- chunk({}, finish), usage))- payload += "data: [DONE]\n\n"- wire = payload.encode()- self.send_response(200)- self.send_header("Content-Type", "text/event-stream")- self.send_header("Cache-Control", "no-cache")- self.send_header("Content-Length", str(len(wire)))- self.end_headers()- try:- self.wfile.write(wire)- self.wfile.flush()- except (BrokenPipeError, ConnectionResetError):- pass---def run_case(binary, label, scenario, base_dir, observation):- home = base_dir / (label + "-" + scenario)- home.mkdir()- agent = home / "agent"- sessions = home / "sessions"- cwd = home / "work"- for path in (agent, sessions, cwd):- path.mkdir()- server = MockServer(scenario)- server.started = time.monotonic()- thread = threading.Thread(target=server.serve_forever, daemon=True)- thread.start()- base_url = "http://127.0.0.1:%d/v1" % server.server_address[1]- models = {"providers": {"fixture": {"api": "openai-completions", "baseUrl": base_url,- "apiKey": "offline-fixture-token", "models": [{- "id": "goal-fixture", "name": "Goal Fixture",- "reasoning": False, "contextWindow": 128000,- "maxTokens": 4096}]}}}- (agent / "models.json").write_text(json.dumps(models))- (agent / "settings.json").write_text(json.dumps({"defaultProvider": "fixture",- "defaultModel": "goal-fixture"}))- # An explicit environment prevents inherited tokens, proxies, or a user's- # package/session paths from reaching either binary or a spawned kernel.- env = {key: os.environ[key] for key in ("PATH", "LANG", "LC_ALL", "TZ", "PYTHONPATH",- "PRIME_AGENT_KERNEL_PYTHON", "PA_E2E_KERNEL_PYTHON")- if key in os.environ}- env.update({"HOME": str(home), "XDG_CONFIG_HOME": str(home / "config"),- "XDG_CACHE_HOME": str(home / "cache"), "XDG_DATA_HOME": str(home / "data"),- "TMPDIR": str(home / "tmp"), "DO_NOT_TRACK": "1", "PI_OFFLINE": "1",- "PI_CODING_AGENT_DIR": str(agent), "PI_SESSION_DIR": str(sessions),- "PRIME_AGENT_CODING_AGENT_DIR": str(agent),- "PRIME_AGENT_SESSION_DIR": str(sessions)})- env[TAG] = str(home.resolve())- (home / "tmp").mkdir()- goal_module = next((pathlib.Path(part) / "goal" / "__init__.py"- for part in env.get("PYTHONPATH", "").split(os.pathsep)- if part and (pathlib.Path(part) / "goal" / "__init__.py").is_file()), None)- kernel_provenance = {- "kernel_python": env.get("PRIME_AGENT_KERNEL_PYTHON"),- "e2e_kernel_python": env.get("PA_E2E_KERNEL_PYTHON"),- "pythonpath": env.get("PYTHONPATH"),- "goal_module_path": str(goal_module) if goal_module else None,- "goal_module_sha256": sha256(goal_module) if goal_module else None,- }- version = None- if scenario == "control":- try:- probe = subprocess.run([str(binary), "--version"], cwd=cwd, env=env,- text=True, capture_output=True, timeout=10, check=False)- except BaseException:- server.shutdown()- server.server_close()- thread.join(timeout=2)- raise- version = {"exit_code": probe.returncode, "stdout": probe.stdout.strip(),- "stderr": probe.stderr.strip()}- if probe.returncode != 0 or not probe.stdout.strip():- server.shutdown()- server.server_close()- thread.join(timeout=2)- raise RuntimeError("--version failed: " + json.dumps(version))- command = [str(binary), "--mode", "json", "--provider", "fixture", "--model",- "goal-fixture", "--no-session"]- if scenario != "control":- command += ["--goal", "Finish the offline fixture objective"]- if scenario == "budget":- command += ["--goal-token-budget", "1"]- command += ["Complete the fixture task."]- stdout_path = home / "stdout.jsonl"- stderr_path = home / "stderr.txt"- started = time.monotonic()- socket_path = home / 'd.sock'- scope = OwnedProcesses(binary, home.resolve(), socket_path)- daemon, client, process = None, None, None- daemon_log = (home / 'daemon.log').open('wb')- done = threading.Event()- tracker_errors = []- def discover():- while not done.is_set():- try:- scope.discover()- except Exception as error:- tracker_errors.append(str(error))- return- done.wait(0.025)- tracker = threading.Thread(target=discover, daemon=True)- primary_error = None- try:- # TS JSON mode otherwise creates a detached daemon that outlives the CLI.- # Supply the same daemon route with an explicitly owned supervisor/socket.- if label == 'ts':- daemon_command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(socket_path)]- daemon = subprocess.Popen(daemon_command, cwd=cwd, env=env, stdout=daemon_log,- stderr=subprocess.STDOUT, start_new_session=True)- scope.register(daemon, daemon_command)- client = Client(socket_path, daemon)- command += ['--daemon-socket', str(socket_path)]- with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr:- process = subprocess.Popen(command, cwd=cwd, env=env, stdout=stdout, stderr=stderr,- start_new_session=True)- scope.register(process, command)- server.process = process- tracker.start()- stopped = None- while True:- try:- exit_code = process.wait(timeout=0.15)- if server.limit_hit:- stopped = "request_observation_limit"- break- except subprocess.TimeoutExpired:- pass- with server.changed:- count = len(server.requests)- if time.monotonic() - started > TIMEOUT_SECONDS:- stopped = "timeout"- elif count >= MAX_REQUESTS:- stopped = "request_observation_limit"- if stopped:- scope.send(process.pid, signal.SIGTERM)- try:- exit_code = process.wait(timeout=2)- except subprocess.TimeoutExpired:- scope.send(process.pid, signal.SIGKILL)- exit_code = process.wait(timeout=2)- break- except BaseException as error:- primary_error = error- observation['primary_error'] = str(error)- raise- finally:- done.set()- if tracker.ident is not None:- tracker.join(timeout=2)- finish(scope, client, daemon, observation)- observation['tracker_errors'] = tracker_errors- observation['requests'] = server.requests- for path, key, limit in ((stdout_path, 'stdout_tail', 3500), (stderr_path, 'stderr_tail', 2500)):- if path.exists():- observation[key] = path.read_text(errors='replace')[-limit:]- daemon_log.close()- observation['daemon_log_tail'] = (home / 'daemon.log').read_text(errors='replace')[-6000:]- server.shutdown()- server.server_close()- thread.join(timeout=2)- if tracker_errors or tracker.is_alive():- observation['cleanup_verified'] = False- observation['cleanup_error'] = 'goal ownership tracker failed: ' + str(tracker_errors)- if not observation['cleanup_verified'] and primary_error is None:- raise AssertionError('goal fixture cleanup failed: ' + observation.get('cleanup_error', 'unknown'))-- raw = stdout_path.read_text(errors="replace")- errors = stderr_path.read_text(errors="replace")- events = []- for line in raw.splitlines():- try:- event = json.loads(line)- if isinstance(event, dict):- events.append(event)- except json.JSONDecodeError:- pass- combined = raw + "\n" + errors- goal_updates = [event["goal"] for event in events- if event.get("type") == "goal_update"- and isinstance(event.get("goal"), dict)]- goal_statuses = [goal.get("status") for goal in goal_updates]- final_goal_status = goal_statuses[-1] if goal_statuses else None- tool_events = []- for event in events:- if event.get("type") == "tool_execution_end":- tool_events.append({key: event.get(key) for key in- ("toolName", "toolCallId", "isError", "result") if key in event})- turn_tool_results = [event.get("toolResults") for event in events- if event.get("type") == "turn_end" and event.get("toolResults")]- model_completion_text = False- for event in events:- message = event.get("message")- if event.get("type") != "message_end" or not isinstance(message, dict):- continue- if message.get("role") != "assistant":- continue- content = message.get("content")- if isinstance(content, list):- model_completion_text |= any(- isinstance(block, dict) and block.get("type") == "text"- and "Goal completed." in block.get("text", "") for block in content- )- observation.update({- "version_probe": version,- "kernel_provenance": kernel_provenance if scenario == "control" else None,- "exit_code": exit_code,- "stopped": stopped,- "elapsed_ms": round((time.monotonic() - started) * 1000),- "requests": server.requests,- "wake_request_numbers": [row["number"] for row in server.requests if row["wake_marker"]],- "goal_context_request_numbers": [row["number"] for row in server.requests if row["goal_context"]],- "request_count": len(server.requests),- "event_types": [event.get("type") for event in events],- "tool_execution_end": tool_events,- "turn_end_tool_results": turn_tool_results,- "goal_statuses": goal_statuses,- "final_goal_status": final_goal_status,- "confirmed_goal_complete": final_goal_status == "complete",- "model_completion_text_seen": model_completion_text,- "goal_context_count": combined.count("goal_context"),- "wake_marker_count": combined.count("<goal_backoff_wake>"),- "cap_reason_seen": "Goal continuation cap reached: consecutive turns made no progress" in combined,- "stderr_tail": errors[-2500:],- "stdout_tail": raw[-3500:],- })- return observation---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--receipt", type=pathlib.Path, required=True)- args = parser.parse_args()- paths = {}- for label in ("TS", "RUST"):- value = os.environ.get("PA_" + label + "_BINARY")- if not value or not pathlib.Path(value).is_file() or not os.access(value, os.X_OK):- parser.error("PA_" + label + "_BINARY must name an executable file")- paths[label.lower()] = pathlib.Path(value).resolve()- if sys.platform != "linux":- parser.error("this fixture runs only in Linux CI")- args.receipt.parent.mkdir(parents=True, exist_ok=True)- if args.receipt.resolve().is_relative_to(pathlib.Path.cwd().resolve()):- parser.error("--receipt must be outside the repository")- archive = os.environ.get("PA_TS_ARCHIVE")- if not archive or not pathlib.Path(archive).is_file():- parser.error("PA_TS_ARCHIVE must name the downloaded official TS 0.9.8 archive")- archive_hash = sha256(archive)- if archive_hash != TS_ARCHIVE_SHA256:- parser.error("PA_TS_ARCHIVE SHA-256 mismatch: " + archive_hash)- result = {"ts_release_archive_sha256": archive_hash,- "binaries": {key: {"path": str(path), "sha256": sha256(path)}- for key, path in paths.items()},- "scenarios": {}, "differences": {}, "fixture_error": None}- temp = tempfile.TemporaryDirectory(prefix="goal-backoff-parity-")- try:- base_dir = pathlib.Path(temp.name)- for scenario in ("control", "empty", "recover", "budget"):- result["scenarios"][scenario] = {}- for label, binary in paths.items():- try:- observation = result["scenarios"][scenario][label] = {}- run_case(binary, label, scenario, base_dir, observation)- except Exception as exc:- result["fixture_error"] = "%s/%s: %s" % (scenario, label, exc)- break- if result["fixture_error"]:- break- ts = result["scenarios"][scenario]["ts"]- rust = result["scenarios"][scenario]["rust"]- if scenario == "control":- for label in paths:- result["binaries"][label]["version_probe"] = result["scenarios"][scenario][label]["version_probe"]- result["binaries"][label]["kernel_provenance"] = result["scenarios"][scenario][label]["kernel_provenance"]- result["differences"][scenario] = {- field: {"ts": ts[field], "rust": rust[field]}- for field in ("request_count", "wake_marker_count", "wake_request_numbers",- "goal_context_request_numbers", "cap_reason_seen",- "final_goal_status", "confirmed_goal_complete",- "model_completion_text_seen", "exit_code", "stopped")- if ts[field] != rust[field]- }- finally:- # Receipt persistence must survive cleanup failure; never suppress it or- # retry deletion while a writer's lifetime has not been proved complete.- try:- temp.cleanup()- except Exception as error:- result['directory_cleanup_error'] = str(error)- if result['fixture_error'] is None:- result['fixture_error'] = 'directory cleanup: ' + str(error)- all_runs = [run for versions in result["scenarios"].values() for run in versions.values()]- result["observed_fields_equal"] = not any(result["differences"].values())- result["validation_complete"] = (not result["fixture_error"] and len(all_runs) == 8- and all(run.get("request_count", 0) > 0 and run.get("stopped") is None- and run.get("cleanup_verified") is True- for run in all_runs))- recovery = result["scenarios"].get("recover", {})- result["recovery_confirmed"] = (len(recovery) == 2 and- all(run.get("confirmed_goal_complete", False) for run in recovery.values()))- result["parity"] = (result["observed_fields_equal"] and result["validation_complete"]- and result["recovery_confirmed"])- result["requires_behavior_decision"] = not result["parity"]- args.receipt.write_text(json.dumps(result, indent=2) + "\n")- print("goal parity receipt: %s" % args.receipt)- for scenario, versions in result["scenarios"].items():- print(scenario + ": " + ", ".join("%s requests=%s exit=%s stopped=%s" %- (label, run.get("request_count"), run.get("exit_code"), run.get("stopped"))- for label, run in versions.items()))- if result["requires_behavior_decision"]:- print("PARITY NOT CONFIRMED: inspect differences and incomplete observations in receipt")- if result["binaries"].get("ts", {}).get("kernel_provenance"):- print("kernel/goal provenance: " + json.dumps(result["binaries"]["ts"]["kernel_provenance"]))- if result["fixture_error"]:- print(result["fixture_error"], file=sys.stderr)- return 1- if any(run.get("request_count", 0) == 0 for versions in result["scenarios"].values()- for run in versions.values()):- print("a binary made no mock-provider request; inspect receipt", file=sys.stderr)- return 1- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/review_goal_fixture_lifecycle.py b/scripts/review_goal_fixture_lifecycle.pydeleted file mode 100644index 899b5a7809..0000000000--- a/scripts/review_goal_fixture_lifecycle.py+++ /dev/null@@ -1,178 +0,0 @@-"""Linux process ownership and cleanup for the offline goal CLI fixture."""-import json-import os-from pathlib import Path-import signal-import threading-import time--TAG = 'PA_GOAL_FIXTURE_ID'---def process_identity(pid):- stat = Path('/proc/%d/stat' % pid).read_text()- fields = stat[stat.rfind(')') + 2:].split()- return 'proc:' + fields[19], fields[0]---def verify_worker(row, active, binary, socket_path):- pid = row['pid']- assert row.get('rootActiveSessionId') == active, 'wrong descriptor identity'- assert row.get('supervisorSocketPath') == str(socket_path), 'wrong supervisor descriptor'- command = Path('/proc/%d/cmdline' % pid).read_bytes().split(b'\0')- assert command[0] == str(binary).encode(), 'worker argv0 is not fixture binary'- env = dict(item.split(b'=', 1) for item in Path('/proc/%d/environ' % pid).read_bytes().split(b'\0') if b'=' in item)- for key, value in {- 'PRIME_AGENT_INTERNAL_DAEMON_WORKER': '1',- 'PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID': active,- 'PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET': str(socket_path),- }.items():- assert env.get(key.encode()) == value.encode(), 'wrong fixture worker env identity'- worker_socket = str(row['socketPath']).encode()- assert (worker_socket in command or env.get(b'PRIME_AGENT_INTERNAL_DAEMON_WORKER_SOCKET') == worker_socket), 'wrong worker socket identity'- identity, state = process_identity(pid)- assert row.get('processStartId') == identity and state != 'Z', 'wrong/reused worker PID'- return pid, identity-----class OwnedProcesses:- def __init__(self, binary, root, socket_path):- self.binary, self.root, self.socket_path = binary, root, socket_path- self.direct = {}- self.targets = {}- self.errors = []-- def register(self, process, command):- identity, state = process_identity(process.pid)- assert state != 'Z', 'fixture process exited before identity capture'- self.direct[process.pid] = (identity, [str(arg).encode() for arg in command])- self.targets[process.pid] = identity-- def ownership(self, pid, identity):- try:- current, state = process_identity(pid)- if current != identity or state == 'Z':- return False- env = dict(item.split(b'=', 1) for item in Path('/proc/%d/environ' % pid).read_bytes().split(b'\0') if b'=' in item)- if env.get(TAG.encode()) != str(self.root).encode():- return False- command = Path('/proc/%d/cmdline' % pid).read_bytes().rstrip(b'\0').split(b'\0')- if pid in self.direct:- return self.direct[pid] == (identity, command)- if command[0] == str(self.binary).encode():- for path in (self.root / 'agent' / 'daemon-workers').rglob('*.json'):- row = json.loads(path.read_text())- if row.get('pid') == pid:- return verify_worker(row, row['rootActiveSessionId'], self.binary, self.socket_path) == (pid, identity)- return False- # Kernels retain the owner PID supplied by the actual TS/Rust launcher.- return ('python' in Path(command[0].decode()).name- and env.get(b'PRIME_AGENT_KERNEL_OWNER_PID') in- {str(owner).encode() for owner in self.targets})- except (OSError, ValueError, KeyError, AssertionError, UnicodeError):- return False-- def discover(self):- # Capture verified workers before their kernels, including detached workers.- for path in (self.root / 'agent' / 'daemon-workers').rglob('*.json'):- try:- row = json.loads(path.read_text())- pid, identity = verify_worker(row, row['rootActiveSessionId'], self.binary, self.socket_path)- if self.ownership(pid, identity):- self.targets[pid] = identity- except (OSError, ValueError, KeyError, AssertionError):- pass # A partial/retired descriptor is not an ownership proof.- for entry in Path('/proc').iterdir():- if entry.name.isdigit():- pid = int(entry.name)- try:- identity, _ = process_identity(pid)- if self.ownership(pid, identity):- self.targets[pid] = identity- except OSError:- pass-- def live(self):- alive = []- for pid, identity in list(self.targets.items()):- try:- current, state = process_identity(pid)- if current == identity and state != 'Z':- alive.append(pid)- except (FileNotFoundError, ProcessLookupError):- pass- return alive-- def wait_gone(self, timeout):- deadline = time.monotonic() + timeout- while True:- self.discover()- alive = self.live()- if not alive:- return- if time.monotonic() >= deadline:- raise AssertionError('owned goal fixture processes remained: ' + str(alive))- threading.Event().wait(0.025)-- def send(self, pid, signum):- identity = self.targets[pid]- try:- fd = os.pidfd_open(pid)- except ProcessLookupError:- return False- try:- if not self.ownership(pid, identity):- return False- signal.pidfd_send_signal(fd, signum)- return True- except ProcessLookupError:- return False- finally:- os.close(fd)---def finish(scope, client, daemon, observation):- """Fallback can reap leftovers but never converts failed shutdown into success."""- observation['cleanup_verified'] = False- try:- scope.discover()- if daemon is not None:- assert client is not None, 'owned daemon cleanup client unavailable'- client.call('shutdown', force=True)- observation['shutdown_wire'] = client.wire- client.close() # TS net.Server.close waits for raw fixture connections.- daemon.wait(timeout=15)- assert daemon.returncode == 0, 'owned goal daemon shutdown failed'- scope.wait_gone(5)- observation['cleanup_verified'] = True- except Exception as error:- observation['cleanup_error'] = str(error)- observation['fallback_signals'] = []- for signum, timeout in ((signal.SIGTERM, 3), (signal.SIGKILL, 2)):- try:- scope.discover()- except Exception as discovery_error:- scope.errors.append('fallback discovery failed: ' + str(discovery_error))- for pid in scope.live():- try:- if scope.send(pid, signum):- observation['fallback_signals'].append({'pid': pid, 'signal': signum.name})- except OSError as signal_error:- scope.errors.append(str(signal_error))- try:- scope.wait_gone(timeout)- break- except Exception as wait_error:- scope.errors.append('fallback wait failed: ' + str(wait_error))- observation['fallback_remaining'] = scope.live()- observation['fallback_errors'] = scope.errors- finally:- if client is not None:- try:- client.close()- except Exception as close_error:- observation['cleanup_verified'] = False- observation.setdefault('cleanup_error', str(close_error))- observation['owned_process_identities'] = dict(scope.targets)diff --git a/scripts/review_markdown_frames_parity.py b/scripts/review_markdown_frames_parity.pydeleted file mode 100644index d7b5211ae2..0000000000--- a/scripts/review_markdown_frames_parity.py+++ /dev/null@@ -1,315 +0,0 @@-#!/usr/bin/env python3-"""Pinned real-binary Markdown assistant-history frames, including SGR and OSC8.--Compares the bounded transcript region between literal sentinel paragraphs, not-the unrelated app chrome. Does not claim streaming, scrolling or mouse parity.-Only hosted Linux runs execute binaries; raw PTY captures remain in the receipt.-"""-import argparse-import codecs-import fcntl-import json-import os-from pathlib import Path-import pty-import re-import struct-import subprocess-import sys-import tempfile-import termios-import unicodedata--from review_draft_disconnect_parity import (- Screen, Supervisor, Terminal, actual_hello, digest, env_for,- TS_ARCHIVE_SHA256, TS_SOURCE_COMMIT,-)--START, END = "MARKDOWN FRAME START", "MARKDOWN FRAME END"-CORPUS = {- "adjacent_emphasis": "**bold***italic*\n**outer *inner***\n**outer *inner* tail***next*\n**outer `*` tail***next*\n" + r'''*a\*b* **a\**b**-***a\*b*** ~~a\~~b~~-*a\\* tail-**a *b** **a*b**''',- "escaped_titles": r'''[t](https://example.com "a \"b\"")-[t](https://example.com 'a \'b\'')-[t](foo(bar) "title")-[t](foo\(bar\) "a \"b\"")-[t](foo(bar "title")''',- "headings": "# Heading one\n## Heading two\n#### Heading four\n###### Heading six",- "nested_lists": "1. parent\n - child\n - leaf\n continuation\n2. sibling",- "quotes": "> quoted **bold** and `code`\n> lazy continuation",- "fences": "~~~python\nx = 1\nprint(x)\n~~~",- "escapes_images": r"\*literal\* snake_case_name \",- "unicode_wrap": "A **styledword**. Unicode café 界 words with `code` and trailing punctuation. " * 2,-}---class StyledScreen(Screen):- """Reuse the existing VT grid; retain style/link state on every painted cell."""- def __init__(self, width, height=40):- super().__init__(width, height)- self.stream = ""- self.stream_decoder = codecs.getincrementaldecoder("utf-8")("strict")- self.fg = self.bg = self.link = None- self.mods = set()- self.styles = [[None] * width for _ in range(height)]- self.style_errors = []- self.keyboard_controls = []-- def sgr(self, params):- nums = [int(x or 0) for x in params.split(";")]- i = 0- while i < len(nums):- n = nums[i]- if n == 0:- self.fg = self.bg = None- self.mods.clear()- elif n in (1, 2, 3, 4, 5, 7, 8, 9): self.mods.add(n)- elif n == 22: self.mods.difference_update((1, 2))- elif n in (23, 24, 25, 27, 28, 29): self.mods.discard(n - 20)- elif n in (39, 49):- if n == 39: self.fg = None- else: self.bg = None- elif 30 <= n <= 37 or 90 <= n <= 97:- self.fg = ("indexed", n - 30 if n < 90 else n - 90 + 8)- elif 40 <= n <= 47 or 100 <= n <= 107:- self.bg = ("indexed", n - 40 if n < 100 else n - 100 + 8)- elif n in (38, 48) and i + 1 < len(nums):- mode = nums[i + 1]- count = 1 if mode == 5 else (3 if mode == 2 else 0)- if not count or i + 2 + count > len(nums):- self.style_errors.append(f"unsupported color SGR {params}")- return- color = tuple(["indexed" if mode == 5 else "rgb"] + nums[i + 2:i + 2 + count])- if n == 38: self.fg = color- else: self.bg = color- i += 1 + count- else: self.style_errors.append(f"unsupported SGR {n}")- i += 1-- def feed(self, data):- self.stream += self.stream_decoder.decode(data)- replies = []- while self.stream:- if self.stream.startswith("\x1b"):- if len(self.stream) < 2: break- if self.stream[1] in "]P_^":- end = re.search(r"\x07|\x1b\\", self.stream[2:])- if end is None: break- size = 2 + end.end()- token, self.stream = self.stream[:size], self.stream[size:]- if token.startswith("\x1b]8;"):- payload = token[2:-len(end.group())]- self.link = payload.split(";", 2)[2] or None- replies.extend(super().feed(token.encode()))- continue- if self.stream[1] == "[":- hit = re.match(r"\x1b\[([0-?]*)([ -/]*)([@-~])", self.stream)- if hit is None: break- token, self.stream = self.stream[:hit.end()], self.stream[hit.end():]- params, _, command = hit.groups()- # These private controls configure/query keyboard input. They- # never modify painted cells; interpreting >4 as SGR4 would- # invent underline, and int('>4') is not a color parser.- if command == 'm' and params in ('>4;0', '>4;1', '>4;2'):- self.keyboard_controls.append(token)- continue- if command == 'u' and params == '?':- self.keyboard_controls.append(token)- # A flags response, even zero, advertises Kitty support.- # Stay silent; the following DA1 query is answered by the- # legacy Screen and settles crossterm's probe as non-Kitty.- continue- if command == 'u' and (re.fullmatch(r'[>=]\d+(?:;\d+)?', params)- or re.fullmatch(r'<\d*', params)):- self.keyboard_controls.append(token)- continue- if params.startswith(('?', '<', '>')) and command not in 'hlnc':- self.style_errors.append(f"unsupported private VT command {token!r}")- continue- nums = [int(x) if x.isdigit() else 0 for x in params.lstrip("?<>").split(";")]- n = nums[0] or 1- if command == "m": self.sgr(params)- elif command == "J":- if nums[0] in (2, 3): self.styles = [[None] * self.width for _ in range(self.height)]- elif nums[0] == 0:- self.styles[self.row][self.col:] = [None] * (self.width - self.col)- for row in range(self.row + 1, self.height): self.styles[row] = [None] * self.width- elif command == "K":- start, end = (0, self.width) if nums[0] == 2 else ((0, self.col + 1) if nums[0] == 1 else (self.col, self.width))- self.styles[self.row][start:end] = [None] * (end - start)- elif command == "P":- row = self.styles[self.row]- row[self.col:] = (row[self.col + n:] + [None] * n)[:self.width - self.col]- elif command == "X":- end = min(self.width, self.col + n)- self.styles[self.row][self.col:end] = [None] * (end - self.col)- elif command not in "HfABCDGnc" and not (command in "hl" and params.startswith("?")):- self.style_errors.append(f"unsupported VT command {token!r}")- replies.extend(super().feed(token.encode()))- continue- size = 3 if self.stream[1] in "()" else 2- if len(self.stream) < size: break- token, self.stream = self.stream[:size], self.stream[size:]- if token[1] not in "78()=><":- self.style_errors.append(f"unsupported VT escape {token!r}")- replies.extend(super().feed(token.encode()))- continue- char, self.stream = self.stream[0], self.stream[1:]- if char == "\n" and self.row == self.height - 1:- self.styles.pop(0)- self.styles.append([None] * self.width)- elif char >= " " and not unicodedata.combining(char):- row, col = self.row, self.col- if col >= self.width: col, row = 0, min(self.height - 1, row + 1)- self.styles[row][col] = (self.fg, self.bg, tuple(sorted(self.mods)), self.link)- if unicodedata.east_asian_width(char) in "WF" and col + 1 < self.width:- self.cells[row][col + 1] = " "- self.styles[row][col + 1] = None- if char == "\u200d" or "\ufe00" <= char <= "\ufe0f":- self.style_errors.append("unsupported joined/variation-selector grapheme")- elif unicodedata.combining(char) and self.col > 0:- self.cells[self.row][self.col - 1] += char- replies.extend(super().feed(char.encode()))- return replies-- def region(self):- lines = ["".join(row) for row in self.cells]- starts = [(n, row.index(START)) for n, row in enumerate(lines) if START in row]- ends = [n for n, row in enumerate(lines) if END in row]- if len(starts) != 1 or len(ends) != 1 or ends[0] <= starts[0][0]:- raise ValueError("complete bounded Markdown frame is not visible")- first, left = starts[0]- rows = []- for y in range(first + 1, ends[0]):- last = len(lines[y].rstrip())- rows.append([(self.cells[y][x], None if self.cells[y][x].isspace() else self.styles[y][x])- for x in range(left, max(left, last))])- while rows and not rows[0]: rows.pop(0)- while rows and not rows[-1]: rows.pop()- return rows---class StyledTerminal(Terminal):- def __init__(self, command, root, env, width):- self.master, slave = pty.openpty()- attrs = termios.tcgetattr(slave)- attrs[3] &= ~(termios.ECHO | termios.ICANON)- termios.tcsetattr(slave, termios.TCSANOW, attrs)- fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 40, width, 0, 0))- self.process = subprocess.Popen(command, cwd=root, env=env, stdin=slave,- stdout=slave, stderr=slave, start_new_session=True)- os.close(slave)- self.screen, self.raw = StyledScreen(width), bytearray()---class MarkdownSupervisor(Supervisor):- def __init__(self, path, hello, root, cwd):- self.cwd = str(cwd)- super().__init__(path, hello, 'markdown', root)-- def send(self, sock, data):- if data.get('type') == 'response' and data.get('command') == 'attach':- data['data']['snapshot']['state']['cwd'] = self.cwd- data['data']['snapshot']['summary']['cwd'] = self.cwd- elif data.get('type') == 'response' and data.get('command') in ('get_state', 'get_connection_state'):- data['data']['cwd'] = self.cwd- super().send(sock, data)---def assistant(text):- return {"role": "assistant", "stopReason": "stop", "api": "openai-completions",- "provider": "parity-local", "model": "parity-1", "timestamp": 1750000000000,- "content": [{"type": "text", "text": f"{START}\n\n{text}\n\n{END}"}],- "usage": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 0,- "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0}}}---def capture(kind, binary, root, hello, text, width, cwd):- root.mkdir()- env = env_for(root, kind)- server = MarkdownSupervisor(root / "fixture.sock", hello, root, cwd)- server.messages = [assistant(text)]- terminal = None- result = {"executed": False}- try:- terminal = StyledTerminal([str(binary), "--daemon-socket", str(server.path)], cwd, env, width)- terminal.wait("Markdown history fully painted", lambda: START in terminal.screen.text()- and END in terminal.screen.text(), server)- if terminal.screen.style_errors: raise RuntimeError(terminal.screen.style_errors)- region = terminal.screen.region()- painted = [style for row in region for char, style in row if not char.isspace()]- if not painted:- raise RuntimeError("Markdown corpus body was not painted")- if r'\' in text:- targets = {style[3] for style in painted if style and style[3]}- expected = cwd.as_uri() + '/url'- if targets != {expected}:- raise RuntimeError(f"relative hyperlink target differs: {targets!r} vs {expected!r}")- if "**bold***italic*" in text and not all(any(style and modifier in style[2] for style in painted)- for modifier in (1, 3)):- raise RuntimeError("actual PTY did not render both bold and italic modifiers")- result.update(executed=True, styled_region=region, commands=server.commands,- osc8_observed=any(style and style[3] for style in painted),- keyboard_controls=terminal.screen.keyboard_controls,- explicit_session_cwd=str(cwd),- screen=terminal.screen.text())- except Exception as error: result["error"] = f"{type(error).__name__}: {error}"- finally:- try:- if terminal:- result["raw_terminal"] = bytes(terminal.raw).decode("utf-8", "replace")- terminal.close()- finally:- server.close()- return result---def main():- parser = argparse.ArgumentParser()- parser.add_argument("--receipt", type=Path, required=True)- args = parser.parse_args()- receipt = {"verified": False, "results": {}, "comparisons": {}, "corpus": CORPUS,- "scope": "Actual assistant-history transcript region cells, foreground/background, modifiers and OSC8 at widths40/80/120; excludes chrome, streaming, scrolling and mouse actions.",- "source_commit": TS_SOURCE_COMMIT,- "ci": {k: os.environ.get(k) for k in ("GITHUB_RUN_ID", "GITHUB_SHA")}}- try:- if sys.platform != "linux": raise RuntimeError("binary execution requires hosted Linux")- if digest(Path(os.environ["PA_TS_ARCHIVE"])) != TS_ARCHIVE_SHA256:- raise RuntimeError("pinned official TS archive hash mismatch")- receipt["ts_archive_sha256"] = TS_ARCHIVE_SHA256- with tempfile.TemporaryDirectory(prefix="pa-md-frames-") as temp:- cwd = Path(temp) / 'project'- cwd.mkdir()- for kind in ("ts", "rust"):- binary = Path(os.environ[f"PA_{kind.upper()}_BINARY"]).resolve()- root = Path(temp) / kind- root.mkdir()- env = env_for(root, kind)- hello = actual_hello(binary, root, env)- side = receipt["results"][kind] = {"binary_sha256": digest(binary), "hello": hello, "cases": {}}- version = subprocess.run([str(binary), "--version"], cwd=root, env=env,- capture_output=True, text=True, timeout=15, check=True).stdout.strip()- side["version"] = version- if kind == "ts" and "0.9.8" not in version:- raise RuntimeError("unexpected TS binary version")- for name, text in CORPUS.items():- for width in (40, 80, 120):- key = f"{name}-{width}"- side["cases"][key] = capture(kind, binary, root / key, hello, text, width, cwd)- for key in receipt["results"]["ts"]["cases"]:- a, b = [receipt["results"][kind]["cases"][key] for kind in ("ts", "rust")]- receipt["comparisons"][key] = bool(a.get("executed") and b.get("executed")- and a["styled_region"] == b["styled_region"])- receipt["verified"] = bool(receipt["comparisons"] and all(receipt["comparisons"].values()))- except Exception as error: receipt["error"] = f"{type(error).__name__}: {error}"- args.receipt.parent.mkdir(parents=True, exist_ok=True)- args.receipt.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n")- print(json.dumps({"verified": receipt["verified"], "comparisons": receipt["comparisons"],- "error": receipt.get("error")}))- return 0 if receipt["verified"] else 1---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/review_sidecar_exit_parity.py b/scripts/review_sidecar_exit_parity.pydeleted file mode 100644index 4787fa1e09..0000000000--- a/scripts/review_sidecar_exit_parity.py+++ /dev/null@@ -1,12 +0,0 @@-#!/usr/bin/env python3-"""Compare actual TS/Rust lifecycle/catalog values and require Rust exit-sidecar currency.--The Rust-only v2 info sidecar must certify the final ended child transcript.-The imported verifier retains actual TS catalog and cache-boundary observations;-TS has no Rust sidecar-format requirement.-"""-import sys-from review_ledger_liveness_parity import main--if __name__ == '__main__':- sys.exit(main(require_current_sidecar=True))diff --git a/scripts/review_socket_pin_parity.py b/scripts/review_socket_pin_parity.pydeleted file mode 100644index d948fb8fc8..0000000000--- a/scripts/review_socket_pin_parity.py+++ /dev/null@@ -1,147 +0,0 @@-#!/usr/bin/env python3-"""Real daemon comparison of preserved legacy sockets and Rust-only byte fallback.--The TS default namespace remains the migration-marker baseline. The new Rust-only-fallback is deliberately distinct; a Darwin uname shim exercises the actual-published launcher on Linux with the exact CI-built Rust payload. Both daemons-run only in fixture-owned homes and socket paths. No installer downloads occur.-"""-import argparse-import json-import os-from pathlib import Path-import shutil-import socket-import subprocess-import tempfile-import threading-import time--from review_draft_disconnect_parity import digest, env_for, stop, TS_ARCHIVE_SHA256---def launch_daemon(command, expected, root, env):- log_path = root / 'daemon.log'- with log_path.open('wb') as log:- process = subprocess.Popen(command + ['--mode', 'daemon'], cwd=root, env=env,- stdout=log, stderr=log, start_new_session=True)- try:- deadline = time.monotonic() + 35- while time.monotonic() < deadline:- if process.poll() is not None:- raise RuntimeError('daemon exited before bind: ' + log_path.read_text(errors='replace'))- try:- with socket.socket(socket.AF_UNIX) as sock:- sock.settimeout(2)- sock.connect(str(expected))- with sock.makefile('rb') as stream:- hello = json.loads(stream.readline())- assert hello.get('type') == 'daemon_hello' and hello.get('schemaId'), hello- return {'bound_socket': str(expected), 'hello': hello,- 'log': log_path.read_text(errors='replace')}- except (FileNotFoundError, ConnectionRefusedError, socket.timeout):- threading.Event().wait(0.05)- raise TimeoutError('daemon did not bind expected launcher socket: ' + str(expected))- finally:- stop(process)---def install_launcher(binary, root, env):- prefix = root / 'prefix'- payload = prefix / 'share/prime-agent'- payload.mkdir(parents=True)- (payload / 'prime-agent').symlink_to(binary)- installer = Path(__file__).resolve().parents[1].joinpath('install-rust.sh').read_text()- marker = '# --- the launcher (the takeover lives here)'- section = marker + installer.split(marker, 1)[1]- section = section.split('# The cmd/PowerShell launcher twin', 1)[0]- script = '''PREFIX="$PRIME_AGENT_RUST_PREFIX"-bin_dir="$PREFIX/bin"-mkdir -p "$bin_dir"-launcher="$bin_dir/prime-agent"-WINDOWS=no-say() { :; }; note() { :; }; die() { echo "$*" >&2; exit 1; }-trap '[ -z "${launcher_tmp:-}" ] || rm -f "$launcher_tmp"' EXIT-''' + section- installed = subprocess.run(['sh', '-eu'], input=script,- env={**env, 'PRIME_AGENT_RUST_PREFIX': str(prefix)},- cwd=root, text=True, capture_output=True, timeout=15)- if installed.returncode:- raise RuntimeError('launcher extraction failed: ' + installed.stderr)- return prefix / 'bin/prime-agent'---def main():- parser = argparse.ArgumentParser()- parser.add_argument('--receipt', type=Path, required=True)- args = parser.parse_args()- receipt = {'passed': False, 'scenario': 'socket_pin', 'runs': {},- 'scope': 'Actual daemons: legacy namespace compatibility and explicit override; actual Rust launcher and installer stop probe: UTF-8 byte fallback under Darwin uname shim.',- 'intentional_difference': 'Unmarked Rust launcher uses rust-only namespace; non-Linux oversized pins fall back to /tmp. TS namespace and migration marker remain unchanged.'}- fallback_dir = None- try:- assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256- ts, rust = (Path(os.environ[key]).resolve() for key in ('PA_TS_BINARY', 'PA_RUST_BINARY'))- receipt['binary_sha256'] = {'ts': digest(ts), 'rust': digest(rust)}- with tempfile.TemporaryDirectory(prefix='pa-pin-', dir='/tmp') as temp:- root = Path(temp)- for kind, binary in (('ts', ts), ('rust', rust)):- owned = root / kind- owned.mkdir()- env = env_for(owned, kind)- tmp = owned / 'tmp'- legacy = tmp / f'prime-agent-{os.getuid()}/daemon.sock'- command = binary- if kind == 'rust':- command = install_launcher(binary, owned, env)- marker = owned / 'prefix/share/.prime-agent-npm-bridge/legacy-daemon-socket'- marker.parent.mkdir()- marker.write_text('fixture\n')- receipt['runs'][kind + '_legacy'] = launch_daemon([str(command)], legacy, owned, env)- explicit = tmp / 'explicit.sock'- receipt['runs'][kind + '_override'] = launch_daemon([str(command), '--daemon-socket', str(explicit)], explicit, owned,- {**env, 'PRIME_AGENT_DAEMON_SOCKET': str(explicit)})- if kind == 'rust':- marker.unlink()- shim = owned / 'shim'- shim.mkdir()- fixture_uid = str(500000000 + os.getpid())- for name, text in (('uname', 'Darwin'), ('id', fixture_uid)):- path = shim / name- path.write_text(f'#!/bin/sh\nprintf "%s\\n" "{text}"\n')- path.chmod(0o755)- long_tmp = str(owned / ('é' * 25))- long_pin = f'{long_tmp}/prime-agent-rust-{fixture_uid}/daemon.sock'- assert len(long_pin) <= 103 and len(long_pin.encode()) > 103, long_pin- candidate = Path(f'/tmp/prime-agent-rust-{fixture_uid}')- # Atomic reservation: a collision never authorizes cleanup.- candidate.mkdir(mode=0o700, exist_ok=False)- fallback_dir = candidate- fallback = fallback_dir / 'daemon.sock'- long_env = {**env, 'TMPDIR': long_tmp,- 'PATH': str(shim) + os.pathsep + env['PATH'], 'OS': 'Darwin',- 'LC_ALL': 'C.UTF-8'}- receipt['runs']['rust_utf8_fallback'] = launch_daemon([str(command)], fallback,- owned, long_env)- source = Path(__file__).resolve().parents[1].joinpath('install-rust.sh').read_text()- probe = 'rust_socket="${TMPDIR:-/tmp}' + source.split('rust_socket="${TMPDIR:-/tmp}', 1)[1].split('env_socket=', 1)[0]- observed = subprocess.run(['sh', '-eu'], input=probe + '\nprintf "%s" "$rust_socket"',- env=long_env, text=True, capture_output=True, timeout=10, check=True).stdout- assert observed == str(fallback), (observed, fallback)- receipt['stop_probe'] = observed- receipt['utf8_pin'] = {'characters': len(long_pin), 'bytes': len(long_pin.encode()),- 'original_pin': long_pin}- receipt['passed'] = True- except Exception as error:- receipt['error'] = f'{type(error).__name__}: {error}'- finally:- if fallback_dir is not None and fallback_dir.exists():- shutil.rmtree(fallback_dir)- args.receipt.parent.mkdir(parents=True, exist_ok=True)- args.receipt.write_text(json.dumps(receipt, indent=2) + '\n')- print(json.dumps({'passed': receipt['passed'], 'error': receipt.get('error')}))- return 0 if receipt['passed'] else 1---if __name__ == '__main__':- raise SystemExit(main())diff --git a/scripts/test_review_agent_bounce_parity.py b/scripts/test_check_agent_bounce.pysimilarity index 98%rename from scripts/test_review_agent_bounce_parity.pyrename to scripts/test_check_agent_bounce.pyindex dda00f0115..2d64563ff6 100644--- a/scripts/test_review_agent_bounce_parity.py+++ b/scripts/test_check_agent_bounce.py@@ -8,7 +8,7 @@ import tempfileimport threadingimport unittest-from review_agent_bounce_parity import Client, Provider+from check_agent_bounce import Client, Providerclass LiveProcess:diff --git a/scripts/test_review_at_completion_parity.py b/scripts/test_check_at_completion.pysimilarity index 64%rename from scripts/test_review_at_completion_parity.pyrename to scripts/test_check_at_completion.pyindex ffafc57398..e11e388162 100644--- a/scripts/test_review_at_completion_parity.py+++ b/scripts/test_check_at_completion.py@@ -4,18 +4,15 @@ import copyimport unittestfrom unittest.mock import Mock, patch-from review_at_completion_parity import (- CASES, children_visible, close_terminal, compare, completion_rows, discover_direct, frame,-)-from review_dock_screen import DockScreen+from check_at_completion import CASES, children_visible, close_terminal, completion_rows, discover_direct, frame, verify+from lifecycle_lib import DockScreendef observations():- side = {'behavior_verified': True, 'cleanup_verified': True, 'inputs': ['40646972', '09'],+ case = {'behavior_verified': True, 'cleanup_verified': True, 'inputs': ['40646972', '09'],'frames': {'after': {'text': 'only_child.rs', 'menu_rows': ['only_child.rs'],'children_visible': True}}}- return {'runs': {kind: {'cases': {case: copy.deepcopy(side) for case in CASES}}- for kind in ('ts', 'rust')}}+ return {name: copy.deepcopy(case) for name in CASES}class EvidenceGuards(unittest.TestCase):@@ -32,8 +29,8 @@ class EvidenceGuards(unittest.TestCase):scope = Mock(root='/case', direct={}, targets={})scope.ownership.return_value = ownership- with patch('review_at_completion_parity.Path') as proc, \- patch('review_at_completion_parity.process_identity', return_value=('proc:10', 'S')):+ with patch('check_at_completion.Path') as proc, \+ patch('check_at_completion.process_identity', return_value=('proc:10', 'S')):proc.return_value.iterdir.return_value = [Entry()]discover_direct(scope, ['/binary', '--daemon-socket', '/case/fixture.sock'])return scope@@ -61,45 +58,29 @@ class EvidenceGuards(unittest.TestCase):def test_directory_row_alone_is_not_a_child(self):self.assertFalse(children_visible('› dir with spaces/ dir with spaces\n│ @dir'))- def test_intended_ts_closed_menu_is_reported_without_normalization(self):- receipt = observations()- for case in CASES:- receipt['runs']['ts']['cases'][case]['frames']['after'].update(- children_visible=False, menu_rows=[], text='│ @"dir with spaces/"')- result = compare(receipt)- self.assertTrue(all(not row['ts_children_visible'] and row['rust_children_visible']- and not row['full_text_equal'] and not row['menu_rows_equal']- for row in result.values()))-- def test_missing_rust_children_fails_even_when_other_phases_pass(self):- receipt = observations()- receipt['runs']['rust']['cases']['enter']['frames']['after']['children_visible'] = False+ def test_missing_children_fails_even_when_other_phases_pass(self):+ cases = observations()+ cases['enter']['frames']['after']['children_visible'] = Falsewith self.assertRaises(AssertionError):- compare(receipt)+ verify(cases)def test_unexecuted_case_cannot_pass(self):- receipt = observations()- receipt['runs']['ts']['cases']['tab']['behavior_verified'] = False+ cases = observations()+ cases['tab']['behavior_verified'] = Falsewith self.assertRaises(AssertionError):- compare(receipt)+ verify(cases)def test_failed_cleanup_cannot_pass(self):- receipt = observations()- receipt['runs']['rust']['cases']['typed_slash']['cleanup_verified'] = False+ cases = observations()+ cases['typed_slash']['cleanup_verified'] = Falsewith self.assertRaises(AssertionError):- compare(receipt)+ verify(cases)def test_caught_case_error_cannot_pass(self):- receipt = observations()- receipt['runs']['ts']['cases']['enter']['error'] = 'capture failed'+ cases = observations()+ cases['enter']['error'] = 'capture failed'with self.assertRaises(AssertionError):- compare(receipt)-- def test_different_keys_cannot_claim_comparison(self):- receipt = observations()- receipt['runs']['ts']['cases']['tab']['inputs'] = ['different']- with self.assertRaises(AssertionError):- compare(receipt)+ verify(cases)def test_unknown_terminal_geometry_cannot_pass_frame_evidence(self):screen = DockScreen()@@ -114,9 +95,9 @@ class EvidenceGuards(unittest.TestCase):scope.live.return_value = []server = Mock(commands=[], errors=[])observed = {}- with patch('review_at_completion_parity.discover_direct'), \- patch('review_at_completion_parity.time.monotonic', side_effect=[0, 20]), \- patch('review_at_completion_parity.os.close'):+ with patch('check_at_completion.discover_direct'), \+ patch('check_at_completion.time.monotonic', side_effect=[0, 20]), \+ patch('check_at_completion.os.close'):with self.assertRaisesRegex(AssertionError, 'ordinary TUI exit'):close_terminal(terminal, scope, server, observed)self.assertFalse(observed['cleanup_verified'])@@ -128,8 +109,8 @@ class EvidenceGuards(unittest.TestCase):scope = Mock(targets={})server = Mock(commands=[], errors=[])observed = {}- with patch('review_at_completion_parity.discover_direct'), \- patch('review_at_completion_parity.os.close', side_effect=OSError('close failed')):+ with patch('check_at_completion.discover_direct'), \+ patch('check_at_completion.os.close', side_effect=OSError('close failed')):with self.assertRaisesRegex(AssertionError, 'PTY close'):close_terminal(terminal, scope, server, observed)self.assertFalse(observed['cleanup_verified'])@@ -141,7 +122,7 @@ class EvidenceGuards(unittest.TestCase):scope.wait_gone.side_effect = AssertionError('owned child survived')server = Mock(commands=[], errors=[])observed = {}- with patch('review_at_completion_parity.discover_direct') as discover:+ with patch('check_at_completion.discover_direct') as discover:with self.assertRaisesRegex(AssertionError, 'owned child survived'):close_terminal(None, scope, server, observed)discover.assert_called_once()diff --git a/scripts/test_review_catalog_field_removal_parity.py b/scripts/test_check_catalog_field_removal.pysimilarity index 70%rename from scripts/test_review_catalog_field_removal_parity.pyrename to scripts/test_check_catalog_field_removal.pyindex 0a03794948..272a6a3668 100644--- a/scripts/test_review_catalog_field_removal_parity.py+++ b/scripts/test_check_catalog_field_removal.py@@ -4,7 +4,7 @@ from pathlib import Pathimport tempfileimport unittest-from review_catalog_field_removal_parity import (COUNT, CWD, REMOVED, seed, validate)+from check_catalog_field_removal import COUNT, CWD, REMOVED, seed, validateclass CatalogFieldRemovalGuards(unittest.TestCase):@@ -12,14 +12,12 @@ class CatalogFieldRemovalGuards(unittest.TestCase):self.directory = tempfile.TemporaryDirectory()self.addCleanup(self.directory.cleanup)self.root = Path(self.directory.name)- self.expected, self.transcripts = seed(self.root)+ self.expected = seed(self.root)- def observation(self, kind):+ def observation(self):rows = copy.deepcopy(self.expected)for row in rows:row['path'] = str(self.root / 'agent/sessions' / row['path'])- if kind == 'ts':- row[REMOVED] = self.transcripts[row['id']]frames = [{'type': 'session_list_item', 'id': '1','command': 'list_saved_sessions', 'session': copy.deepcopy(row)} for row in rows]frames.append({'type': 'session_list_progress', 'id': '1',@@ -37,45 +35,32 @@ class CatalogFieldRemovalGuards(unittest.TestCase):observed['raw_received_hex'] = [(json.dumps(frame) + '\n').encode().hex()for frame in observed['frames']]- def check(self, observed, kind):- return validate(observed, kind, self.root, self.expected, self.transcripts)+ def check(self, observed):+ return validate(observed, self.root, self.expected)- def test_exact_ts_corpus_and_rust_omission_keep_same_stable_fields(self):- self.assertEqual(self.check(self.observation('ts'), 'ts'),- self.check(self.observation('rust'), 'rust'))+ def test_omission_keeps_seeded_stable_fields(self):+ self.assertEqual(self.check(self.observation()),+ sorted(self.expected, key=lambda row: row['id']))for path in (self.root / 'agent/sessions').glob('*.jsonl'):entries = [json.loads(line) for line in path.read_text().splitlines()]self.assertEqual(entries[0]['type'], 'session')self.assertEqual(entries[0]['id'], path.stem)self.assertIn('café 界', entries[-1]['message']['content'][0]['text'])- def test_rust_null_empty_or_text_key_fails_in_both_stream_and_final(self):+ def test_null_empty_or_text_key_fails_in_both_stream_and_final(self):for location in ('stream', 'final'):for value in (None, '', 'stale text'):- observed = self.observation('rust')+ observed = self.observation()row = observed['frames'][0]['session'] if location == 'stream' else observed['final_data']['sessions'][0]row[REMOVED] = valueself.raw(observed)with self.subTest(location=location, value=value), self.assertRaises(AssertionError):- self.check(observed, 'rust')-- def test_ts_missing_empty_or_firstmessage_alias_fails_in_stream_and_final(self):- for location in ('stream', 'final'):- for mode in ('missing', 'empty', 'first_message'):- observed = self.observation('ts')- row = observed['frames'][0]['session'] if location == 'stream' else observed['final_data']['sessions'][0]- if mode == 'missing':- del row[REMOVED]- else:- row[REMOVED] = '' if mode == 'empty' else row['firstMessage']- self.raw(observed)- with self.subTest(location=location, mode=mode), self.assertRaises(AssertionError):- self.check(observed, 'ts')+ self.check(observed)def test_missing_duplicate_escaped_or_changed_stable_rows_fail(self):for location in ('stream', 'final'):for mode in ('missing', 'duplicate', 'escaped', 'changed'):- observed = self.observation('rust')+ observed = self.observation()rows = [frame['session'] for frame in observed['frames'] if frame['type'] == 'session_list_item'] if location == 'stream' else observed['final_data']['sessions']if mode == 'missing':if location == 'stream':@@ -91,11 +76,11 @@ class CatalogFieldRemovalGuards(unittest.TestCase):rows[0]['path' if mode == 'escaped' else 'name'] = '/ambient/escaped.jsonl' if mode == 'escaped' else 'wrong'self.raw(observed)with self.subTest(location=location, mode=mode), self.assertRaises(AssertionError):- self.check(observed, 'rust')+ self.check(observed)def test_missing_raw_wrong_request_and_postterminal_frames_fail_closed(self):for mode in ('missing_raw', 'wrong_raw', 'wrong_request', 'after_final', 'failure'):- observed = self.observation('rust')+ observed = self.observation()if mode == 'missing_raw':observed['raw_received_hex'] = []elif mode == 'wrong_raw':@@ -109,7 +94,7 @@ class CatalogFieldRemovalGuards(unittest.TestCase):observed['frames'][-1]['success'] = Falseself.raw(observed)with self.subTest(mode=mode), self.assertRaises(AssertionError):- self.check(observed, 'rust')+ self.check(observed)if __name__ == '__main__':diff --git a/scripts/test_review_client_write_cleanup_parity.py b/scripts/test_check_client_write_cleanup.pysimilarity index 66%rename from scripts/test_review_client_write_cleanup_parity.pyrename to scripts/test_check_client_write_cleanup.pyindex 03fd918d9d..0b7f8262ef 100644--- a/scripts/test_review_client_write_cleanup_parity.py+++ b/scripts/test_check_client_write_cleanup.py@@ -1,24 +1,15 @@#!/usr/bin/env python3-"""Lightweight guards on the comparator's strict normalization and raw capture."""+"""Lightweight guards on the check's validation and raw capture."""import ioimport unittestfrom pathlib import Pathimport tempfilefrom unittest.mock import Mock, patch-import review_client_write_cleanup_parity as verifier-from review_client_write_cleanup_parity import RecordedIO, canonical+import check_client_write_cleanup as verifier+from check_client_write_cleanup import RecordedIO-class ComparatorTests(unittest.TestCase):- def test_only_pause_identity_is_normalized(self):- baseline = {'pauseId': 'generated-A', 'error': 'denied', 'nested': {'id': 'keep'}}- equivalent = {'pauseId': 'generated-B', 'error': 'denied', 'nested': {'id': 'keep'}}- changed = {'pauseId': 'generated-B', 'error': 'allowed', 'nested': {'id': 'keep'}}- self.assertEqual(canonical(baseline), canonical(equivalent))- self.assertNotEqual(canonical(baseline), canonical(changed))- self.assertEqual(canonical(baseline)['nested'], {'id': 'keep'})- self.assertEqual(baseline['pauseId'], 'generated-A')-+class CheckTests(unittest.TestCase):def test_primary_failure_survives_a_shutdown_failure(self):provider = Mock(server_port=1)observer = Mock(raw_wire=[], wire=[])@@ -26,27 +17,25 @@ class ComparatorTests(unittest.TestCase):attached = Mock(raw_wire=[], wire=[])attached.call.side_effect = [None, None, {'pauseId': 'fixture-pause'}]second = Mock(raw_wire=[], wire=[])- second.call.side_effect = [{'attachedClients': 1}, None, {'attachedClients': 0}, RuntimeError('primary enqueue failure')]+ summary = {'activeSessionId': 'fixture-session', 'sessionName': 'Write cleanup fixture', 'workerPid': 123}+ second.call.side_effect = [{'attachedClients': 1}, summary, {'attachedClients': 0}, RuntimeError('primary enqueue failure')]process = Mock(poll=Mock(return_value=None))observed = {}with tempfile.TemporaryDirectory() as folder:with patch.object(verifier, 'Provider', return_value=provider), patch.object(verifier.threading, 'Thread'), patch.object(verifier, 'WireClient', side_effect=[observer, attached, second]), patch.object(verifier.subprocess, 'Popen', return_value=process), patch.object(verifier, 'stop'), patch.object(verifier, 'settle_owned_processes'), patch.object(verifier, 'pause_released', side_effect=[False, True]):with self.assertRaisesRegex(RuntimeError, '^primary enqueue failure$'):- verifier.run_case(Path('/fixture/binary'), 'ts', Path(folder), observed)+ verifier.run_case(Path('/fixture/binary'), Path(folder), observed)self.assertEqual(observed['primary_error'], 'primary enqueue failure')self.assertEqual(observed['cleanup_error'], 'cleanup failed')self.assertFalse(observed['verified'])self.assertEqual(second.call.call_args.kwargs['streamingBehavior'], 'followUp')- def test_rename_trigger_deviation_rejects_unexpected_data(self):- verifier.validate_rename_trigger('ts', None, 'session')- with self.assertRaises(AssertionError):- verifier.validate_rename_trigger('ts', {}, 'session')+ def test_rename_trigger_rejects_unexpected_data(self):summary = {'activeSessionId': 'session', 'sessionName': 'Write cleanup fixture', 'workerPid': 123}- verifier.validate_rename_trigger('rust', summary, 'session')+ verifier.validate_rename_trigger(summary, 'session')for changed in (None, {**summary, 'activeSessionId': 'another'}, {**summary, 'sessionName': 'wrong'}, {**summary, 'workerPid': None}):with self.assertRaises(AssertionError):- verifier.validate_rename_trigger('rust', changed, 'session')+ verifier.validate_rename_trigger(changed, 'session')def test_nonowner_probe_does_not_hide_other_errors(self):response = {'command': 'release_session_input_pause', 'success': False,diff --git a/scripts/test_review_custom_ca_parity.py b/scripts/test_check_custom_ca.pysimilarity index 89%rename from scripts/test_review_custom_ca_parity.pyrename to scripts/test_check_custom_ca.pyindex 8e5a4811c7..336eb8fd96 100644--- a/scripts/test_review_custom_ca_parity.py+++ b/scripts/test_check_custom_ca.py@@ -4,7 +4,7 @@ from pathlib import Pathfrom unittest.mock import patchimport unittest-from review_custom_ca_parity import ANSWER, PROMPT, confirm_cleanup, terminal_assistant, request_contract+from check_custom_ca import ANSWER, PROMPT, confirm_cleanup, terminal_assistant, request_contractclass ReceiptParsingTests(unittest.TestCase):@@ -27,7 +27,7 @@ class ReceiptParsingTests(unittest.TestCase):self.assertEqual(request_contract(request)['current_prompt_count'], 1)def test_shutdown_failure_remains_red(self):- with patch('review_custom_ca_parity.owned_processes', return_value={}):+ with patch('check_custom_ca.owned_processes', return_value={}):with self.assertRaises(AssertionError):confirm_cleanup(Path('/unused'), {'shutdown_error': 'fixture shutdown refused'})diff --git a/scripts/test_review_dead_child_delete_parity.py b/scripts/test_check_dead_child_delete.pysimilarity index 90%rename from scripts/test_review_dead_child_delete_parity.pyrename to scripts/test_check_dead_child_delete.pyindex 881378ca2f..8cc5757c9a 100644--- a/scripts/test_review_dead_child_delete_parity.py+++ b/scripts/test_check_dead_child_delete.py@@ -1,5 +1,5 @@import unittest-from review_dead_child_delete_parity import delete_contract+from check_dead_child_delete import delete_contractclass DeleteReceiptGuards(unittest.TestCase):diff --git a/scripts/test_review_dock_events_parity.py b/scripts/test_check_dock_events.pysimilarity index 80%rename from scripts/test_review_dock_events_parity.pyrename to scripts/test_check_dock_events.pyindex af6dd2935f..3cbb9a5a7e 100644--- a/scripts/test_review_dock_events_parity.py+++ b/scripts/test_check_dock_events.py@@ -6,8 +6,8 @@ import jsonimport threadingfrom unittest.mock import Mock, patch-from review_dock_events_parity import DockSupervisor, child, cost_ready, parent, run_case, running_visible, ts_dock_visible, visible_cost-from review_dock_screen import DockScreen+from check_dock_events import DockSupervisor, child, cost_ready, parent, run_case, running_visible, visible_cost+from lifecycle_lib import DockScreenclass CaptureTests(unittest.TestCase):@@ -34,20 +34,18 @@ class CaptureTests(unittest.TestCase):self.assertEqual(screen.styles[0][0]['bg'], [2, 1, 2, 3])def test_count_predicate_distinguishes_events_and_layouts(self):- self.assertTrue(running_visible('1 running', 'ts', 1))- self.assertFalse(running_visible('1 running', 'ts', 2))- self.assertTrue(running_visible('2 subagents', 'rust', 2))- self.assertTrue(running_visible('◆ 1 subagent ·', 'rust', 1))+ self.assertTrue(running_visible('2 subagents', 2))+ self.assertFalse(running_visible('2 subagents', 1))+ self.assertTrue(running_visible('◆ 1 subagent ·', 1))expanded = '◆ subagents 2 running · 0 idle · 0 inactive'- self.assertTrue(running_visible(expanded, 'rust', 2, expanded=True))- self.assertFalse(running_visible(expanded, 'rust', 2))- self.assertFalse(running_visible('◆ 2 subagents', 'rust', 2, expanded=True))+ self.assertTrue(running_visible(expanded, 2, expanded=True))+ self.assertFalse(running_visible(expanded, 2))+ self.assertFalse(running_visible('◆ 2 subagents', 2, expanded=True))def test_count_has_integer_boundaries(self):- for kind, label in [('ts', 'running'), ('rust', 'subagents')]:- self.assertFalse(running_visible('10 ' + label, kind, 0))- self.assertFalse(running_visible('12 ' + label, kind, 2))- self.assertTrue(running_visible('● 0 ' + label + ' ·', kind, 0))+ self.assertFalse(running_visible('10 subagents', 0))+ self.assertFalse(running_visible('12 subagents', 2))+ self.assertTrue(running_visible('● 0 subagents ·', 0))def test_unknown_geometry_is_recorded(self):screen = DockScreen()@@ -82,12 +80,12 @@ class CaptureTests(unittest.TestCase):terminal.wait.side_effect = RuntimeError('initial readiness failed')terminal.close.side_effect = RuntimeError('terminal cleanup failed')with tempfile.TemporaryDirectory() as folder, \- patch('review_dock_events_parity.actual_hello', return_value={}), \- patch('review_dock_events_parity.DockSupervisor', return_value=server), \- patch('review_dock_events_parity.Terminal', return_value=terminal):+ patch('check_dock_events.actual_hello', return_value={}), \+ patch('check_dock_events.DockSupervisor', return_value=server), \+ patch('check_dock_events.Terminal', return_value=terminal):observed = {}with self.assertRaisesRegex(RuntimeError, 'terminal cleanup failed'):- run_case(Path('/fixture-binary'), 'rust', Path(folder) / 'case', observed)+ run_case(Path('/fixture-binary'), Path(folder) / 'case', observed)server.close.assert_called_once()self.assertNotIn('cleanup_verified', observed)@@ -153,12 +151,6 @@ class CaptureTests(unittest.TestCase):self.assertFalse(cost_ready('partial repaint $0.', '0.42'))self.assertTrue(cost_ready('Dock fixture $0.42', '0.42'))- def test_startup_warning_cannot_make_removed_dock_look_present(self):- warning = 'Prime Agent\n and subagents remain available.\n >\n← manage'- self.assertIn('subagents', warning)- self.assertFalse(ts_dock_visible(warning))- self.assertTrue(ts_dock_visible(warning + '\n╭─ subagents ───╮\n│ ● 0 running │'))-def test_exact_default_color_queries_do_not_mutate_capture(self):screen = DockScreen()screen.feed(b'\x1b[31m1 subagents')diff --git a/scripts/test_review_factory_navigation_parity.py b/scripts/test_check_factory_navigation.pysimilarity index 89%rename from scripts/test_review_factory_navigation_parity.pyrename to scripts/test_check_factory_navigation.pyindex 9a06f1ff35..5d9175dbe7 100644--- a/scripts/test_review_factory_navigation_parity.py+++ b/scripts/test_check_factory_navigation.py@@ -1,7 +1,7 @@import unittestimport json-from review_factory_navigation_parity import factory_click, FactorySupervisor, GRAPH-from review_dock_screen import DockScreen+from check_factory_navigation import factory_click, FactorySupervisor, GRAPH+from lifecycle_lib import DockScreenclass FactoryNavigationGuards(unittest.TestCase):diff --git a/scripts/test_review_factory_resumption_parity.py b/scripts/test_check_factory_resumption.pysimilarity index 96%rename from scripts/test_review_factory_resumption_parity.pyrename to scripts/test_check_factory_resumption.pyindex 74543fee91..8074d51996 100644--- a/scripts/test_review_factory_resumption_parity.py+++ b/scripts/test_check_factory_resumption.py@@ -1,7 +1,7 @@import copyimport jsonimport unittest-from review_factory_resumption_parity import MARKER, extract, validate+from check_factory_resumption import MARKER, extract, validateclass FactoryReceiptGuards(unittest.TestCase):diff --git a/scripts/test_review_factory_validation_parity.py b/scripts/test_check_factory_validation.pysimilarity index 96%rename from scripts/test_review_factory_validation_parity.pyrename to scripts/test_check_factory_validation.pyindex da18476e98..be2d2c54db 100644--- a/scripts/test_review_factory_validation_parity.py+++ b/scripts/test_check_factory_validation.py@@ -2,7 +2,7 @@ import ioimport jsonfrom types import SimpleNamespaceimport unittest-from review_factory_validation_parity import validate, Handler+from check_factory_validation import validate, Handlerclass FactoryValidationGuards(unittest.TestCase):diff --git a/scripts/test_review_kernel_env_parity.py b/scripts/test_check_kernel_env.pysimilarity index 80%rename from scripts/test_review_kernel_env_parity.pyrename to scripts/test_check_kernel_env.pyindex 6f4d76184c..c8933e3d7e 100644--- a/scripts/test_review_kernel_env_parity.py+++ b/scripts/test_check_kernel_env.py@@ -8,7 +8,7 @@ import jsonfrom pathlib import Pathimport signalfrom unittest.mock import patch, MagicMock-from review_kernel_env_parity import current_probe, CODE, MARKER, owned_kernel, finish_daemon, KernelClient, signal_owned, reap_leftovers, wait_gone, live_identities+from check_kernel_env import current_probe, CODE, MARKER, owned_kernel, finish_daemon, KernelClient, signal_owned, reap_leftovers, wait_gone, live_identitiesdef requests(content=None):@@ -45,23 +45,23 @@ class ProbeTests(unittest.TestCase):def test_foreign_fixture_kernel_is_not_owned(self):env = b'PRIME_AGENT_KERNEL_OWNER_PID=123\0PA_KERNEL_ENV_FIXTURE_ID=/other-fixture\0'- with patch('review_kernel_env_parity.process_identity', return_value=('proc:456', 'S')), \+ with patch('check_kernel_env.process_identity', return_value=('proc:456', 'S')), \patch('pathlib.Path.read_bytes', return_value=env):self.assertIsNone(owned_kernel(789, 123, '/fixture'))def test_wrong_kernel_owner_is_not_owned(self):env = b'PRIME_AGENT_KERNEL_OWNER_PID=999\0PA_KERNEL_ENV_FIXTURE_ID=/fixture\0'- with patch('review_kernel_env_parity.process_identity', return_value=('proc:456', 'S')), \+ with patch('check_kernel_env.process_identity', return_value=('proc:456', 'S')), \patch('pathlib.Path.read_bytes', return_value=env):self.assertIsNone(owned_kernel(789, 123, '/fixture'))def test_recycled_kernel_pid_is_not_owned(self):- with patch('review_kernel_env_parity.process_identity', return_value=('proc:new', 'S')):+ with patch('check_kernel_env.process_identity', return_value=('proc:new', 'S')):self.assertIsNone(owned_kernel(789, 123, '/fixture', 'proc:old'))def test_matching_kernel_owner_fixture_and_start_identity(self):env = b'PRIME_AGENT_KERNEL_OWNER_PID=123\0PA_KERNEL_ENV_FIXTURE_ID=/fixture\0'- with patch('review_kernel_env_parity.process_identity', return_value=('proc:456', 'S')), \+ with patch('check_kernel_env.process_identity', return_value=('proc:456', 'S')), \patch('pathlib.Path.read_bytes', side_effect=[env, b'/fixture/python3\0-m\0rlm.kernel\0']):self.assertEqual(owned_kernel(789, 123, '/fixture', 'proc:456'), 'proc:456')@@ -82,12 +82,12 @@ class ProbeTests(unittest.TestCase):process.wait.assert_not_called()def test_process_exiting_during_proc_read_is_gone(self):- with patch('review_kernel_env_parity.process_identity', side_effect=ProcessLookupError(3, 'No such process')):+ with patch('check_kernel_env.process_identity', side_effect=ProcessLookupError(3, 'No such process')):wait_gone({(789, 'proc:456')})self.assertEqual(live_identities({(789, 'proc:456')}), set())def test_other_proc_read_errors_still_fail_cleanup(self):- with patch('review_kernel_env_parity.process_identity', side_effect=PermissionError('denied')):+ with patch('check_kernel_env.process_identity', side_effect=PermissionError('denied')):with self.assertRaises(PermissionError):wait_gone({(789, 'proc:456')})with self.assertRaises(PermissionError):@@ -100,20 +100,20 @@ class ProbeTests(unittest.TestCase):client.sock.gettimeout.return_value = 35client.reader = MagicMock()client.reader.readline.return_value = json.dumps({'type': 'response', 'id': '1', 'success': True, 'data': {'done': True}}).encode()- with patch('review_kernel_env_parity.time.monotonic', side_effect=[0, 36, 36]):+ with patch('check_kernel_env.time.monotonic', side_effect=[0, 36, 36]):self.assertEqual(client.call('prompt_and_wait', timeout_seconds=90), {'done': True})self.assertEqual([call.args[0] for call in client.sock.settimeout.call_args_list], [90, 54, 35])def test_recycled_pid_never_receives_fallback_signal(self):with patch('os.pidfd_open', return_value=42, create=True), patch('os.close'), \- patch('review_kernel_env_parity.process_identity', return_value=('proc:new', 'S')), \+ patch('check_kernel_env.process_identity', return_value=('proc:new', 'S')), \patch('signal.pidfd_send_signal', create=True) as sent:self.assertFalse(signal_owned(789, 'proc:old', lambda: True, signal.SIGTERM))sent.assert_not_called()def test_failed_ownership_check_never_receives_fallback_signal(self):with patch('os.pidfd_open', return_value=42, create=True), patch('os.close'), \- patch('review_kernel_env_parity.process_identity', return_value=('proc:456', 'S')), \+ patch('check_kernel_env.process_identity', return_value=('proc:456', 'S')), \patch('signal.pidfd_send_signal', create=True) as sent:self.assertFalse(signal_owned(789, 'proc:456', lambda: False, signal.SIGTERM))sent.assert_not_called()@@ -122,9 +122,9 @@ class ProbeTests(unittest.TestCase):observation = {'cleanup_error': 'graceful shutdown refused', 'cleanup_verified': False}with patch('pathlib.Path.rglob', return_value=[]), \patch('pathlib.Path.iterdir', return_value=[Path('/proc/789')]), \- patch('review_kernel_env_parity.owned_kernel', return_value='proc:456'), \- patch('review_kernel_env_parity.signal_owned', return_value=True) as sent, \- patch('review_kernel_env_parity.live_identities', return_value=set()):+ patch('check_kernel_env.owned_kernel', return_value='proc:456'), \+ patch('check_kernel_env.signal_owned', return_value=True) as sent, \+ patch('check_kernel_env.live_identities', return_value=set()):reap_leftovers(Path('/fixture'), Path('/fixture/binary'), Path('/fixture/d.sock'),None, {789: 'proc:456'}, 123, '/fixture', observation)sent.assert_called_once()@@ -136,9 +136,9 @@ class ProbeTests(unittest.TestCase):def test_foreign_kernel_never_becomes_fallback_target(self):with patch('pathlib.Path.rglob', return_value=[]), \patch('pathlib.Path.iterdir', return_value=[Path('/proc/789')]), \- patch('review_kernel_env_parity.owned_kernel', return_value=None), \- patch('review_kernel_env_parity.signal_owned') as sent, \- patch('review_kernel_env_parity.live_identities', return_value=set()):+ patch('check_kernel_env.owned_kernel', return_value=None), \+ patch('check_kernel_env.signal_owned') as sent, \+ patch('check_kernel_env.live_identities', return_value=set()):reap_leftovers(Path('/fixture'), Path('/fixture/binary'), Path('/fixture/d.sock'),None, {789: 'proc:456'}, 123, '/fixture', {})sent.assert_not_called()diff --git a/scripts/test_review_late_message_receipt_parity.py b/scripts/test_check_late_message_receipt.pysimilarity index 98%rename from scripts/test_review_late_message_receipt_parity.pyrename to scripts/test_check_late_message_receipt.pyindex 48e127b99e..5ddbbe775a 100644--- a/scripts/test_review_late_message_receipt_parity.py+++ b/scripts/test_check_late_message_receipt.py@@ -9,7 +9,7 @@ import tempfileimport typesimport copyimport unittest-from review_late_message_receipt_parity import MESSAGE, PARENT_CELL, late_entries, validate+from check_late_message_receipt import MESSAGE, PARENT_CELL, late_entries, validateclass LateReceiptGuards(unittest.TestCase):diff --git a/scripts/test_review_launch_env_parity.py b/scripts/test_check_launch_env.pysimilarity index 54%rename from scripts/test_review_launch_env_parity.pyrename to scripts/test_check_launch_env.pyindex 1c29eb4061..14c23fdc72 100644--- a/scripts/test_review_launch_env_parity.py+++ b/scripts/test_check_launch_env.py@@ -5,7 +5,7 @@ from pathlib import Pathimport unittestimport tempfilefrom unittest.mock import patch, MagicMock-from review_launch_env_parity import current_probe, restart, verify_worker, worker_descriptor, finish_daemon, comparable_probes, MARKER+from check_launch_env import current_probe, restart, verify_worker, worker_descriptor, finish_daemon, MARKERdef requests(content=None):@@ -33,21 +33,21 @@ class VerifierTests(unittest.TestCase):current_probe(requests(content), 'new')def test_descriptor_with_wrong_identity_never_kills(self):- with patch('review_launch_env_parity.worker_descriptor', return_value=(Path('/fixture'),+ with patch('check_launch_env.worker_descriptor', return_value=(Path('/fixture'),{'pid': 123, 'rootActiveSessionId': 'someone-else'})), patch('os.kill') as kill:with self.assertRaisesRegex(AssertionError, 'descriptor identity'):- restart(None, 'fixture', Path('/fixture'), Path('/fixture/binary'), {}, False, {}, set(), 'rust', {})+ restart(None, 'fixture', Path('/fixture'), Path('/fixture/binary'), {}, False, {}, set(), {})kill.assert_not_called()def test_wrong_executable_never_kills(self):- with patch('review_launch_env_parity.worker_descriptor', return_value=(Path('/fixture'),+ with patch('check_launch_env.worker_descriptor', return_value=(Path('/fixture'),{'pid': 123, 'rootActiveSessionId': 'fixture', 'supervisorSocketPath': '/d.sock'})), \patch('pathlib.Path.read_bytes', return_value=b'/other/binary\0worker\0'), patch('os.kill') as kill:with self.assertRaisesRegex(AssertionError, 'fixture binary'):- restart(None, 'fixture', Path('/fixture'), Path('/fixture/binary'), {}, False, {}, set(), 'rust', {})+ restart(None, 'fixture', Path('/fixture'), Path('/fixture/binary'), {}, False, {}, set(), {})kill.assert_not_called()- def test_ts_descriptor_filename_need_not_equal_active_id(self):+ def test_descriptor_filename_need_not_equal_active_id(self):with tempfile.TemporaryDirectory() as folder:agent = Path(folder)descriptors = agent / 'daemon-workers' / 'fixture'@@ -57,7 +57,7 @@ class VerifierTests(unittest.TestCase):path.write_text(json.dumps(row))self.assertEqual(worker_descriptor(agent, 'active-id', Path('/fixture.sock')), (path, row))- def test_ts_and_rust_worker_socket_seams_are_both_checked(self):+ def test_both_worker_socket_seams_are_checked(self):row = {'pid': 123, 'rootActiveSessionId': 'fixture', 'supervisorSocketPath': '/fixture/d.sock','socketPath': '/fixture/worker.sock', 'processStartId': 'proc:456'}env = b'PRIME_AGENT_INTERNAL_DAEMON_WORKER=1\0PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID=fixture\0PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET=/fixture/d.sock\0'@@ -66,7 +66,7 @@ class VerifierTests(unittest.TestCase):(b'/fixture/binary\0worker\0', b'PRIME_AGENT_INTERNAL_DAEMON_WORKER_SOCKET=/fixture/worker.sock\0'),]:with patch('pathlib.Path.read_bytes', side_effect=[command, env + extra]), \- patch('review_launch_env_parity.process_identity', return_value=('proc:456', 'S')):+ patch('check_launch_env.process_identity', return_value=('proc:456', 'S')):self.assertEqual(verify_worker(row, 'fixture', Path('/fixture/binary'), Path('/fixture/d.sock')), (123, 'proc:456'))def test_reused_pid_is_rejected(self):@@ -75,7 +75,7 @@ class VerifierTests(unittest.TestCase):command = b'/fixture/binary\0--mode\0daemon\0/fixture/worker.sock\0'env = b'PRIME_AGENT_INTERNAL_DAEMON_WORKER=1\0PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID=fixture\0PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET=/fixture/d.sock\0'with patch('pathlib.Path.read_bytes', side_effect=[command, env]), \- patch('review_launch_env_parity.process_identity', return_value=('proc:new', 'S')):+ patch('check_launch_env.process_identity', return_value=('proc:new', 'S')):with self.assertRaisesRegex(AssertionError, 'reused worker PID'):verify_worker(row, 'fixture', Path('/fixture/binary'), Path('/fixture/d.sock'))@@ -95,56 +95,6 @@ class VerifierTests(unittest.TestCase):finish_daemon(client, process, 'shutdown', force=True)process.wait.assert_not_called()- def test_known_filter_difference_does_not_hide_other_env_difference(self):- ts = {'phase': {'env': {'PA_ENV_MARKER': 'same', 'PRIME_AGENT_INTERNAL_PARITY_CANARY': 'injected'}}}- rust = {'phase': {'env': {'PA_ENV_MARKER': 'same', 'PRIME_AGENT_INTERNAL_PARITY_CANARY': None}}}- self.assertEqual(comparable_probes(ts), comparable_probes(rust))- rust['phase']['env']['PA_ENV_MARKER'] = 'wrong'- self.assertNotEqual(comparable_probes(ts), comparable_probes(rust))- self.assertEqual(ts['phase']['env']['PRIME_AGENT_INTERNAL_PARITY_CANARY'], 'injected')-- def test_ts_resident_reopens_exact_file_with_empty_fresh_context(self):- with tempfile.TemporaryDirectory() as folder:- root = Path(folder)- path = root / 'descriptor.json'- failed = {'pid': 123, 'rootActiveSessionId': 'old-active', 'lifecycle': 'failed',- 'lastError': 'Waiting for a client with fresh runtime context'}- path.write_text(json.dumps(failed))- session = {'sessionId': 'durable-id', 'sessionFile': str(root / 'session.jsonl')}- created = {**session, 'activeSessionId': 'new-active'}- client = MagicMock()- client.call.side_effect = lambda kind, **data: created if kind == 'create' else session- observed = {}- with patch('review_launch_env_parity.worker_descriptor', side_effect=[(path, failed), (root / 'new-descriptor.json', {'pid': 456})]), \- patch('review_launch_env_parity.verify_worker', side_effect=[(123, 'proc:old'), (456, 'proc:new')]), \- patch('review_launch_env_parity.wait_gone'), patch('os.kill'):- active = restart(client, 'old-active', root / 'agent', root / 'binary', {'cwd': str(root)},- False, observed, set(), 'ts', session)- self.assertEqual(active, 'new-active')- self.assertEqual(observed['parked_descriptor'], failed)- create = [call for call in client.call.call_args_list if call.args == ('create',)]- self.assertEqual(len(create), 1)- self.assertEqual(create[0].kwargs['sessionPath'], session['sessionFile'])- self.assertEqual(create[0].kwargs['launchEnv'], {})- self.assertEqual(observed['replacement_state'], session)-- def test_ts_fresh_create_cannot_switch_durable_identity(self):- with tempfile.TemporaryDirectory() as folder:- root = Path(folder)- path = root / 'descriptor.json'- failed = {'pid': 123, 'rootActiveSessionId': 'old-active', 'lifecycle': 'failed',- 'lastError': 'Waiting for a client with fresh runtime context'}- path.write_text(json.dumps(failed))- session = {'sessionId': 'durable-id', 'sessionFile': str(root / 'session.jsonl')}- client = MagicMock()- client.call.return_value = {**session, 'sessionId': 'wrong-id', 'activeSessionId': 'new-active'}- with patch('review_launch_env_parity.worker_descriptor', return_value=(path, failed)), \- patch('review_launch_env_parity.verify_worker', return_value=(123, 'proc:old')), \- patch('review_launch_env_parity.wait_gone'), patch('os.kill'):- with self.assertRaisesRegex(AssertionError, 'changed durable session identity'):- restart(client, 'old-active', root / 'agent', root / 'binary', {}, False,- {}, set(), 'ts', session)-if __name__ == '__main__':unittest.main()diff --git a/scripts/test_review_ledger_liveness_parity.py b/scripts/test_check_ledger_liveness.pysimilarity index 79%rename from scripts/test_review_ledger_liveness_parity.pyrename to scripts/test_check_ledger_liveness.pyindex a1a7b6395c..70d1938510 100644--- a/scripts/test_review_ledger_liveness_parity.py+++ b/scripts/test_check_ledger_liveness.py@@ -5,18 +5,10 @@ from unittest.mock import patchfrom pathlib import Pathimport unittest-from review_ledger_liveness_parity import NAME, MARKER, admitted_probe, archive_restore_unsupported, catalog_row, confirm_cleanup, family_contract+from check_ledger_liveness import NAME, MARKER, admitted_probe, catalog_row, confirm_cleanup, family_contractclass FamilyReceiptTests(unittest.TestCase):- def test_only_exact_actual_archive_refusal_is_classified_unsupported(self):- row = {'type': 'response', 'command': 'send_message', 'success': False,- 'error': 'Unknown active session: saved-id'}- self.assertTrue(archive_restore_unsupported(row, 'saved-id'))- for changed in ({'success': True}, {'error': 'Request timed out'},- {'error': 'Unknown active session: different-id'}, {'command': 'kill'}):- self.assertFalse(archive_restore_unsupported({**row, **changed}, 'saved-id'))-def test_duplicate_catalog_paths_fail(self):with tempfile.TemporaryDirectory() as directory:path = Path(directory) / 'child.jsonl'@@ -42,7 +34,7 @@ class FamilyReceiptTests(unittest.TestCase):admitted_probe({'messages': [row, row]})def test_shutdown_failure_cannot_be_a_green_receipt(self):- with patch('review_ledger_liveness_parity.owned_processes', return_value={}):+ with patch('check_ledger_liveness.owned_processes', return_value={}):with self.assertRaises(AssertionError):confirm_cleanup(Path('/unused'), {'shutdown_error': 'shutdown refused'})diff --git a/scripts/test_review_live_mcp_parity.py b/scripts/test_check_live_mcp.pysimilarity index 79%rename from scripts/test_review_live_mcp_parity.pyrename to scripts/test_check_live_mcp.pyindex 1ee6f580d8..e72ddeb6d1 100644--- a/scripts/test_review_live_mcp_parity.py+++ b/scripts/test_check_live_mcp.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Lightweight verifier tests; these do not claim binary parity."""+"""Lightweight check tests; these never start a product binary."""import copyimport http.clientimport json@@ -9,30 +9,28 @@ import tempfileimport threadingimport unittest-import review_live_mcp_parity as parity+import check_live_mcp as checkclass VerifierTests(unittest.TestCase):def observation(self):- return {'before': {'pid': 10, 'configs': {'fixture-before': parity.BEFORE, 'fixture-after': {}}},- 'after': {'pid': 10, 'configs': {'fixture-before': {}, 'fixture-after': parity.AFTER}}}+ return {'before': {'pid': 10, 'configs': {'fixture-before': check.BEFORE, 'fixture-after': {}}},+ 'after': {'pid': 10, 'configs': {'fixture-before': {}, 'fixture-after': check.AFTER}}}- def test_rejects_stale_and_rebuilt_rust_handler(self):+ def test_rejects_stale_and_rebuilt_handler(self):good = self.observation()- parity.validate_observation(good, 'rust')+ check.validate_observation(good)stale = self.observation()stale['after']['configs'] = copy.deepcopy(stale['before']['configs'])with self.assertRaises(AssertionError):- parity.validate_observation(stale, 'rust')+ check.validate_observation(stale)rebuilt = self.observation()rebuilt['after']['pid'] = 11with self.assertRaises(AssertionError):- parity.validate_observation(rebuilt, 'rust')- parity.validate_observation(rebuilt, 'ts')- self.assertFalse(rebuilt['kernel_pid_equal'])+ check.validate_observation(rebuilt)def test_provider_selects_offered_tool_and_requires_actual_result(self):- server = parity.Server()+ server = check.Server()thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()try:@@ -44,14 +42,14 @@ class VerifierTests(unittest.TestCase):self.assertEqual(response.status, 200)event = json.loads(wire.splitlines()[0].removeprefix('data: '))function = event['choices'][0]['delta']['tool_calls'][0]['function']- self.assertEqual(function, {'name': 'python_repl', 'arguments': json.dumps({'code': parity.CELL})})+ self.assertEqual(function, {'name': 'python_repl', 'arguments': json.dumps({'code': check.CELL})})with self.assertRaises(AssertionError):- parity.latest_probe(server.requests['before'])+ check.latest_probe(server.requests['before'])actual = self.observation()['before']- second = {'messages': [{'role': 'tool', 'content': parity.MARKER + json.dumps(actual)}]}+ second = {'messages': [{'role': 'tool', 'content': check.MARKER + json.dumps(actual)}]}connection.request('POST', '/v1/chat/completions', json.dumps(second), {'Content-Type': 'application/json'})connection.getresponse().read()- self.assertEqual(parity.latest_probe(server.requests['before']), actual)+ self.assertEqual(check.latest_probe(server.requests['before']), actual)connection.close()finally:server.shutdown()@@ -60,10 +58,10 @@ class VerifierTests(unittest.TestCase):def test_after_probe_selects_latest_result_in_history(self):before, after = self.observation()['before'], self.observation()['after']- old = {'role': 'tool', 'content': parity.MARKER + json.dumps(before)}- new = {'role': 'tool', 'content': [{'type': 'text', 'text': parity.MARKER + json.dumps(after)}]}+ old = {'role': 'tool', 'content': check.MARKER + json.dumps(before)}+ new = {'role': 'tool', 'content': [{'type': 'text', 'text': check.MARKER + json.dumps(after)}]}requests = [{'messages': [old]}, {'messages': [old, new]}]- self.assertEqual(parity.latest_probe(requests), after)+ self.assertEqual(check.latest_probe(requests), after)def test_jsonl_client_preserves_fragmented_frames_and_protocol(self):errors = []@@ -89,7 +87,7 @@ class VerifierTests(unittest.TestCase):thread = threading.Thread(target=serve)thread.start()process = type('Process', (), {'poll': lambda self: None})()- client = parity.Client(path, process)+ client = check.Client(path, process)try:self.assertEqual(client.request({'type': 'reload'}), {'ok': 1})self.assertEqual(len(client.frames), 3)diff --git a/scripts/test_review_local_harness_parity.py b/scripts/test_check_local_harness.pysimilarity index 95%rename from scripts/test_review_local_harness_parity.pyrename to scripts/test_check_local_harness.pyindex 6bd05e7258..b32bdc95c0 100644--- a/scripts/test_review_local_harness_parity.py+++ b/scripts/test_check_local_harness.py@@ -3,7 +3,7 @@import jsonimport unittest-from review_local_harness_parity import current_probe, MARKER+from check_local_harness import current_probe, MARKERdef request(current_content=None):diff --git a/scripts/test_review_mcp_oauth_config_parity.py b/scripts/test_check_mcp_oauth_config.pysimilarity index 96%rename from scripts/test_review_mcp_oauth_config_parity.pyrename to scripts/test_check_mcp_oauth_config.pyindex 539b108737..996c887748 100644--- a/scripts/test_review_mcp_oauth_config_parity.py+++ b/scripts/test_check_mcp_oauth_config.py@@ -9,7 +9,7 @@ from unittest.mock import patchimport copyimport jsonimport unittest-from review_mcp_oauth_config_parity import BEFORE, AFTER, DEFAULT, MARKER, CELL, extract, validate+from check_mcp_oauth_config import BEFORE, AFTER, DEFAULT, MARKER, CELL, extract, validateclass OAuthConfigGuards(unittest.TestCase):diff --git a/scripts/test_review_minimum_reasoning_parity.py b/scripts/test_check_minimum_reasoning.pysimilarity index 81%rename from scripts/test_review_minimum_reasoning_parity.pyrename to scripts/test_check_minimum_reasoning.pyindex 697ba10e69..815c46fc1e 100644--- a/scripts/test_review_minimum_reasoning_parity.py+++ b/scripts/test_check_minimum_reasoning.py@@ -6,17 +6,12 @@ import tempfileimport unittestfrom unittest.mock import MagicMock, patch-from review_goal_fixture_lifecycle import OwnedProcesses-from review_minimum_reasoning_parity import MARKER, run_case, summarize_branch, wait_for_operation+from lifecycle_lib import OwnedProcesses+from check_minimum_reasoning import MARKER, run_case, summarize_branch, wait_for_operationclass CleanupTests(unittest.TestCase):def exercise(self, root, *, cleanup_failure=False, controls=True, durable=True):- library = root / 'library'- for skill in ('compact', 'refine'):- path = library / 'skills' / skill / 'src' / skill / '__init__.py'- path.parent.mkdir(parents=True)- path.touch()case = root / 'case'events = []server, process, client, scope, thread = (MagicMock() for _ in range(5))@@ -47,14 +42,13 @@ class CleanupTests(unittest.TestCase):else:scope.wait_gone.side_effect = lambda timeout: events.append('owned_processes_exited')observation = {}- with patch.dict('os.environ', {'PI_PACKAGE_DIR': str(library)}), \- patch('review_minimum_reasoning_parity.Server', return_value=server), \- patch('review_minimum_reasoning_parity.threading.Thread', return_value=thread), \- patch('review_minimum_reasoning_parity.invoke', return_value={'exit_code': 0}), \- patch('review_minimum_reasoning_parity.subprocess.Popen', side_effect=spawn), \- patch('review_minimum_reasoning_parity.KernelClient', return_value=client), \- patch('review_minimum_reasoning_parity.OwnedProcesses', return_value=scope):- result = run_case(Path('/fixture/binary'), 'rust', 'compact', case, observation)+ with patch('check_minimum_reasoning.Server', return_value=server), \+ patch('check_minimum_reasoning.threading.Thread', return_value=thread), \+ patch('check_minimum_reasoning.invoke', return_value={'exit_code': 0}), \+ patch('check_minimum_reasoning.subprocess.Popen', side_effect=spawn), \+ patch('check_minimum_reasoning.KernelClient', return_value=client), \+ patch('check_minimum_reasoning.OwnedProcesses', return_value=scope):+ result = run_case(Path('/fixture/binary'), 'compact', case, observation)return result, observation, eventsdef test_daemon_commands_and_owned_exit_precede_directory_removal(self):@@ -78,7 +72,7 @@ class CleanupTests(unittest.TestCase):def test_cleanup_cannot_hide_missing_durable_outcome(self):with tempfile.TemporaryDirectory() as temp, \- patch('review_minimum_reasoning_parity.time.monotonic', side_effect=[0, 91]):+ patch('check_minimum_reasoning.time.monotonic', side_effect=[0, 91]):with self.assertRaisesRegex(AssertionError, 'timed out waiting.*durable compact outcome'):self.exercise(Path(temp), durable=False)@@ -90,7 +84,7 @@ class CleanupTests(unittest.TestCase):event = MagicMock()event.wait.side_effect = lambda _timeout: server.requests.append({'body': {'messages': [{'role': 'tool', 'content': MARKER + '{"scheduled":true}'}]}})- with patch('review_minimum_reasoning_parity.threading.Event', return_value=event):+ with patch('check_minimum_reasoning.threading.Event', return_value=event):self.assertEqual(wait_for_operation(server, 'compact', sessions),({'scheduled': True}, [{'type': 'compaction'}]))event.wait.assert_called_once_with(0.025)@@ -103,7 +97,7 @@ class CleanupTests(unittest.TestCase):event = MagicMock()event.wait.side_effect = lambda _timeout: (sessions / 'session.jsonl').write_text(json.dumps({'type': 'refinement_outcome', 'customType': 'refinement_outcome'}) + '\n')- with patch('review_minimum_reasoning_parity.threading.Event', return_value=event):+ with patch('check_minimum_reasoning.threading.Event', return_value=event):scheduled, outcomes = wait_for_operation(server, 'refine', sessions)self.assertEqual(scheduled, {'scheduled': True})self.assertEqual(len(outcomes), 1)@@ -113,7 +107,7 @@ class CleanupTests(unittest.TestCase):with tempfile.TemporaryDirectory() as temp:server = MagicMock(error=None, requests=[{'body': {'messages': [{'role': 'tool', 'content': MARKER + 'invalid-json'}]}}])- with patch('review_minimum_reasoning_parity.threading.Event') as event:+ with patch('check_minimum_reasoning.threading.Event') as event:with self.assertRaises(json.JSONDecodeError):wait_for_operation(server, 'compact', Path(temp))event.assert_not_called()@@ -127,7 +121,7 @@ class CleanupTests(unittest.TestCase):{'role': 'tool', 'content': MARKER + '{"scheduled":true}'}]}}])event = MagicMock()event.wait.side_effect = lambda _timeout: path.write_text('{"type":"compaction"}\n')- with patch('review_minimum_reasoning_parity.threading.Event', return_value=event):+ with patch('check_minimum_reasoning.threading.Event', return_value=event):self.assertEqual(wait_for_operation(server, 'compact', sessions),({'scheduled': True}, [{'type': 'compaction'}]))event.wait.assert_called_once_with(0.025)@@ -140,7 +134,7 @@ class CleanupTests(unittest.TestCase):{'role': 'tool', 'content': MARKER + '{"scheduled":true}'}]}}])event = MagicMock()with patch('pathlib.Path.read_bytes', side_effect=[FileNotFoundError(), b'{"type":"compaction"}\n']), \- patch('review_minimum_reasoning_parity.threading.Event', return_value=event):+ patch('check_minimum_reasoning.threading.Event', return_value=event):self.assertEqual(wait_for_operation(server, 'compact', sessions),({'scheduled': True}, [{'type': 'compaction'}]))event.wait.assert_called_once_with(0.025)@@ -152,7 +146,7 @@ class CleanupTests(unittest.TestCase):path.write_text('invalid-json\n')server = MagicMock(error=None, requests=[{'body': {'messages': [{'role': 'tool', 'content': MARKER + '{"scheduled":true}'}]}}])- with patch('review_minimum_reasoning_parity.threading.Event') as event:+ with patch('check_minimum_reasoning.threading.Event') as event:with self.assertRaises(json.JSONDecodeError):wait_for_operation(server, 'compact', sessions)with patch('pathlib.Path.read_bytes', side_effect=PermissionError()):@@ -178,9 +172,9 @@ class CleanupTests(unittest.TestCase):def test_proc_exit_race_is_gone_but_permission_errors_still_fail(self):scope = OwnedProcesses(Path('/fixture/binary'), Path('/fixture'), Path('/fixture/d.sock'))scope.targets = {789: 'proc:123'}- with patch('review_goal_fixture_lifecycle.process_identity', side_effect=ProcessLookupError()):+ with patch('lifecycle_lib.process_identity', side_effect=ProcessLookupError()):self.assertEqual(scope.live(), [])- with patch('review_goal_fixture_lifecycle.process_identity', side_effect=PermissionError()):+ with patch('lifecycle_lib.process_identity', side_effect=PermissionError()):with self.assertRaises(PermissionError):scope.live()diff --git a/scripts/test_review_model_facts_parity.py b/scripts/test_check_model_facts.pysimilarity index 59%rename from scripts/test_review_model_facts_parity.pyrename to scripts/test_check_model_facts.pyindex a51481727d..6d4d35c319 100644--- a/scripts/test_review_model_facts_parity.py+++ b/scripts/test_check_model_facts.py@@ -4,7 +4,7 @@ import copyimport jsonimport unittest-from review_model_facts_parity import MARKER, MODELS, SEQUENCE, latest_probe, verify_probe, compare+from check_model_facts import MARKER, MODELS, latest_probe, verify_probedef probe(model, count):@@ -42,28 +42,6 @@ class VerifierTests(unittest.TestCase):with self.assertRaises(AssertionError):verify_probe(probe(MODELS[1], 1), MODELS[1], 2)- def test_backup_wire_cannot_mask_differing_session_facts(self):- ts = [probe(model, i + 1) for i, model in enumerate(SEQUENCE)]- ts[3] = probe(MODELS[0], 4)- rust = copy.deepcopy(ts)- rust[3]['model_info'] = {'provider': 'fixture-backup', 'id': 'facts-text',- 'input': ['text', 'image']}- rust[3]['compact_status']['context_window'] = 256000- with self.assertRaisesRegex(AssertionError, 'model.info differs'):- compare({'runs': {'ts': {'probes': ts}, 'rust': {'probes': rust}}})-- def test_usage_differences_are_retained_and_disclosed(self):- ts = [probe(model, i + 1) for i, model in enumerate(SEQUENCE)]- rust = copy.deepcopy(ts)- rust[1]['compact_status']['tokens'] = 19- result = {'runs': {'ts': {'probes': ts}, 'rust': {'probes': rust}}}- compare(result)- self.assertEqual(result['complete_compact_status_equal'], [True, False, True, True, True])- self.assertEqual(result['runs']['rust']['probes'][1]['compact_status']['tokens'], 19)- rust[1]['compact_status']['context_window'] = 128000- with self.assertRaises(AssertionError):- compare(result)-if __name__ == '__main__':unittest.main()diff --git a/scripts/test_review_observe_selectors_parity.py b/scripts/test_check_observe_selectors.pysimilarity index 94%rename from scripts/test_review_observe_selectors_parity.pyrename to scripts/test_check_observe_selectors.pyindex 970183ff69..82a90f3b99 100644--- a/scripts/test_review_observe_selectors_parity.py+++ b/scripts/test_check_observe_selectors.py@@ -3,7 +3,7 @@ import astimport jsonimport unittest-import review_observe_selectors_parity as fixture+import check_observe_selectors as fixtureclass SelectorReceiptTests(unittest.TestCase):@@ -51,18 +51,17 @@ class SelectorReceiptTests(unittest.TestCase):fixture.selected(row, expected, 'OBSERVE_TASK_A')def test_foreign_error_and_ambiguity_cannot_be_success_or_other_error(self):- for label, error in (('ts', 'Unknown active session: FFF-123'),- ('rust', 'agent suffix is not reachable')):- row = {'get': {'error': error}, 'recent': {'error': error}}- self.assertEqual(fixture.rejected(row, 'foreign-family', label), {'rejection': 'foreign-family'})- row['get'] = {'value': {'agent': {'activeSessionId': 'foreign'}}}- with self.assertRaises(AssertionError):- fixture.rejected(row, 'foreign-family', label)+ error = 'agent suffix is not reachable'+ row = {'get': {'error': error}, 'recent': {'error': error}}+ self.assertEqual(fixture.rejected(row, 'foreign-family'), {'rejection': 'foreign-family'})+ row['get'] = {'value': {'agent': {'activeSessionId': 'foreign'}}}+ with self.assertRaises(AssertionError):+ fixture.rejected(row, 'foreign-family')row = {'get': {'error': 'No live session'}, 'recent': {'error': 'No live session'}}with self.assertRaises(AssertionError):- fixture.rejected(row, 'ambiguous', 'rust')+ fixture.rejected(row, 'ambiguous')row = {operation: {'error': 'Ambiguous active session: matches a,b'} for operation in ('get', 'recent')}- self.assertEqual(fixture.rejected(row, 'ambiguous', 'ts'), {'rejection': 'ambiguous'})+ self.assertEqual(fixture.rejected(row, 'ambiguous'), {'rejection': 'ambiguous'})def test_child_hold_matches_current_task_not_root_digest_or_history(self):self.assertEqual(fixture.child_task({'messages': [{'role': 'user', 'content': '[task from parent]\n\nOBSERVE_TASK_A'}]}), 'OBSERVE_TASK_A')diff --git a/scripts/test_review_print_bash_parity.py b/scripts/test_check_print_bash.pysimilarity index 68%rename from scripts/test_review_print_bash_parity.pyrename to scripts/test_check_print_bash.pyindex a650ca6223..99a5abbc60 100644--- a/scripts/test_review_print_bash_parity.py+++ b/scripts/test_check_print_bash.py@@ -1,7 +1,7 @@#!/usr/bin/env python3import copyimport unittest-from review_print_bash_parity import validate, validate_ts+from check_print_bash import validateclass PrintBashGuards(unittest.TestCase):@@ -22,14 +22,6 @@ class PrintBashGuards(unittest.TestCase):with self.assertRaises(AssertionError):validate(changed)- def test_ts_print_exits_after_its_first_turn_without_a_notice(self):- exited = {'first_turn_ended_before_release': True, 'request_count': 2, 'notice_count': 0,- 'gate_timed_out': False}- validate_ts(exited)- for key, value in [('request_count', 4), ('notice_count', 1), ('gate_timed_out', True)]:- with self.assertRaises(AssertionError):- validate_ts({**exited, key: value})-if __name__ == '__main__':unittest.main()diff --git a/scripts/test_review_private_default_frames_parity.py b/scripts/test_check_private_default_frames.pysimilarity index 80%rename from scripts/test_review_private_default_frames_parity.pyrename to scripts/test_check_private_default_frames.pyindex 4b6f182475..58310f17e9 100644--- a/scripts/test_review_private_default_frames_parity.py+++ b/scripts/test_check_private_default_frames.py@@ -4,14 +4,11 @@ from pathlib import Pathimport unittestfrom unittest.mock import Mock-from review_private_default_frames_parity import (- PUBLIC, PRIVATE, WARNING, Screen, connection_model, wait_for_created_session,- validate_observation, write_frame,-)+from check_private_default_frames import PUBLIC, PRIVATE, WARNING, Screen, connection_model, wait_for_created_session, validate_observation, write_frame-def observation(label, scenario):- warn = label == 'rust' and scenario == 'unavailable'+def observation(scenario):+ warn = scenario == 'unavailable'return {'selected_model': PUBLIC,'available_ids': [PUBLIC] if scenario == 'unavailable' else [PUBLIC, PRIVATE],'fallback_message': WARNING + ' Using prime-inference/' + PUBLIC if warn else None,@@ -58,41 +55,40 @@ class CaptureGuards(unittest.TestCase):connection_model({'state': {'model': model}}))def test_characterization_does_not_approve_either_priority_policy(self):- for label in ('ts', 'rust'):- for selected in (PUBLIC, PRIVATE):- value = observation(label, 'authorized')- value['selected_model'] = selected- validate_observation(label, 'authorized', value)+ for selected in (PUBLIC, PRIVATE):+ value = observation('authorized')+ value['selected_model'] = selected+ validate_observation('authorized', value)def test_unavailable_or_excluded_private_model_is_rejected(self):for scenario in ('unavailable', 'excluded'):- value = observation('rust', scenario)+ value = observation(scenario)value['selected_model'] = PRIVATEwith self.assertRaisesRegex(AssertionError, 'unavailable or excluded'):- validate_observation('rust', scenario, value)+ validate_observation(scenario, value)def test_mismatched_authorization_state_is_rejected(self):for scenario in ('authorized', 'unavailable'):- value = observation('rust', scenario)+ value = observation(scenario)value['available_ids'] = [PUBLIC] if scenario == 'authorized' else [PUBLIC, PRIVATE]with self.assertRaisesRegex(AssertionError, 'authorization fixture'):- validate_observation('rust', scenario, value)+ validate_observation(scenario, value)def test_missing_duplicate_warning_or_lost_input_is_rejected(self):for field, replacement in (('warning_prefix_count', 0), ('warning_prefix_count', 2),('input_preserved', False), ('selected_model_id_visible', False),('columns', 119), ('warning_text_complete', False)):- value = observation('rust', 'unavailable')+ value = observation('unavailable')value['frames']['120x40'][field] = replacementwith self.assertRaises(AssertionError):- validate_observation('rust', 'unavailable', value)+ validate_observation('unavailable', value)- def test_unexpected_warning_in_ts_or_excluded_case_is_rejected(self):- for label, scenario in (('ts', 'unavailable'), ('rust', 'excluded')):- value = observation(label, scenario)+ def test_unexpected_warning_outside_unavailable_case_is_rejected(self):+ for scenario in ('authorized', 'excluded'):+ value = observation(scenario)value['fallback_message'] = WARNINGwith self.assertRaisesRegex(AssertionError, 'unexpected warning'):- validate_observation(label, scenario, value)+ validate_observation(scenario, value)def test_svg_escapes_real_cells_and_retains_matched_dimensions(self):screen = Screen(120, 40)diff --git a/scripts/test_review_queue_browse_parity.py b/scripts/test_check_queue_browse.pysimilarity index 75%rename from scripts/test_review_queue_browse_parity.pyrename to scripts/test_check_queue_browse.pyindex 3a408f4020..5e5306dfed 100644--- a/scripts/test_review_queue_browse_parity.py+++ b/scripts/test_check_queue_browse.py@@ -1,5 +1,5 @@import unittest-from review_queue_browse_parity import check_mutation, QueueSupervisor, USER_A, USER_B, INTERNAL+from check_queue_browse import check_mutation, QueueSupervisor, USER_A, USER_B, INTERNALclass QueueBrowseGuardTest(unittest.TestCase):@@ -7,20 +7,17 @@ class QueueBrowseGuardTest(unittest.TestCase):return {'type': 'mutate_queued_message', 'activeSessionId': 's1', 'lane': 'steering','index': 0, 'expectedText': USER_A, 'mutation': {'type': 'move', 'direction': direction}}- def test_compares_actual_mutation_target_with_explicit_ts_delta(self):- check_mutation('ts', {**self.command(1), 'id': 'actual-transport-request'})- check_mutation('rust', self.command(2))+ def test_mutation_swaps_with_the_adjacent_user_row(self):+ check_mutation(self.command(2))with self.assertRaises(AssertionError):- check_mutation('rust', self.command(1))- with self.assertRaises(AssertionError):- check_mutation('ts', self.command(2))+ check_mutation(self.command(1))def test_rejects_wrong_source_lane_text_or_index(self):for field, value in [('lane', 'followUp'), ('index', 1), ('expectedText', 'wrong')]:command = self.command(2)command[field] = valuewith self.assertRaises(AssertionError):- check_mutation('rust', command)+ check_mutation(command)def test_subclass_handles_its_commands_without_transient_transport_errors(self):diff --git a/scripts/test_check_queue_priority.py b/scripts/test_check_queue_priority.pynew file mode 100644index 0000000000..f2d8d59d7b--- /dev/null+++ b/scripts/test_check_queue_priority.py@@ -0,0 +1,22 @@+import unittest+from check_queue_priority import check_order, EARLIER, EDITED, AGENT+++class QueuePriorityGuardTest(unittest.TestCase):+ def test_edited_item_keeps_priority_over_the_later_agent_message(self):+ check_order({'steering': [EARLIER, EDITED, AGENT], 'followUp': []}, AGENT)+ with self.assertRaises(AssertionError):+ check_order({'steering': [EARLIER, AGENT, EDITED], 'followUp': []}, AGENT)++ def test_does_not_ignore_missing_duplicate_or_wrong_lane_items(self):+ for queue in [+ {'steering': [EDITED, AGENT], 'followUp': []},+ {'steering': [EARLIER, EDITED, AGENT, AGENT], 'followUp': []},+ {'steering': [EARLIER, EDITED, AGENT], 'followUp': [EDITED]},+ ]:+ with self.assertRaises(AssertionError):+ check_order(queue, AGENT)+++if __name__ == '__main__':+ unittest.main()diff --git a/scripts/test_review_reconnect_version_parity.py b/scripts/test_check_reconnect_version.pysimilarity index 98%rename from scripts/test_review_reconnect_version_parity.pyrename to scripts/test_check_reconnect_version.pyindex 2e6c6609ab..76afe550cf 100644--- a/scripts/test_review_reconnect_version_parity.py+++ b/scripts/test_check_reconnect_version.py@@ -7,7 +7,7 @@ import threadingimport tempfileimport unittest-from review_reconnect_version_parity import RestartSupervisor+from check_reconnect_version import RestartSupervisorclass Connection:diff --git a/scripts/test_check_restore_notice.py b/scripts/test_check_restore_notice.pynew file mode 100644index 0000000000..52458d395b--- /dev/null+++ b/scripts/test_check_restore_notice.py@@ -0,0 +1,30 @@+#!/usr/bin/env python3+"""Guard scope separation between initial headless availability and restored state."""+import copy+import unittest++from check_restore_notice import SKILL_PROBE, skill_availability+++HIDDEN = {'preimports': {'agent_message': True, 'agent_observe': False, 'rlm_heartbeat': False},+ 'model_visible': {'agent-message': True, 'agent-observe': False, 'rlm-heartbeat': False}}+++class AvailabilityTests(unittest.TestCase):+ def test_observation_uses_actual_tool_result_and_inventory(self):+ requests = [+ {'messages': [{'role': 'system', 'content': '<available_skills><skill><name>agent-message</name></skill></available_skills>'}]},+ {'messages': [{'role': 'tool', 'content': SKILL_PROBE + '{"agent_message":true,"agent_observe":false,"rlm_heartbeat":false}'}]}]+ self.assertEqual(skill_availability(requests), HIDDEN)+ broken = copy.deepcopy(requests)+ broken[0]['messages'][0]['content'] = 'agent-message'+ with self.assertRaises(AssertionError):+ skill_availability(broken)+ broken = copy.deepcopy(requests)+ broken[1]['messages'][0]['role'] = 'assistant'+ with self.assertRaises(AssertionError):+ skill_availability(broken)+++if __name__ == '__main__':+ unittest.main()diff --git a/scripts/test_review_saved_catalog_parity.py b/scripts/test_check_saved_catalog.pysimilarity index 88%rename from scripts/test_review_saved_catalog_parity.pyrename to scripts/test_check_saved_catalog.pyindex 9d8a732c50..906fc7f6ee 100644--- a/scripts/test_review_saved_catalog_parity.py+++ b/scripts/test_check_saved_catalog.py@@ -4,8 +4,7 @@ from pathlib import Pathimport tempfileimport unittest-from review_saved_catalog_parity import (COUNT, PAGE, TARGET, normalize,- same_rows, seed, ts_ignores_paging, validate_query)+from check_saved_catalog import COUNT, PAGE, TARGET, normalize, seed, validate_queryclass SavedCatalogGuards(unittest.TestCase):@@ -137,21 +136,6 @@ class SavedCatalogGuards(unittest.TestCase):self.refresh_raw(call)self.check(call)- def test_ts_baseline_order_is_not_misrepresented_as_paging_parity(self):- call = self.call(list(reversed(self.expected)))- del call['final_data']['remaining']- self.refresh_raw(call)- rows = validate_query(call, self.root, self.expected)- same_rows(rows, self.expected)- ts_ignores_paging(call)- for extra in ({'remaining': 0}, {'nextCursor': 'new-ts-cursor'}):- broken = copy.deepcopy(call)- broken['final_data'].update(extra)- with self.assertRaises(AssertionError):- ts_ignores_paging(broken)- with self.assertRaises(AssertionError):- validate_query(self.call(self.expected[:PAGE]), self.root, self.expected)-if __name__ == '__main__':unittest.main()diff --git a/scripts/test_review_shutdown_scope_parity.py b/scripts/test_check_shutdown_scope.pysimilarity index 98%rename from scripts/test_review_shutdown_scope_parity.pyrename to scripts/test_check_shutdown_scope.pyindex dce3b993ca..b6c1a5265f 100644--- a/scripts/test_review_shutdown_scope_parity.py+++ b/scripts/test_check_shutdown_scope.py@@ -5,7 +5,7 @@ from pathlib import Pathimport tempfileimport unittestfrom unittest.mock import Mock, patch-import review_shutdown_scope_parity as verifier+import check_shutdown_scope as verifierclass OwnershipTests(unittest.TestCase):diff --git a/scripts/test_review_socket_pin_parity.py b/scripts/test_check_socket_pin.pysimilarity index 85%rename from scripts/test_review_socket_pin_parity.pyrename to scripts/test_check_socket_pin.pyindex 8c0c2f7bf2..a26ad39c25 100644--- a/scripts/test_review_socket_pin_parity.py+++ b/scripts/test_check_socket_pin.py@@ -3,8 +3,8 @@ import subprocessimport tempfileimport unittestfrom pathlib import Path-from review_socket_pin_parity import install_launcher-from review_draft_disconnect_parity import env_for+from check_socket_pin import install_launcher+from lifecycle_lib import env_forclass LauncherExtractionTests(unittest.TestCase):@@ -14,7 +14,7 @@ class LauncherExtractionTests(unittest.TestCase):fixture = root / 'payload'fixture.write_text('#!/bin/sh\nprintf "%s\n" "fixture-payload"\n')fixture.chmod(0o755)- env = env_for(root, 'rust')+ env = env_for(root)launcher = install_launcher(fixture, root, env)result = subprocess.run([str(launcher), '--version'], env=env,capture_output=True, text=True, timeout=10, check=True)diff --git a/scripts/test_review_goal_backoff_parity.py b/scripts/test_lifecycle_lib.pysimilarity index 72%rename from scripts/test_review_goal_backoff_parity.pyrename to scripts/test_lifecycle_lib.pyindex 2281a182f0..883ea90677 100644--- a/scripts/test_review_goal_backoff_parity.py+++ b/scripts/test_lifecycle_lib.py@@ -1,13 +1,10 @@"""Mocked ownership/cleanup guards; no product binaries or kernels are started."""-import jsonfrom pathlib import Pathimport signal-import tempfileimport unittestfrom unittest.mock import Mock, patch-import review_goal_backoff_parity as goal-import review_goal_fixture_lifecycle as lifecycle+import lifecycle_lib as lifecycleclass CleanupTests(unittest.TestCase):@@ -83,31 +80,6 @@ class CleanupTests(unittest.TestCase):('PA_GOAL_FIXTURE_ID=/fixture\0PRIME_AGENT_KERNEL_OWNER_PID=%s\0' % owner).encode(), b'/usr/bin/python3\0kernel\0']):self.assertEqual(scope.ownership(20, 'proc:8'), expected)- def test_receipt_survives_directory_cleanup_failure_and_primary_error(self):- with tempfile.TemporaryDirectory() as temp:- receipt = Path(temp) / 'receipt.json'- fake_dir = Mock(name='temporary directory')- fake_dir.name = temp- fake_dir.cleanup.side_effect = OSError('Directory not empty')- def run(_binary, _label, _scenario, _base_dir, observation):- observation['primary_error'] = 'original probe failure'- raise AssertionError('original probe failure')- with patch.object(goal.sys, 'argv', ['fixture', '--receipt', str(receipt)]), \- patch.object(goal.sys, 'platform', 'linux'), \- patch.dict(goal.os.environ, {'PA_TS_BINARY': '/fake/ts', 'PA_RUST_BINARY': '/fake/rust', 'PA_TS_ARCHIVE': '/fake/archive'}), \- patch.object(Path, 'is_file', return_value=True), \- patch.object(goal.os, 'access', return_value=True), \- patch.object(goal, 'sha256', return_value=goal.TS_ARCHIVE_SHA256), \- patch.object(goal.tempfile, 'TemporaryDirectory', return_value=fake_dir), \- patch.object(goal, 'run_case', side_effect=run):- self.assertEqual(goal.main(), 1)- result = json.loads(receipt.read_text())- self.assertIn('original probe failure', result['fixture_error'])- self.assertEqual(result['directory_cleanup_error'], 'Directory not empty')- self.assertFalse(result['validation_complete'])- self.assertFalse(result['parity'])- fake_dir.cleanup.assert_called_once()-if __name__ == '__main__':unittest.main()diff --git a/scripts/test_review_draft_disconnect_parity.py b/scripts/test_review_draft_disconnect_parity.pydeleted file mode 100644index bcb450d995..0000000000--- a/scripts/test_review_draft_disconnect_parity.py+++ /dev/null@@ -1,126 +0,0 @@-#!/usr/bin/env python3-"""Decision-only regression tests; these never launch either product binary."""-import copy-import unittest--from review_draft_disconnect_parity import classify_validation---def completed_observations():- accepted = ["sentinel", "probe"]- scenarios = {}- for name in ("queued_close", "refusal", "rebind_close"):- scenarios[name] = {"executed": True, "invariant_passed": True,- "fixture_errors": [], "prompts": accepted[:],- "accepted_logical_messages": accepted[:],- "wire_prompt_messages": accepted[:]}- scenarios["refusal"]["prompts"] = ["sentinel", "sentinel", "probe"]- scenarios["refusal"]["wire_prompt_messages"] = ["sentinel", "sentinel", "probe"]- rust = {"scenarios": scenarios}- ts = copy.deepcopy(rust)- ts["scenarios"]["queued_close"]["wire_prompt_messages"] = ["sentinel", "sentinel", "probe"]- ts["scenarios"]["rebind_close"] = {- "executed": False, "invariant_passed": False, "fixture_errors": [],- "error": "TimeoutError: reconnected attach and visible reconnect result",- "prompts": ["sentinel"], "accepted_logical_messages": ["sentinel"],- "wire_prompt_messages": ["sentinel"]}- return {"results": {"ts": ts, "rust": rust}}---class ValidationDecisionTests(unittest.TestCase):- def test_complete_shared_contracts_and_rust_extension_validate_without_full_parity(self):- receipt = completed_observations()- before = copy.deepcopy(receipt["results"])- self.assertTrue(classify_validation(receipt))- self.assertTrue(receipt["shared_contract_parity"])- self.assertFalse(receipt["parity"])- self.assertEqual(receipt["comparisons"]["rebind_close"]["status"], "not_comparable")- self.assertFalse(receipt["comparisons"]["queued_close"]["same_wire_prompt_observations"])- self.assertEqual(receipt["results"], before)-- def test_incomplete_shared_execution_fails_on_either_side(self):- for kind in ("ts", "rust"):- for name in ("queued_close", "refusal"):- with self.subTest(kind=kind, name=name):- receipt = completed_observations()- receipt["results"][kind]["scenarios"][name]["executed"] = False- self.assertFalse(classify_validation(receipt))-- def test_changed_logical_acceptance_fails(self):- receipt = completed_observations()- receipt["results"]["ts"]["scenarios"]["queued_close"]["accepted_logical_messages"].append("sentinel")- self.assertFalse(classify_validation(receipt))-- def test_shared_invariant_or_prompt_difference_fails(self):- for kind in ("ts", "rust"):- for name in ("queued_close", "refusal"):- for field, value in (("invariant_passed", False), ("prompts", ["different"])):- with self.subTest(kind=kind, name=name, field=field):- receipt = completed_observations()- receipt["results"][kind]["scenarios"][name][field] = value- self.assertFalse(classify_validation(receipt))-- def test_missing_observations_fail_even_when_both_sides_omit_them(self):- for name in ("queued_close", "refusal", "rebind_close"):- for field in ("prompts", "accepted_logical_messages", "wire_prompt_messages"):- with self.subTest(name=name, field=field):- receipt = completed_observations()- for kind in ("ts", "rust"):- del receipt["results"][kind]["scenarios"][name][field]- self.assertFalse(classify_validation(receipt))-- def test_unsupported_case_requires_the_exact_recorded_failure(self):- for field, value in (("error", None), ("executed", True), ("invariant_passed", True)):- with self.subTest(field=field):- receipt = completed_observations()- receipt["results"]["ts"]["scenarios"]["rebind_close"][field] = value- self.assertFalse(classify_validation(receipt))-- def test_rust_rebind_must_execute_and_pass(self):- for field in ("executed", "invariant_passed"):- with self.subTest(field=field):- receipt = completed_observations()- receipt["results"]["rust"]["scenarios"]["rebind_close"][field] = False- self.assertFalse(classify_validation(receipt))-- def test_unexpected_scenario_errors_fail_even_if_other_flags_are_green(self):- for kind in ("ts", "rust"):- for name in ("queued_close", "refusal", "rebind_close"):- with self.subTest(kind=kind, name=name):- receipt = completed_observations()- receipt["results"][kind]["scenarios"][name]["error"] = "unexpected protocol failure"- self.assertFalse(classify_validation(receipt))-- def test_fixture_and_cleanup_errors_fail_on_every_scenario(self):- for kind in ("ts", "rust"):- for name in ("queued_close", "refusal", "rebind_close"):- for field in ("fixture_errors", "cleanup_errors"):- with self.subTest(kind=kind, name=name, field=field):- receipt = completed_observations()- receipt["results"][kind]["scenarios"][name][field] = ["failed"]- self.assertFalse(classify_validation(receipt))-- def test_missing_results_fail(self):- for kind in ("ts", "rust"):- for name in ("queued_close", "refusal", "rebind_close"):- with self.subTest(kind=kind, name=name):- receipt = completed_observations()- del receipt["results"][kind]["scenarios"][name]- self.assertFalse(classify_validation(receipt))- receipt = completed_observations()- del receipt["results"][kind]- self.assertFalse(classify_validation(receipt))- self.assertFalse(classify_validation({}))-- def test_preflight_or_binary_setup_errors_fail(self):- receipt = completed_observations()- receipt["preflight_error"] = "archive checksum mismatch"- self.assertFalse(classify_validation(receipt))- for kind in ("ts", "rust"):- receipt = completed_observations()- receipt["results"][kind]["error"] = "could not launch binary"- self.assertFalse(classify_validation(receipt))---if __name__ == "__main__":- unittest.main()diff --git a/scripts/test_review_markdown_frames_parity.py b/scripts/test_review_markdown_frames_parity.pydeleted file mode 100644index abdf8b26e6..0000000000--- a/scripts/test_review_markdown_frames_parity.py+++ /dev/null@@ -1,65 +0,0 @@-#!/usr/bin/env python3-"""Lightweight capture parser checks; never execute product binaries."""-import unittest-from review_markdown_frames_parity import StyledScreen, START, END, CORPUS---class CaptureTests(unittest.TestCase):- def test_captured_keyboard_controls_are_not_sgr(self):- screen = StyledScreen(40)- screen.feed(b'\x1b[1mA\x1b[>4;0mB')- replies = screen.feed(b'\x1b[?uC')- self.assertEqual(replies, [])- self.assertEqual(screen.keyboard_controls, ['\x1b[>4;0m', '\x1b[?u'])- self.assertEqual(screen.styles[0][:3], [(None, None, (1,), None)] * 3)- self.assertEqual(screen.style_errors, [])-- def test_partial_keyboard_query_and_config_wait_for_terminator(self):- screen = StyledScreen(40)- self.assertEqual(screen.feed(b'\x1b[>4;'), [])- self.assertEqual(screen.keyboard_controls, [])- screen.feed(b'0m\x1b[?')- self.assertEqual(screen.keyboard_controls, ['\x1b[>4;0m'])- self.assertEqual(screen.feed(b'u\x1b[c'), [b'\x1b[?1;2c'])- self.assertEqual(screen.style_errors, [])-- def test_unknown_private_styles_and_geometry_still_fail(self):- screen = StyledScreen(40)- screen.feed(b'\x1b[>31m\x1b[3S')- self.assertEqual(len(screen.style_errors), 2)- self.assertEqual(screen.fg, None)- self.assertEqual(screen.mods, set())-- def test_fragmented_sgr_and_osc8_keep_cell_attributes(self):- screen = StyledScreen(40)- chunks = [b'\x1b[38;2;1;', b'2;3m\x1b[1mA\x1b[22mB',- b'\x1b]8;;https://example.com\x1b\\C\x1b]8;;\x1b\\', b'D']- for chunk in chunks:- screen.feed(chunk)- self.assertEqual(screen.cells[0][:4], list('ABCD'))- self.assertEqual(screen.styles[0][:4], [- (('rgb', 1, 2, 3), None, (1,), None),- (('rgb', 1, 2, 3), None, (), None),- (('rgb', 1, 2, 3), None, (), 'https://example.com'),- (('rgb', 1, 2, 3), None, (), None)])- self.assertEqual(screen.style_errors, [])-- def test_repaint_clears_stale_text_and_style(self):- screen = StyledScreen(40)- screen.feed(b'\x1b[1mABCDE\r\x1b[0mXY\x1b[K')- self.assertEqual(screen.cells[0][:5], list('XY '))- self.assertEqual(screen.styles[0][2:5], [None] * 3)-- def test_sentinel_crop_preserves_indentation_and_nonblank_styles(self):- screen = StyledScreen(40)- screen.feed(f' {START}\r\n '.encode() + b'\x1b[3mtext\x1b[0m\r\n' + f' {END}'.encode())- self.assertEqual(screen.region(), [[(' ', None), (' ', None)] +- [(char, (None, None, (3,), None)) for char in 'text']])-- def test_title_corpus_has_single_backslash_escapes(self):- self.assertIn(r'\"b\"', CORPUS['escaped_titles'])- self.assertNotIn(r'\\"', CORPUS['escaped_titles'])---if __name__ == '__main__':- unittest.main()diff --git a/scripts/test_review_queue_priority_parity.py b/scripts/test_review_queue_priority_parity.pydeleted file mode 100644index 3eabdc5f00..0000000000--- a/scripts/test_review_queue_priority_parity.py+++ /dev/null@@ -1,27 +0,0 @@-import unittest-from review_queue_priority_parity import check_order, EARLIER, EDITED, AGENT---class QueuePriorityGuardTest(unittest.TestCase):- def test_records_the_intended_delta_instead_of_accepting_both_orders(self):- ts = {'steering': [EARLIER, AGENT, EDITED], 'followUp': []}- rust = {'steering': [EARLIER, EDITED, AGENT], 'followUp': []}- check_order('ts', ts, AGENT)- check_order('rust', rust, AGENT)- with self.assertRaises(AssertionError):- check_order('rust', ts, AGENT)- with self.assertRaises(AssertionError):- check_order('ts', rust, AGENT)-- def test_does_not_ignore_missing_duplicate_or_wrong_lane_items(self):- for queue in [- {'steering': [EDITED, AGENT], 'followUp': []},- {'steering': [EARLIER, EDITED, AGENT, AGENT], 'followUp': []},- {'steering': [EARLIER, EDITED, AGENT], 'followUp': [EDITED]},- ]:- with self.assertRaises(AssertionError):- check_order('rust', queue, AGENT)---if __name__ == '__main__':- unittest.main()diff --git a/scripts/test_review_restore_notice_parity.py b/scripts/test_review_restore_notice_parity.pydeleted file mode 100644index c097d08dd7..0000000000--- a/scripts/test_review_restore_notice_parity.py+++ /dev/null@@ -1,47 +0,0 @@-#!/usr/bin/env python3-"""Guard scope separation between initial headless availability and restored state."""-import copy-import unittest--from review_restore_notice_parity import SKILL_PROBE, skill_availability, validate_skill_availability---def run(available):- return {'skill_availability': {- 'preimports': {'agent_message': True, 'agent_observe': available,- 'rlm_heartbeat': available},- 'model_visible': {'agent-message': True, 'agent-observe': available,- 'rlm-heartbeat': available}}}---class AvailabilityTests(unittest.TestCase):- def test_declared_initial_difference_is_exact(self):- validate_skill_availability({'ts': run(True), 'rust': run(False)})-- def test_unexpected_inventory_or_preimport_changes_fail(self):- for label in ['ts', 'rust']:- for kind in ['preimports', 'model_visible']:- for name in run(True)['skill_availability'][kind]:- rows = {'ts': run(True), 'rust': run(False)}- actual = rows[label]['skill_availability'][kind]- actual[name] = not actual[name]- with self.assertRaises(AssertionError):- validate_skill_availability(rows)-- def test_observation_uses_actual_tool_result_and_inventory(self):- requests = [- {'messages': [{'role': 'system', 'content': '<available_skills><skill><name>agent-message</name></skill></available_skills>'}]},- {'messages': [{'role': 'tool', 'content': SKILL_PROBE + '{"agent_message":true,"agent_observe":false,"rlm_heartbeat":false}'}]}]- self.assertEqual(skill_availability(requests), run(False)['skill_availability'])- broken = copy.deepcopy(requests)- broken[0]['messages'][0]['content'] = 'agent-message'- with self.assertRaises(AssertionError):- skill_availability(broken)- broken = copy.deepcopy(requests)- broken[1]['messages'][0]['role'] = 'assistant'- with self.assertRaises(AssertionError):- skill_availability(broken)---if __name__ == '__main__':- unittest.main()