Merge ordinary and State multiselect into the desktop candidate

This commit is contained in:
2026-09-23 11:17:21 -07:00
139 changed files with 21151 additions and 72 deletions
+12 -12
View File
@@ -4,12 +4,12 @@
- Follow `PROJECT_GOAL.md` and the user's current instructions. Work autonomously within scope. Resolve discoverable questions yourself; record, test, and revise reversible assumptions. Ask only when a consequential decision needs information or authorization not already available. Continue independent useful work while blocked elsewhere.
- Map unfamiliar domains through primary sources, comparable systems, and real user workflows. Identify underlying needs, valuable concepts, and avoidable friction; evaluate improvements rather than merely reproducing features. Synthesize findings into decisions or experiments, and stop research when another action offers greater value.
- Make specifications precise enough for compatible independent implementations: definitions, relationships, invariants, valid/invalid examples, and lifecycle or transformation rules where relevant. Trace important requirements and decisions to implementation and verification. Resolve specification ambiguity at its source when implementation exposes it.
- Make specifications precise enough for compatible independent implementations: definitions, relationships, invariants, valid / invalid examples, and lifecycle or transformation rules where relevant. Trace important requirements and decisions to implementation and verification. Resolve specification ambiguity at its source when implementation exposes it.
- For consequential uncertain choices, compare materially different candidates against explicit user-derived criteria. Ask independent critics to challenge assumptions and attempt to falsify proposals; refine or replace candidates as evidence warrants. Record the choice, evidence, tradeoffs, rejected approaches, and reasons to revisit it. Use proportionate effort for reversible local choices.
- Plan milestones that resolve uncertainty or deliver useful capability, with explicit dependencies. Test foundational assumptions before substantial downstream work. At checkpoints, assess progress toward the actual objective and replan when evidence invalidates the strategy or progress stalls.
- Define observable success and suitable evaluators before repeated improvement: invariants, examples, round trips, transformations, performance checks, realistic user tasks, or explicit review rubrics. Ensure the evaluator measures the intended outcome. For experiments, record the question, expectations, method, result, and implications; isolate exploratory prototypes from production architecture.
- Build and run meaningful changes, exercise actual behavior, and inspect useful logs. Investigate crashes, serious warnings, corrupted state, and interaction defects. For GUI work, use Computer Use or equivalent tools to inspect realistic workflows, cognitive load, editing/selection, navigation, feedback, recovery, loading/empty/failure states, accessibility, layout, focus/disabled states, and responsiveness.
- Match independent reviews to the artifact and risks. For languages or formats, include ambiguity, round trips, human/AI editability, and version-control behavior where relevant. Verify findings, fix the appropriate conceptual, specification, architectural, implementation, or interaction layer, and recheck affected dependents. Reuse valid evidence; repeat checks for concrete risks, changes, findings, or required gates. Compilation, screenshots, and worker reports alone do not establish correctness or usability.
- Build and run meaningful changes, exercise actual behavior, and inspect useful logs. Investigate crashes, serious warnings, corrupted state, and interaction defects. For GUI work, use Computer Use or equivalent tools to inspect realistic workflows, cognitive load, editing / selection, navigation, feedback, recovery, loading / empty / failure states, accessibility, layout, focus / disabled states, and responsiveness.
- Match independent reviews to the artifact and risks. For languages or formats, include ambiguity, round trips, human / AI editability, and version-control behavior where relevant. Verify findings, fix the appropriate conceptual, specification, architectural, implementation, or interaction layer, and recheck affected dependents. Reuse valid evidence; repeat checks for concrete risks, changes, findings, or required gates. Compilation, screenshots, and worker reports alone do not establish correctness or usability.
- Favor the simplest maintainable design satisfying known requirements and justified extensibility. Avoid speculative abstraction, unrelated refactoring, and repeating approaches already invalidated by evidence.
## User input
@@ -24,10 +24,10 @@ Keep one authoritative home for each kind of information. Use links and brief sc
| Information | Authoritative home |
| --- | --- |
| Live plans, priorities, dependencies, ownership, status, blockers, and handoffs | Gitea issues/milestones; linked PRs hold change review and validation. |
| Specifications, architecture, interfaces, and build/run documentation | Established version-controlled project documents. |
| Live plans, priorities, dependencies, ownership, status, blockers, and handoffs | Gitea issues / milestones; linked PRs hold change review and validation. |
| Specifications, architecture, interfaces, and build / run documentation | Established version-controlled project documents. |
| Durable decisions and reusable evidence | `harness/DECISIONS.md` and relevant topic notes, or existing equivalents. |
| Navigation and integrated-state checkpoint | `harness/STATE.md`: links, verified code commit/release, capabilities, and material limitations. No live task ledger. |
| Navigation and integrated-state checkpoint | `harness/STATE.md`: links, verified code commit / release, capabilities, and material limitations. No live task ledger. |
| Shared entrypoint | Gitea Wiki: overview and links, without duplicating versioned documentation. |
| Published deliverables | Gitea releases, tied to source commits and verification. |
@@ -38,9 +38,9 @@ Use Gitea for live coordination and the relevant code version for implementation
All independent agents coordinating through Gitea run on completely separate machines, each with its own clone, filesystem, tools, processes, and runtime. Gitea and pushed Git history are the shared communication and delivery channels. Local files (including `harness`), unpushed commits, worktrees, test results, and localhost services are not accessible to peers. Matching branch names or paths do not imply synchronized contents.
1. On starting or resuming, including after compaction, inspect the working branch, local changes, applicable instructions, relevant shared records, and existing implementation. Recover context from authoritative records. Check for newer shared instructions on the actual remote default branch without overwriting local work. Read what is relevant; avoid repeated full-history scans and constant polling.
2. Search before creating tasks. Claim a meaningful outcome in its Gitea issue with a stable session identity, scope, remote repository/branch, and acceptance criteria. Keep small steps within that task. Recheck after claiming; comments are not atomic locks. Respect existing ownership and resolve overlapping claims before overlapping work.
3. Independent sessions are peers. Each owns its contribution and delegated work on its own machine. Record one integration/release owner when a milestone needs shared coordination. Use distinct remote work branches, partition files/interfaces, and coordinate changes to shared specifications and documents. Worktrees provide local isolation only; they do not share work between machines.
4. At meaningful checkpoints or handoffs, record changed results, commit/PR links, verification commands and environment, blockers, and next actions. Identify the tested code version and label uncommitted or unpublished work as local-only. Before asking peers to consume results, push the required code and versioned documentation, including relevant `harness` updates; publish other required artifacts in Gitea and link them. Use repository-relative paths with commit references, reproducible commands, and necessary environment details; local paths and localhost URLs alone are not handoffs. Do not assume another agent is running or has read a message; silence alone does not establish abandonment. Record evidence and preserve existing work when reassigning a task.
2. Search before creating tasks. Claim a meaningful outcome in its Gitea issue with a stable session identity, scope, remote repository / branch, and acceptance criteria. Keep small steps within that task. Recheck after claiming; comments are not atomic locks. Respect existing ownership and resolve overlapping claims before overlapping work.
3. Independent sessions are peers. Each owns its contribution and delegated work on its own machine. Record one integration / release owner when a milestone needs shared coordination. Use distinct remote work branches, partition files / interfaces, and coordinate changes to shared specifications and documents. Worktrees provide local isolation only; they do not share work between machines.
4. At meaningful checkpoints or handoffs, record changed results, commit / PR links, verification commands and environment, blockers, and next actions. Identify the tested code version and label uncommitted or unpublished work as local-only. Before asking peers to consume results, push the required code and versioned documentation, including relevant `harness` updates; publish other required artifacts in Gitea and link them. Use repository-relative paths with commit references, reproducible commands, and necessary environment details; local paths and localhost URLs alone are not handoffs. Do not assume another agent is running or has read a message; silence alone does not establish abandonment. Record evidence and preserve existing work when reassigning a task.
5. Follow project review and merge conventions. Fetch the relevant remote branches and inspect the identified commits before reviewing or integrating another machine's work. Resolve conflicts while preserving others' edits, and verify the combined result locally; report material environment differences. Local instruction-file edits reach peers only after publication and retrieval. Do not overwrite others' work or force-push shared history to resolve coordination problems.
6. Close work when its acceptance criteria are met and the result is integrated or delivered as appropriate. Mark duplicates and superseded tasks explicitly with replacement links. Then choose further useful unowned work while the requested objective remains incomplete.
@@ -64,10 +64,10 @@ Preserve concise records of decisions and rationale, useful experiments, failed
Consolidate duplicates, repair stale guidance, and remove obsolete temporary files alongside useful project work. Before removing material, check references, active ownership, and ongoing use; preserve unique knowledge and update affected links. Prefer closing, superseding, or archiving history over deletion. User input is excluded from autonomous cleanup.
If legacy local task ledgers or plans duplicate Gitea, migrate their live content once into existing or appropriately scoped issues, preserve useful decisions/evidence, and mark the old records superseded. Record the migration so later sessions do not repeat it. Do not create empty documents or maintain records for ceremony.
If legacy local task ledgers or plans duplicate Gitea, migrate their live content once into existing or appropriately scoped issues, preserve useful decisions / evidence, and mark the old records superseded. Record the migration so later sessions do not repeat it. Do not create empty documents or maintain records for ceremony.
## Delivery
Publish versioned Gitea releases at meaningful working milestones; mark unfinished versions as prereleases. Check existing releases/tags and coordinate one owner and version before publishing. Build from an identified integrated commit and verify the packaged result and launch steps.
Publish versioned Gitea releases at meaningful working milestones; mark unfinished versions as prereleases. Check existing releases / tags and coordinate one owner and version before publishing. Build from an identified integrated commit and verify the packaged result and launch steps.
Include runnable builds or appropriate artifacts, concise release notes, build/run/deployment instructions as applicable, known limitations, tested platforms, and verification evidence. Confirm publication and artifact availability. Use existing authorized API access or project tooling when MCP lacks a needed release/upload operation. Do not silently replace published versions with different contents.
Include runnable builds or appropriate artifacts, concise release notes, build / run / deployment instructions as applicable, known limitations, tested platforms, and verification evidence. Confirm publication and artifact availability. Use existing authorized API access or project tooling when MCP lacks a needed release / upload operation. Do not silently replace published versions with different contents.
+2 -2
View File
@@ -17,14 +17,14 @@ Apply these criteria to the scope requested by the user:
- Consequential decisions have evidence and rationale. Major assumptions have been validated, explicitly accepted, or isolated without compromising required behavior.
- The result builds, runs, and operates on the required platforms. Relevant tests and evaluators pass; integrations, edge cases, and failure states have been exercised against the actual result.
- User-facing behavior and usability have been exercised directly, using representative data and workflows.
- A fresh independent review covers requirements, domain/semantic consistency, usability, architecture, correctness, regressions, runtime behavior, documentation, and remaining risks. Valid material findings are addressed, blocking and high-impact issues resolved, and affected behavior reverified; no known blocker or high-severity defect remains.
- A fresh independent review covers requirements, domain / semantic consistency, usability, architecture, correctness, regressions, runtime behavior, documentation, and remaining risks. Valid material findings are addressed, blocking and high-impact issues resolved, and affected behavior reverified; no known blocker or high-severity defect remains.
- Deliverables are maintainable, appropriately extensible, documented, and published as required by `AGENTS.md`. Obsolete scaffolding is removed; documentation and shared state accurately describe the result. Another engineer or agent can reproduce the verification and continue the work.
If required work or verification is blocked, record the specific gap and continue independent useful work without claiming completion.
## Final handoff
Link the delivered result and summarize capabilities, discoveries, architecture and decisions, relevant rejected approaches, verification and independent review, remaining limitations, and exact build/run/deployment/verification instructions. Refer to authoritative records instead of repeating the project history.
Link the delivered result and summarize capabilities, discoveries, architecture and decisions, relevant rejected approaches, verification and independent review, remaining limitations, and exact build / run / deployment / verification instructions. Refer to authoritative records instead of repeating the project history.
## USER-OWNED APPLICATION SPECIFICATION
+3 -1
View File
@@ -94,11 +94,13 @@ Create named **Exchange categories** at the perspective root to group Work excha
In **Select / move**, drag cards on a 10-unit grid, drag empty space to pan, and scroll to zoom. Drag ports along their owner's border or onto any of its four sides. Automatic sides account for direction and visible connections. Manual positions are per diagram and remain relative to the owner through movement or resize; right-click **Reset automatic position** restores automatic placement. **Arrange** changes the current view layout; **Fit** frames its projected bounds. SVG exports the current architecture diagram as a view, not an editable model file.
In saved architecture and State views, **Shift+click** adds or removes an exact displayed item; its context menu also offers **Add to selection** and **Remove from selection**. Properties edits only the primary item. Drag a selected member to move a placement-only group in one operation, including visual descendants once and the authored pins of connections whose endpoint owners move together. A stationary click selects only that member; Escape during a drag cancels it and keeps the group. **Hide selected** removes only selected placements, preserving model elements, unselected descendant placements and other views; one Undo restores the operation. Groups containing connections, ports or State action/internal-transition rows cannot be moved or hidden as placement groups. State rows select their relation, never their owning placement. Dragging a group of allocated work cards and deleting a group from the model remain unavailable; these actions refuse the whole group instead of editing just its primary item. Selection itself is temporary and is not saved.
Connections start with orthogonal routes that avoid cards and container headers. In Select mode, select a connection and drag a segment to add a bend, or right-click for **Add bend here**. Drag its circles to adjust the route; the menu offers **Remove bend** and **Reset routing**. With the canvas focused, Insert adds a bend and Delete removes the selected bend. Shift+F10 opens the selected item's menu; **Actions** in Properties provides the same commands. Drag the connection label independently. Each completed gesture is one undoable edit; Escape cancels a drag. Routes belong to the current diagram and persist in source, JSON, REST and SVG export. Folding an endpoint container temporarily uses an automatic route; expanding it restores your authored route. Dense diagrams can still need manual adjustment; automatic routing is bounded and does not guarantee an overlap-free result.
For state diagrams, use **+ Region** inside a highlighted machine or State/Mode, then choose **+ State / symbol** and click its owning region. **Transition** supports dragging between compatible vertices or clicking the source and then the target. Select a drawn transition and drag its endpoint handle, or right-click **Reconnect source/target**. Right-click a state or the background for **New transition with details…** to create Local, Internal or timed transitions; an existing transition's **Edit transition** form edits its kind, triggers, guard and effects. EntryPoint outgoing transitions use Local.
In the state view, **Select / move** drags vertices and containers without reparenting; container movement includes its descendants. Middle-button drag pans, scroll or **−/+** zooms, and **Fit** frames the view. Right-click for **Fold contents**, **Unfold contents**, **Placement properties**, or **Hide from this diagram**. The **Show an element not yet in this view…** selector restores missing placements. Escape cancels a gesture; **Undo** restores a completed edit. **+ View** creates an independent layout. The persisted diagram's machine reference and placements are the same records in source, JSON and REST; opening the page alone creates no diagram.
In the state view, **Select / move** drags vertices and containers without reparenting or grid snapping; container movement includes its descendants. Multiple selected placements share the same fractional displacement, including authored positions of boundary symbols. State route bends retain their separate 5-unit grid. Middle-button drag pans, scroll or **−/+** zooms, and **Fit** frames the view. Right-click for **Fold contents**, **Unfold contents**, **Placement properties**, or **Hide from this diagram**. The **Show an element not yet in this view…** selector restores missing placements. Escape cancels a gesture; **Undo** restores a completed edit. **+ View** creates an independent layout. The persisted diagram's machine reference and placements are the same records in source, JSON and REST; opening the page alone creates no diagram.
## Edit the same model as text
@@ -0,0 +1,717 @@
//! Native evidence fixture/checker; install as a temporary oa-core example.
//! This invariant evaluator derives delta from saved A, NOT from pointer input.
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 {
// Make the intended OA view first for default UUID-ordered view selection.
if alias == "oa_view" {
return Id::from_u128(0x29_0001);
}
Id::new_v5(
&Id::from_u128(0xc1192026_0923_5000_8000_000000000029),
alias.as_bytes(),
)
}
fn point(x: f32, y: f32) -> Position {
Position { x, y }
}
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 diagram(p: &mut Project, alias: &str, name: &str, layer: Layer) {
p.diagrams.insert(
id(alias),
Diagram {
id: id(alias),
alias: alias.into(),
name: name.into(),
description: "Selection changes placement geometry only.".into(),
layer,
projection: ProjectionKind::Overview,
view_options: Default::default(),
layout: None,
nodes: Default::default(),
routes: vec![],
},
);
}
fn place(p: &mut Project, view: &str, alias: &str, object: &str, position: Position, size: Size) {
p.diagrams.get_mut(&id(view)).unwrap().nodes.insert(
id(alias),
NodePlacement {
id: id(alias),
alias: alias.into(),
element: id(object),
position,
size,
collapsed: false,
port_anchors: vec![],
},
);
}
fn route(edge: &str, pins: Vec<Position>) -> EdgeRoute {
EdgeRoute {
edge: id(edge),
waypoints: pins,
source_attachment: Some(EdgeAttachment {
side: PortAnchorSide::Right,
offset: 0.25,
}),
target_attachment: Some(EdgeAttachment {
side: PortAnchorSide::Left,
offset: 0.7,
}),
label: Some(EdgeLabel {
fraction: 0.45,
offset: point(7., -19.),
}),
}
}
fn fixture() -> Result<Project> {
let mut p = Project::empty();
p.id = id("project");
p.alias = "multiselect_native".into();
p.name = "Multiselect native".into();
p.description =
"Shift-select A and B; move together, retain C and engineering semantics.".into();
for (alias, name, parent) in [
("activity_a", "A - receive request", None),
("activity_b", "B - assess request", None),
("activity_c", "C - dispatch response", None),
(
"activity_child",
"A.1 - classify request",
Some(id("activity_a")),
),
] {
element(&mut p, alias, name, Kind::Activity, Layer::Oa, parent);
}
element(
&mut p,
"sa_function",
"Technical request processing",
Kind::Function,
Layer::Sa,
None,
);
for (alias, name, source, target) in [
("internal", "Request assessment", "activity_a", "activity_b"),
("external", "Response decision", "activity_b", "activity_c"),
] {
let old = p.relate(RelationKind::Interaction, name, id(source), id(target));
reidentify(&mut p, old, id(alias))?;
p.relations.get_mut(&id(alias)).unwrap().alias = alias.into();
}
diagram(
&mut p,
"oa_view",
"Multiselect native - OA overview",
Layer::Oa,
);
diagram(&mut p, "oa_other", "Other OA view - preserve", Layer::Oa);
diagram(&mut p, "sa_view", "SA engineering - preserve", Layer::Sa);
let size = Size {
width: 224.,
height: 94.,
};
place(
&mut p,
"oa_view",
"node_a",
"activity_a",
point(80., 80.),
Size {
width: 310.,
height: 260.,
},
);
place(
&mut p,
"oa_view",
"node_b",
"activity_b",
point(470., 120.),
size,
);
place(
&mut p,
"oa_view",
"node_c",
"activity_c",
point(780., 270.),
size,
);
place(
&mut p,
"oa_view",
"node_child",
"activity_child",
point(120., 210.),
size,
);
place(
&mut p,
"oa_other",
"other_a",
"activity_a",
point(40., 60.),
size,
);
place(
&mut p,
"sa_view",
"sa_node",
"sa_function",
point(100., 110.),
size,
);
p.diagrams.get_mut(&id("oa_view")).unwrap().routes = vec![
route("internal", vec![point(420., 145.), point(420., 186.)]),
route("external", vec![point(725., 150.), point(725., 336.)]),
];
p.traces.insert(
id("trace"),
Trace {
id: id("trace"),
alias: "preserved_refinement".into(),
name: "Reviewed request refinement".into(),
description: "Group geometry and Hide preserve this trace and both endpoints.".into(),
oa: id("activity_a"),
sa: id("sa_function"),
kind: TraceKind::Refinement,
baseline: Some(TraceBaseline {
oa: p.properties(id("activity_a")).unwrap(),
sa: p.properties(id("sa_function")).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())?;
// This deliberately partial engineering fixture has completeness
// warnings (allocation/behavior context). They are not source errors.
// Compilation, candidate validation and whole-Project equality still
// reject malformed source or any unexpected model change.
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 e = serde_json::to_value(expected)?;
let a = serde_json::to_value(actual)?;
let fields: Vec<_> = e
.as_object()
.unwrap()
.keys()
.filter(|key| e[*key] != a[*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 names = [
"project",
"oa_view",
"oa_other",
"sa_view",
"activity_a",
"activity_b",
"activity_c",
"activity_child",
"node_a",
"node_b",
"node_c",
"node_child",
"internal",
"external",
"trace",
"sa_function",
"sa_node",
"other_a",
];
let ids: std::collections::BTreeMap<_, _> =
names.into_iter().map(|name| (name, id(name))).collect();
write_new(
&out.join("manifest.json"),
&serde_json::to_vec_pretty(&serde_json::json!({
"fixture": "multiselect-native-20260923", "ids": ids, "source_entry": bundle.entry,
"move_members": ["node_a", "node_b", "node_child"], "fixed_member": "node_c",
"evaluation": "Whole Project invariant comparison; saved A supplies bounded shared delta, not an exact pointer oracle",
"hide": "Remove node_a/node_b only; retain child, stored routes, all model records and other views",
}))?,
)?;
equal(&p, &load(&out.join("baseline.json"))?)?;
equal(&p, &load(&out.join("source/project.arcadia"))?)?;
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)?;
if before.id != id("project") {
return Err("Not this fixture's baseline project".into());
}
let mut expected = before.clone();
let mut delta = None;
match mode {
"unchanged" => {}
"hide" => {
let view = expected
.diagrams
.get_mut(&id("oa_view"))
.ok_or("Missing OA view")?;
for alias in ["node_a", "node_b"] {
view.nodes
.remove(&id(alias))
.ok_or("Baseline selected placement missing")?;
}
// references::remove_objects removes routes only when their semantic
// edge is deleted. Hide deletes placements; both routes MUST survive.
}
"moved" => {
let old = before
.diagrams
.get(&id("oa_view"))
.ok_or("Missing baseline OA view")?;
let new = actual
.diagrams
.get(&id("oa_view"))
.ok_or("Missing saved OA view")?;
let a = old
.nodes
.get(&id("node_a"))
.ok_or("Missing baseline A")?
.position;
let moved_a = new
.nodes
.get(&id("node_a"))
.ok_or("Missing saved A")?
.position;
let d = point(moved_a.x - a.x, moved_a.y - a.y);
if !d.x.is_finite()
|| !d.y.is_finite()
|| d.x.abs().max(d.y.abs()) > 500.
|| d.x.hypot(d.y) < 10.
{
return Err(format!(
"Move delta must have length >=10 and each axis <=500 world units: {d:?}"
)
.into());
}
if moved_a.x % 10. != 0. || moved_a.y % 10. != 0. {
return Err("Saved anchor is not on 10-unit grid".into());
}
let view = expected.diagrams.get_mut(&id("oa_view")).unwrap();
// Independent explicit fixture enumeration: no group/descendant/
// routing planner is called to predict the result.
for alias in ["node_a", "node_b", "node_child"] {
let node = view
.nodes
.get_mut(&id(alias))
.ok_or("Missing expected moved placement")?;
node.position.x += d.x;
node.position.y += d.y;
}
let internal = view
.routes
.iter_mut()
.find(|route| route.edge == id("internal"))
.ok_or("Missing internal pins")?;
for pin in &mut internal.waypoints {
pin.x += d.x;
pin.y += d.y;
}
delta = Some(d);
}
_ => return Err("Mode must be moved, hide, 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", "inferred_common_delta": delta,
"limits": "Invariant evaluator only; 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: multiselect-native-producer generate DIRECTORY | check moved|hide|unchanged BASELINE SAVED".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
// Produce evidence through real validated commands; the checker itself uses
// explicit fixture enumeration and never calls this movement implementation.
fn moved(before: &Project, delta: Position) -> Project {
let command = diagram_edit::translate_placements(
before,
id("oa_view"),
&BTreeSet::from([id("node_a"), id("node_b")]),
delta,
)
.unwrap();
let mut session = Session::new(before.clone());
session.execute(command).unwrap();
session.project().clone()
}
fn hidden(before: &Project) -> Project {
let mut session = Session::new(before.clone());
session
.execute(Command::Batch(vec![
Command::Delete(id("node_a")),
Command::Delete(id("node_b")),
]))
.unwrap();
session.project().clone()
}
fn through_saved_json(mode: &str, baseline: &Project, actual: &Project) -> Result<()> {
let dir = tempfile::tempdir()?;
let before = dir.path().join("before.json");
let saved = dir.path().join("saved.json");
// These assertions distinguish meaningful invariant corruptions from
// malformed projects rejected before the evaluator even sees them.
validate_candidate(baseline).expect("test baseline must be valid");
validate_candidate(actual).expect("corruption must remain a valid model");
persistence::save(&before, baseline)?;
persistence::save(&saved, actual)?;
check(mode, &before, &saved)
}
fn mismatch(mode: &str, before: &Project, actual: &Project, case: &str) {
let error = through_saved_json(mode, before, actual)
.expect_err(case)
.to_string();
assert!(
error.contains("Whole Project mismatch"),
"{case}: unexpected rejection: {error}"
);
}
fn edge<'a>(p: &'a mut Project, alias: &str) -> &'a mut EdgeRoute {
p.diagrams
.get_mut(&id("oa_view"))
.unwrap()
.routes
.iter_mut()
.find(|route| route.edge == id(alias))
.unwrap()
}
#[test]
fn generated_json_and_real_source_bundle_are_accepted_unchanged() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("fixture");
generate(&out).unwrap();
let baseline = out.join("baseline.json");
let saved = out.join("saved.json");
persistence::save(&saved, &fixture().unwrap()).unwrap();
check("unchanged", &baseline, &saved).unwrap();
check("unchanged", &baseline, &out.join("source/project.arcadia")).unwrap();
let bytes = fs::read(&baseline).unwrap();
assert!(
generate(&out).is_err(),
"generation cannot overwrite evidence"
);
assert_eq!(fs::read(&baseline).unwrap(), bytes);
let invalid = dir.path().join("invalid.arcadia");
fs::write(&invalid, "project {").unwrap();
assert!(load(&invalid).is_err(), "source errors must still reject");
}
#[test]
fn real_group_command_outputs_pass_and_are_not_unchanged() {
let before = fixture().unwrap();
for delta in [point(40., 60.), point(-20., 30.)] {
let actual = moved(&before, delta);
through_saved_json("moved", &before, &actual).unwrap();
mismatch(
"unchanged",
&before,
&actual,
"real movement cannot count as unchanged",
);
}
}
#[test]
fn real_hide_command_outputs_pass_before_and_after_movement() {
let initial = fixture().unwrap();
for before in [initial.clone(), moved(&initial, point(40., 60.))] {
let actual = hidden(&before);
through_saved_json("hide", &before, &actual).unwrap();
mismatch(
"unchanged",
&before,
&actual,
"real Hide cannot count as unchanged",
);
}
}
#[test]
fn omitted_and_double_moved_child_are_rejected() {
let before = fixture().unwrap();
let delta = point(40., 60.);
let correct = moved(&before, delta);
let initial = before.diagrams[&id("oa_view")].nodes[&id("node_child")].position;
for position in [
initial,
point(initial.x + 2. * delta.x, initial.y + 2. * delta.y),
] {
let mut bad = correct.clone();
bad.diagrams
.get_mut(&id("oa_view"))
.unwrap()
.nodes
.get_mut(&id("node_child"))
.unwrap()
.position = position;
mismatch("moved", &before, &bad, "child did not move exactly once");
}
}
#[test]
fn internal_pins_left_behind_and_external_pins_moved_are_rejected() {
let mut before = fixture().unwrap();
let original_pins = edge(&mut before, "internal").waypoints.clone();
let correct = moved(&before, point(40., 60.));
let mut bad = correct.clone();
edge(&mut bad, "internal").waypoints = original_pins;
mismatch("moved", &before, &bad, "internal pins left behind");
let mut bad = correct;
for pin in &mut edge(&mut bad, "external").waypoints {
pin.x += 40.;
pin.y += 60.;
}
mismatch("moved", &before, &bad, "one-ended pins moved");
}
#[test]
fn manual_attachments_and_label_data_must_remain_exact() {
let before = fixture().unwrap();
let correct = moved(&before, point(40., 60.));
let mutations: [fn(&mut EdgeRoute); 4] = [
|r| r.source_attachment.as_mut().unwrap().offset = 0.65,
|r| r.target_attachment.as_mut().unwrap().side = PortAnchorSide::Top,
|r| r.label.as_mut().unwrap().offset.x += 40.,
|r| r.label.as_mut().unwrap().fraction = 0.75,
];
for mutate in mutations {
let mut bad = correct.clone();
mutate(edge(&mut bad, "internal"));
mismatch("moved", &before, &bad, "relative route metadata changed");
}
}
#[test]
fn semantic_other_view_fixed_node_and_trace_drift_are_rejected() {
let before = fixture().unwrap();
let correct = moved(&before, point(40., 60.));
let mutations: [fn(&mut Project); 5] = [
|p| {
p.elements
.get_mut(&id("activity_a"))
.unwrap()
.description
.push_str(" drift")
},
|p| {
p.diagrams
.get_mut(&id("oa_other"))
.unwrap()
.nodes
.get_mut(&id("other_a"))
.unwrap()
.position
.x += 40.
},
|p| {
p.diagrams
.get_mut(&id("sa_view"))
.unwrap()
.nodes
.get_mut(&id("sa_node"))
.unwrap()
.position
.y += 60.
},
|p| {
p.diagrams
.get_mut(&id("oa_view"))
.unwrap()
.nodes
.get_mut(&id("node_c"))
.unwrap()
.position
.x += 40.
},
|p| {
p.traces
.get_mut(&id("trace"))
.unwrap()
.description
.push_str(" drift")
},
];
for mutate in mutations {
let mut bad = correct.clone();
mutate(&mut bad);
mismatch(
"moved",
&before,
&bad,
"record outside permitted movement changed",
);
}
}
#[test]
fn zero_small_excessive_and_offgrid_moves_cannot_satisfy_move_evidence() {
let before = fixture().unwrap();
for (delta, reason) in [
(point(0., 0.), "length >=10"),
(point(3., 0.), "length >=10"),
(point(510., 0.), "each axis <=500"),
(point(20.5, 0.), "10-unit grid"),
] {
let actual = moved(&before, delta);
let error = through_saved_json("moved", &before, &actual)
.unwrap_err()
.to_string();
assert!(error.contains(reason), "{delta:?}: {error}");
}
}
#[test]
fn hide_must_preserve_child_routes_and_semantic_objects() {
let before = fixture().unwrap();
let correct = hidden(&before);
let mut missing_child = correct.clone();
missing_child
.diagrams
.get_mut(&id("oa_view"))
.unwrap()
.nodes
.remove(&id("node_child"));
mismatch(
"hide",
&before,
&missing_child,
"Hide removed unselected child placement",
);
let mut missing_routes = correct;
missing_routes
.diagrams
.get_mut(&id("oa_view"))
.unwrap()
.routes
.clear();
mismatch(
"hide",
&before,
&missing_routes,
"Hide removed persistent route records",
);
let mut semantic_delete = Session::new(before.clone());
semantic_delete
.execute(Command::Batch(vec![
Command::Delete(id("activity_a")),
Command::Delete(id("activity_b")),
]))
.unwrap();
mismatch(
"hide",
&before,
semantic_delete.project(),
"Hide became semantic deletion",
);
}
#[test]
fn unchanged_rejects_valid_semantic_drift_without_geometry_changes() {
let before = fixture().unwrap();
let mut actual = before.clone();
actual
.elements
.get_mut(&id("activity_b"))
.unwrap()
.name
.push_str(" edited");
mismatch(
"unchanged",
&before,
&actual,
"geometry equality is not complete Project equality",
);
}
}
@@ -0,0 +1,912 @@
//! Deterministic persisted-State native fixture and complete-Project checker.
//! This invariant evaluator derives delta from saved A, NOT from pointer input.
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 {
// Dedicated State view is the smallest diagram UUID, for native opening.
if alias == "state_view" {
return Id::from_u128(0x29_0101);
}
Id::new_v5(
&Id::from_u128(0xc1192026_0923_5000_8000_000000002929),
alias.as_bytes(),
)
}
fn point(x: f32, y: f32) -> Position {
Position { x, y }
}
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 diagram(p: &mut Project, alias: &str, name: &str, layer: Layer) {
p.diagrams.insert(
id(alias),
Diagram {
id: id(alias),
alias: alias.into(),
name: name.into(),
description: "Selection changes placement geometry only.".into(),
layer,
projection: ProjectionKind::Overview,
view_options: Default::default(),
layout: None,
nodes: Default::default(),
routes: vec![],
},
);
}
fn place(p: &mut Project, view: &str, alias: &str, object: &str, position: Position, size: Size) {
p.diagrams.get_mut(&id(view)).unwrap().nodes.insert(
id(alias),
NodePlacement {
id: id(alias),
alias: alias.into(),
element: id(object),
position,
size,
collapsed: false,
port_anchors: vec![],
},
);
}
fn route(edge: &str, pins: Vec<Position>) -> EdgeRoute {
EdgeRoute {
edge: id(edge),
waypoints: pins,
source_attachment: Some(EdgeAttachment {
side: PortAnchorSide::Right,
offset: 0.25,
}),
target_attachment: Some(EdgeAttachment {
side: PortAnchorSide::Left,
offset: 0.7,
}),
label: Some(EdgeLabel {
fraction: 0.45,
offset: point(7., -19.),
}),
}
}
fn transition(
p: &mut Project,
alias: &str,
name: &str,
source: &str,
target: &str,
kind: TransitionKind,
) -> Result<()> {
let old = p.relate(RelationKind::StateTransition, 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 transition {alias}.");
if let RelationBody::StateTransition {
transition_kind,
guard,
..
} = &mut relation.body
{
*transition_kind = kind;
*guard = if alias == "between" {
"request_ready"
} else {
""
}
.into();
}
Ok(())
}
fn fixture() -> Result<Project> {
let mut p = Project::empty();
p.id = id("project");
p.alias = "state_multiselect_native".into();
p.name = "State group native".into();
p.description = "Shift-select A and B; move their placements together. C and shared engineering records stay fixed.".into();
for (alias, name, kind, parent) in [
("crew", "Operations crew", Kind::Entity, None),
(
"machine",
"Request lifecycle",
Kind::StateMachine,
Some(id("crew")),
),
("region", "Main region", Kind::Region, Some(id("machine"))),
("state_a", "A - Processing", Kind::State, Some(id("region"))),
("state_b", "B - Ready", Kind::State, Some(id("region"))),
("state_c", "C - Complete", Kind::State, Some(id("region"))),
(
"inner",
"A nested region",
Kind::Region,
Some(id("state_a")),
),
(
"state_leaf",
"A.1 - Classify",
Kind::State,
Some(id("inner")),
),
("entry", "Enter A", Kind::EntryPoint, Some(id("inner"))),
("exit", "Leave A", Kind::ExitPoint, Some(id("inner"))),
("shared_work", "Record request", Kind::Activity, None),
] {
element(&mut p, alias, name, kind, Layer::Oa, parent);
}
element(
&mut p,
"sa_function",
"Technical record request",
Kind::Function,
Layer::Sa,
None,
);
for (alias, name, source, target, kind) in [
(
"between",
"Ready\nfor review",
"state_a",
"state_b",
TransitionKind::External,
),
(
"external",
"Complete request",
"state_b",
"state_c",
TransitionKind::External,
),
(
"entry_route",
"Begin classification",
"entry",
"state_leaf",
TransitionKind::Local,
),
(
"exit_route",
"Classification complete",
"state_leaf",
"exit",
TransitionKind::External,
),
(
"refresh",
"Refresh record",
"state_a",
"state_a",
TransitionKind::Internal,
),
] {
transition(&mut p, alias, name, source, target, kind)?;
}
for (alias, source, phase) in [
("action_a", "state_a", StateActionKind::Entry),
("action_c", "state_c", StateActionKind::Do),
] {
let old = p.relate(
RelationKind::StateAction,
"Record shared work",
id(source),
id("shared_work"),
);
reidentify(&mut p, old, id(alias))?;
let relation = p.relations.get_mut(&id(alias)).unwrap();
relation.alias = alias.into();
relation.description = format!("Preserve shared-work action {alias}.");
if let RelationBody::StateAction { phase: value, .. } = &mut relation.body {
*value = phase;
}
}
for (alias, name) in [
("state_view", "State multiselect - main"),
("state_other", "Other State view - preserve"),
] {
diagram(&mut p, alias, name, Layer::Oa);
p.diagrams.get_mut(&id(alias)).unwrap().projection = ProjectionKind::StateMachine {
machine: id("machine"),
};
}
diagram(&mut p, "sa_view", "SA engineering - preserve", Layer::Sa);
// The main machine and outer Region are deliberately unplaced to keep
// the target headers readable in a 1442 x 932 native window after Fit.
// A starts at the authored origin so saved A recovers the exact f32 delta;
// subtracting a nonzero original can round it differently from sibling XY.
for (alias, object, x, y, width, height) in [
("node_a", "state_a", 0., 0., 340., 450.),
("node_b", "state_b", 410., 30., 210., 150.),
("node_c", "state_c", 410., 330., 210., 140.),
("node_inner", "inner", 25., 220., 290., 200.),
("node_leaf", "state_leaf", 60., 290., 180., 90.),
("node_entry", "entry", -210., 280., 24., 24.),
("node_exit", "exit", 870., 350., 24., 24.),
] {
place(
&mut p,
"state_view",
alias,
object,
point(x, y),
Size { width, height },
);
}
let size = Size {
width: 224.,
height: 94.,
};
place(
&mut p,
"state_other",
"other_a",
"state_a",
point(40., 60.),
Size {
width: 340.,
height: 220.,
},
);
place(
&mut p,
"state_other",
"other_b",
"state_b",
point(460., 80.),
size,
);
place(
&mut p,
"sa_view",
"sa_node",
"sa_function",
point(100., 110.),
size,
);
p.diagrams.get_mut(&id("state_view")).unwrap().routes = vec![
route("between", vec![point(365., 70.), point(365., 120.)]),
route("external", vec![point(660., 140.), point(660., 360.)]),
route("entry_route", vec![point(40., 280.), point(40., 320.)]),
route("exit_route", vec![point(290., 335.), point(290., 370.)]),
];
p.traces.insert(
id("trace"),
Trace {
id: id("trace"),
alias: "preserved_refinement".into(),
name: "Reviewed recording refinement".into(),
description:
"Moving states or hiding placements must preserve shared work and its refinement."
.into(),
oa: id("shared_work"),
sa: id("sa_function"),
kind: TraceKind::Refinement,
baseline: Some(TraceBaseline {
oa: p.properties(id("shared_work")).unwrap(),
sa: p.properties(id("sa_function")).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())?;
// This deliberately partial engineering fixture has completeness
// warnings (allocation/behavior context). They are not source errors.
// Compilation, candidate validation and whole-Project equality still
// reject malformed source or any unexpected model change.
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 e = serde_json::to_value(expected)?;
let a = serde_json::to_value(actual)?;
let fields: Vec<_> = e
.as_object()
.unwrap()
.keys()
.filter(|key| e[*key] != a[*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 names = [
"crew",
"machine",
"region",
"inner",
"entry",
"exit",
"shared_work",
"node_inner",
"node_entry",
"node_exit",
"entry_route",
"exit_route",
"refresh",
"action_a",
"action_c",
"other_b",
"project",
"state_view",
"state_other",
"sa_view",
"state_a",
"state_b",
"state_c",
"state_leaf",
"node_a",
"node_b",
"node_c",
"node_leaf",
"between",
"external",
"trace",
"sa_function",
"sa_node",
"other_a",
];
let ids: std::collections::BTreeMap<_, _> =
names.into_iter().map(|name| (name, id(name))).collect();
write_new(
&out.join("manifest.json"),
&serde_json::to_vec_pretty(&serde_json::json!({
"fixture": "state-multiselect-native-20260923", "ids": ids, "source_entry": bundle.entry,
"move_members": ["node_a", "node_b", "node_inner", "node_leaf", "node_entry", "node_exit"],
"translated_routes": ["between", "entry_route", "exit_route"],
"fixed_route": "external",
"window": [1442, 932],
"target_headers_world": {"A": [40, 35], "B": [450, 65]},
"delta_limits": "finite, nonzero length >=0.01, each axis <=300; no grid quantization",
"receipt": "Pin baseline.json, manifest.json and generation command externally before interaction; baseline identity alone does not authenticate evidence", "fixed_member": "node_c",
"evaluation": "Whole Project invariant comparison; saved A supplies bounded shared delta, not an exact pointer oracle",
"hide": "Remove node_a/node_b only; retain nested Region/leaf/entry/exit, stored routes, all model records and other views",
}))?,
)?;
equal(&p, &load(&out.join("baseline.json"))?)?;
equal(&p, &load(&out.join("source/project.arcadia"))?)?;
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)?;
if before.id != id("project") {
return Err("Not this fixture's baseline project".into());
}
let mut expected = before.clone();
let mut delta = None;
match mode {
"unchanged" => {}
"hide" => {
let view = expected
.diagrams
.get_mut(&id("state_view"))
.ok_or("Missing State view")?;
for alias in ["node_a", "node_b"] {
view.nodes
.remove(&id(alias))
.ok_or("Baseline selected placement missing")?;
}
// references::remove_objects removes routes only when their semantic
// edge is deleted. Hide deletes placements; both routes MUST survive.
}
"moved" => {
let old = before
.diagrams
.get(&id("state_view"))
.ok_or("Missing baseline State view")?;
let new = actual
.diagrams
.get(&id("state_view"))
.ok_or("Missing saved State view")?;
let a = old
.nodes
.get(&id("node_a"))
.ok_or("Missing baseline A")?
.position;
let moved_a = new
.nodes
.get(&id("node_a"))
.ok_or("Missing saved A")?
.position;
let d = point(moved_a.x - a.x, moved_a.y - a.y);
if !d.x.is_finite()
|| !d.y.is_finite()
|| d.x.abs().max(d.y.abs()) > 300.
|| d.x.hypot(d.y) < 0.01
{
return Err(format!(
"Move delta must have length >=0.01 and each axis <=300 world units: {d:?}"
)
.into());
}
let view = expected.diagrams.get_mut(&id("state_view")).unwrap();
// Independent explicit fixture enumeration: no group/descendant/
// routing planner is called to predict the result.
for alias in [
"node_a",
"node_b",
"node_inner",
"node_leaf",
"node_entry",
"node_exit",
] {
let node = view
.nodes
.get_mut(&id(alias))
.ok_or("Missing expected moved placement")?;
node.position.x += d.x;
node.position.y += d.y;
}
for alias in ["between", "entry_route", "exit_route"] {
let route = view
.routes
.iter_mut()
.find(|route| route.edge == id(alias))
.ok_or("Missing explicitly expected moved route")?;
for pin in &mut route.waypoints {
pin.x += d.x;
pin.y += d.y;
}
}
delta = Some(d);
}
_ => return Err("Mode must be moved, hide, 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", "inferred_common_delta": delta,
"limits": "Invariant evaluator only; 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: state_multiselect_native generate DIRECTORY | check moved|hide|unchanged BASELINE SAVED".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
// Produce evidence through real validated commands; the checker itself uses
// explicit fixture enumeration and never calls this movement implementation.
fn moved(before: &Project, delta: Position) -> Project {
let command = diagram_edit::translate_placements(
before,
id("state_view"),
&BTreeSet::from([id("node_a"), id("node_b")]),
delta,
)
.unwrap();
let mut session = Session::new(before.clone());
session.execute(command).unwrap();
session.project().clone()
}
fn hidden(before: &Project) -> Project {
let mut session = Session::new(before.clone());
session
.execute(Command::Batch(vec![
Command::Delete(id("node_a")),
Command::Delete(id("node_b")),
]))
.unwrap();
session.project().clone()
}
fn through_saved_json(mode: &str, baseline: &Project, actual: &Project) -> Result<()> {
let dir = tempfile::tempdir()?;
let before = dir.path().join("before.json");
let saved = dir.path().join("saved.json");
// These assertions distinguish meaningful invariant corruptions from
// malformed projects rejected before the evaluator even sees them.
validate_candidate(baseline).expect("test baseline must be valid");
validate_candidate(actual).expect("corruption must remain a valid model");
persistence::save(&before, baseline)?;
persistence::save(&saved, actual)?;
check(mode, &before, &saved)
}
fn mismatch(mode: &str, before: &Project, actual: &Project, case: &str) {
let error = through_saved_json(mode, before, actual)
.expect_err(case)
.to_string();
assert!(
error.contains("Whole Project mismatch"),
"{case}: unexpected rejection: {error}"
);
}
fn edge<'a>(p: &'a mut Project, alias: &str) -> &'a mut EdgeRoute {
p.diagrams
.get_mut(&id("state_view"))
.unwrap()
.routes
.iter_mut()
.find(|route| route.edge == id(alias))
.unwrap()
}
#[test]
fn generated_json_and_real_source_bundle_are_accepted_unchanged() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("fixture");
generate(&out).unwrap();
let baseline = out.join("baseline.json");
let saved = out.join("saved.json");
persistence::save(&saved, &fixture().unwrap()).unwrap();
check("unchanged", &baseline, &saved).unwrap();
check("unchanged", &baseline, &out.join("source/project.arcadia")).unwrap();
let bytes = fs::read(&baseline).unwrap();
assert!(
generate(&out).is_err(),
"generation cannot overwrite evidence"
);
assert_eq!(fs::read(&baseline).unwrap(), bytes);
let invalid = dir.path().join("invalid.arcadia");
fs::write(&invalid, "project {").unwrap();
assert!(load(&invalid).is_err(), "source errors must still reject");
}
#[test]
fn real_group_command_outputs_pass_and_are_not_unchanged() {
let before = fixture().unwrap();
for delta in [
point(7.25, -2.75),
point(-20.5, 30.125),
point(0.25, 0.),
point(0.01, 10.),
point(0.1, -0.2),
] {
let actual = moved(&before, delta);
through_saved_json("moved", &before, &actual).unwrap();
mismatch(
"unchanged",
&before,
&actual,
"real movement cannot count as unchanged",
);
}
}
#[test]
fn real_hide_command_outputs_pass_before_and_after_movement() {
let initial = fixture().unwrap();
for before in [initial.clone(), moved(&initial, point(40., 60.))] {
let actual = hidden(&before);
through_saved_json("hide", &before, &actual).unwrap();
mismatch(
"unchanged",
&before,
&actual,
"real Hide cannot count as unchanged",
);
}
}
#[test]
fn omitted_and_double_moved_child_are_rejected() {
let before = fixture().unwrap();
let delta = point(40., 60.);
let correct = moved(&before, delta);
for alias in ["node_inner", "node_leaf", "node_entry", "node_exit"] {
let initial = before.diagrams[&id("state_view")].nodes[&id(alias)].position;
for position in [
initial,
point(initial.x + 2. * delta.x, initial.y + 2. * delta.y),
] {
let mut bad = correct.clone();
bad.diagrams
.get_mut(&id("state_view"))
.unwrap()
.nodes
.get_mut(&id(alias))
.unwrap()
.position = position;
mismatch("moved", &before, &bad, "child did not move exactly once");
}
}
}
#[test]
fn internal_pins_left_behind_and_external_pins_moved_are_rejected() {
let mut before = fixture().unwrap();
let correct = moved(&before, point(40., 60.));
for alias in ["between", "entry_route", "exit_route"] {
let original_pins = edge(&mut before, alias).waypoints.clone();
let mut bad = correct.clone();
edge(&mut bad, alias).waypoints = original_pins;
mismatch("moved", &before, &bad, "internal pins left behind");
}
let mut bad = correct;
for pin in &mut edge(&mut bad, "external").waypoints {
pin.x += 40.;
pin.y += 60.;
}
mismatch("moved", &before, &bad, "one-ended pins moved");
}
#[test]
fn manual_attachments_and_label_data_must_remain_exact() {
let before = fixture().unwrap();
let correct = moved(&before, point(40., 60.));
let mutations: [fn(&mut EdgeRoute); 4] = [
|r| r.source_attachment.as_mut().unwrap().offset = 0.65,
|r| r.target_attachment.as_mut().unwrap().side = PortAnchorSide::Top,
|r| r.label.as_mut().unwrap().offset.x += 40.,
|r| r.label.as_mut().unwrap().fraction = 0.75,
];
for mutate in mutations {
let mut bad = correct.clone();
mutate(edge(&mut bad, "between"));
mismatch("moved", &before, &bad, "relative route metadata changed");
}
}
#[test]
fn semantic_other_view_fixed_node_and_trace_drift_are_rejected() {
let before = fixture().unwrap();
let correct = moved(&before, point(40., 60.));
let mutations: [fn(&mut Project); 9] = [
|p| p.traces.get_mut(&id("trace")).unwrap().baseline = None,
|p| {
p.elements
.get_mut(&id("shared_work"))
.unwrap()
.description
.push_str(" drift")
},
|p| {
if let RelationBody::StateAction { phase, .. } =
&mut p.relations.get_mut(&id("action_a")).unwrap().body
{
*phase = StateActionKind::Exit;
}
},
|p| {
if let RelationBody::StateTransition { guard, .. } =
&mut p.relations.get_mut(&id("refresh")).unwrap().body
{
*guard = "changed_refresh_guard".into();
}
},
|p| {
p.elements
.get_mut(&id("state_a"))
.unwrap()
.description
.push_str(" drift")
},
|p| {
p.diagrams
.get_mut(&id("state_other"))
.unwrap()
.nodes
.get_mut(&id("other_a"))
.unwrap()
.position
.x += 40.
},
|p| {
p.diagrams
.get_mut(&id("sa_view"))
.unwrap()
.nodes
.get_mut(&id("sa_node"))
.unwrap()
.position
.y += 60.
},
|p| {
p.diagrams
.get_mut(&id("state_view"))
.unwrap()
.nodes
.get_mut(&id("node_c"))
.unwrap()
.position
.x += 40.
},
|p| {
p.traces
.get_mut(&id("trace"))
.unwrap()
.description
.push_str(" drift")
},
];
for mutate in mutations {
let mut bad = correct.clone();
mutate(&mut bad);
mismatch(
"moved",
&before,
&bad,
"record outside permitted movement changed",
);
}
}
#[test]
fn zero_and_excessive_moves_cannot_satisfy_move_evidence() {
let before = fixture().unwrap();
for (delta, reason) in [
(point(0., 0.), "length >=0.01"),
(point(310., 0.), "each axis <=300"),
] {
let actual = moved(&before, delta);
let error = through_saved_json("moved", &before, &actual)
.unwrap_err()
.to_string();
assert!(error.contains(reason), "{delta:?}: {error}");
}
}
#[test]
fn hide_must_preserve_child_routes_and_semantic_objects() {
let before = fixture().unwrap();
let correct = hidden(&before);
let mut missing_child = correct.clone();
missing_child
.diagrams
.get_mut(&id("state_view"))
.unwrap()
.nodes
.remove(&id("node_leaf"));
mismatch(
"hide",
&before,
&missing_child,
"Hide removed unselected child placement",
);
let mut missing_routes = correct;
missing_routes
.diagrams
.get_mut(&id("state_view"))
.unwrap()
.routes
.clear();
mismatch(
"hide",
&before,
&missing_routes,
"Hide removed persistent route records",
);
let mut semantic_delete = Session::new(before.clone());
semantic_delete
.execute(Command::Batch(vec![
Command::Delete(id("state_a")),
Command::Delete(id("state_b")),
]))
.unwrap();
mismatch(
"hide",
&before,
semantic_delete.project(),
"Hide became semantic deletion",
);
}
#[test]
fn unchanged_rejects_valid_semantic_drift_without_geometry_changes() {
let before = fixture().unwrap();
let mut actual = before.clone();
actual
.elements
.get_mut(&id("state_b"))
.unwrap()
.name
.push_str(" edited");
mismatch(
"unchanged",
&before,
&actual,
"geometry equality is not complete Project equality",
);
}
#[test]
fn moved_and_hidden_source_inputs_are_checked_against_complete_expected_projects() {
let before = fixture().unwrap();
for (mode, actual) in [
("moved", moved(&before, point(7.25, -2.75))),
("hide", hidden(&before)),
] {
let dir = tempfile::tempdir().unwrap();
let baseline = dir.path().join("baseline.json");
persistence::save(&baseline, &before).unwrap();
let bundle = roundtrip(&actual).unwrap();
for (path, source) in &bundle.files {
write_new(&dir.path().join("saved").join(path), source.as_bytes()).unwrap();
}
check(
mode,
&baseline,
&dir.path().join("saved").join(&bundle.entry),
)
.unwrap();
let mut corrupt = actual.clone();
corrupt.elements.get_mut(&id("shared_work")).unwrap().name =
"Unrequested source edit".into();
let bundle = roundtrip(&corrupt).unwrap();
for (path, source) in &bundle.files {
write_new(&dir.path().join("corrupt").join(path), source.as_bytes()).unwrap();
}
let error = check(
mode,
&baseline,
&dir.path().join("corrupt").join(&bundle.entry),
)
.unwrap_err()
.to_string();
assert!(error.contains("Whole Project mismatch"), "{error}");
}
}
}
+91
View File
@@ -0,0 +1,91 @@
//! Pure diagram edits shared by movement previews and committed transactions.
use crate::{Command, Id, MAX_COORDINATE, ModelError, Position, Project, projection};
use std::collections::{BTreeMap, BTreeSet};
/// Translate selected placements and their projected descendants simultaneously.
///
/// Membership and geometry are read from one snapshot, including folded children.
/// Overlapping roots move each placement once. Route pins follow the combined
/// movement of their actual endpoint owners (and State boundaries). Semantic
/// ownership and other views are untouched. Apply the returned batch through the
/// normal validated command path; its selected identity is not a primary selection.
pub fn translate_placements(
project: &Project,
diagram: Id,
selected: &BTreeSet<Id>,
delta: Position,
) -> Result<Command, ModelError> {
let view = project
.diagrams
.get(&diagram)
.ok_or_else(|| ModelError("Movement requires an existing diagram.".into()))?;
if selected.is_empty() {
return Err(ModelError(
"Movement requires at least one placement.".into(),
));
}
if selected.iter().any(|id| !view.nodes.contains_key(id)) {
return Err(ModelError(
"Every selected placement must belong to the diagram.".into(),
));
}
if !delta.x.is_finite() || !delta.y.is_finite() {
return Err(ModelError("Movement displacement must be finite.".into()));
}
if delta.x == 0. && delta.y == 0. {
return Ok(Command::Batch(vec![]));
}
let mut children: BTreeMap<Id, Vec<Id>> = BTreeMap::new();
for (child, parent) in projection::parents(project, view) {
if let Some(parent) = parent {
children.entry(parent).or_default().push(child);
}
}
let mut moved = BTreeSet::new();
let mut pending: Vec<_> = selected.iter().copied().collect();
while let Some(id) = pending.pop() {
if moved.insert(id) {
pending.extend(children.get(&id).into_iter().flatten().copied());
}
}
let deltas: BTreeMap<_, _> = moved.iter().map(|id| (*id, delta)).collect();
let routes = projection::translated_routes(project, view, &deltas);
let bounded = |value: f32| value.is_finite() && value.abs() <= MAX_COORDINATE;
let mut commands = Vec::with_capacity(moved.len() + routes.len());
for id in moved {
let mut node = view.nodes[&id].clone();
node.position.x += delta.x;
node.position.y += delta.y;
if ![
node.position.x,
node.position.y,
node.size.width,
node.size.height,
]
.into_iter()
.all(bounded)
|| node.size.width <= 0.
|| node.size.height <= 0.
{
return Err(ModelError(
"Movement produces invalid placement bounds.".into(),
));
}
commands.push(Command::EditNode {
diagram,
original: id,
node,
});
}
for route in routes {
if route
.waypoints
.iter()
.any(|point| !bounded(point.x) || !bounded(point.y))
{
return Err(ModelError("Movement produces invalid route bounds.".into()));
}
commands.push(Command::SetEdgeRoute { diagram, route });
}
Ok(Command::Batch(commands))
}
+1
View File
@@ -1,6 +1,7 @@
//! Framework-independent OA/SA model, transactional commands and editing services.
pub mod analysis_numeric;
pub mod data;
pub mod diagram_edit;
pub mod language;
pub mod model;
pub mod operations;
+427
View File
@@ -0,0 +1,427 @@
use oa_core::{diagram_edit::translate_placements, source_project::*, *};
use std::collections::BTreeSet;
fn point(x: f32, y: f32) -> Position {
Position { x, y }
}
fn route(edge: Id, x: f32, y: f32) -> EdgeRoute {
EdgeRoute {
edge,
source_attachment: Some(EdgeAttachment {
side: PortAnchorSide::Bottom,
offset: 0.2,
}),
target_attachment: Some(EdgeAttachment {
side: PortAnchorSide::Top,
offset: 0.8,
}),
waypoints: vec![point(x, y)],
label: Some(EdgeLabel {
fraction: 0.4,
offset: point(3., -9.),
}),
}
}
struct Fixture {
project: Project,
diagram: Id,
a: Id,
b: Id,
child: Id,
foreign: Id,
}
fn fixture() -> Fixture {
let mut p = Project::empty();
let a = p.add_element(Kind::Activity, Layer::Oa, "A", None).unwrap();
let b = p.add_element(Kind::Activity, Layer::Oa, "B", None).unwrap();
let c = p.add_element(Kind::Activity, Layer::Oa, "C", None).unwrap();
let child = p
.add_element(Kind::Activity, Layer::Oa, "Child", Some(a))
.unwrap();
let internal = p.relate(RelationKind::Interaction, "Internal", a, b);
let external = p.relate(RelationKind::Interaction, "External", b, c);
let d = p.ensure_diagram(Layer::Oa);
let na = p.place(d, a, point(10., 20.));
let nb = p.place(d, b, point(400., 20.));
let nc = p.place(d, child, point(30., 80.));
p.place(d, c, point(800., 20.));
p.diagrams.get_mut(&d).unwrap().routes =
vec![route(internal, 320., 150.), route(external, 720., 170.)];
p.diagrams
.get_mut(&d)
.unwrap()
.nodes
.get_mut(&na)
.unwrap()
.collapsed = true;
let other = Id::new_v4();
let mut other_view = p.diagrams[&d].clone();
other_view.id = other;
other_view.alias = "other_view".into();
other_view.nodes.clear();
other_view.routes.clear();
p.diagrams.insert(other, other_view);
let foreign = p.place(other, a, point(-40., -50.));
validate_candidate(&p).unwrap();
Fixture {
project: p,
diagram: d,
a: na,
b: nb,
child: nc,
foreign,
}
}
#[test]
fn simultaneous_siblings_translate_internal_pins_once_and_preserve_complete_project() {
let f = fixture();
let before = f.project.clone();
let command = translate_placements(
&before,
f.diagram,
&BTreeSet::from([f.a, f.b]),
point(40., 60.),
)
.unwrap();
assert_eq!(
before, f.project,
"command construction must not mutate input"
);
// Independently enumerated expected edits, without the projection helpers.
let mut expected = before.clone();
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
view.nodes.get_mut(&f.a).unwrap().position = point(50., 80.);
view.nodes.get_mut(&f.b).unwrap().position = point(440., 80.);
view.nodes.get_mut(&f.child).unwrap().position = point(70., 140.);
view.routes[0].waypoints = vec![point(360., 210.)];
let mut session = Session::new(before.clone());
session.execute(command.clone()).unwrap();
assert_eq!(session.project(), &expected);
session.undo();
assert_eq!(session.project(), &before);
assert!(
!session.can_undo(),
"one movement must be one history entry"
);
session.redo();
assert_eq!(session.project(), &expected);
assert!(!session.can_redo());
// Independent one-node moves cannot see the shared endpoint displacement.
let mut sequential = Session::new(before.clone());
for (node, position) in [(f.a, point(50., 80.)), (f.b, point(440., 80.))] {
sequential
.execute(Command::MoveNode {
diagram: f.diagram,
node,
position,
with_descendants: true,
})
.unwrap();
}
assert_eq!(
sequential.project().diagrams[&f.diagram].routes[0],
before.diagrams[&f.diagram].routes[0]
);
assert_ne!(sequential.project(), &expected);
let json = serde_json::to_string(&expected).unwrap();
assert_eq!(serde_json::from_str::<Project>(&json).unwrap(), expected);
let mut bundle = format_bundle(&before);
bundle
.files
.get_mut(&bundle.entry.clone())
.unwrap()
.insert_str(0, "// preserve movement rationale\n");
let original = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
let prepared = prepare_command(&before, &command).unwrap();
let updated = update_bundle_with_identity_map(
&original,
&prepared.project,
&prepared.identity_map,
ProjectLimits::default(),
)
.unwrap();
assert_eq!(updated.decoded.project, expected);
assert!(updated.bundle.files[&bundle.entry].starts_with("// preserve movement rationale\n"));
let reread = compile_bundle(&updated.bundle, ProjectLimits::default()).unwrap();
assert_eq!(reread.decoded.project, expected);
assert_eq!(reread.bundle, updated.bundle);
}
#[test]
fn selecting_folded_ancestor_and_hidden_descendant_moves_each_once() {
let f = fixture();
assert!(
!projection::project_view(&f.project, f.diagram)
.nodes
.iter()
.any(|n| n.id == f.child)
);
let ancestor = translate_placements(
&f.project,
f.diagram,
&BTreeSet::from([f.a]),
point(-15., 25.),
)
.unwrap();
let overlap = translate_placements(
&f.project,
f.diagram,
&BTreeSet::from([f.a, f.child]),
point(-15., 25.),
)
.unwrap();
assert_eq!(overlap, ancestor);
let after = prepare_command(&f.project, &overlap).unwrap().project;
assert_eq!(
after.diagrams[&f.diagram].nodes[&f.child].position,
point(15., 105.)
);
assert_eq!(
after.diagrams[&f.diagram].routes,
f.project.diagrams[&f.diagram].routes
);
}
#[test]
fn invalid_movements_refuse_atomically_and_zero_has_no_history() {
let f = fixture();
let selected = BTreeSet::from([f.a, f.b]);
for (diagram, ids, delta) in [
(Id::new_v4(), selected.clone(), point(1., 1.)),
(f.diagram, BTreeSet::new(), point(1., 1.)),
(
f.diagram,
BTreeSet::from([f.a, Id::new_v4()]),
point(1., 1.),
),
(f.diagram, BTreeSet::from([f.a, f.foreign]), point(0., 0.)),
(f.diagram, selected.clone(), point(f32::NAN, 1.)),
(f.diagram, selected.clone(), point(1., f32::INFINITY)),
(f.diagram, selected.clone(), point(MAX_COORDINATE, 0.)),
(f.diagram, selected.clone(), point(f32::MAX, f32::MAX)),
] {
let before = f.project.clone();
assert!(translate_placements(&f.project, diagram, &ids, delta).is_err());
assert_eq!(f.project, before);
}
let mut bad_route = f.project.clone();
bad_route.diagrams.get_mut(&f.diagram).unwrap().routes[0].waypoints =
vec![point(MAX_COORDINATE, 0.)];
validate_candidate(&bad_route).unwrap();
let snapshot = bad_route.clone();
assert!(translate_placements(&bad_route, f.diagram, &selected, point(1., 0.)).is_err());
assert_eq!(bad_route, snapshot);
let zero = translate_placements(&f.project, f.diagram, &selected, point(0., -0.)).unwrap();
assert_eq!(zero, Command::Batch(vec![]));
let mut session = Session::new(f.project.clone());
session.execute(zero).unwrap();
assert_eq!(session.project(), &f.project);
assert!(!session.can_undo());
assert_eq!(session.revision(), 0);
}
#[test]
fn typed_component_port_endpoints_follow_their_owner_placements() {
let mut p = Project::empty();
let a = p
.add_element(Kind::System, Layer::Sa, "System", None)
.unwrap();
let b = p
.add_element(Kind::SystemActor, Layer::Sa, "Actor", None)
.unwrap();
let output = Id::new_v4();
let input = Id::new_v4();
for (id, owner, name, orientation) in [
(output, a, "Output", ComponentPortOrientation::Out),
(input, b, "Input", ComponentPortOrientation::In),
] {
let port = make_port(
&p,
id,
owner,
name,
PortContract::Component {
kind: ComponentPortKind::Flow,
orientation,
},
)
.unwrap();
p.elements.insert(id, port);
}
let edge = p.relate(RelationKind::BoundaryExchange, "Boundary", output, input);
let d = p.ensure_diagram(Layer::Sa);
let na = p.place(d, a, point(0., 0.));
let nb = p.place(d, b, point(400., 0.));
for (node, port, side, offset) in [
(na, output, PortAnchorSide::Bottom, 0.3),
(nb, input, PortAnchorSide::Top, 0.7),
] {
p.diagrams
.get_mut(&d)
.unwrap()
.nodes
.get_mut(&node)
.unwrap()
.port_anchors
.push(PortAnchor { port, side, offset });
}
p.diagrams
.get_mut(&d)
.unwrap()
.routes
.push(route(edge, 300., 100.));
validate_candidate(&p).unwrap();
let command = translate_placements(&p, d, &BTreeSet::from([na, nb]), point(10., -20.)).unwrap();
let after = prepare_command(&p, &command).unwrap().project;
let mut expected = p.clone();
let view = expected.diagrams.get_mut(&d).unwrap();
view.nodes.get_mut(&na).unwrap().position = point(10., -20.);
view.nodes.get_mut(&nb).unwrap().position = point(410., -20.);
view.routes[0].waypoints = vec![point(310., 80.)];
assert_eq!(after, expected);
}
#[test]
fn allocation_movement_follows_visual_performers_and_same_performer_work_groups() {
let mut p = Project::empty();
let performer_a = p
.add_element(Kind::Entity, Layer::Oa, "Performer A", None)
.unwrap();
let performer_b = p
.add_element(Kind::Entity, Layer::Oa, "Performer B", None)
.unwrap();
let mixed = p
.add_element(Kind::Activity, Layer::Oa, "Mixed work", None)
.unwrap();
let branch = p
.add_element(Kind::Activity, Layer::Oa, "A work", Some(mixed))
.unwrap();
let leaf_a = p
.add_element(Kind::Activity, Layer::Oa, "A leaf", Some(branch))
.unwrap();
let leaf_b = p
.add_element(Kind::Activity, Layer::Oa, "B leaf", Some(mixed))
.unwrap();
p.relate(RelationKind::Allocation, "A performs", performer_a, leaf_a);
p.relate(RelationKind::Allocation, "B performs", performer_b, leaf_b);
let d = p.ensure_diagram(Layer::Oa);
p.diagrams.get_mut(&d).unwrap().projection = ProjectionKind::Allocation;
let na = p.place(d, performer_a, point(0., 0.));
p.place(d, performer_b, point(600., 0.));
let nm = p.place(d, mixed, point(1000., 0.));
let branch_node = p.place(d, branch, point(20., 80.));
let leaf_node = p.place(d, leaf_a, point(40., 160.));
p.place(d, leaf_b, point(620., 80.));
validate_candidate(&p).unwrap();
// Mixed work retains semantic ownership of both branches, but its leaves
// have different performers. A work is visually nested under Performer A,
// with its own same-performer leaf nested inside it.
let command =
translate_placements(&p, d, &BTreeSet::from([na, branch_node]), point(15., -25.)).unwrap();
let after = prepare_command(&p, &command).unwrap().project;
let mut expected = p.clone();
let view = expected.diagrams.get_mut(&d).unwrap();
view.nodes.get_mut(&na).unwrap().position = point(15., -25.);
view.nodes.get_mut(&branch_node).unwrap().position = point(35., 55.);
view.nodes.get_mut(&leaf_node).unwrap().position = point(55., 135.);
assert_eq!(after, expected);
// Moving the semantic parent does not move children displayed elsewhere.
let command = translate_placements(&p, d, &BTreeSet::from([nm]), point(15., -25.)).unwrap();
let after = prepare_command(&p, &command).unwrap().project;
let mut expected = p.clone();
expected
.diagrams
.get_mut(&d)
.unwrap()
.nodes
.get_mut(&nm)
.unwrap()
.position = point(1015., -25.);
assert_eq!(after, expected);
}
#[test]
fn traceability_movement_is_flat_even_for_a_semantic_parent() {
let mut f = fixture();
f.project.diagrams.get_mut(&f.diagram).unwrap().projection = ProjectionKind::Traceability;
validate_candidate(&f.project).unwrap();
let command = translate_placements(
&f.project,
f.diagram,
&BTreeSet::from([f.a]),
point(40., 60.),
)
.unwrap();
let after = prepare_command(&f.project, &command).unwrap().project;
let mut expected = f.project.clone();
expected
.diagrams
.get_mut(&f.diagram)
.unwrap()
.nodes
.get_mut(&f.a)
.unwrap()
.position = point(50., 80.);
assert_eq!(
after, expected,
"flat view movement must preserve semantic descendants, routes, other views and all semantics"
);
}
#[test]
fn state_entry_pins_follow_the_boundary_only_when_it_also_moves() {
let mut p = Project::empty();
let machine = p
.add_element(Kind::StateMachine, Layer::Oa, "Machine", None)
.unwrap();
let region = p
.add_element(Kind::Region, Layer::Oa, "Region", Some(machine))
.unwrap();
let composite = p
.add_element(Kind::State, Layer::Oa, "Composite", Some(region))
.unwrap();
let inner = p
.add_element(Kind::Region, Layer::Oa, "Inner", Some(composite))
.unwrap();
let entry = p
.add_element(Kind::EntryPoint, Layer::Oa, "Entry", Some(inner))
.unwrap();
let leaf = p
.add_element(Kind::State, Layer::Oa, "Leaf", Some(inner))
.unwrap();
let edge = p.relate(RelationKind::StateTransition, "Enter", entry, leaf);
if let RelationBody::StateTransition {
transition_kind, ..
} = &mut p.relations.get_mut(&edge).unwrap().body
{
*transition_kind = TransitionKind::Local;
}
let d = p.ensure_diagram(Layer::Oa);
p.diagrams.get_mut(&d).unwrap().projection = ProjectionKind::StateMachine { machine };
let boundary = p.place(d, composite, point(0., 0.));
let ne = p.place(d, entry, point(20., 80.));
let nl = p.place(d, leaf, point(100., 80.));
p.diagrams
.get_mut(&d)
.unwrap()
.routes
.push(route(edge, 90., 100.));
validate_candidate(&p).unwrap();
let endpoints =
translate_placements(&p, d, &BTreeSet::from([ne, nl]), point(10., 20.)).unwrap();
let after = prepare_command(&p, &endpoints).unwrap().project;
assert_eq!(after.diagrams[&d].routes, p.diagrams[&d].routes);
let with_boundary =
translate_placements(&p, d, &BTreeSet::from([boundary, ne, nl]), point(10., 20.)).unwrap();
let after = prepare_command(&p, &with_boundary).unwrap().project;
assert_eq!(
after.diagrams[&d].routes[0].waypoints,
vec![point(100., 120.)]
);
assert_eq!(after.diagrams[&d].nodes[&ne].position, point(30., 100.));
}
@@ -60,6 +60,7 @@ impl Root<'_> {
return false;
}
let canvas = DiagramCanvas {
selection: self.app.diagram_selection.as_ref(),
allocation: Some(self.app.allocation_capability()),
project: self.app.project(),
view_index: Some(self.app.document.view_index()),
+100 -3
View File
@@ -15,6 +15,9 @@ mod diagram_reveal;
mod diagram_selection_tests;
mod diagram_usages;
mod hosted;
pub(crate) mod multiselect;
#[cfg(test)]
mod multiselect_tests;
mod reference_authoring;
#[cfg(test)]
mod review_navigation_tests;
@@ -26,6 +29,10 @@ mod scenario_spacing;
mod source_indentation_tests;
pub(crate) mod source_rename;
mod source_symbols;
#[cfg(test)]
mod state_multiselect_focus_tests;
#[cfg(test)]
mod state_multiselect_tests;
pub(crate) mod text_workspace;
#[cfg(test)]
mod transition_context_tests;
@@ -371,6 +378,7 @@ pub enum Message {
Select(Id),
EditProperties(Id),
SelectNode(Id),
DiagramSelection(multiselect::Event),
SelectProject,
Search(String),
StartTransition,
@@ -515,6 +523,7 @@ pub struct App {
pub layer: Layer,
pub selected: Id,
pub selected_node: Option<Id>,
pub diagram_selection: Option<crate::diagram_selection::Selection>,
pub draft: Option<Draft>,
pub active_diagram: Option<Id>,
pub search: String,
@@ -636,6 +645,7 @@ impl App {
layer,
selected,
selected_node: None,
diagram_selection: None,
draft,
active_diagram,
search: String::new(),
@@ -1337,6 +1347,38 @@ impl App {
])
}
pub fn update(&mut self, message: Message) -> Task<Message> {
let selection_boundary = self.multiselect_boundary();
// Reject delayed gestures before they can retire newer input ownership.
if let Message::DiagramSelection(event)
| Message::StateDiagram(crate::behavior::state_edit::Event::Selection(event)) = &message
&& !self.multiselect_envelope(event)
{
return Task::none();
}
if let Message::StateDiagram(event) = &message
&& let Some(captured) = event.context()
&& self.state_context().is_none_or(|current| {
crate::behavior::state_edit::validate_context(self.project(), captured, current)
.is_err()
})
{
return Task::none();
}
if matches!(
&message,
Message::StateDiagram(
crate::behavior::state_edit::Event::Select(..)
| crate::behavior::state_edit::Event::Move { .. }
| crate::behavior::state_edit::Event::Remove(_)
)
) && self
.multiselect_snapshot()
.is_some_and(|s| s.targets().len() > 1)
{
// A queued singleton cannot retire the current group's navigation
// or allocation ownership before its edit is refused.
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 {
@@ -1439,7 +1481,11 @@ impl App {
self.reconcile_pending_diagram_reveal(&message);
self.allocation_before(&message);
if let Message::WorkDrag(event) = message {
return self.allocation_event(event);
let task = self.allocation_event(event);
if self.multiselect_boundary() != selection_boundary {
self.reconcile_multiselect();
}
return task;
}
let allocation_before = self.allocation_boundary();
if let Message::BehaviorControl(intent) = message {
@@ -1480,6 +1526,11 @@ impl App {
self.camera_epoch = self.camera_epoch.wrapping_add(1);
self.camera_boundary_epoch = self.canvas_epoch;
}
if self.multiselect_boundary() != selection_boundary
|| (self.diagram_selection.is_none() && self.multiselect_context().is_some())
{
self.reconcile_multiselect();
}
task
}
fn behavior_control(&mut self, intent: behavior::canvas_workspace::Intent) -> Task<Message> {
@@ -1847,6 +1898,7 @@ impl App {
message,
Message::Page(_) | Message::Layer(_) | Message::Diagram(_)
) {
self.diagram_selection = None;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
self.selected_bend = None;
}
@@ -2563,8 +2615,17 @@ impl App {
"Apply or revert pending edits before using modeling actions.".into();
return Task::none();
}
if matches!(*action, Message::DiagramSelection(_)) {
return self.update(*action);
}
self.select(menu.request.object);
self.selected_node = menu.request.placement;
if self.page == Page::Behavior && menu.request.canvas.is_some() {
self.behavior.diagram.placement = menu.request.placement;
self.selected_node = None;
} else {
self.selected_node = menu.request.placement;
}
self.reconcile_multiselect();
self.selected_bend = menu.request.bend.map(|i| (menu.request.object, i));
return self.update(*action);
}
@@ -2722,6 +2783,7 @@ impl App {
self.status = "Property draft reverted".into();
}
Message::Select(id) => self.select(id),
Message::DiagramSelection(event) => self.multiselect_event(event),
Message::EditProperties(id) => {
self.select(id);
self.inspector_tab = crate::navigation::InspectorTab::Properties;
@@ -3395,7 +3457,21 @@ impl App {
}
}
}
Message::DiagramRemove(intent) => self.remove_from_diagram(intent),
Message::DiagramRemove(intent) => {
if self
.multiselect_snapshot()
.is_some_and(|s| s.targets().len() > 1)
{
// A pre-redraw singleton Delete cannot remove just one
// member of a selection changed earlier in the same batch.
if Some(intent.context) == self.route_context() {
self.status =
"Selection changed. Use Hide selected or press Delete again.".into();
}
} else {
self.remove_from_diagram(intent);
}
}
Message::DiagramTraverse(back) => {
return if back {
iced::widget::operation::focus_previous()
@@ -3404,6 +3480,13 @@ impl App {
};
}
Message::Delete => {
if self
.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();
return Task::none();
}
if self.selected != self.project().id && self.apply() {
self.begin_model_delete(None);
}
@@ -3556,6 +3639,13 @@ impl App {
}
}
Message::HideSelected => {
if let Some(snapshot) = self
.multiselect_snapshot()
.filter(|s| s.targets().len() > 1)
{
self.multiselect_event(multiselect::Event::Hide(snapshot));
return Task::none();
}
if self.apply()
&& let Some(node) = self.selected_node
{
@@ -3585,6 +3675,13 @@ impl App {
}
Message::Route(event) => self.edit_route(event),
Message::MoveNode(node, position) => {
if self
.multiselect_snapshot()
.is_some_and(|s| s.targets().len() > 1)
{
self.status = "Selection changed. Start the group drag again.".into();
return Task::none();
}
let original = self.selected;
if self.apply()
&& let Some(diagram) = self.active_diagram
@@ -59,6 +59,7 @@ fn fixture(layer: Layer) -> Fixture {
}
fn canvas(app: &App) -> DiagramCanvas<'_> {
DiagramCanvas {
selection: None,
allocation: Some(app.allocation_capability()),
project: app.project(),
view_index: Some(app.document.view_index()),
@@ -66,6 +66,7 @@ fn architecture_f2_routes_selected_node_to_inline_rename_and_exact_undo() {
let camera = (app.zoom, app.pan);
let bounds = iced::Rectangle::new(iced::Point::ORIGIN, iced::Size::new(600., 380.));
let canvas = crate::diagram::DiagramCanvas {
selection: None,
project: app.project(),
view_index: None,
diagram: app.active_diagram.unwrap(),
@@ -221,6 +221,7 @@ fn architecture_canvas_left_click_uses_world_coordinate_once_at_zoom_and_pan() {
y: (local.y - app.pan.y) / app.zoom,
};
let canvas = crate::diagram::DiagramCanvas {
selection: None,
project: app.project(),
view_index: None,
diagram: app.active_diagram.unwrap(),
@@ -298,6 +299,7 @@ fn architecture_f2_rename_preserves_identity_placement_and_atomic_history() {
let diagrams = app.project().diagrams.clone();
let camera = (app.zoom, app.pan);
let canvas = crate::diagram::DiagramCanvas {
selection: None,
project: app.project(),
view_index: None,
diagram: app.active_diagram.unwrap(),
@@ -154,3 +154,440 @@ async fn mounted_f2_requires_canvas_focus_and_yields_to_clean_inspector() {
}
}
}
async fn modifier_focus_fixture() -> (App, Mounted, Id, Id, Id) {
let mut project = Project::empty();
let a = project
.add_element(Kind::Entity, Layer::Oa, "First team", None)
.unwrap();
let b = project
.add_element(Kind::Entity, Layer::Oa, "Second team", None)
.unwrap();
let diagram = project.ensure_diagram(Layer::Oa);
let first = project.place(diagram, a, Position { x: 80., y: 80. });
let second = project.place(diagram, b, Position { x: 500., y: 80. });
let mut app = App::with_project(project);
app.page = Page::Diagram;
app.layer = Layer::Oa;
app.active_diagram = Some(diagram);
app.window_size = Size::new(2000., 1400.);
let _ = app.update(Message::Select(a));
let mut mounted = Mounted::new(&mut app).await;
app.zoom = 1.;
app.pan = Vector::ZERO;
app.fit_to_view = false;
mounted.settle(&mut app).await;
(app, mounted, diagram, first, second)
}
fn modifier_node_point(mounted: &mut Mounted, app: &App, diagram: Id, placement: Id) -> Point {
let bounds = mounted
.geometry(app)
.bounds(crate::allocation_input::CANVAS_ID);
let node = projection::project_view(app.project(), diagram)
.nodes
.into_iter()
.find(|n| n.id == placement)
.unwrap();
Point::new(
bounds.x + node.position.x + 40.,
bounds.y + node.position.y + 35.,
)
}
fn modifier_canvas_focused(mounted: &mut Mounted, app: &App) -> bool {
mounted
.geometry(app)
.focused
.iter()
.find(|(id, _, _)| {
id.as_ref() == Some(&iced::advanced::widget::Id::from("diagram-keyboard-owner"))
})
.expect("production focus::Owner is mounted")
.2
}
fn modifier_event(shift: bool) -> iced::Event {
iced::Event::Keyboard(iced::keyboard::Event::ModifiersChanged(if shift {
iced::keyboard::Modifiers::SHIFT
} else {
iced::keyboard::Modifiers::default()
}))
}
#[tokio::test]
async fn mounted_shift_before_canvas_focus_toggles_exact_node_without_granting_keyboard_focus() {
use crate::diagram_usage::Target;
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
let before = app.document.snapshot();
let field = mounted
.geometry(&app)
.text_inputs
.into_iter()
.filter(|bounds| bounds.x > app.window_size.width - 320.)
.min_by(|a, b| a.y.total_cmp(&b.y))
.expect("clean Inspector name input");
mounted.operate(&app, &mut FocusField(field));
assert!(!modifier_canvas_focused(&mut mounted, &app));
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(first)]
);
mounted
.batch(
&mut app,
&[modifier_event(true)],
mouse::Cursor::Unavailable,
)
.await;
assert!(
!modifier_canvas_focused(&mut mounted, &app),
"modifier tracking must not acquire focus"
);
let at = modifier_node_point(&mut mounted, &app, diagram, second);
let messages = mounted.click(&mut app, at).await;
assert!(messages.iter().any(|m| matches!(m,
Message::DiagramSelection(multiselect::Event::Choose(_, Target::Placement(id), multiselect::Choice::Toggle)) if *id == second
)), "Shift already held before the first canvas press must reach its exact-target adapter");
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(first), Target::Placement(second)]
);
assert_eq!(app.selected_node, Some(second));
assert_eq!(app.project(), &before.decoded.project);
assert_eq!(app.document.bundle(), &before.bundle);
assert!(!app.document.can_undo());
assert!(!app.draft_dirty());
}
#[tokio::test]
async fn mounted_unfocused_typing_and_delete_remain_denied_after_passive_modifiers() {
use crate::diagram_usage::Target;
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
mounted
.batch(
&mut app,
&[modifier_event(true)],
mouse::Cursor::Unavailable,
)
.await;
let at = modifier_node_point(&mut mounted, &app, diagram, second);
mounted.click(&mut app, at).await;
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(first), Target::Placement(second)]
);
// Revoke every field's focus through the real widget operation. No widget
// has this off-window rectangle, so neither Inspector nor canvas owns keys.
mounted.operate(
&app,
&mut FocusField(Rectangle {
x: -1000.,
y: -1000.,
width: 1.,
height: 1.,
}),
);
assert!(!modifier_canvas_focused(&mut mounted, &app));
let before = app.document.snapshot();
let selection = app.multiselect_snapshot().unwrap();
let messages = mounted
.batch(
&mut app,
&[
modifier_event(false),
crate::behavior::canvas_workspace::tests::character("x"),
key(Named::Delete),
key(Named::F2),
],
mouse::Cursor::Unavailable,
)
.await;
assert!(!messages.iter().any(|m| matches!(
m,
Message::DiagramSelection(_)
| Message::DiagramRemove(_)
| Message::HideSelected
| Message::Delete
)));
assert!(!rename_emitted(&messages));
assert!(!modifier_canvas_focused(&mut mounted, &app));
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
selection.targets()
);
assert_eq!(app.project(), &before.decoded.project);
assert_eq!(app.document.bundle(), &before.bundle);
assert!(!app.document.can_undo());
assert!(!app.draft_dirty());
assert!(!app.delete_pending);
}
#[tokio::test]
async fn mounted_suspended_modifiers_are_passive_and_survive_until_resumed_click() {
use crate::diagram_usage::Target;
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
let before = app.document.snapshot();
let at = modifier_node_point(&mut mounted, &app, diagram, second);
app.busy = true;
mounted.settle(&mut app).await;
assert!(!modifier_canvas_focused(&mut mounted, &app));
mounted
.batch(
&mut app,
&[modifier_event(true), key(Named::Delete)],
mouse::Cursor::Unavailable,
)
.await;
mounted.click(&mut app, at).await;
assert!(
!modifier_canvas_focused(&mut mounted, &app),
"passive I/O cannot grant canvas focus"
);
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(first)]
);
assert_eq!(app.document.bundle(), &before.bundle);
app.busy = false;
mounted.settle(&mut app).await;
assert!(!modifier_canvas_focused(&mut mounted, &app));
mounted.click(&mut app, at).await;
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(first), Target::Placement(second)]
);
assert_eq!(app.project(), &before.decoded.project);
assert_eq!(app.document.bundle(), &before.bundle);
assert!(!app.document.can_undo());
}
#[tokio::test]
async fn mounted_shift_held_before_suspension_survives_without_another_modifier_event() {
use crate::diagram_usage::Target;
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
let before = app.document.snapshot();
let field = mounted
.geometry(&app)
.text_inputs
.into_iter()
.filter(|bounds| bounds.x > app.window_size.width - 320.)
.min_by(|a, b| a.y.total_cmp(&b.y))
.expect("clean Inspector name input");
mounted.operate(&app, &mut FocusField(field));
mounted
.batch(
&mut app,
&[modifier_event(true)],
mouse::Cursor::Unavailable,
)
.await;
assert!(!modifier_canvas_focused(&mut mounted, &app));
app.busy = true;
mounted.settle(&mut app).await;
assert!(!modifier_canvas_focused(&mut mounted, &app));
app.busy = false;
mounted.settle(&mut app).await;
assert!(
!modifier_canvas_focused(&mut mounted, &app),
"restoring passive modifiers must not grant keyboard focus"
);
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(first)]
);
// No modifier transition follows the subtree replacement during I/O.
let at = modifier_node_point(&mut mounted, &app, diagram, second);
let messages = mounted.click(&mut app, at).await;
assert!(messages.iter().any(|m| matches!(m,
Message::DiagramSelection(multiselect::Event::Choose(_, Target::Placement(id), multiselect::Choice::Toggle)) if *id == second
)));
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(first), Target::Placement(second)]
);
assert_eq!(app.project(), &before.decoded.project);
assert_eq!(app.document.bundle(), &before.bundle);
assert!(!app.document.can_undo());
assert!(!app.draft_dirty());
}
#[tokio::test]
async fn mounted_shift_release_or_window_unfocus_during_suspension_does_not_restore_stale_shift() {
use crate::diagram_usage::Target;
for release in [
modifier_event(false),
iced::Event::Window(iced::window::Event::Unfocused),
] {
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
let before = app.document.snapshot();
mounted
.batch(
&mut app,
&[modifier_event(true)],
mouse::Cursor::Unavailable,
)
.await;
app.busy = true;
mounted.settle(&mut app).await;
mounted
.batch(&mut app, &[release], mouse::Cursor::Unavailable)
.await;
assert!(!modifier_canvas_focused(&mut mounted, &app));
app.busy = false;
mounted.settle(&mut app).await;
// A further I/O cycle must restore the updated owner state too.
app.busy = true;
mounted.settle(&mut app).await;
app.busy = false;
mounted.settle(&mut app).await;
assert!(!modifier_canvas_focused(&mut mounted, &app));
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(first)]
);
let at = modifier_node_point(&mut mounted, &app, diagram, second);
let messages = mounted.click(&mut app, at).await;
assert!(!messages.iter().any(|m| matches!(
m,
Message::DiagramSelection(multiselect::Event::Choose(
_,
_,
multiselect::Choice::Toggle
))
)));
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(second)]
);
assert_eq!(app.project(), &before.decoded.project);
assert_eq!(app.document.bundle(), &before.bundle);
assert!(!app.document.can_undo());
assert!(!app.draft_dirty());
}
}
#[tokio::test]
async fn mounted_window_unfocus_resets_held_shift_before_next_canvas_press() {
use crate::diagram_usage::Target;
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
let at_first = modifier_node_point(&mut mounted, &app, diagram, first);
mounted.click(&mut app, at_first).await;
let before = app.document.snapshot();
mounted
.batch(
&mut app,
&[
modifier_event(true),
iced::Event::Window(iced::window::Event::Unfocused),
],
mouse::Cursor::Unavailable,
)
.await;
assert!(!modifier_canvas_focused(&mut mounted, &app));
// No ModifiersChanged(empty) follows: a lost window must itself reset it.
let at_second = modifier_node_point(&mut mounted, &app, diagram, second);
mounted.click(&mut app, at_second).await;
assert_eq!(
app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(second)]
);
assert_eq!(app.project(), &before.decoded.project);
assert_eq!(app.document.bundle(), &before.bundle);
assert!(!app.document.can_undo());
}
#[tokio::test]
async fn mounted_selection_strip_keeps_canvas_and_fitted_camera_fixed_for_empty_single_group_and_mixed()
{
use crate::diagram_usage::Target;
let mut project = Project::empty();
let a = project
.add_element(Kind::Activity, Layer::Oa, "First activity", None)
.unwrap();
let b = project
.add_element(
Kind::Activity,
Layer::Oa,
&format!(
"Second activity {}",
"with a very long primary name ".repeat(20)
),
None,
)
.unwrap();
let edge = project.relate(RelationKind::Interaction, "Activity exchange", a, b);
let diagram = project.ensure_diagram(Layer::Oa);
project.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Overview;
let first = project.place(diagram, a, Position { x: 80., y: 80. });
let second = project.place(diagram, b, Position { x: 500., y: 80. });
let mut app = App::with_project(project);
app.page = Page::Diagram;
app.layer = Layer::Oa;
app.active_diagram = Some(diagram);
app.window_size = Size::new(1442., 932.);
let _ = app.update(Message::Select(diagram));
app.fit_to_view = true;
let mut mounted = Mounted::new(&mut app).await;
let baseline = app.document.snapshot();
let bounds = mounted
.geometry(&app)
.bounds(crate::allocation_input::CANVAS_ID);
let camera = (app.zoom, app.pan, app.fit_to_view, app.canvas_size);
assert!(camera.2, "exercise the native resize-triggered refit path");
assert!(app.multiselect_snapshot().unwrap().targets().is_empty());
assert!(bounds.width > 500. && bounds.height > 300.);
for (target, expected) in [
(
Some(Target::Placement(first)),
vec![Target::Placement(first)],
),
(
Some(Target::Placement(second)),
vec![Target::Placement(first), Target::Placement(second)],
),
(
Some(Target::Edge(edge)),
vec![
Target::Placement(first),
Target::Placement(second),
Target::Edge(edge),
],
),
(
Some(Target::Edge(edge)),
vec![Target::Placement(first), Target::Placement(second)],
),
(
Some(Target::Placement(second)),
vec![Target::Placement(first)],
),
(None, vec![]),
] {
let context = app.multiselect_context().unwrap();
let event = match target {
Some(target) => {
multiselect::Event::Choose(context, target, multiselect::Choice::Toggle)
}
None => multiselect::Event::Clear(context),
};
let task = app.update(Message::DiagramSelection(event));
mounted.perform(&mut app, task).await;
mounted.settle(&mut app).await;
assert_eq!(app.multiselect_snapshot().unwrap().targets(), expected);
assert_eq!(
mounted
.geometry(&app)
.bounds(crate::allocation_input::CANVAS_ID),
bounds,
"selection feedback must not change the measured canvas rectangle"
);
assert_eq!(
(app.zoom, app.pan, app.fit_to_view, app.canvas_size),
camera
);
assert_eq!(app.project(), &baseline.decoded.project);
assert_eq!(app.document.bundle(), &baseline.bundle);
assert!(!app.document.can_undo());
assert!(!app.draft_dirty());
}
}
+433
View File
@@ -0,0 +1,433 @@
//! Exact saved-view selection and atomic group commands.
use super::*;
use crate::diagram_selection::{Context, Scope, Selection, Snapshot};
use crate::diagram_usage::{Surface, Target};
#[derive(Debug, Clone, Copy)]
pub(crate) enum Choice {
Replace,
Add,
Remove,
Toggle,
Inspect,
}
#[derive(Debug, Clone)]
pub(crate) enum Event {
Choose(Context, Target, Choice),
Collapse(Snapshot, Target),
Clear(Context),
Move(Snapshot, Position),
Hide(Snapshot),
Refuse(Snapshot, String),
}
pub(crate) fn context(c: crate::route_edit::Context) -> Context {
Context {
scope: Scope {
document: c.document,
surface: Surface::Saved(c.diagram),
},
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()?;
if snapshot.targets().is_empty() {
return None;
}
snapshot
.targets()
.iter()
.map(|target| match target {
Target::Placement(id) => Some(*id),
_ => None,
})
.collect()
}
fn visible(
project: &Project,
diagram: Id,
view: &projection::ProjectedView,
target: &Target,
) -> bool {
match target {
Target::Placement(id) => view.nodes.iter().any(|n| n.id == *id),
Target::Port { port, placement } => view
.ports
.iter()
.any(|p| p.element == *port && p.owner == *placement),
Target::Edge(id) => view.edges.iter().any(|e| e.id == *id),
Target::StateRow {
placement,
relation,
} => crate::behavior::state_canvas::visible_row_target(
project, diagram, view, *placement, *relation,
),
_ => false,
}
}
impl App {
pub(crate) fn multiselect_boundary(&self) -> impl PartialEq + use<> {
(
self.canvas_document,
self.document.revision(),
self.page,
self.active_diagram,
self.selected,
self.selected_node,
(self.page == Page::Behavior).then(|| self.state_view_identity()),
(self.page == Page::Behavior).then_some(self.behavior.diagram.placement),
)
}
pub(crate) fn multiselect_context(&self) -> Option<Context> {
match self.page {
Page::Diagram => self.route_context().map(context),
Page::Behavior => {
let current = self.state_context()?;
crate::behavior::state_edit::validate_context(self.project(), current, current)
.ok()?;
Some(context(current))
}
_ => None,
}
}
pub(crate) fn multiselect_target_visible(&self, target: &Target) -> bool {
let Some(Context {
scope:
Scope {
surface: Surface::Saved(diagram),
..
},
..
}) = self.multiselect_context()
else {
return false;
};
let view = projection::project_view_with_index(
self.project(),
diagram,
self.document.view_index(),
);
visible(self.project(), diagram, &view, target)
}
pub(crate) fn multiselect_snapshot(&self) -> Option<Snapshot> {
self.diagram_selection
.as_ref()?
.snapshot(self.multiselect_context()?)
}
pub(crate) fn multiselect_envelope(&self, event: &Event) -> bool {
let Some(current) = self.multiselect_context() else {
return false;
};
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))
}
}
}
fn legacy_target(&self, diagram: Id, view: &projection::ProjectedView) -> Option<Target> {
let placement = if self.page == Page::Behavior {
self.behavior.diagram.placement
} else {
self.selected_node
};
if let Some(id) = placement
&& view.nodes.iter().any(|node| {
node.id == id && (node.element == self.selected || node.id == self.selected)
})
{
return Some(Target::Placement(id));
}
if self.page == Page::Behavior {
// Keep a row's exact occurrence while inspecting its relation.
// Its owner placement is never a node-inspection or Hide target.
if let Some(target @ Target::StateRow { relation, .. }) =
self.diagram_selection.as_ref().and_then(|s| s.primary())
&& *relation == self.selected
&& visible(self.project(), diagram, view, target)
{
return Some(target.clone());
}
if let Some(node) = view.nodes.iter().find(|node| {
crate::behavior::state_canvas::visible_row_target(
self.project(),
diagram,
view,
node.id,
self.selected,
)
}) {
return Some(Target::StateRow {
placement: node.id,
relation: self.selected,
});
}
}
if let Some(port) = view.ports.iter().find(|port| port.element == self.selected) {
return Some(Target::Port {
port: port.element,
placement: port.owner,
});
}
view.edges
.iter()
.any(|edge| edge.id == self.selected)
.then_some(Target::Edge(self.selected))
}
pub(crate) fn reconcile_multiselect(&mut self) {
let Some(current) = self.multiselect_context() else {
self.diagram_selection = None;
return;
};
let Surface::Saved(diagram) = current.scope.surface else {
return;
};
let view = projection::project_view_with_index(
self.project(),
diagram,
self.document.view_index(),
);
let legacy = self.legacy_target(diagram, &view);
let lost_primary = self
.diagram_selection
.as_ref()
.filter(|s| s.scope() == current.scope)
.and_then(|s| s.primary())
.is_some_and(|target| !visible(self.project(), diagram, &view, target));
let primary_placement = if self.page == Page::Behavior {
self.behavior.diagram.placement
} else {
self.selected_node
};
let held_primary = self
.diagram_selection
.as_ref()
.filter(|s| s.scope() == current.scope)
.and_then(|s| s.primary())
.is_some_and(|target| match target {
Target::Placement(id) => primary_placement == Some(*id),
Target::Port { port, .. } => self.selected == *port,
Target::Edge(id) => self.selected == *id,
Target::StateRow { relation, .. } => {
self.selected == *relation && primary_placement.is_none()
}
_ => false,
});
let project = self.document.project();
let selection = self
.diagram_selection
.get_or_insert_with(|| Selection::new(current.scope));
selection.reconcile(current.scope, |target| {
visible(project, diagram, &view, target)
});
// Navigation/property selection remains explicit. A removed exact target
// is never rebound through its semantic identity to a different placement.
if held_primary || lost_primary {
if selection.primary() != legacy.as_ref() {
self.inspect_multiselect_primary();
}
} else if selection.primary() != legacy.as_ref() {
if let Some(target) = legacy {
selection.replace(target, |target| visible(project, diagram, &view, target));
} else {
selection.clear();
}
}
}
fn inspect_multiselect_primary(&mut self) {
let diagram = self
.multiselect_context()
.and_then(|c| match c.scope.surface {
Surface::Saved(diagram) => Some(diagram),
_ => None,
});
let primary = self
.diagram_selection
.as_ref()
.and_then(|s| s.primary())
.cloned();
self.selected_node = None;
if self.page == Page::Behavior {
self.behavior.diagram.placement = None;
}
match primary {
Some(Target::Placement(id)) => {
if let Some(node) = diagram
.and_then(|d| self.project().diagrams.get(&d))
.and_then(|d| d.nodes.get(&id))
{
self.selected = node.element;
if self.page == Page::Behavior {
self.behavior.diagram.placement = Some(id);
} else {
self.selected_node = Some(id);
}
}
}
Some(Target::Port { port, .. }) => self.selected = port,
Some(Target::Edge(id)) => self.selected = id,
Some(Target::StateRow { relation, .. }) => self.selected = relation,
_ => self.selected = diagram.unwrap_or(self.project().id),
}
self.selected_bend = None;
self.selected_attachment = None;
self.refresh_draft();
}
pub(crate) fn multiselect_event(&mut self, event: Event) {
if !self.multiselect_envelope(&event) {
return;
}
if !diagram_removal::enabled(self)
|| self.architecture.is_some()
|| self.connection.is_some()
|| (self.page == Page::Behavior
&& self.behavior.diagram.tool != crate::behavior::state_edit::Tool::Select)
{
self.status =
"Finish or cancel the active edit before changing the diagram selection.".into();
return;
}
let current = self.multiselect_context().unwrap();
let Surface::Saved(diagram) = current.scope.surface else {
return;
};
let view = projection::project_view_with_index(
self.project(),
diagram,
self.document.view_index(),
);
match event {
Event::Collapse(_, target) => {
if !visible(self.project(), diagram, &view, &target) {
return;
}
let project = self.document.project();
self.diagram_selection
.as_mut()
.unwrap()
.replace(target, |target| visible(project, diagram, &view, target));
self.inspect_multiselect_primary();
}
Event::Choose(_, target, choice) => {
if !visible(self.project(), diagram, &view, &target) {
return;
}
self.reconcile_multiselect();
let project = self.document.project();
let selection = self.diagram_selection.as_mut().unwrap();
let valid = |target: &Target| visible(project, diagram, &view, target);
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_multiselect_primary();
}
Event::Clear(_) => {
if let Some(selection) = &mut self.diagram_selection {
selection.clear();
}
self.inspect_multiselect_primary();
}
Event::Refuse(_, reason) => self.status = reason,
Event::Move(snapshot, delta) => {
let Some(ids) = placements(&snapshot) else {
self.status = "Move requires only placed elements. Remove ports, rows and connections from the selection.".into();
return;
};
if !snapshot
.targets()
.iter()
.all(|target| visible(self.project(), diagram, &view, target))
{
return;
}
if self.project().diagrams[&diagram].projection == ProjectionKind::Allocation
&& ids.iter().any(|id| {
self.project().elements
[&self.project().diagrams[&diagram].nodes[id].element]
.kind()
.is_work()
})
{
self.status =
"Group allocation drag is not available yet. The selection was retained."
.into();
return;
}
if delta.x == 0. && delta.y == 0. {
return;
}
match oa_core::diagram_edit::translate_placements(
self.project(),
diagram,
&ids,
delta,
) {
Ok(command) => {
if self.execute(command) {
self.inspect_multiselect_primary();
self.status = format!(
"Moved {} selected elements · Undo restores the group",
ids.len()
);
}
}
Err(error) => self.status = error.to_string(),
}
}
Event::Hide(snapshot) => {
let Some(ids) = placements(&snapshot) else {
self.status =
"Hide requires only placed elements. Model objects remain unchanged."
.into();
return;
};
if !snapshot
.targets()
.iter()
.all(|target| visible(self.project(), diagram, &view, target))
{
return;
}
if self.execute(Command::Batch(
ids.iter().copied().map(Command::Delete).collect(),
)) {
if let Some(selection) = &mut self.diagram_selection {
selection.clear();
}
self.inspect_multiselect_primary();
self.status = format!("Hid {} placements · Model objects retained", ids.len());
}
}
}
}
}
@@ -0,0 +1,602 @@
//! Saved-view group operations through the real App message boundary.
use super::multiselect::{Choice as GroupChoice, Event as GroupEvent};
use super::*;
use crate::diagram_usage::Target;
fn point(x: f32, y: f32) -> Position {
Position { x, y }
}
struct Fixture {
app: App,
diagram: Id,
a: Id,
b: Id,
child: Id,
edge: Id,
}
fn fixture() -> Fixture {
let mut p = Project::empty();
let a = p
.add_element(Kind::Function, Layer::Sa, "Send", None)
.unwrap();
let b = p
.add_element(Kind::Function, Layer::Sa, "Receive", None)
.unwrap();
let child = p
.add_element(Kind::Function, Layer::Sa, "Prepare", Some(a))
.unwrap();
let edge = p.relate(RelationKind::FunctionalExchange, "Signal", a, b);
let diagram = p.ensure_diagram(Layer::Sa);
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::FunctionalDataflow;
let a = p.place(diagram, a, point(10., 20.));
let b = p.place(diagram, b, point(500., 20.));
let child = p.place(diagram, child, point(40., 100.));
p.diagrams
.get_mut(&diagram)
.unwrap()
.routes
.push(EdgeRoute {
edge,
source_attachment: Some(EdgeAttachment {
side: PortAnchorSide::Bottom,
offset: 0.3,
}),
target_attachment: Some(EdgeAttachment {
side: PortAnchorSide::Top,
offset: 0.7,
}),
waypoints: vec![point(370., 150.)],
label: Some(EdgeLabel {
fraction: 0.4,
offset: point(5., -9.),
}),
});
let other = p
.add_element(Kind::Activity, Layer::Oa, "Operational work", None)
.unwrap();
let other_diagram = p.ensure_diagram(Layer::Oa);
p.place(other_diagram, other, point(-50., -100.));
let mut app = App::with_project(p);
app.page = Page::Diagram;
app.layer = Layer::Sa;
app.active_diagram = Some(diagram);
app.selected = diagram;
app.selected_node = None;
app.refresh_draft();
app.reconcile_multiselect();
Fixture {
app,
diagram,
a,
b,
child,
edge,
}
}
fn dispatch(app: &mut App, event: GroupEvent) {
let _ = app.update(Message::DiagramSelection(event));
}
fn choose(app: &mut App, target: Target, choice: GroupChoice) {
let context = app.multiselect_context().unwrap();
dispatch(app, GroupEvent::Choose(context, target, choice));
}
fn select_pair(f: &mut Fixture) {
choose(&mut f.app, Target::Placement(f.a), GroupChoice::Replace);
choose(&mut f.app, Target::Placement(f.b), GroupChoice::Toggle);
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(f.a), Target::Placement(f.b)]
);
}
#[test]
fn queued_singleton_move_or_delete_cannot_partially_edit_a_new_group() {
for model in [false, true] {
let mut f = fixture();
select_pair(&mut f);
let before = f.app.document.snapshot();
let selected = f.app.multiselect_snapshot().unwrap();
let object = f.app.project().diagrams[&f.diagram].nodes[&f.b].element;
for message in [
Message::MoveNode(f.b, point(700., 600.)),
Message::DiagramRemove(super::diagram_removal::Intent {
context: f.app.route_context().unwrap(),
object,
placement: Some(f.b),
model,
}),
Message::Delete,
] {
let _ = f.app.update(message);
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
selected.targets()
);
assert!(!f.app.delete_pending);
assert!(!f.app.document.can_undo());
}
}
}
#[test]
fn legacy_hide_action_applies_to_the_complete_visible_group() {
let mut f = fixture();
select_pair(&mut f);
let before = f.app.document.snapshot();
let mut expected = f.app.project().clone();
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
view.nodes.remove(&f.a);
view.nodes.remove(&f.b);
let _ = f.app.update(Message::HideSelected);
assert_eq!(f.app.project(), &expected);
assert_source_matches_model(&f.app);
let _ = f.app.update(Message::Undo);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(!f.app.document.can_undo());
}
fn assert_source_matches_model(app: &App) {
let compiled = oa_core::source_project::compile_bundle(app.document.bundle(), LIMITS).unwrap();
assert_eq!(&compiled.decoded.project, app.project());
assert_eq!(&compiled.bundle, app.document.bundle());
}
#[test]
fn toggled_group_moves_model_and_source_once_and_keeps_primary_through_history() {
let mut f = fixture();
select_pair(&mut f);
let before = f.app.document.snapshot();
let snapshot = f.app.multiselect_snapshot().unwrap();
assert_eq!(snapshot.primary(), Some(&Target::Placement(f.b)));
let mut expected = f.app.project().clone();
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
view.nodes.get_mut(&f.a).unwrap().position = point(50., 80.);
view.nodes.get_mut(&f.b).unwrap().position = point(540., 80.);
view.nodes.get_mut(&f.child).unwrap().position = point(80., 160.);
view.routes[0].waypoints = vec![point(410., 210.)];
dispatch(
&mut f.app,
GroupEvent::Move(snapshot.clone(), point(40., 60.)),
);
assert_eq!(f.app.project(), &expected);
assert_source_matches_model(&f.app);
assert_eq!(f.app.selected_node, Some(f.b));
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
snapshot.targets()
);
let after = f.app.document.snapshot();
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());
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());
assert_eq!(f.app.selected_node, Some(f.b));
}
#[test]
fn ancestor_and_child_selection_moves_child_exactly_once() {
let mut f = fixture();
choose(&mut f.app, Target::Placement(f.a), GroupChoice::Replace);
choose(&mut f.app, Target::Placement(f.child), GroupChoice::Toggle);
let snapshot = f.app.multiselect_snapshot().unwrap();
assert_eq!(snapshot.targets().len(), 2);
let mut expected = f.app.project().clone();
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
view.nodes.get_mut(&f.a).unwrap().position = point(0., 45.);
view.nodes.get_mut(&f.child).unwrap().position = point(30., 125.);
dispatch(&mut f.app, GroupEvent::Move(snapshot, point(-10., 25.)));
assert_eq!(f.app.project(), &expected);
assert_eq!(f.app.selected_node, Some(f.child));
assert_source_matches_model(&f.app);
}
#[test]
fn mixed_edge_or_port_selection_refuses_the_entire_move() {
for include_port in [false, true] {
let mut f = fixture();
choose(&mut f.app, Target::Placement(f.a), GroupChoice::Replace);
let extra = if include_port {
let view = projection::project_view(f.app.project(), f.diagram);
let port = view
.ports
.iter()
.find(|p| p.owner == f.a)
.expect("functional exchange exposes its typed owner port");
Target::Port {
port: port.element,
placement: port.owner,
}
} else {
Target::Edge(f.edge)
};
choose(&mut f.app, extra.clone(), GroupChoice::Toggle);
let selection = f.app.multiselect_snapshot().unwrap();
assert_eq!(selection.targets(), &[Target::Placement(f.a), extra]);
let before = f.app.document.snapshot();
let revision = f.app.document.revision();
dispatch(
&mut f.app,
GroupEvent::Move(selection.clone(), point(40., 60.)),
);
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert_eq!(f.app.document.revision(), revision);
assert!(!f.app.document.can_undo());
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
selection.targets()
);
assert!(f.app.status.contains("Move requires only placed elements"));
}
}
#[test]
fn stale_operation_envelopes_have_no_selection_history_status_or_allocation_side_effects() {
// Isolate each lifetime component, including the same visible set recreated
// by a remove/re-add cycle. Accepted setup changes are outside the assertion.
for stale_by in ["epoch", "revision", "document", "selection generation"] {
for action in ["move", "hide", "refuse", "collapse"] {
let mut f = fixture();
select_pair(&mut f);
let stale = f.app.multiselect_snapshot().unwrap();
match stale_by {
"epoch" => f.app.canvas_epoch += 1,
"revision" => {
let semantic = f.app.project().diagrams[&f.diagram].nodes[&f.a].element;
// Advance only the document revision, retaining this canvas
// and selection epoch to independently test revision checking.
f.app
.document
.execute(Command::Describe(semantic, "New revision".into()))
.unwrap();
}
"document" => f.app.canvas_document = Id::new_v4(),
_ => {
choose(&mut f.app, Target::Placement(f.b), GroupChoice::Toggle);
choose(&mut f.app, Target::Placement(f.b), GroupChoice::Toggle);
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
stale.targets()
);
}
}
f.app.status = "Current feedback must survive".into();
f.app.allocation_drag.arrange_next = true;
let before = f.app.document.snapshot();
let selection = f.app.multiselect_snapshot();
let legacy = (f.app.selected, f.app.selected_node);
let revision = f.app.document.revision();
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());
let draft = f
.app
.draft
.as_ref()
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap());
let event = match action {
"move" => GroupEvent::Move(stale, point(99., 100.)),
"hide" => GroupEvent::Hide(stale),
"collapse" => GroupEvent::Collapse(stale, Target::Placement(f.a)),
_ => GroupEvent::Refuse(stale, "Obsolete refusal".into()),
};
dispatch(&mut f.app, event);
assert_eq!(
f.app.project(),
&before.decoded.project,
"{stale_by}/{action}"
);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert_eq!(f.app.document.revision(), revision);
assert_eq!(f.app.multiselect_snapshot(), selection);
assert_eq!((f.app.selected, f.app.selected_node), legacy);
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 feedback must survive");
assert!(f.app.allocation_drag.arrange_next);
assert_eq!(
f.app
.draft
.as_ref()
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap()),
draft
);
}
}
}
#[test]
fn pending_valid_and_invalid_property_drafts_refuse_group_edits_without_applying_them() {
for (path, value) in [("/name", "Unapplied name"), ("/id", "-")] {
for hide in [false, true] {
let mut f = fixture();
select_pair(&mut f);
let _ = f.app.update(Message::Field(path.into(), value.into()));
assert!(f.app.draft_dirty());
let snapshot = f.app.multiselect_snapshot().unwrap();
let before = f.app.document.snapshot();
let draft =
serde_json::to_value(f.app.draft.as_ref().unwrap().recovery_snapshot()).unwrap();
let event = if hide {
GroupEvent::Hide(snapshot.clone())
} else {
GroupEvent::Move(snapshot.clone(), point(20., 30.))
};
dispatch(&mut f.app, event);
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(!f.app.document.can_undo());
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
snapshot.targets()
);
assert_eq!(
serde_json::to_value(f.app.draft.as_ref().unwrap().recovery_snapshot()).unwrap(),
draft
);
assert!(f.app.status.contains("Finish or cancel"));
}
}
}
#[test]
fn hiding_a_group_removes_only_exact_placements_and_roundtrips_in_one_history_step() {
let mut f = fixture();
select_pair(&mut f);
let snapshot = f.app.multiselect_snapshot().unwrap();
let before = f.app.document.snapshot();
let mut expected = f.app.project().clone();
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
view.nodes.remove(&f.a);
view.nodes.remove(&f.b);
dispatch(&mut f.app, GroupEvent::Hide(snapshot));
assert_eq!(
f.app.project(),
&expected,
"engineering objects, descendant placement, authored route and opposite-layer view survive"
);
assert!(f.app.multiselect_snapshot().unwrap().targets().is_empty());
assert_source_matches_model(&f.app);
let after = f.app.document.snapshot();
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());
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());
}
fn assert_surviving_primary(f: &Fixture) {
let selection = f.app.multiselect_snapshot().unwrap();
assert_eq!(selection.targets(), &[Target::Placement(f.a)]);
assert_eq!(selection.primary(), Some(&Target::Placement(f.a)));
assert_eq!(f.app.selected_node, Some(f.a));
assert_eq!(
f.app.selected,
f.app.project().diagrams[&f.diagram].nodes[&f.a].element
);
}
#[test]
fn removing_primary_placement_from_model_preserves_exact_survivor_after_undo() {
let mut f = fixture();
select_pair(&mut f);
let before = f.app.document.snapshot();
let _ = f.app.update(Message::Command(Command::Delete(f.b)));
assert!(
!f.app.project().diagrams[&f.diagram]
.nodes
.contains_key(&f.b)
);
assert_surviving_primary(&f);
let _ = f.app.update(Message::Undo);
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert_surviving_primary(&f);
let _ = f.app.update(Message::Redo);
assert_surviving_primary(&f);
}
#[test]
fn deleting_primary_model_object_then_undo_does_not_restore_removed_selection_membership() {
let mut f = fixture();
select_pair(&mut f);
let before = f.app.document.snapshot();
let semantic = f.app.project().diagrams[&f.diagram].nodes[&f.b].element;
let _ = f.app.update(Message::Command(Command::Delete(semantic)));
assert!(!f.app.project().elements.contains_key(&semantic));
assert_surviving_primary(&f);
let _ = f.app.update(Message::Undo);
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert_surviving_primary(&f);
let _ = f.app.update(Message::Redo);
assert_surviving_primary(&f);
}
#[test]
fn replacing_primary_occurrence_with_same_semantic_placement_does_not_retarget_selection() {
let mut f = fixture();
select_pair(&mut f);
let mut candidate = f.app.project().clone();
let view = candidate.diagrams.get_mut(&f.diagram).unwrap();
let mut replacement = view.nodes.remove(&f.b).unwrap();
let replacement_id = Id::new_v4();
replacement.id = replacement_id;
replacement.alias = "replacement_receive".into();
replacement.position = point(800., 300.);
view.nodes.insert(replacement_id, replacement);
// Replace preserves the semantic inspector identity. Its normal sync used
// to rediscover the new occurrence through that identity and steal the set.
let _ = f
.app
.update(Message::Command(Command::Replace(candidate.clone())));
assert_eq!(f.app.project(), &candidate);
assert_surviving_primary(&f);
assert!(
!f.app
.multiselect_snapshot()
.unwrap()
.targets()
.contains(&Target::Placement(replacement_id))
);
assert_source_matches_model(&f.app);
let _ = f.app.update(Message::Undo);
assert!(
f.app.project().diagrams[&f.diagram]
.nodes
.contains_key(&f.b)
);
assert_surviving_primary(&f);
}
#[test]
fn explicit_surface_navigation_and_return_never_resurrect_the_group() {
for destination in [Page::Catalog, Page::Behavior] {
let mut f = fixture();
select_pair(&mut f);
let before = f.app.document.snapshot();
let stale = f.app.multiselect_snapshot().unwrap();
let _ = f.app.update(Message::Page(destination));
assert!(f.app.multiselect_snapshot().is_none());
let _ = f.app.update(Message::Page(Page::Diagram));
let live = f.app.multiselect_snapshot().unwrap();
assert!(
live.targets().len() <= 1,
"navigation may inspect one exact member but must not restore the group"
);
dispatch(&mut f.app, GroupEvent::Move(stale, point(400., 500.)));
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(!f.app.document.can_undo());
}
}
fn open_placement_menu(f: &mut Fixture, placement: Id) {
let semantic = f.app.project().diagrams[&f.diagram].nodes[&placement].element;
let mut request = crate::model_menu::Request::object(semantic, iced::Point::new(100., 100.));
request.placement = Some(placement);
request.canvas = f.app.route_context();
let _ = f
.app
.update(Message::Menu(crate::model_menu::Event::Open(request)));
assert!(f.app.model_menu.is_some());
}
fn menu_action(app: &App, caption: &str) -> Message {
crate::model_menu::popup(app)
.unwrap()
.entries
.into_iter()
.find_map(|entry| match entry {
crate::context_menu::Entry::Action { label, message, .. } if label == caption => {
message
}
_ => None,
})
.unwrap_or_else(|| panic!("enabled menu action {caption:?} must exist"))
}
#[test]
fn context_menu_dismissal_preserves_group_and_add_keeps_pre_menu_members() {
let mut f = fixture();
select_pair(&mut f);
let before = f.app.document.snapshot();
let selected = f.app.multiselect_snapshot().unwrap();
let child = f.child;
open_placement_menu(&mut f, child);
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
selected.targets()
);
assert_eq!(
f.app.multiselect_snapshot().unwrap().primary(),
selected.primary()
);
let _ = f.app.update(Message::Menu(crate::model_menu::Event::Close));
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
selected.targets()
);
assert_eq!(
f.app.multiselect_snapshot().unwrap().primary(),
selected.primary()
);
open_placement_menu(&mut f, child);
let add = menu_action(&f.app, "Add to selection");
let _ = f.app.update(add);
let selected = f.app.multiselect_snapshot().unwrap();
assert_eq!(
selected.targets(),
&[
Target::Placement(f.a),
Target::Placement(f.b),
Target::Placement(child)
]
);
assert_eq!(selected.primary(), Some(&Target::Placement(child)));
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(!f.app.document.can_undo());
}
#[test]
fn selected_member_context_menu_exposes_and_executes_group_hide_not_singleton_deletion() {
let mut f = fixture();
select_pair(&mut f);
let before = f.app.document.snapshot();
let member = f.a;
open_placement_menu(&mut f, member);
let popup = crate::model_menu::popup(&f.app).unwrap();
for entry in &popup.entries {
if let crate::context_menu::Entry::Action {
message: Some(Message::Menu(crate::model_menu::Event::Invoke(_, action))),
..
} = entry
{
assert!(
!matches!(
action.as_ref(),
Message::HideSelected | Message::Delete | Message::DiagramRemove(_)
),
"a selected-member group menu must not expose singleton removal"
);
}
}
let hide = menu_action(&f.app, "Hide selected placements");
let _ = f.app.update(hide);
let mut expected = before.decoded.project.clone();
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
view.nodes.remove(&f.a);
view.nodes.remove(&f.b);
assert_eq!(f.app.project(), &expected);
assert!(!f.app.delete_pending);
assert!(f.app.model_menu.is_none());
assert_source_matches_model(&f.app);
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());
}
@@ -53,6 +53,7 @@ async fn armed() -> (App, Mounted, Id) {
context,
object: relation,
placement: None,
selection_target: None,
anchor: iced::Point::new(450., 400.),
bend: None,
route_segment: None,
@@ -79,6 +79,7 @@ fn state_bend_menu_carries_exact_segment_and_pin_without_changing_delete_action(
context,
object: relation,
placement: None,
selection_target: None,
anchor: iced::Point::ORIGIN,
bend: Some(1),
route_segment: Some((2, point)),
@@ -115,6 +115,7 @@ impl App {
}
}
match event {
Event::Selection(event) => self.multiselect_event(event),
Event::Remove(intent) => self.remove_from_diagram(intent),
Event::Viewport(_, size) => {
if size.width.is_finite()
@@ -157,6 +158,7 @@ impl App {
context,
object,
placement,
selection_target,
anchor,
bend,
route_segment,
@@ -164,6 +166,7 @@ impl App {
let mut request = crate::model_menu::Request::object(object, anchor);
request.canvas = Some(context);
request.placement = placement;
request.selection_target = selection_target.map(Box::new);
request.bend = bend;
request.route_segment = route_segment;
return self.handle(Message::Menu(crate::model_menu::Event::Open(request)));
@@ -0,0 +1,374 @@
//! State selection layout and modifier admission on the mounted production App.
use super::*;
use crate::behavior::{
canvas_workspace::tests::{Mounted, key},
state_edit,
};
use crate::diagram_usage::Target;
use iced::advanced::widget::{Operation, operation};
use iced::{Point, Rectangle, Size, Vector, keyboard, mouse};
struct Fixture {
app: App,
diagram: Id,
a: Id,
b: Id,
a_element: Id,
b_element: Id,
edge: Id,
action: Id,
}
fn fixture() -> Fixture {
let mut p = Project::empty();
let machine = p
.add_element(Kind::StateMachine, Layer::Oa, "Operating modes", None)
.unwrap();
let region = p
.add_element(Kind::Region, Layer::Oa, "Main region", Some(machine))
.unwrap();
let a_element = p
.add_element(Kind::State, Layer::Oa, "First state", Some(region))
.unwrap();
let b_element = p
.add_element(
Kind::State,
Layer::Oa,
&format!("Second state {}", "with a long primary name ".repeat(20)),
Some(region),
)
.unwrap();
let work = p
.add_element(Kind::Activity, Layer::Oa, "Reusable work", None)
.unwrap();
let action = p.relate(RelationKind::StateAction, "On entry", a_element, work);
let edge = p.relate(
RelationKind::StateTransition,
"Next state",
a_element,
b_element,
);
let diagram = p.ensure_diagram(Layer::Oa);
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::StateMachine { machine };
let mut placements = vec![];
// All State elements, including machine/Region, are initially placed.
// A fixture already missing its containers would not test picker insertion.
for (element, x, y, width, height) in [
(machine, 0., 0., 800., 500.),
(region, 20., 70., 760., 410.),
(a_element, 60., 160., 230., 180.),
(b_element, 430., 160., 260., 180.),
] {
let node = p.place(diagram, element, Position { x, y });
p.diagrams
.get_mut(&diagram)
.unwrap()
.nodes
.get_mut(&node)
.unwrap()
.size = oa_core::Size { width, height };
placements.push(node);
}
let a = placements[2];
let b = placements[3];
validate_candidate(&p).unwrap();
assert!(state_edit::unplaced(&p, diagram).is_empty());
let mut app = App::with_project(p);
app.page = Page::Behavior;
app.layer = Layer::Oa;
app.behavior.active_owner = Some(machine);
app.behavior.diagram = crate::behavior::state_view::State {
diagram: Some(diagram),
fit: true,
..Default::default()
};
app.selected = diagram;
app.selected_node = None;
app.window_size = Size::new(1442., 932.);
app.refresh_draft();
app.reconcile_multiselect();
assert_eq!(app.state_context().unwrap().diagram, diagram);
Fixture {
app,
diagram,
a,
b,
a_element,
b_element,
edge,
action,
}
}
fn owner(mounted: &mut Mounted, app: &App) -> (Rectangle, bool) {
let geometry = mounted.geometry(app);
let (_, bounds, focused) = geometry
.focused
.into_iter()
.find(|(id, _, _)| {
id.as_ref() == Some(&iced::advanced::widget::Id::from("diagram-keyboard-owner"))
})
.expect("real State focus::Owner rectangle must be measurable");
(bounds, focused)
}
fn camera(app: &App) -> (f32, Vector, bool, Option<Size>) {
let state = &app.behavior.diagram;
(state.zoom, state.pan, state.fit, state.viewport)
}
async fn selection(mounted: &mut Mounted, app: &mut App, target: Option<Target>) {
let context = app.multiselect_context().unwrap();
let event = match target {
Some(target) => multiselect::Event::Choose(context, target, multiselect::Choice::Toggle),
None => multiselect::Event::Clear(context),
};
let task = app.update(Message::DiagramSelection(event));
mounted.perform(app, task).await;
mounted.settle(app).await;
}
fn node_point(mounted: &mut Mounted, f: &Fixture, placement: Id) -> Point {
let bounds = owner(mounted, &f.app).0;
let node = &f.app.project().diagrams[&f.diagram].nodes[&placement];
let state = &f.app.behavior.diagram;
Point::new(
bounds.x + (node.position.x + 40.) * state.zoom + state.pan.x,
bounds.y + (node.position.y + 25.) * state.zoom + state.pan.y,
)
}
fn modifiers(shift: bool) -> iced::Event {
iced::Event::Keyboard(keyboard::Event::ModifiersChanged(if shift {
keyboard::Modifiers::SHIFT
} else {
keyboard::Modifiers::default()
}))
}
struct FocusField(Rectangle);
impl Operation for FocusField {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn Operation)) {
visit(self);
}
fn focusable(
&mut self,
_: Option<&iced::advanced::widget::Id>,
bounds: Rectangle,
state: &mut dyn operation::Focusable,
) {
if bounds == self.0 {
state.focus();
} else {
state.unfocus();
}
}
}
#[tokio::test]
async fn mounted_state_selection_and_missing_picker_never_resize_or_refit_the_canvas() {
let mut f = fixture();
let mut mounted = Mounted::new(&mut f.app).await;
let baseline = f.app.document.snapshot();
let bounds = owner(&mut mounted, &f.app).0;
let fitted = camera(&f.app);
assert!(
fitted.2,
"keep Fit active to expose any resize-triggered camera jump"
);
assert!(fitted.3.is_some());
assert!(bounds.width > 400. && bounds.height > 200.);
assert!(state_edit::unplaced(f.app.project(), f.diagram).is_empty());
assert!(f.app.multiselect_snapshot().unwrap().targets().is_empty());
for (target, expected) in [
(Some(Target::Placement(f.a)), vec![Target::Placement(f.a)]),
(
Some(Target::Placement(f.b)),
vec![Target::Placement(f.a), Target::Placement(f.b)],
),
(
Some(Target::Edge(f.edge)),
vec![
Target::Placement(f.a),
Target::Placement(f.b),
Target::Edge(f.edge),
],
),
(
Some(Target::Edge(f.edge)),
vec![Target::Placement(f.a), Target::Placement(f.b)],
),
(
Some(Target::StateRow {
placement: f.a,
relation: f.action,
}),
vec![
Target::Placement(f.a),
Target::Placement(f.b),
Target::StateRow {
placement: f.a,
relation: f.action,
},
],
),
(None, vec![]),
] {
selection(&mut mounted, &mut f.app, target).await;
assert_eq!(f.app.multiselect_snapshot().unwrap().targets(), expected);
assert_eq!(
owner(&mut mounted, &f.app).0,
bounds,
"selection strip changed the measured State canvas rectangle"
);
assert_eq!(
camera(&f.app),
fitted,
"selection feedback silently refitted the camera"
);
assert_eq!(f.app.project(), &baseline.decoded.project);
assert_eq!(f.app.document.bundle(), &baseline.bundle);
assert!(!f.app.document.can_undo());
assert!(!f.app.draft_dirty());
}
selection(&mut mounted, &mut f.app, Some(Target::Placement(f.a))).await;
selection(&mut mounted, &mut f.app, Some(Target::Placement(f.b))).await;
let captured = f.app.multiselect_snapshot().unwrap();
let task = f
.app
.update(Message::DiagramSelection(multiselect::Event::Hide(
captured,
)));
mounted.perform(&mut f.app, task).await;
mounted.settle(&mut f.app).await;
let missing: std::collections::BTreeSet<_> = state_edit::unplaced(f.app.project(), f.diagram)
.into_iter()
.collect();
assert_eq!(
missing,
std::collections::BTreeSet::from([f.a_element, f.b_element])
);
let mut expected = baseline.decoded.project.clone();
expected
.diagrams
.get_mut(&f.diagram)
.unwrap()
.nodes
.remove(&f.a);
expected
.diagrams
.get_mut(&f.diagram)
.unwrap()
.nodes
.remove(&f.b);
assert_eq!(f.app.project(), &expected);
assert_eq!(
owner(&mut mounted, &f.app).0,
bounds,
"the first unplaced picker changed canvas bounds"
);
assert_eq!(camera(&f.app), fitted);
let hidden_source = f.app.document.bundle().clone();
let task = f.app.update(Message::Undo);
mounted.perform(&mut f.app, task).await;
mounted.settle(&mut f.app).await;
assert!(state_edit::unplaced(f.app.project(), f.diagram).is_empty());
assert_eq!(f.app.project(), &baseline.decoded.project);
assert_eq!(f.app.document.bundle(), &baseline.bundle);
assert!(!f.app.document.can_undo());
assert_eq!(
owner(&mut mounted, &f.app).0,
bounds,
"removing the unplaced picker changed canvas bounds"
);
assert_eq!(camera(&f.app), fitted);
let task = f.app.update(Message::Redo);
mounted.perform(&mut f.app, task).await;
mounted.settle(&mut f.app).await;
assert_eq!(f.app.project(), &expected);
assert_eq!(f.app.document.bundle(), &hidden_source);
assert_eq!(owner(&mut mounted, &f.app).0, bounds);
assert_eq!(camera(&f.app), fitted);
}
#[tokio::test]
async fn mounted_state_shift_held_in_clean_inspector_toggles_on_first_canvas_press() {
let mut f = fixture();
let mut mounted = Mounted::new(&mut f.app).await;
selection(&mut mounted, &mut f.app, Some(Target::Placement(f.a))).await;
let field = mounted
.geometry(&f.app)
.text_inputs
.into_iter()
.filter(|bounds| bounds.x > f.app.window_size.width - 320.)
.min_by(|a, b| a.y.total_cmp(&b.y))
.expect("State Inspector field is mounted");
mounted.operate(&f.app, &mut FocusField(field));
assert!(!owner(&mut mounted, &f.app).1);
let before = f.app.document.snapshot();
mounted
.batch(&mut f.app, &[modifiers(true)], mouse::Cursor::Unavailable)
.await;
assert!(
!owner(&mut mounted, &f.app).1,
"passive Shift must not acquire State canvas focus"
);
let at = node_point(&mut mounted, &f, f.b);
let messages = mounted.click(&mut f.app, at).await;
assert!(messages.iter().any(|message| matches!(message,
Message::DiagramSelection(multiselect::Event::Choose(_, Target::Placement(id), multiselect::Choice::Toggle)) if *id == f.b
)), "StateCanvas must map its typed selection event to the common App boundary");
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(f.a), Target::Placement(f.b)]
);
assert_eq!(f.app.behavior.diagram.placement, Some(f.b));
assert_eq!(f.app.selected_node, None);
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(!f.app.document.can_undo());
assert!(!f.app.draft_dirty());
}
#[tokio::test]
async fn mounted_state_busy_suspension_tracks_shift_without_granting_focus_or_commands() {
let mut f = fixture();
let mut mounted = Mounted::new(&mut f.app).await;
selection(&mut mounted, &mut f.app, Some(Target::Placement(f.a))).await;
// Explicitly revoke focus rather than relying on incidental initial focus.
mounted.operate(
&f.app,
&mut FocusField(Rectangle {
x: -1000.,
y: -1000.,
width: 1.,
height: 1.,
}),
);
let before = f.app.document.snapshot();
let at = node_point(&mut mounted, &f, f.b);
f.app.busy = true;
mounted.settle(&mut f.app).await;
mounted
.batch(
&mut f.app,
&[modifiers(true), key(keyboard::key::Named::Delete)],
mouse::Cursor::Unavailable,
)
.await;
mounted.click(&mut f.app, at).await;
assert!(!owner(&mut mounted, &f.app).1);
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(f.a)]
);
assert_eq!(f.app.document.bundle(), &before.bundle);
f.app.busy = false;
mounted.settle(&mut f.app).await;
assert!(!owner(&mut mounted, &f.app).1);
// No second modifier event: the passive suspended update must survive.
mounted.click(&mut f.app, at).await;
assert_eq!(
f.app.multiselect_snapshot().unwrap().targets(),
&[Target::Placement(f.a), Target::Placement(f.b)]
);
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(!f.app.document.can_undo());
assert!(!f.app.delete_pending);
}
File diff suppressed because it is too large Load Diff
@@ -391,7 +391,7 @@ fn state_bends_context_menu_distinguishes_authored_pin_from_computed_segment() {
motion(&canvas, &mut state, pin, pin);
assert!(
matches!(input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Right), pin),
Some(Event::ContextMenu { context, object, placement: None, anchor, bend: Some(0), route_segment: None })
Some(Event::ContextMenu { context, object, placement: None, anchor, bend: Some(0), route_segment: None, .. })
if context == canvas.context && object == relation && anchor == pin)
);
let (index, midpoint) = bend_segment(&scene, relation);
@@ -399,7 +399,7 @@ fn state_bends_context_menu_distinguishes_authored_pin_from_computed_segment() {
motion(&canvas, &mut state, at, at);
assert!(
matches!(input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Right), at),
Some(Event::ContextMenu { context, object, placement: None, anchor, bend: None, route_segment: Some((segment, world)) })
Some(Event::ContextMenu { context, object, placement: None, anchor, bend: None, route_segment: Some((segment, world)), .. })
if context == canvas.context && object == relation && anchor == at && segment == index && point(world).distance(midpoint) < 0.001)
);
}
+473 -27
View File
@@ -1,5 +1,11 @@
//! Persisted state-diagram geometry with context-bound, ordered pointer gestures.
use super::state_edit::{self, Context, Endpoint, Event, Tool};
use crate::app::multiselect::{Choice, Event as SelectionEvent, context as selection_context};
use crate::diagram::group_gesture::{
DisplacementPolicy, Gesture as GroupGesture, Outcome, Viewport,
};
use crate::diagram_selection::{Selection, Snapshot};
use crate::diagram_usage::Target;
use crate::style;
use iced::{
Color, Point, Rectangle, Renderer, Size, Theme, Vector, keyboard, mouse,
@@ -27,6 +33,7 @@ pub struct StateCanvas<'a> {
pub diagram: Id,
pub context: Context,
pub selected: Id,
pub selection: Option<&'a Selection>,
/// Presentation-only navigation marker; never an authoring placement.
pub navigation_focus: Option<Rectangle>,
pub tool: Tool,
@@ -41,6 +48,8 @@ pub struct State {
tool: Option<Tool>,
pointer: Option<Point>,
press: Option<Press>,
group: Option<GroupPress>,
modifiers: keyboard::Modifiers,
source: Option<Id>,
preview: Option<(Id, Position)>,
attachment_preview: Option<AttachmentPreview>,
@@ -113,6 +122,7 @@ struct Scene {
}
struct CachedScene {
context: Context,
group_preview: Option<(Snapshot, Position)>,
preview: Option<(Id, Position)>,
attachment_preview: Option<AttachmentPreview>,
bend_preview: Option<EdgeRoute>,
@@ -121,6 +131,8 @@ struct CachedScene {
#[derive(PartialEq)]
struct PaintKey {
context: Context,
group_preview: Option<(Snapshot, Position)>,
selection: Option<Snapshot>,
preview: Option<(Id, Position)>,
attachment_preview: Option<AttachmentPreview>,
bend_preview: Option<EdgeRoute>,
@@ -132,12 +144,82 @@ struct PaintKey {
enum Hit {
Node { placement: Id, element: Id },
Transition(Id),
StateAction(Id),
Row { placement: Id, relation: Id },
}
impl Hit {
fn target(self) -> Target {
match self {
Self::Node { placement, .. } => Target::Placement(placement),
Self::Transition(id) => Target::Edge(id),
Self::Row {
placement,
relation,
} => Target::StateRow {
placement,
relation,
},
}
}
}
/// Unsupported mixtures retain the same click/cancel lifecycle as placement groups.
struct GroupPress {
snapshot: Snapshot,
target: Target,
start: Point,
viewport: Viewport,
movement: Option<GroupGesture>,
crossed: bool,
retired: bool,
}
impl GroupPress {
fn move_to(&mut self, pointer: Point) {
if self.retired {
return;
}
if !pointer.x.is_finite()
|| !pointer.y.is_finite()
|| !self.viewport.bounds.contains(pointer)
{
self.retired = true;
return;
}
self.crossed |= pointer.distance(self.start) > 3.;
if let Some(movement) = &mut self.movement
&& !movement.move_to(pointer)
{
self.retired = true;
}
}
fn release(mut self, pointer: Point) -> Option<SelectionEvent> {
self.move_to(pointer);
if self.retired {
return None;
}
if !self.crossed {
return Some(SelectionEvent::Collapse(self.snapshot, self.target));
}
let Some(movement) = self.movement else {
return Some(SelectionEvent::Refuse(self.snapshot,
"Move requires only placed elements. Remove rows, ports and transitions from the selection.".into()));
};
match movement.release(pointer)? {
Outcome::Click(id) => Some(SelectionEvent::Collapse(
self.snapshot,
Target::Placement(id),
)),
Outcome::Move(snapshot, delta) => Some(SelectionEvent::Move(snapshot, delta)),
}
}
}
impl State {
fn cancel_edit(&mut self) {
self.press = None;
self.group = None;
self.preview = None;
self.attachment_preview = None;
self.bend = None;
@@ -485,6 +567,32 @@ pub(crate) fn visible_row_relation(
})
}
/// Validate this occurrence, including the relation's current source. A surviving
/// relation reassigned to another State must not rebound an old row selection.
pub(crate) fn visible_row_target(
project: &Project,
diagram: Id,
view: &ProjectedView,
placement: Id,
relation: Id,
) -> bool {
visible_row_relation(project, diagram, view, relation)
&& view
.nodes
.iter()
.find(|node| node.id == placement)
.is_some_and(|node| {
project
.relations
.get(&relation)
.is_some_and(|row| row.source() == node.element)
&& state_action_rows(project, node)
.into_iter()
.chain(internal_rows(project, node))
.any(|(row, _)| row.id == relation)
})
}
fn state_action_label(project: &Project, relation: &Relation) -> String {
let RelationBody::StateAction { target, phase, .. } = relation.body else {
return String::new();
@@ -663,6 +771,210 @@ pub(crate) fn diagram_usages(
}
impl StateCanvas<'_> {
fn current_selection(&self) -> Option<&Selection> {
self.selection
.filter(|s| s.scope() == selection_context(self.context).scope)
}
fn group_viewport(&self, bounds: Rectangle) -> Viewport {
Viewport {
zoom: self.scale(),
pan: self.pan,
bounds: Rectangle::new(
Point::new(bounds.x, bounds.y + GUIDANCE_HEIGHT),
Self::content(bounds).size(),
),
}
}
fn group_current(&self, group: &GroupPress, bounds: Option<Rectangle>) -> bool {
!group.retired
&& self.editable
&& self.tool == Tool::Select
&& group.viewport.zoom == self.scale()
&& group.viewport.pan == self.pan
&& bounds.is_none_or(|b| group.viewport == self.group_viewport(b))
&& self
.current_selection()
.is_some_and(|s| s.matches(&group.snapshot, selection_context(self.context)))
}
fn group_preview_key(
&self,
state: &State,
bounds: Option<Rectangle>,
) -> Option<(Snapshot, Position)> {
let group = state.group.as_ref()?;
if !self.group_current(group, bounds) || !group.crossed {
return None;
}
Some((group.snapshot.clone(), group.movement.as_ref()?.delta()))
}
fn group_input(
&self,
state: &mut State,
event: &canvas::Event,
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Option<Action<Event>> {
if let Some(group) = &state.group {
let cancelled = matches!(
event,
canvas::Event::Mouse(
mouse::Event::CursorLeft
| mouse::Event::WheelScrolled { .. }
| mouse::Event::ButtonPressed(mouse::Button::Right | mouse::Button::Middle)
) | canvas::Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(keyboard::key::Named::Escape),
..
})
);
if !self.group_current(group, Some(bounds)) || cancelled {
state.cancel_edit();
return Some(Action::request_redraw().and_capture());
}
}
if let Some(group) = &mut state.group {
match event {
canvas::Event::Mouse(mouse::Event::CursorMoved { position }) => {
group.move_to(*position);
return Some(Action::request_redraw().and_capture());
}
canvas::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
let group = state.group.take().unwrap();
return Some(
cursor
.position()
.and_then(|p| group.release(p))
.map_or_else(
|| Action::request_redraw().and_capture(),
|event| Action::publish(Event::Selection(event)).and_capture(),
),
);
}
canvas::Event::Keyboard(_)
| canvas::Event::Mouse(mouse::Event::ButtonPressed(_)) => {
return Some(Action::capture());
}
_ => {}
}
}
let selection = self.current_selection()?;
if !self.editable || self.tool != Tool::Select || state.pan_from.is_some() {
return None;
}
if let canvas::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event {
use keyboard::{Key, key::Named};
if *key == Key::Named(Named::Escape) && state.press.is_none() && state.source.is_none()
{
return Some(
Action::publish(Event::Selection(SelectionEvent::Clear(selection_context(
self.context,
))))
.and_capture(),
);
}
if selection.targets().len() > 1 && *key == Key::Named(Named::Delete) {
let snapshot = selection.snapshot(selection_context(self.context))?;
let event = if modifiers.is_empty()
&& crate::app::multiselect::placements(&snapshot).is_some()
{
SelectionEvent::Hide(snapshot)
} else {
SelectionEvent::Refuse(snapshot, if modifiers.is_empty() {
"Hide requires only placed elements. Rows, ports and transitions cannot be hidden as a placement group."
} else {
"Group model deletion requires an aggregate impact review and is not available yet. Use Hide selected for placements."
}.into())
};
return Some(Action::publish(Event::Selection(event)).and_capture());
}
}
if !matches!(
event,
canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
) {
return None;
}
let window = cursor
.position()
.filter(|p| self.group_viewport(bounds).bounds.contains(*p))?;
let local = Point::new(window.x - bounds.x, window.y - bounds.y);
let scene = self.scene(state)?;
let world = self.world(local);
// Route handles belong to the exact edge, including when an endpoint
// overlaps a node. They cannot bypass Shift/group admission.
let handle = self
.endpoint_at(&scene, world)
.map(|(id, _)| Target::Edge(id))
.or_else(|| {
self.bend_at(&scene, world)
.map(|_| Target::Edge(self.selected))
});
let target = handle.or_else(|| self.hit(&scene, world).map(Hit::target))?;
if state.modifiers.shift() {
state.cancel_edit();
return Some(
Action::publish(Event::Selection(SelectionEvent::Choose(
selection_context(self.context),
target,
Choice::Toggle,
)))
.and_capture(),
);
}
if selection.targets().len() <= 1 || !selection.contains(&target) {
return None;
}
let snapshot = selection.snapshot(selection_context(self.context))?;
let viewport = self.group_viewport(bounds);
let movement = if crate::app::multiselect::placements(&snapshot).is_some()
&& let Target::Placement(anchor) = target
{
let original = self
.project
.diagrams
.get(&self.diagram)?
.nodes
.get(&anchor)?
.position;
Some(GroupGesture::new_with_policy(
snapshot.clone(),
anchor,
original,
window,
viewport,
DisplacementPolicy::Unsnapped,
)?)
} else {
None
};
state.cancel_edit();
state.group = Some(GroupPress {
snapshot,
target,
start: window,
viewport,
movement,
crossed: false,
retired: false,
});
Some(Action::request_redraw().and_capture())
}
fn select_event(&self, hit: Hit, semantic: Id) -> Event {
if self.current_selection().is_some() {
Event::Selection(SelectionEvent::Choose(
selection_context(self.context),
hit.target(),
Choice::Replace,
))
} else {
Event::Select(self.context, semantic)
}
}
fn scale(&self) -> f32 {
if self.zoom.is_finite() {
self.zoom.clamp(0.0001, 3.)
@@ -695,6 +1007,7 @@ impl StateCanvas<'_> {
return None;
}
let route_active = self.gesture_active(state) && self.route_viewport_current(state, bounds);
let group_preview = self.group_preview_key(state, bounds);
let preview = self
.gesture_active(state)
.then_some(state.preview)
@@ -703,6 +1016,7 @@ impl StateCanvas<'_> {
let bend_preview = route_active.then(|| state.bend_preview.clone()).flatten();
if let Some(cached) = state.scene.borrow().as_ref()
&& cached.context == self.context
&& cached.group_preview == group_preview
&& cached.preview == preview
&& cached.attachment_preview == attachment_preview
&& cached.bend_preview == bend_preview
@@ -710,6 +1024,27 @@ impl StateCanvas<'_> {
return Some(cached.scene.clone());
}
let mut diagram = self.project.diagrams.get(&self.diagram)?.clone();
if let Some((snapshot, delta)) = &group_preview
&& let Some(ids) = crate::app::multiselect::placements(snapshot)
&& let Ok(Command::Batch(commands)) = oa_core::diagram_edit::translate_placements(
self.project,
self.diagram,
&ids,
*delta,
)
{
for command in commands {
match command {
Command::EditNode { node, .. } => {
diagram.nodes.insert(node.id, node);
}
Command::SetEdgeRoute { route, .. } => {
crate::route_edit::with_route(&mut diagram, route)
}
_ => unreachable!("placement planner returned a non-geometry command"),
}
}
}
if let Some(route) = &bend_preview {
crate::route_edit::with_route(&mut diagram, route.clone());
}
@@ -761,6 +1096,7 @@ impl StateCanvas<'_> {
});
*state.scene.borrow_mut() = Some(CachedScene {
context: self.context,
group_preview,
preview,
attachment_preview,
bend_preview,
@@ -823,13 +1159,19 @@ impl StateCanvas<'_> {
.into_iter()
.find(|(_, r)| r.contains(world))
{
return Some(Hit::StateAction(relation.id));
return Some(Hit::Row {
placement: node.id,
relation: relation.id,
});
}
if let Some((relation, _)) = internal_rows(self.project, node)
.into_iter()
.find(|(_, r)| r.contains(world))
{
return Some(Hit::Transition(relation.id));
return Some(Hit::Row {
placement: node.id,
relation: relation.id,
});
}
let container = self
.project
@@ -1148,7 +1490,13 @@ impl StateCanvas<'_> {
},
_ => match world.and_then(|p| self.hit(scene, p)) {
Some(Hit::Transition(id)) => self.project.relations.get(&id).map(|r| format!("{} · {} · right-click to edit", r.name, routing::state_transition_summary(self.project, r))).unwrap_or_default(),
Some(Hit::StateAction(id)) => self.project.relations.get(&id).map(|r| format!("{} · select the action link to inspect its referenced work", state_action_label(self.project, r))).unwrap_or_default(),
Some(Hit::Row { relation: id, .. }) => self.project.relations.get(&id).map(|r| {
if matches!(r.body, RelationBody::StateAction { .. }) {
format!("{} · select the action link to inspect its referenced work", state_action_label(self.project, r))
} else {
format!("{} · {} · right-click to edit", r.name, routing::state_transition_summary(self.project, r))
}
}).unwrap_or_default(),
_ => "Select / move · drag a vertex · drag selected transition endpoints to reconnect · middle-drag to pan".into(),
},
}
@@ -1172,6 +1520,15 @@ impl canvas::Program<Event> for StateCanvas<'_> {
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Option<Action<Event>> {
if let canvas::Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) = event {
// Passive observation must not capture the event or grant focus.
state.modifiers = *modifiers;
return None;
}
let retired_group = state.group.is_some()
&& (state.context != Some(self.context)
|| state.tool != Some(self.tool)
|| !self.editable);
if state.context != Some(self.context) || state.tool != Some(self.tool) {
if state.context != Some(self.context) {
state.viewport = None;
@@ -1226,6 +1583,7 @@ impl canvas::Program<Event> for StateCanvas<'_> {
cursor
}
canvas::Event::Window(iced::window::Event::Unfocused) => {
state.modifiers = keyboard::Modifiers::default();
state.reset();
return None;
}
@@ -1239,6 +1597,14 @@ impl canvas::Program<Event> for StateCanvas<'_> {
let window = cursor.position();
let local = window.map(|p| Point::new(p.x - bounds.x, p.y - bounds.y));
let inside = local.is_some_and(|p| Self::content(bounds).contains(p));
if retired_group {
// The event which retired a held gesture cannot be reinterpreted as
// a fresh keyboard edit against the surviving selection.
return Some(Action::request_redraw().and_capture());
}
if let Some(action) = self.group_input(state, event, bounds, cursor) {
return Some(action);
}
if let canvas::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event {
use keyboard::{Key, key::Named};
if *key == Key::Named(Named::Escape) {
@@ -1310,13 +1676,17 @@ impl canvas::Program<Event> for StateCanvas<'_> {
// Menu commands must target the committed route instead.
let scene = self.scene(state)?;
let bend = self.bend_at(&scene, world);
let (object, placement) = if bend.is_some() {
(self.selected, None)
let (object, placement, selection_target) = if bend.is_some() {
(self.selected, None, Some(Target::Edge(self.selected)))
} else {
match self.hit(&scene, world) {
Some(Hit::Node { element, placement }) => (element, Some(placement)),
Some(Hit::Transition(id) | Hit::StateAction(id)) => (id, None),
None => (self.diagram, None),
Some(hit @ Hit::Node { element, placement }) => {
(element, Some(placement), Some(hit.target()))
}
Some(hit @ (Hit::Transition(id) | Hit::Row { relation: id, .. })) => {
(id, None, Some(hit.target()))
}
None => (self.diagram, None, None),
}
};
let route_segment = if bend.is_none() {
@@ -1329,6 +1699,7 @@ impl canvas::Program<Event> for StateCanvas<'_> {
context: self.context,
object,
placement,
selection_target,
anchor: window,
bend,
route_segment,
@@ -1336,12 +1707,17 @@ impl canvas::Program<Event> for StateCanvas<'_> {
.and_capture(),
);
}
if *button != mouse::Button::Left || !self.editable {
if *button != mouse::Button::Left || !self.editable || state.pan_from.is_some() {
return None;
}
match self.tool {
Tool::Select => {
if let Some((relation, endpoint)) = self.endpoint_at(&scene, world) {
let singleton = self
.current_selection()
.is_none_or(|s| s.targets().len() <= 1);
if singleton
&& let Some((relation, endpoint)) = self.endpoint_at(&scene, world)
{
state.press = Some(Press::Reconnect {
relation,
endpoint,
@@ -1349,7 +1725,7 @@ impl canvas::Program<Event> for StateCanvas<'_> {
});
return Some(Action::capture());
}
if let Some(index) = self.bend_at(&scene, world) {
if singleton && let Some(index) = self.bend_at(&scene, world) {
let route = crate::route_edit::stored_route(
&self.project.diagrams[&self.diagram],
self.selected,
@@ -1358,7 +1734,7 @@ impl canvas::Program<Event> for StateCanvas<'_> {
return Some(Action::capture());
}
match self.hit(&scene, world) {
Some(Hit::Node { placement, element }) => {
Some(hit @ Hit::Node { placement, element }) => {
let original = self
.project
.diagrams
@@ -1371,13 +1747,11 @@ impl canvas::Program<Event> for StateCanvas<'_> {
start: window,
original,
});
Some(
Action::publish(Event::Select(self.context, element))
.and_capture(),
)
Some(Action::publish(self.select_event(hit, element)).and_capture())
}
Some(Hit::Transition(id) | Hit::StateAction(id)) => {
if id == self.selected
Some(hit @ (Hit::Transition(id) | Hit::Row { relation: id, .. })) => {
if singleton
&& id == self.selected
&& let Some(edge) = scene.routed.edges.get(&id)
&& !Rectangle::new(
point(edge.label.bounds.position),
@@ -1407,7 +1781,7 @@ impl canvas::Program<Event> for StateCanvas<'_> {
return Some(Action::capture());
}
}
Some(Action::publish(Event::Select(self.context, id)).and_capture())
Some(Action::publish(self.select_event(hit, id)).and_capture())
}
None => {
state.pan_from = Some((mouse::Button::Left, window));
@@ -1643,6 +2017,10 @@ impl canvas::Program<Event> for StateCanvas<'_> {
self.gesture_active(state) && self.route_viewport_current(state, Some(bounds));
let key = PaintKey {
context: self.context,
group_preview: self.group_preview_key(state, Some(bounds)),
selection: self
.current_selection()
.and_then(|s| s.snapshot(selection_context(self.context))),
preview: self
.gesture_active(state)
.then_some(state.preview)
@@ -1671,23 +2049,40 @@ impl canvas::Program<Event> for StateCanvas<'_> {
frame.translate(self.offset());
frame.scale(self.scale());
for node in &scene.view.nodes {
let selected =
self.current_selection()
.map_or(self.selected, |s| match s.primary() {
Some(Target::Placement(id)) if *id == node.id => node.element,
Some(Target::StateRow {
placement,
relation,
}) if *placement == node.id => *relation,
_ => Id::nil(),
});
paint_node(
frame,
self.project,
node,
self.selected,
selected,
scene.symbol_labels.get(&node.id),
);
}
// Containers are already painted. Route bodies have shared
// clearance from state headers and internal-transition rows.
for edge in scene.routed.edges.values() {
let active = edge.id == self.selected;
let active = self
.current_selection()
.map_or(edge.id == self.selected, |s| {
s.contains(&Target::Edge(edge.id))
});
let primary = self
.current_selection()
.map_or(active, |s| s.primary() == Some(&Target::Edge(edge.id)));
let color = if active { style::TEAL } else { style::INK };
frame.stroke(
&polyline(&edge.points),
Stroke::default().with_color(color).with_width(if active {
2.4
if primary { 3.2 } else { 2.0 }
} else {
1.4
}),
@@ -1727,7 +2122,11 @@ impl canvas::Program<Event> for StateCanvas<'_> {
10.,
style::MUTED,
);
if active {
if active
&& self
.current_selection()
.is_none_or(|s| s.targets().len() <= 1)
{
if !edge.custom_suspended && self.tool == Tool::Select {
for pin in &edge.pins {
let radius = 4. / self.scale();
@@ -1758,6 +2157,42 @@ impl canvas::Program<Event> for StateCanvas<'_> {
}
}
}
if let Some(selection) = self.current_selection() {
for target in selection.targets() {
let rect = match target {
Target::Placement(id) => {
scene.view.nodes.iter().find(|n| n.id == *id).map(rectangle)
}
Target::StateRow {
placement,
relation,
} => scene
.view
.nodes
.iter()
.find(|n| n.id == *placement)
.and_then(|node| {
state_action_rows(self.project, node)
.into_iter()
.chain(internal_rows(self.project, node))
.find(|(row, _)| row.id == *relation)
.map(|(_, rect)| rect)
}),
_ => None,
};
if let Some(rect) = rect {
let primary = selection.primary() == Some(target);
let rect =
expanded(rect, if primary { 3. } else { 1.5 } / self.scale());
frame.stroke(
&Path::rectangle(rect.position(), rect.size()),
Stroke::default()
.with_color(style::TEAL)
.with_width(if primary { 3. } else { 1.5 } / self.scale()),
);
}
}
}
});
});
let mut overlay = Frame::new(renderer, bounds.size());
@@ -2159,6 +2594,7 @@ mod tests {
use crate::document::Document;
include!("state_bend_tests.rs");
include!("state_multiselect_canvas_tests.rs");
struct Fixture {
project: Project,
@@ -2313,7 +2749,10 @@ mod tests {
let scene = canvas.scene(&State::default()).unwrap();
assert_eq!(
canvas.hit(&scene, row.bounds.center()),
Some(Hit::StateAction(action))
Some(Hit::Row {
placement,
relation: action
})
);
assert_eq!(f.project, before);
f.project
@@ -2428,6 +2867,7 @@ mod tests {
epoch: 3,
},
selected: f.machine,
selection: None,
navigation_focus: None,
tool,
zoom,
@@ -3246,7 +3686,10 @@ mod tests {
for (relation, row) in rows {
assert_eq!(
canvas.hit(&scene, row.center()),
Some(Hit::StateAction(relation.id))
Some(Hit::Row {
placement: a.id,
relation: relation.id
})
);
let events = click(&canvas, &mut State::default(), row.center());
assert!(
@@ -3307,7 +3750,10 @@ mod tests {
for (relation, rect) in rows {
assert_eq!(
canvas.hit(&scene, rect.center()),
Some(Hit::Transition(relation.id))
Some(Hit::Row {
placement: a.id,
relation: relation.id
})
);
}
let initial = scene
+4 -1
View File
@@ -25,6 +25,7 @@ pub enum Tool {
#[derive(Debug, Clone)]
pub enum Event {
Selection(crate::app::multiselect::Event),
Remove(crate::app::diagram_removal::Intent),
Choose(Tool),
CreateView(Id),
@@ -38,6 +39,7 @@ pub enum Event {
context: Context,
object: Id,
placement: Option<Id>,
selection_target: Option<crate::diagram_usage::Target>,
anchor: iced::Point,
bend: Option<usize>,
route_segment: Option<(usize, Position)>,
@@ -101,7 +103,8 @@ impl Event {
pub fn context(&self) -> Option<Context> {
match self {
Self::Remove(intent) => Some(intent.context),
Self::Choose(_) | Self::CreateView(_) => None,
// Group events carry their own exact selection envelope.
Self::Selection(_) | Self::Choose(_) | Self::CreateView(_) => None,
Self::Select(c, _)
| Self::Pan(c, _)
| Self::Zoom(c, _)
@@ -0,0 +1,395 @@
// Included in state_canvas::tests. Drive production Program input and projection.
#[test]
fn state_singleton_selection_bend_uses_five_unit_grid_and_escape_keeps_selection() {
for zoom in [0.5, 1., 2.] {
for cancel in [false, true] {
let (f, relation) = bend_fixture(true);
let original = f.project.diagrams[&f.diagram].routes[0].clone();
let mut canvas = canvas(&f, Tool::Select, zoom);
canvas.selected = relation;
let selection = group_selection(&canvas, [Target::Edge(relation)]);
let snapshot = selection.snapshot(selection_context(canvas.context)).unwrap();
canvas.selection = Some(&selection);
let mut state = State::default();
let baseline = canvas.scene(&state).unwrap();
let start = screen(&canvas, point(original.waypoints[0]));
// A fractional pointer target distinguishes route snapping from the
// unsnapped State placement policy, at every supported test zoom.
let release = screen(&canvas, Point::new(683.75, 362.25));
let expected_pin = Position { x: 685., y: 360. };
motion(&canvas, &mut state, start, release);
assert!(input(&canvas, &mut state,
mouse::Event::ButtonPressed(mouse::Button::Left), release).is_none());
assert!(matches!(state.press, Some(Press::Bend { relation: id }) if id == relation));
assert!(state.group.is_none());
motion(&canvas, &mut state, release, release);
let mut expected_route = original.clone();
expected_route.waypoints[0] = expected_pin;
assert_eq!(state.bend_preview.as_ref(), Some(&expected_route));
assert_eq!(canvas.scene(&state).unwrap().routed.edges[&relation].pins, vec![expected_pin]);
assert_eq!(f.project.diagrams[&f.diagram].routes[0], original);
if cancel {
let escape = group_key(&canvas, &mut state, keyboard::key::Named::Escape,
keyboard::Modifiers::empty());
assert!(matches!(escape, Some(Event::Choose(Tool::Select))),
"Escape cancels the bend before it can emit selection Clear: {escape:?}");
assert!(state.press.is_none() && state.bend.is_none() && state.bend_preview.is_none());
assert_eq!(canvas.scene(&state).unwrap().routed.edges[&relation].points,
baseline.routed.edges[&relation].points);
assert!(input(&canvas, &mut state,
mouse::Event::ButtonReleased(mouse::Button::Left), release).is_none());
} else {
let event = input(&canvas, &mut state,
mouse::Event::ButtonReleased(mouse::Button::Left), release).unwrap();
assert!(matches!(&event, Event::SetBends { context, relation: id, waypoints }
if *context == canvas.context && *id == relation && *waypoints == vec![expected_pin]));
let plan = state_edit::plan(&f.project, canvas.context, &event).unwrap();
let actual = prepare_command(&f.project, &plan.command).unwrap().project;
let mut expected = f.project.clone();
expected.diagrams.get_mut(&f.diagram).unwrap().routes[0] = expected_route;
assert_eq!(actual, expected);
}
assert_eq!(selection.snapshot(selection_context(canvas.context)).unwrap(), snapshot);
assert!(state.group.is_none());
}
}
}
#[test]
fn state_singleton_selection_endpoint_reconnect_stationary_cancel_and_commit() {
for outcome in 0..3 {
let mut f = fixture();
let relation = f.project.relate(RelationKind::StateTransition, "Go standby", f.a, f.b);
let mut canvas = canvas(&f, Tool::Select, 1.);
canvas.selected = relation;
let selection = group_selection(&canvas, [Target::Edge(relation)]);
let snapshot = selection.snapshot(selection_context(canvas.context)).unwrap();
canvas.selection = Some(&selection);
let mut state = State::default();
let baseline = canvas.scene(&state).unwrap();
let handle = screen(&canvas, point(*baseline.routed.edges[&relation].points.last().unwrap()));
let target = screen(&canvas, header(&canvas, f.c));
motion(&canvas, &mut state, handle, target);
assert!(input(&canvas, &mut state,
mouse::Event::ButtonPressed(mouse::Button::Left), target).is_none());
assert!(matches!(state.press,
Some(Press::Reconnect { relation: id, endpoint: Endpoint::Target, start: Some(at) })
if id == relation && at == handle));
assert!(state.group.is_none() && state.bend.is_none());
if outcome > 0 { motion(&canvas, &mut state, target, target); }
if outcome == 1 {
let escape = group_key(&canvas, &mut state, keyboard::key::Named::Escape,
keyboard::Modifiers::empty());
assert!(matches!(escape, Some(Event::Choose(Tool::Select))),
"Escape cancels reconnect without clearing the exact edge: {escape:?}");
assert!(state.press.is_none());
}
let event = input(&canvas, &mut state,
mouse::Event::ButtonReleased(mouse::Button::Left), target);
if outcome < 2 {
assert!(event.is_none(), "stationary/cancelled reconnect produced {event:?}");
} else {
let event = event.unwrap();
assert!(matches!(&event, Event::Reconnect { context, relation: id, endpoint: Endpoint::Target, vertex }
if *context == canvas.context && *id == relation && *vertex == f.c));
let plan = state_edit::plan(&f.project, canvas.context, &event).unwrap();
let actual = prepare_command(&f.project, &plan.command).unwrap().project;
assert_eq!(plan.selected, relation);
assert_eq!(actual.relations[&relation].source(), f.a);
assert_eq!(actual.relations[&relation].target(), f.c);
assert_eq!(actual.elements, f.project.elements);
}
assert_eq!(f.project.relations[&relation].target(), f.b);
assert_eq!(selection.snapshot(selection_context(canvas.context)).unwrap(), snapshot);
assert!(state.group.is_none() && state.press.is_none());
}
}
#[test]
fn state_singleton_selection_shift_handles_toggle_exact_edge_before_route_tools() {
let (f, relation) = bend_fixture(true);
let mut canvas = canvas(&f, Tool::Select, 1.);
canvas.selected = relation;
let selection = group_selection(&canvas, [Target::Edge(relation)]);
canvas.selection = Some(&selection);
let baseline = canvas.scene(&State::default()).unwrap();
let edge = &baseline.routed.edges[&relation];
for world in [edge.pins[0], *edge.points.last().unwrap()] {
let mut state = State::default();
assert!(canvas::Program::update(&canvas, &mut state,
&canvas::Event::Keyboard(keyboard::Event::ModifiersChanged(keyboard::Modifiers::SHIFT)),
bounds(), mouse::Cursor::Unavailable).is_none());
let at = screen(&canvas, point(world));
motion(&canvas, &mut state, at, at);
assert!(matches!(input(&canvas, &mut state,
mouse::Event::ButtonPressed(mouse::Button::Left), at),
Some(Event::Selection(SelectionEvent::Choose(context, Target::Edge(id), Choice::Toggle)))
if context == selection_context(canvas.context) && id == relation));
assert!(state.group.is_none() && state.press.is_none() && state.bend.is_none());
let away = at + Vector::new(35., 20.);
motion(&canvas, &mut state, away, away);
assert!(input(&canvas, &mut state,
mouse::Event::ButtonReleased(mouse::Button::Left), away).is_none());
assert!(state.bend_preview.is_none());
assert_eq!(canvas.scene(&state).unwrap().routed.edges[&relation].points, edge.points);
}
}
fn group_selection(canvas: &StateCanvas<'_>, targets: impl IntoIterator<Item = Target>) -> Selection {
let mut selection = Selection::new(selection_context(canvas.context).scope);
for target in targets { selection.add(target, |_| true); }
selection
}
fn group_key(canvas: &StateCanvas<'_>, state: &mut State, key: keyboard::key::Named,
modifiers: keyboard::Modifiers) -> Option<Event>
{
canvas::Program::update(canvas, state, &canvas::Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(key), modified_key: keyboard::Key::Named(key),
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::Delete),
location: keyboard::Location::Standard, modifiers, text: None, repeat: false,
}), bounds(), mouse::Cursor::Unavailable).and_then(|action| action.into_inner().0)
}
#[test]
fn state_group_ordered_press_preview_and_fractional_release_preserve_primary() {
let (f, relation) = bend_fixture(true);
for zoom in [0.5, 1., 2.] {
let mut canvas = canvas(&f, Tool::Select, zoom);
let b = placement(&f, f.b);
let c = placement(&f, f.c);
let selection = group_selection(&canvas, [Target::Placement(b), Target::Placement(c)]);
canvas.selection = Some(&selection);
canvas.selected = f.c;
let before = selection.snapshot(selection_context(canvas.context)).unwrap();
let mut state = State::default();
let start = screen(&canvas, header(&canvas, f.b));
let end = start + Vector::new(7.25 * zoom, 10.5 * zoom);
motion(&canvas, &mut state, start, end);
assert!(input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Left), end).is_none());
assert!(state.group.is_some() && state.press.is_none());
assert_eq!(selection.primary(), Some(&Target::Placement(c)));
motion(&canvas, &mut state, end, end);
let scene = canvas.scene_with_bounds(&state, Some(bounds())).unwrap();
for id in [b, c] {
let node = scene.view.nodes.iter().find(|n| n.id == id).unwrap();
let original = &f.project.diagrams[&f.diagram].nodes[&id];
assert_eq!(node.position, Position { x: original.position.x + 7.25, y: original.position.y + 10.5 });
}
assert_eq!(scene.routed.edges[&relation].pins, vec![Position { x: 657.5, y: 351.25 }]);
assert!(matches!(input(&canvas, &mut state, mouse::Event::ButtonReleased(mouse::Button::Left), start),
Some(Event::Selection(SelectionEvent::Move(snapshot, Position { x: 7.25, y: 10.5 }))) if snapshot == before));
assert_eq!(selection.snapshot(selection_context(canvas.context)).unwrap(), before);
}
}
#[test]
fn state_group_stationary_collapses_but_out_and_back_keeps_group() {
let f = fixture();
let mut canvas = canvas(&f, Tool::Select, 1.);
let a = placement(&f, f.a);
let b = placement(&f, f.b);
let selection = group_selection(&canvas, [Target::Placement(a), Target::Placement(b)]);
canvas.selection = Some(&selection);
let start = screen(&canvas, header(&canvas, f.a));
for dragged in [false, true] {
let mut state = State::default();
motion(&canvas, &mut state, start, start);
assert!(input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Left), start).is_none());
if dragged {
motion(&canvas, &mut state, start + Vector::new(20., 0.), start);
motion(&canvas, &mut state, start, start);
}
let event = input(&canvas, &mut state, mouse::Event::ButtonReleased(mouse::Button::Left), start);
if dragged {
assert!(matches!(event, Some(Event::Selection(SelectionEvent::Move(_, Position { x: 0., y: 0. })))));
} else {
assert!(matches!(event, Some(Event::Selection(SelectionEvent::Collapse(_, Target::Placement(id)))) if id == a));
}
}
}
#[test]
fn state_group_changed_authority_viewport_or_membership_retires_preview_and_release() {
let f = fixture();
for change in 0..7 {
let mut canvas = canvas(&f, Tool::Select, 1.);
let a = placement(&f, f.a);
let b = placement(&f, f.b);
let selection = group_selection(&canvas, [Target::Placement(a), Target::Placement(b)]);
let mut replacement = group_selection(&canvas, [Target::Placement(a), Target::Placement(b)]);
replacement.remove(&Target::Placement(a));
replacement.add(Target::Placement(a), |_| true);
canvas.selection = Some(&selection);
let mut state = State::default();
let start = screen(&canvas, header(&canvas, f.a));
motion(&canvas, &mut state, start, start);
input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Left), start);
motion(&canvas, &mut state, start + Vector::new(12., 8.), start);
assert!(canvas.group_preview_key(&state, Some(bounds())).is_some());
let mut changed_bounds = bounds();
match change {
0 => canvas.context.revision += 1,
1 => canvas.context.epoch += 1,
2 => canvas.context.document = Id::new_v4(),
3 => canvas.zoom = 1.1,
4 => canvas.pan.x += 1.,
5 => changed_bounds.x += 1.,
_ => canvas.selection = Some(&replacement),
}
assert!(canvas.group_preview_key(&state, Some(changed_bounds)).is_none());
if change < 3 {
assert!(group_key(&canvas, &mut state, keyboard::key::Named::Delete, keyboard::Modifiers::empty()).is_none());
}
assert!(input_at_bounds(&canvas, &mut state, mouse::Event::ButtonReleased(mouse::Button::Left), start, changed_bounds).is_none());
assert!(state.group.is_none());
}
}
#[test]
fn state_group_mixed_route_handle_refuses_drag_and_preserves_stationary_collapse() {
let (f, relation) = bend_fixture(true);
let mut canvas = canvas(&f, Tool::Select, 1.);
let selection = group_selection(&canvas, [Target::Placement(placement(&f, f.b)), Target::Edge(relation)]);
canvas.selection = Some(&selection);
canvas.selected = relation;
let scene = canvas.scene(&State::default()).unwrap();
let at = screen(&canvas, point(scene.routed.edges[&relation].pins[0]));
for dragged in [false, true] {
let mut state = State::default();
motion(&canvas, &mut state, at, at);
input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Left), at);
assert!(state.group.is_some() && state.bend.is_none() && state.press.is_none());
if dragged {
motion(&canvas, &mut state, at + Vector::new(25., 10.), at);
motion(&canvas, &mut state, at, at);
}
let event = input(&canvas, &mut state, mouse::Event::ButtonReleased(mouse::Button::Left), at);
if dragged {
assert!(matches!(event, Some(Event::Selection(SelectionEvent::Refuse(_, _)))));
} else {
assert!(matches!(event, Some(Event::Selection(SelectionEvent::Collapse(_, Target::Edge(id)))) if id == relation));
}
assert!(state.bend_preview.is_none());
}
}
#[test]
fn state_group_shift_row_hit_menu_and_reassignment_keep_exact_identity() {
let mut f = fixture();
let work = f.project.add_element(Kind::Function, Layer::Sa, "Action work", None).unwrap();
let action = f.project.relate(RelationKind::StateAction, "Entry", f.a, work);
let internal = f.project.relate(RelationKind::StateTransition, "Internal", f.a, f.a);
if let RelationBody::StateTransition { transition_kind, .. } = &mut f.project.relations.get_mut(&internal).unwrap().body {
*transition_kind = TransitionKind::Internal;
}
let a = placement(&f, f.a);
for relation in [action, internal] {
let mut canvas = canvas(&f, Tool::Select, 1.);
let selection = group_selection(&canvas, [Target::Placement(placement(&f, f.b))]);
canvas.selection = Some(&selection);
let scene = canvas.scene(&State::default()).unwrap();
let node = scene.view.nodes.iter().find(|n| n.id == a).unwrap();
let rect = state_action_rows(&f.project, node).into_iter().chain(internal_rows(&f.project, node))
.find(|(row, _)| row.id == relation).unwrap().1;
assert!(visible_row_target(&f.project, f.diagram, &scene.view, a, relation));
let target = Target::StateRow { placement: a, relation };
assert_eq!(canvas.hit(&scene, rect.center()).unwrap().target(), target);
let mut state = State::default();
let modifiers = canvas::Program::update(&canvas, &mut state,
&canvas::Event::Keyboard(keyboard::Event::ModifiersChanged(keyboard::Modifiers::SHIFT)),
bounds(), mouse::Cursor::Unavailable);
assert!(modifiers.is_none());
let at = screen(&canvas, rect.center());
motion(&canvas, &mut state, at, at);
assert!(matches!(input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Left), at),
Some(Event::Selection(SelectionEvent::Choose(_, actual, Choice::Toggle))) if actual == target));
assert!(matches!(input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Right), at),
Some(Event::ContextMenu { object, placement: None, selection_target: Some(actual), .. }) if object == relation && actual == target));
canvas::Program::update(&canvas, &mut state, &canvas::Event::Window(iced::window::Event::Unfocused), bounds(), mouse::Cursor::Unavailable);
assert!(state.modifiers.is_empty());
}
if let RelationBody::StateAction { source, .. } = &mut f.project.relations.get_mut(&action).unwrap().body { *source = f.b; }
if let RelationBody::StateTransition { source, target, .. } = &mut f.project.relations.get_mut(&internal).unwrap().body { *source = f.b; *target = f.b; }
let view = projection::project_diagram(&f.project, &f.project.diagrams[&f.diagram]);
for relation in [action, internal] {
assert!(!visible_row_target(&f.project, f.diagram, &view, a, relation));
assert!(visible_row_target(&f.project, f.diagram, &view, placement(&f, f.b), relation));
}
}
#[test]
fn state_group_delete_and_escape_respect_held_gesture_and_full_set() {
let f = fixture();
let mut canvas = canvas(&f, Tool::Select, 1.);
let selection = group_selection(&canvas, [Target::Placement(placement(&f, f.a)), Target::Placement(placement(&f, f.b))]);
canvas.selection = Some(&selection);
let mut state = State::default();
use keyboard::key::Named;
assert!(matches!(group_key(&canvas, &mut state, Named::Delete, keyboard::Modifiers::empty()), Some(Event::Selection(SelectionEvent::Hide(_)))));
assert!(matches!(group_key(&canvas, &mut state, Named::Delete, keyboard::Modifiers::SHIFT), Some(Event::Selection(SelectionEvent::Refuse(_, _)))));
let at = screen(&canvas, header(&canvas, f.a));
motion(&canvas, &mut state, at, at);
input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Left), at);
assert!(group_key(&canvas, &mut state, Named::Delete, keyboard::Modifiers::empty()).is_none());
assert!(state.group.is_some());
assert!(group_key(&canvas, &mut state, Named::Escape, keyboard::Modifiers::empty()).is_none());
assert!(state.group.is_none());
assert!(matches!(group_key(&canvas, &mut state, Named::Escape, keyboard::Modifiers::empty()), Some(Event::Selection(SelectionEvent::Clear(_)))));
input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Middle), at);
input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Left), at);
assert!(state.group.is_none() && state.press.is_none() && state.pan_from.is_some());
assert!(matches!(motion(&canvas, &mut state, at + Vector::new(20., 10.), at), Some(Event::Pan(_, _))));
}
#[test]
fn state_group_entry_anchor_uses_authored_position_with_unsnapped_delta() {
let mut f = fixture();
let inner = f.project.elements[&f.leaf].parent.unwrap();
let entry = f.project.add_element(Kind::EntryPoint, Layer::Sa, "Enter", Some(inner)).unwrap();
let original = Position { x: 450.25, y: 410.75 };
let entry_node = f.project.place(f.diagram, entry, original);
let mut canvas = canvas(&f, Tool::Select, 1.);
let selection = group_selection(&canvas, [Target::Placement(entry_node), Target::Placement(placement(&f, f.leaf))]);
canvas.selection = Some(&selection);
let scene = canvas.scene(&State::default()).unwrap();
let shown = scene.view.nodes.iter().find(|n| n.id == entry_node).unwrap();
assert_ne!(shown.position.x, original.x);
let at = screen(&canvas, rectangle(shown).center());
let mut state = State::default();
motion(&canvas, &mut state, at, at);
input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Left), at);
assert!(state.group.is_some());
let end = at + Vector::new(7.25, 8.5);
motion(&canvas, &mut state, end, end);
assert!(matches!(input(&canvas, &mut state, mouse::Event::ButtonReleased(mouse::Button::Left), end),
Some(Event::Selection(SelectionEvent::Move(_, Position { x: 7.25, y: 8.5 })))));
assert_eq!(f.project.diagrams[&f.diagram].nodes[&entry_node].position, original);
}
#[test]
fn state_group_row_and_port_mixtures_refuse_complete_set_without_owner_promotion() {
let mut f = fixture();
let work = f.project.add_element(Kind::Function, Layer::Sa, "Action work", None).unwrap();
let action = f.project.relate(RelationKind::StateAction, "Entry", f.a, work);
let a = placement(&f, f.a);
for other in [Target::StateRow { placement: a, relation: action }, Target::Port { placement: a, port: work }] {
let mut canvas = canvas(&f, Tool::Select, 1.);
let selection = group_selection(&canvas, [Target::Placement(a), other]);
canvas.selection = Some(&selection);
let mut state = State::default();
assert!(matches!(group_key(&canvas, &mut state, keyboard::key::Named::Delete, keyboard::Modifiers::empty()),
Some(Event::Selection(SelectionEvent::Refuse(_, _)))));
let at = screen(&canvas, header(&canvas, f.a));
motion(&canvas, &mut state, at, at);
input(&canvas, &mut state, mouse::Event::ButtonPressed(mouse::Button::Left), at);
assert!(state.group.as_ref().is_some_and(|g| g.movement.is_none()));
let end = at + Vector::new(12., 8.);
motion(&canvas, &mut state, end, end);
assert!(canvas.group_preview_key(&state, Some(bounds())).is_none());
assert!(matches!(input(&canvas, &mut state, mouse::Event::ButtonReleased(mouse::Button::Left), end),
Some(Event::Selection(SelectionEvent::Refuse(snapshot, _))) if snapshot.targets().len() == 2));
assert!(state.press.is_none() && state.preview.is_none());
}
}
+51 -4
View File
@@ -41,7 +41,10 @@ pub fn diagram(app: &App, machine: Id) -> Option<Id> {
}
fn event(e: Event) -> Message {
Message::StateDiagram(e)
match e {
Event::Selection(selection) => Message::DiagramSelection(selection),
other => Message::StateDiagram(other),
}
}
pub fn view<'a>(app: &'a App, machine: Id, mut out: Column<'a, Message>) -> Element<'a, Message> {
@@ -143,8 +146,9 @@ pub fn view<'a>(app: &'a App, machine: Id, mut out: Column<'a, Message>) -> Elem
.collect::<Vec<_>>();
// Keep the optional picker in its own stable slot. Inserting it as a
// sibling before the canvas would replace the positional Iced focus tree.
let missing_spacing = if missing.is_empty() { 0.0_f32 } else { 8.0 };
let mut missing_controls = Column::new();
// Reserve the picker height even when all elements are placed. Group Hide
// and Undo must not resize the canvas and silently refit its camera.
let mut missing_controls = Column::new().height(34);
if !missing.is_empty() {
let position = Position {
x: (48. - state.pan.x) / state.zoom,
@@ -169,6 +173,7 @@ pub fn view<'a>(app: &'a App, machine: Id, mut out: Column<'a, Message>) -> Elem
diagram: id,
context,
selected: app.selected,
selection: app.diagram_selection.as_ref(),
navigation_focus: app
.diagram_focus(crate::diagram_usage::Surface::Saved(id))
.map(|usage| usage.bounds),
@@ -183,6 +188,7 @@ pub fn view<'a>(app: &'a App, machine: Id, mut out: Column<'a, Message>) -> Elem
out = out.push(
column![
missing_controls,
selection_controls(app),
crate::diagram::focus::wrap(
canvas.map(event),
context,
@@ -191,7 +197,7 @@ pub fn view<'a>(app: &'a App, machine: Id, mut out: Column<'a, Message>) -> Elem
Message::DiagramTraverse,
)
]
.spacing(missing_spacing)
.spacing(8)
.height(Fill),
);
let base: Element<'_, Message> = container(out.spacing(8))
@@ -202,6 +208,47 @@ pub fn view<'a>(app: &'a App, machine: Id, mut out: Column<'a, Message>) -> Elem
with_form(app, machine, base)
}
fn selection_controls(app: &App) -> Element<'_, Message> {
use crate::app::multiselect::{Event as SelectionEvent, placements};
let snapshot = app.multiselect_snapshot();
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().len() > 1) {
if placements(&snapshot).is_some() {
controls = controls.push(action(
"Hide selected",
Message::DiagramSelection(SelectionEvent::Hide(snapshot.clone())),
));
}
controls = controls
.push(action(
"Clear selection",
Message::DiagramSelection(SelectionEvent::Clear(snapshot.context())),
))
.push(
label(format!(
"Properties edit only {}",
crate::views::short(app.project().named(app.selected), 18)
))
.wrapping(iced::widget::text::Wrapping::None),
);
}
let hint = if app.behavior.diagram.tool == Tool::Select {
"Shift+click adds or removes from selection"
} else {
"Use Select / move to select multiple elements"
};
column![
controls,
label(hint).wrapping(iced::widget::text::Wrapping::None)
]
.height(56)
.into()
}
fn transition_details(machine: Id, selected: Id) -> Element<'static, Message> {
action(
"New transition with details…",
+72 -10
View File
@@ -39,12 +39,17 @@ mod port_labels;
pub use port_labels::PortLabels;
#[path = "diagram/focus.rs"]
pub(crate) mod focus;
pub(crate) mod group_gesture;
mod multiselect;
#[cfg(test)]
mod multiselect_tests;
#[path = "diagram/work_drag.rs"]
mod work_drag;
pub use work_drag::WorkFeedback;
#[derive(Clone, Copy)]
pub struct DiagramCanvas<'a> {
pub selection: Option<&'a crate::diagram_selection::Selection>,
pub allocation: Option<crate::app::allocation_drag::Capability<'a>>,
pub project: &'a Project,
pub view_index: Option<&'a oa_core::view_options::ViewIndex>,
@@ -63,6 +68,8 @@ pub struct DiagramCanvas<'a> {
}
#[derive(Default)]
pub struct State {
modifiers: iced::keyboard::Modifiers,
group: Option<multiselect::Press>,
work: Option<Arc<crate::app::allocation_drag::Press>>,
work_cache: RefCell<Option<Arc<Scene>>>,
pointer: Option<Point>,
@@ -462,6 +469,7 @@ impl DiagramCanvas<'_> {
}
fn preview_diagram(&self, state: &State) -> Diagram {
let mut diagram = self.project.diagrams[&self.diagram].clone();
self.group_preview(state, &mut diagram);
if let (Some((id, _, original)), Some(preview)) = (state.drag, state.preview) {
let delta = Position {
x: preview.x - original.x,
@@ -604,6 +612,13 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Option<Action<Message>> {
if let canvas::Event::Keyboard(iced::keyboard::Event::ModifiersChanged(modifiers)) = event {
state.modifiers = *modifiers;
return None;
}
if matches!(event, canvas::Event::Window(iced::window::Event::Unfocused)) {
state.modifiers = iced::keyboard::Modifiers::default();
}
// An attachment belongs to the boundary geometry captured at press.
// Camera/layout changes must not reinterpret its pointer in another space.
if matches!(
@@ -641,6 +656,7 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
return Some(action);
}
if state.context != Some(self.context) {
state.group = None;
state.work = None;
state.pointer = None;
state.port_drag = None;
@@ -707,6 +723,9 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
let local = cursor
.position()
.map(|p| Point::new(p.x - bounds.x, p.y - bounds.y));
if let Some(action) = self.group_input(state, event, bounds, cursor) {
return Some(action);
}
match event {
canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right))
if cursor.is_over(bounds) =>
@@ -1262,7 +1281,17 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
.collect::<BTreeSet<_>>();
for n in &view.nodes {
if containers.contains(&n.id) {
paint_node(&mut f, project, n, self.selected, true);
paint_node(
&mut f,
project,
n,
if self.selection_contains(crate::diagram_usage::Target::Placement(n.id)) {
n.element
} else {
self.selected
},
true,
);
}
}
let highlighted = highlighted_exchanges(project, self.selected);
@@ -1274,7 +1303,9 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
continue;
};
let end = point(end);
let active = edge.id == self.selected || highlighted.contains(&edge.id);
let active = edge.id == self.selected
|| highlighted.contains(&edge.id)
|| self.selection_contains(crate::diagram_usage::Target::Edge(edge.id));
let color = if active {
style::TEAL
} else if routed
@@ -1370,17 +1401,42 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
}
for n in &view.nodes {
if !containers.contains(&n.id) {
paint_node(&mut f, project, n, self.selected, false);
paint_node(
&mut f,
project,
n,
if self.selection_contains(crate::diagram_usage::Target::Placement(n.id)) {
n.element
} else {
self.selected
},
false,
);
} else {
// Container headers stay readable when relationships traverse
// the allocation enclosure. Children remain on top.
let mut header = n.clone();
header.size.height = 62.;
paint_node(&mut f, project, &header, self.selected, true);
paint_node(
&mut f,
project,
&header,
if self.selection_contains(crate::diagram_usage::Target::Placement(n.id)) {
n.element
} else {
self.selected
},
true,
);
}
}
for port in &view.ports {
let color = if self.selected == port.element {
let selected = self.selected == port.element
|| self.selection_contains(crate::diagram_usage::Target::Port {
port: port.element,
placement: port.owner,
});
let color = if selected {
style::TEAL
} else {
style::kind_color(
@@ -1408,11 +1464,7 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
let mut stroke =
Stroke::default()
.with_color(color)
.with_width(if self.selected == port.element {
2.5
} else {
1.5
});
.with_width(if selected { 2.5 } else { 1.5 });
if glyph == PortGlyph::Legacy {
stroke.line_dash = canvas::LineDash {
segments: &[3., 2.],
@@ -2277,6 +2329,7 @@ mod tests {
y: original.y - 200.,
};
let canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
context: Context {
@@ -2354,6 +2407,7 @@ mod tests {
.unwrap()
.id;
let canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
context: Context {
@@ -2482,6 +2536,7 @@ mod tests {
};
let session = Session::new(&p, &view, context, Tool::FunctionalExchange);
let canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
diagram,
@@ -2657,6 +2712,7 @@ mod tests {
for zoom in [0.5, 1., 1.5] {
let (p, diagram, edge) = route_fixture();
let canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
diagram,
@@ -2735,6 +2791,7 @@ mod tests {
fn fast_drags_commit_the_release_cursor_without_a_final_motion_event() {
let (p, diagram, edge) = route_fixture();
let canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
diagram,
@@ -2834,6 +2891,7 @@ mod tests {
fn route_cache_ignores_pan_zoom_and_cancelled_drag_cannot_commit() {
let (p, diagram, edge) = route_fixture();
let mut canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
diagram,
@@ -2964,6 +3022,7 @@ mod tests {
assert!(!svg.contains("data-navigation=\"source\""));
assert!(svg.contains("data-navigation=\"target\""));
let mut canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
diagram,
@@ -3020,6 +3079,7 @@ mod tests {
offset: Position { x: 0., y: -160. },
});
let mut canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
diagram,
@@ -3096,6 +3156,7 @@ mod tests {
},
});
let canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
diagram,
@@ -3131,6 +3192,7 @@ mod tests {
routed.edges.insert(duplicate, duplicate_route);
let selected = edge.max(duplicate); // UUID ordering must not override selection.
let canvas = DiagramCanvas {
selection: None,
project: &p,
view_index: None,
diagram,
@@ -34,6 +34,7 @@ fn fixture() -> App {
fn canvas(app: &App, zoom: f32) -> DiagramCanvas<'_> {
DiagramCanvas {
selection: None,
allocation: None,
project: app.project(),
view_index: None,
+37 -2
View File
@@ -12,6 +12,8 @@ struct Input {
suspended: bool,
traversing: bool,
pointer: Option<Point>,
modifiers: iced::keyboard::Modifiers,
restore_modifiers: bool,
}
impl operation::Focusable for Input {
fn is_focused(&self) -> bool {
@@ -95,6 +97,7 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Owner<'_, Mes
// canvas's transient gestures without retiring this focus owner.
state.pointer = None;
tree.children[0] = Tree::new(self.content.as_widget());
state.restore_modifiers = true;
} else {
tree.diff_children(std::slice::from_ref(&self.content));
}
@@ -143,6 +146,14 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Owner<'_, Mes
viewport: &Rectangle,
) {
let state = tree.state.downcast_mut::<Input>();
if let InputEvent::Keyboard(iced::keyboard::Event::ModifiersChanged(modifiers)) = event {
state.modifiers = *modifiers;
state.restore_modifiers = false;
}
if matches!(event, InputEvent::Window(iced::window::Event::Unfocused)) {
state.modifiers = iced::keyboard::Modifiers::default();
state.restore_modifiers = true;
}
if let InputEvent::Mouse(mouse::Event::CursorMoved { position }) = event {
state.pointer = Some(*position);
}
@@ -171,7 +182,14 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Owner<'_, Mes
}
// Save/export I/O denies commands and acquisition, while real focus
// operations and outside clicks can still revoke the retained owner.
if self.suspended && matches!(event, InputEvent::Keyboard(_) | InputEvent::Mouse(_)) {
let passive_modifiers = matches!(
event,
InputEvent::Keyboard(iced::keyboard::Event::ModifiersChanged(_))
);
if self.suspended
&& !passive_modifiers
&& matches!(event, InputEvent::Keyboard(_) | InputEvent::Mouse(_))
{
return;
}
if let InputEvent::Keyboard(iced::keyboard::Event::KeyPressed {
@@ -193,13 +211,30 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Owner<'_, Mes
return;
}
if matches!(event, InputEvent::Keyboard(_))
&& !passive_modifiers
&& (!state.focused || state.traversing || !self.enabled)
{
return;
}
if shell.is_event_captured() {
if shell.is_event_captured() && !passive_modifiers {
return;
}
if state.restore_modifiers {
// Suspending I/O replaces the child to retire pointer gestures.
// Held modifiers belong to this longer-lived passive owner, so
// restore them before the first admitted event reaches the child.
state.restore_modifiers = false;
self.content.as_widget_mut().update(
&mut tree.children[0],
&InputEvent::Keyboard(iced::keyboard::Event::ModifiersChanged(state.modifiers)),
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
@@ -0,0 +1,685 @@
//! Saved-view pointer geometry. Selection, capability and model admission remain
//! with the caller; this module never applies a selection or a model command.
use crate::diagram_selection::Snapshot;
use crate::diagram_usage::{Surface, Target};
use iced::{Point, Rectangle, Vector};
use oa_core::{Id, Position};
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Viewport {
pub zoom: f32,
pub pan: Vector,
pub bounds: Rectangle,
}
/// Node displacement policy; route-bend snapping remains outside this helper.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DisplacementPolicy {
/// Preserve the ordinary saved-view ten-unit anchor grid.
Grid10,
/// Preserve State views' fractional authored placement displacement.
Unsnapped,
}
#[derive(Debug)]
pub(crate) struct Gesture {
snapshot: Snapshot,
anchor: Id,
original: Position,
press: Point,
viewport: Viewport,
displacement: DisplacementPolicy,
crossed_threshold: bool,
delta: Position,
retired: bool,
}
#[derive(Debug, PartialEq)]
pub(crate) enum Outcome {
Click(Id),
Move(Snapshot, Position),
}
impl Gesture {
pub fn new(
snapshot: Snapshot,
anchor: Id,
original: Position,
press: Point,
viewport: Viewport,
) -> Option<Self> {
Self::new_with_policy(
snapshot,
anchor,
original,
press,
viewport,
DisplacementPolicy::Grid10,
)
}
/// `original` is the authored placement position, not its projected symbol
/// position (State entry/exit symbols can be displayed on another boundary).
/// Pointer displacement comes from frozen screen geometry and zoom.
pub fn new_with_policy(
snapshot: Snapshot,
anchor: Id,
original: Position,
press: Point,
viewport: Viewport,
displacement: DisplacementPolicy,
) -> Option<Self> {
if !matches!(snapshot.context().scope.surface, Surface::Saved(_))
|| !snapshot.targets().contains(&Target::Placement(anchor))
|| !snapshot
.targets()
.iter()
.all(|target| matches!(target, Target::Placement(_)))
|| !viewport.valid()
|| !finite_position(original)
|| !finite_point(press)
|| !viewport.bounds.contains(press)
{
return None;
}
Some(Self {
snapshot,
anchor,
original,
press,
viewport,
displacement,
crossed_threshold: false,
delta: Position { x: 0., y: 0. },
retired: false,
})
}
pub fn snapshot(&self) -> &Snapshot {
&self.snapshot
}
#[cfg(test)]
pub fn anchor(&self) -> Id {
self.anchor
}
/// Compare before processing each event. On mismatch, the caller must drop
/// this gesture, just as on Escape, focus loss or changed model authority.
pub fn viewport_matches(&self, viewport: Viewport) -> bool {
!self.retired && self.viewport == viewport
}
pub fn crossed_threshold(&self) -> bool {
self.crossed_threshold
}
/// Common policy-adjusted world delta for preview and release; zero before a drag.
pub fn delta(&self) -> Position {
self.delta
}
/// Process an absolute screen position. False permanently retires the
/// gesture; the caller must remove its preview and produce no operation.
pub fn move_to(&mut self, pointer: Point) -> bool {
if self.retired {
return false;
}
if !finite_point(pointer) || !self.viewport.bounds.contains(pointer) {
self.retire();
return false;
}
let screen = pointer - self.press;
self.crossed_threshold |= screen.x.hypot(screen.y) > 3.;
if !self.crossed_threshold {
return true;
}
let unsnapped = Position {
x: screen.x / self.viewport.zoom,
y: screen.y / self.viewport.zoom,
};
let desired = Position {
x: self.original.x + unsnapped.x,
y: self.original.y + unsnapped.y,
};
if !finite_position(desired) {
self.retire();
return false;
}
// Returning to the original position must not align an off-grid anchor
// as an accidental edit. It is still a drag, so selection stays grouped.
let delta = match self.displacement {
// Use the pointer delta directly, avoiding precision loss from
// subtracting a large authored original from its desired position.
DisplacementPolicy::Unsnapped => unsnapped,
DisplacementPolicy::Grid10 if desired == self.original => Position { x: 0., y: 0. },
DisplacementPolicy::Grid10 => Position {
x: (desired.x / 10.).round() * 10. - self.original.x,
y: (desired.y / 10.).round() * 10. - self.original.y,
},
};
if !finite_position(delta) {
self.retire();
return false;
}
self.delta = delta;
true
}
/// Consume the final pointer too: a release can be the first displaced
/// event. The caller must validate snapshot and viewport before acting on
/// either outcome. Cancelling is dropping the gesture without calling this.
pub fn release(mut self, pointer: Point) -> Option<Outcome> {
if !self.move_to(pointer) {
return None;
}
Some(if self.crossed_threshold {
Outcome::Move(self.snapshot, self.delta)
} else {
Outcome::Click(self.anchor)
})
}
fn retire(&mut self) {
self.retired = true;
self.delta = Position { x: 0., y: 0. };
}
}
impl Viewport {
fn valid(self) -> bool {
self.zoom.is_finite()
&& self.zoom > 0.
&& self.pan.x.is_finite()
&& self.pan.y.is_finite()
&& self.bounds.x.is_finite()
&& self.bounds.y.is_finite()
&& self.bounds.width.is_finite()
&& self.bounds.height.is_finite()
&& self.bounds.width > 0.
&& self.bounds.height > 0.
&& (self.bounds.x + self.bounds.width).is_finite()
&& (self.bounds.y + self.bounds.height).is_finite()
}
}
fn finite_point(point: Point) -> bool {
point.x.is_finite() && point.y.is_finite()
}
fn finite_position(position: Position) -> bool {
position.x.is_finite() && position.y.is_finite()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::diagram_selection::{Context, Scope, Selection};
fn id(value: u128) -> Id {
Id::from_u128(value)
}
fn context() -> Context {
Context {
scope: Scope {
document: id(1),
surface: Surface::Saved(id(2)),
},
revision: 3,
epoch: 4,
}
}
fn snapshot(targets: impl IntoIterator<Item = Target>) -> Snapshot {
let mut selection = Selection::new(context().scope);
for target in targets {
selection.add(target, |_| true);
}
selection.snapshot(context()).unwrap()
}
fn viewport() -> Viewport {
Viewport {
zoom: 1.,
pan: Vector::new(17., -8.),
bounds: Rectangle {
x: 100.,
y: 50.,
width: 400.,
height: 300.,
},
}
}
fn press() -> Point {
Point::new(150., 120.)
}
fn gesture(original: Position) -> Gesture {
Gesture::new(
snapshot([Target::Placement(id(10)), Target::Placement(id(11))]),
id(10),
original,
press(),
viewport(),
)
.unwrap()
}
#[test]
fn stationary_or_exact_threshold_release_is_click_without_snapping() {
for pointer in [press(), Point::new(153., 120.), Point::new(152., 122.)] {
let mut gesture = gesture(Position { x: 13., y: -7. });
assert!(gesture.move_to(pointer));
assert!(!gesture.crossed_threshold());
assert_eq!(gesture.delta(), Position { x: 0., y: 0. });
assert_eq!(gesture.release(pointer), Some(Outcome::Click(id(10))));
}
}
#[test]
fn threshold_latches_and_return_to_offgrid_origin_is_zero_move() {
let mut gesture = gesture(Position { x: 13., y: -7. });
let captured = gesture.snapshot().clone();
assert!(gesture.move_to(Point::new(170., 140.)));
assert!(gesture.crossed_threshold());
assert!(gesture.move_to(press()));
assert!(gesture.crossed_threshold());
assert_eq!(gesture.delta(), Position { x: 0., y: 0. });
assert_eq!(
gesture.release(press()),
Some(Outcome::Move(captured, Position { x: 0., y: 0. }))
);
}
#[test]
fn release_only_displacement_that_snaps_to_zero_still_preserves_group() {
let gesture = gesture(Position { x: 20., y: 40. });
let captured = gesture.snapshot().clone();
assert_eq!(
gesture.release(Point::new(154., 120.)),
Some(Outcome::Move(captured, Position { x: 0., y: 0. }))
);
}
#[test]
fn offgrid_anchor_yields_one_shared_delta_and_release_matches_preview() {
let mut gesture = gesture(Position { x: 13., y: -7. });
let captured = gesture.snapshot().clone();
assert_eq!(gesture.anchor(), id(10));
let pointer = Point::new(167., 133.);
assert!(gesture.move_to(pointer));
// Desired anchor (30,6) snaps to (30,10), hence shared delta (17,17).
assert_eq!(gesture.delta(), Position { x: 17., y: 17. });
let sibling = Position { x: -6., y: 24. };
let translated = Position {
x: sibling.x + gesture.delta().x,
y: sibling.y + gesture.delta().y,
};
assert_eq!(translated, Position { x: 11., y: 41. });
assert_eq!(
gesture.release(pointer),
Some(Outcome::Move(captured, Position { x: 17., y: 17. }))
);
}
#[test]
fn zoom_scales_world_delta_but_threshold_remains_in_screen_pixels() {
let mut gesture = Gesture::new(
snapshot([Target::Placement(id(10))]),
id(10),
Position { x: 20., y: 40. },
press(),
Viewport {
zoom: 2.,
..viewport()
},
)
.unwrap();
assert!(gesture.move_to(Point::new(153., 120.)));
assert!(!gesture.crossed_threshold());
assert!(gesture.move_to(Point::new(168., 112.)));
// Screen (18,-8) means world (9,-4), snapped anchor (30,40).
assert_eq!(gesture.delta(), Position { x: 10., y: 0. });
assert!(gesture.crossed_threshold());
}
#[test]
fn unsnapped_fractional_pointer_delta_preserves_authored_offset() {
let authored = Position {
x: 1024.125,
y: -321.5,
};
let mut gesture = Gesture::new_with_policy(
snapshot([Target::Placement(id(10)), Target::Placement(id(11))]),
id(10),
authored,
press(),
Viewport {
zoom: 2.,
..viewport()
},
DisplacementPolicy::Unsnapped,
)
.unwrap();
let captured = gesture.snapshot().clone();
let pointer = Point::new(164.5, 114.5);
assert!(gesture.move_to(pointer));
assert_eq!(gesture.delta(), Position { x: 7.25, y: -2.75 });
let translated_authored = Position {
x: authored.x + gesture.delta().x,
y: authored.y + gesture.delta().y,
};
assert_eq!(
translated_authored,
Position {
x: 1031.375,
y: -324.25
}
);
assert_eq!(
gesture.release(pointer),
Some(Outcome::Move(captured, Position { x: 7.25, y: -2.75 })),
);
}
#[test]
fn unsnapped_threshold_and_return_to_origin_preserve_group_lifecycle() {
let make = || {
Gesture::new_with_policy(
snapshot([Target::Placement(id(10)), Target::Placement(id(11))]),
id(10),
Position { x: 13.25, y: -7.5 },
press(),
viewport(),
DisplacementPolicy::Unsnapped,
)
.unwrap()
};
let mut click = make();
assert!(click.move_to(Point::new(153., 120.)));
assert!(!click.crossed_threshold());
assert_eq!(click.delta(), Position { x: 0., y: 0. });
assert_eq!(
click.release(Point::new(153., 120.)),
Some(Outcome::Click(id(10)))
);
let mut drag = make();
let captured = drag.snapshot().clone();
assert!(drag.move_to(Point::new(157.25, 117.25)));
assert_eq!(drag.delta(), Position { x: 7.25, y: -2.75 });
assert!(drag.move_to(press()));
assert!(drag.crossed_threshold());
assert_eq!(drag.delta(), Position { x: 0., y: 0. });
assert_eq!(
drag.release(press()),
Some(Outcome::Move(captured, Position { x: 0., y: 0. }))
);
}
#[test]
fn explicit_grid_and_default_constructor_keep_existing_quantization() {
let original = Position { x: 13., y: -7. };
let mut default = gesture(original);
let mut explicit = Gesture::new_with_policy(
default.snapshot().clone(),
id(10),
original,
press(),
viewport(),
DisplacementPolicy::Grid10,
)
.unwrap();
let pointer = Point::new(167., 133.);
assert!(default.move_to(pointer));
assert!(explicit.move_to(pointer));
// Existing ordinary behavior: desired (30,6), grid (30,10).
assert_eq!(default.delta(), Position { x: 17., y: 17. });
assert_eq!(explicit.delta(), Position { x: 17., y: 17. });
assert_eq!(default.release(pointer), explicit.release(pointer));
}
#[test]
fn unsnapped_release_only_movement_and_invalid_pointer_retirement() {
let make = || {
Gesture::new_with_policy(
snapshot([Target::Placement(id(10))]),
id(10),
Position {
x: 20.125,
y: 40.25,
},
press(),
viewport(),
DisplacementPolicy::Unsnapped,
)
.unwrap()
};
let release_only = make();
let captured = release_only.snapshot().clone();
assert_eq!(
release_only.release(Point::new(154.25, 120.)),
Some(Outcome::Move(captured, Position { x: 4.25, y: 0. })),
);
for invalid in [Point::new(f32::NAN, 120.), Point::new(501., 120.)] {
let mut gesture = make();
assert!(gesture.move_to(Point::new(154.25, 120.)));
assert!(!gesture.move_to(invalid));
assert!(!gesture.viewport_matches(viewport()));
assert_eq!(gesture.delta(), Position { x: 0., y: 0. });
assert_eq!(gesture.release(press()), None);
}
}
#[test]
fn full_typed_selection_and_saved_surface_are_required() {
for targets in [
vec![],
vec![Target::Placement(id(11))],
vec![Target::Placement(id(10)), Target::Edge(id(20))],
vec![
Target::Placement(id(10)),
Target::Port {
port: id(20),
placement: id(10),
},
],
] {
assert!(
Gesture::new(
snapshot(targets),
id(10),
Position { x: 0., y: 0. },
press(),
viewport()
)
.is_none()
);
}
let other = Context {
scope: Scope {
surface: Surface::Process(id(2)),
..context().scope
},
..context()
};
let mut selection = Selection::new(other.scope);
selection.add(Target::Placement(id(10)), |_| true);
assert!(
Gesture::new(
selection.snapshot(other).unwrap(),
id(10),
Position { x: 0., y: 0. },
press(),
viewport()
)
.is_none()
);
}
#[test]
fn any_frozen_viewport_change_is_detected() {
let gesture = gesture(Position { x: 0., y: 0. });
assert!(gesture.viewport_matches(viewport()));
for changed in [
Viewport {
zoom: 2.,
..viewport()
},
Viewport {
pan: Vector::new(18., -8.),
..viewport()
},
Viewport {
pan: Vector::new(17., -7.),
..viewport()
},
Viewport {
bounds: Rectangle {
x: 101.,
..viewport().bounds
},
..viewport()
},
Viewport {
bounds: Rectangle {
y: 51.,
..viewport().bounds
},
..viewport()
},
Viewport {
bounds: Rectangle {
width: 401.,
..viewport().bounds
},
..viewport()
},
Viewport {
bounds: Rectangle {
height: 301.,
..viewport().bounds
},
..viewport()
},
] {
assert!(!gesture.viewport_matches(changed));
}
}
#[test]
fn invalid_initial_geometry_cannot_start() {
let saved = snapshot([Target::Placement(id(10))]);
for invalid in [
Viewport {
zoom: 0.,
..viewport()
},
Viewport {
zoom: -1.,
..viewport()
},
Viewport {
zoom: f32::NAN,
..viewport()
},
Viewport {
zoom: f32::INFINITY,
..viewport()
},
Viewport {
pan: Vector::new(f32::NAN, 0.),
..viewport()
},
Viewport {
bounds: Rectangle {
width: 0.,
..viewport().bounds
},
..viewport()
},
Viewport {
bounds: Rectangle {
height: -1.,
..viewport().bounds
},
..viewport()
},
Viewport {
bounds: Rectangle {
x: f32::INFINITY,
..viewport().bounds
},
..viewport()
},
] {
assert!(
Gesture::new(
saved.clone(),
id(10),
Position { x: 0., y: 0. },
press(),
invalid
)
.is_none()
);
}
assert!(
Gesture::new(
saved.clone(),
id(10),
Position { x: f32::NAN, y: 0. },
press(),
viewport()
)
.is_none()
);
for invalid in [Point::new(f32::NAN, 120.), Point::new(99., 120.)] {
assert!(
Gesture::new(
saved.clone(),
id(10),
Position { x: 0., y: 0. },
invalid,
viewport()
)
.is_none()
);
}
}
#[test]
fn invalid_pointer_permanently_retires_even_if_pointer_returns() {
for invalid in [Point::new(f32::NAN, 120.), Point::new(501., 120.)] {
let mut gesture = gesture(Position { x: 20., y: 40. });
assert!(gesture.move_to(Point::new(170., 140.)));
assert!(!gesture.move_to(invalid));
assert_eq!(gesture.delta(), Position { x: 0., y: 0. });
assert!(!gesture.move_to(press()));
assert!(!gesture.viewport_matches(viewport()));
assert_eq!(gesture.release(press()), None);
}
assert_eq!(
gesture(Position { x: 20., y: 40. }).release(Point::new(501., 120.)),
None
);
}
#[test]
fn finite_inputs_that_overflow_world_geometry_retire_without_an_operation() {
let mut gesture = Gesture::new(
snapshot([Target::Placement(id(10))]),
id(10),
Position { x: 0., y: 0. },
press(),
Viewport {
zoom: f32::MIN_POSITIVE,
..viewport()
},
)
.unwrap();
assert!(!gesture.move_to(Point::new(170., 140.)));
assert_eq!(gesture.release(press()), None);
}
}
@@ -53,6 +53,7 @@ fn bounds() -> Rectangle {
}
fn canvas(app: &App) -> DiagramCanvas<'_> {
DiagramCanvas {
selection: None,
project: app.project(),
view_index: None,
diagram: app.active_diagram.unwrap(),
@@ -0,0 +1,297 @@
use super::group_gesture::{Gesture as GroupGesture, Outcome, Viewport};
use super::*;
use crate::app::multiselect::{Choice, Event, context};
use crate::diagram_selection::Snapshot;
use crate::diagram_usage::Target;
/// Even an unsupported mixed group must retain an ordinary click lifecycle.
pub(super) struct Press {
snapshot: Snapshot,
target: Target,
start: Point,
viewport: Viewport,
movement: Option<GroupGesture>,
reason: Option<String>,
crossed: bool,
retired: bool,
}
impl Press {
fn snapshot(&self) -> &Snapshot {
self.movement
.as_ref()
.map_or(&self.snapshot, GroupGesture::snapshot)
}
fn viewport_matches(&self, viewport: Viewport) -> bool {
!self.retired
&& self.viewport == viewport
&& self
.movement
.as_ref()
.is_none_or(|movement| movement.viewport_matches(viewport))
}
fn crossed_threshold(&self) -> bool {
self.movement
.as_ref()
.map_or(self.crossed, GroupGesture::crossed_threshold)
}
fn delta(&self) -> Position {
self.movement
.as_ref()
.map_or(Position { x: 0., y: 0. }, GroupGesture::delta)
}
fn move_to(&mut self, pointer: Point) {
if self.retired {
return;
}
if !pointer.x.is_finite()
|| !pointer.y.is_finite()
|| !self.viewport.bounds.contains(pointer)
{
self.retired = true;
self.movement = None;
return;
}
self.crossed |= pointer.distance(self.start) > 3.;
if let Some(movement) = &mut self.movement
&& !movement.move_to(pointer)
{
self.retired = true;
}
}
fn release(mut self, pointer: Point) -> Option<Event> {
self.move_to(pointer);
if self.retired {
return None;
}
if !self.crossed {
return Some(Event::Collapse(self.snapshot, self.target));
}
if let Some(reason) = self.reason {
return Some(Event::Refuse(self.snapshot, reason));
}
match self.movement?.release(pointer)? {
Outcome::Click(id) => Some(Event::Collapse(self.snapshot, Target::Placement(id))),
Outcome::Move(snapshot, delta) => Some(Event::Move(snapshot, delta)),
}
}
}
impl DiagramCanvas<'_> {
pub(super) fn selection_contains(&self, target: Target) -> bool {
self.selection
.is_some_and(|s| s.scope() == context(self.context).scope && s.contains(&target))
}
pub(super) fn group_input(
&self,
state: &mut State,
event: &canvas::Event,
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Option<Action<Message>> {
let viewport = Viewport {
zoom: self.zoom,
pan: self.pan,
bounds,
};
if let Some(gesture) = &state.group {
let valid = gesture.viewport_matches(viewport)
&& self.editable
&& self.connection.is_none()
&& !self.placing
&& self
.selection
.is_some_and(|s| s.matches(gesture.snapshot(), context(self.context)));
let cancelled = 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(iced::keyboard::Event::KeyPressed {
key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape),
..
})
);
if !valid || cancelled {
state.group = None;
*state.cache.borrow_mut() = None;
return Some(Action::request_redraw().and_capture());
}
}
if let Some(gesture) = &mut state.group {
match event {
canvas::Event::Mouse(mouse::Event::CursorMoved { position }) => {
gesture.move_to(*position);
*state.cache.borrow_mut() = None;
return Some(Action::request_redraw().and_capture());
}
canvas::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
let gesture = state.group.take().unwrap();
*state.cache.borrow_mut() = None;
let outcome = cursor
.position()
.and_then(|pointer| gesture.release(pointer));
return Some(match outcome {
Some(event) => {
Action::publish(Message::DiagramSelection(event)).and_capture()
}
None => Action::request_redraw().and_capture(),
});
}
canvas::Event::Keyboard(_) => return Some(Action::capture()),
_ => {}
}
}
let selection = self
.selection
.filter(|s| s.scope() == context(self.context).scope)?;
if state.pan_start.is_some() {
return None;
}
if self.connection.is_some() || self.placing {
return None;
}
if let canvas::Event::Keyboard(iced::keyboard::Event::KeyPressed {
key, modifiers, ..
}) = event
{
use iced::keyboard::{Key, key::Named};
if *key == Key::Named(Named::Escape)
&& state.drag.is_none()
&& state.route_drag.is_none()
&& state.port_drag.is_none()
&& state.work.is_none()
{
return Some(
Action::publish(Message::DiagramSelection(Event::Clear(context(
self.context,
))))
.and_capture(),
);
}
if selection.targets().len() > 1 && *key == Key::Named(Named::Delete) {
let snapshot = selection.snapshot(context(self.context))?;
let action = if modifiers.is_empty() {
Event::Hide(snapshot)
} else {
Event::Refuse(snapshot, "Use Hide selected to remove placements. Group model-deletion review is not available yet.".into())
};
return Some(Action::publish(Message::DiagramSelection(action)).and_capture());
}
}
if !matches!(
event,
canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
) || !cursor.is_over(bounds)
{
return None;
}
let pointer = cursor.position()?;
let local = Point::new(pointer.x - bounds.x, pointer.y - bounds.y);
let scene = self.scene(state);
let target = if let Some(port) = self.hit_port(&scene.view, local) {
Some(Target::Port {
port: port.element,
placement: port.owner,
})
} else if let Some(id) = self.hit(&scene.view, local) {
Some(Target::Placement(id))
} else {
self.hit_label(&scene.routed, local)
.or_else(|| self.hit_association_label(&scene.routed, local))
.or_else(|| self.hit_edge(&scene.routed, local).map(|hit| hit.0))
.map(Target::Edge)
}?;
if state.modifiers.shift() {
state.drag = None;
state.preview = None;
state.port_drag = None;
state.route_drag = None;
return Some(
Action::publish(Message::DiagramSelection(Event::Choose(
context(self.context),
target,
Choice::Toggle,
)))
.and_capture(),
);
}
if selection.targets().len() <= 1 || !selection.contains(&target) {
return None;
}
let snapshot = selection.snapshot(context(self.context))?;
if !self.editable {
return Some(Action::capture());
}
let reason = if crate::app::multiselect::placements(&snapshot).is_none() {
Some(
"Move requires only placed elements. Remove ports and connections from the selection.",
)
} else if snapshot
.targets()
.iter()
.any(|t| matches!(t, Target::Placement(id) if self.work_eligible(*id)))
{
Some("Group allocation drag is not available yet. The selection was retained.")
} else {
None
};
let movement = if reason.is_none()
&& let Target::Placement(anchor) = target
{
let original = self.project.diagrams[&self.diagram].nodes[&anchor].position;
GroupGesture::new(snapshot.clone(), anchor, original, pointer, viewport)
} else {
None
};
if movement.is_none() && reason.is_none() {
return Some(Action::capture());
}
state.group = Some(Press {
snapshot,
target,
start: pointer,
viewport,
movement,
reason: reason.map(str::to_owned),
crossed: false,
retired: false,
});
*state.cache.borrow_mut() = None;
Some(Action::request_redraw().and_capture())
}
pub(super) fn group_preview(&self, state: &State, diagram: &mut Diagram) {
let Some(gesture) = &state.group else {
return;
};
if !gesture.crossed_threshold() {
return;
}
let Some(ids) = crate::app::multiselect::placements(gesture.snapshot()) else {
return;
};
let Ok(Command::Batch(commands)) = oa_core::diagram_edit::translate_placements(
self.project,
self.diagram,
&ids,
gesture.delta(),
) else {
return;
};
// Apply only the planner's presentation records. Full model validation
// and source/history updates occur once, when App accepts the release.
for command in commands {
match command {
Command::EditNode { node, .. } => {
diagram.nodes.insert(node.id, node);
}
Command::SetEdgeRoute { route, .. } => route_edit::with_route(diagram, route),
_ => unreachable!("placement planner returned a non-geometry command"),
}
}
}
}
@@ -0,0 +1,758 @@
//! Production canvas event regressions for exact multi-selection and group gestures.
use super::{DiagramCanvas, State};
use crate::app::{
Message,
multiselect::{Choice, Event as SelectionEvent, context},
};
use crate::diagram_selection::Selection;
use crate::diagram_usage::Target;
use iced::widget::canvas::{self, Program};
use iced::{Point, Rectangle, Size, Vector, event::Status, keyboard, mouse};
use oa_core::*;
fn position(x: f32, y: f32) -> Position {
Position { x, y }
}
fn bounds() -> Rectangle {
Rectangle::new(Point::new(260., 100.), Size::new(2400., 1800.))
}
struct Fixture {
project: Project,
diagram: Id,
a: Id,
b: Id,
child: Id,
internal: Id,
context: crate::route_edit::Context,
}
impl Fixture {
fn new() -> Self {
let mut project = Project::empty();
let a = project
.add_element(Kind::Activity, Layer::Oa, "A", None)
.unwrap();
let b = project
.add_element(Kind::Activity, Layer::Oa, "B", None)
.unwrap();
let c = project
.add_element(Kind::Activity, Layer::Oa, "C", None)
.unwrap();
let child = project
.add_element(Kind::Activity, Layer::Oa, "Child", Some(a))
.unwrap();
let internal = project.relate(RelationKind::Interaction, "Internal", a, b);
let external = project.relate(RelationKind::Interaction, "External", b, c);
let diagram = project.ensure_diagram(Layer::Oa);
project.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Overview;
let a = project.place(diagram, a, position(100., 200.));
let b = project.place(diagram, b, position(500., 200.));
let child = project.place(diagram, child, position(120., 280.));
project.place(diagram, c, position(900., 200.));
let view = project.diagrams.get_mut(&diagram).unwrap();
view.nodes.get_mut(&a).unwrap().collapsed = true;
view.routes = [
(internal, position(400., 320.)),
(external, position(800., 340.)),
]
.into_iter()
.map(|(edge, point)| EdgeRoute {
edge,
source_attachment: None,
target_attachment: None,
waypoints: vec![point],
label: Some(EdgeLabel {
fraction: 0.4,
offset: position(3., -9.),
}),
})
.collect();
validate_candidate(&project).unwrap();
Self {
project,
diagram,
a,
b,
child,
internal,
context: crate::route_edit::Context {
document: Id::new_v4(),
diagram,
revision: 7,
epoch: 11,
},
}
}
fn selection(&self, targets: impl IntoIterator<Item = Target>) -> Selection {
let mut selection = Selection::new(context(self.context).scope);
for target in targets {
assert!(selection.add(target, |_| true));
}
selection
}
fn pair(&self) -> Selection {
self.selection([Target::Placement(self.a), Target::Placement(self.b)])
}
fn canvas<'a>(&'a self, selection: &'a Selection, zoom: f32) -> DiagramCanvas<'a> {
let selected = match selection.primary() {
Some(Target::Placement(id)) => self.project.diagrams[&self.diagram].nodes[id].element,
Some(Target::Edge(id)) => *id,
Some(Target::Port { port, .. }) => *port,
_ => self.diagram,
};
DiagramCanvas {
selection: Some(selection),
project: &self.project,
view_index: None,
diagram: self.diagram,
selected,
navigation_focus: None,
zoom,
pan: Vector::new(20., 30.),
context: self.context,
selected_bend: None,
selected_attachment: None,
editable: true,
placing: false,
connection: None,
allocation: None,
}
}
fn screen(&self, placement: Id, zoom: f32) -> Point {
let p = self.project.diagrams[&self.diagram].nodes[&placement].position;
Point::new(
bounds().x + (p.x + 30.) * zoom + 20.,
bounds().y + (p.y + 25.) * zoom + 30.,
)
}
fn expected_move(&self) -> Diagram {
// Independent literal expectations: the folded child moves with A,
// only the internal edge's authored world pin translates.
let mut expected = self.project.diagrams[&self.diagram].clone();
expected.nodes.get_mut(&self.a).unwrap().position = position(140., 260.);
expected.nodes.get_mut(&self.b).unwrap().position = position(540., 260.);
expected.nodes.get_mut(&self.child).unwrap().position = position(160., 340.);
expected.routes[0].waypoints = vec![position(440., 380.)];
expected
}
}
fn input(
c: &DiagramCanvas<'_>,
state: &mut State,
event: canvas::Event,
viewport: Rectangle,
final_cursor: Point,
) -> (Option<Message>, Status) {
c.update(
state,
&event,
viewport,
mouse::Cursor::Available(final_cursor),
)
.map_or((None, Status::Ignored), |action| {
let (message, _, status) = action.into_inner();
(message, status)
})
}
fn pointer(
c: &DiagramCanvas<'_>,
state: &mut State,
event: mouse::Event,
final_cursor: Point,
) -> (Option<Message>, Status) {
input(
c,
state,
canvas::Event::Mouse(event),
bounds(),
final_cursor,
)
}
fn start(c: &DiagramCanvas<'_>, state: &mut State, press: Point, final_cursor: Point) {
assert!(
pointer(
c,
state,
mouse::Event::CursorMoved { position: press },
final_cursor
)
.0
.is_none()
);
let (message, status) = pointer(
c,
state,
mouse::Event::ButtonPressed(mouse::Button::Left),
final_cursor,
);
assert!(message.is_none());
assert_eq!(status, Status::Captured);
assert!(state.group.is_some());
assert!(state.drag.is_none());
}
fn key(named: keyboard::key::Named) -> canvas::Event {
canvas::Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(named),
modified_key: keyboard::Key::Named(named),
physical_key: keyboard::key::Physical::Code(if named == keyboard::key::Named::Escape {
keyboard::key::Code::Escape
} else {
keyboard::key::Code::Delete
}),
location: keyboard::Location::Standard,
modifiers: keyboard::Modifiers::empty(),
text: None,
repeat: false,
})
}
fn expect_move(
message: Option<Message>,
selection: &Selection,
current: crate::route_edit::Context,
expected: Position,
) -> crate::diagram_selection::Snapshot {
let Some(Message::DiagramSelection(SelectionEvent::Move(snapshot, delta))) = message else {
panic!("expected one captured group Move");
};
assert_eq!(delta, expected);
assert!(selection.matches(&snapshot, context(current)));
snapshot
}
#[test]
fn shift_press_uses_ordered_hit_not_native_batch_final_cursor() {
let f = Fixture::new();
let selection = f.selection([Target::Placement(f.b)]);
let before = selection.snapshot(context(f.context)).unwrap();
let c = f.canvas(&selection, 1.);
let mut state = State::default();
let at_a = f.screen(f.a, 1.);
let final_cursor = f.screen(f.b, 1.);
assert!(
input(
&c,
&mut state,
canvas::Event::Keyboard(keyboard::Event::ModifiersChanged(
keyboard::Modifiers::SHIFT
)),
bounds(),
final_cursor
)
.0
.is_none()
);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: at_a },
final_cursor
)
.0
.is_none()
);
let (message, status) = pointer(
&c,
&mut state,
mouse::Event::ButtonPressed(mouse::Button::Left),
final_cursor,
);
assert_eq!(status, Status::Captured);
assert!(
matches!(message, Some(Message::DiagramSelection(SelectionEvent::Choose(captured, Target::Placement(id), Choice::Toggle))) if captured == context(f.context) && id == f.a)
);
assert!(
state.group.is_none()
&& state.drag.is_none()
&& state.route_drag.is_none()
&& state.port_drag.is_none()
);
assert!(
pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
final_cursor
)
.0
.is_none()
);
assert!(
selection.matches(&before, context(f.context)),
"canvas emits intent without mutating selection"
);
}
#[test]
fn group_canvas_preview_and_release_match_independent_expected_geometry() {
for zoom in [0.5, 1., 2.] {
let f = Fixture::new();
let selection = f.pair();
let captured = selection.snapshot(context(f.context)).unwrap();
let c = f.canvas(&selection, zoom);
let mut state = State::default();
let press = f.screen(f.a, zoom);
let end = press + Vector::new(40. * zoom, 60. * zoom);
start(&c, &mut state, press, end);
assert_eq!(c.preview_diagram(&state), f.project.diagrams[&f.diagram]);
let (message, status) = pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: end },
end,
);
assert!(message.is_none());
assert_eq!(status, Status::Captured);
assert_eq!(c.preview_diagram(&state), f.expected_move());
let (message, status) = pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
end,
);
assert_eq!(status, Status::Captured);
let snapshot = expect_move(message, &selection, f.context, position(40., 60.));
assert_eq!(snapshot, captured);
assert!(state.group.is_none());
let ids = crate::app::multiselect::placements(&snapshot).unwrap();
let command =
diagram_edit::translate_placements(&f.project, f.diagram, &ids, position(40., 60.))
.unwrap();
let actual = prepare_command(&f.project, &command).unwrap().project;
let mut expected = f.project.clone();
expected.diagrams.insert(f.diagram, f.expected_move());
assert_eq!(actual, expected);
assert!(selection.matches(&captured, context(f.context)));
}
}
#[test]
fn stationary_group_click_does_not_use_motion_after_release_in_same_batch() {
let f = Fixture::new();
let selection = f.pair();
let c = f.canvas(&selection, 1.);
let mut state = State::default();
let press = f.screen(f.a, 1.);
let end = press + Vector::new(80., 70.);
start(&c, &mut state, press, end);
let (message, _) = pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
end,
);
assert!(
matches!(message, Some(Message::DiagramSelection(SelectionEvent::Collapse(captured, Target::Placement(id)))) if selection.matches(&captured, context(f.context)) && id == f.a)
);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: end },
end
)
.0
.is_none()
);
assert_eq!(c.preview_diagram(&state), f.project.diagrams[&f.diagram]);
}
#[test]
fn mixed_set_keeps_click_lifecycle_and_refuses_only_actual_drag() {
for moved in [false, true] {
let f = Fixture::new();
let selection = f.selection([Target::Placement(f.a), Target::Edge(f.internal)]);
let captured = selection.snapshot(context(f.context)).unwrap();
let c = f.canvas(&selection, 1.);
let mut state = State::default();
let press = f.screen(f.a, 1.);
let end = if moved {
press + Vector::new(40., 60.)
} else {
press + Vector::new(2., 1.)
};
start(&c, &mut state, press, end);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: end },
end
)
.0
.is_none()
);
assert_eq!(c.preview_diagram(&state), f.project.diagrams[&f.diagram]);
let (message, status) = pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
end,
);
assert_eq!(status, Status::Captured);
if moved {
assert!(
matches!(message, Some(Message::DiagramSelection(SelectionEvent::Refuse(snapshot, reason))) if snapshot == captured && reason.contains("only placed elements"))
);
} else {
assert!(
matches!(message, Some(Message::DiagramSelection(SelectionEvent::Collapse(current, Target::Placement(id)))) if current == captured && id == f.a)
);
}
assert!(state.group.is_none());
assert!(selection.matches(&captured, context(f.context)));
}
}
#[test]
fn escape_cancels_live_group_without_clearing_or_publishing_a_model_intent() {
let f = Fixture::new();
let selection = f.pair();
let captured = selection.snapshot(context(f.context)).unwrap();
let c = f.canvas(&selection, 1.);
let mut state = State::default();
let press = f.screen(f.a, 1.);
let end = press + Vector::new(40., 60.);
start(&c, &mut state, press, end);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: end },
end
)
.0
.is_none()
);
assert_eq!(c.preview_diagram(&state), f.expected_move());
let (message, status) = input(
&c,
&mut state,
key(keyboard::key::Named::Escape),
bounds(),
end,
);
assert!(message.is_none());
assert_eq!(status, Status::Captured);
assert!(state.group.is_none());
assert_eq!(c.preview_diagram(&state), f.project.diagrams[&f.diagram]);
assert!(
pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
end
)
.0
.is_none()
);
assert!(selection.matches(&captured, context(f.context)));
// A subsequent Escape, after the gesture is idle, may clear selection.
assert!(matches!(
input(
&c,
&mut state,
key(keyboard::key::Named::Escape),
bounds(),
end
)
.0,
Some(Message::DiagramSelection(SelectionEvent::Clear(_)))
));
}
#[test]
fn delete_is_captured_without_hiding_during_live_group_then_release_moves_once() {
let f = Fixture::new();
let selection = f.pair();
let c = f.canvas(&selection, 1.);
let mut state = State::default();
let press = f.screen(f.a, 1.);
let end = press + Vector::new(40., 60.);
start(&c, &mut state, press, end);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: end },
end
)
.0
.is_none()
);
let (message, status) = input(
&c,
&mut state,
key(keyboard::key::Named::Delete),
bounds(),
end,
);
assert!(message.is_none());
assert_eq!(status, Status::Captured);
assert!(state.group.is_some());
assert_eq!(c.preview_diagram(&state), f.expected_move());
expect_move(
pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
end,
)
.0,
&selection,
f.context,
position(40., 60.),
);
}
#[test]
fn middle_pan_excludes_group_start_and_delete_even_when_left_is_pressed() {
let f = Fixture::new();
let selection = f.pair();
let captured = selection.snapshot(context(f.context)).unwrap();
let c = f.canvas(&selection, 1.);
let mut state = State::default();
let press = f.screen(f.a, 1.);
let end = press + Vector::new(40., 60.);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: press },
end
)
.0
.is_none()
);
assert!(
pointer(
&c,
&mut state,
mouse::Event::ButtonPressed(mouse::Button::Middle),
end
)
.0
.is_none()
);
let (message, status) = pointer(
&c,
&mut state,
mouse::Event::ButtonPressed(mouse::Button::Left),
end,
);
assert!(message.is_none());
assert_eq!(status, Status::Captured);
assert!(state.group.is_none() && state.drag.is_none());
assert!(
input(
&c,
&mut state,
key(keyboard::key::Named::Delete),
bounds(),
end
)
.0
.is_none()
);
assert!(
matches!(pointer(&c, &mut state, mouse::Event::CursorMoved { position: end }, end).0, Some(Message::Pan(delta)) if delta == Vector::new(40., 60.))
);
assert!(
pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
end
)
.0
.is_none()
);
assert!(
pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Middle),
end
)
.0
.is_none()
);
assert_eq!(c.preview_diagram(&state), f.project.diagrams[&f.diagram]);
assert!(selection.matches(&captured, context(f.context)));
}
#[test]
fn changed_viewport_or_context_retires_group_without_a_release_intent() {
for change in 0..7 {
let f = Fixture::new();
let selection = f.pair();
let c = f.canvas(&selection, 1.);
let mut state = State::default();
let press = f.screen(f.a, 1.);
let end = press + Vector::new(40., 60.);
start(&c, &mut state, press, end);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: end },
end
)
.0
.is_none()
);
let mut changed = c;
let mut viewport = bounds();
match change {
0 => viewport.x += 1.,
1 => viewport.width -= 1.,
2 => changed.pan.x += 1.,
3 => changed.zoom = 2.,
4 => changed.context.epoch += 1,
5 => changed.context.revision += 1,
_ => changed.context.document = Id::new_v4(),
}
let (message, _) = input(
&changed,
&mut state,
canvas::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
viewport,
end,
);
assert!(
message.is_none(),
"changed viewport/context {change} must not publish a commit or click"
);
assert!(state.group.is_none());
assert_eq!(
changed.preview_diagram(&state),
f.project.diagrams[&f.diagram]
);
}
}
#[test]
fn changed_selection_generation_rejects_press_even_after_membership_is_restored() {
let f = Fixture::new();
let mut selection = f.pair();
let press = f.screen(f.a, 1.);
let end = press + Vector::new(40., 60.);
let mut state = State::default();
{
let c = f.canvas(&selection, 1.);
start(&c, &mut state, press, end);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: end },
end
)
.0
.is_none()
);
}
assert!(selection.remove(&Target::Placement(f.b)));
assert!(selection.add(Target::Placement(f.b), |_| true));
let c = f.canvas(&selection, 1.);
let (message, status) = pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
end,
);
assert!(message.is_none());
assert_eq!(status, Status::Captured);
assert!(state.group.is_none());
assert_eq!(c.preview_diagram(&state), f.project.diagrams[&f.diagram]);
}
#[test]
fn initial_press_without_pointer_history_consumes_release_only_displacement() {
let f = Fixture::new();
let selection = f.pair();
let c = f.canvas(&selection, 1.);
let mut state = State::default();
let press = f.screen(f.a, 1.);
let end = press + Vector::new(40., 60.);
// With no earlier ordered move, the supplied release cursor is authoritative.
assert!(
pointer(
&c,
&mut state,
mouse::Event::ButtonPressed(mouse::Button::Left),
press
)
.0
.is_none()
);
assert!(state.group.is_some());
expect_move(
pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
end,
)
.0,
&selection,
f.context,
position(40., 60.),
);
}
#[test]
fn threshold_crossing_then_return_to_origin_emits_zero_move_not_singleton_click() {
let f = Fixture::new();
let selection = f.pair();
let c = f.canvas(&selection, 1.);
let mut state = State::default();
let press = f.screen(f.a, 1.);
let end = press + Vector::new(40., 60.);
start(&c, &mut state, press, end);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: end },
end
)
.0
.is_none()
);
assert!(
pointer(
&c,
&mut state,
mouse::Event::CursorMoved { position: press },
end
)
.0
.is_none()
);
assert_eq!(c.preview_diagram(&state), f.project.diagrams[&f.diagram]);
expect_move(
pointer(
&c,
&mut state,
mouse::Event::ButtonReleased(mouse::Button::Left),
end,
)
.0,
&selection,
f.context,
position(0., 0.),
);
assert_eq!(selection.targets().len(), 2);
}
@@ -61,6 +61,7 @@ fn screen(p: Position, zoom: f32) -> Point {
}
fn canvas(app: &App, zoom: f32) -> DiagramCanvas<'_> {
DiagramCanvas {
selection: None,
project: app.project(),
view_index: None,
diagram: app.active_diagram.unwrap(),
@@ -2,6 +2,7 @@ use super::*;
fn canvas(project: &Project, diagram: Id, zoom: f32) -> DiagramCanvas<'_> {
DiagramCanvas {
selection: None,
project,
view_index: None,
diagram,
@@ -177,6 +177,7 @@ mod tests {
fn program(app: &App) -> PortLabels<'_> {
PortLabels(DiagramCanvas {
selection: None,
project: app.project(),
view_index: None,
diagram: app.active_diagram.unwrap(),
+416
View File
@@ -0,0 +1,416 @@
//! Transient exact-target selection; admission and model operations belong to adapters.
use crate::diagram_usage::{Surface, Target};
use oa_core::Id;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Scope {
/// Document-instance identity, not the persisted project UUID.
pub document: Id,
pub surface: Surface,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Context {
pub scope: Scope,
pub revision: u64,
pub epoch: u64,
}
/// Insertion-ordered unique targets. Membership does not grant edit capability.
#[derive(Debug)]
pub(crate) struct Selection {
scope: Scope,
targets: Vec<Target>,
primary: Option<Target>,
generation: u64,
}
/// Immutable operation input, including the selection lifetime that captured it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Snapshot {
context: Context,
generation: u64,
targets: Vec<Target>,
primary: Option<Target>,
}
impl Selection {
pub fn new(scope: Scope) -> Self {
Self {
scope,
targets: Vec::new(),
primary: None,
generation: 0,
}
}
pub fn scope(&self) -> Scope {
self.scope
}
pub fn targets(&self) -> &[Target] {
&self.targets
}
pub fn primary(&self) -> Option<&Target> {
self.primary.as_ref()
}
pub fn contains(&self, target: &Target) -> bool {
self.targets.contains(target)
}
/// Replace with one valid target. Rejected admission preserves the old set.
pub fn replace(&mut self, target: Target, valid: impl FnOnce(&Target) -> bool) -> bool {
if !admitted(&target, valid) || (self.targets.len() == 1 && self.contains(&target)) {
return false;
}
self.targets = vec![target.clone()];
self.primary = Some(target);
self.changed();
true
}
/// Add a new member as primary. Adding an existing exact target is a no-op.
pub fn add(&mut self, target: Target, valid: impl FnOnce(&Target) -> bool) -> bool {
if !admitted(&target, valid) || self.contains(&target) {
return false;
}
self.targets.push(target.clone());
self.primary = Some(target);
self.changed();
true
}
/// Removal is allowed even if the target is no longer valid in the model.
pub fn remove(&mut self, target: &Target) -> bool {
let Some(index) = self.targets.iter().position(|member| member == target) else {
return false;
};
self.targets.remove(index);
if self.primary.as_ref() == Some(target) {
self.primary = self.targets.last().cloned();
}
self.changed();
true
}
pub fn toggle(&mut self, target: Target, valid: impl FnOnce(&Target) -> bool) -> bool {
if self.contains(&target) {
self.remove(&target)
} else {
self.add(target, valid)
}
}
/// Inspect another selected member without changing membership or its order.
pub fn set_primary(&mut self, target: &Target) -> bool {
if !self.contains(target) || self.primary.as_ref() == Some(target) {
return false;
}
self.primary = Some(target.clone());
self.changed();
true
}
pub fn clear(&mut self) -> bool {
if self.targets.is_empty() {
return false;
}
self.targets.clear();
self.primary = None;
self.changed();
true
}
/// Change owner or prune exact targets against the current rendered surface.
/// The predicate checks identity/visibility, not eligibility for one action.
/// Revision-only changes may retain survivors; no semantic retargeting occurs.
pub fn reconcile(&mut self, scope: Scope, valid: impl FnMut(&Target) -> bool) -> bool {
if self.scope != scope {
self.scope = scope;
self.targets.clear();
self.primary = None;
self.changed();
return true;
}
let previous_len = self.targets.len();
self.targets.retain(valid);
if self.targets.len() == previous_len {
return false;
}
if !self
.primary
.as_ref()
.is_some_and(|target| self.contains(target))
{
self.primary = self.targets.last().cloned();
}
self.changed();
true
}
/// Capture input, including an empty selection before a first pointer press.
/// Does not grant permission to mutate; adapters still guard drafts, modals,
/// capability and geometry. A mismatched owner cannot capture a snapshot.
pub fn snapshot(&self, context: Context) -> Option<Snapshot> {
if context.scope != self.scope {
return None;
}
Some(Snapshot {
context,
generation: self.generation,
targets: self.targets.clone(),
primary: self.primary.clone(),
})
}
/// Check before any operation side effect, using the caller's live context.
/// Generation rejects remove/re-add and primary-change/restore ABA cycles.
pub fn matches(&self, snapshot: &Snapshot, current: Context) -> bool {
snapshot.context == current
&& current.scope == self.scope
&& snapshot.generation == self.generation
&& snapshot.targets == self.targets
&& self.primary == snapshot.primary
}
fn changed(&mut self) {
self.generation = self
.generation
.checked_add(1)
.expect("selection generation exhausted");
}
}
impl Snapshot {
pub fn context(&self) -> Context {
self.context
}
pub fn targets(&self) -> &[Target] {
&self.targets
}
pub fn primary(&self) -> Option<&Target> {
self.primary.as_ref()
}
}
fn admitted(target: &Target, valid: impl FnOnce(&Target) -> bool) -> bool {
!matches!(target, Target::Whole) && valid(target)
}
#[cfg(test)]
mod tests {
use super::*;
use oa_core::OccurrenceEndpoint;
fn id(value: u128) -> Id {
Id::from_u128(value)
}
fn scope() -> Scope {
Scope {
document: id(1),
surface: Surface::Saved(id(2)),
}
}
fn context() -> Context {
Context {
scope: scope(),
revision: 7,
epoch: 11,
}
}
fn node(value: u128) -> Target {
Target::Placement(id(value))
}
#[test]
fn exact_duplicates_are_noops_but_distinct_visual_identities_survive() {
let mut selection = Selection::new(scope());
let port_a = Target::Port {
port: id(30),
placement: id(3),
};
let port_b = Target::Port {
port: id(30),
placement: id(4),
};
assert!(selection.add(node(3), |_| true));
assert!(selection.add(port_a.clone(), |_| true));
let captured = selection.snapshot(context()).unwrap();
assert!(!selection.add(node(3), |_| true));
assert!(!selection.add(port_a.clone(), |_| true));
assert!(selection.matches(&captured, context()));
assert!(selection.add(port_b.clone(), |_| true));
assert_eq!(selection.targets(), &[node(3), port_a, port_b.clone()]);
assert_eq!(selection.primary(), Some(&port_b));
assert_eq!(
captured.targets(),
&[
node(3),
Target::Port {
port: id(30),
placement: id(3)
}
]
);
}
#[test]
fn primary_removal_uses_latest_survivor_without_reordering() {
let mut selection = Selection::new(scope());
for value in [3, 4, 5] {
selection.add(node(value), |_| true);
}
assert!(selection.set_primary(&node(3)));
assert_eq!(selection.targets(), &[node(3), node(4), node(5)]);
assert!(!selection.set_primary(&node(99)));
assert!(selection.remove(&node(4)));
assert_eq!(selection.primary(), Some(&node(3)));
assert!(selection.remove(&node(3)));
assert_eq!(selection.primary(), Some(&node(5)));
// A now-invalid member remains removable; validity applies to additions.
assert!(selection.toggle(node(5), |_| false));
assert!(selection.targets().is_empty());
assert_eq!(selection.primary(), None);
let empty = selection.snapshot(context()).unwrap();
assert!(empty.targets().is_empty());
assert_eq!(empty.primary(), None);
assert!(selection.matches(&empty, context()));
selection.add(node(5), |_| true);
assert!(!selection.matches(&empty, context()));
}
#[test]
fn whole_and_rejected_targets_cannot_replace_an_existing_selection() {
let mut selection = Selection::new(scope());
selection.add(node(3), |_| true);
let captured = selection.snapshot(context()).unwrap();
assert!(!selection.replace(Target::Whole, |_| true));
assert!(!selection.add(Target::Whole, |_| true));
assert!(!selection.toggle(Target::Whole, |_| true));
assert!(!selection.replace(node(4), |_| false));
assert!(!selection.toggle(node(4), |_| false));
assert!(selection.matches(&captured, context()));
assert!(selection.replace(node(4), |_| true));
assert_eq!(selection.targets(), &[node(4)]);
assert_eq!(selection.primary(), Some(&node(4)));
assert!(!selection.replace(node(4), |_| true));
assert!(selection.clear());
assert!(!selection.clear());
assert_eq!(selection.primary(), None);
}
#[test]
fn reused_process_occurrences_reconcile_by_full_path_never_definition() {
let owner = Scope {
surface: Surface::Process(id(2)),
..scope()
};
let mut selection = Selection::new(owner);
let occurrence = |path| {
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![id(path), id(50)],
occurrence: id(60),
})
};
let first = occurrence(10);
let second = occurrence(20);
selection.add(first.clone(), |_| true);
selection.add(second.clone(), |_| true);
assert_eq!(selection.targets(), &[first.clone(), second.clone()]);
assert!(selection.reconcile(owner, |target| target == &first));
assert_eq!(selection.targets(), std::slice::from_ref(&first));
assert_eq!(selection.primary(), Some(&first));
// A new call path with the same definition is not a replacement identity.
let replacement = occurrence(70);
assert!(selection.reconcile(owner, |target| target == &replacement));
assert!(selection.targets().is_empty());
assert_eq!(selection.primary(), None);
}
#[test]
fn revision_reconciliation_retains_exact_survivors_but_invalidates_operations() {
let mut selection = Selection::new(scope());
selection.add(node(3), |_| true);
selection.add(node(4), |_| true);
selection.set_primary(&node(3));
let captured = selection.snapshot(context()).unwrap();
let next = Context {
revision: 8,
..context()
};
assert!(!selection.reconcile(scope(), |_| true));
assert_eq!(selection.targets(), &[node(3), node(4)]);
assert_eq!(selection.primary(), Some(&node(3)));
assert!(!selection.matches(&captured, next));
let accepted = selection.snapshot(next).unwrap();
assert!(selection.matches(&accepted, next));
assert!(selection.reconcile(scope(), |target| target != &node(4)));
assert_eq!(selection.primary(), Some(&node(3)));
assert!(!selection.matches(&accepted, next));
}
#[test]
fn changing_document_or_surface_clears_even_identical_target_ids() {
for changed in [
Scope {
document: id(99),
..scope()
},
Scope {
surface: Surface::Saved(id(99)),
..scope()
},
Scope {
surface: Surface::Scenario(id(2)),
..scope()
},
] {
let mut selection = Selection::new(scope());
selection.add(node(3), |_| true);
let captured = selection.snapshot(context()).unwrap();
assert!(selection.reconcile(changed, |_| true));
assert_eq!(selection.scope(), changed);
assert!(selection.targets().is_empty());
assert_eq!(selection.primary(), None);
assert!(!selection.matches(&captured, context()));
assert!(selection.snapshot(context()).is_none());
selection.reconcile(scope(), |_| true);
selection.add(node(3), |_| true);
assert!(!selection.matches(&captured, context()));
}
}
#[test]
fn stale_epoch_selection_and_primary_cycles_do_not_regain_authority() {
let mut selection = Selection::new(scope());
selection.add(node(3), |_| true);
selection.add(node(4), |_| true);
let captured = selection.snapshot(context()).unwrap();
assert_eq!(captured.context(), context());
assert_eq!(captured.primary(), Some(&node(4)));
assert!(!selection.matches(
&captured,
Context {
epoch: 12,
..context()
}
));
selection.set_primary(&node(3));
selection.set_primary(&node(4));
assert!(!selection.matches(&captured, context()));
let restored_primary = selection.snapshot(context()).unwrap();
selection.remove(&node(4));
selection.add(node(4), |_| true);
assert_eq!(selection.targets(), captured.targets());
assert_eq!(selection.primary(), captured.primary());
assert!(!selection.matches(&restored_primary, context()));
assert!(selection.matches(&selection.snapshot(context()).unwrap(), context()));
}
}
+1
View File
@@ -10,6 +10,7 @@ mod data_values;
mod data_view;
mod diagnostic_input;
mod diagram;
mod diagram_selection;
mod diagram_usage;
mod document;
mod explorer;
+149 -4
View File
@@ -12,6 +12,7 @@ pub struct Request {
pub anchor: Point,
pub object: Id,
pub placement: Option<Id>,
pub selection_target: Option<Box<crate::diagram_usage::Target>>,
pub bend: Option<usize>,
pub route_point: Option<Position>,
pub route_segment: Option<(usize, Position)>,
@@ -25,6 +26,7 @@ impl Request {
anchor,
object,
placement: None,
selection_target: None,
bend: None,
route_point: None,
route_segment: None,
@@ -55,6 +57,7 @@ pub struct Opened {
impl Opened {
pub fn new(app: &App, request: Request, token: u64) -> Option<Self> {
if !app.project().contains(request.object)
|| !target_matches(app, &request)
|| request
.canvas
.is_some_and(|c| Some(c) != current_canvas(app))
@@ -80,6 +83,7 @@ impl Opened {
&& self.layer == app.layer
&& self.diagram == current_diagram(app)
&& app.project().contains(self.request.object)
&& target_matches(app, &self.request)
&& self
.request
.canvas
@@ -92,6 +96,32 @@ impl Opened {
}
}
fn target_matches(app: &App, request: &Request) -> bool {
use crate::diagram_usage::Target;
let Some(target) = request.selection_target.as_deref() else {
return true;
};
if request.canvas.is_none() || !app.multiselect_target_visible(target) {
return false;
}
match target {
Target::Placement(id) => {
request.placement == Some(*id)
&& request
.canvas
.and_then(|context| app.project().diagrams.get(&context.diagram))
.and_then(|diagram| diagram.nodes.get(id))
.is_some_and(|node| node.element == request.object || node.id == request.object)
}
Target::Port { port, .. } => request.placement.is_none() && *port == request.object,
Target::Edge(id) => request.placement.is_none() && *id == request.object,
Target::StateRow { relation, .. } => {
request.placement.is_none() && *relation == request.object
}
_ => false,
}
}
fn current_canvas(app: &App) -> Option<route_edit::Context> {
if app.page == Page::Behavior {
app.state_context()
@@ -126,7 +156,22 @@ pub fn trigger(app: &App) -> iced::Element<'_, Message> {
request.canvas = app.route_context();
} else if app.page == Page::Behavior {
request.canvas = app.state_context();
if let Some(context) = request.canvas
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 {
crate::diagram_usage::Target::Placement(id) => {
if let Some(node) = request
.canvas
.and_then(|c| app.project().diagrams.get(&c.diagram))
.and_then(|d| d.nodes.get(id))
{
request.object = node.element;
}
Some(*id)
}
_ => None,
};
} else if let Some(context) = request.canvas
&& let Some(node) = app.project().diagrams[&context.diagram]
.nodes
.values()
@@ -187,12 +232,112 @@ pub fn popup(app: &App) -> Option<Menu<Message>> {
on_close: Message::Menu(Event::Close),
});
}
if app.page == Page::Behavior
&& let Some(menu) = crate::behavior::state_menu::popup(app, opened, clean)
let mut entries = vec![Entry::title(crate::views::short(p.named(id), 38))];
if request.canvas.is_some()
&& let Some(context) = app.multiselect_context()
{
use crate::app::multiselect::{Choice, Event as SelectionEvent};
use crate::diagram_usage::Target;
let view = request
.canvas
.map(|context| context.diagram)
.map(|d| projection::project_view_with_index(p, d, app.document.view_index()));
let target = request
.selection_target
.as_deref()
.cloned()
.or_else(|| request.placement.map(Target::Placement))
.or_else(|| {
view.as_ref()?
.ports
.iter()
.find(|port| port.element == id)
.map(|port| Target::Port {
port: port.element,
placement: port.owner,
})
})
.or_else(|| {
view.as_ref()?
.edges
.iter()
.any(|edge| edge.id == id)
.then_some(Target::Edge(id))
});
if let Some(target) = target {
let selected = app
.diagram_selection
.as_ref()
.is_some_and(|s| s.contains(&target));
entries.push(item(
if selected {
"Remove from selection"
} else {
"Add to selection"
},
Message::DiagramSelection(SelectionEvent::Choose(
context,
target.clone(),
if selected {
Choice::Remove
} else {
Choice::Add
},
)),
true,
));
if let Some(snapshot) = app.multiselect_snapshot().filter(|s| s.targets().len() > 1)
&& selected
{
entries.push(Entry::title(format!(
"{} selected",
snapshot.targets().len()
)));
entries.push(item(
"Inspect this element",
Message::DiagramSelection(SelectionEvent::Choose(
context,
target.clone(),
Choice::Inspect,
)),
true,
));
entries.push(item(
"Select only this element",
Message::DiagramSelection(SelectionEvent::Choose(
context,
target,
Choice::Replace,
)),
true,
));
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)",
));
return Some(Menu {
token: opened.token,
anchor: request.anchor,
entries,
on_close: Message::Menu(Event::Close),
});
}
entries.push(Entry::separator());
}
}
if app.page == Page::Behavior
&& let Some(mut menu) = crate::behavior::state_menu::popup(app, opened, clean)
{
if entries.len() > 1 {
entries.extend(menu.entries.into_iter().skip(1));
menu.entries = entries;
}
return Some(menu);
}
let mut entries = vec![Entry::title(crate::views::short(p.named(id), 38))];
if !clean {
entries.push(Entry::title("Apply or revert pending edits first"));
}
+57 -4
View File
@@ -468,6 +468,7 @@ fn diagram(app: &App) -> View<'_, Message> {
.align_y(iced::Center);
let canvas: View<'_, Message> = if let Some(id) = app.active_diagram {
let program = DiagramCanvas {
selection: app.diagram_selection.as_ref(),
allocation: Some(app.allocation_capability()),
project: app.project(),
view_index: Some(app.document.view_index()),
@@ -621,6 +622,37 @@ fn diagram(app: &App) -> View<'_, Message> {
)
.is_some_and(|(source, target)| source != edge.source || target != edge.target)
});
let selection = app.multiselect_snapshot();
let count = selection.as_ref().map_or(0, |s| s.targets().len());
let mut selection_controls =
row![label(format!("{count} selected")).wrapping(widget::text::Wrapping::None)]
.spacing(7)
.align_y(iced::Center)
.height(32);
if let Some(snapshot) = selection.as_ref().filter(|s| s.targets().len() > 1) {
if crate::app::multiselect::placements(snapshot).is_some() {
selection_controls = selection_controls.push(action(
"Hide selected",
Message::DiagramSelection(crate::app::multiselect::Event::Hide(
snapshot.clone(),
)),
));
}
selection_controls = selection_controls
.push(action(
"Clear selection",
Message::DiagramSelection(crate::app::multiselect::Event::Clear(
snapshot.context(),
)),
))
.push(
label(format!(
"Properties edit only {}",
short(app.project().named(app.selected), 36)
))
.wrapping(widget::text::Wrapping::None),
);
}
let hint = if let Some(feedback) = &app.allocation_drag.feedback {
feedback.text.as_str()
} else if let Some(session) = &app.connection {
@@ -633,16 +665,37 @@ fn diagram(app: &App) -> View<'_, Message> {
} else {
session.tool.hint()
}
} else if count > 1 {
if selection
.as_ref()
.is_some_and(|s| crate::app::multiselect::placements(s).is_some())
&& projection != Some(ProjectionKind::Allocation)
{
"Shift-click to add/remove · drag selected to move · right-click for actions · scroll to zoom"
} else {
"Shift-click to add/remove · right-click for selection actions · Esc clears selection"
}
} else if promoted {
"Expand endpoint containers to edit this connection route"
} else if edge.is_some() {
"Right-click for routing · drag line / bend / label · Insert adds a bend · Esc cancels"
} else {
"Right-click for actions · drag to arrange · scroll to zoom"
"Shift-click to add/remove · right-click for actions · drag to arrange · scroll to zoom"
};
// Status is outside the measured canvas. Clipping prevents long text
// from painting over work headers or the dedicated destination slot.
tools = tools.push(container(label(hint)).height(30).width(Fill).clip(true));
// Selection changes must not resize the measured canvas or refit its
// camera. Reserve both rows even when no group actions are available.
tools = tools.push(
container(
column![
selection_controls,
label(hint).wrapping(widget::text::Wrapping::None)
]
.spacing(3),
)
.height(56)
.width(Fill)
.clip(true),
);
}
column![container(tools).padding(14), canvas].into()
}
+9
View File
@@ -489,3 +489,12 @@ Missing global and scoped parameter IDs remain explicit stabilization metadata,
not new random identities assigned on each parse. Public source8 integration must
thread the same accounting through the outer project and included files; this
private checkpoint does not itself admit a complete version8 source bundle.
## Connection-end presentation preferences — 2026-09-22
Issue #33 uses optional side/fraction attachments on each view's `EdgeRoute`,
with semantic Port precedence and shared shape-aware routing. Visual attachment
editing remains separate from semantic reconnect. The [decision and evidence
map](edge-attachments-20260922.md) records alternatives, lifecycle rules,
independent falsifiers, evaluators and the Process/Scenario applicability limits.
This is branch-specific work; it does not establish an integrated release.
+103
View File
@@ -0,0 +1,103 @@
# Connection attachment editing — issue 33
Branch-specific work from `3f9e6a18af96b5cd10940da4093be8da28b9c835` on
`codex/edge-anchors-ytr83r-20260922`, owned by Codex-ytr83r/root.
[Live scope and handoff](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/33)
remain in Gitea. This is not an integrated release checkpoint.
The user needs to move where a connection touches an element without changing
the relationship. The existing ordinary route editor offered bends and labels;
unported ends were selected from four side midpoints. SA semantic ports already
had per-placement anchors. State endpoint handles instead performed semantic
reconnect. These are different operations and remain distinct.
## Decision and alternatives
Store optional `source_attachment` and `target_attachment` values on `EdgeRoute`.
Each contains a side and normalized fraction, interpreted against the actual
projected shape. No additional semantic object, ID or reference is introduced.
The precise format, geometry, Port precedence, folding, reconnect and reset rules
are in [the normative language contract](../docs/language.rst); REST uses the
same data and existing `SetEdgeRoute` transaction.
Compared alternatives:
- Absolute endpoint coordinates are easy to store but become detached from the
owner after movement/resizing and duplicate derived geometry.
- Reusing semantic Port anchors would invent ports for OA/state relationships
and conflate each connection's presentation with a shared port's identity.
- Binding an attachment to an additional semantic endpoint/placement reference
would preserve the old owner's identity after reconnect, but needs stale
reference cleanup and a dormant preference lifecycle without a current user
need. The selected rule retains the edge-end preference across reconnect,
just as authored bends are retained; it is documented, not inferred silently.
Fractions remain precise in source/API; pointer edits snap to hundredths.
Automatic absence and authored values are distinct. Press/release without a
drag, Escape, stale context, focus/camera/layout change and outside release do
not author a preference. Returning within three screen pixels of the press
restores the exact initial optional value, including its original precision.
Successful editing changes one field in one route in one view in one history
operation. Per-end reset preserves the other end, bends and label.
Ordinary diagrams expose eligible selected-end handles and explicit source/target
menu choice for overlapping handles. State menus expose separately labelled
Adjust attachment and Reconnect actions; selecting a transition still retains
the existing reconnect gesture. Ports keep their existing movement policy.
This work does not adopt or alter the separate #16 resize/port-capacity policy.
## Review-driven corrections and evaluators
Independent contract review identified projection-filtered Port markers as an
unsafe authority: eligibility and routing now consult semantic endpoint identity.
Attachment metadata participates in the route-preview cache key. Inset contours
use actual lead lengths for path costs and pin fractions; shape scan-line
intersections are shared by routing and pointer gestures. Side choice uses the
nearest cardinal bounding segment, avoiding coincident circle scan-line points
that otherwise retain the wrong exit direction. Hysteresis is capped by symbol
size so small circles can change sides at low zoom; an explicit regression
covers midpoint, overshoot and near-corner intent.
The first frozen gate exposed a remaining overshoot case: distances measured
from far outside a small symbol converged, keeping the previous perpendicular
side. Measuring side intent at the cursor clamped to the bounding box preserves
the intended side under overshoot. The failed gate is retained separately.
Valid Port-to-Port Item traces also omit projected port IDs; routing now resolves
the semantic port before looking up its visible, owner-qualified marker. An
actual trace regression checks moved anchors and unchanged trace metadata.
Coincident authored self ends previously threatened an empty candidate list.
They retain their positions and receive an explicit loop warning. A critic then
showed a fixed invented detour point could collide with a neighboring card even
though the opposite side was clear. Computed detours now consider both directions
and multiple bounded extents, preferring clear candidates. These points never
become persisted hard pins. Geometry tests exercise blockers on either side.
Cross-review found ordinary attachment drags survived camera/focus/layout
changes and outside release. They now carry a viewport stamp and cancel on those
changes, with an actual pointer-event cancellation matrix. The same review
reconciled return-to-press behavior across ordinary and State canvases.
Meaningful evaluators are `oa-core` integration tests `attachment_geometry`,
`attachment_lifecycle`, `attachment_trace_ports`, `attachment_workshop`,
`edge_attachments` and the existing routing/port/state suites; desktop ordinary
attachment and State pointer/planner tests; server `http::edge_attachments`
conditional transactions, exact source exports and restart. Tests compare complete
projects/source where applicable, not just attachment fields. Native acceptance
uses the [fixture and workflow plan](experiments/edge-attachments-20260922/native-plan.md).
Final test/native results and exact tested commit belong in the publication
handoff, not an unverified claim in this decision record.
## Applicability and integration limits
Process topology uses generated cards and qualified contextual addresses.
Scenario endpoints derive from lifelines, activations, lifecycle and time/order
notation. Neither renderer consumes ordinary `Diagram.routes`; their visual
editing requires separate notation-aware contracts. This change does not claim
to implement arbitrary attachment dragging there, or to resolve automatic
arrangement (#32) or State bend editing (#23).
The base includes ordinary Text work, not the separately published Scenario
spacing/inspector branches or the latest transition lifecycle branch. Integration
owner #27 must compose actual pushed commits and verify the combined result.
Linux/WSL verification remains paused by the user.
@@ -0,0 +1,70 @@
# Native endpoint attachment acceptance
This is a prepared plan, not a record of passed native checks. `native-fixture.arcadia` is a deliberately small schema-7 source fixture with 49 explicit stable UUIDs. The parent must parse and validate it with the candidate before staging a working copy. No GUI, compilation, or evaluator has been run for this preparation.
## Bind the run
Record the exact candidate commit, source/worktree cleanliness, GUI/runtime hashes, successful gate receipts, fixture hash and recipe hash. Keep an immutable baseline and a separate mutable working source; use an isolated profile. Record launch, normal close, stdout/stderr, saved checkpoints, and captures. Compile baseline and checkpoints to full typed Project values with the same pinned source evaluator. Use a baseline-derived expected Project with only the named field changes; compare the entire Project, not a JSON subset or screenshot. Source text formatting may differ after save; source must parse to the exact expected Project. Save/reopen comparisons must use the same expected Project. Preserve raw files and integer precision.
The fixture contains two OA activities and their one interaction, one small SA state machine, and a separate two-function semantic-port regression view. Its controller is semantic ownership, not a large canvas placement. The State view places the machine, region, and all five vertices. Two saved views per edited graph expose view-isolation failures. View 05 is separate to keep the main workflows uncluttered.
## Identities and geometry
Every ID has prefix `ea202922-0033-4000-8000-`; the twelve-digit suffix below is decimal-padded. The source file is authoritative for all fields.
| Object / alias | ID suffix | Purpose |
|---|---:|---|
| `dispatch_request` | 20 | Stored source `receive_report` (10), target `dispatch_crew` (11) |
| `dispatch_view` / `dispatch_reference` | 100 / 101 | Edited OA view / untouched OA view |
| `readiness` / `main_region` | 31 / 32 | Machine / region membership |
| `start`, `ready`, `active`, `decision`, `finished` | 33–37 | Initial, two stable states, choice, final |
| `activate` | 41 | Stored Ready source → Active target |
| `initialize` / `finish` | 40 / 44 | Circle-source / diamond-source contour checks |
| `refresh` / `internal_check` | 45 / 46 | External self-transition / internal row |
| `readiness_view` / `readiness_reference` | 200 / 201 | Edited State view / untouched State view |
| `status_exchange` / `ports_view` | 54 / 300 | Real semantic ports regression |
Coordinates below are **diagram coordinates**, not assumed native screen coordinates. After Fit, identify bounds and zoom/pan from actual UI; map `window = canvas origin + pan + zoom × diagram`. State canvas includes a guidance strip in its offset. Confirm painted handles before pressing; retain screenshots documenting the mapping. Source and target describe stored ends, regardless of arrow appearance.
| View / endpoint | Baseline attachment / contour point | Intended destination |
|---|---|---|
| OA `dispatch_request` source | Right 0.5 → (340,240) | Top 0.25 → (160,180) |
| OA `dispatch_request` target | Left 0.6 → (600,252) | Bottom 0.75 → (780,300) |
| State `activate` source | Right 0.5 → (430,270) | Top 0.25 → (250,210) |
| State `activate` target | Left 0.6 → (570,294) | Bottom 0.75 → (750,350) |
| State `initialize` initial source | Right 0.5 → (126,260) | Top 0.5 → (118,252) |
| State `finish` choice source | Right 0.5 → (698,444) | Top 0.5 → (684,430) |
| Real `status_out` / `status_in` | Right 0.5 → (340,240) / Left 0.5 → (600,240) | No attachment editing permitted |
For rounded corners, the quarter-width points are on the straight section. Circle and diamond checks intentionally use contour extrema with unambiguous 0.5 offsets. Native drag input may quantize to adjacent hundredths: if the intended fraction is not attained, do not change the expected oracle to match output. Repeat from the prior checkpoint using the painted geometry, or record the observed limitation and narrow the claim.
## OA workflow and exact expectations
1. Open view **01 Dispatch — edit attachments** and Fit. Select `Dispatch request` on its line. Confirm distinct endpoint handles and context actions. Save baseline checkpoint `00` before edits; full Project equals baseline B.
2. Drag source handle from (340,240) to (160,180), inspect live preview and release. Save `01`. Expected O1 = B with **only** `diagrams[100].routes[edge20].source_attachment = {Top,0.25}`. Target sentinel `{Left,0.6}`, waypoint `(440,340)`, label `{fraction:0.5,offset:(12,-18)}`, relation description/direction, nodes and all other views remain exact.
3. Undo and save `02`: B exactly. Redo and save `03`: O1 exactly. One Undo must remove the entire drag, not a partial movement.
4. Drag target to (780,300), save `04`: O2 = O1 with only target `{Bottom,0.75}`. Open source and target context actions to ensure end identity is clear. Use **Reset source attachment**, save `05`: O3 = O2 with source None; preserve target, waypoint and label. Undo returns O2, redo returns O3.
5. Start a drag, move away and return within three screen pixels of the press, then release: no source/history change. Repeat a drag canceled with Escape; repeat with right click, middle pan, wheel/camera change, focus loss, and release outside. Save a checkpoint after each meaningful cancellation; expect O3 exactly. Camera-only state is outside Project. After these checks, one Undo still reverses the last real reset (O2), showing no hidden history entry; Redo restores O3.
6. Open view **02 Dispatch — untouched reference**: its independent target `{Bottom,0.25}` and placements remain baseline. Return to 01, save, close normally, reopen the saved working file and save `06`: O3 exactly. Confirm the saved source contains the attachment and existing waypoint/label.
## State workflow and exact expectations
Continue from saved O3 so the State trial also proves preservation of the prior OA edits. The frozen expected catalog composes State changes on O3; B remains the unchanged comparison for view 201.
1. Open **Rescue readiness** in Behavior / State diagram and choose **03 Readiness — edit attachments**. Check source-defined membership is visible, with Ready and Active readable and no nested hierarchy. Select `Activate`; choose **Adjust source attachment** from its actions, then drag the highlighted source to (250,210). Save `S01`: S1 = O3 with only `diagrams[200].routes[edge41].source_attachment={Top,0.25}`. Preserve target `{Left,0.6}`, waypoint `(500,310)`, label `{fraction:0.5,offset:(8,-16)}`, all semantic transitions and view 201.
2. Undo → O3, redo → S1. Adjust target to (750,350), save `S02`: S2 adds only target `{Bottom,0.75}`. Reset target and save `S03`: S3 has target None, preserves source/bend/label. Cancel an attachment gesture with Escape and perform away-return and wheel interruption; checkpoints remain S3. View **04 Readiness — untouched reference** stays B exactly.
3. Choose `Initialize` → **Adjust source attachment**, drag the initial circle source to (118,252), save `S04`: S4 = S3 with only route edge40 source `{Top,0.5}`. Choose `Finish` → Adjust source, drag the choice source to (684,430), save `S05`: S5 = S4 with only route edge44 source `{Top,0.5}`. Capture both painted contours; the typed checkpoint is the persistence oracle. Undo/redo each as practical. Save/normal-close/reopen final checkpoint: S5 exactly.
4. Inspect external `Refresh: Active → Active`: both Adjust source and Adjust target must be discoverable and identify the corresponding end even on a self-transition. Inspect `Internal status check` row: it must not offer external attachment handles/actions. Do not infer every symbol was exercised from these checks.
5. **Separate reversible reconnect trial from S5:** with Select / move, drag the selected `Activate` target handle from Active to `Dispatch decision` (or use explicitly labelled Reconnect target). Expected R1 differs from S5 only in relation41's semantic target: 35 → 36. Route presentation fields and every other relation field remain unchanged. Undo must restore S5. This distinguishes semantic reconnect from Adjust; do not mix its checkpoint with S5. If cardinality/validity blocks the trial, record it and do not claim reconnect success without a valid alternative approved against source rules.
## Real semantic ports regression
Open **05 Status — semantic ports regression**. Select the `Readiness status` functional exchange. Both attachment Move/Reset actions must be disabled or absent because source_port52 and target_port53 remain authoritative. Drag Status output to its owner's Top/0.25 position through the established port-layout interaction, then Undo. That trial may change only the emitting node's port_anchor and must restore S5 exactly on Undo; relation/source_port/target_port identities must never change. No edge-attachment record should be created by port dragging. Record UI hit selection and full saved Project, then leave this trial out of the final OA/State checkpoint.
## Acceptance and limits
Require exact full-Project checks for every named checkpoint, normal-close/reopen retention, source/target discoverability, useful previews, and cancellation without hidden history. Inspect native fit/readability and any port/label/handle overlap; reduce claim or fix defects rather than interpreting screenshots as model proof. This fixture does not establish Process/Scenario authoring support, all state symbols, every projection, promoted/folded endpoints, continuous held-motion performance, or exact camera persistence. Those require separate evidence; targeted automated tests remain complementary. Runtime source parsing/validation and native execution are pending parent gates.
### Prepared layout clearance correction
The edited State view places Ready and Active at y=210 and Startup at y=252. The reference view intentionally retains its earlier positions. Region header clearance reaches y=180 (104 + 64 + 12); the planned Ready top lead now ends at y=192 (210 - 18), above the card but below the header obstacle. This changes only the three edited-view placements; the manual waypoint (500,310), both route labels, semantic objects, and reference view are preserved. `crates/oa-core/tests/attachment_workshop.rs` validates the fixture and routes the named edited edges at every planned checkpoint. Test execution is pending the parent gate; no clear-path claim is made from static inspection alone.
@@ -0,0 +1,3 @@
# Preserve the exact pinned evidence and verifier bytes through Git round trips.
* -text whitespace=cr-at-eol
incidents/**/*.arcadia whitespace=-blank-at-eof,cr-at-eol
@@ -0,0 +1,96 @@
# Closed multiselect gate evidence
This package preserves all 19 closed captures selected from
`.local/group-movement-gates`: 14 recorded exit 0, and five recorded exit 101.
Every run reports unchanged captured inputs. The five failures remain failures;
their complete original receipts and streams are included. See the separate
[saved-view report](../../../multiselect-saved-view-20260923.md) for scope and
native observations. These standard-library Python 3.10+ tools do not run Cargo,
Git, archived source or executables.
| Run | Recorded exit | Input files |
| --- | ---: | ---: |
| core-1 | 0 | 722 |
| core-2 | 101 | 729 |
| core-3 | 0 | 729 |
| desktop-1 | 101 | 727 |
| desktop-2 | 101 | 728 |
| desktop-3 | 0 | 729 |
| desktop-4 | 0 | 729 |
| desktop-5 | 0 | 729 |
| format-1 | 0 | 729 |
| format-2 | 0 | 729 |
| lint-1 | 101 | 729 |
| lint-2 | 0 | 729 |
| lint-3 | 0 | 729 |
| native-build-1 | 0 | 729 |
| native-build-2 | 0 | 729 |
| oracle-2 | 101 | 729 |
| oracle-3 | 0 | 729 |
| windows-build-1 | 0 | 729 |
| windows-build-2 | 0 | 729 |
Core-3, desktop-4, format-1, lint-2, native-build-1 and windows-build-1 share the
729-file map `55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb`.
Desktop-5, format-2, lint-3, native-build-2 and windows-build-2 share the distinct
729-file map `99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c`.
The [source identity verifier](../source/README.md) compares those maps with Git
commits `12a7352ddef5f69a144ead8219a50916233d63a9` and
`f6a6010baed9e6164a1fcc7ecd58256a562827d7`, respectively. Earlier maps retain
their own evidence scope; they are not reruns against the later source.
To validate this exact raw run list without writing a package, from the checkout
root run:
```text
python -B harness/experiments/multiselect-20260923/checks/prepare.py --root . --runs core-1 core-2 core-3 desktop-1 desktop-2 desktop-3 desktop-4 desktop-5 format-1 format-2 lint-1 lint-2 lint-3 native-build-1 native-build-2 oracle-2 oracle-3 windows-build-1 windows-build-2 --check-only
```
Missing closure, changed inputs, inconsistent receipts, unavailable exact helpers,
and extra/unexpected run files are refused. Run names must be supplied, must be
unique, and cannot contain path separators.
To create a package, use the same explicit `--runs` list, omit `--check-only`, and
optionally supply `--output PATH`. The default output is this checks directory.
An output package is not overwritten. `--helper PATH` can be repeated to supply
an older gate helper whose exact pinned bytes are no longer the current helper.
Default helper candidates are `.local/group-movement-gates/*.py`.
Verify a completed package anywhere, without the original checkout:
```text
python -B PATH_TO_PACKAGE/verify.py
```
The packager preserves the seven original files per run: started/process/result
receipts, stdout/stderr logs, the input map, and its source ZIP. It preserves the
exact helper bytes named by each receipt. Only byte-identical input maps and ZIPs
are deduplicated into hash-named capsules; their per-run logical mapping remains.
ZIP member ordering and timestamps are fixed. Raw input/log bytes are unchanged.
`manifest.json` records the explicit run list, outcomes, commands, recorded HEADs,
input counts, helper paths, logical mapping and every stored member pin.
`files.json` pins `prepare.py`, `verify.py`, this README, the manifest and archive.
The verifier checks safe exact ZIP membership (including nested source ZIPs),
every recorded byte count/hash, input counts, the 71 vendored iced_widget files,
start/process/finish order, receipt relationships, unchanged-input flags, helper
identity, and exact ordered executable-artifact records parsed from Cargo JSON
stdout. Missing JSON artifact records remain missing; they are not synthesized
from paths or inferred from a successful exit. Non-null artifact readback pins
are checked structurally; executable bytes are not included or independently
verified by this package.
The source capsules are **local historical input snapshots**, including captured
uncommitted work. A recorded HEAD alone does not identify their contents. They
are not an integrated release, a hermetic toolchain distribution, or a claim that
one run's gate applies to a later input map. Commands, paths, PIDs, times and
artifact hashes are historical receipts, not authenticated execution records.
The verifier checks their internal consistency and does not access historical
absolute paths, contact services, extract archives or rerun tests. Pin integrity
is not an external signature or proof against coordinated receipt alteration.
This package has no native interaction, focus, selection, movement, saved-model,
Undo/Redo or full #29 acceptance implication. The native evidence and its
independent evaluator belong in their separate reviewed record. The verification
summary reports captured outcomes, including failures; it does not declare the
feature or all captured gates successful.
@@ -0,0 +1,22 @@
{
"prepare.py": {
"bytes": 4818,
"sha256": "29eedcec091874b26572530517f015ab690ed1a9040abea52248e99603ba5f25"
},
"verify.py": {
"bytes": 8873,
"sha256": "c03513407073bef092d57b968f982b8ffc0c58e095f834fe7464c6a0e8454a9a"
},
"README.md": {
"bytes": 5001,
"sha256": "3f5232af2ebb12003c833e6bc6643b4858950ebf015435a9b850c6a826fe27d0"
},
"manifest.json": {
"bytes": 37083,
"sha256": "c23269443cd059895c672330720a10508ab8ecade0d3686ec3d82ff792c9b457"
},
"evidence.zip": {
"bytes": 25914867,
"sha256": "261660dd8a5e93d917c1d36cad19d1eec0b93e312d1e0dd15f9ea16f5e11c864"
}
}
@@ -0,0 +1,935 @@
{
"schema": 1,
"kind": "multiselect-cargo-gates",
"runs": {
"core-1": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-core",
"--test",
"group_movement",
"--test",
"state_diagrams",
"--",
"--nocapture"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 0,
"inputCount": 722,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"core-2": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-core",
"--test",
"group_movement",
"--test",
"state_diagrams",
"--example",
"multiselect_native",
"--",
"--nocapture"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 101,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"core-3": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-core",
"--test",
"group_movement",
"--test",
"state_diagrams",
"--example",
"multiselect_native",
"--",
"--nocapture"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"desktop-1": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-desktop",
"multiselect",
"--",
"--nocapture"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 101,
"inputCount": 727,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"desktop-2": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-desktop",
"--",
"--nocapture"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 101,
"inputCount": 728,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"desktop-3": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-desktop",
"--",
"--nocapture"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"desktop-4": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-desktop",
"--",
"--nocapture"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"desktop-5": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-desktop",
"--",
"--nocapture"
],
"head": "12a7352ddef5f69a144ead8219a50916233d63a9",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"format-1": {
"command": [
"cargo",
"fmt",
"--all",
"--",
"--check"
],
"head": "12a7352ddef5f69a144ead8219a50916233d63a9",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"format-2": {
"command": [
"cargo",
"fmt",
"--all",
"--",
"--check"
],
"head": "f6a6010baed9e6164a1fcc7ecd58256a562827d7",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"lint-1": {
"command": [
"cargo",
"clippy",
"--locked",
"--offline",
"-p",
"oa-core",
"-p",
"oa-desktop",
"--all-targets",
"--",
"-D",
"warnings"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 101,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"lint-2": {
"command": [
"cargo",
"clippy",
"--locked",
"--offline",
"-p",
"oa-core",
"-p",
"oa-desktop",
"--all-targets",
"--",
"-D",
"warnings"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"lint-3": {
"command": [
"cargo",
"clippy",
"--locked",
"--offline",
"-p",
"oa-core",
"-p",
"oa-desktop",
"--all-targets",
"--",
"-D",
"warnings"
],
"head": "12a7352ddef5f69a144ead8219a50916233d63a9",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"native-build-1": {
"command": [
"cargo",
"build",
"--locked",
"--offline",
"-p",
"oa-core",
"--example",
"multiselect_native",
"--message-format=json"
],
"head": "12a7352ddef5f69a144ead8219a50916233d63a9",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"native-build-2": {
"command": [
"cargo",
"build",
"--locked",
"--offline",
"-p",
"oa-core",
"--example",
"multiselect_native",
"--message-format=json"
],
"head": "f6a6010baed9e6164a1fcc7ecd58256a562827d7",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"oracle-2": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-core",
"--example",
"multiselect_native",
"--",
"--nocapture"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 101,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"oracle-3": {
"command": [
"cargo",
"test",
"--locked",
"--offline",
"-p",
"oa-core",
"--example",
"multiselect_native",
"--",
"--nocapture"
],
"head": "b8685416f56e53e30bd11ecf93a54cea10ac8458",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"windows-build-1": {
"command": [
"cargo",
"build",
"--locked",
"--offline",
"-p",
"oa-desktop",
"--bin",
"arcadia-studio",
"--message-format=json"
],
"head": "12a7352ddef5f69a144ead8219a50916233d63a9",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"windows-build-2": {
"command": [
"cargo",
"build",
"--locked",
"--offline",
"-p",
"oa-desktop",
"--bin",
"arcadia-studio",
"--message-format=json"
],
"head": "f6a6010baed9e6164a1fcc7ecd58256a562827d7",
"exitCode": 0,
"inputCount": 729,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
}
},
"logicalFiles": {
"cargo/core-1/inputs.json": "capsules/a73d565f90b14c986e0f87a7ac3d368c93e053b7e591cffdfa20d8e81e2eae08.json",
"cargo/core-1/inputs.zip": "capsules/2dcb54b1dd51a05cdd983432b114da8a08dce326c42b6e77a6b8772e75d2282f.zip",
"cargo/core-1/process.json": "cargo/core-1/process.json",
"cargo/core-1/result.json": "cargo/core-1/result.json",
"cargo/core-1/started.json": "cargo/core-1/started.json",
"cargo/core-1/stderr.log": "cargo/core-1/stderr.log",
"cargo/core-1/stdout.log": "cargo/core-1/stdout.log",
"cargo/core-2/inputs.json": "capsules/c5b23cd340869d57bd1bc4400041d499ea06a1a7619a6fd6b51e75278c1755e1.json",
"cargo/core-2/inputs.zip": "capsules/df441a733bf28d1c59eab52063ca4b2645067b490b0a2f0072f98fc9225ea2e8.zip",
"cargo/core-2/process.json": "cargo/core-2/process.json",
"cargo/core-2/result.json": "cargo/core-2/result.json",
"cargo/core-2/started.json": "cargo/core-2/started.json",
"cargo/core-2/stderr.log": "cargo/core-2/stderr.log",
"cargo/core-2/stdout.log": "cargo/core-2/stdout.log",
"cargo/core-3/inputs.json": "capsules/55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb.json",
"cargo/core-3/inputs.zip": "capsules/e1c7f3abe7b32616d1081b4a2bb8af2d6d4b071bc2a7cbdd61e96a92ffdc0533.zip",
"cargo/core-3/process.json": "cargo/core-3/process.json",
"cargo/core-3/result.json": "cargo/core-3/result.json",
"cargo/core-3/started.json": "cargo/core-3/started.json",
"cargo/core-3/stderr.log": "cargo/core-3/stderr.log",
"cargo/core-3/stdout.log": "cargo/core-3/stdout.log",
"cargo/desktop-1/inputs.json": "capsules/c1083b630ad79ed1fea6933de3221f05b8eb9200694fb0e5dbd637527803579c.json",
"cargo/desktop-1/inputs.zip": "capsules/8d6b08c2b1220cdb48d32cc74004cc9b82e4385f6f50a764f76c4a8630d070bf.zip",
"cargo/desktop-1/process.json": "cargo/desktop-1/process.json",
"cargo/desktop-1/result.json": "cargo/desktop-1/result.json",
"cargo/desktop-1/started.json": "cargo/desktop-1/started.json",
"cargo/desktop-1/stderr.log": "cargo/desktop-1/stderr.log",
"cargo/desktop-1/stdout.log": "cargo/desktop-1/stdout.log",
"cargo/desktop-2/inputs.json": "capsules/5f049dbbee443af86cde70efc74027f290a9bfbd434e5d644aa74ddb4e97566b.json",
"cargo/desktop-2/inputs.zip": "capsules/bf7dc41142e6d087f213b2914e0ffb0e9cd52294f5830301e5e5b78c3470f725.zip",
"cargo/desktop-2/process.json": "cargo/desktop-2/process.json",
"cargo/desktop-2/result.json": "cargo/desktop-2/result.json",
"cargo/desktop-2/started.json": "cargo/desktop-2/started.json",
"cargo/desktop-2/stderr.log": "cargo/desktop-2/stderr.log",
"cargo/desktop-2/stdout.log": "cargo/desktop-2/stdout.log",
"cargo/desktop-3/inputs.json": "capsules/6f8eae7613666bca412e62f67151d6fee9f5bd32fb50363d0ff9b9ac8b190acf.json",
"cargo/desktop-3/inputs.zip": "capsules/cc6233ddec2db0e322659a73a55e1681f5cb3554750ba183a756a29dadf8a8c9.zip",
"cargo/desktop-3/process.json": "cargo/desktop-3/process.json",
"cargo/desktop-3/result.json": "cargo/desktop-3/result.json",
"cargo/desktop-3/started.json": "cargo/desktop-3/started.json",
"cargo/desktop-3/stderr.log": "cargo/desktop-3/stderr.log",
"cargo/desktop-3/stdout.log": "cargo/desktop-3/stdout.log",
"cargo/desktop-4/inputs.json": "capsules/55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb.json",
"cargo/desktop-4/inputs.zip": "capsules/e1c7f3abe7b32616d1081b4a2bb8af2d6d4b071bc2a7cbdd61e96a92ffdc0533.zip",
"cargo/desktop-4/process.json": "cargo/desktop-4/process.json",
"cargo/desktop-4/result.json": "cargo/desktop-4/result.json",
"cargo/desktop-4/started.json": "cargo/desktop-4/started.json",
"cargo/desktop-4/stderr.log": "cargo/desktop-4/stderr.log",
"cargo/desktop-4/stdout.log": "cargo/desktop-4/stdout.log",
"cargo/desktop-5/inputs.json": "capsules/99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c.json",
"cargo/desktop-5/inputs.zip": "capsules/aa8bb3d7fbd1f73c36913235b0b1d3aa79f6ac418b6c07ade94a7dee4a617bd9.zip",
"cargo/desktop-5/process.json": "cargo/desktop-5/process.json",
"cargo/desktop-5/result.json": "cargo/desktop-5/result.json",
"cargo/desktop-5/started.json": "cargo/desktop-5/started.json",
"cargo/desktop-5/stderr.log": "cargo/desktop-5/stderr.log",
"cargo/desktop-5/stdout.log": "cargo/desktop-5/stdout.log",
"cargo/format-1/inputs.json": "capsules/55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb.json",
"cargo/format-1/inputs.zip": "capsules/e1c7f3abe7b32616d1081b4a2bb8af2d6d4b071bc2a7cbdd61e96a92ffdc0533.zip",
"cargo/format-1/process.json": "cargo/format-1/process.json",
"cargo/format-1/result.json": "cargo/format-1/result.json",
"cargo/format-1/started.json": "cargo/format-1/started.json",
"cargo/format-1/stderr.log": "cargo/format-1/stderr.log",
"cargo/format-1/stdout.log": "cargo/format-1/stdout.log",
"cargo/format-2/inputs.json": "capsules/99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c.json",
"cargo/format-2/inputs.zip": "capsules/aa8bb3d7fbd1f73c36913235b0b1d3aa79f6ac418b6c07ade94a7dee4a617bd9.zip",
"cargo/format-2/process.json": "cargo/format-2/process.json",
"cargo/format-2/result.json": "cargo/format-2/result.json",
"cargo/format-2/started.json": "cargo/format-2/started.json",
"cargo/format-2/stderr.log": "cargo/format-2/stderr.log",
"cargo/format-2/stdout.log": "cargo/format-2/stdout.log",
"cargo/lint-1/inputs.json": "capsules/292f6139450109875549801a1da337dac08a8bca4cfa0124139a5d8d042386b9.json",
"cargo/lint-1/inputs.zip": "capsules/d2ec5025067db2c05736bb1c9c9b6250d9199f1b7190e8c09f5a777424790c10.zip",
"cargo/lint-1/process.json": "cargo/lint-1/process.json",
"cargo/lint-1/result.json": "cargo/lint-1/result.json",
"cargo/lint-1/started.json": "cargo/lint-1/started.json",
"cargo/lint-1/stderr.log": "cargo/lint-1/stderr.log",
"cargo/lint-1/stdout.log": "cargo/lint-1/stdout.log",
"cargo/lint-2/inputs.json": "capsules/55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb.json",
"cargo/lint-2/inputs.zip": "capsules/e1c7f3abe7b32616d1081b4a2bb8af2d6d4b071bc2a7cbdd61e96a92ffdc0533.zip",
"cargo/lint-2/process.json": "cargo/lint-2/process.json",
"cargo/lint-2/result.json": "cargo/lint-2/result.json",
"cargo/lint-2/started.json": "cargo/lint-2/started.json",
"cargo/lint-2/stderr.log": "cargo/lint-2/stderr.log",
"cargo/lint-2/stdout.log": "cargo/lint-2/stdout.log",
"cargo/lint-3/inputs.json": "capsules/99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c.json",
"cargo/lint-3/inputs.zip": "capsules/aa8bb3d7fbd1f73c36913235b0b1d3aa79f6ac418b6c07ade94a7dee4a617bd9.zip",
"cargo/lint-3/process.json": "cargo/lint-3/process.json",
"cargo/lint-3/result.json": "cargo/lint-3/result.json",
"cargo/lint-3/started.json": "cargo/lint-3/started.json",
"cargo/lint-3/stderr.log": "cargo/lint-3/stderr.log",
"cargo/lint-3/stdout.log": "cargo/lint-3/stdout.log",
"cargo/native-build-1/inputs.json": "capsules/55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb.json",
"cargo/native-build-1/inputs.zip": "capsules/e1c7f3abe7b32616d1081b4a2bb8af2d6d4b071bc2a7cbdd61e96a92ffdc0533.zip",
"cargo/native-build-1/process.json": "cargo/native-build-1/process.json",
"cargo/native-build-1/result.json": "cargo/native-build-1/result.json",
"cargo/native-build-1/started.json": "cargo/native-build-1/started.json",
"cargo/native-build-1/stderr.log": "cargo/native-build-1/stderr.log",
"cargo/native-build-1/stdout.log": "cargo/native-build-1/stdout.log",
"cargo/native-build-2/inputs.json": "capsules/99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c.json",
"cargo/native-build-2/inputs.zip": "capsules/aa8bb3d7fbd1f73c36913235b0b1d3aa79f6ac418b6c07ade94a7dee4a617bd9.zip",
"cargo/native-build-2/process.json": "cargo/native-build-2/process.json",
"cargo/native-build-2/result.json": "cargo/native-build-2/result.json",
"cargo/native-build-2/started.json": "cargo/native-build-2/started.json",
"cargo/native-build-2/stderr.log": "cargo/native-build-2/stderr.log",
"cargo/native-build-2/stdout.log": "cargo/native-build-2/stdout.log",
"cargo/oracle-2/inputs.json": "capsules/ae16337dbc617e26b23468adb86d963e3bcf7eddf177e8fb4654c69019904548.json",
"cargo/oracle-2/inputs.zip": "capsules/e99bcaf1ab2becbcad0a005bdd0a4eb14fad2075bd7a38433857df4d3cad5e4d.zip",
"cargo/oracle-2/process.json": "cargo/oracle-2/process.json",
"cargo/oracle-2/result.json": "cargo/oracle-2/result.json",
"cargo/oracle-2/started.json": "cargo/oracle-2/started.json",
"cargo/oracle-2/stderr.log": "cargo/oracle-2/stderr.log",
"cargo/oracle-2/stdout.log": "cargo/oracle-2/stdout.log",
"cargo/oracle-3/inputs.json": "capsules/292f6139450109875549801a1da337dac08a8bca4cfa0124139a5d8d042386b9.json",
"cargo/oracle-3/inputs.zip": "capsules/d2ec5025067db2c05736bb1c9c9b6250d9199f1b7190e8c09f5a777424790c10.zip",
"cargo/oracle-3/process.json": "cargo/oracle-3/process.json",
"cargo/oracle-3/result.json": "cargo/oracle-3/result.json",
"cargo/oracle-3/started.json": "cargo/oracle-3/started.json",
"cargo/oracle-3/stderr.log": "cargo/oracle-3/stderr.log",
"cargo/oracle-3/stdout.log": "cargo/oracle-3/stdout.log",
"cargo/windows-build-1/inputs.json": "capsules/55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb.json",
"cargo/windows-build-1/inputs.zip": "capsules/e1c7f3abe7b32616d1081b4a2bb8af2d6d4b071bc2a7cbdd61e96a92ffdc0533.zip",
"cargo/windows-build-1/process.json": "cargo/windows-build-1/process.json",
"cargo/windows-build-1/result.json": "cargo/windows-build-1/result.json",
"cargo/windows-build-1/started.json": "cargo/windows-build-1/started.json",
"cargo/windows-build-1/stderr.log": "cargo/windows-build-1/stderr.log",
"cargo/windows-build-1/stdout.log": "cargo/windows-build-1/stdout.log",
"cargo/windows-build-2/inputs.json": "capsules/99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c.json",
"cargo/windows-build-2/inputs.zip": "capsules/aa8bb3d7fbd1f73c36913235b0b1d3aa79f6ac418b6c07ade94a7dee4a617bd9.zip",
"cargo/windows-build-2/process.json": "cargo/windows-build-2/process.json",
"cargo/windows-build-2/result.json": "cargo/windows-build-2/result.json",
"cargo/windows-build-2/started.json": "cargo/windows-build-2/started.json",
"cargo/windows-build-2/stderr.log": "cargo/windows-build-2/stderr.log",
"cargo/windows-build-2/stdout.log": "cargo/windows-build-2/stdout.log",
"helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"members": {
"capsules/292f6139450109875549801a1da337dac08a8bca4cfa0124139a5d8d042386b9.json": {
"bytes": 121985,
"sha256": "292f6139450109875549801a1da337dac08a8bca4cfa0124139a5d8d042386b9"
},
"capsules/2dcb54b1dd51a05cdd983432b114da8a08dce326c42b6e77a6b8772e75d2282f.zip": {
"bytes": 2885634,
"sha256": "2dcb54b1dd51a05cdd983432b114da8a08dce326c42b6e77a6b8772e75d2282f"
},
"capsules/55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb.json": {
"bytes": 121985,
"sha256": "55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb"
},
"capsules/5f049dbbee443af86cde70efc74027f290a9bfbd434e5d644aa74ddb4e97566b.json": {
"bytes": 121820,
"sha256": "5f049dbbee443af86cde70efc74027f290a9bfbd434e5d644aa74ddb4e97566b"
},
"capsules/6f8eae7613666bca412e62f67151d6fee9f5bd32fb50363d0ff9b9ac8b190acf.json": {
"bytes": 121984,
"sha256": "6f8eae7613666bca412e62f67151d6fee9f5bd32fb50363d0ff9b9ac8b190acf"
},
"capsules/8d6b08c2b1220cdb48d32cc74004cc9b82e4385f6f50a764f76c4a8630d070bf.zip": {
"bytes": 2903240,
"sha256": "8d6b08c2b1220cdb48d32cc74004cc9b82e4385f6f50a764f76c4a8630d070bf"
},
"capsules/99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c.json": {
"bytes": 121985,
"sha256": "99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c"
},
"capsules/a73d565f90b14c986e0f87a7ac3d368c93e053b7e591cffdfa20d8e81e2eae08.json": {
"bytes": 120844,
"sha256": "a73d565f90b14c986e0f87a7ac3d368c93e053b7e591cffdfa20d8e81e2eae08"
},
"capsules/aa8bb3d7fbd1f73c36913235b0b1d3aa79f6ac418b6c07ade94a7dee4a617bd9.zip": {
"bytes": 2918930,
"sha256": "aa8bb3d7fbd1f73c36913235b0b1d3aa79f6ac418b6c07ade94a7dee4a617bd9"
},
"capsules/ae16337dbc617e26b23468adb86d963e3bcf7eddf177e8fb4654c69019904548.json": {
"bytes": 121984,
"sha256": "ae16337dbc617e26b23468adb86d963e3bcf7eddf177e8fb4654c69019904548"
},
"capsules/bf7dc41142e6d087f213b2914e0ffb0e9cd52294f5830301e5e5b78c3470f725.zip": {
"bytes": 2909281,
"sha256": "bf7dc41142e6d087f213b2914e0ffb0e9cd52294f5830301e5e5b78c3470f725"
},
"capsules/c1083b630ad79ed1fea6933de3221f05b8eb9200694fb0e5dbd637527803579c.json": {
"bytes": 121652,
"sha256": "c1083b630ad79ed1fea6933de3221f05b8eb9200694fb0e5dbd637527803579c"
},
"capsules/c5b23cd340869d57bd1bc4400041d499ea06a1a7619a6fd6b51e75278c1755e1.json": {
"bytes": 121984,
"sha256": "c5b23cd340869d57bd1bc4400041d499ea06a1a7619a6fd6b51e75278c1755e1"
},
"capsules/cc6233ddec2db0e322659a73a55e1681f5cb3554750ba183a756a29dadf8a8c9.zip": {
"bytes": 2917494,
"sha256": "cc6233ddec2db0e322659a73a55e1681f5cb3554750ba183a756a29dadf8a8c9"
},
"capsules/d2ec5025067db2c05736bb1c9c9b6250d9199f1b7190e8c09f5a777424790c10.zip": {
"bytes": 2918296,
"sha256": "d2ec5025067db2c05736bb1c9c9b6250d9199f1b7190e8c09f5a777424790c10"
},
"capsules/df441a733bf28d1c59eab52063ca4b2645067b490b0a2f0072f98fc9225ea2e8.zip": {
"bytes": 2917518,
"sha256": "df441a733bf28d1c59eab52063ca4b2645067b490b0a2f0072f98fc9225ea2e8"
},
"capsules/e1c7f3abe7b32616d1081b4a2bb8af2d6d4b071bc2a7cbdd61e96a92ffdc0533.zip": {
"bytes": 2918309,
"sha256": "e1c7f3abe7b32616d1081b4a2bb8af2d6d4b071bc2a7cbdd61e96a92ffdc0533"
},
"capsules/e99bcaf1ab2becbcad0a005bdd0a4eb14fad2075bd7a38433857df4d3cad5e4d.zip": {
"bytes": 2917719,
"sha256": "e99bcaf1ab2becbcad0a005bdd0a4eb14fad2075bd7a38433857df4d3cad5e4d"
},
"cargo/core-1/process.json": {
"bytes": 210,
"sha256": "92e5a88b5b86400c13bad4d0a9d490466bb2ef0b6077d14930ac5084187b5506"
},
"cargo/core-1/result.json": {
"bytes": 1821,
"sha256": "c90e020e6d912516fbc5ef5b4bf6a5df5fc668e5f5e19a9108c29bf3723cea9c"
},
"cargo/core-1/started.json": {
"bytes": 1428,
"sha256": "230ea369285569a0fa179fe420b0b2133e7fcb2349601a53d69881e9a66bd39b"
},
"cargo/core-1/stderr.log": {
"bytes": 434,
"sha256": "84a1b0b7352dcde2fe51293feabbddf8e94206d9278e4a38e6d354af8a1bcd48"
},
"cargo/core-1/stdout.log": {
"bytes": 1671,
"sha256": "eb04561c11e394cc368ea1c5e38aa4b1dc8b5c3c44acb168469dd941f80f14e8"
},
"cargo/core-2/process.json": {
"bytes": 245,
"sha256": "020d6cb0ce6e4b9122ac2dcbd86c9c1719479f29d3690247182ade858caba12d"
},
"cargo/core-2/result.json": {
"bytes": 1870,
"sha256": "c97cbcd85b60a3476135bf9026d41868ea091061c12ce4bbc18a40c6023c5b3e"
},
"cargo/core-2/started.json": {
"bytes": 1473,
"sha256": "f367b289c9d378975514fa450e4fa25049f4461156417ba5bd6e79836faf401e"
},
"cargo/core-2/stderr.log": {
"bytes": 5287,
"sha256": "4ea6f38eef014ab8176c3ab1ed9d3be3addb4463a8f073425f1b5493b33a7c86"
},
"cargo/core-2/stdout.log": {
"bytes": 4138,
"sha256": "a2dfdb0d7c6c7ba7e9ef86063a815f43111188a44ae4b0e20717cc3e518b7c3d"
},
"cargo/core-3/process.json": {
"bytes": 245,
"sha256": "b26f22b0aed07e55906b024d1fd94198da1ab1d56363fc5ad66868940ae1c9a4"
},
"cargo/core-3/result.json": {
"bytes": 1867,
"sha256": "6d04a2818750491cb73ebb1b257d214316c048e1ac6165a119a27534d636406c"
},
"cargo/core-3/started.json": {
"bytes": 1473,
"sha256": "49e9d637eb063277925c577266a63e5fd06723ca24726d609dc0e458596e8316"
},
"cargo/core-3/stderr.log": {
"bytes": 539,
"sha256": "f05f7ab2f0244968100eb0e0a82808af8e42dceb5b5de70d034b7ae56bad9489"
},
"cargo/core-3/stdout.log": {
"bytes": 4797,
"sha256": "d0f2180aaecc3b253b473200b77348a19a21594e193ce45c21f040b7242be253"
},
"cargo/desktop-1/process.json": {
"bytes": 172,
"sha256": "d9ba2b6a0968b702af0aa857e7bb8667680eeddc32a0403781cd3d5e2467c067"
},
"cargo/desktop-1/result.json": {
"bytes": 1769,
"sha256": "2384c076e4bbc0e15951671e3a830725213c31cfcded0a27e1bb72802c576dbc"
},
"cargo/desktop-1/started.json": {
"bytes": 1375,
"sha256": "6b1ba478ebe5e14d5ee76199a56874a6a10156c2dd7e9d3830fd5ba5311094d6"
},
"cargo/desktop-1/stderr.log": {
"bytes": 4604,
"sha256": "6a47286c4daaf9f4ac8ac8cca3e98931f7812a44b192128aa67880c1ac930b87"
},
"cargo/desktop-1/stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/desktop-2/process.json": {
"bytes": 157,
"sha256": "cc037bab1ec44bd2e4095e165597f5e1d077bae5fce7a96c6a5fd814470d4244"
},
"cargo/desktop-2/result.json": {
"bytes": 1753,
"sha256": "9c037405572273086737e22b60796eff0745f4746ee3f25529f928da53c98fbc"
},
"cargo/desktop-2/started.json": {
"bytes": 1355,
"sha256": "18f71e571722bdb3696195623b3af3a2b9a45d38f98307a68049aacff3fbad9c"
},
"cargo/desktop-2/stderr.log": {
"bytes": 1085,
"sha256": "316e0179675fb071d7d9773d7073d771438ecd70e66c99559f4239e0638a3238"
},
"cargo/desktop-2/stdout.log": {
"bytes": 145051,
"sha256": "7c907317d106ff63347456b5ad2015fa8a9974ffbb7003d0a123afc99879ce42"
},
"cargo/desktop-3/process.json": {
"bytes": 157,
"sha256": "368d265e1ee5cceeb5995172c662dc3bc551591b9600a781c63ed64579760c24"
},
"cargo/desktop-3/result.json": {
"bytes": 1751,
"sha256": "32076fb49a6ddfcef63e77ca9f1edec34700ca80d36f32890581d56035f80054"
},
"cargo/desktop-3/started.json": {
"bytes": 1355,
"sha256": "da1ccd8352380b357d5954a70d86f2c51c8a2da8d1c4b553ca7b281d3000eab9"
},
"cargo/desktop-3/stderr.log": {
"bytes": 626,
"sha256": "5333e25e78f515449877867d0a2bf714b7cb3302c9497d4f4343a1e05e0f8b03"
},
"cargo/desktop-3/stdout.log": {
"bytes": 145562,
"sha256": "dc7e40a7d2ab1e78c74f0ee0344c4b2e5b1402bc6367e93a40780774000e4f81"
},
"cargo/desktop-4/process.json": {
"bytes": 157,
"sha256": "0823d0fbda95fe5efb08a7c11c98a7ac2409b5b3d170cf2e41b702895211abf4"
},
"cargo/desktop-4/result.json": {
"bytes": 1750,
"sha256": "d88b177e9d181f7c9c3685100c8676c0c8954cd0b071344ff5b4bb7a8e498865"
},
"cargo/desktop-4/started.json": {
"bytes": 1355,
"sha256": "0f9927d5c0b09c7fcc8922c68a2c88a4d840e0420a7be90193f566b02312a3d3"
},
"cargo/desktop-4/stderr.log": {
"bytes": 628,
"sha256": "992db238282b7acf1bbfeee7f2c459f9afe4bce814761d70df789e4f6239afcf"
},
"cargo/desktop-4/stdout.log": {
"bytes": 145802,
"sha256": "70c38e8c98cac4f220999481908beb549e5377f6f48c31931f9412ed25a67a41"
},
"cargo/desktop-5/process.json": {
"bytes": 157,
"sha256": "83bf9efc58fa5692f3ed038c107c081e5483d91117c73eddba62d3eb45cc7267"
},
"cargo/desktop-5/result.json": {
"bytes": 1751,
"sha256": "7cbbae8bbceec07cebb4696b999701cd29d46bfd047351aa3e20ea49d7c67ae6"
},
"cargo/desktop-5/started.json": {
"bytes": 1355,
"sha256": "0bfd2a6c185afb1b301e3b6b5f746d0e37251f147590aa2e9f25e370e99f53e8"
},
"cargo/desktop-5/stderr.log": {
"bytes": 631,
"sha256": "466f26c41956ed05629b633827d7ffca497c57c87ff67acff6351043c7bdefd4"
},
"cargo/desktop-5/stdout.log": {
"bytes": 146577,
"sha256": "e89cf5f2375fd40ae70261471d797cbaca5127cb27730e6094a616afa12514ae"
},
"cargo/format-1/process.json": {
"bytes": 116,
"sha256": "bb8e0a7620b40bb5f0932643848a57b0d207dde39006a9a20141c00f13d94284"
},
"cargo/format-1/result.json": {
"bytes": 1687,
"sha256": "967eeddb3fc6a0dc0fdf9a75f575d75fa8f8b0b5ea9c8a422590bcbece6de77b"
},
"cargo/format-1/started.json": {
"bytes": 1299,
"sha256": "ceb354dfbc4a41d72e496342e28475ddcce5a3c17a4e1553f0d699404c374657"
},
"cargo/format-1/stderr.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/format-1/stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/format-2/process.json": {
"bytes": 116,
"sha256": "aa31b91d224845b7dd1df777e865c88c5b8f55b66f173053be318132d1bc3870"
},
"cargo/format-2/result.json": {
"bytes": 1687,
"sha256": "c4d5529c8d2feae1b805bd8d404a3817053a5a0cd4ec341aa8c1e0a5c05eed5b"
},
"cargo/format-2/started.json": {
"bytes": 1299,
"sha256": "2ea70bb29d7fef73a194acd7aa36836fd4a54ae8a4be173f919cd2fc32e97919"
},
"cargo/format-2/stderr.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/format-2/stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/lint-1/process.json": {
"bytes": 196,
"sha256": "d30e400277dc0bb4a1618689b16ab86be7838cc1b42688185d655df235080286"
},
"cargo/lint-1/result.json": {
"bytes": 1808,
"sha256": "7ffb361d398def4520afc48683a69effbb8b066efd9442ba3b356c8124aae6d9"
},
"cargo/lint-1/started.json": {
"bytes": 1414,
"sha256": "771b5bdc31662fb3b4f76735e92b0e89d31a02188fbce35c5cfb0aea4c37c0ca"
},
"cargo/lint-1/stderr.log": {
"bytes": 1023,
"sha256": "9cbab357d810ce8164a0e614491f53529e61c1cad79793ca429e13897a8dc5ed"
},
"cargo/lint-1/stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/lint-2/process.json": {
"bytes": 196,
"sha256": "f4aed65014ed120dc72bd08160559ae0285bc5c4968305a5fb86cf29e8c0d347"
},
"cargo/lint-2/result.json": {
"bytes": 1805,
"sha256": "b873add4777fd8f7516513e2423f9d3eb4a40505a3b1fa7edfbee89fb5c7e0d3"
},
"cargo/lint-2/started.json": {
"bytes": 1414,
"sha256": "0d01a20ec0f7cd796c066c95936c74df0abf8947fca655d900a5bdd4f8dbd610"
},
"cargo/lint-2/stderr.log": {
"bytes": 207,
"sha256": "e6f76746d5864a4de1e9d238c74799e2080e2c6214f51b68a4692d5e15f5b107"
},
"cargo/lint-2/stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/lint-3/process.json": {
"bytes": 196,
"sha256": "620094b52dab8f23f389687cf72b8b3aa4effa55697842206a618293537eb869"
},
"cargo/lint-3/result.json": {
"bytes": 1805,
"sha256": "1e7dc472c03d653094850ed653599cee41e50d1639389bbc3fee45e40a754b5c"
},
"cargo/lint-3/started.json": {
"bytes": 1414,
"sha256": "b921ee7102386187c288c1b25aea96a3019ff00a4a508065aefbc4499b7c7818"
},
"cargo/lint-3/stderr.log": {
"bytes": 137,
"sha256": "d19e47547a69ce7956c74f2a65cd1064571985d073bcf497a11a0b0eebcfbd04"
},
"cargo/lint-3/stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/native-build-1/process.json": {
"bytes": 194,
"sha256": "390cb979d680b9fdb7e0afa05d6b9d10a25dc27abaff16596d113bb0b2142b43"
},
"cargo/native-build-1/result.json": {
"bytes": 3132,
"sha256": "35f76499ac2a49446b896932c963fd8734a5755e00e3511cedf1e584e7b17704"
},
"cargo/native-build-1/started.json": {
"bytes": 1397,
"sha256": "5f37fc095aa00eae8fae043651a29f387f484bf4a0cc454e3919ea4f49567126"
},
"cargo/native-build-1/stderr.log": {
"bytes": 130,
"sha256": "731d61ee089d75c107edcd02d2cdedcddaad57ec06607ccd0822d9dc71a72720"
},
"cargo/native-build-1/stdout.log": {
"bytes": 41700,
"sha256": "832dc599cad2c9ba28ff9153537fb428390d8f25959f5b4a080cd432f6bea0e8"
},
"cargo/native-build-2/process.json": {
"bytes": 194,
"sha256": "46ff130840d8b12272be43f479adeb0b2ace94ee1d5389c5638a61b22d732496"
},
"cargo/native-build-2/result.json": {
"bytes": 3131,
"sha256": "fbecac3b0f7913db5e2ad19043c7df167a92287833ddf3ea4f24766e86ae523b"
},
"cargo/native-build-2/started.json": {
"bytes": 1397,
"sha256": "cbd2c7ad98baddc3719a5c03bef103747d4cb5c560d631376149f116ede49584"
},
"cargo/native-build-2/stderr.log": {
"bytes": 60,
"sha256": "b2558545bbfa50a0f0c26623c0982eb5f96d71ea228d7c56180edbac0d0b295d"
},
"cargo/native-build-2/stdout.log": {
"bytes": 41699,
"sha256": "7884b8ea1a92d58c7174657560ec38ff9a073e52f93cc19a78290840f2ab5486"
},
"cargo/oracle-2/process.json": {
"bytes": 189,
"sha256": "1e8ffd7a03b22bf2ec43b0d66ae3cc98016a431c4a07499faf3ca0c635b92337"
},
"cargo/oracle-2/result.json": {
"bytes": 1789,
"sha256": "e0b7331751bae8564ee5c28d05029071f1c8460195e6f9e2f0d00a5ae4e05a16"
},
"cargo/oracle-2/started.json": {
"bytes": 1397,
"sha256": "b7a8278dfa2324f0c3ff6e9616a65ef7a51c99699ad700adfe90e2accc435765"
},
"cargo/oracle-2/stderr.log": {
"bytes": 520,
"sha256": "9dd8b849afdbbb2207a9ad82f1b6c6f07fd9cd0846fe4591f33c40fdadcbb3ac"
},
"cargo/oracle-2/stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/oracle-3/process.json": {
"bytes": 189,
"sha256": "a2cb30f512ee390bb03c9fcf5ea8069ca3a05da91f798985efc3f9f54670ace4"
},
"cargo/oracle-3/result.json": {
"bytes": 1791,
"sha256": "f0768fecc9f6711dd3cfc627c60aaf6118216bce47e76faa4cbdda571ac675e4"
},
"cargo/oracle-3/started.json": {
"bytes": 1397,
"sha256": "30cf614b6dede363ae4bdeca56fc4a1ddb7ee19a7e592b1b1616d4a98a53b535"
},
"cargo/oracle-3/stderr.log": {
"bytes": 307,
"sha256": "b4ccc583c5001d81b7208fe6f2e52788d0d40b63c7da034ca1fb90ec2adb18a4"
},
"cargo/oracle-3/stdout.log": {
"bytes": 2968,
"sha256": "e0a62ca8b008370c5a41378eb4c9e2a229a2fcde7bdba55426313c7d23da8aca"
},
"cargo/windows-build-1/process.json": {
"bytes": 189,
"sha256": "4e6b57dc0d5f10ac1b4af991f8b0f7558f4fc5b626e00f1a49c5782ea13abe18"
},
"cargo/windows-build-1/result.json": {
"bytes": 3082,
"sha256": "3cdd09a859288afe71dde6fb51bcc4bca84e47ceb9cb6389d57f6722d9e23fdf"
},
"cargo/windows-build-1/started.json": {
"bytes": 1392,
"sha256": "a3ebcdffc01e93fd5609005a0539eb11bf473b45bc28eee71dd175b943b387eb"
},
"cargo/windows-build-1/stderr.log": {
"bytes": 319,
"sha256": "7201ff3f71fe793907482992a00682023fc6ee1ac0a016f53a048b299ec2fffd"
},
"cargo/windows-build-1/stdout.log": {
"bytes": 284182,
"sha256": "3fc90b8c923415496c7990d33a5fe7211423b83df833a80111079fad71f04a2d"
},
"cargo/windows-build-2/process.json": {
"bytes": 189,
"sha256": "f18acb4c9feede438e1aa67bb86ce2d74f5b3aa0142499ae99b56b23daaf834b"
},
"cargo/windows-build-2/result.json": {
"bytes": 3081,
"sha256": "d7b191ee07c302ffed1017374b0c5d8b86245c0f3348fbac4778ae573397b9de"
},
"cargo/windows-build-2/started.json": {
"bytes": 1392,
"sha256": "b6a6656d966559060f01e87ccbd75837b0cf67e70c77246b20f587167bdbf651"
},
"cargo/windows-build-2/stderr.log": {
"bytes": 137,
"sha256": "aafe81cdd7c1e5558e957d4296d46e3238c72af79ba79d6147c5cc16f938d6ef"
},
"cargo/windows-build-2/stdout.log": {
"bytes": 284179,
"sha256": "cfba733cb79a9496004109bb0bc8b8996df5ec1645691fd79b952063faa519c5"
},
"helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py": {
"bytes": 3502,
"sha256": "6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06"
}
}
}
@@ -0,0 +1,90 @@
"""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/group-movement-gates"
candidates = sorted(gates.glob("*.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
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,
"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, default=HERE.parents[3], help="checkout holding .local/group-movement-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, default=HERE, help="package directory; existing evidence is never overwritten")
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")
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=True)
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,164 @@
"""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"]
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())
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])
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), "logicalFiles": len(logical), "storedMembers": len(stored), "sourceCapsulePairs": len(seen_capsules)}
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,35 @@
# Run-2 baseline checker environment incident
The first baseline checker invocation exited `3221225781` (`0xC0000135`) at
2026-09-23 09:07:10 UTC with empty stdout/stderr. The parent reported that this
shell omitted dot-sourcing the toolchain `env.ps1`. After that environment setup,
the same checker command succeeded at 09:08:08 UTC with a complete-Project PASS.
This records a checker-process launch incident, not a failure of the running GUI.
No particular missing DLL was measured or identified.
`run-2-baseline-runtime-environment/` is an exact copy of the failed snapshot:
started/result receipts, empty streams and all nine source files. Its unchanged
command text still names the original `run-2/snapshots/baseline` location; the
parent moved the failed directory aside before retrying. Paths in these records
are historical labels and have not been rewritten.
`retry-baseline/` preserves the successful retry's original started/result
receipts and streams. Direct comparison confirmed identical command, build
receipt, binary, helper, baseline and source pins between attempts. All three
unchanged flags are true in both results. The nine retry source files were
also compared byte for byte with the failed snapshot and are identical; they
are not duplicated here. The successful run's complete snapshots belong in the
separate native evidence package.
`helpers/check-snapshot-2.py` matches the helper pin in both receipts.
`helpers/env.ps1` preserves the environment setup script available when this
incident was packaged. It sets toolchain paths and runtime search paths and
contains no credentials. The checker receipts do not record the environment or
pin `env.ps1`, so the omitted/setup distinction is the parent's invocation
observation, not an independently measured environment comparison. Both scripts
are historical data; this package does not execute them.
The checker binary pin in both attempts is
`4de47a2b62192be6a1394e654f368be19e36fb966d60d6c833a5d51d18247bb1`.
`files.json` pins every included file except itself. Raw bytes are preserved.
No frozen checks, source-identity or native packaging tools were changed.
@@ -0,0 +1,82 @@
{
"helpers/check-snapshot-2.py": {
"bytes": 2494,
"sha256": "1dbfff41f07bd750d4e550660d91ae9790d2442fbfe685dc88b7f63a47f5acb8"
},
"helpers/env.ps1": {
"bytes": 621,
"sha256": "d7eb6249bef73adacdb05cebefe7ca478758c3c38de17a1731bf01f8b25dc379"
},
"README.md": {
"bytes": 2146,
"sha256": "d5a853c62713a6c87d28acfbe28c03bd95459275d0a2eb752d978e5a9b427bc8"
},
"retry-baseline/result.json": {
"bytes": 2758,
"sha256": "ae16cbc54bf5b6054750ef082f47bf0a26ee2dfb7bce46f19c8fd2c1ac622d7f"
},
"retry-baseline/started.json": {
"bytes": 2356,
"sha256": "e172a36f0872d49a8fe0f7200fb56d597b71fd1849dc9902d53ac1813a3c7d4a"
},
"retry-baseline/stderr.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"retry-baseline/stdout.log": {
"bytes": 441,
"sha256": "12842cc4e483e2546f5c8615b17fe72c5fe07f3fb4440469071433c82d9a9b30"
},
"run-2-baseline-runtime-environment/result.json": {
"bytes": 2765,
"sha256": "539b950952461cc300876dbc45fa9ee02a9ecefb6d712fce6b74bad3fa701b30"
},
"run-2-baseline-runtime-environment/source/oa/activities/activity_activity_a.arcadia": {
"bytes": 474,
"sha256": "9bf7c5637d87c97213cf869118e942e8a29a67b429fa58e4de42235bba0980ee"
},
"run-2-baseline-runtime-environment/source/oa/activities/activity_activity_b.arcadia": {
"bytes": 286,
"sha256": "152007669b7c570674aff99615a48a6f557be50f88bbbb3a5edc20b423c79a1f"
},
"run-2-baseline-runtime-environment/source/oa/activities/activity_activity_c.arcadia": {
"bytes": 153,
"sha256": "d726b6b4e1200edd9ef752bb767e38d3d69dcac8eb6135d5f83c93832ff849b1"
},
"run-2-baseline-runtime-environment/source/project.arcadia": {
"bytes": 597,
"sha256": "e7bd67c5785a78766298255ed3d53ff6d65dcd24bde1570ac8a0ff45cc9dc385"
},
"run-2-baseline-runtime-environment/source/sa/functions/function_sa_function.arcadia": {
"bytes": 162,
"sha256": "1c724a9204784435e729badd4ad164b1a6b891840bb1ddc354ac1e175e3d712c"
},
"run-2-baseline-runtime-environment/source/traceability.arcadia": {
"bytes": 522,
"sha256": "26b0b10715ced7aefcde941e6d1c1a6973f174997eae989e32a25c695dfb7cd1"
},
"run-2-baseline-runtime-environment/source/views/diagram_oa_other.arcadia": {
"bytes": 315,
"sha256": "06ceef9cfdbb3ef229a22db6c48d8bb808388e027c37294648555ecbfb6bfab9"
},
"run-2-baseline-runtime-environment/source/views/diagram_oa_view.arcadia": {
"bytes": 1896,
"sha256": "4e7d47d6a03153070687136c89faf01fc6df45ae89e2695beeab2fe4872dbc88"
},
"run-2-baseline-runtime-environment/source/views/diagram_sa_view.arcadia": {
"bytes": 331,
"sha256": "c75b0fe14496631c9b017a32e277d1e5ad5b25e00e06b804fc54d950d7fb57f6"
},
"run-2-baseline-runtime-environment/started.json": {
"bytes": 2356,
"sha256": "338c14c7dc827bd4ab09009bb974ad3c481b07cdbad2437f5291b1ff67b5ba42"
},
"run-2-baseline-runtime-environment/stderr.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"run-2-baseline-runtime-environment/stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
}
@@ -0,0 +1,41 @@
"""Copy stable native-saved source and check its complete Project independently."""
from pathlib import Path
import datetime, hashlib, json, re, shutil, subprocess, sys
root = Path('C:/ar-multiselect-9e8r6t')
native = root / '.local/multiselect-native'
label, mode, *rest = sys.argv[1:]
assert not rest and re.fullmatch('[a-z0-9-]+', label)
working = native / 'working-2'
out = native / 'run-2/snapshots' / label
out.mkdir(parents=True, exist_ok=False)
gate_path = root / '.local/group-movement-gates/native-build-2/result.json'
gate = json.loads(gate_path.read_bytes())
assert gate['exitCode'] == 0 and gate['inputsUnchanged']
artifact, = [a for a in gate['artifacts'] if a['cargo']['target']['name'] == 'multiselect_native']
binary = Path(artifact['cargo']['executable'])
baseline = native / 'fixture-2/baseline.json'
def pin(path):
b = path.read_bytes()
return {'bytes': len(b), 'sha256': hashlib.sha256(b).hexdigest()}
def inventory():
return {p.relative_to(working).as_posix():pin(p) for p in sorted(working.rglob('*.arcadia')) if p.is_file()}
def now(): return datetime.datetime.now(datetime.timezone.utc).isoformat()
before = inventory()
assert 'project.arcadia' in before and pin(binary) == artifact['readback']
for name in before:
target = out/'source'/name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(working/name, target)
assert before == inventory() == {name:pin(out/'source'/name) for name in before}
command = [str(binary), 'check', mode, str(baseline), str(out/'source/project.arcadia')]
start = {'start':now(), 'command':command, 'buildReceipt':pin(gate_path), 'binary':pin(binary), 'helper':pin(Path(__file__)), 'source':before, 'baseline':pin(baseline)}
(out/'started.json').write_text(json.dumps(start,indent=2),encoding='utf-8')
r = subprocess.run(command,cwd=root,capture_output=True)
(out/'stdout.log').write_bytes(r.stdout)
(out/'stderr.log').write_bytes(r.stderr)
result = {**start, 'finish':now(), 'exitCode':r.returncode, 'binaryUnchanged':pin(binary)==artifact['readback'], 'workingSourceUnchanged':before==inventory(), 'baselineUnchanged':pin(baseline)==start['baseline'], 'stdout':pin(out/'stdout.log'), 'stderr':pin(out/'stderr.log')}
(out/'result.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
print(r.stdout.decode(errors='replace'))
print(r.stderr.decode(errors='replace'))
assert result['binaryUnchanged'] and result['workingSourceUnchanged'] and result['baselineUnchanged']
sys.exit(r.returncode)
@@ -0,0 +1,9 @@
$taskRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$env:RUSTUP_HOME = Join-Path $taskRoot '.local\toolchain\rustup'
$env:CARGO_HOME = Join-Path $taskRoot '.local\toolchain\cargo'
$env:RUSTUP_TOOLCHAIN = 'stable-x86_64-pc-windows-gnullvm'
$env:PATH = "$env:CARGO_HOME\bin;$(Join-Path $taskRoot '.local\toolchain\llvm-mingw-20260826-ucrt-x86_64\bin');$env:PATH"
$env:CARGO_TARGET_DIR = Join-Path $taskRoot '.local\target-gnullvm'
# Keep this small development disk from accumulating multi-GiB incremental caches.
$env:CARGO_INCREMENTAL = '0'
$env:CARGO_TARGET_X86_64_PC_WINDOWS_GNULLVM_LINKER = 'clang.exe'
@@ -0,0 +1,77 @@
{
"start": "2026-09-23T09:08:07.906733+00:00",
"command": [
"C:\\Users\\User\\Documents\\Git\\ARCADIA-Studio\\.local\\target-gnullvm\\debug\\examples\\multiselect_native.exe",
"check",
"unchanged",
"C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\fixture-2\\baseline.json",
"C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\run-2\\snapshots\\baseline\\source\\project.arcadia"
],
"buildReceipt": {
"bytes": 3131,
"sha256": "fbecac3b0f7913db5e2ad19043c7df167a92287833ddf3ea4f24766e86ae523b"
},
"binary": {
"bytes": 22162432,
"sha256": "4de47a2b62192be6a1394e654f368be19e36fb966d60d6c833a5d51d18247bb1"
},
"helper": {
"bytes": 2494,
"sha256": "1dbfff41f07bd750d4e550660d91ae9790d2442fbfe685dc88b7f63a47f5acb8"
},
"source": {
"oa/activities/activity_activity_a.arcadia": {
"bytes": 474,
"sha256": "9bf7c5637d87c97213cf869118e942e8a29a67b429fa58e4de42235bba0980ee"
},
"oa/activities/activity_activity_b.arcadia": {
"bytes": 286,
"sha256": "152007669b7c570674aff99615a48a6f557be50f88bbbb3a5edc20b423c79a1f"
},
"oa/activities/activity_activity_c.arcadia": {
"bytes": 153,
"sha256": "d726b6b4e1200edd9ef752bb767e38d3d69dcac8eb6135d5f83c93832ff849b1"
},
"project.arcadia": {
"bytes": 597,
"sha256": "e7bd67c5785a78766298255ed3d53ff6d65dcd24bde1570ac8a0ff45cc9dc385"
},
"sa/functions/function_sa_function.arcadia": {
"bytes": 162,
"sha256": "1c724a9204784435e729badd4ad164b1a6b891840bb1ddc354ac1e175e3d712c"
},
"traceability.arcadia": {
"bytes": 522,
"sha256": "26b0b10715ced7aefcde941e6d1c1a6973f174997eae989e32a25c695dfb7cd1"
},
"views/diagram_oa_other.arcadia": {
"bytes": 315,
"sha256": "06ceef9cfdbb3ef229a22db6c48d8bb808388e027c37294648555ecbfb6bfab9"
},
"views/diagram_oa_view.arcadia": {
"bytes": 1896,
"sha256": "4e7d47d6a03153070687136c89faf01fc6df45ae89e2695beeab2fe4872dbc88"
},
"views/diagram_sa_view.arcadia": {
"bytes": 331,
"sha256": "c75b0fe14496631c9b017a32e277d1e5ad5b25e00e06b804fc54d950d7fb57f6"
}
},
"baseline": {
"bytes": 8944,
"sha256": "d1278e58cd31e1d61093292eddc1d7b2cc9c8cdc7fe5dd3801de8411af8db89d"
},
"finish": "2026-09-23T09:08:08.158861+00:00",
"exitCode": 0,
"binaryUnchanged": true,
"workingSourceUnchanged": true,
"baselineUnchanged": true,
"stdout": {
"bytes": 441,
"sha256": "12842cc4e483e2546f5c8615b17fe72c5fe07f3fb4440469071433c82d9a9b30"
},
"stderr": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
}
@@ -0,0 +1,64 @@
{
"start": "2026-09-23T09:08:07.906733+00:00",
"command": [
"C:\\Users\\User\\Documents\\Git\\ARCADIA-Studio\\.local\\target-gnullvm\\debug\\examples\\multiselect_native.exe",
"check",
"unchanged",
"C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\fixture-2\\baseline.json",
"C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\run-2\\snapshots\\baseline\\source\\project.arcadia"
],
"buildReceipt": {
"bytes": 3131,
"sha256": "fbecac3b0f7913db5e2ad19043c7df167a92287833ddf3ea4f24766e86ae523b"
},
"binary": {
"bytes": 22162432,
"sha256": "4de47a2b62192be6a1394e654f368be19e36fb966d60d6c833a5d51d18247bb1"
},
"helper": {
"bytes": 2494,
"sha256": "1dbfff41f07bd750d4e550660d91ae9790d2442fbfe685dc88b7f63a47f5acb8"
},
"source": {
"oa/activities/activity_activity_a.arcadia": {
"bytes": 474,
"sha256": "9bf7c5637d87c97213cf869118e942e8a29a67b429fa58e4de42235bba0980ee"
},
"oa/activities/activity_activity_b.arcadia": {
"bytes": 286,
"sha256": "152007669b7c570674aff99615a48a6f557be50f88bbbb3a5edc20b423c79a1f"
},
"oa/activities/activity_activity_c.arcadia": {
"bytes": 153,
"sha256": "d726b6b4e1200edd9ef752bb767e38d3d69dcac8eb6135d5f83c93832ff849b1"
},
"project.arcadia": {
"bytes": 597,
"sha256": "e7bd67c5785a78766298255ed3d53ff6d65dcd24bde1570ac8a0ff45cc9dc385"
},
"sa/functions/function_sa_function.arcadia": {
"bytes": 162,
"sha256": "1c724a9204784435e729badd4ad164b1a6b891840bb1ddc354ac1e175e3d712c"
},
"traceability.arcadia": {
"bytes": 522,
"sha256": "26b0b10715ced7aefcde941e6d1c1a6973f174997eae989e32a25c695dfb7cd1"
},
"views/diagram_oa_other.arcadia": {
"bytes": 315,
"sha256": "06ceef9cfdbb3ef229a22db6c48d8bb808388e027c37294648555ecbfb6bfab9"
},
"views/diagram_oa_view.arcadia": {
"bytes": 1896,
"sha256": "4e7d47d6a03153070687136c89faf01fc6df45ae89e2695beeab2fe4872dbc88"
},
"views/diagram_sa_view.arcadia": {
"bytes": 331,
"sha256": "c75b0fe14496631c9b017a32e277d1e5ad5b25e00e06b804fc54d950d7fb57f6"
}
},
"baseline": {
"bytes": 8944,
"sha256": "d1278e58cd31e1d61093292eddc1d7b2cc9c8cdc7fe5dd3801de8411af8db89d"
}
}
@@ -0,0 +1,9 @@
{
"baseline": "C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\fixture-2\\baseline.json",
"comparison": "complete Project equality",
"inferred_common_delta": null,
"limits": "Invariant evaluator only; no pointer/action/focus/Undo/source-byte acceptance claim",
"mode": "unchanged",
"result": "PASS",
"saved": "C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\run-2\\snapshots\\baseline\\source\\project.arcadia"
}
@@ -0,0 +1,77 @@
{
"start": "2026-09-23T09:07:10.546708+00:00",
"command": [
"C:\\Users\\User\\Documents\\Git\\ARCADIA-Studio\\.local\\target-gnullvm\\debug\\examples\\multiselect_native.exe",
"check",
"unchanged",
"C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\fixture-2\\baseline.json",
"C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\run-2\\snapshots\\baseline\\source\\project.arcadia"
],
"buildReceipt": {
"bytes": 3131,
"sha256": "fbecac3b0f7913db5e2ad19043c7df167a92287833ddf3ea4f24766e86ae523b"
},
"binary": {
"bytes": 22162432,
"sha256": "4de47a2b62192be6a1394e654f368be19e36fb966d60d6c833a5d51d18247bb1"
},
"helper": {
"bytes": 2494,
"sha256": "1dbfff41f07bd750d4e550660d91ae9790d2442fbfe685dc88b7f63a47f5acb8"
},
"source": {
"oa/activities/activity_activity_a.arcadia": {
"bytes": 474,
"sha256": "9bf7c5637d87c97213cf869118e942e8a29a67b429fa58e4de42235bba0980ee"
},
"oa/activities/activity_activity_b.arcadia": {
"bytes": 286,
"sha256": "152007669b7c570674aff99615a48a6f557be50f88bbbb3a5edc20b423c79a1f"
},
"oa/activities/activity_activity_c.arcadia": {
"bytes": 153,
"sha256": "d726b6b4e1200edd9ef752bb767e38d3d69dcac8eb6135d5f83c93832ff849b1"
},
"project.arcadia": {
"bytes": 597,
"sha256": "e7bd67c5785a78766298255ed3d53ff6d65dcd24bde1570ac8a0ff45cc9dc385"
},
"sa/functions/function_sa_function.arcadia": {
"bytes": 162,
"sha256": "1c724a9204784435e729badd4ad164b1a6b891840bb1ddc354ac1e175e3d712c"
},
"traceability.arcadia": {
"bytes": 522,
"sha256": "26b0b10715ced7aefcde941e6d1c1a6973f174997eae989e32a25c695dfb7cd1"
},
"views/diagram_oa_other.arcadia": {
"bytes": 315,
"sha256": "06ceef9cfdbb3ef229a22db6c48d8bb808388e027c37294648555ecbfb6bfab9"
},
"views/diagram_oa_view.arcadia": {
"bytes": 1896,
"sha256": "4e7d47d6a03153070687136c89faf01fc6df45ae89e2695beeab2fe4872dbc88"
},
"views/diagram_sa_view.arcadia": {
"bytes": 331,
"sha256": "c75b0fe14496631c9b017a32e277d1e5ad5b25e00e06b804fc54d950d7fb57f6"
}
},
"baseline": {
"bytes": 8944,
"sha256": "d1278e58cd31e1d61093292eddc1d7b2cc9c8cdc7fe5dd3801de8411af8db89d"
},
"finish": "2026-09-23T09:07:10.828848+00:00",
"exitCode": 3221225781,
"binaryUnchanged": true,
"workingSourceUnchanged": true,
"baselineUnchanged": true,
"stdout": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stderr": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
}
@@ -0,0 +1,14 @@
oa_activity activity_a "A - receive request" id "f0149281-4798-58d3-acff-131eed250959" {
description "Preserve engineering record activity_a.";
}
oa_activity activity_child "A.1 - classify request" id "5a80d3af-c7ee-59eb-9680-eb80d60cb94f" {
description "Preserve engineering record activity_child.";
parent @activity_a;
}
interaction internal "Request assessment" id "be7a39d9-3463-534e-b37b-76a74077d434" {
source @activity_a;
target @activity_b;
}
@@ -0,0 +1,9 @@
oa_activity activity_b "B - assess request" id "ecf076b7-e8be-5f64-8808-6a2edae5b9e2" {
description "Preserve engineering record activity_b.";
}
interaction external "Response decision" id "927dfa82-40d2-5c5f-a525-6a884725ea1d" {
source @activity_b;
target @activity_c;
}
@@ -0,0 +1,4 @@
oa_activity activity_c "C - dispatch response" id "3b258d00-854d-5ddd-a057-16eedbe31714" {
description "Preserve engineering record activity_c.";
}
@@ -0,0 +1,12 @@
arcadia 7;
project multiselect_native "Multiselect native" id "c1deb118-0fb0-5692-8b80-d24339e5b6c3" {
description "Shift-select A and B; move together, retain C and engineering semantics.";
include "oa/activities/activity_activity_a.arcadia";
include "oa/activities/activity_activity_b.arcadia";
include "oa/activities/activity_activity_c.arcadia";
include "sa/functions/function_sa_function.arcadia";
include "traceability.arcadia";
include "views/diagram_oa_other.arcadia";
include "views/diagram_oa_view.arcadia";
include "views/diagram_sa_view.arcadia";
}
@@ -0,0 +1,4 @@
sa_function sa_function "Technical request processing" id "878a1b33-a7c2-5a68-a8b6-d8273c6354e0" {
description "Preserve engineering record sa_function.";
}
@@ -0,0 +1,16 @@
trace preserved_refinement "Reviewed request refinement" id "b42fb6e3-db90-5349-b957-faeba373ba91" {
baseline {
oa {
description "Preserve engineering record activity_a.";
name "A - receive request";
};
sa {
description "Preserve engineering record sa_function.";
name "Technical request processing";
};
};
description "Group geometry and Hide preserve this trace and both endpoints.";
oa @activity_a;
sa @sa_function;
}
@@ -0,0 +1,13 @@
diagram oa_other "Other OA view - preserve" id "c4a58011-d2d7-59b1-ad58-feacef0e2d78" {
description "Selection changes placement geometry only.";
}
node other_a id "9aa9a68b-4c26-5d21-bc35-63d3f0f311d6" {
diagram @oa_other;
element @activity_a;
position {
x 40.0;
y 60.0;
};
}
@@ -0,0 +1,93 @@
diagram oa_view "Multiselect native - OA overview" id "00000000-0000-0000-0000-000000290001" {
description "Selection changes placement geometry only.";
routes [{
edge @internal;
label {
fraction 0.44999998807907104;
offset {
x 7.0;
y -19.0;
};
};
source_attachment {
offset 0.25;
side Right;
};
target_attachment {
offset 0.699999988079071;
side Left;
};
waypoints [{
x 420.0;
y 145.0;
}, {
x 420.0;
y 186.0;
}];
}, {
edge @external;
label {
fraction 0.44999998807907104;
offset {
x 7.0;
y -19.0;
};
};
source_attachment {
offset 0.25;
side Right;
};
target_attachment {
offset 0.699999988079071;
side Left;
};
waypoints [{
x 725.0;
y 150.0;
}, {
x 725.0;
y 336.0;
}];
}];
}
node node_a id "2670dd46-9fe7-5047-b13d-59817cff96dd" {
diagram @oa_view;
element @activity_a;
position {
x 80.0;
y 80.0;
};
size {
height 260.0;
width 310.0;
};
}
node node_b id "70e322db-f401-58c8-a50e-2f71c61ad721" {
diagram @oa_view;
element @activity_b;
position {
x 470.0;
y 120.0;
};
}
node node_c id "d6b89a5a-6e2f-50f9-9d1e-993304a54583" {
diagram @oa_view;
element @activity_c;
position {
x 780.0;
y 270.0;
};
}
node node_child id "87f4652b-15ef-55ed-ad7e-cc5d22b7facb" {
diagram @oa_view;
element @activity_child;
position {
x 120.0;
y 210.0;
};
}
@@ -0,0 +1,14 @@
diagram sa_view "SA engineering - preserve" id "637b9a3e-bd74-534c-9be5-4470a408729f" {
description "Selection changes placement geometry only.";
layer Sa;
}
node sa_node id "5f1b1c24-0583-5923-a69c-d0ea99ccb18c" {
diagram @sa_view;
element @sa_function;
position {
x 100.0;
y 110.0;
};
}
@@ -0,0 +1,64 @@
{
"start": "2026-09-23T09:07:10.546708+00:00",
"command": [
"C:\\Users\\User\\Documents\\Git\\ARCADIA-Studio\\.local\\target-gnullvm\\debug\\examples\\multiselect_native.exe",
"check",
"unchanged",
"C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\fixture-2\\baseline.json",
"C:\\ar-multiselect-9e8r6t\\.local\\multiselect-native\\run-2\\snapshots\\baseline\\source\\project.arcadia"
],
"buildReceipt": {
"bytes": 3131,
"sha256": "fbecac3b0f7913db5e2ad19043c7df167a92287833ddf3ea4f24766e86ae523b"
},
"binary": {
"bytes": 22162432,
"sha256": "4de47a2b62192be6a1394e654f368be19e36fb966d60d6c833a5d51d18247bb1"
},
"helper": {
"bytes": 2494,
"sha256": "1dbfff41f07bd750d4e550660d91ae9790d2442fbfe685dc88b7f63a47f5acb8"
},
"source": {
"oa/activities/activity_activity_a.arcadia": {
"bytes": 474,
"sha256": "9bf7c5637d87c97213cf869118e942e8a29a67b429fa58e4de42235bba0980ee"
},
"oa/activities/activity_activity_b.arcadia": {
"bytes": 286,
"sha256": "152007669b7c570674aff99615a48a6f557be50f88bbbb3a5edc20b423c79a1f"
},
"oa/activities/activity_activity_c.arcadia": {
"bytes": 153,
"sha256": "d726b6b4e1200edd9ef752bb767e38d3d69dcac8eb6135d5f83c93832ff849b1"
},
"project.arcadia": {
"bytes": 597,
"sha256": "e7bd67c5785a78766298255ed3d53ff6d65dcd24bde1570ac8a0ff45cc9dc385"
},
"sa/functions/function_sa_function.arcadia": {
"bytes": 162,
"sha256": "1c724a9204784435e729badd4ad164b1a6b891840bb1ddc354ac1e175e3d712c"
},
"traceability.arcadia": {
"bytes": 522,
"sha256": "26b0b10715ced7aefcde941e6d1c1a6973f174997eae989e32a25c695dfb7cd1"
},
"views/diagram_oa_other.arcadia": {
"bytes": 315,
"sha256": "06ceef9cfdbb3ef229a22db6c48d8bb808388e027c37294648555ecbfb6bfab9"
},
"views/diagram_oa_view.arcadia": {
"bytes": 1896,
"sha256": "4e7d47d6a03153070687136c89faf01fc6df45ae89e2695beeab2fe4872dbc88"
},
"views/diagram_sa_view.arcadia": {
"bytes": 331,
"sha256": "c75b0fe14496631c9b017a32e277d1e5ad5b25e00e06b804fc54d950d7fb57f6"
}
},
"baseline": {
"bytes": 8944,
"sha256": "d1278e58cd31e1d61093292eddc1d7b2cc9c8cdc7fe5dd3801de8411af8db89d"
}
}
@@ -0,0 +1,91 @@
# Native multiselect evidence package
This package preserves native run-1 and run-2, both closed with exit 0, empty app
stdout/stderr and all three GUI/checker/fixture unchanged flags true. Each run
contains nine positive complete-Project checker snapshots, nine source files per
snapshot and three exact source-history equality groups. Only
`views/diagram_oa_view.arcadia` differs from baseline in its move and hidden
states. These artifacts do not establish native acceptance on their own; consult
the separate [saved-view report](../../../multiselect-saved-view-20260923.md) for
action observations, usability findings and the implemented subset of issue 29.
| Run | Source commit | Captures | Layout scope |
| --- | --- | ---: | --- |
| run-1 | `12a7352ddef5f69a144ead8219a50916233d63a9` | 27 | Before selection/status toolbar correction |
| run-2 | `f6a6010baed9e6164a1fcc7ecd58256a562827d7` | 24 | Corrected toolbar layout build |
Run-1 GUI/checker build receipts refer to the 729-file input map
`55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb`;
run-2 refers to the distinct 729-file map
`99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c`.
The [source identity evidence](../source/README.md) ties those maps to the commits
above. The GUI binary pins differ; the recorded checker binary pins match.
Run-1 is retained as evidence of the earlier layout, not as verification of the
corrected build.
The first run-2 baseline checker attempt failed before the successful retry after
the toolchain environment was initialized. Its unchanged raw snapshot and retry
comparison are preserved separately in the [environment incident](../incidents/README.md).
The successful retry is the baseline snapshot included in this native package;
the failed invocation is not silently reclassified or presented as a GUI failure.
These Python 3.10+ standard-library tools never operate the GUI or rerun the model
checker. From the checkout root, validate both raw runs without writing a package:
```text
python -B harness/experiments/multiselect-20260923/native/prepare.py --root . --runs run-1 run-2 --check-only
```
Omit `--check-only` to package; optionally choose `--output DIRECTORY`. The default
is this native directory. Existing package outputs are not overwritten. A missing
or unfinished run, changed recorded inputs, missing/extra fixture or snapshot
files, unmatched helper bytes, or inconsistent receipts fails preparation.
Verify a completed package independently of the original machine:
```text
python -B PATH_TO_PACKAGE/verify.py
```
Each run includes all original capture JSON/images, process/start/finish records,
generation and app streams, all nine source snapshots and checker streams/receipts,
and the history-bytes record. Its fixture includes baseline JSON, the manifest,
and canonical source files. Exact helpers are found by their recorded hashes among
the native directory's `.py`/`.js` files, so original and suffixed run-2 helpers can
coexist. Helpers are archived as data and never executed by these tools.
Referenced GUI/checker build results, exact gate helpers and input maps are
included. The checker example is read from its pinned historical input ZIP, not
from current source.
Full build logs and large source ZIPs belong in the sibling `checks` package;
verify that package separately. This package validates build receipt, input map,
example-source and executable-pin relationships without duplicating those ZIPs.
It does not contain or execute the GUI/checker binaries.
The verifier checks every archived byte pin and exact safe membership, clean
recorded exit and unchanged flags, process and capture lifetimes, each capture's
normalized executable path against the launched GUI, one consistent positive
window ID per run, fixture/source inventories, nine positive complete-Project
checker reports, baseline/binary/helper
relationships, and the actual archived bytes in three history equality groups.
It verifies that only `views/diagram_oa_view.arcadia` differs from baseline in the
move and hidden source states, and that baseline source bytes match the fixture.
Window identity checks join recorded metadata; the receipts do not independently
map that window handle to the recorded PID. Source models are not recompiled by
this offline Python verifier. Screenshot dimensions are recorded metadata, not a
minimum-window usability evaluation.
`manifest.json` maps each run's original historical paths to archived run,
fixture, helper, build and checker-source members and pins their bytes.
`files.json` pins the packager, verifier, README, manifest and archive. Raw bytes
are preserved; ZIP ordering and timestamps are fixed. Historic absolute paths are
labels and are not accessed by offline verification.
GUI actions remain separately documented parent observations. Screenshots do
not prove which inputs occurred, and the checker infers a bounded common delta
from saved geometry; it cannot validate the exact pointer destination. Source
history byte equality supports the stated saved-state relationships but does not
independently authenticate button presses, focus behavior or Undo stack structure.
Run-1 evidence does not establish the corrected toolbar's usability or any later
binary's behavior. Consult the parent report for the evaluated version, observed
limitations, run differences and the remaining full-issue acceptance work.
@@ -0,0 +1,22 @@
{
"prepare.py": {
"bytes": 7237,
"sha256": "d9d49d3082e485e670b43010822ebd3ab7a79762b36a247dcd3bdfc6b5d7f41d"
},
"verify.py": {
"bytes": 14703,
"sha256": "7ef5f28b6c9a43bf0361eec2d8be33a1e9f284d0ffc21b50fd09a2d082642ce3"
},
"README.md": {
"bytes": 5418,
"sha256": "8d6fa25d8bd97c654e78b89194bd499637427ce027157d568215e13421b22c03"
},
"manifest.json": {
"bytes": 72794,
"sha256": "de7642ad43aa881f7d984629db52ea41b62d0ebacc09260edd80a5c1fee7dd7b"
},
"evidence.zip": {
"bytes": 4399281,
"sha256": "7dc3e0571179e0f67fefe3c73462308b79e4c7f7a09bbd805e0acf0e4faeb1cf"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,129 @@
"""Package explicit completed native runs; helpers are pinned data, never executed."""
from pathlib import Path
import argparse
import json
import re
import zipfile
from verify import pin, parsed, need, norm, relative, safe, verify_data, verify_package
HERE = Path(__file__).resolve().parent
def collect(root, runs):
native = root / ".local/multiselect-native"
candidates = [path for path in native.iterdir() if path.is_file() and path.suffix in (".py", ".js")]
candidates.extend(sorted((root / ".local/group-movement-gates").glob("*.py")))
helpers = [(path.suffix, path.read_bytes()) for path 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
def tree(folder, prefix):
need(folder.is_dir(), "missing directory: " + str(folder))
for path in sorted(folder.rglob("*")):
need(not path.is_symlink(), "symlink evidence input")
if path.is_file():
add(prefix + path.relative_to(folder).as_posix(), path.read_bytes())
for run in runs:
folder = native / run
start = parsed((folder / "started.json").read_bytes())
end = parsed((folder / "finished.json").read_bytes())
need(end["exitCode"] == 0 and all(end[k] is True for k in
("guiUnchanged", "checkerUnchanged", "fixtureUnchanged")), "unfinished/changed native run: " + run)
generation = parsed((folder / "generation.json").read_bytes())
history = parsed((folder / "history-bytes.json").read_bytes())
tree(folder, "runs/" + run + "/raw/")
fixture_relative = relative(generation["command"][2], start["cwd"])
need(fixture_relative.startswith(".local/multiselect-native/"), "fixture outside native root")
tree(root / fixture_relative, "runs/" + run + "/fixture/")
spec = {"originalRun": norm(start["cwd"]) + "/.local/multiselect-native/" + run,
"originalFixture": norm(generation["command"][2]), "helpers": {}, "builds": {}}
for key, expected in [("helper", start["helper"]), ("capture", start["capture"]),
("snapshotHelper", start["snapshotHelper"]), ("history", history["helper"])]:
matches = [(suffix, data) for suffix, data in helpers if pin(data) == expected]
need(bool(matches), "exact historical helper unavailable: " + key)
suffix, data = matches[0]
member = "helpers/" + expected["sha256"] + suffix
add(member, data)
spec["helpers"][key] = member
for kind in ("gui", "checker"):
recorded = start[kind]
rel = relative(recorded["receipt"], start["cwd"])
need(rel.startswith(".local/group-movement-gates/") and rel.endswith("/result.json"), "unexpected build receipt location")
receipt = root / rel
data = receipt.read_bytes()
need(pin(data) == recorded["receiptPin"], "historical build receipt changed")
prefix = "builds/" + pin(data)["sha256"] + "/"
add(prefix + "result.json", data)
inputs_data = (receipt.parent / "inputs.json").read_bytes()
need(pin(inputs_data) == recorded["inputs"], "historical build input map changed")
add(prefix + "inputs.json", inputs_data)
spec["builds"][kind] = {"receipt": prefix + "result.json", "inputs": prefix + "inputs.json", "originalRelative": rel}
build_helper = parsed(data)["helper"]
matching_helpers = [(suffix, value) for suffix, value in helpers if pin(value) == build_helper]
need(bool(matching_helpers), "exact historical build helper unavailable")
suffix, helper_data = matching_helpers[0]
helper_member = "helpers/" + build_helper["sha256"] + suffix
add(helper_member, helper_data)
spec["builds"][kind]["helper"] = helper_member
if kind == "checker":
# Read only the pinned historical example, not today's checkout.
archive_path = receipt.parent / "inputs.zip"
need(pin(archive_path.read_bytes()) == parsed(data)["archive"], "checker input archive pin")
source_path = "crates/oa-core/examples/multiselect_native.rs"
with zipfile.ZipFile(archive_path) as archive:
source = archive.read(source_path)
need(pin(source) == parsed(inputs_data)[source_path], "historical checker source pin")
member = "checker-source/" + pin(source)["sha256"] + ".rs"
add(member, source)
spec["checkerSource"] = {"inputPath": source_path, "member": member}
specs[run] = spec
manifest = {"schema": 1, "kind": "multiselect-native", "runs": specs,
"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 stream:
stream.write((json.dumps(value, indent=2) + "\n").encode())
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=HERE.parents[3])
parser.add_argument("--runs", nargs="+", required=True)
parser.add_argument("--output", type=Path, default=HERE)
parser.add_argument("--check-only", action="store_true")
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")
payload, manifest, summary = collect(args.root.resolve(), args.runs)
if args.check_only:
print("PASS raw consistency; no archive written:", summary)
return
out = args.output.resolve()
out.mkdir(parents=True, exist_ok=True)
for name in ("evidence.zip", "manifest.json", "files.json"):
need(not (out / name).exists(), "existing output refused: " + name)
for name in ("prepare.py", "verify.py", "README.md"):
data = (HERE / name).read_bytes()
if (out / name).exists():
need((out / name).read_bytes() == data, "different existing package tool")
else:
with (out / name).open("xb") as stream:
stream.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 evidence")
print("PASS package readback:", out, summary)
if __name__ == "__main__":
main()
@@ -0,0 +1,235 @@
"""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 math
import stat
import zipfile
BASE = {"started.json", "finished.json", "generation.json", "generation.stdout.log",
"generation.stderr.log", "app.stdout.log", "app.stderr.log", "processes.json", "history-bytes.json"}
GROUPS = [["baseline", "move-undo", "before-hide", "hide-undo"], ["move", "move-redo"],
["hidden", "hide-redo", "reopened-hidden"]]
MODES = {name: mode for group, mode in zip(GROUPS, ["unchanged", "moved", "hide"]) for name in group}
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"] == "multiselect-native", "manifest kind")
members, runs = manifest["members"], manifest["runs"]
need(bool(runs) and all(safe(run) and "/" not in 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 = 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, "exact pinned tree: " + prefix)
return actual
for run, spec in runs.items():
prefix = "runs/" + run + "/raw/"
start, end = obj(prefix + "started.json"), obj(prefix + "finished.json")
generation, process = obj(prefix + "generation.json"), obj(prefix + "processes.json")
history = obj(prefix + "history-bytes.json")
need(end["exitCode"] == 0 and all(end[key] is True for key in
("guiUnchanged", "checkerUnchanged", "fixtureUnchanged")), run + ": clean unchanged closure")
need(ordered(generation["start"], generation["finish"], process["CreationDate"], start["start"], end["finish"], history["verified"]), run + ": process/generation times")
need(process["ProcessId"] == start["pid"] and type(start["pid"]) is int and start["pid"] > 0, run + ": process identity")
need(norm(process["ExecutablePath"]) == norm(start["gui"]["binary"])
and start["command"] == [start["gui"]["binary"]], run + ": GUI command")
need(spec["originalRun"] == norm(start["cwd"]) + "/.local/multiselect-native/" + run, run + ": original run mapping")
need(generation["exitCode"] == 0 and generation["checker"] == start["checker"], run + ": generation checker")
need(generation["command"][:2] == [start["checker"]["binary"], "generate"]
and len(generation["command"]) == 3 and norm(generation["command"][2]) == spec["originalFixture"], run + ": generation command")
for stream in ("stdout", "stderr"):
need(end[stream] == pin(raw(prefix + "app." + stream + ".log")), run + ": app stream")
need(generation[stream] == pin(raw(prefix + "generation." + stream + ".log")), run + ": generation stream")
fixture = pinned_tree("runs/" + run + "/fixture/", start["fixture"])
need(set(fixture) == {"baseline.json", "manifest.json"} | {"source/" + name for name in
obj(prefix + "snapshots/baseline/result.json")["source"]}, run + ": fixture membership")
fixture_manifest = parsed(fixture["manifest.json"])
need(fixture_manifest["fixture"] == "multiselect-native-20260923"
and fixture_manifest["source_entry"] == "project.arcadia", run + ": fixture identity")
need(parsed(fixture["baseline.json"])["id"] == fixture_manifest["ids"]["project"], run + ": baseline identity")
for key, expected in [("helper", start["helper"]), ("capture", start["capture"]),
("snapshotHelper", start["snapshotHelper"]), ("history", history["helper"])]:
need(pin(raw(spec["helpers"][key])) == expected, run + ": helper " + key)
builds = {}
for kind, target in [("gui", "arcadia-studio"), ("checker", "multiselect_native")]:
recorded = start[kind]
build = obj(spec["builds"][kind]["receipt"])
need(pin(raw(spec["builds"][kind]["receipt"])) == recorded["receiptPin"], run + ": build receipt pin")
need(relative(recorded["receipt"], start["cwd"]) == spec["builds"][kind]["originalRelative"], run + ": build path mapping")
need(build["exitCode"] == 0 and build["inputsUnchanged"] is True
and ordered(build["start"], build["finish"], generation["start"]), run + ": accepted preceding build")
need(build["inputs"] == recorded["inputs"] == pin(raw(spec["builds"][kind]["inputs"])), run + ": build input map")
need(pin(raw(spec["builds"][kind]["helper"])) == build["helper"], run + ": build helper pin")
inputs = obj(spec["builds"][kind]["inputs"])
need(len(inputs) == build["inputCount"] and sum(name.startswith("crates/vendor/iced_widget/") for name in inputs) == 71, run + ": build input count")
artifacts = [item for item in build["artifacts"] if item["cargo"]["target"]["name"] == target]
need(len(artifacts) == 1 and artifacts[0]["readback"] == recorded["pin"]
and artifacts[0]["cargo"]["executable"] == recorded["binary"], run + ": executable relationship")
builds[kind] = inputs
need(start["gui"]["inputs"] == start["checker"]["inputs"], run + ": matching GUI/checker inputs")
source = spec["checkerSource"]
need(source["inputPath"] == "crates/oa-core/examples/multiselect_native.rs"
and pin(raw(source["member"])) == builds["checker"][source["inputPath"]], run + ": archived exact checker source")
top = {name[len(prefix):] for name in members if name.startswith(prefix) and "/" not in name[len(prefix):]}
captures = sorted(name for name in top - BASE if name.endswith(".json"))
need(bool(captures), run + ": missing captures")
expected_top = set(BASE) | set(captures)
captured_window = None
for name in captures:
capture = obj(prefix + name)
need(ordered(start["start"], capture["time"], end["finish"]), run + ": capture lifetime")
window = capture["window"]
app = window["app"]
need(isinstance(app, str) and app.startswith("process:")
and norm(app[len("process:"):]) == norm(start["gui"]["binary"]), run + ": captured executable relationship")
need(type(window["id"]) is int and window["id"] > 0, run + ": captured window identity")
if captured_window is None:
captured_window = window["id"]
need(window["id"] == captured_window, run + ": inconsistent captured window identity")
need(isinstance(capture["images"], list), run + ": capture images")
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")), run + ": capture image mapping")
need(type(image["width"]) is int and image["width"] > 0
and type(image["height"]) is int and image["height"] > 0, run + ": image dimensions")
need(filename not in expected_top, run + ": duplicate image reference")
expected_top.add(filename)
raw(prefix + filename)
need(top == expected_top, run + ": extra/missing top-level run files")
snapshots = {name[len(prefix + "snapshots/"):].split("/")[0] for name in members if name.startswith(prefix + "snapshots/")}
need(snapshots == set(MODES), run + ": exact nine snapshot labels")
states = {}
for label, mode in MODES.items():
folder = prefix + "snapshots/" + label + "/"
began, result = obj(folder + "started.json"), obj(folder + "result.json")
need(all(result.get(key) == value for key, value in began.items()), label + ": start/result")
need(result["exitCode"] == 0 and all(result[key] is True for key in
("binaryUnchanged", "workingSourceUnchanged", "baselineUnchanged")), label + ": unchanged successful checker")
need(ordered(start["start"], result["start"], result["finish"], end["finish"]), label + ": checker lifetime")
need(result["buildReceipt"] == start["checker"]["receiptPin"] and result["binary"] == start["checker"]["pin"]
and result["helper"] == start["snapshotHelper"], label + ": checker provenance")
need(result["baseline"] == pin(fixture["baseline.json"]), label + ": baseline pin")
command = result["command"]
need(len(command) == 5 and command[:3] == [start["checker"]["binary"], "check", mode]
and norm(command[3]) == spec["originalFixture"] + "/baseline.json"
and norm(command[4]) == spec["originalRun"] + "/snapshots/" + label + "/source/project.arcadia", label + ": exact checker command")
for stream in ("stdout", "stderr"):
need(result[stream] == pin(raw(folder + stream + ".log")), label + ": stream pin")
need(not raw(folder + "stderr.log"), label + ": checker stderr")
report = obj(folder + "stdout.log")
need(report["result"] == "PASS" and report["comparison"] == "complete Project equality"
and report["mode"] == mode and report["baseline"] == command[3] and report["saved"] == command[4], label + ": positive checker report")
delta = report["inferred_common_delta"]
if mode == "moved":
need(isinstance(delta, dict) and set(delta) == {"x", "y"}
and all(type(v) in (int, float) and math.isfinite(v) and abs(v) <= 500 for v in delta.values())
and math.hypot(delta["x"], delta["y"]) >= 10, label + ": inferred movement bounds")
else:
need(delta is None, label + ": unexpected inferred delta")
states[label] = pinned_tree(folder + "source/", result["source"])
need(len(states[label]) == history["sourceFilesPerSnapshot"] == 9, label + ": source count")
expected = {folder + name for name in ("started.json", "result.json", "stdout.log", "stderr.log")}
expected.update(folder + "source/" + name for name in states[label])
need({name for name in members if name.startswith(folder)} == expected, label + ": extra snapshot files")
need(history["status"] == "PASS" and history["equalByteGroups"] == GROUPS, run + ": history groups")
for group in GROUPS:
need(all(states[label] == states[group[0]] for label in group), run + ": actual history bytes " + str(group))
need(all(states[a[0]] != states[b[0]] for i, a in enumerate(GROUPS) for b in GROUPS[i + 1:]), run + ": distinct history states")
need(states["baseline"] == {name[7:]: data for name, data in fixture.items() if name.startswith("source/")}, run + ": baseline source exact")
changed = {label: sorted(name for name in set(states["baseline"]) | set(states[label])
if states["baseline"].get(name) != states[label].get(name)) for label in ("move", "hidden")}
need(changed == history["changedFilesFromBaseline"]
== {label: ["views/diagram_oa_view.arcadia"] for label in ("move", "hidden")}, run + ": changed source files")
print(run, "closed exit 0;", len(captures), "captures; nine positive snapshots; exact three-group source history")
need(used == set(members), "unreferenced/extra package members")
return {"runs": len(runs), "members": len(members)}
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)
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 native evidence byte/receipt consistency:", verify_package(args.package))
print("No GUI/checker execution; actions and native acceptance require the separate parent review.")
if __name__ == "__main__":
main()
@@ -0,0 +1,2 @@
# Preserve pinned historical receipts and helper bytes through Git round trips.
* -text whitespace=cr-at-eol
@@ -0,0 +1,52 @@
# Captured inputs and committed source identity
This directory preserves exact historical `committed-desktop-4.json` and
`committed-desktop-5.json` receipts plus `verify-committed-inputs.py` as data.
The original helper contains its historical absolute checkout path; do not run
it for portable verification. The receipts do not themselves pin that helper;
`files.json` pins the copies distributed here and the new verifier/README.
The local `.gitattributes` preserves those pinned bytes through Git round trips;
retain it with this directory rather than normalizing the historical text.
With Python 3.10+, Git, a repository containing both commits, and the completed
sibling checks package, run:
```text
python -B SOURCE_DIRECTORY/verify.py --repo REPOSITORY --checks CHECKS_PACKAGE_DIRECTORY
```
Before that package exists, an explicitly optional raw-input mode is available:
```text
python -B harness/experiments/multiselect-20260923/source/verify.py --repo . --raw-gates .local/group-movement-gates
```
The verifier checks source-evidence pins, captured map byte hashes, recorded gate
success/unchanged flags, counts and 71 vendored iced_widget inputs. It compares the
complete relevant Git tree inventory and every blob's size/SHA-256 at these
commits with their corresponding captured input maps:
- `desktop-4`: `12a7352ddef5f69a144ead8219a50916233d63a9`
- `desktop-5`: `f6a6010baed9e6164a1fcc7ecd58256a562827d7`
The scope matches the historical helper: Cargo manifests/lock/toolchain file,
`crates/`, `build/`, `.cargo/`, `scripts/`, `docs/`, `examples/`,
`harness/fixtures/`, and `harness/prototypes/`. This is the complete inventory
within that scope, not a whole-repository identity claim. Worktree contents,
current HEAD, line-ending checkout conversion and original machine paths do not
participate. Git objects are read by object ID; no checkout, build or archived
helper runs. Both commits must already be available; lazy object fetching is
disabled for these reads.
In package mode, outer checks-package pins and selected member/run relationships
are also checked. Run the checks package's own verifier for its full source ZIP,
logs, helpers and all other gate relationships. Raw mode reads the named local
maps/receipts directly and is not a substitute for packaged-evidence verification.
No source maps or ZIPs are duplicated in this directory.
Historical receipts report an earlier comparison. A successful run of this new
verifier performs a fresh Git-object comparison against the pinned maps. A gate's
recorded HEAD can predate its later source-identical commit; that difference is
why blob comparison is necessary. This evidence identifies tested source bytes;
it does not rerun tests or establish native usability, release integration or
full #29 acceptance.
@@ -0,0 +1,11 @@
{
"checked": "2026-09-23T08:11:54.115058+00:00",
"commit": "12a7352ddef5f69a144ead8219a50916233d63a9",
"gate": "desktop-4",
"inputCount": 729,
"inputMap": {
"bytes": 121985,
"sha256": "55a5f354bb5049a8c77ba9bafa833438ebf754649b0cf5d175d0c8dcfcedd7bb"
},
"comparison": "Exact committed Git blobs equal every captured input; same complete filtered inventory"
}
@@ -0,0 +1,11 @@
{
"checked": "2026-09-23T08:53:15.452246+00:00",
"commit": "f6a6010baed9e6164a1fcc7ecd58256a562827d7",
"gate": "desktop-5",
"inputCount": 729,
"inputMap": {
"bytes": 121985,
"sha256": "99dc46645236e674244e7c4867595a6000d3d85b54bcc9ab2b0c601923ecf66c"
},
"comparison": "Exact committed Git blobs equal every captured input; same complete filtered inventory"
}
@@ -0,0 +1,26 @@
{
".gitattributes": {
"bytes": 109,
"sha256": "aca8eef17dbab8cfedcbe18e1175cfee115802376fac4ec69e8c3320a6399d6c"
},
"README.md": {
"bytes": 2792,
"sha256": "b8db0c2c71e491b6179b3e57d27e5dfb23c9283894219feea328bc632603f2aa"
},
"verify.py": {
"bytes": 7255,
"sha256": "2ed667c127470efb669fb43d5dcdb288f891e42e10e67ef98ca4cd1125df09d1"
},
"verify-committed-inputs.py": {
"bytes": 2138,
"sha256": "ac2b50a73f678456b9628684347484c013f5f9c78f054de72b74f56a34c990d5"
},
"committed-desktop-4.json": {
"bytes": 390,
"sha256": "47c6774bcb7d0c37c50e0ed50f8fb58ee9b55c6fcee30af488481c314a4e66e8"
},
"committed-desktop-5.json": {
"bytes": 390,
"sha256": "da1f08e06bd0af6512da4196618b71d0c4ecc090012f061bb82b6a36f5b7686c"
}
}
@@ -0,0 +1,36 @@
"""Check the tested source inventory against exact Git blobs, not HEAD alone."""
from pathlib import Path
import datetime, hashlib, json, subprocess, sys
root=Path('C:/ar-multiselect-9e8r6t')
run,=sys.argv[1:]
gate=root/'.local/group-movement-gates'/run
inputs=json.loads((gate/'inputs.json').read_bytes())
result=json.loads((gate/'result.json').read_bytes())
assert result['exitCode']==0 and result['inputsUnchanged']
head=subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip()
def relevant(p):
return p in ('Cargo.toml','Cargo.lock','rust-toolchain.toml') or p.startswith(('crates/','build/','.cargo/','scripts/','docs/','examples/','harness/fixtures/','harness/prototypes/'))
paths=subprocess.check_output(['git','ls-tree','-r','--name-only','-z',head],cwd=root).decode().split('\0')
assert set(inputs)=={p for p in paths if p and relevant(p)}, 'Committed input inventory differs'
assert all('\n' not in p for p in inputs)
request=''.join(head+':'+p+'\n' for p in inputs).encode()
raw=subprocess.run(['git','cat-file','--batch'],cwd=root,input=request,capture_output=True,check=True).stdout
offset=0
actual={}
for path in inputs:
end=raw.index(b'\n',offset)
oid,kind,size=raw[offset:end].split()
assert kind==b'blob'
size=int(size)
data=raw[end+1:end+1+size]
assert len(data)==size and raw[end+1+size:end+2+size]==b'\n'
actual[path]={'bytes':size,'sha256':hashlib.sha256(data).hexdigest()}
offset=end+2+size
assert offset==len(raw)
changed=[p for p in inputs if inputs[p]!=actual[p]]
assert not changed, 'Tested bytes differ from committed blobs: '+repr(changed)
data=(gate/'inputs.json').read_bytes()
report={'checked':datetime.datetime.now(datetime.timezone.utc).isoformat(),'commit':head,'gate':run,'inputCount':len(inputs),'inputMap':{'bytes':len(data),'sha256':hashlib.sha256(data).hexdigest()},'comparison':'Exact committed Git blobs equal every captured input; same complete filtered inventory'}
out=root/'.local/group-movement-gates'/('committed-'+run+'.json')
with out.open('x',encoding='utf-8') as f: json.dump(report,f,indent=2)
print(json.dumps(report,indent=2))
@@ -0,0 +1,149 @@
"""Compare captured input maps to exact named Git trees; no builds or checkouts."""
from pathlib import Path, PurePosixPath
import argparse
import hashlib
import json
import os
import subprocess
import zipfile
HERE = Path(__file__).resolve().parent
COMMITS = {"desktop-4": "12a7352ddef5f69a144ead8219a50916233d63a9",
"desktop-5": "f6a6010baed9e6164a1fcc7ecd58256a562827d7"}
COMPARISON = "Exact committed Git blobs equal every captured input; same complete filtered inventory"
FILES = {".gitattributes", "verify.py", "README.md", "verify-committed-inputs.py",
"committed-desktop-4.json", "committed-desktop-5.json"}
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 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 packaged(checks, runs):
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 manifest kind")
captured = {}
with zipfile.ZipFile(checks / "evidence.zip") as archive:
names = archive.namelist()
need(len(names) == len(set(names)) and set(names) == set(manifest["members"])
and all(safe(name) for name in names), "checks exact safe members")
def raw(logical):
member = manifest["logicalFiles"][logical]
data = archive.read(member)
need(pin(data) == manifest["members"][member], "checks member pin: " + logical)
return data
for run in runs:
prefix = "cargo/" + run + "/"
result = parsed(raw(prefix + "result.json"))
spec = manifest["runs"][run]
need(all(result[key] == spec[key] for key in ("command", "head", "exitCode", "inputCount")), run + ": checks run relationships")
captured[run] = (raw(prefix + "inputs.json"), result)
return captured
def verify(repo, captured):
outer = parsed((HERE / "files.json").read_bytes())
need(set(outer) == FILES, "source evidence file inventory")
for name, expected in outer.items():
need(pin((HERE / name).read_bytes()) == expected, "source evidence pin: " + name)
for run, commit in COMMITS.items():
receipt = parsed((HERE / ("committed-" + run + ".json")).read_bytes())
need(receipt["gate"] == run and receipt["commit"] == commit
and receipt["comparison"] == COMPARISON, run + ": historical identity relationship")
map_bytes, result = captured[run]
inputs = parsed(map_bytes)
need(pin(map_bytes) == receipt["inputMap"] == result["inputs"], run + ": exact captured input map")
need(result["exitCode"] == 0 and result["inputsUnchanged"] is True, run + ": accepted unchanged gate")
need(len(inputs) == receipt["inputCount"] == result["inputCount"], run + ": input counts")
need(all(safe(path) and relevant(path) for path in inputs), run + ": input scope")
need(sum(path.startswith("crates/vendor/iced_widget/") for path in inputs) == 71, run + ": vendor count")
compare_commit(repo, commit, inputs)
print("PASS exact Git tree/blobs:", run, commit, len(inputs), "captured inputs")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", type=Path, required=True, help="repository with both named commits already present")
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument("--checks", type=Path, help="portable checks package directory")
source.add_argument("--raw-gates", type=Path, help="optional preparation mode: raw gate directory, not a packaged-evidence verification")
args = parser.parse_args()
if args.checks:
captured = packaged(args.checks, COMMITS)
else:
captured = {run: ((args.raw_gates / run / "inputs.json").read_bytes(),
parsed((args.raw_gates / run / "result.json").read_bytes())) for run in COMMITS}
verify(args.repo, captured)
print("Source identity only; no build, checkout, helper execution or native acceptance claim.")
if __name__ == "__main__":
main()
@@ -0,0 +1,23 @@
# Process column-slot experiment — exploratory evidence
Question: does simultaneous column-slot permutation preserve presentation boundaries and stable order without hidden no-op mutations? Separately, can object-anchored Before/After retain selected-target no-op while reaching every useful destination?
Expected: preserve the entire ID set, exact other-column indices, selected source order, unselected within-column order, a contiguous moved block, equivalent normalized-gap results, click-order independence and frozen ID-to-rank map. Identical column order must return unchanged. Cross-column selections must refuse.
Run from the repository root with `node harness/experiments/process-column-slots-20260923/experiment.cjs` and `node harness/experiments/process-column-slots-20260923/anchor-policies.cjs`. Scripts overwrite only their own JSON results. Node was the existing bundled runtime. The parent inspected and reran both original scripts before copying them here. No Cargo, production edits or GUI were used by the experiment.
Results: both scripts exited 0. The first exhausted every steps permutation, set partition, nonempty selected subset and column gap through five IDs: 214,990 admitted property cases, 140,024 cross-column refusals and 127,950 unchanged cases. It separately exhausted all 4,096 directed simple graphs on four IDs and their 24 step permutations: 98,304 graph orders, 861,096 admitted plans, zero changed-rank counterexamples. Its longest-path/fallback rank model follows the documented algorithm but does not execute Rust. The no-source-change assertion uses a sentinel JSON envelope and suppresses serialization for unchanged results; it does not prove the application source writer or history implementation.
Concrete counterexample to global splicing: `[a,u,b,v,c]`, column `[a,b,c]`, selection `{b,c}`, after `a` is unchanged. Column-slot permutation preserves the exact original array; global splicing would write `[a,b,c,u,v]`. Moving that block before `a` produces `[b,u,c,v,a]`: `u` and `v` retain exact indices. Consequently, preserving all globally unselected relative order is intentionally not a requirement (`a` moves relative to `u` and `v`).
Anchor-policy follow-up: all nonempty subsets for column lengths 1..10 (2,036 cases, 18,324 unselected Before/After anchors) reached every remainder-list gap using an unselected neighbor. Raw normalization differs from selected-anchor no-op in 17,004 selected-anchor cases. Example: `[a,b,c,d]`, selection `{b,d}`, Before `d` normalizes to `[a,c,b,d]`; the object-anchor policy keeps `[a,b,c,d]`. The changed result is still reachable through After `c`. The APIs are distinct: normalization does not automatically supersede selected-target no-op. Prefer retaining the latter for object-anchored UI if that is the chosen interaction; every changed result remains reachable. When all are selected, the sole destination is inherently unchanged.
The selected-anchor no-op guard belongs before invoking a block planner: noncontiguous selected items can legitimately remain noncontiguous after that no-op. The block-contiguity postcondition applies to planned moves, not every selected-target gesture.
Legacy exchange-only ordering assigns successive ranks, and cycle-blocked fallback assigns unique ranks. Multi-member sets spanning these ranks refuse. Four-node enumeration cannot exercise a changed multiple-member group beside a cycle: two cycle nodes leave only two peers, whose entire block has nowhere to move. Independent review identified this limit; an added five-node case checks `[a,u,b,v,c]`, cycle `u→v→u`, selection `{b,c}` before `a`, exact result `[b,u,c,v,a]`, and unchanged full ranks. Production should still validate the complete recomputed rank map. The experiment freezes graph edges; it does not rederive legacy OrderedPath adjacency. Valid legacy columns contain one node, so admitted moves are no-op and multiple-member groups refuse under this candidate.
The same independent reviewer confirmed the rank model agrees with current Rust, found no planner counterexample under its assumptions, and noted that anchor reachability does not execute a selected-target guard or test actual pointer hit regions. Existing singleton reorder globally splices steps, so routing it through this planner would intentionally change invisible cross-column source ordering; the candidate must make that migration explicit.
Limitations and next Rust checks: these scripts assume valid unique step IDs, valid complete rank maps, visible local occurrence selection, and valid destination bounds. Rust must reject duplicate/missing/wrong-owner IDs, qualified/link mixtures, stale snapshots and dirty drafts before side effects. Explicitly choose raw-gap versus object-anchor input; keep before-first/after-last reachable. Verify production layout with different card heights and expansion, preview/commit plan identity, OA/SA source roundtrip, unchanged semantics outside steps, one Undo/Redo, no history for no-op, source limits/refusal, and native slot feedback. Deletion mode switching and aggregate removal were not investigated by these movement scripts.
Artifacts are exploratory evidence. They do not establish State acceptance or Process implementation acceptance.
@@ -0,0 +1,31 @@
const fs=require('fs'), assert=require('assert/strict');
let cases=0, anchors=0, divergent=0;
for(let n=1;n<=10;n++) {
const column=Array.from({length:n},(_,i)=>i);
for(let mask=1;mask<(1<<n);mask++) {
const selected=new Set(column.filter(id=>mask&(1<<id)));
const remainder=column.filter(id=>!selected.has(id));
const reached=new Set();
for(const anchor of remainder) for(const after of [false,true]) {
const rawGap=column.indexOf(anchor)+(after?1:0);
const gap=column.slice(0,rawGap).filter(id=>!selected.has(id)).length;
reached.add(gap); anchors++;
assert.equal(gap,remainder.indexOf(anchor)+(after?1:0));
}
if(remainder.length) assert.deepEqual([...reached].sort((a,b)=>a-b),Array.from({length:remainder.length+1},(_,i)=>i));
else assert.equal(selected.size,n); // Only one mathematical gap, all-selected no-op.
for(const anchor of selected) for(const after of [false,true]) {
const rawGap=column.indexOf(anchor)+(after?1:0);
const gap=column.slice(0,rawGap).filter(id=>!selected.has(id)).length;
const block=column.filter(id=>selected.has(id));
const normalized=[...remainder.slice(0,gap),...block,...remainder.slice(gap)];
if(normalized.some((id,i)=>id!==column[i]))divergent++;
// Object policy intentionally preserves original order for selected anchors.
// It need not form a contiguous block when this operation is a no-op.
}
cases++;
}
}
const result={passed:true,method:'All nonempty subsets for column lengths 1..10, all unselected and selected Before/After anchors. Order-label equivariance makes separate ID permutations redundant for this reachability property.',cases,unselectedAnchors:anchors,selectedAnchorRawNormalizationDivergences:divergent,conclusion:'Every remainder gap is reachable via an unselected Before/After anchor. Selected-anchor no-op does not remove any possible changed result. Raw-gap and object-anchor policies remain distinct APIs; neither silently supersedes the other.',counterexample:{column:['a','b','c','d'],selected:['b','d'],drop:'Before d',rawGapResult:['a','c','b','d'],objectAnchorResult:['a','b','c','d'],equivalentUnselectedDrop:'After c'}};
fs.writeFileSync(__dirname+'/anchor-results.json',JSON.stringify(result,null,2)+'\n');
console.log(JSON.stringify(result,null,2));
@@ -0,0 +1,34 @@
{
"passed": true,
"method": "All nonempty subsets for column lengths 1..10, all unselected and selected Before/After anchors. Order-label equivariance makes separate ID permutations redundant for this reachability property.",
"cases": 2036,
"unselectedAnchors": 18324,
"selectedAnchorRawNormalizationDivergences": 17004,
"conclusion": "Every remainder gap is reachable via an unselected Before/After anchor. Selected-anchor no-op does not remove any possible changed result. Raw-gap and object-anchor policies remain distinct APIs; neither silently supersedes the other.",
"counterexample": {
"column": [
"a",
"b",
"c",
"d"
],
"selected": [
"b",
"d"
],
"drop": "Before d",
"rawGapResult": [
"a",
"c",
"b",
"d"
],
"objectAnchorResult": [
"a",
"b",
"c",
"d"
],
"equivalentUnselectedDrop": "After c"
}
}
@@ -0,0 +1,119 @@
// Exploratory model, not production code or a test of the Rust implementation.
const fs = require('fs');
const assert = require('assert/strict');
let count = 0, graphCount = 0, admitted = 0, refused = 0, noops = 0;
function* permutations(a) {
if (!a.length) { yield []; return; }
for (let i=0;i<a.length;i++) for (const tail of permutations(a.filter((_,j)=>i!==j))) yield [a[i],...tail];
}
function* partitions(n, prefix=[]) {
if(prefix.length===n) { yield prefix; return; }
const max=prefix.length?Math.max(...prefix)+1:0;
for(let x=0;x<=max;x++) yield* partitions(n,[...prefix,x]);
}
function plan(steps, ranks, selected, rawGap) {
const rank=ranks[selected[0]];
if(!selected.length || selected.some(id=>ranks[id]!==rank)) return null;
const indices=steps.flatMap((id,i)=>ranks[id]===rank?[i]:[]);
const column=indices.map(i=>steps[i]), set=new Set(selected);
assert(rawGap>=0 && rawGap<=column.length);
const block=column.filter(id=>set.has(id));
const remainder=column.filter(id=>!set.has(id));
const gap=column.slice(0,rawGap).filter(id=>!set.has(id)).length;
const order=[...remainder.slice(0,gap),...block,...remainder.slice(gap)];
const result=steps.slice();
indices.forEach((index,i)=>result[index]=order[i]);
return {result, order, gap, changed:result.some((id,i)=>id!==steps[i])};
}
function verify(steps,ranks,selected,rawGap,p) {
const set=new Set(selected), rank=ranks[selected[0]];
const old=steps.filter(id=>ranks[id]===rank), got=p.result.filter(id=>ranks[id]===rank);
assert.deepEqual([...p.result].sort(),[...steps].sort());
steps.forEach((id,i)=>{if(ranks[id]!==rank) assert.equal(p.result[i],id);});
assert.deepEqual(got.filter(id=>set.has(id)),old.filter(id=>set.has(id)));
assert.deepEqual(got.filter(id=>!set.has(id)),old.filter(id=>!set.has(id)));
const first=got.findIndex(id=>set.has(id));
assert.equal(got.slice(first,first+set.size).every(id=>set.has(id)),true);
// Independent gap oracle: every original unselected item before boundary
// precedes every selected item; all remaining unselected items follow them.
old.forEach((id,i)=>{if(!set.has(id)) selected.forEach(s=>assert.equal(got.indexOf(id)<got.indexOf(s),i<rawGap));});
const stableAlready=old.every((id,i)=>id===got[i]);
assert.equal(p.changed,!stableAlready);
const source=JSON.stringify({steps,untouched:'sentinel'});
const after=p.changed?JSON.stringify({steps:p.result,untouched:'sentinel'}):source;
if(stableAlready) {assert.equal(after,source); noops++;}
count++;
}
for(let n=1;n<=5;n++) {
const ids=Array.from({length:n},(_,i)=>i);
for(const ranks of partitions(n)) for(const steps of permutations(ids)) {
for(let mask=1;mask<(1<<n);mask++) {
const selected=ids.filter(id=>mask&(1<<id));
if(selected.some(id=>ranks[id]!==ranks[selected[0]])) {
assert.equal(plan(steps,ranks,selected,0),null); refused++; continue;
}
const column=steps.filter(id=>ranks[id]===ranks[selected[0]]);
const equivalents=new Map();
for(let gap=0;gap<=column.length;gap++) {
const p=plan(steps,ranks,selected,gap);
verify(steps,ranks,selected,gap,p);
assert.deepEqual(p,plan(steps,ranks,[...selected].reverse(),gap));
if(equivalents.has(p.gap)) assert.deepEqual(p.result,equivalents.get(p.gap));
equivalents.set(p.gap,p.result);
}
}
}
}
// Semantic column model: longest-path Kahn ranks and deterministic residual
// fallback, matching the documented algorithm, independently of planner.
function ranksOf(steps,edges) {
const indegree=Object.fromEntries(steps.map(id=>[id,0]));
const ranks=Object.fromEntries(steps.map(id=>[id,0]));
edges.forEach(([,b])=>indegree[b]++);
const queue=steps.filter(id=>indegree[id]===0), done=new Set();
for(let i=0;i<queue.length;i++) {
const id=queue[i]; if(done.has(id))continue; done.add(id);
for(const [a,b] of edges) if(a===id) {
ranks[b]=Math.max(ranks[b],ranks[a]+1);
if(--indegree[b]===0)queue.push(b);
}
}
let fallback=Math.max(...Object.values(ranks))+1;
steps.forEach(id=>{if(!done.has(id))ranks[id]=fallback++;});
return ranks;
}
const ids=[0,1,2,3], possible=ids.flatMap(a=>ids.filter(b=>a!==b).map(b=>[a,b]));
for(let mask=0;mask<(1<<possible.length);mask++) {
const edges=possible.filter((_,i)=>mask&(1<<i));
for(const steps of permutations(ids)) {
const ranks=ranksOf(steps,edges); graphCount++;
for(let subset=1;subset<16;subset++) {
const selected=ids.filter(id=>subset&(1<<id));
if(selected.some(id=>ranks[id]!==ranks[selected[0]]))continue;
const column=steps.filter(id=>ranks[id]===ranks[selected[0]]);
for(let gap=0;gap<=column.length;gap++) {
const p=plan(steps,ranks,selected,gap);
assert.deepEqual(ranksOf(p.result,edges),ranks); admitted++;
}
}
}
}
const concrete=[];
function example(name,steps,ranks,selected,gap,expected) {
const p=plan(steps,ranks,selected,gap); assert.deepEqual(p?.result??null,expected);
concrete.push({name,steps,ranks,selected,rawGap:gap,result:p?.result??null,changed:p?.changed??false});
}
example('interleaved visual no-op',['a','u','b','v','c'],{a:0,b:0,c:0,u:1,v:1},['c','b'],1,['a','u','b','v','c']);
example('column slot move preserves other indices',['a','u','b','v','c'],{a:0,b:0,c:0,u:1,v:1},['c','b'],0,['b','u','c','v','a']);
example('selected-anchor normalization is not always no-op',['a','b','c','d'],{a:0,b:0,c:0,d:0},['b','d'],3,['a','c','b','d']);
example('legacy successive-rank refusal',['a','b','c'],{a:0,b:1,c:2},['a','c'],0,null);
const cyclicRanks=ranksOf([0,1,2,3],[[2,3],[3,2]]);
example('cycle fallback group refusal',[0,1,2,3],cyclicRanks,[2,3],0,null);
example('acyclic peers beside cycle',[0,1,2,3],cyclicRanks,[1],0,[1,0,2,3]);
const besideCycleSteps=['a','u','b','v','c'], besideCycleEdges=[['u','v'],['v','u']];
const besideCycleRanks=ranksOf(besideCycleSteps,besideCycleEdges);
example('changed multiple-member group beside cycle',besideCycleSteps,besideCycleRanks,['c','b'],0,['b','u','c','v','a']);
assert.deepEqual(ranksOf(['b','u','c','v','a'],besideCycleEdges),besideCycleRanks);
const result={expectation:'Column-slot permutation satisfies stable-block/gap/index invariants; recomputed ranks remain exact.',method:'All permutations and set partitions through n=5; every nonempty subset and raw column gap. Every directed simple graph on 4 IDs, all 24 step permutations, all admitted subsets/gaps. No Rust, source serializer, or GUI exercised.',passed:true,counts:{propertyCases:count,crossColumnRefusals:refused,noops,graphOrders:graphCount,rankCheckedPlans:admitted},concrete};
fs.writeFileSync(__dirname+'/results.json',JSON.stringify(result,null,2)+'\n');
console.log(JSON.stringify(result,null,2));
@@ -0,0 +1,199 @@
{
"expectation": "Column-slot permutation satisfies stable-block/gap/index invariants; recomputed ranks remain exact.",
"method": "All permutations and set partitions through n=5; every nonempty subset and raw column gap. Every directed simple graph on 4 IDs, all 24 step permutations, all admitted subsets/gaps. No Rust, source serializer, or GUI exercised.",
"passed": true,
"counts": {
"propertyCases": 214990,
"crossColumnRefusals": 140024,
"noops": 127950,
"graphOrders": 98304,
"rankCheckedPlans": 861096
},
"concrete": [
{
"name": "interleaved visual no-op",
"steps": [
"a",
"u",
"b",
"v",
"c"
],
"ranks": {
"a": 0,
"b": 0,
"c": 0,
"u": 1,
"v": 1
},
"selected": [
"c",
"b"
],
"rawGap": 1,
"result": [
"a",
"u",
"b",
"v",
"c"
],
"changed": false
},
{
"name": "column slot move preserves other indices",
"steps": [
"a",
"u",
"b",
"v",
"c"
],
"ranks": {
"a": 0,
"b": 0,
"c": 0,
"u": 1,
"v": 1
},
"selected": [
"c",
"b"
],
"rawGap": 0,
"result": [
"b",
"u",
"c",
"v",
"a"
],
"changed": true
},
{
"name": "selected-anchor normalization is not always no-op",
"steps": [
"a",
"b",
"c",
"d"
],
"ranks": {
"a": 0,
"b": 0,
"c": 0,
"d": 0
},
"selected": [
"b",
"d"
],
"rawGap": 3,
"result": [
"a",
"c",
"b",
"d"
],
"changed": true
},
{
"name": "legacy successive-rank refusal",
"steps": [
"a",
"b",
"c"
],
"ranks": {
"a": 0,
"b": 1,
"c": 2
},
"selected": [
"a",
"c"
],
"rawGap": 0,
"result": null,
"changed": false
},
{
"name": "cycle fallback group refusal",
"steps": [
0,
1,
2,
3
],
"ranks": {
"0": 0,
"1": 0,
"2": 1,
"3": 2
},
"selected": [
2,
3
],
"rawGap": 0,
"result": null,
"changed": false
},
{
"name": "acyclic peers beside cycle",
"steps": [
0,
1,
2,
3
],
"ranks": {
"0": 0,
"1": 0,
"2": 1,
"3": 2
},
"selected": [
1
],
"rawGap": 0,
"result": [
1,
0,
2,
3
],
"changed": true
},
{
"name": "changed multiple-member group beside cycle",
"steps": [
"a",
"u",
"b",
"v",
"c"
],
"ranks": {
"a": 0,
"u": 1,
"b": 0,
"v": 2,
"c": 0
},
"selected": [
"c",
"b"
],
"rawGap": 0,
"result": [
"b",
"u",
"c",
"v",
"a"
],
"changed": true
}
]
}
@@ -0,0 +1,3 @@
# Preserve exact pinned captures and verification tools through Git round trips.
* -text whitespace=cr-at-eol
incidents/core-1/core-1/*.log whitespace=-blank-at-eof,cr-at-eol
@@ -0,0 +1,35 @@
# State multiselect closed gate evidence tools
Preparation requires an explicit closed run list from `.local/state-group-gates`.
Preserve failed `desktop-1` alongside accepted unchanged runs. Exclude `core-1`
from this package: its false unchanged-input flag and one map/archive mismatch
belong in the separate pinned incident. Neither failures nor incidents are passes.
Example check-only invocation (extend with every subsequent closed run):
```
python -B prepare.py --root CHECKOUT --runs desktop-1 core-2 desktop-2 --check-only
```
Only after all selected captures close, omit `--check-only` and provide
`--output CHECKOUT/harness/experiments/state-multiselect-20260923/checks`.
Historical helper copies may be passed via repeatable `--helper PATH`.
No existing output is overwritten. Run `python -B verify.py PACKAGE` for readback.
The strict verifier is unchanged from the ordinary multiselect package: exact
seven raw files, helper bytes, safe archive inventories, all input-map/archive
bytes equal, receipt relationships and inputsUnchanged exactly true are required.
Failures retain their actual exits and streams. Source capsules preserve local
historical bytes; recorded HEAD alone does not identify those bytes.
The earlier 733-input helper omitted the core compile-time integration fixture
`harness/experiments/edge-attachments-20260922/native-fixture.arcadia` and the CLI
fixture `harness/experiments/textual-authoring-20260911/alarm-response.arcadia`.
Lint-1 failed, and its all-target capture additionally has a source-capsule
scope limitation for the core fixture. Later 735-input captures add both explicit
inputs. Desktop/core
example captures retain their actual tested scope; do not infer that one map
establishes a later map or complete all-target source identity.
Offline pin/receipt consistency is not test execution, authentication, native
acceptance, or proof of usability. Executables and toolchains are not distributed.
@@ -0,0 +1,22 @@
{
"prepare.py": {
"bytes": 4802,
"sha256": "24f59b1e61a1e9c93d4aa9a47a998cbf9c2058e966cc5a7beceba73e2138943c"
},
"verify.py": {
"bytes": 8873,
"sha256": "c03513407073bef092d57b968f982b8ffc0c58e095f834fe7464c6a0e8454a9a"
},
"README.md": {
"bytes": 1984,
"sha256": "157584ed470fb8320d5a03b79388c6e1b7818b25fee1dee913083a41ff847f60"
},
"manifest.json": {
"bytes": 17487,
"sha256": "d5d71a7352fe8ab8cd63d3ce907c875d98ab048080c28868571819e9afa61e4f"
},
"evidence.zip": {
"bytes": 8859169,
"sha256": "48a47389ffdba1180b1340c3471f3d8615790e709fe563c39941d95f3f242f77"
}
}
@@ -0,0 +1,431 @@
{
"schema": 1,
"kind": "multiselect-cargo-gates",
"runs": {
"desktop-1": {
"command": [
"cargo",
"test",
"-p",
"oa-desktop",
"--message-format=json",
"state_multiselect",
"--",
"--test-threads=1"
],
"head": "7e348d967d1787c052a145b7448636613a6a7054",
"exitCode": 101,
"inputCount": 733,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"core-2": {
"command": [
"cargo",
"test",
"-p",
"oa-core",
"--example",
"state_multiselect_native",
"--message-format=json",
"--",
"--test-threads=1"
],
"head": "7e348d967d1787c052a145b7448636613a6a7054",
"exitCode": 0,
"inputCount": 733,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"desktop-2": {
"command": [
"cargo",
"test",
"-p",
"oa-desktop",
"--message-format=json",
"--",
"--test-threads=1"
],
"head": "7e348d967d1787c052a145b7448636613a6a7054",
"exitCode": 0,
"inputCount": 733,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"lint-1": {
"command": [
"cargo",
"clippy",
"-p",
"oa-core",
"-p",
"oa-desktop",
"--all-targets",
"--message-format=json",
"--",
"-D",
"warnings"
],
"head": "7e348d967d1787c052a145b7448636613a6a7054",
"exitCode": 101,
"inputCount": 733,
"helper": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"lint-2": {
"command": [
"cargo",
"clippy",
"-p",
"oa-core",
"-p",
"oa-desktop",
"--all-targets",
"--message-format=json",
"--",
"-D",
"warnings"
],
"head": "7e348d967d1787c052a145b7448636613a6a7054",
"exitCode": 0,
"inputCount": 735,
"helper": "helpers/1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20.py"
},
"format-1": {
"command": [
"cargo",
"fmt",
"--all",
"--",
"--check"
],
"head": "7e348d967d1787c052a145b7448636613a6a7054",
"exitCode": 0,
"inputCount": 735,
"helper": "helpers/1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20.py"
},
"desktop-3": {
"command": [
"cargo",
"test",
"-p",
"oa-desktop",
"--message-format=json",
"--",
"state_",
"model_menu",
"--test-threads=1"
],
"head": "3480b54201a5f361cca0bcd0d45dd6546a7a7bc9",
"exitCode": 0,
"inputCount": 735,
"helper": "helpers/1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20.py"
},
"native-build-1": {
"command": [
"cargo",
"build",
"-p",
"oa-core",
"--example",
"state_multiselect_native",
"--message-format=json"
],
"head": "3480b54201a5f361cca0bcd0d45dd6546a7a7bc9",
"exitCode": 0,
"inputCount": 735,
"helper": "helpers/1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20.py"
},
"windows-build-1": {
"command": [
"cargo",
"build",
"-p",
"oa-desktop",
"--message-format=json"
],
"head": "3480b54201a5f361cca0bcd0d45dd6546a7a7bc9",
"exitCode": 0,
"inputCount": 735,
"helper": "helpers/1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20.py"
}
},
"logicalFiles": {
"cargo/core-2/inputs.json": "capsules/9cf85879dfb0bb5ec3b15c66b23df316e6bfe8451b6cf0c895bf7b9b5fbdde4a.json",
"cargo/core-2/inputs.zip": "capsules/3419218f9917de0ac689a32dd622ebe55487fa5a37ffaba4b8fa662bc15a5cb9.zip",
"cargo/core-2/process.json": "cargo/core-2/process.json",
"cargo/core-2/result.json": "cargo/core-2/result.json",
"cargo/core-2/started.json": "cargo/core-2/started.json",
"cargo/core-2/stderr.log": "cargo/core-2/stderr.log",
"cargo/core-2/stdout.log": "cargo/core-2/stdout.log",
"cargo/desktop-1/inputs.json": "capsules/d8a64b62b68ac1c37bc3fe9309abc4dc314e343ce546bba4b9445f68dddeda5d.json",
"cargo/desktop-1/inputs.zip": "capsules/cecd6ae0ba45add8e913d9913cd4960c01928db0a4bc795902b7954ffb6f692e.zip",
"cargo/desktop-1/process.json": "cargo/desktop-1/process.json",
"cargo/desktop-1/result.json": "cargo/desktop-1/result.json",
"cargo/desktop-1/started.json": "cargo/desktop-1/started.json",
"cargo/desktop-1/stderr.log": "cargo/desktop-1/stderr.log",
"cargo/desktop-1/stdout.log": "cargo/desktop-1/stdout.log",
"cargo/desktop-2/inputs.json": "capsules/9cf85879dfb0bb5ec3b15c66b23df316e6bfe8451b6cf0c895bf7b9b5fbdde4a.json",
"cargo/desktop-2/inputs.zip": "capsules/3419218f9917de0ac689a32dd622ebe55487fa5a37ffaba4b8fa662bc15a5cb9.zip",
"cargo/desktop-2/process.json": "cargo/desktop-2/process.json",
"cargo/desktop-2/result.json": "cargo/desktop-2/result.json",
"cargo/desktop-2/started.json": "cargo/desktop-2/started.json",
"cargo/desktop-2/stderr.log": "cargo/desktop-2/stderr.log",
"cargo/desktop-2/stdout.log": "cargo/desktop-2/stdout.log",
"cargo/desktop-3/inputs.json": "capsules/4215d0ca0319282768f1acdf05c2c094ea7432e17ed3a715df73aa05cef851bf.json",
"cargo/desktop-3/inputs.zip": "capsules/1e7f68e8d6156ec608b58ff70f7ddcaf690d38da1d5066092c218bce190d3a4c.zip",
"cargo/desktop-3/process.json": "cargo/desktop-3/process.json",
"cargo/desktop-3/result.json": "cargo/desktop-3/result.json",
"cargo/desktop-3/started.json": "cargo/desktop-3/started.json",
"cargo/desktop-3/stderr.log": "cargo/desktop-3/stderr.log",
"cargo/desktop-3/stdout.log": "cargo/desktop-3/stdout.log",
"cargo/format-1/inputs.json": "capsules/4215d0ca0319282768f1acdf05c2c094ea7432e17ed3a715df73aa05cef851bf.json",
"cargo/format-1/inputs.zip": "capsules/1e7f68e8d6156ec608b58ff70f7ddcaf690d38da1d5066092c218bce190d3a4c.zip",
"cargo/format-1/process.json": "cargo/format-1/process.json",
"cargo/format-1/result.json": "cargo/format-1/result.json",
"cargo/format-1/started.json": "cargo/format-1/started.json",
"cargo/format-1/stderr.log": "cargo/format-1/stderr.log",
"cargo/format-1/stdout.log": "cargo/format-1/stdout.log",
"cargo/lint-1/inputs.json": "capsules/9cf85879dfb0bb5ec3b15c66b23df316e6bfe8451b6cf0c895bf7b9b5fbdde4a.json",
"cargo/lint-1/inputs.zip": "capsules/3419218f9917de0ac689a32dd622ebe55487fa5a37ffaba4b8fa662bc15a5cb9.zip",
"cargo/lint-1/process.json": "cargo/lint-1/process.json",
"cargo/lint-1/result.json": "cargo/lint-1/result.json",
"cargo/lint-1/started.json": "cargo/lint-1/started.json",
"cargo/lint-1/stderr.log": "cargo/lint-1/stderr.log",
"cargo/lint-1/stdout.log": "cargo/lint-1/stdout.log",
"cargo/lint-2/inputs.json": "capsules/4215d0ca0319282768f1acdf05c2c094ea7432e17ed3a715df73aa05cef851bf.json",
"cargo/lint-2/inputs.zip": "capsules/1e7f68e8d6156ec608b58ff70f7ddcaf690d38da1d5066092c218bce190d3a4c.zip",
"cargo/lint-2/process.json": "cargo/lint-2/process.json",
"cargo/lint-2/result.json": "cargo/lint-2/result.json",
"cargo/lint-2/started.json": "cargo/lint-2/started.json",
"cargo/lint-2/stderr.log": "cargo/lint-2/stderr.log",
"cargo/lint-2/stdout.log": "cargo/lint-2/stdout.log",
"cargo/native-build-1/inputs.json": "capsules/4215d0ca0319282768f1acdf05c2c094ea7432e17ed3a715df73aa05cef851bf.json",
"cargo/native-build-1/inputs.zip": "capsules/1e7f68e8d6156ec608b58ff70f7ddcaf690d38da1d5066092c218bce190d3a4c.zip",
"cargo/native-build-1/process.json": "cargo/native-build-1/process.json",
"cargo/native-build-1/result.json": "cargo/native-build-1/result.json",
"cargo/native-build-1/started.json": "cargo/native-build-1/started.json",
"cargo/native-build-1/stderr.log": "cargo/native-build-1/stderr.log",
"cargo/native-build-1/stdout.log": "cargo/native-build-1/stdout.log",
"cargo/windows-build-1/inputs.json": "capsules/4215d0ca0319282768f1acdf05c2c094ea7432e17ed3a715df73aa05cef851bf.json",
"cargo/windows-build-1/inputs.zip": "capsules/1e7f68e8d6156ec608b58ff70f7ddcaf690d38da1d5066092c218bce190d3a4c.zip",
"cargo/windows-build-1/process.json": "cargo/windows-build-1/process.json",
"cargo/windows-build-1/result.json": "cargo/windows-build-1/result.json",
"cargo/windows-build-1/started.json": "cargo/windows-build-1/started.json",
"cargo/windows-build-1/stderr.log": "cargo/windows-build-1/stderr.log",
"cargo/windows-build-1/stdout.log": "cargo/windows-build-1/stdout.log",
"helpers/1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20.py": "helpers/1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20.py",
"helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py": "helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py"
},
"members": {
"capsules/1e7f68e8d6156ec608b58ff70f7ddcaf690d38da1d5066092c218bce190d3a4c.zip": {
"bytes": 2952517,
"sha256": "1e7f68e8d6156ec608b58ff70f7ddcaf690d38da1d5066092c218bce190d3a4c"
},
"capsules/3419218f9917de0ac689a32dd622ebe55487fa5a37ffaba4b8fa662bc15a5cb9.zip": {
"bytes": 2948937,
"sha256": "3419218f9917de0ac689a32dd622ebe55487fa5a37ffaba4b8fa662bc15a5cb9"
},
"capsules/4215d0ca0319282768f1acdf05c2c094ea7432e17ed3a715df73aa05cef851bf.json": {
"bytes": 123053,
"sha256": "4215d0ca0319282768f1acdf05c2c094ea7432e17ed3a715df73aa05cef851bf"
},
"capsules/9cf85879dfb0bb5ec3b15c66b23df316e6bfe8451b6cf0c895bf7b9b5fbdde4a.json": {
"bytes": 122682,
"sha256": "9cf85879dfb0bb5ec3b15c66b23df316e6bfe8451b6cf0c895bf7b9b5fbdde4a"
},
"capsules/cecd6ae0ba45add8e913d9913cd4960c01928db0a4bc795902b7954ffb6f692e.zip": {
"bytes": 2947000,
"sha256": "cecd6ae0ba45add8e913d9913cd4960c01928db0a4bc795902b7954ffb6f692e"
},
"capsules/d8a64b62b68ac1c37bc3fe9309abc4dc314e343ce546bba4b9445f68dddeda5d.json": {
"bytes": 122682,
"sha256": "d8a64b62b68ac1c37bc3fe9309abc4dc314e343ce546bba4b9445f68dddeda5d"
},
"cargo/core-2/process.json": {
"bytes": 200,
"sha256": "744543a3f69d993977f0d15bce6e1ab3f64329eda4bb2d80375a8c8794ee83c0"
},
"cargo/core-2/result.json": {
"bytes": 3196,
"sha256": "4625b4558263524424fe6465aea20d1e9831f4c1cb6298124fa3683957f5880e"
},
"cargo/core-2/started.json": {
"bytes": 1403,
"sha256": "965d45f368d29ecbea6a7aa9b8881fe18a652928bad8f3e7665443acee52e19b"
},
"cargo/core-2/stderr.log": {
"bytes": 320,
"sha256": "42a28434514f50c42782a469c68e6aad8644592b9a09c4b50cc43d987bd2fd5d"
},
"cargo/core-2/stdout.log": {
"bytes": 42721,
"sha256": "862bd3e57a3454d29cb6d9ad7673e5bc4b25ab2a288e15d1a7d8dfb912a1457f"
},
"cargo/desktop-1/process.json": {
"bytes": 183,
"sha256": "bc57e00984823c7f417c8455f0db3da10f8e453c7db7a808f115b818525227ac"
},
"cargo/desktop-1/result.json": {
"bytes": 1778,
"sha256": "25f62fde1985dafcf3467895c6a2f389c886e92ceaa9d63ff513f3d4365ffe79"
},
"cargo/desktop-1/started.json": {
"bytes": 1381,
"sha256": "fd570a96b6dc5fc9e750634ef23093a7205cd953be5a7782485e8dbe509098a6"
},
"cargo/desktop-1/stderr.log": {
"bytes": 166,
"sha256": "ad39fc56f685f7f3c6a9b4a342abff1f19f9daad28c394673be0e3a2a1cf2523"
},
"cargo/desktop-1/stdout.log": {
"bytes": 297269,
"sha256": "d1cdbd43e8fe41e4af6fe2d99d665700a78c1d38185d3a373a33895f296e7b93"
},
"cargo/desktop-2/process.json": {
"bytes": 162,
"sha256": "86efe98400b268723e0c3b38b4bcd270f888215060548181b6f4695774a9b640"
},
"cargo/desktop-2/result.json": {
"bytes": 3090,
"sha256": "1ae8d0229e429001c2e6214e94e9c4156eb5db75ad1907f421ec87bdeac22f2e"
},
"cargo/desktop-2/started.json": {
"bytes": 1355,
"sha256": "71356cc6cdcd01d3620a4bd73c8eee2ccbcb870466b7b0419be8e76cd95e4c02"
},
"cargo/desktop-2/stderr.log": {
"bytes": 288,
"sha256": "5e3681e5c50d0d6b25d9594f87a7767456cefefb35ed0575b5d035202d00070f"
},
"cargo/desktop-2/stdout.log": {
"bytes": 441409,
"sha256": "f301281be9caa78720540f89548fc1bb80f9b28cda18e4f6425178d4995ed1ec"
},
"cargo/desktop-3/process.json": {
"bytes": 186,
"sha256": "963dea7f8d8663873ca087b025e53b6555af28a20cce4d5cbdc740c00c4c874d"
},
"cargo/desktop-3/result.json": {
"bytes": 3307,
"sha256": "ecdb5366bb2ca064924e8e967491a7b3db4adffec5cc8cb3370b7afaf739546b"
},
"cargo/desktop-3/started.json": {
"bytes": 1573,
"sha256": "5ddbc4ca4954ca732248437cf774cb7803ddec06bef42c11c63b27295be744b2"
},
"cargo/desktop-3/stderr.log": {
"bytes": 287,
"sha256": "e0d9090ebcc83418a064f8876ec587e4e741a65e380490999c169fa69628fe3b"
},
"cargo/desktop-3/stdout.log": {
"bytes": 307286,
"sha256": "c91fae7883b55901a2c3ab249650c2bb12a991e744a09c18159ffb3bf0079650"
},
"cargo/format-1/process.json": {
"bytes": 116,
"sha256": "d316037b78abff45a450b1c116d0c214d1d3831b6c375538779959e1dec652fb"
},
"cargo/format-1/result.json": {
"bytes": 1871,
"sha256": "2216bb25ce81504c61353456823ec38d77703dd6747f80f2d53b4267799ce21c"
},
"cargo/format-1/started.json": {
"bytes": 1483,
"sha256": "415e0776ec74ee486f2895e3581a8f78308dda9142d4e542442db9979408788b"
},
"cargo/format-1/stderr.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/format-1/stdout.log": {
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"cargo/lint-1/process.json": {
"bytes": 195,
"sha256": "286ba22c1994dfd70834adf811c103057724942f85fa5fbfa22e75e563ac376d"
},
"cargo/lint-1/result.json": {
"bytes": 1806,
"sha256": "7be8d8e2add4ceb69d5814326e4db91c33e804608e0998323dd72d388cf88def"
},
"cargo/lint-1/started.json": {
"bytes": 1409,
"sha256": "2fba3385528cf09df0382cbf4ec3867cdd109daad6de3fbfbc3663dbde7a1610"
},
"cargo/lint-1/stderr.log": {
"bytes": 166,
"sha256": "649dcf5fdf4a79dc2f3b315ef9e6735af44b50c40526c8593d2ce54a834a809d"
},
"cargo/lint-1/stdout.log": {
"bytes": 271410,
"sha256": "c7085d514e4dbdfc7c3b633911793071e13c27775edfe7ca8cc8f02b70219804"
},
"cargo/lint-2/process.json": {
"bytes": 196,
"sha256": "d6370e0e1aede61d5cae46028a6a7bab00e25429d1539e0989ef369d318d06c7"
},
"cargo/lint-2/result.json": {
"bytes": 1988,
"sha256": "0b5458c8567fa43a40c2fcf810999c0bc565d56635ff6fdb9484d79d88c69108"
},
"cargo/lint-2/started.json": {
"bytes": 1593,
"sha256": "4923e64c03112589eea0c15e3d67f66a94e4fdc1012356f24d67aad94142f386"
},
"cargo/lint-2/stderr.log": {
"bytes": 207,
"sha256": "d48449d9fa8226c728f9c979d930e91ebd55b84266edd3f7fb308b88a6451009"
},
"cargo/lint-2/stdout.log": {
"bytes": 309558,
"sha256": "de51e727c694ce4f35e4e732ab820488da053470538f20bdbffd55970eb2caad"
},
"cargo/native-build-1/process.json": {
"bytes": 175,
"sha256": "30f54028726b906c20cc9b7b0c7c965e3f1e54e6d4d54d99088da6b1c65c2f5e"
},
"cargo/native-build-1/result.json": {
"bytes": 3311,
"sha256": "03c22f6269b023f77d0fb3e713d5bbab8d14cf6e67ab4dfc613b4691fe4a6955"
},
"cargo/native-build-1/started.json": {
"bytes": 1552,
"sha256": "340989981b2db65bb194883c1a608f60cacf9a31d36a930dc39da28f5224cb88"
},
"cargo/native-build-1/stderr.log": {
"bytes": 131,
"sha256": "781b5778b0e781b52c25f5342c9c25d3fc45fe7c0da5bf5c94c86ba80ba7e2d2"
},
"cargo/native-build-1/stdout.log": {
"bytes": 41724,
"sha256": "5da6c22e3eef843f8be4539a7692e212c0c74461aaf4bf72ce2dd651abe165ac"
},
"cargo/windows-build-1/process.json": {
"bytes": 137,
"sha256": "2414e8af081cb683edbee3d6b89e5a323b08cce449058d453bffbc9736c1ea12"
},
"cargo/windows-build-1/result.json": {
"bytes": 3193,
"sha256": "172faec4d7708e4539468c3a9062d424f0e00cb80e827cd579274942c757eccb"
},
"cargo/windows-build-1/started.json": {
"bytes": 1504,
"sha256": "fefb683ef0e99046f5a18cbad56b8bb8bddc45b8abd322cb2c1d83e2acb26565"
},
"cargo/windows-build-1/stderr.log": {
"bytes": 137,
"sha256": "f75aa57fe559820a680c771701ea5737995528f29d7dae20e2ae265c07c0b8bb"
},
"cargo/windows-build-1/stdout.log": {
"bytes": 284179,
"sha256": "04422dbc4d720707d951d0654da39921c0a526b0eb0c33088a3a7e0d85686c31"
},
"helpers/1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20.py": {
"bytes": 3827,
"sha256": "1368375b1fba0dfc50b77ea4f406dba71960a78317ce8f259d4c4a0254863a20"
},
"helpers/6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06.py": {
"bytes": 3502,
"sha256": "6b8fcf64a1eb0869ae29abd66b4e89564a1813fef5898b54f2a17a3230dbaa06"
}
}
}
@@ -0,0 +1,90 @@
"""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/state-group-gates"
candidates = sorted(gates.glob("*.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
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,
"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/state-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, default=HERE, help="package directory; existing evidence is never overwritten")
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")
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=True)
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,164 @@
"""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"]
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())
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])
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), "logicalFiles": len(logical), "storedMembers": len(stored), "sourceCapsulePairs": len(seen_capsules)}
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,18 @@
# Core-1 capture incident
The original Cargo command recorded exit 0 and eleven tests passing, but
inputsUnchanged is false. Its source archive differs from its earlier input map
only in crates/oa-desktop/src/model_menu.rs (44572 versus 44757 bytes).
This is an invalid capture for normal gate evidence and is never counted as one.
A later unchanged capture must supply the accepted core gate.
The fixed identity file pins the exact original seven raw files and gate helper,
and the exact two byte hashes for the sole map/archive mismatch. The incident
verifier requires that known mismatch and rejects any other mismatch. It does not
repair or rewrite raw receipts, source bytes, or the false unchanged-input flag.
Use `python -B prepare.py --root CHECKOUT --check-only` to verify originals.
After review, omit --check-only and supply --output NEW_DIRECTORY. This copies
seven raw files, helper, identity and tools without wrapping a new ZIP. The raw
inputs.zip remains byte-identical. Verify with `python -B verify.py PACKAGE`.
Pin consistency records an incident; it does not prove the cause or execution.
@@ -0,0 +1 @@
{"pid": 772, "observed": "2026-09-23T09:44:19.087478+00:00", "command": ["cargo", "test", "-p", "oa-core", "--example", "state_multiselect_native", "--message-format=json", "--", "--test-threads=1"]}

Some files were not shown because too many files have changed in this diff Show More