Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix: list a directory's children as soon as an @ token ends in /, rank @ completions by match, visibility and length (#3604)

Sebastian Müller03be543173f5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 40f4a51230..bd0ff662c0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -376,6 +376,20 @@ jobs:
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
diff --git a/crates/pa-tui/src/autocomplete.rs b/crates/pa-tui/src/autocomplete.rs
index 9bcce45acb..4dcd4db1d1 100644
--- a/crates/pa-tui/src/autocomplete.rs
+++ b/crates/pa-tui/src/autocomplete.rs
@@ -249,7 +249,7 @@ fn home_dir() -> std::path::PathBuf {
/// The `@`-attachment token at the cursor: the token feeds the fuzzy
/// file search below the session cwd (or the typed scope).
-fn extract_at_prefix(text: &[char]) -> Option<String> {
+pub(crate) fn extract_at_prefix(text: &[char]) -> Option<String> {
if let Some(quoted) = extract_quoted_prefix(text) {
if quoted.starts_with("@\"") {
return Some(quoted);
diff --git a/crates/pa-tui/src/autocomplete/fuzzy_file_search.rs b/crates/pa-tui/src/autocomplete/fuzzy_file_search.rs
index ec2eb54674..e366615ad1 100644
--- a/crates/pa-tui/src/autocomplete/fuzzy_file_search.rs
+++ b/crates/pa-tui/src/autocomplete/fuzzy_file_search.rs
@@ -143,16 +143,36 @@ impl AtSearch<'_> {
}
}
- /// The one scoring of a matched form, shared by the walk and the index scan: `None`
- /// for a zero score; an empty query scores every form 1.
+ /// The one ranking key of a matched form, shared by the walk and the index scan, all
+ /// case-insensitive against the once-lowercased query: `None` when neither the name
+ /// nor the path contains the query; an empty query is a name prefix of every form.
+ /// The form is relative to the typed scope, so the scope's own dot directory
+ /// (`@.github/`) hides nothing.
pub(super) fn score<'form>(&self, form: &'form str) -> Option<RankedForm<'form>> {
- let score = if self.lower_query.is_empty() {
- 1
+ let name = form_name(form);
+ let class = if eq_ignore_case(name, self.lower_query) {
+ MatchClass::ExactName
+ } else if starts_with_ignore_case(name, self.lower_query) {
+ MatchClass::NamePrefix
+ } else if contains_ignore_case(name, self.lower_query) {
+ MatchClass::NameSubstring
+ } else if contains_ignore_case(form, self.lower_query) {
+ MatchClass::PathSubstring
} else {
- score_entry(form, self.lower_query, form.ends_with('/'))
+ return None;
};
- (score > 0).then(|| RankedForm {
- score,
+ let dotted_query = self
+ .lower_query
+ .rsplit('/')
+ .next()
+ .is_some_and(|segment| segment.starts_with('.'));
+ let hidden = !dotted_query
+ && form_trimmed(form)
+ .split('/')
+ .any(|segment| segment.starts_with('.'));
+ Some(RankedForm {
+ class,
+ hidden,
depth: form_depth(form),
form,
})
@@ -308,20 +328,37 @@ fn index_scope(display_base: &str) -> IndexScope {
IndexScope::Prefix(normalized.to_string())
}
-/// A scored candidate form, ordered by score (descending), then depth, then path.
+/// How a form contains the typed query, best first.
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+enum MatchClass {
+ ExactName,
+ NamePrefix,
+ NameSubstring,
+ PathSubstring,
+}
+
+/// A matched candidate form with its ranking key (see [`RankedForm::cmp`]).
pub(super) struct RankedForm<'a> {
- score: i32,
+ class: MatchClass,
+ hidden: bool,
depth: usize,
form: &'a str,
}
impl RankedForm<'_> {
+ /// The `@` ranking, a total order (best first): the match class (exact name, name
+ /// prefix, name substring, path substring); visible before hidden (a segment starts
+ /// with `.`; nothing is hidden for a query whose last segment starts with `.`);
+ /// fewer segments; fewer chars; directories before files; byte order.
fn cmp(&self, other: &Self) -> Ordering {
- other
- .score
- .cmp(&self.score)
- .then_with(|| self.depth.cmp(&other.depth))
- .then_with(|| form_trimmed(self.form).cmp(form_trimmed(other.form)))
+ let (this, that) = (form_trimmed(self.form), form_trimmed(other.form));
+ self.class
+ .cmp(&other.class)
+ .then(self.hidden.cmp(&other.hidden))
+ .then(self.depth.cmp(&other.depth))
+ .then_with(|| this.chars().count().cmp(&that.chars().count()))
+ .then_with(|| other.form.ends_with('/').cmp(&self.form.ends_with('/')))
+ .then_with(|| this.cmp(that))
}
}
@@ -434,28 +471,6 @@ fn contains_ignore_case(haystack: &str, lower_needle: &str) -> bool {
}
}
-/// Exact name 100, name prefix 80, name contains 50, path contains 30,
-/// +10 for directories (when positive), all case-insensitive against the
-/// once-lowercased query.
-fn score_entry(form: &str, lower_query: &str, is_directory: bool) -> i32 {
- let file_name = form_name(form);
- let mut score = if eq_ignore_case(file_name, lower_query) {
- 100
- } else if starts_with_ignore_case(file_name, lower_query) {
- 80
- } else if contains_ignore_case(file_name, lower_query) {
- 50
- } else if contains_ignore_case(form, lower_query) {
- 30
- } else {
- 0
- };
- if is_directory && score > 0 {
- score += 10;
- }
- score
-}
-
/// The raw query when it holds no `/`; otherwise the segments
/// regex-escaped and joined with `[\\/]`, a trailing separator included.
fn build_fd_path_query(query: &str) -> String {
diff --git a/crates/pa-tui/src/autocomplete/tests.rs b/crates/pa-tui/src/autocomplete/tests.rs
index 7158847173..5cabb59eda 100644
--- a/crates/pa-tui/src/autocomplete/tests.rs
+++ b/crates/pa-tui/src/autocomplete/tests.rs
@@ -269,8 +269,8 @@ fn at_prefix_lists_nested_fuzzy_matches() {
other => panic!("expected a searching lookup, got {other:?}"),
}
};
- // The exact `.hidden/partial` name (score 100) sorts ahead of
- // the `partial_match.rs` prefix match (80); `.git` never lists.
+ // The exact `.hidden/partial` name sorts ahead of the
+ // `partial_match.rs` prefix match; `.git` never lists.
assert_eq!(
values("see @partial"),
["@.hidden/partial", "@src/deep/partial_match.rs"]
@@ -614,6 +614,84 @@ fn at_values(provider: &CombinedAutocompleteProvider, text: &str) -> Vec<Complet
}
}
+/// The `@` item values of one provider query.
+fn at_item_values(provider: &CombinedAutocompleteProvider, text: &str) -> Vec<String> {
+ at_values(provider, text)
+ .into_iter()
+ .map(|item| item.value)
+ .collect()
+}
+
+/// A typed directory scope with an empty query lists the directory's children.
+#[test]
+fn at_directory_scope_lists_its_children() {
+ let base = tempfile::TempDir::new().expect("temp dir");
+ std::fs::create_dir_all(base.path().join("prime-agent/src")).expect("mkdir");
+ for file in [
+ "prime-agent/src/lib.rs",
+ "prime-agent/README.md",
+ "prime-agent/Cargo.toml",
+ "prime-agent/.env",
+ "other.md",
+ ] {
+ std::fs::write(base.path().join(file), "x").expect("write");
+ }
+ let provider = provider(base.path().to_str().expect("utf8"));
+ assert_eq!(
+ at_item_values(&provider, "@prime-agent/"),
+ [
+ "@prime-agent/src/",
+ "@prime-agent/README.md",
+ "@prime-agent/Cargo.toml",
+ "@prime-agent/src/lib.rs",
+ "@prime-agent/.env",
+ ]
+ );
+}
+
+/// The `@` ranking: match class, hidden entries below unless the query is dotted, fewer
+/// segments, fewer chars, directories before files, then byte order.
+#[test]
+fn at_ranking_orders_by_class_hidden_and_length() {
+ let base = tempfile::TempDir::new().expect("temp dir");
+ for dir in ["main/", "main.d/", "src/", ".github/", "deploy/k8s/"] {
+ std::fs::create_dir_all(base.path().join(dir)).expect("mkdir");
+ }
+ for file in [
+ "main.c",
+ "main.rs",
+ "main.json",
+ "src/main.rs",
+ "src/domain.rs",
+ ".mainrc",
+ ".github/main.yml",
+ "deploy/k8s/app.yml",
+ ] {
+ std::fs::write(base.path().join(file), "x").expect("write");
+ }
+ let provider = provider(base.path().to_str().expect("utf8"));
+ for (query, expected) in [
+ (
+ "@main",
+ vec![
+ "@main/",
+ "@main.d/",
+ "@main.c",
+ "@main.rs",
+ "@main.json",
+ "@src/main.rs",
+ "@.github/main.yml",
+ "@src/domain.rs",
+ "@.mainrc",
+ ],
+ ),
+ ("@yml", vec!["@deploy/k8s/app.yml", "@.github/main.yml"]),
+ ("@.yml", vec!["@.github/main.yml", "@deploy/k8s/app.yml"]),
+ ] {
+ assert_eq!(at_item_values(&provider, query), expected, "query {query}");
+ }
+}
+
/// The parity fixture: nested directories, a hidden file, a pruned `.git`, a gitignored
/// directory (the `.git` directory makes the gitignore rules apply), a directory entry,
/// and mixed case.
diff --git a/crates/pa-tui/src/editor/autocomplete.rs b/crates/pa-tui/src/editor/autocomplete.rs
index 14044717b6..f235f7945f 100644
--- a/crates/pa-tui/src/editor/autocomplete.rs
+++ b/crates/pa-tui/src/editor/autocomplete.rs
@@ -3,7 +3,7 @@
use std::sync::mpsc::TryRecvError;
-use super::text_utils::{char_at, char_prefix, ends_with_symbol_token};
+use super::text_utils::{char_prefix, ends_with_symbol_token};
use super::{AutocompleteSearch, Editor, EditorEvent, PendingAutocomplete};
impl Editor {
@@ -106,29 +106,35 @@ impl Editor {
if self.autocomplete.is_none() {
let slash_ctx = self.current_slash_command_context();
let c = ch.chars().next().unwrap_or(' ');
- if c == '/'
- && matches!(&slash_ctx, Some(ctx) if ctx.kind == crate::autocomplete::SlashKind::Name)
- {
+ let slash_name_slash = c == '/'
+ && matches!(&slash_ctx, Some(ctx) if ctx.kind == crate::autocomplete::SlashKind::Name);
+ let slash_word_char =
+ slash_ctx.is_some() && (c.is_ascii_alphanumeric() || ".-_".contains(c));
+ if slash_name_slash || slash_word_char {
self.request_autocomplete(false, false);
- } else if c == '@' || c == '#' {
- let current_line = &self.lines[self.cursor_line];
- let before = char_prefix(current_line, self.cursor_col);
- let prev = char_at(&before, before.chars().count().saturating_sub(2));
- if before.chars().count() <= 1 || prev == Some(' ') || prev == Some('\t') {
- self.request_autocomplete(false, false);
- }
- } else if c.is_ascii_alphanumeric() || ".-_".contains(c) {
- let current_line = &self.lines[self.cursor_line];
- let before = char_prefix(current_line, self.cursor_col);
- if slash_ctx.is_some() || ends_with_symbol_token(&before) {
- self.request_autocomplete(false, false);
- }
+ } else {
+ self.request_autocomplete_in_symbol_token();
}
} else {
self.refresh_autocomplete_after_edit(false);
}
}
+ /// Request suggestions when the cursor ends an `@`/`#` token: any edit
+ /// inside it — a `/` too, and a completion that keeps it open (an
+ /// applied directory, `@src/`) — lists what the token now matches.
+ pub(crate) fn request_autocomplete_in_symbol_token(&mut self) {
+ if self.cursor_ends_symbol_token() {
+ self.request_autocomplete(false, false);
+ }
+ }
+
+ fn cursor_ends_symbol_token(&self) -> bool {
+ let before = char_prefix(&self.lines[self.cursor_line], self.cursor_col);
+ ends_with_symbol_token(&before)
+ || crate::autocomplete::extract_at_prefix(&before.chars().collect::<Vec<_>>()).is_some()
+ }
+
pub(crate) fn request_autocomplete(&mut self, force: bool, explicit_tab: bool) {
let Some(provider) = self.autocomplete_provider.as_ref() else {
return;
@@ -238,6 +244,7 @@ impl Editor {
self.lines = result.lines;
self.cursor_line = result.cursor_line;
self.set_cursor_col(result.cursor_col);
+ self.request_autocomplete_in_symbol_token();
self.emit(EditorEvent::Changed(self.get_text()));
return;
}
@@ -270,10 +277,8 @@ impl Editor {
}
pub(crate) fn refresh_autocomplete_after_edit(&mut self, retrigger: bool) {
- let current_line = &self.lines[self.cursor_line];
- let before = char_prefix(current_line, self.cursor_col);
let has_ctx =
- self.current_slash_command_context().is_some() || ends_with_symbol_token(&before);
+ self.current_slash_command_context().is_some() || self.cursor_ends_symbol_token();
// An edit that empties the prompt cancels both the open menu and the
// parked request (a parked request can exist without an open menu; if it
@@ -302,3 +307,23 @@ impl Editor {
}
}
}
+
+#[cfg(test)]
+impl Editor {
+ /// Wait for the actual search response, with a failure deadline rather than idle polling.
+ pub(super) fn settle_autocomplete_search(&mut self) {
+ while self.has_pending_autocomplete() {
+ if self.pending_autocomplete.is_some() {
+ self.materialize_autocomplete();
+ }
+ if let Some(active) = self.autocomplete_search.take() {
+ let result = active
+ .search
+ .results
+ .recv_timeout(std::time::Duration::from_secs(10))
+ .expect("autocomplete search must send its result");
+ self.apply_suggestions(result, active.request);
+ }
+ }
+ }
+}
diff --git a/crates/pa-tui/src/editor/input.rs b/crates/pa-tui/src/editor/input.rs
index 92dc93a8f2..148f29c49b 100644
--- a/crates/pa-tui/src/editor/input.rs
+++ b/crates/pa-tui/src/editor/input.rs
@@ -180,6 +180,7 @@ impl Editor {
self.cursor_line = result.cursor_line;
self.set_cursor_col(result.cursor_col);
self.cancel_autocomplete();
+ self.request_autocomplete_in_symbol_token();
if !is_typed_exact || !completed_noop {
self.emit(EditorEvent::Changed(self.get_text()));
return;
diff --git a/crates/pa-tui/src/editor/mod.rs b/crates/pa-tui/src/editor/mod.rs
index e5e34f2c81..48354fa817 100644
--- a/crates/pa-tui/src/editor/mod.rs
+++ b/crates/pa-tui/src/editor/mod.rs
@@ -893,6 +893,142 @@ mod tests {
);
}
+ /// An editor completing `@` tokens over a base holding the
+ /// `prime-agent/` directory with two children beside an unrelated file.
+ fn at_editor() -> (tempfile::TempDir, Editor) {
+ let base = tempfile::TempDir::new().expect("temp dir");
+ std::fs::create_dir_all(base.path().join("prime-agent")).expect("mkdir");
+ std::fs::write(base.path().join("prime-agent/a.rs"), "x").expect("write");
+ std::fs::write(base.path().join("prime-agent/b.rs"), "x").expect("write");
+ std::fs::write(base.path().join("other.md"), "x").expect("write");
+ let mut e = Editor::new();
+ e.set_autocomplete_provider(Box::new(
+ crate::autocomplete::CombinedAutocompleteProvider::from_registry(
+ base.path().to_path_buf(),
+ ),
+ ));
+ (base, e)
+ }
+
+ /// The host loop's idle ticks until no request is parked and no
+ /// background search runs; the open menu's item values, if any.
+ fn settled_menu(e: &mut Editor) -> Option<Vec<String>> {
+ e.settle_autocomplete_search();
+ e.autocomplete_state()
+ .map(|state| state.items.iter().map(|item| item.value.clone()).collect())
+ }
+
+ #[test]
+ fn applying_a_directory_completion_lists_its_children() {
+ let children = Some(vec![
+ "@prime-agent/a.rs".to_string(),
+ "@prime-agent/b.rs".to_string(),
+ ]);
+ // Tab on the open menu applies the directory item.
+ let (_base, mut e) = at_editor();
+ for ch in "@prime-ag".chars() {
+ e.handle_input(&ch.to_string());
+ }
+ assert_eq!(
+ settled_menu(&mut e),
+ Some(vec!["@prime-agent/".to_string()])
+ );
+ e.handle_input("tab");
+ assert_eq!(e.get_text(), "@prime-agent/");
+ assert_eq!(settled_menu(&mut e), children);
+ // Tab before the menu opens applies the single match inline.
+ let (_base, mut e) = at_editor();
+ for ch in "@prime-ag".chars() {
+ e.handle_input(&ch.to_string());
+ }
+ e.handle_input("tab");
+ assert_eq!(settled_menu(&mut e), children);
+ assert_eq!(e.get_text(), "@prime-agent/");
+ }
+
+ #[test]
+ fn quoted_directory_completions_list_children_on_tab_and_enter() {
+ for accept in ["tab", "enter"] {
+ let (base, mut e) = at_editor();
+ std::fs::create_dir_all(base.path().join("dir with spaces")).unwrap();
+ std::fs::write(base.path().join("dir with spaces/child.rs"), "x").unwrap();
+ for ch in "@dir".chars() {
+ e.handle_input(&ch.to_string());
+ }
+ assert_eq!(
+ settled_menu(&mut e),
+ Some(vec!["@\"dir with spaces/\"".to_string()])
+ );
+ e.handle_input(accept);
+ assert_eq!(
+ settled_menu(&mut e),
+ Some(vec!["@\"dir with spaces/child.rs\"".to_string()])
+ );
+ }
+ }
+
+ #[test]
+ fn deleting_in_a_quoted_directory_retriggers_the_closed_menu() {
+ for forward in [false, true] {
+ let (base, mut e) = at_editor();
+ std::fs::create_dir_all(base.path().join("dir with spaces")).unwrap();
+ std::fs::write(base.path().join("dir with spaces/child.rs"), "x").unwrap();
+ for ch in "@\"dir with spaces/x".chars() {
+ e.handle_input(&ch.to_string());
+ }
+ e.materialize_autocomplete();
+ assert!(!e.is_showing_autocomplete());
+ if forward {
+ e.handle_input("left");
+ e.handle_forward_delete();
+ } else {
+ e.handle_backspace();
+ }
+ assert_eq!(
+ settled_menu(&mut e),
+ Some(vec!["@\"dir with spaces/child.rs\"".to_string()])
+ );
+ }
+ }
+
+ #[test]
+ fn slash_in_a_quoted_directory_refreshes_the_running_search() {
+ let (base, mut e) = at_editor();
+ std::fs::create_dir_all(base.path().join("dir with spaces")).unwrap();
+ std::fs::write(base.path().join("dir with spaces/child.rs"), "x").unwrap();
+ for ch in "@\"dir with spaces".chars() {
+ e.handle_input(&ch.to_string());
+ }
+ e.materialize_autocomplete();
+ assert!(e.autocomplete_search.is_some());
+ e.handle_input("/");
+ assert_eq!(
+ settled_menu(&mut e),
+ Some(vec!["@\"dir with spaces/child.rs\"".to_string()])
+ );
+ }
+
+ #[test]
+ fn a_slash_typed_while_the_search_runs_lists_the_children() {
+ let (_base, mut e) = at_editor();
+ for ch in "@prime-agent".chars() {
+ e.handle_input(&ch.to_string());
+ }
+ e.materialize_autocomplete();
+ assert!(
+ !e.is_showing_autocomplete() && e.has_pending_autocomplete(),
+ "the search runs in the background"
+ );
+ e.handle_input("/");
+ assert_eq!(
+ settled_menu(&mut e),
+ Some(vec![
+ "@prime-agent/a.rs".to_string(),
+ "@prime-agent/b.rs".to_string(),
+ ])
+ );
+ }
+
#[test]
fn history_navigation() {
let mut e = ed();
diff --git a/scripts/review_at_completion_parity.py b/scripts/review_at_completion_parity.py
new file mode 100644
index 0000000000..840f3fe45a
--- /dev/null
+++ b/scripts/review_at_completion_parity.py
@@ -0,0 +1,280 @@
+#!/usr/bin/env python3
+"""Hosted actual TS/Rust 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
+refresh 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.
+"""
+import argparse
+import json
+import os
+from pathlib import Path
+import signal
+import shutil
+import subprocess
+import sys
+import tempfile
+import 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
+
+DIRECTORY = 'dir with spaces'
+CHILD = 'only_child.rs'
+APPLIED = '@"dir with spaces/"'
+CASES = ('tab', 'enter', 'typed_slash', 'backspace', 'delete')
+
+
+def completion_rows(text):
+ """Match actual menu rows, excluding the editor's quoted token and chrome."""
+ return [line.strip() for line in text.splitlines()
+ if (CHILD in line or DIRECTORY + '/' in line)
+ and '@' not in line]
+
+
+def children_visible(text):
+ return any(CHILD in row for row in completion_rows(text))
+
+
+def frame(terminal):
+ screen = terminal.screen
+ assert not screen.unsupported_terminal, screen.unsupported_terminal
+ assert not screen.unsupported_sgr, screen.unsupported_sgr
+ return {'text': screen.text(), 'menu_rows': completion_rows(screen.text()),
+ 'children_visible': children_visible(screen.text()),
+ 'cursor': [screen.row, screen.col],
+ 'raw_ansi_complete_hex': bytes(terminal.raw).hex()}
+
+
+def stable_frame(terminal, server, label, predicate):
+ terminal.wait(label, lambda: predicate(terminal.screen.text()), server)
+ previous, count = None, 0
+
+ def stable():
+ nonlocal previous, count
+ current = terminal.screen.text()
+ count = count + 1 if current == previous else 0
+ previous = current
+ return count >= 3 and predicate(current)
+
+ terminal.wait(label + ' stable observable frame', stable, server)
+ return frame(terminal)
+
+
+def discover_direct(scope, command):
+ """Recover an owned spawn even if its PTY constructor failed before assignment."""
+ expected = [str(arg).encode() for arg in command]
+ for entry in Path('/proc').iterdir():
+ if not entry.name.isdigit():
+ continue
+ pid = int(entry.name)
+ try:
+ identity, state = process_identity(pid)
+ if state == 'Z':
+ continue
+ env = dict(item.split(b'=', 1) for item in (entry / 'environ').read_bytes().split(b'\0') if b'=' in item)
+ argv = (entry / 'cmdline').read_bytes().rstrip(b'\0').split(b'\0')
+ if env.get(TAG.encode()) != str(scope.root).encode() or argv != expected:
+ continue
+ scope.direct[pid] = (identity, expected)
+ scope.targets[pid] = identity
+ if not scope.ownership(pid, identity):
+ scope.direct.pop(pid, None)
+ scope.targets.pop(pid, None)
+ except (OSError, ValueError):
+ continue
+ scope.discover()
+
+
+def discover_hello(binary, kind, root, observed):
+ """Learn the real schema; graceful ACK + close + exit, with fallback RED."""
+ root.mkdir(parents=True)
+ env = env_for(root, kind)
+ env[TAG] = str(root)
+ socket_path = root / 'hello.sock'
+ scope = OwnedProcesses(binary, root, socket_path)
+ process = client = None
+ command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(socket_path)]
+ with (root / 'hello.log').open('wb') as log:
+ try:
+ process = subprocess.Popen(command, cwd=root, env=env, stdout=log,
+ stderr=subprocess.STDOUT, start_new_session=True)
+ scope.register(process, command)
+ client = Client(socket_path, process)
+ hello = client.hello
+ assert hello.get('schemaId'), 'actual daemon greeting lacks schema identity'
+ observed['hello'] = hello
+ finally:
+ discover_direct(scope, command)
+ finish(scope, client, process, observed)
+ observed['daemon_log'] = (root / 'hello.log').read_text(errors='replace')
+ assert observed.get('cleanup_verified'), observed
+ return hello
+
+
+def close_terminal(terminal, scope, server, observed):
+ """Exit using normal editor keys; forced PIDFD cleanup never passes."""
+ observed['cleanup_verified'] = False
+ errors = []
+ try:
+ discover_direct(scope, [str(scope.binary), '--daemon-socket', str(server.path)])
+ if terminal is not None:
+ terminal.send('\x15\x0b\x04') # Delete both sides of cursor, Ctrl+D on empty input.
+ deadline = time.monotonic() + 12
+ while terminal.process.poll() is None and time.monotonic() < deadline:
+ terminal.pump()
+ assert terminal.process.poll() == 0, 'ordinary TUI exit did not complete cleanly'
+ scope.wait_gone(3)
+ except Exception as error:
+ errors.append(str(error))
+ observed['fallback_signals'] = []
+ scope.discover()
+ for sig in (signal.SIGTERM, signal.SIGKILL):
+ for pid in scope.live():
+ if scope.send(pid, sig):
+ observed['fallback_signals'].append({'pid': pid, 'signal': sig.name})
+ if terminal is not None:
+ try:
+ terminal.process.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ pass
+ try:
+ scope.wait_gone(3)
+ except Exception as fallback_error:
+ errors.append(str(fallback_error))
+ finally:
+ if terminal is not None:
+ observed['raw_ansi_complete_hex'] = bytes(terminal.raw).hex()
+ try:
+ os.close(terminal.master)
+ except OSError as error:
+ errors.append('owned PTY close: ' + str(error))
+ try:
+ server.close()
+ except Exception as error:
+ errors.append('controlled supervisor cleanup: ' + str(error))
+ observed['wire_commands'] = server.commands
+ observed['fixture_errors'] = server.errors
+ observed['owned_process_identities'] = dict(scope.targets)
+ if server.errors:
+ errors.append('controlled supervisor errors: ' + str(server.errors))
+ if errors:
+ observed['cleanup_errors'] = errors
+ raise AssertionError('; '.join(errors))
+ observed['cleanup_verified'] = True
+
+
+def run_case(binary, kind, root, hello, case, observed):
+ root.mkdir(parents=True)
+ env = env_for(root, kind)
+ env[TAG] = str(root)
+ (root / DIRECTORY).mkdir()
+ (root / DIRECTORY / CHILD).write_text('fixture child\n')
+ socket_path = root / 'fixture.sock'
+ server = Supervisor(socket_path, hello, 'at_completion', root)
+ scope = OwnedProcesses(binary, root, socket_path)
+ terminal = None
+ observed['frames'] = {}
+ observed['inputs'] = []
+ command = [str(binary), '--daemon-socket', str(socket_path)]
+ try:
+ terminal = Terminal(command, root, env)
+ scope.register(terminal.process, command)
+ terminal.screen = DockScreen()
+ terminal.wait('actual ordinary UI attached', lambda: server.attaches >= 1
+ and bool(terminal.screen.text().strip()), server)
+ token = ('@"dir with spaces' if case == 'typed_slash' else
+ '@"dir with spaces/x' if case in ('backspace', 'delete') else '@dir')
+ terminal.send(token)
+ observed['inputs'].append(token.encode().hex())
+ if case in ('tab', 'enter'):
+ observed['frames']['before'] = stable_frame(terminal, server,
+ 'directory suggestion', lambda text: any(DIRECTORY + '/' in row
+ for row in completion_rows(text)))
+ else:
+ observed['frames']['before'] = stable_frame(terminal, server,
+ 'quoted token typed', lambda text: token in text)
+ key = {'tab': '\t', 'enter': '\r', 'typed_slash': '/',
+ 'backspace': '\x7f', 'delete': '\x1b[D\x1b[3~'}[case]
+ terminal.send(key)
+ observed['inputs'].append(key.encode().hex())
+ expected_token = APPLIED if case in ('tab', 'enter') else '@"dir with spaces/'
+ observed['frames']['after'] = stable_frame(terminal, server,
+ 'directory action painted', lambda text: expected_token in text
+ and (token not in text if case in ('backspace', 'delete') else True)
+ and (children_visible(text) if kind == 'rust' else True))
+ assert not server.prompts, 'completion key accidentally submitted a prompt'
+ if kind == 'rust':
+ assert observed['frames']['after']['children_visible'], 'Rust directory children menu missing'
+ observed['behavior_verified'] = True
+ finally:
+ close_terminal(terminal, scope, server, observed)
+
+
+def compare(receipt):
+ """Fail closed on missing execution/cleanup; report actual differences."""
+ comparisons = {}
+ 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
+
+
+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__,
+ '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.',
+ '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)
+ receipt['verified'] = True
+ except Exception as error:
+ receipt['error'] = str(error)
+ args.receipt.parent.mkdir(parents=True, exist_ok=True)
+ args.receipt.write_text(json.dumps(receipt, ensure_ascii=False, indent=2))
+ print(json.dumps({'verified': receipt['verified'], 'error': receipt.get('error')}))
+ return 0 if receipt['verified'] else 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/test_review_at_completion_parity.py b/scripts/test_review_at_completion_parity.py
new file mode 100644
index 0000000000..ffafc57398
--- /dev/null
+++ b/scripts/test_review_at_completion_parity.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python3
+"""Mock-only evidence guards. Never starts a product binary."""
+import copy
+import unittest
+from 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
+
+
+def observations():
+ side = {'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')}}
+
+
+class EvidenceGuards(unittest.TestCase):
+ def discovery(self, tag, argv, ownership=True):
+ files = {'environ': Mock(), 'cmdline': Mock()}
+ files['environ'].read_bytes.return_value = b'PA_GOAL_FIXTURE_ID=' + tag + b'\0'
+ files['cmdline'].read_bytes.return_value = argv
+
+ class Entry:
+ name = '42'
+
+ def __truediv__(self, key):
+ return files[key]
+
+ 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')):
+ proc.return_value.iterdir.return_value = [Entry()]
+ discover_direct(scope, ['/binary', '--daemon-socket', '/case/fixture.sock'])
+ return scope
+
+ def test_constructor_recovery_requires_exact_tag_and_argv(self):
+ argv = b'/binary\0--daemon-socket\0/case/fixture.sock\0'
+ self.assertEqual(self.discovery(b'/case', argv).targets, {42: 'proc:10'})
+ self.assertEqual(self.discovery(b'/other-case', argv).targets, {})
+ self.assertEqual(self.discovery(b'/case', b'/other-binary\0').targets, {})
+
+ def test_reused_identity_is_rejected_after_constructor_recovery(self):
+ argv = b'/binary\0--daemon-socket\0/case/fixture.sock\0'
+ scope = self.discovery(b'/case', argv, ownership=False)
+ self.assertEqual((scope.targets, scope.direct), ({}, {}))
+
+ def test_editor_token_does_not_count_as_a_child_menu(self):
+ text = '│ @"dir with spaces/only_child.rs"\nmodel · 0 tokens'
+ self.assertFalse(children_visible(text))
+ self.assertEqual(completion_rows(text), [])
+
+ def test_actual_menu_row_counts_beside_quoted_editor(self):
+ self.assertTrue(children_visible('› only_child.rs dir with spaces/only_child.rs\n'
+ '│ @"dir with spaces/"'))
+
+ 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
+ with self.assertRaises(AssertionError):
+ compare(receipt)
+
+ def test_unexecuted_case_cannot_pass(self):
+ receipt = observations()
+ receipt['runs']['ts']['cases']['tab']['behavior_verified'] = False
+ with self.assertRaises(AssertionError):
+ compare(receipt)
+
+ def test_failed_cleanup_cannot_pass(self):
+ receipt = observations()
+ receipt['runs']['rust']['cases']['typed_slash']['cleanup_verified'] = False
+ with self.assertRaises(AssertionError):
+ compare(receipt)
+
+ def test_caught_case_error_cannot_pass(self):
+ receipt = observations()
+ receipt['runs']['ts']['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)
+
+ def test_unknown_terminal_geometry_cannot_pass_frame_evidence(self):
+ screen = DockScreen()
+ screen.feed(b'\x1b[3S')
+ with self.assertRaises(AssertionError):
+ frame(Mock(screen=screen, raw=bytearray()))
+
+ def test_cleanup_fallback_remains_red_and_joins_peer(self):
+ terminal = Mock(raw=bytearray(), master=7)
+ terminal.process.poll.return_value = None
+ scope = Mock(targets={})
+ 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 self.assertRaisesRegex(AssertionError, 'ordinary TUI exit'):
+ close_terminal(terminal, scope, server, observed)
+ self.assertFalse(observed['cleanup_verified'])
+ server.close.assert_called_once()
+
+ def test_peer_still_joins_when_pty_close_fails(self):
+ terminal = Mock(raw=bytearray(), master=7)
+ terminal.process.poll.return_value = 0
+ 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 self.assertRaisesRegex(AssertionError, 'PTY close'):
+ close_terminal(terminal, scope, server, observed)
+ self.assertFalse(observed['cleanup_verified'])
+ server.close.assert_called_once()
+
+ def test_constructor_failure_still_discovers_and_rejects_live_owned_processes(self):
+ scope = Mock(targets={})
+ scope.live.return_value = []
+ 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 self.assertRaisesRegex(AssertionError, 'owned child survived'):
+ close_terminal(None, scope, server, observed)
+ discover.assert_called_once()
+ self.assertFalse(observed['cleanup_verified'])
+ server.close.assert_called_once()
+
+
+if __name__ == '__main__':
+ unittest.main()