Add guarded Text alias rename with complete preview and editor reuse

This commit is contained in:
2026-09-12 15:01:08 -07:00
parent be7a8cd8d7
commit dfb6102ba5
40 changed files with 7251 additions and 28 deletions
+3
View File
@@ -71,3 +71,6 @@ harness/history/2026-09-11-state-before-gitea-migration/** -text whitespace=cr-a
harness/experiments/contextual-prerelease-20260911/native/**/*.arcadia whitespace=-blank-at-eol,-blank-at-eof,cr-at-eol
harness/experiments/contextual-prerelease-20260911/producer/package*.log whitespace=-blank-at-eof,cr-at-eol
harness/experiments/contextual-prerelease-20260911/producer/source-push.log -whitespace
harness/experiments/source-alias-rename-native-20260912/** -text whitespace=cr-at-eol
harness/experiments/source-alias-rename-completed-20260912/** -text whitespace=cr-at-eol
harness/experiments/source-alias-rename-refresh-20260912/** -text whitespace=cr-at-eol
+57 -3
View File
@@ -7,6 +7,7 @@ mod diagram_selection_tests;
mod hosted;
#[cfg(test)]
mod review_navigation_tests;
pub(crate) mod source_rename;
mod source_symbols;
#[cfg(test)]
mod transition_context_tests;
@@ -422,6 +423,8 @@ pub enum Message {
crate::source_navigation::SymbolEvent,
),
SourceSymbolsReady(crate::source_navigation::Completion),
SourceRename(source_rename::Event),
SourceRenameReady(source_rename::Completion),
SourceForSelection,
SourceNavigation(crate::source_navigation::Event),
SourceFindClose(crate::source_navigation::SymbolContext, Id),
@@ -500,6 +503,7 @@ pub struct App {
pub source_navigation: crate::source_navigation::State,
source_find_instance: Id,
pub source_symbols: crate::source_navigation::SymbolState,
pub source_rename: source_rename::State,
pub model_issues: Vec<validation::Issue>,
pub migration: Option<persistence::MigrationReport>,
source_version: u64,
@@ -607,6 +611,7 @@ impl App {
source_navigation: crate::source_navigation::State::default(),
source_find_instance: Id::new_v4(),
source_symbols: crate::source_navigation::SymbolState::default(),
source_rename: source_rename::State::default(),
model_issues,
migration: None,
source_version: 0,
@@ -653,19 +658,37 @@ impl App {
|| self.behavior.has_pending()
}
fn sync_source(&mut self) {
self.sync_source_with_alias_editor(None);
}
fn sync_source_with_alias_editor(&mut self, hint: Option<source_rename::EditorRefresh<'_>>) {
self.source_workspace.accept(self.document.bundle());
self.show_source_file(false);
self.show_source_file_with_alias_editor(false, hint);
self.source_diagnostics = self.document.compiled().diagnostics.clone();
self.source_version += 1;
self.lint_requested = None;
}
fn show_source_file(&mut self, restore_cursor: bool) {
self.show_source_file_with_alias_editor(restore_cursor, None);
}
fn show_source_file_with_alias_editor(
&mut self,
restore_cursor: bool,
hint: Option<source_rename::EditorRefresh<'_>>,
) {
self.source_symbols.reveal = None;
self.source_tree.reveal(&self.source_workspace.active);
self.source_select_line = false;
let source = self.source_workspace.text().to_owned();
self.source_navigation.refresh(&source);
if !hint.is_some_and(|hint| {
hint.apply(
&mut self.source_editor,
&self.source_workspace.active,
&source,
)
}) {
self.source_editor = text_editor::Content::with_text(&source);
}
self.source_snapshot = Arc::from(source);
self.source_jump = restore_cursor
.then(|| {
@@ -710,6 +733,9 @@ impl App {
}
}
fn sync(&mut self) {
self.sync_with_alias_editor(None);
}
fn sync_with_alias_editor(&mut self, hint: Option<source_rename::EditorRefresh<'_>>) {
self.explorer_index = crate::explorer::Index::new(self.project(), self.layer);
self.model_issues = validate(self.project());
self.normalize_creation();
@@ -739,7 +765,7 @@ impl App {
.map(|d| d.id);
}
self.refresh_draft();
self.sync_source();
self.sync_source_with_alias_editor(hint);
}
fn normalize_creation(&mut self) {
if !self.create_kind.supports(self.layer) {
@@ -932,6 +958,7 @@ impl App {
let source_version = self.source_version + 1;
let lint_running = self.lint_running;
let navigation_in_flight = self.source_symbols.in_flight;
let rename_in_flight = self.source_rename.in_flight;
let guide = std::mem::take(&mut self.guide);
let mut hosted = std::mem::take(&mut self.hosted);
hosted.leave_document();
@@ -944,6 +971,7 @@ impl App {
self.source_version = source_version;
self.lint_running = lint_running;
self.source_symbols.in_flight = navigation_in_flight;
self.source_rename.in_flight = rename_in_flight;
self.guide = guide;
self.path = path;
self.status = "Project ready".into();
@@ -1061,7 +1089,9 @@ impl App {
self.behavior.creation.has_pending()
|| self.behavior.source_active()
|| (self.page == Page::Text
&& (self.source_symbols.open || self.source_navigation.open)
&& (self.source_symbols.open
|| self.source_navigation.open
|| self.source_rename.open())
&& self.architecture.is_none()),
)
.map(|()| Message::Escape),
@@ -1109,6 +1139,11 @@ impl App {
])
}
pub fn update(&mut self, message: Message) -> Task<Message> {
if let Message::SourceRename(event) = &message
&& !self.source_rename_envelope(event)
{
return Task::none();
}
let message = match message {
Message::SourceFindClose(context, instance) => {
if context != self.source_symbol_context()
@@ -1138,6 +1173,9 @@ impl App {
if let Message::SourceSymbolsReady(completion) = message {
return self.source_symbols_ready(completion);
}
if let Message::SourceRenameReady(completion) = message {
return self.source_rename_ready(completion);
}
if !matches!(
&message,
Message::CheckpointTick
@@ -1328,6 +1366,18 @@ impl App {
{
return Task::none();
}
if self.source_rename.open() {
if matches!(
message,
Message::Escape | Message::Request(Pending::Close(_))
) {
self.close_source_rename();
return Task::none();
}
if !modal_event && !matches!(message, Message::SourceRename(_)) {
return Task::none();
}
}
if matches!(
message,
Message::Page(_) | Message::Layer(_) | Message::Diagram(_)
@@ -1372,6 +1422,7 @@ impl App {
self.last_workspace_page = self.page;
}
let mut task = self.handle(message);
self.refresh_source_rename_context();
self.route_state_diagram_workspace();
if self.page != Page::Home {
self.last_workspace_page = self.page;
@@ -2917,6 +2968,7 @@ impl App {
if self.pending_recovery.as_ref() != Some(&receipt.target) {
return Task::none();
}
self.invalidate_source_rename("Disk recovery changed this source context. Your replacement is retained; close and invoke Rename again.");
self.pending_recovery = None;
self.source_diagnostics
.retain(|issue| issue.diagnostic.code != "pending_save");
@@ -3004,6 +3056,8 @@ impl App {
Message::SourceViewport(ticket) => return self.source_viewport(ticket),
Message::SourceFindClose(..) => return Task::none(), // update checks and unwraps it
Message::SourceSymbols(_, event) => return self.source_symbol_event(event),
Message::SourceRename(event) => return self.source_rename_event(event),
Message::SourceRenameReady(completion) => return self.source_rename_ready(completion),
Message::SourceSymbolsReady(completion) => {
return self.source_symbols_ready(completion);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,219 @@
//! Keep Iced's single-line input from silently filtering pasted control bytes.
//! Only the alias field uses this adapter. The child retains editing and focus.
use iced::advanced::{
Clipboard, Layout, Shell, Widget, clipboard, layout, overlay, renderer, text, widget,
};
use iced::{Element, Event, Length, Rectangle, Size, Vector, keyboard, mouse};
pub(super) fn guard<'a, Message: Clone + 'a, Theme: 'a, R: text::Renderer + 'a>(
input: Element<'a, Message, Theme, R>,
rejected: Option<Message>,
) -> Element<'a, Message, Theme, R> {
Element::new(AliasInput { input, rejected })
}
struct AliasInput<'a, Message, Theme, R> {
input: Element<'a, Message, Theme, R>,
rejected: Option<Message>,
}
#[derive(Default)]
struct State {
modifiers: keyboard::Modifiers,
}
// Each fresh child clipboard read uses the checked snapshot. Iced may reuse its
// previously admitted paste while V is held, until KeyReleased clears that cache.
struct CapturedClipboard<'a> {
content: Option<String>,
original: &'a mut dyn Clipboard,
}
impl Clipboard for CapturedClipboard<'_> {
fn read(&self, kind: clipboard::Kind) -> Option<String> {
if kind == clipboard::Kind::Standard {
self.content.clone()
} else {
self.original.read(kind)
}
}
fn write(&mut self, kind: clipboard::Kind, contents: String) {
self.original.write(kind, contents);
}
}
impl<Message: Clone, Theme, R: text::Renderer> Widget<Message, Theme, R>
for AliasInput<'_, Message, Theme, R>
{
fn size(&self) -> Size<Length> {
self.input.as_widget().size()
}
fn size_hint(&self) -> Size<Length> {
self.input.as_widget().size_hint()
}
fn tag(&self) -> widget::tree::Tag {
widget::tree::Tag::of::<State>()
}
fn state(&self) -> widget::tree::State {
widget::tree::State::new(State::default())
}
fn children(&self) -> Vec<widget::Tree> {
vec![widget::Tree::new(self.input.as_widget())]
}
fn diff(&self, tree: &mut widget::Tree) {
tree.diff_children(std::slice::from_ref(&self.input));
}
fn layout(
&mut self,
tree: &mut widget::Tree,
renderer: &R,
limits: &layout::Limits,
) -> layout::Node {
self.input
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn draw(
&self,
tree: &widget::Tree,
renderer: &mut R,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.input.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
}
fn operate(
&mut self,
tree: &mut widget::Tree,
layout: Layout<'_>,
renderer: &R,
operation: &mut dyn widget::Operation,
) {
self.input
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut widget::Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
let focused = tree.children[0]
.state
.downcast_ref::<iced::widget::text_input::State<R::Paragraph>>()
.is_focused();
let state = tree.state.downcast_mut::<State>();
// Iced 0.14.2 uses stored ModifiersChanged state, not KeyPressed.modifiers.
// Mirror its Escape reset and its Latin/physical-key paste shortcut.
if let Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) = event {
state.modifiers = *modifiers;
}
let paste = matches!(event,
Event::Keyboard(keyboard::Event::KeyPressed { key, physical_key, .. })
if key.to_latin(*physical_key) == Some('v')
&& state.modifiers.command() && !state.modifiers.alt());
if focused
&& paste
&& let Some(rejected) = &self.rejected
{
let content = clipboard.read(clipboard::Kind::Standard);
if content
.as_ref()
.is_some_and(|value| value.chars().any(char::is_control))
{
// Do not invoke the child: even an empty replacement would erase
// its selection. Approval invalidation is an explicit App event.
shell.publish(rejected.clone());
shell.capture_event();
return;
}
self.input.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
&mut CapturedClipboard {
content,
original: clipboard,
},
shell,
viewport,
);
return;
}
self.input.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
// In Iced 0.14.2 the only KeyPressed branch that removes focus is its
// Escape branch, which also resets stored modifiers. Observe that branch
// after its text/shortcut early returns and effective-key conversion.
if focused
&& matches!(event, Event::Keyboard(keyboard::Event::KeyPressed { .. }))
&& !tree.children[0]
.state
.downcast_ref::<iced::widget::text_input::State<R::Paragraph>>()
.is_focused()
{
tree.state.downcast_mut::<State>().modifiers = keyboard::Modifiers::default();
}
}
fn mouse_interaction(
&self,
tree: &widget::Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &R,
) -> mouse::Interaction {
self.input.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
fn overlay<'a>(
&'a mut self,
tree: &'a mut widget::Tree,
layout: Layout<'a>,
renderer: &R,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'a, Message, Theme, R>> {
self.input.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
#[cfg(all(test, debug_assertions))]
mod tests;
@@ -0,0 +1,220 @@
use super::*;
use crate::views::source_tests::FontLayout;
use iced::keyboard::{
Key, Modifiers,
key::{Code, Named, Physical},
};
use std::cell::Cell;
#[derive(Debug, Clone, PartialEq)]
enum Signal {
Input(String),
Rejected,
}
struct ClipboardText {
text: String,
reads: Cell<usize>,
}
impl Clipboard for ClipboardText {
fn read(&self, _: clipboard::Kind) -> Option<String> {
self.reads.set(self.reads.get() + 1);
Some(self.text.clone())
}
fn write(&mut self, _: clipboard::Kind, _: String) {}
}
type InputState = iced::widget::text_input::State<<FontLayout as text::Renderer>::Paragraph>;
struct Mounted {
input: Element<'static, Signal, iced::Theme, FontLayout>,
tree: widget::Tree,
node: layout::Node,
clipboard: ClipboardText,
messages: Vec<Signal>,
}
impl Mounted {
fn new(focused: bool, enabled: bool, modifiers: Modifiers) -> Self {
let mut child = iced::widget::text_input("Alias", "send_water");
if enabled {
child = child.on_input(Signal::Input);
}
let mut input = guard(child.into(), enabled.then_some(Signal::Rejected));
let mut tree = widget::Tree::new(input.as_widget());
let node = input.as_widget_mut().layout(
&mut tree,
&FontLayout,
&layout::Limits::new(Size::ZERO, Size::new(500., 40.)),
);
if focused {
let state = tree.children[0].state.downcast_mut::<InputState>();
state.focus();
state.select_range(0, 10);
}
let mut mounted = Self {
input,
tree,
node,
clipboard: ClipboardText {
text: "foo\nbar".into(),
reads: Cell::new(0),
},
messages: vec![],
};
mounted.event(Event::Keyboard(keyboard::Event::ModifiersChanged(
modifiers,
)));
mounted
}
fn state(&self) -> &InputState {
self.tree.children[0].state.downcast_ref::<InputState>()
}
fn event(&mut self, event: Event) -> bool {
let mut shell = Shell::new(&mut self.messages);
self.input.as_widget_mut().update(
&mut self.tree,
&event,
Layout::new(&self.node),
mouse::Cursor::Unavailable,
&FontLayout,
&mut self.clipboard,
&mut shell,
&Rectangle::new(iced::Point::ORIGIN, Size::new(500., 40.)),
);
shell.is_event_captured()
}
}
fn key(key: Key, modified_key: Key, code: Code) -> Event {
Event::Keyboard(keyboard::Event::KeyPressed {
key,
modified_key,
physical_key: Physical::Code(code),
location: keyboard::Location::Standard,
modifiers: Modifiers::empty(),
text: None,
repeat: false,
})
}
fn paste() -> Event {
key(
Key::Character("v".into()),
Key::Character("v".into()),
Code::KeyV,
)
}
#[test]
fn paste_refusal_matches_child_focus_enabled_and_stored_modifier_protocol() {
for focused in [false, true] {
for enabled in [false, true] {
for modifiers in [
Modifiers::empty(),
Modifiers::SHIFT,
Modifiers::COMMAND,
Modifiers::COMMAND | Modifiers::ALT,
Modifiers::COMMAND | Modifiers::SHIFT,
] {
let mut mounted = Mounted::new(focused, enabled, modifiers);
let before = mounted.state().cursor();
let expected = focused && enabled && modifiers.command() && !modifiers.alt();
let captured = mounted.event(paste());
assert_eq!(
mounted.messages,
if expected {
vec![Signal::Rejected]
} else {
vec![]
}
);
assert_eq!(mounted.clipboard.reads.get(), usize::from(expected));
assert_eq!(mounted.state().cursor(), before);
if expected {
assert!(captured);
}
}
}
}
}
#[test]
fn effective_escape_reset_follows_child_after_early_returns() {
// Raw Escape mapped to Home must not clear only the guard's Command state.
let mut mounted = Mounted::new(true, true, Modifiers::COMMAND);
mounted.event(key(
Key::Named(Named::Escape),
Key::Named(Named::Home),
Code::Escape,
));
assert!(mounted.state().is_focused());
assert!(mounted.event(paste()));
assert_eq!(mounted.messages, vec![Signal::Rejected]);
// Effective Escape clears both states; a later focus operation does not
// invent a new ModifiersChanged event or revive the previous Command state.
let mut mounted = Mounted::new(true, true, Modifiers::COMMAND);
mounted.event(key(
Key::Named(Named::Home),
Key::Named(Named::Escape),
Code::Home,
));
assert!(!mounted.state().is_focused());
mounted.tree.children[0]
.state
.downcast_mut::<InputState>()
.focus();
mounted.event(paste());
assert!(mounted.messages.is_empty());
assert_eq!(mounted.clipboard.reads.get(), 0);
// Printable text returns before effective Escape and leaves modifiers live.
let mut mounted = Mounted::new(true, true, Modifiers::COMMAND);
let mut event = key(
Key::Named(Named::Home),
Key::Named(Named::Escape),
Code::Home,
);
if let Event::Keyboard(keyboard::Event::KeyPressed { text, .. }) = &mut event {
*text = Some("x".into());
}
mounted.event(event);
assert!(mounted.state().is_focused());
assert_eq!(mounted.messages, vec![Signal::Input("x".into())]);
mounted.messages.clear();
mounted.event(paste());
assert_eq!(mounted.messages, vec![Signal::Rejected]);
}
#[test]
fn held_paste_cache_contains_only_previously_admitted_text() {
let mut mounted = Mounted::new(true, true, Modifiers::COMMAND);
mounted.clipboard.text = "water".into();
mounted.event(paste());
assert_eq!(mounted.messages, vec![Signal::Input("water".into())]);
mounted.messages.clear();
mounted.clipboard.text = "other".into();
mounted.event(paste());
assert_eq!(
mounted.messages,
vec![Signal::Input("waterwater".into())],
"Iced reuses its first admitted paste while the key is held"
);
mounted.messages.clear();
let before = mounted.state().cursor();
mounted.clipboard.text = "bad\tvalue".into();
mounted.event(paste());
assert_eq!(mounted.messages, vec![Signal::Rejected]);
assert_eq!(mounted.state().cursor(), before);
mounted.messages.clear();
mounted.event(Event::Keyboard(keyboard::Event::KeyReleased {
key: Key::Character("v".into()),
modified_key: Key::Character("v".into()),
physical_key: Physical::Code(Code::KeyV),
location: keyboard::Location::Standard,
modifiers: Modifiers::empty(),
}));
mounted.clipboard.text = "later".into();
mounted.event(paste());
assert_eq!(
mounted.messages,
vec![Signal::Input("waterwaterlater".into())]
);
}
@@ -0,0 +1,303 @@
//! Display-only reuse after a guarded alias rename. This is not model authority.
use iced::{advanced::text::Renderer, widget::text_editor};
use std::sync::Arc;
/// Replace exact, unchanged-line-count source in an existing editor.
///
/// The caller must first authorize/commit the model change and must reconstruct
/// from accepted source on false. Preflight failures do not mutate the editor;
/// a failed final readback can leave it changed. On changing success the cursor
/// is at 0:0 without selection; the caller restores its approved origin/reveal.
/// Direct Content actions deliberately bypass App draft edits and Undo history.
pub(super) fn replace<R: Renderer>(
editor: &mut text_editor::Content<R>,
before: &str,
after: &str,
) -> bool {
if editor.text() != before {
return false;
}
let Some(old_lines) = lines(before) else {
return false;
};
let Some(new_lines) = lines(after) else {
return false;
};
if old_lines.len() != new_lines.len() || old_lines.len() != editor.line_count() {
return false;
}
let mut patches = Vec::new();
for (line, ((old, old_ending), (new, new_ending))) in
old_lines.into_iter().zip(new_lines).enumerate()
{
let Some(actual) = editor.line(line) else {
return false;
};
// Cosmic also recognizes bare CR and LFCR. Comparing the actual lines
// catches its greedy LFCR interpretation of e.g. "x\n\r\ny" too.
if old_ending != new_ending || actual.text != old || actual.ending != old_ending {
return false;
}
if old == new {
continue;
}
let mut start = old
.bytes()
.zip(new.bytes())
.take_while(|(a, b)| a == b)
.count();
while !old.is_char_boundary(start) || !new.is_char_boundary(start) {
start -= 1;
}
let mut suffix = old[start..]
.bytes()
.rev()
.zip(new[start..].bytes().rev())
.take_while(|(a, b)| a == b)
.count();
while !old.is_char_boundary(old.len() - suffix) || !new.is_char_boundary(new.len() - suffix)
{
suffix -= 1;
}
// All positions and owned payloads are prepared before the first edit.
patches.push((
line,
start,
old.len() - suffix,
Arc::new(new[start..new.len() - suffix].to_owned()),
));
}
if patches.is_empty() {
return true;
}
let empty = Arc::new(String::new());
for (line, start, end, replacement) in patches.into_iter().rev() {
select(editor, line, start, end);
editor.perform(text_editor::Action::Edit(text_editor::Edit::Paste(
replacement,
)));
}
// Iced overwrites its earliest-change marker on each Edit. An explicit
// zero-width selection + empty Paste changes no bytes, but marks line zero.
// This also refreshes previously unhighlighted lines before the first patch.
// It resets only line zero's text cache; other unchanged lines retain theirs.
select(editor, 0, 0, 0);
editor.perform(text_editor::Action::Edit(text_editor::Edit::Paste(empty)));
editor.text() == after
}
fn select<R: Renderer>(
editor: &mut text_editor::Content<R>,
line: usize,
start: usize,
end: usize,
) {
editor.move_to(text_editor::Cursor {
position: text_editor::Position {
line,
column: start,
},
// move_to(None) does not clear a previous selection in this Iced version.
selection: Some(text_editor::Position { line, column: end }),
});
}
fn lines(source: &str) -> Option<Vec<(&str, text_editor::LineEnding)>> {
use text_editor::LineEnding;
let mut result = Vec::new();
let mut parts = source.split('\n').peekable();
while let Some(part) = parts.next() {
let (text, ending) = if parts.peek().is_none() {
(part, LineEnding::None)
} else if let Some(text) = part.strip_suffix('\r') {
(text, LineEnding::CrLf)
} else {
(part, LineEnding::Lf)
};
if text.contains('\r')
|| (text.is_empty()
&& ending == LineEnding::CrLf
&& result
.last()
.is_some_and(|(_, previous)| *previous == LineEnding::Lf))
{
return None;
}
result.push((text, ending));
}
Some(result)
}
#[cfg(all(test, debug_assertions))]
mod tests {
use super::*;
use crate::views::source_tests::FontLayout;
use iced::advanced::{layout, text::Highlighter, widget::Tree};
use iced::{Element, Font, Length, Size};
use std::{cell::RefCell, ops::Range};
#[test]
fn exact_text_matrix_and_reverse_preserve_endings() {
for (before, after) in [
("", ""),
("", "alias"),
("alias", ""),
("same", "same"),
("a\n", "alias\n"),
("a\r\n", "alias\r\n"),
("\r\na\r\n\r\n", "\r\nlong_alias\r\n\r\n"),
("\na\n\n", "\nlong_alias\n\n"),
("a\r\nb\nc", "long_a\r\nlong_b\nlong_c"),
(
"雨🙂 e\u{301} @a @a // a",
"雨🙂 e\u{301} @a_long @a_long // a",
),
("@abc", "@abcdef"),
("@abcdef", "@abc"),
("@abc_suffix", "@def_suffix"),
("@none", "@identifier"),
// Shared prefix/suffix bytes inside distinct UTF-8 codepoints must
// not be used as String split positions, even outside alias scope.
("雨xé", "雪xê"),
("é", "©"),
(
"unchanged\n@a\nunchanged\n@a\n",
"unchanged\n@long\nunchanged\n@long\n",
),
] {
let mut editor = text_editor::Content::<FontLayout>::with_text(before);
assert!(
replace(&mut editor, before, after),
"{before:?} -> {after:?}"
);
assert_eq!(editor.text(), after);
let expected = text_editor::Content::<FontLayout>::with_text(after);
assert_eq!(editor.line_count(), expected.line_count());
for (actual, expected) in editor.lines().zip(expected.lines()) {
assert_eq!(actual.text, expected.text);
assert_eq!(actual.ending, expected.ending);
}
if before != after {
assert_eq!(
editor.cursor().position,
text_editor::Position { line: 0, column: 0 }
);
assert_eq!(editor.cursor().selection, None);
}
assert!(replace(&mut editor, after, before));
assert_eq!(editor.text(), before);
}
}
#[test]
fn all_preflight_refusals_leave_text_cursor_and_selection_unchanged() {
for (actual, before, after) in [
("live", "stale", "changed"),
("a\nb", "a\nb", "long\nb\nc"),
("a\nb", "a\nb", "long\r\nb"),
// Refusal on a later line must not apply the earlier planned edit.
("a\nb\r\n", "a\nb\r\n", "long\nb\n"),
("a\rb", "a\rb", "long\rb"),
("a\n\rb", "a\n\rb", "long\n\rb"),
("a\n\r\nb", "a\n\r\nb", "long\n\r\nb"),
// The replacement must not introduce a greedy LFCR boundary either.
("a\nx\r\n", "a\nx\r\n", "a\n\r\n"),
("a", "a", "long\r"),
] {
let mut editor = text_editor::Content::<FontLayout>::with_text(actual);
select(&mut editor, 0, 0, 1);
let cursor = editor.cursor();
let selection = editor.selection();
assert!(
!replace(&mut editor, before, after),
"{before:?} -> {after:?}"
);
assert_eq!(editor.text(), actual);
assert_eq!(editor.cursor(), cursor);
assert_eq!(editor.selection(), selection);
}
}
#[test]
fn unchanged_content_preserves_selection_and_next_direct_edit_works() {
let mut editor = text_editor::Content::<FontLayout>::with_text("@a");
select(&mut editor, 0, 1, 2);
let cursor = editor.cursor();
assert!(replace(&mut editor, "@a", "@a"));
assert_eq!(editor.cursor(), cursor);
assert!(replace(&mut editor, "@a", "@long"));
editor.move_to(text_editor::Cursor {
position: text_editor::Position { line: 0, column: 5 },
selection: None,
});
editor.perform(text_editor::Action::Edit(text_editor::Edit::Insert('!')));
assert_eq!(editor.text(), "@long!");
}
thread_local! {
static CHANGES: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) };
}
struct Tracked(crate::highlight::ArcadiaHighlighter);
impl Highlighter for Tracked {
type Settings = Arc<str>;
type Highlight = oa_core::language::TokenClass;
type Iterator<'a> = std::vec::IntoIter<(Range<usize>, Self::Highlight)>;
fn new(settings: &Self::Settings) -> Self {
Self(crate::highlight::ArcadiaHighlighter::new(settings))
}
fn update(&mut self, settings: &Self::Settings) {
self.0.update(settings);
}
fn change_line(&mut self, line: usize) {
CHANGES.with(|changes| changes.borrow_mut().push(line));
self.0.change_line(line);
}
fn highlight_line(&mut self, line: &str) -> Self::Iterator<'_> {
self.0.highlight_line(line)
}
fn current_line(&self) -> usize {
self.0.current_line()
}
}
fn view(
editor: &text_editor::Content<FontLayout>,
source: Arc<str>,
) -> Element<'_, (), iced::Theme, FontLayout> {
text_editor(editor)
.font(Font::MONOSPACE)
.size(14)
.height(Length::Fill)
.highlight_with::<Tracked>(source, crate::highlight::format)
.into()
}
#[test]
fn already_laid_out_editor_notifies_highlighter_from_zero_after_later_line_patch() {
let before = "// earlier\n// unmodified\n@a";
let after = "// earlier\n// unmodified\n@none";
let mut editor = text_editor::Content::<FontLayout>::with_text(before);
let limits = layout::Limits::new(Size::ZERO, Size::new(400., 60.));
let mut tree = {
let mut widget = view(&editor, Arc::from(before));
let mut tree = Tree::new(widget.as_widget());
let _ = widget
.as_widget_mut()
.layout(&mut tree, &FontLayout, &limits);
tree
};
CHANGES.with(|changes| changes.borrow_mut().clear());
assert!(replace(&mut editor, before, after));
{
let mut widget = view(&editor, Arc::from(after));
let _ = widget
.as_widget_mut()
.layout(&mut tree, &FontLayout, &limits);
}
// Font/metrics/bounds are already stable. This notification must come
// from the helper's empty edit, not a fresh renderer initialization.
CHANGES.with(|changes| assert_eq!(*changes.borrow(), [0]));
assert_eq!(editor.text(), after);
}
}
@@ -0,0 +1,445 @@
//! Real paragraph advances and clipping through the actual preview dialog.
//! Native screenshots additionally check raster ink and the platform renderer.
use super::*;
use crate::views::source_tests::FontLayout;
use iced::advanced::{Layout, layout, renderer, text as shaped, widget};
use iced::{Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation, Vector};
use std::collections::{BTreeMap, BTreeSet};
struct Glyph {
text: String,
paragraph_y: u32,
line: usize,
bytes: std::ops::Range<usize>,
bounds: Rectangle,
clip: Rectangle,
}
struct GlyphRecorder {
wanted: BTreeSet<String>,
transforms: Vec<Transformation>,
clips: Vec<Rectangle>,
glyphs: Vec<Glyph>,
quads: Vec<Rectangle>,
}
impl GlyphRecorder {
fn new(wanted: BTreeSet<String>, viewport: Rectangle) -> Self {
Self {
wanted,
transforms: vec![Transformation::IDENTITY],
clips: vec![viewport],
glyphs: vec![],
quads: vec![],
}
}
fn transform(&self) -> Transformation {
*self.transforms.last().unwrap()
}
fn clip(&self, bounds: Rectangle) -> Rectangle {
self.clips
.last()
.unwrap()
.intersection(&(bounds * self.transform()))
.unwrap_or(Rectangle::with_size(Size::ZERO))
}
}
impl renderer::Renderer for GlyphRecorder {
fn start_layer(&mut self, bounds: Rectangle) {
self.clips.push(self.clip(bounds));
}
fn end_layer(&mut self) {
self.clips.pop().unwrap();
}
fn start_transformation(&mut self, transform: Transformation) {
self.transforms.push(self.transform() * transform);
}
fn end_transformation(&mut self) {
self.transforms.pop().unwrap();
}
fn reset(&mut self, bounds: Rectangle) {
self.transforms = vec![Transformation::IDENTITY];
self.clips = vec![bounds];
self.glyphs.clear();
self.quads.clear();
}
fn fill_quad(&mut self, quad: renderer::Quad, _: impl Into<Background>) {
self.quads.push(quad.bounds * self.transform());
}
fn allocate_image(
&mut self,
handle: &iced::advanced::image::Handle,
callback: impl FnOnce(Result<iced::advanced::image::Allocation, iced::advanced::image::Error>)
+ Send
+ 'static,
) {
renderer::Renderer::allocate_image(&mut FontLayout, handle, callback);
}
}
impl shaped::Renderer for GlyphRecorder {
type Font = Font;
type Paragraph = <FontLayout as shaped::Renderer>::Paragraph;
type Editor = <FontLayout as shaped::Renderer>::Editor;
const ICON_FONT: Font = <FontLayout as shaped::Renderer>::ICON_FONT;
const CHECKMARK_ICON: char = <FontLayout as shaped::Renderer>::CHECKMARK_ICON;
const ARROW_DOWN_ICON: char = <FontLayout as shaped::Renderer>::ARROW_DOWN_ICON;
const SCROLL_UP_ICON: char = <FontLayout as shaped::Renderer>::SCROLL_UP_ICON;
const SCROLL_DOWN_ICON: char = <FontLayout as shaped::Renderer>::SCROLL_DOWN_ICON;
const SCROLL_LEFT_ICON: char = <FontLayout as shaped::Renderer>::SCROLL_LEFT_ICON;
const SCROLL_RIGHT_ICON: char = <FontLayout as shaped::Renderer>::SCROLL_RIGHT_ICON;
const ICED_LOGO: char = <FontLayout as shaped::Renderer>::ICED_LOGO;
fn default_font(&self) -> Font {
shaped::Renderer::default_font(&FontLayout)
}
fn default_size(&self) -> Pixels {
shaped::Renderer::default_size(&FontLayout)
}
fn fill_paragraph(
&mut self,
paragraph: &Self::Paragraph,
position: Point,
_: Color,
clip: Rectangle,
) {
let buffer = paragraph.buffer();
let text = buffer
.lines
.iter()
.map(|line| line.text())
.collect::<Vec<_>>()
.join("\n");
if !self.wanted.contains(&text) {
return;
}
let clip = self.clip(clip);
for run in buffer.layout_runs() {
for glyph in run.glyphs {
if run.text[glyph.start..glyph.end]
.chars()
.all(char::is_whitespace)
{
continue;
}
let bounds = Rectangle {
x: position.x + glyph.x + glyph.x_offset * glyph.font_size,
y: position.y + run.line_top,
width: glyph.w,
height: run.line_height,
} * self.transform();
self.glyphs.push(Glyph {
text: text.clone(),
paragraph_y: position.y.to_bits(),
line: run.line_i,
bytes: glyph.start..glyph.end,
bounds,
clip,
});
}
}
}
fn fill_editor(
&mut self,
editor: &Self::Editor,
position: Point,
color: Color,
clip: Rectangle,
) {
shaped::Renderer::fill_editor(&mut FontLayout, editor, position, color, clip);
}
fn fill_text(&mut self, text: shaped::Text, position: Point, color: Color, clip: Rectangle) {
shaped::Renderer::fill_text(&mut FontLayout, text, position, color, clip);
}
}
#[derive(Default)]
struct ScrollGeometry {
bounds: Option<Rectangle>,
content: Option<Rectangle>,
offset: Vector,
}
impl widget::Operation for ScrollGeometry {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn widget::Operation)) {
visit(self);
}
fn scrollable(
&mut self,
id: Option<&widget::Id>,
bounds: Rectangle,
content: Rectangle,
offset: Vector,
_: &mut dyn widget::operation::Scrollable,
) {
if id == Some(&widget::Id::new("source-rename-diff")) {
self.bounds = Some(bounds);
self.content = Some(content);
self.offset = offset;
}
}
}
fn normalized(text: &str) -> String {
text.replace("\r\n", "\n").replace('\r', "\n")
}
fn required_chars(text: &str) -> BTreeSet<(usize, usize)> {
text.split('\n')
.enumerate()
.flat_map(|(line, text)| {
text.char_indices()
.filter(|(_, ch)| !ch.is_whitespace())
.map(move |(byte, _)| (line, byte))
})
.collect()
}
fn declarations(long: bool) -> App {
let name = if long {
format!("Assess {} request", "界🚀".repeat(90))
} else {
"Assess 救援 request".into()
};
let source = SourceBundle { entry: "project.arcadia".into(), files: BTreeMap::from([
("project.arcadia".into(), "arcadia 7;\r\nproject navigation_trial \"Navigation — 救援\" id \"9e8f0000-0000-4000-8000-000000000001\" {\r\n include \"救援/assess.arcadia\";\r\n}\r\n".into()),
("救援/assess.arcadia".into(), format!("// Comment @assess must not be a lexical use.\r\noa_activity assess \"{name}\" id \"9e8f0000-0000-4000-8000-000000000002\" {{\r\n description \"Keep @assess as prose, not a use.\";\r\n}}\r\n")),
]) };
let mut app = fixture();
app.document = Document::from_bundle(source, LIMITS).unwrap();
app.source_workspace = Workspace::new(app.document.bundle(), true);
app.source_workspace.active = "救援/assess.arcadia".into();
app.selected = app.project().id;
app.refresh_draft();
app.show_source_file(false);
let start = app
.source_workspace
.text()
.find("oa_activity assess")
.unwrap()
+ "oa_activity ".len();
app.source_editor.move_to(cursor(
app.source_workspace.text(),
start,
start + "assess".len(),
));
begin(&mut app);
let replacement = if long {
"a".repeat(255)
} else {
"assess_damage".into()
};
input(&mut app, &replacement);
let _ = preview(&mut app);
app
}
fn assert_page_glyphs_visible(app: &App, host: Size) {
let form = app.source_rename.form.as_ref().unwrap();
let ready = form.approval.as_ref().unwrap();
let file = &ready.preview.files()[form.file];
let mut expected = BTreeMap::<String, usize>::new();
for line in file.hunks()[form.hunk]
.lines()
.iter()
.skip(form.line)
.take(LINES_PER_PAGE)
{
for source in [
line.before_text(&ready.prepared.before().bundle.files[file.path()])
.unwrap(),
line.after_text(&ready.prepared.after().bundle.files[file.path()])
.unwrap(),
] {
if let Some(fragment) = preview::text_segment(source, form.segment) {
let text = normalized(fragment);
if !required_chars(&text).is_empty() {
*expected.entry(text).or_default() += 1;
}
}
}
}
assert!(!expected.is_empty());
let viewport = Rectangle::new(Point::ORIGIN, host);
let mut renderer = GlyphRecorder::new(expected.keys().cloned().collect(), viewport);
let editor = text_editor::Content::<GlyphRecorder>::new();
let mut view = dialog_content(app, &editor);
let mut tree = widget::Tree::new(view.as_widget());
let node =
view.as_widget_mut()
.layout(&mut tree, &renderer, &layout::Limits::new(Size::ZERO, host));
let mut geometry = ScrollGeometry::default();
view.as_widget_mut()
.operate(&mut tree, Layout::new(&node), &renderer, &mut geometry);
let bounds = geometry.bounds.unwrap();
let content = geometry.content.unwrap();
assert!(bounds.height >= 40.);
let maximum = (content.height - bounds.height).max(0.);
let steps = (maximum / (bounds.height * 0.5)).ceil() as usize;
let mut visible = BTreeMap::<(String, u32), BTreeSet<(usize, usize)>>::new();
let mut reserved_bar_gap = true;
for step in 0..=steps {
let offset = (step as f32 * bounds.height * 0.5).min(maximum);
view.as_widget_mut().operate(
&mut tree,
Layout::new(&node),
&renderer,
&mut widget::operation::scrollable::scroll_to(
widget::Id::new("source-rename-diff"),
widget::operation::scrollable::AbsoluteOffset {
x: None,
y: Some(offset),
},
),
);
view.as_widget_mut()
.operate(&mut tree, Layout::new(&node), &renderer, &mut geometry);
assert!(
(geometry.offset.y - offset).abs() <= 0.5,
"actual scroll operation reaches the requested source offset"
);
renderer::Renderer::reset(&mut renderer, viewport);
view.as_widget().draw(
&tree,
&mut renderer,
&iced::Theme::Light,
&renderer::Style::default(),
Layout::new(&node),
iced::mouse::Cursor::Unavailable,
&viewport,
);
// The vertical scrollbar's actual painted thumb fixes its excluded x
// region; the outer scroll clip alone cannot detect overpainting.
let scrollbar_left = renderer
.quads
.iter()
.filter(|quad| {
quad.width > 0.
&& quad.width <= 16.
&& quad.height > 0.
&& quad.x >= bounds.x + bounds.width - 18.
&& quad.x + quad.width <= bounds.x + bounds.width + 0.5
&& quad.y >= bounds.y - 0.5
&& quad.y + quad.height <= bounds.y + bounds.height + 0.5
})
.map(|quad| quad.x)
.min_by(f32::total_cmp);
if maximum > 0. {
let left = scrollbar_left.expect("overflowing actual preview must paint its scrollbar");
reserved_bar_gap &= content.x + content.width <= left - 7.5;
}
for glyph in &renderer.glyphs {
let right = glyph.bounds.x + glyph.bounds.width;
if let Some(left) = scrollbar_left {
assert!(
right <= left - 0.5,
"source glyph under scrollbar: text={:?} cluster={:?} glyph={:?} bar x={left}",
glyph.text,
glyph.bytes,
glyph.bounds
);
}
assert!(
glyph.bounds.x >= content.x - 0.5 && right <= content.x + content.width + 0.5,
"source glyph escaped reserved width: {:?} {:?}",
glyph.text,
glyph.bounds
);
assert!(
glyph.bounds.x >= glyph.clip.x - 0.5
&& right <= glyph.clip.x + glyph.clip.width + 0.5,
"source glyph horizontally clipped: {:?} {:?} {:?}",
glyph.text,
glyph.bounds,
glyph.clip
);
if glyph.bounds.y >= glyph.clip.y - 0.5
&& glyph.bounds.y + glyph.bounds.height <= glyph.clip.y + glyph.clip.height + 0.5
{
let logical_line = glyph.text.split('\n').nth(glyph.line).unwrap();
let chars = logical_line
.char_indices()
.filter(|(byte, ch)| glyph.bytes.contains(byte) && !ch.is_whitespace())
.map(|(byte, _)| (glyph.line, byte));
visible
.entry((glyph.text.clone(), glyph.paragraph_y))
.or_default()
.extend(chars);
}
}
}
assert!(
reserved_bar_gap,
"source content must reserve actual scrollbar width plus gap"
);
assert!(
bounds.width >= host.width - 30.,
"preview must use available dialog width: {bounds:?} / {host:?}"
);
for (text, count) in expected {
let required = required_chars(&text);
let instances: Vec<_> = visible
.iter()
.filter(|((value, _), _)| value == &text)
.collect();
assert_eq!(
instances.len(),
count,
"all before/after occurrences must be seen: {text:?}"
);
for (_, seen) in instances {
assert_eq!(
seen, &required,
"every non-whitespace source cluster must be fully visible at some vertical offset: {text:?}"
);
}
}
}
#[test]
fn actual_preview_source_glyphs_clear_scrollbar_and_all_long_fragments_are_reachable() {
for long in [false, true] {
let mut app = declarations(long);
let ready = app
.source_rename
.form
.as_ref()
.unwrap()
.approval
.as_ref()
.unwrap()
.clone();
let invocation = app.source_rename.form.as_ref().unwrap().invocation;
let before = evidence(&app);
for (width, height) in [(1100., 700.), (580., 700.)] {
app.window_size = Size::new(width, height);
let host = Size::new((width - 84.).min(708.), height - 120.);
let total = segment_total(app.source_rename.form.as_ref().unwrap());
if long {
assert!(
total >= 3,
"include unbroken ASCII and wide Unicode across segments"
);
}
for segment in 0..total {
assert_page_glyphs_visible(&app, host);
if segment + 1 < total {
event(&mut app, Event::Segment(invocation, ready.id, true));
}
}
for _ in 1..total {
event(&mut app, Event::Segment(invocation, ready.id, false));
}
}
assert_eq!(
evidence(&app),
before,
"preview geometry/paging cannot alter transaction inputs"
);
assert_eq!(
app.source_rename
.form
.as_ref()
.unwrap()
.approval
.as_ref()
.unwrap()
.id,
ready.id
);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,313 @@
//! Manual replacement + next-layout/highlight evaluator; no GPU or native paint.
//! Child of source_rename_timing_tests, preserving the separate real App test.
use super::*;
use crate::{highlight, views::source_tests::FontLayout};
use iced::advanced::widget::operation::Focusable;
use iced::advanced::{Layout, graphics, layout, renderer, text as shaped, widget::Tree};
use iced::{
Background, Color, Element, Font, Length, Pixels, Point, Rectangle, Size, Transformation,
};
// The same real Paragraph and Editor as FontLayout. During draw, retain only a
// Weak and fixed geometry; inspect glyphs after timing, never in fill_editor.
#[derive(Default)]
struct ObservedFontLayout {
drawn: Option<(graphics::text::editor::Weak, Point, Rectangle)>,
}
impl renderer::Renderer for ObservedFontLayout {
fn start_layer(&mut self, _: Rectangle) {}
fn end_layer(&mut self) {}
fn start_transformation(&mut self, _: Transformation) {}
fn end_transformation(&mut self) {}
fn reset(&mut self, _: Rectangle) {
self.drawn = None;
}
fn fill_quad(&mut self, _: renderer::Quad, _: impl Into<Background>) {}
fn allocate_image(
&mut self,
handle: &iced::advanced::image::Handle,
callback: impl FnOnce(Result<iced::advanced::image::Allocation, iced::advanced::image::Error>)
+ Send
+ 'static,
) {
renderer::Renderer::allocate_image(&mut FontLayout, handle, callback);
}
}
impl shaped::Renderer for ObservedFontLayout {
type Font = Font;
type Paragraph = <FontLayout as shaped::Renderer>::Paragraph;
type Editor = <FontLayout as shaped::Renderer>::Editor;
const ICON_FONT: Font = <FontLayout as shaped::Renderer>::ICON_FONT;
const CHECKMARK_ICON: char = <FontLayout as shaped::Renderer>::CHECKMARK_ICON;
const ARROW_DOWN_ICON: char = <FontLayout as shaped::Renderer>::ARROW_DOWN_ICON;
const SCROLL_UP_ICON: char = <FontLayout as shaped::Renderer>::SCROLL_UP_ICON;
const SCROLL_DOWN_ICON: char = <FontLayout as shaped::Renderer>::SCROLL_DOWN_ICON;
const SCROLL_LEFT_ICON: char = <FontLayout as shaped::Renderer>::SCROLL_LEFT_ICON;
const SCROLL_RIGHT_ICON: char = <FontLayout as shaped::Renderer>::SCROLL_RIGHT_ICON;
const ICED_LOGO: char = <FontLayout as shaped::Renderer>::ICED_LOGO;
fn default_font(&self) -> Font {
shaped::Renderer::default_font(&FontLayout)
}
fn default_size(&self) -> Pixels {
shaped::Renderer::default_size(&FontLayout)
}
fn fill_paragraph(&mut self, _: &Self::Paragraph, _: Point, _: Color, _: Rectangle) {}
fn fill_editor(&mut self, editor: &Self::Editor, position: Point, _: Color, clip: Rectangle) {
self.drawn = Some((editor.downgrade(), position, clip));
}
fn fill_text(&mut self, _: shaped::Text, _: Point, _: Color, _: Rectangle) {}
}
type Content = text_editor::Content<ObservedFontLayout>;
const HOST: Size = Size::new(640., 350.);
fn view(editor: &Content, source: Arc<str>) -> Element<'_, (), iced::Theme, ObservedFontLayout> {
text_editor(editor)
.on_action(|_| ())
.font(Font::MONOSPACE)
.size(14)
.padding(16)
.height(Length::Fill)
.highlight_with::<highlight::ArcadiaHighlighter>(source, highlight::format)
.into()
}
fn check_text(editor: &Content, expected: &str, cursor: text_editor::Cursor) {
assert_eq!(editor.text(), expected);
assert_eq!(editor.cursor(), cursor);
let lines: Vec<_> = expected.split('\n').collect();
assert_eq!(editor.line_count(), lines.len());
for (index, part) in lines.iter().enumerate() {
let (text, ending) = if index + 1 == lines.len() {
(*part, text_editor::LineEnding::None)
} else if let Some(text) = part.strip_suffix('\r') {
(text, text_editor::LineEnding::CrLf)
} else {
(*part, text_editor::LineEnding::Lf)
};
let actual = editor.line(index).unwrap();
assert_eq!(actual.text, text);
assert_eq!(actual.ending, ending);
}
}
fn check_draw(renderer: &ObservedFontLayout, cursor: text_editor::Cursor, alias: &str) {
let (weak, position, clip) = renderer.drawn.as_ref().expect("real editor draw");
let editor = weak.upgrade().expect("drawn editor is still live");
let buffer = editor.buffer();
assert_eq!(weak.bounds, Size::new(608., 318.));
assert_eq!(buffer.size(), (Some(608.), Some(318.)));
assert_eq!(buffer.metrics().font_size, 14.);
assert_eq!(
buffer.scroll().horizontal,
0.,
"fixture origin fits the viewport"
);
let start = cursor.position;
let end = cursor.selection.expect("approved alias selection");
assert_eq!(start.line, end.line);
assert_eq!(end.column - start.column, alias.len());
let line = &buffer.lines[start.line];
assert_eq!(&line.text()[start.column..end.column], alias);
let color = graphics::text::to_color(Color::from_rgb8(20, 93, 139));
let font = graphics::text::to_attributes(Font::MONOSPACE);
for byte in start.column..end.column {
let attrs = line.attrs_list().get_span(byte);
assert_eq!(
attrs.color_opt,
Some(color),
"accepted alias syntax attributes"
);
assert_eq!(attrs.family, font.family);
}
let mut covered = vec![false; alias.len()];
for run in buffer.layout_runs().filter(|run| run.line_i == start.line) {
for glyph in run.glyphs {
let from = glyph.start.max(start.column);
let to = glyph.end.min(end.column);
if from >= to {
continue;
}
assert_eq!(glyph.color_opt, Some(color), "drawn alias glyph color");
let x = position.x + glyph.x + glyph.x_offset * glyph.font_size;
let y = position.y + run.line_top;
assert!(x >= clip.x - 0.5 && x + glyph.w <= clip.x + clip.width + 0.5);
assert!(y + run.line_height > clip.y && y < clip.y + clip.height);
covered[from - start.column..to - start.column].fill(true);
}
}
assert!(
covered.into_iter().all(|seen| seen),
"entire alias has visible shaped glyphs"
);
// This temporary strong upgrade is dropped before the next editor mutation.
}
#[derive(Clone, Copy)]
enum Arm {
Constructor,
Reuse,
}
impl Arm {
fn name(self) -> &'static str {
match self {
Self::Constructor => "with_text",
Self::Reuse => "same_line_reuse",
}
}
fn phases(self) -> [&'static str; 4] {
match self {
Self::Constructor => [
"constructor_replace_origin",
"constructor_next_layout",
"constructor_highlight_draw",
"constructor_combined",
],
Self::Reuse => [
"reuse_replace_origin",
"reuse_next_layout",
"reuse_highlight_draw",
"reuse_combined",
],
}
}
}
fn trial(
fixture: &Fixture,
cursor: text_editor::Cursor,
arm: Arm,
trial: usize,
samples: &mut Samples,
) {
let before = &fixture.bundle.files[ORIGIN];
let after = &fixture.expected_bundle.files[ORIGIN];
let mut editor = Content::with_text(before);
editor.move_to(fixture.cursor);
let mut renderer = ObservedFontLayout::default();
let theme = iced::Theme::Light;
let defaults = renderer::Style::default();
let viewport = Rectangle::with_size(HOST);
let limits = layout::Limits::new(Size::ZERO, HOST);
let mut tree = {
let mut widget = view(&editor, Arc::from(before.as_str()));
let mut tree = Tree::new(widget.as_widget());
let node = widget.as_widget_mut().layout(&mut tree, &renderer, &limits);
tree.state
.downcast_mut::<text_editor::State<highlight::ArcadiaHighlighter>>()
.focus();
widget.as_widget().draw(
&tree,
&mut renderer,
&theme,
&defaults,
Layout::new(&node),
iced::mouse::Cursor::Unavailable,
&viewport,
);
tree
};
check_text(&editor, before, fixture.cursor);
check_draw(&renderer, fixture.cursor, OLD);
// No recorder Weak/Strong from setup may perturb replacement ownership.
renderer.drawn = None;
let next_source: Arc<str> = Arc::from(after.as_str());
// Only normal operations and four timestamps occur between start and end.
// Source/model oracles, logging and recorder glyph inspection are outside.
let started = Instant::now();
let replaced = match arm {
Arm::Constructor => {
editor = Content::with_text(after);
true
}
Arm::Reuse => super::super::editor_patch::replace(&mut editor, before, after),
};
editor.move_to(cursor);
let replaced_at = Instant::now();
let mut widget = view(&editor, next_source);
let node = widget.as_widget_mut().layout(&mut tree, &renderer, &limits);
let laid_out_at = Instant::now();
widget.as_widget().draw(
&tree,
&mut renderer,
&theme,
&defaults,
Layout::new(&node),
iced::mouse::Cursor::Unavailable,
&viewport,
);
let drawn_at = Instant::now();
drop(widget);
assert!(replaced, "reuse must not silently time a fallback/refusal");
check_text(&editor, after, cursor);
check_draw(&renderer, cursor, NEW);
renderer.drawn = None;
for (phase, duration) in arm.phases().into_iter().zip([
replaced_at.duration_since(started),
laid_out_at.duration_since(replaced_at),
drawn_at.duration_since(laid_out_at),
drawn_at.duration_since(started),
]) {
println!(
"{}",
serde_json::json!({
"record": "editor_layout_timing", "arm": arm.name(), "phase": phase,
"trial": trial, "warmup": trial == 0,
"elapsed_ns": duration.as_nanos().to_string(),
"elapsed_ms": duration.as_secs_f64() * 1000.0,
})
);
if trial != 0 {
samples.0.entry(phase).or_default().push(duration);
}
}
}
#[test]
#[ignore = "manual Windows dev/debug editor replacement + layout/highlight trial; run alone with --ignored --nocapture --test-threads=1"]
fn accepted_release1_constructor_vs_reuse_through_next_highlight() {
let fixture = Fixture::load();
// Resolve the exact production approval and verify full Project/source once,
// outside all intervals. The actual App Confirm evaluator remains separate.
let cursor = {
let app = fixture.app();
let target = resolve(&app, &app.rename_context());
let prepared = app
.document
.alias_rename_request(target.id, NEW.into())
.unwrap()
.prepare()
.unwrap();
fixture.check_candidate(&prepared);
prepare_approval(prepared, &target, ORIGIN).unwrap().cursor
};
println!(
"{}",
serde_json::json!({
"record": "editor_layout_fixture", "host_width": HOST.width, "host_height": HOST.height,
"font": "MONOSPACE", "font_size": 14, "padding": 16, "height": "Fill",
"active_file": ORIGIN, "before_bytes": fixture.bundle.files[ORIGIN].len(),
"after_bytes": fixture.expected_bundle.files[ORIGIN].len(), "warmups_per_arm": 1,
"measured_trials_per_arm": 5, "debug_assertions": cfg!(debug_assertions),
"scope": "real editor replacement, retained Tree layout and Widget draw/highlight; no GPU, native paint or App Confirm",
})
);
let mut samples = Samples::default();
for index in 0..=5 {
let arms = if index % 2 == 0 {
[Arm::Constructor, Arm::Reuse]
} else {
[Arm::Reuse, Arm::Constructor]
};
println!(
"{}",
serde_json::json!({"record": "editor_layout_order", "trial": index, "first": arms[0].name()})
);
for arm in arms {
trial(&fixture, cursor, arm, index, &mut samples);
}
}
samples.report();
}
@@ -0,0 +1,347 @@
//! Manual timing through the real Document and App paths. No disk writes,
//! executor polling, layout, GPU work or first-paint measurement occurs here.
//! Register as a test child of app::source_rename to use its actual worker helpers.
use super::*;
use crate::source_workspace::Workspace;
use oa_core::source_project::SourceBundle;
use std::{
collections::BTreeMap,
path::PathBuf,
time::{Duration, Instant},
};
#[cfg(debug_assertions)]
#[path = "source_rename_layout_timing_tests.rs"]
mod layout_timing_tests;
const OLD: &str = "oa_restore_work";
const NEW: &str = "oa_restore_pressure";
const DECLARATIONS: &str = "oa/activities/activity_oa_restore_work.arcadia";
const ORIGIN: &str = "traceability.arcadia";
struct Fixture {
bundle: SourceBundle,
project: Project,
expected_bundle: SourceBundle,
expected_project: Project,
target: Id,
cursor: text_editor::Cursor,
}
impl Fixture {
fn load() -> Self {
// The optional entry selects a parent-pinned copy of this exact fixture,
// not an arbitrary performance generator or a mutable GUI destination.
let entry = std::env::var_os("ARCADIA_RENAME_TIMING_ENTRY")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../examples/release1/project.arcadia")
});
let loaded = oa_core::source_files::load_project(&entry, LIMITS).unwrap();
let bundle = loaded.reachable_bundle();
assert_eq!(
bundle.files.len(),
30,
"use the preserved release1 walkthrough"
);
let document = Document::from_bundle(bundle.clone(), LIMITS).unwrap();
assert_eq!(
document.bundle(),
&bundle,
"fixture must need no stabilization/migration"
);
assert!(!document.dirty());
let project = document.project().clone();
let target = Id::parse_str("1b91f8a7-0bdb-514e-b1cd-955658e09927").unwrap();
assert_eq!(project.elements[&target].alias, OLD);
assert!(!project.identities().iter().any(|(_, alias)| *alias == NEW));
let mut expected_project = project.clone();
expected_project.elements.get_mut(&target).unwrap().alias = NEW.into();
// Independent literal source oracle, authored before running the rename.
// Do not replace the alias substring in filenames or the trace's alias.
let mut expected_bundle = bundle.clone();
let declarations = expected_bundle.files.get_mut(DECLARATIONS).unwrap();
assert_eq!(
declarations.matches("oa_activity oa_restore_work ").count(),
1
);
assert_eq!(declarations.matches("parent @oa_restore_work;").count(), 4);
*declarations = declarations
.replace(
"oa_activity oa_restore_work ",
"oa_activity oa_restore_pressure ",
)
.replace("parent @oa_restore_work;", "parent @oa_restore_pressure;");
let traces = expected_bundle.files.get_mut(ORIGIN).unwrap();
assert_eq!(traces.matches("oa @oa_restore_work;").count(), 1);
*traces = traces.replace("oa @oa_restore_work;", "oa @oa_restore_pressure;");
let source = &bundle.files[ORIGIN];
let start = source.rfind("@oa_restore_work;").unwrap() + 1;
let position = |offset| {
let prefix = &source[..offset];
text_editor::Position {
line: prefix.bytes().filter(|byte| *byte == b'\n').count(),
column: prefix
.rsplit_once('\n')
.map_or(prefix.len(), |(_, tail)| tail.len()),
}
};
let cursor = text_editor::Cursor {
position: position(start),
selection: Some(position(start + OLD.len())),
};
assert!(nav::exact_cursor(source, cursor));
println!(
"{}",
serde_json::json!({
"record": "fixture", "entry": entry, "reachable_files": bundle.files.len(),
"source_bytes": bundle.files.values().map(String::len).sum::<usize>(),
"identities": project.identities().len(), "active_file": ORIGIN,
"active_file_bytes": source.len(), "old": OLD, "new": NEW,
"warmups": 1, "measured_trials": 5, "debug_assertions": cfg!(debug_assertions),
"scope": "real worker helpers, guarded Document commit, App sync and Confirm update; no task polling or rendering"
})
);
Self {
bundle,
project,
expected_bundle,
expected_project,
target,
cursor,
}
}
fn app(&self) -> App {
let mut app = App::with_project(Project::empty());
app.document = Document::from_bundle(self.bundle.clone(), LIMITS).unwrap();
app.source_workspace = Workspace::new(app.document.bundle(), true);
app.source_workspace.active = ORIGIN.into();
app.selected = app.project().id;
app.page = Page::Text;
app.sync();
app.source_editor.move_to(self.cursor);
assert_eq!(app.project(), &self.project);
assert_eq!(app.document.bundle(), &self.bundle);
assert_eq!(app.document.revision(), 0);
assert!(!app.document.dirty() && !app.document.can_undo() && !app.document.can_redo());
assert!(app.rename_admission().is_ok());
app
}
fn check_candidate(&self, prepared: &PreparedAliasRename) {
assert!(prepared.changed());
assert_eq!(prepared.before().bundle, self.bundle);
assert_eq!(prepared.before().decoded.project, self.project);
assert_eq!(prepared.after().bundle, self.expected_bundle);
assert_eq!(prepared.after().decoded.project, self.expected_project);
}
fn check_adopted(&self, app: &mut App, candidate_address: *const CompiledSourceProject) {
assert!(
std::ptr::eq(app.document.compiled(), candidate_address),
"adopt exact candidate allocation"
);
assert_eq!(app.project(), &self.expected_project);
assert_eq!(app.document.bundle(), &self.expected_bundle);
assert_eq!(app.source_workspace.bundle(), self.expected_bundle);
assert_eq!(app.source_editor.text(), self.expected_bundle.files[ORIGIN]);
assert_eq!(app.document.revision(), 1);
assert!(app.document.dirty() && app.document.can_undo() && !app.document.can_redo());
assert!(app.document.undo());
assert_eq!(app.project(), &self.project);
assert_eq!(app.document.bundle(), &self.bundle);
assert!(
!app.document.dirty(),
"live known saved baseline remains authoritative"
);
assert!(
!app.document.can_undo(),
"exactly one preceding model transaction"
);
assert!(app.document.redo());
assert_eq!(app.project(), &self.expected_project);
assert_eq!(app.document.bundle(), &self.expected_bundle);
assert!(std::ptr::eq(app.document.compiled(), candidate_address));
}
}
#[derive(Default)]
struct Samples(BTreeMap<&'static str, Vec<Duration>>);
impl Samples {
fn time<T>(&mut self, phase: &'static str, trial: usize, action: impl FnOnce() -> T) -> T {
let started = Instant::now();
let result = action();
let elapsed = started.elapsed();
// Printing, assertions and dropping the returned value are outside this
// interval. Full Confirm still includes production's own local drops.
println!(
"{}",
serde_json::json!({
"record": "timing", "phase": phase, "trial": trial,
"warmup": trial == 0, "elapsed_ns": elapsed.as_nanos().to_string(),
"elapsed_ms": elapsed.as_secs_f64() * 1000.0
})
);
if trial != 0 {
self.0.entry(phase).or_default().push(elapsed);
}
result
}
fn report(mut self) {
for (phase, values) in &mut self.0 {
assert_eq!(values.len(), 5);
values.sort();
println!(
"{}",
serde_json::json!({
"record": "summary", "phase": phase, "samples": values.len(),
"min_ms": values[0].as_secs_f64() * 1000.0,
"median_ms": values[2].as_secs_f64() * 1000.0,
"max_ms": values[4].as_secs_f64() * 1000.0
})
);
}
}
}
fn resolve(app: &App, context: &Context) -> Target {
let snapshot = app
.with_source_input(|input| query::admit_owned(input, query::Limits::default()))
.unwrap()
.capture()
.unwrap();
let offset = nav::cursor_offset(app.source_workspace.text(), context.begin.cursor).unwrap();
resolve_target(&snapshot, context, offset).unwrap()
}
fn active_job(app: &App) -> Job {
let form = app.source_rename.form.as_ref().unwrap();
let id = form.pending.unwrap();
assert_eq!(app.source_rename.in_flight, Some(id));
Job {
id,
invocation: form.invocation,
generation: form.generation,
context: form.context.clone(),
}
}
fn separate_phases(fixture: &Fixture, samples: &mut Samples, trial: usize) {
let mut app = fixture.app();
let target = resolve(&app, &app.rename_context());
assert_eq!(target.id, fixture.target);
let request = samples
.time("document_request_mint", trial, || {
app.document.alias_rename_request(target.id, NEW.into())
})
.unwrap();
let prepared = samples
.time("worker_document_prepare", trial, || request.prepare())
.unwrap();
fixture.check_candidate(&prepared);
let approval = samples
.time("worker_preview_and_origin", trial, || {
prepare_approval(prepared, &target, ORIGIN)
})
.unwrap();
assert_eq!(approval.preview.files().len(), 2);
assert_eq!(approval.preview.changed_line_count(), 6);
let candidate_address = approval.prepared.after() as *const CompiledSourceProject;
// Same-destination save completion is a legitimate live update after Preview.
app.document.mark_saved(app.document.snapshot());
let changed = samples
.time("document_guarded_commit", trial, || {
app.document.commit_alias_rename(&approval.prepared)
})
.unwrap();
assert!(changed);
samples.time("app_sync", trial, || app.sync());
fixture.check_adopted(&mut app, candidate_address);
}
fn whole_confirm(fixture: &Fixture, samples: &mut Samples, trial: usize) {
let mut app = fixture.app();
let begin = app.source_rename_message();
// These Tasks are deliberately not polled: deterministic worker helpers
// supply the same results through the real readiness messages below.
drop(app.update(begin));
let target_job = active_job(&app);
let target = Arc::new(resolve(&app, &target_job.context));
assert_eq!(target.id, fixture.target);
drop(app.update(Message::SourceRenameReady(Completion {
job: target_job,
payload: Payload::Target(Ok(target.clone())),
})));
let invocation = app.source_rename.form.as_ref().unwrap().invocation;
drop(app.update(Message::SourceRename(Event::Input(invocation, NEW.into()))));
let generation = app.source_rename.form.as_ref().unwrap().generation;
drop(app.update(Message::SourceRename(Event::Preview(
invocation, generation,
))));
let preview_job = active_job(&app);
let prepared = app
.document
.alias_rename_request(target.id, NEW.into())
.unwrap()
.prepare()
.unwrap();
fixture.check_candidate(&prepared);
let approval = Arc::new(prepare_approval(prepared, &target, ORIGIN).unwrap());
drop(target);
let candidate_address = approval.prepared.after() as *const CompiledSourceProject;
let expected_cursor = approval.cursor;
let approval_id = approval.id;
drop(app.update(Message::SourceRenameReady(Completion {
job: preview_job,
payload: Payload::Preview(Ok(approval)),
})));
assert_eq!(
app.source_rename
.form
.as_ref()
.unwrap()
.approval
.as_ref()
.unwrap()
.id,
approval_id
);
app.document.mark_saved(app.document.snapshot());
let confirm = Message::SourceRename(Event::Confirm(invocation, generation, approval_id));
let task = samples.time("app_confirm_update", trial, || app.update(confirm));
samples.time("confirm_returned_task_drop_without_polling", trial, || {
drop(task)
});
assert!(!app.source_rename.open());
assert!(app.source_rename.in_flight.is_none());
assert!(app.source_rename_undo_message().is_some());
assert_eq!(app.source_editor.cursor(), expected_cursor);
fixture.check_adopted(&mut app, candidate_address);
}
#[test]
#[ignore = "manual Windows dev/debug rename latency trial; run alone with --ignored --nocapture --test-threads=1"]
fn accepted_release1_prepare_commit_sync_and_confirm_timing() {
let fixture = Fixture::load();
let mut samples = Samples::default();
for trial in 0..=5 {
println!(
"{}",
serde_json::json!({ "record": "order", "trial": trial,
"warmup": trial == 0, "separate_phases_first": trial % 2 == 0 })
);
if trial % 2 == 0 {
separate_phases(&fixture, &mut samples, trial);
whole_confirm(&fixture, &mut samples, trial);
} else {
whole_confirm(&fixture, &mut samples, trial);
separate_phases(&fixture, &mut samples, trial);
}
}
samples.report();
}
+3 -2
View File
@@ -52,7 +52,7 @@ impl App {
}
}
fn with_source_input<T>(&self, use_input: impl FnOnce(query::Input<'_>) -> T) -> T {
pub(super) fn with_source_input<T>(&self, use_input: impl FnOnce(query::Input<'_>) -> T) -> T {
let files: Vec<_> = self
.source_workspace
.files
@@ -83,13 +83,14 @@ impl App {
})
}
fn source_snapshot_matches(&self, snapshot: &query::Snapshot) -> bool {
pub(super) fn source_snapshot_matches(&self, snapshot: &query::Snapshot) -> bool {
snapshot.key() == self.source_key()
&& self.with_source_input(|input| snapshot.matches(input))
}
pub fn source_navigation_available(&self) -> bool {
self.page == Page::Text
&& !self.source_rename.open()
&& !self.busy
&& self.pending.is_none()
&& self.file_prompt.is_none()
+17 -1
View File
@@ -10,6 +10,10 @@ use std::{fmt, sync::Arc};
const HISTORY_LIMIT: usize = 100;
const HISTORY_BYTES: usize = 32 * 1024 * 1024;
#[path = "document_alias_rename.rs"]
mod alias_rename;
pub use alias_rename::PreparedAliasRename;
struct HistoryEntry {
snapshot: Arc<CompiledSourceProject>,
bytes: usize,
@@ -91,6 +95,8 @@ impl From<Vec<SourceDiagnostic>> for DocumentError {
}
pub struct Document {
// Distinguishes equal accepted snapshots belonging to different documents.
alias_owner: Arc<()>,
current: Arc<CompiledSourceProject>,
past: Vec<HistoryEntry>,
future: Vec<HistoryEntry>,
@@ -121,6 +127,7 @@ impl Document {
let current = Arc::new(source_project::compile_bundle(&bundle, limits)?);
let current_bytes = estimated_bytes(&current);
Ok(Self {
alias_owner: Arc::new(()),
current,
current_bytes,
past: Vec::new(),
@@ -394,8 +401,17 @@ impl Document {
return false;
}
let bytes = estimated_bytes(&compiled);
self.commit_snapshot(Arc::new(compiled), bytes)
}
// Only validated internal paths supply a changed snapshot and its exact
// estimate. The ordinary commit wrapper checks bundle inequality; the alias
// path checks its private changed flag and exact accepted-snapshot authority.
// Alias preparation shares this algorithm while retaining the live save and
// history state, and does not clone/recompile the candidate on adoption.
fn commit_snapshot(&mut self, compiled: Arc<CompiledSourceProject>, bytes: usize) -> bool {
self.past.push(HistoryEntry {
snapshot: std::mem::replace(&mut self.current, Arc::new(compiled)),
snapshot: std::mem::replace(&mut self.current, compiled),
bytes: std::mem::replace(&mut self.current_bytes, bytes),
});
self.future.clear();
@@ -0,0 +1,233 @@
//! Alias-only worker preparation and guarded adoption. Public compiled DTOs do
//! not authorize adoption; only this module can mint a prepared rename.
use super::*;
use std::collections::BTreeMap;
/// A pinned intent minted by its owning Document. Move it to a worker and call
/// `prepare`; preparation has no access to the live Document or its histories.
#[derive(Debug)]
pub struct AliasRenameRequest {
owner: Arc<()>,
before: Arc<CompiledSourceProject>,
revision: u64,
limits: ProjectLimits,
target: Id,
old_alias: String,
new_alias: String,
}
#[derive(Debug)]
struct PreparedData {
request: AliasRenameRequest,
after: Arc<CompiledSourceProject>,
before_bytes: usize,
after_bytes: usize,
changed: bool,
}
/// Immutable, Clone-compatible transport for preview and approval. Neither
/// mutable candidate access nor deserialization can manufacture this authority.
#[derive(Debug, Clone)]
pub struct PreparedAliasRename(Arc<PreparedData>);
impl PreparedAliasRename {
pub fn before(&self) -> &CompiledSourceProject {
&self.0.request.before
}
pub fn after(&self) -> &CompiledSourceProject {
&self.0.after
}
pub fn target(&self) -> Id {
self.0.request.target
}
pub fn old_alias(&self) -> &str {
&self.0.request.old_alias
}
pub fn new_alias(&self) -> &str {
&self.0.request.new_alias
}
pub fn revision(&self) -> u64 {
self.0.request.revision
}
pub fn changed(&self) -> bool {
self.0.changed
}
}
fn refusal(message: &str) -> DocumentError {
ModelError(message.into()).into()
}
fn check_history_capacity(before_bytes: usize, after_bytes: usize) -> Result<(), DocumentError> {
if before_bytes.saturating_add(after_bytes) > HISTORY_BYTES {
return Err(refusal(
"This rename exceeds the model Undo budget. No rename was applied.",
));
}
Ok(())
}
impl Document {
pub fn alias_rename_request(
&self,
target: Id,
replacement: String,
) -> Result<AliasRenameRequest, DocumentError> {
if self.revision == u64::MAX {
return Err(refusal(
"The document revision is exhausted. Reopen before renaming.",
));
}
let old_alias = self
.project()
.identities()
.into_iter()
.find_map(|(id, alias)| (id == target).then(|| alias.to_owned()))
.ok_or_else(|| refusal("The alias target is no longer present."))?;
// A candidate has a nonzero estimate. Avoid expensive preparation when
// even the current snapshot leaves no room for its immediate Undo.
if old_alias != replacement && self.current_bytes >= HISTORY_BYTES {
return Err(refusal(
"This rename exceeds the model Undo budget. No rename was applied.",
));
}
Ok(AliasRenameRequest {
owner: self.alias_owner.clone(),
before: self.current.clone(),
revision: self.revision,
limits: self.limits,
target,
old_alias,
new_alias: replacement,
})
}
/// App must separately consume its current approval and check workspace,
/// invocation and draft freshness. This checks accepted Document authority.
pub fn commit_alias_rename(
&mut self,
prepared: &PreparedAliasRename,
) -> Result<bool, DocumentError> {
let data = &prepared.0;
let request = &data.request;
if self.revision == u64::MAX
|| self.revision != request.revision
|| !Arc::ptr_eq(&self.alias_owner, &request.owner)
|| !Arc::ptr_eq(&self.current, &request.before)
{
return Err(refusal(
"This rename preview is stale. Preview the current alias again.",
));
}
if !data.changed {
return Ok(false);
}
if self.current_bytes != data.before_bytes {
return Err(refusal(
"The rename history estimate is stale. Preview again.",
));
}
check_history_capacity(self.current_bytes, data.after_bytes)?;
Ok(self.commit_snapshot(data.after.clone(), data.after_bytes))
}
}
impl AliasRenameRequest {
/// Run on the preparation worker. The typed command and source updater are
/// the only candidate construction path, followed by alias-only invariants.
pub fn prepare(self) -> Result<PreparedAliasRename, DocumentError> {
let before_project = &self.before.decoded.project;
let candidate = prepare_command(
before_project,
&Command::SetAlias(self.target, self.new_alias.clone()),
)?;
let mut expected = before_project.clone();
assign_expected_alias(&mut expected, self.target, &self.new_alias)?;
let identities: BTreeMap<_, _> = before_project
.identities()
.into_iter()
.map(|(id, _)| (id, id))
.collect();
if candidate.project != expected || candidate.identity_map != identities {
return Err(refusal(
"Alias preparation changed unrelated model data or identities.",
));
}
let after = source_project::update_bundle_with_identity_map(
&self.before,
&candidate.project,
&candidate.identity_map,
self.limits,
)?;
let before = &self.before;
if after.decoded.project != expected
|| before.bundle.entry != after.bundle.entry
|| !before.bundle.files.keys().eq(after.bundle.files.keys())
|| before.index.lexical_owners != after.index.lexical_owners
|| !before
.index
.declarations
.iter()
.map(|(id, loc)| (id, &loc.path))
.eq(after
.index
.declarations
.iter()
.map(|(id, loc)| (id, &loc.path)))
{
return Err(refusal(
"Alias preparation changed source membership or ownership.",
));
}
let changed = before.bundle != after.bundle;
let before_bytes = estimated_bytes(before);
let after_bytes = estimated_bytes(&after);
if changed {
check_history_capacity(before_bytes, after_bytes)?;
}
Ok(PreparedAliasRename(Arc::new(PreparedData {
request: self,
after: Arc::new(after),
before_bytes,
after_bytes,
changed,
})))
}
}
// Independent full-model expectation: SetAlias may change exactly one header
// field, across every supported identity family. Do not reuse command execution
// to derive the expected result, which would hide collateral command changes.
fn assign_expected_alias(project: &mut Project, id: Id, alias: &str) -> Result<(), DocumentError> {
if project.id == id {
project.alias = alias.to_owned();
} else if let Some(record) = project.elements.get_mut(&id) {
record.alias = alias.to_owned();
} else if let Some(record) = project.relations.get_mut(&id) {
record.alias = alias.to_owned();
} else if let Some(record) = project.diagrams.get_mut(&id) {
record.alias = alias.to_owned();
} else if let Some(record) = project.artifact_links.get_mut(&id) {
record.alias = alias.to_owned();
} else if let Some(record) = project.traces.get_mut(&id) {
record.alias = alias.to_owned();
} else {
project
.diagrams
.values_mut()
.find_map(|diagram| diagram.nodes.get_mut(&id))
.ok_or_else(|| refusal("The alias target is no longer present."))?
.alias = alias.to_owned();
}
Ok(())
}
#[cfg(test)]
#[path = "document_alias_rename_tests.rs"]
mod tests;
@@ -0,0 +1,459 @@
use super::*;
fn fixture() -> Document {
let bundle = SourceBundle {
entry: "project.arcadia".into(),
files: BTreeMap::from([
("project.arcadia".into(), r#"arcadia 7;
project mission "Испытание" id "10000000-0000-4000-8000-000000000001" {
include "work.arcadia"; include "views.arcadia";
}
"#.replace('\n', "\r\n")),
("work.arcadia".into(), r#"// @assess and assess are explanatory prose.
oa_activity assess "Оценка\u0020ущерба" id "10000000-0000-4000-8000-000000000002" { description "Keep @assess and assess"; }
oa_activity assist "Оценка\u0020ущерба" id "10000000-0000-4000-8000-000000000003" { parent @ // owner evidence
assess; }
sa_function service "Service" id "10000000-0000-4000-8000-000000000004" {}
interaction transfer "Transfer" id "10000000-0000-4000-8000-000000000005" { source @assess; target @assist; }
trace review "Reviewed correspondence" id "10000000-0000-4000-8000-000000000006" { oa @assess; sa @service; kind Refinement; baseline { oa { name "Old assess"; description "@assess"; }; sa { name "Old service"; description "Kept"; }; }; }
artifact evidence "Evidence" id "10000000-0000-4000-8000-000000000007" { owner @review; uri "docs/assess.md"; }
"#.replace('\n', "\r\n")),
("views.arcadia".into(), r#"diagram overview "Overview" id "10000000-0000-4000-8000-000000000008" { layer Oa; routes [{ edge @ // routed identity
transfer; waypoints [{ x 4.20e2; y -16; }]; }]; }
node placement id "10000000-0000-4000-8000-000000000009" { diagram @overview; element @assess; position { x -0.0; y 12.375; }; size { width 260; height 94; }; }
"#.replace('\n', "\r\n")),
]),
};
let document = Document::from_bundle(bundle.clone(), ProjectLimits::default()).unwrap();
assert_eq!(
document.bundle(),
&bundle,
"fixture must need no migration or ID insertion"
);
document
}
fn id(number: u8) -> Id {
Id::parse_str(&format!("10000000-0000-4000-8000-{number:012}")).unwrap()
}
fn prepare(document: &Document, target: Id, replacement: &str) -> PreparedAliasRename {
document
.alias_rename_request(target, replacement.into())
.unwrap()
.prepare()
.unwrap()
}
// Capture every live Document state relevant to refusal/no-op. Arc identity also
// catches replacing an equal snapshot or saved marker behind the user's back.
struct Unchanged {
current: Arc<CompiledSourceProject>,
saved: Option<Arc<SourceBundle>>,
past: Vec<(Arc<CompiledSourceProject>, usize)>,
future: Vec<(Arc<CompiledSourceProject>, usize)>,
revision: u64,
current_bytes: usize,
recovered: bool,
}
impl Unchanged {
fn capture(document: &Document) -> Self {
Self {
current: document.snapshot(),
saved: document.saved.clone(),
past: document
.past
.iter()
.map(|h| (h.snapshot.clone(), h.bytes))
.collect(),
future: document
.future
.iter()
.map(|h| (h.snapshot.clone(), h.bytes))
.collect(),
revision: document.revision,
current_bytes: document.current_bytes,
recovered: document.recovered_unsaved,
}
}
fn assert(&self, document: &Document) {
assert!(Arc::ptr_eq(&self.current, &document.current));
match (&self.saved, &document.saved) {
(Some(before), Some(after)) => assert!(Arc::ptr_eq(before, after)),
(None, None) => {}
_ => panic!("saved baseline changed"),
}
for (before, after) in [
(&self.past, &document.past),
(&self.future, &document.future),
] {
assert_eq!(before.len(), after.len());
for ((snapshot, bytes), entry) in before.iter().zip(after) {
assert!(Arc::ptr_eq(snapshot, &entry.snapshot));
assert_eq!(*bytes, entry.bytes);
}
}
assert_eq!(self.revision, document.revision);
assert_eq!(self.current_bytes, document.current_bytes);
assert_eq!(self.recovered, document.recovered_unsaved);
}
}
#[test]
fn each_identity_family_changes_only_authored_alias_roles_and_one_history_entry() {
// Literal role-specific replacements are independent of the updater/tokenizer.
// They deliberately exclude prose, historical review text and URI spelling.
type AliasCase<'a> = (u8, &'a str, &'a str, &'a [(&'a str, &'a str)]);
let cases: &[AliasCase<'_>] = &[
(
1,
"mission",
"renamed",
&[("project mission ", "project renamed ")],
),
(
2,
"assess",
"renamed",
&[
("oa_activity assess ", "oa_activity renamed "),
("\r\n assess;", "\r\n renamed;"),
("@assess;", "@renamed;"),
],
),
(
5,
"transfer",
"renamed",
&[
("interaction transfer ", "interaction renamed "),
("\r\n transfer;", "\r\n renamed;"),
],
),
(
6,
"review",
"renamed",
&[
("trace review ", "trace renamed "),
("owner @review;", "owner @renamed;"),
],
),
(
7,
"evidence",
"renamed",
&[("artifact evidence ", "artifact renamed ")],
),
(
8,
"overview",
"renamed",
&[
("diagram overview ", "diagram renamed "),
("diagram @overview;", "diagram @renamed;"),
],
),
(
9,
"placement",
"renamed",
&[("node placement ", "node renamed ")],
),
];
for &(number, old, new, replacements) in cases {
let mut document = fixture();
let original = document.snapshot();
let mut expected_model = document.project().clone();
// Explicit per-family oracle, separate from production expectation helper.
match number {
1 => expected_model.alias = new.into(),
2 => expected_model.elements.get_mut(&id(2)).unwrap().alias = new.into(),
5 => expected_model.relations.get_mut(&id(5)).unwrap().alias = new.into(),
6 => expected_model.traces.get_mut(&id(6)).unwrap().alias = new.into(),
7 => expected_model.artifact_links.get_mut(&id(7)).unwrap().alias = new.into(),
8 => expected_model.diagrams.get_mut(&id(8)).unwrap().alias = new.into(),
9 => {
expected_model
.diagrams
.get_mut(&id(8))
.unwrap()
.nodes
.get_mut(&id(9))
.unwrap()
.alias = new.into()
}
_ => unreachable!(),
}
let mut expected_bundle = document.bundle().clone();
for source in expected_bundle.files.values_mut() {
for &(before, after) in replacements {
*source = source.replace(before, after);
}
}
let state = Unchanged::capture(&document);
let prepared = prepare(&document, id(number), new);
state.assert(&document);
assert!(prepared.changed());
assert_eq!(prepared.old_alias(), old);
assert_eq!(prepared.new_alias(), new);
assert_eq!(prepared.target(), id(number));
assert_eq!(prepared.revision(), 0);
assert_eq!(prepared.before().bundle, original.bundle);
assert_eq!(prepared.after().bundle, expected_bundle);
assert_eq!(prepared.after().decoded.project, expected_model);
assert!(document.commit_alias_rename(&prepared).unwrap());
assert!(
Arc::ptr_eq(&document.current, &prepared.0.after),
"adopt the exact prepared Arc"
);
assert_eq!(document.past.len(), 1);
assert!(document.dirty());
let after = Unchanged::capture(&document);
assert!(document.commit_alias_rename(&prepared.clone()).is_err());
after.assert(&document);
assert!(document.undo());
assert!(Arc::ptr_eq(&document.current, &original));
assert!(!document.dirty());
assert!(!document.can_undo());
assert!(document.redo());
assert_eq!(document.bundle(), &expected_bundle);
assert_eq!(document.project(), &expected_model);
document.mark_saved(document.snapshot());
let reopened =
Document::from_bundle(document.bundle().clone(), ProjectLimits::default()).unwrap();
assert_eq!(reopened.project(), &expected_model);
assert_eq!(reopened.bundle(), &expected_bundle);
assert!(!reopened.dirty());
}
}
#[test]
fn highlighted_keyword_alias_is_valid_without_normalizing_input() {
assert!(matches!(
language::tokenize("oa_activity")[0].class,
language::TokenClass::Keyword
));
let mut document = fixture();
let prepared = prepare(&document, id(2), "oa_activity");
document.commit_alias_rename(&prepared).unwrap();
assert_eq!(document.project().elements[&id(2)].alias, "oa_activity");
assert_eq!(document.project().elements[&id(2)].name, "Оценка ущерба");
}
#[test]
fn invalid_and_identical_aliases_preserve_live_state_and_redo() {
let mut document = fixture();
let first = prepare(&document, id(2), "changed");
document.commit_alias_rename(&first).unwrap();
assert!(document.undo());
document.invalidate_saved_baseline();
document.mark_recovered();
let state = Unchanged::capture(&document);
for replacement in ["", "has space", "project", "assist", " assess", "assess "] {
assert!(
document
.alias_rename_request(id(2), replacement.into())
.unwrap()
.prepare()
.is_err()
);
state.assert(&document);
}
assert!(
document
.alias_rename_request(Id::nil(), "new".into())
.is_err()
);
let no_op = prepare(&document, id(2), "assess");
assert!(!no_op.changed());
assert!(!document.commit_alias_rename(&no_op).unwrap());
state.assert(&document);
assert!(document.redo());
assert_eq!(document.project().elements[&id(2)].alias, "changed");
}
#[test]
fn equal_bytes_undo_replay_cross_document_and_exhausted_revision_refuse() {
let mut document = fixture();
let old = prepare(&document, id(2), "renamed");
let mut second = fixture();
let second_state = Unchanged::capture(&second);
assert!(second.commit_alias_rename(&old).is_err());
second_state.assert(&second);
// Even an identical shared accepted Arc cannot confer this Document's owner.
second.current = document.current.clone();
let second_state = Unchanged::capture(&second);
assert!(second.commit_alias_rename(&old).is_err());
second_state.assert(&second);
document
.execute(Command::Rename(id(2), "Later name".into()))
.unwrap();
let edited = Unchanged::capture(&document);
assert!(document.commit_alias_rename(&old).is_err());
edited.assert(&document);
assert!(document.undo());
assert!(Arc::ptr_eq(&document.current, &old.0.request.before));
let undone = Unchanged::capture(&document);
assert!(document.commit_alias_rename(&old).is_err());
undone.assert(&document);
document.revision = u64::MAX - 1;
let last = prepare(&document, id(2), "renamed");
document
.execute(Command::Rename(id(2), "Exhaust revision".into()))
.unwrap();
document.undo();
assert!(Arc::ptr_eq(&document.current, &last.0.request.before));
let exhausted = Unchanged::capture(&document);
assert!(document.commit_alias_rename(&last).is_err());
assert!(
document
.alias_rename_request(id(2), "renamed".into())
.is_err()
);
assert!(
document
.alias_rename_request(id(2), "assess".into())
.is_err()
);
exhausted.assert(&document);
}
#[test]
fn preview_retains_latest_saved_baseline_and_recovery_state() {
for baseline in ["saved_before", "unknown", "raw_repair", "recovered"] {
let mut document = fixture();
let prepared = prepare(&document, id(2), "renamed");
let original = document.snapshot();
match baseline {
"saved_before" => document.mark_saved(original.clone()),
"unknown" => document.invalidate_saved_baseline(),
"raw_repair" => {
let mut raw = document.bundle().clone();
raw.files
.insert("project.arcadia".into(), "invalid repair source".into());
document.bind_repair_baseline(raw);
}
"recovered" => document.mark_recovered(),
_ => unreachable!(),
}
let saved = document.saved.clone();
let recovered = document.recovered_unsaved;
assert!(document.commit_alias_rename(&prepared).unwrap());
assert_eq!(document.saved, saved);
assert_eq!(document.recovered_unsaved, recovered);
assert!(document.dirty());
assert!(document.undo());
assert_eq!(document.saved, saved);
assert_eq!(document.recovered_unsaved, recovered);
assert_eq!(document.dirty(), baseline != "saved_before");
}
// A completed save after Preview remains authoritative, including when it
// clears recovery; a worker must not restore its earlier state on Confirm.
let mut document = fixture();
document.mark_recovered();
document.invalidate_saved_baseline();
let prepared = prepare(&document, id(2), "renamed");
document.mark_saved(document.snapshot());
document.commit_alias_rename(&prepared).unwrap();
assert!(!document.recovered_unsaved);
document.undo();
assert!(!document.dirty());
// Undo from saved C to B, then a new B->C rename can correctly finish clean.
document.redo();
document.mark_saved(document.snapshot());
document.undo();
let return_to_saved = prepare(&document, id(2), "renamed");
document.commit_alias_rename(&return_to_saved).unwrap();
assert!(!document.dirty());
assert!(!document.can_redo());
}
#[test]
fn mutable_public_preview_copies_cannot_change_prepared_authority() {
let mut document = fixture();
let prepared = prepare(&document, id(2), "renamed");
let exact = prepared.after().clone();
let mut counterfeit = prepared.after().clone();
counterfeit.decoded.project.name = "Injected unrelated edit".into();
counterfeit.index.declarations.clear();
let unchanged = Unchanged::capture(&document);
assert!(document.apply_compiled(counterfeit).is_err());
unchanged.assert(&document);
let mut unrelated = exact.decoded.project.clone();
unrelated.name = "A self-consistent unrelated candidate".into();
let forged_dto = source_project::compile_bundle(
&source_project::format_bundle(&unrelated),
ProjectLimits::default(),
)
.unwrap();
assert_ne!(forged_dto.decoded.project, prepared.after().decoded.project);
// No API converts either DTO to PreparedAliasRename. Mutating owned copies
// leaves the opaque capability and its exact adopted model/source intact.
document.commit_alias_rename(&prepared).unwrap();
assert_eq!(document.project(), &exact.decoded.project);
assert_eq!(document.bundle(), &exact.bundle);
}
#[test]
fn exact_history_capacity_admits_immediate_undo_and_rejects_larger_candidate() {
let mut document = fixture();
let mut bundle = document.bundle().clone();
let padding = HISTORY_BYTES / 2 - document.current_bytes;
bundle
.files
.get_mut("views.arcadia")
.unwrap()
.push_str(&format!("//{}\r\n", "x".repeat(padding - 4)));
document.apply_bundle(bundle).unwrap();
assert_eq!(document.current_bytes, HISTORY_BYTES / 2);
// A same-length alias retains the exact estimate; older history is evictable.
let boundary = prepare(&document, id(2), "rating");
assert_eq!(
boundary.0.before_bytes + boundary.0.after_bytes,
HISTORY_BYTES
);
let unchanged = Unchanged::capture(&document);
assert!(
document
.alias_rename_request(id(2), "longer_alias".into())
.unwrap()
.prepare()
.is_err()
);
unchanged.assert(&document);
document.commit_alias_rename(&boundary).unwrap();
assert_eq!(document.past.len(), 1);
assert!(document.undo());
assert!(Arc::ptr_eq(&document.current, &boundary.0.request.before));
assert!(!document.can_undo());
assert!(document.redo());
assert!(Arc::ptr_eq(&document.current, &boundary.0.after));
assert!(check_history_capacity(usize::MAX, 1).is_err());
assert!(check_history_capacity(HISTORY_BYTES, 1).is_err());
}
#[test]
fn mint_and_commit_refuse_exhausted_or_inconsistent_live_history_estimate() {
let mut document = fixture();
let prepared = prepare(&document, id(2), "renamed");
// Inject cache corruption to falsify the commit-side check independently of
// the preparation admission. Normal edits also change revision and Arc.
document.current_bytes = HISTORY_BYTES;
let unchanged = Unchanged::capture(&document);
assert!(
document
.alias_rename_request(id(2), "renamed".into())
.is_err()
);
assert!(document.commit_alias_rename(&prepared).is_err());
// No-op intent needs no Undo reservation even at the admission boundary.
assert!(
document
.alias_rename_request(id(2), "assess".into())
.is_ok()
);
unchanged.assert(&document);
}
+10 -1
View File
@@ -785,7 +785,7 @@ fn article(topic: Topic) -> Article {
const {
Article {
summary: "The text editor and graphical forms edit the same model. Source projects preserve file organization and comments for human review, automation and version control.",
keywords: "text textual source language syntax highlighting lint parser git aliases uuid identity rename diff merge restructuredtext spec canonical parity definition references lexical navigation F12 back",
keywords: "text textual source language syntax highlighting lint parser git aliases uuid identity rename F2 preview diff merge restructuredtext spec canonical parity definition references lexical navigation F12 back",
sections: &[
walkthrough(
"Edit and review source",
@@ -810,6 +810,15 @@ fn article(topic: Topic) -> Article {
"Names, aliases and IDs serve different purposes",
"The displayed name is engineering prose. A stable @alias is the readable source reference and need not change when the name changes. UUID identity distinguishes the persistent record. Preserve IDs when revising the same engineering object; changing identity is a deliberate operation that affects references.",
),
walkthrough(
"Rename a source alias",
&[
"Place the caret on a declaration alias or live @reference, then choose Rename alias or press F2 in the source editor. First finish or revert pending source, property and behavior drafts; close or reattach any extra loaded detached files. Accepted edits do not need to be saved first.",
"Edit Source alias and choose Preview (Enter also previews). Pasting line breaks, tabs or other control characters is rejected without changing the field; choose Preview again after correcting the paste. Review the changed files, hunks and lines; long lines have additional segments. The engineering name and UUID stay unchanged. Comments and quoted prose keep their original spelling. This preview covers the rename; a later Save can include earlier accepted edits too.",
"Choose Rename alias to accept the complete preview, or Cancel/Escape to leave everything unchanged. An invalid, unchanged, stale or oversized preview cannot be confirmed. After editing the replacement, choose Preview again. If the source context changes, close the form and invoke Rename again on the current alias.",
"Use Undo rename immediately, or the model Undo/Redo controls, to restore the complete source/model snapshot. Ctrl+Z in Text still undoes source drafting. Save all and reopen use the normal project workflow; an unconfirmed preview is not saved.",
],
),
example(
"Readable references",
"For example, renaming an activity does not require renaming @assess_incident. A related record can still refer to that alias.",
+1
View File
@@ -24,6 +24,7 @@ mod recovery;
mod route_edit;
mod semantic_review;
mod source_navigation;
mod source_rename;
mod source_tree;
mod source_workspace;
mod style;
@@ -220,12 +220,22 @@ pub struct ReferenceRow {
pub evidence: Evidence,
}
/// Exact lexical occurrence that answered the query, independent of row limits.
/// The optional @ marker is separate from the alias; comments between them do
/// not become part of either hit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Origin {
pub span: Span,
pub marker: Option<Span>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Results {
pub stamp: QueryStamp,
pub action: Action,
pub origin_path: String,
pub origin_offset: usize,
pub origin: Option<Origin>,
pub alias: Option<String>,
pub scope: Scope,
pub disposition: Disposition,
@@ -823,10 +833,28 @@ impl Snapshot {
.ok_or(QueryError::MissingFile)?;
let index = self.index()?;
let hit = index.hit(file, query.byte_offset)?;
let alias = match hit {
Some(symbols::Hit::Definition(handle)) => Some(index.definition(handle)?.alias),
Some(symbols::Hit::Reference(handle)) => Some(index.reference(handle)?.alias),
None => None,
let (alias, origin) = match hit {
Some(symbols::Hit::Definition(handle)) => {
let definition = index.definition(handle)?;
(
Some(definition.alias),
Some(Origin {
span: definition.alias_location.span,
marker: None,
}),
)
}
Some(symbols::Hit::Reference(handle)) => {
let reference = index.reference(handle)?;
(
Some(reference.alias),
Some(Origin {
span: reference.alias_location.span,
marker: Some(reference.at.span),
}),
)
}
None => (None, None),
};
let mut budget = RowBudget {
rows: self.limits.result_rows,
@@ -840,6 +868,7 @@ impl Snapshot {
action: query.action,
origin_path: query.path.to_owned(),
origin_offset: query.byte_offset,
origin,
alias: alias.map(str::to_owned),
scope: self.scope.clone(),
disposition: Disposition::NoSymbol,
@@ -107,6 +107,65 @@ fn reference_offset(fixture: &Fixture) -> usize {
fixture.text("links.arcadia").find("source @").unwrap() + "source ".len()
}
#[test]
fn origin_keeps_exact_hit_when_display_rows_are_omitted() {
let mut fixture = Fixture::standard();
fixture
.text_mut("links.arcadia")
.push_str("// no @pump hit\r\n@pump @pump @ // intervening @pump\r\n pump");
let source = fixture.text("links.arcadia");
let start = source.rfind("pump").unwrap();
let marker = source.rfind("@ // intervening").unwrap();
let limits = Limits {
result_rows: 0,
..Limits::default()
};
let snapshot = fixture.snapshot(None, false, limits);
let expected = Some(Origin {
span: Span {
start,
end: start + 4,
},
marker: Some(Span {
start: marker,
end: marker + 1,
}),
});
for offset in [start, start + 3, marker] {
let result = query(&snapshot, "links.arcadia", offset, Action::References);
assert_eq!(result.origin, expected);
assert!(result.references.is_empty());
assert!(result.omitted_references > 2);
}
let comment = source.rfind("intervening @pump").unwrap() + "intervening @".len();
assert_eq!(
query(&snapshot, "links.arcadia", comment, Action::Definition).origin,
None
);
assert_eq!(
query(&snapshot, "links.arcadia", start + 4, Action::Definition).origin,
None
);
let definition_source = fixture.text("模块/活動.arcadia");
let definition_start = definition_source.find("pump").unwrap();
assert_eq!(
query(
&snapshot,
"模块/活動.arcadia",
definition_start,
Action::Definition
)
.origin,
Some(Origin {
span: Span {
start: definition_start,
end: definition_start + 4
},
marker: None
})
);
}
#[test]
fn exact_multifile_unicode_crlf_definition_and_repeated_lexical_references() {
let fixture = Fixture::standard();
@@ -191,13 +191,6 @@ pub struct AuthoredAnchor {
}
impl AuthoredAnchor {
#[cfg_attr(
not(test),
expect(
dead_code,
reason = "Tested authored-anchor API; editor Back uses exact buffer generations."
)
)]
pub fn id(self) -> Id {
self.id
}
+3
View File
@@ -0,0 +1,3 @@
//! Pure preview and exact origin mapping for the guarded alias-rename controller.
pub mod origin;
pub mod preview;
@@ -0,0 +1,278 @@
//! Map a role-proven alias occurrence through the exact prepared source change.
//! This is cursor restoration, not target resolution or commit authority.
use oa_core::language::{self, Outline, OutlineLimits, Span, TokenClass};
use std::fmt;
const LIMITS: OutlineLimits = OutlineLimits {
max_source_bytes: 64 * 1024 * 1024,
max_tokens: 1_000_000,
max_declarations: 250_000,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OriginError {
Budget,
InvalidSource,
MissingOrigin,
ChangedStructure,
}
impl fmt::Display for OriginError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Budget => "The alias cursor preview exceeds its source scan budget. No rename was applied.",
Self::InvalidSource => "The alias cursor could not be verified in this source. No rename was applied.",
Self::MissingOrigin => "The original alias occurrence no longer matches. Preview again; no rename was applied.",
Self::ChangedStructure => "The preview changed source outside the expected alias tokens. No rename was applied.",
})
}
}
impl std::error::Error for OriginError {}
fn word(class: TokenClass) -> bool {
matches!(class, TokenClass::Identifier | TokenClass::Keyword)
}
/// The controller passes the exact alias span returned by the admitted symbol
/// hit. `marker` is Some only for a reference (its separate @ span), including
/// invocation with the caret on @. A declaration passes None.
pub fn map(
before: &str,
after: &str,
old_alias: &str,
new_alias: &str,
origin: Span,
marker: Option<Span>,
) -> Result<Span, OriginError> {
let old = language::outline(before, LIMITS).map_err(|_| OriginError::Budget)?;
let new = language::outline(after, LIMITS).map_err(|_| OriginError::Budget)?;
if old.has_lexical_errors || new.has_lexical_errors {
return Err(OriginError::InvalidSource);
}
if old.tokens.len() != new.tokens.len() {
return Err(OriginError::ChangedStructure);
}
let roles_before = roles(&old);
let roles_after = roles(&new);
let mut mapped = None;
for (index, (a, b)) in old.tokens.iter().zip(&new.tokens).enumerate() {
let left = &before[a.span.start..a.span.end];
let right = &after[b.span.start..b.span.end];
let alias_pair = word(a.class)
&& word(b.class)
&& left == old_alias
&& right == new_alias
&& roles_before[index].is_some()
&& roles_after[index].is_some()
&& roles_before[index].map(|role| role.is_some())
== roles_after[index].map(|role| role.is_some());
if a.span == origin {
if !alias_pair || roles_before[index] != Some(marker) {
return Err(OriginError::MissingOrigin);
}
mapped = Some(b.span);
}
if !alias_pair && (left != right || a.class != b.class) {
return Err(OriginError::ChangedStructure);
}
}
mapped.ok_or(OriginError::MissingOrigin)
}
/// Outer None is not an alias role; Some(None) is a declaration alias;
/// Some(Some(span)) is a live @ reference with its exact separate marker.
/// Scan sorted declaration spans and tokens together, without repeated searches.
fn roles(outline: &Outline<'_>) -> Vec<Option<Option<Span>>> {
let mut result = vec![None; outline.tokens.len()];
let mut declarations = outline.declarations.iter().peekable();
let mut significant = None;
for (index, token) in outline.tokens.iter().enumerate() {
while declarations
.peek()
.is_some_and(|d| d.alias_span.start < token.span.start)
{
declarations.next();
}
if word(token.class) {
if declarations
.peek()
.is_some_and(|d| d.alias_span == token.span)
{
result[index] = Some(None);
} else if let Some(previous) = significant {
let span: Span = previous;
if &outline.source[span.start..span.end] == "@" {
result[index] = Some(Some(span));
}
}
}
if !matches!(token.class, TokenClass::Whitespace | TokenClass::Comment) {
significant = Some(token.span);
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
fn occurrence(source: &str, needle: &str, which: usize) -> Span {
let start = source.match_indices(needle).nth(which).unwrap().0;
Span {
start,
end: start + needle.len(),
}
}
#[test]
fn maps_last_repeated_reference_with_unicode_crlf_and_comment_separator() {
let before =
"oa_activity a \"救援\" {}\r\n// @a is prose\r\nsource @a; target @ // a\r\n a;\r\n";
let after = "oa_activity renamed \"救援\" {}\r\n// @a is prose\r\nsource @renamed; target @ // a\r\n renamed;\r\n";
let start = before.rfind(" a;").unwrap() + 1;
let marker = before.rfind("@ //").unwrap();
let mapped = map(
before,
after,
"a",
"renamed",
Span {
start,
end: start + 1,
},
Some(Span {
start: marker,
end: marker + 1,
}),
)
.unwrap();
assert_eq!(&after[mapped.start..mapped.end], "renamed");
assert_eq!(mapped.start, after.rfind(" renamed;").unwrap() + 1);
assert_eq!(
before[..start].bytes().filter(|b| *b == b'\n').count(),
after[..mapped.start]
.bytes()
.filter(|b| *b == b'\n')
.count()
);
}
#[test]
fn preserves_final_same_line_occurrence_not_first_or_prose() {
let before = "oa_activity a \"a @a\" {} source @a; target @a;";
let after = "oa_activity longer \"a @a\" {} source @longer; target @longer;";
let start = before.rfind("@a").unwrap();
let result = map(
before,
after,
"a",
"longer",
Span {
start: start + 1,
end: start + 2,
},
Some(Span {
start,
end: start + 1,
}),
)
.unwrap();
assert_eq!(result.start, after.rfind("@longer").unwrap() + 1);
let prose = occurrence(before, "a @a", 0);
assert!(
map(
before,
after,
"a",
"longer",
Span {
start: prose.start,
end: prose.start + 1
},
None
)
.is_err()
);
}
#[test]
fn permits_identifier_keyword_transitions_in_alias_roles() {
let before = "oa_activity a \"Name\" {} source @a;";
let alias = occurrence(before, "a \"Name", 0);
let origin = Span {
start: alias.start,
end: alias.start + 1,
};
for replacement in ["none", "include", "oa_activity"] {
assert!(oa_core::valid_alias(replacement));
assert_eq!(
language::tokenize(replacement)[0].class,
TokenClass::Keyword
);
let after = format!("oa_activity {replacement} \"Name\" {{}} source @{replacement};");
let mapped = map(before, &after, "a", replacement, origin, None).unwrap();
assert_eq!(&after[mapped.start..mapped.end], replacement);
assert_eq!(
map(&after, before, replacement, "a", mapped, None).unwrap(),
origin
);
}
}
#[test]
fn rejects_changed_trivia_non_alias_words_and_wrong_marker() {
let before = "oa_activity a \"Name\" {} source @a;";
let after = "oa_activity b \"Name\" {} source @b;";
let start = before.rfind("@a").unwrap();
let span = Span {
start: start + 1,
end: start + 2,
};
let marker = Some(Span {
start,
end: start + 1,
});
assert_eq!(
map(
before,
&after.replace("Name", "Other"),
"a",
"b",
span,
marker
),
Err(OriginError::ChangedStructure)
);
assert_eq!(
map(
before,
&after.replace(" source", " source"),
"a",
"b",
span,
marker
),
Err(OriginError::ChangedStructure)
);
assert_eq!(
map(before, after, "a", "b", span, None),
Err(OriginError::MissingOrigin)
);
assert!(
map(
before,
after,
"a",
"b",
Span {
start: 0,
end: usize::MAX
},
marker
)
.is_err()
);
}
}
@@ -0,0 +1,578 @@
//! Complete, bounded line-ordinal previews of an already prepared alias rename.
//!
//! Source text remains in the caller's immutable before/after snapshots. This
//! module owns only paths and indexes; it is not rename or commit authority.
use oa_core::source_project::SourceBundle;
use std::{fmt, ops::Range};
const CONTEXT: usize = 3;
// A byte-grid boundary can move back by at most three UTF-8 continuation bytes,
// so a 252-byte grid yields fragments of at most 255 bytes, independent of input.
const SEGMENT_GRID: usize = 252;
/// Count all bounded fragments of exact source text; an empty line has one
/// empty fragment. Page these as well as lines, never mount an unbounded line.
pub fn segment_count(text: &str) -> usize {
text.len().div_ceil(SEGMENT_GRID).max(1)
}
/// Constant-time UTF-8-safe page lookup. Concatenating every fragment gives the
/// original bytes, including CRLF. No ellipsis or truncation replaces content.
pub fn text_segment(text: &str, index: usize) -> Option<&str> {
if index >= segment_count(text) {
return None;
}
let mut start = index.checked_mul(SEGMENT_GRID)?;
let mut end = start.saturating_add(SEGMENT_GRID).min(text.len());
while !text.is_char_boundary(start) {
start -= 1;
}
while !text.is_char_boundary(end) {
end -= 1;
}
text.get(start..end)
}
const LIMITS: Limits = Limits {
files: 256,
changed_lines: 50_000,
display_bytes: 8 * 1024 * 1024,
};
#[derive(Clone, Copy)]
struct Limits {
files: usize,
changed_lines: usize,
display_bytes: usize,
}
#[derive(Debug)]
pub struct Preview {
files: Vec<File>,
changed_lines: usize,
display_bytes: usize,
}
#[derive(Debug)]
pub struct File {
path: String,
hunks: Vec<Hunk>,
}
#[derive(Debug)]
pub struct Hunk {
lines: Vec<Line>,
}
#[derive(Debug)]
pub struct Line {
number: usize,
before: Range<usize>,
after: Range<usize>,
changed: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub enum PreviewError {
MembershipChanged,
LineCountChanged(String),
LineEndingChanged { path: String, line: usize },
TooManyFiles { limit: usize },
TooManyChangedLines { limit: usize },
TooManyDisplayBytes { limit: usize },
}
impl fmt::Display for PreviewError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MembershipChanged => write!(
f,
"Rename preview refused: the entry or source file membership changed. No rename was applied."
),
Self::LineCountChanged(path) => write!(
f,
"Rename preview refused: the line count changed in {path}. No rename was applied."
),
Self::LineEndingChanged { path, line } => write!(
f,
"Rename preview refused: the line ending changed in {path}:{line}. No rename was applied."
),
Self::TooManyFiles { limit } => write!(
f,
"Rename preview exceeds {limit} changed files. A complete preview is required; no rename was applied."
),
Self::TooManyChangedLines { limit } => write!(
f,
"Rename preview exceeds {limit} changed source lines. A complete preview is required; no rename was applied."
),
Self::TooManyDisplayBytes { limit } => write!(
f,
"Rename preview exceeds {limit} display bytes (paths and both versions of changed/context lines). A complete preview is required; no rename was applied."
),
}
}
}
impl std::error::Error for PreviewError {}
impl Preview {
pub fn build(before: &SourceBundle, after: &SourceBundle) -> Result<Self, PreviewError> {
Self::with_limits(before, after, LIMITS)
}
fn with_limits(
before: &SourceBundle,
after: &SourceBundle,
limits: Limits,
) -> Result<Self, PreviewError> {
if before.entry != after.entry
|| !before.files.contains_key(&before.entry)
|| !before.files.keys().eq(after.files.keys())
{
return Err(PreviewError::MembershipChanged);
}
let mut preview = Self {
files: Vec::new(),
changed_lines: 0,
display_bytes: 0,
};
for ((path, old), (_, new)) in before.files.iter().zip(&after.files) {
if old == new {
continue;
}
if preview.files.len() == limits.files {
return Err(PreviewError::TooManyFiles {
limit: limits.files,
});
}
// A changed source line can contain arbitrarily many renamed tokens.
// Count the line once; this count is never a semantic-reference count.
let mut changed = Vec::new();
let mut old_lines = Lines::new(old);
let mut new_lines = Lines::new(new);
let mut count = 0;
loop {
match (old_lines.next(), new_lines.next()) {
(None, None) => break,
(Some(a), Some(b)) => {
count += 1;
if old[a.content_end..a.end] != new[b.content_end..b.end] {
return Err(PreviewError::LineEndingChanged {
path: path.clone(),
line: count,
});
}
if old[a.start..a.end] != new[b.start..b.end] {
if preview.changed_lines == limits.changed_lines {
return Err(PreviewError::TooManyChangedLines {
limit: limits.changed_lines,
});
}
preview.changed_lines += 1;
changed.push(count - 1);
}
}
_ => return Err(PreviewError::LineCountChanged(path.clone())),
}
}
// Merge touching context intervals in order, without pairwise diff.
// At most 7 indexed lines per changed line are retained; unchanged
// lines outside these intervals are scanned but never indexed.
let mut ranges: Vec<Range<usize>> = Vec::new();
for line in changed {
let range =
line.saturating_sub(CONTEXT)..line.saturating_add(CONTEXT + 1).min(count);
if let Some(previous) = ranges.last_mut()
&& range.start <= previous.end
{
previous.end = previous.end.max(range.end);
continue;
}
ranges.push(range);
}
preview.charge(path.len(), limits)?;
let mut file = File {
path: path.clone(),
hunks: Vec::new(),
};
let mut pairs = Lines::new(old).zip(Lines::new(new)).enumerate();
for range in ranges {
let mut hunk = Hunk { lines: Vec::new() };
for (ordinal, (a, b)) in pairs.by_ref() {
if ordinal < range.start {
continue;
}
// Charge exact UTF-8 bytes, including preserved endings and
// both copies of shared context, before adding the index.
// No render-time omission or shortening grants admission.
preview.charge(a.end - a.start, limits)?;
preview.charge(b.end - b.start, limits)?;
hunk.lines.push(Line {
number: ordinal + 1,
changed: old[a.start..a.end] != new[b.start..b.end],
before: a.start..a.end,
after: b.start..b.end,
});
if ordinal + 1 == range.end {
break;
}
}
file.hunks.push(hunk);
}
preview.files.push(file);
}
Ok(preview)
}
fn charge(&mut self, bytes: usize, limits: Limits) -> Result<(), PreviewError> {
let Some(total) = self.display_bytes.checked_add(bytes) else {
return Err(PreviewError::TooManyDisplayBytes {
limit: limits.display_bytes,
});
};
if total > limits.display_bytes {
return Err(PreviewError::TooManyDisplayBytes {
limit: limits.display_bytes,
});
}
self.display_bytes = total;
Ok(())
}
/// All admitted files in source path order; suitable for a file picker/search.
pub fn files(&self) -> &[File] {
&self.files
}
/// Changed source lines, not occurrences, declarations or semantic uses.
pub fn changed_line_count(&self) -> usize {
self.changed_lines
}
/// Exact displayed source bytes for both sides plus each stored path once.
/// Index metadata is separately bounded by 7 lines per changed line.
pub fn display_bytes(&self) -> usize {
self.display_bytes
}
#[cfg(test)]
pub fn is_empty(&self) -> bool {
self.files.is_empty()
}
}
impl File {
pub fn path(&self) -> &str {
&self.path
}
/// Every hunk is present; the caller may page these indexes, never truncate.
pub fn hunks(&self) -> &[Hunk] {
&self.hunks
}
}
impl Hunk {
/// The complete ordered line slice supports paging even a large single hunk.
pub fn lines(&self) -> &[Line] {
&self.lines
}
}
impl Line {
/// One-based source line number, identical on both sides.
pub fn number(&self) -> usize {
self.number
}
pub fn changed(&self) -> bool {
self.changed
}
/// Borrow from the immutable original file; includes its exact line ending.
pub fn before_text<'a>(&self, original: &'a str) -> Option<&'a str> {
original.get(self.before.clone())
}
/// Borrow from the immutable candidate file; includes its exact line ending.
pub fn after_text<'a>(&self, candidate: &'a str) -> Option<&'a str> {
candidate.get(self.after.clone())
}
}
struct RawLine {
start: usize,
content_end: usize,
end: usize,
}
struct Lines<'a> {
bytes: &'a [u8],
offset: usize,
}
impl<'a> Lines<'a> {
fn new(text: &'a str) -> Self {
Self {
bytes: text.as_bytes(),
offset: 0,
}
}
}
impl Iterator for Lines<'_> {
type Item = RawLine;
fn next(&mut self) -> Option<Self::Item> {
if self.offset == self.bytes.len() {
return None;
}
let start = self.offset;
// The compiler and source navigation count LF, not bare CR, as a line
// boundary. Preserve CRLF as an ending and bare CR as source content.
while self.offset < self.bytes.len() && self.bytes[self.offset] != b'\n' {
self.offset += 1;
}
let mut content_end = self.offset;
if self.offset < self.bytes.len() {
if self.offset > start && self.bytes[self.offset - 1] == b'\r' {
content_end -= 1;
}
self.offset += 1;
}
Some(RawLine {
start,
content_end,
end: self.offset,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bundle(source: &str) -> SourceBundle {
SourceBundle {
entry: "救援.arcadia".into(),
files: [("救援.arcadia".into(), source.into())].into(),
}
}
#[test]
fn long_unicode_lines_are_fully_reachable_as_bounded_fragments() {
let text = format!("{}救援🙂{}\r\n", "a".repeat(251), "🙂".repeat(200));
let pieces: Vec<_> = (0..segment_count(&text))
.map(|i| text_segment(&text, i).unwrap())
.collect();
assert!(pieces.len() > 2);
assert!(pieces.iter().all(|part| part.len() <= 255));
assert_eq!(pieces.concat(), text);
assert_eq!(text_segment(&text, segment_count(&text)), None);
assert_eq!(text_segment(&text, usize::MAX), None);
assert_eq!(segment_count(""), 1);
assert_eq!(text_segment("", 0), Some(""));
}
#[test]
fn preserves_unicode_mixed_endings_and_counts_lines_not_repeated_uses() {
let old = bundle("// 救援\r\n@a @a\ncontext\r@a");
let new = bundle("// 救援\r\n@long @long\ncontext\r@long");
let preview = Preview::build(&old, &new).unwrap();
assert_eq!(preview.changed_line_count(), 2);
let file = &preview.files()[0];
assert_eq!(file.path(), "救援.arcadia");
assert_eq!(file.hunks().len(), 1);
let lines = file.hunks()[0].lines();
assert_eq!(
lines.iter().map(Line::number).collect::<Vec<_>>(),
[1, 2, 3]
);
assert_eq!(
lines[0].before_text(&old.files[&old.entry]),
Some("// 救援\r\n")
);
assert_eq!(
lines[1].after_text(&new.files[&new.entry]),
Some("@long @long\n")
);
assert_eq!(
lines[2].after_text(&new.files[&new.entry]),
Some("context\r@long")
);
assert!(lines[1].changed() && lines[2].changed());
assert!(!lines[0].changed());
assert_eq!(
preview.display_bytes(),
old.entry.len() + old.files[&old.entry].len() + new.files[&new.entry].len()
);
}
#[test]
fn first_and_last_lines_form_complete_separate_hunks_and_pages() {
let old = bundle("a\n1\n2\n3\n4\n5\n6\n7\n8\n9\na");
let new = bundle("long\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlong");
let preview = Preview::build(&old, &new).unwrap();
let hunks = preview.files()[0].hunks();
assert_eq!(hunks.len(), 2);
let page_numbers: Vec<_> = hunks
.iter()
.flat_map(|h| h.lines().chunks(2))
.flat_map(|page| page.iter().map(Line::number))
.collect();
assert_eq!(page_numbers, [1, 2, 3, 4, 8, 9, 10, 11]);
assert_eq!(
hunks[1].lines()[3].after_text(&new.files[&new.entry]),
Some("long")
);
}
#[test]
fn nearby_changes_merge_and_all_changed_files_are_reachable() {
let mut old = bundle("a\n1\n2\n3\n4\n5\na\n");
let mut new = bundle("b\n1\n2\n3\n4\n5\nb\n");
old.files.insert("other.arcadia".into(), "a a a".into());
new.files.insert("other.arcadia".into(), "b b b".into());
let preview = Preview::build(&old, &new).unwrap();
assert_eq!(preview.changed_line_count(), 3);
assert_eq!(preview.files().len(), 2);
assert_eq!(preview.files()[0].path(), "other.arcadia");
assert_eq!(preview.files()[0].hunks()[0].lines().len(), 1);
assert_eq!(preview.files()[1].hunks().len(), 1);
assert_eq!(preview.files()[1].hunks()[0].lines().len(), 7);
}
#[test]
fn unchanged_and_empty_sources_have_no_preview() {
for source in ["", "a\r\nb\n", "a"] {
let original = bundle(source);
let preview = Preview::build(&original, &original).unwrap();
assert!(preview.is_empty());
assert_eq!(preview.changed_line_count(), 0);
assert_eq!(preview.display_bytes(), 0);
}
}
#[test]
fn refuses_membership_entry_line_count_and_line_ending_changes() {
let old = bundle("a\nb");
let mut new = old.clone();
new.files.insert("extra.arcadia".into(), "".into());
assert_eq!(
Preview::build(&old, &new).unwrap_err(),
PreviewError::MembershipChanged
);
let mut new = old.clone();
new.entry = "missing.arcadia".into();
assert_eq!(
Preview::build(&old, &new).unwrap_err(),
PreviewError::MembershipChanged
);
assert!(matches!(
Preview::build(&old, &bundle("a\nb\nc")),
Err(PreviewError::LineEndingChanged { .. }) | Err(PreviewError::LineCountChanged(_))
));
assert!(matches!(
Preview::build(&bundle("a\nb\n"), &bundle("a\n")),
Err(PreviewError::LineCountChanged(_))
));
for (a, b) in [("a\r\n", "a\n"), ("a\r", "a\n"), ("a", "a\n")] {
assert_eq!(
Preview::build(&bundle(a), &bundle(b)).unwrap_err(),
PreviewError::LineEndingChanged {
path: old.entry.clone(),
line: 1
}
);
}
}
#[test]
fn each_bound_is_exact_and_overflow_never_returns_a_partial_preview() {
let old = bundle("a\ncontext\na");
let new = bundle("bbb\ncontext\nbbb");
let exact = old.entry.len() + old.files[&old.entry].len() + new.files[&new.entry].len();
let limits = Limits {
files: 1,
changed_lines: 2,
display_bytes: exact,
};
assert!(Preview::with_limits(&old, &new, limits).is_ok());
assert_eq!(
Preview::with_limits(&old, &new, Limits { files: 0, ..limits }).unwrap_err(),
PreviewError::TooManyFiles { limit: 0 }
);
assert_eq!(
Preview::with_limits(
&old,
&new,
Limits {
changed_lines: 1,
..limits
}
)
.unwrap_err(),
PreviewError::TooManyChangedLines { limit: 1 }
);
assert_eq!(
Preview::with_limits(
&old,
&new,
Limits {
display_bytes: exact - 1,
..limits
}
)
.unwrap_err(),
PreviewError::TooManyDisplayBytes { limit: exact - 1 }
);
let long = bundle(&"a".repeat(LIMITS.display_bytes));
assert!(matches!(
Preview::build(&bundle("b"), &long),
Err(PreviewError::TooManyDisplayBytes { .. })
));
}
#[test]
fn limits_apply_to_the_whole_preview_not_each_file() {
let mut old = bundle("a");
let mut new = bundle("b");
old.files.insert("second.arcadia".into(), "a".into());
new.files.insert("second.arcadia".into(), "b".into());
let limits = Limits {
files: 2,
changed_lines: 2,
display_bytes: old.entry.len() + "second.arcadia".len() + 4,
};
let complete = Preview::with_limits(&old, &new, limits).unwrap();
assert_eq!(complete.files().len(), 2);
assert_eq!(complete.changed_line_count(), 2);
assert_eq!(complete.display_bytes(), limits.display_bytes);
assert!(matches!(
Preview::with_limits(&old, &new, Limits { files: 1, ..limits }),
Err(PreviewError::TooManyFiles { limit: 1 })
));
assert!(matches!(
Preview::with_limits(
&old,
&new,
Limits {
changed_lines: 1,
..limits
}
),
Err(PreviewError::TooManyChangedLines { limit: 1 })
));
assert!(matches!(
Preview::with_limits(
&old,
&new,
Limits {
display_bytes: limits.display_bytes - 1,
..limits
}
),
Err(PreviewError::TooManyDisplayBytes { .. })
));
}
}
+33 -7
View File
@@ -350,6 +350,13 @@ pub fn view(app: &App) -> View<'_, Message> {
if app.pending.is_some() {
return modal(root,column![text("Keep your changes?").size(21),text("Save the model and pending edits before continuing. Invalid drafts stay available for correction.").size(13),row![action("Cancel",Message::Cancel),action("Discard changes",Message::Discard),button("Save & continue").padding(10).on_press(Message::SaveAndContinue)].spacing(8)].spacing(16).into());
}
if app.source_rename.open() {
return modal_width(
root,
crate::app::source_rename::dialog(app),
(app.window_size.width - 32.).clamp(120., 760.),
);
}
root
}
fn modal<'a>(base: View<'a, Message>, content: View<'a, Message>) -> View<'a, Message> {
@@ -1004,6 +1011,13 @@ fn source_files(app: &App) -> View<'_, Message> {
fn source(app: &App) -> View<'_, Message> {
use crate::source_navigation::Event as SourceEvent;
let (undo_label, undo_message) = match app.source_rename_undo_message() {
Some(message) => ("Undo rename", Some(message)),
None => (
"Undo model",
(app.document.can_undo() && !app.source_dirty()).then_some(Message::Undo),
),
};
let navigation: View<'_, Message> = if app.source_navigation.open {
column![
row![
@@ -1118,7 +1132,8 @@ fn source(app: &App) -> View<'_, Message> {
.on_action(Message::SourceEdit)
.key_binding({
let context = app.source_symbol_context();
move |press| source_binding(press, &context)
let rename = app.source_rename_begin();
move |press| source_binding(press, &context, Some(&rename))
})
.font(Font::MONOSPACE)
.size(14)
@@ -1146,8 +1161,8 @@ fn source(app: &App) -> View<'_, Message> {
row![
action("Undo text", Message::SourceUndo),
action("Redo text", Message::SourceRedo),
button(text("Undo model").size(12)).padding([8,10]).style(style::nav)
.on_press_maybe((app.document.can_undo() && !app.source_dirty()).then_some(Message::Undo)),
button(text(undo_label).size(12)).padding([8,10]).style(style::nav)
.on_press_maybe(undo_message),
button(text("Redo model").size(12)).padding([8,10]).style(style::nav)
.on_press_maybe((app.document.can_redo() && !app.source_dirty()).then_some(Message::Redo)),
action("Find / go to…", Message::SourceNavigation(SourceEvent::Open(false))),
@@ -1174,6 +1189,7 @@ fn source(app: &App) -> View<'_, Message> {
row![
action("Definition · F12", app.source_symbol_message(crate::source_navigation::SymbolEvent::Query(crate::source_navigation::query::Action::Definition))),
action("References · Shift F12", app.source_symbol_message(crate::source_navigation::SymbolEvent::Query(crate::source_navigation::query::Action::References))),
action("Rename alias · F2", app.source_rename_message()),
button(text("Back · Alt ←").size(12)).padding([8, 10]).style(style::nav)
.on_press_maybe((app.source_symbols.back.iter().any(|entry| entry.session == app.source_workspace.session())).then(|| app.source_symbol_message(crate::source_navigation::SymbolEvent::Back))),
].spacing(7),
@@ -1225,13 +1241,23 @@ fn source_layout<'a, Renderer: iced::advanced::text::Renderer + 'a>(
.height(Fill)
.into()
}
fn source_binding(
pub(crate) fn source_binding(
press: widget::text_editor::KeyPress,
context: &crate::source_navigation::SymbolContext,
rename: Option<&crate::app::source_rename::Begin>,
) -> Option<widget::text_editor::Binding<Message>> {
use crate::source_navigation::{SymbolEvent, query::Action};
use iced::keyboard::{Key, key::Named};
use widget::text_editor::{Binding, Status};
if matches!(press.status, Status::Focused { .. })
&& press.modifiers.is_empty()
&& press.key == Key::Named(Named::F2)
&& let Some(begin) = rename
{
return Some(Binding::Custom(Message::SourceRename(
crate::app::source_rename::Event::Begin(begin.clone()),
)));
}
// Windows owns Alt+Space for its window menu. Iced's default binding would
// otherwise insert a supplied space payload, even after that menu closes.
// Keep Ctrl+Alt (AltGr), shifted input, and ordinary Space unchanged.
@@ -1273,7 +1299,7 @@ fn source_binding(
}
#[cfg(all(test, debug_assertions))]
mod source_tests {
pub(crate) mod source_tests {
use super::*;
use iced::advanced::{
Layout, Shell, graphics, layout, renderer, text as shaped, widget as core_widget,
@@ -1282,7 +1308,7 @@ mod source_tests {
use iced::{Background, Color, Pixels, Point, Rectangle, Size, Transformation, Vector};
// Measure real Iced paragraphs/editor text without constructing a window or GPU.
struct FontLayout;
pub(crate) struct FontLayout;
impl renderer::Renderer for FontLayout {
fn start_layer(&mut self, _: Rectangle) {}
fn end_layer(&mut self) {}
@@ -1612,7 +1638,7 @@ mod source_tests {
.size(14)
.padding(16)
.height(Fill)
.key_binding(|press| source_binding(press, &context))
.key_binding(|press| source_binding(press, &context, None))
.into();
let mut tree = core_widget::Tree::new(editor.as_widget());
let size = Size::new(600., 240.);
+39
View File
@@ -2650,6 +2650,45 @@ limits. If sources change, stale rows cannot navigate: run the query again.
Navigation MUST preserve the accepted model and every source draft, and select
locations in the original UTF-8 bytes. Displayed locations use one-based lines
and UTF-8 byte columns.</p>
<p><strong>Rename alias</strong> (<span class="docutils literal">F2</span> while the source editor has focus) changes the alias
under the caret or its exact selection. It requires a unique authored identity
in the complete accepted source bundle, with no pending source, property or
behavior drafts and no extra loaded detached files. Accepted but unsaved source
is eligible. The operation MUST NOT implicitly apply a draft or allocate an ID.
The engineering name and UUID remain unchanged.</p>
<p>The <strong>Source alias</strong> field does not trim or normalize the entered alias. Pasting
line breaks, tabs or other control characters is explicitly rejected as a whole:
the field and its selection remain unchanged, and any previous preview approval
is invalidated. <strong>Preview</strong>
prepares a typed alias change and displays every changed file and source line;
comments, strings, engineering data, file membership and declaration ownership
remain unchanged. Enter in the field requests Preview, never confirmation.
The preview is for this operation against accepted source, so a later Save may
also contain earlier accepted edits. A changing rename requires enough model
history capacity to retain its immediate Undo. An invalid, identical, stale or
oversized candidate cannot enable confirmation.</p>
<p>The preview MUST provide access to all admitted files, hunks, lines and long-line
segments. Refuse a candidate whose complete preview exceeds the editor's bounds:
256 changed files, 50,000 changed lines or 8 MiB of displayed source bytes
(both versions of changed/context lines and file paths). Index metadata is
separately bounded to seven retained line records per changed line. These
limits do not restrict the language itself. A changed-line count is not a count
of semantic references. Cancel, Preview and Rename alias remain reachable
outside the independently scrolling source preview.</p>
<p>Explicit <strong>Rename alias</strong> confirms the current preview once, as one accepted
model/source transaction. A source, document, recovery or replacement change
invalidates its approval even if later bytes match the old preview. Closing the
form cancels approval; a late worker result MUST NOT reopen it. Rejected,
canceled and unchanged operations preserve accepted bytes, drafts, save state,
revisions, selection and both histories. Successful rename selects the new alias
at the original occurrence rather than the first matching spelling in the file.
Editing the replacement permits a new Preview in the same form. After a source
context change, close the form and invoke Rename again on the current alias.</p>
<p><strong>Undo rename</strong> is guarded against intervening edits and uses model history;
the persistent <strong>Undo model</strong> and <strong>Redo model</strong> controls restore the complete
accepted snapshots. Text <span class="docutils literal">Ctrl+Z</span> remains <strong>Undo text</strong>. Save is separate and
uses the ordinary guarded source-save contract. An unconfirmed preview and Undo
history are not persisted on reopening.</p>
<p>Changing a graphical UUID must atomically update map keys and every reference.
Alias changes preserve UUID identity. Deletion must account for owned elements,
incident relationships, ordered occurrences, and diagram placements without
+44
View File
@@ -2073,6 +2073,50 @@ Navigation MUST preserve the accepted model and every source draft, and select
locations in the original UTF-8 bytes. Displayed locations use one-based lines
and UTF-8 byte columns.
**Rename alias** (``F2`` while the source editor has focus) changes the alias
under the caret or its exact selection. It requires a unique authored identity
in the complete accepted source bundle, with no pending source, property or
behavior drafts and no extra loaded detached files. Accepted but unsaved source
is eligible. The operation MUST NOT implicitly apply a draft or allocate an ID.
The engineering name and UUID remain unchanged.
The **Source alias** field does not trim or normalize the entered alias. Pasting
line breaks, tabs or other control characters is explicitly rejected as a whole:
the field and its selection remain unchanged, and any previous preview approval
is invalidated. **Preview**
prepares a typed alias change and displays every changed file and source line;
comments, strings, engineering data, file membership and declaration ownership
remain unchanged. Enter in the field requests Preview, never confirmation.
The preview is for this operation against accepted source, so a later Save may
also contain earlier accepted edits. A changing rename requires enough model
history capacity to retain its immediate Undo. An invalid, identical, stale or
oversized candidate cannot enable confirmation.
The preview MUST provide access to all admitted files, hunks, lines and long-line
segments. Refuse a candidate whose complete preview exceeds the editor's bounds:
256 changed files, 50,000 changed lines or 8 MiB of displayed source bytes
(both versions of changed/context lines and file paths). Index metadata is
separately bounded to seven retained line records per changed line. These
limits do not restrict the language itself. A changed-line count is not a count
of semantic references. Cancel, Preview and Rename alias remain reachable
outside the independently scrolling source preview.
Explicit **Rename alias** confirms the current preview once, as one accepted
model/source transaction. A source, document, recovery or replacement change
invalidates its approval even if later bytes match the old preview. Closing the
form cancels approval; a late worker result MUST NOT reopen it. Rejected,
canceled and unchanged operations preserve accepted bytes, drafts, save state,
revisions, selection and both histories. Successful rename selects the new alias
at the original occurrence rather than the first matching spelling in the file.
Editing the replacement permits a new Preview in the same form. After a source
context change, close the form and invoke Rename again on the current alias.
**Undo rename** is guarded against intervening edits and uses model history;
the persistent **Undo model** and **Redo model** controls restore the complete
accepted snapshots. Text ``Ctrl+Z`` remains **Undo text**. Save is separate and
uses the ordinary guarded source-save contract. An unconfirmed preview and Undo
history are not persisted on reopening.
Changing a graphical UUID must atomically update map keys and every reference.
Alias changes preserve UUID identity. Deletion must account for owned elements,
incident relationships, ordered occurrences, and diagram placements without
@@ -0,0 +1,19 @@
{
"archive": "source-rename-completed-evidence-20260912.zip",
"sha256": "2282e4e755bb03ab3ecb079391909f3978297ad307e76306ef7eb5a87a9437cf",
"bytes": 10755689,
"members": 77,
"payloadBytes": 12361849,
"completedRuns": [
"attempt-6",
"clipping-negative-1",
"clipping-positive-diagnostic-1",
"nested-sync-diagnostic-1",
"editor-patch-check-1"
],
"commandReceipts": 8,
"inputArchivesVerified": 5,
"sourceReadbacks": 73,
"allMemberBytesAndCrcVerified": true,
"scope": "Completed source gates and bounded experiments only; not candidate acceptance or native paint."
}
@@ -0,0 +1,145 @@
"""Archive only explicitly selected completed receipts; execute no project code."""
import hashlib
import io
import json
from pathlib import Path
import zipfile
ROOT = Path(__file__).resolve().parents[2]
OUT = Path(__file__).resolve().parent
PREFIX = "source-rename-completed-evidence/"
RUNS = ["attempt-6", "clipping-negative-1", "clipping-positive-diagnostic-1",
"nested-sync-diagnostic-1", "editor-patch-check-1"]
payload = {}
originals = {}
checks = []
def sha(data):
return hashlib.sha256(data).hexdigest()
def encoded(value):
return (json.dumps(value, ensure_ascii=True, indent=2) + "\n").encode()
def add(source, target):
path = ROOT / source
data = path.read_bytes()
assert target not in payload
assert path.suffix.lower() not in {".exe", ".dll", ".pyc"}
payload[target] = data
originals[str(path)] = data
for run in RUNS:
directory = ROOT / ".local/source-rename-integration-20260912" / run
names = ["inputs.zip", "inputs.json", "environment.json"]
phases = ["clippy", "tests", "timing", "gui"] if run == "attempt-6" else [""]
if run == "attempt-6":
names.append("complete.json")
complete = json.loads((directory / "complete.json").read_bytes())
assert complete["inputsUnchanged"] and complete["gates"] == phases
for phase in phases:
receipt_name = phase + "-result.json" if phase else "result.json"
receipt = json.loads((directory / receipt_name).read_bytes())
assert receipt["finished"] and receipt["inputsUnchanged"]
assert receipt["exitCode"] == (101 if run == "clipping-negative-1" else 0)
names.append(receipt_name)
for stream in ["stdout", "stderr"]:
log = (phase + "-" if phase else "") + stream + ".log"
assert sha((directory / log).read_bytes()) == receipt[stream + "Sha256"]
names.append(log)
checks.append({"run": run, "phase": phase or "command", "exitCode": receipt["exitCode"],
"finished": receipt["finished"], "command": receipt["command"]})
manifest = json.loads((directory / "inputs.json").read_bytes())
raw = (directory / "inputs.zip").read_bytes()
assert sha(raw) == manifest["archiveSha256"]
with zipfile.ZipFile(io.BytesIO(raw)) as inner:
expected = {entry["path"]: entry for entry in manifest["files"]}
assert len(inner.namelist()) == len(set(inner.namelist())) == len(expected)
assert set(inner.namelist()) == set(expected) and inner.testzip() is None
for name, entry in expected.items():
assert not Path(name).is_absolute() and ".." not in Path(name).parts
assert Path(name).suffix.lower() not in {".exe", ".dll", ".pyc"}
data = inner.read(name)
assert len(data) == entry["bytes"] and sha(data) == entry["sha256"]
checks.append({"run": run, "inputArchiveSha256": sha(raw), "inputMembers": len(expected),
"allInputBytesAndCrcVerified": True})
for name in names:
add(directory.relative_to(ROOT) / name, "runs/" + run + "/" + name)
diagnosis = ".local/source-rename-latency-diagnosis-20260912/"
notes = ["notes.md", "read-bindings.json", "nested-summary.json", "summarize.py",
"editor-initialization-candidates.md", "editor-initialization-bindings.json",
"same-line-patch-assessment.md", "editor-patch-independent-review.md",
"editor-patch-review-bindings.json", "prepare-instrumentation.ps1",
"candidate/editor_patch.rs", "candidate/README.md"]
for name in notes:
add(diagnosis + name, "diagnosis/" + name)
for path in sorted((ROOT / diagnosis / "instrumentation").rglob("*")):
if path.is_file():
add(path.relative_to(ROOT), "diagnosis/instrumentation/" + path.relative_to(ROOT / diagnosis / "instrumentation").as_posix())
for name in ["README.md", "source_rename.rs", "controller-tests.rs", "preview_glyph_tests.rs", "base-hashes.json", "staged-hashes.json"]:
add(".local/source-rename-preview-clipping-20260912/" + name, "clipping-stage/" + name)
for name in ["native-preview-clipping-review.md", "native-preview-clipping-bindings.json", "staged-clipping-review.md", "staged-clipping-review-bindings.json"]:
add(".local/source-rename-controller-independent-review-20260912/" + name, "reviews/" + name)
for name in ["gate.py", "focused.py"]:
add(".local/source-rename-integration-20260912/" + name, "helpers-current-readback/" + name)
assert sha(payload["diagnosis/candidate/editor_patch.rs"]) == "f301b8a043916b69dccb176da527a50ee85124b7e8b1da18921e4a0374a5153b"
# Bind the corrected helper from the completed check snapshot, never moving live source.
with zipfile.ZipFile(io.BytesIO(payload["runs/editor-patch-check-1/inputs.zip"])) as inner:
corrected = inner.read("crates/oa-desktop/src/app/source_rename/editor_patch.rs")
assert sha(corrected) == "049c9774c1ca28cda01f9a8e024604bef282366aa52c53c17c1918dbd09c3441"
negative = payload["runs/clipping-negative-1/stderr.log"].decode()
assert "source glyph under scrollbar" in negative and "cluster=92..93" in negative
native_path = "harness/experiments/source-alias-rename-native-20260912/source-rename-native-attempt-6-20260912.zip"
native = (ROOT / native_path).read_bytes()
assert sha(native) == "77adda5a33eb1def6dab23352ca0ab172300ea65fc21d2c215d545d7fcce0d08"
gui = json.loads(payload["runs/attempt-6/gui-result.json"])["binary"]
summary = {"scope": "Completed source gates and bounded experiments only; not candidate acceptance or native paint.",
"checks": checks, "externalBindings": [{"path": native_path, "sha256": sha(native), "bytes": len(native), "included": False},
{"path": ".local/source-rename-integration-20260912/attempt-6/arcadia-studio.exe", "sha256": gui["sha256"], "bytes": gui["bytes"], "included": False}],
"correctedHelperFromCheckInputSha256": sha(corrected),
"excluded": ["editor-patch-tests-1", "next-layout evaluator", "executable/DLL bytes", "private profiles", "caches", "duplicate native trial archive"]}
payload["SUMMARY.json"] = encoded(summary)
payload["INDEX.md"] = b"""# Completed alias source gates and bounded experiments
This private archive preserves five completed runs only. It is not a release or acceptance of an editor-reuse candidate. Native trial evidence is separately versioned and SHA-bound in SUMMARY.json, without duplicate payload.
| Run | Meaning |
| --- | --- |
| attempt-6 | Four successful Windows source gates: Clippy, tests, existing full Confirm timing, GUI executable build. The GUI JSON records the external binary; building it is not native acceptance. |
| clipping-negative-1 | Expected test failure (101): original layout allows actual shaped declaration glyph cluster92..93 beneath the scrollbar. |
| clipping-positive-diagnostic-1 | Successful focused rename tests with corrected preview layout and temporary timing instrumentation in source. This is an experimental capture, not clean production acceptance. |
| nested-sync-diagnostic-1 | Successful ignored real-Confirm timing experiment with nested instrumentation. Inclusive phase levels must not be added together; no GPU, first-paint or native responsiveness claim. |
| editor-patch-check-1 | Successful cargo check of corrected reuse helper integration only. It does not execute helper behavior, later layout timing or native rendering. |
Every run has its exact inputs.zip, complete membership/hash manifest, environment, commands/receipts and raw logs. All eight command receipt log hashes and all five nested ZIP memberships/member bytes/CRCs were independently checked during construction. Inputs manifests bind historical uncommitted snapshots; baseCommit alone is not their source identity.
diagnosis/instrumentation preserves removed diagnostic baseline/modified files, exact patch, bindings and generator. Historical notes retain their original time-scoped claims; later receipts qualify earlier hypotheses. diagnosis/candidate/editor_patch.rs is frozen f301b8a0 and has the known after-only LFCR counterexample documented in editor-patch-independent-review.md. Its original README's broad fallback claim is superseded by that review. Corrected helper049c9774 is preserved inside editor-patch-check-1/inputs.zip. The review is static, not proof of executed correctness.
clipping-stage and reviews preserve the earlier proposed repair/evaluator and source review; the exact executed evaluator is in each run's inputs.zip. helpers-current-readback are archive-time helper source snapshots, not independently proven historical executed versions. Historical absolute paths are evidence, not portable execution instructions. Reproduce with the recorded Windows compiler/dependencies and exact source snapshot; do not run relocated helpers blindly.
No current editor-patch-tests-1 or subsequent layout evaluation is included. No executables, DLLs, caches or private profiles are included, and no native trial payload is duplicated. PAYLOAD-MANIFEST.json covers all members except itself; external archive-result.json binds the entire archive.
"""
add(Path(__file__).relative_to(ROOT), "archive-tools/build_archive.py")
payload["READBACK-SOURCES.json"] = encoded([{"path": str(Path(path).relative_to(ROOT)), "sha256": sha(data), "bytes": len(data)} for path, data in originals.items()])
payload["PAYLOAD-MANIFEST.json"] = encoded({"selfExcluded": "PAYLOAD-MANIFEST.json", "members": [{"path": name, "bytes": len(data), "sha256": sha(data)} for name, data in sorted(payload.items())]})
archive = OUT / "source-rename-completed-evidence-20260912.zip"
with zipfile.ZipFile(archive, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zipped:
for name, data in sorted(payload.items()):
info = zipfile.ZipInfo(PREFIX + name, date_time=(2026, 9, 12, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
zipped.writestr(info, data)
with zipfile.ZipFile(archive) as zipped:
assert zipped.testzip() is None and set(zipped.namelist()) == {PREFIX + n for n in payload}
for name, data in payload.items():
assert zipped.read(PREFIX + name) == data
for path, data in originals.items():
assert Path(path).read_bytes() == data, "Source changed during archive: " + path
receipt = {"archive": archive.name, "sha256": sha(archive.read_bytes()), "bytes": archive.stat().st_size,
"members": len(payload), "payloadBytes": sum(map(len, payload.values())), "completedRuns": RUNS,
"commandReceipts": 8, "inputArchivesVerified": 5, "sourceReadbacks": len(originals),
"allMemberBytesAndCrcVerified": True, "scope": summary["scope"]}
with (OUT / "archive-result.json").open("x", encoding="utf-8") as stream:
json.dump(receipt, stream, indent=2)
print(json.dumps(receipt))
@@ -0,0 +1,11 @@
# Independent archive verification — PASS
2026-09-12, `/root/publication_review`. No discrepancies found. Read-only verification of archive/original bytes; no archived helper, project code, Cargo or native application was executed. See `independent-verification.json` and the separate `independent_verify.py` evaluator.
- Whole ZIP matches `archive-result.json`: SHA256 `2282e4e755bb03ab3ecb079391909f3978297ad307e76306ef7eb5a87a9437cf`, 10,755,689 bytes, 77 members, 12,361,849 uncompressed payload bytes.
- Complete outer manifest membership, every payload hash/length and all CRCs pass. All five nested input ZIPs pass exact membership, every input hash/length and CRC: 513/514/514/514/515 members respectively. No duplicate or unsafe paths, executable/DLL/cache/profile payloads, or nested native archive duplicates were found.
- All eight completed command receipts agree with their raw log hashes and summary entries. All 73 original-source readbacks are byte-identical, including the archive builder. External native ZIP `77adda5a…` and preserved executable `d1ec6305…` match their complete SHA256 and byte bindings.
- Raw outcomes match the stated historical scope: attempt6 has 796 tests passed, zero failed, two ignored, plus successful strict Clippy, separate ignored timing and executable build. The clipping negative control fails with the recorded glyph cluster92..93 beneath the scrollbar. The corrected-layout diagnostic run passes 33 focused tests; nested timing passes its one experiment. Editor-patch-check-1 is a successful **check**, not executed behavior.
- The original candidate `f301b8a0…`, its documented LFCR finding, and corrected helper `049c9774…` inside the completed check snapshot are correctly distinguished. Staged clipping hashes and nested timing summary-to-log binding pass.
Limitations are accurately stated in INDEX.md: this is historical evidence, not acceptance of the current reuse candidate, subsequent evaluator runs, corrected native layout, or release. Native trial payload remains separately bound. Helper sources labeled archive-time readbacks are not asserted to be the exact historical executed versions. Historical uncommitted input snapshots, rather than baseCommit alone, identify each tested source. No new native painting or latency claim follows from this verification.
@@ -0,0 +1,133 @@
{
"status": "PASS",
"checks": 2945,
"archiveSha256": "2282e4e755bb03ab3ecb079391909f3978297ad307e76306ef7eb5a87a9437cf",
"bytes": 10755689,
"members": 77,
"payloadBytes": 12361849,
"nestedInputs": {
"attempt-6": {
"members": 513,
"sha256": "03b5a9e3f4e9e220421320c09f1ecf46f811edf2e3c6c45dcd9522c6d78b8255",
"topLevelCounts": {
"Cargo.lock": 1,
"Cargo.toml": 1,
"build": 3,
"crates": 275,
"docs": 18,
"examples": 51,
"harness": 164
}
},
"clipping-negative-1": {
"members": 514,
"sha256": "1a59b58373d615a534244881a931f4423f590f04e0e632c986bf2a93af7d287d",
"topLevelCounts": {
"Cargo.lock": 1,
"Cargo.toml": 1,
"build": 3,
"crates": 276,
"docs": 18,
"examples": 51,
"harness": 164
}
},
"clipping-positive-diagnostic-1": {
"members": 514,
"sha256": "fc899e533e04317d0ba27dfa9f1bdfbfca77d3dede8478c45480f0edb19931a0",
"topLevelCounts": {
"Cargo.lock": 1,
"Cargo.toml": 1,
"build": 3,
"crates": 276,
"docs": 18,
"examples": 51,
"harness": 164
}
},
"nested-sync-diagnostic-1": {
"members": 514,
"sha256": "5bbd5145f6eea69fabe5cbfa3da14f059cf4446de49072f8714a5dc709d35cfa",
"topLevelCounts": {
"Cargo.lock": 1,
"Cargo.toml": 1,
"build": 3,
"crates": 276,
"docs": 18,
"examples": 51,
"harness": 164
}
},
"editor-patch-check-1": {
"members": 515,
"sha256": "1b18763ba3f74cbff0e842ff51b58879a6d7f82daac4ce65086b8c579ae0b272",
"topLevelCounts": {
"Cargo.lock": 1,
"Cargo.toml": 1,
"build": 3,
"crates": 277,
"docs": 18,
"examples": 51,
"harness": 164
}
}
},
"commandReceipts": [
{
"run": "attempt-6",
"phase": "clippy",
"exitCode": 0
},
{
"run": "attempt-6",
"phase": "tests",
"exitCode": 0
},
{
"run": "attempt-6",
"phase": "timing",
"exitCode": 0
},
{
"run": "attempt-6",
"phase": "gui",
"exitCode": 0
},
{
"run": "clipping-negative-1",
"phase": "command",
"exitCode": 101
},
{
"run": "clipping-positive-diagnostic-1",
"phase": "command",
"exitCode": 0
},
{
"run": "nested-sync-diagnostic-1",
"phase": "command",
"exitCode": 0
},
{
"run": "editor-patch-check-1",
"phase": "command",
"exitCode": 0
}
],
"originalReadbacks": 73,
"originalDeltas": [],
"externalBindings": [
{
"path": "harness/experiments/source-alias-rename-native-20260912/source-rename-native-attempt-6-20260912.zip",
"sha256": "77adda5a33eb1def6dab23352ca0ab172300ea65fc21d2c215d545d7fcce0d08",
"bytes": 3221627
},
{
"path": ".local/source-rename-integration-20260912/attempt-6/arcadia-studio.exe",
"sha256": "d1ec63050e95513064155e9d04f443d95667b1e468dcdbb3b810dad379504814",
"bytes": 113854464
}
],
"failures": [],
"scope": "Independent byte/CRC/membership and receipt verification only; no archived or production code executed."
}
@@ -0,0 +1,140 @@
"""Read archive/original bytes only; never import or execute archived helpers."""
from pathlib import Path, PurePosixPath, PureWindowsPath
from collections import Counter
import hashlib
import io
import json
import zipfile
root = Path(__file__).resolve().parents[2]
folder = Path(__file__).resolve().parent
receipt = json.loads((folder / 'archive-result.json').read_bytes())
raw = (folder / receipt['archive']).read_bytes()
sha = lambda b: hashlib.sha256(b).hexdigest()
failures = []
checks = 0
def check(ok, message):
global checks
checks += 1
if not ok:
failures.append(message)
def safe(name):
pos = PurePosixPath(name)
win = PureWindowsPath(name)
return not pos.is_absolute() and not win.is_absolute() and not win.drive and '..' not in pos.parts and '\\' not in name
def verify_zip(z, label):
names = z.namelist()
check(len(names) == len(set(names)), label + ': duplicate member')
check(z.testzip() is None, label + ': CRC')
check(all(safe(n) for n in names), label + ': unsafe member path')
check(all(not n.endswith('/') for n in names), label + ': unexpected directory member')
check(all(PurePosixPath(n).suffix.lower() not in {'.exe', '.dll', '.pyc'} for n in names), label + ': executable/cache member')
check(all(not ({'node_modules', 'target', '.git', '__pycache__', 'profile', 'profiles', 'cache', 'caches'} & set(PurePosixPath(n).parts)) for n in names), label + ': out-of-scope directory')
return names
check(sha(raw) == receipt['sha256'], 'whole archive SHA')
check(len(raw) == receipt['bytes'], 'whole archive bytes')
prefix = 'source-rename-completed-evidence/'
z = zipfile.ZipFile(io.BytesIO(raw))
names = verify_zip(z, 'outer')
check(len(names) == receipt['members'] == 77, 'outer member count')
check(all(n.startswith(prefix) for n in names), 'outer prefix')
payload = {n[len(prefix):]: z.read(n) for n in names}
check(sum(map(len, payload.values())) == receipt['payloadBytes'], 'outer payload bytes')
manifest = json.loads(payload['PAYLOAD-MANIFEST.json'])
entries = manifest['members']
check(manifest['selfExcluded'] == 'PAYLOAD-MANIFEST.json', 'manifest self exclusion')
check(len(entries) == len({e['path'] for e in entries}), 'manifest duplicate entry')
check(set(e['path'] for e in entries) == set(payload) - {'PAYLOAD-MANIFEST.json'}, 'manifest complete membership')
for entry in entries:
data = payload[entry['path']]
check(len(data) == entry['bytes'] and sha(data) == entry['sha256'], 'manifest member: ' + entry['path'])
source_maps = [
('.local/source-rename-latency-diagnosis-20260912/', 'diagnosis/'),
('.local/source-rename-preview-clipping-20260912/', 'clipping-stage/'),
('.local/source-rename-controller-independent-review-20260912/', 'reviews/'),
]
source_entries = json.loads(payload['READBACK-SOURCES.json'])
check(len(source_entries) == receipt['sourceReadbacks'] == 73, 'readback count')
original_deltas = []
for entry in source_entries:
source = entry['path'].replace('\\', '/')
check(safe(source), 'unsafe original path: ' + source)
if source.endswith('/build_archive.py'):
member = 'archive-tools/build_archive.py'
elif source in {'.local/source-rename-integration-20260912/gate.py', '.local/source-rename-integration-20260912/focused.py'}:
member = 'helpers-current-readback/' + source.rsplit('/', 1)[1]
elif source.startswith('.local/source-rename-integration-20260912/'):
member = 'runs/' + source.removeprefix('.local/source-rename-integration-20260912/')
else:
mapped = [target + source.removeprefix(base) for base, target in source_maps if source.startswith(base)]
check(len(mapped) == 1, 'original target mapping: ' + source)
if not mapped:
continue
member = mapped[0]
archived = payload[member]
check(len(archived) == entry['bytes'] and sha(archived) == entry['sha256'], 'readback archive binding: ' + member)
actual = (root / source).read_bytes()
if actual != archived:
original_deltas.append({'path': source, 'currentSha256': sha(actual), 'archiveSha256': sha(archived)})
check(not original_deltas, 'original source byte differences')
summary = json.loads(payload['SUMMARY.json'])
runs = receipt['completedRuns']
check(runs == ['attempt-6', 'clipping-negative-1', 'clipping-positive-diagnostic-1', 'nested-sync-diagnostic-1', 'editor-patch-check-1'], 'completed run scope')
check({PurePosixPath(n).parts[1] for n in payload if n.startswith('runs/')} == set(runs), 'actual run membership')
nested = {}
commands = []
for run in runs:
start = f'runs/{run}/'
manifest = json.loads(payload[start + 'inputs.json'])
data = payload[start + 'inputs.zip']
check(sha(data) == manifest['archiveSha256'], run + ': input ZIP binding')
inner = zipfile.ZipFile(io.BytesIO(data))
inner_names = verify_zip(inner, run)
expected = manifest['files']
check(len(expected) == len({e['path'] for e in expected}), run + ': duplicate input manifest entry')
check(set(inner_names) == {e['path'] for e in expected}, run + ': input membership')
for entry in expected:
item = inner.read(entry['path'])
check(len(item) == entry['bytes'] and sha(item) == entry['sha256'], run + ': ' + entry['path'])
nested[run] = {'members': len(inner_names), 'sha256': sha(data), 'topLevelCounts': dict(Counter(PurePosixPath(n).parts[0] for n in inner_names))}
recorded = [r for r in summary['checks'] if r['run'] == run and 'inputArchiveSha256' in r]
check(len(recorded) == 1 and recorded[0]['inputArchiveSha256'] == sha(data) and recorded[0]['inputMembers'] == len(inner_names), run + ': summary input binding')
phases = ['clippy', 'tests', 'timing', 'gui'] if run == 'attempt-6' else ['']
for phase in phases:
stem = phase + '-' if phase else ''
result = json.loads(payload[start + stem + 'result.json'])
check(bool(result['finished']) and result['inputsUnchanged'] and result['started'] < result['finished'], run + ': completion ' + phase)
check(result['exitCode'] == (101 if run == 'clipping-negative-1' else 0), run + ': exit ' + phase)
for stream in ['stdout', 'stderr']:
check(sha(payload[start + stem + stream + '.log']) == result[stream + 'Sha256'], run + ': log ' + phase + stream)
recorded = [r for r in summary['checks'] if r['run'] == run and r.get('phase') == (phase or 'command')]
check(len(recorded) == 1 and all(recorded[0][key] == result[key] for key in ['command', 'finished', 'exitCode']), run + ': command summary ' + phase)
commands.append({'run': run, 'phase': phase or 'command', 'exitCode': result['exitCode']})
if run == 'editor-patch-check-1':
corrected = inner.read('crates/oa-desktop/src/app/source_rename/editor_patch.rs')
check(sha(corrected) == summary['correctedHelperFromCheckInputSha256'] == '049c9774c1ca28cda01f9a8e024604bef282366aa52c53c17c1918dbd09c3441', 'corrected helper binding')
check(len(commands) == receipt['commandReceipts'] == 8, 'command count')
check(len(nested) == receipt['inputArchivesVerified'] == 5, 'input archive count')
complete = json.loads(payload['runs/attempt-6/complete.json'])
check(complete['inputsUnchanged'] and complete['gates'] == ['clippy', 'tests', 'timing', 'gui'], 'gate6 closure')
check(sha(payload['diagnosis/candidate/editor_patch.rs']) == 'f301b8a043916b69dccb176da527a50ee85124b7e8b1da18921e4a0374a5153b', 'original candidate binding')
check('source glyph under scrollbar' in payload['runs/clipping-negative-1/stderr.log'].decode() and 'cluster=92..93' in payload['runs/clipping-negative-1/stderr.log'].decode(), 'negative glyph failure receipt')
check(json.loads(payload['diagnosis/nested-summary.json'])['logSha256'] == sha(payload['runs/nested-sync-diagnostic-1/stdout.log']), 'nested timing summary log binding')
for entry in json.loads(payload['clipping-stage/staged-hashes.json']):
member = 'clipping-stage/' + PureWindowsPath(entry['Path']).name
check(sha(payload[member]) == entry['Hash'].lower(), 'staged layout source binding: ' + member)
external = []
for entry in summary['externalBindings']:
data = (root / entry['path']).read_bytes()
check(not entry['included'], 'external mistakenly marked included')
check(len(data) == entry['bytes'] and sha(data) == entry['sha256'], 'external binding: ' + entry['path'])
external.append({'path': entry['path'], 'sha256': sha(data), 'bytes': len(data)})
binary = json.loads(payload['runs/attempt-6/gui-result.json'])['binary']
check(external[1]['sha256'] == binary['sha256'] and external[1]['bytes'] == binary['bytes'], 'external binary gate receipt')
result = {'status': 'PASS' if not failures else 'FAIL', 'checks': checks, 'archiveSha256': sha(raw), 'bytes': len(raw), 'members': len(names), 'payloadBytes': sum(map(len, payload.values())), 'nestedInputs': nested, 'commandReceipts': commands, 'originalReadbacks': len(source_entries), 'originalDeltas': original_deltas, 'externalBindings': external, 'failures': failures, 'scope': 'Independent byte/CRC/membership and receipt verification only; no archived or production code executed.'}
(folder / 'independent-verification.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
print(json.dumps(result, indent=2))
@@ -0,0 +1,59 @@
{
"archive": "C:\\Users\\User\\Documents\\Git\\ARCADIA-Studio\\.local\\source-rename-native-evidence-20260912\\source-rename-native-attempt-6-20260912.zip",
"sha256": "77adda5a33eb1def6dab23352ca0ab172300ea65fc21d2c215d545d7fcce0d08",
"bytes": 3221627,
"members": 284,
"payloadBytes": 5375259,
"screenshots": {
"metadataFiles": 47,
"originalJpegFiles": 59
},
"verifiedUnchangedReadbacks": 285,
"exactFixtureReadbacks": [
{
"case": "simple",
"variant": "baseline",
"matchesManifest": "original_files",
"files": 4,
"bytes": 772
},
{
"case": "simple",
"variant": "expected",
"matchesManifest": "expected_files",
"files": 4,
"bytes": 786
},
{
"case": "simple",
"variant": "work",
"matchesManifest": "expected_files",
"files": 4,
"bytes": 786
},
{
"case": "representative",
"variant": "baseline",
"matchesManifest": "original_files",
"files": 37,
"bytes": 294617
},
{
"case": "representative",
"variant": "expected",
"matchesManifest": "expected_files",
"files": 37,
"bytes": 294641
},
{
"case": "representative",
"variant": "work",
"matchesManifest": "original_files",
"files": 37,
"bytes": 294617
}
],
"zipCrcAndAllMemberBytesVerified": true,
"scope": "Completed attempt-6 native trial only; partial native outcome, not acceptance or release.",
"binarySha256": "d1ec63050e95513064155e9d04f443d95667b1e468dcdbb3b810dad379504814"
}
@@ -0,0 +1,20 @@
# Independent archive review
Reviewer: Codex-9e8r6t /root/native_archive. Reviewed 2026-09-12. PASS for archival integrity and claim scope; this is not native acceptance.
Reviewed archive: source-rename-native-attempt-6-20260912.zip
- SHA256: 77adda5a33eb1def6dab23352ca0ab172300ea65fc21d2c215d545d7fcce0d08
- ZIP size: 3,221,627 bytes; 284 unique members.
- ZIP CRC check passed. Exact manifest membership and all 283 payload byte lengths/SHA256 values passed; PAYLOAD-MANIFEST.json correctly excludes itself.
- All 59 original JPEGs and 47 metadata files match the original trial directory byte-for-byte, with exact membership.
- All six physical fixture trees match the preauthored fixture manifest: simple baseline/expected/work contain four files each; representative baseline/expected/work contain 37 each. Simple work matches expected; representative work remains baseline. Physical support files are retained.
- All five saved-disk verification receipts report exit 0, no failure, exact physical-byte match and unchanged-by-oracle. Their expected variants, four-file maps, pinned oracle/DLL/binary hashes, and stdout/stderr hashes agree with the archived evidence. Their logs report exact model/identity/four reachable sources and four exact disk files.
- Closure receipt binds PID 9108, exit 0, unchanged binary/runtime and SHA256 values of both empty raw logs.
- Historical launcher SHA256 cf65065d18c110a029ec4dc6bbf712cfedc0b9970992b42cb158e676a289b343 verified. Comparison to the current launcher shows only the later profile/Desktop mkdir-list entry; the archive accurately describes the historical helper as a hash-proved reconstruction.
INDEX.md and SUMMARY.json explicitly identify the minimum-size preview clipping failure and partial native outcome. They do not claim representative native rename, immediate Undo Rename acceptance, unsaved-memory inspection by disk oracles, or acceptance of a later repair. The saved Undo/Redo evidence concerns model Undo/Redo with subsequent saved-disk checks.
No executable, DLL, private-profile directory or cache payload is included. External binary/source-build bindings remain separate; archived relocated helpers are not represented as portable launch instructions.
This review used read-only archive/hash/CRC comparisons, receipt inspection and comparison with original files. No Cargo, compiler, native application, oracle, GUI, network or production edit was executed. This note records that completed review without rerunning it.
@@ -0,0 +1,20 @@
{
"archive": "source-rename-refresh-evidence-20260912.zip",
"sha256": "d46aacbba1dfccec64b195482e2857c97ceefecad6b0176c62c73c50964e18ba",
"bytes": 6411947,
"members": 37,
"payloadBytes": 7201600,
"completedRuns": [
"editor-patch-tests-2",
"editor-patch-timing-1",
"attempt-7"
],
"commandReceipts": 6,
"inputArchivesVerified": 3,
"inputMembersEach": 516,
"exactThreeWayInputMembershipAndBytes": true,
"originalReadbacks": 34,
"allMemberBytesAndCrcVerified": true,
"externalBinarySha256": "2486eecc00d8de9160ecd930f69394e00b1a1ce102d76fb776b978db33414ed3",
"scope": "Windows debug source gates and bounded timing only; corrected native trial not yet accepted."
}
@@ -0,0 +1,52 @@
{
"scope": "Independent archive byte/CRC/provenance review only; no execution of builders, project code, native app or gate tools. No corrected native acceptance.",
"archiveSha256": "d46aacbba1dfccec64b195482e2857c97ceefecad6b0176c62c73c50964e18ba",
"archiveBytes": 6411947,
"members": 37,
"manifestPayloadsVerified": 36,
"originalReadbacks": 34,
"nestedInputArchives": 3,
"nestedInputMembersEach": 516,
"exactThreeWayInputMembershipAndBytes": true,
"allCrcsAndMemberHashesPassed": true,
"completedCommands": [
{
"run": "editor-patch-tests-2",
"phase": "",
"finished": "2026-09-12T13:51:44.023824+00:00"
},
{
"run": "editor-patch-timing-1",
"phase": "",
"finished": "2026-09-12T13:54:04.503303+00:00"
},
{
"run": "attempt-7",
"phase": "clippy",
"finished": "2026-09-12T14:00:02.795856+00:00"
},
{
"run": "attempt-7",
"phase": "tests",
"finished": "2026-09-12T14:09:16.517298+00:00"
},
{
"run": "attempt-7",
"phase": "timing",
"finished": "2026-09-12T14:10:05.679440+00:00"
},
{
"run": "attempt-7",
"phase": "gui",
"finished": "2026-09-12T14:15:41.805763+00:00"
}
],
"externalBinary": {
"path": ".local/source-rename-integration-20260912/attempt-7/arcadia-studio.exe",
"sha256": "2486eecc00d8de9160ecd930f69394e00b1a1ce102d76fb776b978db33414ed3",
"bytes": 113879552,
"included": false
},
"producerReceiptSha256": "ec91311ea6850745960072571d088415df4d3f3210e58c0dad1bd4f0ee7135ad",
"builderSha256": "6fbfca25bf38c459e723f30b9333786372a5207c937e34b6204d6f8161baca11"
}
@@ -0,0 +1,15 @@
# Independent refresh archive review
2026-09-12; Codex-9e8r6t /root/native_archive. PASS for archive integrity, original bindings and stated scope. No builder/project code, Cargo, native application or gate tool was executed. The active native trial was not touched or evaluated.
Archive SHA256 d46aacbba1dfccec64b195482e2857c97ceefecad6b0176c62c73c50964e18ba; 6,411,947 bytes;37 unique members. This agrees with archive-result.json (the earlier dispatch typo is not authoritative).
ZIP CRC and all36 manifest payload byte lengths/SHA256 values passed, with exact membership and correct self-exclusion. All34 ORIGINAL-SOURCES bindings match both archived member bytes and current preserved originals; adjacent INDEX.md/PAYLOAD-MANIFEST.json match their archived versions. All three nested input ZIP hashes, CRCs and516-member manifests passed. Exact member sets and bytes are equal across tests-2, timing-1 and attempt-7 despite distinct whole ZIP hashes.
All six command receipts have terminal timestamps, exit0 and inputsUnchanged=true; raw stdout/stderr hashes agree. Attempt-7 complete.json lists the four completed Clippy/tests/timing/GUI gates. Its full test log reports802 passed,0 failed,3 ignored. GUI completion is14:15:41.805763UTC. Static App-review source bindings match the exact archived inputs; the earlier execution review's receipt/log/input bindings also match. Its then-running attempt-7 language is correctly identified as historical in the index.
The external preserved binary independently matches2486eecc00d8de9160ecd930f69394e00b1a1ce102d76fb776b978db33414ed3 and113,879,552 bytes. Binary bytes are excluded. No executable/DLL/cache/profile payload was found, including nested input archives.
Builder inspected as source only: explicit completed-run whitelist, exclusive outputs, exact input/log/source checks, original readbacks and no project execution. The index honestly limits conclusions to completed Windows debug source gates and bounded timing. It distinguishes ordinary sync from optimized Confirm, fixed-fixture timing from native/GPU/first-paint results, and static reviews from executable assertions. It makes no corrected-native acceptance or later-source claim. The new native trial remains separate.
Detailed bindings/check outcomes: independent-review-receipt.json. Original archive, builder and producer receipt are unchanged.
@@ -39,11 +39,11 @@ Resolve only an alias token or live `@` use under the exact caret/selection, usi
Accepted-but-unsaved documents are eligible. Preview compares against the **accepted source**, not the last disk baseline. Stabilization/migration already accepted by ordinary Open/Apply retains its fixed IDs; this rename must add no new ID, migration, default, file or include change. Save may later include earlier unsaved accepted edits as well as this rename; the modal says that it only previews this operation.
**Form and preview.** Capture invocation ID, document snapshot `Arc`, document revision, workspace session/revision, active path and exact origin cursor/alias span/UUID. Keep the replacement string raw. Invalid syntax, reserved/colliding aliases and same-alias input produce useful inline feedback; same alias is “No change” with Confirm unavailable and no history/reset. Duplicate engineering names are valid and never disambiguate identity.
**Form and preview.** Capture invocation ID, document snapshot `Arc`, document revision, workspace session/revision, active path and exact origin cursor/alias span/UUID. Keep the replacement string raw; do not silently normalize pasted text. The single-line field explicitly rejects a whole paste containing control characters, retaining its text and selection while invalidating approval and pending intent. Invalid syntax, reserved/colliding aliases and same-alias input produce useful inline feedback; same alias is “No change” with Confirm unavailable and no history/reset. Duplicate engineering names are valid and never disambiguate identity.
Explicit Preview starts at most one worker. It prepares `SetAlias(target_uuid, replacement)` against the pinned accepted snapshot with the desktop limits. Require full candidate Project equality to an independently formed alias-only expectation, identity-map identity for every surviving record, identical file membership/entry and ownership, and unchanged non-alias fields. Preserve old/new source via the two snapshots, not duplicated whole-file strings in every row. Updater errors leave accepted data and all drafts intact.
Preview rows are derived from every changed file in the complete candidate. Because alias replacement cannot add/remove newlines, pair source lines by ordinal, collect every changed line and group nearby context into hunks; unexpected line-ending/line-count changes refuse rather than falling back to a lossy preview. The changed-line count is not presented as a count of semantic references. Proposed display admission is 256 changed files, 50,000 changed lines and 8 MiB of retained diff display data; exceeding a bound explains that no rename was applied. Page complete admitted hunks; never approve a truncated candidate. These are proposed editor limits, not new grammar limits. Do not use unbounded quadratic line diff or copy the CLI's single potentially huge middle hunk into one widget.
Preview rows are derived from every changed file in the complete candidate. Because alias replacement cannot add/remove newlines, pair source lines by ordinal, collect every changed line and group nearby context into hunks; unexpected line-ending/line-count changes refuse rather than falling back to a lossy preview. The changed-line count is not presented as a count of semantic references. Display admission is 256 changed files, 50,000 changed lines and 8 MiB of exact displayed source bytes (both versions of changed/context lines plus each path once); exceeding a bound explains that no rename was applied. Source stays in the immutable snapshots. Index metadata has a separate bound of seven retained line records per changed line (350,000 maximum), rather than being included in that 8 MiB source-byte count. This distinction was clarified during implementation review on September 12: sparse tiny-line changes can use more index memory than displayed source bytes. Page complete admitted hunks, lines and UTF-8-safe fragments of unusually long lines; never approve a truncated candidate. These are editor limits, not new grammar limits. Do not use unbounded quadratic line diff or copy the CLI's single potentially huge middle hunk into one widget.
**Stale and confirmation.** Every dialog event carries its invocation ID; Preview/Confirm also identify the exact replacement generation and preview ID. Reject old widget events before canceling or changing the current form. Worker completion must match the wanted job, invocation, replacement generation, original document snapshot/revision and exact workspace readback. Close hides the form immediately but retains the occupied worker slot until its completion; late results do not reopen it. A source edit, file/membership switch, reset, recovery, model transaction, Undo/Redo or replacement edit invalidates approval, even if later bytes happen to match again. The input field survives same-form invalidation for correction. Reopen/new-session IDs cannot reuse an old approval.
@@ -0,0 +1,350 @@
# Text alias rename — branch validation
Codex-9e8r6t `/root`, Windows, 2026-09-12. This records **uncommitted branch work**
over `be7a8cd8d7d63aa18e0196bbd36f9e646764c761`; it is not an integrated release
or native acceptance claim. [Issue 9](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/9)
owns the current task. The [design](release-source-alias-rename-design-20260911.md)
and [transaction critique](release-source-alias-rename-transaction-critique-20260911.md)
define the intended behavior and evaluators. Linux/WSL remains user-paused.
## Verification method
Root coordinates one Windows compiler job. The local toolchain environment is
`.local/toolchain/env.ps1`; `CARGO_BUILD_JOBS=1`. Commands use `--locked --offline`
and the Windows GNU LLVM development profile. The attempt helper
`.local/source-rename-integration-20260912/gate.py` preserves each attempt in an
exclusive directory, including raw input ZIP, complete scoped file membership,
per-file hashes, compiler/environment records, raw logs and stage receipts.
It verifies the same file membership and bytes before and after each command.
Its scopes include the workspace manifests, crates, build support, Cargo config,
documentation, examples and harness fixtures. These private evidence directories
are not yet published artifacts; preserve them until final evidence packaging.
The serial gates are strict Clippy for all desktop targets, the complete desktop
binary test suite, an explicit ignored representative timing experiment and
the matching desktop build. Attempts 1–5 ran tests before Clippy; attempt 6
moves Clippy first to catch lint failures before the longer suite. A failed
stage stops the attempt. Native checks
use a separately identified executable only after these gates pass.
## Earlier findings and verified results
The isolated Document/query trial initially omitted `build/windows_manifest.rs`
from its reconstruction and failed before tests. Its corrected `v2` capture
passed 8 alias-transaction, 13 existing Document and 20 query tests, finishing
at 11:20:55 UTC. This establishes those isolated seams only. The combined
`cargo check --locked --offline -p oa-desktop --tests` subsequently passed;
unused preview range accessors were removed after its warning.
Attempt 1 failed compilation on two mounted-test calls that attempted mutable
widget operations through `as_widget()`. Correcting those test calls to
`as_widget_mut()` allowed execution. Attempt 2 passed 791 tests, failed one and
ignored two. Its sole failure used an invalid property-field key, `name` instead
of `/name`, so it had never created the intended dirty draft. The fixture was
corrected and strengthened to assert retention of the exact `/name` draft value.
Neither finding justified a production behavior change.
Attempt 3 passed **792 tests, zero failed, two ignored**, finishing at
11:49:39.273922 UTC (165.53 seconds of test execution). Its captured inputs
remained unchanged. Raw stdout SHA-256:
`392379b23ca446ad1d617da25c640f2911a9ab643fd61d6b8fc15a72d346f92b`;
stderr: `f5b640295276418cb45226fe82f3dfdfe5f7ee018c1777516784f80d562620a3`.
The subsequent strict Clippy stage stopped on five diagnostics: a collapsible
search conditional, two constant platform/profile assertions in the timing
experiment, a test-case type-complexity diagnostic and field reassignment after
`Default` in a query test. The correction uses a let-chain, scopes the manual
timing module to Windows debug tests, names the case type and initializes the
query limit directly. The platform-specific experiment does not prevent other
platforms or release profiles from compiling their applicable tests.
No timing or desktop-build stage ran in attempts 1–3. Passing attempt 3 does not
cover the subsequent paste guard described below.
Attempt 4 passed 792 tests, failed the newly added normal-paste assertion and
ignored two, finishing at 12:03:16.113761 UTC (167.39 seconds of test execution).
The rejection cases reached their expected outcomes before the normal-paste
case failed. The attempt's captured inputs remained unchanged; no subsequent
gate ran. Its stdout SHA-256 is
`62cc9471678fabe08fc32db0e46665f1b9babd1d70f814371995c96a6b5de430`.
Root and the implementation owner independently traced the failure to the test
fixture: Iced calls the test operation's selection callback before its focus
callback, and `focus()` moves the cursor to the end. Thus the fixture erased its
own selection before pasting. The correction must focus and select separately,
assert a real nonempty selection and retain the exact replacement oracle. This
is an evaluator defect, not a reason to change valid-paste production behavior.
## Clipboard finding and correction
Root inspected the actual dependency source, Iced `iced_widget` 0.14.2
`src/text_input.rs`, whose paste path filters `char::is_control` before invoking
either input callback. Consequently, a pasted `foo\nbar` could silently become
the valid alias `foobar`. Merely validating the callback value or adding an
`on_paste` callback would miss the original input. This contradicted the
design's prohibition on silent replacement normalization.
The alias field now has a narrow widget adapter that checks the actual paste
shortcut before the child input handles it. It rejects the whole paste if it
contains control characters, retaining field text and selection, displaying
feedback and invalidating the previous preview approval and pending intent.
An occupied worker remains occupied until its matching completion. Permitted
first-paste input uses one captured clipboard value passed to the child; normal
Iced editing, focus and key-repeat behavior remain with the child widget.
No dependency, vendor or cached Iced source was changed.
Mounted evaluator cases cover newline, tab, CRLF and NUL refusal; unchanged
selection through feedback/rebuild; normal valid paste; exactly one actual
clipboard read; and refusal of an old confirmation. Independent review checks
the wrapper against the cached Iced implementation, with particular attention
to stored modifiers, focus, pending workers and repeated paste.
That review found another production counterexample: the wrapper initially
reset its modifier state on `KeyPressed.key == Escape`, whereas the child uses
its effective dispatch, including `modified_key` and earlier shortcut returns.
For `key=Escape, modified_key=Home`, the wrapper could clear Command while the
child retained it, allowing a following paste to bypass rejection. The
correction observes the child's actual focused-to-unfocused transition after
forwarding a key press instead of guessing its dispatch. Mounted tests must
exercise mismatched key fields, pending worker retention and the relevant
focus/enabled/modifier conditions. Held-key paste may reuse the child's earlier
admitted cache; the single-read claim applies to fresh clipboard reads.
The final bounded static review found no remaining concrete paste defect and
bound the corrected adapter, wrapper tests and controller tests to exact hashes
in `.local/source-rename-controller-independent-review-20260912/paste-resolution-bindings.json`.
The focused `source_rename::` run then passed **32 tests, zero failed, one
ignored**, finishing at 12:08:16.497392 UTC (3.20 seconds of test execution).
This includes the actual-selection correction, valid paste, the 20-condition
focus/enabled/modifier matrix, divergent key fields, held-key cache release and
pending-worker rejection. Raw logs and the command receipt are retained under
`.local/source-rename-integration-20260912/focused-paste-v2`.
## Remaining acceptance
Attempt 5 passed the full desktop suite: **796 passed, zero failed, two
ignored**, finishing at 12:11:20.769886 UTC (147.44 seconds of execution).
Inputs remained unchanged. Stdout SHA-256:
`38e9413b678de73fdc1e277be5313193002c81326f32e29bafdd4e45701fe322`;
stderr: `43c2d65557dd4392177fcb91e097ca375acfc796928e92a51b129c69892fb66d`.
Its Clippy stage subsequently found a preview helper used only by tests and an
obsolete `expect(dead_code)` on the now-used authored identity accessor. The
helper is now test-only and the obsolete expectation removed. Attempt 5 stopped
at 12:12:23.924779 UTC without timing/build execution; its Clippy stderr SHA-256
is `87a4858cf1d4116b1938268db07095c17b301e64a1e115f42a4020da633ea58f`.
Before attempt 6 the edited guide and generated HTML were aligned to the
repository's LF policy; no frozen evidence or fixture bytes were normalized.
Attempt 6 captures these final inputs, with lint first. The native launch
helper checks this same required gate order; its behavior otherwise remains
the independently reviewed launch protocol.
Attempt 6 passed strict all-target Clippy at 12:14:39.585030 UTC, then the
full suite (**796 passed, zero failed, two ignored**) at 12:18:12.718483 UTC
(172.07 seconds of test execution). The explicit timing experiment also passed
its complete-model/source/identity/history assertions at 12:18:36.171758 UTC.
All three stages verified unchanged captured inputs. The desktop build also
passed at 12:21:39.274814 UTC. Its preserved executable is 113,854,464 bytes,
SHA-256 `d1ec63050e95513064155e9d04f443d95667b1e468dcdbb3b810dad379504814`.
The 513-file raw input ZIP SHA-256 is
`03b5a9e3f4e9e220421320c09f1ecf46f811edf2e3c6c45dcd9522c6d78b8255`.
All four gates verified unchanged captured membership and bytes.
For the 30-file, 78,414-byte, 258-identity walkthrough, five measured Windows
debug trials after one warmup reported these median/range values in milliseconds:
| Phase | Median | Min–max |
| --- | ---: | ---: |
| Mint Document request | 0.092 | 0.052–0.170 |
| Worker Document preparation | 282.259 | 165.302–298.259 |
| Worker preview and origin | 13.429 | 10.763–23.969 |
| Guarded Document commit | 0.0109 | 0.0082–0.0229 |
| Application synchronization | 495.499 | 472.030–610.017 |
| Actual Confirm update | 571.893 | 433.909–1122.241 |
The phases and full Confirm use separate fresh fixtures with alternating trial
order; their values must not be added or subtracted as simultaneous timings.
Task polling, layout, GPU work and first paint are excluded. Fast snapshot
adoption does **not** establish a responsive UI: application refresh still takes
roughly half a second in these samples. Native assessment and a discriminating
refresh-phase diagnosis are needed before making a responsiveness claim. The
timing log SHA-256 is
`a063b67755b972e7f0b6a42c4af7fb9e1a41ecbda9775e1f40b031b8dd0c9a5c`.
Native fixtures in `.local/source-rename-native-20260912` preserve
independent baseline/work/expected trees for a four-source project and the
30-source engineering walkthrough. Their expected edits were authored by
literal role-specific replacements, preserving every physical supporting file.
Preparation-only oracle passes do not establish future GUI correctness.
Native acceptance must inspect complete preview access, focus and bounded
layout, cancellation, confirmation, model Undo/Redo, Save and reopen, comparing
the full saved Project, identities and source bytes against the authored oracle.
The reviewed launch helper preserves the identified executable and runtime,
uses a private profile and retains the child process handle until exit to record
the actual exit code and final logs.
## First native transaction trial and blocking findings
The identified attempt-6 executable ran in a private profile as PID 9108 from
12:22:14 UTC, with actual process exit zero recorded at 12:45:42.336483 UTC.
Both logs were empty; the executable and runtime DLL remained unchanged.
The private profile initially lacked a Desktop directory, causing a file-picker
notice. Creating that private directory resolved the harness setup issue.
The four-source Unicode-path project exercised F2 on the typed reference,
invalid alias feedback, Enter to preview, Enter again without confirmation,
both changed-file previews, minimum 1100×700 client layout, Escape cancellation,
explicit confirmation, Save, persistent model Undo/Save, Redo/Save and reopen.
The new alias was selected at the original typed reference after confirmation;
the same spelling in prose remained unchanged. Reopen showed the expected
`assess_damage` alias. Five independent saved-disk oracle runs passed: cancelled
baseline, renamed save, undone save, redone save and reopened result. Each
compared the complete Project, identities and all four exact physical files.
The representative 30-source native workflow and immediate Undo Rename button
were not exercised in this trial.
Native preview acceptance **failed**: screenshot
`trial-attempt-6/screenshots/032-simple-preview-minimum-bottom-0.jpg` shows the
final brace of the longer After declaration occluded by the vertical scrollbar.
Independent image/source review confirmed default Shrink width and a floating
scrollbar, plus inadequate wrapping for unbroken fragments. Byte-complete
preview indexes and rectangle-only layout checks did not catch this defect.
The correction must reserve scrollbar space, wrap unbroken fragments, and add
actual shaped-glyph/paint visibility checks before a new native trial.
Publication also needs byte-reproducible source. The provenance review verified
all 513 captured files but identified 13 Git-clean baseline files whose live
CRLF bytes differ from the LF bytes in HEAD. These are strict newline-only
differences, distinct from intentional alias changes. After closing the native
trial, root verified each current hash, Git-clean status and strict newline-only
equivalence, then aligned exactly those 13 ordinary files with their HEAD LF
bytes. The receipt is `aligned-reviewed-lf.json` in the integration evidence
directory. New checks/builds use new captures; attempt-6 and all earlier raw
archives remain unchanged and bound to their original bytes.
The new real-paragraph visibility evaluator compiled against the **old** layout
and failed as intended at 12:57:38.285740 UTC. It identified the exact native
declaration's final brace (UTF-8 cluster 92–93) at x591.398 with width6.598,
crossing the actual scrollbar boundary x587.996. Captured inputs remained
unchanged. This is a demonstrated regression falsifier, not a passing gate.
Receipt/logs: `clipping-negative-1` in the integration evidence directory;
stderr SHA-256 `2ac214f31252edeef4f33b64a46b11fb42dbf0c04848d38bb8730978d9d5ce10`.
The reviewed correction fills the preview width, reserves the scrollbar's
actual width plus spacing, and uses glyph-fallback wrapping. It leaves source
indexing and the transaction unchanged. A positive check is separate.
The corrected layout then passed all **33 focused rename tests**, zero failed,
one ignored, at 13:05:52.950223 UTC (11.89 seconds of test execution).
That capture included disabled-by-default temporary timing instrumentation;
the geometry and transaction tests did not enable it. Inputs remained unchanged.
Stdout SHA-256 `307bd915536983fc19102fcff39535df950cee06841d968f5be2092c091ccc76`.
The independently reviewed nested diagnostic subsequently passed the existing
full Project/source/identity/history/origin assertions in all warmup and measured
trials, finishing at 13:07:20.854282 UTC. It measured the same real Confirm
message path, with fixed-capacity timestamps enabled only around direct sync
or Confirm. In the whole-Confirm arm, five measured samples gave these medians:
actual update **1039.0 ms**, source Content assignment **996.7 ms** (814.4–1182.2),
validation **26.4 ms**, property refresh **6.3 ms**, and Workspace acceptance
**0.28 ms**. Each nested phase belongs to that same arm; earlier runs have
different absolute timings and are not a paired performance comparison.
Source Content assignment includes construction and destruction of the previous
editor. Layout, highlighting during draw and native paint remain excluded.
The raw log SHA-256 is
`a98877362ca52a024942803e0ab698a1fd84703d4512fcf7137c147a28817039`.
The temporary instrumentation was removed afterwards, restoring both exact
production baselines before implementing any candidate.
This evidence justifies a bounded display-refresh experiment: retain the laid-out
editor and apply complete, preflighted same-line changes only after the existing
Document commit succeeds. Every ordinary synchronization step remains shared;
incompatible line endings, stale display bytes or a failed exact final readback
fall back to reconstruction from accepted source. A review found that deleting
an entire line body could introduce a greedy LFCR boundary; both before and after
preflight now refuse that representation. The candidate resets highlighting from
line zero without changing text, and restores the same approved origin. It passed
`cargo check --locked --offline -p oa-desktop --tests` at 13:25:02.235871 UTC,
with unchanged captured inputs. Execution, first subsequent layout/highlighting
cost, native behavior and final gates remain separate acceptance requirements.
The user's new [Text UX issue 13](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/13)
also rules out adding permanent command clutter. The new separate Undo Rename
row has been removed; the existing model Undo control uses the guarded rename
action while it remains available. Broader compact-editor work is owned in that
issue and is not claimed complete by this local adjustment.
The completed native trial is preserved in the
[attempt-6 evidence archive](experiments/source-alias-rename-native-20260912/source-rename-native-attempt-6-20260912.zip),
with [archive receipt](experiments/source-alias-rename-native-20260912/archive-result.json)
and [independent verification](experiments/source-alias-rename-native-20260912/review.md).
Its 284 members occupy 3,221,627 compressed bytes; SHA-256
`77adda5a33eb1def6dab23352ca0ab172300ea65fc21d2c215d545d7fcce0d08`.
The archive retains all original captures, complete fixture trees, five saved
verification receipts, helper sources and clean-exit logs; executable/DLL bytes
are externally hash-bound. The gate inputs and provenance evidence are preserved
separately below. This archive describes the first trial only; later corrections
and execution do not turn its clipping failure into a passing native result.
## Corrected editor refresh execution
The next-layout evaluator initially failed to compile because its new focus call
lacked Iced's `Focusable` trait import. The failed `editor-patch-tests-1` capture
is preserved unchanged; no runtime result is claimed for it. After adding that
test-only import, `editor-patch-tests-2` passed **38 focused tests**, zero failed,
two ignored, at 13:51:44.023824 UTC. This includes exact editor text and line
endings, the LFCR refusal, retained-tree highlighter reset, real Confirm/history
checks and normal synchronization fallback. All captured inputs stayed unchanged.
Stdout SHA-256: `a25dd49c669c09936d1da7ddeba4f7d3d6b6a918b72cd39dde4df6f75d201344`.
On the same source, `editor-patch-timing-1` passed both ignored experiments at
13:54:04.503303 UTC. The real App Confirm update had median **46.0 ms**
(23.0–206.1 ms, five measured samples); ordinary `app_sync` deliberately retains
the reconstruction path and is not the same operation. The paired editor trial
used one warmup and five alternating fresh trials per arm, the 29,506-byte
traceability source, a retained widget tree, a 640×350 viewport, 14px monospace
font and 16px padding. Replacement plus next layout plus draw/highlighting had
median **35.5 ms** with reuse (13.6–73.4), versus **2782.7 ms** with reconstruction
(2697.7–3994.6). Exact source/line-ending/cursor checks and accepted alias
attributes, shaped glyph colors and visible glyph bounds passed after every arm.
This measures real text layout and highlighting, but excludes GPU/native paint
and is not an end-to-end production latency guarantee. Source inputs stayed
unchanged; stdout SHA-256:
`ae8d57e0d65084d71d92815c093607c7cd4d9d9166c562cec33a061b2fcba74c`.
Independent static review of the App seam found no actionable defect: commit
authority, ordinary synchronization order, fallback, metadata, histories and
guarded reveal remain intact. Native focus/reveal, the next text edit, corrected
preview rendering and full gates still require their own evidence.
The earlier completed gates and experiments are preserved separately in the
[historical evidence archive](experiments/source-alias-rename-completed-20260912/source-rename-completed-evidence-20260912.zip)
with its [independent review](experiments/source-alias-rename-completed-20260912/independent-review.md).
All 77 members, five nested source archives, eight receipt/log pairs and 73
original readbacks passed verification. ZIP SHA-256:
`2282e4e755bb03ab3ecb079391909f3978297ad307e76306ef7eb5a87a9437cf`.
That archive intentionally ends at the earlier check-only candidate; the newer
focused execution and timing captures are separate.
## Full corrected Windows gates
Attempt 7 completed unchanged at **14:15:41.805763 UTC**: strict desktop Clippy
with all targets and `-D warnings`, **802 desktop tests passed** (zero failed,
three ignored), the required isolated Confirm experiment passed, and the GUI
build passed. The repeated Confirm median was 71.9 ms (43.2–101.8); the separate
paired layout experiment above remains the rendering-cost evidence. Formatting
of all changed/new Rust files passed with `rustfmt --edition 2024 --check
--config skip_children=true`; `git diff --check` also passed.
The identified GUI is 113,879,552 bytes, SHA-256
`2486eecc00d8de9160ecd930f69394e00b1a1ce102d76fb776b978db33414ed3`,
built with the Windows GNU LLVM development profile, no optimization/debuginfo,
and debug assertions enabled. All 516 captured input files match the preceding
focused test and paired timing inputs byte for byte.
[Corrected refresh evidence](experiments/source-alias-rename-refresh-20260912/source-rename-refresh-evidence-20260912.zip)
preserves those three complete captures, receipts, raw logs and independent App
and execution reviews. Its [independent archive review](experiments/source-alias-rename-refresh-20260912/independent-review.md)
verified all 37 members, three nested source snapshots, six command receipts
and original bindings. ZIP SHA-256:
`d46aacbba1dfccec64b195482e2857c97ceefecad6b0176c62c73c50964e18ba`.
This is a source-verification checkpoint, not a released or fully native-accepted
milestone. The corrected native trial is separate and must retain its actual
workflow coverage and limitations.