Compare commits

...
Author SHA1 Message Date
sorokin.oleg.edu 6d99aacab8 docs: publish Process multiselect verification and native correction evidence 2026-09-23 06:51:41 -07:00
sorokin.oleg.edu b743a10d51 Make native group reorder discriminate singleton fallback
Prescribe inspected and pressed Card C after reverse membership selection. A singleton C drop is unchanged while the group changes order; preserve prior evaluator scope and test the unchanged negative outcome explicitly.
2026-09-23 06:27:39 -07:00
sorokin.oleg.edu ff712b2419 Preserve exact Process selection across definition navigation
Keep caller identity and property subjects aligned when opening and returning from qualified contributions, and when explicitly navigating to local references. Validate camera, source, history and read-only boundaries.
2026-09-23 06:25:50 -07:00
sorokin.oleg.edu b15345123a Bound Process payload sizes and capture rendered order feedback
Box the optional Process menu context and changed order command without changing identity or command semantics. Add opt-in actual WGPU readbacks to the split-event OA/SA reorder evaluator. Strict all-target lint, format and affected desktop paths pass; native acceptance follows.
2026-09-23 05:47:08 -07:00
sorokin.oleg.edu 1711bff650 Add exact Process selection and atomic column-slot group reorder
Preserve the full-desktop-1 captured source. Qualified previews inspect their exact subject read-only; group movement preserves source order and other columns. Native acceptance and strict-lint payload-size corrections follow separately.
2026-09-23 05:39:10 -07:00
73 changed files with 9196 additions and 148 deletions
@@ -0,0 +1,548 @@
//! Deterministic Process native fixture and independent complete-Project oracle.
//! Expected order is literal; no desktop reorder/layout planner is used here.
use oa_core::{source_project::*, *};
use std::{fs, io::Write, path::Path};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn id(alias: &str) -> Id {
Id::new_v5(
&Id::from_u128(0xc1192026_0923_5000_8000_000000002930),
alias.as_bytes(),
)
}
fn element(p: &mut Project, alias: &str, name: &str, kind: Kind, layer: Layer, parent: Option<Id>) {
p.elements.insert(
id(alias),
Element {
id: id(alias),
alias: alias.into(),
name: name.into(),
description: format!("Preserve engineering record {alias}."),
parent,
body: ElementBody::new(kind, layer).unwrap(),
},
);
}
fn occurrence(
p: &mut Project,
alias: &str,
name: &str,
layer: Layer,
owner: &str,
value: OccurrenceBody,
) {
element(p, alias, name, Kind::Occurrence, layer, Some(id(owner)));
let Some(SharedBody::Occurrence { body, .. }) =
p.elements.get_mut(&id(alias)).unwrap().shared_mut()
else {
panic!("Occurrence body");
};
*body = value;
}
fn set_steps(p: &mut Project, owner: &str, aliases: &[&str]) {
*p.elements.get_mut(&id(owner)).unwrap().steps_mut().unwrap() =
aliases.iter().map(|alias| id(alias)).collect();
}
fn sequence_link(
p: &mut Project,
alias: &str,
name: &str,
source: &str,
target: &str,
) -> Result<()> {
let old = p.relate(RelationKind::SequenceLink, name, id(source), id(target));
reidentify(p, old, id(alias))?;
let relation = p.relations.get_mut(&id(alias)).unwrap();
relation.alias = alias.into();
relation.description = format!("Preserve link {alias} exactly.");
if let RelationBody::SequenceLink { guard, .. } = &mut relation.body {
*guard = "ready".into();
}
Ok(())
}
fn fixture() -> Result<Project> {
let mut p = Project::empty();
p.id = id("project");
p.alias = "process_multiselect_native".into();
p.name = "Process group native".into();
p.description = "Select Card C then Shift-select Card A; drop after Card B. Other columns and reusable engineering records remain exact.".into();
for (layer, prefix, owner, name, owner_kind, work_kind) in [
(
Layer::Oa,
"oa",
"oa_process",
"01 OA group order",
Kind::Process,
Kind::Activity,
),
(
Layer::Sa,
"sa",
"sa_chain",
"SA chain - preserve",
Kind::FunctionalChain,
Kind::Function,
),
] {
element(&mut p, owner, name, owner_kind, layer, None);
let shared = format!("{prefix}_shared_work");
let downstream = format!("{prefix}_downstream_work");
element(
&mut p,
&shared,
"Shared request work",
work_kind,
layer,
None,
);
element(
&mut p,
&downstream,
"Downstream verification",
work_kind,
layer,
None,
);
for (suffix, label) in [
("a", "Card A"),
("u", "Downstream U"),
("b", "Card B"),
("v", "Downstream V"),
("c", "Card C"),
] {
let body = if suffix == "b" {
OccurrenceBody::Control {
kind: ControlKind::Choice,
}
} else {
OccurrenceBody::Action {
action: Some(id(if suffix == "a" || suffix == "c" {
&shared
} else {
&downstream
})),
lifeline: None,
}
};
occurrence(
&mut p,
&format!("{prefix}_{suffix}"),
label,
layer,
owner,
body,
);
}
let order: Vec<_> = ["a", "u", "b", "v", "c"]
.map(|suffix| format!("{prefix}_{suffix}"))
.into_iter()
.collect();
set_steps(
&mut p,
owner,
&order.iter().map(String::as_str).collect::<Vec<_>>(),
);
sequence_link(
&mut p,
&format!("{prefix}_a_u"),
"A to U",
&format!("{prefix}_a"),
&format!("{prefix}_u"),
)?;
sequence_link(
&mut p,
&format!("{prefix}_b_v"),
"B to V",
&format!("{prefix}_b"),
&format!("{prefix}_v"),
)?;
}
element(
&mut p,
"reusable",
"Reusable request detail",
Kind::Process,
Layer::Oa,
None,
);
occurrence(
&mut p,
"reused_leaf",
"Shared detail",
Layer::Oa,
"reusable",
OccurrenceBody::Action {
action: Some(id("oa_shared_work")),
lifeline: None,
},
);
set_steps(&mut p, "reusable", &["reused_leaf"]);
element(
&mut p,
"reuse_trial",
"02 Read-only preview trial",
Kind::Process,
Layer::Oa,
None,
);
for (alias, name) in [
("reference_one", "First use"),
("reference_two", "Second use"),
] {
occurrence(
&mut p,
alias,
name,
Layer::Oa,
"reuse_trial",
OccurrenceBody::SequenceReference {
sequence: Some(id("reusable")),
},
);
}
set_steps(&mut p, "reuse_trial", &["reference_one", "reference_two"]);
p.traces.insert(
id("trace"),
Trace {
id: id("trace"),
alias: "preserved_work_refinement".into(),
name: "Shared request refinement".into(),
description: "Process arrangement must preserve cross-layer correspondence.".into(),
oa: id("oa_shared_work"),
sa: id("sa_shared_work"),
kind: TraceKind::Refinement,
baseline: Some(TraceBaseline {
oa: p.properties(id("oa_shared_work")).unwrap(),
sa: p.properties(id("sa_shared_work")).unwrap(),
semantic: None,
}),
},
);
validate_candidate(&p)?;
Ok(p)
}
fn load(path: &Path) -> Result<Project> {
if path
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("arcadia"))
{
let disk = source_files::load_project(path, ProjectLimits::default())?;
if disk
.diagnostics
.iter()
.any(|d| d.diagnostic.severity == validation::Severity::Error)
{
return Err(format!("Source discovery diagnostics: {:?}", disk.diagnostics).into());
}
let compiled = compile_bundle(&disk.reachable_bundle(), ProjectLimits::default())
.map_err(|e| format!("Source compile diagnostics: {e:?}"))?;
Ok(compiled.decoded.project)
} else {
Ok(persistence::load(path)?)
}
}
fn equal(expected: &Project, actual: &Project) -> Result<()> {
if expected == actual {
return Ok(());
}
let expected = serde_json::to_value(expected)?;
let actual = serde_json::to_value(actual)?;
let fields: Vec<_> = expected
.as_object()
.unwrap()
.keys()
.filter(|key| expected[*key] != actual[*key])
.cloned()
.collect();
Err(format!("Whole Project mismatch in {fields:?}; no partial PASS").into())
}
fn roundtrip(p: &Project) -> Result<SourceBundle> {
validate_candidate(p)?;
equal(p, &persistence::decode(&serde_json::to_vec(p)?)?)?;
let bundle = format_bundle(p);
let compiled = compile_bundle(&bundle, ProjectLimits::default())
.map_err(|e| format!("Roundtrip: {e:?}"))?;
equal(p, &compiled.decoded.project)?;
Ok(bundle)
}
fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
fs::create_dir_all(path.parent().ok_or("Missing parent directory")?)?;
fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)?
.write_all(bytes)?;
Ok(())
}
fn generate(out: &Path) -> Result<()> {
if out.exists() {
return Err("Output directory already exists; choose a fresh path".into());
}
let p = fixture()?;
let bundle = roundtrip(&p)?;
write_new(&out.join("baseline.json"), &serde_json::to_vec_pretty(&p)?)?;
for (path, source) in &bundle.files {
write_new(&out.join("source").join(path), source.as_bytes())?;
}
let ids: std::collections::BTreeMap<_, _> = [
"project",
"oa_process",
"oa_a",
"oa_u",
"oa_b",
"oa_v",
"oa_c",
"oa_a_u",
"oa_b_v",
"oa_shared_work",
"oa_downstream_work",
"sa_chain",
"sa_shared_work",
"sa_downstream_work",
"sa_a",
"sa_u",
"sa_b",
"sa_v",
"sa_c",
"sa_a_u",
"sa_b_v",
"trace",
"reusable",
"reused_leaf",
"reuse_trial",
"reference_one",
"reference_two",
]
.into_iter()
.map(|name| (name, id(name)))
.collect();
write_new(
&out.join("manifest.json"),
&serde_json::to_vec_pretty(&serde_json::json!({
"fixture": "process-multiselect-native-20260923", "ids": ids, "source_entry": bundle.entry,
"original_oa_steps": ["oa_a", "oa_u", "oa_b", "oa_v", "oa_c"],
"reordered_oa_steps": ["oa_b", "oa_u", "oa_a", "oa_v", "oa_c"],
"gesture": "Select Card C then add Card A; Inspect Card C without changing membership, then drag Card C to After Card B",
"fixed_slots": {"1": "oa_u", "3": "oa_v"},
"read_only_trial": "02 Read-only preview trial has two qualified tiles of reused_leaf through distinct references",
"receipt": "Pin baseline.json, manifest.json and generation command externally before interaction. Never replace baseline with a later saved snapshot.",
"evaluation": "Literal expected OA steps and complete Project equality; all SA/reuse/trace records exact",
"limits": "No pointer, focus, selection-paint, history or source-byte acceptance claim",
}))?,
)?;
equal(&p, &load(&out.join("baseline.json"))?)?;
equal(&p, &load(&out.join("source").join(&bundle.entry))?)?;
println!("PASS generated JSON and source bundle: {}", out.display());
Ok(())
}
fn check(mode: &str, baseline: &Path, saved: &Path) -> Result<()> {
let before = load(baseline)?;
let actual = load(saved)?;
validate_candidate(&before)?;
validate_candidate(&actual)?;
// Pin the exact deterministic original, not merely a reusable project UUID.
equal(&fixture()?, &before)
.map_err(|e| format!("Baseline is not the immutable original: {e}"))?;
let mut expected = before;
match mode {
"unchanged" => {}
"reordered" => set_steps(
&mut expected,
"oa_process",
&["oa_b", "oa_u", "oa_a", "oa_v", "oa_c"],
),
_ => return Err("Mode must be reordered or unchanged".into()),
}
equal(&expected, &actual)?;
roundtrip(&actual)?;
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"result": "PASS", "mode": mode, "baseline": baseline, "saved": saved,
"comparison": "complete Project equality; literal expected order",
"limits": "No pointer/action/focus/Undo/source-byte acceptance claim",
}))?
);
Ok(())
}
fn main() -> Result<()> {
let args: Vec<_> = std::env::args().skip(1).collect();
match args.as_slice() {
[command, out] if command == "generate" => generate(Path::new(out)),
[command, mode, baseline, saved] if command == "check" => check(mode, Path::new(baseline), Path::new(saved)),
_ => Err("Usage: process_multiselect_native generate DIRECTORY | check reordered|unchanged BASELINE SAVED".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn reordered(before: &Project) -> Project {
let mut session = Session::new(before.clone());
session
.execute(Command::SetSteps(
id("oa_process"),
["oa_b", "oa_u", "oa_a", "oa_v", "oa_c"].map(id).to_vec(),
))
.unwrap();
session.project().clone()
}
fn through_json(mode: &str, baseline: &Project, actual: &Project) -> Result<()> {
validate_candidate(baseline).expect("Baseline must be valid");
validate_candidate(actual).expect("Corruption must remain semantically valid");
let dir = tempfile::tempdir()?;
let before = dir.path().join("before.json");
let saved = dir.path().join("saved.json");
persistence::save(&before, baseline)?;
persistence::save(&saved, actual)?;
check(mode, &before, &saved)
}
fn mismatch(before: &Project, actual: &Project) {
let error = through_json("reordered", before, actual)
.unwrap_err()
.to_string();
assert!(
error.contains("Whole Project mismatch"),
"Unexpected rejection: {error}"
);
}
#[test]
fn generate_is_deterministic_create_only_and_checks_real_source() {
equal(&fixture().unwrap(), &fixture().unwrap()).unwrap();
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("fixture");
generate(&out).unwrap();
let baseline = out.join("baseline.json");
let bytes = fs::read(&baseline).unwrap();
check("unchanged", &baseline, &out.join("source/project.arcadia")).unwrap();
assert!(generate(&out).is_err());
assert_eq!(fs::read(&baseline).unwrap(), bytes);
let invalid = dir.path().join("invalid.arcadia");
fs::write(&invalid, "project {").unwrap();
assert!(load(&invalid).is_err());
}
#[test]
fn real_set_steps_passes_but_unchanged_and_mutated_baseline_do_not() {
let before = fixture().unwrap();
let actual = reordered(&before);
through_json("reordered", &before, &actual).unwrap();
through_json("unchanged", &before, &before).unwrap();
mismatch(&before, &before);
assert!(through_json("unchanged", &before, &actual).is_err());
let error = through_json("unchanged", &actual, &actual)
.unwrap_err()
.to_string();
assert!(error.contains("immutable original"), "{error}");
}
#[test]
fn global_splice_reversed_block_and_singleton_c_results_are_rejected() {
let before = fixture().unwrap();
// Native primary/pressed C is already after B, so a singleton C move
// is unchanged. Group {C,A} instead puts B before both selected cards.
// If A were primary, its singleton result could equal the group result.
mismatch(&before, &before);
for order in [
["oa_u", "oa_b", "oa_a", "oa_c", "oa_v"],
["oa_b", "oa_u", "oa_c", "oa_v", "oa_a"],
["oa_a", "oa_u", "oa_b", "oa_c", "oa_v"],
] {
let mut actual = before.clone();
set_steps(&mut actual, "oa_process", &order);
mismatch(&before, &actual);
}
}
#[test]
fn semantic_link_work_sa_reuse_and_trace_changes_are_rejected() {
let before = fixture().unwrap();
let correct = reordered(&before);
let mutations: [fn(&mut Project); 7] = [
|p| {
if let RelationBody::SequenceLink { guard, .. } =
&mut p.relations.get_mut(&id("oa_a_u")).unwrap().body
{
*guard = "changed".into();
}
},
|p| {
if let RelationBody::SequenceLink { target, .. } =
&mut p.relations.get_mut(&id("oa_a_u")).unwrap().body
{
*target = id("oa_v");
}
},
|p| {
p.elements
.get_mut(&id("oa_shared_work"))
.unwrap()
.name
.push_str(" drift");
},
|p| {
p.elements
.get_mut(&id("sa_shared_work"))
.unwrap()
.description
.push_str(" drift");
},
|p| {
set_steps(p, "sa_chain", &["sa_b", "sa_u", "sa_a", "sa_v", "sa_c"]);
},
|p| {
p.elements
.get_mut(&id("reused_leaf"))
.unwrap()
.description
.push_str(" drift");
},
|p| {
p.traces.get_mut(&id("trace")).unwrap().baseline = None;
},
];
for mutate in mutations {
let mut bad = correct.clone();
mutate(&mut bad);
mismatch(&before, &bad);
}
}
#[test]
fn changed_source_roundtrip_preserves_both_layers_and_checker_rejects_source_drift() {
let before = fixture().unwrap();
let actual = reordered(&before);
let dir = tempfile::tempdir().unwrap();
let baseline = dir.path().join("baseline.json");
persistence::save(&baseline, &before).unwrap();
for corrupt in [false, true] {
let mut saved = actual.clone();
if corrupt {
saved
.elements
.get_mut(&id("sa_c"))
.unwrap()
.name
.push_str(" drift");
}
let bundle = roundtrip(&saved).unwrap();
let folder = dir.path().join(if corrupt { "corrupt" } else { "saved" });
for (path, text) in &bundle.files {
write_new(&folder.join(path), text.as_bytes()).unwrap();
}
let parsed = load(&folder.join(&bundle.entry)).unwrap();
assert_eq!(parsed.elements[&id("oa_process")].kind(), Kind::Process);
assert_eq!(
parsed.elements[&id("sa_chain")].kind(),
Kind::FunctionalChain
);
let result = check("reordered", &baseline, &folder.join(&bundle.entry));
if corrupt {
assert!(
result
.unwrap_err()
.to_string()
.contains("Whole Project mismatch")
);
} else {
result.unwrap();
}
}
}
}
+74 -3
View File
@@ -268,6 +268,7 @@ mod direct_scenario_tests {
#[cfg(test)]
mod behavior_lifecycle_tests;
mod process_canvas;
mod process_multiselect;
mod state_diagram;
#[cfg(test)]
mod state_diagram_tests;
@@ -818,6 +819,9 @@ impl App {
.map(|n| n.id);
}
self.draft = Draft::from_project(self.project(), self.selected);
if self.process_preview_primary().is_some() {
self.draft = None;
}
if self.exact_strings
&& let Some(d) = &mut self.draft
{
@@ -1115,10 +1119,13 @@ impl App {
previous != (self.layer, self.active_diagram)
}
fn select(&mut self, id: Id) {
// An exact Process preview and its defining object share a semantic ID,
// but ordinary Explorer/property navigation must still leave the use.
let process_preview = self.process_preview_primary().is_some();
if id != self.selected {
self.selected_attachment = None;
}
if self.selected == id {
if self.selected == id && !process_preview {
return;
}
if !self.apply() {
@@ -1127,6 +1134,10 @@ impl App {
if !self.project().contains(id) {
return;
}
self.behavior.topology.clear_context();
if process_preview {
self.diagram_navigation_focus = None;
}
let previous_state_view = self.state_view_identity();
self.selected = id;
self.selected_node = None;
@@ -1294,6 +1305,7 @@ impl App {
])
}
pub fn update(&mut self, message: Message) -> Task<Message> {
let preview_read_only = self.process_preview_primary().is_some();
let selection_boundary = self.multiselect_boundary();
// Reject delayed gestures before they can retire newer input ownership.
if let Message::DiagramSelection(event)
@@ -1326,6 +1338,52 @@ impl App {
// or allocation ownership before its edit is refused.
return Task::none();
}
if let Message::TopologyCanvas(event) = &message {
use crate::behavior::topology::CanvasEvent;
if !matches!(
event,
CanvasEvent::Camera(..) | CanvasEvent::Scrolled(..) | CanvasEvent::Viewport(..)
) && self.topology_context() != Some(event.context())
{
return Task::none();
}
if matches!(
event,
CanvasEvent::Select(..)
| CanvasEvent::SelectQualified(..)
| CanvasEvent::Remove(..)
| CanvasEvent::Reorder { .. }
| CanvasEvent::Reconnect { .. }
) && self
.multiselect_snapshot()
.is_some_and(|s| s.targets().len() > 1)
{
return Task::none();
}
}
if self.process_order_noop(&message) {
return Task::none();
}
if self.process_preview_primary().is_some()
&& matches!(
&message,
Message::Field(..)
| Message::FieldText(..)
| Message::FieldShape(..)
| Message::FieldAppend(..)
| Message::FieldValuePath(..)
| Message::FieldVariant(..)
| Message::FieldArray(..)
| Message::ElementKind(_)
| Message::RelationKind(_)
| Message::Apply
| Message::Delete
| Message::DiagramRemove(_)
)
{
self.status = "Open the referenced definition to edit its contents.".into();
return Task::none();
}
// Captured Text commands validate their origin before they can
// invalidate that same origin or pass into existing command handlers.
if let Message::TextWorkspace(event) = message {
@@ -1420,6 +1478,9 @@ impl App {
{
self.reconcile_multiselect();
}
if preview_read_only && self.process_preview_primary().is_none() && self.draft.is_none() {
self.refresh_draft();
}
task
}
fn behavior_control(&mut self, intent: behavior::canvas_workspace::Intent) -> Task<Message> {
@@ -2333,6 +2394,9 @@ impl App {
self.route_context()
};
}
if request.process.is_some() {
request.process = self.topology_context().map(Box::new);
}
self.model_menu = crate::model_menu::Opened::new(self, request, self.menu_sequence);
}
Message::Menu(crate::model_menu::Event::Close) => {
@@ -2362,7 +2426,10 @@ impl App {
"Apply or revert pending edits before using modeling actions.".into();
return Task::none();
}
if matches!(*action, Message::DiagramSelection(_)) {
if matches!(*action, Message::DiagramSelection(_))
|| (menu.request.process.is_some()
&& matches!(*action, Message::TopologyCanvas(_)))
{
return self.update(*action);
}
self.select(menu.request.object);
@@ -3215,7 +3282,11 @@ impl App {
.multiselect_snapshot()
.is_some_and(|s| s.targets().len() > 1)
{
self.status = "Group model-deletion review is not available yet. Select one element or use Hide selected.".into();
self.status = if self.topology_context().is_some() {
"Group removal needs an aggregate review. Select one contribution to remove it individually."
} else {
"Group model-deletion review is not available yet. Select one element or use Hide selected."
}.into();
return Task::none();
}
if self.selected != self.project().id && self.apply() {
@@ -518,9 +518,16 @@ async fn mounted_qualified_process_child_delete_refuses_outer_reference_and_shar
.await;
assert!(messages.iter().any(|message| matches!(
message,
Message::TopologyCanvas(topology::CanvasEvent::SelectQualified(..))
Message::DiagramSelection(multiselect::Event::Choose(
_, crate::diagram_usage::Target::ProcessOccurrence(actual), multiselect::Choice::Replace
)) if actual == &endpoint
)));
assert_eq!(app.selected, references[0]);
assert_eq!(app.selected, f.nodes[0]);
assert!(app.draft.is_none(), "Qualified inspection stays read-only");
assert_eq!(
app.behavior.topology.selection_address().unwrap().endpoint,
endpoint
);
assert!(
app.behavior
.topology
+1 -8
View File
@@ -319,14 +319,7 @@ impl App {
| Target::ScenarioObject(id)
| Target::AllocationGrouping { relation: id, .. }
| Target::ProcessPreviewLink { relation: id, .. } => (*id, None),
Target::ProcessOccurrence(endpoint) => (
endpoint
.references
.first()
.copied()
.unwrap_or(endpoint.occurrence),
None,
),
Target::ProcessOccurrence(endpoint) => (endpoint.occurrence, None),
};
match usage.surface {
Surface::Saved(id) => {
@@ -881,7 +881,32 @@ fn repeated_process_calls_reveal_the_chosen_caller_and_distinct_tile_camera() {
.unwrap()
.clone();
choose(&mut app, token, row);
assert_eq!(app.selected, first);
assert_eq!(app.selected, leaf);
let context = app.topology_context().unwrap();
send(
&mut app,
Message::TopologyCanvas(behavior::topology::CanvasEvent::Viewport(
context,
iced::Size::new(850., 460.),
)),
);
assert!(app.pending_diagram_reveal.is_none());
assert_eq!(
app.behavior.topology.selection_address().unwrap().endpoint,
OccurrenceEndpoint {
references: vec![first],
occurrence: leaf
}
);
assert_eq!(
app.multiselect_snapshot().unwrap().primary(),
Some(&Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![first],
occurrence: leaf
}))
);
assert!(app.process_preview_primary().is_some());
assert!(app.draft.is_none());
assert_eq!(app.page, Page::Behavior);
assert_eq!(app.behavior.active_owner, Some(fixture.owner));
let first_camera = app.behavior.topology.camera_boundary();
@@ -898,7 +923,33 @@ fn repeated_process_calls_reveal_the_chosen_caller_and_distinct_tile_camera() {
})
.unwrap();
choose(&mut app, token, row);
assert_eq!(app.selected, second);
assert_eq!(app.selected, leaf);
let context = app.topology_context().unwrap();
send(
&mut app,
Message::TopologyCanvas(behavior::topology::CanvasEvent::Viewport(
context,
iced::Size::new(850., 460.),
)),
);
assert!(app.pending_diagram_reveal.is_none());
assert_eq!(app.behavior.active_owner, Some(fixture.owner));
assert_eq!(
app.behavior.topology.selection_address().unwrap().endpoint,
OccurrenceEndpoint {
references: vec![second],
occurrence: leaf
}
);
assert_eq!(
app.multiselect_snapshot().unwrap().primary(),
Some(&Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![second],
occurrence: leaf
}))
);
assert!(app.process_preview_primary().is_some());
assert!(app.draft.is_none());
assert_eq!(app.selected_node, None);
assert!(app.behavior.topology.camera_boundary() != first_camera);
assert_eq!(authored(&app), before);
+48 -5
View File
@@ -19,6 +19,10 @@ pub(crate) enum Event {
Clear(Context),
Move(Snapshot, Position),
Hide(Snapshot),
ProcessReorder(
Snapshot,
crate::behavior::topology::group_reorder::Destination,
),
Refuse(Snapshot, String),
}
@@ -33,6 +37,17 @@ pub(crate) fn context(c: crate::route_edit::Context) -> Context {
}
}
pub(crate) fn process_context(c: crate::behavior::topology::Context) -> Context {
Context {
scope: Scope {
document: c.document,
surface: Surface::Process(c.owner),
},
revision: c.revision,
epoch: c.epoch,
}
}
/// The entire typed set must support a placement action. Never filter a mixture.
pub(crate) fn placements(snapshot: &Snapshot) -> Option<std::collections::BTreeSet<Id>> {
snapshot.primary()?;
@@ -83,12 +98,17 @@ impl App {
self.selected_node,
(self.page == Page::Behavior).then(|| self.state_view_identity()),
(self.page == Page::Behavior).then_some(self.behavior.diagram.placement),
self.topology_context(),
self.behavior.topology.selection_address(),
)
}
pub(crate) fn multiselect_context(&self) -> Option<Context> {
match self.page {
Page::Diagram => self.route_context().map(context),
Page::Behavior => {
if let Some(current) = self.topology_context() {
return Some(process_context(current));
}
let current = self.state_context()?;
crate::behavior::state_edit::validate_context(self.project(), current, current)
.ok()?;
@@ -99,6 +119,13 @@ impl App {
}
pub(crate) fn multiselect_target_visible(&self, target: &Target) -> bool {
if let Some(context) = self.topology_context() {
return self
.behavior
.topology
.selection_targets(self.project(), context.owner)
.contains(target);
}
let Some(Context {
scope:
Scope {
@@ -130,11 +157,14 @@ impl App {
};
match event {
Event::Choose(c, ..) | Event::Clear(c) => *c == current,
Event::Move(s, _) | Event::Hide(s) | Event::Refuse(s, _) | Event::Collapse(s, _) => {
self.diagram_selection
.as_ref()
.is_some_and(|selection| selection.matches(s, current))
}
Event::Move(s, _)
| Event::Hide(s)
| Event::ProcessReorder(s, _)
| Event::Refuse(s, _)
| Event::Collapse(s, _) => self
.diagram_selection
.as_ref()
.is_some_and(|selection| selection.matches(s, current)),
}
}
@@ -189,6 +219,10 @@ impl App {
}
pub(crate) fn reconcile_multiselect(&mut self) {
if self.topology_context().is_some() {
self.reconcile_process_multiselect();
return;
}
let Some(current) = self.multiselect_context() else {
self.diagram_selection = None;
return;
@@ -250,6 +284,10 @@ impl App {
}
fn inspect_multiselect_primary(&mut self) {
if self.topology_context().is_some() {
self.inspect_process_multiselect_primary();
return;
}
let diagram = self
.multiselect_context()
.and_then(|c| match c.scope.surface {
@@ -293,6 +331,10 @@ impl App {
if !self.multiselect_envelope(&event) {
return;
}
if self.topology_context().is_some() {
self.process_multiselect_event(event);
return;
}
if !diagram_removal::enabled(self)
|| self.architecture.is_some()
|| self.connection.is_some()
@@ -313,6 +355,7 @@ impl App {
self.document.view_index(),
);
match event {
Event::ProcessReorder(..) => {}
Event::Collapse(_, target) => {
if !visible(self.project(), diagram, &view, &target) {
return;
+31 -18
View File
@@ -128,6 +128,12 @@ impl App {
let resolved = oa_core::topology_context::TopologyIndex::new(self.project())
.resolve(context.owner, &endpoint);
if let Ok(resolved) = resolved {
// The definition may be opened from a nonprimary context
// target. Remember that exact invocation, not whichever
// qualified occurrence happened to be primary beforehand.
self.behavior
.topology
.select_context(resolved.address.clone());
self.behavior.topology.remember(
context.owner,
endpoint
@@ -137,27 +143,18 @@ impl App {
.unwrap_or(endpoint.occurrence),
resolved.defining_sequence,
);
self.behavior.topology.clear_context();
self.behavior.active_owner = Some(resolved.defining_sequence);
self.select(endpoint.occurrence);
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
}
CanvasEvent::SelectQualified(_, endpoint) => {
if !self.behavior.has_pending()
&& !self.draft_dirty()
&& !self.source_dirty()
&& let Ok(resolved) =
oa_core::topology_context::TopologyIndex::new(self.project())
.resolve(context.owner, &endpoint)
{
let reference = endpoint
.references
.first()
.copied()
.unwrap_or(endpoint.occurrence);
self.select(reference);
self.behavior.topology.select_context(resolved.address);
}
self.multiselect_event(multiselect::Event::Choose(
multiselect::process_context(context),
crate::diagram_usage::Target::ProcessOccurrence(endpoint),
multiselect::Choice::Replace,
));
}
CanvasEvent::Select(_, id) => {
if !self.behavior.has_pending()
@@ -198,6 +195,9 @@ impl App {
if let Some(target) =
topology::referenced(self.project(), context.owner, occurrence)
{
// Opening a local card returns to that local use, even if
// a qualified tile was the previous inspection target.
self.behavior.topology.clear_context();
if self
.project()
.elements
@@ -222,8 +222,20 @@ impl App {
self.behavior.topology = state;
if let Some((owner, occurrence)) = back {
self.behavior.active_owner = Some(owner);
self.select(occurrence);
// Back restores a use, whereas ordinary select navigates
// to a defining object. The validated return address owns
// the exact subject; never infer it from the outer card ID.
self.selected = self
.behavior
.topology
.selection_address()
.filter(|address| address.owner == owner)
.map_or(occurrence, |address| address.endpoint.occurrence);
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
// Synchronize the exact primary and inspector before the
// returned caller is drawn or accepts property edits.
self.reconcile_process_multiselect();
self.inspect_process_multiselect_primary();
}
}
mutation => {
@@ -293,8 +305,9 @@ impl App {
occurrence, before, ..
} => {
match topology::reorder(self.project(), context.owner, occurrence, before) {
Ok(command) => {
if self.execute(command) {
Ok(topology::group_reorder::Plan::Noop) => {}
Ok(topology::group_reorder::Plan::Change(command)) => {
if self.execute(*command) {
self.selected = occurrence;
self.refresh_draft();
return self.reveal_process_selection();
@@ -0,0 +1,260 @@
//! Exact Process presentation selection and one atomic order transaction.
use super::*;
use crate::behavior::topology::group_reorder::{Plan, Prepared};
use crate::diagram_selection::Selection;
use crate::diagram_usage::{Surface, Target};
use multiselect::{Choice, Event};
fn subject(target: &Target) -> Option<Id> {
match target {
Target::ProcessOccurrence(endpoint) => Some(endpoint.occurrence),
Target::ProcessLink(id) | Target::ProcessPreviewLink { relation: id, .. } => Some(*id),
_ => None,
}
}
impl App {
pub(crate) fn process_preview_primary(&self) -> Option<&Target> {
let context = self.topology_context()?;
let selection = self.diagram_selection.as_ref()?;
if selection.scope() != multiselect::process_context(context).scope {
return None;
}
selection
.primary()
.filter(|target| subject(target) == Some(self.selected))
.filter(|target| match target {
Target::ProcessOccurrence(endpoint) => !endpoint.references.is_empty(),
Target::ProcessPreviewLink { .. } => true,
_ => false,
})
}
pub(super) fn reconcile_process_multiselect(&mut self) {
let Some(context) = self.topology_context() else {
return;
};
let current = multiselect::process_context(context);
let visible = self
.behavior
.topology
.selection_targets(self.project(), context.owner);
let old = self
.diagram_selection
.as_ref()
.filter(|s| s.scope() == current.scope)
.and_then(Selection::primary)
.cloned();
let address = self.behavior.topology.selection_address();
let focused = self
.diagram_focus(Surface::Process(context.owner))
.map(|usage| usage.target.clone());
let legacy = focused
.clone()
.or_else(|| {
address
.as_ref()
.filter(|a| a.owner == context.owner && a.endpoint.occurrence == self.selected)
.map(|a| Target::ProcessOccurrence(a.endpoint.clone()))
})
.or_else(|| {
visible
.iter()
.find(|target| match target {
Target::ProcessOccurrence(endpoint) => {
endpoint.references.is_empty() && endpoint.occurrence == self.selected
}
Target::ProcessLink(id) => *id == self.selected,
_ => false,
})
.cloned()
})
.filter(|target| visible.contains(target));
let held = old.as_ref().is_some_and(|target| {
subject(target) == Some(self.selected)
&& focused.as_ref().is_none_or(|focused| focused == target)
&& match target {
Target::ProcessOccurrence(endpoint) if !endpoint.references.is_empty() => {
address
.as_ref()
.is_some_and(|a| a.owner == context.owner && a.endpoint == *endpoint)
}
_ => true,
}
});
let lost = old.as_ref().is_some_and(|target| !visible.contains(target));
let selection = self
.diagram_selection
.get_or_insert_with(|| Selection::new(current.scope));
selection.reconcile(current.scope, |target| visible.contains(target));
if held || lost {
if selection.primary() != old.as_ref() {
self.inspect_process_multiselect_primary();
}
} else if selection.primary() != legacy.as_ref() {
if let Some(target) = legacy {
selection.replace(target, |t| visible.contains(t));
} else {
selection.clear();
}
}
if self.process_preview_primary().is_some() {
self.draft = None;
}
}
pub(super) fn inspect_process_multiselect_primary(&mut self) {
let Some(context) = self.topology_context() else {
return;
};
let primary = self
.diagram_selection
.as_ref()
.and_then(Selection::primary)
.cloned();
self.behavior.topology.clear_context();
self.selected = primary.as_ref().and_then(subject).unwrap_or(context.owner);
self.selected_node = None;
self.selected_bend = None;
self.selected_attachment = None;
self.diagram_navigation_focus = None;
if let Some(Target::ProcessOccurrence(endpoint)) = primary
&& !endpoint.references.is_empty()
&& let Ok(resolved) = oa_core::topology_context::TopologyIndex::new(self.project())
.resolve(context.owner, &endpoint)
{
self.behavior.topology.select_context(resolved.address);
}
self.refresh_draft();
if self.process_preview_primary().is_some() {
self.draft = None;
}
}
pub(super) fn process_multiselect_event(&mut self, event: Event) {
let Some(context) = self.topology_context() else {
return;
};
if let Event::Refuse(_, reason) = &event
&& diagram_removal::enabled(self)
{
self.status = reason.clone();
return;
}
if !diagram_removal::enabled(self) || !self.behavior.topology.selecting() {
self.status =
"Finish or cancel the active edit before changing the process selection.".into();
return;
}
let visible = self
.behavior
.topology
.selection_targets(self.project(), context.owner);
match event {
Event::Choose(_, target, choice) => {
if !visible.contains(&target) {
return;
}
self.reconcile_process_multiselect();
let selection = self.diagram_selection.as_mut().unwrap();
let valid = |t: &Target| visible.contains(t);
match choice {
Choice::Replace => {
selection.replace(target, valid);
}
Choice::Add => {
selection.add(target, valid);
}
Choice::Remove => {
selection.remove(&target);
}
Choice::Toggle => {
selection.toggle(target, valid);
}
Choice::Inspect => {
selection.set_primary(&target);
}
}
self.inspect_process_multiselect_primary();
}
Event::Collapse(_, target) => {
if !visible.contains(&target) {
return;
}
self.diagram_selection
.as_mut()
.unwrap()
.replace(target, |t| visible.contains(t));
self.inspect_process_multiselect_primary();
}
Event::Clear(_) => {
self.diagram_selection.as_mut().unwrap().clear();
self.inspect_process_multiselect_primary();
}
Event::Refuse(_, reason) => self.status = reason,
Event::Hide(_) => {
self.status =
"Process cards are model contributions, not placements. Hide is unavailable."
.into()
}
Event::Move(..) => {
self.status =
"Process positions come from their paths. Reorder within one column instead."
.into()
}
Event::ProcessReorder(snapshot, destination) => {
if !snapshot
.targets()
.iter()
.all(|target| visible.contains(target))
{
return;
}
match Prepared::new(self.project(), context.owner, snapshot.targets())
.and_then(|prepared| prepared.plan(destination))
{
Ok(Plan::Noop) => {}
Ok(Plan::Change(command)) => {
if self.execute(*command) {
self.inspect_process_multiselect_primary();
self.status = format!(
"Reordered {} contributions · Undo restores their order",
snapshot.targets().len()
);
}
}
Err(error) => self.status = error,
}
}
}
}
/// A no-op must not retire a pending reveal or allocate a history entry.
pub(super) fn process_order_noop(&self, message: &Message) -> bool {
let Some(context) = self.topology_context() else {
return false;
};
match message {
Message::DiagramSelection(Event::ProcessReorder(snapshot, destination)) => {
Prepared::new(self.project(), context.owner, snapshot.targets())
.and_then(|prepared| prepared.plan(*destination))
.is_ok_and(|p| matches!(p, Plan::Noop))
}
Message::TopologyCanvas(crate::behavior::topology::CanvasEvent::Reorder {
context: captured,
occurrence,
before,
}) if *captured == context => crate::behavior::topology::reorder(
self.project(),
context.owner,
*occurrence,
*before,
)
.is_ok_and(|p| matches!(p, Plan::Noop)),
_ => false,
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,979 @@
//! Process selection through the real App admission, document and source boundary.
use super::*;
use crate::behavior::topology::group_reorder::Destination;
use crate::behavior::topology::{self, CanvasEvent, CanvasTool};
use oa_core::OccurrenceEndpoint;
struct Fixture {
app: App,
owner: Id,
nodes: [Id; 5],
link: Id,
work: Id,
other_owner: Id,
}
fn local(id: Id) -> Target {
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: id,
})
}
fn add(project: &mut Project, owner: Id, name: &str, body: OccurrenceBody) -> Id {
let mut element = project
.make_element(
Kind::Occurrence,
project.elements[&owner].layer(),
name,
Some(owner),
)
.unwrap();
let Some(SharedBody::Occurrence { body: value, .. }) = element.shared_mut() else {
unreachable!()
};
*value = body;
let id = element.id;
*project = execute_batch(project, &[Command::CreateElement(element)]).unwrap();
id
}
fn open(project: Project, owner: Id) -> App {
let mut app = App::with_project(project);
let _ = app.update(Message::Select(owner));
let _ = app.update(Message::Page(Page::Behavior));
app.reconcile_multiselect();
assert_eq!(app.topology_context().unwrap().owner, owner);
assert_eq!(
app.multiselect_context().unwrap().scope.surface,
Surface::Process(owner)
);
app
}
fn fixture(layer: Layer) -> Fixture {
let (f, _) = topology::direct_tests::empty_exchange_fixture(layer);
let mut project = f.p;
let mut nodes = vec![];
for name in ["a", "u", "b", "v", "c"] {
nodes.push(add(
&mut project,
f.owner,
name,
OccurrenceBody::Action {
action: Some(f.work[0]),
lifeline: None,
},
));
}
let nodes: [Id; 5] = nodes.try_into().unwrap();
let [a, u, b, v, _] = nodes;
let link = project.relate(RelationKind::SequenceLink, "a to u", a, u);
project.relate(RelationKind::SequenceLink, "b to v", b, v);
let other = project
.make_element(
if layer == Layer::Oa {
Kind::Process
} else {
Kind::FunctionalChain
},
layer,
"Other owner",
None,
)
.unwrap();
let other_owner = other.id;
project = execute_batch(&project, &[Command::CreateElement(other)]).unwrap();
validate_candidate(&project).unwrap();
Fixture {
app: open(project, f.owner),
owner: f.owner,
nodes,
link,
work: f.work[0],
other_owner,
}
}
fn send(app: &mut App, event: Event) {
let _ = app.update(Message::DiagramSelection(event));
}
fn choose(app: &mut App, target: Target, choice: Choice) {
let context = app.multiselect_context().unwrap();
send(app, Event::Choose(context, target, choice));
}
fn pair(f: &mut Fixture) {
choose(&mut f.app, local(f.nodes[4]), Choice::Replace);
choose(&mut f.app, local(f.nodes[0]), Choice::Add);
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
&[local(f.nodes[4]), local(f.nodes[0])]
);
}
fn source_matches(app: &App) {
let compiled = source_project::compile_bundle(app.document.bundle(), LIMITS).unwrap();
assert_eq!(&compiled.decoded.project, app.project());
assert_eq!(&compiled.bundle, app.document.bundle());
assert_eq!(
source_workspace::reachable(&app.source_workspace.bundle()).unwrap(),
*app.document.bundle()
);
}
fn marker(app: &mut App, owner: Id, occurrence: Id) {
use crate::diagram_usage as usage;
let target = usage::collect(
app.project(),
occurrence,
&app.behavior.topology,
&app.behavior.scenario,
)
.into_iter()
.find(|u| u.surface == Surface::Process(owner) && u.target == local(occurrence))
.unwrap();
let context = usage::Context {
document: app.canvas_document,
revision: app.document.revision(),
subject: occurrence,
};
app.pending_diagram_reveal = Some((context, target.clone(), app.canvas_epoch));
app.diagram_navigation_focus = Some(usage::Focus {
context,
usage: target,
selected: app.selected,
});
assert!(app.diagram_focus(Surface::Process(owner)).is_some());
}
#[test]
fn process_group_reverse_click_order_changes_only_owner_steps_and_undoes_once() {
for layer in [Layer::Oa, Layer::Sa] {
let mut f = fixture(layer);
let [a, u, b, v, c] = f.nodes;
pair(&mut f);
let before = f.app.document.snapshot();
let selection = f.app.multiselect_snapshot().unwrap();
assert_eq!(selection.primary(), Some(&local(a)));
send(
&mut f.app,
Event::ProcessReorder(selection.clone(), Destination::After(b)),
);
let mut expected = before.decoded.project.clone();
*expected
.elements
.get_mut(&f.owner)
.unwrap()
.steps_mut()
.unwrap() = vec![b, u, a, v, c];
assert_eq!(f.app.project(), &expected);
assert_eq!(f.app.selected, a);
let after_selection = f.app.multiselect_snapshot().unwrap();
assert_eq!(after_selection.targets(), selection.targets());
assert_eq!(after_selection.primary(), selection.primary());
source_matches(&f.app);
let after = f.app.document.snapshot();
let reopened = Document::from_bundle(after.bundle.clone(), LIMITS).unwrap();
assert_eq!(reopened.project(), &expected);
let _ = f.app.update(Message::Undo);
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(!f.app.document.can_undo());
source_matches(&f.app);
let _ = f.app.update(Message::Redo);
assert_eq!(f.app.project(), &expected);
assert_eq!(f.app.document.bundle(), &after.bundle);
assert!(!f.app.document.can_redo());
source_matches(&f.app);
}
}
#[test]
fn process_noop_group_and_legacy_reorder_preserve_history_camera_and_pending_reveal() {
for group in [true, false] {
let mut f = fixture(Layer::Oa);
if group {
pair(&mut f);
} else {
choose(&mut f.app, local(f.nodes[0]), Choice::Replace);
}
marker(&mut f.app, f.owner, f.nodes[0]);
let before = f.app.document.snapshot();
let selection = f.app.multiselect_snapshot().unwrap();
let pending = f.app.pending_diagram_reveal.clone();
let camera = f.app.behavior.topology.camera_boundary();
let epochs = (f.app.canvas_epoch, f.app.camera_epoch);
f.app.status = "Unchanged order feedback".into();
let message = if group {
Message::DiagramSelection(Event::ProcessReorder(
selection.clone(),
Destination::Before(f.nodes[4]),
))
} else {
Message::TopologyCanvas(CanvasEvent::Reorder {
context: f.app.topology_context().unwrap(),
occurrence: f.nodes[0],
before: f.nodes[2],
})
};
let _ = f.app.update(message);
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert_eq!(f.app.multiselect_snapshot().unwrap(), selection);
assert_eq!(f.app.pending_diagram_reveal, pending);
assert!(f.app.behavior.topology.camera_boundary() == camera);
assert_eq!((f.app.canvas_epoch, f.app.camera_epoch), epochs);
assert_eq!(f.app.status, "Unchanged order feedback");
assert!(!f.app.document.can_undo());
assert!(!f.app.document.can_redo());
}
}
#[test]
fn process_mixed_link_and_cross_column_groups_refuse_whole_operation() {
for layer in [Layer::Oa, Layer::Sa] {
for mixed in [true, false] {
let mut f = fixture(layer);
choose(&mut f.app, local(f.nodes[0]), Choice::Replace);
let other = if mixed {
Target::ProcessLink(f.link)
} else {
local(f.nodes[1])
};
choose(&mut f.app, other.clone(), Choice::Add);
let selection = f.app.multiselect_snapshot().unwrap();
assert_eq!(selection.targets(), &[local(f.nodes[0]), other]);
let before = f.app.document.snapshot();
send(
&mut f.app,
Event::ProcessReorder(selection.clone(), Destination::After(f.nodes[2])),
);
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert_eq!(f.app.multiselect_snapshot().unwrap(), selection);
assert!(!f.app.document.can_undo());
source_matches(&f.app);
}
}
}
#[test]
fn process_stale_document_revision_owner_epoch_and_selection_aba_reject_before_shared_hooks() {
for stale_by in ["document", "revision", "owner", "epoch", "ABA"] {
let mut f = fixture(Layer::Oa);
pair(&mut f);
let stale = f.app.multiselect_snapshot().unwrap();
match stale_by {
"document" => f.app.canvas_document = Id::new_v4(),
"revision" => {
f.app
.document
.execute(Command::Describe(f.work, "New revision".into()))
.unwrap();
}
"owner" => {
f.app.behavior.active_owner = Some(f.other_owner);
f.app.selected = f.other_owner;
f.app.reconcile_multiselect();
}
"epoch" => f.app.canvas_epoch += 1,
_ => {
choose(&mut f.app, local(f.nodes[0]), Choice::Toggle);
choose(&mut f.app, local(f.nodes[0]), Choice::Toggle);
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
stale.targets()
);
assert_eq!(
f.app.multiselect_snapshot().unwrap().primary(),
stale.primary()
);
}
}
let before = f.app.document.snapshot();
let selection = f.app.multiselect_snapshot();
let camera = f.app.behavior.topology.camera_boundary();
let selected = f.app.selected;
let epochs = (
f.app.canvas_epoch,
f.app.camera_epoch,
f.app.allocation_drag.epoch,
);
let history = (f.app.document.can_undo(), f.app.document.can_redo());
f.app.status = "Current owner feedback".into();
f.app.allocation_drag.arrange_next = true;
send(
&mut f.app,
Event::ProcessReorder(stale, Destination::After(f.nodes[2])),
);
assert!(
Arc::ptr_eq(&before, &f.app.document.snapshot()),
"{stale_by}"
);
assert_eq!(f.app.multiselect_snapshot(), selection);
assert_eq!(f.app.selected, selected);
assert!(f.app.behavior.topology.camera_boundary() == camera);
assert_eq!(
(
f.app.canvas_epoch,
f.app.camera_epoch,
f.app.allocation_drag.epoch
),
epochs
);
assert_eq!(
(f.app.document.can_undo(), f.app.document.can_redo()),
history
);
assert_eq!(f.app.status, "Current owner feedback");
assert!(f.app.allocation_drag.arrange_next);
}
}
#[test]
fn process_pending_properties_source_form_tool_and_busy_never_implicitly_apply_or_change_group() {
for pending in [
"properties",
"invalid properties",
"source",
"form",
"tool",
"busy",
] {
let mut f = fixture(Layer::Oa);
pair(&mut f);
match pending {
"properties" => {
let _ = f.app.update(Message::Field(
"/name".into(),
"Unapplied contribution".into(),
));
}
"invalid properties" => {
let _ = f
.app
.update(Message::Field("/alias".into(), "invalid alias!".into()));
}
"source" => {
let text = format!("{}\n// Unapplied source\n", f.app.source_workspace.text());
let _ = f
.app
.update(Message::SourceEdit(text_editor::Action::SelectAll));
let _ = f.app.update(Message::SourceEdit(text_editor::Action::Edit(
text_editor::Edit::Paste(Arc::new(text)),
)));
}
"form" => {
let context = f.app.topology_context().unwrap();
let _ = f.app.update(Message::TopologyCanvas(CanvasEvent::Begin {
context,
tool: topology::Tool::Work,
control: ControlKind::Choice,
insertion: topology::Insertion::default(),
}));
let _ = f.app.update(Message::Behavior(behavior::Event::Topology(
topology::Event::Name("Unsubmitted form".into()),
)));
assert!(f.app.behavior.has_pending());
}
"tool" => f.app.behavior.topology.choose(CanvasTool::Connect),
_ => f.app.busy = true,
}
if pending == "source" {
assert!(f.app.source_dirty());
}
if pending.contains("properties") {
assert!(f.app.draft_dirty());
}
let selection = f.app.multiselect_snapshot().unwrap();
let before = f.app.document.snapshot();
let source = f.app.source_workspace.bundle();
let draft = f
.app
.draft
.as_ref()
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap());
let form = f.app.behavior.recovery_snapshot();
for event in [
Event::ProcessReorder(selection.clone(), Destination::After(f.nodes[2])),
Event::Clear(selection.context()),
Event::Choose(selection.context(), local(f.nodes[2]), Choice::Replace),
] {
send(&mut f.app, event);
assert!(
Arc::ptr_eq(&before, &f.app.document.snapshot()),
"{pending}"
);
assert_eq!(f.app.source_workspace.bundle(), source);
assert_eq!(
f.app
.draft
.as_ref()
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap()),
draft
);
assert_eq!(f.app.behavior.recovery_snapshot(), form);
assert_eq!(f.app.multiselect_snapshot().unwrap(), selection);
assert!(!f.app.document.can_undo());
}
}
}
#[test]
fn process_queued_singleton_selection_remove_reorder_and_reconnect_cannot_retire_current_group() {
let mut f = fixture(Layer::Oa);
pair(&mut f);
marker(&mut f.app, f.owner, f.nodes[0]);
let context = f.app.topology_context().unwrap();
let before = f.app.document.snapshot();
let selection = f.app.multiselect_snapshot().unwrap();
let pending = f.app.pending_diagram_reveal.clone();
let camera = f.app.behavior.topology.camera_boundary();
let epochs = (
f.app.canvas_epoch,
f.app.camera_epoch,
f.app.allocation_drag.epoch,
);
f.app.status = "Group owns input".into();
for event in [
CanvasEvent::Select(context, f.nodes[2]),
CanvasEvent::SelectQualified(
context,
OccurrenceEndpoint {
references: vec![],
occurrence: f.nodes[2],
},
),
CanvasEvent::Remove(context, f.nodes[0]),
CanvasEvent::Reorder {
context,
occurrence: f.nodes[0],
before: f.nodes[4],
},
CanvasEvent::Reconnect {
context,
link: f.link,
end: topology::End::Target,
target: f.nodes[4],
},
] {
let _ = f.app.update(Message::TopologyCanvas(event));
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert_eq!(f.app.multiselect_snapshot().unwrap(), selection);
assert_eq!(f.app.pending_diagram_reveal, pending);
assert!(f.app.behavior.topology.camera_boundary() == camera);
assert_eq!(
(
f.app.canvas_epoch,
f.app.camera_epoch,
f.app.allocation_drag.epoch
),
epochs
);
assert_eq!(f.app.status, "Group owns input");
assert!(!f.app.delete_pending);
assert!(!f.app.document.can_undo());
}
}
fn qualified_fixture() -> (Fixture, Id, Id, Id, Id) {
let mut f = fixture(Layer::Oa);
let mut project = f.app.project().clone();
let sequence = project
.make_element(Kind::Process, Layer::Oa, "Reusable checks", None)
.unwrap();
let sequence_id = sequence.id;
project = execute_batch(&project, &[Command::CreateElement(sequence)]).unwrap();
// Collapsed reuse cards still show four preview entries. Keep the tested
// leaf beyond that bound so collapsing really removes its exact target.
for index in 0..4 {
add(
&mut project,
sequence_id,
&format!("Preview prefix {index}"),
OccurrenceBody::Action {
action: Some(f.work),
lifeline: None,
},
);
}
let leaf = add(
&mut project,
sequence_id,
"Shared check",
OccurrenceBody::Action {
action: Some(f.work),
lifeline: None,
},
);
let first = add(
&mut project,
f.owner,
"First call",
OccurrenceBody::SequenceReference {
sequence: Some(sequence_id),
},
);
let second = add(
&mut project,
f.owner,
"Second call",
OccurrenceBody::SequenceReference {
sequence: Some(sequence_id),
},
);
f.app = open(project, f.owner);
let p = f.app.project().clone();
assert!(f.app.behavior.topology.expand(&p, f.owner, first));
assert!(f.app.behavior.topology.expand(&p, f.owner, second));
(f, sequence_id, first, second, leaf)
}
#[test]
fn process_qualified_primary_is_exact_readonly_and_clears_without_semantic_rebinding() {
let (mut f, _, first, second, leaf) = qualified_fixture();
let p = f.app.project().clone();
let endpoint = OccurrenceEndpoint {
references: vec![first],
occurrence: leaf,
};
let target = Target::ProcessOccurrence(endpoint.clone());
assert!(f.app.multiselect_target_visible(&target));
choose(&mut f.app, target.clone(), Choice::Replace);
assert_eq!(
f.app.selected, leaf,
"Inspect exact leaf, not the first caller or shared work"
);
assert_eq!(f.app.process_preview_primary(), Some(&target));
assert_eq!(
f.app
.behavior
.topology
.selection_address()
.unwrap()
.endpoint,
endpoint
);
assert!(f.app.draft.is_none());
let before = f.app.document.snapshot();
for message in [
Message::Field("/name".into(), "Forbidden definition rename".into()),
Message::Apply,
Message::Delete,
] {
let _ = f.app.update(message);
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert!(f.app.draft.is_none());
assert!(!f.app.delete_pending);
assert_eq!(f.app.process_preview_primary(), Some(&target));
}
choose(&mut f.app, local(f.nodes[0]), Choice::Add);
let mixed = f.app.multiselect_snapshot().unwrap();
send(
&mut f.app,
Event::ProcessReorder(mixed.clone(), Destination::After(f.nodes[2])),
);
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert_eq!(f.app.multiselect_snapshot().unwrap(), mixed);
choose(&mut f.app, target.clone(), Choice::Replace);
let current = f.app.multiselect_context().unwrap();
send(&mut f.app, Event::Clear(current));
assert!(f.app.multiselect_snapshot().unwrap().targets().is_empty());
assert_eq!(f.app.selected, f.owner);
assert!(f.app.behavior.topology.selection_address().is_none());
choose(&mut f.app, target, Choice::Replace);
assert!(f.app.behavior.topology.expand(&p, f.owner, first));
f.app.reconcile_multiselect();
assert!(f.app.multiselect_snapshot().unwrap().targets().is_empty());
assert_eq!(f.app.selected, f.owner);
assert!(f.app.behavior.topology.selection_address().is_none());
assert!(f.app.process_preview_primary().is_none());
assert!(
f.app
.multiselect_target_visible(&Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![second],
occurrence: leaf
}))
);
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
}
fn menu(app: &mut App, target: Target, label: &str) -> Message {
use crate::context_menu::Entry;
use crate::model_menu;
let object = match &target {
Target::ProcessOccurrence(endpoint) => endpoint.occurrence,
_ => panic!("This fixture opens contribution menus"),
};
let mut request = model_menu::Request::object(object, iced::Point::new(180., 150.));
request.process = app.topology_context().map(Box::new);
request.selection_target = Some(Box::new(target));
let _ = app.update(Message::Menu(model_menu::Event::Open(request)));
let opened = app
.model_menu
.as_ref()
.expect("Captured Process menu must survive the open epoch change");
assert!(opened.valid(app));
assert_eq!(
opened.request.process.as_deref().copied(),
app.topology_context()
);
model_menu::popup(app)
.unwrap()
.entries
.into_iter()
.find_map(|entry| match entry {
Entry::Action {
label: name,
message: Some(message),
..
} if name == label => Some(message),
_ => None,
})
.unwrap_or_else(|| panic!("Missing enabled menu action: {label}"))
}
#[test]
fn process_menu_add_uses_rebound_epoch_and_preserves_existing_primary_membership() {
let mut f = fixture(Layer::Oa);
choose(&mut f.app, local(f.nodes[0]), Choice::Replace);
let before = f.app.document.snapshot();
let old_context = f.app.topology_context().unwrap();
let action = menu(&mut f.app, local(f.nodes[4]), "Add to selection");
assert_ne!(f.app.topology_context().unwrap().epoch, old_context.epoch);
assert_eq!(f.app.selected, f.nodes[0]);
let _ = f.app.update(action);
let selection = f.app.multiselect_snapshot().unwrap();
assert_eq!(selection.targets(), &[local(f.nodes[0]), local(f.nodes[4])]);
assert_eq!(selection.primary(), Some(&local(f.nodes[4])));
assert_eq!(f.app.selected, f.nodes[4]);
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert!(!f.app.document.can_undo());
}
#[test]
fn process_qualified_nonprimary_menu_opens_definition_from_caller_and_back_returns() {
let (mut f, definition, first, _, leaf) = qualified_fixture();
choose(&mut f.app, local(f.nodes[0]), Choice::Replace);
let before = f.app.document.snapshot();
let target = Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![first],
occurrence: leaf,
});
let action = menu(&mut f.app, target, "Open referenced definition");
assert_eq!(f.app.selected, f.nodes[0]);
assert_eq!(f.app.topology_context().unwrap().owner, f.owner);
let _ = f.app.update(action);
assert_eq!(f.app.behavior.active_owner, Some(definition));
assert_eq!(f.app.topology_context().unwrap().owner, definition);
let context = f.app.topology_context().unwrap();
let _ = f
.app
.update(Message::TopologyCanvas(CanvasEvent::Back(context)));
assert_eq!(f.app.behavior.active_owner, Some(f.owner));
assert_eq!(f.app.topology_context().unwrap().owner, f.owner);
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert!(!f.app.document.can_undo());
}
#[test]
fn process_qualified_definition_back_restores_exact_invocation_readonly_subject_and_camera() {
for open_nonprimary in [false, true] {
let (mut f, definition, first, second, leaf) = qualified_fixture();
// The shared fixture has already expanded both fifth-tile invocations.
let context = f.app.topology_context().unwrap();
let _ = f.app.update(Message::TopologyCanvas(CanvasEvent::Zoom(
context,
Some(0.75),
)));
let first_target = Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![first],
occurrence: leaf,
});
let second_target = Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![second],
occurrence: leaf,
});
if open_nonprimary {
// Keep the requested second path outside the current selection so
// its ordinary definition action is available in its context menu.
choose(&mut f.app, local(f.nodes[0]), Choice::Replace);
choose(&mut f.app, first_target.clone(), Choice::Add);
} else {
choose(&mut f.app, first_target.clone(), Choice::Replace);
choose(&mut f.app, second_target.clone(), Choice::Add);
}
assert_eq!(f.app.multiselect_snapshot().unwrap().targets().len(), 2);
assert_eq!(
f.app.multiselect_snapshot().unwrap().primary(),
Some(if open_nonprimary {
&first_target
} else {
&second_target
})
);
assert_eq!(f.app.selected, leaf);
assert!(f.app.draft.is_none());
let original = f.app.document.snapshot();
let source = f.app.document.bundle().clone();
let camera = f.app.behavior.topology.camera_boundary();
let target = second_target;
let action = if open_nonprimary {
menu(&mut f.app, target.clone(), "Open referenced definition")
} else {
let Target::ProcessOccurrence(endpoint) = &target else {
unreachable!()
};
Message::TopologyCanvas(CanvasEvent::OpenQualified(
f.app.topology_context().unwrap(),
endpoint.clone(),
))
};
let _ = f.app.update(action);
assert_eq!(f.app.topology_context().unwrap().owner, definition);
assert_eq!(f.app.selected, leaf);
assert!(f.app.process_preview_primary().is_none());
assert!(f.app.draft.is_some(), "Definition view is editable");
let context = f.app.topology_context().unwrap();
let _ = f
.app
.update(Message::TopologyCanvas(CanvasEvent::Back(context)));
assert_eq!(f.app.topology_context().unwrap().owner, f.owner);
assert_eq!(f.app.behavior.active_owner, Some(f.owner));
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
std::slice::from_ref(&target)
);
assert_eq!(
f.app.multiselect_snapshot().unwrap().primary(),
Some(&target)
);
assert_eq!(
f.app.selected, leaf,
"Back must not inspect the outer reference"
);
assert_eq!(f.app.process_preview_primary(), Some(&target));
let Target::ProcessOccurrence(endpoint) = &target else {
unreachable!()
};
let address = f.app.behavior.topology.selection_address().unwrap();
assert_eq!(address.owner, f.owner);
assert_eq!(&address.endpoint, endpoint);
assert!(
f.app.multiselect_target_visible(&target),
"Caller expansions survive Back"
);
assert!(
f.app.draft.is_none(),
"Returned qualified inspector stays read-only"
);
assert!(f.app.behavior.topology.camera_boundary() == camera);
let _ = f.app.update(Message::Field(
"/name".into(),
"Must not edit the outer reference or definition".into(),
));
assert!(f.app.draft.is_none());
assert_eq!(f.app.process_preview_primary(), Some(&target));
assert!(Arc::ptr_eq(&original, &f.app.document.snapshot()));
assert_eq!(f.app.document.bundle(), &source);
assert!(!f.app.document.can_undo() && !f.app.document.can_redo());
source_matches(&f.app);
}
}
#[test]
fn process_open_current_qualified_primary_and_catalog_navigation_restore_editable_draft() {
for catalog in [false, true] {
let (mut f, definition, first, _, leaf) = qualified_fixture();
let target = Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![first],
occurrence: leaf,
});
choose(&mut f.app, target.clone(), Choice::Replace);
assert_eq!(f.app.selected, leaf);
assert!(f.app.draft.is_none());
let before = f.app.document.snapshot();
if catalog {
let _ = f.app.update(Message::Page(Page::Catalog));
assert_eq!(f.app.page, Page::Catalog);
} else {
let action = menu(&mut f.app, target, "Open referenced definition");
let _ = f.app.update(action);
assert_eq!(f.app.topology_context().unwrap().owner, definition);
}
assert_eq!(f.app.selected, leaf);
assert!(f.app.process_preview_primary().is_none());
assert!(
f.app.draft.is_some(),
"Leaving a read-only presentation restores normal property editing"
);
let _ = f.app.update(Message::Field(
"/name".into(),
"Definition edit stays unapplied".into(),
));
assert!(f.app.draft_dirty());
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert!(!f.app.document.can_undo());
}
}
#[test]
fn process_explicit_object_navigation_leaves_qualified_use_even_for_same_leaf_id() {
for edit_properties in [false, true] {
for defining_leaf in [false, true] {
let (mut f, definition, first, _, leaf) = qualified_fixture();
let qualified = Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![first],
occurrence: leaf,
});
choose(&mut f.app, qualified.clone(), Choice::Replace);
assert_eq!(f.app.selected, leaf);
assert_eq!(f.app.process_preview_primary(), Some(&qualified));
assert!(f.app.draft.is_none());
let before = f.app.document.snapshot();
let source = f.app.document.bundle().clone();
let camera = f.app.behavior.topology.camera_boundary();
let target = if defining_leaf { leaf } else { first };
let expected_owner = if defining_leaf { definition } else { f.owner };
let message = if edit_properties {
Message::EditProperties(target)
} else {
Message::Select(target)
};
let _ = f.app.update(message);
assert_eq!(f.app.selected, target);
assert_eq!(f.app.topology_context().unwrap().owner, expected_owner);
assert_eq!(f.app.behavior.active_owner, Some(expected_owner));
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
&[local(target)]
);
assert_eq!(
f.app.multiselect_snapshot().unwrap().primary(),
Some(&local(target))
);
assert!(f.app.behavior.topology.selection_address().is_none());
assert!(f.app.process_preview_primary().is_none());
assert!(
f.app.draft.is_some(),
"Explicit model-object navigation restores its editor"
);
assert!(!f.app.draft_dirty());
if !defining_leaf {
assert!(f.app.behavior.topology.camera_boundary() == camera);
}
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert_eq!(f.app.document.bundle(), &source);
assert!(!f.app.document.can_undo() && !f.app.document.can_redo());
source_matches(&f.app);
}
}
}
#[test]
fn process_open_local_reference_after_qualified_inspection_returns_local_reference() {
let (mut f, definition, first, _, leaf) = qualified_fixture();
choose(
&mut f.app,
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![first],
occurrence: leaf,
}),
Choice::Replace,
);
let before = f.app.document.snapshot();
let source = f.app.document.bundle().clone();
let camera = f.app.behavior.topology.camera_boundary();
let context = f.app.topology_context().unwrap();
let _ = f
.app
.update(Message::TopologyCanvas(CanvasEvent::Open(context, first)));
assert_eq!(f.app.topology_context().unwrap().owner, definition);
assert_eq!(f.app.selected, definition);
assert!(f.app.behavior.topology.selection_address().is_none());
let context = f.app.topology_context().unwrap();
let _ = f
.app
.update(Message::TopologyCanvas(CanvasEvent::Back(context)));
assert_eq!(f.app.topology_context().unwrap().owner, f.owner);
assert_eq!(f.app.selected, first);
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
&[local(first)]
);
assert!(f.app.behavior.topology.selection_address().is_none());
assert!(f.app.process_preview_primary().is_none());
assert!(f.app.draft.is_some());
assert!(f.app.behavior.topology.camera_boundary() == camera);
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
assert_eq!(f.app.document.bundle(), &source);
assert!(!f.app.document.can_undo() && !f.app.document.can_redo());
source_matches(&f.app);
}
#[test]
fn process_usage_navigation_between_two_preview_paths_keeps_exact_link_identity() {
use crate::diagram_usage as usage;
let (mut f, definition, first, second, leaf) = qualified_fixture();
let mut project = f.app.project().clone();
let next = add(
&mut project,
definition,
"Following check",
OccurrenceBody::Action {
action: Some(f.work),
lifeline: None,
},
);
let relation = project.relate(RelationKind::SequenceLink, "Reusable path", leaf, next);
f.app = open(project, f.owner);
let project = f.app.project().clone();
assert!(f.app.behavior.topology.expand(&project, f.owner, first));
assert!(f.app.behavior.topology.expand(&project, f.owner, second));
let before = f.app.document.snapshot();
for call in [first, second] {
let target = Target::ProcessPreviewLink {
relation,
source: OccurrenceEndpoint {
references: vec![call],
occurrence: leaf,
},
target: OccurrenceEndpoint {
references: vec![call],
occurrence: next,
},
};
let context = usage::Context {
document: f.app.canvas_document,
revision: f.app.document.revision(),
subject: relation,
};
let _ = f
.app
.update(Message::DiagramUsage(usage::Event::Open(context)));
let token = f.app.diagram_usages.as_ref().unwrap().token;
let rows = usage::collect(
f.app.project(),
relation,
&f.app.behavior.topology,
&f.app.behavior.scenario,
);
let row = rows
.iter()
.find(|row| row.surface == Surface::Process(f.owner) && row.target == target)
.unwrap()
.clone();
let _ = f.app.update(Message::DiagramUsagesReady(usage::Completion {
token,
context,
result: Ok(rows),
}));
let _ = f
.app
.update(Message::DiagramUsage(usage::Event::Choose(token, row)));
assert_eq!(f.app.selected, relation);
assert_eq!(
f.app.multiselect_snapshot().unwrap().primary(),
Some(&target)
);
assert_eq!(f.app.process_preview_primary(), Some(&target));
assert!(f.app.draft.is_none());
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
}
}
@@ -15,6 +15,7 @@ struct Input {
pan: Option<(mouse::Button, Point)>,
space: bool,
bounds: Option<Rectangle>,
modifiers: keyboard::Modifiers,
}
impl operation::Focusable for Input {
fn is_focused(&self) -> bool {
@@ -83,7 +84,11 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Viewport<'_,
(s.document, s.owner, s.revision)
!= (self.scope.document, self.scope.owner, self.scope.revision)
}) {
*state = Input::default();
let modifiers = state.modifiers;
*state = Input {
modifiers,
..Input::default()
};
}
if state
.scope
@@ -143,10 +148,29 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Viewport<'_,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
let state = tree.state.downcast_mut::<Input>();
if let Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) = event {
// Physical modifiers outlive focus, busy-state child replacement,
// and semantic revisions. Observing these emits no camera command.
state.modifiers = *modifiers;
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
return;
}
if matches!(event, Event::Window(iced::window::Event::Unfocused)) {
state.modifiers = keyboard::Modifiers::default();
}
if shell.is_event_captured() {
return;
}
let state = tree.state.downcast_mut::<Input>();
// A traversal operation is applied after this Iced event batch. Keep
// its focus witness, but retire keyboard admission immediately.
if state.focus_pending && matches!(event, Event::Keyboard(_)) {
@@ -334,6 +358,20 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Viewport<'_,
} else {
mouse::Cursor::Unavailable
};
if matches!(event, Event::Mouse(mouse::Event::ButtonPressed(_))) {
// A canvas may have been rebuilt while focus/commands were denied.
// Restore held (or released) Shift before this new pointer gesture.
self.content.as_widget_mut().update(
&mut tree.children[0],
&Event::Keyboard(keyboard::Event::ModifiersChanged(state.modifiers)),
layout,
child_cursor,
renderer,
clipboard,
shell,
viewport,
);
}
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
@@ -3,6 +3,58 @@ use crate::behavior::canvas_workspace::tests::{Geometry, Mounted};
use iced::Vector;
use iced::advanced::{Layout, layout, widget};
#[tokio::test]
async fn production_scenario_passive_modifiers_do_not_acquire_keyboard_focus_or_mutate_model() {
use crate::behavior::canvas_workspace::tests::{focused, key};
let f = super::super::direct_tests::fixture();
let mut app = App::with_project(f.project.clone());
let _ = app.update(Message::Select(f.owner));
let _ = app.update(Message::Page(crate::app::Page::Behavior));
app.window_size = Size::new(1100., 700.);
let mut mounted = Mounted::new(&mut app).await;
let bounds = mounted.geometry(&app).bounds("scenario-viewport");
let point = bounds.position() + Vector::new(50., 50.);
let camera = app.behavior.scenario.camera_boundary();
let source = app.document.bundle().clone();
let shift = |held| {
iced::Event::Keyboard(iced::keyboard::Event::ModifiersChanged(if held {
iced::keyboard::Modifiers::SHIFT
} else {
iced::keyboard::Modifiers::empty()
}))
};
for busy in [false, true, false] {
app.busy = busy;
mounted.settle(&mut app).await;
let messages = mounted
.batch(
&mut app,
&[
shift(true),
shift(false),
key(iced::keyboard::key::Named::ArrowRight),
],
mouse::Cursor::Available(point),
)
.await;
assert!(
!messages
.iter()
.any(|message| matches!(message, Message::ScenarioCanvas(_)))
);
assert!(!focused(&mut mounted, &app, "viewport"));
assert!(app.behavior.scenario.camera_boundary() == camera);
assert_eq!(app.document.bundle(), &source);
}
mounted
.pan(&mut app, point, point + Vector::new(-15., 25.))
.await;
assert!(app.behavior.scenario.camera_boundary() != camera);
assert_eq!(app.document.bundle(), &source);
assert!(!app.document.can_undo());
assert_eq!(mounted.geometry(&app).bounds("scenario-viewport"), bounds);
}
#[tokio::test]
async fn production_scenario_canvas_keeps_bounds_draft_identity_and_camera_through_editing() {
use crate::behavior::canvas_workspace::{self, tests::Mounted};
+74 -54
View File
@@ -5,8 +5,11 @@ use iced::widget::{Column, text_input};
use std::collections::BTreeSet;
pub(crate) mod contextual;
mod direct;
pub(crate) mod group_reorder;
mod usages;
mod view;
#[cfg(test)]
pub(crate) use direct::End;
use direct::Input;
pub(crate) use direct::{
CanvasEvent, CanvasTool, Context, Insertion, reconnect, referenced, reorder,
@@ -909,6 +912,53 @@ fn sequence_links(p: &Project, owner: Id) -> Vec<&Relation> {
})
.collect()
}
/// Integer columns shared by rendering and order planning. Edges whose endpoints
/// are absent from the displayed order cannot participate in its layout.
fn column_ranks(order: &[Id], adjacency: &[(Id, Id)]) -> BTreeMap<Id, usize> {
let ids: BTreeSet<_> = order.iter().copied().collect();
let adjacency: Vec<_> = adjacency
.iter()
.copied()
.filter(|(source, target)| ids.contains(source) && ids.contains(target))
.collect();
let mut incoming: BTreeMap<_, usize> = ids.iter().map(|id| (*id, 0)).collect();
let mut ranks: BTreeMap<_, usize> = ids.iter().map(|id| (*id, 0)).collect();
for &(_, target) in &adjacency {
*incoming.get_mut(&target).expect("Displayed endpoint") += 1;
}
let mut queue: Vec<_> = order
.iter()
.copied()
.filter(|id| incoming[id] == 0)
.collect();
let mut done = BTreeSet::new();
let mut offset = 0;
while offset < queue.len() {
let id = queue[offset];
offset += 1;
if !done.insert(id) {
continue;
}
for &(_, next) in adjacency.iter().filter(|(source, _)| *source == id) {
ranks.insert(next, ranks[&next].max(ranks[&id] + 1));
let count = incoming.get_mut(&next).expect("Displayed endpoint");
*count = count.saturating_sub(1);
if *count == 0 {
queue.push(next);
}
}
}
// Preserve deterministic fallback order for loops and cycle-blocked nodes.
let mut fallback = ranks.values().copied().max().unwrap_or(0) + 1;
for id in order {
if !done.contains(id) {
ranks.insert(*id, fallback);
fallback += 1;
}
}
ranks
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct PreviewLink {
relation: Id,
@@ -1066,6 +1116,7 @@ struct Graph<'a> {
selected: Id,
selected_preview: Option<OccurrenceEndpoint>,
selected_preview_link: Option<PreviewLink>,
selection: Option<crate::diagram_selection::Snapshot>,
scale: f32,
}
impl<'a> Graph<'a> {
@@ -1084,50 +1135,19 @@ impl<'a> Graph<'a> {
) -> Self {
let context_index = oa_core::topology_context::TopologyIndex::new(p);
let choices = contributions(p, owner);
let links = sequence_links(p, owner);
let displayed: BTreeSet<_> = choices.iter().map(|choice| choice.id).collect();
let links: Vec<_> = sequence_links(p, owner)
.into_iter()
.filter(|link| displayed.contains(&link.source()) && displayed.contains(&link.target()))
.collect();
let order = legacy_order(p, owner);
let adjacency: Vec<_> = links
.iter()
.map(|r| (r.source(), r.target()))
.chain(order.windows(2).map(|pair| (pair[0], pair[1])))
.collect();
let ids: BTreeSet<_> = choices.iter().map(|c| c.id).collect();
let mut incoming: BTreeMap<_, usize> = ids.iter().map(|id| (*id, 0)).collect();
let mut ranks: BTreeMap<_, usize> = ids.iter().map(|id| (*id, 0)).collect();
for &(_, target) in &adjacency {
*incoming.entry(target).or_default() += 1;
}
let mut queue: Vec<_> = choices
.iter()
.filter(|c| incoming[&c.id] == 0)
.map(|c| c.id)
.collect();
let mut done = BTreeSet::new();
let mut offset = 0;
while offset < queue.len() {
let id = queue[offset];
offset += 1;
if !done.insert(id) {
continue;
}
for &(_, next) in adjacency.iter().filter(|(source, _)| *source == id) {
ranks.insert(next, ranks[&next].max(ranks[&id] + 1));
let count = incoming.get_mut(&next).expect("Graph endpoint");
*count = count.saturating_sub(1);
if *count == 0 {
queue.push(next);
}
}
}
// Cycles remain explicit edges; deterministic fallback placement must
// terminate even while users are building a loop or incomplete graph.
let mut fallback = ranks.values().copied().max().unwrap_or(0) + 1;
for c in &choices {
if !done.contains(&c.id) {
ranks.insert(c.id, fallback);
fallback += 1;
}
}
let displayed_order: Vec<_> = choices.iter().map(|choice| choice.id).collect();
let ranks = column_ranks(&displayed_order, &adjacency);
let mut rows: BTreeMap<usize, f32> = BTreeMap::new();
let mut nodes = vec![];
let mut size: Size = Size::new(640., 220.);
@@ -1238,25 +1258,17 @@ impl<'a> Graph<'a> {
}
let ordered_paths = order
.windows(2)
.map(|pair| {
let a = nodes
.iter()
.find(|n| n.id == pair[0])
.expect("ordered source")
.rect;
let b = nodes
.iter()
.find(|n| n.id == pair[1])
.expect("ordered target")
.rect;
OrderedPath {
.filter_map(|pair| {
let a = nodes.iter().find(|n| n.id == pair[0])?.rect;
let b = nodes.iter().find(|n| n.id == pair[1])?.rect;
Some(OrderedPath {
source: pair[0],
target: pair[1],
points: vec![
Point::new(a.x + a.width, a.center_y()),
Point::new(b.x, b.center_y()),
],
}
})
})
.collect();
let mut edges = vec![];
@@ -1400,6 +1412,7 @@ impl<'a> Graph<'a> {
selected,
selected_preview: None,
selected_preview_link: None,
selection: None,
scale: 1.,
}
}
@@ -1518,9 +1531,16 @@ impl canvas::Program<Message> for Graph<'_> {
EdgeLayer::Contextual
}
}) {
let selected = e.id == self.selected
|| e.source == self.selected
|| e.target == self.selected;
let selected = self.selection.as_ref().map_or(
e.id == self.selected
|| e.source == self.selected
|| e.target == self.selected,
|selection| {
selection
.targets()
.contains(&crate::diagram_usage::Target::ProcessLink(e.id))
},
);
if e.incidence {
f.stroke(
&Path::new(|path| {
@@ -1,5 +1,7 @@
//! Local pointer state and ordinary command proposals for the derived process graph.
use super::*;
#[path = "direct_selection.rs"]
mod selection;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Context {
@@ -445,27 +447,23 @@ pub(crate) fn reconnect(
execute_batch(p, std::slice::from_ref(&command)).map_err(|e| e.to_string())?;
Ok(command)
}
pub(crate) fn reorder(p: &Project, owner: Id, id: Id, before: Id) -> Result<Command, String> {
if !is_contribution(p, owner, id) || !is_contribution(p, owner, before) {
return Err("Reorder contributions in this process only.".into());
}
let graph = Graph::new(p, owner, id);
let position = |id| graph.nodes.iter().find(|n| n.id == id).map(|n| n.rect.x);
if position(id) != position(before) {
return Err("Reorder within this column; links determine the path columns.".into());
}
let mut steps = p.elements[&owner].steps().unwrap().clone();
if id != before {
steps.retain(|v| *v != id);
let index = steps
.iter()
.position(|v| *v == before)
.ok_or("This slot no longer exists.")?;
steps.insert(index, id);
}
let command = Command::SetSteps(owner, steps);
execute_batch(p, std::slice::from_ref(&command)).map_err(|e| e.to_string())?;
Ok(command)
pub(crate) fn reorder(
p: &Project,
owner: Id,
id: Id,
before: Id,
) -> Result<super::group_reorder::Plan, String> {
super::group_reorder::Prepared::new(
p,
owner,
&[crate::diagram_usage::Target::ProcessOccurrence(
OccurrenceEndpoint {
references: vec![],
occurrence: id,
},
)],
)?
.plan(super::group_reorder::Destination::Before(before))
}
#[derive(Default)]
@@ -476,6 +474,8 @@ pub(super) struct Input {
bounds: Option<Rectangle>,
source: Option<Id>,
press: Option<Press>,
modifiers: iced::keyboard::Modifiers,
group: Option<selection::GroupPress>,
}
#[derive(Clone, Copy)]
enum Press {
@@ -504,6 +504,7 @@ impl Input {
fn cancel(&mut self) {
self.source = None;
self.press = None;
self.group = None;
}
}
impl Graph<'_> {
@@ -592,6 +593,9 @@ impl Graph<'_> {
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Option<Action<Message>> {
if let Some(action) = self.selection_input(state, event, bounds, cursor) {
return Some(action);
}
let (context, tool, editable) = self
.interaction
.map_or((None, CanvasTool::Select, false), |(c, t, e)| {
@@ -835,6 +839,7 @@ impl Graph<'_> {
cursor: mouse::Cursor,
bounds: Rectangle,
) {
self.selection_overlay(state, f, bounds);
let Some((context, tool, editable)) = self.interaction else {
return;
};
@@ -935,7 +940,12 @@ impl Graph<'_> {
);
}
}
if tool == CanvasTool::Select {
if tool == CanvasTool::Select
&& self
.selection
.as_ref()
.is_none_or(|s| s.targets().len() == 1)
{
if let Some(r) = self.handle(self.selected) {
f.fill_rectangle(r.position(), r.size(), Color::WHITE);
draw_text(f, "↕".into(), r.position(), 17., style::TEAL);
@@ -0,0 +1,474 @@
//! Exact-target selection and an order gesture over one immutable selection.
use super::super::group_reorder::{Destination, Plan, Prepared};
use super::*;
use crate::app::multiselect::{Choice, Event as SelectionEvent, process_context};
use crate::diagram_selection::Snapshot;
use crate::diagram_usage::Target;
pub(super) struct GroupPress {
snapshot: Snapshot,
target: Target,
start: Point,
bounds: Rectangle,
pan: iced::Vector,
scale: f32,
crossed: bool,
retired: bool,
prepared: Result<Prepared, String>,
destination: Option<Destination>,
plan: Option<Result<Plan, String>>,
}
impl Graph<'_> {
fn exact_target_at(&self, point: Point) -> Option<Target> {
// Visible singleton reconnect rings are painted over the card/edge.
// Shift and context selection must resolve that same topmost target.
if self.interaction.is_some_and(|(_, tool, editable)| editable && tool == CanvasTool::Select)
&& self.selection.as_ref().is_some_and(|snapshot| {
snapshot.targets().len() == 1
&& matches!(snapshot.primary(), Some(Target::ProcessLink(id)) if *id == self.selected)
})
&& let Some((link, _)) = self.endpoint_at(point)
{
return Some(Target::ProcessLink(link));
}
if let Some(endpoint) = self.qualified_at(point) {
return Some(Target::ProcessOccurrence(endpoint));
}
for node in &self.nodes {
for link in &node.preview_links {
if node
.preview_link_visible_segment(link)
.is_some_and(|[a, b]| {
crate::diagram::distance_to_segment(point, a, b) < 5. / self.scale
})
{
return Some(Target::ProcessPreviewLink {
relation: link.relation,
source: link.source.clone(),
target: link.target.clone(),
});
}
}
}
self.contextual_edge_at(point)
.map(Target::ProcessLink)
.or_else(|| {
self.node_at(point).map(|id| {
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: id,
})
})
})
.or_else(|| self.edge_at(point).map(Target::ProcessLink))
}
fn destination_at(&self, point: Point) -> Option<Destination> {
let id = self.node_at(point)?;
let node = self.nodes.iter().find(|n| n.id == id)?;
Some(if point.y < node.rect.center_y() {
Destination::Before(id)
} else {
Destination::After(id)
})
}
fn update_group(&self, group: &mut GroupPress, pointer: Point) {
if group.retired {
return;
}
if !pointer.x.is_finite() || !pointer.y.is_finite() || !group.bounds.contains(pointer) {
group.retired = true;
group.plan = None;
return;
}
group.crossed |= pointer.distance(group.start) >= 3.;
let world = Point::new(
(pointer.x - group.bounds.x - self.camera_pan.x) / self.scale,
(pointer.y - group.bounds.y - self.camera_pan.y) / self.scale,
);
let destination = self.destination_at(world);
// The captured semantic facts are prepared once. Only a changed object
// anchor/side needs another order plan; motion within a slot is free.
if destination != group.destination {
group.destination = destination;
group.plan = destination.map(|destination| match &group.prepared {
Ok(prepared) => prepared.plan(destination),
Err(reason) => Err(reason.clone()),
});
}
}
pub(super) fn selection_input(
&self,
state: &mut Input,
event: &canvas::Event,
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Option<Action<Message>> {
use iced::keyboard::{Event as KeyEvent, Key, key::Named};
match event {
canvas::Event::Keyboard(KeyEvent::ModifiersChanged(modifiers))
| canvas::Event::Keyboard(KeyEvent::KeyPressed { modifiers, .. })
| canvas::Event::Keyboard(KeyEvent::KeyReleased { modifiers, .. }) => {
state.modifiers = *modifiers
}
canvas::Event::Window(iced::window::Event::Unfocused) => {
state.modifiers = iced::keyboard::Modifiers::empty()
}
_ => {}
}
let Some((context, tool, editable)) = self.interaction else {
state.group = None;
return None;
};
let snapshot = self
.selection
.as_ref()
.filter(|s| s.context() == process_context(context));
if let Some(group) = &state.group {
let cancelled = !editable
|| tool != CanvasTool::Select
|| snapshot != Some(&group.snapshot)
|| group.bounds != bounds
|| group.pan != self.camera_pan
|| group.scale != self.scale
|| matches!(
event,
canvas::Event::Window(
iced::window::Event::Unfocused | iced::window::Event::Resized(_)
) | canvas::Event::Mouse(
mouse::Event::CursorLeft
| mouse::Event::WheelScrolled { .. }
| mouse::Event::ButtonPressed(
mouse::Button::Right | mouse::Button::Middle
)
) | canvas::Event::Keyboard(KeyEvent::KeyPressed {
key: Key::Named(Named::Escape),
..
})
);
if cancelled {
state.cancel();
state.pointer = None;
return Some(Action::request_redraw().and_capture());
}
}
if let Some(group) = &mut state.group {
match event {
canvas::Event::Mouse(mouse::Event::CursorMoved { position }) => {
state.pointer = Some(*position);
self.update_group(group, *position);
return Some(Action::request_redraw().and_capture());
}
canvas::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
let mut group = state.group.take().unwrap();
// An unavailable cursor must never reuse the last inside point.
if let Some(pointer) = cursor.position() {
self.update_group(&mut group, pointer);
} else {
group.retired = true;
}
let result = if group.retired {
None
} else if !group.crossed {
Some(SelectionEvent::Collapse(group.snapshot, group.target))
} else if let Err(reason) = group.prepared {
Some(SelectionEvent::Refuse(group.snapshot, reason))
} else {
match (group.destination, group.plan) {
(Some(destination), Some(Ok(Plan::Change(_)))) => {
Some(SelectionEvent::ProcessReorder(group.snapshot, destination))
}
(_, Some(Err(reason))) => {
Some(SelectionEvent::Refuse(group.snapshot, reason))
}
_ => None,
}
};
return Some(
result
.map_or_else(Action::request_redraw, |event| {
Action::publish(Message::DiagramSelection(event))
})
.and_capture(),
);
}
canvas::Event::Keyboard(iced::keyboard::Event::ModifiersChanged(_)) => return None,
canvas::Event::Keyboard(_) => return Some(Action::capture()),
_ => {}
}
}
let snapshot = snapshot?;
if !editable {
return None;
}
let publish = |event| Some(Action::publish(Message::DiagramSelection(event)).and_capture());
if matches!(
event,
canvas::Event::Keyboard(KeyEvent::KeyPressed {
key: Key::Named(Named::Delete),
repeat: false,
..
})
) && (snapshot.targets().len() > 1
|| snapshot.targets().iter().any(|t| match t {
Target::ProcessPreviewLink { .. } => true,
Target::ProcessOccurrence(endpoint) => !endpoint.references.is_empty(),
_ => false,
}))
{
return publish(SelectionEvent::Refuse(snapshot.clone(), "Remove is unavailable for this selection. Open the referenced definition to edit qualified contributions; group removal needs an aggregate review.".into()));
}
let pointer = match event {
canvas::Event::Mouse(mouse::Event::CursorMoved { position }) => Some(*position),
_ => cursor.position().and(state.pointer.or(cursor.position())),
}?;
if !bounds.contains(pointer) {
return None;
}
let world = Point::new(
(pointer.x - bounds.x - self.camera_pan.x) / self.scale,
(pointer.y - bounds.y - self.camera_pan.y) / self.scale,
);
if matches!(
event,
canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right))
) {
state.cancel();
let target = self.exact_target_at(world)?;
let object = match &target {
Target::ProcessOccurrence(endpoint) => endpoint.occurrence,
Target::ProcessLink(id) | Target::ProcessPreviewLink { relation: id, .. } => *id,
_ => return None,
};
let mut request = crate::model_menu::Request::object(object, pointer);
request.selection_target = Some(Box::new(target));
request.process = Some(Box::new(context));
return Some(
Action::publish(Message::Menu(crate::model_menu::Event::Open(request)))
.and_capture(),
);
}
if !matches!(
event,
canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
) {
return None;
}
if tool == CanvasTool::Connect && snapshot.targets().len() > 1 {
state.cancel();
return publish(SelectionEvent::Refuse(
snapshot.clone(),
"Connecting a selection as a group is unavailable. Select one contribution first."
.into(),
));
}
if tool != CanvasTool::Select {
return None;
}
let target = self.exact_target_at(world);
if state.modifiers.shift() {
state.cancel();
return target
.and_then(|target| {
publish(SelectionEvent::Choose(
process_context(context),
target,
Choice::Toggle,
))
})
.or_else(|| Some(Action::capture()));
}
let Some(target) = target else {
state.cancel();
// Clearing and starting the existing background camera pan can
// share this press; only semantic object hits capture it.
return Some(Action::publish(Message::DiagramSelection(
SelectionEvent::Clear(process_context(context)),
)));
};
// The ordinary endpoint gesture is valid only for an exact singleton
// local link. A mixed selection must never reconnect just its primary.
if snapshot.targets().len() == 1
&& matches!(snapshot.primary(), Some(Target::ProcessLink(id)) if *id == self.selected)
&& self.endpoint_at(world).is_some()
{
return None;
}
if !snapshot.targets().contains(&target) {
state.cancel();
return publish(SelectionEvent::Choose(
process_context(context),
target,
Choice::Replace,
));
}
state.cancel();
state.context = Some(context);
state.tool = tool;
state.bounds = Some(bounds);
state.pointer = Some(pointer);
state.group = Some(GroupPress {
snapshot: snapshot.clone(),
target,
start: pointer,
bounds,
pan: self.camera_pan,
scale: self.scale,
crossed: false,
retired: false,
prepared: Prepared::new(self.project, context.owner, snapshot.targets()),
destination: None,
plan: None,
});
Some(Action::request_redraw().and_capture())
}
pub(super) fn selection_overlay(&self, state: &Input, frame: &mut Frame, bounds: Rectangle) {
if let Some(selection) = &self.selection {
for target in selection.targets() {
let primary = selection.primary() == Some(target);
let width = if primary { 3.5 } else { 2. };
let color = if primary {
style::TEAL
} else {
Color::from_rgb8(64, 123, 188)
};
match target {
Target::ProcessOccurrence(endpoint) => {
let rect = if endpoint.references.is_empty() {
self.nodes
.iter()
.find(|n| n.id == endpoint.occurrence)
.map(|n| n.rect)
} else {
self.nodes
.iter()
.find(|n| n.preview.iter().any(|(shown, _)| shown == endpoint))
.map(|n| n.endpoint_rect(endpoint))
};
if let Some(rect) = rect {
frame.stroke(
&Path::rounded_rectangle(rect.position(), rect.size(), 5.into()),
Stroke::default().with_color(color).with_width(width),
);
}
}
Target::ProcessPreviewLink {
relation,
source,
target,
} => {
let link = PreviewLink {
relation: *relation,
source: source.clone(),
target: target.clone(),
};
for node in &self.nodes {
if node.preview_links.contains(&link)
&& let Some([a, b]) = node.preview_link_visible_segment(&link)
{
frame.stroke(
&Path::line(a, b),
Stroke::default().with_color(color).with_width(width),
);
}
}
}
_ => {}
}
}
}
let Some(group) = &state.group else {
return;
};
if group.retired
|| !group.crossed
|| group.bounds != bounds
|| self.selection.as_ref() != Some(&group.snapshot)
|| group.pan != self.camera_pan
|| group.scale != self.scale
{
return;
}
let reason = group
.prepared
.as_ref()
.err()
.or_else(|| group.plan.as_ref().and_then(|plan| plan.as_ref().err()));
let color = if reason.is_some() {
Color::from_rgb8(178, 49, 49)
} else {
style::TEAL
};
let mut position = state
.pointer
.map(|p| {
Point::new(
(p.x - bounds.x - self.camera_pan.x) / self.scale + 12.,
(p.y - bounds.y - self.camera_pan.y) / self.scale + 18.,
)
})
.unwrap_or(Point::ORIGIN);
if let Some(destination) = group.destination {
let (id, after) = match destination {
Destination::Before(id) => (id, false),
Destination::After(id) => (id, true),
};
if let Some(node) = self.nodes.iter().find(|n| n.id == id) {
let y = if after {
node.rect.y + node.rect.height + 7.
} else {
node.rect.y - 7.
};
frame.stroke(
&Path::line(
Point::new(node.rect.x, y),
Point::new(node.rect.x + node.rect.width, y),
),
Stroke::default().with_color(color).with_width(3.),
);
position = Point::new(node.rect.x, y + 3.);
}
}
let caption = reason.cloned().unwrap_or_else(|| match &group.plan {
Some(Ok(Plan::Noop)) => "Order unchanged".into(),
Some(Ok(Plan::Change(_))) => format!(
"Insert {} in source order · paths unchanged",
group.snapshot.targets().len()
),
_ => "Point at a card's upper / lower half to insert before / after".into(),
});
draw_text(frame, caption, position, 12. / self.scale, color);
if reason.is_none() {
let mut index = 0;
// Graph nodes are in original steps order; these numbers describe
// the block the exact same cached plan will commit on release.
for node in &self.nodes {
if group
.snapshot
.targets()
.contains(&Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: node.id,
}))
{
index += 1;
draw_text(
frame,
format!("{index}"),
Point::new(node.rect.x + node.rect.width - 18., node.rect.y + 7.),
13.,
style::TEAL,
);
}
}
}
}
}
#[cfg(test)]
#[path = "direct_selection_tests.rs"]
mod tests;
@@ -0,0 +1,403 @@
use super::*;
use crate::behavior::topology::direct_tests::{Fixture, context, fixture};
use crate::diagram_selection::Selection;
fn local(id: Id) -> Target {
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: id,
})
}
fn peers(layer: Layer) -> Fixture {
let mut fixture = fixture(layer);
fixture.p = execute_batch(&fixture.p, &[Command::Delete(fixture.link)]).unwrap();
fixture
}
fn graph<'a>(fixture: &'a Fixture, targets: &[Target]) -> Graph<'a> {
let context = context(fixture.owner);
let mut selection = Selection::new(process_context(context).scope);
for target in targets {
selection.add(target.clone(), |_| true);
}
let mut graph = Graph::new(&fixture.p, fixture.owner, fixture.owner);
graph.interaction = Some((context, CanvasTool::Select, true));
graph.selection = selection.snapshot(process_context(context));
graph
}
fn bounds() -> Rectangle {
Rectangle::new(Point::ORIGIN, Size::new(1800., 1400.))
}
fn point(graph: &Graph<'_>, id: Id, after: bool) -> Point {
let rect = graph.nodes.iter().find(|node| node.id == id).unwrap().rect;
Point::new(
rect.x + 70.,
rect.y + if after { rect.height - 15. } else { 20. },
)
}
fn send(
graph: &Graph<'_>,
input: &mut Input,
event: canvas::Event,
point: Point,
) -> Option<Message> {
graph
.input(input, &event, bounds(), mouse::Cursor::Available(point))
.and_then(|action| action.into_inner().0)
}
fn press(graph: &Graph<'_>, input: &mut Input, point: Point) -> Option<Message> {
send(
graph,
input,
canvas::Event::Mouse(mouse::Event::CursorMoved { position: point }),
point,
);
send(
graph,
input,
canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
point,
)
}
fn release(graph: &Graph<'_>, input: &mut Input, point: Point) -> Option<Message> {
send(
graph,
input,
canvas::Event::Mouse(mouse::Event::CursorMoved { position: point }),
point,
);
send(
graph,
input,
canvas::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
point,
)
}
#[test]
fn exact_shift_toggle_and_stationary_group_click_defer_primary() {
let f = peers(Layer::Oa);
let graph = graph(&f, &[local(f.nodes[2]), local(f.nodes[0])]);
let mut input = Input::default();
let at = point(&graph, f.nodes[2], false);
assert!(press(&graph, &mut input, at).is_none());
assert!(
matches!(release(&graph, &mut input, at), Some(Message::DiagramSelection(SelectionEvent::Collapse(snapshot, target)))
if target == local(f.nodes[2]) && snapshot == graph.selection.clone().unwrap())
);
send(
&graph,
&mut input,
canvas::Event::Keyboard(iced::keyboard::Event::ModifiersChanged(
iced::keyboard::Modifiers::SHIFT,
)),
at,
);
assert!(
matches!(press(&graph, &mut input, at), Some(Message::DiagramSelection(SelectionEvent::Choose(_, target, Choice::Toggle))) if target == local(f.nodes[2]))
);
assert!(input.group.is_none());
send(
&graph,
&mut input,
canvas::Event::Window(iced::window::Event::Unfocused),
at,
);
assert!(!input.modifiers.shift());
}
#[test]
fn group_drag_uses_midpoint_anchors_and_original_order_and_singleton_after_gap() {
for layer in [Layer::Oa, Layer::Sa] {
let f = peers(layer);
for targets in [
vec![local(f.nodes[2]), local(f.nodes[0])],
vec![local(f.nodes[0])],
] {
let graph = graph(&f, &targets);
let mut input = Input::default();
let start = point(&graph, f.nodes[0], false);
let end = point(&graph, f.nodes[1], true);
assert!(press(&graph, &mut input, start).is_none());
let Some(Message::DiagramSelection(SelectionEvent::ProcessReorder(
snapshot,
destination,
))) = release(&graph, &mut input, end)
else {
panic!("admitted after slot");
};
assert_eq!(snapshot, graph.selection.clone().unwrap());
assert_eq!(destination, Destination::After(f.nodes[1]));
let Plan::Change(command) = Prepared::new(&f.p, f.owner, snapshot.targets())
.unwrap()
.plan(destination)
.unwrap()
else {
panic!("changed steps");
};
let Command::SetSteps(owner, steps) = *command else {
panic!("expected SetSteps");
};
assert_eq!(owner, f.owner);
assert_eq!(steps, vec![f.nodes[1], f.nodes[0], f.nodes[2]]);
}
}
}
#[test]
fn selected_anchor_noop_and_irreversible_threshold_never_collapse_after_motion() {
let f = peers(Layer::Oa);
let graph = graph(&f, &[local(f.nodes[0]), local(f.nodes[2])]);
let mut input = Input::default();
let start = point(&graph, f.nodes[0], false);
press(&graph, &mut input, start);
let away = start + iced::Vector::new(10., 0.);
send(
&graph,
&mut input,
canvas::Event::Mouse(mouse::Event::CursorMoved { position: away }),
away,
);
assert!(release(&graph, &mut input, start).is_none());
assert!(input.group.is_none());
press(&graph, &mut input, start);
let outside = Point::new(-1., 100.);
send(
&graph,
&mut input,
canvas::Event::Mouse(mouse::Event::CursorMoved { position: outside }),
outside,
);
assert!(release(&graph, &mut input, point(&graph, f.nodes[1], true)).is_none());
}
#[test]
fn whole_mixed_set_refuses_drag_delete_and_connect_without_singleton_bypass() {
let f = fixture(Layer::Sa);
let mut graph = graph(&f, &[local(f.nodes[0]), Target::ProcessLink(f.link)]);
graph.selected = f.link;
let mut input = Input::default();
let start = point(&graph, f.nodes[0], false);
press(&graph, &mut input, start);
assert!(
matches!(release(&graph, &mut input, point(&graph, f.nodes[2], true)), Some(Message::DiagramSelection(SelectionEvent::Refuse(snapshot, _))) if snapshot.targets().len() == 2)
);
let key = crate::behavior::canvas_workspace::tests::key(iced::keyboard::key::Named::Delete);
let iced::Event::Keyboard(key) = key else {
panic!("keyboard");
};
assert!(matches!(
send(&graph, &mut input, canvas::Event::Keyboard(key), start),
Some(Message::DiagramSelection(SelectionEvent::Refuse(_, _)))
));
graph.interaction.as_mut().unwrap().1 = CanvasTool::Connect;
assert!(matches!(
press(&graph, &mut input, start),
Some(Message::DiagramSelection(SelectionEvent::Refuse(_, _)))
));
}
#[test]
fn camera_busy_context_bounds_and_escape_retire_captured_gestures() {
let f = peers(Layer::Oa);
for change in 0..6 {
let mut graph = graph(&f, &[local(f.nodes[0]), local(f.nodes[2])]);
let mut input = Input::default();
let start = point(&graph, f.nodes[0], false);
press(&graph, &mut input, start);
match change {
0 => graph.camera_pan.x += 1.,
1 => graph.scale = 2.,
2 => graph.interaction.as_mut().unwrap().2 = false,
3 => graph.interaction.as_mut().unwrap().0.epoch += 1,
4 => {
let iced::Event::Keyboard(key) = crate::behavior::canvas_workspace::tests::key(
iced::keyboard::key::Named::Escape,
) else {
panic!("keyboard");
};
send(&graph, &mut input, canvas::Event::Keyboard(key), start);
}
_ => {
graph.input(
&mut input,
&canvas::Event::Mouse(mouse::Event::CursorMoved { position: start }),
Rectangle::new(Point::new(1., 0.), bounds().size()),
mouse::Cursor::Available(start),
);
}
}
assert!(release(&graph, &mut input, point(&graph, f.nodes[1], true)).is_none());
assert!(input.group.is_none());
}
}
#[test]
fn qualified_occurrences_and_visible_preview_links_keep_exact_invocation_paths() {
let mut f = peers(Layer::Oa);
let source =
f.p.make_element(Kind::Process, Layer::Oa, "Reusable", None)
.unwrap();
let source_id = source.id;
f.p = execute_batch(&f.p, &[Command::CreateElement(source)]).unwrap();
let mut leaves = vec![];
for name in ["One", "Two"] {
let leaf = occurrence(
&f.p,
source_id,
name,
OccurrenceBody::Action {
action: Some(f.work[0]),
lifeline: None,
},
);
leaves.push(leaf.id);
f.p = execute_batch(&f.p, &[Command::CreateElement(leaf)]).unwrap();
}
let link = link(&f.p, leaves[0], leaves[1], "");
f.p = execute_batch(&f.p, &[link]).unwrap();
let mut references = vec![];
for name in ["First", "Second"] {
let reference = occurrence(
&f.p,
f.owner,
name,
OccurrenceBody::SequenceReference {
sequence: Some(source_id),
},
);
references.push(reference.id);
f.p = execute_batch(&f.p, &[Command::CreateElement(reference)]).unwrap();
}
let graph = graph(&f, &[]);
let mut targets = vec![];
for reference in references {
let node = graph.nodes.iter().find(|n| n.id == reference).unwrap();
let endpoint = OccurrenceEndpoint {
references: vec![reference],
occurrence: leaves[0],
};
let tile = node.endpoint_rect(&endpoint).center();
assert_eq!(
graph.exact_target_at(tile),
Some(Target::ProcessOccurrence(endpoint.clone()))
);
targets.push(Target::ProcessOccurrence(endpoint));
let link = &node.preview_links[0];
let [a, b] = node.preview_link_visible_segment(link).unwrap();
let at = Point::new((a.x + b.x) / 2., (a.y + b.y) / 2.);
let expected = Target::ProcessPreviewLink {
relation: link.relation,
source: link.source.clone(),
target: link.target.clone(),
};
assert_eq!(graph.exact_target_at(at), Some(expected.clone()));
let mut input = Input::default();
send(
&graph,
&mut input,
canvas::Event::Keyboard(iced::keyboard::Event::ModifiersChanged(
iced::keyboard::Modifiers::SHIFT,
)),
at,
);
assert!(
matches!(press(&graph, &mut input, at), Some(Message::DiagramSelection(SelectionEvent::Choose(_, target, Choice::Toggle))) if target == expected)
);
assert!(
matches!(send(&graph, &mut input, canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right)), at), Some(Message::Menu(crate::model_menu::Event::Open(request))) if request.selection_target.as_deref() == Some(&expected) && request.process.as_deref().copied() == graph.interaction.map(|(context,_,_)| context))
);
}
assert_ne!(targets[0], targets[1]);
assert!(Prepared::new(&f.p, f.owner, &targets).is_err());
}
// The endpoint ring is drawn last, over the underlying contribution card.
// Probe two pixels inside that card: both semantic shapes occupy the point,
// so these tests establish the visible handle's selection precedence.
fn handle_point(graph: &Graph<'_>, link: Id, end: End) -> Point {
let edge = graph.edges.iter().find(|edge| edge.id == link).unwrap();
match end {
End::Source => edge.points[0] + iced::Vector::new(-2., 0.),
End::Target => *edge.points.last().unwrap() + iced::Vector::new(2., 0.),
}
}
#[test]
fn singleton_process_link_snapshot_reconnects_both_ends_but_stationary_release_is_inert() {
for layer in [Layer::Oa, Layer::Sa] {
let f = fixture(layer);
for end in [End::Source, End::Target] {
let mut graph = graph(&f, &[Target::ProcessLink(f.link)]);
graph.selected = f.link;
let original = graph.selection.clone().unwrap();
let start = handle_point(&graph, f.link, end);
let mut input = Input::default();
assert!(press(&graph, &mut input, start).is_none());
assert!(input.group.is_none());
assert!(
matches!(input.press, Some(Press::Reconnect { link, end: armed, moved: false, .. }) if link == f.link && armed == end)
);
assert!(release(&graph, &mut input, start).is_none());
assert!(input.press.is_none());
assert_eq!(graph.selection.as_ref(), Some(&original));
assert!(press(&graph, &mut input, start).is_none());
let target = point(&graph, f.nodes[2], false);
assert!(matches!(release(&graph, &mut input, target),
Some(Message::TopologyCanvas(CanvasEvent::Reconnect { context, link, end: actual, target }))
if context == graph.interaction.unwrap().0 && link == f.link && actual == end && target == f.nodes[2]));
assert!(input.group.is_none());
assert_eq!(graph.selection.as_ref(), Some(&original));
}
}
}
#[test]
fn shift_on_visible_singleton_process_link_handle_toggles_that_link_not_underlying_card() {
for layer in [Layer::Oa, Layer::Sa] {
let f = fixture(layer);
for (end, underneath) in [(End::Source, f.nodes[0]), (End::Target, f.nodes[1])] {
let mut graph = graph(&f, &[Target::ProcessLink(f.link)]);
graph.selected = f.link;
let start = handle_point(&graph, f.link, end);
assert_eq!(graph.node_at(start), Some(underneath));
let mut input = Input::default();
send(
&graph,
&mut input,
canvas::Event::Keyboard(iced::keyboard::Event::ModifiersChanged(
iced::keyboard::Modifiers::SHIFT,
)),
start,
);
assert!(matches!(press(&graph, &mut input, start),
Some(Message::DiagramSelection(SelectionEvent::Choose(_, Target::ProcessLink(id), Choice::Toggle)))
if id == f.link));
assert!(input.group.is_none() && input.press.is_none());
}
}
}
#[test]
fn mixed_group_at_endpoint_card_refuses_whole_drag_without_hidden_singleton_handle() {
for layer in [Layer::Oa, Layer::Sa] {
let f = fixture(layer);
for (end, underneath) in [(End::Source, f.nodes[0]), (End::Target, f.nodes[1])] {
let mut graph = graph(&f, &[local(underneath), Target::ProcessLink(f.link)]);
graph.selected = f.link;
let snapshot = graph.selection.clone().unwrap();
let start = handle_point(&graph, f.link, end);
// Multiple selections render no reconnect rings. The visible
// selected card owns this point, while the mixed set stays whole.
assert_eq!(graph.exact_target_at(start), Some(local(underneath)));
let mut input = Input::default();
assert!(press(&graph, &mut input, start).is_none());
assert!(input.group.is_some() && input.press.is_none());
assert!(
matches!(release(&graph, &mut input, point(&graph, f.nodes[2], false)),
Some(Message::DiagramSelection(SelectionEvent::Refuse(captured, _))) if captured == snapshot)
);
assert_eq!(graph.selection.as_ref(), Some(&snapshot));
}
}
}
@@ -360,11 +360,12 @@ fn direct_process_reconnect_delete_and_reorder_preserve_other_paths_and_sources(
assert_eq!(doc.bundle(), &reconnected);
doc.undo();
assert_eq!(doc.bundle(), &original);
let reordered = execute_batch(
&f.p,
&[direct::reorder(&f.p, f.owner, f.nodes[2], f.nodes[0]).unwrap()],
)
.unwrap();
let group_reorder::Plan::Change(command) =
direct::reorder(&f.p, f.owner, f.nodes[2], f.nodes[0]).unwrap()
else {
panic!("changed order");
};
let reordered = execute_batch(&f.p, &[*command]).unwrap();
assert_eq!(reordered.elements[&f.owner].steps().unwrap()[0], f.nodes[2]);
assert_eq!(reordered.relations, f.p.relations);
assert!(direct::reorder(&f.p, f.owner, f.nodes[0], f.nodes[1]).is_err());
@@ -0,0 +1,176 @@
//! Immutable, bounded order proposals for local Process/FunctionalChain cards.
use super::*;
use crate::diagram_usage::Target;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Destination {
Before(Id),
After(Id),
}
#[derive(Debug)]
pub(crate) enum Plan {
Noop,
Change(Box<Command>),
}
/// Captured semantic facts only: no project clone, projection or routed scene.
/// The adapter must check its document/revision/selection lifetime before commit
/// and apply the returned command through the ordinary validated transaction.
#[derive(Debug)]
pub(crate) struct Prepared {
owner: Id,
steps: Vec<Id>,
adjacency: Vec<(Id, Id)>,
legacy: bool,
ranks: BTreeMap<Id, usize>,
selected: BTreeSet<Id>,
column: usize,
}
impl Prepared {
pub(crate) fn new(project: &Project, owner: Id, targets: &[Target]) -> Result<Self, String> {
let element = project
.elements
.get(&owner)
.filter(|e| matches!(e.kind(), Kind::Process | Kind::FunctionalChain))
.ok_or("Choose a Process or Functional Chain.")?;
let steps = element
.steps()
.ok_or("This owner has no contribution order.")?;
let mut ids = BTreeSet::new();
for id in steps {
if !is_contribution(project, owner, *id) || !ids.insert(*id) {
return Err(
"Every process step must name a unique local contribution before reordering."
.into(),
);
}
}
let mut adjacency: Vec<_> = sequence_links(project, owner)
.into_iter()
.map(|link| (link.source(), link.target()))
.collect();
// Unlisted local occurrences are legal incomplete source. Rendering can
// omit their links, but order editing must not silently ignore them.
if adjacency
.iter()
.any(|(a, b)| !ids.contains(a) || !ids.contains(b))
{
return Err("A sequence link refers to an unlisted contribution; repair the process order before reordering.".into());
}
let legacy = !legacy_order(project, owner).is_empty();
if legacy {
adjacency.extend(steps.windows(2).map(|pair| (pair[0], pair[1])));
}
if targets.is_empty() {
return Err("Select at least one local contribution.".into());
}
let mut selected = BTreeSet::new();
for target in targets {
let Target::ProcessOccurrence(endpoint) = target else {
return Err(
"Reorder requires local contribution cards only; links cannot move with them."
.into(),
);
};
if !endpoint.references.is_empty() {
return Err("Open the referenced definition to reorder its contents.".into());
}
if !ids.contains(&endpoint.occurrence) || !selected.insert(endpoint.occurrence) {
return Err(
"Every selected contribution must occur exactly once in this process.".into(),
);
}
}
let ranks = column_ranks(steps, &adjacency);
let first = *selected.first().expect("Nonempty selection admitted");
let column = ranks[&first];
if selected.iter().any(|id| ranks[id] != column) {
return Err("Reorder within one column; links determine the path columns.".into());
}
Ok(Self {
owner,
steps: steps.clone(),
adjacency,
legacy,
ranks,
selected,
column,
})
}
pub(crate) fn plan(&self, destination: Destination) -> Result<Plan, String> {
let (anchor, after) = match destination {
Destination::Before(id) => (id, false),
Destination::After(id) => (id, true),
};
if self.ranks.get(&anchor) != Some(&self.column) {
return Err(
"Choose a local contribution in the selected column as the destination.".into(),
);
}
// Complete step, adjacency and typed selection admission already ran.
if self.selected.contains(&anchor) {
return Ok(Plan::Noop);
}
let indices: Vec<_> = self
.steps
.iter()
.enumerate()
.filter_map(|(i, id)| (self.ranks[id] == self.column).then_some(i))
.collect();
let block: Vec<_> = indices
.iter()
.map(|&i| self.steps[i])
.filter(|id| self.selected.contains(id))
.collect();
let mut remaining: Vec<_> = indices
.iter()
.map(|&i| self.steps[i])
.filter(|id| !self.selected.contains(id))
.collect();
let gap = remaining
.iter()
.position(|id| *id == anchor)
.ok_or("The destination slot no longer exists.")?
+ usize::from(after);
remaining.splice(gap..gap, block);
let mut ordered = self.steps.clone();
for (index, id) in indices.into_iter().zip(remaining) {
ordered[index] = id;
}
if ordered == self.steps {
return Ok(Plan::Noop);
}
// Legacy adjacency comes from order itself. In valid legacy layouts each
// card has its own column; retain the check instead of assuming that.
let ranks = if self.legacy {
let adjacency: Vec<_> = ordered.windows(2).map(|pair| (pair[0], pair[1])).collect();
column_ranks(&ordered, &adjacency)
} else {
column_ranks(&ordered, &self.adjacency)
};
if ranks != self.ranks {
return Err(
"This reorder would change process columns; the whole move was refused.".into(),
);
}
Ok(Plan::Change(Box::new(Command::SetSteps(
self.owner, ordered,
))))
}
}
#[cfg(test)]
fn plan(
project: &Project,
owner: Id,
targets: &[Target],
destination: Destination,
) -> Result<Plan, String> {
Prepared::new(project, owner, targets)?.plan(destination)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,407 @@
use super::*;
use crate::document::Document;
use oa_core::source_project::ProjectLimits;
fn local(id: Id) -> Target {
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: id,
})
}
fn columns(project: &Project, owner: Id) -> BTreeMap<Id, usize> {
let first = project.elements[&owner].steps().unwrap()[0];
Prepared::new(project, owner, &[local(first)])
.unwrap()
.ranks
}
// Literal order [a,u,b,v,c]; a,b,c are peers. u,v are either downstream
// contributions or a separate cycle, so their slots must never change.
fn fixture(layer: Layer, cycle: bool) -> (Project, Id, [Id; 5]) {
let (f, _) = super::super::direct_tests::empty_exchange_fixture(layer);
let mut project = f.p;
let mut ids = vec![];
for name in ["a", "u", "b", "v", "c"] {
let element = occurrence(
&project,
f.owner,
name,
OccurrenceBody::Action {
action: Some(f.work[0]),
lifeline: None,
},
);
ids.push(element.id);
project = execute_batch(&project, &[Command::CreateElement(element)]).unwrap();
}
let ids: [Id; 5] = ids.try_into().unwrap();
let [a, u, b, v, _] = ids;
let pairs = if cycle {
[(u, v), (v, u)]
} else {
[(a, u), (b, v)]
};
// fresh_alias must see the first link before generating the second; two
// commands built from the same snapshot both choose "sequence_link".
for (source, target) in pairs {
let command = link(&project, source, target, "");
project = execute_batch(&project, &[command]).unwrap();
}
assert_eq!(project.elements[&f.owner].steps().unwrap(), &ids);
(project, f.owner, ids)
}
fn changed(project: &Project, owner: Id, targets: &[Target], drop: Destination) -> Command {
let Plan::Change(command) = plan(project, owner, targets, drop).unwrap() else {
panic!("Expected an actual order change");
};
assert!(matches!(command.as_ref(), Command::SetSteps(id, _) if *id == owner));
*command
}
#[test]
fn process_group_columns_reverse_noncontiguous_selection_preserves_project_and_history() {
for layer in [Layer::Oa, Layer::Sa] {
for cycle in [false, true] {
let (project, owner, [a, u, b, v, c]) = fixture(layer, cycle);
assert_eq!(
columns(&project, owner),
BTreeMap::from([
(a, 0),
(u, 1),
(b, 0),
(v, if cycle { 2 } else { 1 }),
(c, 0)
])
);
// Reverse click order must not reverse the source-ordered a,c block.
let command = changed(
&project,
owner,
&[local(c), local(a)],
Destination::After(b),
);
let mut expected = project.clone();
*expected
.elements
.get_mut(&owner)
.unwrap()
.steps_mut()
.unwrap() = vec![b, u, a, v, c];
let result = execute_batch(&project, std::slice::from_ref(&command)).unwrap();
assert_eq!(result, expected, "Nothing outside owner steps may change");
assert_eq!(columns(&result, owner), columns(&project, owner));
let mut doc =
Document::from_project(project.clone(), ProjectLimits::default()).unwrap();
let original = doc.bundle().clone();
doc.execute(command).unwrap();
assert_eq!(doc.project(), &expected);
let after = doc.bundle().clone();
let reopened = Document::from_bundle(after.clone(), ProjectLimits::default()).unwrap();
assert_eq!(reopened.project(), &expected);
assert_eq!(reopened.bundle(), &after);
assert!(doc.undo());
assert_eq!(doc.project(), &project);
assert_eq!(doc.bundle(), &original);
assert!(!doc.can_undo());
assert!(doc.redo());
assert_eq!(doc.project(), &expected);
assert_eq!(doc.bundle(), &after);
assert!(!doc.can_redo());
}
}
}
#[test]
fn process_group_columns_end_gaps_and_selected_anchor_noops() {
for layer in [Layer::Oa, Layer::Sa] {
let (project, owner, [a, u, b, v, c]) = fixture(layer, false);
for (members, drop, expected) in [
(
vec![local(c), local(b)],
Destination::Before(a),
vec![b, u, c, v, a],
),
(
vec![local(b), local(a)],
Destination::After(c),
vec![c, u, a, v, b],
),
] {
let command = changed(&project, owner, &members, drop);
assert_eq!(
execute_batch(&project, &[command]).unwrap().elements[&owner]
.steps()
.unwrap(),
&expected
);
}
let doc = Document::from_project(project.clone(), ProjectLimits::default()).unwrap();
let original = doc.bundle().clone();
for (members, drop) in [
(vec![local(b), local(c)], Destination::After(a)),
(vec![local(c), local(a)], Destination::Before(c)),
(vec![local(a), local(c)], Destination::After(a)),
(vec![local(c), local(b), local(a)], Destination::After(b)),
] {
assert!(matches!(
plan(doc.project(), owner, &members, drop),
Ok(Plan::Noop)
));
assert_eq!(doc.bundle(), &original);
assert!(!doc.can_undo());
}
}
}
#[test]
fn process_group_columns_refuse_entire_invalid_typed_sets_before_noop() {
for layer in [Layer::Oa, Layer::Sa] {
let (project, owner, [a, u, _, _, c]) = fixture(layer, true);
let foreign = super::super::direct_tests::fixture(layer).nodes[0];
let qualified = Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![a],
occurrence: c,
});
let relation = *project.relations.keys().next().unwrap();
for members in [
vec![],
vec![local(a), local(a)],
vec![local(a), local(u)],
vec![local(a), local(foreign)],
vec![local(a), qualified],
vec![local(a), Target::ProcessLink(relation)],
vec![local(a), Target::Placement(c)],
] {
// A selected anchor must not conceal invalid second members.
assert!(plan(&project, owner, &members, Destination::Before(a)).is_err());
}
assert!(plan(&project, owner, &[local(a)], Destination::After(foreign)).is_err());
assert!(plan(&project, a, &[local(a)], Destination::Before(a)).is_err());
assert!(
plan(
&project,
owner,
&[
local(u),
local(project.elements[&owner].steps().unwrap()[3])
],
Destination::Before(u)
)
.is_err()
);
}
}
#[test]
fn process_group_columns_legacy_exchange_order_refuses_cross_rank_group() {
for layer in [Layer::Oa, Layer::Sa] {
let (f, next) = super::super::direct_tests::empty_exchange_fixture(layer);
let mut project = f.p;
let mut ids = vec![];
for (name, exchange) in [("first", f.exchange), ("second", next)] {
let element = occurrence(
&project,
f.owner,
name,
OccurrenceBody::Exchange {
exchange: Some(exchange),
sender: None,
receiver: None,
message_kind: MessageKind::default(),
reply_to: None,
values: vec![],
operation: None,
},
);
ids.push(element.id);
project = execute_batch(&project, &[Command::CreateElement(element)]).unwrap();
}
assert_eq!(legacy_order(&project, f.owner), ids);
assert!(
plan(
&project,
f.owner,
&[local(ids[0]), local(ids[1])],
Destination::Before(ids[0])
)
.is_err()
);
assert!(matches!(
plan(
&project,
f.owner,
&[local(ids[1])],
Destination::After(ids[1])
),
Ok(Plan::Noop)
));
}
}
#[test]
fn process_group_columns_accept_all_local_card_kinds_and_different_heights() {
for layer in [Layer::Oa, Layer::Sa] {
let (f, _) = super::super::direct_tests::empty_exchange_fixture(layer);
let mut project = f.p;
let source = project
.make_element(
project.elements[&f.owner].kind(),
layer,
"Reusable definition",
None,
)
.unwrap();
let source_id = source.id;
project = execute_batch(&project, &[Command::CreateElement(source)]).unwrap();
let bodies = [
OccurrenceBody::Action {
action: Some(f.work[0]),
lifeline: None,
},
OccurrenceBody::Exchange {
exchange: Some(f.exchange),
sender: None,
receiver: None,
message_kind: MessageKind::default(),
reply_to: None,
values: vec![],
operation: None,
},
OccurrenceBody::Control {
kind: ControlKind::Choice,
},
OccurrenceBody::SequenceReference {
sequence: Some(source_id),
},
OccurrenceBody::Action {
action: Some(f.work[0]),
lifeline: None,
},
];
let mut ids = vec![];
for (index, body) in bodies.into_iter().enumerate() {
let element = occurrence(&project, f.owner, &format!("Card {index}"), body);
ids.push(element.id);
project = execute_batch(&project, &[Command::CreateElement(element)]).unwrap();
}
let graph = Graph::new(&project, f.owner, ids[0]);
assert_ne!(graph.nodes[0].rect.height, graph.nodes[3].rect.height);
let selected = vec![local(ids[3]), local(ids[2]), local(ids[1]), local(ids[0])];
let command = changed(&project, f.owner, &selected, Destination::After(ids[4]));
let mut expected = project.clone();
*expected
.elements
.get_mut(&f.owner)
.unwrap()
.steps_mut()
.unwrap() = vec![ids[4], ids[0], ids[1], ids[2], ids[3]];
assert_eq!(execute_batch(&project, &[command]).unwrap(), expected);
}
}
#[test]
fn process_group_columns_full_order_admission_precedes_selected_anchor_noop() {
for layer in [Layer::Oa, Layer::Sa] {
let (mut project, owner, [a, u, b, v, c]) = fixture(layer, false);
let other = project
.make_element(project.elements[&owner].kind(), layer, "Other", None)
.unwrap();
let other_owner = other.id;
project = execute_batch(&project, &[Command::CreateElement(other)]).unwrap();
let foreign = occurrence(
&project,
other_owner,
"Foreign local occurrence",
OccurrenceBody::Control {
kind: ControlKind::Choice,
},
);
let foreign_id = foreign.id;
project = execute_batch(&project, &[Command::CreateElement(foreign)]).unwrap();
assert!(Prepared::new(&project, owner, &[local(a), local(foreign_id)]).is_err());
let prepared = Prepared::new(&project, owner, &[local(a)]).unwrap();
assert!(prepared.plan(Destination::Before(foreign_id)).is_err());
// Corrupt/incomplete imported orders must fail even when only the valid
// card is selected and the requested destination would be a no-op.
for order in [
vec![a, u, b, v, c, c],
vec![a, u, b, v, Id::new_v4()],
vec![a, u, b, v, foreign_id],
vec![a, b, v, c], // local a -> u remains, but u is unlisted
] {
let mut incomplete = project.clone();
*incomplete
.elements
.get_mut(&owner)
.unwrap()
.steps_mut()
.unwrap() = order;
let original = incomplete.clone();
assert!(plan(&incomplete, owner, &[local(a)], Destination::Before(a)).is_err());
assert_eq!(incomplete, original);
}
}
}
#[test]
fn process_group_columns_renderer_omits_links_to_unlisted_nodes_without_panicking() {
for layer in [Layer::Oa, Layer::Sa] {
let (project, owner, [a, u, b, v, c]) = fixture(layer, false);
for (omitted, expected_ids, expected_ranks) in [
(
u,
vec![a, b, v, c],
BTreeMap::from([(a, 0), (b, 0), (v, 1), (c, 0)]),
),
(
a,
vec![u, b, v, c],
BTreeMap::from([(u, 0), (b, 0), (v, 1), (c, 0)]),
),
] {
// This omission is core-valid incomplete source, not a renderer-only
// manufactured dangling element. The semantic occurrence remains.
let incomplete =
execute_batch(&project, &[Command::SetSteps(owner, expected_ids.clone())]).unwrap();
assert!(incomplete.elements.contains_key(&omitted));
let graph = Graph::new(&incomplete, owner, b);
assert_eq!(
graph.nodes.iter().map(|node| node.id).collect::<Vec<_>>(),
expected_ids
);
assert_eq!(graph.edges.len(), 1);
assert_eq!((graph.edges[0].source, graph.edges[0].target), (b, v));
for node in &graph.nodes {
assert_eq!(node.rect.x, 24. + expected_ranks[&node.id] as f32 * 420.);
}
assert!(Prepared::new(&incomplete, owner, &[local(b)]).is_err());
}
}
}
#[test]
fn process_group_columns_parallel_links_keep_exact_ranks_and_relation_records() {
for layer in [Layer::Oa, Layer::Sa] {
let (mut project, owner, [a, u, b, v, c]) = fixture(layer, false);
project = execute_batch(&project, &[link(&project, a, u, "alternative")]).unwrap();
assert_eq!(
columns(&project, owner),
BTreeMap::from([(a, 0), (u, 1), (b, 0), (v, 1), (c, 0)])
);
let prepared = Prepared::new(&project, owner, &[local(c), local(b)]).unwrap();
let Plan::Change(command) = prepared.plan(Destination::Before(a)).unwrap() else {
panic!("Expected move");
};
let result = execute_batch(&project, &[*command]).unwrap();
assert_eq!(
result.elements[&owner].steps().unwrap(),
&vec![b, u, c, v, a]
);
assert_eq!(result.relations, project.relations);
assert_eq!(columns(&result, owner), prepared.ranks);
assert_eq!(Graph::new(&result, owner, b).edges.len(), 3);
}
}
@@ -1,5 +1,320 @@
use super::*;
#[tokio::test]
async fn production_process_multiselect_modifiers_survive_focus_busy_and_clear_on_window_loss() {
use crate::behavior::canvas_workspace::tests::Mounted;
use iced::keyboard::{Event as KeyEvent, Modifiers};
let mut f = super::super::direct_tests::fixture(Layer::Oa);
f.p = execute_batch(&f.p, &[Command::Delete(f.link)]).unwrap();
let mut app = App::with_project(f.p);
let _ = app.update(Message::Select(f.owner));
let _ = app.update(Message::Page(crate::app::Page::Behavior));
app.window_size = Size::new(1440., 900.);
let mut mounted = Mounted::new(&mut app).await;
let bounds = mounted.geometry(&app).bounds("process-viewport");
let at = |app: &App, id| {
let graph = Graph::new(app.project(), f.owner, id);
let rect = graph.nodes.iter().find(|n| n.id == id).unwrap().rect;
bounds.position()
+ app.behavior.topology.pan
+ iced::Vector::new(rect.x + 60., rect.y + 20.)
* app
.behavior
.topology
.scale(graph.size, (app.window_size.width - 600.).max(200.))
};
let shift = |held| {
iced::Event::Keyboard(KeyEvent::ModifiersChanged(if held {
Modifiers::SHIFT
} else {
Modifiers::empty()
}))
};
let first = at(&app, f.nodes[2]);
mounted
.batch(&mut app, &[shift(true)], mouse::Cursor::Available(first))
.await;
mounted.click(&mut app, first).await;
let second = at(&app, f.nodes[0]);
mounted.click(&mut app, second).await;
assert_eq!(
app.multiselect_snapshot().unwrap().targets().len(),
2,
"Shift before canvas focus reaches both clicks"
);
assert_eq!(mounted.geometry(&app).bounds("process-viewport"), bounds);
app.busy = true;
mounted.settle(&mut app).await;
mounted
.batch(&mut app, &[shift(false)], mouse::Cursor::Available(second))
.await;
app.busy = false;
mounted.settle(&mut app).await;
let third = at(&app, f.nodes[1]);
mounted.click(&mut app, third).await;
assert_eq!(
app.multiselect_snapshot().unwrap().targets().len(),
1,
"Shift released during busy is not resurrected"
);
app.busy = true;
mounted
.batch(&mut app, &[shift(true)], mouse::Cursor::Available(second))
.await;
app.busy = false;
mounted.settle(&mut app).await;
mounted.click(&mut app, second).await;
assert_eq!(
app.multiselect_snapshot().unwrap().targets().len(),
2,
"Shift held through busy survives child lifetime"
);
mounted
.batch(
&mut app,
&[iced::Event::Window(iced::window::Event::Unfocused)],
mouse::Cursor::Unavailable,
)
.await;
mounted.click(&mut app, first).await;
assert_eq!(
app.multiselect_snapshot().unwrap().targets().len(),
1,
"real window loss clears held modifiers"
);
assert_eq!(mounted.geometry(&app).bounds("process-viewport"), bounds);
assert!(!app.document.can_undo());
let pan = app.behavior.topology.pan;
let source = app.document.bundle().clone();
let blank = bounds.position() + iced::Vector::new(bounds.width - 40., bounds.height - 40.);
let end = blank + iced::Vector::new(-25., -20.);
mounted
.batch(
&mut app,
&[
iced::Event::Mouse(mouse::Event::CursorMoved { position: blank }),
iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
],
mouse::Cursor::Available(blank),
)
.await;
assert!(app.multiselect_snapshot().unwrap().targets().is_empty());
assert_eq!(app.behavior.topology.pan, pan);
assert_eq!(app.document.bundle(), &source);
// Each batch rebuilds the production tree and applies all App messages.
// Selection Clear must not retire the camera pan started by its press.
assert_eq!(mounted.geometry(&app).bounds("process-viewport"), bounds);
mounted
.batch(
&mut app,
&[iced::Event::Mouse(mouse::Event::CursorMoved {
position: end,
})],
mouse::Cursor::Available(end),
)
.await;
assert_eq!(
app.behavior.topology.pan,
pan + iced::Vector::new(-25., -20.)
);
assert_eq!(app.document.bundle(), &source);
assert_eq!(mounted.geometry(&app).bounds("process-viewport"), bounds);
mounted
.batch(
&mut app,
&[iced::Event::Mouse(mouse::Event::ButtonReleased(
mouse::Button::Left,
))],
mouse::Cursor::Available(end),
)
.await;
assert!(app.multiselect_snapshot().unwrap().targets().is_empty());
assert_eq!(
app.behavior.topology.pan,
pan + iced::Vector::new(-25., -20.)
);
assert_eq!(app.document.bundle(), &source);
assert!(!app.document.can_undo());
}
#[tokio::test]
async fn production_process_multiselect_reverse_click_group_drop_has_one_history_step_and_stable_camera()
{
use crate::behavior::canvas_workspace::tests::Mounted;
for layer in [Layer::Oa, Layer::Sa] {
let mut f = super::super::direct_tests::fixture(layer);
f.p = execute_batch(&f.p, &[Command::Delete(f.link)]).unwrap();
let mut app = App::with_project(f.p);
let _ = app.update(Message::Select(f.owner));
let _ = app.update(Message::Page(crate::app::Page::Behavior));
app.window_size = Size::new(1440., 900.);
let mut mounted = Mounted::new(&mut app).await;
let bounds = mounted.geometry(&app).bounds("process-viewport");
let graph = Graph::new(app.project(), f.owner, f.owner);
let scale = app
.behavior
.topology
.scale(graph.size, (app.window_size.width - 600.).max(200.));
let at = |id, after| {
let rect = graph.nodes.iter().find(|n| n.id == id).unwrap().rect;
bounds.position()
+ iced::Vector::new(
rect.x + 60.,
rect.y + if after { rect.height - 15. } else { 20. },
) * scale
};
let points = [
at(f.nodes[2], false),
at(f.nodes[0], false),
at(f.nodes[1], true),
];
drop(graph);
mounted
.batch(
&mut app,
&[iced::Event::Keyboard(
iced::keyboard::Event::ModifiersChanged(iced::keyboard::Modifiers::SHIFT),
)],
mouse::Cursor::Available(points[0]),
)
.await;
mounted.click(&mut app, points[0]).await;
mounted.click(&mut app, points[1]).await;
mounted
.batch(
&mut app,
&[iced::Event::Keyboard(
iced::keyboard::Event::ModifiersChanged(iced::keyboard::Modifiers::empty()),
)],
mouse::Cursor::Available(points[1]),
)
.await;
let snapshot = app.multiselect_snapshot().unwrap();
let source = app.document.bundle().clone();
let camera = (app.behavior.topology.pan, app.behavior.topology.zoom);
// Reuse the existing opt-in raw WGPU evidence convention. These are
// actual production-tree pixels, not a reconstructed preview image.
let record_feedback = |stage: &str, mounted: &mut Mounted, app: &App, cursor: Point| {
let Some(path) = std::env::var_os("ARCADIA_RENDER_EVIDENCE_DIR") else {
return;
};
let path = std::path::PathBuf::from(path);
std::fs::create_dir_all(&path).unwrap();
let name = format!("process-{layer:?}-{stage}");
let pixels = mounted.pixels_at(app, mouse::Cursor::Available(cursor));
let width = app.window_size.width as u32;
let height = app.window_size.height as u32;
assert_eq!(pixels.len(), width as usize * height as usize * 4);
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path.join(format!("{name}.rgba")))
.unwrap();
std::io::Write::write_all(&mut file, &pixels).unwrap();
let metadata = serde_json::json!({
"width": width, "height": height, "format": "RGBA8",
"stage": stage, "layer": format!("{layer:?}"),
"canvas": [bounds.x, bounds.y, bounds.width, bounds.height],
"cursor": [cursor.x, cursor.y], "scale": scale,
"camera": [app.behavior.topology.pan.x, app.behavior.topology.pan.y],
"selectionCount": snapshot.targets().len(),
"selection": format!("{snapshot:?}"),
"source": app.document.bundle(),
});
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path.join(format!("{name}.json")))
.unwrap();
std::io::Write::write_all(&mut file, &serde_json::to_vec_pretty(&metadata).unwrap())
.unwrap();
assert_eq!(app.document.bundle(), &source);
assert_eq!(app.multiselect_snapshot().unwrap(), snapshot);
assert!(!app.document.can_undo());
};
record_feedback("before-press", &mut mounted, &app, points[1]);
let pressed = mounted
.batch(
&mut app,
&[
iced::Event::Mouse(mouse::Event::CursorMoved {
position: points[1],
}),
iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
],
mouse::Cursor::Available(points[1]),
)
.await;
assert!(
!pressed
.iter()
.any(|message| matches!(message, Message::DiagramSelection(_)))
);
assert_eq!(app.multiselect_snapshot().unwrap(), snapshot);
assert_eq!(app.document.bundle(), &source);
assert!(!app.document.can_undo());
assert_eq!(mounted.geometry(&app).bounds("process-viewport"), bounds);
let moved = mounted
.batch(
&mut app,
&[iced::Event::Mouse(mouse::Event::CursorMoved {
position: points[2],
})],
mouse::Cursor::Available(points[2]),
)
.await;
assert!(
!moved
.iter()
.any(|message| matches!(message, Message::DiagramSelection(_)))
);
assert_eq!(app.multiselect_snapshot().unwrap(), snapshot);
assert_eq!(app.document.bundle(), &source);
assert!(!app.document.can_undo());
assert_eq!(mounted.geometry(&app).bounds("process-viewport"), bounds);
assert_eq!(
(app.behavior.topology.pan, app.behavior.topology.zoom),
camera
);
record_feedback("after-motion", &mut mounted, &app, points[2]);
let messages = mounted
.batch(
&mut app,
&[iced::Event::Mouse(mouse::Event::ButtonReleased(
mouse::Button::Left,
))],
mouse::Cursor::Available(points[2]),
)
.await;
assert!(
messages.iter().any(|m| matches!(
m,
Message::DiagramSelection(crate::app::multiselect::Event::ProcessReorder(_, _))
)),
"{messages:?}"
);
assert_eq!(
app.project().elements[&f.owner].steps().unwrap(),
&vec![f.nodes[1], f.nodes[0], f.nodes[2]]
);
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
snapshot.targets()
);
assert_eq!(mounted.geometry(&app).bounds("process-viewport"), bounds);
assert_eq!(
(app.behavior.topology.pan, app.behavior.topology.zoom),
camera
);
let changed = app.document.bundle().clone();
let _ = app.update(Message::Undo);
assert_eq!(app.document.bundle(), &source);
assert!(!app.document.can_undo());
let _ = app.update(Message::Redo);
assert_eq!(app.document.bundle(), &changed);
}
}
#[tokio::test]
async fn production_process_canvas_scaled_path_creation_preserves_source_and_editor_bounds() {
use crate::behavior::canvas_workspace::{self, tests::Mounted};
@@ -23,6 +23,38 @@ impl UsageSnapshot {
}
impl State {
pub(crate) fn selection_address(&self) -> Option<oa_core::topology_context::ContextAddress> {
self.selected_context.clone()
}
pub(crate) fn selection_targets(&self, p: &Project, owner: Id) -> Vec<Target> {
let graph = self.usage_graph(p, owner);
let mut targets = vec![];
for node in &graph.nodes {
targets.push(Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: node.id,
}));
targets.extend(
node.preview
.iter()
.map(|(endpoint, _)| Target::ProcessOccurrence(endpoint.clone())),
);
for link in &node.preview_links {
let target = Target::ProcessPreviewLink {
relation: link.relation,
source: link.source.clone(),
target: link.target.clone(),
};
if graph.usage_bounds(&target).is_some() {
targets.push(target);
}
}
}
targets.extend(graph.edges.iter().map(|edge| Target::ProcessLink(edge.id)));
targets
}
pub(crate) fn usage_snapshot(&self) -> UsageSnapshot {
UsageSnapshot {
identity: self.identity,
@@ -66,7 +66,8 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
let pending = state.draft.is_some();
let ordered = !legacy_order(p, owner).is_empty();
let selected = is_contribution(p, owner, app.selected).then_some(app.selected);
let clean = !app.behavior.has_pending() && !app.draft_dirty() && !app.source_dirty();
let clean =
!app.busy && !app.behavior.has_pending() && !app.draft_dirty() && !app.source_dirty();
// A fixed sibling keeps Iced's canvas scroll state through selection/form changes.
let mut navigation = column![].spacing(6);
if let Some(Relation {
@@ -183,6 +184,7 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
&state.expanded,
&state.contextual_expanded,
);
graph.selection = app.multiselect_snapshot();
graph.selected_preview = state
.qualified_selection(p, owner)
.filter(|address| {
@@ -195,6 +197,11 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
== app.selected
})
.map(|address| address.endpoint.clone());
if let Some(crate::diagram_usage::Target::ProcessOccurrence(endpoint)) =
graph.selection.as_ref().and_then(|s| s.primary())
{
graph.selected_preview = (!endpoint.references.is_empty()).then(|| endpoint.clone());
}
graph.selected_preview_link = app
.diagram_focus(crate::diagram_usage::Surface::Process(owner))
.and_then(|usage| match &usage.target {
@@ -255,7 +262,8 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
event(Event::Shelf(Shelf::Selection)),
move |zoom| Message::TopologyCanvas(CanvasEvent::Zoom(context, zoom)),
camera
)
),
selection_controls(app)
]
.spacing(4);
let entries = [
@@ -321,7 +329,7 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
)
}),
);
let details = scrollable(navigation.push(text("Layout is derived. The reorder handle changes display order within its column; it does not author a position.").size(11)))
let details = scrollable(navigation.push(text("Drag selected local cards to the upper or lower half of a card to insert before or after it in the same column. The group keeps source order; paths stay unchanged. Qualified previews remain read-only.").size(11)))
.id("process-details").width(Fill).height(Fill).into();
let mut form_panel: Element<'_, Message> = iced::widget::Space::new().height(0).into();
if let Some(d) = state.draft.as_ref().filter(|d| d.owner == owner) {
@@ -551,6 +559,42 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
super::super::canvas_workspace::host(header.into(), palette, canvas, editor)
}
fn selection_controls(app: &App) -> Element<'_, Message> {
use crate::app::multiselect::Event as SelectionEvent;
let snapshot = app.multiselect_snapshot();
let enabled = !app.busy
&& !app.behavior.has_pending()
&& !app.draft_dirty()
&& !app.source_dirty()
&& app.behavior.topology.tool == CanvasTool::Select;
let count = snapshot.as_ref().map_or(0, |s| s.targets().len());
let mut controls = row![label(format!("{count} selected"))]
.spacing(7)
.align_y(iced::Center)
.height(32);
if let Some(snapshot) = snapshot.filter(|s| !s.targets().is_empty()) {
controls = controls.push(button("Clear selection").on_press_maybe(
enabled.then(|| Message::DiagramSelection(SelectionEvent::Clear(snapshot.context()))),
));
controls = controls.push(
label(format!(
"Properties: {}",
short(app.project().named(app.selected), 24)
))
.wrapping(iced::widget::text::Wrapping::None),
);
}
// These two rows exist even with an empty set so selection never moves the
// canvas viewport or changes the camera's interpretation of the pointer.
column![
controls,
label("Shift+click toggles · drag selected cards to reorder · previews are read-only")
.wrapping(iced::widget::text::Wrapping::None)
]
.height(56)
.into()
}
fn editor_panel<'a, R: iced::advanced::text::Renderer + 'a>(
session: Id,
actions: iced::Element<'a, Message, iced::Theme, R>,
+74 -8
View File
@@ -18,6 +18,7 @@ pub struct Request {
pub route_segment: Option<(usize, Position)>,
pub creation_point: Option<Position>,
pub canvas: Option<route_edit::Context>,
pub process: Option<Box<crate::behavior::topology::Context>>,
pub source_file: Option<String>,
}
impl Request {
@@ -32,6 +33,7 @@ impl Request {
route_segment: None,
creation_point: None,
canvas: None,
process: None,
source_file: None,
}
}
@@ -61,6 +63,10 @@ impl Opened {
|| request
.canvas
.is_some_and(|c| Some(c) != current_canvas(app))
|| request
.process
.as_deref()
.is_some_and(|c| Some(*c) != app.topology_context())
{
return None;
}
@@ -88,6 +94,11 @@ impl Opened {
.request
.canvas
.is_none_or(|c| Some(c) == current_canvas(app))
&& self
.request
.process
.as_deref()
.is_none_or(|c| Some(*c) == app.topology_context())
&& self
.request
.source_file
@@ -101,10 +112,24 @@ fn target_matches(app: &App, request: &Request) -> bool {
let Some(target) = request.selection_target.as_deref() else {
return true;
};
if request.canvas.is_none() || !app.multiselect_target_visible(target) {
if (request.canvas.is_none() && request.process.is_none())
|| !app.multiselect_target_visible(target)
{
return false;
}
match target {
Target::ProcessOccurrence(endpoint) => {
request.process.is_some()
&& request.canvas.is_none()
&& request.placement.is_none()
&& endpoint.occurrence == request.object
}
Target::ProcessLink(id) | Target::ProcessPreviewLink { relation: id, .. } => {
request.process.is_some()
&& request.canvas.is_none()
&& request.placement.is_none()
&& *id == request.object
}
Target::Placement(id) => {
request.placement == Some(*id)
&& request
@@ -132,7 +157,9 @@ fn current_canvas(app: &App) -> Option<route_edit::Context> {
fn current_diagram(app: &App) -> Option<Id> {
if app.page == Page::Behavior {
app.state_context().map(|context| context.diagram)
app.topology_context()
.map(|context| context.owner)
.or_else(|| app.state_context().map(|context| context.diagram))
} else {
app.active_diagram
}
@@ -156,6 +183,7 @@ pub fn trigger(app: &App) -> iced::Element<'_, Message> {
request.canvas = app.route_context();
} else if app.page == Page::Behavior {
request.canvas = app.state_context();
request.process = app.topology_context().map(Box::new);
if let Some(target) = app.diagram_selection.as_ref().and_then(|s| s.primary()) {
request.selection_target = Some(Box::new(target.clone()));
request.placement = match target {
@@ -233,7 +261,7 @@ pub fn popup(app: &App) -> Option<Menu<Message>> {
});
}
let mut entries = vec![Entry::title(crate::views::short(p.named(id), 38))];
if request.canvas.is_some()
if (request.canvas.is_some() || request.process.is_some())
&& let Some(context) = app.multiselect_context()
{
use crate::app::multiselect::{Choice, Event as SelectionEvent};
@@ -311,11 +339,20 @@ pub fn popup(app: &App) -> Option<Menu<Message>> {
)),
true,
));
entries.push(item(
"Hide selected placements",
Message::DiagramSelection(SelectionEvent::Hide(snapshot.clone())),
crate::app::multiselect::placements(&snapshot).is_some(),
));
if request.process.is_some() {
entries.push(Entry::title(
"Drag contributions within one column to reorder",
));
entries.push(Entry::disabled(
"Hide unavailable · cards are model contributions",
));
} else {
entries.push(item(
"Hide selected placements",
Message::DiagramSelection(SelectionEvent::Hide(snapshot.clone())),
crate::app::multiselect::placements(&snapshot).is_some(),
));
}
entries.push(Entry::disabled(
"Delete selected from model (not yet available)",
));
@@ -327,6 +364,35 @@ pub fn popup(app: &App) -> Option<Menu<Message>> {
});
}
entries.push(Entry::separator());
if let Some(context) = request.process.as_deref().copied() {
let endpoint = match request.selection_target.as_deref() {
Some(Target::ProcessOccurrence(endpoint))
if !endpoint.references.is_empty() =>
{
Some(endpoint.clone())
}
Some(Target::ProcessPreviewLink { source, .. }) => Some(source.clone()),
_ => None,
};
if let Some(endpoint) = endpoint {
entries.push(Entry::title("Reused contents · read-only in this process"));
entries.push(item(
"Open referenced definition",
Message::TopologyCanvas(
crate::behavior::topology::CanvasEvent::OpenQualified(
context, endpoint,
),
),
true,
));
return Some(Menu {
token: opened.token,
anchor: request.anchor,
entries,
on_close: Message::Menu(Event::Close),
});
}
}
}
}
if app.page == Page::Behavior
+28
View File
@@ -689,6 +689,34 @@ fn diagram(app: &App) -> View<'_, Message> {
fn inspector(app: &App) -> View<'_, Message> {
let p = app.project();
if let Some(target) = app.process_preview_primary() {
let endpoint = match target {
crate::diagram_usage::Target::ProcessOccurrence(endpoint) => endpoint.clone(),
crate::diagram_usage::Target::ProcessPreviewLink { source, .. } => source.clone(),
_ => unreachable!(),
};
let context = app.topology_context().unwrap();
return container(
column![
text(p.named(app.selected)).size(17),
label("Reused contents · read-only here"),
label("Open the referenced definition to edit this contribution or connection."),
action(
"Open referenced definition",
Message::TopologyCanvas(crate::behavior::topology::CanvasEvent::OpenQualified(
context, endpoint
))
),
crate::model_menu::trigger(app),
]
.spacing(12),
)
.padding(14)
.width(320)
.height(Fill)
.style(style::panel)
.into();
}
if app.source_dirty() {
let mut notice = column![
text("Source drafts pending").size(17),
+72
View File
@@ -0,0 +1,72 @@
# Process multi-selection evidence — 2026-09-23
This slice implements exact multi-selection and topology-preserving order for OA Process and SA Functional Chain. Desktop, independent-source and corrected Windows native checks pass within the scopes below. This is branch-specific evidence, not a release, combined integration or completion of multi-selection issue #29. Combined release publication remains with the integration owner.
The [adapter design](multiselect-process-adapter-design-20260923.md) owns the selection, planning and lifecycle contract. The [native evaluator design](multiselect-process-native-design-20260923.md) owns the independent fixture/oracle and discriminating gesture. Detailed evidence is separated into [checks](multiselect-process-evidence-20260923/checks/), [source identity](multiselect-process-evidence-20260923/source/), [render feedback](multiselect-process-evidence-20260923/feedback/), [native trials](multiselect-process-evidence-20260923/native/), [reviews](multiselect-process-evidence-20260923/reviews/) and [preparation failure](multiselect-process-evidence-20260923/preparation-run-2/).
## Implementation and integration seams
Selection is transient and owner-scoped, preserving local occurrence/link and qualified path/preview-link identities. Primary controls Properties; qualified subjects stay read-only. Shift toggles, stationary member clicks collapse, and contextual membership/inspection is explicit. Feedback preserves canvas bounds. Visible reconnect handles win hit testing; groups cannot fall through to singleton mutations. Mixed/qualified movement refuses the whole set unchanged.
Local occurrences in one column move in source order into Before/After slots, preserving other-column indices and all ranks. `[A,U,B,V,C]`, C then A After B, becomes `[B,U,A,V,C]`. Singleton order shares the planner. One `SetSteps` transaction records a change; invalid/no-op results create no history. Facts are captured once per press; plans cache destinations without pointer-time Project clones/Graph rebuilds. Feedback shows slot/count and source-order numbers.
Integration uses `app::multiselect`, Process App handlers, topology `direct_selection.rs`/`group_reorder.rs`, existing menus/transactions and shared Viewport modifier retention. Mounted tests split press/motion/release across App rebuilds and check snapshots, reconnect precedence, intermediate source/history and final order/Undo/Redo. Scenario has a shared-modifier regression, not multi-selection implementation.
## Exact-subject failure and correction
Native run 1 on `b153451...` exposed a blocking identity defect: Back restored caller/camera but showed editable outer-reference Properties alongside qualified-leaf highlighting (frame 26). Baseline/mixed/qualified refusal saves passed three independent complete-Project `unchanged` checks, which could not detect UI identity. The run stopped before order/history/reopen acceptance. It exited 0 with empty logs and unchanged pinned binaries/fixture; it has no successful history-bytes receipt.
The correction remembers the requested qualified address, including nonprimary menu invocation. Back selects its validated leaf and refreshes read-only inspection. Select/EditProperties clears obsolete context after admission, including same-ID defining-leaf navigation; ordinary Open saves a local frame. Tests assert path, subject, draft, camera, source/history and ordinary return. Back restores the invoked singleton. Review 2 found no concrete regression; protective-test suggestions remain notes rather than claimed coverage.
Run 3 confirms current/nonprimary Open/Back, exact read-only caller subject, and Explorer navigation to outer reference and same-ID leaf with editable local Properties. [Parent observations](multiselect-process-evidence-20260923/reviews/run-3-observations.md) and the [independent native review](multiselect-process-evidence-20260923/reviews/process-native-review-3.md) establish these UI results separately from saved-Project checks.
## Source and test evidence
Gates retain commands/logs, artifact/helper hashes and unchanged 742-file maps/archives, including 71 vendored files and compile-time fixtures. Source receipts compare bytes with named Git blobs; captured HEAD alone cannot identify uncommitted source.
| Source | Matching evidence and result |
| --- | --- |
| Historical `1711bff650dabb1df3a9bc37f19060d5db297feb`, map `d5acfcf6...` | `full-desktop-1`: **1,317 passed, 6 ignored**; `format-1` passed. Historical implementation, before final navigation corrections. |
| `b15345123a7feaf630ef24d45f591c76c6715778`, map `7f5b3de4...` | `desktop-3`: **147 passed**; strict `lint-2`, `format-2`, `feedback-1` passed; `core-2`: **5 passed**. Matching checker/GUI builds passed. Native run 1 failed as recorded above. |
| Production correction `ff712b24190342363d0275467e96f181872da6ad`, map `1ba4ed41...` | `desktop-6`: **150 passed**; `full-desktop-2`: **1,320 passed, 0 failed, 6 ignored**. Strict core/desktop all-target `lint-3` and `format-3` passed. |
| Evaluator clarification `b743a10d51032dc1655b94fed5e49fbbbcee83f4`, map `f3fd180a...` | `core-3`: **5 passed**; example-scoped `lint-4`, `format-4`, `windows-build-2`, `native-build-2` passed. Production desktop/core library unchanged from `ff712...`; this is not a second full-desktop run. Matching GUI/checker used for native run 3. |
Failures remain preserved: `desktop-1` 94 passed/8 failed; `desktop-2` 104/1; `lint-1` failed before the payload-size correction. `desktop-4` rejected invalid Cargo filter placement before tests. `desktop-5` ran 147/1 because the new fixture toggled already-expanded references closed, yielding an empty initial group; corrected setup/navigation pass in `desktop-6`. Preparation run 2 failed while generating its fixture with missing toolchain DLL environment (exit 3221225781); **no GUI trial occurred**. Run 3 corrected the environment and used a fresh directory.
## Independent semantics, rendering and native history
The core checker compares complete Projects against immutable baseline/literal expected OA order without invoking the desktop planner. SA/reuse/trace are preservation sentinels. Primary A would be ambiguous: singleton-A After B equals the group result. The clarified evaluator adds unchanged-C rejection and a discriminating trial: membership `[C,A]`, Inspect C, drag C After B. Group output is `[B,U,A,V,C]`; singleton primary/pressed C leaves the original order.
The native observer performed that sequence in run 3: click C, context Add A, Inspect C, verify two selected/primary C, then drag C After B. The visible column became B,A,C with U,V unchanged. One Ctrl+Z restored baseline; one Ctrl+Y restored reordered output; an in-process reopen retained it. The trial also observed mixed-set refusal and selected-anchor no-op. Run 3 closed normally at `2026-09-23T13:43:54Z`, exit 0, empty stdout/stderr and unchanged pinned checker/GUI/fixture.
**Routing remains visibly imperfect.** In the [reordered frame](multiselect-process-evidence-20260923/reviews/images/run-3/39-group-reordered-0.jpg), A→U and B→V share portions of their orthogonal paths, obscuring endpoint connectivity. The independent review confirms this defect; unchanged link records do not establish readable routing. It is related to the intersection concerns in issue #32, whose original scope is Auto Arrange; this trial exercises Process order instead. No source-level attribution or routing fix is claimed here.
All eight saved snapshots passed the independent complete-Project checker: baseline, qualified-navigation, mixed-refusal, anchor-noop, reordered, undo, redo and reopened. The history-byte gate passed for all ten source files: `baseline == undo == qualified-navigation == mixed-refusal == anchor-noop` and `reordered == redo == reopened`, also checking immutable fixture equality for the baseline group. Only `oa/behavior/process_oa_process.arcadia` differs between groups. This lexical proof complements observed one-step history; equality alone cannot prove the user actions.
Actual headless WGPU App feedback covers OA/SA at 1440×900 and 100% zoom: stable source/selection/camera, legible insertion slot/count and source-order numbers. Raw RGBA, lossless PNG readback and parent inspection are preserved. These split-batch renderings establish actual production pixels, not a paused native drag or other DPI/window sizes. Native membership used context actions; held Shift-click is mounted-test evidence. Reopen is in-process, not cold restart. Aggregate removal, Allocation/Scenario adapters, native SA reorder, Linux/DPI and full accessibility remain outside this slice's acceptance.
## Reproduction and package verification
From the named source checkout, use the documented project toolchain. Captures used Windows GNU LLVM, Cargo/rustc 1.98.1, one build job and incremental compilation disabled. Multiple test filters belong **after** `--`:
```text
cargo test -p oa-core --example process_multiselect_native -- --test-threads=1
cargo test -p oa-desktop -- topology process_ canvas_workspace repeated_process menu --test-threads=1
cargo test -p oa-desktop -- --test-threads=1
cargo clippy -p oa-core -p oa-desktop --all-targets -- -D warnings
cargo fmt --all -- --check
cargo build -p oa-core --example process_multiselect_native
cargo build -p oa-desktop
```
Portable evidence checks use Python; feedback PNG verification also needs Pillow. They do not build or execute archived sources. From repository root:
```text
python -B harness/multiselect-process-evidence-20260923/checks/verify.py
python -B harness/multiselect-process-evidence-20260923/source/verify.py --repo .
python -B harness/multiselect-process-evidence-20260923/feedback/verify.py --checks harness/multiselect-process-evidence-20260923/checks
python -B harness/multiselect-process-evidence-20260923/native/verify.py
python -B harness/multiselect-process-evidence-20260923/preparation-run-2/verify.py
```
The source check requires named commits locally; omit `--repo .` for offline receipt consistency. Before publication, all five verifiers and review pins passed against a fresh export of the exact 47 staged evidence files; exported bytes matched the working files. The first staging attempt omitted the two ignored empty preparation logs; inventory validation caught that omission before verification or publication, and they were explicitly staged. Package READMEs cover native reproduction with fresh fixtures and matching GUI/checker receipts. Preserve failures and immutable baselines. Package consistency, semantic equality, lexical history, rendered feedback and observed interaction remain distinct claims.
@@ -1,55 +1,119 @@
# Process group adapter candidate
# Process selection and column-order adapter
Read-only Astra investigation against the State follow-up working tree above `7e348d967d1787c052a145b7448636613a6a7054`. This is a proposed next adapter, not implementation, accepted semantics, or verification. Live ownership and priorities remain in Gitea #29. No source, build or GUI change accompanied the investigation.
**Accepted implementation contract; runtime/native acceptance pending.** This document describes the current unpublished Process working source above `bed7f825fd00ec32299032a664a5f5d753aad86d`, implementing the Process portion of the [multiple-selection contract](multiselect-contract-20260923.md). It does not establish a verified release or completion of issue #29. Gitea holds live ownership, priorities and gate results. The initial read-only investigation inspected State follow-up source above `7e348d967d1787c052a145b7448636613a6a7054`; its alternatives, critiques and experiment evidence are retained as history below.
## Representation facts
## Accepted implemented contract
The surface is `Surface::Process(owner)` for an OA Process or SA FunctionalChain. Selection is a transient insertion-ordered exact target set with one primary Inspector target:
| Target | Identity and admitted use |
| --- | --- |
| `ProcessOccurrence(OccurrenceEndpoint { references: [], occurrence })` | One local semantic contribution card. Action, Exchange, Control and SequenceReference cards participate in order planning; these are not saved placements or reusable work definitions. |
| `ProcessOccurrence` with nonempty references | One visible qualified tile with its complete reuse path. Select/inspect; no caller-side reorder or deletion. |
| `ProcessLink(id)` | One local rendered SequenceLink or ContextualLink. Select/inspect; not a member of a contribution reorder. Existing singleton local SequenceLink reconnect remains separate. |
| `ProcessPreviewLink { relation, source, target }` | One actually painted qualified preview segment with exact endpoint paths. Select/inspect; read-only through the caller. |
Different caller paths to the same defining occurrence remain different targets. A qualified primary identifies the **actual occurrence or relation subject**, not the outer reference's properties. Its caller owner/path remains captured; properties are read-only until explicit **Open** navigates to the defining process. Hidden/collapsed targets are pruned exactly without rebinding to another reuse path or outer card. Open/Back and owner changes establish a new surface lifetime. Legacy `OrderedPath` arrows have no relation identity and do not become editable links. Navigation emphasis alone is not mutation authority.
Shift-click toggles the exact hit. Plain press on an unselected target replaces the set. A selected-member press freezes membership and primary until stationary release versus drag; stationary release collapses to that member. Right-click captures a target without replacing the selection; contextual Add/Remove changes membership explicitly. Counts and distinct primary/membership paint describe the set. Ordinary local property edits remain primary-only.
### One admitted column-slot plan
`behavior/topology/group_reorder.rs::Prepared::new(&Project, owner, &[Target])` captures immutable steps, adjacency, integer ranks and selected IDs. It rejects empty/duplicate selections, non-occurrence members, qualified paths, wrong-owner/missing contributions, cross-column roots, or any missing/foreign/duplicate **unselected** step. A local SequenceLink whose endpoint is omitted from owner steps also refuses before any selected-anchor no-op. Such incomplete source can be core-valid; that does not authorize silently ignoring its topology when editing order.
The renderer and planner share `topology.rs::column_ranks`, extracted from the established rank algorithm. The renderer filters direct links to displayed endpoints and skips unavailable legacy path pairs, retaining displayed nodes without panicking. This tolerant display behavior does not weaken planner admission. Parallel SequenceLinks remain distinct; longest-path and deterministic cycle-blocked integer ranks retain their existing meaning.
`Prepared::plan(Destination::Before(id) | Destination::After(id))` requires an anchor in the selected column. After full admission, a selected anchor returns `Plan::Noop`, even for a noncontiguous set. For an unselected anchor: extract the column's order and original step indices; remove selected IDs and form their block in original source order; insert before/after the remaining anchor; write the column permutation back to those same indices. Other-column IDs retain exact indices, and unselected IDs within this column retain relative order. Identical steps return Noop. Otherwise the complete ID-to-rank map is recomputed and must remain exact before one existing `Command::SetSteps` is returned.
Example: `[a,u,b,v,c]`, column `[a,b,c]`, selection C then A, After B yields `[b,u,a,v,c]`. U/V retain indices 1/3, and A/C retain source order. Selected `{b,c}` After A is unchanged. There is no XY schema, control-flow rewiring, reusable-definition edit or unrelated-record change. Legacy exchange-only paths have successive ranks; cycle-blocked nodes receive distinct fallback ranks, so multi-member sets spanning those columns refuse. A cycle elsewhere does not prevent movement of an acyclic peer group.
Semantic facts are prepared once per press and candidate plans are cached by anchor/side. Motion within a slot does not clone the Project, rebuild a Graph or run whole-model validation. App release handling re-admits the live exact selection and uses the same planner before one source-validated transaction. Source failure preserves model/history. Successful commit restores the exact primary without an incidental Fit/reveal. Noop emits no command/history entry.
**Singleton migration is implemented:** `topology/direct.rs::reorder` delegates a singleton typed target to this planner and returns Noop/Change. Moving B before A in `[a,u,b,v,c]` now writes `[b,u,a,v,c]`, replacing the old global splice `[b,a,u,v,c]`. This deliberately changes invisible cross-column source order to preserve unrelated indices consistently for singleton and group operations.
### Pointer feedback and lifetime
`behavior/topology/direct_selection.rs` owns an order-specific press; it does not use the saved-placement XY constructor. The press captures exact selection snapshot, target, screen position, bounds, pan and scale. Its 3-screen-pixel threshold is irreversible: out-and-back movement, refused drops and no-op destinations retain the set rather than becoming stationary clicks. Native pointer order is preserved; an unavailable/outside release cannot reuse an earlier inside point.
Each local card's upper half means Before and its lower half means After. An insertion indicator, refusal/unchanged caption and source-order member numbers describe the cached operation. Cards are not freely translated or reflowed during the drag. Before-first and after-last are reachable through the first/last unselected card. Actual reachability/readability at native zoom/window sizes remains an acceptance gate.
Snapshot/document/revision/surface/selection-generation changes, tool/editability changes, bounds/pan/scale changes, resize/unfocus, wheel, cursor exit, right/middle press and Escape cancel the captured gesture. Escape cancels a live press before selection clearing. Passive modifiers support Shift across editor focus. Stable count/Inspector layout and retained camera geometry are required; selection and qualified inspection do not authorize incidental source application or camera movement.
Shift/context hits on painted reconnect rings resolve the exact link. A mixed set cannot reconnect only its primary, and Connect with several selected targets is refused. Existing singleton tools retain their separate ownership. App envelope validation precedes incidental selection/camera/allocation state changes; dirty source/property/forms or stale packets cannot partially act.
### Current removal boundary and remaining adapters
Process has no saved placements: Hide explicitly refuses instead of deleting contributions or adding hidden-card persistence. Group Delete and qualified-target Delete explicitly refuse. Existing admissible local singleton deletion remains separate; no depicted group falls through to it. Aggregate local-occurrence removal still requires one captured impact review and atomic union deletion, including ContextualLink cleanup and explicit-to-legacy meaning changes described in the historical critique below.
This slice implements exact Process selection and column reorder with whole-set refusals. Aggregate removal, Allocation assignment/Arrange-only groups and Scenario order adapters remain required by the [overall contract](multiselect-contract-20260923.md), outside this Process acceptance claim.
### Implementation and verification boundaries
| Source | Responsibility |
| --- | --- |
| `app/multiselect.rs`, `app/process_multiselect.rs` | Scope/envelope admission, exact reconciliation, actual-subject primary and transaction dispatch. |
| `app/process_canvas.rs`, `app.rs` | Legacy command guards, navigation/tool lifetime and existing Process command integration. |
| `behavior/topology/group_reorder.rs`, `topology.rs::column_ranks` | Immutable admitted facts, column-slot planning and shared production ranks. |
| `behavior/topology/direct_selection.rs`, `direct.rs` | Exact hits/modifiers, order gesture, feedback, singleton migration and separate tool ownership. |
| `behavior/topology.rs`, `topology/view.rs`, `topology/usages.rs` | Exact paint/visibility, stable controls/camera and incomplete-topology rendering. |
| `model_menu.rs`, Inspector/behavior property boundaries | Captured membership menus, qualified read-only subject and explicit Open. |
Planner tests define independent literal OA/SA orders, whole-Project preservation, source roundtrip/Undo/Redo, all four card kinds/differing heights, reverse noncontiguous selection, end gaps/noops, typed refusal, five-node cycle-plus-peer ranks, parallel links and malformed/unlisted steps. App/input tests cover qualified primary, reconciliation, stale messages and gesture boundaries. Their definitions and source inspection alone do not establish current full-suite or native acceptance.
The [native evaluator design](multiselect-process-native-design-20260923.md) and [core example](../crates/oa-core/examples/process_multiselect_native.rs) use an immutable deterministic OA/SA fixture, literal expected `[b,u,a,v,c]` and complete Project comparison. Global splice, reversed-block, primary-only and unrelated-record corruptions are falsifiers. Native Shift/focus, menus, cancellation, insertion reachability, stable layout/camera, real save/reopen and Undo/Redo require matching executable evidence. No acceptance receipt is asserted here.
## Historical investigation and design alternatives
The following sections retain the original reasoning, corrected by the accepted contract above. Statements of proposed work describe that earlier investigation, not the current implementation status.
### Representation facts recorded initially
`diagram_usage.rs` already defines `Surface::Process(owner)`, exact `ProcessOccurrence(OccurrenceEndpoint { references, occurrence })`, local `ProcessLink`, and qualified `ProcessPreviewLink` targets. Local cards are semantic occurrences in owner steps; they reference reusable definitions and are not saved diagram placements. Different reference paths to the same defining occurrence are different selected targets. Legacy derived `OrderedPath` arrows lack relation identities: do not fabricate editable IDs or substitute endpoints.
`topology/usages.rs::Graph::usage_bounds` provides exact displayed-target visibility, including bounded qualified previews. Hidden preview tiles do not fall back to their outer reference. Its approximate reveal rectangles are not adequate edge hit tests. Qualified preview content stays read-only until its definition is explicitly opened.
## Movement candidates
### Movement candidates considered
| Candidate | Assessment |
| --- | --- |
| Persist arbitrary XY | Conflicts with derived process topology and needs new schema; reject for this adapter. |
| Sequential singleton reorder | Produces click-order-dependent layouts and does not define a simultaneous operation; reject. |
| Stable block within one original column | Candidate: preserves existing topology and uses one existing `SetSteps` command. |
| Stable block within one original column | Accepted with the column-slot correction: preserves topology and uses one existing `SetSteps` command. |
| Rewire links during a cross-column drag | Alters process execution meaning; requires a separate capability and explicit interaction. |
Existing `topology/direct.rs::reorder` verifies local contributions and equal original graph X-columns, then validates `SetSteps`. `Graph::expanded_qualified` derives ranks from sequence links and legacy order, with steps supplying vertical order; cyclic fallback can depend on enumeration order.
The former `topology/direct.rs::reorder` verified local contributions and equal graph X-columns, globally spliced steps, then validated `SetSteps`. `Graph::expanded_qualified` derived ranks from sequence links and legacy order, with steps supplying vertical order; cyclic fallback could depend on enumeration order. The shared integer rank helper and singleton migration supersede that implementation.
The proposed pure planner admits the whole nonempty set only if every target is a visible local occurrence with an empty reference path and belongs to this owner. Selected IDs and the destination must share one original column. Build the block in original steps order, then use the column-slot permutation below: preserve other-column indices and unselected order within this column. Object-anchored drops on selected items are no-op; a raw gap is a separate API. Check the complete rank map remains unchanged, especially cycle fallback. Distinguish no-op from a command so it creates no source/history entry. Preview and commit must consume this same planned order; do not freely translate cards.
Before-card only could reuse existing behavior but makes moving to the end awkward. Before/after slots are the preferred candidate, subject to independent review and actual interaction testing. Participation of each occurrence-body type also needs a precise decision.
Before-card only could reuse earlier behavior but made moving to the end awkward. Before/After and all four local contribution kinds were subsequently accepted and implemented; actual interaction acceptance remains pending.
## Hide and removal
### Original Hide and removal proposal
Process has no saved placements and therefore no existing Hide operation. Explain that limitation; do not silently substitute semantic deletion or add persisted hidden cards without a separate design decision.
Homogeneous local-occurrence removal should present one aggregate impact review and apply one `Batch(Delete(...))`. Core deferred deletion already supports union cleanup. Preserve referenced work, exchanges, reused process definitions and opposite-layer counterparts. Initially refuse qualified or mixed sets in full; local-link-only deletion can be a separate extension. Never invoke singleton deletion once per member. Capture document, revision, surface and selection generation through confirmation, revalidate the whole set, and preserve pending property/source/forms.
## Implementation boundaries and falsifiers
### Initial implementation plan and falsifiers
Extend `app/multiselect.rs` with Process dispatch and exact primary paths, avoiding the assumption that every context is a saved diagram. Use `app/process_canvas.rs` for captured adapter commands. The input and reorder planner belong in `behavior/topology/direct.rs`; graph/render changes in `topology.rs`; exact visibility in `topology/usages.rs`; stable controls in `topology/view.rs`. Process currently lacks the needed canvas right-click branch, so contextual Add/Remove needs explicit transport into `model_menu.rs`. Aggregate confirmation belongs at `app/diagram_removal.rs` and its view. Reject stale and legacy singleton commands before App's shared side effects.
The initial plan called for Process dispatch, exact primary paths, right-click membership and whole-set guards rather than assuming every context is a saved diagram. These are implemented across the source boundaries above; the pure planner and input adapter were factored into dedicated modules rather than expanding `direct.rs`. Aggregate confirmation at `app/diagram_removal.rs` remains deferred.
The current shared group gesture requires saved placements and an XY anchor; reuse its lifecycle concepts, not that constructor unchanged. Compare a small shared threshold/cancellation component with a Process order-specific gesture before introducing abstraction.
The saved-view group gesture requires placements and an XY anchor. A Process order-specific gesture was chosen, preserving its lifecycle principles without widening that constructor into an inappropriate generic geometry abstraction.
First useful outcome: exact local/qualified/link selection with whole-set refusals, plus one atomic same-column local-occurrence reorder and one Undo/Redo. Aggregate removal remains separate acceptance if omitted from that outcome.
Tests must independently assert source-order blocks from noncontiguous reverse-click selections; unchanged other-column indices and unselected order within the affected column, relations and reusable definitions; identical referenced work represented by distinct occurrences; distinct qualified paths and collapse visibility; full refusal of cross-column/mixed/stale sets; no-op history; ordered pointer/focus/Shift/cancellation/camera behavior; no primary-only reconnect bypass; OA and SA, legacy exchange order, explicit branches and cyclic fallback. Native slot feedback, stable canvas/camera, source save/reopen and one-step history are required beyond compilation.
## Independent critique: revise before implementation
### Independent critiques that changed the design
A fresh read-only Astra review found a concrete defect in global block splicing. Given steps `[a,u,b,v,c]`, one displayed column `[a,b,c]`, and selected `{b,c}`, dropping after `a` is visually a no-op. The proposed global splice produces `[a,b,c,u,v]`, changing source/history without a visible change. Equivalent before/after positions in the same displayed gap must have one interpretation.
The revised candidate is a **column-slot permutation**: extract this column's order from original steps, remove the selected members, normalize the drop to a gap in the remainder, insert the original-order selected block, then write the resulting column order back into this column's original steps indices. Other-column indices remain exact; unselected relative order within the affected column is preserved. This deliberately replaces the earlier all-unselected-global-order condition. Return no command when column order is unchanged, and verify the complete ID-to-rank map remains unchanged before accepting `SetSteps`. Local Action, Exchange, Control and SequenceReference occurrences are proposed participants; qualified descendants and links are whole-set refusals. This revision still requires an independent pure experiment before UI implementation.
The correction was a **column-slot permutation**, now implemented as specified above. It deliberately replaces the earlier all-unselected-global-order condition with exact other-column indices and within-column unselected order. The independent pure experiment preceded UI implementation; selected-anchor no-op remained distinct from raw-gap normalization.
Scope correction: legacy ordered-path nodes have successive ranks, and cycle-blocked nodes receive distinct fallback ranks (`topology.rs` rank computation). A multiple selection of those nodes cannot satisfy same-column admission. Test refusal and unchanged execution meaning rather than claiming useful reordering of those sets. A graph containing a cycle can still admit a separate acyclic peer group.
Removal has an additional semantic consequence: `behavior.rs` derives explicit-versus-legacy interpretation from remaining occurrence kinds and SequenceLinks. Deleting action/control from `[action,exchange1,control,exchange2]` without links leaves an exchange-only sequence with implicit ordered-linear meaning. Aggregate review must expose this transition or initially refuse it. Include caller-owned ContextualLinks targeting removed occurrences in the impact union (`references.rs` cleanup), not just local links. See the presentation-versus-legacy distinction in `docs/language.rst`.
Removal has an additional semantic consequence: `behavior.rs` derives explicit-versus-legacy interpretation from remaining occurrence kinds and SequenceLinks. Deleting action/control from `[action,exchange1,control,exchange2]` without links leaves an exchange-only sequence with implicit ordered-linear meaning. Aggregate review must expose this transition or initially refuse it. Include caller-owned ContextualLinks targeting removed occurrences in the impact union (`references.rs` cleanup), not just local links. See the presentation-versus-legacy distinction in [language documentation](../docs/language.rst).
Smallest production experiment: independent OA/SA fixtures with interleaved steps and different card heights; reverse-click selection; before-first/after-last and equivalent gaps; already-positioned no-ops; literal expected steps; complete Project equality outside steps; unchanged ranks; exact source roundtrip and one Undo/Redo. Add legacy and cycle refusal plus acyclic peers beside a cycle. Separately demonstrate deletion-induced mode switching before designing confirmation. These Rust/application checks have not run yet.
The original production-evaluator plan became the Rust/App tests and native fixture above. Deletion-induced mode switching still needs a separate removal evaluator. A later source critic found an incomplete-order panic (`a→u` with U omitted from owner steps), prompting complete planner admission and graceful renderer omission. Bounded test results must remain tied to the source and receipts actually exercised.
## Bounded permutation experiment
@@ -57,4 +121,4 @@ Smallest production experiment: independent OA/SA fixtures with interleaved step
An object-anchored Before/After interface can keep selected-target no-op without losing changed destinations: all remainder gaps were reachable using unselected anchors in 2,036 bounded subsets. Raw-gap normalization is different: in `[a,b,c,d]`, selecting `{b,d}` and normalizing Before `d` gives `[a,c,b,d]`; selected-target no-op keeps the original, while After unselected `c` reaches the changed order. This supports the simpler selected-target no-op interaction. Block contiguity applies to an admitted planned move, not to that no-op. Actual pointer feedback, production graph admission, serialization and history remain unverified.
An independent critic matched the experiment's rank algorithm to Rust and found no counterexample under the stated valid-input assumptions. The review prompted an explicit five-node changed group beside a cycle; four-node enumeration could only cover singleton movement or unchanged whole-peer blocks there. It also identified a compatibility choice: current singleton `direct::reorder` globally splices, so moving `b` before `a` in `[a,u,b,v,c]` writes `[b,a,u,v,c]`, while this candidate writes `[b,u,a,v,c]` with the same display. Prefer one column-slot planner for both singleton and group reorder, preserving unrelated column indices consistently. This would intentionally revise singleton source ordering and requires production regression/roundtrip/history checks; no such migration is implemented here. Retaining global singleton splice was rejected as two source transformation rules for the same visible operation. Native anchor reachability and selected-target guard execution remain separate checks.
An independent critic matched the experiment's rank algorithm to Rust and found no counterexample under the stated valid-input assumptions. The review prompted an explicit five-node changed group beside a cycle; four-node enumeration could only cover singleton movement or unchanged whole-peer blocks there. It also identified the singleton global-splice compatibility choice. Retaining that splice was rejected as two source transformation rules for the same visible operation; the implemented migration above intentionally preserves unrelated column indices instead. Native anchor reachability and selected-target guard execution remain separate acceptance checks. These exploratory results support the design but do not replace runtime/native verification.
@@ -0,0 +1,2 @@
# Receipt-bound files must retain exact bytes through Git checkout.
** -text whitespace=cr-at-eol
@@ -0,0 +1,58 @@
# Process multiselect closed gate evidence
These tools adapt the State multiselect checks packager/verifier. They copy
explicitly named **closed** runs from `.local/process-group-gates`, preserve
their exact seven raw files, retain nonzero exit codes and both streams, and
verify all source-map/archive bytes before writing and again after ZIP readback.
They never run Cargo, execute archived code, extract inputs, or publish evidence.
Check-only example:
```text
python -B prepare.py --root CHECKOUT --runs core-1 desktop-1 desktop-2 lint-1 full-desktop-1 lint-2 format-2 --check-only
```
After all desired runs close, supply a fresh, nonexistent output directory:
```text
python -B prepare.py --root CHECKOUT --runs core-1 desktop-1 desktop-2 lint-1 full-desktop-1 desktop-3 feedback-1 lint-2 format-2 native-build-1 windows-build-1 --output FRESH_DIRECTORY
python -B verify.py FRESH_DIRECTORY
```
Run names in the second example are a proposed final inventory, not an existence,
completion, pass, or source-equivalence claim. The parent chooses the final list.
Preserve failed desktop-1, desktop-2, and lint-1 alongside subsequent receipts;
their successful packaging means only byte/receipt consistency. No run is inferred
from directory scanning. Open/incomplete runs, changed-input receipts, missing
historical helpers, unsafe/duplicate archive members, and mismatched input
maps/bytes are refused. An existing output directory is refused even if empty.
Use repeatable `--helper PATH` to provide an exact historical capture helper when
the current two helpers no longer match a selected receipt.
`manifest.json` maps each logical raw path to its stored ZIP member. Input maps
and input ZIPs deduplicate independently by their exact SHA-256 bytes, including
ZIP metadata; equal source contents need not imply byte-identical ZIPs.
`captureHelpers` names both gate.py and gate-feedback.py and points to their
hash-addressed archived bytes. Each run separately references the helper matching
its receipt. Current reviewed helper SHA-256 values are:
```text
gate.py 1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20
gate-feedback.py 230f1222f133edef76ffb9c09ed6eecf952fc326b04a0bbccb3f3f49df4c0c29
```
Both current named helpers are included even when no selected run uses one yet.
The manifest is authoritative for helper pins at packaging time; this README's
values document this tooling review, not a substitute for receipt matching.
`files.json` pins the archive, manifest, tools and this README. Keep that pin file
under the parent's source/evidence record; self-consistency is not authentication.
The verifier retains the existing 71-file vendored-input invariant and requires
`inputsUnchanged` to be exactly true. Source coverage is whatever each original
input map and receipt actually captured; recorded HEAD alone does not identify
uncommitted tested bytes. Executable readback pins are receipts only: no executable
or toolchain is packaged or independently reconstructed. Rendered feedback images,
native screenshots/saves and source-to-commit receipts are separate parent-owned
packages. Offline validation is not test execution, native acceptance or usability
evidence. `selfcheck.py` checks these tools against explicitly selected closed runs
and includes in-memory corruption rejection checks.
@@ -0,0 +1,22 @@
{
"prepare.py": {
"bytes": 5326,
"sha256": "2c8d7cbd1ec2415e671c35734fb5b78beb9a535626b54492a4c1d3687a6e4dd9"
},
"verify.py": {
"bytes": 9497,
"sha256": "a52e4057d975717d132c1a8b656d34e1ef8ef8fbd125687715a69696a866fd44"
},
"README.md": {
"bytes": 3344,
"sha256": "9d1eaa1dabdad0d95829da6d6e3004703ba90bc9824a963c43ca61e24b210e7e"
},
"manifest.json": {
"bytes": 45584,
"sha256": "ea8d070535c3d62f3e2c13b81340ad2d506863fd93fe981f03a4edb87552e943"
},
"evidence.zip": {
"bytes": 20916711,
"sha256": "591a81f55aa409044ecbcaf6da83ca107602a6ab690b347b84fd40bea469fd35"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,99 @@
"""Package explicitly selected closed gate captures without running Cargo."""
from pathlib import Path
import argparse
import json
import zipfile
from verify import RAW_FILES, pin, parsed, need, run_name, verify_data, verify_package
HERE = Path(__file__).resolve().parent
def collect(root, runs, helpers):
gates = root / ".local/process-group-gates"
candidates = [gates / name for name in ("gate.py", "gate-feedback.py")] + helpers
helper_bytes = [path.read_bytes() for path in candidates]
payload, logical, specs = {}, {}, {}
def add(name, data):
stored = ("capsules/" + pin(data)["sha256"] + Path(name).suffix
if name.rsplit("/", 1)[1] in {"inputs.json", "inputs.zip"} else name)
need(stored not in payload or payload[stored] == data, "deduplication collision")
payload[stored] = data
logical[name] = stored
helper_catalog = {}
for name, data in zip(("gate.py", "gate-feedback.py"), helper_bytes):
helper = "helpers/" + pin(data)["sha256"] + ".py"
add(helper, data)
helper_catalog[name] = helper
for run in runs:
folder = gates / run
need(folder.is_dir(), "run directory missing: " + run)
paths = list(folder.iterdir())
need(all(path.is_file() and not path.is_symlink() for path in paths)
and {path.name for path in paths} == RAW_FILES, "exact closed raw files required: " + run)
raw = {path.name: path.read_bytes() for path in paths}
result = parsed(raw["result.json"])
need("finish" in result and result["inputsUnchanged"] is True, "unfinished/changed run refused: " + run)
matches = [data for data in helper_bytes if pin(data) == result["helper"]]
need(bool(matches), "exact historical helper unavailable for " + run + "; supply --helper PATH")
helper = "helpers/" + result["helper"]["sha256"] + ".py"
add(helper, matches[0])
for name, data in sorted(raw.items()):
add("cargo/" + run + "/" + name, data)
specs[run] = {key: result[key] for key in ("command", "head", "exitCode", "inputCount")}
specs[run]["helper"] = helper
manifest = {"schema": 1, "kind": "multiselect-cargo-gates", "runs": specs,
"captureHelpers": helper_catalog,
"logicalFiles": dict(sorted(logical.items())),
"members": {name: pin(data) for name, data in sorted(payload.items())}}
summary = verify_data(manifest, payload.__getitem__)
return payload, manifest, summary
def write_json(path, value):
with path.open("xb") as output:
output.write((json.dumps(value, indent=2) + "\n").encode("utf-8"))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True, help="checkout holding .local/process-group-gates")
parser.add_argument("--runs", nargs="+", required=True, help="explicit run names, including failures to retain")
parser.add_argument("--helper", type=Path, action="append", default=[], help="additional exact historical helper (repeatable)")
parser.add_argument("--output", type=Path, help="fresh, nonexistent package directory (required unless --check-only)")
parser.add_argument("--check-only", action="store_true", help="validate raw captures in memory without creating an archive")
args = parser.parse_args()
need(all(run_name(run) for run in args.runs) and len(args.runs) == len(set(args.runs)), "unique safe run names required")
need(args.check_only or args.output is not None, "--output is required unless --check-only")
if not args.check_only:
need(not args.output.exists(), "output must be a fresh directory: " + str(args.output))
payload, manifest, summary = collect(args.root.resolve(), args.runs, args.helper)
if args.check_only:
print("PASS raw consistency; no package written:", summary)
return
out = args.output.resolve()
out.mkdir(parents=True, exist_ok=False)
for name in ("evidence.zip", "manifest.json", "files.json"):
need(not (out / name).exists(), "existing package output refused: " + name)
for name in ("prepare.py", "verify.py", "README.md"):
data = (HERE / name).read_bytes()
destination = out / name
if destination.exists():
need(destination.read_bytes() == data, "different existing package tool: " + name)
else:
with destination.open("xb") as output:
output.write(data)
with zipfile.ZipFile(out / "evidence.zip", "x", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
for name, data in sorted(payload.items()):
info = zipfile.ZipInfo(name, date_time=(2026, 9, 23, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
archive.writestr(info, data)
write_json(out / "manifest.json", manifest)
names = ("prepare.py", "verify.py", "README.md", "manifest.json", "evidence.zip")
write_json(out / "files.json", {name: pin((out / name).read_bytes()) for name in names})
need(verify_package(out) == summary, "written package differs from validated captures")
print("PASS package readback:", out, summary)
if __name__ == "__main__":
main()
@@ -0,0 +1,173 @@
"""Offline consistency checks only; never execute or extract archived inputs."""
from pathlib import Path, PurePosixPath
from datetime import datetime
import argparse
import hashlib
import io
import json
import math
import re
import stat
import zipfile
RAW_FILES = {"started.json", "process.json", "result.json", "stdout.log", "stderr.log", "inputs.json", "inputs.zip"}
OUTER_FILES = {"prepare.py", "verify.py", "README.md", "manifest.json", "evidence.zip"}
def need(condition, message):
if not condition:
raise ValueError(message)
def pin(data):
return {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
def valid_pin(value):
return (isinstance(value, dict) and set(value) == {"bytes", "sha256"}
and type(value["bytes"]) is int and value["bytes"] >= 0
and isinstance(value["sha256"], str)
and re.fullmatch(r"[0-9a-f]{64}", value["sha256"]) is not None)
def safe(name):
return (isinstance(name, str) and bool(name) and "\\" not in name and ":" not in name
and all(ord(char) >= 32 for char in name)
and not PurePosixPath(name).is_absolute()
and all(part not in ("", ".", "..") for part in name.split("/")))
def run_name(name):
return isinstance(name, str) and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", name) is not None
def parsed(data):
def pairs(items):
result = {}
for key, value in items:
need(key not in result, "duplicate JSON key: " + key)
result[key] = value
return result
def constant(value):
raise ValueError("nonfinite JSON constant: " + value)
return json.loads(data, object_pairs_hook=pairs, parse_constant=constant)
def inventory(archive, expected):
names = archive.namelist()
need(len(names) == len(set(names)) and set(names) == set(expected), "exact ZIP membership")
for entry in archive.infolist():
need(safe(entry.filename) and not entry.is_dir(), "unsafe ZIP member: " + entry.filename)
need(not stat.S_ISLNK(entry.external_attr >> 16), "ZIP symlink: " + entry.filename)
need(valid_pin(expected[entry.filename]), "invalid member pin: " + entry.filename)
need(entry.file_size == expected[entry.filename]["bytes"], "ZIP recorded size: " + entry.filename)
def ordered_times(*values):
times = [datetime.fromisoformat(value) for value in values]
return all(value.utcoffset() is not None for value in times) and times == sorted(times)
def verify_data(manifest, read):
"""Shared read-only verifier for packaged bytes or prepare's in-memory payload."""
need(manifest["schema"] == 1 and manifest["kind"] == "multiselect-cargo-gates", "manifest schema")
runs, logical, stored = manifest["runs"], manifest["logicalFiles"], manifest["members"]
helpers = manifest["captureHelpers"]
need(isinstance(helpers, dict) and set(helpers) == {"gate.py", "gate-feedback.py"}, "capture helper names")
need(all(isinstance(name, str) and re.fullmatch(r"helpers/[0-9a-f]{64}\.py", name)
for name in helpers.values()), "capture helper mapping")
need(isinstance(runs, dict) and bool(runs) and all(run_name(run) for run in runs), "explicit run inventory")
need(all(safe(name) for name in logical) and all(safe(name) for name in stored), "unsafe manifest path")
need(set(logical.values()) == set(stored), "unreferenced or absent stored members")
for name, expected in stored.items():
need(valid_pin(expected) and pin(read(name)) == expected, "stored member hash: " + name)
expected_logical = {"cargo/" + run + "/" + name for run in runs for name in RAW_FILES}
expected_logical.update(spec["helper"] for spec in runs.values())
expected_logical.update(helpers.values())
need(set(logical) == expected_logical, "exact logical raw/helper inventory")
for name, destination in logical.items():
if name.startswith("cargo/") and name.rsplit("/", 1)[1] in {"inputs.json", "inputs.zip"}:
expected = "capsules/" + stored[destination]["sha256"] + PurePosixPath(name).suffix
need(destination == expected, "input capsule mapping: " + name)
else:
need(destination == name, "only input maps/archives may be deduplicated: " + name)
def raw(name):
return read(logical[name])
for name, helper in helpers.items():
need(helper == "helpers/" + pin(raw(helper))["sha256"] + ".py", "named helper hash: " + name)
seen_capsules = set()
for run, spec in runs.items():
prefix = "cargo/" + run + "/"
start = parsed(raw(prefix + "started.json"))
process = parsed(raw(prefix + "process.json"))
result = parsed(raw(prefix + "result.json"))
required_start = {"start", "command", "cwd", "head", "scope", "inputs", "archive",
"inputCount", "environment", "helper", "cargo", "rustc"}
need(required_start <= start.keys(), run + ": incomplete start receipt")
need(all(result.get(key) == value for key, value in start.items()), run + ": start/result relationship")
command = result["command"]
need(isinstance(command, list) and command and command[0] == "cargo"
and all(isinstance(arg, str) for arg in command), run + ": Cargo command")
need(command == process["command"] == spec["command"], run + ": command relationship")
need(result["head"] == spec["head"] and re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", result["head"]), run + ": HEAD")
need(type(result["exitCode"]) is int and result["exitCode"] == spec["exitCode"], run + ": recorded exit")
need(result["inputsUnchanged"] is True, run + ": changed inputs refused")
need(type(result["seconds"]) in (int, float) and math.isfinite(result["seconds"])
and result["seconds"] >= 0, run + ": duration")
need(type(process["pid"]) is int and process["pid"] > 0, run + ": process identity")
need(ordered_times(start["start"], process["observed"], result["finish"]), run + ": completed timestamp order")
for field, filename in [("inputs", "inputs.json"), ("archive", "inputs.zip"), ("stdout", "stdout.log"), ("stderr", "stderr.log")]:
need(result[field] == pin(raw(prefix + filename)), run + ": " + field + " pin")
need(valid_pin(result["helper"]) and result["helper"] == pin(raw(spec["helper"])), run + ": helper pin")
need(spec["helper"] == "helpers/" + result["helper"]["sha256"] + ".py", run + ": helper mapping")
inputs = parsed(raw(prefix + "inputs.json"))
need(isinstance(inputs, dict) and all(safe(name) for name in inputs), run + ": safe input inventory")
need(type(result["inputCount"]) is int and len(inputs) == result["inputCount"] == spec["inputCount"], run + ": input counts")
need(sum(name.startswith("crates/vendor/iced_widget/") for name in inputs) == 71, run + ": vendor count")
capsule = (logical[prefix + "inputs.json"], logical[prefix + "inputs.zip"])
if capsule not in seen_capsules:
with zipfile.ZipFile(io.BytesIO(raw(prefix + "inputs.zip"))) as source:
inventory(source, inputs)
for name, expected in inputs.items():
need(pin(source.read(name)) == expected, run + ": source hash " + name)
seen_capsules.add(capsule)
artifacts = []
for line in raw(prefix + "stdout.log").decode("utf-8", errors="replace").splitlines():
try:
value = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(value, dict) and value.get("reason") == "compiler-artifact" and value.get("executable"):
artifacts.append(value)
need(isinstance(result["artifacts"], list), run + ": artifact records")
need(artifacts == [record["cargo"] for record in result["artifacts"]], run + ": Cargo JSON artifact relationship")
for record in result["artifacts"]:
need(set(record) == {"cargo", "readback"}
and (record["readback"] is None or valid_pin(record["readback"])), run + ": artifact readback pin")
print(run, "recorded exit", result["exitCode"], "inputs", len(inputs), "executable records", len(artifacts))
return {"runs": len(runs), "recordedFailures": sum(spec["exitCode"] != 0 for spec in runs.values()),
"logicalFiles": len(logical), "storedMembers": len(stored), "sourceCapsulePairs": len(seen_capsules),
"captureHelpers": helpers}
def verify_package(root):
files = parsed((root / "files.json").read_bytes())
need(set(files) == OUTER_FILES, "outer file inventory")
for name, expected in files.items():
need(valid_pin(expected) and pin((root / name).read_bytes()) == expected, "outer hash: " + name)
manifest = parsed((root / "manifest.json").read_bytes())
with zipfile.ZipFile(root / "evidence.zip") as archive:
inventory(archive, manifest["members"])
return verify_data(manifest, archive.read)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("package", nargs="?", type=Path, default=Path(__file__).resolve().parent)
args = parser.parse_args()
print("PASS offline consistency:", verify_package(args.package))
print("Historical receipts only; no source/binary execution or native acceptance claim.")
if __name__ == "__main__":
main()
@@ -0,0 +1,42 @@
# Actual Process render feedback byte proof
This small package holds the four actual WGPU RGBA readbacks, adjacent JSON
metadata, lossless PNGs, original png-readback.json, encode-png.py and parent
observations.md from `.local/process-feedback-review/capture-1`. It requires
Python and Pillow; it never invokes Cargo, a GUI, or archived capture helpers.
Use a portable Process checks package containing the closed `feedback-1` gate:
```text
python -B prepare.py --root C:/ar-multiselect-9e8r6t --checks CHECKS_PACKAGE --check-only
python -B prepare.py --root C:/ar-multiselect-9e8r6t --checks CHECKS_PACKAGE --output FRESH_DIRECTORY
python -B FRESH_DIRECTORY/verify.py --checks CHECKS_PACKAGE
```
Run the checks package's own verifier too. Feedback references exact logical
feedback-1 receipt/helper/log/input pins, so the checks package may include other
runs and may be moved independently. No full source capsule is duplicated here.
Preparation refuses existing output and compares all 742 captured input bytes
to Git commit b15345123a7feaf630ef24d45f591c76c6715778. Verification checks the
fixed source map identity and every source-capsule member through the supplied
checks package. The original gate HEAD predates b153; its captured inputs, rather
than that HEAD, identify the rendered source. The relevant captured test and
Mounted renderer paths have explicit source pins.
Every PNG is decoded and required to equal its raw RGBA byte for byte at the
recorded 1440x900 size. For OA and SA separately, before-press and after-motion
must preserve complete source bundle, selection string/count, canvas, camera,
scale and dimensions while pixels differ. The original PNG readback receipt,
unique safe ZIP inventory and every archived file hash are checked. A matching
checks receipt must record the exact passing test and capture output directory.
This is byte/provenance consistency, not native acceptance or independent image
interpretation. Pixel files have no gate-time hashes: their linkage is the
recorded output directory, create-only captured test code, passing test receipt
and parent observations; package pins establish bytes at packaging time.
Selection metadata stores the test's captured snapshot; unchanged current
selection and empty history are separately asserted in the passing test.
There is no history metadata, and this tool does not invent any. Source text in
metadata is compared exactly between stages, not reparsed as a Project.
The parent observations describe visible quality and scope limits. Encoding
helpers and observations are preserved, not executed or treated as instructions.
@@ -0,0 +1,22 @@
{
"README.md": {
"bytes": 2623,
"sha256": "731c4062a0bc4a66a44246fc69c53b8aa32fd09613e62c9bbef4716f7c930641"
},
"evidence.zip": {
"bytes": 797909,
"sha256": "6ebd3beafec69da81124511a509f56fe966d35fbd1b127567a1b7f57eb1a9051"
},
"manifest.json": {
"bytes": 4079,
"sha256": "caf50753143216c0cf503473508581f1229528215cf6a72b038ddc8f84a75000"
},
"prepare.py": {
"bytes": 3753,
"sha256": "4fb1db6b465ae6fd25cdabdf63b3a5fb76a6cd9399f01afd3dca4dd9ec4e7f86"
},
"verify.py": {
"bytes": 8730,
"sha256": "d0bcb4fc8b07c7ba9b4573505b72e865a5eb18070b9b5e4411db757e13175d96"
}
}
@@ -0,0 +1,112 @@
{
"schema": 1,
"kind": "process-render-feedback",
"sourceCommit": "b15345123a7feaf630ef24d45f591c76c6715778",
"checksRun": "feedback-1",
"checksPins": {
"started.json": {
"bytes": 1747,
"sha256": "01fbcfd28b752921ded95c40a711909851bcd005394b34b5f4f49a7eaa0a594c"
},
"process.json": {
"bytes": 260,
"sha256": "b8559e934c97f9eba407b1ceceed637fc570a9a8ba9e3362b961824cb0344fcd"
},
"result.json": {
"bytes": 3481,
"sha256": "2f007dfda469a75eaaf713577b394605af7d3d42fed2137d9e3ed632301c78d3"
},
"stdout.log": {
"bytes": 293378,
"sha256": "8c611aa1671316570c79b079882400e3b710d3eff8fe04e37ec59f17071fa92c"
},
"stderr.log": {
"bytes": 210,
"sha256": "504bdaa5c008c52a9462aeca71413f9933a4e9c6b0272715ba5ca916411781c1"
},
"inputs.json": {
"bytes": 124276,
"sha256": "7f5b3de4d5bb70282e424fbe90211af2ac259965aef10b05438b46076467a767"
},
"inputs.zip": {
"bytes": 2985964,
"sha256": "f681fb5ead73d5aba1d9a0f25ea29a96ccb430692630b64987b984623cd38148"
},
"helper": {
"bytes": 3856,
"sha256": "230f1222f133edef76ffb9c09ed6eecf952fc326b04a0bbccb3f3f49df4c0c29"
}
},
"capturingSources": {
"crates/oa-desktop/src/behavior/topology/layout_tests.rs": {
"bytes": 50414,
"sha256": "993d700d6590757fb329cab3029dd0202e71c2c2f852e13fe1228417b01d8fd9"
},
"crates/oa-desktop/src/behavior/canvas_workspace/tests.rs": {
"bytes": 27368,
"sha256": "de13f0112b1a39fa03f32a9308dcbd30b235eef9ead877b440dde023c93bc5a3"
}
},
"members": {
"capture-1/png-readback.json": {
"bytes": 1006,
"sha256": "4f397109e46512010fdb777c85abb6dc658fc9e26cb255d22165b0a1c6502eac"
},
"capture-1/process-Oa-after-motion.json": {
"bytes": 2674,
"sha256": "17c55c7275634ac9a22b78a6eeab7464ceb0f0e389f02947d9ec96caaf18ecfe"
},
"capture-1/process-Oa-after-motion.png": {
"bytes": 111782,
"sha256": "051c44a392eb23787b6e7ff28b0384336602eb2d6e166cca2859c7e44a8f5386"
},
"capture-1/process-Oa-after-motion.rgba": {
"bytes": 5184000,
"sha256": "7726fa5de90ad7ec5b14e87883c40cace0007ece54279048c6f49c9386ce5d6d"
},
"capture-1/process-Oa-before-press.json": {
"bytes": 2674,
"sha256": "6c1d80c1690d13a8fa2c21505322651c7436673368035fa7a054d0ee55ddbb5f"
},
"capture-1/process-Oa-before-press.png": {
"bytes": 108986,
"sha256": "d9b5c2e0b7b50ea894986aa38c63b8d1559169974d6a93954dd0a69107b5740d"
},
"capture-1/process-Oa-before-press.rgba": {
"bytes": 5184000,
"sha256": "399e7442f56d320a92d6d9beccd2f66a241e572adadcd733ba797aef97453a1e"
},
"capture-1/process-Sa-after-motion.json": {
"bytes": 3186,
"sha256": "441d18d75dab872012f68020012840aa67a09b52a5946749ceea669e2839439e"
},
"capture-1/process-Sa-after-motion.png": {
"bytes": 111760,
"sha256": "bc31d57fae268b6ad19c5b14aaa0860e14b7a5f80608a8896970f7ad82b041f0"
},
"capture-1/process-Sa-after-motion.rgba": {
"bytes": 5184000,
"sha256": "82493c91aa5ac0e1f44a50f52496fe933104acd7992b2f9adbb7710ed3e85e29"
},
"capture-1/process-Sa-before-press.json": {
"bytes": 3186,
"sha256": "b13fbdab939a9d34a8950ee89800f41c2082b5928ef5c8781dc813940ecf6df1"
},
"capture-1/process-Sa-before-press.png": {
"bytes": 108966,
"sha256": "9b2a4a7cc355639e26e4e87cddf17b9ce859a00e5a80400da62b67ba27198a59"
},
"capture-1/process-Sa-before-press.rgba": {
"bytes": 5184000,
"sha256": "30ede8974ba5d9227c109fd9a5c08c93119bdb897ad7f273e87a6602bc42bdd5"
},
"encode-png.py": {
"bytes": 2181,
"sha256": "c05b2d9f2a02d72dba50422da733e36758bd6e2773e48d84174b72ec0a804b5e"
},
"observations.md": {
"bytes": 1912,
"sha256": "11828e5467785990a11d462813b821f677cbff1c64dcd1ca8244a94fe01e2423"
}
}
}
@@ -0,0 +1,70 @@
"""Package the fixed, closed capture-1 pixels using an existing checks package."""
from pathlib import Path
import argparse
import json
import subprocess
import zipfile
from verify import COMMIT, MEMBERS, SOURCES, OUTER, need, pin, checks_data, verify_data, verify_package
HERE = Path(__file__).resolve().parent
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--checks", type=Path, required=True)
parser.add_argument("--output", type=Path)
parser.add_argument("--check-only", action="store_true")
args = parser.parse_args()
need(args.check_only or args.output is not None, "--output or --check-only required")
if args.output:
need(not args.output.exists(), "fresh nonexistent output directory required")
checks = checks_data(args.checks)
gate, source = checks
# Compare every captured source byte to the named commit, not current worktree.
paths = sorted(source)
result = subprocess.run(["git", "cat-file", "--batch"], cwd=args.root,
input="".join(COMMIT + ":" + name + "\n" for name in paths).encode(), capture_output=True, check=True)
offset = 0
for name in paths:
end = result.stdout.index(b"\n", offset)
header = result.stdout[offset:end].split()
need(len(header) == 3 and header[1] == b"blob", "missing commit blob: " + name)
size = int(header[2])
data = result.stdout[end + 1:end + 1 + size]
need(data == source[name], "captured input differs from b153: " + name)
offset = end + 2 + size
need(offset == len(result.stdout), "exact Git batch readback")
folder = args.root / ".local/process-feedback-review"
need({p.relative_to(folder).as_posix() for p in (folder / "capture-1").rglob("*") if p.is_file()} == {name for name in MEMBERS if name.startswith("capture-1/")}, "exact captured file inventory")
payload = {}
for name in sorted(MEMBERS):
path = folder / name
need(not path.is_symlink() and not getattr(path, "is_junction", lambda: False)(), "linked input")
payload[name] = path.read_bytes()
manifest = {"schema": 1, "kind": "process-render-feedback", "sourceCommit": COMMIT,
"checksRun": "feedback-1", "checksPins": {name: pin(data) for name, data in gate.items()},
"capturingSources": {name: pin(source[name]) for name in SOURCES},
"members": {name: pin(data) for name, data in payload.items()}}
summary = verify_data(manifest, payload.__getitem__, checks)
if args.check_only:
print("PASS raw pixels, metadata and all 742 b153 source blobs:", summary)
return
out = args.output.resolve()
out.mkdir(parents=True, exist_ok=False)
for name in ("prepare.py", "verify.py", "README.md"):
(out / name).write_bytes((HERE / name).read_bytes())
with zipfile.ZipFile(out / "evidence.zip", "x", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
for name, data in payload.items():
info = zipfile.ZipInfo(name, date_time=(2026, 9, 23, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
archive.writestr(info, data)
(out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
(out / "files.json").write_text(json.dumps({name: pin((out / name).read_bytes()) for name in sorted(OUTER)}, indent=2) + "\n", encoding="utf-8")
need(verify_package(out, checks) == summary, "written archive readback")
print("PASS package readback and all 742 b153 source blobs:", out, summary)
if __name__ == "__main__":
main()
@@ -0,0 +1,142 @@
"""Verify actual rendered feedback bytes against a separate Process checks package."""
from pathlib import Path, PurePosixPath
from datetime import datetime
import argparse
import hashlib
import io
import json
import stat
import zipfile
from PIL import Image
COMMIT = "b15345123a7feaf630ef24d45f591c76c6715778"
INPUT_SHA = "7f5b3de4d5bb70282e424fbe90211af2ac259965aef10b05438b46076467a767"
TEST = "production_process_multiselect_reverse_click_group_drop_has_one_history_step_and_stable_camera"
SOURCES = ("crates/oa-desktop/src/behavior/topology/layout_tests.rs", "crates/oa-desktop/src/behavior/canvas_workspace/tests.rs")
NAMES = [f"process-{layer}-{stage}" for layer in ("Oa", "Sa") for stage in ("before-press", "after-motion")]
MEMBERS = {"observations.md", "encode-png.py", "capture-1/png-readback.json"} | {f"capture-1/{name}.{ext}" for name in NAMES for ext in ("rgba", "png", "json")}
OUTER = {"prepare.py", "verify.py", "README.md", "manifest.json", "evidence.zip"}
def need(ok, message):
if not ok:
raise ValueError(message)
def pin(data):
return {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
def safe(name):
return isinstance(name, str) and bool(name) and not PurePosixPath(name).is_absolute() and all(c not in name for c in ("\\", ":")) and all(ord(c) >= 32 for c in name) and all(p not in ("", ".", "..") for p in name.split("/"))
def parsed(data):
def unique(items):
result = {}
for key, value in items:
need(key not in result, "duplicate JSON key")
result[key] = value
return result
def constant(value):
raise ValueError("nonfinite JSON: " + value)
return json.loads(data, object_pairs_hook=unique, parse_constant=constant)
def inventory(archive, expected):
names = archive.namelist()
need(len(names) == len(set(names)) and set(names) == set(expected), "exact ZIP inventory")
for row in archive.infolist():
need(safe(row.filename) and not row.is_dir() and not stat.S_ISLNK(row.external_attr >> 16), "unsafe ZIP entry")
need(row.file_size == expected[row.filename]["bytes"], "ZIP size")
def checks_data(root):
"""Read referenced gate bytes, without importing or executing package code."""
files = parsed((root / "files.json").read_bytes())
need(set(files) == OUTER, "checks outer inventory")
for name, expected in files.items():
need(pin((root / name).read_bytes()) == expected, "checks outer pin: " + name)
manifest = parsed((root / "manifest.json").read_bytes())
need(manifest["schema"] == 1 and manifest["kind"] == "multiselect-cargo-gates", "checks format")
with zipfile.ZipFile(root / "evidence.zip") as archive:
inventory(archive, manifest["members"])
def raw(logical):
member = manifest["logicalFiles"][logical]
data = archive.read(member)
need(pin(data) == manifest["members"][member], "referenced checks pin")
return data
prefix = "cargo/feedback-1/"
gate = {name: raw(prefix + name) for name in ("started.json", "process.json", "result.json", "stdout.log", "stderr.log", "inputs.json", "inputs.zip")}
spec = manifest["runs"]["feedback-1"]
gate["helper"] = raw(spec["helper"])
result, start, process = [parsed(gate[name + ".json"]) for name in ("result", "started", "process")]
need(all(result.get(k) == v for k, v in start.items()) and result["command"] == process["command"], "feedback start/process/result")
times = [datetime.fromisoformat(t) for t in (start["start"], process["observed"], result["finish"])]
need(all(t.utcoffset() is not None for t in times) and times == sorted(times), "closed feedback chronology")
need(result["exitCode"] == 0 and result["inputsUnchanged"] is True and TEST in result["command"], "passed exact feedback gate")
need(result["environment"]["ARCADIA_RENDER_EVIDENCE_DIR"].replace("\\", "/") == result["cwd"].replace("\\", "/") + "/.local/process-feedback-review/capture-1", "actual output directory provenance")
for key, name in (("inputs", "inputs.json"), ("archive", "inputs.zip"), ("stdout", "stdout.log"), ("stderr", "stderr.log"), ("helper", "helper")):
need(result[key] == pin(gate[name]), "feedback receipt pin: " + key)
need(result["inputs"]["sha256"] == INPUT_SHA, "fixed b153 input map identity")
inputs = parsed(gate["inputs.json"])
need(len(inputs) == result["inputCount"] == 742 and all(safe(name) for name in inputs), "captured source inventory")
with zipfile.ZipFile(io.BytesIO(gate["inputs.zip"])) as capsule:
inventory(capsule, inputs)
source = {name: capsule.read(name) for name in inputs}
need(all(pin(source[name]) == expected for name, expected in inputs.items()), "all captured source bytes")
need(("test behavior::topology::view::layout_tests::" + TEST + " ... ok").encode() in gate["stdout.log"], "actual test result")
return gate, source
def verify_data(manifest, read, checks):
need(manifest["schema"] == 1 and manifest["kind"] == "process-render-feedback" and manifest["sourceCommit"] == COMMIT, "feedback manifest")
need(set(manifest["members"]) == MEMBERS, "exact feedback files")
for name, expected in manifest["members"].items():
need(pin(read(name)) == expected, "feedback pin: " + name)
gate, source = checks
need(manifest["checksRun"] == "feedback-1" and manifest["checksPins"] == {name: pin(data) for name, data in gate.items()}, "exact checks references")
need(manifest["capturingSources"] == {name: pin(source[name]) for name in SOURCES}, "capturing test and renderer source identity")
report = parsed(read("capture-1/png-readback.json"))
need(set(report["captures"]) == set(NAMES), "four readback records")
for layer in ("Oa", "Sa"):
previous = None
for stage in ("before-press", "after-motion"):
name = f"process-{layer}-{stage}"
metadata = parsed(read("capture-1/" + name + ".json"))
raw = read("capture-1/" + name + ".rgba")
need(metadata["layer"] == layer and metadata["stage"] == stage and metadata["format"] == "RGBA8", "capture identity")
need(metadata["width"] == 1440 and metadata["height"] == 900 and len(raw) == 1440 * 900 * 4, "exact original dimensions")
need(metadata["selectionCount"] == 2 and isinstance(metadata["selection"], str) and "history" not in metadata, "selection metadata; no invented history field")
bundle = metadata["source"]
need(safe(bundle["entry"]) and bundle["entry"] in bundle["files"] and all(safe(n) and isinstance(s, str) for n, s in bundle["files"].items()), "complete captured source bundle")
with Image.open(io.BytesIO(read("capture-1/" + name + ".png"))) as png:
need(png.format == "PNG" and png.size == (1440, 900) and png.convert("RGBA").tobytes() == raw, "decoded PNG equals actual raw RGBA")
expected = {"bytes": len(raw), "rgbaSha256": pin(raw)["sha256"], "width": 1440, "height": 900}
need(report["captures"][name] == expected, "original PNG readback receipt")
if previous:
for field in ("source", "selection", "selectionCount", "canvas", "camera", "scale", "width", "height"):
need(metadata[field] == previous[0][field], layer + " changed " + field + " before release")
need(raw != previous[1], "actual before/after pixel difference")
previous = metadata, raw
return {"captures": 4, "pngPixelsExact": True, "stableMetadataPairs": 2, "checksRun": "feedback-1", "nativeAcceptance": False}
def verify_package(root, checks):
files = parsed((root / "files.json").read_bytes())
need(set(files) == OUTER, "feedback outer inventory")
for name, expected in files.items():
need(pin((root / name).read_bytes()) == expected, "feedback outer pin")
manifest = parsed((root / "manifest.json").read_bytes())
with zipfile.ZipFile(root / "evidence.zip") as archive:
inventory(archive, manifest["members"])
return verify_data(manifest, archive.read, checks)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("package", nargs="?", type=Path, default=Path(__file__).resolve().parent)
parser.add_argument("--checks", type=Path, required=True, help="Process checks package containing closed feedback-1")
args = parser.parse_args()
print("PASS feedback byte proof:", verify_package(args.package, checks_data(args.checks)))
print("History is asserted by the captured test, not recorded in image metadata. No native acceptance claim.")
@@ -0,0 +1,48 @@
# Portable Process native receipts
Adapted from the State native evidence package. Python standard library only;
neither preparation nor verification runs any GUI, checker, archived helper or binary.
From a checkout, validate explicit closed runs:
```text
python -B prepare.py --root C:/ar-multiselect-9e8r6t --runs run-1 --check-only
python -B prepare.py --root C:/ar-multiselect-9e8r6t --runs run-1 run-2 --output FRESH_DIRECTORY
python -B FRESH_DIRECTORY/verify.py
```
The output directory must not exist. Run-2 is an example, usable only after its
finished.json exists. Explicit names prevent accidental capture of a live run.
No run is automatically accepted. Run-1 always retains `reviewStatus: failed`:
Back exposed the outer reference's editable Properties while highlighting the
qualified tile; reorder and history were not performed. Later runs are
`unreviewed` by this tool even if independently accepted in the parent's report.
The archive retains every run file byte, exact prepared helpers (including
common.py and README.md), the actual capture-executed.js separately, complete
fixture/working/snapshot source, screenshots and accessibility JSON, logs,
normal-exit/closure flags, and history-bytes.json when present. The executed
capture function is preserved and package-pinned; the preparation receipt does
not authenticate it as the same bytes as the prepared capture.js template.
Both GUI and checker build raw receipts, process/start metadata, logs, complete
input maps and source ZIPs are archived. Source maps/ZIPs are deduplicated by
exact hash. The historical checker source is also directly available. Helpers
must match recorded pins; use repeated `--helper PATH` for unavailable historical
versions. Never rewrite original capture helpers to make pins pass.
Verification checks safe unique ZIP paths and JSON keys, all member hashes,
reference closure, lifecycle/time relationships, exact prepared helpers,
source-map equality, every source-capsule byte, executable receipt identity,
artifact membership in raw Cargo output, all snapshot reports, and literal
history bytes if present. Nonzero native/checker exits are retained as data;
missing closure or inconsistent receipts refuse packaging. A successful receipt
consistency check is not a claim that native interactions succeeded.
The verifier does not authenticate authorship, independently replay the checker,
interpret screenshot contents, verify pixel dimensions, infer click/drag/focus
actions, prove one-step history, or establish usability/native acceptance. Input
hashes establish recorded consistency, not a reproducible-build proof. Binaries
are identified by build readback pins and native receipts, not included or run.
Independent parent review remains necessary. Failed checker output is preserved
verbatim and not required to be a positive JSON report.
@@ -0,0 +1,22 @@
{
"prepare.py": {
"bytes": 6712,
"sha256": "d6b265b0047e9e0f8d67b71a9208b0467cd12b0470690713bfce6e3ceba6e0d3"
},
"verify.py": {
"bytes": 16518,
"sha256": "035e2e3eacdfb4205e6560fa85befbe65bbc2d20c5c8a42a11e4a965131ed0e4"
},
"README.md": {
"bytes": 2857,
"sha256": "57d447f984fd8dccc1e93fdb7b493bbb9e76a081b2a0a2d28689da86c0d61ce4"
},
"manifest.json": {
"bytes": 80265,
"sha256": "7bd4fa9247941d17939de989501b66c0d5d04f222424fb092c00f52f765b5bca"
},
"evidence.zip": {
"bytes": 12355442,
"sha256": "e94c3e9f2fb644c8e415e09b75eaf973d9c2a93534ad9e41d69793a3c11e8f88"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,115 @@
"""Package explicitly named closed Process native runs; never execute archived helpers."""
from pathlib import Path
import argparse
import io
import json
import re
import zipfile
from verify import pin, parsed, need, norm, relative, safe, zip_inventory, verify_data, verify_package
HERE = Path(__file__).resolve().parent
FAILED_RUN_ONE = "Observed Back restored qualified highlight with outer-reference editable Properties; reorder and Undo/Redo/reopen history were not performed. Failed native workflow, despite three positive unchanged Project reports."
def collect(root, runs, extra_helpers=()):
native = root / ".local/process-multiselect-native"
candidates = [p for p in native.iterdir() if p.is_file()]
candidates += sorted((root / ".local/process-group-gates").glob("*.py"))
candidates += list(extra_helpers)
helpers = [(p.suffix, p.read_bytes()) for p in candidates]
payload, specs = {}, {}
def add(name, data):
need(safe(name) and (name not in payload or payload[name] == data), "member collision: " + name)
payload[name] = data
return name
def helper(expected):
matches = [(suffix, data) for suffix, data in helpers if pin(data) == expected]
need(matches, "exact historical helper unavailable: " + str(expected))
suffix, data = matches[0]
return add("helpers/" + expected["sha256"] + suffix, data)
def tree(folder, prefix):
need(folder.is_dir(), "missing directory: " + str(folder))
for path in sorted(folder.rglob("*")):
need(not path.is_symlink() and not getattr(path, "is_junction", lambda: False)(), "linked evidence input")
if path.is_file():
add(prefix + path.relative_to(folder).as_posix(), path.read_bytes())
for run in runs:
folder = native / run
need((folder / "finished.json").is_file(), "open/unlaunched run refused: " + run)
prepared = parsed((folder / "prepared.json").read_bytes())
tree(folder, "runs/" + run + "/raw/")
spec = {"originalRun": norm(prepared["cwd"]) + "/.local/process-multiselect-native/" + run,
"reviewStatus": "failed" if run == "run-1" else "unreviewed",
"reviewNote": FAILED_RUN_ONE if run == "run-1" else "Packaging consistency does not decide native acceptance. Consult the independent parent review.",
"helpers": {name: helper(expected) for name, expected in prepared["helpers"].items()},
"executedCapture": pin((folder / "capture-executed.js").read_bytes()), "builds": {}}
for kind in ("gui", "checker"):
recorded = prepared[kind]
rel = relative(recorded["receipt"], prepared["cwd"])
need(rel.startswith(".local/process-group-gates/") and rel.endswith("/result.json"), "unexpected receipt location")
receipt = root / rel
result_data = receipt.read_bytes()
need(pin(result_data) == recorded["receiptPin"], "historical build receipt changed")
result = parsed(result_data)
prefix = "builds/" + pin(result_data)["sha256"] + "/"
build = {"originalRelative": rel, "helper": helper(result["helper"])}
for name in ("started.json", "process.json", "result.json", "stdout.log", "stderr.log", "inputs.json", "inputs.zip"):
data = (receipt.parent / name).read_bytes()
# Deduplicate source capsules independently of differing build receipts.
member = ("inputs/" + pin(data)["sha256"] + Path(name).suffix) if name.startswith("inputs.") else prefix + name
build[name] = add(member, data)
spec["builds"][kind] = build
if kind == "checker":
capsule = payload[build["inputs.zip"]]
need(pin(capsule) == result["archive"], "historical checker capsule pin")
inputs = parsed(payload[build["inputs.json"]])
with zipfile.ZipFile(io.BytesIO(capsule)) as archive:
zip_inventory(archive, inputs)
source = archive.read("crates/oa-core/examples/process_multiselect_native.rs")
spec["checkerSource"] = add("checker-source/" + pin(source)["sha256"] + ".rs", source)
specs[run] = spec
manifest = {"schema": 1, "kind": "process-multiselect-native", "runs": specs,
"members": {name: pin(data) for name, data in sorted(payload.items())}}
return payload, manifest, verify_data(manifest, payload.__getitem__)
def write_json(path, value):
with path.open("xb") as stream:
stream.write((json.dumps(value, indent=2) + "\n").encode())
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--runs", nargs="+", required=True)
parser.add_argument("--output", type=Path)
parser.add_argument("--check-only", action="store_true")
parser.add_argument("--helper", type=Path, action="append", default=[], help="Exact historical helper bytes if current helper changed")
args = parser.parse_args()
need(len(args.runs) == len(set(args.runs)) and all(re.fullmatch(r"run-[0-9]+", name) for name in args.runs), "explicit unique run-N names required")
need(args.check_only or args.output is not None, "--output or --check-only required")
if args.output is not None:
need(not args.output.exists(), "fresh nonexistent output directory required")
payload, manifest, summary = collect(args.root.resolve(), args.runs, args.helper)
if args.check_only:
print("PASS raw consistency; no archive written:", summary)
return
out = args.output.resolve()
out.mkdir(parents=True, exist_ok=False)
for name in ("prepare.py", "verify.py", "README.md"):
with (out / name).open("xb") as stream:
stream.write((HERE / name).read_bytes())
with zipfile.ZipFile(out / "evidence.zip", "x", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
for name, data in sorted(payload.items()):
info = zipfile.ZipInfo(name, date_time=(2026, 9, 23, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
archive.writestr(info, data)
write_json(out / "manifest.json", manifest)
write_json(out / "files.json", {name: pin((out / name).read_bytes()) for name in ("prepare.py", "verify.py", "README.md", "manifest.json", "evidence.zip")})
need(verify_package(out) == summary, "written package differs from raw evidence")
print("PASS package readback:", out, summary)
if __name__ == "__main__":
main()
@@ -0,0 +1,229 @@
"""Verify archived native receipts and bytes; do not rerun the GUI or checker."""
from pathlib import Path, PurePosixPath
from datetime import datetime
import argparse
import hashlib
import json
import io
import re
import stat
import zipfile
BASE = {"prepared.json", "started.json", "finished.json", "generation.json", "generation.stdout.log",
"generation.stderr.log", "app.stdout.log", "app.stderr.log", "capture-executed.js"}
OUTER = {"prepare.py", "verify.py", "README.md", "manifest.json", "evidence.zip"}
def need(ok, message):
if not ok:
raise ValueError(message)
def pin(data):
return {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
def safe(name):
return (isinstance(name, str) and bool(name) and "\\" not in name and ":" not in name
and not PurePosixPath(name).is_absolute() and all(ord(c) >= 32 for c in name)
and all(part not in ("", ".", "..") for part in name.split("/")))
def parsed(data):
def unique(items):
result = {}
for key, value in items:
need(key not in result, "duplicate JSON key: " + key)
result[key] = value
return result
return json.loads(data, object_pairs_hook=unique)
def norm(path):
return path.replace("\\", "/").rstrip("/")
def relative(path, root):
prefix = norm(root) + "/"
need(norm(path).startswith(prefix), "recorded path outside owner: " + path)
value = norm(path)[len(prefix):]
need(safe(value), "unsafe recorded relative path")
return value
def ordered(*values):
times = [datetime.fromisoformat(value) for value in values]
return all(t.utcoffset() is not None for t in times) and times == sorted(times)
def zip_inventory(archive, members):
names = archive.namelist()
need(len(names) == len(set(names)) and set(names) == set(members), "exact archive members")
for info in archive.infolist():
need(safe(info.filename) and not info.is_dir() and not stat.S_ISLNK(info.external_attr >> 16), "unsafe archive member")
need(info.file_size == members[info.filename]["bytes"], "archive member size")
def verify_data(manifest, read):
need(manifest["schema"] == 1 and manifest["kind"] == "process-multiselect-native", "manifest kind")
members, runs = manifest["members"], manifest["runs"]
need(bool(runs) and all(re.fullmatch(r"run-[0-9]+", run) for run in runs), "run names")
need(all(safe(name) for name in members), "safe member names")
for name, expected in members.items():
need(pin(read(name)) == expected, "member pin: " + name)
used, summaries = set(), {}
def raw(name):
need(name in members, "missing member: " + name)
used.add(name)
return read(name)
def obj(name):
return parsed(raw(name))
def tree(prefix):
return {name[len(prefix):]: raw(name) for name in members if name.startswith(prefix)}
def pinned_tree(prefix, expected):
actual = tree(prefix)
need({name: pin(data) for name, data in actual.items()} == expected, "pinned tree: " + prefix)
return actual
for run, spec in runs.items():
prefix = "runs/" + run + "/raw/"
prepared, start, end, generation = [obj(prefix + n + ".json") for n in ("prepared", "started", "finished", "generation")]
need(spec["reviewStatus"] in ("failed", "unreviewed") and isinstance(spec["reviewNote"], str) and spec["reviewNote"], "explicit non-acceptance status")
if run == "run-1":
need(spec["reviewStatus"] == "failed", "run-1 must retain observed native failure")
origin = norm(prepared["cwd"]) + "/.local/process-multiselect-native/" + run
need(spec["originalRun"] == origin and prepared["run"] == run and start["cwd"] == prepared["cwd"], "original run mapping")
need(start["prepared"] == pin(raw(prefix + "prepared.json")), "launch preparation pin")
need(ordered(generation["start"], generation["finish"], prepared["prepared"], start["start"], end["finish"]), "native lifetime")
need(type(start["pid"]) is int and start["pid"] > 0 and type(end["exitCode"]) is int, "closed native process")
for key in ("guiUnchanged", "checkerUnchanged", "fixtureUnchanged"):
need(type(end[key]) is bool, "closure flag")
need(start["gui"] == prepared["gui"] and start["checker"] == prepared["checker"] == generation["checker"], "binary identity")
need(start["command"] == [prepared["gui"]["binary"]], "GUI command")
need(generation["exitCode"] == 0 and generation["command"][:2] == [prepared["checker"]["binary"], "generate"] and len(generation["command"]) == 3 and norm(generation["command"][2]) == origin + "/fixture", "generation command")
for stream in ("stdout", "stderr"):
need(end[stream] == pin(raw(prefix + "app." + stream + ".log")), "GUI log pin")
need(generation[stream] == pin(raw(prefix + "generation." + stream + ".log")), "generation log pin")
need(set(spec["helpers"]) == set(prepared["helpers"]), "exact prepared helper mapping")
for name, expected in prepared["helpers"].items():
need(safe(name) and "/" not in name and pin(raw(spec["helpers"][name])) == expected, "historical helper: " + name)
need(start["helper"] == prepared["helpers"]["native.py"], "launch helper")
need(pin(raw(prefix + "capture-executed.js")) == spec["executedCapture"], "actual capture function pin")
fixture = pinned_tree(prefix + "fixture/", prepared["fixture"])
fm = parsed(fixture["manifest.json"])
need(fm["fixture"] == "process-multiselect-native-20260923" and fm["source_entry"] == prepared["entry"] and safe(prepared["entry"]), "fixture identity/entry")
need(parsed(fixture["baseline.json"])["id"] == fm["ids"]["project"], "complete Project baseline identity")
fixture_source = {name[7:]: data for name, data in fixture.items() if name.startswith("source/")}
need(prepared["entry"] in fixture_source and norm(prepared["workingEntry"]) == origin + "/working/" + prepared["entry"], "working entry mapping")
working = tree(prefix + "working/")
need(bool(working) and all(name.endswith(".arcadia") for name in working), "saved working tree")
build_maps = {}
for kind, target in (("gui", "arcadia-studio"), ("checker", "process_multiselect_native")):
recorded, b = prepared[kind], spec["builds"][kind]
result, began, process = [obj(b[n]) for n in ("result.json", "started.json", "process.json")]
need(pin(raw(b["result.json"])) == recorded["receiptPin"] and relative(recorded["receipt"], prepared["cwd"]) == b["originalRelative"], "build receipt mapping")
need(all(result.get(k) == v for k, v in began.items()) and process["command"] == result["command"] and type(process["pid"]) is int and process["pid"] > 0, "build start/result/process")
need(result["exitCode"] == 0 and result["inputsUnchanged"] is True and ordered(result["start"], process["observed"], result["finish"], generation["start"]), "successful preceding build")
for stream in ("stdout", "stderr"):
need(pin(raw(b[stream + ".log"])) == result[stream], "build log pin")
need(pin(raw(b["helper"])) == result["helper"], "build helper pin")
need(pin(raw(b["inputs.json"])) == recorded["inputs"] == result["inputs"], "build source map pin")
inputs = obj(b["inputs.json"])
need(len(inputs) == result["inputCount"] and all(safe(name) for name in inputs), "source map count/paths")
capsule = raw(b["inputs.zip"])
need(pin(capsule) == result["archive"], "build source capsule pin")
with zipfile.ZipFile(io.BytesIO(capsule)) as archive:
zip_inventory(archive, inputs)
need(all(pin(archive.read(name)) == expected for name, expected in inputs.items()), "all captured source bytes")
if kind == "checker":
path = "crates/oa-core/examples/process_multiselect_native.rs"
need(raw(spec["checkerSource"]) == archive.read(path), "historical checker source")
artifacts = [row for row in result["artifacts"] if row["cargo"]["target"]["name"] == target]
need(len(artifacts) == 1 and artifacts[0]["readback"] == recorded["pin"] and artifacts[0]["cargo"]["executable"] == recorded["binary"] and artifacts[0]["cargo"]["profile"]["test"] is False, "native executable provenance")
stdout_rows = [parsed(line) for line in raw(b["stdout.log"]).splitlines() if line.strip().startswith(b"{")]
need(artifacts[0]["cargo"] in stdout_rows, "artifact appears in raw Cargo output")
build_maps[kind] = inputs
need(prepared["gui"]["inputs"] == prepared["checker"]["inputs"] and build_maps["gui"] == build_maps["checker"], "same GUI/checker source map")
top = {name[len(prefix):] for name in members if name.startswith(prefix) and "/" not in name[len(prefix):]}
base = BASE | (top & {"history-bytes.json", "observations.md"})
if "observations.md" in top:
raw(prefix + "observations.md")
captures = sorted(name for name in top - base if name.endswith(".json"))
need(captures, "native captures required")
expected_top = base | set(captures)
for name in captures:
capture = obj(prefix + name)
need(ordered(start["start"], capture["time"], end["finish"]), "capture lifetime")
window = capture["window"]
need(norm(window["app"]) == "process:" + norm(prepared["gui"]["binary"]) and type(window["id"]) is int and window["id"] > 0, "captured executable/window")
need(isinstance(capture["accessibility"], dict) and isinstance(capture["images"], list), "accessibility/capture payload")
for image in capture["images"]:
filename = image["file"]
need(safe(filename) and "/" not in filename and filename.startswith(name[:-5] + "-") and filename.endswith((".jpg", ".png")) and filename not in expected_top, "unique image mapping")
need(all(type(image[k]) is int and image[k] > 0 for k in ("width", "height")), "image dimensions")
expected_top.add(filename)
data = raw(prefix + filename)
need(data.startswith(b"\xff\xd8") if filename.endswith(".jpg") else data.startswith(b"\x89PNG\r\n\x1a\n"), "image signature")
need(top == expected_top, "exact top-level run files")
labels = {name[len(prefix + "snapshots/"):].split("/")[0] for name in members if name.startswith(prefix + "snapshots/")}
states, results, positive = {}, {}, []
for label in sorted(labels):
need(re.fullmatch(r"[a-z0-9-]+", label), "snapshot label")
folder = prefix + "snapshots/" + label + "/"
began, result = obj(folder + "started.json"), obj(folder + "result.json")
need(all(result.get(k) == v for k, v in began.items()), "snapshot start/result")
need(result["prepared"] == start["prepared"] and result["checker"] == prepared["checker"] and result["helper"] == prepared["helpers"]["snapshot.py"], "snapshot provenance")
need(ordered(start["start"], result["start"], result["finish"], end["finish"]), "snapshot lifetime")
mode, command = result["mode"], result["command"]
need(mode in ("unchanged", "reordered") and len(command) == 5 and command[:3] == [prepared["checker"]["binary"], "check", mode] and norm(command[3]) == origin + "/fixture/baseline.json" and norm(command[4]) == origin + "/snapshots/" + label + "/source/" + prepared["entry"], "snapshot command")
need(result["baseline"] == pin(fixture["baseline.json"]), "snapshot baseline")
for stream in ("stdout", "stderr"):
need(result[stream] == pin(raw(folder + stream + ".log")), "snapshot log pin")
need(type(result["exitCode"]) is int and all(type(result[k]) is bool for k in ("binaryUnchanged", "workingSourceUnchanged", "snapshotUnchanged", "baselineUnchanged")), "snapshot closure")
states[label] = pinned_tree(folder + "source/", result["source"])
need({name for name in members if name.startswith(folder)} == {folder + n for n in ("started.json", "result.json", "stdout.log", "stderr.log")} | {folder + "source/" + n for n in states[label]}, "exact snapshot files")
if result["exitCode"] == 0:
report = obj(folder + "stdout.log")
need(report["result"] == "PASS" and report["comparison"] == "complete Project equality; literal expected order" and report["mode"] == mode and report["baseline"] == command[3] and report["saved"] == command[4], "positive complete Project report")
positive.append(label)
results[label] = result
history_present = "history-bytes.json" in top
if history_present:
history = obj(prefix + "history-bytes.json")
groups = history["equalByteGroups"]
need(len(groups) == 2 and groups[0][:2] == ["baseline", "undo"] and groups[1] == ["reordered", "redo", "reopened"], "literal Process history groups")
history_labels = [label for group in groups for label in group]
need(len(history_labels) == len(set(history_labels)) and set(history_labels) == set(history["snapshots"]) and set(history_labels) <= set(positive), "history labels/positive reports")
need(history["status"] == "PASS" and history["prepared"] == start["prepared"] and history["helper"] == prepared["helpers"]["history-bytes.py"] and ordered(end["finish"], history["verified"]), "history provenance")
need(end["exitCode"] == 0 and all(end[k] is True for k in ("guiUnchanged", "checkerUnchanged", "fixtureUnchanged")), "history clean closure")
for group, mode in zip(groups, ("unchanged", "reordered")):
for label in group:
need(states[label] == states[group[0]] and results[label]["mode"] == mode and history["snapshots"][label] == pin(raw(prefix + "snapshots/" + label + "/result.json")), "literal history bytes/receipt")
need(all(results[label][k] is True for k in ("binaryUnchanged", "workingSourceUnchanged", "snapshotUnchanged", "baselineUnchanged")), "stable history snapshot")
need(len(states[label]) == history["sourceFilesPerSnapshot"], "history source count")
need(states["baseline"] == fixture_source and states["baseline"] != states["reordered"], "baseline exact and reorder changed")
changed = sorted(name for name in set(states["baseline"]) | set(states["reordered"]) if states["baseline"].get(name) != states["reordered"].get(name))
need(changed == history["changedFilesFromBaseline"] == ["oa/behavior/process_oa_process.arcadia"], "only intended OA source changed")
sequence = [results[label] for label in ("baseline", "reordered", "undo", "redo", "reopened")]
need(all(ordered(a["finish"], b["start"]) for a, b in zip(sequence, sequence[1:])), "history chronology")
summaries[run] = {"reviewStatus": spec["reviewStatus"], "exitCode": end["exitCode"], "captures": len(captures), "snapshots": len(labels), "positiveReports": len(positive), "historyBytes": history_present}
need(used == set(members), "unreferenced package members: " + repr(set(members) - used))
return summaries
def verify_package(root):
files = parsed((root / "files.json").read_bytes())
need(set(files) == OUTER, "outer files")
for name, expected in files.items():
need(pin((root / name).read_bytes()) == expected, "outer pin: " + name)
manifest = parsed((root / "manifest.json").read_bytes())
with zipfile.ZipFile(root / "evidence.zip") as archive:
zip_inventory(archive, manifest["members"])
return verify_data(manifest, archive.read)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("package", nargs="?", type=Path, default=Path(__file__).resolve().parent)
args = parser.parse_args()
print("PASS byte/receipt consistency only:", verify_package(args.package))
print("No GUI/checker execution or native acceptance claim; see independent parent review.")
@@ -0,0 +1,31 @@
# Process run-2 preparation failure
These are the exact three files retained from
`.local/process-multiselect-native/run-2`: generation.json and its empty stdout
and stderr logs. Fixture generation exited **3221225781 (0xC0000135)** before
preparation completed. There was no GUI launch, prepared.json, started.json or
finished.json. This is a failed preparation receipt, not a native run or a
failed complete-Project comparison.
The checker came from `native-build-2`, source commit
`b743a10d51032dc1655b94fed5e49fbbbcee83f4`. The parent diagnosed the omitted
toolchain runtime environment in its preparation shell; Windows reported the
missing-DLL status. The parent subsequently retried with that environment in
run-3 successfully. That diagnosis and retry outcome are parent observations;
the raw run-2 receipt records the exit code, executable/build pins and empty
streams, and does not record its environment or name a missing DLL. Run-3's
separate native evidence owns its acceptance claims.
Verify with Python's standard library, using the portable sibling checks:
```text
python -B verify.py --checks ../checks
```
The verifier checks exact raw/outer bytes, failed generation command and
chronology, empty stream pins, and the checker's precise build receipt, input
map and Cargo executable/readback relationship. It also checks the shared
source map against the sibling source proof for b743a10. Run the checks and
source verifiers separately for their complete gate/source verification.
No binary, capture helper or GUI is executed. Pins establish consistency,
not independent authentication or a reproduction of the environment failure.
@@ -0,0 +1,26 @@
{
".gitattributes": {
"bytes": 8,
"sha256": "705fd4d6451a31d36b3df7de96f83f30ac976c9b4a6d1e51671d8e2f33e2d0da"
},
"generation.json": {
"bytes": 1251,
"sha256": "a1b145327abcc8fe11a1871e1895dba4a58366e59edd7e21eda7dd971bb6106a"
},
"generation.stderr.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"generation.stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"README.md": {
"bytes": 1654,
"sha256": "774ad0e899198ab177b52e1f231d05f0b0cf953c8d8f08388b0ce3ab113e9f9c"
},
"verify.py": {
"bytes": 6029,
"sha256": "93824a57652fad13cf780837dc19f3db0913d67893ade6ae4bc26a3569667a63"
}
}
@@ -0,0 +1,34 @@
{
"start": "2026-09-23T13:29:37.155542+00:00",
"finish": "2026-09-23T13:29:37.176859+00:00",
"command": [
"C:\\Users\\User\\Documents\\Git\\ARCADIA-Studio\\.local\\target-gnullvm\\debug\\examples\\process_multiselect_native.exe",
"generate",
"C:\\ar-multiselect-9e8r6t\\.local\\process-multiselect-native\\run-2\\fixture"
],
"exitCode": 3221225781,
"checker": {
"receipt": "C:\\ar-multiselect-9e8r6t\\.local\\process-group-gates\\native-build-2\\result.json",
"receiptPin": {
"bytes": 3322,
"sha256": "1df7538acda0f38b36f91d0293a7f74a5f4d308797f35b1d4dabaa7155aae23b"
},
"binary": "C:\\Users\\User\\Documents\\Git\\ARCADIA-Studio\\.local\\target-gnullvm\\debug\\examples\\process_multiselect_native.exe",
"pin": {
"bytes": 22190080,
"sha256": "1cbafb797c9451f908d7567048ace474511a76d98129dabc635e4ee6f976367c"
},
"inputs": {
"bytes": 124276,
"sha256": "f3fd180af294e0797f9dfdbff647274de30a907b685a4fe1a2b58027bfe7da95"
}
},
"stdout": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stderr": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
}
@@ -0,0 +1,97 @@
"""Verify a preserved failed preparation; never run its executable or helpers."""
from pathlib import Path, PurePosixPath
from datetime import datetime
import argparse
import hashlib
import json
import stat
import zipfile
HERE = Path(__file__).resolve().parent
COMMIT = "b743a10d51032dc1655b94fed5e49fbbbcee83f4"
FILES = {".gitattributes", "README.md", "verify.py", "generation.json", "generation.stdout.log", "generation.stderr.log"}
def need(ok, message):
if not ok:
raise ValueError(message)
def pin(data):
return {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
def parsed(data):
def unique(items):
result = {}
for key, value in items:
need(key not in result, "duplicate JSON key")
result[key] = value
return result
return json.loads(data, object_pairs_hook=unique)
def safe(name):
return isinstance(name, str) and bool(name) and not PurePosixPath(name).is_absolute() and all(c not in name for c in ("\\", ":")) and all(ord(c) >= 32 for c in name) and all(p not in ("", ".", "..") for p in name.split("/"))
def verify(root, checks, source):
pins = parsed((root / "files.json").read_bytes())
need(set(pins) == FILES and {p.name for p in root.iterdir()} == FILES | {"files.json"}, "exact failed-preparation files")
for name, expected in pins.items():
need((root / name).is_file() and not (root / name).is_symlink() and pin((root / name).read_bytes()) == expected, "preserved pin: " + name)
generation = parsed((root / "generation.json").read_bytes())
need(generation["exitCode"] == 3221225781, "original missing-DLL status")
for stream in ("stdout", "stderr"):
data = (root / ("generation." + stream + ".log")).read_bytes()
need(not data and pin(data) == generation[stream], "original empty generation stream")
recorded = generation["checker"]
outer = parsed((checks / "files.json").read_bytes())
need(set(outer) == {"README.md", "prepare.py", "verify.py", "manifest.json", "evidence.zip"}, "checks package inventory")
for name, expected in outer.items():
need(pin((checks / name).read_bytes()) == expected, "checks outer pin")
manifest = parsed((checks / "manifest.json").read_bytes())
need(manifest["kind"] == "multiselect-cargo-gates", "checks kind")
with zipfile.ZipFile(checks / "evidence.zip") as archive:
need(len(archive.namelist()) == len(set(archive.namelist())) and set(archive.namelist()) == set(manifest["members"]), "checks archive inventory")
for row in archive.infolist():
need(safe(row.filename) and not row.is_dir() and not stat.S_ISLNK(row.external_attr >> 16), "unsafe checks archive member")
def raw(name):
member = manifest["logicalFiles"]["cargo/native-build-2/" + name]
data = archive.read(member)
need(pin(data) == manifest["members"][member], "checks member pin")
return data
result_bytes, input_bytes = raw("result.json"), raw("inputs.json")
result = parsed(result_bytes)
need(recorded["receiptPin"] == pin(result_bytes), "exact checker build receipt")
need(recorded["inputs"] == result["inputs"] == pin(input_bytes), "same exact checker input map")
need(len(parsed(input_bytes)) == result["inputCount"] == 742, "complete Process source count")
need(result["head"] == COMMIT and result["exitCode"] == 0 and result["inputsUnchanged"] is True, "successful b743 checker build")
need(recorded["receipt"].replace("\\", "/") == result["cwd"].replace("\\", "/") + "/.local/process-group-gates/native-build-2/result.json", "original receipt path")
rows = [row for row in result["artifacts"] if row["cargo"]["target"]["name"] == "process_multiselect_native"]
need(len(rows) == 1 and rows[0]["readback"] == recorded["pin"] and rows[0]["cargo"]["executable"] == recorded["binary"] and rows[0]["cargo"]["profile"]["test"] is False, "exact native checker artifact")
stdout = raw("stdout.log")
need(pin(stdout) == result["stdout"], "checker build log pin")
cargo_rows = [parsed(line) for line in stdout.splitlines() if line.startswith(b"{")]
need(rows[0]["cargo"] in cargo_rows, "actual Cargo output artifact")
command = generation["command"]
need(len(command) == 3 and command[:2] == [recorded["binary"], "generate"] and command[2].replace("\\", "/") == result["cwd"].replace("\\", "/") + "/.local/process-multiselect-native/run-2/fixture", "exact failed generation command")
times = [datetime.fromisoformat(t) for t in (result["start"], result["finish"], generation["start"], generation["finish"])]
need(all(t.utcoffset() is not None for t in times) and times == sorted(times), "build then failed generation chronology")
source_pins = parsed((source / "files.json").read_bytes())
for name in ("manifest.json", "source-core-3.json"):
need(pin((source / name).read_bytes()) == source_pins[name], "source proof pin")
spec = parsed((source / "manifest.json").read_bytes())["runs"]["core-3"]
proof_bytes = (source / "source-core-3.json").read_bytes()
proof = parsed(proof_bytes)
need(spec["receiptPin"] == pin(proof_bytes) and spec["commit"] == proof["commit"] == COMMIT and spec["inputMap"] == proof["inputMap"] == recorded["inputs"], "same b743 source proof")
return {"preparationExit": generation["exitCode"], "hexExit": hex(generation["exitCode"]), "checkerBuild": "native-build-2", "sourceCommit": COMMIT, "guiLaunch": False}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("package", nargs="?", type=Path, default=HERE)
parser.add_argument("--checks", type=Path)
parser.add_argument("--source", type=Path)
args = parser.parse_args()
print("PASS preserved failed-preparation consistency:", verify(args.package, args.checks or args.package.parent / "checks", args.source or args.package.parent / "source"))
@@ -0,0 +1 @@
* -text
@@ -0,0 +1,15 @@
# Historical Process return/navigation reviews
The two Markdown reports are byte-for-byte copies of the independent delegated
reviews `.local/process-return-review.md` and `.local/process-return-review-2.md`,
written on 2026-09-23 against successive working diffs over b153451. They record
static source inspection, findings, correction assessment and remaining test
gaps at those checkpoints. They did not execute Cargo or native UI and are not
acceptance receipts for the final source.
Review 1 identified the invalid nonprimary menu test setup and retained qualified
identity during explicit local navigation. Review 2 assessed the broader fix
and distinguished protective test gaps from demonstrated defects. Preserve
their historical wording; subsequent gate/source/native evidence establishes
what was tested later. files.json pins both exact copied reports and this
provenance note. The [native run-3 review](process-native-review-3.md) is a portable copy with only archive-link formatting adapted; the original review hash is recorded in it. [Parent observations](run-3-observations.md) describe the actual input sequence. The four browseable screenshots under `images/` are exact copies of their native archive members. The review identifies a remaining routing readability defect, not a model-corruption result.
@@ -0,0 +1,42 @@
{
".gitattributes": {
"bytes": 8,
"sha256": "705fd4d6451a31d36b3df7de96f83f30ac976c9b4a6d1e51671d8e2f33e2d0da"
},
"images/run-1/26-back-to-caller-0.jpg": {
"bytes": 166409,
"sha256": "a74368cc8ce4ad3ffb397b8ad3fc88349220635320bfe7458f29a980e033dcfe"
},
"images/run-3/16-exact-qualified-back-0.jpg": {
"bytes": 129288,
"sha256": "dd32a1faceb0dcda161fce7b614ed554ad97d85471b01f09faeea319255bb7fc"
},
"images/run-3/36-group-primary-c-0.jpg": {
"bytes": 137655,
"sha256": "8ba0c813893e00371ac34af5231b48e82f5b25b60c5797f4e618df7a1dab462f"
},
"images/run-3/39-group-reordered-0.jpg": {
"bytes": 139094,
"sha256": "3f967cd523085ba01607ec33ff30e908480ed1847e2688b2b28b896f43d5c0c9"
},
"process-native-review-3.md": {
"bytes": 7040,
"sha256": "dacf078c1f3e9e669fd93bb13949851e7e2c54a9ff3e66a559c34308646af86c"
},
"process-return-review-2.md": {
"bytes": 4489,
"sha256": "65dfd4dd26c492fc32c9c8abecea299648c560eb69ff4f73438f77302e63c4b8"
},
"process-return-review.md": {
"bytes": 3903,
"sha256": "a2da6b641e594438b94194664a3d44ef1d07c28d080d25fc4252d45d199e5dfe"
},
"README.md": {
"bytes": 1324,
"sha256": "ba2beda41d8e3af88e2830280364dc4791f48e159f445c99716cc2e2d32a5b76"
},
"run-3-observations.md": {
"bytes": 5124,
"sha256": "d5bccef8f0492e180aaa71d0d470c461d571c6ce3ad2c2fbd43c63762af43cac"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

@@ -0,0 +1,39 @@
# Independent Process native review — run 3
Reviewed on 2026-09-23, read-only. Directly inspected run-3 images 12–23, 27–44 and 49–52, and run-1 frame 26. No source edits, builds, UI actions, commits or publication. The native window captures are 1442×932 including Windows chrome, with Process zoom 100%; this review does not generalize to other display sizes.
Capture paths below are members of [native/evidence.zip](../native/evidence.zip). Only link formatting was adapted for this portable copy; original review SHA-256: `bbe98aa59fa9000cb612843dd2a6f5e33692a19512de32cd0baff5ff059b3a69`.
## Result
**No new selection, primary, qualified-return, group-order or saved-state blocker found in the reviewed evidence.** The run-1 Inspector mismatch is visibly corrected. There remains a concrete routing readability problem after reorder, described separately below; do not call routing fully accepted.
## Visible evidence
- 12 first qualified (`runs/run-3/raw/12-first-qualified-0.jpg`) selects Shared detail inside First use. 13 nonprimary menu (`runs/run-3/raw/13-nonprimary-menu-0.jpg`) addresses Shared detail inside Second use while First use remains selected. 14 definition (`runs/run-3/raw/14-nonprimary-definition-0.jpg`) shows the local Shared detail editor with alias `reused_leaf`.
- 16 exact Back (`runs/run-3/raw/16-exact-qualified-back-0.jpg`) and 17 (`runs/run-3/raw/17-caller-tree-expanded-0.jpg`) return to the Second use's inner Shared detail tile, with the exact Second use path in Details, Shared detail as Properties subject and a read-only Inspector. The outer card is not simultaneously highlighted. In contrast, run-1 frame 26 (`runs/run-1/raw/26-back-to-caller-0.jpg`) shows both inner/outer outlines and the editable Second use Inspector despite qualified Details.
- 18 explicit outer (`runs/run-3/raw/18-explicit-outer-properties-0.jpg`) deliberately selects Second use: outline, Properties label and editable Inspector name/alias `reference_two` agree. 19–21 (`runs/run-3/raw/21-current-back-readonly-0.jpg`) show current-qualified Open and Back again returning to read-only Shared detail. 22 same-leaf Explorer navigation (`runs/run-3/raw/22-explorer-same-leaf-definition-0.jpg`) changes to Reusable request detail and restores the editable local `reused_leaf` Inspector. Card bounds/100% scale are stable across equivalent caller states; no visual camera jump is apparent.
- 29 mixed selection (`runs/run-3/raw/29-mixed-selected-0.jpg`) displays two selected, Card A as member and A→U link as primary, with the link Inspector. 30 refusal (`runs/run-3/raw/30-mixed-refused-0.jpg`) retains those identities/positions and presents the readable status: “Reorder requires local contribution cards only; links cannot move with them.” Saved frame 31 preserves that display.
- 32 C (`runs/run-3/raw/32-card-c-0.jpg`), 33 Add A (`runs/run-3/raw/33-card-a-menu-0.jpg`), 34 primary A (`runs/run-3/raw/34-group-primary-a-0.jpg`), 35 Inspect C (`runs/run-3/raw/35-group-menu-c-0.jpg`) and 36 primary C (`runs/run-3/raw/36-group-primary-c-0.jpg`) provide consistent membership/count and primary feedback. Inspect changes the primary to C without dropping A. The menu fits and its unavailable Hide/group-delete explanations are visible.
- 37 selected anchor (`runs/run-3/raw/37-selected-anchor-0.jpg`) / 38 saved (`runs/run-3/raw/38-anchor-saved-0.jpg`) retain A/B/C order and primary C. 39 reordered (`runs/run-3/raw/39-group-reordered-0.jpg`) / 40 saved (`runs/run-3/raw/40-reordered-saved-0.jpg`) show B/A/C, U/V still in their original right-column slots, count two and primary C. This is consistent with source-order A,C despite selection C then A. 41 Undo (`runs/run-3/raw/41-one-undo-0.jpg`) returns A/B/C; 43 Redo (`runs/run-3/raw/43-one-redo-0.jpg`) restores B/A/C; primary C/count stay visible. Actions themselves were observed by the parent, not by this reviewer.
- 49 reopen (`runs/run-3/raw/49-reopened-0.jpg`), 50 Behavior (`runs/run-3/raw/50-reopened-behavior-0.jpg`), 51 order (`runs/run-3/raw/51-reopened-order-0.jpg`) and 52 saved (`runs/run-3/raw/52-reopened-saved-0.jpg`) show the reopened project and B/A/C order with zero selected. The process Inspector agrees with the newly selected process. The Explorer tooltip temporarily covers part of Card A's title in 51/52; this is transient pointer feedback, not missing content.
## Concrete remaining visual issue
In reordered frames 39/40/43/44/51/52, the two orthogonal A→U and B→V routes overlap along their shared middle x-coordinate and horizontal segments. Portions of the central vertical path appear interrupted, and the resulting picture can be read as B→U and A→V without carefully tracing the bends. Card titles and primary outlines remain readable, but endpoint connectivity is not reliably legible from this drawing. This is consistent with the parent's existing routing issue #32; I have not independently established its source-level attribution. The complete-Project checker establishes unchanged link records separately, so this should not be reported as group reassignment or source corruption, nor hidden by a blanket “visual pass.”
## Receipt cross-check, independent of screenshots
Read history-bytes.json (`runs/run-3/raw/history-bytes.json`), all eight `snapshots/*/result.json` and checker stdout/stderr, plus the actual ten saved source files for each snapshot. Independently recomputed SHA-256/size pins and confirmed:
- All eight pinned checker receipts/logs/source maps match actual bytes; each checker reports PASS for complete Project equality against literal expected order and exits zero with unchanged baseline/checker/snapshot flags.
- Baseline = undo = qualified-navigation = mixed-refusal = anchor-noop across all ten source files.
- Reordered = redo = reopened across all ten source files.
- Only `oa/behavior/process_oa_process.arcadia` differs between baseline and reordered.
- finished.json (`runs/run-3/raw/finished.json`) records normal exit 0 at `2026-09-23T13:43:54.209222+00:00`; both actual application logs are empty and match their recorded pins. GUI/checker/fixture unchanged flags are true.
The launch receipt records matching GUI/checker input-map pin `f3fd180af294e0797f9dfdbff647274de30a907b685a4fe1a2b58027bfe7da95`; the parent identifies this run with `b743a10`. This review did not independently repeat commit-to-build source identity proof or rerun the checker executable.
## Limits
Screenshots establish visible states, not exact model equality, action counts or Undo stack depth. Those conclusions rely respectively on the checker/source readbacks and the parent's observed single Undo/Redo actions. Frames 37/39 are post-action states; they do not establish native mid-drag insertion-line/count feedback (separate WGPU evidence exists). No new evidence here for SA native interaction, keyboard Shift behavior, dirty/stale guards, Escape/out-and-back, other DPI, accessibility contrast, performance or routing correctness beyond the concrete issue above.
@@ -0,0 +1,27 @@
# Process return/navigation review 2
Read-only review on 2026-09-23 of the working diff over `b153451` in `app.rs`, `app/process_canvas.rs`, `app/process_multiselect.rs` and its tests. No source edits, Cargo, GUI, or native input. This is a correctness review, not runtime acceptance.
## Finding
**No concrete regression found in the reviewed fix.** The previous editable-outer-Inspector failure is addressed at its source: Back restores the validated address's actual occurrence, then reconciles exact selection and explicitly refreshes the primary Inspector. It no longer relies on ordinary object navigation or on matching the outer reference ID to an address.
The new tests cover primary/nonprimary qualified Open and Back, exact invocation path, singleton returned selection, leaf Inspector read-only enforcement, camera/source/history stability, ordinary Select/EditProperties to both the outer reference and same-ID defining leaf, and local-reference Open after qualified inspection. These are assertions in reviewed source; I did not run them.
## Interaction checks
- `App::select` captures preview status before changing owner/selection. Same semantic ID is no longer an early-return when it denotes a qualified preview. Context/focus clearing occurs after `apply()` and existence admission. Existing cross-layer selection still sets layer/diagram, fits and updates the selected behavior owner through the unchanged path.
- `OpenQualified` records the requested resolved address before saving the frame, rather than relying on previous primary. Clearing the live address after saving leaves the frame's address intact. For same-ID current-preview Open, the outer update's existing `preview_read_only` refresh restores a definition draft even if `select` returns early after the owner has already changed.
- Local Open clears the old qualified address before `remember`, so ordinary Back restores a local occurrence rather than inheriting a prior preview. Its new test explicitly covers this.
- `State::back` validates a surviving return route/address and restores camera/expansion state. The App now selects its validated actual subject; `inspect_process_multiselect_primary` clears stale node/bend/attachment/navigation-focus state and restores qualified context only from the exact selected endpoint.
- Usage focus has precedence during reconciliation, but the normal update retires focus as soon as its surface/selected identity becomes invalid on definition navigation. The final inspect clears it again. I found no reachable stale caller-focus override in the reviewed Open→Back path. Existing preview-link usage tests exercise distinct invocation identities, though not this return sequence.
- The Back/Open `apply()` guard remains before frame/context mutation. This preserves the existing policy of applying valid dirty property drafts and refusing pending behavior/source or invalid property edits. It is not a new blanket prohibition on dirty property navigation.
- Qualified resolution enforces identical sequence kind and layer (`topology_context::resolve_path`), so successful qualified Back cannot require a cross-layer restoration that the new direct assignment forgot. Ordinary generic cross-layer navigation still goes through `select`.
## Focused missing regression coverage
The principal gap is **refused navigation at the newly sensitive same-ID boundary**. Add a test starting from a qualified preview with a dirty source draft: send `Select(leaf)` and `EditProperties(leaf)`, and assert exact owner, address, selection/primary, read-only draft, camera, source draft/cursor, and history preservation. Also open a definition, make its property draft invalid, attempt Back, then revert and Back again: the first attempt must leave the return frame available and the second must restore the exact invocation. The static guard ordering appears correct, so this is a missing protective test, not a demonstrated bug.
A smaller extension is generic same-ID navigation from `ProcessPreviewLink`, preferably after a diagram-usage focus. The shared `process_preview_primary` path includes links, but the new generic navigation matrix tests only occurrences. Verify local defining-link selection and editable draft after navigation. Existing tests establish preview-link identity/readonly display, not this transition.
Native pointer/menu/rebuild behavior, focused compile/test results, and final screenshot acceptance remain the parent's separate evidence.
@@ -0,0 +1,21 @@
# Process qualified return review — 2026-09-23
Scope: static review of the two-file working diff over `b153451`, plus the existing return-frame, selection reconciliation and menu code. No production edits, Cargo, or GUI execution. The parent owns the running gate and native acceptance.
## Findings
1. **Concrete new test error:** `app/process_multiselect/tests.rs:676` creates a two-member group containing `second_target`, then in the nonprimary case requests its menu action “Open referenced definition.” `model_menu.rs:312` returns the selected-group menu before the qualified-open action is added. Therefore the `menu` helper cannot find that action and panics. Keep the invoked target unselected while a different qualified target is primary (optionally add a local card), or dispatch captured `OpenQualified` directly and retain a separate actual-menu case. Do not expose a new group menu action merely to satisfy this fixture.
2. **Concrete adjacent identity mismatch remains in generic local navigation:** choose qualified `[R]/leaf`, then send `Message::Select(R)` from Explorer, or `EditProperties(R)`. `App::select` changes `selected` to R and builds its editable draft without clearing the qualified address. `reconcile_process_multiselect` accepts the address when `references.first() == selected`, so it retains the qualified leaf target. The result is the same class of disagreement: leaf highlight with editable R properties. This path predates the proposed Back fix; it is not a new regression caused by the two-file patch. Expected explicit local navigation is local R primary with its own editable draft and no retained qualified address. Add this minimal case before claiming that return/selection identity is generally reconciled. The outer-reference compatibility condition should be confined to return-frame reconstruction, not ordinary selection admission.
## Product patch assessment
- Seeding `resolved.address` immediately before `remember` in `app/process_canvas.rs:131` correctly records the requested qualified invocation when opening a nonprimary context target. The previous primary cannot substitute its reference path.
- Back now reconciles the restored caller scope and inspects its exact primary (`app/process_canvas.rs:226`). This repairs the observed native case: return ID is the outer reference, restored address identifies the qualified leaf, and inspection changes the semantic subject to that leaf with `draft=None` before the next render.
- Ordinary Open/Back with no qualified address continues to reconcile to the local reference and leaves its properties editable. Existing ordinary App and mounted camera-return tests exercise that simpler path (`app/process_canvas.rs:666`, `behavior/topology/layout_tests.rs:805`); this review did not rerun them. A stale qualified address from the generic-navigation finding deserves the additional ordinary-open regression case.
- The new calls do not modify pan/zoom/fit/viewport. Those remain restored by `State::back`; the added inspection clears only selection context/focus and rebuilds properties. Dirty-draft/source/behavior refusal still runs before Back, so this patch does not introduce an unapplied-draft discard path.
- Returning clears the departed surface's group and selects the invoked caller target alone, consistent with surface-scoped selection. The patch does not promise to restore the entire earlier group. Preview-link OpenQualified still transports its source endpoint, so this review does not establish restoration of the exact link selection.
## Gate implications
Correct the test setup, retain the ordinary return/camera checks, and add qualified-to-explicit-local navigation coverage. Native rerun must verify caller path, primary, inspector read-only state, camera and saved Project/source together. Static reasoning here is not a passing gate or native acceptance receipt.
@@ -0,0 +1,28 @@
# Process native run 3 — parent observations
Root operated the Windows app through Computer Use on 2026-09-23. Source b743a10d51032dc1655b94fed5e49fbbbcee83f4; matching captured GUI/checker builds windows-build-2/native-build-2. Production is unchanged from ff712b24190342363d0275467e96f181872da6ad. This run followed a preparation-only run-2 failure; no GUI launched in run 2. Review screenshots with the same-numbered accessibility/time JSON, prepared/start/finish records, and snapshots. Native acceptance below is the parent's observed workflow judgment, separate from automated receipt consistency.
## Observed actions and outcomes
- 01–11: launched, opened the generated run-3 working source, selected Behavior, saved baseline. The Open dialog's accessibility click did not dismiss it; fresh window selection and screenshot-grounded coordinate Open did. UIA reports Search Box focus although the visible filename caret/text is correct. No app failure is inferred from that automation mismatch.
- 12–16: selected first invocation's Shared detail; right-clicked second invocation's tile and explicitly opened its definition while it was nonprimary. Actual defining leaf became editable. Back restored the second qualified tile alone, Shared detail read-only Properties, exact Second use → Shared detail breadcrumb, and caller camera. Outer card was not primary/highlighted. This corrects run-1 frame 26.
- 17–18: Explorer selection of the outer Second use changed to its local editable inspector and outer-card highlight; the qualified leaf was no longer primary.
- 19–21: selected the second leaf and used inspector Open referenced definition, then Back. Current-primary return again restored exact second leaf and read-only Properties.
- 22–23: Explorer selection of the same-ID Shared detail while in preview navigated to its defining owner and editable local inspector. Saved complete Project remained unchanged.
- 24–27: returned to OA group order, selected Card A. Frame 26 tool output was truncated; frame 27 reobserved before further input.
- 28–31: context Add included A-to-U link with Card A, count 2, link primary. Drag A after B was refused with the explicit local-cards-only explanation. Membership, primary, camera and order remained unchanged. Saved Project unchanged.
- 32–36: clicked C, context Add A, then context Inspect this element on C. Count stayed 2; A secondary blue and C primary teal, Properties Card C. Selection order was C then A, contrary to source A then C.
- 37–38: dragged C onto selected A's lower half. Order, count and primary remained unchanged; saved Project unchanged.
- 39–40: dragged C from (420,620) after B at (420,529). Left column became B,A,C; right column U,V unchanged. Count 2, C primary and A secondary persisted; camera stayed 100%. Status reported two contributions reordered. This discriminates against singleton pressed/primary C, whose valid same-column move after B would leave the original order. Saved complete Project matches literal [B,U,A,V,C], with all other model records identical.
- 41–42: exactly one Ctrl+Z restored A,B,C and original complete Project; selection and primary stayed stable. Saved Undo snapshot.
- 43–44: exactly one Ctrl+Y restored B,A,C and the reordered complete Project. Saved Redo snapshot.
- 45–52: opened the exact run-3 working project again in the same process, returned to Behavior/OA group owner, observed B,A,C and U,V, and saved. Transient selection cleared on reopening. Reopened complete Project matches reordered.
- Closed via Alt+F4; launch wrapper finished 13:43:54.209222Z, exit 0, empty stdout/stderr, binaries and immutable fixture unchanged.
## Independent saved-model and byte checks
Eight complete-Project checks passed: baseline, qualified-navigation, mixed-refusal, anchor-noop and undo equal the immutable baseline; reordered, redo and reopened equal the literal expected Project. `history-bytes.json` passes ten files per snapshot: fixture/baseline/undo/three unchanged extras are byte-identical; reordered/redo/reopened are byte-identical. Only `oa/behavior/process_oa_process.arcadia` changes across the two groups. These checks do not infer gestures, focus, selection, read-only state or one-step history; the observed actions above supply that evidence.
## Scope and limitations
Accepted for the observed Windows OA workflow at 1442×932 and 100% zoom. Context Add/Inspect was used; native held Shift was not exercised. Drag API executes a whole gesture, so held-motion line readability comes from the separate actual-WGPU mounted OA/SA capture. Native SA reorder, alternate DPI/minimum window, full accessibility, aggregate deletion, Allocation/Scenario adapters and Linux are not established. Run 1's qualified drag/Delete refusal is historical b153 evidence, supported by final focused/full tests; it was not repeated here. Existing crossing/routing appearance after reordered rows is visible and is not claimed repaired by this change (routing tracked separately in issue 32). This is branch-specific verification, not combined integration or release acceptance.
@@ -0,0 +1 @@
* text eol=lf
@@ -0,0 +1,21 @@
# Process source identity tools
Adapted from the State source package. The Git comparator retains its exact filtered `ls-tree` inventory and `cat-file --batch` blob-byte comparison, with `GIT_NO_LAZY_FETCH=1`. Process scope always contains 742 inputs, including all 71 vendored files and both explicit compile-time fixtures. Commit IDs must be full, explicit IDs already available locally; neither captured HEAD, timestamps nor the current working tree substitutes for comparison.
Validate completed raw captures without writing:
```powershell
python -B prepare.py --repo CHECKOUT --raw-gates CHECKOUT/.local/process-group-gates --gate full-desktop-1 1711bff650dabb1df3a9bc37f19060d5db297feb --gate lint-2 b15345123a7feaf630ef24d45f591c76c6715778 --check-only
```
For the final gate, append `--gate full-desktop-2 FULL_FINAL_COMMIT` only after its result exists and the exact final source commit is available. No final commit is guessed or hardcoded. Other completed gates may be named explicitly. Failed, missing, changed-input or mismatching source gates refuse.
For portable preparation, supply the completed Process `--checks CHECKS_PACKAGE`, remove `--check-only`, and add `--output NEW_SOURCE_PACKAGE`. `--raw-gates` may be omitted when using the package; supplying both requires their selected captured maps/results/archives to be equal. The output is create-only. Preparation validates all captures and Git comparisons before writing pinned manifest, newly generated source receipts, tools and files.json, then performs portable readback. Existing historical receipt files are neither consumed nor rewritten.
```powershell
python -B SOURCE_PACKAGE/verify.py --checks CHECKS_PACKAGE --repo CHECKOUT
```
Without `--repo`, verification validates pinned receipt/map relationships and sibling archived source capsules, but explicitly reports that Git comparison was not rerun. The sibling defaults to ../checks. The checks package must use the existing `multiselect-cargo-gates` schema. All outer/member byte pins, exact ZIP inventory and source capsule mappings are checked; selected nested source archives are checked byte-for-byte against their maps. Run the sibling checks verifier separately for complete helper/process/stream relationships. No archived executable/helper is run or extracted.
`manifest.json` pins the explicitly selected run/commit/map/count/fixture/receipt relationships; files.json pins all package bytes. These are consistency evidence, not independent authentication, hermetic build proof, native usability or release acceptance. Package source checks should be run with `python -B` to avoid an extra __pycache__ directory violating exact package inventory.
@@ -0,0 +1,38 @@
{
".gitattributes": {
"bytes": 14,
"sha256": "a79691a93b46e49ce460c26ef22afcc03d6eca1e63bf2edbc20e96159510f6c9"
},
"README.md": {
"bytes": 2695,
"sha256": "7f20dc17395af4d5f7e08c2873788de9e6dffd0d0401b11efd8a9987cb78bdac"
},
"manifest.json": {
"bytes": 2462,
"sha256": "d4a958402395d806e037dcb236e2460329db42003e72d958939133a049da8bb4"
},
"prepare.py": {
"bytes": 3493,
"sha256": "da6a1c8da417b3caf5ba44a0848cbfd64e6d299ccf2d16f3e7ae742eed69f1c6"
},
"source-core-3.json": {
"bytes": 570,
"sha256": "c0ad71de62a092df89c851c2be6e466c1f24932e43db1b8a7a2b188401ec12cf"
},
"source-feedback-1.json": {
"bytes": 574,
"sha256": "b8688707c7661d22858b2b799f6c671509f8a438069085790a2e43f0fee4aa22"
},
"source-full-desktop-1.json": {
"bytes": 578,
"sha256": "7f2f7675dc11e649a3ac3e3ee834a7dc135436747feaa789d4d7c89c41300d73"
},
"source-full-desktop-2.json": {
"bytes": 578,
"sha256": "7d34865d642f40c865ff69be1c7d744bf1660dd8f5e7a7d421d3f05c45bd446a"
},
"verify.py": {
"bytes": 10094,
"sha256": "7805832d5f563ab2d7a50dd3de700792b5d6f459c68f7b1d8bcfcc9800fa0c3a"
}
}
@@ -0,0 +1,70 @@
{
"kind": "process-multiselect-source",
"runs": {
"core-3": {
"commit": "b743a10d51032dc1655b94fed5e49fbbbcee83f4",
"explicitCompileTimeFixtures": [
"harness/experiments/edge-attachments-20260922/native-fixture.arcadia",
"harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
],
"inputCount": 742,
"inputMap": {
"bytes": 124276,
"sha256": "f3fd180af294e0797f9dfdbff647274de30a907b685a4fe1a2b58027bfe7da95"
},
"receiptPin": {
"bytes": 570,
"sha256": "c0ad71de62a092df89c851c2be6e466c1f24932e43db1b8a7a2b188401ec12cf"
}
},
"feedback-1": {
"commit": "b15345123a7feaf630ef24d45f591c76c6715778",
"explicitCompileTimeFixtures": [
"harness/experiments/edge-attachments-20260922/native-fixture.arcadia",
"harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
],
"inputCount": 742,
"inputMap": {
"bytes": 124276,
"sha256": "7f5b3de4d5bb70282e424fbe90211af2ac259965aef10b05438b46076467a767"
},
"receiptPin": {
"bytes": 574,
"sha256": "b8688707c7661d22858b2b799f6c671509f8a438069085790a2e43f0fee4aa22"
}
},
"full-desktop-1": {
"commit": "1711bff650dabb1df3a9bc37f19060d5db297feb",
"explicitCompileTimeFixtures": [
"harness/experiments/edge-attachments-20260922/native-fixture.arcadia",
"harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
],
"inputCount": 742,
"inputMap": {
"bytes": 124276,
"sha256": "d5acfcf62fb4efd4efaf073abcc7e671644a6086e9e6cf105a06034c4a27daf8"
},
"receiptPin": {
"bytes": 578,
"sha256": "7f2f7675dc11e649a3ac3e3ee834a7dc135436747feaa789d4d7c89c41300d73"
}
},
"full-desktop-2": {
"commit": "ff712b24190342363d0275467e96f181872da6ad",
"explicitCompileTimeFixtures": [
"harness/experiments/edge-attachments-20260922/native-fixture.arcadia",
"harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
],
"inputCount": 742,
"inputMap": {
"bytes": 124276,
"sha256": "1ba4ed414b3ccbc139ad4998af77370cba994f3edf4395b80acc69d3440ccc45"
},
"receiptPin": {
"bytes": 578,
"sha256": "7d34865d642f40c865ff69be1c7d744bf1660dd8f5e7a7d421d3f05c45bd446a"
}
}
},
"schema": 1
}
@@ -0,0 +1,61 @@
"""Bind explicitly named Process gate captures to Git commits; no builds or checkouts."""
from pathlib import Path
import argparse
import datetime
import json
import re
from verify import (HERE, TOOLS, COMPARISON, EXPLICIT_FIXTURES, need, pin, parsed,
compare_commit, verify_data, raw_captures, packaged, verify_package)
def encode(value):
return (json.dumps(value, indent=2, sort_keys=True) + "\n").encode("utf-8")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", required=True, type=Path, help="repository containing the explicitly named full commit IDs")
parser.add_argument("--raw-gates", type=Path, help="completed raw captures; required unless --checks provided")
parser.add_argument("--checks", type=Path, help="completed portable Process checks package; required for writing")
parser.add_argument("--gate", nargs=2, action="append", required=True, metavar=("RUN", "COMMIT"))
parser.add_argument("--check-only", action="store_true")
parser.add_argument("--output", type=Path, help="new source package directory")
args = parser.parse_args()
pairs = {}
for run, commit in args.gate:
need(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", run) is not None, "safe gate name")
need(re.fullmatch(r"[0-9a-f]{40}", commit) is not None, "explicit full commit ID required")
need(run not in pairs, "duplicate gate")
pairs[run] = commit
need(args.raw_gates is not None or args.checks is not None, "capture input required")
captured = packaged(args.checks, pairs) if args.checks else raw_captures(args.raw_gates, pairs)
if args.checks and args.raw_gates:
need(captured == raw_captures(args.raw_gates, pairs), "raw and packaged captures differ")
specs, receipts = {}, {}
for run, commit in pairs.items():
map_bytes, result, _archive = captured[run]
spec = {"commit": commit, "inputCount": 742, "inputMap": pin(map_bytes),
"explicitCompileTimeFixtures": sorted(EXPLICIT_FIXTURES)}
# No receipt is written until every capture and exact commit comparison passes.
receipts[run] = encode({**spec, "gate": run, "comparison": COMPARISON,
"checked": datetime.datetime.now(datetime.timezone.utc).isoformat()})
specs[run] = {**spec, "receiptPin": pin(receipts[run])}
summary = verify_data(receipts, captured, specs, args.repo)
if args.check_only:
need(args.output is None, "--check-only does not write output")
print("PASS source check-only; no package written:", summary)
return
need(args.checks is not None and args.output is not None, "writing requires completed --checks and new --output")
out = args.output.resolve()
need(not out.exists(), "existing output refused")
payload = {name:(HERE/name).read_bytes() for name in TOOLS}
payload["manifest.json"] = encode({"schema":1, "kind":"process-multiselect-source", "runs":specs})
payload.update({"source-"+run+".json": value for run,value in receipts.items()})
out.mkdir(parents=True)
for name, value in payload.items():
with (out/name).open("xb") as stream:
stream.write(value)
with (out/"files.json").open("xb") as stream:
stream.write(encode({name:pin(value) for name,value in sorted(payload.items())}))
print("PASS written package readback:", verify_package(out,args.checks), out)
if __name__ == "__main__":
main()
@@ -0,0 +1,15 @@
{
"checked": "2026-09-23T13:41:55.911287+00:00",
"commit": "b743a10d51032dc1655b94fed5e49fbbbcee83f4",
"comparison": "Exact committed Git blobs equal every captured input; same complete filtered inventory",
"explicitCompileTimeFixtures": [
"harness/experiments/edge-attachments-20260922/native-fixture.arcadia",
"harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
],
"gate": "core-3",
"inputCount": 742,
"inputMap": {
"bytes": 124276,
"sha256": "f3fd180af294e0797f9dfdbff647274de30a907b685a4fe1a2b58027bfe7da95"
}
}
@@ -0,0 +1,15 @@
{
"checked": "2026-09-23T13:41:55.910110+00:00",
"commit": "b15345123a7feaf630ef24d45f591c76c6715778",
"comparison": "Exact committed Git blobs equal every captured input; same complete filtered inventory",
"explicitCompileTimeFixtures": [
"harness/experiments/edge-attachments-20260922/native-fixture.arcadia",
"harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
],
"gate": "feedback-1",
"inputCount": 742,
"inputMap": {
"bytes": 124276,
"sha256": "7f5b3de4d5bb70282e424fbe90211af2ac259965aef10b05438b46076467a767"
}
}
@@ -0,0 +1,15 @@
{
"checked": "2026-09-23T13:41:55.910110+00:00",
"commit": "1711bff650dabb1df3a9bc37f19060d5db297feb",
"comparison": "Exact committed Git blobs equal every captured input; same complete filtered inventory",
"explicitCompileTimeFixtures": [
"harness/experiments/edge-attachments-20260922/native-fixture.arcadia",
"harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
],
"gate": "full-desktop-1",
"inputCount": 742,
"inputMap": {
"bytes": 124276,
"sha256": "d5acfcf62fb4efd4efaf073abcc7e671644a6086e9e6cf105a06034c4a27daf8"
}
}
@@ -0,0 +1,15 @@
{
"checked": "2026-09-23T13:41:55.911287+00:00",
"commit": "ff712b24190342363d0275467e96f181872da6ad",
"comparison": "Exact committed Git blobs equal every captured input; same complete filtered inventory",
"explicitCompileTimeFixtures": [
"harness/experiments/edge-attachments-20260922/native-fixture.arcadia",
"harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
],
"gate": "full-desktop-2",
"inputCount": 742,
"inputMap": {
"bytes": 124276,
"sha256": "1ba4ed414b3ccbc139ad4998af77370cba994f3edf4395b80acc69d3440ccc45"
}
}
@@ -0,0 +1,186 @@
"""Verify pinned Process source receipts against sibling capture capsules; optionally compare Git blobs."""
from pathlib import Path, PurePosixPath
import argparse
import hashlib
import json
import os
import subprocess
import zipfile
import io
import stat
HERE = Path(__file__).resolve().parent
COMPARISON = "Exact committed Git blobs equal every captured input; same complete filtered inventory"
EXPLICIT_FIXTURES = {
"harness/experiments/edge-attachments-20260922/native-fixture.arcadia",
"harness/experiments/textual-authoring-20260911/alarm-response.arcadia",
}
INCLUDE_FIXTURES = True
def need(ok, message):
if not ok:
raise ValueError(message)
def pin(data):
return {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
def parsed(data):
def unique(items):
result = {}
for key, value in items:
need(key not in result, "duplicate JSON key: " + key)
result[key] = value
return result
return json.loads(data, object_pairs_hook=unique)
def safe(name):
return (isinstance(name, str) and bool(name) and "\\" not in name and ":" not in name
and not PurePosixPath(name).is_absolute()
and all(part not in ("", ".", "..") for part in name.split("/")))
def relevant(path):
return (INCLUDE_FIXTURES and path in EXPLICIT_FIXTURES) or path in ("Cargo.toml", "Cargo.lock", "rust-toolchain.toml") or path.startswith(
("crates/", "build/", ".cargo/", "scripts/", "docs/", "examples/", "harness/fixtures/", "harness/prototypes/"))
def git(repo, *arguments, data=None):
environment = dict(os.environ, GIT_NO_LAZY_FETCH="1")
return subprocess.run(["git", *arguments], cwd=repo, input=data, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, check=True, env=environment).stdout
def compare_commit(repo, commit, inputs):
need(git(repo, "rev-parse", "--verify", commit + "^{commit}").decode().strip() == commit, "named commit unavailable")
entries = git(repo, "ls-tree", "-r", "--full-tree", "-z", commit).split(b"\0")
blobs = {}
for entry in filter(None, entries):
header, path_bytes = entry.split(b"\t", 1)
path = path_bytes.decode("utf-8")
if relevant(path):
_mode, kind, oid = header.split()
need(kind == b"blob", "relevant non-blob tree entry: " + path)
need(path not in blobs, "duplicate tree path")
blobs[path] = oid
need(set(blobs) == set(inputs), "complete filtered Git inventory differs; missing="
+ repr(sorted(set(inputs) - set(blobs))) + "; additional=" + repr(sorted(set(blobs) - set(inputs))))
# Object IDs avoid path quoting and commit:path interpretation in batch input.
paths = sorted(blobs)
data = git(repo, "cat-file", "--batch", data=b"".join(blobs[path] + b"\n" for path in paths))
offset, actual = 0, {}
for path in paths:
end = data.index(b"\n", offset)
oid, kind, size_bytes = data[offset:end].split()
size = int(size_bytes)
need(oid == blobs[path] and kind == b"blob" and size >= 0, "Git batch object relationship")
content = data[end + 1:end + 1 + size]
need(len(content) == size and data[end + 1 + size:end + 2 + size] == b"\n", "Git batch framing")
actual[path] = pin(content)
offset = end + 2 + size
need(offset == len(data), "trailing Git batch bytes")
different = [path for path in paths if actual[path] != inputs[path]]
need(not different, "captured bytes differ from named commit: " + repr(different))
def inventory(archive, expected):
names = archive.namelist()
need(len(names) == len(set(names)) and set(names) == set(expected), "exact ZIP inventory")
for item in archive.infolist():
need(safe(item.filename) and not item.is_dir() and not stat.S_ISLNK(item.external_attr >> 16), "safe ZIP member")
need(pin(archive.read(item.filename)) == expected[item.filename], "ZIP member pin: " + item.filename)
def verify_data(receipts, captured, specs, repo=None):
need(set(receipts) == set(captured) == set(specs), "exact source run inventory")
for run, spec in specs.items():
receipt_bytes = receipts[run]
need(pin(receipt_bytes) == spec["receiptPin"], run + ": exact historical receipt bytes")
receipt = parsed(receipt_bytes)
need(receipt["gate"] == run and receipt["comparison"] == COMPARISON, run + ": receipt identity")
need(all(receipt[key] == spec[key] for key in ("commit", "inputCount", "inputMap", "explicitCompileTimeFixtures")), run + ": pinned receipt relationships")
map_bytes, result, archive_bytes = captured[run]
need(pin(map_bytes) == spec["inputMap"] == result["inputs"], run + ": exact captured input map")
need(result["exitCode"] == 0 and result["inputsUnchanged"] is True, run + ": accepted unchanged gate")
inputs = parsed(map_bytes)
need(len(inputs) == 742, run + ": Process 742-input scope required")
need(len(inputs) == spec["inputCount"] == result["inputCount"], run + ": input counts")
need(spec["explicitCompileTimeFixtures"] == (sorted(EXPLICIT_FIXTURES) if INCLUDE_FIXTURES else []), run + ": exact fixture scope")
need(all(safe(name) and relevant(name) for name in inputs), run + ": input scope")
need((EXPLICIT_FIXTURES & set(inputs)) == (EXPLICIT_FIXTURES if INCLUDE_FIXTURES else set()), run + ": explicit fixture membership")
need(sum(name.startswith("crates/vendor/iced_widget/") for name in inputs) == 71, run + ": vendor count")
need(pin(archive_bytes) == result["archive"], run + ": source capsule pin")
with zipfile.ZipFile(io.BytesIO(archive_bytes)) as archive:
inventory(archive, inputs)
if repo is not None:
compare_commit(repo, spec["commit"], inputs)
print("PASS", run, spec["commit"], len(inputs), "source pins" + (" and exact Git blobs" if repo is not None else " (Git comparison not rerun)"))
return {"runs": len(specs), "gitCompared": repo is not None}
def raw_captures(gates, specs):
return {run: ((gates/run/"inputs.json").read_bytes(), parsed((gates/run/"result.json").read_bytes()),
(gates/run/"inputs.zip").read_bytes()) for run in specs}
def packaged(checks, specs):
files = parsed((checks/"files.json").read_bytes())
need(set(files) == {"prepare.py", "verify.py", "README.md", "manifest.json", "evidence.zip"}, "checks outer inventory")
for name, expected in files.items():
need(pin((checks/name).read_bytes()) == expected, "checks outer pin: " + name)
manifest = parsed((checks/"manifest.json").read_bytes())
need(manifest["schema"] == 1 and manifest["kind"] == "multiselect-cargo-gates", "checks kind")
logical, members = manifest["logicalFiles"], manifest["members"]
need(all(safe(name) and safe(target) for name,target in logical.items()) and set(logical.values()) == set(members), "checks logical inventory")
captured = {}
with zipfile.ZipFile(checks/"evidence.zip") as archive:
inventory(archive, members)
for run in specs:
prefix = "cargo/" + run + "/"
result = parsed(archive.read(logical[prefix + "result.json"]))
spec = manifest["runs"][run]
need(all(result[key] == spec[key] for key in ("command", "head", "exitCode", "inputCount")), run + ": checks relationships")
for name in ("inputs.json", "inputs.zip"):
member = logical[prefix+name]
need(member == "capsules/" + members[member]["sha256"] + Path(name).suffix, run + ": source capsule mapping")
captured[run] = (archive.read(logical[prefix+"inputs.json"]), result, archive.read(logical[prefix+"inputs.zip"]))
return captured
TOOLS = {".gitattributes", "prepare.py", "verify.py", "README.md"}
def specifications(manifest):
import re
need(manifest.get("schema") == 1 and manifest.get("kind") == "process-multiselect-source", "source manifest kind")
specs = manifest["runs"]
need(isinstance(specs, dict) and bool(specs), "nonempty explicit source run inventory")
for run, spec in specs.items():
need(isinstance(run, str) and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", run), "safe source gate")
need(isinstance(spec["commit"], str) and re.fullmatch(r"[0-9a-f]{40}", spec["commit"]), "full explicit commit required")
need(spec["inputCount"] == 742 and spec["explicitCompileTimeFixtures"] == sorted(EXPLICIT_FIXTURES), "fixed Process input scope")
return specs
def verify_package(package, checks, repo=None):
files = parsed((package/"files.json").read_bytes())
manifest = parsed((package/"manifest.json").read_bytes())
specs = specifications(manifest)
expected = TOOLS | {"manifest.json"} | {"source-"+run+".json" for run in specs}
need(set(files) == expected, "source outer inventory")
need({p.name for p in package.iterdir()} == expected | {"files.json"}, "source exact package inventory")
for name, value in files.items():
need((package/name).is_file() and not (package/name).is_symlink() and pin((package/name).read_bytes()) == value, "source outer pin: " + name)
receipts = {run:(package/("source-"+run+".json")).read_bytes() for run in specs}
return verify_data(receipts, packaged(checks, specs), specs, repo)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("package", nargs="?", type=Path, default=HERE)
parser.add_argument("--checks", type=Path, help="completed sibling checks package; default ../checks")
parser.add_argument("--repo", type=Path, help="repeat exact named-commit Git inventory/blob comparison")
args = parser.parse_args()
print("PASS source evidence:", verify_package(args.package, args.checks or args.package.parent/"checks", args.repo))
print("No builds or archived helper execution. Run checks verifier separately for full process/log relationships.")
if __name__ == "__main__":
main()
@@ -0,0 +1,32 @@
# Process multiple-selection native evaluator design
The independent evaluator is `crates/oa-core/examples/process_multiselect_native.rs`. This document describes its intended gates, not successful build/test/native evidence. It was prepared while the parent integrated the desktop adapter; no Cargo or formatting command ran during preparation.
## Fixture and expected operation
Generate a fresh directory with deterministic UUIDs, `baseline.json`, source bundle and `manifest.json`. Generation refuses an existing output directory; every write is create-only. The checker also compares the loaded baseline with its deterministic original fixture, so a reordered snapshot cannot silently become the baseline. Pin the generated files and command in the native receipt before interaction; these checks do not authenticate external evidence by themselves.
Open the generated source, choose Behavior and **01 OA group order**. Its source steps are `[Card A, Downstream U, Card B, Downstream V, Card C]`. Explicit links A→U and B→V produce one column containing A/B/C and another containing U/V. A and C are distinct Action occurrences sharing the same reusable Activity; B is a Choice control. Select C, add A, then use **Inspect this element** on C without changing membership. Drag C after B. C is both pressed member and primary: a singleton C reorder would leave the original order unchanged, whereas the group moves A before C. With A primary, a singleton A reorder could accidentally produce the expected group order; that weaker trial is insufficient. Literal expected source steps are `[B,U,A,V,C]`, retaining U/V in indices 1/3 and A/C in their original internal order despite reverse selection.
The checker has `unchanged` and `reordered` modes. It modifies only the expected OA owner's steps with that literal list, then compares the complete Project. It never calls a desktop planner, renderer, selection helper or inferred pointer geometry. Links/guards, reused work, occurrence bodies, all SA records, trace baseline and unrelated processes must remain exact. JSON and source roundtrips are also checked; completeness warnings are permitted, source errors are not.
The compact **SA chain - preserve** contains a matching five-card FunctionalChain fixture. Its complete records must remain unchanged during OA trials. **02 Read-only preview trial** has two local references to **Reusable request detail**. Their preview tiles show the same defining occurrence through different paths, permitting exact-identity/read-only refusal trials; saving after those refusal trials should satisfy `unchanged` against the original baseline.
## Proposed commands
Use the parent's established toolchain and gate receipts. From the repository root:
```text
cargo test --locked --offline -p oa-core --example process_multiselect_native -- --nocapture
cargo run --locked --offline -p oa-core --example process_multiselect_native -- generate FRESH_DIRECTORY
cargo run --locked --offline -p oa-core --example process_multiselect_native -- check unchanged FRESH_DIRECTORY/baseline.json SAVED_SOURCE_ENTRY
cargo run --locked --offline -p oa-core --example process_multiselect_native -- check reordered FRESH_DIRECTORY/baseline.json SAVED_SOURCE_ENTRY
```
The manifest identifies the emitted source entry. Native windows/load paths and executable hashes must be captured by the actual evaluator run. The example supports JSON saved inputs too.
## Falsifiers and limits
Five evaluator tests exercise deterministic/create-only generation; real validated `SetSteps` output; unchanged/reordered distinction and replaced-baseline refusal; wrong global splicing, reversed block, and the unchanged singleton-C result for the prescribed gesture; link guard/endpoint drift, reusable Activity changes, SA semantic/order changes, reused-definition and cross-layer baseline corruption; source compile/roundtrip and valid source drift. Negative Project mutations are asserted core-valid before checker rejection, distinguishing oracle sensitivity from trivial malformed-input rejection.
Native acceptance must separately establish Shift/focus delivery, selection painting/count, selected-anchor no-op, actual Before/After zones, cancellation, context menus, whole-set mixed/qualified refusal, one Undo/Redo, source inspection, stable camera/layout and responsiveness. Whole-Project equality does not establish those interactions or exact source-byte preservation. This fixture does not test aggregate deletion, Allocation or Scenario semantics. `reordered` is specifically the OA operation above; the SA fixture is a preservation sentinel, not an accepted SA native reorder run.